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