]> mj.ucw.cz Git - home-hw.git/blob - lib/dfu-bootloader.c
Bootloader: The big rename
[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                         *(u16*)(prog.buf + HDR_FLASH_IN_PROGRESS) = 0xffff;
141                 flash_unlock();
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);
148                 }
149                 flash_lock();
150                 dfu_state = STATE_DFU_DNLOAD_IDLE;
151                 return;
152         case STATE_DFU_MANIFEST:
153                 // At the very end, program the first page
154                 // FIXME
155                 flash_unlock();
156                 flash_program_half_word(BOOTLOADER_APP_START + 0x20, 0);
157                 flash_lock();
158                 dfu_state = STATE_DFU_MANIFEST_WAIT_RESET;
159                 return;
160         default:
161                 return;
162         }
163 }
164
165 static enum usbd_request_return_codes dfu_control_request(usbd_device *usbd_dev,
166         struct usb_setup_data *req,
167         byte **buf,
168         u16 *len,
169         void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
170 {
171         if ((req->bmRequestType & 0x7F) != 0x21)
172                 return USBD_REQ_NOTSUPP; /* Only accept class request. */
173
174         DEBUG("DFU: Request %02x in state %d\n", req->bRequest, dfu_state);
175
176         switch (req->bRequest) {
177         case DFU_DNLOAD:
178                 if (len == NULL || *len == 0) {
179                         dfu_state = STATE_DFU_MANIFEST_SYNC;
180                 } else {
181                         /* Copy download data for use on GET_STATUS. */
182                         prog.blocknum = req->wValue;
183                         prog.len = *len;
184                         memcpy(prog.buf, *buf, *len);
185                         dfu_state = STATE_DFU_DNLOAD_SYNC;
186                 }
187                 return USBD_REQ_HANDLED;
188         case DFU_CLRSTATUS:
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;
193         case DFU_ABORT:
194                 /* Abort returns to dfuIDLE state. */
195                 dfu_state = STATE_DFU_IDLE;
196                 return USBD_REQ_HANDLED;
197         case DFU_UPLOAD:
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 */
208                 *len = 6;
209                 *complete = dfu_getstatus_complete;
210                 return USBD_REQ_HANDLED;
211                 }
212         case DFU_GETSTATE:
213                 /* Return state with no state transition. */
214                 *buf[0] = dfu_state;
215                 *len = 1;
216                 return USBD_REQ_HANDLED;
217         }
218
219         return USBD_REQ_NOTSUPP;
220 }
221
222 static void dfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
223 {
224         usbd_register_control_callback(
225                                 usbd_dev,
226                                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
227                                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
228                                 dfu_control_request);
229 }
230
231 static void dfu_reset(void)
232 {
233         dfu_state = STATE_DFU_IDLE;
234 }
235
236 /*
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.
239  */
240 static void my_rcc_clock_setup_in_hsi_out_48mhz(void)
241 {
242         /* Enable internal high-speed oscillator. */
243         rcc_osc_on(RCC_HSI);
244         rcc_wait_for_osc_ready(RCC_HSI);
245
246         /* Select HSI as SYSCLK source. */
247         rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
248
249         // XXX: Disable PLL
250         rcc_osc_off(RCC_PLL);
251
252         /*
253          * Set prescalers for AHB, ADC, ABP1, ABP2.
254          * Do this before touching the PLL (TODO: why?).
255          */
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 */
261
262         /*
263          * Sysclk runs with 48MHz -> 1 waitstates.
264          * 0WS from 0-24MHz
265          * 1WS from 24-48MHz
266          * 2WS from 48-72MHz
267          */
268         flash_set_ws(FLASH_ACR_LATENCY_1WS);
269
270         /*
271          * Set the PLL multiplication factor to 12.
272          * 8MHz (internal) * 12 (multiplier) / 2 (PLLSRC_HSI_CLK_DIV2) = 48MHz
273          */
274         rcc_set_pll_multiplication_factor(RCC_CFGR_PLLMUL_PLL_CLK_MUL12);
275
276         /* Select HSI/2 as PLL source. */
277         rcc_set_pll_source(RCC_CFGR_PLLSRC_HSI_CLK_DIV2);
278
279         /* Enable PLL oscillator and wait for it to stabilize. */
280         rcc_osc_on(RCC_PLL);
281         rcc_wait_for_osc_ready(RCC_PLL);
282
283         /* Select PLL as SYSCLK source. */
284         rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_PLLCLK);
285
286         /* Set the peripheral clock frequencies used */
287         rcc_ahb_frequency = 48000000;
288         rcc_apb1_frequency = 24000000;
289         rcc_apb2_frequency = 48000000;
290 }
291
292 static void clock_plain_hsi(void)
293 {
294         // Select HSI as SYSCLK source
295         rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
296
297         // Disable PLL
298         rcc_osc_off(RCC_PLL);
299
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);
306 }
307
308 static void reset_peripherals(void)
309 {
310         // Turn off clock to all peripherals and reset them
311         RCC_AHBENR = 0x00000014;
312         RCC_APB1ENR = 0;
313         RCC_APB2ENR = 0;
314         RCC_APB1RSTR = 0x22fec9ff;
315         RCC_APB2RSTR = 0x0038fffd;
316         RCC_APB1RSTR = 0;
317         RCC_APB2RSTR = 0;
318 }
319
320 int main(void)
321 {
322         usbd_device *usbd_dev;
323
324         reset_peripherals();
325
326         // Flash programming requires running on the internal oscillator
327         my_rcc_clock_setup_in_hsi_out_48mhz();
328
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);
333
334 #ifdef DEBUG_USART
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);
339
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);
346
347         usart_enable(USART1);
348 #endif
349
350 #ifdef DEBUG_LED_BLUEPILL
351         // BluePill LED
352         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
353         debug_led(1);
354 #endif
355
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);
358         systick_clear();
359         systick_counter_enable();
360
361         desig_get_unique_id_as_dfu(usb_serial_number);
362
363         DEBUG("DFU: Entered boot-loader (SN %s)\n", usb_serial_number);
364
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())
370                         ;
371         }
372
373         DEBUG("DFU: Ready\n");
374         debug_led(0);
375
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);
379
380 restart: ;
381
382         uint timeout = 5000;
383         while (timeout || (dfu_state != STATE_DFU_IDLE && dfu_state != STATE_DFU_MANIFEST_WAIT_RESET)) {
384                 usbd_poll(usbd_dev);
385                 if (timeout && systick_get_countflag()) {
386                         timeout--;
387                         if (!(timeout & 0x3f))
388                                 debug_led_toggle();
389                 }
390         }
391
392         u32 *app = (u32 *) BOOTLOADER_APP_START;
393         u32 sp = app[0];
394         u32 pc = app[1];
395         u32 len = app[HDR_LENGTH/4];
396         u16 flash_in_progress = *(u16 *)(BOOTLOADER_APP_START + HDR_FLASH_IN_PROGRESS);
397
398         crc_reset();
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");
404                 goto restart;
405         }
406
407         DEBUG("DFU: Starting application (sp=%08x, pc=%08x)\n", (uint) sp, (uint) pc);
408
409 #ifdef DEBUG_USART
410         while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
411                 ;
412 #endif
413         debug_led(0);
414
415         reset_peripherals();
416         clock_plain_hsi();
417
418         /* Set vector table base address. */
419         SCB_VTOR = BOOTLOADER_APP_START;
420
421         /* Initialize master stack pointer. */
422         asm volatile("msr msp, %0"::"g" (sp));
423
424         /* Jump to application. */
425         ((void (*)(void)) pc)();
426 }