Added incomplete MIDIToneGenerator project.
[pub/USBasp.git] / Projects / AVRISP-MKII / Lib / ISP / ISPProtocol.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 * ISP Protocol handler, to process V2 Protocol wrapped ISP commands used in Atmel programmer devices.
34 */
35
36 #include "ISPProtocol.h"
37
38 #if defined(ENABLE_ISP_PROTOCOL) || defined(__DOXYGEN__)
39
40 /** Handler for the CMD_ENTER_PROGMODE_ISP command, which attempts to enter programming mode on
41 * the attached device, returning success or failure back to the host.
42 */
43 void ISPProtocol_EnterISPMode(void)
44 {
45 struct
46 {
47 uint8_t TimeoutMS;
48 uint8_t PinStabDelayMS;
49 uint8_t ExecutionDelayMS;
50 uint8_t SynchLoops;
51 uint8_t ByteDelay;
52 uint8_t PollValue;
53 uint8_t PollIndex;
54 uint8_t EnterProgBytes[4];
55 } Enter_ISP_Params;
56
57 Endpoint_Read_Stream_LE(&Enter_ISP_Params, sizeof(Enter_ISP_Params), NO_STREAM_CALLBACK);
58
59 Endpoint_ClearOUT();
60 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
61
62 uint8_t ResponseStatus = STATUS_CMD_FAILED;
63
64 CurrentAddress = 0;
65
66 /* Set up the synchronous USART to generate the recovery clock on XCK pin */
67 UBRR1 = (F_CPU / 500000UL);
68 UCSR1B = (1 << TXEN1);
69 UCSR1C = (1 << UMSEL10) | (1 << UPM11) | (1 << USBS1) | (1 << UCSZ11) | (1 << UCSZ10) | (1 << UCPOL1);
70 DDRD |= (1 << 5);
71
72 /* Perform execution delay, initialize SPI bus */
73 ISPProtocol_DelayMS(Enter_ISP_Params.ExecutionDelayMS);
74 SPI_Init(ISPTarget_GetSPIPrescalerMask() | SPI_SCK_LEAD_RISING | SPI_SAMPLE_LEADING | SPI_MODE_MASTER);
75
76 /* Continuously attempt to synchronize with the target until either the number of attempts specified
77 * by the host has exceeded, or the the device sends back the expected response values */
78 while (Enter_ISP_Params.SynchLoops-- && (ResponseStatus == STATUS_CMD_FAILED) && TimeoutMSRemaining)
79 {
80 uint8_t ResponseBytes[4];
81
82 ISPTarget_ChangeTargetResetLine(true);
83 ISPProtocol_DelayMS(Enter_ISP_Params.PinStabDelayMS);
84
85 for (uint8_t RByte = 0; RByte < sizeof(ResponseBytes); RByte++)
86 {
87 ISPProtocol_DelayMS(Enter_ISP_Params.ByteDelay);
88 ResponseBytes[RByte] = SPI_TransferByte(Enter_ISP_Params.EnterProgBytes[RByte]);
89 }
90
91 /* Check if polling disabled, or if the polled value matches the expected value */
92 if (!(Enter_ISP_Params.PollIndex) || (ResponseBytes[Enter_ISP_Params.PollIndex - 1] == Enter_ISP_Params.PollValue))
93 {
94 ResponseStatus = STATUS_CMD_OK;
95 }
96 else
97 {
98 ISPTarget_ChangeTargetResetLine(false);
99 ISPProtocol_DelayMS(Enter_ISP_Params.PinStabDelayMS);
100 }
101 }
102
103 Endpoint_Write_Byte(CMD_ENTER_PROGMODE_ISP);
104 Endpoint_Write_Byte(ResponseStatus);
105 Endpoint_ClearIN();
106 }
107
108 /** Handler for the CMD_LEAVE_ISP command, which releases the target from programming mode. */
109 void ISPProtocol_LeaveISPMode(void)
110 {
111 struct
112 {
113 uint8_t PreDelayMS;
114 uint8_t PostDelayMS;
115 } Leave_ISP_Params;
116
117 Endpoint_Read_Stream_LE(&Leave_ISP_Params, sizeof(Leave_ISP_Params), NO_STREAM_CALLBACK);
118
119 Endpoint_ClearOUT();
120 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
121
122 /* Perform pre-exit delay, release the target /RESET, disable the SPI bus and perform the post-exit delay */
123 ISPProtocol_DelayMS(Leave_ISP_Params.PreDelayMS);
124 ISPTarget_ChangeTargetResetLine(false);
125 SPI_ShutDown();
126 ISPProtocol_DelayMS(Leave_ISP_Params.PostDelayMS);
127
128 /* Turn off the synchronous USART to terminate the recovery clock on XCK pin */
129 UBRR1 = (F_CPU / 500000UL);
130 UCSR1B = (1 << TXEN1);
131 UCSR1C = (1 << UMSEL10) | (1 << UPM11) | (1 << USBS1) | (1 << UCSZ11) | (1 << UCSZ10) | (1 << UCPOL1);
132 DDRD &= ~(1 << 5);
133
134 Endpoint_Write_Byte(CMD_LEAVE_PROGMODE_ISP);
135 Endpoint_Write_Byte(STATUS_CMD_OK);
136 Endpoint_ClearIN();
137 }
138
139 /** Handler for the CMD_PROGRAM_FLASH_ISP and CMD_PROGRAM_EEPROM_ISP commands, writing out bytes,
140 * words or pages of data to the attached device.
141 *
142 * \param[in] V2Command Issued V2 Protocol command byte from the host
143 */
144 void ISPProtocol_ProgramMemory(uint8_t V2Command)
145 {
146 struct
147 {
148 uint16_t BytesToWrite;
149 uint8_t ProgrammingMode;
150 uint8_t DelayMS;
151 uint8_t ProgrammingCommands[3];
152 uint8_t PollValue1;
153 uint8_t PollValue2;
154 uint8_t ProgData[256]; // Note, the Jungo driver has a very short ACK timeout period, need to buffer the
155 } Write_Memory_Params; // whole page and ACK the packet as fast as possible to prevent it from aborting
156
157 Endpoint_Read_Stream_LE(&Write_Memory_Params, (sizeof(Write_Memory_Params) -
158 sizeof(Write_Memory_Params.ProgData)), NO_STREAM_CALLBACK);
159
160
161 Write_Memory_Params.BytesToWrite = SwapEndian_16(Write_Memory_Params.BytesToWrite);
162
163 if (Write_Memory_Params.BytesToWrite > sizeof(Write_Memory_Params.ProgData))
164 {
165 Endpoint_ClearOUT();
166 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
167
168 Endpoint_Write_Byte(V2Command);
169 Endpoint_Write_Byte(STATUS_CMD_FAILED);
170 Endpoint_ClearIN();
171 return;
172 }
173
174 Endpoint_Read_Stream_LE(&Write_Memory_Params.ProgData, Write_Memory_Params.BytesToWrite, NO_STREAM_CALLBACK);
175
176 Endpoint_ClearOUT();
177 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
178
179 uint8_t ProgrammingStatus = STATUS_CMD_OK;
180 uint16_t PollAddress = 0;
181 uint8_t PollValue = (V2Command == CMD_PROGRAM_FLASH_ISP) ? Write_Memory_Params.PollValue1 :
182 Write_Memory_Params.PollValue2;
183 uint8_t* NextWriteByte = Write_Memory_Params.ProgData;
184
185 /* Check to see if the host has issued a SET ADDRESS command and we haven't sent a
186 * LOAD EXTENDED ADDRESS command (if needed, used when operating beyond the 128KB
187 * FLASH barrier) */
188 if (MustSetAddress)
189 {
190 if (CurrentAddress & (1UL << 31))
191 ISPTarget_LoadExtendedAddress();
192
193 MustSetAddress = false;
194 }
195
196 /* Check the programming mode desired by the host, either Paged or Word memory writes */
197 if (Write_Memory_Params.ProgrammingMode & PROG_MODE_PAGED_WRITES_MASK)
198 {
199 uint16_t StartAddress = (CurrentAddress & 0xFFFF);
200
201 /* Paged mode memory programming */
202 for (uint16_t CurrentByte = 0; CurrentByte < Write_Memory_Params.BytesToWrite; CurrentByte++)
203 {
204 bool IsOddByte = (CurrentByte & 0x01);
205 uint8_t ByteToWrite = *(NextWriteByte++);
206
207 SPI_SendByte(Write_Memory_Params.ProgrammingCommands[0]);
208 SPI_SendByte(CurrentAddress >> 8);
209 SPI_SendByte(CurrentAddress & 0xFF);
210 SPI_SendByte(ByteToWrite);
211
212 /* AVR FLASH addressing requires us to modify the write command based on if we are writing a high
213 * or low byte at the current word address */
214 if (V2Command == CMD_PROGRAM_FLASH_ISP)
215 Write_Memory_Params.ProgrammingCommands[0] ^= READ_WRITE_HIGH_BYTE_MASK;
216
217 /* Check to see the write completion method, to see if we have a valid polling address */
218 if (!(PollAddress) && (ByteToWrite != PollValue))
219 {
220 if (IsOddByte && (V2Command == CMD_PROGRAM_FLASH_ISP))
221 Write_Memory_Params.ProgrammingCommands[2] |= READ_WRITE_HIGH_BYTE_MASK;
222
223 PollAddress = (CurrentAddress & 0xFFFF);
224 }
225
226 if (IsOddByte || (V2Command == CMD_PROGRAM_EEPROM_ISP))
227 CurrentAddress++;
228 }
229
230 /* If the current page must be committed, send the PROGRAM PAGE command to the target */
231 if (Write_Memory_Params.ProgrammingMode & PROG_MODE_COMMIT_PAGE_MASK)
232 {
233 SPI_SendByte(Write_Memory_Params.ProgrammingCommands[1]);
234 SPI_SendByte(StartAddress >> 8);
235 SPI_SendByte(StartAddress & 0xFF);
236 SPI_SendByte(0x00);
237
238 /* Check if polling is possible, if not switch to timed delay mode */
239 if (!(PollAddress))
240 {
241 Write_Memory_Params.ProgrammingMode &= ~PROG_MODE_PAGED_VALUE_MASK;
242 Write_Memory_Params.ProgrammingMode |= PROG_MODE_PAGED_TIMEDELAY_MASK;
243 }
244
245 ProgrammingStatus = ISPTarget_WaitForProgComplete(Write_Memory_Params.ProgrammingMode, PollAddress, PollValue,
246 Write_Memory_Params.DelayMS, Write_Memory_Params.ProgrammingCommands[2]);
247 }
248 }
249 else
250 {
251 /* Word/byte mode memory programming */
252 for (uint16_t CurrentByte = 0; CurrentByte < Write_Memory_Params.BytesToWrite; CurrentByte++)
253 {
254 bool IsOddByte = (CurrentByte & 0x01);
255 uint8_t ByteToWrite = *(NextWriteByte++);
256
257 SPI_SendByte(Write_Memory_Params.ProgrammingCommands[0]);
258 SPI_SendByte(CurrentAddress >> 8);
259 SPI_SendByte(CurrentAddress & 0xFF);
260 SPI_SendByte(ByteToWrite);
261
262 /* AVR FLASH addressing requires us to modify the write command based on if we are writing a high
263 * or low byte at the current word address */
264 if (V2Command == CMD_PROGRAM_FLASH_ISP)
265 Write_Memory_Params.ProgrammingCommands[0] ^= READ_WRITE_HIGH_BYTE_MASK;
266
267 if (ByteToWrite != PollValue)
268 {
269 if (IsOddByte && (V2Command == CMD_PROGRAM_FLASH_ISP))
270 Write_Memory_Params.ProgrammingCommands[2] |= READ_WRITE_HIGH_BYTE_MASK;
271
272 PollAddress = (CurrentAddress & 0xFFFF);
273 }
274
275 if (IsOddByte || (V2Command == CMD_PROGRAM_EEPROM_ISP))
276 CurrentAddress++;
277
278 ProgrammingStatus = ISPTarget_WaitForProgComplete(Write_Memory_Params.ProgrammingMode, PollAddress, PollValue,
279 Write_Memory_Params.DelayMS, Write_Memory_Params.ProgrammingCommands[2]);
280
281 if (ProgrammingStatus != STATUS_CMD_OK)
282 break;
283 }
284 }
285
286 Endpoint_Write_Byte(V2Command);
287 Endpoint_Write_Byte(ProgrammingStatus);
288 Endpoint_ClearIN();
289 }
290
291 /** Handler for the CMD_READ_FLASH_ISP and CMD_READ_EEPROM_ISP commands, reading in bytes,
292 * words or pages of data from the attached device.
293 *
294 * \param[in] V2Command Issued V2 Protocol command byte from the host
295 */
296 void ISPProtocol_ReadMemory(uint8_t V2Command)
297 {
298 struct
299 {
300 uint16_t BytesToRead;
301 uint8_t ReadMemoryCommand;
302 } Read_Memory_Params;
303
304 Endpoint_Read_Stream_LE(&Read_Memory_Params, sizeof(Read_Memory_Params), NO_STREAM_CALLBACK);
305 Read_Memory_Params.BytesToRead = SwapEndian_16(Read_Memory_Params.BytesToRead);
306
307 Endpoint_ClearOUT();
308 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
309
310 Endpoint_Write_Byte(V2Command);
311 Endpoint_Write_Byte(STATUS_CMD_OK);
312
313 /* Check to see if the host has issued a SET ADDRESS command and we haven't sent a
314 * LOAD EXTENDED ADDRESS command (if needed, used when operating beyond the 128KB
315 * FLASH barrier) */
316 if (MustSetAddress)
317 {
318 if (CurrentAddress & (1UL << 31))
319 ISPTarget_LoadExtendedAddress();
320
321 MustSetAddress = false;
322 }
323
324 /* Read each byte from the device and write them to the packet for the host */
325 for (uint16_t CurrentByte = 0; CurrentByte < Read_Memory_Params.BytesToRead; CurrentByte++)
326 {
327 /* Read the next byte from the desired memory space in the device */
328 SPI_SendByte(Read_Memory_Params.ReadMemoryCommand);
329 SPI_SendByte(CurrentAddress >> 8);
330 SPI_SendByte(CurrentAddress & 0xFF);
331 Endpoint_Write_Byte(SPI_ReceiveByte());
332
333 /* Check if the endpoint bank is currently full, if so send the packet */
334 if (!(Endpoint_IsReadWriteAllowed()))
335 {
336 Endpoint_ClearIN();
337 Endpoint_WaitUntilReady();
338 }
339
340 /* AVR FLASH addressing requires us to modify the read command based on if we are reading a high
341 * or low byte at the current word address */
342 if (V2Command == CMD_READ_FLASH_ISP)
343 Read_Memory_Params.ReadMemoryCommand ^= READ_WRITE_HIGH_BYTE_MASK;
344
345 /* Only increment the current address if we have read both bytes in the current word when in FLASH
346 * read mode, or for each byte when in EEPROM read mode */
347 if (((CurrentByte & 0x01) && (V2Command == CMD_READ_FLASH_ISP)) || (V2Command == CMD_READ_EEPROM_ISP))
348 CurrentAddress++;
349 }
350
351 Endpoint_Write_Byte(STATUS_CMD_OK);
352
353 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
354 Endpoint_ClearIN();
355
356 /* Ensure last packet is a short packet to terminate the transfer */
357 if (IsEndpointFull)
358 {
359 Endpoint_WaitUntilReady();
360 Endpoint_ClearIN();
361 Endpoint_WaitUntilReady();
362 }
363 }
364
365 /** Handler for the CMD_CHI_ERASE_ISP command, clearing the target's FLASH memory. */
366 void ISPProtocol_ChipErase(void)
367 {
368 struct
369 {
370 uint8_t EraseDelayMS;
371 uint8_t PollMethod;
372 uint8_t EraseCommandBytes[4];
373 } Erase_Chip_Params;
374
375 Endpoint_Read_Stream_LE(&Erase_Chip_Params, sizeof(Erase_Chip_Params), NO_STREAM_CALLBACK);
376
377 Endpoint_ClearOUT();
378 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
379
380 uint8_t ResponseStatus = STATUS_CMD_OK;
381
382 /* Send the chip erase commands as given by the host to the device */
383 for (uint8_t SByte = 0; SByte < sizeof(Erase_Chip_Params.EraseCommandBytes); SByte++)
384 SPI_SendByte(Erase_Chip_Params.EraseCommandBytes[SByte]);
385
386 /* Use appropriate command completion check as given by the host (delay or busy polling) */
387 if (!(Erase_Chip_Params.PollMethod))
388 ISPProtocol_DelayMS(Erase_Chip_Params.EraseDelayMS);
389 else
390 ResponseStatus = ISPTarget_WaitWhileTargetBusy();
391
392 Endpoint_Write_Byte(CMD_CHIP_ERASE_ISP);
393 Endpoint_Write_Byte(ResponseStatus);
394 Endpoint_ClearIN();
395 }
396
397 /** Handler for the CMD_READ_FUSE_ISP, CMD_READ_LOCK_ISP, CMD_READ_SIGNATURE_ISP and CMD_READ_OSCCAL commands,
398 * reading the requested configuration byte from the device.
399 *
400 * \param[in] V2Command Issued V2 Protocol command byte from the host
401 */
402 void ISPProtocol_ReadFuseLockSigOSCCAL(uint8_t V2Command)
403 {
404 struct
405 {
406 uint8_t RetByte;
407 uint8_t ReadCommandBytes[4];
408 } Read_FuseLockSigOSCCAL_Params;
409
410 Endpoint_Read_Stream_LE(&Read_FuseLockSigOSCCAL_Params, sizeof(Read_FuseLockSigOSCCAL_Params), NO_STREAM_CALLBACK);
411
412 Endpoint_ClearOUT();
413 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
414
415 uint8_t ResponseBytes[4];
416
417 /* Send the Fuse or Lock byte read commands as given by the host to the device, store response */
418 for (uint8_t RByte = 0; RByte < sizeof(ResponseBytes); RByte++)
419 ResponseBytes[RByte] = SPI_TransferByte(Read_FuseLockSigOSCCAL_Params.ReadCommandBytes[RByte]);
420
421 Endpoint_Write_Byte(V2Command);
422 Endpoint_Write_Byte(STATUS_CMD_OK);
423 Endpoint_Write_Byte(ResponseBytes[Read_FuseLockSigOSCCAL_Params.RetByte - 1]);
424 Endpoint_Write_Byte(STATUS_CMD_OK);
425 Endpoint_ClearIN();
426 }
427
428 /** Handler for the CMD_WRITE_FUSE_ISP and CMD_WRITE_LOCK_ISP commands, writing the requested configuration
429 * byte to the device.
430 *
431 * \param[in] V2Command Issued V2 Protocol command byte from the host
432 */
433 void ISPProtocol_WriteFuseLock(uint8_t V2Command)
434 {
435 struct
436 {
437 uint8_t WriteCommandBytes[4];
438 } Write_FuseLockSig_Params;
439
440 Endpoint_Read_Stream_LE(&Write_FuseLockSig_Params, sizeof(Write_FuseLockSig_Params), NO_STREAM_CALLBACK);
441
442 Endpoint_ClearOUT();
443 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
444
445 /* Send the Fuse or Lock byte program commands as given by the host to the device */
446 for (uint8_t SByte = 0; SByte < sizeof(Write_FuseLockSig_Params.WriteCommandBytes); SByte++)
447 SPI_SendByte(Write_FuseLockSig_Params.WriteCommandBytes[SByte]);
448
449 Endpoint_Write_Byte(V2Command);
450 Endpoint_Write_Byte(STATUS_CMD_OK);
451 Endpoint_Write_Byte(STATUS_CMD_OK);
452 Endpoint_ClearIN();
453 }
454
455 /** Handler for the CMD_SPI_MULTI command, writing and reading arbitrary SPI data to and from the attached device. */
456 void ISPProtocol_SPIMulti(void)
457 {
458 struct
459 {
460 uint8_t TxBytes;
461 uint8_t RxBytes;
462 uint8_t RxStartAddr;
463 uint8_t TxData[255];
464 } SPI_Multi_Params;
465
466 Endpoint_Read_Stream_LE(&SPI_Multi_Params, (sizeof(SPI_Multi_Params) - sizeof(SPI_Multi_Params.TxData)), NO_STREAM_CALLBACK);
467 Endpoint_Read_Stream_LE(&SPI_Multi_Params.TxData, SPI_Multi_Params.TxBytes, NO_STREAM_CALLBACK);
468
469 Endpoint_ClearOUT();
470 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
471
472 Endpoint_Write_Byte(CMD_SPI_MULTI);
473 Endpoint_Write_Byte(STATUS_CMD_OK);
474
475 uint8_t CurrTxPos = 0;
476 uint8_t CurrRxPos = 0;
477
478 /* Write out bytes to transmit until the start of the bytes to receive is met */
479 while (CurrTxPos < SPI_Multi_Params.RxStartAddr)
480 {
481 if (CurrTxPos < SPI_Multi_Params.TxBytes)
482 SPI_SendByte(SPI_Multi_Params.TxData[CurrTxPos]);
483 else
484 SPI_SendByte(0);
485
486 CurrTxPos++;
487 }
488
489 /* Transmit remaining bytes with padding as needed, read in response bytes */
490 while (CurrRxPos < SPI_Multi_Params.RxBytes)
491 {
492 if (CurrTxPos < SPI_Multi_Params.TxBytes)
493 Endpoint_Write_Byte(SPI_TransferByte(SPI_Multi_Params.TxData[CurrTxPos++]));
494 else
495 Endpoint_Write_Byte(SPI_ReceiveByte());
496
497 /* Check to see if we have filled the endpoint bank and need to send the packet */
498 if (!(Endpoint_IsReadWriteAllowed()))
499 {
500 Endpoint_ClearIN();
501 Endpoint_WaitUntilReady();
502 }
503
504 CurrRxPos++;
505 }
506
507 Endpoint_Write_Byte(STATUS_CMD_OK);
508
509 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
510 Endpoint_ClearIN();
511
512 /* Ensure last packet is a short packet to terminate the transfer */
513 if (IsEndpointFull)
514 {
515 Endpoint_WaitUntilReady();
516 Endpoint_ClearIN();
517 Endpoint_WaitUntilReady();
518 }
519 }
520
521 /** Blocking delay for a given number of milliseconds.
522 *
523 * \param[in] DelayMS Number of milliseconds to delay for
524 */
525 void ISPProtocol_DelayMS(uint8_t DelayMS)
526 {
527 while (DelayMS-- && TimeoutMSRemaining)
528 {
529 if (TimeoutMSRemaining)
530 TimeoutMSRemaining--;
531
532 _delay_ms(1);
533 }
534 }
535
536 #endif