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/gpio.h>
20 #include <libopencm3/stm32/flash.h>
21 #include <libopencm3/stm32/usart.h>
22 #include <libopencm3/stm32/desig.h>
23 #include <libopencm3/usb/usbd.h>
24 #include <libopencm3/usb/dfu.h>
28 #ifdef BOOTLOADER_DEBUG
29 #define DEBUG(x...) debug_printf(x)
31 #define DEBUG(x...) do { } while (0)
34 byte usbd_control_buffer[1024];
36 static enum dfu_state usbdfu_state = STATE_DFU_IDLE;
39 byte buf[sizeof(usbd_control_buffer)];
44 static struct prog_info prog_page;
46 // The first page of application code is programmed last,
47 // so that we are able to detect incompletely uploaded firmware.
48 static struct prog_info prog_header;
50 static char usb_serial_number[13];
58 static const char *usb_strings[] = {
64 const struct usb_device_descriptor dev = {
65 .bLength = USB_DT_DEVICE_SIZE,
66 .bDescriptorType = USB_DT_DEVICE,
71 .bMaxPacketSize0 = 64,
72 .idVendor = BOOTLOADER_MFG_ID,
73 .idProduct = BOOTLOADER_PROD_ID,
74 .bcdDevice = BOOTLOADER_PROD_VERSION,
75 .iManufacturer = STR_MANUFACTURER,
76 .iProduct = STR_PRODUCT,
77 .iSerialNumber = STR_SERIAL,
78 .bNumConfigurations = 1,
81 const struct usb_dfu_descriptor dfu_function = {
82 .bLength = sizeof(struct usb_dfu_descriptor),
83 .bDescriptorType = DFU_FUNCTIONAL,
84 .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
85 .wDetachTimeout = 255,
86 .wTransferSize = 1024,
87 .bcdDFUVersion = 0x0100,
90 const struct usb_interface_descriptor iface = {
91 .bLength = USB_DT_INTERFACE_SIZE,
92 .bDescriptorType = USB_DT_INTERFACE,
93 .bInterfaceNumber = 0,
94 .bAlternateSetting = 0,
96 .bInterfaceClass = 0xFE, /* Device Firmware Upgrade */
97 .bInterfaceSubClass = 1,
98 .bInterfaceProtocol = 2,
99 .extra = &dfu_function,
100 .extralen = sizeof(dfu_function),
103 const struct usb_interface ifaces[] = {{
105 .altsetting = &iface,
108 const struct usb_config_descriptor config = {
109 .bLength = USB_DT_CONFIGURATION_SIZE,
110 .bDescriptorType = USB_DT_CONFIGURATION,
113 .bConfigurationValue = 1,
115 .bmAttributes = USB_CONFIG_ATTR_DEFAULT, // bus-powered
116 .bMaxPower = 50, // multiplied by 2 mA
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 program_page(struct prog_info *prog, bool need_erase)
139 u32 baseaddr = BOOTLOADER_APP_START + prog->blocknum * dfu_function.wTransferSize;
140 DEBUG("DFU: Block %u -> %08x\n", prog->blocknum, (uint) baseaddr);
142 flash_erase_page(baseaddr);
143 for (uint i = 0; i < prog->len; i += 2) {
144 u16 data = *(u16 *)(prog->buf + i);
145 flash_program_half_word(baseaddr + i, data);
150 static void usbdfu_getstatus_complete(usbd_device *usbd_dev UNUSED, struct usb_setup_data *req UNUSED)
152 switch (usbdfu_state) {
153 case STATE_DFU_DNBUSY:
154 if (prog_page.blocknum == 0) {
155 // The first block will be programmed last
156 prog_header = prog_page;
158 flash_erase_page(BOOTLOADER_APP_START);
161 program_page(&prog_page, true);
162 usbdfu_state = STATE_DFU_DNLOAD_IDLE;
164 case STATE_DFU_MANIFEST:
165 // At the very end, program the first page
166 program_page(&prog_header, false);
167 /* USB device must detach, we just reset... */
169 return; /* Will never return. */
175 static enum usbd_request_return_codes usbdfu_control_request(usbd_device *usbd_dev,
176 struct usb_setup_data *req,
179 void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
181 if ((req->bmRequestType & 0x7F) != 0x21)
182 return USBD_REQ_NOTSUPP; /* Only accept class request. */
184 DEBUG("DFU: Request %02x in state %d\n", req->bRequest, usbdfu_state);
186 switch (req->bRequest) {
188 if (len == NULL || *len == 0) {
189 usbdfu_state = STATE_DFU_MANIFEST_SYNC;
191 /* Copy download data for use on GET_STATUS. */
192 prog_page.blocknum = req->wValue;
193 prog_page.len = *len;
194 memcpy(prog_page.buf, *buf, *len);
195 usbdfu_state = STATE_DFU_DNLOAD_SYNC;
197 return USBD_REQ_HANDLED;
199 /* Clear error and return to dfuIDLE. */
200 if (usbdfu_state == STATE_DFU_ERROR)
201 usbdfu_state = STATE_DFU_IDLE;
202 return USBD_REQ_HANDLED;
204 /* Abort returns to dfuIDLE state. */
205 usbdfu_state = STATE_DFU_IDLE;
206 return USBD_REQ_HANDLED;
208 /* Upload not supported for now. */
209 return USBD_REQ_NOTSUPP;
210 case DFU_GETSTATUS: {
211 u32 bwPollTimeout = 0; /* 24-bit number of milliseconds */
212 (*buf)[0] = usbdfu_getstatus(usbd_dev, &bwPollTimeout);
213 (*buf)[1] = bwPollTimeout & 0xFF;
214 (*buf)[2] = (bwPollTimeout >> 8) & 0xFF;
215 (*buf)[3] = (bwPollTimeout >> 16) & 0xFF;
216 (*buf)[4] = usbdfu_state;
217 (*buf)[5] = 0; /* iString not used here */
219 *complete = usbdfu_getstatus_complete;
220 return USBD_REQ_HANDLED;
223 /* Return state with no state transition. */
224 *buf[0] = usbdfu_state;
226 return USBD_REQ_HANDLED;
229 return USBD_REQ_NOTSUPP;
232 static void usbdfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
234 usbd_register_control_callback(
236 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
237 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
238 usbdfu_control_request);
241 static void usbdfu_reset(void)
243 usbdfu_state = STATE_DFU_IDLE;
248 usbd_device *usbd_dev;
250 // Flash programming requires running on the internal oscillator
251 rcc_clock_setup_in_hsi_out_48mhz();
253 rcc_periph_clock_enable(RCC_GPIOA);
254 rcc_periph_clock_enable(RCC_GPIOC);
255 rcc_periph_clock_enable(RCC_USB);
257 rcc_periph_reset_pulse(RST_GPIOA);
258 rcc_periph_reset_pulse(RST_GPIOC);
259 rcc_periph_reset_pulse(RST_USB);
262 // Currently, only USART1 is supported
263 rcc_periph_clock_enable(RCC_USART1);
264 rcc_periph_reset_pulse(RST_USART1);
265 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
267 usart_set_baudrate(USART1, 115200);
268 usart_set_databits(USART1, 8);
269 usart_set_stopbits(USART1, USART_STOPBITS_1);
270 usart_set_mode(USART1, USART_MODE_TX);
271 usart_set_parity(USART1, USART_PARITY_NONE);
272 usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
274 usart_enable(USART1);
277 #ifdef DEBUG_LED_BLUEPILL
279 gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
283 // Systick: set to overflow in 1 ms, will use only the overflow flag, no interrupts
284 systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
286 systick_counter_enable();
288 desig_get_unique_id_as_dfu(usb_serial_number);
290 DEBUG("DFU: Entered boot-loader (SN %s)\n", usb_serial_number);
292 // Simulate USB disconnect
293 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
294 gpio_clear(GPIOA, GPIO11 | GPIO12);
295 for (uint i=0; i<100; i++) {
296 while (!systick_get_countflag())
300 DEBUG("DFU: Ready\n");
303 usbd_dev = usbd_init(&st_usbfs_v1_usb_driver, &dev, &config, usb_strings, ARRAY_SIZE(usb_strings), usbd_control_buffer, sizeof(usbd_control_buffer));
304 usbd_register_reset_callback(usbd_dev, usbdfu_reset);
305 usbd_register_set_config_callback(usbd_dev, usbdfu_set_config);
312 if (systick_get_countflag()) {
314 if (!(timeout & 0x3f))
319 volatile u32 *app = (volatile u32 *) BOOTLOADER_APP_START;
323 DEBUG("DFU: Starting application (sp=%08x, pc=%08x)\n", (uint) sp, (uint) pc);
324 if ((sp & 0x2ffe0000) != 0x20000000) {
325 DEBUG("DFU: Suspicious SP, refusing to start\n");
330 while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
334 cm_disable_interrupts();
336 /* Set vector table base address. */
337 SCB_VTOR = BOOTLOADER_APP_START & 0xFFFF;
339 /* Initialize master stack pointer. */
340 asm volatile("msr msp, %0"::"g" (sp));
342 /* Jump to application. */
343 ((void (*)(void)) pc)();