# Why are words bit-shifted for an Atmel SAM4S SPI slave?

I have discovered a problem when using the SPI peripheral in slave mode on an Atmel SAM4S. Occasionally words can become bit-shifted. I can force this condition by enabling the peripheral some number of clocks after NSS goes active. I do this by waiting for NSSR, then using a delay loop to wait a specific time before I enable the peripheral. I have confirmed on a scope that when the peripheral is enabled n clocks after NSS goes active, the words are shifted by n bits.

When the peripheral gets in this state, the only way to recover is to perform a reset (i.e. set the SWRST in the control register). Disabling and re-enabling is not sufficient.

This issue has also been observed on a SAM9G45 MPU.

This is due to the design of their SPI peripheral. In slave mode, the shift register is shifted each SPCK (assuming NSS is low and SPIENS is set). There is an internal counter (not shown in the block diagram) for the shift register, and when it reaches the word size, the contents are shifted to SPI_RDR and from SPI_TDR. Thus if you have a word size of 8, and only 7 clocks are present for the first NSS, on the next NSS, the shift register contents will not be transferred until after the first clock cycle.
When NSS goes high, this counter is not reset. Similarly, setting SPIDIS does not reset the counter. Only SWRST resets the counter.
In addition to the method described to force this condition, glitches on SPCK during NSS (such as from EMI) can also result in a bit-shift.