From 16289c720a0f63d636faaaf4d4432496a8aa4231 Mon Sep 17 00:00:00 2001 From: Vegard Storheil Eriksen Date: Fri, 19 Aug 2016 01:54:24 +0200 Subject: Ported bootloader from arcin. --- .gdbinit | 9 +- SConstruct | 5 +- bootloader.cpp | 306 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bootloader.ld | 6 ++ hidapi.py | 19 ++++ hidflash.py | 90 +++++++++++++++++ laks | 2 +- main.ld | 6 ++ 8 files changed, 439 insertions(+), 4 deletions(-) create mode 100644 bootloader.cpp create mode 100644 bootloader.ld create mode 100644 hidapi.py create mode 100755 hidflash.py create mode 100644 main.ld diff --git a/.gdbinit b/.gdbinit index 99eae86..4699cc9 100644 --- a/.gdbinit +++ b/.gdbinit @@ -1,5 +1,10 @@ define flash -file demo.elf +file main.elf +load +end + +define flash_bootloader +file bootloader.elf load end @@ -17,6 +22,6 @@ mon jtag_scan attach 1 end -file demo.elf +file main.elf set mem inaccessible-by-default off diff --git a/SConstruct b/SConstruct index 6926505..0bcf8f6 100644 --- a/SConstruct +++ b/SConstruct @@ -8,4 +8,7 @@ SConscript('laks/build_rules') env.SelectMCU('stm32l052c8') -env.Firmware('demo.elf', Glob('*.cpp')) +env.Firmware('main.elf', ['main.cpp'], LINK_SCRIPT = 'main.ld') + +env.Firmware('bootloader.elf', ['bootloader.cpp'], LINK_SCRIPT = 'bootloader.ld') + diff --git a/bootloader.cpp b/bootloader.cpp new file mode 100644 index 0000000..a2cf77c --- /dev/null +++ b/bootloader.cpp @@ -0,0 +1,306 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +Pin button = GPIOA[3]; +Pin led = GPIOA[4]; + +static uint32_t& reset_reason = *(uint32_t*)0x10000000; +static const uint32_t* firmware_vtors = (uint32_t*)0x8002000; + +static bool do_reset; + +void reset() { + SCB.AIRCR = (0x5fa << 16) | (1 << 2); // SYSRESETREQ +} + +void chainload(uint32_t offset) { + SCB.VTOR = offset; + + asm volatile("ldr r1, [%0]; mov sp, r1; ldr %0, [%0, #4]; bx %0" :: "r" (offset) : "r1"); + + while(1); +} + +auto report_desc = pack( + usage_page(0xff55), + usage(0xb007), + collection(Collection::Application, + logical_minimum(0), + logical_maximum(255), + report_size(8), + report_count(1), + + usage(0xb007), + input(0x02), // Status + + usage(0xb007), + feature(0x02), // Function + + usage(0xb007), + report_count(64), + output(0x02) // Data + ) +); + +auto dev_desc = device_desc(0x200, 0, 0, 0, 64, 0x1d50, 0x60f7, 0x100, 1, 2, 3, 1); +auto conf_desc = configuration_desc(1, 1, 0, 0xc0, 0, + // HID interface. + interface_desc(0, 0, 1, 0x03, 0x00, 0x00, 0, + hid_desc(0x111, 0, 1, 0x22, sizeof(report_desc)), + endpoint_desc(0x81, 0x03, 64, 1) + ) +); + +desc_t dev_desc_p = {sizeof(dev_desc), (void*)&dev_desc}; +desc_t conf_desc_p = {sizeof(conf_desc), (void*)&conf_desc}; +desc_t report_desc_p = {sizeof(report_desc), (void*)&report_desc}; + +USB_l0 usb(USB, dev_desc_p, conf_desc_p); + +class Flashloader { + private: + bool state; + uint32_t addr; + + public: + Flashloader() : state(false) {} + + bool prepare() { + addr = 0x8002000; + state = true; + + // Unlock flash. + FLASH.PEKEYR = 0x89ABCDEF; + FLASH.PEKEYR = 0x02030405; + FLASH.PRGKEYR = 0x8C9DAEBF; + FLASH.PRGKEYR = 0x13141516; + + return true; + } + + bool write_block(uint32_t size, void* data) { + if(!state) { + return false; + } + + if(size & (4 - 1)) { + return false; + } + + if(addr + size > 0x8010000) { + return false; + } + + if(!(addr & (128 - 1))) { + // Erase page. + + FLASH.PECR = (1 << 9) | (1 << 3); // ERASE, PROG + while(FLASH.SR & (1 << 0)); // BSY + + *(uint32_t*)addr = 0; + } + + uint32_t* src = (uint32_t*)data; + uint32_t* dest = (uint32_t*)addr; + + for(uint32_t n = 0; n < size; n += 4) { + FLASH.PECR = 0; + while(FLASH.SR & (1 << 0)); // BSY + + *dest++ = *src++; + } + + addr += size; + return true; + } + + bool finish() { + state = false; + + FLASH.PECR = (1 << 1) | (1 << 0); // PRGLOCK, PELOCK + + return true; + } +}; + +Flashloader flashloader; + +class HID_bootloader : public USB_HID { + public: + HID_bootloader(USB_generic& usbd, desc_t rdesc) : USB_HID(usbd, rdesc, 0, 1, 64) {} + + protected: + virtual bool set_output_report(uint32_t* buf, uint32_t len) { + if(len != 64) { + return false; + } + + return flashloader.write_block(len, buf); + } + + virtual bool set_feature_report(uint32_t* buf, uint32_t len) { + if(len != 1) { + return false; + } + + switch(*buf & 0xff) { + case 0: + return true; + + case 0x10: // Reset to bootloader + return false; // Not available in bootloader mode + + case 0x11: // Reset to runtime + do_reset = true; + return true; + + case 0x20: // Flash prepare + return flashloader.prepare(); + + case 0x21: // Flash finish + return flashloader.finish(); + + default: + return false; + } + } +}; + +HID_bootloader usb_hid(usb, report_desc_p); + +uint32_t serial_num() { + uint32_t* uid = (uint32_t*)0x1ff80050; + + return uid[0] * uid[1] * uid[5]; +} + +class USB_strings : public USB_class_driver { + private: + USB_generic& usb; + + public: + USB_strings(USB_generic& usbd) : usb(usbd) { + usb.register_driver(this); + } + + protected: + virtual SetupStatus handle_setup(uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, uint16_t wLength) { + // Get string descriptor. + if(bmRequestType == 0x80 && bRequest == 0x06 && (wValue & 0xff00) == 0x0300) { + const void* desc = nullptr; + uint16_t buf[9]; + + switch(wValue & 0xff) { + case 0: + desc = u"\u0304\u0409"; + break; + + case 1: + desc = u"\u0308zyp"; + break; + + case 2: + desc = u"\u0322arcin bootloader"; + break; + + case 3: + { + buf[0] = 0x0312; + uint32_t id = serial_num(); + for(int i = 8; i > 0; i--) { + buf[i] = (id & 0xf) > 9 ? 'A' + (id & 0xf) - 0xa : '0' + (id & 0xf); + id >>= 4; + } + desc = buf; + } + break; + } + + if(!desc) { + return SetupStatus::Unhandled; + } + + uint8_t len = *(uint8_t*)desc; + + if(len > wLength) { + len = wLength; + } + + usb.write(0, (uint32_t*)desc, len); + + return SetupStatus::Ok; + } + + return SetupStatus::Unhandled; + } +}; + +USB_strings usb_strings(usb); + +bool normal_boot() { + // Check if this was a reset-to-bootloader. + //if(reset_reason == 0xb007) { + // reset_reason = 0; + // return false; + //} + + // Check that reset vector is a valid flash address. + uint32_t reset_vector = firmware_vtors[1]; + if(reset_vector < 0x8002000 || reset_vector >= 0x8010000) { + return false; + } + + // Check buttons. + if(!button.get()) { + return false; + } + + // No reason to enter bootloader. + return true; +} + +int main() { + RCC.enable(RCC.GPIOA); + RCC.enable(RCC.GPIOB); + RCC.enable(RCC.GPIOC); + + button.set_mode(Pin::Input); + button.set_pull(Pin::PullUp); + + if(normal_boot()) { + chainload(0x8002000); + } + + rcc_init(); + + // Initialize system timer. + STK.LOAD = 32000000 / 8 / 1000; // 1000 Hz. + STK.VAL = 0; + STK.CTRL = 0x03; + + led.set_mode(Pin::Output); + + RCC.enable(RCC.USB); + + usb.init(); + + Time::sleep(10); + USB.reg.BCDR |= 1 << 15; + + while(1) { + usb.process(); + + if(do_reset) { + Time::sleep(10); + reset(); + } + + led.set(Time::time() & 512); + } +} diff --git a/bootloader.ld b/bootloader.ld new file mode 100644 index 0000000..c7c947f --- /dev/null +++ b/bootloader.ld @@ -0,0 +1,6 @@ +MEMORY { + flash (rx) : org = 0x08000000, len = 8k + ram (rwx) : org = 0x20000000, len = 8k +} + +INCLUDE "arm_flash_ram.ld" diff --git a/hidapi.py b/hidapi.py new file mode 100644 index 0000000..06ee90c --- /dev/null +++ b/hidapi.py @@ -0,0 +1,19 @@ +import ctypes, ctypes.util + +path = ctypes.util.find_library('hidapi') + +if not path: + raise ImportError('Cannot find hidapi library') + +hidapi = ctypes.CDLL(path) + +hidapi.hid_open.argtypes = [ctypes.c_ushort, ctypes.c_ushort, ctypes.c_wchar_p] +hidapi.hid_open.restype = ctypes.c_void_p + +hidapi.hid_close.argtypes = [ctypes.c_void_p] + +hidapi.hid_read_timeout.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_int] +hidapi.hid_read.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] +hidapi.hid_write.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] +hidapi.hid_send_feature_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] +hidapi.hid_get_feature_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] diff --git a/hidflash.py b/hidflash.py new file mode 100755 index 0000000..a9df48c --- /dev/null +++ b/hidflash.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python + +from hidapi import hidapi +from elftools.elf.elffile import ELFFile + +import ctypes, time, sys + +e = ELFFile(open(sys.argv[1])) + +buf = '' + +for segment in sorted(e.iter_segments(), key = lambda x: x.header.p_paddr): + if segment.header.p_type != 'PT_LOAD': + continue + + data = segment.data() + lma = segment.header.p_paddr + + # Workaround for LD aligning segments to a larger boundary than 8k. + if lma == 0x8000000: + lma += 0x2000 + data = data[0x2000:] + + # Add padding if necessary. + buf += '\0' * (lma - 0x8002000 - len(buf)) + + buf += data + +# Align to 64B +if len(buf) & (64 - 1): + buf += '\0' * (64 - (len(buf) & (64 - 1))) + +# Open device +dev = hidapi.hid_open(0x1d50, 0x60f7, None) + +if not dev: + dev = hidapi.hid_open(0x1d50, 0x60f8, None) + + if not dev: + raise RuntimeError('Device not found.') + + print 'Found runtime device, resetting to bootloader.' + + # Reset bootloader + if hidapi.hid_send_feature_report(dev, ctypes.c_char_p('\x00\x10'), 2) != 2: + raise RuntimeError('Reset failed.') + + time.sleep(1) + + hidapi.hid_exit() + + dev = hidapi.hid_open(0x1d50, 0x60f7, None) + + if not dev: + raise RuntimeError('Device not found.') + +print 'Found bootloader device, starting flashing.' + +# Prepare +if hidapi.hid_send_feature_report(dev, ctypes.c_char_p('\x00\x20'), 2) != 2: + raise RuntimeError('Prepare failed.') + +# Flash +while buf: + if hidapi.hid_write(dev, ctypes.c_char_p('\x00' + buf[:64]), 65) != 65: + raise RuntimeError('Writing failed.') + buf = buf[64:] + +# Finish +if hidapi.hid_send_feature_report(dev, ctypes.c_char_p('\x00\x21'), 2) != 2: + raise RuntimeError('Finish failed.') + +print 'Flashing finished, resetting to runtime.' + +# Reset +if hidapi.hid_send_feature_report(dev, ctypes.c_char_p('\x00\x11'), 2) != 2: + raise RuntimeError('Reset failed.') + +time.sleep(1) + +hidapi.hid_exit() + +if hidapi.hid_open(0x1d50, 0x6080, None): + print 'Done, everything ok.' + +elif hidapi.hid_open(0x1d50, 0x6084, None): + print 'Still in bootloader mode.' + +else: + print 'Device disappeared.' diff --git a/laks b/laks index a6de1f8..037ba6e 160000 --- a/laks +++ b/laks @@ -1 +1 @@ -Subproject commit a6de1f8069e8eec1dead5952f203dc6ed69ecf5a +Subproject commit 037ba6e1e22e8577d7823f0abe22c331934a4d06 diff --git a/main.ld b/main.ld new file mode 100644 index 0000000..92c253c --- /dev/null +++ b/main.ld @@ -0,0 +1,6 @@ +MEMORY { + flash (rx) : org = 0x08002000, len = 56k + ram (rwx) : org = 0x20000000, len = 8k +} + +INCLUDE "arm_flash_ram.ld" -- cgit v1.2.3