code-comments
[soc.git] / src / soc / simple / core.py
1 """simple core
2
3 not in any way intended for production use. connects up FunctionUnits to
4 Register Files in a brain-dead fashion that only permits one and only one
5 Function Unit to be operational.
6
7 the principle here is to take the Function Units, analyse their regspecs,
8 and turn their requirements for access to register file read/write ports
9 into groupings by Register File and Register File Port name.
10
11 under each grouping - by regfile/port - a list of Function Units that
12 need to connect to that port is created. as these are a contended
13 resource a "Broadcast Bus" per read/write port is then also created,
14 with access to it managed by a PriorityPicker.
15
16 the brain-dead part of this module is that even though there is no
17 conflict of access, regfile read/write hazards are *not* analysed,
18 and consequently it is safer to wait for the Function Unit to complete
19 before allowing a new instruction to proceed.
20 (update: actually this is being added now:
21 https://bugs.libre-soc.org/show_bug.cgi?id=737)
22 """
23
24 from nmigen import (Elaboratable, Module, Signal, ResetSignal, Cat, Mux,
25 Const)
26 from nmigen.cli import rtlil
27
28 from openpower.decoder.power_decoder2 import PowerDecodeSubset
29 from openpower.decoder.power_regspec_map import regspec_decode_read
30 from openpower.decoder.power_regspec_map import regspec_decode_write
31 from openpower.sv.svp64 import SVP64Rec
32
33 from nmutil.picker import PriorityPicker
34 from nmutil.util import treereduce
35 from nmutil.singlepipe import ControlBase
36
37 from soc.fu.compunits.compunits import AllFunctionUnits, LDSTFunctionUnit
38 from soc.regfile.regfiles import RegFiles
39 from openpower.decoder.power_decoder2 import get_rdflags
40 from soc.experiment.l0_cache import TstL0CacheBuffer # test only
41 from soc.config.test.test_loadstore import TestMemPspec
42 from openpower.decoder.power_enums import MicrOp, Function
43 from soc.simple.core_data import CoreInput, CoreOutput
44
45 from collections import defaultdict, namedtuple
46 import operator
47
48 from nmutil.util import rising_edge
49
50 FUSpec = namedtuple("FUSpec", ["funame", "fu", "idx"])
51 ByRegSpec = namedtuple("ByRegSpec", ["rdport", "wrport", "read",
52 "write", "wid", "specs"])
53
54 # helper function for reducing a list of signals down to a parallel
55 # ORed single signal.
56 def ortreereduce(tree, attr="o_data"):
57 return treereduce(tree, operator.or_, lambda x: getattr(x, attr))
58
59
60 def ortreereduce_sig(tree):
61 return treereduce(tree, operator.or_, lambda x: x)
62
63
64 # helper function to place full regs declarations first
65 def sort_fuspecs(fuspecs):
66 res = []
67 for (regname, fspec) in fuspecs.items():
68 if regname.startswith("full"):
69 res.append((regname, fspec))
70 for (regname, fspec) in fuspecs.items():
71 if not regname.startswith("full"):
72 res.append((regname, fspec))
73 return res # enumerate(res)
74
75
76 # derive from ControlBase rather than have a separate Stage instance,
77 # this is simpler to do
78 class NonProductionCore(ControlBase):
79 def __init__(self, pspec):
80 self.pspec = pspec
81
82 # test is SVP64 is to be enabled
83 self.svp64_en = hasattr(pspec, "svp64") and (pspec.svp64 == True)
84
85 # test to see if regfile ports should be reduced
86 self.regreduce_en = (hasattr(pspec, "regreduce") and
87 (pspec.regreduce == True))
88
89 # test to see if overlapping of instructions is allowed
90 # (not normally enabled for TestIssuer FSM but useful for checking
91 # the bitvector hazard detection, before doing In-Order)
92 self.allow_overlap = (hasattr(pspec, "allow_overlap") and
93 (pspec.allow_overlap == True))
94
95 # test core type
96 self.make_hazard_vecs = self.allow_overlap
97 self.core_type = "fsm"
98 if hasattr(pspec, "core_type"):
99 self.core_type = pspec.core_type
100
101 super().__init__(stage=self)
102
103 # single LD/ST funnel for memory access
104 self.l0 = l0 = TstL0CacheBuffer(pspec, n_units=1)
105 pi = l0.l0.dports[0]
106
107 # function units (only one each)
108 # only include mmu if enabled in pspec
109 self.fus = AllFunctionUnits(pspec, pilist=[pi])
110
111 # link LoadStore1 into MMU
112 mmu = self.fus.get_fu('mmu0')
113 print ("core pspec", pspec.ldst_ifacetype)
114 print ("core mmu", mmu)
115 if mmu is not None:
116 print ("core lsmem.lsi", l0.cmpi.lsmem.lsi)
117 mmu.alu.set_ldst_interface(l0.cmpi.lsmem.lsi)
118
119 # register files (yes plural)
120 self.regs = RegFiles(pspec, make_hazard_vecs=self.make_hazard_vecs)
121
122 # set up input and output: unusual requirement to set data directly
123 # (due to the way that the core is set up in a different domain,
124 # see TestIssuer.setup_peripherals
125 self.p.i_data, self.n.o_data = self.new_specs(None)
126 self.i, self.o = self.p.i_data, self.n.o_data
127
128 # actual internal input data used (captured)
129 self.ireg = self.ispec()
130
131 # create per-FU instruction decoders (subsetted). these "satellite"
132 # decoders reduce wire fan-out from the one (main) PowerDecoder2
133 # (used directly by the trap unit) to the *twelve* (or more)
134 # Function Units. we can either have 32 wires (the instruction)
135 # to each, or we can have well over a 200 wire fan-out (to 12
136 # ALUs). it's an easy choice to make.
137 self.decoders = {}
138 self.des = {}
139
140 for funame, fu in self.fus.fus.items():
141 f_name = fu.fnunit.name
142 fnunit = fu.fnunit.value
143 opkls = fu.opsubsetkls
144 if f_name == 'TRAP':
145 # TRAP decoder is the *main* decoder
146 self.trapunit = funame
147 continue
148 self.decoders[funame] = PowerDecodeSubset(None, opkls, f_name,
149 final=True,
150 state=self.ireg.state,
151 svp64_en=self.svp64_en,
152 regreduce_en=self.regreduce_en)
153 self.des[funame] = self.decoders[funame].do
154
155 # create per-Function Unit write-after-write hazard signals
156 # yes, really, this should have been added in ReservationStations
157 # but hey.
158 for funame, fu in self.fus.fus.items():
159 fu._waw_hazard = Signal(name="waw_%s" % funame)
160
161 # share the SPR decoder with the MMU if it exists
162 if "mmu0" in self.decoders:
163 self.decoders["mmu0"].mmu0_spr_dec = self.decoders["spr0"]
164
165 # next 3 functions are Stage API Compliance
166 def setup(self, m, i):
167 pass
168
169 def ispec(self):
170 return CoreInput(self.pspec, self.svp64_en, self.regreduce_en)
171
172 def ospec(self):
173 return CoreOutput()
174
175 # elaborate function to create HDL
176 def elaborate(self, platform):
177 m = super().elaborate(platform)
178
179 # for testing purposes, to cut down on build time in coriolis2
180 if hasattr(self.pspec, "nocore") and self.pspec.nocore == True:
181 x = Signal() # dummy signal
182 m.d.sync += x.eq(~x)
183 return m
184 comb = m.d.comb
185
186 m.submodules.fus = self.fus
187 m.submodules.l0 = l0 = self.l0
188 self.regs.elaborate_into(m, platform)
189 regs = self.regs
190 fus = self.fus.fus
191
192 # amalgamate write-hazards into a single top-level Signal
193 self.waw_hazard = Signal()
194 whaz = []
195 for funame, fu in self.fus.fus.items():
196 whaz.append(fu._waw_hazard)
197 comb += self.waw_hazard.eq(Cat(*whaz).bool())
198
199 # connect decoders
200 self.connect_satellite_decoders(m)
201
202 # ssh, cheat: trap uses the main decoder because of the rewriting
203 self.des[self.trapunit] = self.ireg.e.do
204
205 # connect up Function Units, then read/write ports, and hazard conflict
206 self.issue_conflict = Signal()
207 fu_bitdict, fu_selected = self.connect_instruction(m)
208 raw_hazard = self.connect_rdports(m, fu_bitdict, fu_selected)
209 self.connect_wrports(m, fu_bitdict, fu_selected)
210 if self.allow_overlap:
211 comb += self.issue_conflict.eq(raw_hazard)
212
213 # note if an exception happened. in a pipelined or OoO design
214 # this needs to be accompanied by "shadowing" (or stalling)
215 el = []
216 for exc in self.fus.excs.values():
217 el.append(exc.happened)
218 if len(el) > 0: # at least one exception
219 comb += self.o.exc_happened.eq(Cat(*el).bool())
220
221 return m
222
223 def connect_satellite_decoders(self, m):
224 comb = m.d.comb
225 for k, v in self.decoders.items():
226 # connect each satellite decoder and give it the instruction.
227 # as subset decoders this massively reduces wire fanout given
228 # the large number of ALUs
229 setattr(m.submodules, "dec_%s" % v.fn_name, v)
230 comb += v.dec.raw_opcode_in.eq(self.ireg.raw_insn_i)
231 comb += v.dec.bigendian.eq(self.ireg.bigendian_i)
232 # sigh due to SVP64 RA_OR_ZERO detection connect these too
233 comb += v.sv_a_nz.eq(self.ireg.sv_a_nz)
234 if self.svp64_en:
235 comb += v.pred_sm.eq(self.ireg.sv_pred_sm)
236 comb += v.pred_dm.eq(self.ireg.sv_pred_dm)
237 if k != self.trapunit:
238 comb += v.sv_rm.eq(self.ireg.sv_rm) # pass through SVP64 RM
239 comb += v.is_svp64_mode.eq(self.ireg.is_svp64_mode)
240 # only the LDST PowerDecodeSubset *actually* needs to
241 # know to use the alternative decoder. this is all
242 # a terrible hack
243 if k.lower().startswith("ldst"):
244 comb += v.use_svp64_ldst_dec.eq(
245 self.ireg.use_svp64_ldst_dec)
246
247 def connect_instruction(self, m):
248 """connect_instruction
249
250 uses decoded (from PowerOp) function unit information from CSV files
251 to ascertain which Function Unit should deal with the current
252 instruction.
253
254 some (such as OP_ATTN, OP_NOP) are dealt with here, including
255 ignoring it and halting the processor. OP_NOP is a bit annoying
256 because the issuer expects busy flag still to be raised then lowered.
257 (this requires a fake counter to be set).
258 """
259 comb, sync = m.d.comb, m.d.sync
260 fus = self.fus.fus
261
262 # indicate if core is busy
263 busy_o = self.o.busy_o
264 any_busy_o = self.o.any_busy_o
265
266 # connect up temporary copy of incoming instruction. the FSM will
267 # either blat the incoming instruction (if valid) into self.ireg
268 # or if the instruction could not be delivered, keep dropping the
269 # latched copy into ireg
270 ilatch = self.ispec()
271 self.instr_active = Signal()
272
273 # enable/busy-signals for each FU, get one bit for each FU (by name)
274 fu_enable = Signal(len(fus), reset_less=True)
275 fu_busy = Signal(len(fus), reset_less=True)
276 fu_bitdict = {}
277 fu_selected = {}
278 for i, funame in enumerate(fus.keys()):
279 fu_bitdict[funame] = fu_enable[i]
280 fu_selected[funame] = fu_busy[i]
281
282 # identify function units and create a list by fnunit so that
283 # PriorityPickers can be created for selecting one of them that
284 # isn't busy at the time the incoming instruction needs passing on
285 by_fnunit = defaultdict(list)
286 for fname, member in Function.__members__.items():
287 for funame, fu in fus.items():
288 fnunit = fu.fnunit.value
289 if member.value & fnunit: # this FU handles this type of op
290 by_fnunit[fname].append((funame, fu)) # add by Function
291
292 # ok now just print out the list of FUs by Function, because we can
293 for fname, fu_list in by_fnunit.items():
294 print ("FUs by type", fname, fu_list)
295
296 # now create a PriorityPicker per FU-type such that only one
297 # non-busy FU will be picked
298 issue_pps = {}
299 fu_found = Signal() # take a note if no Function Unit was available
300 for fname, fu_list in by_fnunit.items():
301 i_pp = PriorityPicker(len(fu_list))
302 m.submodules['i_pp_%s' % fname] = i_pp
303 i_l = []
304 for i, (funame, fu) in enumerate(fu_list):
305 # match the decoded instruction (e.do.fn_unit) against the
306 # "capability" of this FU, gate that by whether that FU is
307 # busy, and drop that into the PriorityPicker.
308 # this will give us an output of the first available *non-busy*
309 # Function Unit (Reservation Statio) capable of handling this
310 # instruction.
311 fnunit = fu.fnunit.value
312 en_req = Signal(name="issue_en_%s" % funame, reset_less=True)
313 fnmatch = (self.ireg.e.do.fn_unit & fnunit).bool()
314 comb += en_req.eq(fnmatch & ~fu.busy_o &
315 self.instr_active)
316 i_l.append(en_req) # store in list for doing the Cat-trick
317 # picker output, gated by enable: store in fu_bitdict
318 po = Signal(name="o_issue_pick_"+funame) # picker output
319 comb += po.eq(i_pp.o[i] & i_pp.en_o)
320 comb += fu_bitdict[funame].eq(po)
321 comb += fu_selected[funame].eq(fu.busy_o | po)
322 # if we don't do this, then when there are no FUs available,
323 # the "p.o_ready" signal will go back "ok we accepted this
324 # instruction" which of course isn't true.
325 with m.If(i_pp.en_o):
326 comb += fu_found.eq(1)
327 # for each input, Cat them together and drop them into the picker
328 comb += i_pp.i.eq(Cat(*i_l))
329
330 # rdmask, which is for registers needs to come from the *main* decoder
331 for funame, fu in fus.items():
332 rdmask = get_rdflags(self.ireg.e, fu)
333 comb += fu.rdmaskn.eq(~rdmask)
334
335 # sigh - need a NOP counter
336 counter = Signal(2)
337 with m.If(counter != 0):
338 sync += counter.eq(counter - 1)
339 comb += busy_o.eq(1)
340
341 # default to reading from incoming instruction: may be overridden
342 # by copy from latch when "waiting"
343 comb += self.ireg.eq(self.i)
344 # always say "ready" except if overridden
345 comb += self.p.o_ready.eq(1)
346
347 with m.FSM():
348 with m.State("READY"):
349 with m.If(self.p.i_valid): # run only when valid
350 with m.Switch(self.ireg.e.do.insn_type):
351 # check for ATTN: halt if true
352 with m.Case(MicrOp.OP_ATTN):
353 m.d.sync += self.o.core_terminate_o.eq(1)
354
355 # fake NOP - this isn't really used (Issuer detects NOP)
356 with m.Case(MicrOp.OP_NOP):
357 sync += counter.eq(2)
358 comb += busy_o.eq(1)
359
360 with m.Default():
361 comb += self.instr_active.eq(1)
362 comb += self.p.o_ready.eq(0)
363 # connect instructions. only one enabled at a time
364 for funame, fu in fus.items():
365 do = self.des[funame]
366 enable = fu_bitdict[funame]
367
368 # run this FunctionUnit if enabled route op,
369 # issue, busy, read flags and mask to FU
370 with m.If(enable):
371 # operand comes from the *local* decoder
372 # do not actually issue, though, if there
373 # is a waw hazard. decoder has to still
374 # be asserted in order to detect that, tho
375 comb += fu.oper_i.eq_from(do)
376 # issue when valid (and no write-hazard)
377 comb += fu.issue_i.eq(~self.waw_hazard)
378 # instruction ok, indicate ready
379 comb += self.p.o_ready.eq(1)
380
381 if self.allow_overlap:
382 with m.If(~fu_found | self.waw_hazard):
383 # latch copy of instruction
384 sync += ilatch.eq(self.i)
385 comb += self.p.o_ready.eq(1) # accept
386 comb += busy_o.eq(1)
387 m.next = "WAITING"
388
389 with m.State("WAITING"):
390 comb += self.instr_active.eq(1)
391 comb += self.p.o_ready.eq(0)
392 comb += busy_o.eq(1)
393 # using copy of instruction, keep waiting until an FU is free
394 comb += self.ireg.eq(ilatch)
395 with m.If(fu_found): # wait for conflict to clear
396 # connect instructions. only one enabled at a time
397 for funame, fu in fus.items():
398 do = self.des[funame]
399 enable = fu_bitdict[funame]
400
401 # run this FunctionUnit if enabled route op,
402 # issue, busy, read flags and mask to FU
403 with m.If(enable):
404 # operand comes from the *local* decoder,
405 # which is asserted even if not issued,
406 # so that WaW-detection can check for hazards.
407 # only if the waw hazard is clear does the
408 # instruction actually get issued
409 comb += fu.oper_i.eq_from(do)
410 # issue when valid
411 comb += fu.issue_i.eq(~self.waw_hazard)
412 with m.If(~self.waw_hazard):
413 comb += self.p.o_ready.eq(1)
414 comb += busy_o.eq(0)
415 m.next = "READY"
416
417 print ("core: overlap allowed", self.allow_overlap)
418 busys = map(lambda fu: fu.busy_o, fus.values())
419 comb += any_busy_o.eq(Cat(*busys).bool())
420 if not self.allow_overlap:
421 # for simple non-overlap, if any instruction is busy, set
422 # busy output for core.
423 comb += busy_o.eq(any_busy_o)
424 else:
425 # sigh deal with a fun situation that needs to be investigated
426 # and resolved
427 with m.If(self.issue_conflict | self.waw_hazard):
428 comb += busy_o.eq(1)
429
430 # return both the function unit "enable" dict as well as the "busy".
431 # the "busy-or-issued" can be passed in to the Read/Write port
432 # connecters to give them permission to request access to regfiles
433 return fu_bitdict, fu_selected
434
435 def connect_rdport(self, m, fu_bitdict, fu_selected,
436 rdpickers, regfile, regname, fspec):
437 comb, sync = m.d.comb, m.d.sync
438 fus = self.fus.fus
439 regs = self.regs
440
441 rpidx = regname
442
443 # select the required read port. these are pre-defined sizes
444 rfile = regs.rf[regfile.lower()]
445 rport = rfile.r_ports[rpidx]
446 print("read regfile", rpidx, regfile, regs.rf.keys(),
447 rfile, rfile.unary)
448
449 # for checking if the read port has an outstanding write
450 if self.make_hazard_vecs:
451 wv = regs.wv[regfile.lower()]
452 wvchk = wv.r_ports["issue"] # write-vec bit-level hazard check
453
454 # if a hazard is detected on this read port, simply blithely block
455 # every FU from reading on it. this is complete overkill but very
456 # simple for now.
457 hazard_detected = Signal(name="raw_%s_%s" % (regfile, rpidx))
458
459 fspecs = fspec
460 if not isinstance(fspecs, list):
461 fspecs = [fspecs]
462
463 rdflags = []
464 pplen = 0
465 ppoffs = []
466 for i, fspec in enumerate(fspecs):
467 # get the regfile specs for this regfile port
468 (rf, wf, _read, _write, wid, fuspecs) = \
469 (fspec.rdport, fspec.wrport, fspec.read, fspec.write,
470 fspec.wid, fspec.specs)
471 print ("fpsec", i, fspec, len(fuspecs))
472 ppoffs.append(pplen) # record offset for picker
473 pplen += len(fspec.specs)
474 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
475 rdflag = Signal(name=name, reset_less=True)
476 comb += rdflag.eq(fspec.rdport)
477 rdflags.append(rdflag)
478
479 print ("pplen", pplen)
480
481 # create a priority picker to manage this port
482 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
483 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
484
485 rens = []
486 addrs = []
487 wvens = []
488
489 for i, fspec in enumerate(fspecs):
490 (rf, wf, _read, _write, wid, fuspecs) = \
491 (fspec.rdport, fspec.wrport, fspec.read, fspec.write,
492 fspec.wid, fspec.specs)
493 # connect up the FU req/go signals, and the reg-read to the FU
494 # and create a Read Broadcast Bus
495 for pi, fuspec in enumerate(fspec.specs):
496 (funame, fu, idx) = (fuspec.funame, fuspec.fu, fuspec.idx)
497 pi += ppoffs[i]
498 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
499 fu_active = fu_selected[funame]
500 fu_issued = fu_bitdict[funame]
501
502 # get (or set up) a latched copy of read register number
503 rname = "%s_%s_%s_%d" % (funame, regfile, regname, pi)
504 read = Signal.like(_read, name="read_"+name)
505 if rname not in fu.rd_latches:
506 rdl = Signal.like(_read, name="rdlatch_"+rname)
507 fu.rd_latches[rname] = rdl
508 with m.If(fu.issue_i):
509 sync += rdl.eq(_read)
510 else:
511 rdl = fu.rd_latches[rname]
512 # latch to make the read immediately available on issue cycle
513 # after the read cycle, use the latched copy
514 with m.If(fu.issue_i):
515 comb += read.eq(_read)
516 with m.Else():
517 comb += read.eq(rdl)
518
519 # connect request-read to picker input, and output to go-rd
520 addr_en = Signal.like(read, name="addr_en_"+name)
521 pick = Signal(name="pick_"+name) # picker input
522 rp = Signal(name="rp_"+name) # picker output
523 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
524 rhazard = Signal(name="rhaz_"+name)
525
526 # exclude any currently-enabled read-request (mask out active)
527 # entirely block anything hazarded from being picked
528 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
529 ~delay_pick & ~rhazard)
530 comb += rdpick.i[pi].eq(pick)
531 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
532
533 # if picked, select read-port "reg select" number to port
534 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
535 sync += delay_pick.eq(rp) # delayed "pick"
536 comb += addr_en.eq(Mux(rp, read, 0))
537
538 # the read-enable happens combinatorially (see mux-bus below)
539 # but it results in the data coming out on a one-cycle delay.
540 if rfile.unary:
541 rens.append(addr_en)
542 else:
543 addrs.append(addr_en)
544 rens.append(rp)
545
546 # use the *delayed* pick signal to put requested data onto bus
547 with m.If(delay_pick):
548 # connect regfile port to input, creating fan-out Bus
549 src = fu.src_i[idx]
550 print("reg connect widths",
551 regfile, regname, pi, funame,
552 src.shape(), rport.o_data.shape())
553 # all FUs connect to same port
554 comb += src.eq(rport.o_data)
555
556 if not self.make_hazard_vecs:
557 continue
558
559 # read the write-hazard bitvector (wv) for any bit that is
560 wvchk_en = Signal(len(wvchk.ren), name="wv_chk_addr_en_"+name)
561 issue_active = Signal(name="rd_iactive_"+name)
562 # XXX combinatorial loop here
563 comb += issue_active.eq(fu_active & rf)
564 with m.If(issue_active):
565 if rfile.unary:
566 comb += wvchk_en.eq(read)
567 else:
568 comb += wvchk_en.eq(1<<read)
569 # if FU is busy (which doesn't get set at the same time as
570 # issue) and no hazard was detected, clear wvchk_en (i.e.
571 # stop checking for hazards). there is a loop here, but it's
572 # via a DFF, so is ok. some linters may complain, but hey.
573 with m.If(fu.busy_o & ~rhazard):
574 comb += wvchk_en.eq(0)
575
576 # read-hazard is ANDed with (filtered by) what is actually
577 # being requested.
578 comb += rhazard.eq((wvchk.o_data & wvchk_en).bool())
579
580 wvens.append(wvchk_en)
581
582 # or-reduce the muxed read signals
583 if rfile.unary:
584 # for unary-addressed
585 comb += rport.ren.eq(ortreereduce_sig(rens))
586 else:
587 # for binary-addressed
588 comb += rport.addr.eq(ortreereduce_sig(addrs))
589 comb += rport.ren.eq(Cat(*rens).bool())
590 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
591
592 if not self.make_hazard_vecs:
593 return Const(0) # declare "no hazards"
594
595 # enable the read bitvectors for this issued instruction
596 # and return whether any write-hazard bit is set
597 comb += wvchk.ren.eq(ortreereduce_sig(wvens))
598 comb += hazard_detected.eq(wvchk.o_data.bool())
599 return hazard_detected
600
601 def connect_rdports(self, m, fu_bitdict, fu_selected):
602 """connect read ports
603
604 orders the read regspecs into a dict-of-dicts, by regfile, by
605 regport name, then connects all FUs that want that regport by
606 way of a PriorityPicker.
607 """
608 comb, sync = m.d.comb, m.d.sync
609 fus = self.fus.fus
610 regs = self.regs
611 rd_hazard = []
612
613 # dictionary of lists of regfile read ports
614 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
615
616 # okaay, now we need a PriorityPicker per regfile per regfile port
617 # loootta pickers... peter piper picked a pack of pickled peppers...
618 rdpickers = {}
619 for regfile, spec in byregfiles_rd.items():
620 fuspecs = byregfiles_rdspec[regfile]
621 rdpickers[regfile] = {}
622
623 # argh. an experiment to merge RA and RB in the INT regfile
624 # (we have too many read/write ports)
625 if self.regreduce_en:
626 if regfile == 'INT':
627 fuspecs['rabc'] = [fuspecs.pop('rb')]
628 fuspecs['rabc'].append(fuspecs.pop('rc'))
629 fuspecs['rabc'].append(fuspecs.pop('ra'))
630 if regfile == 'FAST':
631 fuspecs['fast1'] = [fuspecs.pop('fast1')]
632 if 'fast2' in fuspecs:
633 fuspecs['fast1'].append(fuspecs.pop('fast2'))
634 if 'fast3' in fuspecs:
635 fuspecs['fast1'].append(fuspecs.pop('fast3'))
636
637 # for each named regfile port, connect up all FUs to that port
638 # also return (and collate) hazard detection)
639 for (regname, fspec) in sort_fuspecs(fuspecs):
640 print("connect rd", regname, fspec)
641 rh = self.connect_rdport(m, fu_bitdict, fu_selected,
642 rdpickers, regfile,
643 regname, fspec)
644 rd_hazard.append(rh)
645
646 return Cat(*rd_hazard).bool()
647
648 def make_hazards(self, m, regfile, rfile, wvclr, wvset,
649 funame, regname, idx,
650 addr_en, wp, fu, fu_active, wrflag, write,
651 fu_wrok):
652 """make_hazards: a setter and a clearer for the regfile write ports
653
654 setter is at issue time (using PowerDecoder2 regfile write numbers)
655 clearer is at regfile write time (when FU has said what to write to)
656
657 there is *one* unusual case here which has to be dealt with:
658 when the Function Unit does *NOT* request a write to the regfile
659 (has its data.ok bit CLEARED). this is perfectly legitimate.
660 and a royal pain.
661 """
662 comb, sync = m.d.comb, m.d.sync
663 name = "%s_%s_%d" % (funame, regname, idx)
664
665 # connect up the bitvector write hazard. unlike the
666 # regfile writeports, a ONE must be written to the corresponding
667 # bit of the hazard bitvector (to indicate the existence of
668 # the hazard)
669
670 # the detection of what shall be written to is based
671 # on *issue*
672 print ("write vector (for regread)", regfile, wvset)
673 wviaddr_en = Signal(len(wvset.wen), name="wv_issue_addr_en_"+name)
674 issue_active = Signal(name="iactive_"+name)
675 comb += issue_active.eq(fu.issue_i & fu_active & wrflag)
676 with m.If(issue_active):
677 if rfile.unary:
678 comb += wviaddr_en.eq(write)
679 else:
680 comb += wviaddr_en.eq(1<<write)
681
682 # deal with write vector clear: this kicks in when the regfile
683 # is written to, and clears the corresponding bitvector entry
684 print ("write vector", regfile, wvclr)
685 wvaddr_en = Signal(len(wvclr.wen), name="wvaddr_en_"+name)
686 if rfile.unary:
687 comb += wvaddr_en.eq(addr_en)
688 else:
689 with m.If(wp):
690 comb += wvaddr_en.eq(1<<addr_en)
691
692 # XXX ASSUME that LDSTFunctionUnit always sets the data it intends to
693 # this may NOT be the case when an exception occurs
694 if isinstance(fu, LDSTFunctionUnit):
695 return wvaddr_en, wviaddr_en
696
697 # okaaay, this is preparation for the awkward case.
698 # * latch a copy of wrflag when issue goes high.
699 # * when the fu_wrok (data.ok) flag is NOT set,
700 # but the FU is done, the FU is NEVER going to write
701 # so the bitvector has to be cleared.
702 latch_wrflag = Signal(name="latch_wrflag_"+name)
703 with m.If(~fu.busy_o):
704 sync += latch_wrflag.eq(0)
705 with m.If(fu.issue_i & fu_active):
706 sync += latch_wrflag.eq(wrflag)
707 with m.If(fu.alu_done_o & latch_wrflag & ~fu_wrok):
708 if rfile.unary:
709 comb += wvaddr_en.eq(write) # addr_en gated with wp, don't use
710 else:
711 comb += wvaddr_en.eq(1<<addr_en) # binary addr_en not gated
712
713 return wvaddr_en, wviaddr_en
714
715 def connect_wrport(self, m, fu_bitdict, fu_selected,
716 wrpickers, regfile, regname, fspec):
717 comb, sync = m.d.comb, m.d.sync
718 fus = self.fus.fus
719 regs = self.regs
720
721 rpidx = regname
722
723 # select the required write port. these are pre-defined sizes
724 rfile = regs.rf[regfile.lower()]
725 wport = rfile.w_ports[rpidx]
726
727 print("connect wr", regname, "unary", rfile.unary, fspec)
728 print(regfile, regs.rf.keys())
729
730 # select the write-protection hazard vector. note that this still
731 # requires to WRITE to the hazard bitvector! read-requests need
732 # to RAISE the bitvector (set it to 1), which, duh, requires a WRITE
733 if self.make_hazard_vecs:
734 wv = regs.wv[regfile.lower()]
735 wvset = wv.w_ports["set"] # write-vec bit-level hazard ctrl
736 wvclr = wv.w_ports["clr"] # write-vec bit-level hazard ctrl
737 wvchk = wv.r_ports["whazard"] # write-after-write hazard check
738
739 fspecs = fspec
740 if not isinstance(fspecs, list):
741 fspecs = [fspecs]
742
743 pplen = 0
744 writes = []
745 ppoffs = []
746 rdflags = []
747 wrflags = []
748 for i, fspec in enumerate(fspecs):
749 # get the regfile specs for this regfile port
750 (rf, wf, _read, _write, wid, fuspecs) = \
751 (fspec.rdport, fspec.wrport, fspec.read, fspec.write,
752 fspec.wid, fspec.specs)
753 print ("fpsec", i, "wrflag", wf, fspec, len(fuspecs))
754 ppoffs.append(pplen) # record offset for picker
755 pplen += len(fuspecs)
756
757 name = "%s_%s_%d" % (regfile, regname, i)
758 rdflag = Signal(name="rd_flag_"+name)
759 wrflag = Signal(name="wr_flag_"+name)
760 if rf is not None:
761 comb += rdflag.eq(rf)
762 else:
763 comb += rdflag.eq(0)
764 if wf is not None:
765 comb += wrflag.eq(wf)
766 else:
767 comb += wrflag.eq(0)
768 rdflags.append(rdflag)
769 wrflags.append(wrflag)
770
771 # create a priority picker to manage this port
772 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
773 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
774
775 wsigs = []
776 wens = []
777 wvsets = []
778 wvseten = []
779 wvclren = []
780 #wvens = [] - not needed: reading of writevec is permanently held hi
781 addrs = []
782 for i, fspec in enumerate(fspecs):
783 # connect up the FU req/go signals and the reg-read to the FU
784 # these are arbitrated by Data.ok signals
785 (rf, wf, _read, _write, wid, fuspecs) = \
786 (fspec.rdport, fspec.wrport, fspec.read, fspec.write,
787 fspec.wid, fspec.specs)
788 for pi, fuspec in enumerate(fspec.specs):
789 (funame, fu, idx) = (fuspec.funame, fuspec.fu, fuspec.idx)
790 pi += ppoffs[i]
791 name = "%s_%s_%s_%d" % (funame, regfile, regname, idx)
792 # get (or set up) a write-latched copy of write register number
793 write = Signal.like(_write, name="write_"+name)
794 rname = "%s_%s_%s_%d" % (funame, regfile, regname, idx)
795 if rname not in fu.wr_latches:
796 wrl = Signal.like(_write, name="wrlatch_"+rname)
797 fu.wr_latches[rname] = write
798 with m.If(fu.issue_i):
799 sync += wrl.eq(_write)
800 comb += write.eq(_write)
801 with m.Else():
802 comb += write.eq(wrl)
803 else:
804 write = fu.wr_latches[rname]
805
806 # write-request comes from dest.ok
807 dest = fu.get_out(idx)
808 fu_dest_latch = fu.get_fu_out(idx) # latched output
809 name = "%s_%s_%d" % (funame, regname, idx)
810 fu_wrok = Signal(name="fu_wrok_"+name, reset_less=True)
811 comb += fu_wrok.eq(dest.ok & fu.busy_o)
812
813 # connect request-write to picker input, and output to go-wr
814 fu_active = fu_selected[funame]
815 pick = fu.wr.rel_o[idx] & fu_active
816 comb += wrpick.i[pi].eq(pick)
817 # create a single-pulse go write from the picker output
818 wr_pick = Signal(name="wpick_%s_%s_%d" % (funame, regname, idx))
819 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
820 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
821
822 # connect the regspec write "reg select" number to this port
823 # only if one FU actually requests (and is granted) the port
824 # will the write-enable be activated
825 wname = "waddr_en_%s_%s_%d" % (funame, regname, idx)
826 addr_en = Signal.like(write, name=wname)
827 wp = Signal()
828 comb += wp.eq(wr_pick & wrpick.en_o)
829 comb += addr_en.eq(Mux(wp, write, 0))
830 if rfile.unary:
831 wens.append(addr_en)
832 else:
833 addrs.append(addr_en)
834 wens.append(wp)
835
836 # connect regfile port to input
837 print("reg connect widths",
838 regfile, regname, pi, funame,
839 dest.shape(), wport.i_data.shape())
840 wsigs.append(fu_dest_latch)
841
842 # now connect up the bitvector write hazard
843 if not self.make_hazard_vecs:
844 continue
845 res = self.make_hazards(m, regfile, rfile, wvclr, wvset,
846 funame, regname, idx,
847 addr_en, wp, fu, fu_active,
848 wrflags[i], write, fu_wrok)
849 wvaddr_en, wv_issue_en = res
850 wvclren.append(wvaddr_en) # set only: no data => clear bit
851 wvseten.append(wv_issue_en) # set data same as enable
852 wvsets.append(wv_issue_en) # because enable needs a 1
853
854 # read the write-hazard bitvector (wv) for any bit that is
855 fu_issue = fu_bitdict[funame]
856 wvchk_en = Signal(len(wvchk.ren), name="waw_chk_addr_en_"+name)
857 issue_active = Signal(name="waw_iactive_"+name)
858 whazard = Signal(name="whaz_"+name)
859 if wf is None:
860 # XXX EEK! STATE regfile (branch) does not have an
861 # write-active indicator in regspec_decode_write()
862 print ("XXX FIXME waw_iactive", issue_active, fu_issue, wf)
863 else:
864 # check bits from the incoming instruction. note (back
865 # in connect_instruction) that the decoder is held for
866 # us to be able to do this, here... *without* issue being
867 # held HI. we MUST NOT gate this with fu.issue_i or
868 # with fu_bitdict "enable": it would create a loop
869 comb += issue_active.eq(wf)
870 with m.If(issue_active):
871 if rfile.unary:
872 comb += wvchk_en.eq(write)
873 else:
874 comb += wvchk_en.eq(1<<write)
875 # if FU is busy (which doesn't get set at the same time as
876 # issue) and no hazard was detected, clear wvchk_en (i.e.
877 # stop checking for hazards). there is a loop here, but it's
878 # via a DFF, so is ok. some linters may complain, but hey.
879 with m.If(fu.busy_o & ~whazard):
880 comb += wvchk_en.eq(0)
881
882 # write-hazard is ANDed with (filtered by) what is actually
883 # being requested.
884 comb += whazard.eq((wvchk.o_data & wvchk_en).bool())
885 with m.If(whazard):
886 comb += fu._waw_hazard.eq(1)
887
888 #wvens.append(wvchk_en)
889
890 # here is where we create the Write Broadcast Bus. simple, eh?
891 comb += wport.i_data.eq(ortreereduce_sig(wsigs))
892 if rfile.unary:
893 # for unary-addressed
894 comb += wport.wen.eq(ortreereduce_sig(wens))
895 else:
896 # for binary-addressed
897 comb += wport.addr.eq(ortreereduce_sig(addrs))
898 comb += wport.wen.eq(ortreereduce_sig(wens))
899
900 if not self.make_hazard_vecs:
901 return
902
903 # for write-vectors
904 comb += wvclr.wen.eq(ortreereduce_sig(wvclren)) # clear (regfile write)
905 comb += wvset.wen.eq(ortreereduce_sig(wvseten)) # set (issue time)
906 comb += wvset.i_data.eq(ortreereduce_sig(wvsets))
907
908 # for write-after-write. this gets the write vector one cycle
909 # late but that's ok... no, actually it's essential, and here's why:
910 # on issue, the write-to-bitvector occurs, but occurs one cycle late.
911 # if we were not reading the write-bitvector one cycle early (its
912 # previous state on the previous cycle), we would end up reading
913 # our *own* write-request as a write-after-write hazard!
914 comb += wvchk.ren.eq(-1) # always enable #ortreereduce_sig(wvens))
915
916 def connect_wrports(self, m, fu_bitdict, fu_selected):
917 """connect write ports
918
919 orders the write regspecs into a dict-of-dicts, by regfile,
920 by regport name, then connects all FUs that want that regport
921 by way of a PriorityPicker.
922
923 note that the write-port wen, write-port data, and go_wr_i all need to
924 be on the exact same clock cycle. as there is a combinatorial loop bug
925 at the moment, these all use sync.
926 """
927 comb, sync = m.d.comb, m.d.sync
928 fus = self.fus.fus
929 regs = self.regs
930 # dictionary of lists of regfile write ports
931 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
932
933 # same for write ports.
934 # BLECH! complex code-duplication! BLECH!
935 wrpickers = {}
936 for regfile, spec in byregfiles_wr.items():
937 fuspecs = byregfiles_wrspec[regfile]
938 wrpickers[regfile] = {}
939
940 if self.regreduce_en:
941 # argh, more port-merging
942 if regfile == 'INT':
943 fuspecs['o'] = [fuspecs.pop('o')]
944 fuspecs['o'].append(fuspecs.pop('o1'))
945 if regfile == 'FAST':
946 fuspecs['fast1'] = [fuspecs.pop('fast1')]
947 if 'fast2' in fuspecs:
948 fuspecs['fast1'].append(fuspecs.pop('fast2'))
949 if 'fast3' in fuspecs:
950 fuspecs['fast1'].append(fuspecs.pop('fast3'))
951
952 for (regname, fspec) in sort_fuspecs(fuspecs):
953 self.connect_wrport(m, fu_bitdict, fu_selected, wrpickers,
954 regfile, regname, fspec)
955
956 def get_byregfiles(self, readmode):
957
958 mode = "read" if readmode else "write"
959 regs = self.regs
960 fus = self.fus.fus
961 e = self.ireg.e # decoded instruction to execute
962
963 # dictionary of dictionaries of lists/tuples of regfile ports.
964 # first key: regfile. second key: regfile port name
965 byregfiles = defaultdict(lambda: defaultdict(list))
966 byregfiles_spec = defaultdict(dict)
967
968 for (funame, fu) in fus.items():
969 # create in each FU a receptacle for the read/write register
970 # hazard numbers. to be latched in connect_rd/write_ports
971 # XXX better that this is moved into the actual FUs, but
972 # the issue there is that this function is actually better
973 # suited at the moment
974 if readmode:
975 fu.rd_latches = {}
976 else:
977 fu.wr_latches = {}
978
979 print("%s ports for %s" % (mode, funame))
980 for idx in range(fu.n_src if readmode else fu.n_dst):
981 # construct regfile specs: read uses inspec, write outspec
982 if readmode:
983 (regfile, regname, wid) = fu.get_in_spec(idx)
984 else:
985 (regfile, regname, wid) = fu.get_out_spec(idx)
986 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
987
988 # the PowerDecoder2 (main one, not the satellites) contains
989 # the decoded regfile numbers. obtain these now
990 if readmode:
991 rdport, read = regspec_decode_read(e, regfile, regname)
992 wrport, write = None, None
993 else:
994 rdport, read = None, None
995 wrport, write = regspec_decode_write(e, regfile, regname)
996
997 # construct the dictionary of regspec information by regfile
998 if regname not in byregfiles_spec[regfile]:
999 byregfiles_spec[regfile][regname] = \
1000 ByRegSpec(rdport, wrport, read, write, wid, [])
1001 # here we start to create "lanes"
1002 fuspec = FUSpec(funame, fu, idx)
1003 byregfiles[regfile][idx].append(fuspec)
1004 byregfiles_spec[regfile][regname].specs.append(fuspec)
1005
1006 continue
1007 # append a latch Signal to the FU's list of latches
1008 rname = "%s_%s" % (regfile, regname)
1009 if readmode:
1010 if rname not in fu.rd_latches:
1011 rdl = Signal.like(read, name="rdlatch_"+rname)
1012 fu.rd_latches[rname] = rdl
1013 else:
1014 if rname not in fu.wr_latches:
1015 wrl = Signal.like(write, name="wrlatch_"+rname)
1016 fu.wr_latches[rname] = wrl
1017
1018 # ok just print that all out, for convenience
1019 for regfile, spec in byregfiles.items():
1020 print("regfile %s ports:" % mode, regfile)
1021 fuspecs = byregfiles_spec[regfile]
1022 for regname, fspec in fuspecs.items():
1023 [rdport, wrport, read, write, wid, fuspecs] = fspec
1024 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
1025 print(" %s" % regname, wid, read, write, rdport, wrport)
1026 for (funame, fu, idx) in fuspecs:
1027 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
1028 print(" ", funame, fu.__class__.__name__, idx, fusig)
1029 print()
1030
1031 return byregfiles, byregfiles_spec
1032
1033 def __iter__(self):
1034 yield from self.fus.ports()
1035 yield from self.i.e.ports()
1036 yield from self.l0.ports()
1037 # TODO: regs
1038
1039 def ports(self):
1040 return list(self)
1041
1042
1043 if __name__ == '__main__':
1044 pspec = TestMemPspec(ldst_ifacetype='testpi',
1045 imem_ifacetype='',
1046 addr_wid=48,
1047 mask_wid=8,
1048 reg_wid=64)
1049 dut = NonProductionCore(pspec)
1050 vl = rtlil.convert(dut, ports=dut.ports())
1051 with open("test_core.il", "w") as f:
1052 f.write(vl)