From b52415983bf1ba06a63e8352d134d3b1f944998f Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Mon, 16 Sep 2024 11:10:49 +1000 Subject: [PATCH] added bootloader update firmware --- Makefile | 59 ++++++++++++--- Mcu/l431/Inc/blutil.h | 2 + Mcu/v203/Link_BLU.ld | 138 ++++++++++++++++++++++++++++++++++++ bl_update/ldscript_bl.ld | 135 +++++++++++++++++++++++++++++++++++ bl_update/main.c | 98 +++++++++++++++++++++++++ bl_update/make_binheader.py | 69 ++++++++++++++++++ v203makefile.mk | 1 + 7 files changed, 494 insertions(+), 8 deletions(-) create mode 100644 Mcu/v203/Link_BLU.ld create mode 100644 bl_update/ldscript_bl.ld create mode 100644 bl_update/main.c create mode 100755 bl_update/make_binheader.py diff --git a/Makefile b/Makefile index 3c995cf7..5dc34b9a 100644 --- a/Makefile +++ b/Makefile @@ -11,11 +11,8 @@ IDENTIFIER := AM32 # Folders HAL_FOLDER := Mcu -MAIN_SRC_DIR := Src MAIN_INC_DIR := Inc -SRC_DIRS_COMMON := $(MAIN_SRC_DIR) - # Working directories ROOT := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST)))) @@ -58,9 +55,6 @@ CFLAGS_COMMON := $(CFLAGS_BASE) # Linker options LDFLAGS_COMMON := -specs=nano.specs $(LIBS) -Wl,--gc-sections -Wl,--print-memory-usage -# Search source files -SRC_COMMON := $(foreach dir,$(SRC_DIRS_COMMON),$(wildcard $(dir)/*.[cs])) - # configure some directories that are relative to wherever ROOT_DIR is located OBJ := obj BIN_DIR := $(ROOT)/$(OBJ) @@ -89,7 +83,10 @@ clean : BOOTLOADER_VERSION := $(shell $(FGREP) "define BOOTLOADER_VERSION" $(MAIN_INC_DIR)/version.h | $(CUT) -d" " -f3 ) SRC_BL := $(foreach dir,bootloader,$(wildcard $(dir)/*.[cs])) +SRC_BLU := $(foreach dir,bl_update,$(wildcard $(dir)/*.[cs])) + LDSCRIPT_BL := bootloader/ldscript_bl.ld +LDSCRIPT_BLU := bl_update/ldscript_bl.ld # get a define in form -DBOARD_FLASH_SIZE=N if the target has a _NK suffix define flash_size_flag @@ -106,13 +103,23 @@ define BOOTLOADER_BASENAME $(IDENTIFIER)_$(call base_mcu,$(1))_BOOTLOADER_$(2)$(call get_k_tag,$(1)) endef +define BOOTLOADER_UPDATE_BASENAME +$(IDENTIFIER)_$(call base_mcu,$(1))_BL_UPDATER_$(2)$(call get_k_tag,$(1)) +endef + # bootloader target names with version for filename define BOOTLOADER_BASENAME_VER $(call BOOTLOADER_BASENAME,$(1),$(2))_V$(BOOTLOADER_VERSION) endef +# bootloader target names with version for filename +define BOOTLOADER_UPDATE_BASENAME_VER +$(call BOOTLOADER_UPDATE_BASENAME,$(1),$(2))_V$(BOOTLOADER_VERSION) +endef + # list of targets formed using CREATE_BOOTLOADER_TARGET ALL_BUILDS := +BLU_BUILDS := # create a bootloader build target given a build in the form MCU or MCU_nK and a PIN define CREATE_BOOTLOADER_TARGET @@ -123,14 +130,22 @@ $(eval EXTRA_CFLAGS := $(call flash_size_flag,$(1))) $(eval ELF_FILE := $(BIN_DIR)/$(call BOOTLOADER_BASENAME_VER,$(BUILD),$(PIN)).elf) $(eval HEX_FILE := $(ELF_FILE:.elf=.hex)) $(eval DEP_FILE := $(ELF_FILE:.elf=.d)) +$(eval BIN_FILE := $(ELF_FILE:.elf=.bin)) +$(eval H_FILE := $(ELF_FILE:.elf=.h)) +$(eval BLU_ELF_FILE := $(BIN_DIR)/$(call BOOTLOADER_UPDATE_BASENAME_VER,$(BUILD),$(PIN)).elf) +$(eval BLU_HEX_FILE := $(BLU_ELF_FILE:.elf=.hex)) +$(eval BLU_DEP_FILE := $(BLU_ELF_FILE:.elf=.d)) $(eval TARGET := $(call BOOTLOADER_BASENAME,$(BUILD),$(PIN))) +$(eval BLU_TARGET := $(call BOOTLOADER_UPDATE_BASENAME,$(BUILD),$(PIN))) # get MCU specific compiler, objcopy and link script or use the ARM SDK one $(eval xCC := $(if $($(MCU)_CC), $($(MCU)_CC), $(CC))) $(eval xOBJCOPY := $(if $($(MCU)_OBJCOPY), $($(MCU)_OBJCOPY), $(OBJCOPY))) $(eval xLDSCRIPT := $(if $($(MCU)_LDSCRIPT), $($(MCU)_LDSCRIPT), $(LDSCRIPT_BL))) +$(eval xBLU_LDSCRIPT := $(if $($(MCU)_LDSCRIPT_BLU), $($(MCU)_LDSCRIPT_BLU), $(LDSCRIPT_BLU))) -include $(DEP_FILE) +-include $(BLU_DEP_FILE) $(ELF_FILE): CFLAGS_BL := $$(MCU_$(MCU)) $$(CFLAGS_$(MCU)) $$(CFLAGS_BASE) -DBOOTLOADER -DUSE_$(PIN) $(EXTRA_CFLAGS) $(ELF_FILE): LDFLAGS_BL := $$(LDFLAGS_COMMON) $$(LDFLAGS_$(MCU)) -T$(xLDSCRIPT) @@ -143,22 +158,46 @@ $(ELF_FILE): $$(SRC_$(MCU)_BL) $$(SRC_BL) $$(QUIET)$$(CP) -f $$(SVD_$(MCU)) $$(OBJ)/debug.svd $$(QUIET)$$(CP) -f Mcu$(DSEP)$(call lc,$(MCU))$(DSEP)openocd.cfg $$(OBJ)$$(DSEP)openocd.cfg > $$(NUL) +$(H_FILE): $(BIN_FILE) + python3 bl_update/make_binheader.py $(BIN_FILE) $(H_FILE) + +$(BLU_ELF_FILE): CFLAGS_BLU := $$(MCU_$(MCU)) $$(CFLAGS_$(MCU)) $$(CFLAGS_BASE) -DBOOTLOADER -DUSE_$(PIN) $(EXTRA_CFLAGS) -Wno-unused-variable -Wno-unused-function +$(BLU_ELF_FILE): LDFLAGS_BLU := $$(LDFLAGS_COMMON) $$(LDFLAGS_$(MCU)) -T$(xBLU_LDSCRIPT) +$(BLU_ELF_FILE): $$(SRC_$(MCU)_BL) $$(SRC_BLU) $(H_FILE) + $$(QUIET)echo building bootloader updater for $(BUILD) with pin $(PIN) + $$(QUIET)$$(MKDIR) -p $(OBJ) + $$(QUIET)echo Compiling $(notdir $$@) + $$(QUIET)$(xCC) $$(CFLAGS_BLU) $$(LDFLAGS_BLU) -MMD -MP -MF $(DEP_FILE) -o $$(@) $$(SRC_$(MCU)_BL) $$(SRC_BLU) -I. -DBL_HEADER_FILE=$(H_FILE) + # Generate bin and hex files -$(HEX_FILE): $(ELF_FILE) +$(HEX_FILE): $$(ELF_FILE) + $$(QUIET)echo Generating $(notdir $$@) + $$(QUIET)$(xOBJCOPY) -O binary $$(<) $$(@:.hex=.bin) + $$(QUIET)$(xOBJCOPY) $$(<) -O ihex $$(@:.bin=.hex) + +$(BIN_FILE): $$(HEX_FILE) + +# Generate bin and hex files for bl updater +$(BLU_HEX_FILE): $$(BLU_ELF_FILE) $$(QUIET)echo Generating $(notdir $$@) $$(QUIET)$(xOBJCOPY) -O binary $$(<) $$(@:.hex=.bin) $$(QUIET)$(xOBJCOPY) $$(<) -O ihex $$(@:.bin=.hex) -$(TARGET): $(HEX_FILE) +$(TARGET): $$(HEX_FILE) + +$(BLU_TARGET): $$(BLU_HEX_FILE) # add to list ALL_BUILDS := $(ALL_BUILDS) $(TARGET) +BLU_BUILDS := $(BLU_BUILDS) $(BLU_TARGET) endef $(foreach BUILD,$(MCU_BUILDS),$(foreach PIN,$(BOOTLOADER_PINS),$(eval $(call CREATE_BOOTLOADER_TARGET,$(BUILD),$(PIN))))) bootloaders: $(ALL_BUILDS) +updaters: $(BLU_BUILDS) + # include the targets for installing tools include $(ROOT)/make/tools_install.mk @@ -167,3 +206,7 @@ include $(ROOT)/make/tools_install.mk targets: $(QUIET)echo List of targets. To build a target use 'make TARGETNAME' $(QUIET)echo $(ALL_BUILDS) + +updater_targets: + $(QUIET)echo List of updater targets. To build a target use 'make TARGETNAME' + $(QUIET)echo $(BLU_BUILDS) diff --git a/Mcu/l431/Inc/blutil.h b/Mcu/l431/Inc/blutil.h index 625e8b2b..fa0e336d 100644 --- a/Mcu/l431/Inc/blutil.h +++ b/Mcu/l431/Inc/blutil.h @@ -148,6 +148,7 @@ void Error_Handler() while (1) {} } +#ifdef FIRMWARE_RELATIVE_START /* jump from the bootloader to the application code */ @@ -170,6 +171,7 @@ static inline void jump_to_application(void) "bx %1 \n" : : "r"(stack_top), "r"(JumpAddress) :); } +#endif // FIRMWARE_RELATIVE_START void SystemInit(void) { diff --git a/Mcu/v203/Link_BLU.ld b/Mcu/v203/Link_BLU.ld new file mode 100644 index 00000000..f16834f2 --- /dev/null +++ b/Mcu/v203/Link_BLU.ld @@ -0,0 +1,138 @@ +/* + linker script for CH32V203 bootloader updater +*/ +ENTRY( _start ) + +__stack_size = 2048; + +PROVIDE( _stack_size = __stack_size ); + +MEMORY +{ + /* + note that flash for eeprom is at 0x08000000, but we flash at 0x00000000 for link + */ + FLASH (rx) : ORIGIN = 0x00001000, LENGTH = 8K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 20K +} + + +SECTIONS +{ + + .init : + { + _sinit = .; + . = ALIGN(4); + KEEP(*(SORT_NONE(.init))) + . = ALIGN(4); + _einit = .; + } >FLASH AT>FLASH + + .vector : + { + *(.vector); + . = ALIGN(64); + } >FLASH AT>FLASH + + .text : + { + . = ALIGN(4); + *(.text) + *(.text.*) + *(.rodata) + *(.rodata*) + *(.gnu.linkonce.t.*) + . = ALIGN(4); + } >FLASH AT>FLASH + + .fini : + { + KEEP(*(SORT_NONE(.fini))) + . = ALIGN(4); + } >FLASH AT>FLASH + + PROVIDE( _etext = . ); + PROVIDE( _eitcm = . ); + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH AT>FLASH + + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*))) + KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH AT>FLASH + + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*))) + KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH AT>FLASH + + .dalign : + { + . = ALIGN(4); + PROVIDE(_data_vma = .); + } >RAM AT>FLASH + + .dlalign : + { + . = ALIGN(4); + PROVIDE(_data_lma = .); + } >FLASH AT>FLASH + + .data : + { + *(.gnu.linkonce.r.*) + *(.data .data.*) + *(.gnu.linkonce.d.*) + . = ALIGN(8); + PROVIDE( __global_pointer$ = . + 0x800 ); + *(.sdata .sdata.*) + *(.sdata2.*) + *(.gnu.linkonce.s.*) + . = ALIGN(8); + *(.srodata.cst16) + *(.srodata.cst8) + *(.srodata.cst4) + *(.srodata.cst2) + *(.srodata .srodata.*) + . = ALIGN(4); + PROVIDE( _edata = .); + } >RAM AT>FLASH + + .bss : + { + . = ALIGN(4); + PROVIDE( _sbss = .); + *(.sbss*) + *(.gnu.linkonce.sb.*) + *(.bss*) + *(.gnu.linkonce.b.*) + *(COMMON*) + . = ALIGN(4); + PROVIDE( _ebss = .); + } >RAM AT>FLASH + + PROVIDE( _end = _ebss); + PROVIDE( end = . ); + + .stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size : + { + PROVIDE( _heap_end = . ); + . = ALIGN(4); + PROVIDE(_susrstack = . ); + . = . + __stack_size; + PROVIDE( _eusrstack = .); + } >RAM + +} diff --git a/bl_update/ldscript_bl.ld b/bl_update/ldscript_bl.ld new file mode 100644 index 00000000..8f5f4eb5 --- /dev/null +++ b/bl_update/ldscript_bl.ld @@ -0,0 +1,135 @@ +/* + linker file for AM32 bootloader updater +*/ + +/* Entry Point */ +ENTRY(Reset_Handler) + +_estack = 0x20001000; /* end of RAM */ +_Min_Heap_Size = 0x200; /* required amount of heap */ +_Min_Stack_Size = 0x400; /* required amount of stack */ + +/* Specify the memory areas */ +MEMORY +{ +FLASH (rx) : ORIGIN = 0x08001000, LENGTH = 8K +RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 4K +} + +/* Define output sections */ +SECTIONS +{ + /* The startup code goes first into FLASH */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data goes into FLASH */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data goes into FLASH */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + /* used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections goes into RAM, load LMA copy after code */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + } >RAM AT> FLASH + + /* Uninitialized data section */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss secion */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + /* User_heap_stack section, used to check that there is enough RAM left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + /* Remove information from the standard libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} diff --git a/bl_update/main.c b/bl_update/main.c new file mode 100644 index 00000000..e741d9f3 --- /dev/null +++ b/bl_update/main.c @@ -0,0 +1,98 @@ +/* + bootloader update firmware + + this updates the bootloader on an AM32 ESC. It assumes the + bootloader flash sectors are unlocked + */ +#include +#include + +#include +#include +#include "eeprom.h" + +#pragma GCC optimize("O0") + +#include + +#define GPIO_PORT_TYPE typeof(GPIOA) + +// dummy pin and port so we can re-use blutil.h +static GPIO_PORT_TYPE input_port; +static uint32_t input_pin; +#define FIRMWARE_RELATIVE_START 0x1000 + +#define MCU_FLASH_START 0x08000000 + +/* + use stringize to construct an include of the right bootloader header + */ +#define bl_header BL_HEADER_FILE +#define xstr(x) #x +#define str(x) xstr(x) +#include str(bl_header) + +#include + +static void delayMicroseconds(uint32_t micros) +{ + while (micros > 0) { + uint32_t us = micros>10000?10000:micros; + bl_timer_reset(); + while (bl_timer_us() < us) ; + micros -= us; + } +} + +static void flash_bootloader(void) +{ + uint32_t length = sizeof(bl_image); + uint32_t address = MCU_FLASH_START; + const uint8_t *bl = &bl_image[0]; + + while (length > 0) { + uint32_t chunk = 256; + if (chunk > length) { + chunk = length; + } + // loop until the flash succeeds. We expect it to pass + // first time, so this is paranoia + while (!save_flash_nolib(bl, chunk, address)) { + } + length -= chunk; + address += chunk; + bl += chunk; + } +} + +int main(void) +{ + bl_clock_config(); + bl_timer_init(); + + // give 1.5s for debugger to attach + delayMicroseconds(1500000); + + // don't risk erasing the bootloader if it already matches + if (memcmp((const void*)MCU_FLASH_START, bl_image, sizeof(bl_image)) != 0) { + flash_bootloader(); + } + + /* + wipe eeprom header to ensure we don't boot this firmware + again. We wipe all 3 possible eeprom addresses for 32k, 64k and + 128k boards + + On boards with 32k of flash the 2nd two will fail. On boards + with 64k flash the last one will fail + */ + const uint8_t zeros[8] = {0}; + save_flash_nolib(zeros, sizeof(zeros), MCU_FLASH_START+0x7c00); + save_flash_nolib(zeros, sizeof(zeros), MCU_FLASH_START+0xf800); + save_flash_nolib(zeros, sizeof(zeros), MCU_FLASH_START+0x1f800); + + // if we got here then reboot + NVIC_SystemReset(); + + return 0; +} diff --git a/bl_update/make_binheader.py b/bl_update/make_binheader.py new file mode 100755 index 00000000..024be0be --- /dev/null +++ b/bl_update/make_binheader.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +''' +convert a binary file to a C header +''' + +import sys + +def binary_to_c_header(binary_filename, header_filename, array_name="bl_image", pad=8): + """ + Reads a binary file and writes a C header file with a constant uint8_t array. + + :param binary_filename: The path to the binary file to read. + :param header_filename: The path to the C header file to write. + :param array_name: The name of the array variable in the generated C code. + """ + try: + # Read the binary file + with open(binary_filename, 'rb') as bin_file: + binary_data = bin_file.read() + + # possibly pad with zeros + if len(binary_data) % pad != 0: + pad_len = pad - len(binary_data) % pad + pad_bytes = bytes([0]*pad_len) + binary_data += pad_bytes + + # Open the header file for writing + with open(header_filename, 'w') as header_file: + # Write header guard + guard_macro = '{}_H'.format(array_name.upper()) + header_file.write(f'// generated from {binary_filename}\n') + header_file.write('#pragma once\n') + header_file.write('#include \n\n') + + # Write the array declaration + header_file.write('static const uint8_t {}[] = {{\n'.format(array_name)) + + # Convert binary data to a list of hex strings + hex_values = ['0x{:02X}'.format(b) for b in binary_data] + + # Define how many values to include per line + line_length = 16 # Adjust this for more or fewer per line + + # Write the hex values into the array + for i in range(0, len(hex_values), line_length): + line = ', '.join(hex_values[i:i+line_length]) + if i + line_length >= len(hex_values): + # Last line without trailing comma + header_file.write(' {}\n'.format(line)) + else: + header_file.write(' {},\n'.format(line)) + + header_file.write('};\n\n') + + print("Wrote {}".format(header_filename)) + + except IOError as e: + print("An I/O error occurred: {}".format(e)) + sys.exit(1) + +from argparse import ArgumentParser +parser = ArgumentParser(description=__doc__) + +parser.add_argument("binfile", help="binary input file") +parser.add_argument("header", help="C header output file") +args = parser.parse_args() + +binary_to_c_header(args.binfile, args.header) +sys.exit(0) diff --git a/v203makefile.mk b/v203makefile.mk index dc6bcfc0..bdaf0454 100644 --- a/v203makefile.mk +++ b/v203makefile.mk @@ -5,6 +5,7 @@ RISCV_SDK_PREFIX := tools/$(OSDIR)/riscv-embedded-gcc/bin/riscv-none-embed- $(MCU)_CC := $(RISCV_SDK_PREFIX)gcc $(MCU)_OBJCOPY := $(RISCV_SDK_PREFIX)objcopy $(MCU)_LDSCRIPT := Mcu/v203/Link.ld +$(MCU)_LDSCRIPT_BLU := Mcu/v203/Link_BLU.ld MCU_LC := $(call lc,$(MCU))