Ping-Pong Buffer
Medium · Sequential · SystemVerilog · VHDL
A premium problem. Subscribe to open it in the editor, run the testbench and see where your design lands.
Design a ping-pong buffer: two banks of DEPTH words of DATA_W bits, one written while the other is read.
A ping-pong (double) buffer lets a producer fill one bank while a consumer drains the other, then swaps the two, so the producer only waits when both banks are full and the consumer only when both are empty.
At any time one bank is the write bank and the other the read bank; bank_sel is the index of the write bank. wr_ready is high while the write bank holds fewer than DEPTH words, and rd_valid while the read bank holds a word not yet read.
A write (wr_en high while wr_ready is high) stores wr_data in the write bank. A read (rd_en high while rd_valid is high) takes the read bank's next word, in the order the words were written, and rd_data shows it in the following cycle; in every other cycle rd_data may take any value. A write and a read can happen in the same cycle. wr_en while wr_ready is low, and rd_en while rd_valid is low, have no effect.
The banks swap in a cycle in which, counting that cycle's write and read, the write bank becomes full and the read bank has no word left to read: the full bank becomes the read bank, with all DEPTH words unread, and the other becomes an empty write bank. So while the read bank is empty, the write that fills the write bank also swaps them; once both banks are full, wr_ready stays low until the read of the read bank's last word swaps them. wr_ready, rd_valid and bank_sel change in the cycle after the write, read or swap that changes them.
rst_n is a synchronous, active-low reset: both banks become empty and bank 0 becomes the write bank.
DEPTH may be any positive integer, not only a power of two.
- FIFOs & memory