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