Fixed bootloaders not disabling global interrupts during erase and write operations...
[pub/lufa.git] / Bootloaders / Printer / BootloaderPrinter.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 Printer class bootloader. This file contains the complete bootloader logic.
34 */
35
36 #include "BootloaderPrinter.h"
37
38 /** LUFA Printer Class driver interface configuration and state information. This structure is
39 * passed to all Printer Class driver functions, so that multiple instances of the same class
40 * within a device can be differentiated from one another.
41 */
42 USB_ClassInfo_PRNT_Device_t TextOnly_Printer_Interface =
43 {
44 .Config =
45 {
46 .InterfaceNumber = INTERFACE_ID_Printer,
47 .DataINEndpoint =
48 {
49 .Address = PRINTER_IN_EPADDR,
50 .Size = PRINTER_IO_EPSIZE,
51 .Banks = 1,
52 },
53 .DataOUTEndpoint =
54 {
55 .Address = PRINTER_OUT_EPADDR,
56 .Size = PRINTER_IO_EPSIZE,
57 .Banks = 1,
58 },
59 .IEEE1284String =
60 "MFG:Generic;"
61 "MDL:Generic_/_Text_Only;"
62 "CMD:1284.4;"
63 "CLS:PRINTER",
64 },
65 };
66
67 /** Intel HEX parser state machine state information, to track the contents of
68 * a HEX file streamed in as a sequence of arbitrary bytes.
69 */
70 struct
71 {
72 /** Current HEX parser state machine state. */
73 uint8_t ParserState;
74 /** Previously decoded numerical byte of data. */
75 uint8_t PrevData;
76 /** Currently decoded numerical byte of data. */
77 uint8_t Data;
78 /** Indicates if both bytes that correspond to a single decoded numerical
79 * byte of data (HEX encodes values in ASCII HEX, two characters per byte)
80 * have been read.
81 */
82 bool ReadMSB;
83 /** Intel HEX record type of the current Intel HEX record. */
84 uint8_t RecordType;
85 /** Numerical bytes of data remaining to be read in the current record. */
86 uint8_t DataRem;
87 /** Checksum of the current record received so far. */
88 uint8_t Checksum;
89 /** Starting address of the last addressed FLASH page. */
90 uint32_t PageStartAddress;
91 /** Current 32-bit byte extended base address in FLASH being targeted. */
92 uint32_t CurrBaseAddress;
93 /** Current 32-bit byte address in FLASH being targeted. */
94 uint32_t CurrAddress;
95 } HEXParser;
96
97 /** Indicates if there is data waiting to be written to a physical page of
98 * memory in FLASH.
99 */
100 static bool PageDirty = false;
101
102 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
103 * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
104 * started via a forced watchdog reset.
105 */
106 static bool RunBootloader = true;
107
108 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
109 * 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
110 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
111 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
112 */
113 uint16_t MagicBootKey ATTR_NO_INIT;
114
115
116 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
117 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
118 * this will force the user application to start via a software jump.
119 */
120 void Application_Jump_Check(void)
121 {
122 bool JumpToApplication = false;
123
124 #if (BOARD == BOARD_LEONARDO)
125 /* Enable pull-up on the IO13 pin so we can use it to select the mode */
126 PORTC |= (1 << 7);
127 Delay_MS(10);
128
129 /* If IO13 is not jumpered to ground, start the user application instead */
130 JumpToApplication = ((PINC & (1 << 7)) != 0);
131
132 /* Disable pull-up after the check has completed */
133 PORTC &= ~(1 << 7);
134 #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
135 /* Disable JTAG debugging */
136 JTAG_DISABLE();
137
138 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
139 PORTF |= (1 << 4);
140 Delay_MS(10);
141
142 /* If the TCK pin is not jumpered to ground, start the user application instead */
143 JumpToApplication = ((PINF & (1 << 4)) != 0);
144
145 /* Re-enable JTAG debugging */
146 JTAG_ENABLE();
147 #else
148 /* Check if the device's BOOTRST fuse is set */
149 if (BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & FUSE_BOOTRST)
150 {
151 /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
152 if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
153 JumpToApplication = true;
154
155 /* Clear reset source */
156 MCUSR &= ~(1 << EXTRF);
157 }
158 else
159 {
160 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
161 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
162 if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
163 JumpToApplication = true;
164
165 /* Clear reset source */
166 MCUSR &= ~(1 << WDRF);
167 }
168 #endif
169
170 /* Don't run the user application if the reset vector is blank (no app loaded) */
171 bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
172
173 /* If a request has been made to jump to the user application, honor it */
174 if (JumpToApplication && ApplicationValid)
175 {
176 /* Turn off the watchdog */
177 MCUSR &= ~(1 << WDRF);
178 wdt_disable();
179
180 /* Clear the boot key and jump to the user application */
181 MagicBootKey = 0;
182
183 // cppcheck-suppress constStatement
184 ((void (*)(void))0x0000)();
185 }
186 }
187
188 /**
189 * Converts a given input byte of data from an ASCII encoded HEX value to an integer value.
190 *
191 * \note Input HEX bytes are expected to be in uppercase only.
192 *
193 * \param[in] Byte ASCII byte of data to convert
194 *
195 * \return Integer converted value of the input ASCII encoded HEX byte of data, or -1 if the
196 * input is not valid ASCII encoded HEX.
197 */
198 static int8_t HexToDecimal(const char Byte)
199 {
200 if ((Byte >= 'A') && (Byte <= 'F'))
201 return (10 + (Byte - 'A'));
202 else if ((Byte >= '0') && (Byte <= '9'))
203 return (Byte - '0');
204
205 return -1;
206 }
207
208 /**
209 * Flushes a partially written page of data to physical FLASH, if a page
210 * boundary has been crossed.
211 *
212 * \note If a page flush occurs the global HEX parser state is updated.
213 */
214 static void FlushPageIfRequired(void)
215 {
216 /* Abort if no data has been buffered for writing to the current page */
217 if (!PageDirty)
218 return;
219
220 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
221 uint32_t NewPageStartAddress = (HEXParser.CurrAddress & ~(SPM_PAGESIZE - 1));
222 if (HEXParser.PageStartAddress != NewPageStartAddress)
223 {
224 BootloaderAPI_WritePage(HEXParser.PageStartAddress);
225
226 HEXParser.PageStartAddress = NewPageStartAddress;
227
228 PageDirty = false;
229 }
230 }
231
232 /**
233 * Parses an input Intel HEX formatted stream one character at a time, loading
234 * the data contents into the device's internal FLASH memory.
235 *
236 * \param[in] ReadCharacter Next input ASCII byte of data to parse
237 */
238 static void ParseIntelHEXByte(const char ReadCharacter)
239 {
240 /* Reset the line parser while waiting for a new line to start */
241 if ((HEXParser.ParserState == HEX_PARSE_STATE_WAIT_LINE) || (ReadCharacter == ':'))
242 {
243 HEXParser.Checksum = 0;
244 HEXParser.CurrAddress = HEXParser.CurrBaseAddress;
245 HEXParser.ReadMSB = false;
246
247 /* ASCII ':' indicates the start of a new HEX record */
248 if (ReadCharacter == ':')
249 HEXParser.ParserState = HEX_PARSE_STATE_BYTE_COUNT;
250
251 return;
252 }
253
254 /* Only allow ASCII HEX encoded digits, ignore all other characters */
255 int8_t ReadCharacterDec = HexToDecimal(ReadCharacter);
256 if (ReadCharacterDec < 0)
257 return;
258
259 /* Read and convert the next nibble of data from the current character */
260 HEXParser.Data = (HEXParser.Data << 4) | ReadCharacterDec;
261 HEXParser.ReadMSB = !HEXParser.ReadMSB;
262
263 /* Only process further when a full byte (two nibbles) have been read */
264 if (HEXParser.ReadMSB)
265 return;
266
267 /* Intel HEX checksum is for all fields except starting character and the
268 * checksum itself
269 */
270 if (HEXParser.ParserState != HEX_PARSE_STATE_CHECKSUM)
271 HEXParser.Checksum += HEXParser.Data;
272
273 switch (HEXParser.ParserState)
274 {
275 case HEX_PARSE_STATE_BYTE_COUNT:
276 HEXParser.DataRem = HEXParser.Data;
277 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_HIGH;
278 break;
279
280 case HEX_PARSE_STATE_ADDRESS_HIGH:
281 HEXParser.CurrAddress += ((uint16_t)HEXParser.Data << 8);
282 HEXParser.ParserState = HEX_PARSE_STATE_ADDRESS_LOW;
283 break;
284
285 case HEX_PARSE_STATE_ADDRESS_LOW:
286 HEXParser.CurrAddress += HEXParser.Data;
287 HEXParser.ParserState = HEX_PARSE_STATE_RECORD_TYPE;
288 break;
289
290 case HEX_PARSE_STATE_RECORD_TYPE:
291 HEXParser.RecordType = HEXParser.Data;
292 HEXParser.ParserState = (HEXParser.DataRem ? HEX_PARSE_STATE_READ_DATA : HEX_PARSE_STATE_CHECKSUM);
293 break;
294
295 case HEX_PARSE_STATE_READ_DATA:
296 /* Track the number of read data bytes in the record */
297 HEXParser.DataRem--;
298
299 /* Protect the bootloader against being written to */
300 if (HEXParser.CurrAddress >= BOOT_START_ADDR)
301 {
302 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
303 PageDirty = false;
304 return;
305 }
306
307 /* Wait for a machine word (two bytes) of data to be read */
308 if (HEXParser.DataRem & 0x01)
309 {
310 HEXParser.PrevData = HEXParser.Data;
311 break;
312 }
313
314 /* Convert the last two received data bytes into a 16-bit word */
315 uint16_t NewDataWord = ((uint16_t)HEXParser.Data << 8) | HEXParser.PrevData;
316
317 switch (HEXParser.RecordType)
318 {
319 case HEX_RECORD_TYPE_Data:
320 /* If we are writing to a new page, we need to erase it first */
321 if (!(PageDirty))
322 {
323 BootloaderAPI_ErasePage(HEXParser.PageStartAddress);
324
325 PageDirty = true;
326 }
327
328 /* Fill the FLASH memory buffer with the new word of data */
329 BootloaderAPI_FillWord(HEXParser.CurrAddress, NewDataWord);
330 HEXParser.CurrAddress += 2;
331
332 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
333 FlushPageIfRequired();
334 break;
335
336 case HEX_RECORD_TYPE_ExtendedSegmentAddress:
337 /* Extended address data - store the upper 12-bits of the new address */
338 HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 4);
339 break;
340
341 case HEX_RECORD_TYPE_ExtendedLinearAddress:
342 /* Extended address data - store the upper 16-bits of the new address */
343 HEXParser.CurrBaseAddress = ((uint32_t)NewDataWord << 16);
344 break;
345 }
346
347 if (!HEXParser.DataRem)
348 HEXParser.ParserState = HEX_PARSE_STATE_CHECKSUM;
349 break;
350
351 case HEX_PARSE_STATE_CHECKSUM:
352 /* Verify checksum of the completed record */
353 if (HEXParser.Data != ((~HEXParser.Checksum + 1) & 0xFF))
354 break;
355
356 /* Flush the FLASH page to physical memory if we are crossing a page boundary */
357 FlushPageIfRequired();
358
359 /* If end of the HEX file reached, the bootloader should exit at next opportunity */
360 if (HEXParser.RecordType == HEX_RECORD_TYPE_EndOfFile)
361 RunBootloader = false;
362
363 break;
364
365 default:
366 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
367 break;
368 }
369 }
370
371 /** Main program entry point. This routine configures the hardware required by the application, then
372 * enters a loop to run the application tasks in sequence.
373 */
374 int main(void)
375 {
376 SetupHardware();
377
378 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
379 GlobalInterruptEnable();
380
381 while (RunBootloader)
382 {
383 uint8_t BytesReceived = PRNT_Device_BytesReceived(&TextOnly_Printer_Interface);
384
385 if (BytesReceived)
386 {
387 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
388
389 while (BytesReceived--)
390 {
391 int16_t ReceivedByte = PRNT_Device_ReceiveByte(&TextOnly_Printer_Interface);
392
393 /* Feed the next byte of data to the HEX parser */
394 ParseIntelHEXByte(ReceivedByte);
395 }
396
397 LEDs_SetAllLEDs(LEDMASK_USB_READY);
398 }
399
400 PRNT_Device_USBTask(&TextOnly_Printer_Interface);
401 USB_USBTask();
402 }
403
404 /* Disconnect from the host - USB interface will be reset later along with the AVR */
405 USB_Detach();
406
407 /* Unlock the forced application start mode of the bootloader if it is restarted */
408 MagicBootKey = MAGIC_BOOT_KEY;
409
410 /* Enable the watchdog and force a timeout to reset the AVR */
411 wdt_enable(WDTO_250MS);
412
413 for (;;);
414 }
415
416 /** Configures the board hardware and chip peripherals for the demo's functionality. */
417 static void SetupHardware(void)
418 {
419 /* Disable watchdog if enabled by bootloader/fuses */
420 MCUSR &= ~(1 << WDRF);
421 wdt_disable();
422
423 /* Disable clock division */
424 clock_prescale_set(clock_div_1);
425
426 /* Relocate the interrupt vector table to the bootloader section */
427 MCUCR = (1 << IVCE);
428 MCUCR = (1 << IVSEL);
429
430 /* Hardware Initialization */
431 LEDs_Init();
432 USB_Init();
433
434 /* Bootloader active LED toggle timer initialization */
435 TIMSK1 = (1 << TOIE1);
436 TCCR1B = ((1 << CS11) | (1 << CS10));
437 }
438
439 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
440 ISR(TIMER1_OVF_vect, ISR_BLOCK)
441 {
442 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
443 }
444
445 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
446 void EVENT_USB_Device_Connect(void)
447 {
448 /* Indicate USB enumerating */
449 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
450 }
451
452 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
453 * the status LEDs and stops the Printer management task.
454 */
455 void EVENT_USB_Device_Disconnect(void)
456 {
457 /* Indicate USB not ready */
458 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
459 }
460
461 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
462 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
463 */
464 void EVENT_USB_Device_ConfigurationChanged(void)
465 {
466 bool ConfigSuccess = true;
467
468 /* Setup Printer Data Endpoints */
469 ConfigSuccess &= PRNT_Device_ConfigureEndpoints(&TextOnly_Printer_Interface);
470
471 /* Reset the HEX parser upon successful connection to a host */
472 HEXParser.ParserState = HEX_PARSE_STATE_WAIT_LINE;
473
474 /* Indicate endpoint configuration success or failure */
475 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
476 }
477
478 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
479 * the device from the USB host before passing along unhandled control requests to the library for processing
480 * internally.
481 */
482 void EVENT_USB_Device_ControlRequest(void)
483 {
484 PRNT_Device_ProcessControlRequest(&TextOnly_Printer_Interface);
485 }