Clocks and timing: setup, hold and metastability
For a flip-flop to capture a value properly, the input has to stay still before and after the clock. What happens when that condition is broken.
Setup time and hold time
- Setup time: the minimum time the input must be stable before the clock edge
- Hold time: the minimum time the input must be held after the clock edge
The tSU and tH in the timing diagrams of SPI or external-memory datasheets are these values. The higher the clock, the smaller the margin, and violations occur when long traces add delay.
Maximum clock frequency
A signal leaving one flip-flop has to pass through the combinational logic and reach the next flip-flop before its setup time. The delay of the longest path (the critical path) sets the lower limit on the clock period.
Metastability
A signal that changes without regard to the clock, such as a button input or a signal from another clock domain, will sooner or later violate setup and hold. The flip-flop output can then sit for a while in a state that is neither 0 nor 1.
The solution is a synchroniser of two flip-flops in series. The probability that instability in the first stage resolves before it reaches the second is very high. MCU GPIO inputs contain a synchroniser like this, which is why an input takes a few clocks before it can be read.