3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
33 * Main source file for the CDC class bootloader. This file contains the complete bootloader logic.
36 #define INCLUDE_FROM_BOOTLOADERCDC_C
37 #include "BootloaderCDC.h"
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.
46 CDC_Line_Coding_t LineCoding
= { BaudRateBPS
: 9600,
47 CharFormat
: OneStopBit
,
48 ParityType
: Parity_None
,
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
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.
61 bool RunBootloader
= true;
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.
70 /* Disable watchdog if enabled by bootloader/fuses */
71 MCUSR
&= ~(1 << WDRF
);
74 /* Disable Clock Division */
75 SetSystemClockPrescaler(0);
77 /* Relocate the interrupt vector table to the bootloader section */
81 /* Initialize USB Subsystem */
90 Endpoint_SelectEndpoint(CDC_TX_EPNUM
);
92 /* Wait until any pending transmissions have completed before shutting down */
93 while (!(Endpoint_ReadWriteAllowed()));
95 /* Shut down the USB subsystem */
98 /* Relocate the interrupt vector table back to the application section */
102 /* Reset any used hardware ports back to their defaults */
111 /* Re-enable RWW section */
114 /* Start the user application */
115 AppPtr_t AppStartPtr
= (AppPtr_t
)0x0000;
119 /** Event handler for the USB_Disconnect event. This indicates that the bootloader should exit and the user
120 * application started.
122 EVENT_HANDLER(USB_Disconnect
)
124 /* Upon disconnection, run user application */
125 RunBootloader
= false;
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.
131 EVENT_HANDLER(USB_ConfigurationChanged
)
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
);
138 Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
,
139 ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
,
140 ENDPOINT_BANK_SINGLE
);
142 Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
,
143 ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
,
144 ENDPOINT_BANK_SINGLE
);
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.
151 EVENT_HANDLER(USB_UnhandledControlPacket
)
153 uint8_t* LineCodingData
= (uint8_t*)&LineCoding
;
155 Endpoint_Discard_Word();
157 /* Process CDC specific control requests */
160 case REQ_GetLineEncoding
:
161 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
163 Endpoint_ClearSetupReceived();
165 for (uint8_t i
= 0; i
< sizeof(LineCoding
); i
++)
166 Endpoint_Write_Byte(*(LineCodingData
++));
168 Endpoint_ClearSetupIN();
170 while (!(Endpoint_IsSetupOUTReceived()));
171 Endpoint_ClearSetupOUT();
175 case REQ_SetLineEncoding
:
176 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
178 Endpoint_ClearSetupReceived();
180 while (!(Endpoint_IsSetupOUTReceived()));
182 for (uint8_t i
= 0; i
< sizeof(LineCoding
); i
++)
183 *(LineCodingData
++) = Endpoint_Read_Byte();
185 Endpoint_ClearSetupOUT();
187 while (!(Endpoint_IsSetupINReady()));
188 Endpoint_ClearSetupIN();
192 case REQ_SetControlLineState
:
193 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
195 Endpoint_ClearSetupReceived();
197 while (!(Endpoint_IsSetupINReady()));
198 Endpoint_ClearSetupIN();
205 /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending
206 * on the AVR910 protocol command issued.
208 * \param Command Single character AVR910 protocol command indicating what memory operation to perform
210 static void ProgramReadWriteMemoryBlock(const uint8_t Command
)
215 bool HighByte
= false;
218 BlockSize
= (FetchNextCommandByte() << 8);
219 BlockSize
|= FetchNextCommandByte();
221 MemoryType
= FetchNextCommandByte();
223 if ((MemoryType
== 'E') || (MemoryType
== 'F'))
225 /* Check if command is to read memory */
228 /* Re-enable RWW section */
233 if (MemoryType
== 'E')
235 /* Read the next EEPROM byte into the endpoint */
236 WriteNextResponseByte(eeprom_read_byte((uint8_t*)CurrAddress
));
238 /* Increment the address counter after use */
243 /* Read the next FLASH byte from the current FLASH page */
245 WriteNextResponseByte(pgm_read_byte_far(((uint32_t)CurrAddress
<< 1) + HighByte
));
247 WriteNextResponseByte(pgm_read_byte((CurrAddress
<< 1) + HighByte
));
250 /* If both bytes in current word have been read, increment the address counter */
260 uint32_t PageStartAddress
= ((uint32_t)CurrAddress
<< 1);
262 if (MemoryType
== 'F')
264 boot_page_erase(PageStartAddress
);
265 boot_spm_busy_wait();
270 if (MemoryType
== 'E')
272 /* Write the next EEPROM byte from the endpoint */
273 eeprom_write_byte((uint8_t*)CurrAddress
, FetchNextCommandByte());
275 /* Increment the address counter after use */
280 /* If both bytes in current word have been written, increment the address counter */
283 /* Write the next FLASH word to the current FLASH page */
284 boot_page_fill(((uint32_t)CurrAddress
<< 1), ((FetchNextCommandByte() << 8) | LowByte
));
288 /* Increment the address counter after use */
293 LowByte
= FetchNextCommandByte();
300 /* If in FLASH programming mode, commit the page after writing */
301 if (MemoryType
== 'F')
303 /* Commit the flash page to memory */
304 boot_page_write(PageStartAddress
);
306 /* Wait until write operation has completed */
307 boot_spm_busy_wait();
310 /* Send response byte back to the host */
311 WriteNextResponseByte('\r');
316 /* Send error byte back to the host */
317 WriteNextResponseByte('?');
321 /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed
322 * to allow reception of the next data packet from the host.
324 * \return Next received byte from the host in the CDC data OUT endpoint
326 static uint8_t FetchNextCommandByte(void)
328 /* Select the OUT endpoint so that the next data byte can be read */
329 Endpoint_SelectEndpoint(CDC_RX_EPNUM
);
331 /* If OUT endpoint empty, clear it and wait for the next packet from the host */
332 if (!(Endpoint_ReadWriteAllowed()))
334 Endpoint_ClearCurrentBank();
335 while (!(Endpoint_ReadWriteAllowed()));
338 /* Fetch the next byte from the OUT endpoint */
339 return Endpoint_Read_Byte();
342 /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the
343 * bank when full ready for the next byte in the packet to the host.
345 * \param Response Next response byte to send to the host
347 static void WriteNextResponseByte(const uint8_t Response
)
349 /* Select the IN endpoint so that the next data byte can be written */
350 Endpoint_SelectEndpoint(CDC_TX_EPNUM
);
352 /* If OUT endpoint empty, clear it and wait for the next packet from the host */
353 if (!(Endpoint_ReadWriteAllowed()))
355 Endpoint_ClearCurrentBank();
356 while (!(Endpoint_ReadWriteAllowed()));
359 /* Write the next byte to the OUT endpoint */
360 Endpoint_Write_Byte(Response
);
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.
368 /* Select the OUT endpoint */
369 Endpoint_SelectEndpoint(CDC_RX_EPNUM
);
371 /* Check if endpoint has a command in it sent from the host */
372 if (Endpoint_ReadWriteAllowed())
374 /* Read in the bootloader command (first byte sent from host) */
375 uint8_t Command
= FetchNextCommandByte();
377 if ((Command
== 'L') || (Command
== 'P') || (Command
== 'T') || (Command
== 'E'))
380 RunBootloader
= false;
382 FetchNextCommandByte();
384 /* Send confirmation byte back to the host */
385 WriteNextResponseByte('\r');
387 else if (Command
== 't')
389 /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */
390 WriteNextResponseByte(0x44);
392 WriteNextResponseByte(0x00);
394 else if (Command
== 'a')
396 /* Indicate auto-address increment is supported */
397 WriteNextResponseByte('Y');
399 else if (Command
== 'A')
401 /* Set the current address to that given by the host */
402 CurrAddress
= (FetchNextCommandByte() << 8);
403 CurrAddress
|= FetchNextCommandByte();
405 /* Send confirmation byte back to the host */
406 WriteNextResponseByte('\r');
408 else if (Command
== 'p')
410 /* Indicate serial programmer back to the host */
411 WriteNextResponseByte('S');
413 else if (Command
== 'S')
415 /* Write the 7-byte software identifier to the endpoint */
416 for (uint8_t CurrByte
= 0; CurrByte
< 7; CurrByte
++)
417 WriteNextResponseByte(SOFTWARE_IDENTIFIER
[CurrByte
]);
419 else if (Command
== 'V')
421 WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR
);
422 WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR
);
424 else if (Command
== 's')
426 WriteNextResponseByte(boot_signature_byte_get(4));
427 WriteNextResponseByte(boot_signature_byte_get(2));
428 WriteNextResponseByte(boot_signature_byte_get(0));
430 else if (Command
== 'b')
432 WriteNextResponseByte('Y');
434 /* Send block size to the host */
435 WriteNextResponseByte(SPM_PAGESIZE
>> 8);
436 WriteNextResponseByte(SPM_PAGESIZE
& 0xFF);
438 else if (Command
== 'e')
440 /* Clear the application section of flash */
441 for (uint32_t CurrFlashAddress
= 0; CurrFlashAddress
< BOOT_START_ADDR
; CurrFlashAddress
++)
443 boot_page_erase(CurrFlashAddress
);
444 boot_spm_busy_wait();
445 boot_page_write(CurrFlashAddress
);
446 boot_spm_busy_wait();
448 CurrFlashAddress
+= SPM_PAGESIZE
;
451 /* Send confirmation byte back to the host */
452 WriteNextResponseByte('\r');
454 else if (Command
== 'l')
456 /* Set the lock bits to those given by the host */
457 boot_lock_bits_set(FetchNextCommandByte());
459 /* Send confirmation byte back to the host */
460 WriteNextResponseByte('\r');
462 else if (Command
== 'r')
464 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS
));
466 else if (Command
== 'F')
468 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS
));
470 else if (Command
== 'N')
472 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS
));
474 else if (Command
== 'Q')
476 WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS
));
478 else if ((Command
== 'C') || (Command
== 'c'))
482 /* Increment the address if the second byte is being written */
486 /* Write the high byte to the current flash page */
487 boot_page_fill(((uint32_t)CurrAddress
<< 1), FetchNextCommandByte());
489 /* Send confirmation byte back to the host */
490 WriteNextResponseByte('\r');
492 else if (Command
== 'm')
494 /* Commit the flash page to memory */
495 boot_page_write((uint32_t)CurrAddress
<< 1);
497 /* Wait until write operation has completed */
498 boot_spm_busy_wait();
500 /* Send confirmation byte back to the host */
501 WriteNextResponseByte('\r');
503 else if ((Command
== 'B') || (Command
== 'g'))
505 /* Delegate the block write/read to a seperate function for clarity */
506 ProgramReadWriteMemoryBlock(Command
);
508 else if (Command
== 'R')
511 uint16_t ProgramWord
= pgm_read_word_far(((uint32_t)CurrAddress
<< 1));
513 uint16_t ProgramWord
= pgm_read_word(CurrAddress
<< 1);
516 WriteNextResponseByte(ProgramWord
>> 8);
517 WriteNextResponseByte(ProgramWord
& 0xFF);
519 else if (Command
== 'D')
521 /* Read the byte from the endpoint and write it to the EEPROM */
522 eeprom_write_byte((uint8_t*)CurrAddress
, FetchNextCommandByte());
524 /* Increment the address after use */
527 /* Send confirmation byte back to the host */
528 WriteNextResponseByte('\r');
530 else if (Command
== 'd')
532 /* Read the EEPROM byte and write it to the endpoint */
533 WriteNextResponseByte(eeprom_read_byte((uint8_t*)CurrAddress
));
535 /* Increment the address after use */
538 else if (Command
== 27)
540 /* Escape is sync, ignore */
544 /* Unknown command, return fail code */
545 WriteNextResponseByte('?');
548 /* Select the IN endpoint */
549 Endpoint_SelectEndpoint(CDC_TX_EPNUM
);
551 /* Remember if the endpoint is completely full before clearing it */
552 bool IsEndpointFull
= !(Endpoint_ReadWriteAllowed());
554 /* Send the endpoint data to the host */
555 Endpoint_ClearCurrentBank();
557 /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */
560 while (!(Endpoint_ReadWriteAllowed()));
561 Endpoint_ClearCurrentBank();
564 /* Select the OUT endpoint */
565 Endpoint_SelectEndpoint(CDC_RX_EPNUM
);
567 /* Acknowledge the command from the host */
568 Endpoint_ClearCurrentBank();