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