2 * Generic DFU Bootloader
4 * (c) 2020 Martin Mareš <mj@ucw.cz>
6 * Based on example code from the libopencm3 project, which is
7 * Copyright (C) 2010 Gareth McMullin <gareth@blacksphere.co.nz>
9 * Licensed under the GNU LGPL v3 or any later version.
14 #include <libopencm3/cm3/cortex.h>
15 #include <libopencm3/cm3/nvic.h>
16 #include <libopencm3/cm3/scb.h>
17 #include <libopencm3/cm3/systick.h>
18 #include <libopencm3/stm32/rcc.h>
19 #include <libopencm3/stm32/crc.h>
20 #include <libopencm3/stm32/gpio.h>
21 #include <libopencm3/stm32/flash.h>
22 #include <libopencm3/stm32/usart.h>
23 #include <libopencm3/stm32/desig.h>
24 #include <libopencm3/usb/usbd.h>
25 #include <libopencm3/usb/dfu.h>
29 #ifdef BOOTLOADER_DEBUG
30 #define DEBUG(x...) debug_printf(x)
32 #define DEBUG(x...) do { } while (0)
35 // Offsets to firmware header fields (see tools/dfu-sign.c)
36 #define HDR_LENGTH 0x1c
37 #define HDR_FLASH_IN_PROGRESS 0x20
39 byte usbd_control_buffer[1024];
41 static enum dfu_state usbdfu_state = STATE_DFU_IDLE;
44 byte buf[sizeof(usbd_control_buffer)];
49 static char usb_serial_number[13];
57 static const char *usb_strings[] = {
63 const struct usb_device_descriptor dev = {
64 .bLength = USB_DT_DEVICE_SIZE,
65 .bDescriptorType = USB_DT_DEVICE,
70 .bMaxPacketSize0 = 64,
71 .idVendor = BOOTLOADER_MFG_ID,
72 .idProduct = BOOTLOADER_PROD_ID,
73 .bcdDevice = BOOTLOADER_PROD_VERSION,
74 .iManufacturer = STR_MANUFACTURER,
75 .iProduct = STR_PRODUCT,
76 .iSerialNumber = STR_SERIAL,
77 .bNumConfigurations = 1,
80 const struct usb_dfu_descriptor dfu_function = {
81 .bLength = sizeof(struct usb_dfu_descriptor),
82 .bDescriptorType = DFU_FUNCTIONAL,
83 .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
84 .wDetachTimeout = 255,
85 .wTransferSize = 1024,
86 .bcdDFUVersion = 0x0100,
89 const struct usb_interface_descriptor iface = {
90 .bLength = USB_DT_INTERFACE_SIZE,
91 .bDescriptorType = USB_DT_INTERFACE,
92 .bInterfaceNumber = 0,
93 .bAlternateSetting = 0,
95 .bInterfaceClass = 0xFE, /* Device Firmware Upgrade */
96 .bInterfaceSubClass = 1,
97 .bInterfaceProtocol = 2,
98 .extra = &dfu_function,
99 .extralen = sizeof(dfu_function),
102 const struct usb_interface ifaces[] = {{
104 .altsetting = &iface,
107 const struct usb_config_descriptor config = {
108 .bLength = USB_DT_CONFIGURATION_SIZE,
109 .bDescriptorType = USB_DT_CONFIGURATION,
112 .bConfigurationValue = 1,
114 .bmAttributes = USB_CONFIG_ATTR_DEFAULT, // bus-powered
115 .bMaxPower = 50, // multiplied by 2 mA
119 // FIXME: Rename usbdfu_ to dfu_
120 static byte usbdfu_getstatus(usbd_device *usbd_dev UNUSED, u32 *bwPollTimeout)
122 switch (usbdfu_state) {
123 case STATE_DFU_DNLOAD_SYNC:
124 usbdfu_state = STATE_DFU_DNBUSY;
125 *bwPollTimeout = 100;
126 return DFU_STATUS_OK;
127 case STATE_DFU_MANIFEST_SYNC:
128 /* Device will reset when read is complete. */
129 usbdfu_state = STATE_DFU_MANIFEST;
130 return DFU_STATUS_OK;
132 return DFU_STATUS_OK;
136 static void usbdfu_getstatus_complete(usbd_device *usbd_dev UNUSED, struct usb_setup_data *req UNUSED)
138 switch (usbdfu_state) {
139 case STATE_DFU_DNBUSY:
140 if (prog.blocknum == 0)
141 *(u16*)(prog.buf + HDR_FLASH_IN_PROGRESS) = 0xffff;
143 u32 baseaddr = BOOTLOADER_APP_START + prog.blocknum * dfu_function.wTransferSize;
144 DEBUG("DFU: Block %u -> %08x + %u\n", prog.blocknum, (uint) baseaddr, prog.len);
145 flash_erase_page(baseaddr);
146 for (uint i = 0; i < prog.len; i += 2) {
147 u16 data = *(u16 *)(prog.buf + i);
148 flash_program_half_word(baseaddr + i, data);
151 usbdfu_state = STATE_DFU_DNLOAD_IDLE;
153 case STATE_DFU_MANIFEST:
154 // At the very end, program the first page
157 flash_program_half_word(BOOTLOADER_APP_START + 0x20, 0);
159 usbdfu_state = STATE_DFU_MANIFEST_WAIT_RESET;
166 static enum usbd_request_return_codes usbdfu_control_request(usbd_device *usbd_dev,
167 struct usb_setup_data *req,
170 void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
172 if ((req->bmRequestType & 0x7F) != 0x21)
173 return USBD_REQ_NOTSUPP; /* Only accept class request. */
175 DEBUG("DFU: Request %02x in state %d\n", req->bRequest, usbdfu_state);
177 switch (req->bRequest) {
179 if (len == NULL || *len == 0) {
180 usbdfu_state = STATE_DFU_MANIFEST_SYNC;
182 /* Copy download data for use on GET_STATUS. */
183 prog.blocknum = req->wValue;
185 memcpy(prog.buf, *buf, *len);
186 usbdfu_state = STATE_DFU_DNLOAD_SYNC;
188 return USBD_REQ_HANDLED;
190 /* Clear error and return to dfuIDLE. */
191 if (usbdfu_state == STATE_DFU_ERROR)
192 usbdfu_state = STATE_DFU_IDLE;
193 return USBD_REQ_HANDLED;
195 /* Abort returns to dfuIDLE state. */
196 usbdfu_state = STATE_DFU_IDLE;
197 return USBD_REQ_HANDLED;
199 /* Upload not supported for now. */
200 return USBD_REQ_NOTSUPP;
201 case DFU_GETSTATUS: {
202 u32 bwPollTimeout = 0; /* 24-bit number of milliseconds */
203 (*buf)[0] = usbdfu_getstatus(usbd_dev, &bwPollTimeout);
204 (*buf)[1] = bwPollTimeout & 0xFF;
205 (*buf)[2] = (bwPollTimeout >> 8) & 0xFF;
206 (*buf)[3] = (bwPollTimeout >> 16) & 0xFF;
207 (*buf)[4] = usbdfu_state;
208 (*buf)[5] = 0; /* iString not used here */
210 *complete = usbdfu_getstatus_complete;
211 return USBD_REQ_HANDLED;
214 /* Return state with no state transition. */
215 *buf[0] = usbdfu_state;
217 return USBD_REQ_HANDLED;
220 return USBD_REQ_NOTSUPP;
223 static void usbdfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
225 usbd_register_control_callback(
227 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
228 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
229 usbdfu_control_request);
232 static void usbdfu_reset(void)
234 usbdfu_state = STATE_DFU_IDLE;
238 * This is a modified version of rcc_clock_setup_in_hsi_out_48mhz(),
239 * which properly turns off the PLL before setting its parameters.
241 static void my_rcc_clock_setup_in_hsi_out_48mhz(void)
243 /* Enable internal high-speed oscillator. */
245 rcc_wait_for_osc_ready(RCC_HSI);
247 /* Select HSI as SYSCLK source. */
248 rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
251 rcc_osc_off(RCC_PLL);
254 * Set prescalers for AHB, ADC, ABP1, ABP2.
255 * Do this before touching the PLL (TODO: why?).
257 rcc_set_hpre(RCC_CFGR_HPRE_SYSCLK_NODIV); /*Set.48MHz Max.72MHz */
258 rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV8); /*Set. 6MHz Max.14MHz */
259 rcc_set_ppre1(RCC_CFGR_PPRE1_HCLK_DIV2); /*Set.24MHz Max.36MHz */
260 rcc_set_ppre2(RCC_CFGR_PPRE2_HCLK_NODIV); /*Set.48MHz Max.72MHz */
261 rcc_set_usbpre(RCC_CFGR_USBPRE_PLL_CLK_NODIV); /*Set.48MHz Max.48MHz */
264 * Sysclk runs with 48MHz -> 1 waitstates.
269 flash_set_ws(FLASH_ACR_LATENCY_1WS);
272 * Set the PLL multiplication factor to 12.
273 * 8MHz (internal) * 12 (multiplier) / 2 (PLLSRC_HSI_CLK_DIV2) = 48MHz
275 rcc_set_pll_multiplication_factor(RCC_CFGR_PLLMUL_PLL_CLK_MUL12);
277 /* Select HSI/2 as PLL source. */
278 rcc_set_pll_source(RCC_CFGR_PLLSRC_HSI_CLK_DIV2);
280 /* Enable PLL oscillator and wait for it to stabilize. */
282 rcc_wait_for_osc_ready(RCC_PLL);
284 /* Select PLL as SYSCLK source. */
285 rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_PLLCLK);
287 /* Set the peripheral clock frequencies used */
288 rcc_ahb_frequency = 48000000;
289 rcc_apb1_frequency = 24000000;
290 rcc_apb2_frequency = 48000000;
293 static void clock_plain_hsi(void)
295 // Select HSI as SYSCLK source
296 rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
299 rcc_osc_off(RCC_PLL);
301 // Set prescalers for AHB, ADC, ABP1, ABP2, USB to defaults
302 rcc_set_hpre(RCC_CFGR_HPRE_SYSCLK_NODIV);
303 rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV2);
304 rcc_set_ppre1(RCC_CFGR_PPRE1_HCLK_NODIV);
305 rcc_set_ppre2(RCC_CFGR_PPRE2_HCLK_NODIV);
306 rcc_set_usbpre(RCC_CFGR_USBPRE_PLL_VCO_CLK_DIV3);
309 static void reset_peripherals(void)
311 // Turn off clock to all peripherals and reset them
312 RCC_AHBENR = 0x00000014;
315 RCC_APB1RSTR = 0x22fec9ff;
316 RCC_APB2RSTR = 0x0038fffd;
323 usbd_device *usbd_dev;
327 // Flash programming requires running on the internal oscillator
328 my_rcc_clock_setup_in_hsi_out_48mhz();
330 rcc_periph_clock_enable(RCC_GPIOA);
331 rcc_periph_clock_enable(RCC_GPIOC);
332 rcc_periph_clock_enable(RCC_USB);
333 rcc_periph_clock_enable(RCC_CRC);
336 // Currently, only USART1 is supported
337 rcc_periph_clock_enable(RCC_USART1);
338 rcc_periph_reset_pulse(RST_USART1);
339 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
341 usart_set_baudrate(USART1, 115200);
342 usart_set_databits(USART1, 8);
343 usart_set_stopbits(USART1, USART_STOPBITS_1);
344 usart_set_mode(USART1, USART_MODE_TX);
345 usart_set_parity(USART1, USART_PARITY_NONE);
346 usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
348 usart_enable(USART1);
351 #ifdef DEBUG_LED_BLUEPILL
353 gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
357 // Systick: set to overflow in 1 ms, will use only the overflow flag, no interrupts
358 systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
360 systick_counter_enable();
362 desig_get_unique_id_as_dfu(usb_serial_number);
364 DEBUG("DFU: Entered boot-loader (SN %s)\n", usb_serial_number);
366 // Simulate USB disconnect
367 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
368 gpio_clear(GPIOA, GPIO11 | GPIO12);
369 for (uint i=0; i<100; i++) {
370 while (!systick_get_countflag())
374 DEBUG("DFU: Ready\n");
377 usbd_dev = usbd_init(&st_usbfs_v1_usb_driver, &dev, &config, usb_strings, ARRAY_SIZE(usb_strings), usbd_control_buffer, sizeof(usbd_control_buffer));
378 usbd_register_reset_callback(usbd_dev, usbdfu_reset);
379 usbd_register_set_config_callback(usbd_dev, usbdfu_set_config);
384 while (timeout || (usbdfu_state != STATE_DFU_IDLE && usbdfu_state != STATE_DFU_MANIFEST_WAIT_RESET)) {
386 if (timeout && systick_get_countflag()) {
388 if (!(timeout & 0x3f))
393 u32 *app = (u32 *) BOOTLOADER_APP_START;
396 u32 len = app[HDR_LENGTH/4];
397 u16 flash_in_progress = *(u16 *)(BOOTLOADER_APP_START + HDR_FLASH_IN_PROGRESS);
400 u32 crc = crc_calculate_block(app, len/4);
401 u32 want_crc = *(u32 *)(BOOTLOADER_APP_START + len);
402 DEBUG("DFU: fip=%04x, crc=%08x, want=%08x, len=%u\n", (uint) flash_in_progress, (uint) crc, (uint) want_crc, (uint) len);
403 if (flash_in_progress || crc != want_crc) {
404 DEBUG("DFU: Bad firmware\n");
408 DEBUG("DFU: Starting application (sp=%08x, pc=%08x)\n", (uint) sp, (uint) pc);
411 while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
419 /* Set vector table base address. */
420 SCB_VTOR = BOOTLOADER_APP_START;
422 /* Initialize master stack pointer. */
423 asm volatile("msr msp, %0"::"g" (sp));
425 /* Jump to application. */
426 ((void (*)(void)) pc)();