Documentation: Update copyrights to 2020.
[pub/USBasp.git] / Bootloaders / MassStorage / BootloaderMassStorage.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2020.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2020 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 Mass Storage class bootloader. This file contains the complete bootloader logic.
34 */
35
36 #define INCLUDE_FROM_BOOTLOADER_MASSSTORAGE_C
37 #include "BootloaderMassStorage.h"
38
39 /** LUFA Mass Storage Class driver interface configuration and state information. This structure is
40 * passed to all Mass Storage Class driver functions, so that multiple instances of the same class
41 * within a device can be differentiated from one another.
42 */
43 USB_ClassInfo_MS_Device_t Disk_MS_Interface =
44 {
45 .Config =
46 {
47 .InterfaceNumber = INTERFACE_ID_MassStorage,
48 .DataINEndpoint =
49 {
50 .Address = MASS_STORAGE_IN_EPADDR,
51 .Size = MASS_STORAGE_IO_EPSIZE,
52 .Banks = 1,
53 },
54 .DataOUTEndpoint =
55 {
56 .Address = MASS_STORAGE_OUT_EPADDR,
57 .Size = MASS_STORAGE_IO_EPSIZE,
58 .Banks = 1,
59 },
60 .TotalLUNs = 1,
61 },
62 };
63
64 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
65 * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
66 * started via a forced watchdog reset.
67 */
68 bool RunBootloader = true;
69
70 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
71 * 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
72 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
73 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
74 */
75 uint16_t MagicBootKey ATTR_NO_INIT;
76
77 /** Indicates if the bootloader is allowed to exit immediately if \ref RunBootloader is \c false. During shutdown all
78 * pending commands must be processed before jumping to the user-application, thus this tracks the main program loop
79 * iterations since a SCSI command from the host was received.
80 */
81 static uint8_t TicksSinceLastCommand = 0;
82
83
84 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
85 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
86 * this will force the user application to start via a software jump.
87 */
88 void Application_Jump_Check(void)
89 {
90 bool JumpToApplication = false;
91
92 #if (BOARD == BOARD_LEONARDO)
93 /* Enable pull-up on the IO13 pin so we can use it to select the mode */
94 PORTC |= (1 << 7);
95 Delay_MS(10);
96
97 /* If IO13 is not jumpered to ground, start the user application instead */
98 JumpToApplication = ((PINC & (1 << 7)) != 0);
99
100 /* Disable pull-up after the check has completed */
101 PORTC &= ~(1 << 7);
102 #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
103 /* Disable JTAG debugging */
104 JTAG_DISABLE();
105
106 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
107 PORTF |= (1 << 4);
108 Delay_MS(10);
109
110 /* If the TCK pin is not jumpered to ground, start the user application instead */
111 JumpToApplication = ((PINF & (1 << 4)) != 0);
112
113 /* Re-enable JTAG debugging */
114 JTAG_ENABLE();
115 #else
116 /* Check if the device's BOOTRST fuse is set */
117 if (!(BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & ~FUSE_BOOTRST))
118 {
119 /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
120 if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
121 JumpToApplication = true;
122
123 /* Clear reset source */
124 MCUSR &= ~(1 << EXTRF);
125 }
126 else
127 {
128 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
129 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
130 if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
131 JumpToApplication = true;
132
133 /* Clear reset source */
134 MCUSR &= ~(1 << WDRF);
135 }
136 #endif
137
138 /* Don't run the user application if the reset vector is blank (no app loaded) */
139 bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
140
141 /* If a request has been made to jump to the user application, honor it */
142 if (JumpToApplication && ApplicationValid)
143 {
144 /* Turn off the watchdog */
145 MCUSR &= ~(1 << WDRF);
146 wdt_disable();
147
148 /* Clear the boot key and jump to the user application */
149 MagicBootKey = 0;
150
151 // cppcheck-suppress constStatement
152 ((void (*)(void))0x0000)();
153 }
154 }
155
156 /** Main program entry point. This routine configures the hardware required by the application, then
157 * enters a loop to run the application tasks in sequence.
158 */
159 int main(void)
160 {
161 SetupHardware();
162
163 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
164 GlobalInterruptEnable();
165
166 while (RunBootloader || TicksSinceLastCommand++ < 0xFF)
167 {
168 MS_Device_USBTask(&Disk_MS_Interface);
169 USB_USBTask();
170 }
171
172 /* Wait a short time to end all USB transactions and then disconnect */
173 _delay_us(1000);
174
175 /* Disconnect from the host - USB interface will be reset later along with the AVR */
176 USB_Detach();
177
178 /* Unlock the forced application start mode of the bootloader if it is restarted */
179 MagicBootKey = MAGIC_BOOT_KEY;
180
181 /* Enable the watchdog and force a timeout to reset the AVR */
182 wdt_enable(WDTO_250MS);
183
184 for (;;);
185 }
186
187 /** Configures the board hardware and chip peripherals for the demo's functionality. */
188 static void SetupHardware(void)
189 {
190 /* Disable watchdog if enabled by bootloader/fuses */
191 MCUSR &= ~(1 << WDRF);
192 wdt_disable();
193
194 /* Disable clock division */
195 clock_prescale_set(clock_div_1);
196
197 /* Relocate the interrupt vector table to the bootloader section */
198 MCUCR = (1 << IVCE);
199 MCUCR = (1 << IVSEL);
200
201 /* Hardware Initialization */
202 LEDs_Init();
203 USB_Init();
204
205 /* Bootloader active LED toggle timer initialization */
206 TIMSK1 = (1 << TOIE1);
207 TCCR1B = ((1 << CS11) | (1 << CS10));
208 }
209
210 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
211 ISR(TIMER1_OVF_vect, ISR_BLOCK)
212 {
213 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
214 }
215
216 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
217 void EVENT_USB_Device_Connect(void)
218 {
219 /* Indicate USB enumerating */
220 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
221 }
222
223 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
224 * the status LEDs and stops the Mass Storage management task.
225 */
226 void EVENT_USB_Device_Disconnect(void)
227 {
228 /* Indicate USB not ready */
229 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
230 }
231
232 /** Event handler for the library USB Configuration Changed event. */
233 void EVENT_USB_Device_ConfigurationChanged(void)
234 {
235 bool ConfigSuccess = true;
236
237 /* Setup Mass Storage Data Endpoints */
238 ConfigSuccess &= MS_Device_ConfigureEndpoints(&Disk_MS_Interface);
239
240 /* Indicate endpoint configuration success or failure */
241 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
242 }
243
244 /** Event handler for the library USB Control Request reception event. */
245 void EVENT_USB_Device_ControlRequest(void)
246 {
247 MS_Device_ProcessControlRequest(&Disk_MS_Interface);
248 }
249
250 /** Mass Storage class driver callback function the reception of SCSI commands from the host, which must be processed.
251 *
252 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface configuration structure being referenced
253 */
254 bool CALLBACK_MS_Device_SCSICommandReceived(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
255 {
256 bool CommandSuccess;
257
258 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
259 CommandSuccess = SCSI_DecodeSCSICommand(MSInterfaceInfo);
260 LEDs_SetAllLEDs(LEDMASK_USB_READY);
261
262 /* Signal that a command was processed, must not exit bootloader yet */
263 TicksSinceLastCommand = 0;
264
265 return CommandSuccess;
266 }