]> git.donarmstrong.com Git - qmk_firmware.git/blob - lib/lufa/Bootloaders/HID/BootloaderHID.c
Merge commit '60b30c036397cb5627fa374bb930794b225daa29' as 'lib/lufa'
[qmk_firmware.git] / lib / lufa / Bootloaders / HID / BootloaderHID.c
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2017.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2017  Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12   Permission to use, copy, modify, distribute, and sell this
13   software and its documentation for any purpose is hereby granted
14   without fee, provided that the above copyright notice appear in
15   all copies and that both that the copyright notice and this
16   permission notice and warranty disclaimer appear in supporting
17   documentation, and that the name of the author not be used in
18   advertising or publicity pertaining to distribution of the
19   software without specific, written prior permission.
20
21   The author disclaims all warranties with regard to this
22   software, including all implied warranties of merchantability
23   and fitness.  In no event shall the author be liable for any
24   special, indirect or consequential damages or any damages
25   whatsoever resulting from loss of use, data or profits, whether
26   in an action of contract, negligence or other tortious action,
27   arising out of or in connection with the use or performance of
28   this software.
29 */
30
31 /** \file
32  *
33  *  Main source file for the HID class bootloader. This file contains the complete bootloader logic.
34  */
35
36 #include "BootloaderHID.h"
37
38 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
39  *  via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
40  *  started via a forced watchdog reset.
41  */
42 static bool RunBootloader = true;
43
44 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
45  *  will start if the /HWB line of the AVR is held low and the system is reset. However, if the /HWB line is still held
46  *  low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
47  *  \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
48  */
49 uint16_t MagicBootKey ATTR_NO_INIT;
50
51
52 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
53  *  start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
54  *  this will force the user application to start via a software jump.
55  */
56 void Application_Jump_Check(void)
57 {
58         /* If the reset source was the bootloader and the key is correct, clear it and jump to the application */
59         if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
60         {
61                 /* Turn off the watchdog */
62                 MCUSR &= ~(1 << WDRF);
63                 wdt_disable();
64
65                 /* Clear the boot key and jump to the user application */
66                 MagicBootKey = 0;
67
68                 // cppcheck-suppress constStatement
69                 ((void (*)(void))0x0000)();
70         }
71 }
72
73 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
74  *  runs the bootloader processing routine until instructed to soft-exit.
75  */
76 int main(void)
77 {
78         /* Setup hardware required for the bootloader */
79         SetupHardware();
80
81         /* Enable global interrupts so that the USB stack can function */
82         GlobalInterruptEnable();
83
84         while (RunBootloader)
85           USB_USBTask();
86
87         /* Disconnect from the host - USB interface will be reset later along with the AVR */
88         USB_Detach();
89
90         /* Unlock the forced application start mode of the bootloader if it is restarted */
91         MagicBootKey = MAGIC_BOOT_KEY;
92
93         /* Enable the watchdog and force a timeout to reset the AVR */
94         wdt_enable(WDTO_250MS);
95
96         for (;;);
97 }
98
99 /** Configures all hardware required for the bootloader. */
100 static void SetupHardware(void)
101 {
102         /* Disable watchdog if enabled by bootloader/fuses */
103         MCUSR &= ~(1 << WDRF);
104         wdt_disable();
105
106         /* Disable clock division */
107         clock_prescale_set(clock_div_1);
108
109         /* Relocate the interrupt vector table to the bootloader section */
110         MCUCR = (1 << IVCE);
111         MCUCR = (1 << IVSEL);
112
113         /* Initialize USB subsystem */
114         USB_Init();
115 }
116
117 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
118  *  to relay data to and from the attached USB host.
119  */
120 void EVENT_USB_Device_ConfigurationChanged(void)
121 {
122         /* Setup HID Report Endpoint */
123         Endpoint_ConfigureEndpoint(HID_IN_EPADDR, EP_TYPE_INTERRUPT, HID_IN_EPSIZE, 1);
124 }
125
126 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
127  *  the device from the USB host before passing along unhandled control requests to the library for processing
128  *  internally.
129  */
130 void EVENT_USB_Device_ControlRequest(void)
131 {
132         /* Ignore any requests that aren't directed to the HID interface */
133         if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
134             (REQTYPE_CLASS | REQREC_INTERFACE))
135         {
136                 return;
137         }
138
139         /* Process HID specific control requests */
140         switch (USB_ControlRequest.bRequest)
141         {
142                 case HID_REQ_SetReport:
143                         Endpoint_ClearSETUP();
144
145                         /* Wait until the command has been sent by the host */
146                         while (!(Endpoint_IsOUTReceived()));
147
148                         /* Read in the write destination address */
149                         #if (FLASHEND > 0xFFFF)
150                         uint32_t PageAddress = ((uint32_t)Endpoint_Read_16_LE() << 8);
151                         #else
152                         uint16_t PageAddress = Endpoint_Read_16_LE();
153                         #endif
154
155                         /* Check if the command is a program page command, or a start application command */
156                         #if (FLASHEND > 0xFFFF)
157                         if ((uint16_t)(PageAddress >> 8) == COMMAND_STARTAPPLICATION)
158                         #else
159                         if (PageAddress == COMMAND_STARTAPPLICATION)
160                         #endif
161                         {
162                                 RunBootloader = false;
163                         }
164                         else if (PageAddress < BOOT_START_ADDR)
165                         {
166                                 /* Erase the given FLASH page, ready to be programmed */
167                                 boot_page_erase(PageAddress);
168                                 boot_spm_busy_wait();
169
170                                 /* Write each of the FLASH page's bytes in sequence */
171                                 for (uint8_t PageWord = 0; PageWord < (SPM_PAGESIZE / 2); PageWord++)
172                                 {
173                                         /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
174                                         if (!(Endpoint_BytesInEndpoint()))
175                                         {
176                                                 Endpoint_ClearOUT();
177                                                 while (!(Endpoint_IsOUTReceived()));
178                                         }
179
180                                         /* Write the next data word to the FLASH page */
181                                         boot_page_fill(PageAddress + ((uint16_t)PageWord << 1), Endpoint_Read_16_LE());
182                                 }
183
184                                 /* Write the filled FLASH page to memory */
185                                 boot_page_write(PageAddress);
186                                 boot_spm_busy_wait();
187
188                                 /* Re-enable RWW section */
189                                 boot_rww_enable();
190                         }
191
192                         Endpoint_ClearOUT();
193
194                         Endpoint_ClearStatusStage();
195                         break;
196         }
197 }
198