Renamed all library events to properly seperate out Device and Host mode events....
[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_Disconnect event. This indicates that the bootloader should exit and the user
120 * application started.
121 */
122 void EVENT_USB_Device_Disconnect(void)
123 {
124 /* Upon disconnection, run user application */
125 RunBootloader = false;
126 }
127
128 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
129 * to relay data to and from the attached USB host.
130 */
131 void EVENT_USB_Device_ConfigurationChanged(void)
132 {
133 /* Setup CDC Notification, Rx and Tx Endpoints */
134 Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
135 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
136 ENDPOINT_BANK_SINGLE);
137
138 Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
139 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
140 ENDPOINT_BANK_SINGLE);
141
142 Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
143 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
144 ENDPOINT_BANK_SINGLE);
145 }
146
147 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
148 * control requests that are not handled internally by the USB library, so that they can be handled appropriately
149 * for the application.
150 */
151 void EVENT_USB_Device_UnhandledControlRequest(void)
152 {
153 uint8_t* LineCodingData = (uint8_t*)&LineCoding;
154
155 /* Process CDC specific control requests */
156 switch (USB_ControlRequest.bRequest)
157 {
158 case REQ_GetLineEncoding:
159 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
160 {
161 Endpoint_ClearSETUP();
162
163 for (uint8_t i = 0; i < sizeof(LineCoding); i++)
164 Endpoint_Write_Byte(*(LineCodingData++));
165
166 Endpoint_ClearIN();
167
168 Endpoint_ClearStatusStage();
169 }
170
171 break;
172 case REQ_SetLineEncoding:
173 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
174 {
175 Endpoint_ClearSETUP();
176
177 while (!(Endpoint_IsOUTReceived()))
178 {
179 if (USB_DeviceState == DEVICE_STATE_Unattached)
180 return;
181 }
182
183 for (uint8_t i = 0; i < sizeof(LineCoding); i++)
184 *(LineCodingData++) = Endpoint_Read_Byte();
185
186 Endpoint_ClearOUT();
187
188 Endpoint_ClearStatusStage();
189 }
190
191 break;
192 case REQ_SetControlLineState:
193 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
194 {
195 Endpoint_ClearSETUP();
196
197 Endpoint_ClearStatusStage();
198 }
199
200 break;
201 }
202 }
203
204 /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending
205 * on the AVR910 protocol command issued.
206 *
207 * \param[in] Command Single character AVR910 protocol command indicating what memory operation to perform
208 */
209 static void ReadWriteMemoryBlock(const uint8_t Command)
210 {
211 uint16_t BlockSize;
212 char MemoryType;
213
214 bool HighByte = false;
215 uint8_t LowByte = 0;
216
217 BlockSize = (FetchNextCommandByte() << 8);
218 BlockSize |= FetchNextCommandByte();
219
220 MemoryType = FetchNextCommandByte();
221
222 if ((MemoryType != 'E') && (MemoryType != 'F'))
223 {
224 /* Send error byte back to the host */
225 WriteNextResponseByte('?');
226
227 return;
228 }
229
230 /* Check if command is to read memory */
231 if (Command == 'g')
232 {
233 /* Re-enable RWW section */
234 boot_rww_enable();
235
236 while (BlockSize--)
237 {
238 if (MemoryType == 'E')
239 {
240 /* Read the next EEPROM byte into the endpoint */
241 WriteNextResponseByte(eeprom_read_byte((uint8_t*)(uint16_t)(CurrAddress >> 1)));
242
243 /* Increment the address counter after use */
244 CurrAddress += 2;
245 }
246 else
247 {
248 /* Read the next FLASH byte from the current FLASH page */
249 #if (FLASHEND > 0xFFFF)
250 WriteNextResponseByte(pgm_read_byte_far(CurrAddress | HighByte));
251 #else
252 WriteNextResponseByte(pgm_read_byte(CurrAddress | HighByte));
253 #endif
254
255 /* If both bytes in current word have been read, increment the address counter */
256 if (HighByte)
257 CurrAddress += 2;
258
259 HighByte = !HighByte;
260 }
261 }
262 }
263 else
264 {
265 uint32_t PageStartAddress = CurrAddress;
266
267 if (MemoryType == 'F')
268 {
269 boot_page_erase(PageStartAddress);
270 boot_spm_busy_wait();
271 }
272
273 while (BlockSize--)
274 {
275 if (MemoryType == 'F')
276 {
277 /* If both bytes in current word have been written, increment the address counter */
278 if (HighByte)
279 {
280 /* Write the next FLASH word to the current FLASH page */
281 boot_page_fill(CurrAddress, ((FetchNextCommandByte() << 8) | LowByte));
282
283 /* Increment the address counter after use */
284 CurrAddress += 2;
285
286 HighByte = false;
287 }
288 else
289 {
290 LowByte = FetchNextCommandByte();
291
292 HighByte = true;
293 }
294 }
295 else
296 {
297 /* Write the next EEPROM byte from the endpoint */
298 eeprom_write_byte((uint8_t*)(uint16_t)(CurrAddress >> 1), FetchNextCommandByte());
299
300 /* Increment the address counter after use */
301 CurrAddress += 2;
302 }
303 }
304
305 /* If in FLASH programming mode, commit the page after writing */
306 if (MemoryType == 'F')
307 {
308 /* Commit the flash page to memory */
309 boot_page_write(PageStartAddress);
310
311 /* Wait until write operation has completed */
312 boot_spm_busy_wait();
313 }
314
315 /* Send response byte back to the host */
316 WriteNextResponseByte('\r');
317 }
318 }
319
320 /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed
321 * to allow reception of the next data packet from the host.
322 *
323 * \return Next received byte from the host in the CDC data OUT endpoint
324 */
325 static uint8_t FetchNextCommandByte(void)
326 {
327 /* Select the OUT endpoint so that the next data byte can be read */
328 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
329
330 /* If OUT endpoint empty, clear it and wait for the next packet from the host */
331 while (!(Endpoint_IsReadWriteAllowed()))
332 {
333 Endpoint_ClearOUT();
334
335 while (!(Endpoint_IsOUTReceived()))
336 {
337 if (USB_DeviceState == DEVICE_STATE_Unattached)
338 return 0;
339 }
340 }
341
342 /* Fetch the next byte from the OUT endpoint */
343 return Endpoint_Read_Byte();
344 }
345
346 /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the
347 * bank when full ready for the next byte in the packet to the host.
348 *
349 * \param[in] Response Next response byte to send to the host
350 */
351 static void WriteNextResponseByte(const uint8_t Response)
352 {
353 /* Select the IN endpoint so that the next data byte can be written */
354 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
355
356 /* If IN endpoint full, clear it and wait util ready for the next packet to the host */
357 if (!(Endpoint_IsReadWriteAllowed()))
358 {
359 Endpoint_ClearIN();
360
361 while (!(Endpoint_IsINReady()))
362 {
363 if (USB_DeviceState == DEVICE_STATE_Unattached)
364 return;
365 }
366 }
367
368 /* Write the next byte to the OUT endpoint */
369 Endpoint_Write_Byte(Response);
370 }
371
372 /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions
373 * and send the appropriate response back to the host.
374 */
375 void CDC_Task(void)
376 {
377 /* Select the OUT endpoint */
378 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
379
380 /* Check if endpoint has a command in it sent from the host */
381 if (Endpoint_IsOUTReceived())
382 {
383 /* Read in the bootloader command (first byte sent from host) */
384 uint8_t Command = FetchNextCommandByte();
385
386 if ((Command == 'L') || (Command == 'P') || (Command == 'T') || (Command == 'E'))
387 {
388 if (Command == 'E')
389 RunBootloader = false;
390 if (Command == 'T')
391 FetchNextCommandByte();
392
393 /* Send confirmation byte back to the host */
394 WriteNextResponseByte('\r');
395 }
396 else if (Command == 't')
397 {
398 /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */
399 WriteNextResponseByte(0x44);
400
401 WriteNextResponseByte(0x00);
402 }
403 else if (Command == 'a')
404 {
405 /* Indicate auto-address increment is supported */
406 WriteNextResponseByte('Y');
407 }
408 else if (Command == 'A')
409 {
410 /* Set the current address to that given by the host */
411 CurrAddress = (FetchNextCommandByte() << 9);
412 CurrAddress |= (FetchNextCommandByte() << 1);
413
414 /* Send confirmation byte back to the host */
415 WriteNextResponseByte('\r');
416 }
417 else if (Command == 'p')
418 {
419 /* Indicate serial programmer back to the host */
420 WriteNextResponseByte('S');
421 }
422 else if (Command == 'S')
423 {
424 /* Write the 7-byte software identifier to the endpoint */
425 for (uint8_t CurrByte = 0; CurrByte < 7; CurrByte++)
426 WriteNextResponseByte(SOFTWARE_IDENTIFIER[CurrByte]);
427 }
428 else if (Command == 'V')
429 {
430 WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR);
431 WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR);
432 }
433 else if (Command == 's')
434 {
435 WriteNextResponseByte(AVR_SIGNATURE_3);
436 WriteNextResponseByte(AVR_SIGNATURE_2);
437 WriteNextResponseByte(AVR_SIGNATURE_1);
438 }
439 else if (Command == 'b')
440 {
441 WriteNextResponseByte('Y');
442
443 /* Send block size to the host */
444 WriteNextResponseByte(SPM_PAGESIZE >> 8);
445 WriteNextResponseByte(SPM_PAGESIZE & 0xFF);
446 }
447 else if (Command == 'e')
448 {
449 /* Clear the application section of flash */
450 for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < BOOT_START_ADDR; CurrFlashAddress++)
451 {
452 boot_page_erase(CurrFlashAddress);
453 boot_spm_busy_wait();
454 boot_page_write(CurrFlashAddress);
455 boot_spm_busy_wait();
456
457 CurrFlashAddress += SPM_PAGESIZE;
458 }
459
460 /* Send confirmation byte back to the host */
461 WriteNextResponseByte('\r');
462 }
463 else if (Command == 'l')
464 {
465 /* Set the lock bits to those given by the host */
466 boot_lock_bits_set(FetchNextCommandByte());
467
468 /* Send confirmation byte back to the host */
469 WriteNextResponseByte('\r');
470 }
471 else if (Command == 'r')
472 {
473 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS));
474 }
475 else if (Command == 'F')
476 {
477 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS));
478 }
479 else if (Command == 'N')
480 {
481 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS));
482 }
483 else if (Command == 'Q')
484 {
485 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS));
486 }
487 else if (Command == 'C')
488 {
489 /* Write the high byte to the current flash page */
490 boot_page_fill(CurrAddress, FetchNextCommandByte());
491
492 /* Send confirmation byte back to the host */
493 WriteNextResponseByte('\r');
494 }
495 else if (Command == 'c')
496 {
497 /* Write the low byte to the current flash page */
498 boot_page_fill(CurrAddress | 1, FetchNextCommandByte());
499
500 /* Increment the address */
501 CurrAddress += 2;
502
503 /* Send confirmation byte back to the host */
504 WriteNextResponseByte('\r');
505 }
506 else if (Command == 'm')
507 {
508 /* Commit the flash page to memory */
509 boot_page_write(CurrAddress);
510
511 /* Wait until write operation has completed */
512 boot_spm_busy_wait();
513
514 /* Send confirmation byte back to the host */
515 WriteNextResponseByte('\r');
516 }
517 else if ((Command == 'B') || (Command == 'g'))
518 {
519 /* Delegate the block write/read to a separate function for clarity */
520 ReadWriteMemoryBlock(Command);
521 }
522 else if (Command == 'R')
523 {
524 #if (FLASHEND > 0xFFFF)
525 uint16_t ProgramWord = pgm_read_word_far(CurrAddress);
526 #else
527 uint16_t ProgramWord = pgm_read_word(CurrAddress);
528 #endif
529
530 WriteNextResponseByte(ProgramWord >> 8);
531 WriteNextResponseByte(ProgramWord & 0xFF);
532 }
533 else if (Command == 'D')
534 {
535 /* Read the byte from the endpoint and write it to the EEPROM */
536 eeprom_write_byte((uint8_t*)(uint16_t)(CurrAddress >> 1), FetchNextCommandByte());
537
538 /* Increment the address after use */
539 CurrAddress += 2;
540
541 /* Send confirmation byte back to the host */
542 WriteNextResponseByte('\r');
543 }
544 else if (Command == 'd')
545 {
546 /* Read the EEPROM byte and write it to the endpoint */
547 WriteNextResponseByte(eeprom_read_byte((uint8_t*)(uint16_t)(CurrAddress >> 1)));
548
549 /* Increment the address after use */
550 CurrAddress += 2;
551 }
552 else if (Command == 27)
553 {
554 /* Escape is sync, ignore */
555 }
556 else
557 {
558 /* Unknown command, return fail code */
559 WriteNextResponseByte('?');
560 }
561
562 /* Select the IN endpoint */
563 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
564
565 /* Remember if the endpoint is completely full before clearing it */
566 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
567
568 /* Send the endpoint data to the host */
569 Endpoint_ClearIN();
570
571 /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */
572 if (IsEndpointFull)
573 {
574 while (!(Endpoint_IsINReady()))
575 {
576 if (USB_DeviceState == DEVICE_STATE_Unattached)
577 return;
578 }
579
580 Endpoint_ClearIN();
581 }
582
583 /* Wait until the data has been sent to the host */
584 while (!(Endpoint_IsINReady()))
585 {
586 if (USB_DeviceState == DEVICE_STATE_Unattached)
587 return;
588 }
589
590 /* Select the OUT endpoint */
591 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
592
593 /* Acknowledge the command from the host */
594 Endpoint_ClearOUT();
595 }
596 }