new fast3 needs to be remapped to fast1 port in "reduced ports" case in core
[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 """
21
22 from nmigen import Elaboratable, Module, Signal, ResetSignal, Cat, Mux
23 from nmigen.cli import rtlil
24
25 from openpower.decoder.power_decoder2 import PowerDecodeSubset
26 from openpower.decoder.power_regspec_map import regspec_decode_read
27 from openpower.decoder.power_regspec_map import regspec_decode_write
28
29 from nmutil.picker import PriorityPicker
30 from nmutil.util import treereduce
31
32 from soc.fu.compunits.compunits import AllFunctionUnits
33 from soc.regfile.regfiles import RegFiles
34 from openpower.decoder.decode2execute1 import Decode2ToExecute1Type
35 from openpower.decoder.decode2execute1 import IssuerDecode2ToOperand
36 from openpower.decoder.power_decoder2 import get_rdflags
37 from openpower.decoder.decode2execute1 import Data
38 from soc.experiment.l0_cache import TstL0CacheBuffer # test only
39 from soc.config.test.test_loadstore import TestMemPspec
40 from openpower.decoder.power_enums import MicrOp
41 from soc.config.state import CoreState
42
43 import operator
44
45 from nmutil.util import rising_edge
46
47
48 # helper function for reducing a list of signals down to a parallel
49 # ORed single signal.
50 def ortreereduce(tree, attr="data_o"):
51 return treereduce(tree, operator.or_, lambda x: getattr(x, attr))
52
53
54 def ortreereduce_sig(tree):
55 return treereduce(tree, operator.or_, lambda x: x)
56
57
58 # helper function to place full regs declarations first
59 def sort_fuspecs(fuspecs):
60 res = []
61 for (regname, fspec) in fuspecs.items():
62 if regname.startswith("full"):
63 res.append((regname, fspec))
64 for (regname, fspec) in fuspecs.items():
65 if not regname.startswith("full"):
66 res.append((regname, fspec))
67 return res # enumerate(res)
68
69
70 class NonProductionCore(Elaboratable):
71 def __init__(self, pspec):
72 self.pspec = pspec
73
74 # test is SVP64 is to be enabled
75 self.svp64_en = hasattr(pspec, "svp64") and (pspec.svp64 == True)
76
77 # test to see if regfile ports should be reduced
78 self.regreduce_en = (hasattr(pspec, "regreduce") and
79 (pspec.regreduce == True))
80
81 # single LD/ST funnel for memory access
82 self.l0 = l0 = TstL0CacheBuffer(pspec, n_units=1)
83 pi = l0.l0.dports[0]
84
85 # function units (only one each)
86 # only include mmu if enabled in pspec
87 self.fus = AllFunctionUnits(pspec, pilist=[pi])
88
89 # link LoadStore1 into MMU
90 mmu = self.fus.get_fu('mmu0')
91 print ("core pspec", pspec.ldst_ifacetype)
92 print ("core mmu", mmu)
93 print ("core lsmem.lsi", l0.cmpi.lsmem.lsi)
94 if mmu is not None:
95 mmu.alu.set_ldst_interface(l0.cmpi.lsmem.lsi)
96
97 # register files (yes plural)
98 self.regs = RegFiles(pspec)
99
100 # instruction decoder - needs a Trap-capable Record (captures EINT etc.)
101 self.e = Decode2ToExecute1Type("core", opkls=IssuerDecode2ToOperand,
102 regreduce_en=self.regreduce_en)
103
104 # SVP64 RA_OR_ZERO needs to know if the relevant EXTRA2/3 field is zero
105 self.sv_a_nz = Signal()
106
107 # state and raw instruction
108 self.state = CoreState("core")
109 self.raw_insn_i = Signal(32) # raw instruction
110 self.bigendian_i = Signal() # bigendian - TODO, set by MSR.BE
111
112 # issue/valid/busy signalling
113 self.ivalid_i = Signal(reset_less=True) # instruction is valid
114 self.issue_i = Signal(reset_less=True)
115 self.busy_o = Signal(name="corebusy_o", reset_less=True)
116
117 # start/stop and terminated signalling
118 self.core_terminate_o = Signal(reset=0) # indicates stopped
119
120 # create per-FU instruction decoders (subsetted)
121 self.decoders = {}
122 self.des = {}
123
124 for funame, fu in self.fus.fus.items():
125 f_name = fu.fnunit.name
126 fnunit = fu.fnunit.value
127 opkls = fu.opsubsetkls
128 if f_name == 'TRAP':
129 self.trapunit = funame
130 continue
131 self.decoders[funame] = PowerDecodeSubset(None, opkls, f_name,
132 final=True,
133 state=self.state,
134 svp64_en=self.svp64_en,
135 regreduce_en=self.regreduce_en)
136 self.des[funame] = self.decoders[funame].do
137
138 if "mmu0" in self.decoders:
139 self.decoders["mmu0"].mmu0_spr_dec = self.decoders["spr0"]
140
141 def elaborate(self, platform):
142 m = Module()
143 # for testing purposes, to cut down on build time in coriolis2
144 if hasattr(self.pspec, "nocore") and self.pspec.nocore == True:
145 x = Signal() # dummy signal
146 m.d.sync += x.eq(~x)
147 return m
148 comb = m.d.comb
149
150 m.submodules.fus = self.fus
151 m.submodules.l0 = l0 = self.l0
152 self.regs.elaborate_into(m, platform)
153 regs = self.regs
154 fus = self.fus.fus
155
156 # connect decoders
157 for k, v in self.decoders.items():
158 setattr(m.submodules, "dec_%s" % v.fn_name, v)
159 comb += v.dec.raw_opcode_in.eq(self.raw_insn_i)
160 comb += v.dec.bigendian.eq(self.bigendian_i)
161 # sigh due to SVP64 RA_OR_ZERO detection connect these too
162 comb += v.sv_a_nz.eq(self.sv_a_nz)
163
164 # ssh, cheat: trap uses the main decoder because of the rewriting
165 self.des[self.trapunit] = self.e.do
166
167 # connect up Function Units, then read/write ports
168 fu_bitdict = self.connect_instruction(m)
169 self.connect_rdports(m, fu_bitdict)
170 self.connect_wrports(m, fu_bitdict)
171
172 return m
173
174 def connect_instruction(self, m):
175 """connect_instruction
176
177 uses decoded (from PowerOp) function unit information from CSV files
178 to ascertain which Function Unit should deal with the current
179 instruction.
180
181 some (such as OP_ATTN, OP_NOP) are dealt with here, including
182 ignoring it and halting the processor. OP_NOP is a bit annoying
183 because the issuer expects busy flag still to be raised then lowered.
184 (this requires a fake counter to be set).
185 """
186 comb, sync = m.d.comb, m.d.sync
187 fus = self.fus.fus
188
189 # enable-signals for each FU, get one bit for each FU (by name)
190 fu_enable = Signal(len(fus), reset_less=True)
191 fu_bitdict = {}
192 for i, funame in enumerate(fus.keys()):
193 fu_bitdict[funame] = fu_enable[i]
194
195 # enable the required Function Unit based on the opcode decode
196 # note: this *only* works correctly for simple core when one and
197 # *only* one FU is allocated per instruction
198 for funame, fu in fus.items():
199 fnunit = fu.fnunit.value
200 enable = Signal(name="en_%s" % funame, reset_less=True)
201 comb += enable.eq((self.e.do.fn_unit & fnunit).bool())
202 comb += fu_bitdict[funame].eq(enable)
203
204 # sigh - need a NOP counter
205 counter = Signal(2)
206 with m.If(counter != 0):
207 sync += counter.eq(counter - 1)
208 comb += self.busy_o.eq(1)
209
210 with m.If(self.ivalid_i): # run only when valid
211 with m.Switch(self.e.do.insn_type):
212 # check for ATTN: halt if true
213 with m.Case(MicrOp.OP_ATTN):
214 m.d.sync += self.core_terminate_o.eq(1)
215
216 with m.Case(MicrOp.OP_NOP):
217 sync += counter.eq(2)
218 comb += self.busy_o.eq(1)
219
220 with m.Default():
221 # connect up instructions. only one enabled at a time
222 for funame, fu in fus.items():
223 do = self.des[funame]
224 enable = fu_bitdict[funame]
225
226 # run this FunctionUnit if enabled
227 # route op, issue, busy, read flags and mask to FU
228 with m.If(enable):
229 # operand comes from the *local* decoder
230 comb += fu.oper_i.eq_from(do)
231 #comb += fu.oper_i.eq_from_execute1(e)
232 comb += fu.issue_i.eq(self.issue_i)
233 comb += self.busy_o.eq(fu.busy_o)
234 # rdmask, which is for registers, needs to come
235 # from the *main* decoder
236 rdmask = get_rdflags(self.e, fu)
237 comb += fu.rdmaskn.eq(~rdmask)
238
239 return fu_bitdict
240
241 def connect_rdport(self, m, fu_bitdict, rdpickers, regfile, regname, fspec):
242 comb, sync = m.d.comb, m.d.sync
243 fus = self.fus.fus
244 regs = self.regs
245
246 rpidx = regname
247
248 # select the required read port. these are pre-defined sizes
249 rfile = regs.rf[regfile.lower()]
250 rport = rfile.r_ports[rpidx]
251 print("read regfile", rpidx, regfile, regs.rf.keys(),
252 rfile, rfile.unary)
253
254 fspecs = fspec
255 if not isinstance(fspecs, list):
256 fspecs = [fspecs]
257
258 rdflags = []
259 pplen = 0
260 reads = []
261 ppoffs = []
262 for i, fspec in enumerate(fspecs):
263 # get the regfile specs for this regfile port
264 (rf, read, write, wid, fuspec) = fspec
265 print ("fpsec", i, fspec, len(fuspec))
266 ppoffs.append(pplen) # record offset for picker
267 pplen += len(fuspec)
268 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
269 rdflag = Signal(name=name, reset_less=True)
270 comb += rdflag.eq(rf)
271 rdflags.append(rdflag)
272 reads.append(read)
273
274 print ("pplen", pplen)
275
276 # create a priority picker to manage this port
277 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
278 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
279
280 rens = []
281 addrs = []
282 for i, fspec in enumerate(fspecs):
283 (rf, read, write, wid, fuspec) = fspec
284 # connect up the FU req/go signals, and the reg-read to the FU
285 # and create a Read Broadcast Bus
286 for pi, (funame, fu, idx) in enumerate(fuspec):
287 pi += ppoffs[i]
288
289 # connect request-read to picker input, and output to go-rd
290 fu_active = fu_bitdict[funame]
291 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
292 addr_en = Signal.like(reads[i], name="addr_en_"+name)
293 pick = Signal(name="pick_"+name) # picker input
294 rp = Signal(name="rp_"+name) # picker output
295 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
296
297 # exclude any currently-enabled read-request (mask out active)
298 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
299 ~delay_pick)
300 comb += rdpick.i[pi].eq(pick)
301 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
302
303 # if picked, select read-port "reg select" number to port
304 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
305 sync += delay_pick.eq(rp) # delayed "pick"
306 comb += addr_en.eq(Mux(rp, reads[i], 0))
307
308 # the read-enable happens combinatorially (see mux-bus below)
309 # but it results in the data coming out on a one-cycle delay.
310 if rfile.unary:
311 rens.append(addr_en)
312 else:
313 addrs.append(addr_en)
314 rens.append(rp)
315
316 # use the *delayed* pick signal to put requested data onto bus
317 with m.If(delay_pick):
318 # connect regfile port to input, creating fan-out Bus
319 src = fu.src_i[idx]
320 print("reg connect widths",
321 regfile, regname, pi, funame,
322 src.shape(), rport.data_o.shape())
323 # all FUs connect to same port
324 comb += src.eq(rport.data_o)
325
326 # or-reduce the muxed read signals
327 if rfile.unary:
328 # for unary-addressed
329 comb += rport.ren.eq(ortreereduce_sig(rens))
330 else:
331 # for binary-addressed
332 comb += rport.addr.eq(ortreereduce_sig(addrs))
333 comb += rport.ren.eq(Cat(*rens).bool())
334 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
335
336 def connect_rdports(self, m, fu_bitdict):
337 """connect read ports
338
339 orders the read regspecs into a dict-of-dicts, by regfile, by
340 regport name, then connects all FUs that want that regport by
341 way of a PriorityPicker.
342 """
343 comb, sync = m.d.comb, m.d.sync
344 fus = self.fus.fus
345 regs = self.regs
346
347 # dictionary of lists of regfile read ports
348 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
349
350 # okaay, now we need a PriorityPicker per regfile per regfile port
351 # loootta pickers... peter piper picked a pack of pickled peppers...
352 rdpickers = {}
353 for regfile, spec in byregfiles_rd.items():
354 fuspecs = byregfiles_rdspec[regfile]
355 rdpickers[regfile] = {}
356
357 # argh. an experiment to merge RA and RB in the INT regfile
358 # (we have too many read/write ports)
359 if self.regreduce_en:
360 if regfile == 'INT':
361 fuspecs['rabc'] = [fuspecs.pop('rb')]
362 fuspecs['rabc'].append(fuspecs.pop('rc'))
363 fuspecs['rabc'].append(fuspecs.pop('ra'))
364 if regfile == 'FAST':
365 fuspecs['fast1'] = [fuspecs.pop('fast1')]
366 if 'fast2' in fuspecs:
367 fuspecs['fast1'].append(fuspecs.pop('fast2'))
368 if 'fast3' in fuspecs:
369 fuspecs['fast1'].append(fuspecs.pop('fast3'))
370
371 # for each named regfile port, connect up all FUs to that port
372 for (regname, fspec) in sort_fuspecs(fuspecs):
373 print("connect rd", regname, fspec)
374 self.connect_rdport(m, fu_bitdict, rdpickers, regfile,
375 regname, fspec)
376
377 def connect_wrport(self, m, fu_bitdict, wrpickers, regfile, regname, fspec):
378 comb, sync = m.d.comb, m.d.sync
379 fus = self.fus.fus
380 regs = self.regs
381
382 print("connect wr", regname, fspec)
383 rpidx = regname
384
385 # select the required write port. these are pre-defined sizes
386 print(regfile, regs.rf.keys())
387 rfile = regs.rf[regfile.lower()]
388 wport = rfile.w_ports[rpidx]
389
390 fspecs = fspec
391 if not isinstance(fspecs, list):
392 fspecs = [fspecs]
393
394 pplen = 0
395 writes = []
396 ppoffs = []
397 for i, fspec in enumerate(fspecs):
398 # get the regfile specs for this regfile port
399 (rf, read, write, wid, fuspec) = fspec
400 print ("fpsec", i, fspec, len(fuspec))
401 ppoffs.append(pplen) # record offset for picker
402 pplen += len(fuspec)
403
404 # create a priority picker to manage this port
405 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
406 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
407
408 wsigs = []
409 wens = []
410 addrs = []
411 for i, fspec in enumerate(fspecs):
412 # connect up the FU req/go signals and the reg-read to the FU
413 # these are arbitrated by Data.ok signals
414 (rf, read, write, wid, fuspec) = fspec
415 for pi, (funame, fu, idx) in enumerate(fuspec):
416 pi += ppoffs[i]
417
418 # write-request comes from dest.ok
419 dest = fu.get_out(idx)
420 fu_dest_latch = fu.get_fu_out(idx) # latched output
421 name = "wrflag_%s_%s_%d" % (funame, regname, idx)
422 wrflag = Signal(name=name, reset_less=True)
423 comb += wrflag.eq(dest.ok & fu.busy_o)
424
425 # connect request-write to picker input, and output to go-wr
426 fu_active = fu_bitdict[funame]
427 pick = fu.wr.rel_o[idx] & fu_active # & wrflag
428 comb += wrpick.i[pi].eq(pick)
429 # create a single-pulse go write from the picker output
430 wr_pick = Signal()
431 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
432 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
433
434 # connect the regspec write "reg select" number to this port
435 # only if one FU actually requests (and is granted) the port
436 # will the write-enable be activated
437 addr_en = Signal.like(write)
438 wp = Signal()
439 comb += wp.eq(wr_pick & wrpick.en_o)
440 comb += addr_en.eq(Mux(wp, write, 0))
441 if rfile.unary:
442 wens.append(addr_en)
443 else:
444 addrs.append(addr_en)
445 wens.append(wp)
446
447 # connect regfile port to input
448 print("reg connect widths",
449 regfile, regname, pi, funame,
450 dest.shape(), wport.data_i.shape())
451 wsigs.append(fu_dest_latch)
452
453 # here is where we create the Write Broadcast Bus. simple, eh?
454 comb += wport.data_i.eq(ortreereduce_sig(wsigs))
455 if rfile.unary:
456 # for unary-addressed
457 comb += wport.wen.eq(ortreereduce_sig(wens))
458 else:
459 # for binary-addressed
460 comb += wport.addr.eq(ortreereduce_sig(addrs))
461 comb += wport.wen.eq(ortreereduce_sig(wens))
462
463 def connect_wrports(self, m, fu_bitdict):
464 """connect write ports
465
466 orders the write regspecs into a dict-of-dicts, by regfile,
467 by regport name, then connects all FUs that want that regport
468 by way of a PriorityPicker.
469
470 note that the write-port wen, write-port data, and go_wr_i all need to
471 be on the exact same clock cycle. as there is a combinatorial loop bug
472 at the moment, these all use sync.
473 """
474 comb, sync = m.d.comb, m.d.sync
475 fus = self.fus.fus
476 regs = self.regs
477 # dictionary of lists of regfile write ports
478 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
479
480 # same for write ports.
481 # BLECH! complex code-duplication! BLECH!
482 wrpickers = {}
483 for regfile, spec in byregfiles_wr.items():
484 fuspecs = byregfiles_wrspec[regfile]
485 wrpickers[regfile] = {}
486
487 if self.regreduce_en:
488 # argh, more port-merging
489 if regfile == 'INT':
490 fuspecs['o'] = [fuspecs.pop('o')]
491 fuspecs['o'].append(fuspecs.pop('o1'))
492 if regfile == 'FAST':
493 fuspecs['fast1'] = [fuspecs.pop('fast1')]
494 if 'fast2' in fuspecs:
495 fuspecs['fast1'].append(fuspecs.pop('fast2'))
496 if 'fast3' in fuspecs:
497 fuspecs['fast1'].append(fuspecs.pop('fast3'))
498
499 for (regname, fspec) in sort_fuspecs(fuspecs):
500 self.connect_wrport(m, fu_bitdict, wrpickers,
501 regfile, regname, fspec)
502
503 def get_byregfiles(self, readmode):
504
505 mode = "read" if readmode else "write"
506 regs = self.regs
507 fus = self.fus.fus
508 e = self.e # decoded instruction to execute
509
510 # dictionary of lists of regfile ports
511 byregfiles = {}
512 byregfiles_spec = {}
513 for (funame, fu) in fus.items():
514 print("%s ports for %s" % (mode, funame))
515 for idx in range(fu.n_src if readmode else fu.n_dst):
516 if readmode:
517 (regfile, regname, wid) = fu.get_in_spec(idx)
518 else:
519 (regfile, regname, wid) = fu.get_out_spec(idx)
520 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
521 if readmode:
522 rdflag, read = regspec_decode_read(e, regfile, regname)
523 write = None
524 else:
525 rdflag, read = None, None
526 wrport, write = regspec_decode_write(e, regfile, regname)
527 if regfile not in byregfiles:
528 byregfiles[regfile] = {}
529 byregfiles_spec[regfile] = {}
530 if regname not in byregfiles_spec[regfile]:
531 byregfiles_spec[regfile][regname] = \
532 (rdflag, read, write, wid, [])
533 # here we start to create "lanes"
534 if idx not in byregfiles[regfile]:
535 byregfiles[regfile][idx] = []
536 fuspec = (funame, fu, idx)
537 byregfiles[regfile][idx].append(fuspec)
538 byregfiles_spec[regfile][regname][4].append(fuspec)
539
540 # ok just print that out, for convenience
541 for regfile, spec in byregfiles.items():
542 print("regfile %s ports:" % mode, regfile)
543 fuspecs = byregfiles_spec[regfile]
544 for regname, fspec in fuspecs.items():
545 [rdflag, read, write, wid, fuspec] = fspec
546 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
547 print(" %s" % regname, wid, read, write, rdflag)
548 for (funame, fu, idx) in fuspec:
549 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
550 print(" ", funame, fu, idx, fusig)
551 print()
552
553 return byregfiles, byregfiles_spec
554
555 def __iter__(self):
556 yield from self.fus.ports()
557 yield from self.e.ports()
558 yield from self.l0.ports()
559 # TODO: regs
560
561 def ports(self):
562 return list(self)
563
564
565 if __name__ == '__main__':
566 pspec = TestMemPspec(ldst_ifacetype='testpi',
567 imem_ifacetype='',
568 addr_wid=48,
569 mask_wid=8,
570 reg_wid=64)
571 dut = NonProductionCore(pspec)
572 vl = rtlil.convert(dut, ports=dut.ports())
573 with open("test_core.il", "w") as f:
574 f.write(vl)