add two functions for checking permissions, to be based on microwatt
[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
79 # see qemu/target/ppc/mmu-radix64.c for reference
80 class RADIX:
81 def __init__(self, mem, caller):
82 self.mem = mem
83 self.caller = caller
84
85 def ld(self, address, width=8, swap=True, check_in_mem=False):
86 print("RADIX: ld from addr 0x{:x} width {:d}".format(address, width))
87
88 pte = self._walk_tree()
89 # use pte to caclculate phys address
90 #mem.ld(address,width,swap,check_in_mem)
91
92 # TODO implement
93 # def st(self, addr, v, width=8, swap=True):
94 # def memassign(self, addr, sz, val):
95 def _next_level(self):
96 return True
97 ## DSISR_R_BADCONFIG
98 ## read_entry
99 ## DSISR_NOPTE
100 ## Prepare for next iteration
101
102 def _walk_tree(self):
103 # walk tree starts on prtbl
104 while True:
105 ret = self._next_level()
106 if ret: return ret
107
108 def _segment_check(self):
109 """checks segment valid
110 mbits := '0' & r.mask_size;
111 v.shift := r.shift + (31 - 12) - mbits;
112 nonzero := or(r.addr(61 downto 31) and not finalmask(30 downto 0));
113 if r.addr(63) /= r.addr(62) or nonzero = '1' then
114 v.state := RADIX_FINISH;
115 v.segerror := '1';
116 elsif mbits < 5 or mbits > 16 or mbits > (r.shift + (31 - 12)) then
117 v.state := RADIX_FINISH;
118 v.badtree := '1';
119 else
120 v.state := RADIX_LOOKUP;
121 """
122
123 def _check_perms(self):
124 """check page permissions
125 -- test leaf bit
126 if data(62) = '1' then
127 -- check permissions and RC bits
128 perm_ok := '0';
129 if r.priv = '1' or data(3) = '0' then
130 if r.iside = '0' then
131 perm_ok := data(1) or (data(2) and not r.store);
132 else
133 -- no IAMR, so no KUEP support for now
134 -- deny execute permission if cache inhibited
135 perm_ok := data(0) and not data(5);
136 end if;
137 end if;
138 rc_ok := data(8) and (data(7) or not r.store);
139 if perm_ok = '1' and rc_ok = '1' then
140 v.state := RADIX_LOAD_TLB;
141 else
142 v.state := RADIX_FINISH;
143 v.perm_err := not perm_ok;
144 -- permission error takes precedence over RC error
145 v.rc_error := perm_ok;
146 end if;
147 """
148
149
150 class Mem:
151
152 def __init__(self, row_bytes=8, initial_mem=None):
153 self.mem = {}
154 self.bytes_per_word = row_bytes
155 self.word_log2 = math.ceil(math.log2(row_bytes))
156 print("Sim-Mem", initial_mem, self.bytes_per_word, self.word_log2)
157 if not initial_mem:
158 return
159
160 # different types of memory data structures recognised (for convenience)
161 if isinstance(initial_mem, list):
162 initial_mem = (0, initial_mem)
163 if isinstance(initial_mem, tuple):
164 startaddr, mem = initial_mem
165 initial_mem = {}
166 for i, val in enumerate(mem):
167 initial_mem[startaddr + row_bytes*i] = (val, row_bytes)
168
169 for addr, (val, width) in initial_mem.items():
170 #val = swap_order(val, width)
171 self.st(addr, val, width, swap=False)
172
173 def _get_shifter_mask(self, wid, remainder):
174 shifter = ((self.bytes_per_word - wid) - remainder) * \
175 8 # bits per byte
176 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=377
177 # BE/LE mode?
178 shifter = remainder * 8
179 mask = (1 << (wid * 8)) - 1
180 print("width,rem,shift,mask", wid, remainder, hex(shifter), hex(mask))
181 return shifter, mask
182
183 # TODO: Implement ld/st of lesser width
184 def ld(self, address, width=8, swap=True, check_in_mem=False):
185 print("ld from addr 0x{:x} width {:d}".format(address, width))
186 remainder = address & (self.bytes_per_word - 1)
187 address = address >> self.word_log2
188 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
189 if address in self.mem:
190 val = self.mem[address]
191 elif check_in_mem:
192 return None
193 else:
194 val = 0
195 print("mem @ 0x{:x} rem {:d} : 0x{:x}".format(address, remainder, val))
196
197 if width != self.bytes_per_word:
198 shifter, mask = self._get_shifter_mask(width, remainder)
199 print("masking", hex(val), hex(mask << shifter), shifter)
200 val = val & (mask << shifter)
201 val >>= shifter
202 if swap:
203 val = swap_order(val, width)
204 print("Read 0x{:x} from addr 0x{:x}".format(val, address))
205 return val
206
207 def st(self, addr, v, width=8, swap=True):
208 staddr = addr
209 remainder = addr & (self.bytes_per_word - 1)
210 addr = addr >> self.word_log2
211 print("Writing 0x{:x} to ST 0x{:x} "
212 "memaddr 0x{:x}/{:x}".format(v, staddr, addr, remainder, swap))
213 assert remainder & (width - 1) == 0, "Unaligned access unsupported!"
214 if swap:
215 v = swap_order(v, width)
216 if width != self.bytes_per_word:
217 if addr in self.mem:
218 val = self.mem[addr]
219 else:
220 val = 0
221 shifter, mask = self._get_shifter_mask(width, remainder)
222 val &= ~(mask << shifter)
223 val |= v << shifter
224 self.mem[addr] = val
225 else:
226 self.mem[addr] = v
227 print("mem @ 0x{:x}: 0x{:x}".format(addr, self.mem[addr]))
228
229 def __call__(self, addr, sz):
230 val = self.ld(addr.value, sz, swap=False)
231 print("memread", addr, sz, val)
232 return SelectableInt(val, sz*8)
233
234 def memassign(self, addr, sz, val):
235 print("memassign", addr, sz, val)
236 self.st(addr.value, val.value, sz, swap=False)
237
238
239 class GPR(dict):
240 def __init__(self, decoder, isacaller, svstate, regfile):
241 dict.__init__(self)
242 self.sd = decoder
243 self.isacaller = isacaller
244 self.svstate = svstate
245 for i in range(32):
246 self[i] = SelectableInt(regfile[i], 64)
247
248 def __call__(self, ridx):
249 return self[ridx]
250
251 def set_form(self, form):
252 self.form = form
253
254 def getz(self, rnum):
255 # rnum = rnum.value # only SelectableInt allowed
256 print("GPR getzero", rnum)
257 if rnum == 0:
258 return SelectableInt(0, 64)
259 return self[rnum]
260
261 def _get_regnum(self, attr):
262 getform = self.sd.sigforms[self.form]
263 rnum = getattr(getform, attr)
264 return rnum
265
266 def ___getitem__(self, attr):
267 """ XXX currently not used
268 """
269 rnum = self._get_regnum(attr)
270 offs = self.svstate.srcstep
271 print("GPR getitem", attr, rnum, "srcoffs", offs)
272 return self.regfile[rnum]
273
274 def dump(self):
275 for i in range(0, len(self), 8):
276 s = []
277 for j in range(8):
278 s.append("%08x" % self[i+j].value)
279 s = ' '.join(s)
280 print("reg", "%2d" % i, s)
281
282
283 class PC:
284 def __init__(self, pc_init=0):
285 self.CIA = SelectableInt(pc_init, 64)
286 self.NIA = self.CIA + SelectableInt(4, 64) # only true for v3.0B!
287
288 def update_nia(self, is_svp64):
289 increment = 8 if is_svp64 else 4
290 self.NIA = self.CIA + SelectableInt(increment, 64)
291
292 def update(self, namespace, is_svp64):
293 """updates the program counter (PC) by 4 if v3.0B mode or 8 if SVP64
294 """
295 self.CIA = namespace['NIA'].narrow(64)
296 self.update_nia(is_svp64)
297 namespace['CIA'] = self.CIA
298 namespace['NIA'] = self.NIA
299
300
301 # Simple-V: see https://libre-soc.org/openpower/sv
302 class SVP64State:
303 def __init__(self, init=0):
304 self.spr = SelectableInt(init, 32)
305 # fields of SVSTATE, see https://libre-soc.org/openpower/sv/sprs/
306 self.maxvl = FieldSelectableInt(self.spr, tuple(range(0,7)))
307 self.vl = FieldSelectableInt(self.spr, tuple(range(7,14)))
308 self.srcstep = FieldSelectableInt(self.spr, tuple(range(14,21)))
309 self.dststep = FieldSelectableInt(self.spr, tuple(range(21,28)))
310 self.subvl = FieldSelectableInt(self.spr, tuple(range(28,30)))
311 self.svstep = FieldSelectableInt(self.spr, tuple(range(30,32)))
312
313
314 # SVP64 ReMap field
315 class SVP64RMFields:
316 def __init__(self, init=0):
317 self.spr = SelectableInt(init, 24)
318 # SVP64 RM fields: see https://libre-soc.org/openpower/sv/svp64/
319 self.mmode = FieldSelectableInt(self.spr, [0])
320 self.mask = FieldSelectableInt(self.spr, tuple(range(1,4)))
321 self.elwidth = FieldSelectableInt(self.spr, tuple(range(4,6)))
322 self.ewsrc = FieldSelectableInt(self.spr, tuple(range(6,8)))
323 self.subvl = FieldSelectableInt(self.spr, tuple(range(8,10)))
324 self.extra = FieldSelectableInt(self.spr, tuple(range(10,19)))
325 self.mode = FieldSelectableInt(self.spr, tuple(range(19,24)))
326 # these cover the same extra field, split into parts as EXTRA2
327 self.extra2 = list(range(4))
328 self.extra2[0] = FieldSelectableInt(self.spr, tuple(range(10,12)))
329 self.extra2[1] = FieldSelectableInt(self.spr, tuple(range(12,14)))
330 self.extra2[2] = FieldSelectableInt(self.spr, tuple(range(14,16)))
331 self.extra2[3] = FieldSelectableInt(self.spr, tuple(range(16,18)))
332 self.smask = FieldSelectableInt(self.spr, tuple(range(16,19)))
333 # and here as well, but EXTRA3
334 self.extra3 = list(range(3))
335 self.extra3[0] = FieldSelectableInt(self.spr, tuple(range(10,13)))
336 self.extra3[1] = FieldSelectableInt(self.spr, tuple(range(13,16)))
337 self.extra3[2] = FieldSelectableInt(self.spr, tuple(range(16,19)))
338
339
340 SVP64RM_MMODE_SIZE = len(SVP64RMFields().mmode.br)
341 SVP64RM_MASK_SIZE = len(SVP64RMFields().mask.br)
342 SVP64RM_ELWIDTH_SIZE = len(SVP64RMFields().elwidth.br)
343 SVP64RM_EWSRC_SIZE = len(SVP64RMFields().ewsrc.br)
344 SVP64RM_SUBVL_SIZE = len(SVP64RMFields().subvl.br)
345 SVP64RM_EXTRA2_SPEC_SIZE = len(SVP64RMFields().extra2[0].br)
346 SVP64RM_EXTRA3_SPEC_SIZE = len(SVP64RMFields().extra3[0].br)
347 SVP64RM_SMASK_SIZE = len(SVP64RMFields().smask.br)
348 SVP64RM_MODE_SIZE = len(SVP64RMFields().mode.br)
349
350
351 # SVP64 Prefix fields: see https://libre-soc.org/openpower/sv/svp64/
352 class SVP64PrefixFields:
353 def __init__(self):
354 self.insn = SelectableInt(0, 32)
355 # 6 bit major opcode EXT001, 2 bits "identifying" (7, 9), 24 SV ReMap
356 self.major = FieldSelectableInt(self.insn, tuple(range(0,6)))
357 self.pid = FieldSelectableInt(self.insn, (7, 9)) # must be 0b11
358 rmfields = [6, 8] + list(range(10,32)) # SVP64 24-bit RM (ReMap)
359 self.rm = FieldSelectableInt(self.insn, rmfields)
360
361
362 SV64P_MAJOR_SIZE = len(SVP64PrefixFields().major.br)
363 SV64P_PID_SIZE = len(SVP64PrefixFields().pid.br)
364 SV64P_RM_SIZE = len(SVP64PrefixFields().rm.br)
365
366
367 class SPR(dict):
368 def __init__(self, dec2, initial_sprs={}):
369 self.sd = dec2
370 dict.__init__(self)
371 for key, v in initial_sprs.items():
372 if isinstance(key, SelectableInt):
373 key = key.value
374 key = special_sprs.get(key, key)
375 if isinstance(key, int):
376 info = spr_dict[key]
377 else:
378 info = spr_byname[key]
379 if not isinstance(v, SelectableInt):
380 v = SelectableInt(v, info.length)
381 self[key] = v
382
383 def __getitem__(self, key):
384 print("get spr", key)
385 print("dict", self.items())
386 # if key in special_sprs get the special spr, otherwise return key
387 if isinstance(key, SelectableInt):
388 key = key.value
389 if isinstance(key, int):
390 key = spr_dict[key].SPR
391 key = special_sprs.get(key, key)
392 if key == 'HSRR0': # HACK!
393 key = 'SRR0'
394 if key == 'HSRR1': # HACK!
395 key = 'SRR1'
396 if key in self:
397 res = dict.__getitem__(self, key)
398 else:
399 if isinstance(key, int):
400 info = spr_dict[key]
401 else:
402 info = spr_byname[key]
403 dict.__setitem__(self, key, SelectableInt(0, info.length))
404 res = dict.__getitem__(self, key)
405 print("spr returning", key, res)
406 return res
407
408 def __setitem__(self, key, value):
409 if isinstance(key, SelectableInt):
410 key = key.value
411 if isinstance(key, int):
412 key = spr_dict[key].SPR
413 print("spr key", key)
414 key = special_sprs.get(key, key)
415 if key == 'HSRR0': # HACK!
416 self.__setitem__('SRR0', value)
417 if key == 'HSRR1': # HACK!
418 self.__setitem__('SRR1', value)
419 print("setting spr", key, value)
420 dict.__setitem__(self, key, value)
421
422 def __call__(self, ridx):
423 return self[ridx]
424
425 def get_pdecode_idx_in(dec2, name):
426 op = dec2.dec.op
427 in1_sel = yield op.in1_sel
428 in2_sel = yield op.in2_sel
429 in3_sel = yield op.in3_sel
430 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
431 in1 = yield dec2.e.read_reg1.data
432 in2 = yield dec2.e.read_reg2.data
433 in3 = yield dec2.e.read_reg3.data
434 in1_isvec = yield dec2.in1_isvec
435 in2_isvec = yield dec2.in2_isvec
436 in3_isvec = yield dec2.in3_isvec
437 print ("get_pdecode_idx", in1_sel, In1Sel.RA.value, in1, in1_isvec)
438 # identify which regnames map to in1/2/3
439 if name == 'RA':
440 if (in1_sel == In1Sel.RA.value or
441 (in1_sel == In1Sel.RA_OR_ZERO.value and in1 != 0)):
442 return in1, in1_isvec
443 if in1_sel == In1Sel.RA_OR_ZERO.value:
444 return in1, in1_isvec
445 elif name == 'RB':
446 if in2_sel == In2Sel.RB.value:
447 return in2, in2_isvec
448 if in3_sel == In3Sel.RB.value:
449 return in3, in3_isvec
450 # XXX TODO, RC doesn't exist yet!
451 elif name == 'RC':
452 assert False, "RC does not exist yet"
453 elif name == 'RS':
454 if in1_sel == In1Sel.RS.value:
455 return in1, in1_isvec
456 if in2_sel == In2Sel.RS.value:
457 return in2, in2_isvec
458 if in3_sel == In3Sel.RS.value:
459 return in3, in3_isvec
460 return None, False
461
462
463 def get_pdecode_cr_out(dec2, name):
464 op = dec2.dec.op
465 out_sel = yield op.cr_out
466 out_bitfield = yield dec2.dec_cr_out.cr_bitfield.data
467 sv_cr_out = yield op.sv_cr_out
468 spec = yield dec2.crout_svdec.spec
469 sv_override = yield dec2.dec_cr_out.sv_override
470 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
471 out = yield dec2.e.write_cr.data
472 o_isvec = yield dec2.o_isvec
473 print ("get_pdecode_cr_out", out_sel, CROutSel.CR0.value, out, o_isvec)
474 print (" sv_cr_out", sv_cr_out)
475 print (" cr_bf", out_bitfield)
476 print (" spec", spec)
477 print (" override", sv_override)
478 # identify which regnames map to out / o2
479 if name == 'CR0':
480 if out_sel == CROutSel.CR0.value:
481 return out, o_isvec
482 print ("get_pdecode_idx_out not found", name)
483 return None, False
484
485
486 def get_pdecode_idx_out(dec2, name):
487 op = dec2.dec.op
488 out_sel = yield op.out_sel
489 # get the IN1/2/3 from the decoder (includes SVP64 remap and isvec)
490 out = yield dec2.e.write_reg.data
491 o_isvec = yield dec2.o_isvec
492 print ("get_pdecode_idx_out", out_sel, OutSel.RA.value, out, o_isvec)
493 # identify which regnames map to out / o2
494 if name == 'RA':
495 if out_sel == OutSel.RA.value:
496 return out, o_isvec
497 elif name == 'RT':
498 if out_sel == OutSel.RT.value:
499 return out, o_isvec
500 print ("get_pdecode_idx_out not found", name)
501 return None, False
502
503
504 # XXX TODO
505 def get_pdecode_idx_out2(dec2, name):
506 op = dec2.dec.op
507 print ("TODO: get_pdecode_idx_out2", name)
508 return None, False
509
510
511 class ISACaller:
512 # decoder2 - an instance of power_decoder2
513 # regfile - a list of initial values for the registers
514 # initial_{etc} - initial values for SPRs, Condition Register, Mem, MSR
515 # respect_pc - tracks the program counter. requires initial_insns
516 def __init__(self, decoder2, regfile, initial_sprs=None, initial_cr=0,
517 initial_mem=None, initial_msr=0,
518 initial_svstate=0,
519 initial_insns=None, respect_pc=False,
520 disassembly=None,
521 initial_pc=0,
522 bigendian=False):
523
524 self.bigendian = bigendian
525 self.halted = False
526 self.is_svp64_mode = False
527 self.respect_pc = respect_pc
528 if initial_sprs is None:
529 initial_sprs = {}
530 if initial_mem is None:
531 initial_mem = {}
532 if initial_insns is None:
533 initial_insns = {}
534 assert self.respect_pc == False, "instructions required to honor pc"
535
536 print("ISACaller insns", respect_pc, initial_insns, disassembly)
537 print("ISACaller initial_msr", initial_msr)
538
539 # "fake program counter" mode (for unit testing)
540 self.fake_pc = 0
541 disasm_start = 0
542 if not respect_pc:
543 if isinstance(initial_mem, tuple):
544 self.fake_pc = initial_mem[0]
545 disasm_start = self.fake_pc
546 else:
547 disasm_start = initial_pc
548
549 # disassembly: we need this for now (not given from the decoder)
550 self.disassembly = {}
551 if disassembly:
552 for i, code in enumerate(disassembly):
553 self.disassembly[i*4 + disasm_start] = code
554
555 # set up registers, instruction memory, data memory, PC, SPRs, MSR
556 self.svp64rm = SVP64RM()
557 if isinstance(initial_svstate, int):
558 initial_svstate = SVP64State(initial_svstate)
559 self.svstate = initial_svstate
560 self.gpr = GPR(decoder2, self, self.svstate, regfile)
561 self.mem = Mem(row_bytes=8, initial_mem=initial_mem)
562 self.imem = Mem(row_bytes=4, initial_mem=initial_insns)
563 self.pc = PC()
564 self.spr = SPR(decoder2, initial_sprs)
565 self.msr = SelectableInt(initial_msr, 64) # underlying reg
566
567 # TODO, needed here:
568 # FPR (same as GPR except for FP nums)
569 # 4.2.2 p124 FPSCR (definitely "separate" - not in SPR)
570 # note that mffs, mcrfs, mtfsf "manage" this FPSCR
571 # 2.3.1 CR (and sub-fields CR0..CR6 - CR0 SO comes from XER.SO)
572 # note that mfocrf, mfcr, mtcr, mtocrf, mcrxrx "manage" CRs
573 # -- Done
574 # 2.3.2 LR (actually SPR #8) -- Done
575 # 2.3.3 CTR (actually SPR #9) -- Done
576 # 2.3.4 TAR (actually SPR #815)
577 # 3.2.2 p45 XER (actually SPR #1) -- Done
578 # 3.2.3 p46 p232 VRSAVE (actually SPR #256)
579
580 # create CR then allow portions of it to be "selectable" (below)
581 #rev_cr = int('{:016b}'.format(initial_cr)[::-1], 2)
582 self.cr = SelectableInt(initial_cr, 64) # underlying reg
583 #self.cr = FieldSelectableInt(self._cr, list(range(32, 64)))
584
585 # "undefined", just set to variable-bit-width int (use exts "max")
586 #self.undefined = SelectableInt(0, 256) # TODO, not hard-code 256!
587
588 self.namespace = {}
589 self.namespace.update(self.spr)
590 self.namespace.update({'GPR': self.gpr,
591 'MEM': self.mem,
592 'SPR': self.spr,
593 'memassign': self.memassign,
594 'NIA': self.pc.NIA,
595 'CIA': self.pc.CIA,
596 'CR': self.cr,
597 'MSR': self.msr,
598 'undefined': undefined,
599 'mode_is_64bit': True,
600 'SO': XER_bits['SO']
601 })
602
603 # update pc to requested start point
604 self.set_pc(initial_pc)
605
606 # field-selectable versions of Condition Register TODO check bitranges?
607 self.crl = []
608 for i in range(8):
609 bits = tuple(range(i*4+32, (i+1)*4+32)) # errr... maybe?
610 _cr = FieldSelectableInt(self.cr, bits)
611 self.crl.append(_cr)
612 self.namespace["CR%d" % i] = _cr
613
614 self.decoder = decoder2.dec
615 self.dec2 = decoder2
616
617 def TRAP(self, trap_addr=0x700, trap_bit=PIb.TRAP):
618 print("TRAP:", hex(trap_addr), hex(self.namespace['MSR'].value))
619 # store CIA(+4?) in SRR0, set NIA to 0x700
620 # store MSR in SRR1, set MSR to um errr something, have to check spec
621 self.spr['SRR0'].value = self.pc.CIA.value
622 self.spr['SRR1'].value = self.namespace['MSR'].value
623 self.trap_nia = SelectableInt(trap_addr, 64)
624 self.spr['SRR1'][trap_bit] = 1 # change *copy* of MSR in SRR1
625
626 # set exception bits. TODO: this should, based on the address
627 # in figure 66 p1065 V3.0B and the table figure 65 p1063 set these
628 # bits appropriately. however it turns out that *for now* in all
629 # cases (all trap_addrs) the exact same thing is needed.
630 self.msr[MSRb.IR] = 0
631 self.msr[MSRb.DR] = 0
632 self.msr[MSRb.FE0] = 0
633 self.msr[MSRb.FE1] = 0
634 self.msr[MSRb.EE] = 0
635 self.msr[MSRb.RI] = 0
636 self.msr[MSRb.SF] = 1
637 self.msr[MSRb.TM] = 0
638 self.msr[MSRb.VEC] = 0
639 self.msr[MSRb.VSX] = 0
640 self.msr[MSRb.PR] = 0
641 self.msr[MSRb.FP] = 0
642 self.msr[MSRb.PMM] = 0
643 self.msr[MSRb.TEs] = 0
644 self.msr[MSRb.TEe] = 0
645 self.msr[MSRb.UND] = 0
646 self.msr[MSRb.LE] = 1
647
648 def memassign(self, ea, sz, val):
649 self.mem.memassign(ea, sz, val)
650
651 def prep_namespace(self, formname, op_fields):
652 # TODO: get field names from form in decoder*1* (not decoder2)
653 # decoder2 is hand-created, and decoder1.sigform is auto-generated
654 # from spec
655 # then "yield" fields only from op_fields rather than hard-coded
656 # list, here.
657 fields = self.decoder.sigforms[formname]
658 for name in op_fields:
659 if name == 'spr':
660 sig = getattr(fields, name.upper())
661 else:
662 sig = getattr(fields, name)
663 val = yield sig
664 # these are all opcode fields involved in index-selection of CR,
665 # and need to do "standard" arithmetic. CR[BA+32] for example
666 # would, if using SelectableInt, only be 5-bit.
667 if name in ['BF', 'BFA', 'BC', 'BA', 'BB', 'BT', 'BI']:
668 self.namespace[name] = val
669 else:
670 self.namespace[name] = SelectableInt(val, sig.width)
671
672 self.namespace['XER'] = self.spr['XER']
673 self.namespace['CA'] = self.spr['XER'][XER_bits['CA']].value
674 self.namespace['CA32'] = self.spr['XER'][XER_bits['CA32']].value
675
676 def handle_carry_(self, inputs, outputs, already_done):
677 inv_a = yield self.dec2.e.do.invert_in
678 if inv_a:
679 inputs[0] = ~inputs[0]
680
681 imm_ok = yield self.dec2.e.do.imm_data.ok
682 if imm_ok:
683 imm = yield self.dec2.e.do.imm_data.data
684 inputs.append(SelectableInt(imm, 64))
685 assert len(outputs) >= 1
686 print("outputs", repr(outputs))
687 if isinstance(outputs, list) or isinstance(outputs, tuple):
688 output = outputs[0]
689 else:
690 output = outputs
691 gts = []
692 for x in inputs:
693 print("gt input", x, output)
694 gt = (gtu(x, output))
695 gts.append(gt)
696 print(gts)
697 cy = 1 if any(gts) else 0
698 print("CA", cy, gts)
699 if not (1 & already_done):
700 self.spr['XER'][XER_bits['CA']] = cy
701
702 print("inputs", already_done, inputs)
703 # 32 bit carry
704 # ARGH... different for OP_ADD... *sigh*...
705 op = yield self.dec2.e.do.insn_type
706 if op == MicrOp.OP_ADD.value:
707 res32 = (output.value & (1 << 32)) != 0
708 a32 = (inputs[0].value & (1 << 32)) != 0
709 if len(inputs) >= 2:
710 b32 = (inputs[1].value & (1 << 32)) != 0
711 else:
712 b32 = False
713 cy32 = res32 ^ a32 ^ b32
714 print("CA32 ADD", cy32)
715 else:
716 gts = []
717 for x in inputs:
718 print("input", x, output)
719 print(" x[32:64]", x, x[32:64])
720 print(" o[32:64]", output, output[32:64])
721 gt = (gtu(x[32:64], output[32:64])) == SelectableInt(1, 1)
722 gts.append(gt)
723 cy32 = 1 if any(gts) else 0
724 print("CA32", cy32, gts)
725 if not (2 & already_done):
726 self.spr['XER'][XER_bits['CA32']] = cy32
727
728 def handle_overflow(self, inputs, outputs, div_overflow):
729 if hasattr(self.dec2.e.do, "invert_in"):
730 inv_a = yield self.dec2.e.do.invert_in
731 if inv_a:
732 inputs[0] = ~inputs[0]
733
734 imm_ok = yield self.dec2.e.do.imm_data.ok
735 if imm_ok:
736 imm = yield self.dec2.e.do.imm_data.data
737 inputs.append(SelectableInt(imm, 64))
738 assert len(outputs) >= 1
739 print("handle_overflow", inputs, outputs, div_overflow)
740 if len(inputs) < 2 and div_overflow is None:
741 return
742
743 # div overflow is different: it's returned by the pseudo-code
744 # because it's more complex than can be done by analysing the output
745 if div_overflow is not None:
746 ov, ov32 = div_overflow, div_overflow
747 # arithmetic overflow can be done by analysing the input and output
748 elif len(inputs) >= 2:
749 output = outputs[0]
750
751 # OV (64-bit)
752 input_sgn = [exts(x.value, x.bits) < 0 for x in inputs]
753 output_sgn = exts(output.value, output.bits) < 0
754 ov = 1 if input_sgn[0] == input_sgn[1] and \
755 output_sgn != input_sgn[0] else 0
756
757 # OV (32-bit)
758 input32_sgn = [exts(x.value, 32) < 0 for x in inputs]
759 output32_sgn = exts(output.value, 32) < 0
760 ov32 = 1 if input32_sgn[0] == input32_sgn[1] and \
761 output32_sgn != input32_sgn[0] else 0
762
763 self.spr['XER'][XER_bits['OV']] = ov
764 self.spr['XER'][XER_bits['OV32']] = ov32
765 so = self.spr['XER'][XER_bits['SO']]
766 so = so | ov
767 self.spr['XER'][XER_bits['SO']] = so
768
769 def handle_comparison(self, outputs, cr_idx=0):
770 out = outputs[0]
771 assert isinstance(out, SelectableInt), \
772 "out zero not a SelectableInt %s" % repr(outputs)
773 print("handle_comparison", out.bits, hex(out.value))
774 # TODO - XXX *processor* in 32-bit mode
775 # https://bugs.libre-soc.org/show_bug.cgi?id=424
776 # if is_32bit:
777 # o32 = exts(out.value, 32)
778 # print ("handle_comparison exts 32 bit", hex(o32))
779 out = exts(out.value, out.bits)
780 print("handle_comparison exts", hex(out))
781 zero = SelectableInt(out == 0, 1)
782 positive = SelectableInt(out > 0, 1)
783 negative = SelectableInt(out < 0, 1)
784 SO = self.spr['XER'][XER_bits['SO']]
785 print("handle_comparison SO", SO)
786 cr_field = selectconcat(negative, positive, zero, SO)
787 self.crl[cr_idx].eq(cr_field)
788
789 def set_pc(self, pc_val):
790 self.namespace['NIA'] = SelectableInt(pc_val, 64)
791 self.pc.update(self.namespace, self.is_svp64_mode)
792
793 def setup_one(self):
794 """set up one instruction
795 """
796 if self.respect_pc:
797 pc = self.pc.CIA.value
798 else:
799 pc = self.fake_pc
800 self._pc = pc
801 ins = self.imem.ld(pc, 4, False, True)
802 if ins is None:
803 raise KeyError("no instruction at 0x%x" % pc)
804 print("setup: 0x%x 0x%x %s" % (pc, ins & 0xffffffff, bin(ins)))
805 print("CIA NIA", self.respect_pc, self.pc.CIA.value, self.pc.NIA.value)
806
807 yield self.dec2.sv_rm.eq(0)
808 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff)
809 yield self.dec2.dec.bigendian.eq(self.bigendian)
810 yield self.dec2.state.msr.eq(self.msr.value)
811 yield self.dec2.state.pc.eq(pc)
812 yield self.dec2.state.svstate.eq(self.svstate.spr.value)
813
814 # SVP64. first, check if the opcode is EXT001, and SVP64 id bits set
815 yield Settle()
816 opcode = yield self.dec2.dec.opcode_in
817 pfx = SVP64PrefixFields() # TODO should probably use SVP64PrefixDecoder
818 pfx.insn.value = opcode
819 major = pfx.major.asint(msb0=True) # MSB0 inversion
820 print ("prefix test: opcode:", major, bin(major),
821 pfx.insn[7] == 0b1, pfx.insn[9] == 0b1)
822 self.is_svp64_mode = ((major == 0b000001) and
823 pfx.insn[7].value == 0b1 and
824 pfx.insn[9].value == 0b1)
825 self.pc.update_nia(self.is_svp64_mode)
826 if not self.is_svp64_mode:
827 return
828
829 # in SVP64 mode. decode/print out svp64 prefix, get v3.0B instruction
830 print ("svp64.rm", bin(pfx.rm.asint(msb0=True)))
831 print (" svstate.vl", self.svstate.vl.asint(msb0=True))
832 print (" svstate.mvl", self.svstate.maxvl.asint(msb0=True))
833 sv_rm = pfx.rm.asint(msb0=True)
834 ins = self.imem.ld(pc+4, 4, False, True)
835 print(" svsetup: 0x%x 0x%x %s" % (pc+4, ins & 0xffffffff, bin(ins)))
836 yield self.dec2.dec.raw_opcode_in.eq(ins & 0xffffffff) # v3.0B suffix
837 yield self.dec2.sv_rm.eq(sv_rm) # svp64 prefix
838 yield Settle()
839
840 def execute_one(self):
841 """execute one instruction
842 """
843 # get the disassembly code for this instruction
844 if self.is_svp64_mode:
845 code = self.disassembly[self._pc+4]
846 print(" svp64 sim-execute", hex(self._pc), code)
847 else:
848 code = self.disassembly[self._pc]
849 print("sim-execute", hex(self._pc), code)
850 opname = code.split(' ')[0]
851 yield from self.call(opname)
852
853 # don't use this except in special circumstances
854 if not self.respect_pc:
855 self.fake_pc += 4
856
857 print("execute one, CIA NIA", self.pc.CIA.value, self.pc.NIA.value)
858
859 def get_assembly_name(self):
860 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
861 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
862 dec_insn = yield self.dec2.e.do.insn
863 asmcode = yield self.dec2.dec.op.asmcode
864 print("get assembly name asmcode", asmcode, hex(dec_insn))
865 asmop = insns.get(asmcode, None)
866 int_op = yield self.dec2.dec.op.internal_op
867
868 # sigh reconstruct the assembly instruction name
869 if hasattr(self.dec2.e.do, "oe"):
870 ov_en = yield self.dec2.e.do.oe.oe
871 ov_ok = yield self.dec2.e.do.oe.ok
872 else:
873 ov_en = False
874 ov_ok = False
875 if hasattr(self.dec2.e.do, "rc"):
876 rc_en = yield self.dec2.e.do.rc.rc
877 rc_ok = yield self.dec2.e.do.rc.ok
878 else:
879 rc_en = False
880 rc_ok = False
881 # grrrr have to special-case MUL op (see DecodeOE)
882 print("ov %d en %d rc %d en %d op %d" %
883 (ov_ok, ov_en, rc_ok, rc_en, int_op))
884 if int_op in [MicrOp.OP_MUL_H64.value, MicrOp.OP_MUL_H32.value]:
885 print("mul op")
886 if rc_en & rc_ok:
887 asmop += "."
888 else:
889 if not asmop.endswith("."): # don't add "." to "andis."
890 if rc_en & rc_ok:
891 asmop += "."
892 if hasattr(self.dec2.e.do, "lk"):
893 lk = yield self.dec2.e.do.lk
894 if lk:
895 asmop += "l"
896 print("int_op", int_op)
897 if int_op in [MicrOp.OP_B.value, MicrOp.OP_BC.value]:
898 AA = yield self.dec2.dec.fields.FormI.AA[0:-1]
899 print("AA", AA)
900 if AA:
901 asmop += "a"
902 spr_msb = yield from self.get_spr_msb()
903 if int_op == MicrOp.OP_MFCR.value:
904 if spr_msb:
905 asmop = 'mfocrf'
906 else:
907 asmop = 'mfcr'
908 # XXX TODO: for whatever weird reason this doesn't work
909 # https://bugs.libre-soc.org/show_bug.cgi?id=390
910 if int_op == MicrOp.OP_MTCRF.value:
911 if spr_msb:
912 asmop = 'mtocrf'
913 else:
914 asmop = 'mtcrf'
915 return asmop
916
917 def get_spr_msb(self):
918 dec_insn = yield self.dec2.e.do.insn
919 return dec_insn & (1 << 20) != 0 # sigh - XFF.spr[-1]?
920
921 def call(self, name):
922 """call(opcode) - the primary execution point for instructions
923 """
924 name = name.strip() # remove spaces if not already done so
925 if self.halted:
926 print("halted - not executing", name)
927 return
928
929 # TODO, asmregs is from the spec, e.g. add RT,RA,RB
930 # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
931 asmop = yield from self.get_assembly_name()
932 print("call", name, asmop)
933
934 # check privileged
935 int_op = yield self.dec2.dec.op.internal_op
936 spr_msb = yield from self.get_spr_msb()
937
938 instr_is_privileged = False
939 if int_op in [MicrOp.OP_ATTN.value,
940 MicrOp.OP_MFMSR.value,
941 MicrOp.OP_MTMSR.value,
942 MicrOp.OP_MTMSRD.value,
943 # TODO: OP_TLBIE
944 MicrOp.OP_RFID.value]:
945 instr_is_privileged = True
946 if int_op in [MicrOp.OP_MFSPR.value,
947 MicrOp.OP_MTSPR.value] and spr_msb:
948 instr_is_privileged = True
949
950 print("is priv", instr_is_privileged, hex(self.msr.value),
951 self.msr[MSRb.PR])
952 # check MSR priv bit and whether op is privileged: if so, throw trap
953 if instr_is_privileged and self.msr[MSRb.PR] == 1:
954 self.TRAP(0x700, PIb.PRIV)
955 self.namespace['NIA'] = self.trap_nia
956 self.pc.update(self.namespace, self.is_svp64_mode)
957 return
958
959 # check halted condition
960 if name == 'attn':
961 self.halted = True
962 return
963
964 # check illegal instruction
965 illegal = False
966 if name not in ['mtcrf', 'mtocrf']:
967 illegal = name != asmop
968
969 if illegal:
970 print("illegal", name, asmop)
971 self.TRAP(0x700, PIb.ILLEG)
972 self.namespace['NIA'] = self.trap_nia
973 self.pc.update(self.namespace, self.is_svp64_mode)
974 print("name %s != %s - calling ILLEGAL trap, PC: %x" %
975 (name, asmop, self.pc.CIA.value))
976 return
977
978 info = self.instrs[name]
979 yield from self.prep_namespace(info.form, info.op_fields)
980
981 # preserve order of register names
982 input_names = create_args(list(info.read_regs) +
983 list(info.uninit_regs))
984 print(input_names)
985
986 # get SVP64 entry for the current instruction
987 sv_rm = self.svp64rm.instrs.get(name)
988 if sv_rm is not None:
989 dest_cr, src_cr, src_byname, dest_byname = decode_extra(sv_rm)
990 else:
991 dest_cr, src_cr, src_byname, dest_byname = False, False, {}, {}
992 print ("sv rm", sv_rm, dest_cr, src_cr, src_byname, dest_byname)
993
994 # get SVSTATE srcstep. TODO: dststep (twin predication)
995 srcstep = self.svstate.srcstep.asint(msb0=True)
996 vl = self.svstate.vl.asint(msb0=True)
997 mvl = self.svstate.maxvl.asint(msb0=True)
998
999 # VL=0 in SVP64 mode means "do nothing: skip instruction"
1000 if self.is_svp64_mode and vl == 0:
1001 self.pc.update(self.namespace, self.is_svp64_mode)
1002 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1003 return
1004
1005 # main input registers (RT, RA ...)
1006 inputs = []
1007 for name in input_names:
1008 # using PowerDecoder2, first, find the decoder index.
1009 # (mapping name RA RB RC RS to in1, in2, in3)
1010 regnum, is_vec = yield from get_pdecode_idx_in(self.dec2, name)
1011 if regnum is None:
1012 # doing this is not part of svp64, it's because output
1013 # registers, to be modified, need to be in the namespace.
1014 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2, name)
1015 # here's where we go "vector". TODO: zero-testing (RA_IS_ZERO)
1016 # XXX already done by PowerDecoder2, now
1017 #if is_vec:
1018 # regnum += srcstep # TODO, elwidth overrides
1019
1020 # in case getting the register number is needed, _RA, _RB
1021 regname = "_" + name
1022 self.namespace[regname] = regnum
1023 print('reading reg %s %d' % (name, regnum), is_vec)
1024 reg_val = self.gpr(regnum)
1025 inputs.append(reg_val)
1026
1027 # "special" registers
1028 for special in info.special_regs:
1029 if special in special_sprs:
1030 inputs.append(self.spr[special])
1031 else:
1032 inputs.append(self.namespace[special])
1033
1034 # clear trap (trap) NIA
1035 self.trap_nia = None
1036
1037 print("inputs", inputs)
1038 results = info.func(self, *inputs)
1039 print("results", results)
1040
1041 # "inject" decorator takes namespace from function locals: we need to
1042 # overwrite NIA being overwritten (sigh)
1043 if self.trap_nia is not None:
1044 self.namespace['NIA'] = self.trap_nia
1045
1046 print("after func", self.namespace['CIA'], self.namespace['NIA'])
1047
1048 # detect if CA/CA32 already in outputs (sra*, basically)
1049 already_done = 0
1050 if info.write_regs:
1051 output_names = create_args(info.write_regs)
1052 for name in output_names:
1053 if name == 'CA':
1054 already_done |= 1
1055 if name == 'CA32':
1056 already_done |= 2
1057
1058 print("carry already done?", bin(already_done))
1059 if hasattr(self.dec2.e.do, "output_carry"):
1060 carry_en = yield self.dec2.e.do.output_carry
1061 else:
1062 carry_en = False
1063 if carry_en:
1064 yield from self.handle_carry_(inputs, results, already_done)
1065
1066 # detect if overflow was in return result
1067 overflow = None
1068 if info.write_regs:
1069 for name, output in zip(output_names, results):
1070 if name == 'overflow':
1071 overflow = output
1072
1073 if hasattr(self.dec2.e.do, "oe"):
1074 ov_en = yield self.dec2.e.do.oe.oe
1075 ov_ok = yield self.dec2.e.do.oe.ok
1076 else:
1077 ov_en = False
1078 ov_ok = False
1079 print("internal overflow", overflow, ov_en, ov_ok)
1080 if ov_en & ov_ok:
1081 yield from self.handle_overflow(inputs, results, overflow)
1082
1083 if hasattr(self.dec2.e.do, "rc"):
1084 rc_en = yield self.dec2.e.do.rc.rc
1085 else:
1086 rc_en = False
1087 if rc_en:
1088 regnum, is_vec = yield from get_pdecode_cr_out(self.dec2, "CR0")
1089 self.handle_comparison(results, regnum)
1090
1091 # any modified return results?
1092 if info.write_regs:
1093 for name, output in zip(output_names, results):
1094 if name == 'overflow': # ignore, done already (above)
1095 continue
1096 if isinstance(output, int):
1097 output = SelectableInt(output, 256)
1098 if name in ['CA', 'CA32']:
1099 if carry_en:
1100 print("writing %s to XER" % name, output)
1101 self.spr['XER'][XER_bits[name]] = output.value
1102 else:
1103 print("NOT writing %s to XER" % name, output)
1104 elif name in info.special_regs:
1105 print('writing special %s' % name, output, special_sprs)
1106 if name in special_sprs:
1107 self.spr[name] = output
1108 else:
1109 self.namespace[name].eq(output)
1110 if name == 'MSR':
1111 print('msr written', hex(self.msr.value))
1112 else:
1113 regnum, is_vec = yield from get_pdecode_idx_out(self.dec2,
1114 name)
1115 if regnum is None:
1116 # temporary hack for not having 2nd output
1117 regnum = yield getattr(self.decoder, name)
1118 is_vec = False
1119 print('writing reg %d %s' % (regnum, str(output)), is_vec)
1120 if output.bits > 64:
1121 output = SelectableInt(output.value, 64)
1122 self.gpr[regnum] = output
1123
1124 # check if it is the SVSTATE.src/dest step that needs incrementing
1125 # this is our Sub-Program-Counter loop from 0 to VL-1
1126 if self.is_svp64_mode:
1127 # XXX twin predication TODO
1128 vl = self.svstate.vl.asint(msb0=True)
1129 mvl = self.svstate.maxvl.asint(msb0=True)
1130 srcstep = self.svstate.srcstep.asint(msb0=True)
1131 print (" svstate.vl", vl)
1132 print (" svstate.mvl", mvl)
1133 print (" svstate.srcstep", srcstep)
1134 # check if srcstep needs incrementing by one, stop PC advancing
1135 # svp64 loop can end early if the dest is scalar
1136 svp64_dest_vector = not (yield self.dec2.no_out_vec)
1137 if svp64_dest_vector and srcstep != vl-1:
1138 self.svstate.srcstep += SelectableInt(1, 7)
1139 self.pc.NIA.value = self.pc.CIA.value
1140 self.namespace['NIA'] = self.pc.NIA
1141 print("end of sub-pc call", self.namespace['CIA'],
1142 self.namespace['NIA'])
1143 return # DO NOT allow PC to update whilst Sub-PC loop running
1144 # reset to zero
1145 self.svstate.srcstep[0:7] = 0
1146 print (" svstate.srcstep loop end (PC to update)")
1147 self.pc.update_nia(self.is_svp64_mode)
1148 self.namespace['NIA'] = self.pc.NIA
1149
1150 # UPDATE program counter
1151 self.pc.update(self.namespace, self.is_svp64_mode)
1152 print("end of call", self.namespace['CIA'], self.namespace['NIA'])
1153
1154
1155 def inject():
1156 """Decorator factory.
1157
1158 this decorator will "inject" variables into the function's namespace,
1159 from the *dictionary* in self.namespace. it therefore becomes possible
1160 to make it look like a whole stack of variables which would otherwise
1161 need "self." inserted in front of them (*and* for those variables to be
1162 added to the instance) "appear" in the function.
1163
1164 "self.namespace['SI']" for example becomes accessible as just "SI" but
1165 *only* inside the function, when decorated.
1166 """
1167 def variable_injector(func):
1168 @wraps(func)
1169 def decorator(*args, **kwargs):
1170 try:
1171 func_globals = func.__globals__ # Python 2.6+
1172 except AttributeError:
1173 func_globals = func.func_globals # Earlier versions.
1174
1175 context = args[0].namespace # variables to be injected
1176 saved_values = func_globals.copy() # Shallow copy of dict.
1177 func_globals.update(context)
1178 result = func(*args, **kwargs)
1179 print("globals after", func_globals['CIA'], func_globals['NIA'])
1180 print("args[0]", args[0].namespace['CIA'],
1181 args[0].namespace['NIA'])
1182 args[0].namespace = func_globals
1183 #exec (func.__code__, func_globals)
1184
1185 # finally:
1186 # func_globals = saved_values # Undo changes.
1187
1188 return result
1189
1190 return decorator
1191
1192 return variable_injector