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