rename truncaddr to splitaddr, return LSBs and MSBs
[soc.git] / src / soc / experiment / l0_cache.py
1 """L0 Cache/Buffer
2
3 This first version is intended for prototyping and test purposes:
4 it has "direct" access to Memory.
5
6 The intention is that this version remains an integral part of the
7 test infrastructure, and, just as with minerva's memory arrangement,
8 a dynamic runtime config *selects* alternative memory arrangements
9 rather than *replaces and discards* this code.
10
11 Links:
12
13 * https://bugs.libre-soc.org/show_bug.cgi?id=216
14 * https://libre-soc.org/3d_gpu/architecture/memory_and_cache/
15
16 """
17
18 from nmigen.compat.sim import run_simulation, Settle
19 from nmigen.cli import verilog, rtlil
20 from nmigen import Module, Signal, Mux, Elaboratable, Array, Cat
21 from nmutil.iocontrol import RecordObject
22 from nmigen.utils import log2_int
23 from nmigen.hdl.rec import Record, Layout
24
25 from nmutil.latch import SRLatch, latchregister
26 from soc.decoder.power_decoder2 import Data
27 from soc.decoder.power_enums import InternalOp
28 from soc.regfile.regfile import ortreereduce
29 from nmutil.util import treereduce
30
31 from soc.experiment.compldst import CompLDSTOpSubset
32 from soc.decoder.power_decoder2 import Data
33 #from nmutil.picker import PriorityPicker
34 from nmigen.lib.coding import PriorityEncoder
35 from soc.scoreboard.addr_split import LDSTSplitter
36 from soc.scoreboard.addr_match import LenExpand
37
38 # for testing purposes
39 from soc.experiment.testmem import TestMemory
40
41
42 class PortInterface(RecordObject):
43 """PortInterface
44
45 defines the interface - the API - that the LDSTCompUnit connects
46 to. note that this is NOT a "fire-and-forget" interface. the
47 LDSTCompUnit *must* be kept appraised that the request is in
48 progress, and only when it has a 100% successful completion rate
49 can the notification be given (busy dropped).
50
51 The interface FSM rules are as follows:
52
53 * if busy_o is asserted, a LD/ST is in progress. further
54 requests may not be made until busy_o is deasserted.
55
56 * only one of is_ld_i or is_st_i may be asserted. busy_o
57 will immediately be asserted and remain asserted.
58
59 * addr.ok is to be asserted when the LD/ST address is known.
60 addr.data is to be valid on the same cycle.
61
62 addr.ok and addr.data must REMAIN asserted until busy_o
63 is de-asserted. this ensures that there is no need
64 for the L0 Cache/Buffer to have an additional address latch
65 (because the LDSTCompUnit already has it)
66
67 * addr_ok_o (or addr_exc_o) must be waited for. these will
68 be asserted *only* for one cycle and one cycle only.
69
70 * addr_exc_o will be asserted if there is no chance that the
71 memory request may be fulfilled.
72
73 busy_o is deasserted on the same cycle as addr_exc_o is asserted.
74
75 * conversely: addr_ok_o must *ONLY* be asserted if there is a
76 HUNDRED PERCENT guarantee that the memory request will be
77 fulfilled.
78
79 * for a LD, ld.ok will be asserted - for only one clock cycle -
80 at any point in the future that is acceptable to the underlying
81 Memory subsystem. the recipient MUST latch ld.data on that cycle.
82
83 busy_o is deasserted on the same cycle as ld.ok is asserted.
84
85 * for a ST, st.ok may be asserted only after addr_ok_o had been
86 asserted, alongside valid st.data at the same time. st.ok
87 must only be asserted for one cycle.
88
89 the underlying Memory is REQUIRED to pick up that data and
90 guarantee its delivery. no back-acknowledgement is required.
91
92 busy_o is deasserted on the cycle AFTER st.ok is asserted.
93 """
94
95 def __init__(self, name=None, regwid=64, addrwid=48):
96
97 self._regwid = regwid
98 self._addrwid = addrwid
99
100 RecordObject.__init__(self, name=name)
101
102 # distinguish op type (ld/st)
103 self.is_ld_i = Signal(reset_less=True)
104 self.is_st_i = Signal(reset_less=True)
105 self.op = CompLDSTOpSubset() # hm insn_type ld/st duplicates here
106
107 # common signals
108 self.busy_o = Signal(reset_less=True) # do not use if busy
109 self.go_die_i = Signal(reset_less=True) # back to reset
110 self.addr = Data(addrwid, "addr_i") # addr/addr-ok
111 # addr is valid (TLB, L1 etc.)
112 self.addr_ok_o = Signal(reset_less=True)
113 self.addr_exc_o = Signal(reset_less=True) # TODO, "type" of exception
114
115 # LD/ST
116 self.ld = Data(regwid, "ld_data_o") # ok to be set by L0 Cache/Buf
117 self.st = Data(regwid, "st_data_i") # ok to be set by CompUnit
118
119 # TODO: elaborate function
120
121
122 class DualPortSplitter(Elaboratable):
123 """DualPortSplitter
124
125 * one incoming PortInterface
126 * two *OUTGOING* PortInterfaces
127 * uses LDSTSplitter to do it
128
129 (actually, thinking about it LDSTSplitter could simply be
130 modified to conform to PortInterface: one in, two out)
131
132 once that is done each pair of ports may be wired directly
133 to the dual ports of L0CacheBuffer
134
135 The split is carried out so that, regardless of alignment or
136 mis-alignment, outgoing PortInterface[0] takes bit 4 == 0
137 of the address, whilst outgoing PortInterface[1] takes
138 bit 4 == 1.
139
140 PortInterface *may* need to be changed so that the length is
141 a binary number (accepting values 1-16).
142 """
143 def __init__(self):
144 self.outp = [PortInterface(name="outp_0"),
145 PortInterface(name="outp_1")]
146 self.inp = PortInterface(name="inp")
147 print(self.outp)
148
149 def elaborate(self, platform):
150 m = Module()
151 comb = m.d.comb
152 m.submodules.splitter = splitter = LDSTSplitter(64, 48, 4)
153 comb += splitter.addr_i.eq(self.inp.addr) #XXX
154 #comb += splitter.len_i.eq()
155 #comb += splitter.valid_i.eq()
156 comb += splitter.is_ld_i.eq(self.inp.is_ld_i)
157 comb += splitter.is_st_i.eq(self.inp.is_st_i)
158 #comb += splitter.st_data_i.eq()
159 #comb += splitter.sld_valid_i.eq()
160 #comb += splitter.sld_data_i.eq()
161 #comb += splitter.sst_valid_i.eq()
162 return m
163
164 class DataMergerRecord(Record):
165 """
166 {data: 128 bit, byte_enable: 16 bit}
167 """
168
169 def __init__(self, name=None):
170 layout = (('data', 128),
171 ('en', 16)
172 )
173
174 Record.__init__(self, Layout(layout), name=name)
175
176 #FIXME: make resetless
177
178 # TODO: formal verification
179
180 class DataMerger(Elaboratable):
181 """DataMerger
182
183 Merges data based on an address-match matrix.
184 Identifies (picks) one (any) row, then uses that row,
185 based on matching address bits, to merge (OR) all data
186 rows into the output.
187
188 Basically, by the time DataMerger is used, all of its incoming data is
189 determined not to conflict. The last step before actually submitting
190 the request to the Memory Subsystem is to work out which requests,
191 on the same 128-bit cache line, can be "merged" due to them being:
192 (A) on the same address (bits 4 and above) (B) having byte-enable
193 lines that (as previously mentioned) do not conflict.
194
195 Therefore, put simply, this module will:
196 (1) pick a row (any row) and identify it by an index labelled "idx"
197 (2) merge all byte-enable lines which are on that same address, as
198 indicated by addr_match_i[idx], onto the output
199 """
200
201 def __init__(self, array_size):
202 """
203 :addr_array_i: an NxN Array of Signals with bits set indicating address
204 match. bits across the diagonal (addr_array_i[x][x])
205 will always be set, to indicate "active".
206 :data_i: an Nx Array of Records {data: 128 bit, byte_enable: 16 bit}
207 :data_o: an Output Record of same type
208 {data: 128 bit, byte_enable: 16 bit}
209 """
210 self.array_size = array_size
211 ul = []
212 for i in range(array_size):
213 ul.append(Signal(array_size,
214 reset_less=True,
215 name="addr_match_%d" % i))
216 self.addr_array_i = Array(ul)
217
218 ul = []
219 for i in range(array_size):
220 ul.append(DataMergerRecord())
221 self.data_i = Array(ul)
222 self.data_o = DataMergerRecord()
223
224 def elaborate(self, platform):
225 m = Module()
226 comb = m.d.comb
227 #(1) pick a row
228 m.submodules.pick = pick = PriorityEncoder(self.array_size)
229 for j in range(self.array_size):
230 comb += pick.i[j].eq(self.addr_array_i[j].bool())
231 valid = ~pick.n
232 idx = pick.o
233 #(2) merge
234 with m.If(valid):
235 l = []
236 for j in range(self.array_size):
237 select = self.addr_array_i[idx][j]
238 r = DataMergerRecord()
239 with m.If(select):
240 comb += r.eq(self.data_i[j])
241 l.append(r)
242 comb += self.data_o.data.eq(ortreereduce(l,"data"))
243 comb += self.data_o.en.eq(ortreereduce(l,"en"))
244
245 return m
246
247
248 class LDSTPort(Elaboratable):
249 def __init__(self, idx, regwid=64, addrwid=48):
250 self.pi = PortInterface("ldst_port%d" % idx, regwid, addrwid)
251
252 def elaborate(self, platform):
253 m = Module()
254 comb, sync = m.d.comb, m.d.sync
255
256 # latches
257 m.submodules.busy_l = busy_l = SRLatch(False, name="busy")
258 m.submodules.cyc_l = cyc_l = SRLatch(True, name="cyc")
259 comb += cyc_l.s.eq(0)
260 comb += cyc_l.r.eq(0)
261
262 # this is a little weird: we let the L0Cache/Buffer set
263 # the outputs: this module just monitors "state".
264
265 # LD/ST requested activates "busy"
266 with m.If(self.pi.is_ld_i | self.pi.is_st_i):
267 comb += busy_l.s.eq(1)
268
269 # monitor for an exception or the completion of LD.
270 with m.If(self.pi.addr_exc_o):
271 comb += busy_l.r.eq(1)
272
273 # however ST needs one cycle before busy is reset
274 with m.If(self.pi.st.ok | self.pi.ld.ok):
275 comb += cyc_l.s.eq(1)
276
277 with m.If(cyc_l.q):
278 comb += cyc_l.r.eq(1)
279 comb += busy_l.r.eq(1)
280
281 # busy latch outputs to interface
282 comb += self.pi.busy_o.eq(busy_l.q)
283
284 return m
285
286 def __iter__(self):
287 yield self.pi.is_ld_i
288 yield self.pi.is_st_i
289 yield from self.pi.op.ports()
290 yield self.pi.busy_o
291 yield self.pi.go_die_i
292 yield from self.pi.addr.ports()
293 yield self.pi.addr_ok_o
294 yield self.pi.addr_exc_o
295
296 yield from self.pi.ld.ports()
297 yield from self.pi.st.ports()
298
299 def ports(self):
300 return list(self)
301
302
303 class L0CacheBuffer(Elaboratable):
304 """L0 Cache / Buffer
305
306 Note that the final version will have *two* interfaces per LDSTCompUnit,
307 to cover mis-aligned requests, as well as *two* 128-bit L1 Cache
308 interfaces: one for odd (addr[4] == 1) and one for even (addr[4] == 1).
309
310 This version is to be used for test purposes (and actively maintained
311 for such, rather than "replaced")
312
313 There are much better ways to implement this. However it's only
314 a "demo" / "test" class, and one important aspect: it responds
315 combinatorially, where a nmigen FSM's state-changes only activate
316 on clock-sync boundaries.
317 """
318
319 def __init__(self, n_units, mem, regwid=64, addrwid=48):
320 self.n_units = n_units
321 self.mem = mem
322 self.regwid = regwid
323 self.addrwid = addrwid
324 ul = []
325 for i in range(n_units):
326 ul.append(LDSTPort(i, regwid, addrwid))
327 self.dports = Array(ul)
328
329 @property
330 def addrbits(self):
331 return log2_int(self.mem.regwid//8)
332
333 def splitaddr(self, addr):
334 """split the address into top and bottom bits of the memory granularity
335 """
336 return addr[:self.addrbits], addr[self.addrbits:]
337
338 def elaborate(self, platform):
339 m = Module()
340 comb, sync = m.d.comb, m.d.sync
341
342 # connect the ports as modules
343 for i in range(self.n_units):
344 setattr(m.submodules, "port%d" % i, self.dports[i])
345
346 # state-machine latches
347 m.submodules.st_active = st_active = SRLatch(False, name="st_active")
348 m.submodules.ld_active = ld_active = SRLatch(False, name="ld_active")
349 m.submodules.reset_l = reset_l = SRLatch(True, name="reset")
350 m.submodules.idx_l = idx_l = SRLatch(False, name="idx_l")
351 m.submodules.adrok_l = adrok_l = SRLatch(False, name="addr_acked")
352
353 # find one LD (or ST) and do it. only one per cycle.
354 # TODO: in the "live" (production) L0Cache/Buffer, merge multiple
355 # LD/STs using mask-expansion - see LenExpand class
356
357 m.submodules.ldpick = ldpick = PriorityEncoder(self.n_units)
358 m.submodules.stpick = stpick = PriorityEncoder(self.n_units)
359 m.submodules.lenexp = lenexp = LenExpand(self.regwid//8, 8)
360
361 lds = Signal(self.n_units, reset_less=True)
362 sts = Signal(self.n_units, reset_less=True)
363 ldi = []
364 sti = []
365 for i in range(self.n_units):
366 pi = self.dports[i].pi
367 ldi.append(pi.is_ld_i & pi.busy_o) # accumulate ld-req signals
368 sti.append(pi.is_st_i & pi.busy_o) # accumulate st-req signals
369 # put the requests into the priority-pickers
370 comb += ldpick.i.eq(Cat(*ldi))
371 comb += stpick.i.eq(Cat(*sti))
372
373 # hmm, have to select (record) the right port index
374 nbits = log2_int(self.n_units, False)
375 ld_idx = Signal(nbits, reset_less=False)
376 st_idx = Signal(nbits, reset_less=False)
377 # use these because of the sync-and-comb pass-through capability
378 latchregister(m, ldpick.o, ld_idx, idx_l.qn, name="ld_idx_l")
379 latchregister(m, stpick.o, st_idx, idx_l.qn, name="st_idx_l")
380
381 # convenience variables to reference the "picked" port
382 ldport = self.dports[ld_idx].pi
383 stport = self.dports[st_idx].pi
384 # and the memory ports
385 rdport = self.mem.rdport
386 wrport = self.mem.wrport
387
388 # Priority-Pickers pick one and only one request, capture its index.
389 # from that point on this code *only* "listens" to that port.
390
391 sync += adrok_l.s.eq(0)
392 comb += adrok_l.r.eq(0)
393 with m.If(~ldpick.n):
394 comb += ld_active.s.eq(1) # activate LD mode
395 comb += idx_l.r.eq(1) # pick (and capture) the port index
396 with m.Elif(~stpick.n):
397 comb += st_active.s.eq(1) # activate ST mode
398 comb += idx_l.r.eq(1) # pick (and capture) the port index
399
400 # from this point onwards, with the port "picked", it stays picked
401 # until ld_active (or st_active) are de-asserted.
402
403 # if now in "LD" mode: wait for addr_ok, then send the address out
404 # to memory, acknowledge address, and send out LD data
405 with m.If(ld_active.q):
406 with m.If(ldport.addr.ok & adrok_l.qn):
407 comb += rdport.addr.eq(ldport.addr.data) # addr ok, send thru
408 comb += ldport.addr_ok_o.eq(1) # acknowledge addr ok
409 sync += adrok_l.s.eq(1) # and pull "ack" latch
410
411 # if now in "ST" mode: likewise do the same but with "ST"
412 # to memory, acknowledge address, and send out LD data
413 with m.If(st_active.q):
414 with m.If(stport.addr.ok):
415 comb += wrport.addr.eq(stport.addr.data) # addr ok, send thru
416 with m.If(adrok_l.qn):
417 comb += stport.addr_ok_o.eq(1) # acknowledge addr ok
418 sync += adrok_l.s.eq(1) # and pull "ack" latch
419
420 # NOTE: in both these, below, the port itself takes care
421 # of de-asserting its "busy_o" signal, based on either ld.ok going
422 # high (by us, here) or by st.ok going high (by the LDSTCompUnit).
423
424 # for LD mode, when addr has been "ok'd", assume that (because this
425 # is a "Memory" test-class) the memory read data is valid.
426 comb += reset_l.s.eq(0)
427 comb += reset_l.r.eq(0)
428 with m.If(ld_active.q & adrok_l.q):
429 comb += ldport.ld.data.eq(rdport.data) # put data out
430 comb += ldport.ld.ok.eq(1) # indicate data valid
431 comb += reset_l.s.eq(1) # reset mode after 1 cycle
432
433 # for ST mode, when addr has been "ok'd", wait for incoming "ST ok"
434 with m.If(st_active.q & stport.st.ok):
435 comb += wrport.data.eq(stport.st.data) # write st to mem
436 comb += wrport.en.eq(1) # enable write
437 comb += reset_l.s.eq(1) # reset mode after 1 cycle
438
439 # after waiting one cycle (reset_l is "sync" mode), reset the port
440 with m.If(reset_l.q):
441 comb += idx_l.s.eq(1) # deactivate port-index selector
442 comb += ld_active.r.eq(1) # leave the ST active for 1 cycle
443 comb += st_active.r.eq(1) # leave the ST active for 1 cycle
444 comb += reset_l.r.eq(1) # clear reset
445 comb += adrok_l.r.eq(1) # address reset
446
447 return m
448
449 def ports(self):
450 for p in self.dports:
451 yield from p.ports()
452
453
454 class TstL0CacheBuffer(Elaboratable):
455 def __init__(self, n_units=3, regwid=16, addrwid=4):
456 self.mem = TestMemory(regwid, addrwid)
457 self.l0 = L0CacheBuffer(n_units, self.mem, regwid, addrwid)
458
459 def elaborate(self, platform):
460 m = Module()
461 m.submodules.mem = self.mem
462 m.submodules.l0 = self.l0
463
464 return m
465
466 def ports(self):
467 yield from self.l0.ports()
468 yield self.mem.rdport.addr
469 yield self.mem.rdport.data
470 yield self.mem.wrport.addr
471 yield self.mem.wrport.data
472 # TODO: mem ports
473
474
475 def wait_busy(port, no=False):
476 while True:
477 busy = yield port.pi.busy_o
478 print("busy", no, busy)
479 if bool(busy) == no:
480 break
481 yield
482
483
484 def wait_addr(port):
485 while True:
486 addr_ok = yield port.pi.addr_ok_o
487 print("addrok", addr_ok)
488 if not addr_ok:
489 break
490 yield
491
492
493 def wait_ldok(port):
494 while True:
495 ldok = yield port.pi.ld.ok
496 print("ldok", ldok)
497 if ldok:
498 break
499 yield
500
501
502 def l0_cache_st(dut, addr, data):
503 l0 = dut.l0
504 mem = dut.mem
505 port0 = l0.dports[0]
506 port1 = l0.dports[1]
507
508 # have to wait until not busy
509 yield from wait_busy(port1, no=False) # wait until not busy
510
511 # set up a ST on the port. address first:
512 yield port1.pi.is_st_i.eq(1) # indicate LD
513
514 yield port1.pi.addr.data.eq(addr) # set address
515 yield port1.pi.addr.ok.eq(1) # set ok
516 yield from wait_addr(port1) # wait until addr ok
517 # yield # not needed, just for checking
518 # yield # not needed, just for checking
519 # assert "ST" for one cycle (required by the API)
520 yield port1.pi.st.data.eq(data)
521 yield port1.pi.st.ok.eq(1)
522 yield
523 yield port1.pi.st.ok.eq(0)
524
525 # can go straight to reset.
526 yield port1.pi.is_st_i.eq(0) # end
527 yield port1.pi.addr.ok.eq(0) # set !ok
528 # yield from wait_busy(port1, False) # wait until not busy
529
530
531 def l0_cache_ld(dut, addr, expected):
532
533 l0 = dut.l0
534 mem = dut.mem
535 port0 = l0.dports[0]
536 port1 = l0.dports[1]
537
538 # have to wait until not busy
539 yield from wait_busy(port1, no=False) # wait until not busy
540
541 # set up a LD on the port. address first:
542 yield port1.pi.is_ld_i.eq(1) # indicate LD
543
544 yield port1.pi.addr.data.eq(addr) # set address
545 yield port1.pi.addr.ok.eq(1) # set ok
546 yield from wait_addr(port1) # wait until addr ok
547
548 yield from wait_ldok(port1) # wait until ld ok
549 data = yield port1.pi.ld.data
550
551 # cleanup
552 yield port1.pi.is_ld_i.eq(0) # end
553 yield port1.pi.addr.ok.eq(0) # set !ok
554 # yield from wait_busy(port1, no=False) # wait until not busy
555
556 return data
557
558
559 def l0_cache_ldst(dut):
560 yield
561 addr = 0x2
562 data = 0xbeef
563 data2 = 0xf00f
564 #data = 0x4
565 yield from l0_cache_st(dut, 0x2, data)
566 yield from l0_cache_st(dut, 0x3, data2)
567 result = yield from l0_cache_ld(dut, 0x2, data)
568 result2 = yield from l0_cache_ld(dut, 0x3, data2)
569 yield
570 assert data == result, "data %x != %x" % (result, data)
571 assert data2 == result2, "data2 %x != %x" % (result2, data2)
572
573 def data_merger_merge(dut):
574 print("data_merger")
575 #starting with all inputs zero
576 yield Settle()
577 en = yield dut.data_o.en
578 data = yield dut.data_o.data
579 assert en == 0, "en must be zero"
580 assert data == 0, "data must be zero"
581 yield
582
583 yield dut.addr_array_i[0].eq(0xFF)
584 for j in range(dut.array_size):
585 yield dut.data_i[j].en.eq(1 << j)
586 yield dut.data_i[j].data.eq(0xFF << (16*j))
587 yield Settle()
588
589 en = yield dut.data_o.en
590 data = yield dut.data_o.data
591 assert data == 0xff00ff00ff00ff00ff00ff00ff00ff
592 assert en == 0xff
593 yield
594
595 def test_l0_cache():
596
597 dut = TstL0CacheBuffer(regwid=64)
598 #vl = rtlil.convert(dut, ports=dut.ports())
599 #with open("test_basic_l0_cache.il", "w") as f:
600 # f.write(vl)
601
602 run_simulation(dut, l0_cache_ldst(dut),
603 vcd_name='test_l0_cache_basic.vcd')
604
605 def test_data_merger():
606
607 dut = DataMerger(8)
608 #vl = rtlil.convert(dut, ports=dut.ports())
609 #with open("test_data_merger.il", "w") as f:
610 # f.write(vl)
611
612 run_simulation(dut, data_merger_merge(dut),
613 vcd_name='test_data_merger.vcd')
614
615 def test_dual_port_splitter():
616
617 dut = DualPortSplitter()
618 #vl = rtlil.convert(dut, ports=dut.ports())
619 #with open("test_data_merger.il", "w") as f:
620 # f.write(vl)
621
622 #run_simulation(dut, data_merger_merge(dut),
623 # vcd_name='test_dual_port_splitter.vcd')
624
625 if __name__ == '__main__':
626 test_l0_cache()
627 test_data_merger()
628 #test_dual_port_splitter()