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