]> mj.ucw.cz Git - home-hw.git/blob - lib/dfu-bootloader.c
f40676c925c52d23f98549aa6cb5a41c19bf43a8
[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/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>
26
27 #include <string.h>
28
29 #ifdef BOOTLOADER_DEBUG
30 #define DEBUG(x...) debug_printf(x)
31 #else
32 #define DEBUG(x...) do { } while (0)
33 #endif
34
35 // Offsets to firmware header fields (see tools/dfu-sign.c)
36 #define HDR_LENGTH 0x1c
37 #define HDR_FLASH_IN_PROGRESS 0x20
38
39 byte usbd_control_buffer[1024];
40
41 static enum dfu_state dfu_state = STATE_DFU_IDLE;
42
43 static struct {
44         byte buf[sizeof(usbd_control_buffer)];
45         u16 blocknum;
46         u16 len;
47 } prog;
48
49 static char usb_serial_number[13];
50
51 enum usb_string {
52         STR_MANUFACTURER = 1,
53         STR_PRODUCT,
54         STR_SERIAL,
55 };
56
57 static const char *usb_strings[] = {
58         BOOTLOADER_MFG_NAME,
59         BOOTLOADER_PROD_NAME,
60         usb_serial_number,
61 };
62
63 const struct usb_device_descriptor dev = {
64         .bLength = USB_DT_DEVICE_SIZE,
65         .bDescriptorType = USB_DT_DEVICE,
66         .bcdUSB = 0x0200,
67         .bDeviceClass = 0,
68         .bDeviceSubClass = 0,
69         .bDeviceProtocol = 0,
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,
78 };
79
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,
87 };
88
89 const struct usb_interface_descriptor iface = {
90         .bLength = USB_DT_INTERFACE_SIZE,
91         .bDescriptorType = USB_DT_INTERFACE,
92         .bInterfaceNumber = 0,
93         .bAlternateSetting = 0,
94         .bNumEndpoints = 0,
95         .bInterfaceClass = 0xFE, /* Device Firmware Upgrade */
96         .bInterfaceSubClass = 1,
97         .bInterfaceProtocol = 2,
98         .extra = &dfu_function,
99         .extralen = sizeof(dfu_function),
100 };
101
102 const struct usb_interface ifaces[] = {{
103         .num_altsetting = 1,
104         .altsetting = &iface,
105 }};
106
107 const struct usb_config_descriptor config = {
108         .bLength = USB_DT_CONFIGURATION_SIZE,
109         .bDescriptorType = USB_DT_CONFIGURATION,
110         .wTotalLength = 0,
111         .bNumInterfaces = 1,
112         .bConfigurationValue = 1,
113         .iConfiguration = 0,
114         .bmAttributes = USB_CONFIG_ATTR_DEFAULT,        // bus-powered
115         .bMaxPower = 50,                                // multiplied by 2 mA
116         .interface = ifaces,
117 };
118
119 static byte dfu_getstatus(usbd_device *usbd_dev UNUSED, u32 *bwPollTimeout)
120 {
121         switch (dfu_state) {
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;
130         default:
131                 return DFU_STATUS_OK;
132         }
133 }
134
135 static void dfu_getstatus_complete(usbd_device *usbd_dev UNUSED, struct usb_setup_data *req UNUSED)
136 {
137         switch (dfu_state) {
138         case STATE_DFU_DNBUSY:
139                 if (prog.blocknum == 0) {
140                         // The "flash in progress" word is programmed as 0xffff first and reset later
141                         *(u16*)(prog.buf + HDR_FLASH_IN_PROGRESS) = 0xffff;
142                 }
143                 flash_unlock();
144                 u32 baseaddr = BOOTLOADER_APP_START + prog.blocknum * dfu_function.wTransferSize;
145                 DEBUG("DFU: Block %u -> %08x + %u\n", prog.blocknum, (uint) baseaddr, prog.len);
146                 flash_erase_page(baseaddr);
147                 for (uint i = 0; i < prog.len; i += 2) {
148                         u16 data = *(u16 *)(prog.buf + i);
149                         flash_program_half_word(baseaddr + i, data);
150                 }
151                 flash_lock();
152                 dfu_state = STATE_DFU_DNLOAD_IDLE;
153                 return;
154         case STATE_DFU_MANIFEST:
155                 // At the very end, re-flash the "flash in progress" word
156                 flash_unlock();
157                 flash_program_half_word(BOOTLOADER_APP_START + 0x20, 0);
158                 flash_lock();
159                 dfu_state = STATE_DFU_MANIFEST_WAIT_RESET;
160                 return;
161         default:
162                 return;
163         }
164 }
165
166 static enum usbd_request_return_codes dfu_control_request(usbd_device *usbd_dev,
167         struct usb_setup_data *req,
168         byte **buf,
169         u16 *len,
170         void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
171 {
172         if ((req->bmRequestType & 0x7F) != 0x21)
173                 return USBD_REQ_NOTSUPP; /* Only accept class request. */
174
175         DEBUG("DFU: Request %02x in state %d\n", req->bRequest, dfu_state);
176
177         switch (req->bRequest) {
178         case DFU_DNLOAD:
179                 if (len == NULL || *len == 0) {
180                         dfu_state = STATE_DFU_MANIFEST_SYNC;
181                 } else {
182                         /* Copy download data for use on GET_STATUS. */
183                         prog.blocknum = req->wValue;
184                         prog.len = *len;
185                         memcpy(prog.buf, *buf, *len);
186                         dfu_state = STATE_DFU_DNLOAD_SYNC;
187                 }
188                 return USBD_REQ_HANDLED;
189         case DFU_CLRSTATUS:
190                 /* Clear error and return to dfuIDLE. */
191                 if (dfu_state == STATE_DFU_ERROR)
192                         dfu_state = STATE_DFU_IDLE;
193                 return USBD_REQ_HANDLED;
194         case DFU_ABORT:
195                 /* Abort returns to dfuIDLE state. */
196                 dfu_state = STATE_DFU_IDLE;
197                 return USBD_REQ_HANDLED;
198         case DFU_UPLOAD:
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] = dfu_getstatus(usbd_dev, &bwPollTimeout);
204                 (*buf)[1] = bwPollTimeout & 0xFF;
205                 (*buf)[2] = (bwPollTimeout >> 8) & 0xFF;
206                 (*buf)[3] = (bwPollTimeout >> 16) & 0xFF;
207                 (*buf)[4] = dfu_state;
208                 (*buf)[5] = 0; /* iString not used here */
209                 *len = 6;
210                 *complete = dfu_getstatus_complete;
211                 return USBD_REQ_HANDLED;
212                 }
213         case DFU_GETSTATE:
214                 /* Return state with no state transition. */
215                 *buf[0] = dfu_state;
216                 *len = 1;
217                 return USBD_REQ_HANDLED;
218         }
219
220         return USBD_REQ_NOTSUPP;
221 }
222
223 static void dfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
224 {
225         usbd_register_control_callback(
226                                 usbd_dev,
227                                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
228                                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
229                                 dfu_control_request);
230 }
231
232 static void dfu_reset(void)
233 {
234         dfu_state = STATE_DFU_IDLE;
235 }
236
237 /*
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.
240  */
241 static void my_rcc_clock_setup_in_hsi_out_48mhz(void)
242 {
243         /* Enable internal high-speed oscillator. */
244         rcc_osc_on(RCC_HSI);
245         rcc_wait_for_osc_ready(RCC_HSI);
246
247         /* Select HSI as SYSCLK source. */
248         rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
249
250         // XXX: Disable PLL
251         rcc_osc_off(RCC_PLL);
252
253         /*
254          * Set prescalers for AHB, ADC, ABP1, ABP2.
255          * Do this before touching the PLL (TODO: why?).
256          */
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 */
262
263         /*
264          * Sysclk runs with 48MHz -> 1 waitstates.
265          * 0WS from 0-24MHz
266          * 1WS from 24-48MHz
267          * 2WS from 48-72MHz
268          */
269         flash_set_ws(FLASH_ACR_LATENCY_1WS);
270
271         /*
272          * Set the PLL multiplication factor to 12.
273          * 8MHz (internal) * 12 (multiplier) / 2 (PLLSRC_HSI_CLK_DIV2) = 48MHz
274          */
275         rcc_set_pll_multiplication_factor(RCC_CFGR_PLLMUL_PLL_CLK_MUL12);
276
277         /* Select HSI/2 as PLL source. */
278         rcc_set_pll_source(RCC_CFGR_PLLSRC_HSI_CLK_DIV2);
279
280         /* Enable PLL oscillator and wait for it to stabilize. */
281         rcc_osc_on(RCC_PLL);
282         rcc_wait_for_osc_ready(RCC_PLL);
283
284         /* Select PLL as SYSCLK source. */
285         rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_PLLCLK);
286
287         /* Set the peripheral clock frequencies used */
288         rcc_ahb_frequency = 48000000;
289         rcc_apb1_frequency = 24000000;
290         rcc_apb2_frequency = 48000000;
291 }
292
293 static void clock_plain_hsi(void)
294 {
295         // Select HSI as SYSCLK source
296         rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
297
298         // Disable PLL
299         rcc_osc_off(RCC_PLL);
300
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);
307 }
308
309 static void reset_peripherals(void)
310 {
311         // Turn off clock to all peripherals and reset them
312         RCC_AHBENR = 0x00000014;
313         RCC_APB1ENR = 0;
314         RCC_APB2ENR = 0;
315         RCC_APB1RSTR = 0x22fec9ff;
316         RCC_APB2RSTR = 0x0038fffd;
317         RCC_APB1RSTR = 0;
318         RCC_APB2RSTR = 0;
319 }
320
321 int main(void)
322 {
323         usbd_device *usbd_dev;
324
325         reset_peripherals();
326
327         // Flash programming requires running on the internal oscillator
328         my_rcc_clock_setup_in_hsi_out_48mhz();
329
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);
334
335 #ifdef DEBUG_USART
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);
340
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);
347
348         usart_enable(USART1);
349 #endif
350
351 #ifdef DEBUG_LED_BLUEPILL
352         // BluePill LED
353         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
354         debug_led(1);
355 #endif
356
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);
359         systick_clear();
360         systick_counter_enable();
361
362         desig_get_unique_id_as_dfu(usb_serial_number);
363
364         DEBUG("DFU: Entered boot-loader (SN %s)\n", usb_serial_number);
365
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())
371                         ;
372         }
373
374         DEBUG("DFU: Ready\n");
375         debug_led(0);
376
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, dfu_reset);
379         usbd_register_set_config_callback(usbd_dev, dfu_set_config);
380
381 restart: ;
382
383         uint timeout = 5000;
384         while (timeout || (dfu_state != STATE_DFU_IDLE && dfu_state != STATE_DFU_MANIFEST_WAIT_RESET)) {
385                 usbd_poll(usbd_dev);
386                 if (timeout && systick_get_countflag()) {
387                         timeout--;
388                         if (!(timeout & 0x3f))
389                                 debug_led_toggle();
390                 }
391         }
392
393         u32 *app = (u32 *) BOOTLOADER_APP_START;
394         u32 sp = app[0];
395         u32 pc = app[1];
396         u32 len = app[HDR_LENGTH/4];
397         u16 flash_in_progress = *(u16 *)(BOOTLOADER_APP_START + HDR_FLASH_IN_PROGRESS);
398
399         crc_reset();
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");
405                 goto restart;
406         }
407
408         DEBUG("DFU: Starting application (sp=%08x, pc=%08x)\n", (uint) sp, (uint) pc);
409
410 #ifdef DEBUG_USART
411         while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
412                 ;
413 #endif
414         debug_led(0);
415
416         reset_peripherals();
417         clock_plain_hsi();
418
419         /* Set vector table base address. */
420         SCB_VTOR = BOOTLOADER_APP_START;
421
422         /* Initialize master stack pointer. */
423         asm volatile("msr msp, %0"::"g" (sp));
424
425         /* Jump to application. */
426         ((void (*)(void)) pc)();
427 }