-
Notifications
You must be signed in to change notification settings - Fork 166
/
fifo.py
529 lines (451 loc) · 19.6 KB
/
fifo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
"""First-in first-out queues."""
from .. import *
from ..asserts import *
from .._utils import log2_int, deprecated
from .coding import GrayEncoder, GrayDecoder
from .cdc import FFSynchronizer, AsyncFFSynchronizer
__all__ = ["FIFOInterface", "SyncFIFO", "SyncFIFOBuffered", "AsyncFIFO", "AsyncFIFOBuffered"]
class FIFOInterface:
_doc_template = """
{description}
Parameters
----------
width : int
Bit width of data entries.
depth : int
Depth of the queue. If zero, the FIFO cannot be read from or written to.
{parameters}
Attributes
----------
{attributes}
w_data : in, width
Input data.
w_rdy : out
Asserted if there is space in the queue, i.e. ``w_en`` can be asserted to write
a new entry.
w_en : in
Write strobe. Latches ``w_data`` into the queue. Does nothing if ``w_rdy`` is not asserted.
w_level : out
Number of unread entries.
{w_attributes}
r_data : out, width
Output data. {r_data_valid}
r_rdy : out
Asserted if there is an entry in the queue, i.e. ``r_en`` can be asserted to read
an existing entry.
r_en : in
Read strobe. Makes the next entry (if any) available on ``r_data`` at the next cycle.
Does nothing if ``r_rdy`` is not asserted.
r_level : out
Number of unread entries.
{r_attributes}
"""
__doc__ = _doc_template.format(description="""
Data written to the input interface (``w_data``, ``w_rdy``, ``w_en``) is buffered and can be
read at the output interface (``r_data``, ``r_rdy``, ``r_en`). The data entry written first
to the input also appears first on the output.
""",
parameters="",
r_data_valid="The conditions in which ``r_data`` is valid depends on the type of the queue.",
attributes="""
fwft : bool
First-word fallthrough. If set, when ``r_rdy`` rises, the first entry is already
available, i.e. ``r_data`` is valid. Otherwise, after ``r_rdy`` rises, it is necessary
to strobe ``r_en`` for ``r_data`` to become valid.
""".strip(),
w_attributes="",
r_attributes="")
def __init__(self, *, width, depth, fwft):
if not isinstance(width, int) or width < 0:
raise TypeError("FIFO width must be a non-negative integer, not {!r}"
.format(width))
if not isinstance(depth, int) or depth < 0:
raise TypeError("FIFO depth must be a non-negative integer, not {!r}"
.format(depth))
self.width = width
self.depth = depth
self.fwft = fwft
self.w_data = Signal(width, reset_less=True)
self.w_rdy = Signal() # writable; not full
self.w_en = Signal()
self.w_level = Signal(range(depth + 1))
self.r_data = Signal(width, reset_less=True)
self.r_rdy = Signal() # readable; not empty
self.r_en = Signal()
self.r_level = Signal(range(depth + 1))
def _incr(signal, modulo):
if modulo == 2 ** len(signal):
return signal + 1
else:
return Mux(signal == modulo - 1, 0, signal + 1)
class SyncFIFO(Elaboratable, FIFOInterface):
__doc__ = FIFOInterface._doc_template.format(
description="""
Synchronous first in, first out queue.
Read and write interfaces are accessed from the same clock domain. If different clock domains
are needed, use :class:`AsyncFIFO`.
""".strip(),
parameters="""
fwft : bool
First-word fallthrough. If set, when the queue is empty and an entry is written into it,
that entry becomes available on the output on the same clock cycle. Otherwise, it is
necessary to assert ``r_en`` for ``r_data`` to become valid.
""".strip(),
r_data_valid="""
For FWFT queues, valid if ``r_rdy`` is asserted. For non-FWFT queues, valid on the next
cycle after ``r_rdy`` and ``r_en`` have been asserted.
""".strip(),
attributes="",
r_attributes="",
w_attributes="")
def __init__(self, *, width, depth, fwft=True):
super().__init__(width=width, depth=depth, fwft=fwft)
self.level = Signal(range(depth + 1))
def elaborate(self, platform):
m = Module()
if self.depth == 0:
m.d.comb += [
self.w_rdy.eq(0),
self.r_rdy.eq(0),
]
return m
m.d.comb += [
self.w_rdy.eq(self.level != self.depth),
self.r_rdy.eq(self.level != 0),
self.w_level.eq(self.level),
self.r_level.eq(self.level),
]
do_read = self.r_rdy & self.r_en
do_write = self.w_rdy & self.w_en
storage = Memory(width=self.width, depth=self.depth)
w_port = m.submodules.w_port = storage.write_port()
r_port = m.submodules.r_port = storage.read_port(
domain="comb" if self.fwft else "sync", transparent=self.fwft)
produce = Signal(range(self.depth))
consume = Signal(range(self.depth))
m.d.comb += [
w_port.addr.eq(produce),
w_port.data.eq(self.w_data),
w_port.en.eq(self.w_en & self.w_rdy),
]
with m.If(do_write):
m.d.sync += produce.eq(_incr(produce, self.depth))
m.d.comb += [
r_port.addr.eq(consume),
self.r_data.eq(r_port.data),
]
if not self.fwft:
m.d.comb += r_port.en.eq(self.r_en)
with m.If(do_read):
m.d.sync += consume.eq(_incr(consume, self.depth))
with m.If(do_write & ~do_read):
m.d.sync += self.level.eq(self.level + 1)
with m.If(do_read & ~do_write):
m.d.sync += self.level.eq(self.level - 1)
if platform == "formal":
# TODO: move this logic to SymbiYosys
with m.If(Initial()):
m.d.comb += [
Assume(produce < self.depth),
Assume(consume < self.depth),
]
with m.If(produce == consume):
m.d.comb += Assume((self.level == 0) | (self.level == self.depth))
with m.If(produce > consume):
m.d.comb += Assume(self.level == (produce - consume))
with m.If(produce < consume):
m.d.comb += Assume(self.level == (self.depth + produce - consume))
with m.Else():
m.d.comb += [
Assert(produce < self.depth),
Assert(consume < self.depth),
]
with m.If(produce == consume):
m.d.comb += Assert((self.level == 0) | (self.level == self.depth))
with m.If(produce > consume):
m.d.comb += Assert(self.level == (produce - consume))
with m.If(produce < consume):
m.d.comb += Assert(self.level == (self.depth + produce - consume))
return m
class SyncFIFOBuffered(Elaboratable, FIFOInterface):
__doc__ = FIFOInterface._doc_template.format(
description="""
Buffered synchronous first in, first out queue.
This queue's interface is identical to :class:`SyncFIFO` configured as ``fwft=True``, but it
does not use asynchronous memory reads, which are incompatible with FPGA block RAMs.
In exchange, the latency between an entry being written to an empty queue and that entry
becoming available on the output is increased by one cycle compared to :class:`SyncFIFO`.
""".strip(),
parameters="""
fwft : bool
Always set.
""".strip(),
attributes="",
r_data_valid="Valid if ``r_rdy`` is asserted.",
r_attributes="""
level : out
Number of unread entries.
""".strip(),
w_attributes="")
def __init__(self, *, width, depth):
super().__init__(width=width, depth=depth, fwft=True)
self.level = Signal(range(depth + 1))
def elaborate(self, platform):
m = Module()
if self.depth == 0:
m.d.comb += [
self.w_rdy.eq(0),
self.r_rdy.eq(0),
]
return m
# Effectively, this queue treats the output register of the non-FWFT inner queue as
# an additional storage element.
m.submodules.unbuffered = fifo = SyncFIFO(width=self.width, depth=self.depth - 1,
fwft=False)
m.d.comb += [
fifo.w_data.eq(self.w_data),
fifo.w_en.eq(self.w_en),
self.w_rdy.eq(fifo.w_rdy),
]
m.d.comb += [
self.r_data.eq(fifo.r_data),
fifo.r_en.eq(fifo.r_rdy & (~self.r_rdy | self.r_en)),
]
with m.If(fifo.r_en):
m.d.sync += self.r_rdy.eq(1)
with m.Elif(self.r_en):
m.d.sync += self.r_rdy.eq(0)
m.d.comb += [
self.level.eq(fifo.level + self.r_rdy),
self.w_level.eq(self.level),
self.r_level.eq(self.level),
]
return m
class AsyncFIFO(Elaboratable, FIFOInterface):
__doc__ = FIFOInterface._doc_template.format(
description="""
Asynchronous first in, first out queue.
Read and write interfaces are accessed from different clock domains, which can be set when
constructing the FIFO.
:class:`AsyncFIFO` can be reset from the write clock domain. When the write domain reset is
asserted, the FIFO becomes empty. When the read domain is reset, data remains in the FIFO - the
read domain logic should correctly handle this case.
:class:`AsyncFIFO` only supports power of 2 depths. Unless ``exact_depth`` is specified,
the ``depth`` parameter is rounded up to the next power of 2.
""".strip(),
parameters="""
r_domain : str
Read clock domain.
w_domain : str
Write clock domain.
""".strip(),
attributes="""
fwft : bool
Always set.
""".strip(),
r_data_valid="Valid if ``r_rdy`` is asserted.",
r_attributes="""
r_rst : Signal, out
Asserted while the FIFO is being reset by the write-domain reset (for at least one
read-domain clock cycle).
""".strip(),
w_attributes="")
def __init__(self, *, width, depth, r_domain="read", w_domain="write", exact_depth=False):
if depth != 0:
try:
depth_bits = log2_int(depth, need_pow2=exact_depth)
depth = 1 << depth_bits
except ValueError as e:
raise ValueError("AsyncFIFO only supports depths that are powers of 2; requested "
"exact depth {} is not"
.format(depth)) from None
else:
depth_bits = 0
super().__init__(width=width, depth=depth, fwft=True)
self.r_rst = Signal()
self._r_domain = r_domain
self._w_domain = w_domain
self._ctr_bits = depth_bits + 1
def elaborate(self, platform):
m = Module()
if self.depth == 0:
m.d.comb += [
self.w_rdy.eq(0),
self.r_rdy.eq(0),
]
return m
# The design of this queue is the "style #2" from Clifford E. Cummings' paper "Simulation
# and Synthesis Techniques for Asynchronous FIFO Design":
# http://www.sunburst-design.com/papers/CummingsSNUG2002SJ_FIFO1.pdf
do_write = self.w_rdy & self.w_en
do_read = self.r_rdy & self.r_en
# TODO: extract this pattern into lib.cdc.GrayCounter
produce_w_bin = Signal(self._ctr_bits)
produce_w_nxt = Signal(self._ctr_bits)
m.d.comb += produce_w_nxt.eq(produce_w_bin + do_write)
m.d[self._w_domain] += produce_w_bin.eq(produce_w_nxt)
# Note: Both read-domain counters must be reset_less (see comments below)
consume_r_bin = Signal(self._ctr_bits, reset_less=True)
consume_r_nxt = Signal(self._ctr_bits)
m.d.comb += consume_r_nxt.eq(consume_r_bin + do_read)
m.d[self._r_domain] += consume_r_bin.eq(consume_r_nxt)
produce_w_gry = Signal(self._ctr_bits)
produce_r_gry = Signal(self._ctr_bits)
produce_enc = m.submodules.produce_enc = \
GrayEncoder(self._ctr_bits)
produce_cdc = m.submodules.produce_cdc = \
FFSynchronizer(produce_w_gry, produce_r_gry, o_domain=self._r_domain)
m.d.comb += produce_enc.i.eq(produce_w_nxt),
m.d[self._w_domain] += produce_w_gry.eq(produce_enc.o)
consume_r_gry = Signal(self._ctr_bits, reset_less=True)
consume_w_gry = Signal(self._ctr_bits)
consume_enc = m.submodules.consume_enc = \
GrayEncoder(self._ctr_bits)
consume_cdc = m.submodules.consume_cdc = \
FFSynchronizer(consume_r_gry, consume_w_gry, o_domain=self._w_domain)
m.d.comb += consume_enc.i.eq(consume_r_nxt)
m.d[self._r_domain] += consume_r_gry.eq(consume_enc.o)
consume_w_bin = Signal(self._ctr_bits)
consume_dec = m.submodules.consume_dec = \
GrayDecoder(self._ctr_bits)
m.d.comb += consume_dec.i.eq(consume_w_gry),
m.d[self._w_domain] += consume_w_bin.eq(consume_dec.o)
produce_r_bin = Signal(self._ctr_bits)
produce_dec = m.submodules.produce_dec = \
GrayDecoder(self._ctr_bits)
m.d.comb += produce_dec.i.eq(produce_r_gry),
m.d.comb += produce_r_bin.eq(produce_dec.o)
w_full = Signal()
r_empty = Signal()
m.d.comb += [
w_full.eq((produce_w_gry[-1] != consume_w_gry[-1]) &
(produce_w_gry[-2] != consume_w_gry[-2]) &
(produce_w_gry[:-2] == consume_w_gry[:-2])),
r_empty.eq(consume_r_gry == produce_r_gry),
]
m.d[self._w_domain] += self.w_level.eq((produce_w_bin - consume_w_bin))
m.d.comb += self.r_level.eq((produce_r_bin - consume_r_bin))
storage = Memory(width=self.width, depth=self.depth)
w_port = m.submodules.w_port = storage.write_port(domain=self._w_domain)
r_port = m.submodules.r_port = storage.read_port (domain=self._r_domain,
transparent=False)
m.d.comb += [
w_port.addr.eq(produce_w_bin[:-1]),
w_port.data.eq(self.w_data),
w_port.en.eq(do_write),
self.w_rdy.eq(~w_full),
]
m.d.comb += [
r_port.addr.eq(consume_r_nxt[:-1]),
self.r_data.eq(r_port.data),
r_port.en.eq(1),
self.r_rdy.eq(~r_empty),
]
# Reset handling to maintain FIFO and CDC invariants in the presence of a write-domain
# reset.
# There is a CDC hazard associated with resetting an async FIFO - Gray code counters which
# are reset to 0 violate their Gray code invariant. One way to handle this is to ensure
# that both sides of the FIFO are asynchronously reset by the same signal. We adopt a
# slight variation on this approach - reset control rests entirely with the write domain.
# The write domain's reset signal is used to asynchronously reset the read domain's
# counters and force the FIFO to be empty when the write domain's reset is asserted.
# This requires the two read domain counters to be marked as "reset_less", as they are
# reset through another mechanism. See https://github.com/nmigen/nmigen/issues/181 for the
# full discussion.
w_rst = ResetSignal(domain=self._w_domain, allow_reset_less=True)
r_rst = Signal()
# Async-set-sync-release synchronizer avoids CDC hazards
rst_cdc = m.submodules.rst_cdc = \
AsyncFFSynchronizer(w_rst, r_rst, o_domain=self._r_domain)
# Decode Gray code counter synchronized from write domain to overwrite binary
# counter in read domain.
rst_dec = m.submodules.rst_dec = \
GrayDecoder(self._ctr_bits)
m.d.comb += rst_dec.i.eq(produce_r_gry)
with m.If(r_rst):
m.d.comb += r_empty.eq(1)
m.d[self._r_domain] += consume_r_gry.eq(produce_r_gry)
m.d[self._r_domain] += consume_r_bin.eq(rst_dec.o)
m.d[self._r_domain] += self.r_rst.eq(1)
with m.Else():
m.d[self._r_domain] += self.r_rst.eq(0)
if platform == "formal":
with m.If(Initial()):
m.d.comb += Assume(produce_w_gry == (produce_w_bin ^ produce_w_bin[1:]))
m.d.comb += Assume(consume_r_gry == (consume_r_bin ^ consume_r_bin[1:]))
return m
class AsyncFIFOBuffered(Elaboratable, FIFOInterface):
__doc__ = FIFOInterface._doc_template.format(
description="""
Buffered asynchronous first in, first out queue.
Read and write interfaces are accessed from different clock domains, which can be set when
constructing the FIFO.
:class:`AsyncFIFOBuffered` only supports power of 2 plus one depths. Unless ``exact_depth``
is specified, the ``depth`` parameter is rounded up to the next power of 2 plus one.
(The output buffer acts as an additional queue element.)
This queue's interface is identical to :class:`AsyncFIFO`, but it has an additional register
on the output, improving timing in case of block RAM that has large clock-to-output delay.
In exchange, the latency between an entry being written to an empty queue and that entry
becoming available on the output is increased by one cycle compared to :class:`AsyncFIFO`.
""".strip(),
parameters="""
r_domain : str
Read clock domain.
w_domain : str
Write clock domain.
""".strip(),
attributes="""
fwft : bool
Always set.
""".strip(),
r_data_valid="Valid if ``r_rdy`` is asserted.",
r_attributes="""
r_rst : Signal, out
Asserted while the FIFO is being reset by the write-domain reset (for at least one
read-domain clock cycle).
""".strip(),
w_attributes="")
def __init__(self, *, width, depth, r_domain="read", w_domain="write", exact_depth=False):
if depth != 0:
try:
depth_bits = log2_int(max(0, depth - 1), need_pow2=exact_depth)
depth = (1 << depth_bits) + 1
except ValueError as e:
raise ValueError("AsyncFIFOBuffered only supports depths that are one higher "
"than powers of 2; requested exact depth {} is not"
.format(depth)) from None
super().__init__(width=width, depth=depth, fwft=True)
self.r_rst = Signal()
self._r_domain = r_domain
self._w_domain = w_domain
def elaborate(self, platform):
m = Module()
if self.depth == 0:
m.d.comb += [
self.w_rdy.eq(0),
self.r_rdy.eq(0),
]
return m
m.submodules.unbuffered = fifo = AsyncFIFO(width=self.width, depth=self.depth - 1,
r_domain=self._r_domain, w_domain=self._w_domain)
m.d.comb += [
fifo.w_data.eq(self.w_data),
self.w_rdy.eq(fifo.w_rdy),
fifo.w_en.eq(self.w_en),
]
r_consume_buffered = Signal()
m.d.comb += r_consume_buffered.eq(self.r_rdy - self.r_en)
m.d[self._r_domain] += self.r_level.eq(fifo.r_level + r_consume_buffered)
w_consume_buffered = Signal()
m.submodules.consume_buffered_cdc = AsyncFFSynchronizer(r_consume_buffered, w_consume_buffered, o_domain=self._w_domain)
m.d.comb += self.w_level.eq(fifo.w_level + w_consume_buffered)
with m.If(self.r_en | ~self.r_rdy):
m.d[self._r_domain] += [
self.r_data.eq(fifo.r_data),
self.r_rdy.eq(fifo.r_rdy),
self.r_rst.eq(fifo.r_rst),
]
m.d.comb += [
fifo.r_en.eq(1)
]
return m