Fix Doxygen treating the license as a documentation source file.
[pub/USBasp.git] / Bootloaders / CDC / BootloaderCDC.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2010 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 disclaim 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 CDC class bootloader. This file contains the complete bootloader logic.
34 */
35
36 #define INCLUDE_FROM_BOOTLOADERCDC_C
37 #include "BootloaderCDC.h"
38
39 /** Line coding options for the virtual serial port. Although the virtual serial port data is never
40 * sent through a physical serial port, the line encoding data must still be read and preserved from
41 * the host, or the host will detect a problem and fail to open the port. This structure contains the
42 * current encoding options, including baud rate, character format, parity mode and total number of
43 * bits in each data chunk.
44 */
45 CDC_Line_Coding_t LineCoding = { .BaudRateBPS = 9600,
46 .CharFormat = OneStopBit,
47 .ParityType = Parity_None,
48 .DataBits = 8 };
49
50 /** Current address counter. This stores the current address of the FLASH or EEPROM as set by the host,
51 * and is used when reading or writing to the AVRs memory (either FLASH or EEPROM depending on the issued
52 * command.)
53 */
54 uint32_t CurrAddress;
55
56 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
57 * via a watchdog reset. When cleared the bootloader will exit, starting the watchdog and entering an infinite
58 * loop until the AVR restarts and the application runs.
59 */
60 bool RunBootloader = true;
61
62
63 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
64 * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
65 * the loaded application code.
66 */
67 int main(void)
68 {
69 /* Setup hardware required for the bootloader */
70 SetupHardware();
71
72 /* Enable global interrupts so that the USB stack can function */
73 sei();
74
75 while (RunBootloader)
76 {
77 CDC_Task();
78 USB_USBTask();
79 }
80
81 /* Disconnect from the host - USB interface will be reset later along with the AVR */
82 USB_Detach();
83
84 /* Enable the watchdog and force a timeout to reset the AVR */
85 wdt_enable(WDTO_250MS);
86
87 for (;;);
88 }
89
90 /** Configures all hardware required for the bootloader. */
91 void SetupHardware(void)
92 {
93 /* Disable watchdog if enabled by bootloader/fuses */
94 MCUSR &= ~(1 << WDRF);
95 wdt_disable();
96
97 /* Disable clock division */
98 clock_prescale_set(clock_div_1);
99
100 /* Relocate the interrupt vector table to the bootloader section */
101 MCUCR = (1 << IVCE);
102 MCUCR = (1 << IVSEL);
103
104 /* Initialize USB Subsystem */
105 USB_Init();
106 }
107
108 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
109 * to relay data to and from the attached USB host.
110 */
111 void EVENT_USB_Device_ConfigurationChanged(void)
112 {
113 /* Setup CDC Notification, Rx and Tx Endpoints */
114 Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
115 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
116 ENDPOINT_BANK_SINGLE);
117
118 Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
119 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
120 ENDPOINT_BANK_SINGLE);
121
122 Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
123 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
124 ENDPOINT_BANK_SINGLE);
125 }
126
127 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
128 * control requests that are not handled internally by the USB library, so that they can be handled appropriately
129 * for the application.
130 */
131 void EVENT_USB_Device_UnhandledControlRequest(void)
132 {
133 uint8_t* LineCodingData = (uint8_t*)&LineCoding;
134
135 /* Process CDC specific control requests */
136 switch (USB_ControlRequest.bRequest)
137 {
138 case REQ_GetLineEncoding:
139 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
140 {
141 Endpoint_ClearSETUP();
142
143 for (uint8_t i = 0; i < sizeof(LineCoding); i++)
144 Endpoint_Write_Byte(*(LineCodingData++));
145
146 Endpoint_ClearIN();
147
148 Endpoint_ClearStatusStage();
149 }
150
151 break;
152 case REQ_SetLineEncoding:
153 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
154 {
155 Endpoint_ClearSETUP();
156
157 while (!(Endpoint_IsOUTReceived()))
158 {
159 if (USB_DeviceState == DEVICE_STATE_Unattached)
160 return;
161 }
162
163 for (uint8_t i = 0; i < sizeof(LineCoding); i++)
164 *(LineCodingData++) = Endpoint_Read_Byte();
165
166 Endpoint_ClearOUT();
167
168 Endpoint_ClearStatusStage();
169 }
170
171 break;
172 case REQ_SetControlLineState:
173 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
174 {
175 Endpoint_ClearSETUP();
176
177 Endpoint_ClearStatusStage();
178 }
179
180 break;
181 }
182 }
183
184 /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending
185 * on the AVR910 protocol command issued.
186 *
187 * \param[in] Command Single character AVR910 protocol command indicating what memory operation to perform
188 */
189 static void ReadWriteMemoryBlock(const uint8_t Command)
190 {
191 uint16_t BlockSize;
192 char MemoryType;
193
194 bool HighByte = false;
195 uint8_t LowByte = 0;
196
197 BlockSize = (FetchNextCommandByte() << 8);
198 BlockSize |= FetchNextCommandByte();
199
200 MemoryType = FetchNextCommandByte();
201
202 if ((MemoryType != 'E') && (MemoryType != 'F'))
203 {
204 /* Send error byte back to the host */
205 WriteNextResponseByte('?');
206
207 return;
208 }
209
210 /* Check if command is to read memory */
211 if (Command == 'g')
212 {
213 /* Re-enable RWW section */
214 boot_rww_enable();
215
216 while (BlockSize--)
217 {
218 if (MemoryType == 'F')
219 {
220 /* Read the next FLASH byte from the current FLASH page */
221 #if (FLASHEND > 0xFFFF)
222 WriteNextResponseByte(pgm_read_byte_far(CurrAddress | HighByte));
223 #else
224 WriteNextResponseByte(pgm_read_byte(CurrAddress | HighByte));
225 #endif
226
227 /* If both bytes in current word have been read, increment the address counter */
228 if (HighByte)
229 CurrAddress += 2;
230
231 HighByte = !HighByte;
232 }
233 else
234 {
235 /* Read the next EEPROM byte into the endpoint */
236 WriteNextResponseByte(eeprom_read_byte((uint8_t*)(uint16_t)(CurrAddress >> 1)));
237
238 /* Increment the address counter after use */
239 CurrAddress += 2;
240 }
241 }
242 }
243 else
244 {
245 uint32_t PageStartAddress = CurrAddress;
246
247 if (MemoryType == 'F')
248 {
249 boot_page_erase(PageStartAddress);
250 boot_spm_busy_wait();
251 }
252
253 while (BlockSize--)
254 {
255 if (MemoryType == 'F')
256 {
257 /* If both bytes in current word have been written, increment the address counter */
258 if (HighByte)
259 {
260 /* Write the next FLASH word to the current FLASH page */
261 boot_page_fill(CurrAddress, ((FetchNextCommandByte() << 8) | LowByte));
262
263 /* Increment the address counter after use */
264 CurrAddress += 2;
265
266 HighByte = false;
267 }
268 else
269 {
270 LowByte = FetchNextCommandByte();
271
272 HighByte = true;
273 }
274 }
275 else
276 {
277 /* Write the next EEPROM byte from the endpoint */
278 eeprom_write_byte((uint8_t*)(uint16_t)(CurrAddress >> 1), FetchNextCommandByte());
279
280 /* Increment the address counter after use */
281 CurrAddress += 2;
282 }
283 }
284
285 /* If in FLASH programming mode, commit the page after writing */
286 if (MemoryType == 'F')
287 {
288 /* Commit the flash page to memory */
289 boot_page_write(PageStartAddress);
290
291 /* Wait until write operation has completed */
292 boot_spm_busy_wait();
293 }
294
295 /* Send response byte back to the host */
296 WriteNextResponseByte('\r');
297 }
298 }
299
300 /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed
301 * to allow reception of the next data packet from the host.
302 *
303 * \return Next received byte from the host in the CDC data OUT endpoint
304 */
305 static uint8_t FetchNextCommandByte(void)
306 {
307 /* Select the OUT endpoint so that the next data byte can be read */
308 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
309
310 /* If OUT endpoint empty, clear it and wait for the next packet from the host */
311 while (!(Endpoint_IsReadWriteAllowed()))
312 {
313 Endpoint_ClearOUT();
314
315 while (!(Endpoint_IsOUTReceived()))
316 {
317 if (USB_DeviceState == DEVICE_STATE_Unattached)
318 return 0;
319 }
320 }
321
322 /* Fetch the next byte from the OUT endpoint */
323 return Endpoint_Read_Byte();
324 }
325
326 /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the
327 * bank when full ready for the next byte in the packet to the host.
328 *
329 * \param[in] Response Next response byte to send to the host
330 */
331 static void WriteNextResponseByte(const uint8_t Response)
332 {
333 /* Select the IN endpoint so that the next data byte can be written */
334 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
335
336 /* If IN endpoint full, clear it and wait until ready for the next packet to the host */
337 if (!(Endpoint_IsReadWriteAllowed()))
338 {
339 Endpoint_ClearIN();
340
341 while (!(Endpoint_IsINReady()))
342 {
343 if (USB_DeviceState == DEVICE_STATE_Unattached)
344 return;
345 }
346 }
347
348 /* Write the next byte to the OUT endpoint */
349 Endpoint_Write_Byte(Response);
350 }
351
352 /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions
353 * and send the appropriate response back to the host.
354 */
355 void CDC_Task(void)
356 {
357 /* Select the OUT endpoint */
358 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
359
360 /* Check if endpoint has a command in it sent from the host */
361 if (Endpoint_IsOUTReceived())
362 {
363 /* Read in the bootloader command (first byte sent from host) */
364 uint8_t Command = FetchNextCommandByte();
365
366 if ((Command == 'L') || (Command == 'P') || (Command == 'T') || (Command == 'E'))
367 {
368 if (Command == 'E')
369 RunBootloader = false;
370 if (Command == 'T')
371 FetchNextCommandByte();
372
373 /* Send confirmation byte back to the host */
374 WriteNextResponseByte('\r');
375 }
376 else if (Command == 't')
377 {
378 /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */
379 WriteNextResponseByte(0x44);
380
381 WriteNextResponseByte(0x00);
382 }
383 else if (Command == 'a')
384 {
385 /* Indicate auto-address increment is supported */
386 WriteNextResponseByte('Y');
387 }
388 else if (Command == 'A')
389 {
390 /* Set the current address to that given by the host */
391 CurrAddress = (FetchNextCommandByte() << 9);
392 CurrAddress |= (FetchNextCommandByte() << 1);
393
394 /* Send confirmation byte back to the host */
395 WriteNextResponseByte('\r');
396 }
397 else if (Command == 'p')
398 {
399 /* Indicate serial programmer back to the host */
400 WriteNextResponseByte('S');
401 }
402 else if (Command == 'S')
403 {
404 /* Write the 7-byte software identifier to the endpoint */
405 for (uint8_t CurrByte = 0; CurrByte < 7; CurrByte++)
406 WriteNextResponseByte(SOFTWARE_IDENTIFIER[CurrByte]);
407 }
408 else if (Command == 'V')
409 {
410 WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR);
411 WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR);
412 }
413 else if (Command == 's')
414 {
415 WriteNextResponseByte(AVR_SIGNATURE_3);
416 WriteNextResponseByte(AVR_SIGNATURE_2);
417 WriteNextResponseByte(AVR_SIGNATURE_1);
418 }
419 else if (Command == 'b')
420 {
421 WriteNextResponseByte('Y');
422
423 /* Send block size to the host */
424 WriteNextResponseByte(SPM_PAGESIZE >> 8);
425 WriteNextResponseByte(SPM_PAGESIZE & 0xFF);
426 }
427 else if (Command == 'e')
428 {
429 /* Clear the application section of flash */
430 for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < BOOT_START_ADDR; CurrFlashAddress++)
431 {
432 boot_page_erase(CurrFlashAddress);
433 boot_spm_busy_wait();
434 boot_page_write(CurrFlashAddress);
435 boot_spm_busy_wait();
436
437 CurrFlashAddress += SPM_PAGESIZE;
438 }
439
440 /* Send confirmation byte back to the host */
441 WriteNextResponseByte('\r');
442 }
443 else if (Command == 'l')
444 {
445 /* Set the lock bits to those given by the host */
446 boot_lock_bits_set(FetchNextCommandByte());
447
448 /* Send confirmation byte back to the host */
449 WriteNextResponseByte('\r');
450 }
451 else if (Command == 'r')
452 {
453 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS));
454 }
455 else if (Command == 'F')
456 {
457 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS));
458 }
459 else if (Command == 'N')
460 {
461 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS));
462 }
463 else if (Command == 'Q')
464 {
465 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS));
466 }
467 else if (Command == 'C')
468 {
469 /* Write the high byte to the current flash page */
470 boot_page_fill(CurrAddress, FetchNextCommandByte());
471
472 /* Send confirmation byte back to the host */
473 WriteNextResponseByte('\r');
474 }
475 else if (Command == 'c')
476 {
477 /* Write the low byte to the current flash page */
478 boot_page_fill(CurrAddress | 1, FetchNextCommandByte());
479
480 /* Increment the address */
481 CurrAddress += 2;
482
483 /* Send confirmation byte back to the host */
484 WriteNextResponseByte('\r');
485 }
486 else if (Command == 'm')
487 {
488 /* Commit the flash page to memory */
489 boot_page_write(CurrAddress);
490
491 /* Wait until write operation has completed */
492 boot_spm_busy_wait();
493
494 /* Send confirmation byte back to the host */
495 WriteNextResponseByte('\r');
496 }
497 else if ((Command == 'B') || (Command == 'g'))
498 {
499 /* Delegate the block write/read to a separate function for clarity */
500 ReadWriteMemoryBlock(Command);
501 }
502 else if (Command == 'R')
503 {
504 #if (FLASHEND > 0xFFFF)
505 uint16_t ProgramWord = pgm_read_word_far(CurrAddress);
506 #else
507 uint16_t ProgramWord = pgm_read_word(CurrAddress);
508 #endif
509
510 WriteNextResponseByte(ProgramWord >> 8);
511 WriteNextResponseByte(ProgramWord & 0xFF);
512 }
513 else if (Command == 'D')
514 {
515 /* Read the byte from the endpoint and write it to the EEPROM */
516 eeprom_write_byte((uint8_t*)((uint16_t)(CurrAddress >> 1)), FetchNextCommandByte());
517
518 /* Increment the address after use */
519 CurrAddress += 2;
520
521 /* Send confirmation byte back to the host */
522 WriteNextResponseByte('\r');
523 }
524 else if (Command == 'd')
525 {
526 /* Read the EEPROM byte and write it to the endpoint */
527 WriteNextResponseByte(eeprom_read_byte((uint8_t*)((uint16_t)(CurrAddress >> 1))));
528
529 /* Increment the address after use */
530 CurrAddress += 2;
531 }
532 else if (Command == 27)
533 {
534 /* Escape is sync, ignore */
535 }
536 else
537 {
538 /* Unknown command, return fail code */
539 WriteNextResponseByte('?');
540 }
541
542 /* Select the IN endpoint */
543 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
544
545 /* Remember if the endpoint is completely full before clearing it */
546 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
547
548 /* Send the endpoint data to the host */
549 Endpoint_ClearIN();
550
551 /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */
552 if (IsEndpointFull)
553 {
554 while (!(Endpoint_IsINReady()))
555 {
556 if (USB_DeviceState == DEVICE_STATE_Unattached)
557 return;
558 }
559
560 Endpoint_ClearIN();
561 }
562
563 /* Wait until the data has been sent to the host */
564 while (!(Endpoint_IsINReady()))
565 {
566 if (USB_DeviceState == DEVICE_STATE_Unattached)
567 return;
568 }
569
570 /* Select the OUT endpoint */
571 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
572
573 /* Acknowledge the command from the host */
574 Endpoint_ClearOUT();
575 }
576 }