AVRISP-MKII Clone: Add length checks to SPI Multi and XPROG read/write commands.
[pub/lufa.git] / Projects / AVRISP-MKII / Lib / ISP / ISPProtocol.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2021.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2021 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Copyright 2019 Jacob September (jacobseptember [at] gmail [dot] com)
13
14 Permission to use, copy, modify, distribute, and sell this
15 software and its documentation for any purpose is hereby granted
16 without fee, provided that the above copyright notice appear in
17 all copies and that both that the copyright notice and this
18 permission notice and warranty disclaimer appear in supporting
19 documentation, and that the name of the author not be used in
20 advertising or publicity pertaining to distribution of the
21 software without specific, written prior permission.
22
23 The author disclaims all warranties with regard to this
24 software, including all implied warranties of merchantability
25 and fitness. In no event shall the author be liable for any
26 special, indirect or consequential damages or any damages
27 whatsoever resulting from loss of use, data or profits, whether
28 in an action of contract, negligence or other tortious action,
29 arising out of or in connection with the use or performance of
30 this software.
31 */
32
33 /** \file
34 *
35 * ISP Protocol handler, to process V2 Protocol wrapped ISP commands used in Atmel programmer devices.
36 */
37
38 #include "ISPProtocol.h"
39
40 #if defined(ENABLE_ISP_PROTOCOL) || defined(__DOXYGEN__)
41
42 /* Half cycles of the OSCCAL calibration period remaining */
43 static volatile uint16_t ISPProtocol_HalfCyclesRemaining;
44
45 /** Target device response I/O pin toggles remaining for successful OSCCAL calibration */
46 static volatile uint8_t ISPProtocol_ResponseTogglesRemaining;
47
48
49 /** ISR to toggle MOSI pin when TIMER1 overflows */
50 ISR(TIMER1_OVF_vect, ISR_BLOCK)
51 {
52 PINB |= (1 << PB2); // toggle PB2 (MOSI) by writing 1 to its bit in PINB
53 ISPProtocol_HalfCyclesRemaining--;
54 }
55
56 /** ISR to listen for toggles on MISO pin */
57 ISR(PCINT0_vect, ISR_BLOCK)
58 {
59 ISPProtocol_ResponseTogglesRemaining--;
60 }
61
62 /** Handler for the CMD_ENTER_PROGMODE_ISP command, which attempts to enter programming mode on
63 * the attached device, returning success or failure back to the host.
64 */
65 void ISPProtocol_EnterISPMode(void)
66 {
67 struct
68 {
69 uint8_t TimeoutMS;
70 uint8_t PinStabDelayMS;
71 uint8_t ExecutionDelayMS;
72 uint8_t SynchLoops;
73 uint8_t ByteDelay;
74 uint8_t PollValue;
75 uint8_t PollIndex;
76 uint8_t EnterProgBytes[4];
77 } Enter_ISP_Params;
78
79 Endpoint_Read_Stream_LE(&Enter_ISP_Params, sizeof(Enter_ISP_Params), NULL);
80
81 Endpoint_ClearOUT();
82 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
83 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
84
85 uint8_t ResponseStatus = STATUS_CMD_FAILED;
86
87 CurrentAddress = 0;
88
89 /* Perform execution delay, initialize SPI bus */
90 ISPProtocol_DelayMS(Enter_ISP_Params.ExecutionDelayMS);
91 ISPTarget_EnableTargetISP();
92
93 ISPTarget_ChangeTargetResetLine(true);
94 ISPProtocol_DelayMS(Enter_ISP_Params.PinStabDelayMS);
95
96 /* Continuously attempt to synchronize with the target until either the number of attempts specified
97 * by the host has exceeded, or the the device sends back the expected response values */
98 while (Enter_ISP_Params.SynchLoops-- && TimeoutTicksRemaining)
99 {
100 uint8_t ResponseBytes[4];
101
102 for (uint8_t RByte = 0; RByte < sizeof(ResponseBytes); RByte++)
103 {
104 ISPProtocol_DelayMS(Enter_ISP_Params.ByteDelay);
105 ResponseBytes[RByte] = ISPTarget_TransferByte(Enter_ISP_Params.EnterProgBytes[RByte]);
106 }
107
108 /* Check if polling disabled, or if the polled value matches the expected value */
109 if (!(Enter_ISP_Params.PollIndex) || (ResponseBytes[Enter_ISP_Params.PollIndex - 1] == Enter_ISP_Params.PollValue))
110 {
111 ResponseStatus = STATUS_CMD_OK;
112 break;
113 }
114 else
115 {
116 ISPTarget_ChangeTargetResetLine(false);
117 ISPProtocol_DelayMS(Enter_ISP_Params.PinStabDelayMS);
118 ISPTarget_ChangeTargetResetLine(true);
119 ISPProtocol_DelayMS(Enter_ISP_Params.PinStabDelayMS);
120 }
121 }
122
123 Endpoint_Write_8(CMD_ENTER_PROGMODE_ISP);
124 Endpoint_Write_8(ResponseStatus);
125 Endpoint_ClearIN();
126 }
127
128 /** Handler for the CMD_LEAVE_ISP command, which releases the target from programming mode. */
129 void ISPProtocol_LeaveISPMode(void)
130 {
131 struct
132 {
133 uint8_t PreDelayMS;
134 uint8_t PostDelayMS;
135 } Leave_ISP_Params;
136
137 Endpoint_Read_Stream_LE(&Leave_ISP_Params, sizeof(Leave_ISP_Params), NULL);
138
139 Endpoint_ClearOUT();
140 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
141 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
142
143 /* Perform pre-exit delay, release the target /RESET, disable the SPI bus and perform the post-exit delay */
144 ISPProtocol_DelayMS(Leave_ISP_Params.PreDelayMS);
145 ISPTarget_ChangeTargetResetLine(false);
146 ISPTarget_DisableTargetISP();
147 ISPProtocol_DelayMS(Leave_ISP_Params.PostDelayMS);
148
149 Endpoint_Write_8(CMD_LEAVE_PROGMODE_ISP);
150 Endpoint_Write_8(STATUS_CMD_OK);
151 Endpoint_ClearIN();
152 }
153
154 /** Handler for the CMD_PROGRAM_FLASH_ISP and CMD_PROGRAM_EEPROM_ISP commands, writing out bytes,
155 * words or pages of data to the attached device.
156 *
157 * \param[in] V2Command Issued V2 Protocol command byte from the host
158 */
159 void ISPProtocol_ProgramMemory(uint8_t V2Command)
160 {
161 struct
162 {
163 uint16_t BytesToWrite;
164 uint8_t ProgrammingMode;
165 uint8_t DelayMS;
166 uint8_t ProgrammingCommands[3];
167 uint8_t PollValue1;
168 uint8_t PollValue2;
169 uint8_t ProgData[256]; // Note, the Jungo driver has a very short ACK timeout period, need to buffer the
170 } Write_Memory_Params; // whole page and ACK the packet as fast as possible to prevent it from aborting
171
172 Endpoint_Read_Stream_LE(&Write_Memory_Params, (sizeof(Write_Memory_Params) -
173 sizeof(Write_Memory_Params.ProgData)), NULL);
174 Write_Memory_Params.BytesToWrite = SwapEndian_16(Write_Memory_Params.BytesToWrite);
175
176 if (Write_Memory_Params.BytesToWrite > sizeof(Write_Memory_Params.ProgData))
177 {
178 Endpoint_ClearOUT();
179 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
180 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
181
182 Endpoint_Write_8(V2Command);
183 Endpoint_Write_8(STATUS_CMD_FAILED);
184 Endpoint_ClearIN();
185 return;
186 }
187
188 Endpoint_Read_Stream_LE(&Write_Memory_Params.ProgData, Write_Memory_Params.BytesToWrite, NULL);
189
190 // The driver will terminate transfers that are a round multiple of the endpoint bank in size with a ZLP, need
191 // to catch this and discard it before continuing on with packet processing to prevent communication issues
192 if (((sizeof(uint8_t) + sizeof(Write_Memory_Params) - sizeof(Write_Memory_Params.ProgData)) +
193 Write_Memory_Params.BytesToWrite) % AVRISP_DATA_EPSIZE == 0)
194 {
195 Endpoint_ClearOUT();
196 Endpoint_WaitUntilReady();
197 }
198
199 Endpoint_ClearOUT();
200 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
201 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
202
203 uint8_t ProgrammingStatus = STATUS_CMD_OK;
204 uint8_t PollValue = (V2Command == CMD_PROGRAM_FLASH_ISP) ? Write_Memory_Params.PollValue1 :
205 Write_Memory_Params.PollValue2;
206 uint16_t PollAddress = 0;
207 uint8_t* NextWriteByte = Write_Memory_Params.ProgData;
208 uint16_t PageStartAddress = (CurrentAddress & 0xFFFF);
209
210 for (uint16_t CurrentByte = 0; CurrentByte < Write_Memory_Params.BytesToWrite; CurrentByte++)
211 {
212 uint8_t ByteToWrite = *(NextWriteByte++);
213 uint8_t ProgrammingMode = Write_Memory_Params.ProgrammingMode;
214
215 /* Check to see if we need to send a LOAD EXTENDED ADDRESS command to the target */
216 if (MustLoadExtendedAddress)
217 {
218 ISPTarget_LoadExtendedAddress();
219 MustLoadExtendedAddress = false;
220 }
221
222 ISPTarget_SendByte(Write_Memory_Params.ProgrammingCommands[0]);
223 ISPTarget_SendByte(CurrentAddress >> 8);
224 ISPTarget_SendByte(CurrentAddress & 0xFF);
225 ISPTarget_SendByte(ByteToWrite);
226
227 /* AVR FLASH addressing requires us to modify the write command based on if we are writing a high
228 * or low byte at the current word address */
229 if (V2Command == CMD_PROGRAM_FLASH_ISP)
230 Write_Memory_Params.ProgrammingCommands[0] ^= READ_WRITE_HIGH_BYTE_MASK;
231
232 /* Check to see if we have a valid polling address */
233 if (!(PollAddress) && (ByteToWrite != PollValue))
234 {
235 if ((CurrentByte & 0x01) && (V2Command == CMD_PROGRAM_FLASH_ISP))
236 Write_Memory_Params.ProgrammingCommands[2] |= READ_WRITE_HIGH_BYTE_MASK;
237 else
238 Write_Memory_Params.ProgrammingCommands[2] &= ~READ_WRITE_HIGH_BYTE_MASK;
239
240 PollAddress = (CurrentAddress & 0xFFFF);
241 }
242
243 /* If in word programming mode, commit the byte to the target's memory */
244 if (!(ProgrammingMode & PROG_MODE_PAGED_WRITES_MASK))
245 {
246 /* If the current polling address is invalid, switch to timed delay write completion mode */
247 if (!(PollAddress) && !(ProgrammingMode & PROG_MODE_WORD_READYBUSY_MASK))
248 ProgrammingMode = (ProgrammingMode & ~PROG_MODE_WORD_VALUE_MASK) | PROG_MODE_WORD_TIMEDELAY_MASK;
249
250 ProgrammingStatus = ISPTarget_WaitForProgComplete(ProgrammingMode, PollAddress, PollValue,
251 Write_Memory_Params.DelayMS,
252 Write_Memory_Params.ProgrammingCommands[2]);
253
254 /* Abort the programming loop early if the byte/word programming failed */
255 if (ProgrammingStatus != STATUS_CMD_OK)
256 break;
257
258 /* Must reset the polling address afterwards, so it is not erroneously used for the next byte */
259 PollAddress = 0;
260 }
261
262 /* EEPROM just increments the address each byte, flash needs to increment on each word and
263 * also check to ensure that a LOAD EXTENDED ADDRESS command is issued each time the extended
264 * address boundary has been crossed during FLASH memory programming */
265 if ((CurrentByte & 0x01) || (V2Command == CMD_PROGRAM_EEPROM_ISP))
266 {
267 CurrentAddress++;
268
269 if ((V2Command == CMD_PROGRAM_FLASH_ISP) && !(CurrentAddress & 0xFFFF))
270 MustLoadExtendedAddress = true;
271 }
272 }
273
274 /* If the current page must be committed, send the PROGRAM PAGE command to the target */
275 if (Write_Memory_Params.ProgrammingMode & PROG_MODE_COMMIT_PAGE_MASK)
276 {
277 ISPTarget_SendByte(Write_Memory_Params.ProgrammingCommands[1]);
278 ISPTarget_SendByte(PageStartAddress >> 8);
279 ISPTarget_SendByte(PageStartAddress & 0xFF);
280 ISPTarget_SendByte(0x00);
281
282 /* Check if polling is enabled and possible, if not switch to timed delay mode */
283 if ((Write_Memory_Params.ProgrammingMode & PROG_MODE_PAGED_VALUE_MASK) && !(PollAddress))
284 {
285 Write_Memory_Params.ProgrammingMode = (Write_Memory_Params.ProgrammingMode & ~PROG_MODE_PAGED_VALUE_MASK) |
286 PROG_MODE_PAGED_TIMEDELAY_MASK;
287 }
288
289 ProgrammingStatus = ISPTarget_WaitForProgComplete(Write_Memory_Params.ProgrammingMode, PollAddress, PollValue,
290 Write_Memory_Params.DelayMS,
291 Write_Memory_Params.ProgrammingCommands[2]);
292
293 /* Check to see if the FLASH address has crossed the extended address boundary */
294 if ((V2Command == CMD_PROGRAM_FLASH_ISP) && !(CurrentAddress & 0xFFFF))
295 MustLoadExtendedAddress = true;
296 }
297
298 Endpoint_Write_8(V2Command);
299 Endpoint_Write_8(ProgrammingStatus);
300 Endpoint_ClearIN();
301 }
302
303 /** Handler for the CMD_READ_FLASH_ISP and CMD_READ_EEPROM_ISP commands, reading in bytes,
304 * words or pages of data from the attached device.
305 *
306 * \param[in] V2Command Issued V2 Protocol command byte from the host
307 */
308 void ISPProtocol_ReadMemory(uint8_t V2Command)
309 {
310 struct
311 {
312 uint16_t BytesToRead;
313 uint8_t ReadMemoryCommand;
314 } Read_Memory_Params;
315
316 Endpoint_Read_Stream_LE(&Read_Memory_Params, sizeof(Read_Memory_Params), NULL);
317 Read_Memory_Params.BytesToRead = SwapEndian_16(Read_Memory_Params.BytesToRead);
318
319 Endpoint_ClearOUT();
320 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
321 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
322
323 Endpoint_Write_8(V2Command);
324 Endpoint_Write_8(STATUS_CMD_OK);
325
326 /* Read each byte from the device and write them to the packet for the host */
327 for (uint16_t CurrentByte = 0; CurrentByte < Read_Memory_Params.BytesToRead; CurrentByte++)
328 {
329 /* Check to see if we need to send a LOAD EXTENDED ADDRESS command to the target */
330 if (MustLoadExtendedAddress)
331 {
332 ISPTarget_LoadExtendedAddress();
333 MustLoadExtendedAddress = false;
334 }
335
336 /* Read the next byte from the desired memory space in the device */
337 ISPTarget_SendByte(Read_Memory_Params.ReadMemoryCommand);
338 ISPTarget_SendByte(CurrentAddress >> 8);
339 ISPTarget_SendByte(CurrentAddress & 0xFF);
340 Endpoint_Write_8(ISPTarget_ReceiveByte());
341
342 /* Check if the endpoint bank is currently full, if so send the packet */
343 if (!(Endpoint_IsReadWriteAllowed()))
344 {
345 Endpoint_ClearIN();
346 Endpoint_WaitUntilReady();
347 }
348
349 /* AVR FLASH addressing requires us to modify the read command based on if we are reading a high
350 * or low byte at the current word address */
351 if (V2Command == CMD_READ_FLASH_ISP)
352 Read_Memory_Params.ReadMemoryCommand ^= READ_WRITE_HIGH_BYTE_MASK;
353
354 /* EEPROM just increments the address each byte, flash needs to increment on each word and
355 * also check to ensure that a LOAD EXTENDED ADDRESS command is issued each time the extended
356 * address boundary has been crossed */
357 if ((CurrentByte & 0x01) || (V2Command == CMD_READ_EEPROM_ISP))
358 {
359 CurrentAddress++;
360
361 if ((V2Command != CMD_READ_EEPROM_ISP) && !(CurrentAddress & 0xFFFF))
362 MustLoadExtendedAddress = true;
363 }
364 }
365
366 Endpoint_Write_8(STATUS_CMD_OK);
367
368 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
369 Endpoint_ClearIN();
370
371 /* Ensure last packet is a short packet to terminate the transfer */
372 if (IsEndpointFull)
373 {
374 Endpoint_WaitUntilReady();
375 Endpoint_ClearIN();
376 Endpoint_WaitUntilReady();
377 }
378 }
379
380 /** Handler for the CMD_CHI_ERASE_ISP command, clearing the target's FLASH memory. */
381 void ISPProtocol_ChipErase(void)
382 {
383 struct
384 {
385 uint8_t EraseDelayMS;
386 uint8_t PollMethod;
387 uint8_t EraseCommandBytes[4];
388 } Erase_Chip_Params;
389
390 Endpoint_Read_Stream_LE(&Erase_Chip_Params, sizeof(Erase_Chip_Params), NULL);
391
392 Endpoint_ClearOUT();
393 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
394 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
395
396 uint8_t ResponseStatus = STATUS_CMD_OK;
397
398 /* Send the chip erase commands as given by the host to the device */
399 for (uint8_t SByte = 0; SByte < sizeof(Erase_Chip_Params.EraseCommandBytes); SByte++)
400 ISPTarget_SendByte(Erase_Chip_Params.EraseCommandBytes[SByte]);
401
402 /* Use appropriate command completion check as given by the host (delay or busy polling) */
403 if (!(Erase_Chip_Params.PollMethod))
404 ISPProtocol_DelayMS(Erase_Chip_Params.EraseDelayMS);
405 else
406 ResponseStatus = ISPTarget_WaitWhileTargetBusy();
407
408 Endpoint_Write_8(CMD_CHIP_ERASE_ISP);
409 Endpoint_Write_8(ResponseStatus);
410 Endpoint_ClearIN();
411 }
412
413 /** Handler for the CMD_OSCCAL command, entering RC-calibration mode as specified in AVR053 */
414 void ISPProtocol_Calibrate(void)
415 {
416 uint8_t ResponseStatus = STATUS_CMD_OK;
417
418 /* Don't entirely know why this is needed, something to do with the USB communication back to PC */
419 Endpoint_ClearOUT();
420 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
421 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
422
423 /* Enable pull-up on MISO and release ~RESET */
424 DDRB = ~(1 << PB3);
425 PORTB |= ( (1 << PB4) | (1 << PB3) );
426
427 /* Set up MISO pin (PCINT3) to listen for toggles */
428 PCMSK0 = (1 << PCINT3);
429
430 /* Set up timer that fires at a rate of 65536 Hz - this will drive the MOSI toggle */
431 OCR1A = ISPPROTOCOL_CALIB_TICKS - 1;
432 TCCR1A = ( (1 << WGM11) | (1 << WGM10) ); // set for fast PWM, TOP = OCR1A
433 TCCR1B = ( (1 << WGM13) | (1 << WGM12) | (1 << CS10) ); // ... and no clock prescaling
434 TCNT1 = 0;
435
436 /* Initialize counter variables */
437 ISPProtocol_HalfCyclesRemaining = ISPPROTOCOL_CALIB_HALF_CYCLE_LIMIT;
438 ISPProtocol_ResponseTogglesRemaining = ISPPROTOCOL_CALIB_SUCCESS_TOGGLE_NUM;
439
440 /* Turn on interrupts */
441 PCICR |= (1 << PCIE0); // enable interrupts for PCINT7:0 (don't touch setting for PCINT12:8)
442 TIMSK1 = (1 << TOIE1); // enable T1 OVF interrupt (and no other T1 interrupts)
443
444 /* Turn on global interrupts for the following block, restoring current state at end */
445 NONATOMIC_BLOCK(NONATOMIC_RESTORESTATE)
446 {
447 /* Let device do its calibration, wait for response on MISO */
448 while (ISPProtocol_HalfCyclesRemaining && ISPProtocol_ResponseTogglesRemaining);
449
450 /* Disable timer and pin change interrupts */
451 PCICR &= ~(1 << PCIE0);
452 TIMSK1 = 0;
453 }
454
455 /* Check if device responded with a success message or if we timed out */
456 if (ISPProtocol_ResponseTogglesRemaining)
457 ResponseStatus = STATUS_CMD_TOUT;
458
459 /* Report back to PC via USB */
460 Endpoint_Write_8(CMD_OSCCAL);
461 Endpoint_Write_8(ResponseStatus);
462 Endpoint_ClearIN();
463 }
464
465 /** Handler for the CMD_READ_FUSE_ISP, CMD_READ_LOCK_ISP, CMD_READ_SIGNATURE_ISP and CMD_READ_OSCCAL commands,
466 * reading the requested configuration byte from the device.
467 *
468 * \param[in] V2Command Issued V2 Protocol command byte from the host
469 */
470 void ISPProtocol_ReadFuseLockSigOSCCAL(uint8_t V2Command)
471 {
472 struct
473 {
474 uint8_t RetByte;
475 uint8_t ReadCommandBytes[4];
476 } Read_FuseLockSigOSCCAL_Params;
477
478 Endpoint_Read_Stream_LE(&Read_FuseLockSigOSCCAL_Params, sizeof(Read_FuseLockSigOSCCAL_Params), NULL);
479
480 Endpoint_ClearOUT();
481 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
482 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
483
484 uint8_t ResponseBytes[4];
485
486 /* Send the Fuse or Lock byte read commands as given by the host to the device, store response */
487 for (uint8_t RByte = 0; RByte < sizeof(ResponseBytes); RByte++)
488 ResponseBytes[RByte] = ISPTarget_TransferByte(Read_FuseLockSigOSCCAL_Params.ReadCommandBytes[RByte]);
489
490 Endpoint_Write_8(V2Command);
491 Endpoint_Write_8(STATUS_CMD_OK);
492 Endpoint_Write_8(ResponseBytes[Read_FuseLockSigOSCCAL_Params.RetByte - 1]);
493 Endpoint_Write_8(STATUS_CMD_OK);
494 Endpoint_ClearIN();
495 }
496
497 /** Handler for the CMD_WRITE_FUSE_ISP and CMD_WRITE_LOCK_ISP commands, writing the requested configuration
498 * byte to the device.
499 *
500 * \param[in] V2Command Issued V2 Protocol command byte from the host
501 */
502 void ISPProtocol_WriteFuseLock(uint8_t V2Command)
503 {
504 struct
505 {
506 uint8_t WriteCommandBytes[4];
507 } Write_FuseLockSig_Params;
508
509 Endpoint_Read_Stream_LE(&Write_FuseLockSig_Params, sizeof(Write_FuseLockSig_Params), NULL);
510
511 Endpoint_ClearOUT();
512 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
513 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
514
515 /* Send the Fuse or Lock byte program commands as given by the host to the device */
516 for (uint8_t SByte = 0; SByte < sizeof(Write_FuseLockSig_Params.WriteCommandBytes); SByte++)
517 ISPTarget_SendByte(Write_FuseLockSig_Params.WriteCommandBytes[SByte]);
518
519 Endpoint_Write_8(V2Command);
520 Endpoint_Write_8(STATUS_CMD_OK);
521 Endpoint_Write_8(STATUS_CMD_OK);
522 Endpoint_ClearIN();
523 }
524
525 /** Handler for the CMD_SPI_MULTI command, writing and reading arbitrary SPI data to and from the attached device. */
526 void ISPProtocol_SPIMulti(void)
527 {
528 struct
529 {
530 uint8_t TxBytes;
531 uint8_t RxBytes;
532 uint8_t RxStartAddr;
533 uint8_t TxData[255];
534 } SPI_Multi_Params;
535
536 Endpoint_Read_Stream_LE(&SPI_Multi_Params, (sizeof(SPI_Multi_Params) - sizeof(SPI_Multi_Params.TxData)), NULL);
537 Endpoint_Read_Stream_LE(&SPI_Multi_Params.TxData, SPI_Multi_Params.TxBytes, NULL);
538
539 if (SPI_Multi_Params.TxBytes >= sizeof(SPI_Multi_Params.TxData))
540 {
541 Endpoint_StallTransaction();
542 return;
543 }
544
545 Endpoint_ClearOUT();
546 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR);
547 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN);
548
549 Endpoint_Write_8(CMD_SPI_MULTI);
550 Endpoint_Write_8(STATUS_CMD_OK);
551
552 uint8_t CurrTxPos = 0;
553 uint8_t CurrRxPos = 0;
554
555 /* Write out bytes to transmit until the start of the bytes to receive is met */
556 while (CurrTxPos < SPI_Multi_Params.RxStartAddr)
557 {
558 if (CurrTxPos < SPI_Multi_Params.TxBytes)
559 ISPTarget_SendByte(SPI_Multi_Params.TxData[CurrTxPos]);
560 else
561 ISPTarget_SendByte(0);
562
563 CurrTxPos++;
564 }
565
566 /* Transmit remaining bytes with padding as needed, read in response bytes */
567 while (CurrRxPos < SPI_Multi_Params.RxBytes)
568 {
569 if (CurrTxPos < SPI_Multi_Params.TxBytes)
570 Endpoint_Write_8(ISPTarget_TransferByte(SPI_Multi_Params.TxData[CurrTxPos++]));
571 else
572 Endpoint_Write_8(ISPTarget_ReceiveByte());
573
574 /* Check to see if we have filled the endpoint bank and need to send the packet */
575 if (!(Endpoint_IsReadWriteAllowed()))
576 {
577 Endpoint_ClearIN();
578 Endpoint_WaitUntilReady();
579 }
580
581 CurrRxPos++;
582 }
583
584 Endpoint_Write_8(STATUS_CMD_OK);
585
586 bool IsEndpointFull = !(Endpoint_IsReadWriteAllowed());
587 Endpoint_ClearIN();
588
589 /* Ensure last packet is a short packet to terminate the transfer */
590 if (IsEndpointFull)
591 {
592 Endpoint_WaitUntilReady();
593 Endpoint_ClearIN();
594 Endpoint_WaitUntilReady();
595 }
596 }
597
598 /** Blocking delay for a given number of milliseconds. This provides a simple wrapper around
599 * the avr-libc provided delay function, so that the delay function can be called with a
600 * constant value (to prevent run-time floating point operations being required).
601 *
602 * \param[in] DelayMS Number of milliseconds to delay for
603 */
604 void ISPProtocol_DelayMS(uint8_t DelayMS)
605 {
606 while (DelayMS-- && TimeoutTicksRemaining)
607 Delay_MS(1);
608 }
609
610 #endif