RADIX: implement memassign and call
[soc.git] / src / soc / decoder / isa / caller.py
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2020, 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Copyright (C) 2020 Michael Nolan
4 # Funded by NLnet http://nlnet.nl
5 """core of the python-based POWER9 simulator
6
7 this is part of a cycle-accurate POWER9 simulator. its primary purpose is
8 not speed, it is for both learning and educational purposes, as well as
9 a method of verifying the HDL.
10
11 related bugs:
12
13 * https://bugs.libre-soc.org/show_bug.cgi?id=424
14 """
15
16 from nmigen.back.pysim import Settle
17 from functools import wraps
18 from copy import copy
19 from soc.decoder.orderedset import OrderedSet
20 from soc.decoder.selectable_int import (FieldSelectableInt, SelectableInt,
21 selectconcat)
22 from soc.decoder.power_enums import (spr_dict, spr_byname, XER_bits,
23 insns, MicrOp, In1Sel, In2Sel, In3Sel,
24 OutSel, CROutSel)
25 from soc.decoder.helpers import exts, gtu, ltu, undefined
26 from soc.consts import PIb, MSRb # big-endian (PowerISA versions)
27 from soc.decoder.power_svp64 import SVP64RM, decode_extra
28
29 from collections import namedtuple
30 import math
31 import sys
32
33 instruction_info = namedtuple('instruction_info',
34 'func read_regs uninit_regs write_regs ' +
35 'special_regs op_fields form asmregs')
36
37 special_sprs = {
38 'LR': 8,
39 'CTR': 9,
40 'TAR': 815,
41 'XER': 1,
42 'VRSAVE': 256}
43
44
45 def swap_order(x, nbytes):
46 x = x.to_bytes(nbytes, byteorder='little')
47 x = int.from_bytes(x, byteorder='big', signed=False)
48 return x
49
50
51 REG_SORT_ORDER = {
52 # TODO (lkcl): adjust other registers that should be in a particular order
53 # probably CA, CA32, and CR
54 "RT": 0,
55 "RA": 0,
56 "RB": 0,
57 "RS": 0,
58 "CR": 0,
59 "LR": 0,
60 "CTR": 0,
61 "TAR": 0,
62 "CA": 0,
63 "CA32": 0,
64 "MSR": 0,
65
66 "overflow": 1,
67 }
68
69
70 def create_args(reglist, extra=None):
71 retval = list(OrderedSet(reglist))
72 retval.sort(key=lambda reg: REG_SORT_ORDER[reg])
73 if extra is not None:
74 return [extra] + retval
75 return retval
76
77
78 # very quick, TODO move to SelectableInt utils later
79 def genmask(shift, size):
80 res = SelectableInt(0, size)
81 for i in range(size):
82 if i < shift:
83 res[size-1-i] = SelectableInt(1, 1)
84 return res
85
86 """
87 Get Root Page
88
89 //Accessing 2nd double word of partition table (pate1)
90 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.1
91 // PTCR Layout
92 // ====================================================
93 // -----------------------------------------------
94 // | /// | PATB | /// | PATS |
95 // -----------------------------------------------
96 // 0 4 51 52 58 59 63
97 // PATB[4:51] holds the base address of the Partition Table,
98 // right shifted by 12 bits.
99 // This is because the address of the Partition base is
100 // 4k aligned. Hence, the lower 12bits, which are always
101 // 0 are ommitted from the PTCR.
102 //
103 // Thus, The Partition Table Base is obtained by (PATB << 12)
104 //
105 // PATS represents the partition table size right-shifted by 12 bits.
106 // The minimal size of the partition table is 4k.
107 // Thus partition table size = (1 << PATS + 12).
108 //
109 // Partition Table
110 // ====================================================
111 // 0 PATE0 63 PATE1 127
112 // |----------------------|----------------------|
113 // | | |
114 // |----------------------|----------------------|
115 // | | |
116 // |----------------------|----------------------|
117 // | | | <-- effLPID
118 // |----------------------|----------------------|
119 // .
120 // .
121 // .
122 // |----------------------|----------------------|
123 // | | |
124 // |----------------------|----------------------|
125 //
126 // The effective LPID forms the index into the Partition Table.
127 //
128 // Each entry in the partition table contains 2 double words, PATE0, PATE1,
129 // corresponding to that partition.
130 //
131 // In case of Radix, The structure of PATE0 and PATE1 is as follows.
132 //
133 // PATE0 Layout
134 // -----------------------------------------------
135 // |1|RTS1|/| RPDB | RTS2 | RPDS |
136 // -----------------------------------------------
137 // 0 1 2 3 4 55 56 58 59 63
138 //
139 // HR[0] : For Radix Page table, first bit should be 1.
140 // RTS1[1:2] : Gives one fragment of the Radix treesize
141 // RTS2[56:58] : Gives the second fragment of the Radix Tree size.
142 // RTS = (RTS1 << 3 + RTS2) + 31.
143 //
144 // RPDB[4:55] = Root Page Directory Base.
145 // RPDS = Logarithm of Root Page Directory Size right shifted by 3.
146 // Thus, Root page directory size = 1 << (RPDS + 3).
147 // Note: RPDS >= 5.
148 //
149 // PATE1 Layout
150 // -----------------------------------------------
151 // |///| PRTB | // | PRTS |
152 // -----------------------------------------------
153 // 0 3 4 51 52 58 59 63
154 //
155 // PRTB[4:51] = Process Table Base. This is aligned to size.
156 // PRTS[59: 63] = Process Table Size right shifted by 12.
157 // Minimal size of the process table is 4k.
158 // Process Table Size = (1 << PRTS + 12).
159 // Note: PRTS <= 24.
160 //
161 // Computing the size aligned Process Table Base:
162 // table_base = (PRTB & ~((1 << PRTS) - 1)) << 12
163 // Thus, the lower 12+PRTS bits of table_base will
164 // be zero.
165
166
167 //Ref: Power ISA Manual v3.0B, Book-III, section 5.7.6.2
168 //
169 // Process Table
170 // ==========================
171 // 0 PRTE0 63 PRTE1 127
172 // |----------------------|----------------------|
173 // | | |
174 // |----------------------|----------------------|
175 // | | |
176 // |----------------------|----------------------|
177 // | | | <-- effPID
178 // |----------------------|----------------------|
179 // .
180 // .
181 // .
182 // |----------------------|----------------------|
183 // | | |
184 // |----------------------|----------------------|
185 //
186 // The effective Process id (PID) forms the index into the Process Table.
187 //
188 // Each entry in the partition table contains 2 double words, PRTE0, PRTE1,
189 // corresponding to that process
190 //
191 // In case of Radix, The structure of PRTE0 and PRTE1 is as follows.
192 //
193 // PRTE0 Layout
194 // -----------------------------------------------
195 // |/|RTS1|/| RPDB | RTS2 | RPDS |
196 // -----------------------------------------------
197 // 0 1 2 3 4 55 56 58 59 63
198 //
199 // RTS1[1:2] : Gives one fragment of the Radix treesize
200 // RTS2[56:58] : Gives the second fragment of the Radix Tree size.
201 // RTS = (RTS1 << 3 + RTS2) << 31,
202 // since minimal Radix Tree size is 4G.
203 //
204 // RPDB = Root Page Directory Base.
205 // RPDS = Root Page Directory Size right shifted by 3.
206 // Thus, Root page directory size = RPDS << 3.
207 // Note: RPDS >= 5.
208 //
209 // PRTE1 Layout
210 // -----------------------------------------------
211 // | /// |
212 // -----------------------------------------------
213 // 0 63
214 // All bits are reserved.
215
216
217 """
218
219 # see qemu/target/ppc/mmu-radix64.c for reference
220 class RADIX:
221 def __init__(self, mem, caller):
222 self.mem = mem
223 self.caller = caller
224
225 # cached page table stuff
226 self.pgtbl0 = 0
227 self.pt0_valid = False
228 self.pgtbl3 = 0
229 self.pt3_valid = False
230
231 def __call__(self,*args, **kwargs):
232 print("TODO: implement RADIX.__call__()")
233 print(args)
234 print(kwargs)
235 return None
236
237 def ld(self, address, width=8, swap=True, check_in_mem=False):
238 print("RADIX: ld from addr 0x%x width %d" % (address, width))
239
240 pte = self._walk_tree()
241 # use pte to caclculate phys address
242 return self.mem.ld(address, width, swap, check_in_mem)
243
244 # TODO implement
245 def st(self, addr, v, width=8, swap=True):
246 print("RADIX: st to addr 0x%x width %d data %x" % (addr, width, v))
247 # use pte to caclculate phys address (addr)
248 return self.mem.st(addr, v, width, swap)
249
250 def memassign(self, addr, sz, val):
251 print("memassign", addr, sz, val)
252 self.st(addr.value, val.value, sz, swap=False)
253
254 def _next_level(self):
255 return True
256 ## DSISR_R_BADCONFIG
257 ## read_entry
258 ## DSISR_NOPTE
259 ## Prepare for next iteration
260
261 def _walk_tree(self):
262 """walk tree
263
264 // vaddr 64 Bit
265 // vaddr |-----------------------------------------------------|
266 // | Unused | Used |
267 // |-----------|-----------------------------------------|
268 // | 0000000 | usefulBits = X bits (typically 52) |
269 // |-----------|-----------------------------------------|
270 // | |<--Cursize---->| |
271 // | | Index | |
272 // | | into Page | |
273 // | | Directory | |
274 // |-----------------------------------------------------|
275 // | |
276 // V |
277 // PDE |---------------------------| |
278 // |V|L|//| NLB |///|NLS| |
279 // |---------------------------| |
280 // PDE = Page Directory Entry |
281 // [0] = V = Valid Bit |
282 // [1] = L = Leaf bit. If 0, then |
283 // [4:55] = NLB = Next Level Base |
284 // right shifted by 8 |
285 // [59:63] = NLS = Next Level Size |
286 // | NLS >= 5 |
287 // | V
288 // | |--------------------------|
289 // | | usfulBits = X-Cursize |
290 // | |--------------------------|
291 // |---------------------><--NLS-->| |
292 // | Index | |
293 // | into | |
294 // | PDE | |
295 // |--------------------------|
296 // |
297 // If the next PDE obtained by |
298 // (NLB << 8 + 8 * index) is a |
299 // nonleaf, then repeat the above. |
300 // |
301 // If the next PDE is a leaf, |
302 // then Leaf PDE structure is as |
303 // follows |
304 // |
305 // |
306 // Leaf PDE |
307 // |------------------------------| |----------------|
308 // |V|L|sw|//|RPN|sw|R|C|/|ATT|EAA| | usefulBits |
309 // |------------------------------| |----------------|
310 // [0] = V = Valid Bit |
311 // [1] = L = Leaf Bit = 1 if leaf |
312 // PDE |
313 // [2] = Sw = Sw bit 0. |
314 // [7:51] = RPN = Real Page Number, V
315 // real_page = RPN << 12 -------------> Logical OR
316 // [52:54] = Sw Bits 1:3 |
317 // [55] = R = Reference |
318 // [56] = C = Change V
319 // [58:59] = Att = Physical Address
320 // 0b00 = Normal Memory
321 // 0b01 = SAO
322 // 0b10 = Non Idenmpotent
323 // 0b11 = Tolerant I/O
324 // [60:63] = Encoded Access
325 // Authority
326 //
327 """
328 # walk tree starts on prtbl
329 while True:
330 ret = self._next_level()
331 if ret: return ret
332
333 def _decode_prte(self, data):
334 """PRTE0 Layout
335 -----------------------------------------------
336 |/|RTS1|/| RPDB | RTS2 | RPDS |
337 -----------------------------------------------
338 0 1 2 3 4 55 56 58 59 63
339 """
340 # note that SelectableInt does big-endian! so the indices
341 # below *directly* match the spec, unlike microwatt which
342 # has to turn them around (to LE)
343 zero = SelectableInt(0, 1)
344 rts = selectconcat(zero,
345 data[56:59], # RTS2
346 data[1:3], # RTS1
347 )
348 masksize = data[59:64] # RPDS
349 mbits = selectconcat(zero, masksize)
350 pgbase = selectconcat(data[8:56], # part of RPDB
351 SelectableInt(0, 16),)
352
353 return (rts, mbits, pgbase)
354
355 def _segment_check(self, addr, mbits, shift):
356 """checks segment valid
357 mbits := '0' & r.mask_size;
358 v.shift := r.shift + (31 - 12) - mbits;
359 nonzero := or(r.addr(61 downto 31) and not finalmask(30 downto 0));
360 if r.addr(63) /= r.addr(62) or nonzero = '1' then
361 v.state := RADIX_FINISH;
362 v.segerror := '1';
363 elsif mbits < 5 or mbits > 16 or mbits > (r.shift + (31 - 12)) then
364 v.state := RADIX_FINISH;
365 v.badtree := '1';
366 else
367 v.state := RADIX_LOOKUP;
368 """
369 # note that SelectableInt does big-endian! so the indices
370 # below *directly* match the spec, unlike microwatt which
371 # has to turn them around (to LE)
372 mask = genmask(shift, 43)
373 nonzero = addr[1:32] & mask[12:43] # mask 31 LSBs (BE numbered 12:43)
374 print ("RADIX _segment_check nonzero", bin(nonzero.value))
375 print ("RADIX _segment_check addr[0-1]", addr[0].value, addr[1].value)
376 if addr[0] != addr[1] or nonzero == 1:
377 return "segerror"
378 limit = shift + (31 - 12)
379 if mbits < 5 or mbits > 16 or mbits > limit:
380 return "badtree"
381 new_shift = shift + (31 - 12) - mbits
382 return new_shift
383
384 def _check_perms(self):
385 """check page permissions
386 -- test leaf bit
387 if data(62) = '1' then
388 -- check permissions and RC bits
389 perm_ok := '0';
390 if r.priv = '1' or data(3) = '0' then
391 if r.iside = '0' then
392 perm_ok := data(1) or (data(2) and not r.store);
393 else
394 -- no IAMR, so no KUEP support for now
395 -- deny execute permission if cache inhibited
396 perm_ok := data(0) and not data(5);
397 end if;
398 end if;
399 rc_ok := data(8) and (data(7) or not r.store);
400 if perm_ok = '1' and rc_ok = '1' then
401 v.state := RADIX_LOAD_TLB;
402 else
403 v.state := RADIX_FINISH;
404 v.perm_err := not perm_ok;
405 -- permission error takes precedence over RC error
406 v.rc_error := perm_ok;
407 end if;
408 """
409
410 def _get_prtable_addr(self, prtbl, addr):
411 """
412 if r.addr(63) = '1' then
413 effpid := x"00000000";
414 else
415 effpid := r.pid;
416 end if;
417 prtable_addr := x"00" & r.prtbl(55 downto 36) &
418 ((r.prtbl(35 downto 12) and not finalmask(23 downto 0)) or
419 (effpid(31 downto 8) and finalmask(23 downto 0))) &
420 effpid(7 downto 0) & "0000";
421 """
422
423 def _get_pgtable_addr(self):
424 """
425 pgtable_addr := x"00" & r.pgbase(55 downto 19) &
426 ((r.pgbase(18 downto 3) and not mask) or (addrsh and mask)) &
427 "000";
428 """
429
430 def _get_pte(self):
431 """
432 pte := x"00" &
433 ((r.pde(55 downto 12) and not finalmask) or (r.addr(55 downto 12) and finalmask))
434 & r.pde(11 downto 0);
435 """
436
437
438 class Mem:
439
440 def __init__(self, row_bytes=8, initial_mem=None):
441 self.mem = {}
442 self.bytes_per_word = row_bytes
443 self.word_log2 = math.ceil(math.log2(row_bytes))
444 print("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
445 if not initial_mem:
446 return
447
448 # different types of memory data structures recognised (for convenience)
449 if isinstance(initial_mem, list):
450 initial_mem = (0, initial_mem)
451 if isinstance(initial_mem, tuple):
452 startaddr, mem = initial_mem
453 initial_mem = {}
454 for i, val in enumerate(mem):
455 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
456
457 for addr, (val, width) in initial_mem.items():
458 #val = swap_order(val, width)
459 self.st(addr, val, width, swap=False)
460
461 def _get_shifter_mask(self, wid, remainder):
462 shifter = ((self.bytes_per_word - wid) - remainder) * \
463 8 # bits per byte
464 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
465 # BE/LE mode?
466 shifter = remainder * 8
467 mask = (1 << (wid * 8)) - 1
468 print("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
469 return shifter, mask
470
471 # TODO: Implement ld/st of lesser width
472 def ld(self, address, width=8, swap=True, check_in_mem=False):
473 print("ld from addr 0x{:x} width {:d}".format(address, width))
474 remainder = address & (self.bytes_per_word - 1)
475 address = address >> self.word_log2
476 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
477 if address in self.mem:
478 val = self.mem[address]
479 elif check_in_mem:
480 return None
481 else:
482 val = 0
483 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
484
485 if width != self.bytes_per_word:
486 shifter, mask = self._get_shifter_mask(width, remainder)
487 print("masking", hex(val), hex(mask << shifter), shifter)
488 val = val & (mask << shifter)
489 val >>= shifter
490 if swap:
491 val = swap_order(val, width)
492 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
493 return val
494
495 def st(self, addr, v, width=8, swap=True):
496 staddr = addr
497 remainder = addr & (self.bytes_per_word - 1)
498 addr = addr >> self.word_log2
499 print("Writing 0x{:x} to ST 0x{:x} "
500 "memaddr 0x{:x}/{:x}".format(v, staddr, addr, remainder, swap))
501 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
502 if swap:
503 v = swap_order(v, width)
504 if width != self.bytes_per_word:
505 if addr in self.mem:
506 val = self.mem[addr]
507 else:
508 val = 0
509 shifter, mask = self._get_shifter_mask(width, remainder)
510 val &= ~(mask << shifter)
511 val |= v << shifter
512 self.mem[addr] = val
513 else:
514 self.mem[addr] = v
515 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
516
517 def __call__(self, addr, sz):
518 val = self.ld(addr.value, sz, swap=False)
519 print("memread", addr, sz, val)
520 return SelectableInt(val, sz*8)
521
522 def memassign(self, addr, sz, val):
523 print("memassign", addr, sz, val)
524 self.st(addr.value, val.value, sz, swap=False)
525
526
527 class GPR(dict):
528 def __init__(self, decoder, isacaller, svstate, regfile):
529 dict.__init__(self)
530 self.sd = decoder
531 self.isacaller = isacaller
532 self.svstate = svstate
533 for i in range(32):
534 self[i] = SelectableInt(regfile[i], 64)
535
536 def __call__(self, ridx):
537 return self[ridx]
538
539 def set_form(self, form):
540 self.form = form
541
542 def getz(self, rnum):
543 # rnum = rnum.value # only SelectableInt allowed
544 print("GPR getzero", rnum)
545 if rnum == 0:
546 return SelectableInt(0, 64)
547 return self[rnum]
548
549 def _get_regnum(self, attr):
550 getform = self.sd.sigforms[self.form]
551 rnum = getattr(getform, attr)
552 return rnum
553
554 def ___getitem__(self, attr):
555 """ XXX currently not used
556 """
557 rnum = self._get_regnum(attr)
558 offs = self.svstate.srcstep
559 print("GPR getitem", attr, rnum, "srcoffs", offs)
560 return self.regfile[rnum]
561
562 def dump(self):
563 for i in range(0, len(self), 8):
564 s = []
565 for j in range(8):
566 s.append("%08x" % self[i+j].value)
567 s = ' '.join(s)
568 print("reg", "%2d" % i, s)
569
570
571 class PC:
572 def __init__(self, pc_init=0):
573 self.CIA = SelectableInt(pc_init, 64)
574 self.NIA = self.CIA + SelectableInt(4, 64) # only true for v3.0B!
575
576 def update_nia(self, is_svp64):
577 increment = 8 if is_svp64 else 4
578 self.NIA = self.CIA + SelectableInt(increment, 64)
579
580 def update(self, namespace, is_svp64):
581 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
582 """
583 self.CIA = namespace['NIA'].narrow(64)
584 self.update_nia(is_svp64)
585 namespace['CIA'] = self.CIA
586 namespace['NIA'] = self.NIA
587
588
589 # Simple-V: see https://libre-soc.org/openpower/sv
590 class SVP64State:
591 def __init__(self, init=0):
592 self.spr = SelectableInt(init, 32)
593 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
594 self.maxvl = FieldSelectableInt(self.spr, tuple(range(0,7)))
595 self.vl = FieldSelectableInt(self.spr, tuple(range(7,14)))
596 self.srcstep = FieldSelectableInt(self.spr, tuple(range(14,21)))
597 self.dststep = FieldSelectableInt(self.spr, tuple(range(21,28)))
598 self.subvl = FieldSelectableInt(self.spr, tuple(range(28,30)))
599 self.svstep = FieldSelectableInt(self.spr, tuple(range(30,32)))
600
601
602 # SVP64 ReMap field
603 class SVP64RMFields:
604 def __init__(self, init=0):
605 self.spr = SelectableInt(init, 24)
606 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
607 self.mmode = FieldSelectableInt(self.spr, [0])
608 self.mask = FieldSelectableInt(self.spr, tuple(range(1,4)))
609 self.elwidth = FieldSelectableInt(self.spr, tuple(range(4,6)))
610 self.ewsrc = FieldSelectableInt(self.spr, tuple(range(6,8)))
611 self.subvl = FieldSelectableInt(self.spr, tuple(range(8,10)))
612 self.extra = FieldSelectableInt(self.spr, tuple(range(10,19)))
613 self.mode = FieldSelectableInt(self.spr, tuple(range(19,24)))
614 # these cover the same extra field, split into parts as EXTRA2
615 self.extra2 = list(range(4))
616 self.extra2[0] = FieldSelectableInt(self.spr, tuple(range(10,12)))
617 self.extra2[1] = FieldSelectableInt(self.spr, tuple(range(12,14)))
618 self.extra2[2] = FieldSelectableInt(self.spr, tuple(range(14,16)))
619 self.extra2[3] = FieldSelectableInt(self.spr, tuple(range(16,18)))
620 self.smask = FieldSelectableInt(self.spr, tuple(range(16,19)))
621 # and here as well, but EXTRA3
622 self.extra3 = list(range(3))
623 self.extra3[0] = FieldSelectableInt(self.spr, tuple(range(10,13)))
624 self.extra3[1] = FieldSelectableInt(self.spr, tuple(range(13,16)))
625 self.extra3[2] = FieldSelectableInt(self.spr, tuple(range(16,19)))
626
627
628 SVP64RM_MMODE_SIZE = len(SVP64RMFields().mmode.br)
629 SVP64RM_MASK_SIZE = len(SVP64RMFields().mask.br)
630 SVP64RM_ELWIDTH_SIZE = len(SVP64RMFields().elwidth.br)
631 SVP64RM_EWSRC_SIZE = len(SVP64RMFields().ewsrc.br)
632 SVP64RM_SUBVL_SIZE = len(SVP64RMFields().subvl.br)
633 SVP64RM_EXTRA2_SPEC_SIZE = len(SVP64RMFields().extra2[0].br)
634 SVP64RM_EXTRA3_SPEC_SIZE = len(SVP64RMFields().extra3[0].br)
635 SVP64RM_SMASK_SIZE = len(SVP64RMFields().smask.br)
636 SVP64RM_MODE_SIZE = len(SVP64RMFields().mode.br)
637
638
639 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
640 class SVP64PrefixFields:
641 def __init__(self):
642 self.insn = SelectableInt(0, 32)
643 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
644 self.major = FieldSelectableInt(self.insn, tuple(range(0,6)))
645 self.pid = FieldSelectableInt(self.insn, (7, 9)) # must be 0b11
646 rmfields = [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
647 self.rm = FieldSelectableInt(self.insn, rmfields)
648
649
650 SV64P_MAJOR_SIZE = len(SVP64PrefixFields().major.br)
651 SV64P_PID_SIZE = len(SVP64PrefixFields().pid.br)
652 SV64P_RM_SIZE = len(SVP64PrefixFields().rm.br)
653
654
655 class SPR(dict):
656 def __init__(self, dec2, initial_sprs={}):
657 self.sd = dec2
658 dict.__init__(self)
659 for key, v in initial_sprs.items():
660 if isinstance(key, SelectableInt):
661 key = key.value
662 key = special_sprs.get(key, key)
663 if isinstance(key, int):
664 info = spr_dict[key]
665 else:
666 info = spr_byname[key]
667 if not isinstance(v, SelectableInt):
668 v = SelectableInt(v, info.length)
669 self[key] = v
670
671 def __getitem__(self, key):
672 print("get spr", key)
673 print("dict", self.items())
674 # if key in special_sprs get the special spr, otherwise return key
675 if isinstance(key, SelectableInt):
676 key = key.value
677 if isinstance(key, int):
678 key = spr_dict[key].SPR
679 key = special_sprs.get(key, key)
680 if key == 'HSRR0': # HACK!
681 key = 'SRR0'
682 if key == 'HSRR1': # HACK!
683 key = 'SRR1'
684 if key in self:
685 res = dict.__getitem__(self, key)
686 else:
687 if isinstance(key, int):
688 info = spr_dict[key]
689 else:
690 info = spr_byname[key]
691 dict.__setitem__(self, key, SelectableInt(0, info.length))
692 res = dict.__getitem__(self, key)
693 print("spr returning", key, res)
694 return res
695
696 def __setitem__(self, key, value):
697 if isinstance(key, SelectableInt):
698 key = key.value
699 if isinstance(key, int):
700 key = spr_dict[key].SPR
701 print("spr key", key)
702 key = special_sprs.get(key, key)
703 if key == 'HSRR0': # HACK!
704 self.__setitem__('SRR0', value)
705 if key == 'HSRR1': # HACK!
706 self.__setitem__('SRR1', value)
707 print("setting spr", key, value)
708 dict.__setitem__(self, key, value)
709
710 def __call__(self, ridx):
711 return self[ridx]
712
713 def get_pdecode_idx_in(dec2, name):
714 op = dec2.dec.op
715 in1_sel = yield op.in1_sel
716 in2_sel = yield op.in2_sel
717 in3_sel = yield op.in3_sel
718 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
719 in1 = yield dec2.e.read_reg1.data
720 in2 = yield dec2.e.read_reg2.data
721 in3 = yield dec2.e.read_reg3.data
722 in1_isvec = yield dec2.in1_isvec
723 in2_isvec = yield dec2.in2_isvec
724 in3_isvec = yield dec2.in3_isvec
725 print ("get_pdecode_idx", in1_sel, In1Sel.RA.value, in1, in1_isvec)
726 # identify which regnames map to in1/2/3
727 if name == 'RA':
728 if (in1_sel == In1Sel.RA.value or
729 (in1_sel == In1Sel.RA_OR_ZERO.value and in1 != 0)):
730 return in1, in1_isvec
731 if in1_sel == In1Sel.RA_OR_ZERO.value:
732 return in1, in1_isvec
733 elif name == 'RB':
734 if in2_sel == In2Sel.RB.value:
735 return in2, in2_isvec
736 if in3_sel == In3Sel.RB.value:
737 return in3, in3_isvec
738 # XXX TODO, RC doesn't exist yet!
739 elif name == 'RC':
740 assert False, "RC does not exist yet"
741 elif name == 'RS':
742 if in1_sel == In1Sel.RS.value:
743 return in1, in1_isvec
744 if in2_sel == In2Sel.RS.value:
745 return in2, in2_isvec
746 if in3_sel == In3Sel.RS.value:
747 return in3, in3_isvec
748 return None, False
749
750
751 def get_pdecode_cr_out(dec2, name):
752 op = dec2.dec.op
753 out_sel = yield op.cr_out
754 out_bitfield = yield dec2.dec_cr_out.cr_bitfield.data
755 sv_cr_out = yield op.sv_cr_out
756 spec = yield dec2.crout_svdec.spec
757 sv_override = yield dec2.dec_cr_out.sv_override
758 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
759 out = yield dec2.e.write_cr.data
760 o_isvec = yield dec2.o_isvec
761 print ("get_pdecode_cr_out", out_sel, CROutSel.CR0.value, out, o_isvec)
762 print (" sv_cr_out", sv_cr_out)
763 print (" cr_bf", out_bitfield)
764 print (" spec", spec)
765 print (" override", sv_override)
766 # identify which regnames map to out / o2
767 if name == 'CR0':
768 if out_sel == CROutSel.CR0.value:
769 return out, o_isvec
770 print ("get_pdecode_idx_out not found", name)
771 return None, False
772
773
774 def get_pdecode_idx_out(dec2, name):
775 op = dec2.dec.op
776 out_sel = yield op.out_sel
777 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
778 out = yield dec2.e.write_reg.data
779 o_isvec = yield dec2.o_isvec
780 print ("get_pdecode_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
781 # identify which regnames map to out / o2
782 if name == 'RA':
783 if out_sel == OutSel.RA.value:
784 return out, o_isvec
785 elif name == 'RT':
786 if out_sel == OutSel.RT.value:
787 return out, o_isvec
788 print ("get_pdecode_idx_out not found", name)
789 return None, False
790
791
792 # XXX TODO
793 def get_pdecode_idx_out2(dec2, name):
794 op = dec2.dec.op
795 print ("TODO: get_pdecode_idx_out2", name)
796 return None, False
797
798
799 class ISACaller:
800 # decoder2 - an instance of power_decoder2
801 # regfile - a list of initial values for the registers
802 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
803 # respect_pc - tracks the program counter. requires initial_insns
804 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
805 initial_mem=None, initial_msr=0,
806 initial_svstate=0,
807 initial_insns=None, respect_pc=False,
808 disassembly=None,
809 initial_pc=0,
810 bigendian=False,
811 mmu=False):
812
813 self.bigendian = bigendian
814 self.halted = False
815 self.is_svp64_mode = False
816 self.respect_pc = respect_pc
817 if initial_sprs is None:
818 initial_sprs = {}
819 if initial_mem is None:
820 initial_mem = {}
821 if initial_insns is None:
822 initial_insns = {}
823 assert self.respect_pc == False, "instructions required to honor pc"
824
825 print("ISACaller insns", respect_pc, initial_insns, disassembly)
826 print("ISACaller initial_msr", initial_msr)
827
828 # "fake program counter" mode (for unit testing)
829 self.fake_pc = 0
830 disasm_start = 0
831 if not respect_pc:
832 if isinstance(initial_mem, tuple):
833 self.fake_pc = initial_mem[0]
834 disasm_start = self.fake_pc
835 else:
836 disasm_start = initial_pc
837
838 # disassembly: we need this for now (not given from the decoder)
839 self.disassembly = {}
840 if disassembly:
841 for i, code in enumerate(disassembly):
842 self.disassembly[i*4 + disasm_start] = code
843
844 # set up registers, instruction memory, data memory, PC, SPRs, MSR
845 self.svp64rm = SVP64RM()
846 if isinstance(initial_svstate, int):
847 initial_svstate = SVP64State(initial_svstate)
848 self.svstate = initial_svstate
849 self.gpr = GPR(decoder2, self, self.svstate, regfile)
850 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
851 if mmu:
852 self.mem = RADIX(self.mem, self)
853 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
854 self.pc = PC()
855 self.spr = SPR(decoder2, initial_sprs)
856 self.msr = SelectableInt(initial_msr, 64) # underlying reg
857
858 # TODO, needed here:
859 # FPR (same as GPR except for FP nums)
860 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
861 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
862 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
863 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
864 # -- Done
865 # 2.3.2 LR (actually SPR #8) -- Done
866 # 2.3.3 CTR (actually SPR #9) -- Done
867 # 2.3.4 TAR (actually SPR #815)
868 # 3.2.2 p45 XER (actually SPR #1) -- Done
869 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
870
871 # create CR then allow portions of it to be "selectable" (below)
872 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
873 self.cr = SelectableInt(initial_cr, 64) # underlying reg
874 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
875
876 # "undefined", just set to variable-bit-width int (use exts "max")
877 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
878
879 self.namespace = {}
880 self.namespace.update(self.spr)
881 self.namespace.update({'GPR': self.gpr,
882 'MEM': self.mem,
883 'SPR': self.spr,
884 'memassign': self.memassign,
885 'NIA': self.pc.NIA,
886 'CIA': self.pc.CIA,
887 'CR': self.cr,
888 'MSR': self.msr,
889 'undefined': undefined,
890 'mode_is_64bit': True,
891 'SO': XER_bits['SO']
892 })
893
894 # update pc to requested start point
895 self.set_pc(initial_pc)
896
897 # field-selectable versions of Condition Register TODO check bitranges?
898 self.crl = []
899 for i in range(8):
900 bits = tuple(range(i*4+32, (i+1)*4+32)) # errr... maybe?
901 _cr = FieldSelectableInt(self.cr, bits)
902 self.crl.append(_cr)
903 self.namespace["CR%d" % i] = _cr
904
905 self.decoder = decoder2.dec
906 self.dec2 = decoder2
907
908 def TRAP(self, trap_addr=0x700, trap_bit=PIb.TRAP):
909 print("TRAP:", hex(trap_addr), hex(self.namespace['MSR'].value))
910 # store CIA(+4?) in SRR0, set NIA to 0x700
911 # store MSR in SRR1, set MSR to um errr something, have to check spec
912 self.spr['SRR0'].value = self.pc.CIA.value
913 self.spr['SRR1'].value = self.namespace['MSR'].value
914 self.trap_nia = SelectableInt(trap_addr, 64)
915 self.spr['SRR1'][trap_bit] = 1 # change *copy* of MSR in SRR1
916
917 # set exception bits. TODO: this should, based on the address
918 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
919 # bits appropriately. however it turns out that *for now* in all
920 # cases (all trap_addrs) the exact same thing is needed.
921 self.msr[MSRb.IR] = 0
922 self.msr[MSRb.DR] = 0
923 self.msr[MSRb.FE0] = 0
924 self.msr[MSRb.FE1] = 0
925 self.msr[MSRb.EE] = 0
926 self.msr[MSRb.RI] = 0
927 self.msr[MSRb.SF] = 1
928 self.msr[MSRb.TM] = 0
929 self.msr[MSRb.VEC] = 0
930 self.msr[MSRb.VSX] = 0
931 self.msr[MSRb.PR] = 0
932 self.msr[MSRb.FP] = 0
933 self.msr[MSRb.PMM] = 0
934 self.msr[MSRb.TEs] = 0
935 self.msr[MSRb.TEe] = 0
936 self.msr[MSRb.UND] = 0
937 self.msr[MSRb.LE] = 1
938
939 def memassign(self, ea, sz, val):
940 self.mem.memassign(ea, sz, val)
941
942 def prep_namespace(self, formname, op_fields):
943 # TODO: get field names from form in decoder*1* (not decoder2)
944 # decoder2 is hand-created, and decoder1.sigform is auto-generated
945 # from spec
946 # then "yield" fields only from op_fields rather than hard-coded
947 # list, here.
948 fields = self.decoder.sigforms[formname]
949 for name in op_fields:
950 if name == 'spr':
951 sig = getattr(fields, name.upper())
952 else:
953 sig = getattr(fields, name)
954 val = yield sig
955 # these are all opcode fields involved in index-selection of CR,
956 # and need to do "standard" arithmetic. CR[BA+32] for example
957 # would, if using SelectableInt, only be 5-bit.
958 if name in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
959 self.namespace[name] = val
960 else:
961 self.namespace[name] = SelectableInt(val, sig.width)
962
963 self.namespace['XER'] = self.spr['XER']
964 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
965 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
966
967 def handle_carry_(self, inputs, outputs, already_done):
968 inv_a = yield self.dec2.e.do.invert_in
969 if inv_a:
970 inputs[0] = ~inputs[0]
971
972 imm_ok = yield self.dec2.e.do.imm_data.ok
973 if imm_ok:
974 imm = yield self.dec2.e.do.imm_data.data
975 inputs.append(SelectableInt(imm, 64))
976 assert len(outputs) >= 1
977 print("outputs", repr(outputs))
978 if isinstance(outputs, list) or isinstance(outputs, tuple):
979 output = outputs[0]
980 else:
981 output = outputs
982 gts = []
983 for x in inputs:
984 print("gt input", x, output)
985 gt = (gtu(x, output))
986 gts.append(gt)
987 print(gts)
988 cy = 1 if any(gts) else 0
989 print("CA", cy, gts)
990 if not (1 & already_done):
991 self.spr['XER'][XER_bits['CA']] = cy
992
993 print("inputs", already_done, inputs)
994 # 32 bit carry
995 # ARGH... different for OP_ADD... *sigh*...
996 op = yield self.dec2.e.do.insn_type
997 if op == MicrOp.OP_ADD.value:
998 res32 = (output.value & (1 << 32)) != 0
999 a32 = (inputs[0].value & (1 << 32)) != 0
1000 if len(inputs) >= 2:
1001 b32 = (inputs[1].value & (1 << 32)) != 0
1002 else:
1003 b32 = False
1004 cy32 = res32 ^ a32 ^ b32
1005 print("CA32 ADD", cy32)
1006 else:
1007 gts = []
1008 for x in inputs:
1009 print("input", x, output)
1010 print(" x[32:64]", x, x[32:64])
1011 print(" o[32:64]", output, output[32:64])
1012 gt = (gtu(x[32:64], output[32:64])) == SelectableInt(1, 1)
1013 gts.append(gt)
1014 cy32 = 1 if any(gts) else 0
1015 print("CA32", cy32, gts)
1016 if not (2 & already_done):
1017 self.spr['XER'][XER_bits['CA32']] = cy32
1018
1019 def handle_overflow(self, inputs, outputs, div_overflow):
1020 if hasattr(self.dec2.e.do, "invert_in"):
1021 inv_a = yield self.dec2.e.do.invert_in
1022 if inv_a:
1023 inputs[0] = ~inputs[0]
1024
1025 imm_ok = yield self.dec2.e.do.imm_data.ok
1026 if imm_ok:
1027 imm = yield self.dec2.e.do.imm_data.data
1028 inputs.append(SelectableInt(imm, 64))
1029 assert len(outputs) >= 1
1030 print("handle_overflow", inputs, outputs, div_overflow)
1031 if len(inputs) < 2 and div_overflow is None:
1032 return
1033
1034 # div overflow is different: it's returned by the pseudo-code
1035 # because it's more complex than can be done by analysing the output
1036 if div_overflow is not None:
1037 ov, ov32 = div_overflow, div_overflow
1038 # arithmetic overflow can be done by analysing the input and output
1039 elif len(inputs) >= 2:
1040 output = outputs[0]
1041
1042 # OV (64-bit)
1043 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
1044 output_sgn = exts(output.value, output.bits) < 0
1045 ov = 1 if input_sgn[0] == input_sgn[1] and \
1046 output_sgn != input_sgn[0] else 0
1047
1048 # OV (32-bit)
1049 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
1050 output32_sgn = exts(output.value, 32) < 0
1051 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
1052 output32_sgn != input32_sgn[0] else 0
1053
1054 self.spr['XER'][XER_bits['OV']] = ov
1055 self.spr['XER'][XER_bits['OV32']] = ov32
1056 so = self.spr['XER'][XER_bits['SO']]
1057 so = so | ov
1058 self.spr['XER'][XER_bits['SO']] = so
1059
1060 def handle_comparison(self, outputs, cr_idx=0):
1061 out = outputs[0]
1062 assert isinstance(out, SelectableInt), \
1063 "out zero not a SelectableInt %s" % repr(outputs)
1064 print("handle_comparison", out.bits, hex(out.value))
1065 # TODO - XXX *processor* in 32-bit mode
1066 # https://bugs.libre-soc.org/show_bug.cgi?id=424
1067 # if is_32bit:
1068 # o32 = exts(out.value, 32)
1069 # print ("handle_comparison exts 32 bit", hex(o32))
1070 out = exts(out.value, out.bits)
1071 print("handle_comparison exts", hex(out))
1072 zero = SelectableInt(out == 0, 1)
1073 positive = SelectableInt(out > 0, 1)
1074 negative = SelectableInt(out < 0, 1)
1075 SO = self.spr['XER'][XER_bits['SO']]
1076 print("handle_comparison SO", SO)
1077 cr_field = selectconcat(negative, positive, zero, SO)
1078 self.crl[cr_idx].eq(cr_field)
1079
1080 def set_pc(self, pc_val):
1081 self.namespace['NIA'] = SelectableInt(pc_val, 64)
1082 self.pc.update(self.namespace, self.is_svp64_mode)
1083
1084 def setup_one(self):
1085 """set up one instruction
1086 """
1087 if self.respect_pc:
1088 pc = self.pc.CIA.value
1089 else:
1090 pc = self.fake_pc
1091 self._pc = pc
1092 ins = self.imem.ld(pc, 4, False, True)
1093 if ins is None:
1094 raise KeyError("no instruction at 0x%x" % pc)
1095 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
1096 print("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
1097
1098 yield self.dec2.sv_rm.eq(0)
1099 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
1100 yield self.dec2.dec.bigendian.eq(self.bigendian)
1101 yield self.dec2.state.msr.eq(self.msr.value)
1102 yield self.dec2.state.pc.eq(pc)
1103 yield self.dec2.state.svstate.eq(self.svstate.spr.value)
1104
1105 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
1106 yield Settle()
1107 opcode = yield self.dec2.dec.opcode_in
1108 pfx = SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
1109 pfx.insn.value = opcode
1110 major = pfx.major.asint(msb0=True) # MSB0 inversion
1111 print ("prefix test: opcode:", major, bin(major),
1112 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
1113 self.is_svp64_mode = ((major == 0b000001) and
1114 pfx.insn[7].value == 0b1 and
1115 pfx.insn[9].value == 0b1)
1116 self.pc.update_nia(self.is_svp64_mode)
1117 if not self.is_svp64_mode:
1118 return
1119
1120 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
1121 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
1122 print (" svstate.vl", self.svstate.vl.asint(msb0=True))
1123 print (" svstate.mvl", self.svstate.maxvl.asint(msb0=True))
1124 sv_rm = pfx.rm.asint(msb0=True)
1125 ins = self.imem.ld(pc+4, 4, False, True)
1126 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
1127 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
1128 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
1129 yield Settle()
1130
1131 def execute_one(self):
1132 """execute one instruction
1133 """
1134 # get the disassembly code for this instruction
1135 if self.is_svp64_mode:
1136 code = self.disassembly[self._pc+4]
1137 print(" svp64 sim-execute", hex(self._pc), code)
1138 else:
1139 code = self.disassembly[self._pc]
1140 print("sim-execute", hex(self._pc), code)
1141 opname = code.split(' ')[0]
1142 yield from self.call(opname)
1143
1144 # don't use this except in special circumstances
1145 if not self.respect_pc:
1146 self.fake_pc += 4
1147
1148 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
1149
1150 def get_assembly_name(self):
1151 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1152 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1153 dec_insn = yield self.dec2.e.do.insn
1154 asmcode = yield self.dec2.dec.op.asmcode
1155 print("get assembly name asmcode", asmcode, hex(dec_insn))
1156 asmop = insns.get(asmcode, None)
1157 int_op = yield self.dec2.dec.op.internal_op
1158
1159 # sigh reconstruct the assembly instruction name
1160 if hasattr(self.dec2.e.do, "oe"):
1161 ov_en = yield self.dec2.e.do.oe.oe
1162 ov_ok = yield self.dec2.e.do.oe.ok
1163 else:
1164 ov_en = False
1165 ov_ok = False
1166 if hasattr(self.dec2.e.do, "rc"):
1167 rc_en = yield self.dec2.e.do.rc.rc
1168 rc_ok = yield self.dec2.e.do.rc.ok
1169 else:
1170 rc_en = False
1171 rc_ok = False
1172 # grrrr have to special-case MUL op (see DecodeOE)
1173 print("ov %d en %d rc %d en %d op %d" %
1174 (ov_ok, ov_en, rc_ok, rc_en, int_op))
1175 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
1176 print("mul op")
1177 if rc_en & rc_ok:
1178 asmop += "."
1179 else:
1180 if not asmop.endswith("."): # don't add "." to "andis."
1181 if rc_en & rc_ok:
1182 asmop += "."
1183 if hasattr(self.dec2.e.do, "lk"):
1184 lk = yield self.dec2.e.do.lk
1185 if lk:
1186 asmop += "l"
1187 print("int_op", int_op)
1188 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
1189 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
1190 print("AA", AA)
1191 if AA:
1192 asmop += "a"
1193 spr_msb = yield from self.get_spr_msb()
1194 if int_op == MicrOp.OP_MFCR.value:
1195 if spr_msb:
1196 asmop = 'mfocrf'
1197 else:
1198 asmop = 'mfcr'
1199 # XXX TODO: for whatever weird reason this doesn't work
1200 # https://bugs.libre-soc.org/show_bug.cgi?id=390
1201 if int_op == MicrOp.OP_MTCRF.value:
1202 if spr_msb:
1203 asmop = 'mtocrf'
1204 else:
1205 asmop = 'mtcrf'
1206 return asmop
1207
1208 def get_spr_msb(self):
1209 dec_insn = yield self.dec2.e.do.insn
1210 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
1211
1212 def call(self, name):
1213 """call(opcode) - the primary execution point for instructions
1214 """
1215 name = name.strip() # remove spaces if not already done so
1216 if self.halted:
1217 print("halted - not executing", name)
1218 return
1219
1220 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
1221 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
1222 asmop = yield from self.get_assembly_name()
1223 print("call", name, asmop)
1224
1225 # check privileged
1226 int_op = yield self.dec2.dec.op.internal_op
1227 spr_msb = yield from self.get_spr_msb()
1228
1229 instr_is_privileged = False
1230 if int_op in [MicrOp.OP_ATTN.value,
1231 MicrOp.OP_MFMSR.value,
1232 MicrOp.OP_MTMSR.value,
1233 MicrOp.OP_MTMSRD.value,
1234 # TODO: OP_TLBIE
1235 MicrOp.OP_RFID.value]:
1236 instr_is_privileged = True
1237 if int_op in [MicrOp.OP_MFSPR.value,
1238 MicrOp.OP_MTSPR.value] and spr_msb:
1239 instr_is_privileged = True
1240
1241 print("is priv", instr_is_privileged, hex(self.msr.value),
1242 self.msr[MSRb.PR])
1243 # check MSR priv bit and whether op is privileged: if so, throw trap
1244 if instr_is_privileged and self.msr[MSRb.PR] == 1:
1245 self.TRAP(0x700, PIb.PRIV)
1246 self.namespace['NIA'] = self.trap_nia
1247 self.pc.update(self.namespace, self.is_svp64_mode)
1248 return
1249
1250 # check halted condition
1251 if name == 'attn':
1252 self.halted = True
1253 return
1254
1255 # check illegal instruction
1256 illegal = False
1257 if name not in ['mtcrf', 'mtocrf']:
1258 illegal = name != asmop
1259
1260 if illegal:
1261 print("illegal", name, asmop)
1262 self.TRAP(0x700, PIb.ILLEG)
1263 self.namespace['NIA'] = self.trap_nia
1264 self.pc.update(self.namespace, self.is_svp64_mode)
1265 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
1266 (name, asmop, self.pc.CIA.value))
1267 return
1268
1269 info = self.instrs[name]
1270 yield from self.prep_namespace(info.form, info.op_fields)
1271
1272 # preserve order of register names
1273 input_names = create_args(list(info.read_regs) +
1274 list(info.uninit_regs))
1275 print(input_names)
1276
1277 # get SVP64 entry for the current instruction
1278 sv_rm = self.svp64rm.instrs.get(name)
1279 if sv_rm is not None:
1280 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
1281 else:
1282 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
1283 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
1284
1285 # get SVSTATE srcstep. TODO: dststep (twin predication)
1286 srcstep = self.svstate.srcstep.asint(msb0=True)
1287 vl = self.svstate.vl.asint(msb0=True)
1288 mvl = self.svstate.maxvl.asint(msb0=True)
1289
1290 # VL=0 in SVP64 mode means "do nothing: skip instruction"
1291 if self.is_svp64_mode and vl == 0:
1292 self.pc.update(self.namespace, self.is_svp64_mode)
1293 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1294 return
1295
1296 # main input registers (RT, RA ...)
1297 inputs = []
1298 for name in input_names:
1299 # using PowerDecoder2, first, find the decoder index.
1300 # (mapping name RA RB RC RS to in1, in2, in3)
1301 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
1302 if regnum is None:
1303 # doing this is not part of svp64, it's because output
1304 # registers, to be modified, need to be in the namespace.
1305 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
1306 # here's where we go "vector". TODO: zero-testing (RA_IS_ZERO)
1307 # XXX already done by PowerDecoder2, now
1308 #if is_vec:
1309 # regnum += srcstep # TODO, elwidth overrides
1310
1311 # in case getting the register number is needed, _RA, _RB
1312 regname = "_" + name
1313 self.namespace[regname] = regnum
1314 print('reading reg %s %d' % (name, regnum), is_vec)
1315 reg_val = self.gpr(regnum)
1316 inputs.append(reg_val)
1317
1318 # "special" registers
1319 for special in info.special_regs:
1320 if special in special_sprs:
1321 inputs.append(self.spr[special])
1322 else:
1323 inputs.append(self.namespace[special])
1324
1325 # clear trap (trap) NIA
1326 self.trap_nia = None
1327
1328 print("inputs", inputs)
1329 results = info.func(self, *inputs)
1330 print("results", results)
1331
1332 # "inject" decorator takes namespace from function locals: we need to
1333 # overwrite NIA being overwritten (sigh)
1334 if self.trap_nia is not None:
1335 self.namespace['NIA'] = self.trap_nia
1336
1337 print("after func", self.namespace['CIA'], self.namespace['NIA'])
1338
1339 # detect if CA/CA32 already in outputs (sra*, basically)
1340 already_done = 0
1341 if info.write_regs:
1342 output_names = create_args(info.write_regs)
1343 for name in output_names:
1344 if name == 'CA':
1345 already_done |= 1
1346 if name == 'CA32':
1347 already_done |= 2
1348
1349 print("carry already done?", bin(already_done))
1350 if hasattr(self.dec2.e.do, "output_carry"):
1351 carry_en = yield self.dec2.e.do.output_carry
1352 else:
1353 carry_en = False
1354 if carry_en:
1355 yield from self.handle_carry_(inputs, results, already_done)
1356
1357 # detect if overflow was in return result
1358 overflow = None
1359 if info.write_regs:
1360 for name, output in zip(output_names, results):
1361 if name == 'overflow':
1362 overflow = output
1363
1364 if hasattr(self.dec2.e.do, "oe"):
1365 ov_en = yield self.dec2.e.do.oe.oe
1366 ov_ok = yield self.dec2.e.do.oe.ok
1367 else:
1368 ov_en = False
1369 ov_ok = False
1370 print("internal overflow", overflow, ov_en, ov_ok)
1371 if ov_en & ov_ok:
1372 yield from self.handle_overflow(inputs, results, overflow)
1373
1374 if hasattr(self.dec2.e.do, "rc"):
1375 rc_en = yield self.dec2.e.do.rc.rc
1376 else:
1377 rc_en = False
1378 if rc_en:
1379 regnum, is_vec = yield from get_pdecode_cr_out(self.dec2, "CR0")
1380 self.handle_comparison(results, regnum)
1381
1382 # any modified return results?
1383 if info.write_regs:
1384 for name, output in zip(output_names, results):
1385 if name == 'overflow': # ignore, done already (above)
1386 continue
1387 if isinstance(output, int):
1388 output = SelectableInt(output, 256)
1389 if name in ['CA', 'CA32']:
1390 if carry_en:
1391 print("writing %s to XER" % name, output)
1392 self.spr['XER'][XER_bits[name]] = output.value
1393 else:
1394 print("NOT writing %s to XER" % name, output)
1395 elif name in info.special_regs:
1396 print('writing special %s' % name, output, special_sprs)
1397 if name in special_sprs:
1398 self.spr[name] = output
1399 else:
1400 self.namespace[name].eq(output)
1401 if name == 'MSR':
1402 print('msr written', hex(self.msr.value))
1403 else:
1404 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
1405 name)
1406 if regnum is None:
1407 # temporary hack for not having 2nd output
1408 regnum = yield getattr(self.decoder, name)
1409 is_vec = False
1410 print('writing reg %d %s' % (regnum, str(output)), is_vec)
1411 if output.bits > 64:
1412 output = SelectableInt(output.value, 64)
1413 self.gpr[regnum] = output
1414
1415 # check if it is the SVSTATE.src/dest step that needs incrementing
1416 # this is our Sub-Program-Counter loop from 0 to VL-1
1417 if self.is_svp64_mode:
1418 # XXX twin predication TODO
1419 vl = self.svstate.vl.asint(msb0=True)
1420 mvl = self.svstate.maxvl.asint(msb0=True)
1421 srcstep = self.svstate.srcstep.asint(msb0=True)
1422 print (" svstate.vl", vl)
1423 print (" svstate.mvl", mvl)
1424 print (" svstate.srcstep", srcstep)
1425 # check if srcstep needs incrementing by one, stop PC advancing
1426 # svp64 loop can end early if the dest is scalar
1427 svp64_dest_vector = not (yield self.dec2.no_out_vec)
1428 if svp64_dest_vector and srcstep != vl-1:
1429 self.svstate.srcstep += SelectableInt(1, 7)
1430 self.pc.NIA.value = self.pc.CIA.value
1431 self.namespace['NIA'] = self.pc.NIA
1432 print("end of sub-pc call", self.namespace['CIA'],
1433 self.namespace['NIA'])
1434 return # DO NOT allow PC to update whilst Sub-PC loop running
1435 # reset to zero
1436 self.svstate.srcstep[0:7] = 0
1437 print (" svstate.srcstep loop end (PC to update)")
1438 self.pc.update_nia(self.is_svp64_mode)
1439 self.namespace['NIA'] = self.pc.NIA
1440
1441 # UPDATE program counter
1442 self.pc.update(self.namespace, self.is_svp64_mode)
1443 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1444
1445
1446 def inject():
1447 """Decorator factory.
1448
1449 this decorator will "inject" variables into the function's namespace,
1450 from the *dictionary* in self.namespace. it therefore becomes possible
1451 to make it look like a whole stack of variables which would otherwise
1452 need "self." inserted in front of them (*and* for those variables to be
1453 added to the instance) "appear" in the function.
1454
1455 "self.namespace['SI']" for example becomes accessible as just "SI" but
1456 *only* inside the function, when decorated.
1457 """
1458 def variable_injector(func):
1459 @wraps(func)
1460 def decorator(*args, **kwargs):
1461 try:
1462 func_globals = func.__globals__ # Python 2.6+
1463 except AttributeError:
1464 func_globals = func.func_globals # Earlier versions.
1465
1466 context = args[0].namespace # variables to be injected
1467 saved_values = func_globals.copy() # Shallow copy of dict.
1468 func_globals.update(context)
1469 result = func(*args, **kwargs)
1470 print("globals after", func_globals['CIA'], func_globals['NIA'])
1471 print("args[0]", args[0].namespace['CIA'],
1472 args[0].namespace['NIA'])
1473 args[0].namespace = func_globals
1474 #exec (func.__code__, func_globals)
1475
1476 # finally:
1477 # func_globals = saved_values # Undo changes.
1478
1479 return result
1480
1481 return decorator
1482
1483 return variable_injector
1484
1485
1486 # very quick test of maskgen function (TODO, move to util later)
1487 if __name__ == '__main__':
1488 shift = SelectableInt(5, 6)
1489 mask = genmask(shift, 43)
1490 print (" mask", bin(mask.value))
1491
1492 mem = Mem(row_bytes=8)
1493 mem = RADIX(mem, None)
1494 # -----------------------------------------------
1495 # |/|RTS1|/| RPDB | RTS2 | RPDS |
1496 # -----------------------------------------------
1497 # |0|1 2|3|4 55|56 58|59 63|
1498 data = SelectableInt(0, 64)
1499 data[1:3] = 0b01
1500 data[56:59] = 0b11
1501 data[59:64] = 0b01101 # mask
1502 data[55] = 1
1503 (rts, mbits, pgbase) = mem._decode_prte(data)
1504 print (" rts", bin(rts.value), rts.bits)
1505 print (" mbits", bin(mbits.value), mbits.bits)
1506 print (" pgbase", hex(pgbase.value), pgbase.bits)
1507 addr = SelectableInt(0x1000, 64)
1508 check = mem._segment_check(addr, mbits, shift)
1509 print (" segment check", check)