---
title: "Project: an asynchronous FIFO"
heading: A cycle model with Gray-code pointers and synchronizers, checked by a constrained-random testbench
eyebrow: S3 · Lesson 51 · Asynchronous FIFO project
xp: 80
---

::: hook
The asynchronous FIFO is the standard way to stream data between two clock domains, and it brings together several ideas from this course: a dual-port memory (lesson 12), pointers that cross clock domains through synchronizers (lesson 24), Gray codes that keep a sampled pointer either old or new, and full and empty flags that must never be optimistic. In this project you'll build a cycle-accurate model of one in Python, with a synchronizer that models metastable sampling, and verify it the way a verification engineer would (lesson 25): a constrained-random testbench that throws thousands of words through random depths, clock ratios, traffic patterns and metastability windows, and checks every word.
:::

::: predict
## Both clocks run at the same frequency, and the FIFO's full flag reaches the writer through a two-flop synchronizer. Why might a 4-deep FIFO fail to keep up with a writer that sends every cycle, even though the reader takes every cycle too?

- [ ] It can't: equal clocks always give full throughput
- [x] The writer sees the reader's progress several cycles late, so it stops at "full" with words already gone
- [ ] Gray codes slow the pointers down
- [ ] The memory can't read and write at once

::: reveal
The writer sees the read pointer only after it crosses two flip-flops, and the reader sees the write pointer just as late. From a write to the moment the writer learns that word has been read takes about five cycles. A 4-deep FIFO lets only 4 words be outstanding in that time, so the writer idles about one cycle in five: 80% throughput. You'll measure this in the project. It's the credit argument from lesson 36: the depth must cover the round trip.
:::
:::

::: nameit
## The design

- A memory of $D = 2^n$ words, written in the write domain and read in the read domain.
- Pointers of **n + 1 bits**: the low n bits address the memory; the extra bit tells a full FIFO (pointers differ by D) from an empty one (pointers equal).
- Each pointer is kept in **Gray code** and passed through two flip-flops into the other domain.
- **Empty** (read domain): the read pointer equals the synchronized write pointer.
- **Full** (write domain): the write pointer equals the synchronized read pointer with its **top two bits inverted** and the rest equal. In Gray code, adding D to an (n + 1)-bit pointer flips exactly the top two bits.

Both flags are computed from a pointer that's two cycles stale. That makes them pessimistic: the FIFO may report full when a slot has just freed, or empty when a word has just arrived, but never the other way round, so no word is ever lost or invented.

## Metastable sampling

The `Crossing` helper (given in step 3) models one synchronized pointer. `drive(value, t)` records a change in the source domain; `clock(t)` is a sampling edge in the destination domain, after which `q2` holds the synchronized value. If the edge comes less than `window` after the last change, each bit that changed resolves to 0 or 1 at random. With Gray code only one bit ever changes, so the sample is always the old or the new pointer.

## The cycle model

`simulate(n, Tw, Tr, data, wprob, rprob, seed, window)`:

- Write edges at Tw, 2Tw, …; read edges at Tr, 2Tr, …; on a tie, the write edge first.
- At a write edge, if words remain, the FIFO isn't full by `is_full(gray(wb), r_to_w.q2, n)`, and `rng.random() < wprob`: store the next word at `mem[wb % D]`, advance `wb` (mod $2^{n+1}$) and `drive` the new Gray pointer into the write-to-read crossing. Then clock the read-to-write crossing.
- At a read edge, symmetrically: if not empty by `is_empty(w_to_r.q2, gray(rb))` and `rng.random() < rprob`, read `mem[rb % D]`, advance `rb`, drive its crossing; then clock the write-to-read crossing.
- Track the largest occupancy, $(wb - rb) \bmod 2^{n+1}$. Stop when every word has been read (or a generous time limit passes) and return `(words read, largest occupancy, time of the last edge)`.

## The testbench

The tests generate 50 random configurations (depth 2 to 16, clock periods 4 to 17, traffic probabilities, metastability windows) and check that every word comes out once, in order, unchanged, that occupancy never exceeds the depth, that a slow reader lets the FIFO fill, and that a 16-deep FIFO with equal clocks runs at full rate.
:::

::: example
## A FIFO of depth 8 has 4-bit pointers. The write pointer is 11 and the read pointer is 3. Show that the Gray comparison reports full.

::: solution
1. **Occupancy.** The FIFO holds $11 - 3 = 8$ words, its depth.
2. **Write pointer in Gray.** 11 = 1011 becomes
   $$1011 \oplus 0101 = 1110$$
3. **Read pointer in Gray.** 3 = 0011 becomes
   $$0011 \oplus 0001 = 0010$$
4. **Compare.** Inverting the top two bits of 0010 gives 1110, equal to the write pointer's Gray code, so the flag reports full.
5. **Why the extra bit matters.** A comparison of only the low three bits would have called it empty.

**Answer:** the read pointer's Gray code with its top two bits inverted, 1110, matches the write pointer's, so the FIFO reports full with 8 words.
:::
:::

::: example
## With equal clocks of period 10 and full traffic, how long do 300 words take through a 16-deep FIFO, and through a 4-deep one?

::: solution
1. **Depth 16.** The model gives 3020 time units: 302 cycles, one word per cycle after a 2-cycle start-up.
2. **Depth 4.** It takes 3760 units, 376 cycles, so the throughput is
   $$\frac{300}{376} = 80\%$$
   the round-trip limit.
3. **What Gray coding adds here.** In this model a reader that takes one word per edge would also survive a mis-sampled binary pointer, because every change is an increment and a wrong sample is used for a single one-word decision.
4. **Where Gray coding matters.** Real designs that compute a fill level, read in bursts or raise an almost-full flag from the synchronized pointer would act on a value that was never on the counter, so the Gray code is what makes those safe.

**Answer:** 3020 time units (302 cycles) through the 16-deep FIFO, and 3760 (376 cycles, 80% throughput) through the 4-deep one.
:::
:::

::: check
kind: python

## Step 1. Write `gray(b)` and `from_gray(g)`.

```python starter
def gray(b):
    # binary to Gray: each bit XOR the bit above it
    return b

def from_gray(g):
    # Gray to binary: each binary bit is the XOR of all Gray bits at or above it
    return g

print([gray(b) for b in range(8)])
```

```python solution
def gray(b):
    return b ^ (b >> 1)

def from_gray(g):
    b = 0
    while g:
        b ^= g
        g >>= 1
    return b

print([gray(b) for b in range(8)])
```

```python tests
assert [gray(b) for b in (5, 6, 7, 8)] == [7, 5, 4, 12], f"gray(5..8) should be 7, 5, 4, 12; got {[gray(b) for b in (5, 6, 7, 8)]}."
for n in range(1, 11):
    N = 1 << n
    for b in range(N):
        assert from_gray(gray(b)) == b, f"from_gray(gray({b})) should be {b}; got {from_gray(gray(b))}."
        d = gray(b) ^ gray((b + 1) % N)
        assert d and d & (d - 1) == 0, f"gray({b}) and gray({(b + 1) % N}) should differ in exactly one bit."
```

::: right
Right. Converting is a shift and an XOR one way, and a running XOR the other.
:::
:::

::: check
kind: python

## Step 2. Write `is_empty(wg, rg)` and `is_full(wg, rg, n)` on Gray pointers of n + 1 bits.

```python starter
def gray(b):
    return b ^ (b >> 1)

def from_gray(g):
    b = 0
    while g:
        b ^= g
        g >>= 1
    return b

def is_empty(wg, rg):
    # Gray pointers of n + 1 bits
    return False

def is_full(wg, rg, n):
    return False

print(is_full(gray(11), gray(3), 3))
```

```python solution
def gray(b):
    return b ^ (b >> 1)

def from_gray(g):
    b = 0
    while g:
        b ^= g
        g >>= 1
    return b

def is_empty(wg, rg):
    return wg == rg

def is_full(wg, rg, n):
    return wg == rg ^ (3 << (n - 1))

print(is_full(gray(11), gray(3), 3))
```

```python tests
for n in range(1, 6):
    D, N = 1 << n, 1 << (n + 1)
    for wb in range(N):
        for occ in range(D + 1):
            rb = (wb - occ) % N
            assert is_empty(gray(wb), gray(rb)) == (occ == 0), f"Depth {D}: write pointer {wb}, read pointer {rb} is {'empty' if occ == 0 else 'not empty'}."
            assert is_full(gray(wb), gray(rb), n) == (occ == D), f"Depth {D}: write pointer {wb}, read pointer {rb} holds {occ} words, so it's {'full' if occ == D else 'not full'}."
```

::: right
Right. Comparing Gray codes directly saves a decoder in each domain: equal means empty, and equal except the top two bits means full.
:::
:::

::: check
kind: python

## Step 3. Write `simulate(...)`, the cycle model of the asynchronous FIFO.

```python starter
import random

def gray(b):
    return b ^ (b >> 1)

def from_gray(g):
    b = 0
    while g:
        b ^= g
        g >>= 1
    return b

def is_empty(wg, rg):
    return wg == rg

def is_full(wg, rg, n):
    return wg == rg ^ (3 << (n - 1))

class Crossing:
    """A Gray pointer seen from the other clock domain through two flip-flops.
    A sampling edge less than `window` after the pointer changed may catch each
    changed bit either way, as a metastable flip-flop would resolve it."""
    def __init__(self, window, rng):
        self.window, self.rng = window, rng
        self.value = self.prev = 0
        self.t_change = -10**9
        self.q1 = self.q2 = 0
    def drive(self, value, t):
        if value != self.value:
            self.prev, self.value, self.t_change = self.value, value, t
    def clock(self, t):
        v = self.value
        if t - self.t_change < self.window:
            diff, v = self.value ^ self.prev, self.prev
            for bit in range(diff.bit_length()):
                if diff >> bit & 1 and self.rng.random() < 0.5:
                    v ^= 1 << bit
        self.q2, self.q1 = self.q1, v

def simulate(n, Tw, Tr, data, wprob=1.0, rprob=1.0, seed=0, window=0):
    # Return (words read, largest occupancy, time of the last edge).
    return [], 0, 0

print(simulate(3, 7, 11, list(range(20)))[0])
```

```python solution
import random

def gray(b):
    return b ^ (b >> 1)

def from_gray(g):
    b = 0
    while g:
        b ^= g
        g >>= 1
    return b

def is_empty(wg, rg):
    return wg == rg

def is_full(wg, rg, n):
    return wg == rg ^ (3 << (n - 1))

class Crossing:
    """A Gray pointer seen from the other clock domain through two flip-flops.
    A sampling edge less than `window` after the pointer changed may catch each
    changed bit either way, as a metastable flip-flop would resolve it."""
    def __init__(self, window, rng):
        self.window, self.rng = window, rng
        self.value = self.prev = 0
        self.t_change = -10**9
        self.q1 = self.q2 = 0
    def drive(self, value, t):
        if value != self.value:
            self.prev, self.value, self.t_change = self.value, value, t
    def clock(self, t):
        v = self.value
        if t - self.t_change < self.window:
            diff, v = self.value ^ self.prev, self.prev
            for bit in range(diff.bit_length()):
                if diff >> bit & 1 and self.rng.random() < 0.5:
                    v ^= 1 << bit
        self.q2, self.q1 = self.q1, v

def simulate(n, Tw, Tr, data, wprob=1.0, rprob=1.0, seed=0, window=0):
    D = 1 << n
    mask = (1 << (n + 1)) - 1
    rng = random.Random(seed)
    mem = [None] * D
    wb = rb = 0
    w_to_r = Crossing(window, rng)
    r_to_w = Crossing(window, rng)
    out, k, max_occ = [], 0, 0
    tw, tr, t = Tw, Tr, 0
    limit = 100 * (len(data) + 10) * max(Tw, Tr)
    while len(out) < len(data) and min(tw, tr) < limit:
        if tw <= tr:
            t = tw
            if k < len(data) and not is_full(gray(wb), r_to_w.q2, n) and rng.random() < wprob:
                mem[wb % D] = data[k]
                k += 1
                wb = (wb + 1) & mask
                w_to_r.drive(gray(wb), t)
            r_to_w.clock(t)
            tw += Tw
        else:
            t = tr
            if not is_empty(w_to_r.q2, gray(rb)) and rng.random() < rprob:
                out.append(mem[rb % D])
                rb = (rb + 1) & mask
                r_to_w.drive(gray(rb), t)
            w_to_r.clock(t)
            tr += Tr
        max_occ = max(max_occ, (wb - rb) & mask)
    return out, max_occ, t

print(simulate(3, 7, 11, list(range(20)))[0])
```

```python tests
import random
rng = random.Random(2026)
for trial in range(50):
    n = rng.randint(1, 4)
    Tw, Tr = rng.randint(4, 17), rng.randint(4, 17)
    window = rng.randint(0, min(Tw, Tr) // 2)
    wp, rp = rng.choice([1.0, 0.7, 0.4]), rng.choice([1.0, 0.7, 0.4])
    data = [rng.randrange(1 << 16) for _ in range(rng.randint(20, 100))]
    out, occ, t = simulate(n, Tw, Tr, data, wp, rp, seed=trial, window=window)
    where = f"trial {trial} (depth {1 << n}, Tw = {Tw}, Tr = {Tr}, window {window})"
    assert len(out) == len(data), f"In {where}, {len(out)} of {len(data)} words came out."
    bad = next((i for i, (a, b) in enumerate(zip(out, data)) if a != b), None)
    assert bad is None, f"In {where}, word {bad} came out as {out[bad]} instead of {data[bad]}."
    assert occ <= 1 << n, f"In {where}, the FIFO held {occ} words, more than its depth."
out, occ, t = simulate(3, 5, 20, list(range(40)))
assert out == list(range(40)) and occ == 8, f"With a slow reader the FIFO should fill to its depth, 8; it peaked at {occ}."
out, occ, t = simulate(4, 10, 10, list(range(300)))
assert out == list(range(300)) and t <= 3200, f"With equal clocks and depth 16, 300 words should pass in under 3200 time units; took {t}."
```

::: right
Right. Fifty random configurations of depth, clock ratio, traffic and metastability pass without a lost, duplicated or corrupted word, the FIFO fills when the reader is slow, and with enough depth it runs at full rate.
:::
:::

::: explain
## Why are an asynchronous FIFO's full and empty flags safe even though each is computed from a pointer that's two cycles out of date?

::: model
Each domain only ever sees the other domain's pointer as it was a couple of cycles ago, and pointers only move forward. The read domain's copy of the write pointer can be behind the truth but never ahead of it, so when the reader decides the FIFO isn't empty, the words it thinks exist really have been written. Likewise the writer's copy of the read pointer can only lag, so space it thinks is free really has been read. Staleness can only make a flag pessimistic: the FIFO may look full or empty for a cycle or two longer than it is, costing a little throughput, but it can never let a word be read before it's written or overwritten before it's read. The Gray code guarantees each synchronized copy is a value the pointer really had, which keeps that argument true.
:::
:::

::: practice

::: check
given: D = 4 | 16 | 64 | 256
answer: log(D)/log(2) + 1
tolerance: 0.4

## How many bits does each pointer of a {D}-deep asynchronous FIFO need?

::: misses
- [any] Address bits plus one wrap bit.
:::
:::

::: check
given: D = 2 | 3 | 4; R = 5 | 6 | 7
answer: 100*D/R
unit: %
tolerance: 0.5%

## A FIFO's flags take a {R}-cycle round trip between the domains, and it's {D} deep. What fraction of full rate can it sustain?

::: misses
- [any] Depth over round trip.
:::
:::

::: check
given: D = 8 | 16; w = 3 | 9 | 14
answer: w - D + 2*D*step(D - 0.5 - w)
tolerance: 0

## A {D}-deep FIFO's pointers count modulo 2·{D}. The write pointer is {w}. What read pointer makes it exactly full?

::: misses
- [any] The write pointer minus D, modulo 2D.
:::
:::
:::
