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