diff --git a/Makefile b/Makefile index 97bd60612da..d600066aef3 100644 --- a/Makefile +++ b/Makefile @@ -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 \ diff --git a/ROMFS/CMakeLists.txt b/ROMFS/CMakeLists.txt index 54b67f76081..e136ba098f0 100644 --- a/ROMFS/CMakeLists.txt +++ b/ROMFS/CMakeLists.txt @@ -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() diff --git a/Tools/prepend_bootloader.py b/Tools/prepend_bootloader.py new file mode 100755 index 00000000000..90713d40371 --- /dev/null +++ b/Tools/prepend_bootloader.py @@ -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() diff --git a/boards/ark/can-flow-mr/default.px4board b/boards/ark/can-flow-mr/default.px4board index 6474b8cdb77..dd42352cab3 100644 --- a/boards/ark/can-flow-mr/default.px4board +++ b/boards/ark/can-flow-mr/default.px4board @@ -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 diff --git a/boards/ark/can-flow-mr/extras/ark_can-flow-mr_bootloader.bin b/boards/ark/can-flow-mr/extras/ark_can-flow-mr_bootloader.bin new file mode 100755 index 00000000000..062027027c5 Binary files /dev/null and b/boards/ark/can-flow-mr/extras/ark_can-flow-mr_bootloader.bin differ diff --git a/boards/ark/can-flow/default.px4board b/boards/ark/can-flow/default.px4board index 54d5438de66..257a51e98b0 100644 --- a/boards/ark/can-flow/default.px4board +++ b/boards/ark/can-flow/default.px4board @@ -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 diff --git a/boards/ark/can-flow/extras/ark_can-flow_bootloader.bin b/boards/ark/can-flow/extras/ark_can-flow_bootloader.bin new file mode 100755 index 00000000000..6b878ad147b Binary files /dev/null and b/boards/ark/can-flow/extras/ark_can-flow_bootloader.bin differ diff --git a/boards/ark/can-gps/default.px4board b/boards/ark/can-gps/default.px4board index ea76d19030b..8b26a3b256e 100644 --- a/boards/ark/can-gps/default.px4board +++ b/boards/ark/can-gps/default.px4board @@ -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 diff --git a/boards/ark/can-gps/extras/ark_can-gps_bootloader.bin b/boards/ark/can-gps/extras/ark_can-gps_bootloader.bin new file mode 100755 index 00000000000..d2131ad5270 Binary files /dev/null and b/boards/ark/can-gps/extras/ark_can-gps_bootloader.bin differ diff --git a/boards/ark/can-rtk-gps/default.px4board b/boards/ark/can-rtk-gps/default.px4board index 1d673aadb7a..125a41c646d 100644 --- a/boards/ark/can-rtk-gps/default.px4board +++ b/boards/ark/can-rtk-gps/default.px4board @@ -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 diff --git a/boards/ark/can-rtk-gps/extras/ark_can-rtk-gps_bootloader.bin b/boards/ark/can-rtk-gps/extras/ark_can-rtk-gps_bootloader.bin new file mode 100755 index 00000000000..bf7ca206d96 Binary files /dev/null and b/boards/ark/can-rtk-gps/extras/ark_can-rtk-gps_bootloader.bin differ diff --git a/boards/ark/cannode/default.px4board b/boards/ark/cannode/default.px4board index ede23712129..bc3302c6195 100644 --- a/boards/ark/cannode/default.px4board +++ b/boards/ark/cannode/default.px4board @@ -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 diff --git a/boards/ark/cannode/extras/ark_cannode_bootloader.bin b/boards/ark/cannode/extras/ark_cannode_bootloader.bin new file mode 100755 index 00000000000..a2165ec641e Binary files /dev/null and b/boards/ark/cannode/extras/ark_cannode_bootloader.bin differ diff --git a/boards/ark/dist/default.px4board b/boards/ark/dist/default.px4board index d908c1d4f79..d660ce517dd 100644 --- a/boards/ark/dist/default.px4board +++ b/boards/ark/dist/default.px4board @@ -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 diff --git a/boards/ark/dist/extras/ark_dist_bootloader.bin b/boards/ark/dist/extras/ark_dist_bootloader.bin new file mode 100755 index 00000000000..de9bc8a8c44 Binary files /dev/null and b/boards/ark/dist/extras/ark_dist_bootloader.bin differ diff --git a/boards/ark/f9p-gps/default.px4board b/boards/ark/f9p-gps/default.px4board index 9975dad4571..cd46d07f23a 100644 --- a/boards/ark/f9p-gps/default.px4board +++ b/boards/ark/f9p-gps/default.px4board @@ -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 diff --git a/boards/ark/f9p-gps/extras/ark_f9p-gps_bootloader.bin b/boards/ark/f9p-gps/extras/ark_f9p-gps_bootloader.bin new file mode 100755 index 00000000000..093ddbc9b40 Binary files /dev/null and b/boards/ark/f9p-gps/extras/ark_f9p-gps_bootloader.bin differ diff --git a/boards/ark/mag/default.px4board b/boards/ark/mag/default.px4board index 53f391b7e85..7ae32c61ab2 100644 --- a/boards/ark/mag/default.px4board +++ b/boards/ark/mag/default.px4board @@ -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 diff --git a/boards/ark/mag/extras/ark_mag_bootloader.bin b/boards/ark/mag/extras/ark_mag_bootloader.bin new file mode 100755 index 00000000000..587e03055b7 Binary files /dev/null and b/boards/ark/mag/extras/ark_mag_bootloader.bin differ diff --git a/boards/ark/septentrio-gps/default.px4board b/boards/ark/septentrio-gps/default.px4board index fd9f8a3eb7e..b80f92a543c 100644 --- a/boards/ark/septentrio-gps/default.px4board +++ b/boards/ark/septentrio-gps/default.px4board @@ -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 diff --git a/boards/ark/septentrio-gps/extras/ark_septentrio-gps_bootloader.bin b/boards/ark/septentrio-gps/extras/ark_septentrio-gps_bootloader.bin new file mode 100755 index 00000000000..3f9cd3a12a9 Binary files /dev/null and b/boards/ark/septentrio-gps/extras/ark_septentrio-gps_bootloader.bin differ diff --git a/boards/ark/x20-gps/default.px4board b/boards/ark/x20-gps/default.px4board index ec99c0a22e5..3f566c325c9 100644 --- a/boards/ark/x20-gps/default.px4board +++ b/boards/ark/x20-gps/default.px4board @@ -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 diff --git a/boards/ark/x20-gps/extras/ark_x20-gps_bootloader.bin b/boards/ark/x20-gps/extras/ark_x20-gps_bootloader.bin new file mode 100755 index 00000000000..a8a2a4c1607 Binary files /dev/null and b/boards/ark/x20-gps/extras/ark_x20-gps_bootloader.bin differ diff --git a/docs/en/dronecan/px4_cannode_fw.md b/docs/en/dronecan/px4_cannode_fw.md index 599003e36d1..c0b84f2a096 100644 --- a/docs/en/dronecan/px4_cannode_fw.md +++ b/docs/en/dronecan/px4_cannode_fw.md @@ -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///extras/__bootloader.bin`. +When that file exists, the `default` build additionally produces `__default_with_bootloader.bin`: bootloader and application in one image, flashed at `0x08000000` (`st-flash write 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 SYS_BL_UPDATE 1 +``` + +The node reports `bootloader updated`, `bootloader unchanged`, or `bootloader update failed: `, which the flight controller logs as `uavcan::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. diff --git a/platforms/nuttx/CMakeLists.txt b/platforms/nuttx/CMakeLists.txt index fa55a8abcfe..a4cce53c801 100644 --- a/platforms/nuttx/CMakeLists.txt +++ b/platforms/nuttx/CMakeLists.txt @@ -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 $ + --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() diff --git a/src/drivers/uavcannode/CMakeLists.txt b/src/drivers/uavcannode/CMakeLists.txt index 3da9e2a00ef..3be36750ae7 100644 --- a/src/drivers/uavcannode/CMakeLists.txt +++ b/src/drivers/uavcannode/CMakeLists.txt @@ -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() diff --git a/src/drivers/uavcannode/UavcanNode.cpp b/src/drivers/uavcannode/UavcanNode.cpp index e405583eb6c..6a9215ed660 100644 --- a/src/drivers/uavcannode/UavcanNode.cpp +++ b/src/drivers/uavcannode/UavcanNode.cpp @@ -47,6 +47,10 @@ extern "C" __attribute__((weak)) const char *board_get_uavcan_hw_name(void) #include #include +#if defined(CONFIG_SYSTEMCMDS_BL_UPDATE) +#include +#endif // CONFIG_SYSTEMCMDS_BL_UPDATE + #if defined(CONFIG_UAVCANNODE_COMMAND_SHELL) #include #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) { diff --git a/src/drivers/uavcannode/UavcanNode.hpp b/src/drivers/uavcannode/UavcanNode.hpp index f5fc46962f4..290fa540990 100644 --- a/src/drivers/uavcannode/UavcanNode.hpp +++ b/src/drivers/uavcannode/UavcanNode.hpp @@ -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. diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 11d0cccd0b6..97bfca96710 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -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) diff --git a/src/lib/bl_update/CMakeLists.txt b/src/lib/bl_update/CMakeLists.txt new file mode 100644 index 00000000000..d84c1501d7e --- /dev/null +++ b/src/lib/bl_update/CMakeLists.txt @@ -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() diff --git a/src/lib/bl_update/bl_update_flash.cpp b/src/lib/bl_update/bl_update_flash.cpp new file mode 100644 index 00000000000..c56c1e03479 --- /dev/null +++ b/src/lib/bl_update/bl_update_flash.cpp @@ -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 + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#if defined(BL_UPDATE_WATCHDOG) +# include +#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 diff --git a/src/lib/bl_update/bl_update_flash.h b/src/lib/bl_update/bl_update_flash.h new file mode 100644 index 00000000000..8a3cd219ee3 --- /dev/null +++ b/src/lib/bl_update/bl_update_flash.h @@ -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 diff --git a/src/lib/systemlib/system_params.yaml b/src/lib/systemlib/system_params.yaml index 36166e2f0a7..01393e750d8 100644 --- a/src/lib/systemlib/system_params.yaml +++ b/src/lib/systemlib/system_params.yaml @@ -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). diff --git a/src/systemcmds/bl_update/CMakeLists.txt b/src/systemcmds/bl_update/CMakeLists.txt index 7e0ddc5075d..e9091c78db4 100644 --- a/src/systemcmds/bl_update/CMakeLists.txt +++ b/src/systemcmds/bl_update/CMakeLists.txt @@ -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 ) diff --git a/src/systemcmds/bl_update/bl_update.cpp b/src/systemcmds/bl_update/bl_update.cpp index ffd4901c8aa..a84e93d7517 100644 --- a/src/systemcmds/bl_update/bl_update.cpp +++ b/src/systemcmds/bl_update/bl_update.cpp @@ -37,34 +37,14 @@ * STM32F4 & STM32F7 bootloader update tool. */ +#include + #include #include #include #include -#include -#include #include -#include -#include -#include -#include - -#include - -#include - -#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