arch-riscv: Updating the SD bit of mstatus upon the register read

Per RISC-V ISA Manual, vol II, section 3.1.6.6, page 26, the SD bit is
a read-only bit indicating whether any of FS, VS, and XS fields being
in the respective dirty state.

Per section 3.1.6, page 20, the SD bit is the most significant bit of
the mstatus register for both RV32 and RV64.

Per section 3.1.6.6, page 29, the explicit formula for updating the SD is,
    SD = ((FS==DIRTY) | (XS==DIRTY) | (VS==DIRTY))

Previously in gem5, this bit is not updated anywhere in the gem5
implementation. This cause an issue of incorrectly saving the context
before entering the system call and consequently, incorecttly restoring
the context after a system call as described here [1].

Ideally, we want to update the SD after every relevant instruction;
however, lazily updating the Status register upon its read produces
the same effect.

[1] https://gem5-review.googlesource.com/c/public/gem5/+/65272/

Change-Id: I1db0cc619d43bc5bacb1d03f6f214345d9d90e28
Signed-off-by: Hoa Nguyen <hoanguyen@ucdavis.edu>
Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/65273
Maintainer: Jason Lowe-Power <power.jg@gmail.com>
Reviewed-by: Jason Lowe-Power <power.jg@gmail.com>
Tested-by: kokoro <noreply+kokoro@google.com>
diff --git a/src/arch/riscv/isa.cc b/src/arch/riscv/isa.cc
index e215e24..c76bb2b 100644
--- a/src/arch/riscv/isa.cc
+++ b/src/arch/riscv/isa.cc
@@ -348,6 +348,29 @@
             else
                 return mbits(val, 63, 1);
         }
+      case MISCREG_STATUS:
+        {
+            // Updating the SD bit.
+            // . Per RISC-V ISA Manual, vol II, section 3.1.6.6, page 26,
+            // the SD bit is a read-only bit indicating whether any of
+            // FS, VS, and XS fields being in the respective dirty state.
+            // . Per section 3.1.6, page 20, the SD bit is the most
+            // significant bit of the MSTATUS CSR for both RV32 and RV64.
+            // . Per section 3.1.6.6, page 29, the explicit formula for
+            // updating the SD is,
+            //   SD = ((FS==DIRTY) | (XS==DIRTY) | (VS==DIRTY))
+            // . Ideally, we want to update the SD after every relevant
+            // instruction, however, lazily updating the Status register
+            // upon its read produces the same effect as well.
+            STATUS status = readMiscRegNoEffect(idx);
+            uint64_t sd_bit = \
+                (status.xs == 3) || (status.fs == 3) || (status.vs == 3);
+            // We assume RV64 here, updating the SD bit at index 63.
+            status.sd = sd_bit;
+            setMiscRegNoEffect(idx, status);
+
+            return readMiscRegNoEffect(idx);
+        }
       default:
         // Try reading HPM counters
         // As a placeholder, all HPM counters are just cycle counters