]> mj.ucw.cz Git - home-hw.git/blob - lib/dfu-bootloader.c
ce01a41c5173872c6c4dd45ec738a6e360fd8caa
[home-hw.git] / lib / dfu-bootloader.c
1 /*
2  *      Generic DFU Bootloader
3  *
4  *      (c) 2020 Martin Mareš <mj@ucw.cz>
5  *
6  *      Based on example code from the libopencm3 project, which is
7  *      Copyright (C) 2010 Gareth McMullin <gareth@blacksphere.co.nz>
8  *
9  *      Licensed under the GNU LGPL v3 or any later version.
10  */
11
12 #include "util.h"
13
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>
25
26 #include <string.h>
27
28 #ifdef BOOTLOADER_DEBUG
29 #define DEBUG(x...) debug_printf(x)
30 #else
31 #define DEBUG(x...) do { } while (0)
32 #endif
33
34 byte usbd_control_buffer[1024];
35
36 static enum dfu_state usbdfu_state = STATE_DFU_IDLE;
37
38 struct prog_info {
39         byte buf[sizeof(usbd_control_buffer)];
40         u16 blocknum;
41         u16 len;
42 };
43
44 static struct prog_info prog_page;
45
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;
49
50 static char usb_serial_number[13];
51
52 enum usb_string {
53         STR_MANUFACTURER = 1,
54         STR_PRODUCT,
55         STR_SERIAL,
56 };
57
58 static const char *usb_strings[] = {
59         BOOTLOADER_MFG_NAME,
60         BOOTLOADER_PROD_NAME,
61         usb_serial_number,
62 };
63
64 const struct usb_device_descriptor dev = {
65         .bLength = USB_DT_DEVICE_SIZE,
66         .bDescriptorType = USB_DT_DEVICE,
67         .bcdUSB = 0x0200,
68         .bDeviceClass = 0,
69         .bDeviceSubClass = 0,
70         .bDeviceProtocol = 0,
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,
79 };
80
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,
88 };
89
90 const struct usb_interface_descriptor iface = {
91         .bLength = USB_DT_INTERFACE_SIZE,
92         .bDescriptorType = USB_DT_INTERFACE,
93         .bInterfaceNumber = 0,
94         .bAlternateSetting = 0,
95         .bNumEndpoints = 0,
96         .bInterfaceClass = 0xFE, /* Device Firmware Upgrade */
97         .bInterfaceSubClass = 1,
98         .bInterfaceProtocol = 2,
99         .extra = &dfu_function,
100         .extralen = sizeof(dfu_function),
101 };
102
103 const struct usb_interface ifaces[] = {{
104         .num_altsetting = 1,
105         .altsetting = &iface,
106 }};
107
108 const struct usb_config_descriptor config = {
109         .bLength = USB_DT_CONFIGURATION_SIZE,
110         .bDescriptorType = USB_DT_CONFIGURATION,
111         .wTotalLength = 0,
112         .bNumInterfaces = 1,
113         .bConfigurationValue = 1,
114         .iConfiguration = 0,
115         .bmAttributes = USB_CONFIG_ATTR_DEFAULT,        // bus-powered
116         .bMaxPower = 50,                                // multiplied by 2 mA
117         .interface = ifaces,
118 };
119
120 static byte usbdfu_getstatus(usbd_device *usbd_dev UNUSED, u32 *bwPollTimeout)
121 {
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;
131         default:
132                 return DFU_STATUS_OK;
133         }
134 }
135
136 static void program_page(struct prog_info *prog, bool need_erase)
137 {
138         flash_unlock();
139         u32 baseaddr = BOOTLOADER_APP_START + prog->blocknum * dfu_function.wTransferSize;
140         DEBUG("DFU: Block %u -> %08x\n", prog->blocknum, (uint) baseaddr);
141         if (need_erase)
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);
146         }
147         flash_lock();
148 }
149
150 static void usbdfu_getstatus_complete(usbd_device *usbd_dev UNUSED, struct usb_setup_data *req UNUSED)
151 {
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;
157                         flash_unlock();
158                         flash_erase_page(BOOTLOADER_APP_START);
159                         flash_lock();
160                 } else
161                         program_page(&prog_page, true);
162                 usbdfu_state = STATE_DFU_DNLOAD_IDLE;
163                 return;
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... */
168                 scb_reset_system();
169                 return; /* Will never return. */
170         default:
171                 return;
172         }
173 }
174
175 static enum usbd_request_return_codes usbdfu_control_request(usbd_device *usbd_dev,
176         struct usb_setup_data *req,
177         byte **buf,
178         u16 *len,
179         void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
180 {
181         if ((req->bmRequestType & 0x7F) != 0x21)
182                 return USBD_REQ_NOTSUPP; /* Only accept class request. */
183
184         DEBUG("DFU: Request %02x in state %d\n", req->bRequest, usbdfu_state);
185
186         switch (req->bRequest) {
187         case DFU_DNLOAD:
188                 if (len == NULL || *len == 0) {
189                         usbdfu_state = STATE_DFU_MANIFEST_SYNC;
190                 } else {
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;
196                 }
197                 return USBD_REQ_HANDLED;
198         case DFU_CLRSTATUS:
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;
203         case DFU_ABORT:
204                 /* Abort returns to dfuIDLE state. */
205                 usbdfu_state = STATE_DFU_IDLE;
206                 return USBD_REQ_HANDLED;
207         case DFU_UPLOAD:
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 */
218                 *len = 6;
219                 *complete = usbdfu_getstatus_complete;
220                 return USBD_REQ_HANDLED;
221                 }
222         case DFU_GETSTATE:
223                 /* Return state with no state transition. */
224                 *buf[0] = usbdfu_state;
225                 *len = 1;
226                 return USBD_REQ_HANDLED;
227         }
228
229         return USBD_REQ_NOTSUPP;
230 }
231
232 static void usbdfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
233 {
234         usbd_register_control_callback(
235                                 usbd_dev,
236                                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
237                                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
238                                 usbdfu_control_request);
239 }
240
241 static void usbdfu_reset(void)
242 {
243         usbdfu_state = STATE_DFU_IDLE;
244 }
245
246 int main(void)
247 {
248         usbd_device *usbd_dev;
249
250         // Flash programming requires running on the internal oscillator
251         rcc_clock_setup_in_hsi_out_48mhz();
252
253         rcc_periph_clock_enable(RCC_GPIOA);
254         rcc_periph_clock_enable(RCC_GPIOC);
255         rcc_periph_clock_enable(RCC_USB);
256
257         rcc_periph_reset_pulse(RST_GPIOA);
258         rcc_periph_reset_pulse(RST_GPIOC);
259         rcc_periph_reset_pulse(RST_USB);
260
261 #ifdef DEBUG_USART
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);
266
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);
273
274         usart_enable(USART1);
275 #endif
276
277 #ifdef DEBUG_LED_BLUEPILL
278         // BluePill LED
279         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
280         debug_led(1);
281 #endif
282
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);
285         systick_clear();
286         systick_counter_enable();
287
288         desig_get_unique_id_as_dfu(usb_serial_number);
289
290         DEBUG("DFU: Entered boot-loader (SN %s)\n", usb_serial_number);
291
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())
297                         ;
298         }
299
300         DEBUG("DFU: Ready\n");
301         debug_led(0);
302
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);
306
307 restart: ;
308
309         uint timeout = 5000;
310         while (timeout) {
311                 usbd_poll(usbd_dev);
312                 if (systick_get_countflag()) {
313                         timeout--;
314                         if (!(timeout & 0x3f))
315                                 debug_led_toggle();
316                 }
317         }
318
319         volatile u32 *app = (volatile u32 *) BOOTLOADER_APP_START;
320         u32 sp = app[0];
321         u32 pc = app[1];
322
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");
326                 goto restart;
327         }
328
329 #ifdef DEBUG_USART
330         while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
331                 ;
332 #endif
333         debug_led(0);
334         cm_disable_interrupts();
335
336         /* Set vector table base address. */
337         SCB_VTOR = BOOTLOADER_APP_START & 0xFFFF;
338
339         /* Initialize master stack pointer. */
340         asm volatile("msr msp, %0"::"g" (sp));
341
342         /* Jump to application. */
343         ((void (*)(void)) pc)();
344 }