]> mj.ucw.cz Git - home-hw.git/blob - bsb/bootloader/main.c
BSB: Experiments with boot-loader
[home-hw.git] / bsb / bootloader / main.c
1 /*
2  *      Bootloader for the BSB Interface
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 #define DEBUG_BOOTLOADER
29
30 #ifdef DEBUG_BOOTLOADER
31 #define DEBUG(x...) debug_printf(x)
32 #else
33 #define DEBUG(x...) do { } while (0)
34 #endif
35
36 #define APP_ADDRESS     0x08002000
37
38 byte usbd_control_buffer[1024];
39
40 static enum dfu_state usbdfu_state = STATE_DFU_IDLE;
41
42 static struct {
43         byte buf[sizeof(usbd_control_buffer)];
44         u16 len;
45         u32 addr;
46         u16 blocknum;
47 } prog;
48
49 static char usb_serial_number[13];
50
51 enum usb_string {
52         STR_MANUFACTURER = 1,
53         STR_DEVICE,
54         STR_SERIAL,
55 };
56
57 static const char *usb_strings[] = {
58         "United Computer Wizards",
59         "Boot Loader",
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 = 0x4242,
72         .idProduct = 0xdead,
73         .bcdDevice = 0x0100,
74         .iManufacturer = STR_MANUFACTURER,
75         .iProduct = STR_DEVICE,
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 usbdfu_getstatus(usbd_device *usbd_dev UNUSED, u32 *bwPollTimeout)
120 {
121         switch (usbdfu_state) {
122         case STATE_DFU_DNLOAD_SYNC:
123                 usbdfu_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                 usbdfu_state = STATE_DFU_MANIFEST;
129                 return DFU_STATUS_OK;
130         default:
131                 return DFU_STATUS_OK;
132         }
133 }
134
135 static void usbdfu_getstatus_complete(usbd_device *usbd_dev UNUSED, struct usb_setup_data *req UNUSED)
136 {
137         switch (usbdfu_state) {
138         case STATE_DFU_DNBUSY: {
139                 flash_unlock();
140                 u32 baseaddr = APP_ADDRESS + prog.blocknum * dfu_function.wTransferSize;
141                 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 *dat = (u16 *)(prog.buf + i);
145                         flash_program_half_word(baseaddr + i, *dat);
146                 }
147                 flash_lock();
148                 usbdfu_state = STATE_DFU_DNLOAD_IDLE;
149                 return;
150                 }
151         case STATE_DFU_MANIFEST:
152                 /* USB device must detach, we just reset... */
153                 scb_reset_system();
154                 return; /* Will never return. */
155         default:
156                 return;
157         }
158 }
159
160 static enum usbd_request_return_codes usbdfu_control_request(usbd_device *usbd_dev,
161         struct usb_setup_data *req,
162         byte **buf,
163         u16 *len,
164         void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
165 {
166         if ((req->bmRequestType & 0x7F) != 0x21)
167                 return USBD_REQ_NOTSUPP; /* Only accept class request. */
168
169         DEBUG("DFU: req %02x in state %d\n", req->bRequest, usbdfu_state);
170
171         switch (req->bRequest) {
172         case DFU_DNLOAD:
173                 if (len == NULL || *len == 0) {
174                         usbdfu_state = STATE_DFU_MANIFEST_SYNC;
175                 } else {
176                         /* Copy download data for use on GET_STATUS. */
177                         prog.blocknum = req->wValue;
178                         prog.len = *len;
179                         memcpy(prog.buf, *buf, *len);
180                         usbdfu_state = STATE_DFU_DNLOAD_SYNC;
181                 }
182                 return USBD_REQ_HANDLED;
183         case DFU_CLRSTATUS:
184                 /* Clear error and return to dfuIDLE. */
185                 if (usbdfu_state == STATE_DFU_ERROR)
186                         usbdfu_state = STATE_DFU_IDLE;
187                 return USBD_REQ_HANDLED;
188         case DFU_ABORT:
189                 /* Abort returns to dfuIDLE state. */
190                 usbdfu_state = STATE_DFU_IDLE;
191                 return USBD_REQ_HANDLED;
192         case DFU_UPLOAD:
193                 /* Upload not supported for now. */
194                 return USBD_REQ_NOTSUPP;
195         case DFU_GETSTATUS: {
196                 u32 bwPollTimeout = 0; /* 24-bit number of milliseconds */
197                 (*buf)[0] = usbdfu_getstatus(usbd_dev, &bwPollTimeout);
198                 (*buf)[1] = bwPollTimeout & 0xFF;
199                 (*buf)[2] = (bwPollTimeout >> 8) & 0xFF;
200                 (*buf)[3] = (bwPollTimeout >> 16) & 0xFF;
201                 (*buf)[4] = usbdfu_state;
202                 (*buf)[5] = 0; /* iString not used here */
203                 *len = 6;
204                 *complete = usbdfu_getstatus_complete;
205                 return USBD_REQ_HANDLED;
206                 }
207         case DFU_GETSTATE:
208                 /* Return state with no state transition. */
209                 *buf[0] = usbdfu_state;
210                 *len = 1;
211                 return USBD_REQ_HANDLED;
212         }
213
214         return USBD_REQ_NOTSUPP;
215 }
216
217 static void usbdfu_set_config(usbd_device *usbd_dev, u16 wValue UNUSED)
218 {
219         usbd_register_control_callback(
220                                 usbd_dev,
221                                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
222                                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
223                                 usbdfu_control_request);
224 }
225
226 static void usbdfu_reset(void)
227 {
228         usbdfu_state = STATE_DFU_IDLE;
229 }
230
231 int main(void)
232 {
233         usbd_device *usbd_dev;
234
235         // Flash programming requires running on the internal oscillator
236         rcc_clock_setup_in_hsi_out_48mhz();
237
238         rcc_periph_clock_enable(RCC_GPIOA);
239         rcc_periph_clock_enable(RCC_GPIOC);
240         rcc_periph_clock_enable(RCC_USB);
241
242         rcc_periph_reset_pulse(RST_GPIOA);
243         rcc_periph_reset_pulse(RST_GPIOC);
244         rcc_periph_reset_pulse(RST_USB);
245
246 #ifdef DEBUG_BOOTLOADER
247         rcc_periph_clock_enable(RCC_USART1);
248         rcc_periph_reset_pulse(RST_USART1);
249         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
250
251         usart_set_baudrate(USART1, 115200);
252         usart_set_databits(USART1, 8);
253         usart_set_stopbits(USART1, USART_STOPBITS_1);
254         usart_set_mode(USART1, USART_MODE_TX);
255         usart_set_parity(USART1, USART_PARITY_NONE);
256         usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
257
258         usart_enable(USART1);
259 #endif
260
261         // BluePill LED
262         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
263         debug_led(1);
264
265         // Systick: set to overflow in 1 ms, will use only the overflow flag, no interrupts
266         systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
267         systick_clear();
268         systick_counter_enable();
269
270         desig_get_unique_id_as_dfu(usb_serial_number);
271
272         DEBUG("Entered boot-loader\n");
273
274         // Simulate USB disconnect
275         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
276         gpio_clear(GPIOA, GPIO11 | GPIO12);
277         for (uint i=0; i<1000; i++) {
278                 while (!systick_get_countflag())
279                         ;
280         }
281
282         DEBUG("DFU: Ready\n");
283         debug_led(0);
284
285         usbd_dev = usbd_init(&st_usbfs_v1_usb_driver, &dev, &config, usb_strings, ARRAY_SIZE(usb_strings), usbd_control_buffer, sizeof(usbd_control_buffer));
286         usbd_register_reset_callback(usbd_dev, usbdfu_reset);
287         usbd_register_set_config_callback(usbd_dev, usbdfu_set_config);
288
289 restart: ;
290
291         uint timeout = 5000;
292         while (timeout) {
293                 usbd_poll(usbd_dev);
294                 if (systick_get_countflag()) {
295                         timeout--;
296                         if (!(timeout & 0x3f))
297                                 debug_led_toggle();
298                 }
299         }
300
301         volatile u32 *app = (volatile u32 *) APP_ADDRESS;
302         u32 sp = app[0];
303         u32 pc = app[1];
304
305         DEBUG("DFU: Starting application (sp=%08x, pc=%08x)\n", (uint) sp, (uint) pc);
306         if (sp & 0x2ffe0000 != 0x20000000) {
307                 DEBUG("DFU: Suspicious SP, refusing to start\n");
308                 goto restart;
309         }
310
311         while (!usart_get_flag(DEBUG_USART, USART_FLAG_TC))
312                 ;
313         debug_led(0);
314         cm_disable_interrupts();
315
316         /* Set vector table base address. */
317         SCB_VTOR = APP_ADDRESS & 0xFFFF;
318
319         /* Initialize master stack pointer. */
320         asm volatile("msr msp, %0"::"g" (sp));
321
322         /* Jump to application. */
323         ((void (*)(void)) pc)();
324 }