Add missing SVN eol-style properties to source files to prevent mixed end-of-line...
[pub/USBasp.git] / Projects / AVRISP-MKII / Lib / ISP / ISPProtocol.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2011.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2011 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), NULL);
58
59 Endpoint_ClearOUT();
60 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
61 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
62
63 uint8_t ResponseStatus = STATUS_CMD_FAILED;
64
65 CurrentAddress = 0;
66
67 /* Perform execution delay, initialize SPI bus */
68 ISPProtocol_DelayMS(Enter_ISP_Params.ExecutionDelayMS);
69 ISPTarget_EnableTargetISP();
70
71 ISPTarget_ChangeTargetResetLine(true);
72
73 /* Continuously attempt to synchronize with the target until either the number of attempts specified
74 * by the host has exceeded, or the the device sends back the expected response values */
75 while (Enter_ISP_Params.SynchLoops-- && (ResponseStatus != STATUS_CMD_OK) && !(TimeoutExpired))
76 {
77 uint8_t ResponseBytes[4];
78
79 for (uint8_t RByte = 0; RByte < sizeof(ResponseBytes); RByte++)
80 {
81 ISPProtocol_DelayMS(Enter_ISP_Params.ByteDelay);
82 ResponseBytes[RByte] = ISPTarget_TransferByte(Enter_ISP_Params.EnterProgBytes[RByte]);
83 }
84
85 /* Check if polling disabled, or if the polled value matches the expected value */
86 if (!(Enter_ISP_Params.PollIndex) || (ResponseBytes[Enter_ISP_Params.PollIndex - 1] == Enter_ISP_Params.PollValue))
87 {
88 ResponseStatus = STATUS_CMD_OK;
89 }
90 else
91 {
92 ISPTarget_ChangeTargetResetLine(false);
93 ISPProtocol_DelayMS(Enter_ISP_Params.PinStabDelayMS);
94 ISPTarget_ChangeTargetResetLine(true);
95 }
96 }
97
98 Endpoint_Write_8(CMD_ENTER_PROGMODE_ISP);
99 Endpoint_Write_8(ResponseStatus);
100 Endpoint_ClearIN();
101 }
102
103 /** Handler for the CMD_LEAVE_ISP command, which releases the target from programming mode. */
104 void ISPProtocol_LeaveISPMode(void)
105 {
106 struct
107 {
108 uint8_t PreDelayMS;
109 uint8_t PostDelayMS;
110 } Leave_ISP_Params;
111
112 Endpoint_Read_Stream_LE(&Leave_ISP_Params, sizeof(Leave_ISP_Params), NULL);
113
114 Endpoint_ClearOUT();
115 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
116 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
117
118 /* Perform pre-exit delay, release the target /RESET, disable the SPI bus and perform the post-exit delay */
119 ISPProtocol_DelayMS(Leave_ISP_Params.PreDelayMS);
120 ISPTarget_ChangeTargetResetLine(false);
121 ISPTarget_DisableTargetISP();
122 ISPProtocol_DelayMS(Leave_ISP_Params.PostDelayMS);
123
124 Endpoint_Write_8(CMD_LEAVE_PROGMODE_ISP);
125 Endpoint_Write_8(STATUS_CMD_OK);
126 Endpoint_ClearIN();
127 }
128
129 /** Handler for the CMD_PROGRAM_FLASH_ISP and CMD_PROGRAM_EEPROM_ISP commands, writing out bytes,
130 * words or pages of data to the attached device.
131 *
132 * \param[in] V2Command Issued V2 Protocol command byte from the host
133 */
134 void ISPProtocol_ProgramMemory(uint8_t V2Command)
135 {
136 struct
137 {
138 uint16_t BytesToWrite;
139 uint8_t ProgrammingMode;
140 uint8_t DelayMS;
141 uint8_t ProgrammingCommands[3];
142 uint8_t PollValue1;
143 uint8_t PollValue2;
144 uint8_t ProgData[256]; // Note, the Jungo driver has a very short ACK timeout period, need to buffer the
145 } Write_Memory_Params; // whole page and ACK the packet as fast as possible to prevent it from aborting
146
147 Endpoint_Read_Stream_LE(&Write_Memory_Params, (sizeof(Write_Memory_Params) -
148 sizeof(Write_Memory_Params.ProgData)), NULL);
149 Write_Memory_Params.BytesToWrite = SwapEndian_16(Write_Memory_Params.BytesToWrite);
150
151 if (Write_Memory_Params.BytesToWrite > sizeof(Write_Memory_Params.ProgData))
152 {
153 Endpoint_ClearOUT();
154 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
155 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
156
157 Endpoint_Write_8(V2Command);
158 Endpoint_Write_8(STATUS_CMD_FAILED);
159 Endpoint_ClearIN();
160 return;
161 }
162
163 Endpoint_Read_Stream_LE(&Write_Memory_Params.ProgData, Write_Memory_Params.BytesToWrite, NULL);
164
165 // The driver will terminate transfers that are a round multiple of the endpoint bank in size with a ZLP, need
166 // to catch this and discard it before continuing on with packet processing to prevent communication issues
167 if (((sizeof(uint8_t) + sizeof(Write_Memory_Params) - sizeof(Write_Memory_Params.ProgData)) +
168 Write_Memory_Params.BytesToWrite) % AVRISP_DATA_EPSIZE == 0)
169 {
170 Endpoint_ClearOUT();
171 Endpoint_WaitUntilReady();
172 }
173
174 Endpoint_ClearOUT();
175 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
176 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
177
178 uint8_t ProgrammingStatus = STATUS_CMD_OK;
179 uint8_t PollValue = (V2Command == CMD_PROGRAM_FLASH_ISP) ? Write_Memory_Params.PollValue1 :
180 Write_Memory_Params.PollValue2;
181 uint16_t PollAddress = 0;
182 uint8_t* NextWriteByte = Write_Memory_Params.ProgData;
183 uint16_t PageStartAddress = (CurrentAddress & 0xFFFF);
184
185 for (uint16_t CurrentByte = 0; CurrentByte < Write_Memory_Params.BytesToWrite; CurrentByte++)
186 {
187 uint8_t ByteToWrite = *(NextWriteByte++);
188 uint8_t ProgrammingMode = Write_Memory_Params.ProgrammingMode;
189
190 /* Check to see if we need to send a LOAD EXTENDED ADDRESS command to the target */
191 if (MustLoadExtendedAddress)
192 {
193 ISPTarget_LoadExtendedAddress();
194 MustLoadExtendedAddress = false;
195 }
196
197 ISPTarget_SendByte(Write_Memory_Params.ProgrammingCommands[0]);
198 ISPTarget_SendByte(CurrentAddress >> 8);
199 ISPTarget_SendByte(CurrentAddress & 0xFF);
200 ISPTarget_SendByte(ByteToWrite);
201
202 /* AVR FLASH addressing requires us to modify the write command based on if we are writing a high
203 * or low byte at the current word address */
204 if (V2Command == CMD_PROGRAM_FLASH_ISP)
205 Write_Memory_Params.ProgrammingCommands[0] ^= READ_WRITE_HIGH_BYTE_MASK;
206
207 /* Check to see if we have a valid polling address */
208 if (!(PollAddress) && (ByteToWrite != PollValue))
209 {
210 if ((CurrentByte & 0x01) && (V2Command == CMD_PROGRAM_FLASH_ISP))
211 Write_Memory_Params.ProgrammingCommands[2] |= READ_WRITE_HIGH_BYTE_MASK;
212 else
213 Write_Memory_Params.ProgrammingCommands[2] &= ~READ_WRITE_HIGH_BYTE_MASK;
214
215 PollAddress = (CurrentAddress & 0xFFFF);
216 }
217
218 /* If in word programming mode, commit the byte to the target's memory */
219 if (!(ProgrammingMode & PROG_MODE_PAGED_WRITES_MASK))
220 {
221 /* If the current polling address is invalid, switch to timed delay write completion mode */
222 if (!(PollAddress) && !(ProgrammingMode & PROG_MODE_WORD_READYBUSY_MASK))
223 ProgrammingMode = (ProgrammingMode & ~PROG_MODE_WORD_VALUE_MASK) | PROG_MODE_WORD_TIMEDELAY_MASK;
224
225 ProgrammingStatus = ISPTarget_WaitForProgComplete(ProgrammingMode, PollAddress, PollValue,
226 Write_Memory_Params.DelayMS,
227 Write_Memory_Params.ProgrammingCommands[2]);
228
229 /* Abort the programming loop early if the byte/word programming failed */
230 if (ProgrammingStatus != STATUS_CMD_OK)
231 break;
232
233 /* Must reset the polling address afterwards, so it is not erroneously used for the next byte */
234 PollAddress = 0;
235 }
236
237 /* EEPROM just increments the address each byte, flash needs to increment on each word and
238 * also check to ensure that a LOAD EXTENDED ADDRESS command is issued each time the extended
239 * address boundary has been crossed during FLASH memory programming */
240 if ((CurrentByte & 0x01) || (V2Command == CMD_PROGRAM_EEPROM_ISP))
241 {
242 CurrentAddress++;
243
244 if ((V2Command == CMD_PROGRAM_FLASH_ISP) && !(CurrentAddress & 0xFFFF))
245 MustLoadExtendedAddress = true;
246 }
247 }
248
249 /* If the current page must be committed, send the PROGRAM PAGE command to the target */
250 if (Write_Memory_Params.ProgrammingMode & PROG_MODE_COMMIT_PAGE_MASK)
251 {
252 ISPTarget_SendByte(Write_Memory_Params.ProgrammingCommands[1]);
253 ISPTarget_SendByte(PageStartAddress >> 8);
254 ISPTarget_SendByte(PageStartAddress & 0xFF);
255 ISPTarget_SendByte(0x00);
256
257 /* Check if polling is enabled and possible, if not switch to timed delay mode */
258 if ((Write_Memory_Params.ProgrammingMode & PROG_MODE_PAGED_VALUE_MASK) && !(PollAddress))
259 {
260 Write_Memory_Params.ProgrammingMode = (Write_Memory_Params.ProgrammingMode & ~PROG_MODE_PAGED_VALUE_MASK) |
261 PROG_MODE_PAGED_TIMEDELAY_MASK;
262 }
263
264 ProgrammingStatus = ISPTarget_WaitForProgComplete(Write_Memory_Params.ProgrammingMode, PollAddress, PollValue,
265 Write_Memory_Params.DelayMS,
266 Write_Memory_Params.ProgrammingCommands[2]);
267
268 /* Check to see if the FLASH address has crossed the extended address boundary */
269 if ((V2Command == CMD_PROGRAM_FLASH_ISP) && !(CurrentAddress & 0xFFFF))
270 MustLoadExtendedAddress = true;
271 }
272
273 Endpoint_Write_8(V2Command);
274 Endpoint_Write_8(ProgrammingStatus);
275 Endpoint_ClearIN();
276 }
277
278 /** Handler for the CMD_READ_FLASH_ISP and CMD_READ_EEPROM_ISP commands, reading in bytes,
279 * words or pages of data from the attached device.
280 *
281 * \param[in] V2Command Issued V2 Protocol command byte from the host
282 */
283 void ISPProtocol_ReadMemory(uint8_t V2Command)
284 {
285 struct
286 {
287 uint16_t BytesToRead;
288 uint8_t ReadMemoryCommand;
289 } Read_Memory_Params;
290
291 Endpoint_Read_Stream_LE(&Read_Memory_Params, sizeof(Read_Memory_Params), NULL);
292 Read_Memory_Params.BytesToRead = SwapEndian_16(Read_Memory_Params.BytesToRead);
293
294 Endpoint_ClearOUT();
295 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
296 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
297
298 Endpoint_Write_8(V2Command);
299 Endpoint_Write_8(STATUS_CMD_OK);
300
301 /* Read each byte from the device and write them to the packet for the host */
302 for (uint16_t CurrentByte = 0; CurrentByte < Read_Memory_Params.BytesToRead; CurrentByte++)
303 {
304 /* Check to see if we need to send a LOAD EXTENDED ADDRESS command to the target */
305 if (MustLoadExtendedAddress)
306 {
307 ISPTarget_LoadExtendedAddress();
308 MustLoadExtendedAddress = false;
309 }
310
311 /* Read the next byte from the desired memory space in the device */
312 ISPTarget_SendByte(Read_Memory_Params.ReadMemoryCommand);
313 ISPTarget_SendByte(CurrentAddress >> 8);
314 ISPTarget_SendByte(CurrentAddress & 0xFF);
315 Endpoint_Write_8(ISPTarget_ReceiveByte());
316
317 /* Check if the endpoint bank is currently full, if so send the packet */
318 if (!(Endpoint_IsReadWriteAllowed()))
319 {
320 Endpoint_ClearIN();
321 Endpoint_WaitUntilReady();
322 }
323
324 /* AVR FLASH addressing requires us to modify the read command based on if we are reading a high
325 * or low byte at the current word address */
326 if (V2Command == CMD_READ_FLASH_ISP)
327 Read_Memory_Params.ReadMemoryCommand ^= READ_WRITE_HIGH_BYTE_MASK;
328
329 /* EEPROM just increments the address each byte, flash needs to increment on each word and
330 * also check to ensure that a LOAD EXTENDED ADDRESS command is issued each time the extended
331 * address boundary has been crossed */
332 if ((CurrentByte & 0x01) || (V2Command == CMD_READ_EEPROM_ISP))
333 {
334 CurrentAddress++;
335
336 if ((V2Command != CMD_READ_EEPROM_ISP) && !(CurrentAddress & 0xFFFF))
337 MustLoadExtendedAddress = true;
338 }
339 }
340
341 Endpoint_Write_8(STATUS_CMD_OK);
342
343 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
344 Endpoint_ClearIN();
345
346 /* Ensure last packet is a short packet to terminate the transfer */
347 if (IsEndpointFull)
348 {
349 Endpoint_WaitUntilReady();
350 Endpoint_ClearIN();
351 Endpoint_WaitUntilReady();
352 }
353 }
354
355 /** Handler for the CMD_CHI_ERASE_ISP command, clearing the target's FLASH memory. */
356 void ISPProtocol_ChipErase(void)
357 {
358 struct
359 {
360 uint8_t EraseDelayMS;
361 uint8_t PollMethod;
362 uint8_t EraseCommandBytes[4];
363 } Erase_Chip_Params;
364
365 Endpoint_Read_Stream_LE(&Erase_Chip_Params, sizeof(Erase_Chip_Params), NULL);
366
367 Endpoint_ClearOUT();
368 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
369 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
370
371 uint8_t ResponseStatus = STATUS_CMD_OK;
372
373 /* Send the chip erase commands as given by the host to the device */
374 for (uint8_t SByte = 0; SByte < sizeof(Erase_Chip_Params.EraseCommandBytes); SByte++)
375 ISPTarget_SendByte(Erase_Chip_Params.EraseCommandBytes[SByte]);
376
377 /* Use appropriate command completion check as given by the host (delay or busy polling) */
378 if (!(Erase_Chip_Params.PollMethod))
379 ISPProtocol_DelayMS(Erase_Chip_Params.EraseDelayMS);
380 else
381 ResponseStatus = ISPTarget_WaitWhileTargetBusy();
382
383 Endpoint_Write_8(CMD_CHIP_ERASE_ISP);
384 Endpoint_Write_8(ResponseStatus);
385 Endpoint_ClearIN();
386 }
387
388 /** Handler for the CMD_READ_FUSE_ISP, CMD_READ_LOCK_ISP, CMD_READ_SIGNATURE_ISP and CMD_READ_OSCCAL commands,
389 * reading the requested configuration byte from the device.
390 *
391 * \param[in] V2Command Issued V2 Protocol command byte from the host
392 */
393 void ISPProtocol_ReadFuseLockSigOSCCAL(uint8_t V2Command)
394 {
395 struct
396 {
397 uint8_t RetByte;
398 uint8_t ReadCommandBytes[4];
399 } Read_FuseLockSigOSCCAL_Params;
400
401 Endpoint_Read_Stream_LE(&Read_FuseLockSigOSCCAL_Params, sizeof(Read_FuseLockSigOSCCAL_Params), NULL);
402
403 Endpoint_ClearOUT();
404 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
405 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
406
407 uint8_t ResponseBytes[4];
408
409 /* Send the Fuse or Lock byte read commands as given by the host to the device, store response */
410 for (uint8_t RByte = 0; RByte < sizeof(ResponseBytes); RByte++)
411 ResponseBytes[RByte] = ISPTarget_TransferByte(Read_FuseLockSigOSCCAL_Params.ReadCommandBytes[RByte]);
412
413 Endpoint_Write_8(V2Command);
414 Endpoint_Write_8(STATUS_CMD_OK);
415 Endpoint_Write_8(ResponseBytes[Read_FuseLockSigOSCCAL_Params.RetByte - 1]);
416 Endpoint_Write_8(STATUS_CMD_OK);
417 Endpoint_ClearIN();
418 }
419
420 /** Handler for the CMD_WRITE_FUSE_ISP and CMD_WRITE_LOCK_ISP commands, writing the requested configuration
421 * byte to the device.
422 *
423 * \param[in] V2Command Issued V2 Protocol command byte from the host
424 */
425 void ISPProtocol_WriteFuseLock(uint8_t V2Command)
426 {
427 struct
428 {
429 uint8_t WriteCommandBytes[4];
430 } Write_FuseLockSig_Params;
431
432 Endpoint_Read_Stream_LE(&Write_FuseLockSig_Params, sizeof(Write_FuseLockSig_Params), NULL);
433
434 Endpoint_ClearOUT();
435 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
436 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
437
438 /* Send the Fuse or Lock byte program commands as given by the host to the device */
439 for (uint8_t SByte = 0; SByte < sizeof(Write_FuseLockSig_Params.WriteCommandBytes); SByte++)
440 ISPTarget_SendByte(Write_FuseLockSig_Params.WriteCommandBytes[SByte]);
441
442 Endpoint_Write_8(V2Command);
443 Endpoint_Write_8(STATUS_CMD_OK);
444 Endpoint_Write_8(STATUS_CMD_OK);
445 Endpoint_ClearIN();
446 }
447
448 /** Handler for the CMD_SPI_MULTI command, writing and reading arbitrary SPI data to and from the attached device. */
449 void ISPProtocol_SPIMulti(void)
450 {
451 struct
452 {
453 uint8_t TxBytes;
454 uint8_t RxBytes;
455 uint8_t RxStartAddr;
456 uint8_t TxData[255];
457 } SPI_Multi_Params;
458
459 Endpoint_Read_Stream_LE(&SPI_Multi_Params, (sizeof(SPI_Multi_Params) - sizeof(SPI_Multi_Params.TxData)), NULL);
460 Endpoint_Read_Stream_LE(&SPI_Multi_Params.TxData, SPI_Multi_Params.TxBytes, NULL);
461
462 Endpoint_ClearOUT();
463 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPNUM);
464 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
465
466 Endpoint_Write_8(CMD_SPI_MULTI);
467 Endpoint_Write_8(STATUS_CMD_OK);
468
469 uint8_t CurrTxPos = 0;
470 uint8_t CurrRxPos = 0;
471
472 /* Write out bytes to transmit until the start of the bytes to receive is met */
473 while (CurrTxPos < SPI_Multi_Params.RxStartAddr)
474 {
475 if (CurrTxPos < SPI_Multi_Params.TxBytes)
476 ISPTarget_SendByte(SPI_Multi_Params.TxData[CurrTxPos]);
477 else
478 ISPTarget_SendByte(0);
479
480 CurrTxPos++;
481 }
482
483 /* Transmit remaining bytes with padding as needed, read in response bytes */
484 while (CurrRxPos < SPI_Multi_Params.RxBytes)
485 {
486 if (CurrTxPos < SPI_Multi_Params.TxBytes)
487 Endpoint_Write_8(ISPTarget_TransferByte(SPI_Multi_Params.TxData[CurrTxPos++]));
488 else
489 Endpoint_Write_8(ISPTarget_ReceiveByte());
490
491 /* Check to see if we have filled the endpoint bank and need to send the packet */
492 if (!(Endpoint_IsReadWriteAllowed()))
493 {
494 Endpoint_ClearIN();
495 Endpoint_WaitUntilReady();
496 }
497
498 CurrRxPos++;
499 }
500
501 Endpoint_Write_8(STATUS_CMD_OK);
502
503 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
504 Endpoint_ClearIN();
505
506 /* Ensure last packet is a short packet to terminate the transfer */
507 if (IsEndpointFull)
508 {
509 Endpoint_WaitUntilReady();
510 Endpoint_ClearIN();
511 Endpoint_WaitUntilReady();
512 }
513 }
514
515 /** Blocking delay for a given number of milliseconds.
516 *
517 * \param[in] DelayMS Number of milliseconds to delay for
518 */
519 void ISPProtocol_DelayMS(uint8_t DelayMS)
520 {
521 while (DelayMS-- && !(TimeoutExpired))
522 Delay_MS(1);
523 }
524
525 #endif