feat(cannode): bootloader update from the app and combined flash image (#28293)

* feat(bl_update): pet the watchdog during erase and program

CAN nodes start the IWDG in the bootloader, and nothing else pets it
while bl_update holds the scheduler lock.

Assisted-by: Claude:claude-opus-5-5

* feat(nuttx): emit canbootloader to board extras and build bootloader+app image

canbootloader builds now write extras/<vendor>_<board>_bootloader.bin
like FMU bootloader builds do, which plugs CAN nodes into the existing
ROMFS / rc.board_bootloader_upgrade / jlink wiring. CAN node app builds
with that file also emit <config>_with_bootloader.bin (bootloader padded
to the app's ELF load address, followed by the CRC'd image) so a bare
board is flashed in one SWD step instead of two.

Assisted-by: Claude:claude-opus-5-5

* feat(cannode): run rc.board_bootloader_upgrade at startup

The hook was only wired into the FMU rcS, so SYS_BL_UPDATE did nothing
on CAN nodes even with bl_update built in.

* feat(ark): enable bootloader update on CAN nodes

Ships the CAN bootloader in the app ROMFS so a node can rewrite it via
SYS_BL_UPDATE without SWD.

Assisted-by: Claude:claude-opus-5-5

* docs(dronecan): bootloader update and combined image for CAN nodes

Assisted-by: Claude:claude-opus-5-5

* build(ark): rebuild CAN node bootloaders from current main

The committed binaries predated the F412 chip-selection and linker fixes
and the NuttX 12.12 upgrade, so they no longer matched the source.

Assisted-by: Claude:claude-opus-5-5

* feat(uavcannode): update the bootloader as soon as SYS_BL_UPDATE is set

Same approach as AP_Periph. Running the update on the next boot needed
two reboots and reported nothing over CAN: it ran before uavcannode
started, and the boot script printed "done" even when bl_update failed.
The node now flashes while running, skips an identical bootloader, and
the result reaches the flight controller through the existing log
message forwarding. A value left set from before boot is cleared rather
than acted on.

The flash routine moves into a library so uavcannode can call it.

Assisted-by: Claude:claude-opus-5-5

* docs(dronecan): note that the combined CAN node image resets parameters

Found on the bench: the padding between bootloader and app covers the
parameter sectors, so every SWD flash of the combined image erases them.

Assisted-by: Claude:claude-opus-5-5

* fix(nuttx): limit CAN bootloader extras and combined image to STM32

Every canbootloader build wrote its binary to the board's extras, so a
later nxp_ucans32k146 default or cyphal configure picked it up and failed
in prepend_bootloader.py: the S32K application loads at 0x6000, below
the 0x08000000 base the script and bl_update assume. CI only passed
because the canbootloader was built after both had configured.

Assisted-by: Claude:claude-fable-5-1

* fix(bl_update): pad the image before erasing and warn on every flash failure

The STM32F4 up_progmem_write() returns -EINVAL for an odd byte count,
which was only found out after sector 0 had been erased. An erase or
program failure also leaves the board without a bootloader, but only a
verify failure told the user to retry before rebooting.

Assisted-by: Claude:claude-fable-5-1

* fix(romfs): pack rc.board_bootloader_upgrade only where rcS runs it

CAN nodes with bl_update carried the script in their ROMFS although the
cannode rcS never sources it: uavcannode flashes the bootloader itself.

Assisted-by: Claude:claude-fable-5-1

* refactor(bl_update): move the flash routine to src/lib

The library lived under systemcmds, which is configured after drivers,
so uavcannode could only link it through a forward reference. The
watchdog is now selected by chip because the platform targets do not
exist yet when src/lib is configured.

Assisted-by: Claude:claude-fable-5-1

* docs(dronecan): the CAN bootloader is written to extras on STM32 only

Assisted-by: Claude:claude-fable-5-1
This commit is contained in:
Jacob Dahl authored and GitHub committed 2026-10-06 15:42:33 -06:00
1 parent 63d157859e
commit de52c98eff
35 files changed
+596 -142

No files matched your search

+10
View File
@@ -360,9 +360,19 @@ px4io_update:
bootloaders_update: \
3dr_ctrl-n1_bootloader \
3dr_ctrl-zero-h7-oem-revg_bootloader \
ark_can-flow_canbootloader \
ark_can-flow-mr_canbootloader \
ark_can-gps_canbootloader \
ark_can-rtk-gps_canbootloader \
ark_cannode_canbootloader \
ark_dist_canbootloader \
ark_f9p-gps_canbootloader \
ark_fmu-v6x_bootloader \
ark_fpv_bootloader \
ark_mag_canbootloader \
ark_pi6x_bootloader \
ark_septentrio-gps_canbootloader \
ark_x20-gps_canbootloader \
auterion_fmu-v6s_bootloader \
auterion_fmu-v6x_bootloader \
cuav_nora_bootloader \
+4 -3
View File
@@ -257,12 +257,13 @@ set(OPTIONAL_BOARD_EXTRAS)
file(GLOB OPTIONAL_BOARD_EXTRAS ${PX4_BOARD_DIR}/extras/*)
# bootloader (optional)
# - if systemcmds/bl_update included and board bootloader available then generate rc.board_bootloader_upgrade and copy bootloader binary
# - if systemcmds/bl_update included and board bootloader available then copy bootloader binary
# - and generate rc.board_bootloader_upgrade for px4fmu_common, the only rcS that runs it
# - otherwise remove bootloader binary from extras in final ROMFS
foreach(board_extra_file ${OPTIONAL_BOARD_EXTRAS})
file(RELATIVE_PATH extra_file_base_name ${PX4_BOARD_DIR}/extras/ ${board_extra_file})
if(${extra_file_base_name} MATCHES "${PX4_BOARD_VENDOR}_${PX4_BOARD_MODEL}_bootloader.bin")
if(CONFIG_SYSTEMCMDS_BL_UPDATE)
if(CONFIG_SYSTEMCMDS_BL_UPDATE AND ("${config_romfs_root}" STREQUAL "px4fmu_common"))
# generate rc.board_bootloader_upgrade
set(BOARD_FIRMWARE_BIN "${PX4_BOARD_VENDOR}_${PX4_BOARD_MODEL}_bootloader.bin")
message(STATUS "ROMFS: Adding platforms/nuttx/init/rc.board_bootloader_upgrade -> /etc/init.d/rc.board_bootloader_upgrade")
@@ -288,7 +289,7 @@ foreach(board_extra_file ${OPTIONAL_BOARD_EXTRAS})
list(APPEND extras_dependencies
rc.board_bootloader_upgrade.stamp
)
else()
elseif(NOT CONFIG_SYSTEMCMDS_BL_UPDATE)
# remove bootloader from extras
list(REMOVE_ITEM OPTIONAL_BOARD_EXTRAS ${board_extra_file})
endif()
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
############################################################################
#
# Copyright (C) 2026 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# 3. Neither the name PX4 nor the names of its contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
############################################################################
"""
Prepend a bootloader to an application image so the pair can be flashed in
one step at the start of flash (e.g. st-flash write out.bin 0x8000000).
The bootloader is padded with 0xff up to the application's load address,
which is taken from the lowest PT_LOAD segment of the application ELF.
"""
import argparse
import struct
import sys
PT_LOAD = 1
def elf_load_address(path):
with open(path, "rb") as f:
data = f.read()
if data[:4] != b"\x7fELF" or data[4] != 1:
sys.exit(f"{path}: not an ELF32 file")
little = data[5] == 1
e = "<" if little else ">"
(e_phoff,) = struct.unpack_from(e + "I", data, 0x1c)
(e_phentsize, e_phnum) = struct.unpack_from(e + "HH", data, 0x2a)
lowest = None
for i in range(e_phnum):
(p_type, p_offset, p_vaddr, p_paddr, p_filesz) = struct.unpack_from(
e + "IIIII", data, e_phoff + i * e_phentsize)
if p_type == PT_LOAD and p_filesz > 0:
lowest = p_paddr if lowest is None else min(lowest, p_paddr)
if lowest is None:
sys.exit(f"{path}: no loadable segments")
return lowest
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--bootloader", required=True, help="bootloader .bin, placed at --base")
parser.add_argument("--app", required=True, help="application .bin, placed at its ELF load address")
parser.add_argument("--elf", required=True, help="application ELF, used for the load address")
parser.add_argument("--base", type=lambda x: int(x, 0), default=0x08000000,
help="flash address the output is flashed to (default 0x08000000)")
parser.add_argument("--output", required=True)
args = parser.parse_args()
app_address = elf_load_address(args.elf)
app_offset = app_address - args.base
with open(args.bootloader, "rb") as f:
bootloader = f.read()
with open(args.app, "rb") as f:
app = f.read()
if app_offset < 0:
sys.exit(f"application load address 0x{app_address:08x} is below --base 0x{args.base:08x}")
if len(bootloader) > app_offset:
sys.exit(f"bootloader ({len(bootloader)} bytes) overlaps the application at offset 0x{app_offset:x}")
with open(args.output, "wb") as f:
f.write(bootloader)
f.write(b"\xff" * (app_offset - len(bootloader)))
f.write(app)
print(f"{args.output}: bootloader {len(bootloader)} bytes @ 0x{args.base:08x}, "
f"application {len(app)} bytes @ 0x{app_address:08x}")
if __name__ == "__main__":
main()
+1
View File
@@ -20,6 +20,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_ACCELERATION is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
# CONFIG_SENSORS_VEHICLE_MAGNETOMETER is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+1
View File
@@ -23,6 +23,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_ACCELERATION is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
# CONFIG_SENSORS_VEHICLE_MAGNETOMETER is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+1
View File
@@ -27,6 +27,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_AIRSPEED is not set
# CONFIG_SENSORS_VEHICLE_AIR_DATA is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+1
View File
@@ -30,6 +30,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_AIRSPEED is not set
# CONFIG_SENSORS_VEHICLE_AIR_DATA is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+1
View File
@@ -42,6 +42,7 @@ CONFIG_UAVCANNODE_STATIC_PRESSURE=y
CONFIG_UAVCANNODE_STATIC_TEMPERATURE=y
CONFIG_MODULES_CONTROL_ALLOCATOR=y
CONFIG_MODULES_SENSORS=y
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW=n
CONFIG_SYSTEMCMDS_ACTUATOR_TEST=y
CONFIG_SYSTEMCMDS_I2CDETECT=y
Binary file not shown.
+1
View File
@@ -9,6 +9,7 @@ CONFIG_DRIVERS_DISTANCE_SENSOR_BROADCOM_AFBRS50=y
CONFIG_MODULES_DATAMAN=y
CONFIG_MODULES_MAVLINK=y
CONFIG_NUM_MISSION_ITEMS_SUPPORTED=100
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
BIN
View File
Binary file not shown.
+1
View File
@@ -27,6 +27,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_AIRSPEED is not set
# CONFIG_SENSORS_VEHICLE_AIR_DATA is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+1
View File
@@ -11,6 +11,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_AIRSPEED is not set
# CONFIG_SENSORS_VEHICLE_AIR_DATA is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
@@ -28,6 +28,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_AIRSPEED is not set
# CONFIG_SENSORS_VEHICLE_AIR_DATA is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+1
View File
@@ -28,6 +28,7 @@ CONFIG_MODULES_SENSORS=y
# CONFIG_SENSORS_VEHICLE_AIRSPEED is not set
# CONFIG_SENSORS_VEHICLE_AIR_DATA is not set
# CONFIG_SENSORS_VEHICLE_GPS_POSITION is not set
CONFIG_SYSTEMCMDS_BL_UPDATE=y
CONFIG_SYSTEMCMDS_PARAM=y
CONFIG_SYSTEMCMDS_PERF=y
CONFIG_SYSTEMCMDS_REBOOT=y
Binary file not shown.
+14
View File
@@ -81,6 +81,20 @@ make ark_can-flow_canbootloader
The binary can then be flashed to the microcontroller using your favorite SWD/JTAG debugger, such as the [Black Magic Probe](https://black-magic.org/index.html), [ST-Link](https://www.st.com/en/development-tools/st-link-v2.html), or [Segger JLink](https://www.segger.com/products/debug-probes/j-link/).
On STM32 boards the `canbootloader` build also writes the binary to `boards/<vendor>/<board>/extras/<vendor>_<board>_bootloader.bin`.
When that file exists, the `default` build additionally produces `<vendor>_<board>_default_with_bootloader.bin`: bootloader and application in one image, flashed at `0x08000000` (`st-flash write <file> 0x8000000`).
The image spans the parameter sectors, so flashing it resets the node's parameters.
Boards with `CONFIG_SYSTEMCMDS_BL_UPDATE=y` embed that bootloader in the application firmware and rewrite the bootloader within about 2 seconds of [SYS_BL_UPDATE](../advanced_config/parameter_reference.md#SYS_BL_UPDATE) being set, without rebooting.
From the flight controller's [MAVLink Shell](../debug/mavlink_shell.md):
```sh
uavcan param set <node_id> SYS_BL_UPDATE 1
```
The node reports `bootloader updated`, `bootloader unchanged`, or `bootloader update failed: <reason>`, which the flight controller logs as `uavcan:<node_id>:uavcannode`.
Do not power off the node during the update.
### Firmware Internals
For the most part, peripheral firmware works the same way as flight controller firmware builds.
+29 -1
View File
@@ -519,8 +519,12 @@ if(${CONFIG_NSH_LIBRARY} MATCHES "y")
endif()
endif()
if("${PX4_BOARD_LABEL}" STREQUAL "bootloader")
# The consumers of a CAN bootloader in extras (bl_update, the combined image
# below) assume the STM32 flash base, so other chips do not emit one.
if(("${PX4_BOARD_LABEL}" STREQUAL "bootloader") OR
(("${PX4_BOARD_LABEL}" STREQUAL "canbootloader") AND ("${PX4_CHIP_MANUFACTURER}" STREQUAL "stm")))
add_custom_command(OUTPUT ${PX4_BOARD_DIR}/extras/${PX4_BOARD}_bootloader.bin
COMMAND ${CMAKE_COMMAND} -E make_directory ${PX4_BOARD_DIR}/extras
COMMAND ${CMAKE_OBJCOPY} -O binary ${PX4_BINARY_DIR_REL}/${FW_NAME} ${PX4_BOARD_DIR}/extras/${PX4_BOARD}_bootloader.bin
DEPENDS px4
)
@@ -547,6 +551,30 @@ if(NOT ("${PX4_BOARD_LABEL}" STREQUAL "bootloader") AND (EXISTS "${PX4_BOARD_DIR
WORKING_DIRECTORY ${PX4_BINARY_DIR}
)
add_custom_target(bootloader_elf DEPENDS ${PX4_BINARY_DIR}/${PX4_BOARD_VENDOR}_${PX4_BOARD_MODEL}_bootloader.elf)
# CAN node application builds: bootloader + application in one image,
# flashed at the start of flash. The application part is the .uavcan.bin
# because the CAN bootloader only boots an image with its descriptor CRCs
# filled in. STM32 only: prepend_bootloader.py defaults to its flash base.
if((TARGET build_uavcan_bl) AND ("${PX4_CHIP_MANUFACTURER}" STREQUAL "stm"))
add_custom_command(
OUTPUT ${PX4_BINARY_DIR}/${PX4_CONFIG}_with_bootloader.bin
COMMAND
${PYTHON_EXECUTABLE} ${PX4_SOURCE_DIR}/Tools/prepend_bootloader.py
--bootloader ${PX4_BOARD_DIR}/extras/${PX4_BOARD_VENDOR}_${PX4_BOARD_MODEL}_bootloader.bin
--app ${PX4_BINARY_DIR}/${uavcan_bl_image_name}
--elf $<TARGET_FILE:px4>
--output ${PX4_BINARY_DIR}/${PX4_CONFIG}_with_bootloader.bin
DEPENDS
${PX4_BOARD_DIR}/extras/${PX4_BOARD_VENDOR}_${PX4_BOARD_MODEL}_bootloader.bin
${PX4_SOURCE_DIR}/Tools/prepend_bootloader.py
${PX4_BINARY_DIR}/${uavcan_bl_image_name}
build_uavcan_bl
px4
COMMENT "Creating ${PX4_CONFIG}_with_bootloader.bin"
)
add_custom_target(px4_with_bootloader ALL DEPENDS ${PX4_BINARY_DIR}/${PX4_CONFIG}_with_bootloader.bin)
endif()
endif()
+12
View File
@@ -126,6 +126,11 @@ if(CONFIG_UAVCANNODE_COMMAND_SHELL)
)
endif()
set(UAVCANNODE_BL_UPDATE_LIBS)
if(CONFIG_SYSTEMCMDS_BL_UPDATE)
list(APPEND UAVCANNODE_BL_UPDATE_LIBS bl_update_flash)
endif()
px4_add_module(
MODULE drivers__uavcannode
MAIN uavcannode
@@ -162,4 +167,11 @@ px4_add_module(
# within libuavcan
uavcan
${UAVCANNODE_BL_UPDATE_LIBS}
)
if(CONFIG_SYSTEMCMDS_BL_UPDATE)
target_compile_definitions(drivers__uavcannode PRIVATE
UAVCANNODE_BOOTLOADER_FILE="/etc/extras/${PX4_BOARD_VENDOR}_${PX4_BOARD_MODEL}_bootloader.bin")
endif()
+54
View File
@@ -47,6 +47,10 @@ extern "C" __attribute__((weak)) const char *board_get_uavcan_hw_name(void)
#include <lib/geo/geo.h>
#include <lib/version/version.h>
#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE)
#include <lib/bl_update/bl_update_flash.h>
#endif // CONFIG_SYSTEMCMDS_BL_UPDATE
#if defined(CONFIG_UAVCANNODE_COMMAND_SHELL)
#include <errno.h>
#endif // CONFIG_UAVCANNODE_COMMAND_SHELL
@@ -459,6 +463,18 @@ int UavcanNode::init(uavcan::NodeID node_id, UAVCAN_DRIVER::BusEvent &bus_events
fill_node_info();
#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE)
// Only setting SYS_BL_UPDATE while running triggers an update, never a
// value left over from before this boot.
int32_t bl_update = 0;
if (param_get(_param_sys_bl_update, &bl_update) == PX4_OK && bl_update != 0) {
bl_update = 0;
param_set(_param_sys_bl_update, &bl_update);
}
#endif // CONFIG_SYSTEMCMDS_BL_UPDATE
if (_fw_update_listner.start(BeginFirmwareUpdateCallBack(this, &UavcanNode::cb_beginfirmware_update)) < 0) {
PX4_ERR("firmware update listener start failed");
return PX4_ERROR;
@@ -610,6 +626,22 @@ int UavcanNode::init(uavcan::NodeID node_id, UAVCAN_DRIVER::BusEvent &bus_events
return 1;
}
#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE)
void UavcanNode::update_bootloader()
{
// The bootloader only runs at reset, so no reboot is needed. The result
// goes out over CAN through the log_message forwarding in Run().
const bl_update::Result result = bl_update::flash(UAVCANNODE_BOOTLOADER_FILE);
if (result == bl_update::Result::Updated || result == bl_update::Result::Unchanged) {
PX4_INFO("%s", bl_update::result_str(result));
} else {
PX4_ERR("bootloader update failed: %s", bl_update::result_str(result));
}
}
#endif // CONFIG_SYSTEMCMDS_BL_UPDATE
// Restart handler
class RestartRequestHandler: public uavcan::IRestartRequestHandler
{
@@ -728,8 +760,30 @@ void UavcanNode::Run()
_parameter_update_sub.copy(&pupdate);
// update parameters from storage
#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE)
int32_t bl_update = 0;
if (param_get(_param_sys_bl_update, &bl_update) == PX4_OK && bl_update != 0) {
bl_update = 0;
param_set(_param_sys_bl_update, &bl_update);
// let the param set response and the autosave go out before flashing stalls everything
_bootloader_update_time = hrt_absolute_time() + 1_s;
}
#endif // CONFIG_SYSTEMCMDS_BL_UPDATE
}
#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE)
if (_bootloader_update_time != 0 && hrt_absolute_time() >= _bootloader_update_time) {
_bootloader_update_time = 0;
update_bootloader();
}
#endif // CONFIG_SYSTEMCMDS_BL_UPDATE
_node.spinOnce();
for (auto &publisher : _publisher_list) {
+7
View File
@@ -155,6 +155,13 @@ private:
void fill_node_info();
int init(uavcan::NodeID node_id, UAVCAN_DRIVER::BusEvent &bus_events);
#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE)
void update_bootloader();
param_t _param_sys_bl_update{param_find("SYS_BL_UPDATE")};
hrt_abstime _bootloader_update_time{0};
#endif // CONFIG_SYSTEMCMDS_BL_UPDATE
px4::atomic_bool _task_should_exit{false}; ///< flag to indicate to tear down the CAN driver
enum {Booted, Interfaced, Allocation, Allocated, Done} _init_state{Booted}; ///< State of the boot.
+1
View File
@@ -35,6 +35,7 @@ add_subdirectory(adsb EXCLUDE_FROM_ALL)
add_subdirectory(airspeed EXCLUDE_FROM_ALL)
add_subdirectory(atmosphere EXCLUDE_FROM_ALL)
add_subdirectory(battery EXCLUDE_FROM_ALL)
add_subdirectory(bl_update EXCLUDE_FROM_ALL)
add_subdirectory(button EXCLUDE_FROM_ALL)
add_subdirectory(cdev EXCLUDE_FROM_ALL)
add_subdirectory(cdrstream EXCLUDE_FROM_ALL)
+45
View File
@@ -0,0 +1,45 @@
############################################################################
#
# Copyright (c) 2026 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# 3. Neither the name PX4 nor the names of its contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
############################################################################
if(CONFIG_SYSTEMCMDS_BL_UPDATE)
px4_add_library(bl_update_flash bl_update_flash.cpp)
target_compile_options(bl_update_flash PRIVATE -Wno-cast-align)
# CAN nodes run with the IWDG their bootloader started, and nothing else
# pets it while the scheduler is locked for erase and program. Matched on
# the chip because the platform targets are configured after src/lib.
if("${PX4_CHIP}" MATCHES "^stm32f[47]$")
target_compile_definitions(bl_update_flash PRIVATE BL_UPDATE_WATCHDOG)
target_link_libraries(bl_update_flash PRIVATE arch_watchdog_iwdg)
endif()
endif()
+224
View File
@@ -0,0 +1,224 @@
/****************************************************************************
*
* Copyright (c) 2012-2026 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "bl_update_flash.h"
#include <px4_platform_common/px4_config.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sched.h>
#include <sys/stat.h>
#include <arch/board/board.h>
#include <nuttx/progmem.h>
#if defined(BL_UPDATE_WATCHDOG)
# include <drivers/drv_watchdog.h>
#else
# define watchdog_pet()
#endif
#if defined(CONFIG_ARCH_CHIP_STM32H7)
# define BL_FILE_SIZE_LIMIT 128*1024
# define STM_RAM_BASE STM32_AXISRAM_BASE
# define PAGE_SIZE_MATTERS 1
#elif defined(CONFIG_ARCH_CHIP_STM32F7)
# define BL_FILE_SIZE_LIMIT 32*1024
# define STM_RAM_BASE STM32_SRAM_BASE
#else
# define BL_FILE_SIZE_LIMIT 16384
# define STM_RAM_BASE STM32_SRAM_BASE
#endif
namespace bl_update
{
#if defined (CONFIG_STM32_STM32F4XXX) || defined (CONFIG_ARCH_CHIP_STM32F7) || \
defined (CONFIG_ARCH_CHIP_STM32H7)
static Result write_flash(const uint8_t *buf, size_t image_size)
{
uint8_t *base = (uint8_t *) PX4_FLASH_BASE;
if (memcmp(base, buf, image_size) == 0) {
return Result::Unchanged;
}
/* prevent other tasks from running while we do this */
sched_lock();
/* The IWDG may already be running (CAN nodes start it in the bootloader)
* and nothing else gets to pet it while the scheduler is locked. */
watchdog_pet();
const bool erased = up_progmem_eraseblock(0) >= 0;
watchdog_pet();
/* Program even if the erase reported an error: the old bootloader is
* already damaged, and a failed program reports it below. */
const ssize_t size = up_progmem_write((size_t) base, buf, image_size);
watchdog_pet();
/* re-lock the flash control register */
stm32_flash_lock();
sched_unlock();
if (size != (ssize_t) image_size) {
return erased ? Result::ProgramFailed : Result::EraseFailed;
}
if (memcmp(base, buf, image_size) != 0) {
return Result::VerifyFailed;
}
return Result::Updated;
}
Result flash(const char *path)
{
int fd = open(path, O_RDONLY);
if (fd < 0) {
return Result::OpenFailed;
}
struct stat s;
if (fstat(fd, &s) != 0) {
close(fd);
return Result::OpenFailed;
}
if (s.st_size > BL_FILE_SIZE_LIMIT) {
close(fd);
return Result::TooLarge;
}
const size_t file_size = s.st_size;
/* up_progmem_write() rejects a size that is not a multiple of its
* program unit, and by then the old bootloader is erased. */
#if defined(PAGE_SIZE_MATTERS)
const size_t align_mask = up_progmem_pagesize(0) - 1;
#else
const size_t align_mask = sizeof(uint32_t) - 1;
#endif
const size_t image_size = (file_size + align_mask) & ~align_mask;
uint8_t *buf = (uint8_t *)malloc(image_size);
if (buf == nullptr) {
close(fd);
return Result::NoMemory;
}
memset(buf, 0xff, image_size);
const ssize_t bytes_read = read(fd, buf, file_size);
close(fd);
if (bytes_read != (ssize_t) file_size) {
free(buf);
return Result::ReadFailed;
}
const uint32_t *hdr = (const uint32_t *)buf;
if ((hdr[0] < STM_RAM_BASE) || /* stack not below RAM */
(hdr[0] > (STM_RAM_BASE + (128 * 1024))) || /* stack not above RAM */
(hdr[1] < PX4_FLASH_BASE) || /* entrypoint not below flash */
((hdr[1] - PX4_FLASH_BASE) > BL_FILE_SIZE_LIMIT)) { /* entrypoint not outside bootloader */
free(buf);
return Result::InvalidImage;
}
const Result result = write_flash(buf, image_size);
free(buf);
return result;
}
#else
Result flash(const char *path)
{
return Result::NotSupported;
}
#endif
const char *result_str(Result result)
{
switch (result) {
case Result::Updated:
return "bootloader updated";
case Result::Unchanged:
return "bootloader unchanged";
case Result::NotSupported:
return "not supported on this hardware";
case Result::OpenFailed:
return "cannot open bootloader file";
case Result::TooLarge:
return "bootloader file too large";
case Result::NoMemory:
return "out of memory";
case Result::ReadFailed:
return "bootloader file read error";
case Result::InvalidImage:
return "not a bootloader image";
case Result::EraseFailed:
return "flash erase failed, retry before rebooting";
case Result::ProgramFailed:
return "flash program failed, retry before rebooting";
case Result::VerifyFailed:
return "verify failed, retry before rebooting";
}
return "unknown error";
}
} // namespace bl_update
+62
View File
@@ -0,0 +1,62 @@
/****************************************************************************
*
* Copyright (c) 2026 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#pragma once
namespace bl_update
{
enum class Result {
Updated,
Unchanged,
NotSupported,
OpenFailed,
TooLarge,
NoMemory,
ReadFailed,
InvalidImage,
EraseFailed,
ProgramFailed,
VerifyFailed,
};
/**
* Write the bootloader image at path to the start of flash, unless flash
* already holds that image. Other tasks do not run while flash is erased
* and programmed.
*/
Result flash(const char *path);
const char *result_str(Result result);
} // namespace bl_update
+2 -1
View File
@@ -226,7 +226,8 @@ parameters:
description:
short: Bootloader update
long: |-
If enabled, update the bootloader on the next boot.
If enabled, update the bootloader on the next boot. DroneCAN nodes
update within about 2 seconds of it being set, without rebooting.
WARNING: do not cut the power during an update process, otherwise you will
have to recover using some alternative method (e.g. JTAG).
+2 -2
View File
@@ -34,8 +34,8 @@ px4_add_module(
MODULE systemcmds__bl_update
MAIN bl_update
STACK_MAIN 4096
COMPILE_FLAGS
-Wno-cast-align # TODO: fix and enable
SRCS
bl_update.cpp
DEPENDS
bl_update_flash
)
+8 -135
View File
@@ -37,34 +37,14 @@
* STM32F4 & STM32F7 bootloader update tool.
*/
#include <lib/bl_update/bl_update_flash.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/log.h>
#include <px4_platform_common/module.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <arch/board/board.h>
#include <nuttx/progmem.h>
#if defined(CONFIG_ARCH_CHIP_STM32H7)
# define BL_FILE_SIZE_LIMIT 128*1024
# define STM_RAM_BASE STM32_AXISRAM_BASE
# define PAGE_SIZE_MATTERS 1
#elif defined(CONFIG_ARCH_CHIP_STM32F7)
# define BL_FILE_SIZE_LIMIT 32*1024
# define STM_RAM_BASE STM32_SRAM_BASE
#else
# define BL_FILE_SIZE_LIMIT 16384
# define STM_RAM_BASE STM32_SRAM_BASE
#endif
#if defined (CONFIG_STM32_STM32F4XXX) || defined (CONFIG_ARCH_CHIP_STM32F7) || \
defined (CONFIG_ARCH_CHIP_STM32H7)
@@ -108,123 +88,16 @@ extern "C" __EXPORT int bl_update_main(int argc, char *argv[])
return setopt();
}
int fd = open(argv[1], O_RDONLY);
const bl_update::Result result = bl_update::flash(argv[1]);
if (fd < 0)
if (result == bl_update::Result::Updated || result == bl_update::Result::Unchanged)
{
PX4_ERR("open %s failed", argv[1]);
return 1;
PX4_INFO("%s", bl_update::result_str(result));
return 0;
}
struct stat s;
if (stat(argv[1], &s) != 0)
{
PX4_ERR("stat %s failed", argv[1]);
close(fd);
return 1;
}
/* sanity-check file size */
if (s.st_size > BL_FILE_SIZE_LIMIT)
{
PX4_ERR("%s: file too large (limit: %u, actual: %jd)", argv[1], BL_FILE_SIZE_LIMIT, (intmax_t) s.st_size);
close(fd);
return 1;
}
off_t file_size = s.st_size;
off_t image_size = file_size;
#if defined(PAGE_SIZE_MATTERS)
size_t page_size = up_progmem_pagesize(0) - 1;
image_size = (file_size + page_size) & ~page_size;
#endif
uint8_t *buf = (uint8_t *)malloc(image_size);
if (buf == nullptr)
{
PX4_ERR("failed to allocate %jd bytes for firmware buffer", (intmax_t) file_size);
close(fd);
return 1;
}
memset(buf, 0xff, image_size);
if (read(fd, buf, file_size) != file_size)
{
PX4_ERR("firmware read error");
close(fd);
free(buf);
return 1;
}
close(fd);
uint32_t *hdr = (uint32_t *)buf;
if ((hdr[0] < STM_RAM_BASE) || /* stack not below RAM */
(hdr[0] > (STM_RAM_BASE + (128 * 1024))) || /* stack not above RAM */
(hdr[1] < PX4_FLASH_BASE) || /* entrypoint not below flash */
((hdr[1] - PX4_FLASH_BASE) > BL_FILE_SIZE_LIMIT)) /* entrypoint not outside bootloader */
{
free(buf);
PX4_ERR("not a bootloader image");
return 1;
}
PX4_INFO("image validated, erasing bootloader...");
px4_usleep(10000);
/* prevent other tasks from running while we do this */
sched_lock();
const size_t page = 0;
uint8_t *base = (uint8_t *) PX4_FLASH_BASE;
ssize_t size = up_progmem_eraseblock(page);
if (size != BL_FILE_SIZE_LIMIT)
{
PX4_ERR("erase error at %p", &base[size]);
}
PX4_INFO("flashing...");
/* now program the bootloader - speed is not critical so use x8 mode */
size = up_progmem_write((size_t) base, buf, image_size);
if (size != image_size)
{
PX4_ERR("program error at %p", &base[size]);
goto flash_end;
}
/* re-lock the flash control register */
stm32_flash_lock();
PX4_INFO("verifying...");
/* now run a verify pass */
for (int i = 0; i < image_size; i++)
{
if (base[i] != buf[i]) {
PX4_WARN("verify failed at %i - retry update, DO NOT reboot", i);
goto flash_end;
}
}
PX4_INFO("bootloader update complete");
flash_end:
/* unlock the scheduler */
sched_unlock();
free(buf);
exit(0);
PX4_ERR("%s: %s", argv[1], bl_update::result_str(result));
return 1;
}
static int