add flatten function
[ieee754fpu.git] / src / add / singlepipe.py
1 """ Pipeline and BufferedHandshake implementation, conforming to the same API.
2 For multi-input and multi-output variants, see multipipe.
3
4 eq:
5 --
6
7 a strategically very important function that is identical in function
8 to nmigen's Signal.eq function, except it may take objects, or a list
9 of objects, or a tuple of objects, and where objects may also be
10 Records.
11
12 Stage API:
13 ---------
14
15 stage requires compliance with a strict API that may be
16 implemented in several means, including as a static class.
17 the methods of a stage instance must be as follows:
18
19 * ispec() - Input data format specification
20 returns an object or a list or tuple of objects, or
21 a Record, each object having an "eq" function which
22 takes responsibility for copying by assignment all
23 sub-objects
24 * ospec() - Output data format specification
25 requirements as for ospec
26 * process(m, i) - Processes an ispec-formatted object
27 returns a combinatorial block of a result that
28 may be assigned to the output, by way of the "eq"
29 function
30 * setup(m, i) - Optional function for setting up submodules
31 may be used for more complex stages, to link
32 the input (i) to submodules. must take responsibility
33 for adding those submodules to the module (m).
34 the submodules must be combinatorial blocks and
35 must have their inputs and output linked combinatorially.
36
37 Both StageCls (for use with non-static classes) and Stage (for use
38 by static classes) are abstract classes from which, for convenience
39 and as a courtesy to other developers, anything conforming to the
40 Stage API may *choose* to derive.
41
42 StageChain:
43 ----------
44
45 A useful combinatorial wrapper around stages that chains them together
46 and then presents a Stage-API-conformant interface. By presenting
47 the same API as the stages it wraps, it can clearly be used recursively.
48
49 RecordBasedStage:
50 ----------------
51
52 A convenience class that takes an input shape, output shape, a
53 "processing" function and an optional "setup" function. Honestly
54 though, there's not much more effort to just... create a class
55 that returns a couple of Records (see ExampleAddRecordStage in
56 examples).
57
58 PassThroughStage:
59 ----------------
60
61 A convenience class that takes a single function as a parameter,
62 that is chain-called to create the exact same input and output spec.
63 It has a process() function that simply returns its input.
64
65 Instances of this class are completely redundant if handed to
66 StageChain, however when passed to UnbufferedPipeline they
67 can be used to introduce a single clock delay.
68
69 ControlBase:
70 -----------
71
72 The base class for pipelines. Contains previous and next ready/valid/data.
73 Also has an extremely useful "connect" function that can be used to
74 connect a chain of pipelines and present the exact same prev/next
75 ready/valid/data API.
76
77 UnbufferedPipeline:
78 ------------------
79
80 A simple stalling clock-synchronised pipeline that has no buffering
81 (unlike BufferedHandshake). Data flows on *every* clock cycle when
82 the conditions are right (this is nominally when the input is valid
83 and the output is ready).
84
85 A stall anywhere along the line will result in a stall back-propagating
86 down the entire chain. The BufferedHandshake by contrast will buffer
87 incoming data, allowing previous stages one clock cycle's grace before
88 also having to stall.
89
90 An advantage of the UnbufferedPipeline over the Buffered one is
91 that the amount of logic needed (number of gates) is greatly
92 reduced (no second set of buffers basically)
93
94 The disadvantage of the UnbufferedPipeline is that the valid/ready
95 logic, if chained together, is *combinatorial*, resulting in
96 progressively larger gate delay.
97
98 PassThroughHandshake:
99 ------------------
100
101 A Control class that introduces a single clock delay, passing its
102 data through unaltered. Unlike RegisterPipeline (which relies
103 on UnbufferedPipeline and PassThroughStage) it handles ready/valid
104 itself.
105
106 RegisterPipeline:
107 ----------------
108
109 A convenience class that, because UnbufferedPipeline introduces a single
110 clock delay, when its stage is a PassThroughStage, it results in a Pipeline
111 stage that, duh, delays its (unmodified) input by one clock cycle.
112
113 BufferedHandshake:
114 ----------------
115
116 nmigen implementation of buffered pipeline stage, based on zipcpu:
117 https://zipcpu.com/blog/2017/08/14/strategies-for-pipelining.html
118
119 this module requires quite a bit of thought to understand how it works
120 (and why it is needed in the first place). reading the above is
121 *strongly* recommended.
122
123 unlike john dawson's IEEE754 FPU STB/ACK signalling, which requires
124 the STB / ACK signals to raise and lower (on separate clocks) before
125 data may proceeed (thus only allowing one piece of data to proceed
126 on *ALTERNATE* cycles), the signalling here is a true pipeline
127 where data will flow on *every* clock when the conditions are right.
128
129 input acceptance conditions are when:
130 * incoming previous-stage strobe (p.i_valid) is HIGH
131 * outgoing previous-stage ready (p.o_ready) is LOW
132
133 output transmission conditions are when:
134 * outgoing next-stage strobe (n.o_valid) is HIGH
135 * outgoing next-stage ready (n.i_ready) is LOW
136
137 the tricky bit is when the input has valid data and the output is not
138 ready to accept it. if it wasn't for the clock synchronisation, it
139 would be possible to tell the input "hey don't send that data, we're
140 not ready". unfortunately, it's not possible to "change the past":
141 the previous stage *has no choice* but to pass on its data.
142
143 therefore, the incoming data *must* be accepted - and stored: that
144 is the responsibility / contract that this stage *must* accept.
145 on the same clock, it's possible to tell the input that it must
146 not send any more data. this is the "stall" condition.
147
148 we now effectively have *two* possible pieces of data to "choose" from:
149 the buffered data, and the incoming data. the decision as to which
150 to process and output is based on whether we are in "stall" or not.
151 i.e. when the next stage is no longer ready, the output comes from
152 the buffer if a stall had previously occurred, otherwise it comes
153 direct from processing the input.
154
155 this allows us to respect a synchronous "travelling STB" with what
156 dan calls a "buffered handshake".
157
158 it's quite a complex state machine!
159
160 SimpleHandshake
161 ---------------
162
163 Synchronised pipeline, Based on:
164 https://github.com/ZipCPU/dbgbus/blob/master/hexbus/rtl/hbdeword.v
165 """
166
167 from nmigen import Signal, Cat, Const, Mux, Module, Value
168 from nmigen.cli import verilog, rtlil
169 from nmigen.lib.fifo import SyncFIFO
170 from nmigen.hdl.ast import ArrayProxy
171 from nmigen.hdl.rec import Record, Layout
172
173 from abc import ABCMeta, abstractmethod
174 from collections.abc import Sequence
175
176
177 class PrevControl:
178 """ contains signals that come *from* the previous stage (both in and out)
179 * i_valid: previous stage indicating all incoming data is valid.
180 may be a multi-bit signal, where all bits are required
181 to be asserted to indicate "valid".
182 * o_ready: output to next stage indicating readiness to accept data
183 * i_data : an input - added by the user of this class
184 """
185
186 def __init__(self, i_width=1, stage_ctl=False):
187 self.stage_ctl = stage_ctl
188 self.i_valid = Signal(i_width, name="p_i_valid") # prev >>in self
189 self._o_ready = Signal(name="p_o_ready") # prev <<out self
190 self.i_data = None # XXX MUST BE ADDED BY USER
191 if stage_ctl:
192 self.s_o_ready = Signal(name="p_s_o_rdy") # prev <<out self
193
194 @property
195 def o_ready(self):
196 """ public-facing API: indicates (externally) that stage is ready
197 """
198 if self.stage_ctl:
199 return self.s_o_ready # set dynamically by stage
200 return self._o_ready # return this when not under dynamic control
201
202 def _connect_in(self, prev, direct=False):
203 """ internal helper function to connect stage to an input source.
204 do not use to connect stage-to-stage!
205 """
206 if direct:
207 i_valid = prev.i_valid
208 else:
209 i_valid = prev.i_valid_test
210 return [self.i_valid.eq(i_valid),
211 prev.o_ready.eq(self.o_ready),
212 eq(self.i_data, prev.i_data),
213 ]
214
215 @property
216 def i_valid_test(self):
217 vlen = len(self.i_valid)
218 if vlen > 1:
219 # multi-bit case: valid only when i_valid is all 1s
220 all1s = Const(-1, (len(self.i_valid), False))
221 i_valid = (self.i_valid == all1s)
222 else:
223 # single-bit i_valid case
224 i_valid = self.i_valid
225
226 # when stage indicates not ready, incoming data
227 # must "appear" to be not ready too
228 if self.stage_ctl:
229 i_valid = i_valid & self.s_o_ready
230
231 return i_valid
232
233
234 class NextControl:
235 """ contains the signals that go *to* the next stage (both in and out)
236 * o_valid: output indicating to next stage that data is valid
237 * i_ready: input from next stage indicating that it can accept data
238 * o_data : an output - added by the user of this class
239 """
240 def __init__(self, stage_ctl=False):
241 self.stage_ctl = stage_ctl
242 self.o_valid = Signal(name="n_o_valid") # self out>> next
243 self.i_ready = Signal(name="n_i_ready") # self <<in next
244 self.o_data = None # XXX MUST BE ADDED BY USER
245 #if self.stage_ctl:
246 self.d_valid = Signal(reset=1) # INTERNAL (data valid)
247
248 @property
249 def i_ready_test(self):
250 if self.stage_ctl:
251 return self.i_ready & self.d_valid
252 return self.i_ready
253
254 def connect_to_next(self, nxt):
255 """ helper function to connect to the next stage data/valid/ready.
256 data/valid is passed *TO* nxt, and ready comes *IN* from nxt.
257 use this when connecting stage-to-stage
258 """
259 return [nxt.i_valid.eq(self.o_valid),
260 self.i_ready.eq(nxt.o_ready),
261 eq(nxt.i_data, self.o_data),
262 ]
263
264 def _connect_out(self, nxt, direct=False):
265 """ internal helper function to connect stage to an output source.
266 do not use to connect stage-to-stage!
267 """
268 if direct:
269 i_ready = nxt.i_ready
270 else:
271 i_ready = nxt.i_ready_test
272 return [nxt.o_valid.eq(self.o_valid),
273 self.i_ready.eq(i_ready),
274 eq(nxt.o_data, self.o_data),
275 ]
276
277
278 class Visitor:
279 """ a helper routine which identifies if it is being passed a list
280 (or tuple) of objects, or signals, or Records, and calls
281 a visitor function.
282
283 the visiting fn is called when an object is identified.
284
285 Record is a special (unusual, recursive) case, where the input may be
286 specified as a dictionary (which may contain further dictionaries,
287 recursively), where the field names of the dictionary must match
288 the Record's field spec. Alternatively, an object with the same
289 member names as the Record may be assigned: it does not have to
290 *be* a Record.
291
292 ArrayProxy is also special-cased, it's a bit messy: whilst ArrayProxy
293 has an eq function, the object being assigned to it (e.g. a python
294 object) might not. despite the *input* having an eq function,
295 that doesn't help us, because it's the *ArrayProxy* that's being
296 assigned to. so.... we cheat. use the ports() function of the
297 python object, enumerate them, find out the list of Signals that way,
298 and assign them.
299 """
300 def visit(self, o, i, act):
301 if isinstance(o, dict):
302 return self.dict_visit(o, i, act)
303
304 res = act.prepare()
305 if not isinstance(o, Sequence):
306 o, i = [o], [i]
307 for (ao, ai) in zip(o, i):
308 #print ("visit", fn, ao, ai)
309 if isinstance(ao, Record):
310 rres = self.record_visit(ao, ai, act)
311 elif isinstance(ao, ArrayProxy) and not isinstance(ai, Value):
312 rres = self.arrayproxy_visit(ao, ai, act)
313 else:
314 rres = act.fn(ao, ai)
315 res += rres
316 return res
317
318 def dict_visit(self, o, i, act):
319 res = act.prepare()
320 for (k, v) in o.items():
321 print ("d-eq", v, i[k])
322 res.append(act.fn(v, i[k]))
323 return res
324
325 def record_visit(self, ao, ai, act):
326 res = act.prepare()
327 for idx, (field_name, field_shape, _) in enumerate(ao.layout):
328 if isinstance(field_shape, Layout):
329 val = ai.fields
330 else:
331 val = ai
332 if hasattr(val, field_name): # check for attribute
333 val = getattr(val, field_name)
334 else:
335 val = val[field_name] # dictionary-style specification
336 val = self.visit(ao.fields[field_name], val, act)
337 if isinstance(val, Sequence):
338 rres += val
339 else:
340 rres.append(val)
341 return res
342
343 def arrayproxy_visit(self, ao, ai, act):
344 res = act.prepare()
345 for p in ai.ports():
346 op = getattr(ao, p.name)
347 #print (op, p, p.name)
348 res.append(fn(op, p))
349 return res
350
351
352 class Eq(Visitor):
353 def __init__(self):
354 self.res = []
355 def prepare(self):
356 return []
357 def fn(self, o, i):
358 rres = o.eq(i)
359 if not isinstance(rres, Sequence):
360 rres = [rres]
361 return rres
362 def __call__(self, o, i):
363 return self.visit(o, i, self)
364
365
366 def eq(o, i):
367 """ makes signals equal: a helper routine which identifies if it is being
368 passed a list (or tuple) of objects, or signals, or Records, and calls
369 the objects' eq function.
370 """
371 return Eq()(o, i)
372
373
374 def flatten(i):
375 """ flattens a compound structure recursively using Cat
376 """
377 if not isinstance(i, Sequence):
378 i = [i]
379 res = []
380 for ai in i:
381 print ("flatten", ai)
382 if isinstance(ai, Record):
383 print ("record", list(ai.layout))
384 rres = []
385 for idx, (field_name, field_shape, _) in enumerate(ai.layout):
386 if isinstance(field_shape, Layout):
387 val = ai.fields
388 else:
389 val = ai
390 if hasattr(val, field_name): # check for attribute
391 val = getattr(val, field_name)
392 else:
393 val = val[field_name] # dictionary-style specification
394 print ("recidx", idx, field_name, field_shape, val)
395 val = flatten(val)
396 print ("recidx flat", idx, val)
397 if isinstance(val, Sequence):
398 rres += val
399 else:
400 rres.append(val)
401
402 elif isinstance(ai, ArrayProxy) and not isinstance(ai, Value):
403 rres = []
404 for p in ai.ports():
405 op = getattr(ai, p.name)
406 #print (op, p, p.name)
407 rres.append(flatten(p))
408 else:
409 rres = ai
410 if not isinstance(rres, Sequence):
411 rres = [rres]
412 res += rres
413 print ("flatten res", res)
414 return Cat(*res)
415
416
417
418 class StageCls(metaclass=ABCMeta):
419 """ Class-based "Stage" API. requires instantiation (after derivation)
420
421 see "Stage API" above.. Note: python does *not* require derivation
422 from this class. All that is required is that the pipelines *have*
423 the functions listed in this class. Derivation from this class
424 is therefore merely a "courtesy" to maintainers.
425 """
426 @abstractmethod
427 def ispec(self): pass # REQUIRED
428 @abstractmethod
429 def ospec(self): pass # REQUIRED
430 #@abstractmethod
431 #def setup(self, m, i): pass # OPTIONAL
432 @abstractmethod
433 def process(self, i): pass # REQUIRED
434
435
436 class Stage(metaclass=ABCMeta):
437 """ Static "Stage" API. does not require instantiation (after derivation)
438
439 see "Stage API" above. Note: python does *not* require derivation
440 from this class. All that is required is that the pipelines *have*
441 the functions listed in this class. Derivation from this class
442 is therefore merely a "courtesy" to maintainers.
443 """
444 @staticmethod
445 @abstractmethod
446 def ispec(): pass
447
448 @staticmethod
449 @abstractmethod
450 def ospec(): pass
451
452 #@staticmethod
453 #@abstractmethod
454 #def setup(m, i): pass
455
456 @staticmethod
457 @abstractmethod
458 def process(i): pass
459
460
461 class RecordBasedStage(Stage):
462 """ convenience class which provides a Records-based layout.
463 honestly it's a lot easier just to create a direct Records-based
464 class (see ExampleAddRecordStage)
465 """
466 def __init__(self, in_shape, out_shape, processfn, setupfn=None):
467 self.in_shape = in_shape
468 self.out_shape = out_shape
469 self.__process = processfn
470 self.__setup = setupfn
471 def ispec(self): return Record(self.in_shape)
472 def ospec(self): return Record(self.out_shape)
473 def process(seif, i): return self.__process(i)
474 def setup(seif, m, i): return self.__setup(m, i)
475
476
477 class StageChain(StageCls):
478 """ pass in a list of stages, and they will automatically be
479 chained together via their input and output specs into a
480 combinatorial chain.
481
482 the end result basically conforms to the exact same Stage API.
483
484 * input to this class will be the input of the first stage
485 * output of first stage goes into input of second
486 * output of second goes into input into third (etc. etc.)
487 * the output of this class will be the output of the last stage
488 """
489 def __init__(self, chain, specallocate=False):
490 self.chain = chain
491 self.specallocate = specallocate
492
493 def ispec(self):
494 return self.chain[0].ispec()
495
496 def ospec(self):
497 return self.chain[-1].ospec()
498
499 def _specallocate_setup(self, m, i):
500 for (idx, c) in enumerate(self.chain):
501 if hasattr(c, "setup"):
502 c.setup(m, i) # stage may have some module stuff
503 o = self.chain[idx].ospec() # last assignment survives
504 m.d.comb += eq(o, c.process(i)) # process input into "o"
505 if idx == len(self.chain)-1:
506 break
507 i = self.chain[idx+1].ispec() # new input on next loop
508 m.d.comb += eq(i, o) # assign to next input
509 return o # last loop is the output
510
511 def _noallocate_setup(self, m, i):
512 for (idx, c) in enumerate(self.chain):
513 if hasattr(c, "setup"):
514 c.setup(m, i) # stage may have some module stuff
515 i = o = c.process(i) # store input into "o"
516 return o # last loop is the output
517
518 def setup(self, m, i):
519 if self.specallocate:
520 self.o = self._specallocate_setup(m, i)
521 else:
522 self.o = self._noallocate_setup(m, i)
523
524 def process(self, i):
525 return self.o # conform to Stage API: return last-loop output
526
527
528 class ControlBase:
529 """ Common functions for Pipeline API
530 """
531 def __init__(self, stage=None, in_multi=None, stage_ctl=False):
532 """ Base class containing ready/valid/data to previous and next stages
533
534 * p: contains ready/valid to the previous stage
535 * n: contains ready/valid to the next stage
536
537 Except when calling Controlbase.connect(), user must also:
538 * add i_data member to PrevControl (p) and
539 * add o_data member to NextControl (n)
540 """
541 self.stage = stage
542
543 # set up input and output IO ACK (prev/next ready/valid)
544 self.p = PrevControl(in_multi, stage_ctl)
545 self.n = NextControl(stage_ctl)
546
547 # set up the input and output data
548 if stage is not None:
549 self.p.i_data = stage.ispec() # input type
550 self.n.o_data = stage.ospec()
551
552 def connect_to_next(self, nxt):
553 """ helper function to connect to the next stage data/valid/ready.
554 """
555 return self.n.connect_to_next(nxt.p)
556
557 def _connect_in(self, prev):
558 """ internal helper function to connect stage to an input source.
559 do not use to connect stage-to-stage!
560 """
561 return self.p._connect_in(prev.p)
562
563 def _connect_out(self, nxt):
564 """ internal helper function to connect stage to an output source.
565 do not use to connect stage-to-stage!
566 """
567 return self.n._connect_out(nxt.n)
568
569 def connect(self, pipechain):
570 """ connects a chain (list) of Pipeline instances together and
571 links them to this ControlBase instance:
572
573 in <----> self <---> out
574 | ^
575 v |
576 [pipe1, pipe2, pipe3, pipe4]
577 | ^ | ^ | ^
578 v | v | v |
579 out---in out--in out---in
580
581 Also takes care of allocating i_data/o_data, by looking up
582 the data spec for each end of the pipechain. i.e It is NOT
583 necessary to allocate self.p.i_data or self.n.o_data manually:
584 this is handled AUTOMATICALLY, here.
585
586 Basically this function is the direct equivalent of StageChain,
587 except that unlike StageChain, the Pipeline logic is followed.
588
589 Just as StageChain presents an object that conforms to the
590 Stage API from a list of objects that also conform to the
591 Stage API, an object that calls this Pipeline connect function
592 has the exact same pipeline API as the list of pipline objects
593 it is called with.
594
595 Thus it becomes possible to build up larger chains recursively.
596 More complex chains (multi-input, multi-output) will have to be
597 done manually.
598 """
599 eqs = [] # collated list of assignment statements
600
601 # connect inter-chain
602 for i in range(len(pipechain)-1):
603 pipe1 = pipechain[i]
604 pipe2 = pipechain[i+1]
605 eqs += pipe1.connect_to_next(pipe2)
606
607 # connect front of chain to ourselves
608 front = pipechain[0]
609 self.p.i_data = front.stage.ispec()
610 eqs += front._connect_in(self)
611
612 # connect end of chain to ourselves
613 end = pipechain[-1]
614 self.n.o_data = end.stage.ospec()
615 eqs += end._connect_out(self)
616
617 return eqs
618
619 def set_input(self, i):
620 """ helper function to set the input data
621 """
622 return eq(self.p.i_data, i)
623
624 def ports(self):
625 res = [self.p.i_valid, self.n.i_ready,
626 self.n.o_valid, self.p.o_ready,
627 ]
628 if hasattr(self.p.i_data, "ports"):
629 res += self.p.i_data.ports()
630 else:
631 res += self.p.i_data
632 if hasattr(self.n.o_data, "ports"):
633 res += self.n.o_data.ports()
634 else:
635 res += self.n.o_data
636 return res
637
638 def _elaborate(self, platform):
639 """ handles case where stage has dynamic ready/valid functions
640 """
641 m = Module()
642
643 if self.stage is not None and hasattr(self.stage, "setup"):
644 self.stage.setup(m, self.p.i_data)
645
646 if not self.p.stage_ctl:
647 return m
648
649 # intercept the previous (outgoing) "ready", combine with stage ready
650 m.d.comb += self.p.s_o_ready.eq(self.p._o_ready & self.stage.d_ready)
651
652 # intercept the next (incoming) "ready" and combine it with data valid
653 sdv = self.stage.d_valid(self.n.i_ready)
654 m.d.comb += self.n.d_valid.eq(self.n.i_ready & sdv)
655
656 return m
657
658
659 class BufferedHandshake(ControlBase):
660 """ buffered pipeline stage. data and strobe signals travel in sync.
661 if ever the input is ready and the output is not, processed data
662 is shunted in a temporary register.
663
664 Argument: stage. see Stage API above
665
666 stage-1 p.i_valid >>in stage n.o_valid out>> stage+1
667 stage-1 p.o_ready <<out stage n.i_ready <<in stage+1
668 stage-1 p.i_data >>in stage n.o_data out>> stage+1
669 | |
670 process --->----^
671 | |
672 +-- r_data ->-+
673
674 input data p.i_data is read (only), is processed and goes into an
675 intermediate result store [process()]. this is updated combinatorially.
676
677 in a non-stall condition, the intermediate result will go into the
678 output (update_output). however if ever there is a stall, it goes
679 into r_data instead [update_buffer()].
680
681 when the non-stall condition is released, r_data is the first
682 to be transferred to the output [flush_buffer()], and the stall
683 condition cleared.
684
685 on the next cycle (as long as stall is not raised again) the
686 input may begin to be processed and transferred directly to output.
687 """
688
689 def elaborate(self, platform):
690 self.m = ControlBase._elaborate(self, platform)
691
692 result = self.stage.ospec()
693 r_data = self.stage.ospec()
694
695 # establish some combinatorial temporaries
696 o_n_validn = Signal(reset_less=True)
697 n_i_ready = Signal(reset_less=True, name="n_i_rdy_data")
698 nir_por = Signal(reset_less=True)
699 nir_por_n = Signal(reset_less=True)
700 p_i_valid = Signal(reset_less=True)
701 nir_novn = Signal(reset_less=True)
702 nirn_novn = Signal(reset_less=True)
703 por_pivn = Signal(reset_less=True)
704 npnn = Signal(reset_less=True)
705 self.m.d.comb += [p_i_valid.eq(self.p.i_valid_test),
706 o_n_validn.eq(~self.n.o_valid),
707 n_i_ready.eq(self.n.i_ready_test),
708 nir_por.eq(n_i_ready & self.p._o_ready),
709 nir_por_n.eq(n_i_ready & ~self.p._o_ready),
710 nir_novn.eq(n_i_ready | o_n_validn),
711 nirn_novn.eq(~n_i_ready & o_n_validn),
712 npnn.eq(nir_por | nirn_novn),
713 por_pivn.eq(self.p._o_ready & ~p_i_valid)
714 ]
715
716 # store result of processing in combinatorial temporary
717 self.m.d.comb += eq(result, self.stage.process(self.p.i_data))
718
719 # if not in stall condition, update the temporary register
720 with self.m.If(self.p.o_ready): # not stalled
721 self.m.d.sync += eq(r_data, result) # update buffer
722
723 # data pass-through conditions
724 with self.m.If(npnn):
725 self.m.d.sync += [self.n.o_valid.eq(p_i_valid), # valid if p_valid
726 eq(self.n.o_data, result), # update output
727 ]
728 # buffer flush conditions (NOTE: can override data passthru conditions)
729 with self.m.If(nir_por_n): # not stalled
730 # Flush the [already processed] buffer to the output port.
731 self.m.d.sync += [self.n.o_valid.eq(1), # reg empty
732 eq(self.n.o_data, r_data), # flush buffer
733 ]
734 # output ready conditions
735 self.m.d.sync += self.p._o_ready.eq(nir_novn | por_pivn)
736
737 return self.m
738
739
740 class SimpleHandshake(ControlBase):
741 """ simple handshake control. data and strobe signals travel in sync.
742 implements the protocol used by Wishbone and AXI4.
743
744 Argument: stage. see Stage API above
745
746 stage-1 p.i_valid >>in stage n.o_valid out>> stage+1
747 stage-1 p.o_ready <<out stage n.i_ready <<in stage+1
748 stage-1 p.i_data >>in stage n.o_data out>> stage+1
749 | |
750 +--process->--^
751 Truth Table
752
753 Inputs Temporary Output
754 ------- ---------- -----
755 P P N N PiV& ~NiV& N P
756 i o i o PoR NoV o o
757 V R R V V R
758
759 ------- - - - -
760 0 0 0 0 0 0 >0 0
761 0 0 0 1 0 1 >1 0
762 0 0 1 0 0 0 0 1
763 0 0 1 1 0 0 0 1
764 ------- - - - -
765 0 1 0 0 0 0 >0 0
766 0 1 0 1 0 1 >1 0
767 0 1 1 0 0 0 0 1
768 0 1 1 1 0 0 0 1
769 ------- - - - -
770 1 0 0 0 0 0 >0 0
771 1 0 0 1 0 1 >1 0
772 1 0 1 0 0 0 0 1
773 1 0 1 1 0 0 0 1
774 ------- - - - -
775 1 1 0 0 1 0 1 0
776 1 1 0 1 1 1 1 0
777 1 1 1 0 1 0 1 1
778 1 1 1 1 1 0 1 1
779 ------- - - - -
780 """
781
782 def elaborate(self, platform):
783 self.m = m = ControlBase._elaborate(self, platform)
784
785 r_busy = Signal()
786 result = self.stage.ospec()
787
788 # establish some combinatorial temporaries
789 n_i_ready = Signal(reset_less=True, name="n_i_rdy_data")
790 p_i_valid_p_o_ready = Signal(reset_less=True)
791 p_i_valid = Signal(reset_less=True)
792 m.d.comb += [p_i_valid.eq(self.p.i_valid_test),
793 n_i_ready.eq(self.n.i_ready_test),
794 p_i_valid_p_o_ready.eq(p_i_valid & self.p.o_ready),
795 ]
796
797 # store result of processing in combinatorial temporary
798 m.d.comb += eq(result, self.stage.process(self.p.i_data))
799
800 # previous valid and ready
801 with m.If(p_i_valid_p_o_ready):
802 m.d.sync += [r_busy.eq(1), # output valid
803 eq(self.n.o_data, result), # update output
804 ]
805 # previous invalid or not ready, however next is accepting
806 with m.Elif(n_i_ready):
807 m.d.sync += [eq(self.n.o_data, result)]
808 # TODO: could still send data here (if there was any)
809 #m.d.sync += self.n.o_valid.eq(0) # ...so set output invalid
810 m.d.sync += r_busy.eq(0) # ...so set output invalid
811
812 m.d.comb += self.n.o_valid.eq(r_busy)
813 # if next is ready, so is previous
814 m.d.comb += self.p._o_ready.eq(n_i_ready)
815
816 return self.m
817
818
819 class UnbufferedPipeline(ControlBase):
820 """ A simple pipeline stage with single-clock synchronisation
821 and two-way valid/ready synchronised signalling.
822
823 Note that a stall in one stage will result in the entire pipeline
824 chain stalling.
825
826 Also that unlike BufferedHandshake, the valid/ready signalling does NOT
827 travel synchronously with the data: the valid/ready signalling
828 combines in a *combinatorial* fashion. Therefore, a long pipeline
829 chain will lengthen propagation delays.
830
831 Argument: stage. see Stage API, above
832
833 stage-1 p.i_valid >>in stage n.o_valid out>> stage+1
834 stage-1 p.o_ready <<out stage n.i_ready <<in stage+1
835 stage-1 p.i_data >>in stage n.o_data out>> stage+1
836 | |
837 r_data result
838 | |
839 +--process ->-+
840
841 Attributes:
842 -----------
843 p.i_data : StageInput, shaped according to ispec
844 The pipeline input
845 p.o_data : StageOutput, shaped according to ospec
846 The pipeline output
847 r_data : input_shape according to ispec
848 A temporary (buffered) copy of a prior (valid) input.
849 This is HELD if the output is not ready. It is updated
850 SYNCHRONOUSLY.
851 result: output_shape according to ospec
852 The output of the combinatorial logic. it is updated
853 COMBINATORIALLY (no clock dependence).
854
855 Truth Table
856
857 Inputs Temp Output
858 ------- - -----
859 P P N N ~NiR& N P
860 i o i o NoV o o
861 V R R V V R
862
863 ------- - - -
864 0 0 0 0 0 0 1
865 0 0 0 1 1 1 0
866 0 0 1 0 0 0 1
867 0 0 1 1 0 0 1
868 ------- - - -
869 0 1 0 0 0 0 1
870 0 1 0 1 1 1 0
871 0 1 1 0 0 0 1
872 0 1 1 1 0 0 1
873 ------- - - -
874 1 0 0 0 0 1 1
875 1 0 0 1 1 1 0
876 1 0 1 0 0 1 1
877 1 0 1 1 0 1 1
878 ------- - - -
879 1 1 0 0 0 1 1
880 1 1 0 1 1 1 0
881 1 1 1 0 0 1 1
882 1 1 1 1 0 1 1
883 ------- - - -
884
885 Note: PoR is *NOT* involved in the above decision-making.
886 """
887
888 def elaborate(self, platform):
889 self.m = m = ControlBase._elaborate(self, platform)
890
891 data_valid = Signal() # is data valid or not
892 r_data = self.stage.ospec() # output type
893
894 # some temporaries
895 p_i_valid = Signal(reset_less=True)
896 pv = Signal(reset_less=True)
897 m.d.comb += p_i_valid.eq(self.p.i_valid_test)
898 m.d.comb += pv.eq(self.p.i_valid & self.p.o_ready)
899
900 m.d.comb += self.n.o_valid.eq(data_valid)
901 m.d.comb += self.p._o_ready.eq(~data_valid | self.n.i_ready_test)
902 m.d.sync += data_valid.eq(p_i_valid | \
903 (~self.n.i_ready_test & data_valid))
904 with m.If(pv):
905 m.d.sync += eq(r_data, self.stage.process(self.p.i_data))
906 m.d.comb += eq(self.n.o_data, r_data)
907
908 return self.m
909
910
911 class UnbufferedPipeline2(ControlBase):
912 """ A simple pipeline stage with single-clock synchronisation
913 and two-way valid/ready synchronised signalling.
914
915 Note that a stall in one stage will result in the entire pipeline
916 chain stalling.
917
918 Also that unlike BufferedHandshake, the valid/ready signalling does NOT
919 travel synchronously with the data: the valid/ready signalling
920 combines in a *combinatorial* fashion. Therefore, a long pipeline
921 chain will lengthen propagation delays.
922
923 Argument: stage. see Stage API, above
924
925 stage-1 p.i_valid >>in stage n.o_valid out>> stage+1
926 stage-1 p.o_ready <<out stage n.i_ready <<in stage+1
927 stage-1 p.i_data >>in stage n.o_data out>> stage+1
928 | | |
929 +- process-> buf <-+
930 Attributes:
931 -----------
932 p.i_data : StageInput, shaped according to ispec
933 The pipeline input
934 p.o_data : StageOutput, shaped according to ospec
935 The pipeline output
936 buf : output_shape according to ospec
937 A temporary (buffered) copy of a valid output
938 This is HELD if the output is not ready. It is updated
939 SYNCHRONOUSLY.
940 """
941
942 def elaborate(self, platform):
943 self.m = m = ControlBase._elaborate(self, platform)
944
945 buf_full = Signal() # is data valid or not
946 buf = self.stage.ospec() # output type
947
948 # some temporaries
949 p_i_valid = Signal(reset_less=True)
950 m.d.comb += p_i_valid.eq(self.p.i_valid_test)
951
952 m.d.comb += self.n.o_valid.eq(buf_full | p_i_valid)
953 m.d.comb += self.p._o_ready.eq(~buf_full)
954 m.d.sync += buf_full.eq(~self.n.i_ready_test & self.n.o_valid)
955
956 odata = Mux(buf_full, buf, self.stage.process(self.p.i_data))
957 m.d.comb += eq(self.n.o_data, odata)
958 m.d.sync += eq(buf, self.n.o_data)
959
960 return self.m
961
962
963 class PassThroughStage(StageCls):
964 """ a pass-through stage which has its input data spec equal to its output,
965 and "passes through" its data from input to output.
966 """
967 def __init__(self, iospecfn):
968 self.iospecfn = iospecfn
969 def ispec(self): return self.iospecfn()
970 def ospec(self): return self.iospecfn()
971 def process(self, i): return i
972
973
974 class PassThroughHandshake(ControlBase):
975 """ A control block that delays by one clock cycle.
976 """
977
978 def elaborate(self, platform):
979 self.m = m = ControlBase._elaborate(self, platform)
980
981 # temporaries
982 p_i_valid = Signal(reset_less=True)
983 pvr = Signal(reset_less=True)
984 m.d.comb += p_i_valid.eq(self.p.i_valid_test)
985 m.d.comb += pvr.eq(p_i_valid & self.p.o_ready)
986
987 m.d.comb += self.p.o_ready.eq(~self.n.o_valid | self.n.i_ready_test)
988 m.d.sync += self.n.o_valid.eq(p_i_valid | ~self.p.o_ready)
989
990 odata = Mux(pvr, self.stage.process(self.p.i_data), self.n.o_data)
991 m.d.sync += eq(self.n.o_data, odata)
992
993 return m
994
995
996 class RegisterPipeline(UnbufferedPipeline):
997 """ A pipeline stage that delays by one clock cycle, creating a
998 sync'd latch out of o_data and o_valid as an indirect byproduct
999 of using PassThroughStage
1000 """
1001 def __init__(self, iospecfn):
1002 UnbufferedPipeline.__init__(self, PassThroughStage(iospecfn))
1003
1004
1005 class FIFOtest(ControlBase):
1006 """ A test of using a SyncFIFO to see if it will work.
1007 Note: the only things it will accept is a Signal of width "width".
1008 """
1009
1010 def __init__(self, width, depth):
1011
1012 self.fwidth = width
1013 self.fdepth = depth
1014 def iospecfn():
1015 return Signal(width, name="data")
1016 stage = PassThroughStage(iospecfn)
1017 ControlBase.__init__(self, stage=stage)
1018
1019 def elaborate(self, platform):
1020 self.m = m = ControlBase._elaborate(self, platform)
1021
1022 fifo = SyncFIFO(self.fwidth, self.fdepth)
1023 m.submodules.fifo = fifo
1024
1025 # prev: make the FIFO "look" like a PrevControl...
1026 fp = PrevControl()
1027 fp.i_valid = fifo.we
1028 fp._o_ready = fifo.writable
1029 fp.i_data = fifo.din
1030 # ... so we can do this!
1031 m.d.comb += fp._connect_in(self.p, True)
1032
1033 # next: make the FIFO "look" like a NextControl...
1034 fn = NextControl()
1035 fn.o_valid = fifo.readable
1036 fn.i_ready = fifo.re
1037 fn.o_data = fifo.dout
1038 # ... so we can do this!
1039 m.d.comb += fn._connect_out(self.n)
1040
1041 # err... that should be all!
1042 return m
1043