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 dfu_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 static byte dfu_getstatus(usbd_device *usbd_dev UNUSED, u32 *bwPollTimeout)
122 case STATE_DFU_DNLOAD_SYNC:
123 dfu_state = STATE_DFU_DNBUSY;
124 *bwPollTimeout = 100;
125 return DFU_STATUS_OK;
126 case STATE_DFU_MANIFEST_SYNC:
127 /* Device will reset when read is complete. */
128 dfu_state = STATE_DFU_MANIFEST;
129 return DFU_STATUS_OK;
131 return DFU_STATUS_OK;
135 static void dfu_getstatus_complete(usbd_device *usbd_dev UNUSED, struct usb_setup_data *req UNUSED)
138 case STATE_DFU_DNBUSY:
139 if (prog.blocknum == 0)
140 *(u16*)(prog.buf + HDR_FLASH_IN_PROGRESS) = 0xffff;
142 u32 baseaddr = BOOTLOADER_APP_START + prog.blocknum * dfu_function.wTransferSize;
143 DEBUG("DFU: Block %u -> %08x + %u\n", prog.blocknum, (uint) baseaddr, prog.len);
144 flash_erase_page(baseaddr);
145 for (uint i = 0; i < prog.len; i += 2) {
146 u16 data = *(u16 *)(prog.buf + i);
147 flash_program_half_word(baseaddr + i, data);
150 dfu_state = STATE_DFU_DNLOAD_IDLE;
152 case STATE_DFU_MANIFEST:
153 // At the very end, program the first page
156 flash_program_half_word(BOOTLOADER_APP_START + 0x20, 0);
158 dfu_state = STATE_DFU_MANIFEST_WAIT_RESET;
165 static enum usbd_request_return_codes dfu_control_request(usbd_device *usbd_dev,
166 struct usb_setup_data *req,
169 void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
171 if ((req->bmRequestType & 0x7F) != 0x21)
172 return USBD_REQ_NOTSUPP; /* Only accept class request. */
174 DEBUG("DFU: Request %02x in state %d\n", req->bRequest, dfu_state);
176 switch (req->bRequest) {
178 if (len == NULL || *len == 0) {
179 dfu_state = STATE_DFU_MANIFEST_SYNC;
181 /* Copy download data for use on GET_STATUS. */
182 prog.blocknum = req->wValue;
184 memcpy(prog.buf, *buf, *len);
185 dfu_state = STATE_DFU_DNLOAD_SYNC;
187 return USBD_REQ_HANDLED;
189 /* Clear error and return to dfuIDLE. */
190 if (dfu_state == STATE_DFU_ERROR)
191 dfu_state = STATE_DFU_IDLE;
192 return USBD_REQ_HANDLED;
194 /* Abort returns to dfuIDLE state. */
195 dfu_state = STATE_DFU_IDLE;
196 return USBD_REQ_HANDLED;
198 /* Upload not supported for now. */
199 return USBD_REQ_NOTSUPP;
200 case DFU_GETSTATUS: {
201 u32 bwPollTimeout = 0; /* 24-bit number of milliseconds */
202 (*buf)[0] = dfu_getstatus(usbd_dev, &bwPollTimeout);
203 (*buf)[1] = bwPollTimeout & 0xFF;
204 (*buf)[2] = (bwPollTimeout >> 8) & 0xFF;
205 (*buf)[3] = (bwPollTimeout >> 16) & 0xFF;
206 (*buf)[4] = dfu_state;
207 (*buf)[5] = 0; /* iString not used here */
209 *complete = dfu_getstatus_complete;
210 return USBD_REQ_HANDLED;
213 /* Return state with no state transition. */
216 return USBD_REQ_HANDLED;
219 return USBD_REQ_NOTSUPP;
222 static void dfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
224 usbd_register_control_callback(
226 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
227 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
228 dfu_control_request);
231 static void dfu_reset(void)
233 dfu_state = STATE_DFU_IDLE;
237 * This is a modified version of rcc_clock_setup_in_hsi_out_48mhz(),
238 * which properly turns off the PLL before setting its parameters.
240 static void my_rcc_clock_setup_in_hsi_out_48mhz(void)
242 /* Enable internal high-speed oscillator. */
244 rcc_wait_for_osc_ready(RCC_HSI);
246 /* Select HSI as SYSCLK source. */
247 rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
250 rcc_osc_off(RCC_PLL);
253 * Set prescalers for AHB, ADC, ABP1, ABP2.
254 * Do this before touching the PLL (TODO: why?).
256 rcc_set_hpre(RCC_CFGR_HPRE_SYSCLK_NODIV); /*Set.48MHz Max.72MHz */
257 rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV8); /*Set. 6MHz Max.14MHz */
258 rcc_set_ppre1(RCC_CFGR_PPRE1_HCLK_DIV2); /*Set.24MHz Max.36MHz */
259 rcc_set_ppre2(RCC_CFGR_PPRE2_HCLK_NODIV); /*Set.48MHz Max.72MHz */
260 rcc_set_usbpre(RCC_CFGR_USBPRE_PLL_CLK_NODIV); /*Set.48MHz Max.48MHz */
263 * Sysclk runs with 48MHz -> 1 waitstates.
268 flash_set_ws(FLASH_ACR_LATENCY_1WS);
271 * Set the PLL multiplication factor to 12.
272 * 8MHz (internal) * 12 (multiplier) / 2 (PLLSRC_HSI_CLK_DIV2) = 48MHz
274 rcc_set_pll_multiplication_factor(RCC_CFGR_PLLMUL_PLL_CLK_MUL12);
276 /* Select HSI/2 as PLL source. */
277 rcc_set_pll_source(RCC_CFGR_PLLSRC_HSI_CLK_DIV2);
279 /* Enable PLL oscillator and wait for it to stabilize. */
281 rcc_wait_for_osc_ready(RCC_PLL);
283 /* Select PLL as SYSCLK source. */
284 rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_PLLCLK);
286 /* Set the peripheral clock frequencies used */
287 rcc_ahb_frequency = 48000000;
288 rcc_apb1_frequency = 24000000;
289 rcc_apb2_frequency = 48000000;
292 static void clock_plain_hsi(void)
294 // Select HSI as SYSCLK source
295 rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
298 rcc_osc_off(RCC_PLL);
300 // Set prescalers for AHB, ADC, ABP1, ABP2, USB to defaults
301 rcc_set_hpre(RCC_CFGR_HPRE_SYSCLK_NODIV);
302 rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV2);
303 rcc_set_ppre1(RCC_CFGR_PPRE1_HCLK_NODIV);
304 rcc_set_ppre2(RCC_CFGR_PPRE2_HCLK_NODIV);
305 rcc_set_usbpre(RCC_CFGR_USBPRE_PLL_VCO_CLK_DIV3);
308 static void reset_peripherals(void)
310 // Turn off clock to all peripherals and reset them
311 RCC_AHBENR = 0x00000014;
314 RCC_APB1RSTR = 0x22fec9ff;
315 RCC_APB2RSTR = 0x0038fffd;
322 usbd_device *usbd_dev;
326 // Flash programming requires running on the internal oscillator
327 my_rcc_clock_setup_in_hsi_out_48mhz();
329 rcc_periph_clock_enable(RCC_GPIOA);
330 rcc_periph_clock_enable(RCC_GPIOC);
331 rcc_periph_clock_enable(RCC_USB);
332 rcc_periph_clock_enable(RCC_CRC);
335 // Currently, only USART1 is supported
336 rcc_periph_clock_enable(RCC_USART1);
337 rcc_periph_reset_pulse(RST_USART1);
338 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
340 usart_set_baudrate(USART1, 115200);
341 usart_set_databits(USART1, 8);
342 usart_set_stopbits(USART1, USART_STOPBITS_1);
343 usart_set_mode(USART1, USART_MODE_TX);
344 usart_set_parity(USART1, USART_PARITY_NONE);
345 usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
347 usart_enable(USART1);
350 #ifdef DEBUG_LED_BLUEPILL
352 gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
356 // Systick: set to overflow in 1 ms, will use only the overflow flag, no interrupts
357 systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
359 systick_counter_enable();
361 desig_get_unique_id_as_dfu(usb_serial_number);
363 DEBUG("DFU: Entered boot-loader (SN %s)\n", usb_serial_number);
365 // Simulate USB disconnect
366 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
367 gpio_clear(GPIOA, GPIO11 | GPIO12);
368 for (uint i=0; i<100; i++) {
369 while (!systick_get_countflag())
373 DEBUG("DFU: Ready\n");
376 usbd_dev = usbd_init(&st_usbfs_v1_usb_driver, &dev, &config, usb_strings, ARRAY_SIZE(usb_strings), usbd_control_buffer, sizeof(usbd_control_buffer));
377 usbd_register_reset_callback(usbd_dev, dfu_reset);
378 usbd_register_set_config_callback(usbd_dev, dfu_set_config);
383 while (timeout || (dfu_state != STATE_DFU_IDLE && dfu_state != STATE_DFU_MANIFEST_WAIT_RESET)) {
385 if (timeout && systick_get_countflag()) {
387 if (!(timeout & 0x3f))
392 u32 *app = (u32 *) BOOTLOADER_APP_START;
395 u32 len = app[HDR_LENGTH/4];
396 u16 flash_in_progress = *(u16 *)(BOOTLOADER_APP_START + HDR_FLASH_IN_PROGRESS);
399 u32 crc = crc_calculate_block(app, len/4);
400 u32 want_crc = *(u32 *)(BOOTLOADER_APP_START + len);
401 DEBUG("DFU: fip=%04x, crc=%08x, want=%08x, len=%u\n", (uint) flash_in_progress, (uint) crc, (uint) want_crc, (uint) len);
402 if (flash_in_progress || crc != want_crc) {
403 DEBUG("DFU: Bad firmware\n");
407 DEBUG("DFU: Starting application (sp=%08x, pc=%08x)\n", (uint) sp, (uint) pc);
410 while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
418 /* Set vector table base address. */
419 SCB_VTOR = BOOTLOADER_APP_START;
421 /* Initialize master stack pointer. */
422 asm volatile("msr msp, %0"::"g" (sp));
424 /* Jump to application. */
425 ((void (*)(void)) pc)();