Skip to contentSkip to conversation

virtual interrupt controller (vAPLIC/vIMSIC) support

PATCH Superseded Oleksii Kurochko 3 participants 129 messages Jul 20 – Aug 20 RISC-V Page 2 of 2

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#102 lore raw

Re: [PATCH v1 13/17] xen/riscv: add unprivileged guest memory read helper

In reply to Jan Beulich
Quoted 25 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 2 lines · Oleksii Kurochko

Introduce riscv_vcpu_unpriv_read() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

Both for the title and the function name: How does "unprivileged" matter here?

Unprivileged because HLV/HLVX reads guest memory as if it were accessed from a less-privileged (guest) context, rather than by the hypervisor in HS mode.

Quoted 7 lines

I think I am okay generally to drop "unpriv..." from the function name.

Quoted 1 line

The same functions would be use for reading Dom0's memory, wouldn't they?

Yes, I don't see any issue to let this function to read DomO's memory too. But Dom0 could be counted as "unprivileged" too as it is executed in VS-mode which is less-privileged then HS-mode.

Well, you need to properly distinguish the different cases of "unprivileged" when writing titles / descriptions. The way you put it in your reply above ("less-privileged (guest)") is sufficiently unambiguous, but what you have in the title ("unprivileged guest") clearly is a synonym for "DomU".

Quoted 5 lines

In the end, as you confirm, "guest" alone is all that's needed here to know what is being talked about. (That said: We often distinguish "guest" and "domain", with the former meaning DomU but the latter meaning all domains, including Dom0 and service domains. Yet for the purpose here I think "guest" is good to use, not matter that all kinds of domains are meant.)

I will use then guest.

Quoted 29 lines
Quoted 29 lines
Quoted 21 lines
Quoted 10 lines
(quoted diff) +9 -0
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1:\n"
+            "   hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bne %[tmp], zero, 3f\n"

Review

Quoted 10 lines
(quoted diff) +10 -0
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2:\n"
+            "   hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   sll %[tmp], %[tmp], 16\n"
+            "   add %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "=&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr)
+        : [ti] "r" (trap) : "memory" );
Quoted 3 lines

You want to tell the compiler that *trap is written. Instead I don't see why a memory clobber would be needed: You access a different address space, i.e. nothing the compiler can make any assumptions about.

memory clobber tells the compiler that the assembly code performs memory reads or writes to items other than those listed in the input and output operands and so I don't tell here that *trap will be changed.

Quoted 5 lines
Quoted 1 line

Why this understanding is wrong?

You can (ab)use "memory" for that purpose, but why would you when you can properly express the operand? All that achieves is the compiler possibly having to emit less efficient code.

Then I will use the option mentioned ...

Quoted 5 lines
Quoted 5 lines

Alternative, I think, could be:

          : [val] "+r" (val), "+m" (*trap)
          : [addr] "r" (guest_addr), [ti] "r" (trap) );

And then memory clobber could be dropped.

... here.

Probably I have to return '[addr] "r" (guest_addr)' to output and use +&r constraint.

Quoted 10 lines
Quoted 10 lines
Quoted 7 lines

You also need to take precautions for not returning an uninitialized "val". I think the variable wants initializing (perhaps to ~0) and "+r" wants using as constraint. (Afaik & isn't necessary to use together with +.)

I agree with '+' if we will initialize val with some value.

Quoted 7 lines
Quoted 1 line

Regarding, '&' my understanding is that I have to use it always when

When what exactly? If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose? '&' indicates to the compiler that it may not use the register used for an output to hold some input's value, as that value may be lost by the time the input is actually consumed.

But what is written in the gcc doc:

& - Means (in a particular alternative) that this operand is an earlyclobber operand, which is written before the instruction is finished using the input operands.

What sounds like if an operand (val) in our case is written before the instruction which using the input operands (and after the write instuction which writes val there are instructions which are using input operands) it is needed to have &.

t1: hlvx.hu %[val], (%[addr]) W:val R:addr + can trap -> read register ti

t2:  andi    %[tmp], %[val], 3   W:tmp   R:val
t3:  addi    %[tmp], %[tmp], -3
t4:  bnez    %[tmp], 3f
t5:  addi    %[addr], %[addr], 2 W:addr  R:addr
t6:  hlvx.hu %[tmp], (%[addr])   W:tmp   R:addr + can trap -> read register ti
t7:  slli    %[tmp], %[tmp], 16
t8:  or      %[val], %[val], %[tmp] W:val

So val is written on t1 before t6 where addr and ti still alive.

The similar is for [addr] "+&r" (guest_addr):

addr is written on t5 and input ti is alive till t6. So if allocator will allocate the same register for addr and ti then addi %[addr], %[addr], 2 will break a pointer and handler will get something wrong.

Am I missing something?

If I am still wrong then in both cases should be just "+r"?

~ Oleksii

#97 lore raw

Re: [PATCH v1 12/17] xen/riscv: extend exception tables with type and data fields

In reply to Oleksii Kurochko
Quoted 95 lines · Oleksii Kurochko
Quoted 87 lines · Jan Beulich
Quoted 86 lines · Oleksii Kurochko
Quoted 84 lines · Jan Beulich
Quoted 73 lines · Oleksii Kurochko
Quoted 14 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
(quoted diff) +9 -0
@@ -60,6 +68,40 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
        regs->sepc = ex_fixup(ex);
    }
 
+static inline unsigned long regs_get_gpr(struct cpu_user_regs *regs,
+                                         unsigned int offset)
+{
+    /*
+     * The GPR number -> offset arithmetic below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural
+     * order.
+     */
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, ra) !=
Quoted 8 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 85

Quoted 6 lines
(quoted diff) +6 -0
+                 sizeof(unsigned long));
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, t6) !=
+                 31 * sizeof(unsigned long));
+
+    if ( unlikely(!offset || (offset > MAX_REG_OFFSET)) )
+        return 0;

And an offset not divisible by sizeof(unsigned long) is okay?

No, it isn't okay. I will apply your comment ...

Quoted 2 lines

Returning 0 as error indicator also feels fragile.

With what I suggested below returning could be just dropped.

Quoted 12 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 93

Quoted 9 lines
(quoted diff) +8 -0
+    return *(unsigned long *)((unsigned long)regs + offset);
+}
+
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data * sizeof(unsigned long));

Related to the earlier comment: Simply pass just ex->data here, leaving the multiplication to regs_get_gpr()?

... It would be better to move the multiplication inside regs_get_gpr().

Your comment made me think about whether the multiplication is needed at all (regardless of where it is done). In other words, ex->data contains the register number, so we could just write:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
/*
* The GPR number -> offset arithmetic below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order.

        */
       BUILD_BUG_ON(offsetof(struct cpu_user_regs, ra) != sizeof(unsigned
long));
       BUILD_BUG_ON(offsetof(struct cpu_user_regs, t6) != 31 *

sizeof(unsigned long));

       ASSERT(num && (num < 32));

       return ((const unsigned long *)regs)[num];
}

Probably, we want to consider this function out of context (for now context is that we use it to recieve a pointer to trap_info which can't be obviously stored in x0 as it should be always hardwired zero). In that case, there is no need to check that num is 0.

Quoted 5 lines

So, it probably makes sense to just have:

     ASSERT(num < 32);

ASSERT() is fine here as I don't think that compiler will use incorrect number during register allocation.

I agree.

However, the x0 aspect is still odd. Why again is it that struct cpu_user_regs has a field for it, when the register value is always 0?

Quoted 6 lines
Quoted 3 lines

zero field isn't there to hold a value, it's there so the first 32 slots form an x0..x31 array indexed by GPR number. It is useful for SET_RD() implementation, for example.

But SET_RD() will need to avoid touching .zero anyway. Why waste the space, when something useful can be put there?

Quoted 8 lines

For SET_RD() agree, it doesn't make sense. Bad example. But it could be somehow a "protection" to not clobber something useful if SET_RD arguments won't handled correctly.

SET_RD() is only half of it. The read accessors matter more: sd x0, 0(a0) to an MMIO address is the normal way a guest writes 0 to a device register, and emulate_store() fetches the operand with GET_RS2(), which is a plain index by register number.

Oh, wow, how fragile. Without a bright comment in struct cpu_user_regs, one should be permitted to move fields around or insert new ones at arbitrary positions. That comment would then also help clarify why "zero" is there as a field.

Quoted 4 lines

If something useful lived at offset
0, that store would hand the device that value instead of zero. So whatever we put there would have to survive being read as a source operand and being clobbered by SET_RD(), which means nothing can go there.

But you can't use it as (reliable zero) source when you allow SET_RD() to clobber it.

Jan

#103 lore raw

Re: [PATCH v1 13/17] xen/riscv: add unprivileged guest memory read helper

In reply to Oleksii Kurochko
Quoted 67 lines · Oleksii Kurochko
Quoted 31 lines · Jan Beulich
Quoted 30 lines · Oleksii Kurochko
Quoted 21 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko
(quoted diff) +9 -0
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1:\n"
+            "   hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bne %[tmp], zero, 3f\n"

Review

Quoted 10 lines
(quoted diff) +10 -0
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2:\n"
+            "   hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   sll %[tmp], %[tmp], 16\n"
+            "   add %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "=&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr)
+        : [ti] "r" (trap) : "memory" );
Quoted 3 lines

You want to tell the compiler that *trap is written. Instead I don't see why a memory clobber would be needed: You access a different address space, i.e. nothing the compiler can make any assumptions about.

memory clobber tells the compiler that the assembly code performs memory reads or writes to items other than those listed in the input and output operands and so I don't tell here that *trap will be changed.

Quoted 5 lines
Quoted 1 line

Why this understanding is wrong?

You can (ab)use "memory" for that purpose, but why would you when you can properly express the operand? All that achieves is the compiler possibly having to emit less efficient code.

Then I will use the option mentioned ...

Quoted 5 lines
Quoted 5 lines

Alternative, I think, could be:

          : [val] "+r" (val), "+m" (*trap)
          : [addr] "r" (guest_addr), [ti] "r" (trap) );

And then memory clobber could be dropped.

... here.

Probably I have to return '[addr] "r" (guest_addr)' to output and use +&r constraint.

Quoted 6 lines
Quoted 6 lines
Quoted 3 lines

You also need to take precautions for not returning an uninitialized "val". I think the variable wants initializing (perhaps to ~0) and "+r" wants using as constraint. (Afaik & isn't necessary to use together with +.)

I agree with '+' if we will initialize val with some value.

Quoted 7 lines
Quoted 1 line

Regarding, '&' my understanding is that I have to use it always when

When what exactly? If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose? '&' indicates to the compiler that it may not use the register used for an output to hold some input's value, as that value may be lost by the time the input is actually consumed.

But what is written in the gcc doc:

Quoted 8 lines

& - Means (in a particular alternative) that this operand is an earlyclobber operand, which is written before the instruction is finished using the input operands.

What sounds like if an operand (val) in our case is written before the instruction which using the input operands (and after the write instuction which writes val there are instructions which are using input operands) it is needed to have &.

And that's indeed relevant, just not here. My crucial earlier question was:
"If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose?" There is a case where the answer to this is not "it can't". In your case all inputs are distinct; in e.g. (using x86 assembly, sorry):

int test(int i, int j) {
	asm("nop %0; nop %1" : "+r" (i) : "r" (i));
	asm("cmc; nop %0; nop %1" : "+&r" (j) : "r" (j));

	return i + j;
}

using "+&r" indeed makes a difference.

Quoted 16 lines

t1: hlvx.hu %[val], (%[addr]) W:val R:addr + can trap -> read register ti

t2:  andi    %[tmp], %[val], 3   W:tmp   R:val
t3:  addi    %[tmp], %[tmp], -3
t4:  bnez    %[tmp], 3f
t5:  addi    %[addr], %[addr], 2 W:addr  R:addr
t6:  hlvx.hu %[tmp], (%[addr])   W:tmp   R:addr + can trap -> read 

register ti

t7:  slli    %[tmp], %[tmp], 16
t8:  or      %[val], %[val], %[tmp] W:val

So val is written on t1 before t6 where addr and ti still alive.

The similar is for [addr] "+&r" (guest_addr):

Quoted 7 lines

addr is written on t5 and input ti is alive till t6. So if allocator will allocate the same register for addr and ti then addi %[addr], %[addr], 2 will break a pointer and handler will get something wrong.

Am I missing something?

If I am still wrong then in both cases should be just "+r"?

As per above, if you want to play absolutely by the rules, use "+&r", even if that's unnecessary here.

Jan

#104 lore raw

Re: [PATCH v1 13/17] xen/riscv: add unprivileged guest memory read helper

Quoted 83 lines · Jan Beulich
Quoted 67 lines · Oleksii Kurochko
Quoted 31 lines · Jan Beulich
Quoted 30 lines · Oleksii Kurochko
Quoted 21 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko
(quoted diff) +9 -0
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1:\n"
+            "   hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bne %[tmp], zero, 3f\n"

Review

Quoted 10 lines
(quoted diff) +10 -0
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2:\n"
+            "   hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   sll %[tmp], %[tmp], 16\n"
+            "   add %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "=&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr)
+        : [ti] "r" (trap) : "memory" );
Quoted 3 lines

You want to tell the compiler that *trap is written. Instead I don't see why a memory clobber would be needed: You access a different address space, i.e. nothing the compiler can make any assumptions about.

memory clobber tells the compiler that the assembly code performs memory reads or writes to items other than those listed in the input and output operands and so I don't tell here that *trap will be changed.

Quoted 5 lines
Quoted 1 line

Why this understanding is wrong?

You can (ab)use "memory" for that purpose, but why would you when you can properly express the operand? All that achieves is the compiler possibly having to emit less efficient code.

Then I will use the option mentioned ...

Quoted 5 lines
Quoted 5 lines

Alternative, I think, could be:

           : [val] "+r" (val), "+m" (*trap)
           : [addr] "r" (guest_addr), [ti] "r" (trap) );

And then memory clobber could be dropped.

... here.

Probably I have to return '[addr] "r" (guest_addr)' to output and use +&r constraint.

Quoted 6 lines
Quoted 6 lines
Quoted 3 lines

You also need to take precautions for not returning an uninitialized "val". I think the variable wants initializing (perhaps to ~0) and "+r" wants using as constraint. (Afaik & isn't necessary to use together with +.)

I agree with '+' if we will initialize val with some value.

Quoted 7 lines
Quoted 1 line

Regarding, '&' my understanding is that I have to use it always when

When what exactly? If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose? '&' indicates to the compiler that it may not use the register used for an output to hold some input's value, as that value may be lost by the time the input is actually consumed.

But what is written in the gcc doc:

Quoted 8 lines

& - Means (in a particular alternative) that this operand is an earlyclobber operand, which is written before the instruction is finished using the input operands.

What sounds like if an operand (val) in our case is written before the instruction which using the input operands (and after the write instuction which writes val there are instructions which are using input operands) it is needed to have &.

And that's indeed relevant, just not here. My crucial earlier question was:
"If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose?" There is a case where the answer to this is not "it can't". In your case all inputs are distinct; in e.g. (using x86 assembly, sorry):

Quoted 8 lines
int test(int i, int j) {
	asm("nop %0; nop %1" : "+r" (i) : "r" (i));
	asm("cmc; nop %0; nop %1" : "+&r" (j) : "r" (j));

	return i + j;
}

using "+&r" indeed makes a difference.

I think it is clear when operands are equal. but what about the case when they are different in first case:
...
asm("nop %0; nop %1" : "+r" (i) : "r" (j));
...

What guarantees that i and j will be in different registers?

We have the similar situation in RISC-V code of riscv_vcpu_unpriv_read():

        : [val] "+r" (val), [tmp] "=&r" (tmp), [addr] "+r" (guest_addr),
          "+m" (*trap)
        : [ti] "r" (trap) );

With having & for val and guest_addr & guarantees that the same registers won't be re-used for ti (and so ti won't be corrupted) but without it?

~ Oleksii

Quoted 29 lines
Quoted 17 lines

t1: hlvx.hu %[val], (%[addr]) W:val R:addr + can trap -> read register ti

t2:  andi    %[tmp], %[val], 3   W:tmp   R:val
t3:  addi    %[tmp], %[tmp], -3
t4:  bnez    %[tmp], 3f
t5:  addi    %[addr], %[addr], 2 W:addr  R:addr
t6:  hlvx.hu %[tmp], (%[addr])   W:tmp   R:addr + can trap -> read

register ti

t7:  slli    %[tmp], %[tmp], 16
t8:  or      %[val], %[val], %[tmp] W:val

So val is written on t1 before t6 where addr and ti still alive.

The similar is for [addr] "+&r" (guest_addr):

Quoted 7 lines

addr is written on t5 and input ti is alive till t6. So if allocator will allocate the same register for addr and ti then addi %[addr], %[addr], 2 will break a pointer and handler will get something wrong.

Am I missing something?

If I am still wrong then in both cases should be just "+r"?

As per above, if you want to play absolutely by the rules, use "+&r", even if that's unnecessary here.

Jan

#105 lore raw

Re: [PATCH v1 13/17] xen/riscv: add unprivileged guest memory read helper

Quoted 95 lines · Oleksii Kurochko
Quoted 83 lines · Jan Beulich
Quoted 67 lines · Oleksii Kurochko
Quoted 31 lines · Jan Beulich
Quoted 30 lines · Oleksii Kurochko
Quoted 21 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko
(quoted diff) +9 -0
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1:\n"
+            "   hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bne %[tmp], zero, 3f\n"

Review

Quoted 10 lines
(quoted diff) +10 -0
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2:\n"
+            "   hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   sll %[tmp], %[tmp], 16\n"
+            "   add %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "=&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr)
+        : [ti] "r" (trap) : "memory" );
Quoted 3 lines

You want to tell the compiler that *trap is written. Instead I don't see why a memory clobber would be needed: You access a different address space, i.e. nothing the compiler can make any assumptions about.

memory clobber tells the compiler that the assembly code performs memory reads or writes to items other than those listed in the input and output operands and so I don't tell here that *trap will be changed.

Quoted 5 lines
Quoted 1 line

Why this understanding is wrong?

You can (ab)use "memory" for that purpose, but why would you when you can properly express the operand? All that achieves is the compiler possibly having to emit less efficient code.

Then I will use the option mentioned ...

Quoted 5 lines
Quoted 5 lines

Alternative, I think, could be:

           : [val] "+r" (val), "+m" (*trap)
           : [addr] "r" (guest_addr), [ti] "r" (trap) );

And then memory clobber could be dropped.

... here.

Probably I have to return '[addr] "r" (guest_addr)' to output and use +&r constraint.

Quoted 6 lines
Quoted 6 lines
Quoted 3 lines

You also need to take precautions for not returning an uninitialized "val". I think the variable wants initializing (perhaps to ~0) and "+r" wants using as constraint. (Afaik & isn't necessary to use together with +.)

I agree with '+' if we will initialize val with some value.

Quoted 7 lines
Quoted 1 line

Regarding, '&' my understanding is that I have to use it always when

When what exactly? If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose? '&' indicates to the compiler that it may not use the register used for an output to hold some input's value, as that value may be lost by the time the input is actually consumed.

But what is written in the gcc doc:

Quoted 8 lines

& - Means (in a particular alternative) that this operand is an earlyclobber operand, which is written before the instruction is finished using the input operands.

What sounds like if an operand (val) in our case is written before the instruction which using the input operands (and after the write instuction which writes val there are instructions which are using input operands) it is needed to have &.

And that's indeed relevant, just not here. My crucial earlier question was:
"If an operand is both input and output, how could the compiler re-use the (generally) register for any further purpose?" There is a case where the answer to this is not "it can't". In your case all inputs are distinct; in e.g. (using x86 assembly, sorry):

Quoted 8 lines
int test(int i, int j) {
	asm("nop %0; nop %1" : "+r" (i) : "r" (i));
	asm("cmc; nop %0; nop %1" : "+&r" (j) : "r" (j));

	return i + j;
}

using "+&r" indeed makes a difference.

Quoted 7 lines

I think it is clear when operands are equal. but what about the case when they are different in first case:
...
asm("nop %0; nop %1" : "+r" (i) : "r" (j));
...

What guarantees that i and j will be in different registers?

They can both be in the same register only if the compiler sees respective call sites, and can determine that the same value is passed for i and j. This ...

Quoted 9 lines

We have the similar situation in RISC-V code of riscv_vcpu_unpriv_read():

         : [val] "+r" (val), [tmp] "=&r" (tmp), [addr] "+r" (guest_addr),
           "+m" (*trap)
         : [ti] "r" (trap) );

With having & for val and guest_addr & guarantees that the same registers won't be re-used for ti (and so ti won't be corrupted) but without it?

... pretty clearly is impossible in your case: val and guest_addr can't possibly have the same origin as trap.

Yet to repeat what I said before, and to not needlessly continue this discussion, just go and use "+&r", despite that being unnecessary here.

Jan

#110 lore raw

Re: [PATCH v1 14/17] xen/riscv: add guest page fault handling stub

In reply to Jan Beulich
Quoted 14 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
Quoted 11 lines · Jan Beulich

xen/arch/riscv/traps.c static void timer_interrupt(void) · line 194

Quoted 7 lines · Oleksii Kurochko
xen/arch/riscv/traps.c +1 -0
@@ -191,6 +191,67 @@ static void timer_interrupt(void)
       raise_softirq(TIMER_SOFTIRQ);
   }
 
+static always_inline unsigned long get_faulting_gpa(void)

May I suggest to use always_inline only when inlining is _functionally_ required?

Quoted 8 lines
Quoted 2 lines

Sure. But it ins't clear to me why it isn't a case here? Is it connected to that function is static and too simple so a compiler will do by itself?

Counter question: What is it that would functionally break if the function ended up not being inlined? (This is the question you generally need to answer to justify use of always_inline. Of course there's the additional case of performance being affected, but I don't view that as applicable here; I'm open to be proven wrong, though.)

Now it is clear how to identrify if function should be always_inline.

I put it only for the purpose to be sure that this function won't be called with prologue/epilogue but I agree that compiler will do that by itself.

Quoted 39 lines
Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
xen/arch/riscv/traps.c +16 -0
+{
+    /*
+     * According to RISC-V spec:
+     *  18.2.8. Hypervisor Trap Value Register (htval)
+     *   ...
+     *   A guest physical address written to htval is shifted right by 2 bits
+     *   to accommodate addresses wider than the current XLEN.
+     *   ...
+     *   If the least-significant two bits of a faulting guest physical address
+     *   are needed, these bits are ordinarily the same as the
+     *   least-significant two bits of the faulting virtual address in stval.
+     *   For faults due to implicit memory accesses for VS-stage address
+     *   translation, the least-significant two bits are instead zeros. These
+     *   cases can be distinguished using the value provided in register htinst.
+     */
+    return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);
Quoted 7 lines
Quoted 2 lines

Well, okay, but instead of not losing the bottom two bits you're now losing the top two ones.

Oh, right, I will add a cast ((uint64_t)csr_read(CSR_HTVAL) << 2) | ...

It will cover all the cases RV32 which has 34-bit guest address and it will be enough for RV64 where GPA is 59bit (the highest possible for Sv59).

Only if the function return type then also changes.

Quoted 11 lines
Quoted 2 lines

Also the spec reads as if htval only _may_ hold the original address of the faulting access. What if htval ends up 0?

good point. then we have to emulate fault instruction and get an address from an instruction. I think that for now it will be enough just to support platforms which always write GPA to HTVAL.

If I understand correctly if htval is supported by platform then htval will be always filled for guest page fault. To verify if HTVAL is supported we could do:

Quoted 8 lines
Quoted 3 lines

'Unless it has reason to assume otherwise (such as a platform standard), software that writes a value to htval should read back from htval to confirm the stored value.'

How does this matter here? It's one thing for htval to be capable of holding (all?) non-zero values, and another that it would always be written. If the platform doesn't indicate the behavior, I fear you have to assume that you may (perhaps even randomly) observe 0.

So to be very sure we could check for two extensions: Sstval and Shtval. They will guarantee that under any circumstances it will be filled.

Also, as an option we could check that htinst value isn't zero as according to the spec:

For guest-page faults, the trap instruction register is written with a special pseudoinstruction value if:
(a) the fault is caused by an implicit memory access for VS-stage address translation, and (b) a nonzero value (the faulting guest physical address) is written to mtval2 or htval.

So if htinst != 0 then htval is filled with GPA and a nonzero guest physical address written to mtval2/htval shall correspond to the exact virtual address written to mtval/stval.

But if htinst is 0 then we have to do VS-stage software pagewalk to get GPA and also we will need to decode instruction to get GVA.

I am thinking if it will be okay for now to cover the case htinst != 0 and have BUG_ON(!htinst) to not miss that the possible future case when VS-stage s/w page walks and parsing of GVA from an instruction are needed. I think it is fine as all real boards on which I was able to test Xen has htval and stval properly filled and of course QEMU code guarantees that htval and stval will be properly filled in the case of QEMU. Also, KVM is based also only htval and stval and I assume that they tested it on real hardware too so it seems like it is okay to go with solution that for now we are using htval + stval to get faulty address.

Quoted 9 lines
Quoted 7 lines

And is it true because:

```
A value of zero in mtval signifies either that the feature is not
supported, or an illegal zero instruction was fetched.
```

(yes, it is about mtval but I asssume that htval has the same behaviour').

Right, but what you quote is specific to illegal instruction exceptions.

Oh, right.

~ Oleksii

#111 lore raw

Re: [PATCH v1 14/17] xen/riscv: add guest page fault handling stub

Quoted 86 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich
Quoted 12 lines · Oleksii Kurochko
Quoted 10 lines · Jan Beulich

xen/arch/riscv/traps.c static void timer_interrupt(void) · line 193

Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/traps.c +1 -0
@@ -191,6 +191,67 @@ static void timer_interrupt(void)
        raise_softirq(TIMER_SOFTIRQ);
    }
+static always_inline unsigned long get_faulting_gpa(void)

May I suggest to use always_inline only when inlining is _functionally_ required?

Quoted 8 lines
Quoted 2 lines

Sure. But it ins't clear to me why it isn't a case here? Is it connected to that function is static and too simple so a compiler will do by itself?

Counter question: What is it that would functionally break if the function ended up not being inlined? (This is the question you generally need to answer to justify use of always_inline. Of course there's the additional case of performance being affected, but I don't view that as applicable here; I'm open to be proven wrong, though.)

Now it is clear how to identrify if function should be always_inline.

I put it only for the purpose to be sure that this function won't be called with prologue/epilogue but I agree that compiler will do that by itself.

Quoted 45 lines
Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
xen/arch/riscv/traps.c +6 -0
+{
+    /*
+     * According to RISC-V spec:
+     *  18.2.8. Hypervisor Trap Value Register (htval)
+     *   ...
+     *   A guest physical address written to htval is shifted 

right by 2 bits
+     *   to accommodate addresses wider than the current XLEN. +     *   ...
+     *   If the least-significant two bits of a faulting guest physical address
+     *   are needed, these bits are ordinarily the same as the +     *   least-significant two bits of the faulting virtual address in stval.
+     *   For faults due to implicit memory accesses for VS-stage address
+     *   translation, the least-significant two bits are instead zeros. These
+     *   cases can be distinguished using the value provided in register htinst.
+     */
+    return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);

Quoted 7 lines
Quoted 2 lines

Well, okay, but instead of not losing the bottom two bits you're now losing the top two ones.

Oh, right, I will add a cast ((uint64_t)csr_read(CSR_HTVAL) << 2) | ...

It will cover all the cases RV32 which has 34-bit guest address and it will be enough for RV64 where GPA is 59bit (the highest possible for Sv59).

Only if the function return type then also changes.

Quoted 11 lines
Quoted 2 lines

Also the spec reads as if htval only _may_ hold the original address of the faulting access. What if htval ends up 0?

good point. then we have to emulate fault instruction and get an address from an instruction. I think that for now it will be enough just to support platforms which always write GPA to HTVAL.

If I understand correctly if htval is supported by platform then htval will be always filled for guest page fault. To verify if HTVAL is supported we could do:

Quoted 8 lines
Quoted 3 lines

'Unless it has reason to assume otherwise (such as a platform standard), software that writes a value to htval should read back from htval to confirm the stored value.'

How does this matter here? It's one thing for htval to be capable of holding (all?) non-zero values, and another that it would always be written. If the platform doesn't indicate the behavior, I fear you have to assume that you may (perhaps even randomly) observe 0.

So to be very sure we could check for two extensions: Sstval and Shtval. They will guarantee that under any circumstances it will be filled.

Quoted 7 lines

Also, as an option we could check that htinst value isn't zero as according to the spec:

For guest-page faults, the trap instruction register is written with a special pseudoinstruction value if:
(a) the fault is caused by an implicit memory access for VS-stage address translation, and (b) a nonzero value (the faulting guest physical address) is written to mtval2 or htval.

So if htinst != 0 then htval is filled with GPA and a nonzero guest physical address written to mtval2/htval shall correspond to the exact virtual address written to mtval/stval.

I've re-read SPEC again and it looks like htinst != 0 doesn't guarantee that htval and stval will contain necessary for me here faulty instruction. What I wrote above guarantee that if a fault during VS-stage translation failed then it htval will contatain GPA of PTE with which was an issue.

So I have to blindly believe that HTVAL and STVAL will always contain necessary for me data as KVM and other hypervisor does or introduce here software guest page table walker if Sstvala and Shtvala aren't provided by platform.

~ Oleksii

Quoted 19 lines

But if htinst is 0 then we have to do VS-stage software pagewalk to get GPA and also we will need to decode instruction to get GVA.

I am thinking if it will be okay for now to cover the case htinst != 0 and have BUG_ON(!htinst) to not miss that the possible future case when VS-stage s/w page walks and parsing of GVA from an instruction are needed. I think it is fine as all real boards on which I was able to test Xen has htval and stval properly filled and of course QEMU code guarantees that htval and stval will be properly filled in the case of QEMU. Also, KVM is based also only htval and stval and I assume that they tested it on real hardware too so it seems like it is okay to go with solution that for now we are using htval + stval to get faulty address.

Quoted 9 lines
Quoted 7 lines

And is it true because:

```
A value of zero in mtval signifies either that the feature is not
supported, or an illegal zero instruction was fetched.
```

(yes, it is about mtval but I asssume that htval has the same behaviour').

Right, but what you quote is specific to illegal instruction exceptions.

Oh, right.

~ Oleksii

#112 lore raw

Re: [PATCH v1 14/17] xen/riscv: add guest page fault handling stub

Quoted 83 lines · Oleksii Kurochko
Quoted 72 lines · Oleksii Kurochko
Quoted 50 lines · Jan Beulich
Quoted 29 lines · Oleksii Kurochko
Quoted 24 lines · Jan Beulich
Quoted 14 lines · Oleksii Kurochko

+{
+    /*
+     * According to RISC-V spec:
+     *  18.2.8. Hypervisor Trap Value Register (htval) +     *   ...
+     *   A guest physical address written to htval is shifted right by 2 bits
+     *   to accommodate addresses wider than the current XLEN. +     *   ...
+     *   If the least-significant two bits of a faulting guest physical address
+     *   are needed, these bits are ordinarily the same as the +     *   least-significant two bits of the faulting virtual address in stval.

Quoted 8 lines

+     *   For faults due to implicit memory accesses for VS-stage address
+     *   translation, the least-significant two bits are instead zeros. These
+     *   cases can be distinguished using the value provided in register htinst.
+     */
+    return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);

Quoted 3 lines

Well, okay, but instead of not losing the bottom two bits you're now losing
the top two ones.

Quoted 5 lines

Oh, right, I will add a cast ((uint64_t)csr_read(CSR_HTVAL) << 2) | ...

It will cover all the cases RV32 which has 34-bit guest address and it will be enough for RV64 where GPA is 59bit (the highest possible for Sv59).

Only if the function return type then also changes.

Quoted 12 lines
Quoted 3 lines

Also the spec reads as if htval only _may_ hold the original address of the
faulting access. What if htval ends up 0?

good point. then we have to emulate fault instruction and get an address from an instruction. I think that for now it will be enough just to support platforms which always write GPA to HTVAL.

If I understand correctly if htval is supported by platform then htval will be always filled for guest page fault. To verify if HTVAL is supported we could do:

Quoted 8 lines
Quoted 3 lines

'Unless it has reason to assume otherwise (such as a platform standard), software that writes a value to htval should read back from htval to confirm the stored value.'

How does this matter here? It's one thing for htval to be capable of holding (all?) non-zero values, and another that it would always be written. If the platform doesn't indicate the behavior, I fear you have to assume that you may (perhaps even randomly) observe 0.

So to be very sure we could check for two extensions: Sstval and Shtval. They will guarantee that under any circumstances it will be filled.

Also, as an option we could check that htinst value isn't zero as according to the spec:

For guest-page faults, the trap instruction register is written with a special pseudoinstruction value if:
(a) the fault is caused by an implicit memory access for VS-stage address translation, and (b) a nonzero
value (the faulting guest physical address) is written to mtval2 or htval.

Quoted 3 lines

So if htinst != 0 then htval is filled with GPA and a nonzero guest physical address written to mtval2/htval shall correspond to the exact virtual address written to mtval/stval.

I've re-read SPEC again and it looks like htinst != 0 doesn't guarantee that htval and stval will contain necessary for me here faulty instruction. What I wrote above guarantee that if a fault during VS-stage translation failed then it htval will contatain GPA of PTE with which was an issue.

Quoted 4 lines

So I have to blindly believe that HTVAL and STVAL will always contain necessary for me data as KVM and other hypervisor does or introduce here software guest page table walker if Sstvala and Shtvala aren't provided by platform.

Why "blindly believe"? Checking for the necessary extension(s) should be an option. Adding fallback code for when an extension isn't available can come later, can't it?

Jan

#113 lore raw

Re: [PATCH v1 14/17] xen/riscv: add guest page fault handling stub

Quoted 84 lines · Jan Beulich
Quoted 83 lines · Oleksii Kurochko
Quoted 72 lines · Oleksii Kurochko
Quoted 50 lines · Jan Beulich
Quoted 29 lines · Oleksii Kurochko
Quoted 24 lines · Jan Beulich
Quoted 14 lines · Oleksii Kurochko

+{
+    /*
+     * According to RISC-V spec:
+     *  18.2.8. Hypervisor Trap Value Register (htval) +     *   ...
+     *   A guest physical address written to htval is shifted right by 2 bits
+     *   to accommodate addresses wider than the current XLEN. +     *   ...
+     *   If the least-significant two bits of a faulting guest physical address
+     *   are needed, these bits are ordinarily the same as the +     *   least-significant two bits of the faulting virtual address in stval.

Quoted 8 lines

+     *   For faults due to implicit memory accesses for VS-stage address
+     *   translation, the least-significant two bits are instead zeros. These
+     *   cases can be distinguished using the value provided in register htinst.
+     */
+    return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);

Quoted 3 lines

Well, okay, but instead of not losing the bottom two bits you're now losing
the top two ones.

Quoted 5 lines

Oh, right, I will add a cast ((uint64_t)csr_read(CSR_HTVAL) << 2) | ...

It will cover all the cases RV32 which has 34-bit guest address and it will be enough for RV64 where GPA is 59bit (the highest possible for Sv59).

Only if the function return type then also changes.

Quoted 12 lines
Quoted 3 lines

Also the spec reads as if htval only _may_ hold the original address of the
faulting access. What if htval ends up 0?

good point. then we have to emulate fault instruction and get an address from an instruction. I think that for now it will be enough just to support platforms which always write GPA to HTVAL.

If I understand correctly if htval is supported by platform then htval will be always filled for guest page fault. To verify if HTVAL is supported we could do:

Quoted 8 lines
Quoted 3 lines

'Unless it has reason to assume otherwise (such as a platform standard), software that writes a value to htval should read back from htval to confirm the stored value.'

How does this matter here? It's one thing for htval to be capable of holding (all?) non-zero values, and another that it would always be written. If the platform doesn't indicate the behavior, I fear you have to assume that you may (perhaps even randomly) observe 0.

So to be very sure we could check for two extensions: Sstval and Shtval. They will guarantee that under any circumstances it will be filled.

Also, as an option we could check that htinst value isn't zero as according to the spec:

For guest-page faults, the trap instruction register is written with a special pseudoinstruction value if:
(a) the fault is caused by an implicit memory access for VS-stage address translation, and (b) a nonzero
value (the faulting guest physical address) is written to mtval2 or htval.

Quoted 3 lines

So if htinst != 0 then htval is filled with GPA and a nonzero guest physical address written to mtval2/htval shall correspond to the exact virtual address written to mtval/stval.

I've re-read SPEC again and it looks like htinst != 0 doesn't guarantee that htval and stval will contain necessary for me here faulty instruction. What I wrote above guarantee that if a fault during VS-stage translation failed then it htval will contatain GPA of PTE with which was an issue.

Quoted 8 lines
Quoted 4 lines

So I have to blindly believe that HTVAL and STVAL will always contain necessary for me data as KVM and other hypervisor does or introduce here software guest page table walker if Sstvala and Shtvala aren't provided by platform.

Why "blindly believe"? Checking for the necessary extension(s) should be an option. Adding fallback code for when an extension isn't available can come later, can't it?

It can be an option. It is what I planned to do.

~ Oleksii

#123 lore raw

Re: [PATCH v1 16/17] xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to Jan Beulich
Quoted 41 lines · Jan Beulich
Quoted 40 lines · Jan Beulich
Quoted 20 lines · Oleksii Kurochko

static int emulate_load(unsigned long fault_addr, unsigned long htinst) {

xen/arch/riscv/traps.c +17 -1
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    mmio_info_t info = { .is_write = false };
+    unsigned long insn;
+    unsigned int shift = 0, len, insn_len;
+    bool is_unsigned = false;
+    int rc;
+
+    if ( decode_trapped_insn(htinst, &insn, &insn_len) )
+        return 0;
+
+    /* Decode length of MMIO and whether it is a sign- or zero-extending load */
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        len = 1;
+        is_unsigned = true;

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 328

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        len = 2;
+        is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        len = 4;

Already up to here this demonstrates a weakness of the INSN_MASK_* set of #define-s (which I similarly observe in binutils, and I expect it all has the same questionable origin). All INSN_MASK_L* and INSN_MASK_FL* (also INSN_MASK_S* and INSN_MASK_FS*) are identical, allowing for a nice switch() to be used here in principle. That said, with access width nicely encoded in FUNCT3, it's not even clear whether a switch() would end up being needed / efficient.

Quoted 8 lines
Quoted 4 lines

Otoh none of these masks cover the pseudoinsns that htinst may supply.

Further, what about A-extension insns? Some (if not all) of them can plausibly be used on MMIO, I think.

Because of the further additions that are going to be needed, may I also suggest to consider putting emulation code in its own file (emulate.c perhaps), rather than directly in traps.c?

Good point. It really makes sense to move emulation now to emulate.c.

Thanks.

~ Oleksii

#124 lore raw

Re: [PATCH v1 16/17] xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to Jan Beulich
Quoted 27 lines · Jan Beulich
Quoted 12 lines · Oleksii Kurochko

Introduce emulate_load() to decode and emulate guest load instructions that fault due to MMIO accesses. This provides the basic infrastructure required for MMIO emulation on RISC-V.

The instruction decode (decode_trapped_insn() and the mask/match chain for standard and compressed load encodings) is adapted from Linux's KVM RISC-V implementation. The completion path differs from KVM's, since Xen dispatches MMIO synchronously to an in-hypervisor handler via try_handle_mmio() and has no userspace exit/return step equivalent to KVM's kvm_io_bus_read() / KVM_EXIT_MMIO / kvm_riscv_vcpu_mmio_return() split.

Quoted 13 lines

A fault taken while re-reading the trapped instruction is handled depending on the faulting translation stage:
- A VS-stage fault is the guest's own fault (e.g. it modified its page tables from another vCPU) and, as in KVM, is redirected to the guest's trap vector, with the cause remapped to CAUSE_FETCH_PAGE_FAULT since HLVX reports execute-permission failures as load faults.
- A G-stage fault would mean the P2M mapping of the instruction page disappeared after the instruction was fetched. KVM must handle this by resuming the guest and retrying, as Linux MM can invalidate G-stage mappings at any time. Xen does not remove P2M mappings of a running domain at the moment, so this case is asserted unreachable with BUG_ON(); it will need to be revisited once such removal is implemented.

Quoted 3 lines

I don't see why this cannot be implemented correctly right away. The behavior should be that of an access to unpopulated space on bare hardware, whatever that behavior is on RISC-V.

I wasn't able to find a spec what should be returned in this case but in QEMU source code I founded (unassigned_mem_ops → MEMTX_DECODE_ERROR → io_failed() → riscv_cpu_do_transaction_failed().):

void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
vaddr addr, unsigned size, MMUAccessType access_type, int mmu_idx, MemTxAttrs attrs, MemTxResult response, uintptr_t
retaddr)

{
    RISCVCPU *cpu = RISCV_CPU(cs);
    CPURISCVState *env = &cpu->env;

    if (access_type == MMU_DATA_STORE) {
        cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
    } else if (access_type == MMU_DATA_LOAD) {
        cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
    } else {
        cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
    }

So RISCV_EXCP_INST_ACCESS_FAULT (in Xen it is CAUSE_FETCH_ACCESS) will be fine to return.

So do the following:

if ( is_load_guest_page_fault(utrap.scause) )
utrap.scause = CAUSE_FETCH_ACCESS;

will be fair enough instead of: BUG_ON(is_load_guest_page_fault(utrap.scause)).

Probably, we want to rename CAUSE_FETCH_ACCESS to be closer to RISC-V spec as for value 1 in spec it is used:
1 Instruction access fault
Interesting that all other CAUSE_* defines are aligned with the spec...

Quoted 17 lines

xen/arch/riscv/include/asm/traps.h struct trap_info { · line 20

Quoted 9 lines
xen/arch/riscv/include/asm/traps.h +4 -0
@@ -13,6 +14,11 @@ struct trap_info {
      register_t stval;
  };
 
+static inline bool is_load_guest_page_fault(unsigned long scause)
+{
+    return (scause == CAUSE_LOAD_GUEST_PAGE_FAULT);
+}

Is something like this really a useful wrapper to have? It doesn't really shorten anything, nor does (imo) it aid readability.

Quoted 4 lines
xen/arch/riscv/traps.c +0 -0
@@ -191,6 +193,11 @@ static void timer_interrupt(void)
      raise_softirq(TIMER_SOFTIRQ);
  }
 
Quoted 5 lines

xen/arch/riscv/traps.c static void timer_interrupt(void) · line 196

Quoted 1 line
xen/arch/riscv/traps.c +1 -0
+static always_inline void advance_pc(struct cpu_user_regs *regs, int step)

See my earlier remark regarding always_inline. Also - why plain int? Are there (going to be) cases where PC is moved backwards (in which case "advance" isn't suitable naming)?

No, it won't. At least, I don't see such use cases now. I'll use unsigned int instead.

Quoted 33 lines
Quoted 20 lines
xen/arch/riscv/traps.c +12 -0
+{
+    regs->sepc += step;
+}
+
  static always_inline unsigned long get_faulting_gpa(void)
  {
      /*
@@ -210,9 +217,162 @@ static always_inline unsigned long get_faulting_gpa(void)
      return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);
  }
 
+/*
+ * Determine the trapped instruction which caused a guest MMIO trap.
+ *
+ * Returns true if the trap was redirected to the guest, in which case
+ * the caller must stop emulation and return success. Otherwise *insn
+ * and *insn_len are filled in and the caller should continue decoding.
+ */
+static bool decode_trapped_insn(unsigned long htinst, unsigned long *insn,

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 237

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+                                unsigned int *insn_len)
+{
+    if ( htinst & 0x1 )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         */
+        *insn = htinst | INSN_16BIT_MASK;
+        *insn_len = (htinst & BIT(1, UL)) ? INSN_LEN(*insn) : 2;

In the if() you don't use BIT(), while here you do. Please be consistent.

Quoted 2 lines

Why the use of INSN_LEN(), when due to the earlier assignment it'll always yield 4 here?

ld/sd instruction which we are trapping here at the moment here could be 2 bit and 4 bit depends on C extension so we need to pass correct instruction length to advance_pc() after it is emulated.

Quoted 3 lines

Finally, how would the caller know whether it looks at a transformed insn or (as fetched below) a "normal" one?

According to the spec ((part from htinst ... ):
On a synchronous exception, if a nonzero value is written, one of the following shall be true about the value:

• Bit 0 is 1, and replacing bit 1 with 1 makes the value into a valid encoding of a standard instruction.
In this case, the instruction that trapped is the same kind as indicated by the register value, and the register value is the transformation of the trapping instruction, as defined later. For example, if bits 1:0 are binary 11 and the register value is the encoding of a standard LW (load word) instruction, then the trapping instruction is LW, and the register value is the transformation of the trapping LW instruction.

• Bit 0 is 1, and replacing bit 1 with 1 makes the value into an instruction encoding that is explicitly designated for a custom instruction (not an unused reserved encoding). This is a custom value. The instruction that trapped is a non-standard instruction. The interpretation of a custom value is not otherwise specified by this standard.

• The value is one of the special pseudoinstructions defined later, all of which have bits 1:0 equal to 00.

So setting bit 0 to 1 we will guarantee that it is normal "normal" instruction.

Quoted 12 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 241

Quoted 5 lines
xen/arch/riscv/traps.c +4 -0
+    }
+    else
+    {
+        struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);

Pointer-to-const.

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 242

Quoted 1 line
xen/arch/riscv/traps.c +1 -0
+        struct trap_info utrap = { 0 };

Just {} please.

Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 247

Quoted 4 lines
xen/arch/riscv/traps.c +4 -0
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value.
+         */

How come you get away without dealing with pseudoinsns? The insn pointed at by regs->sepc is of no interest for faults caused by implicit memory accesses originating from VS-stage address translation.

It is really problem but I think it should be resolved much earlier in handle_guest_page_fault(). I will add the following:

/*
* A guest page fault taken on an implicit memory access performed for
* VS-stage address translation (reading a PTE, or updating its A/D
bits)
* reports a pseudoinstruction in htinst rather than a transformed
* instruction. Such a fault can't be emulated: htval holds the guest
* physical address of a VS-stage PTE rather than of any access the
guest
* itself performed (and its two least significant bits are zero
instead
* of matching stval), while the instruction at sepc is unrelated
to the
* access which actually faulted.
*
* Report an access fault to the guest at the original virtual address,
* which is what stval already holds and what hardware would raise
for a

     * page table walk hitting an inaccessible address.
     */
    if ( (htinst == INSN_PSEUDO_VS_LOAD) || (htinst == 
INSN_PSEUDO_VS_STORE) )
    {
        struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
        struct trap_info utrap = {
            .scause = (htinst == INSN_PSEUDO_VS_LOAD) ? CAUSE_LOAD_ACCESS
                                                      : CAUSE_STORE_ACCESS,
            .sepc = regs->sepc,
            .stval = csr_read(CSR_STVAL),
        };

        riscv_trap_redirect(&utrap);
        return;
    }

and will update the comment:

Quoted 14 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void)

Quoted 13 lines
xen/arch/riscv/traps.c +11 -0
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value. It can't be pseudoinstruction as it is guaranteed by check in handle_guest_page_fault().
+         */
 
 
+        *insn = riscv_vcpu_unpriv_read(true, regs->sepc, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * A G-stage fault here would mean the P2M mapping of the page
+             * containing the trapped instruction disappeared after it was
+             * fetched.
Quoted 7 lines

Does it? What about, again, faults from VS-stage address translation while hardware was trying to fetch an insn? That is ...

Review static always_inline unsigned long get_faulting_gpa(void) · line 261

Quoted 2 lines
(quoted diff) +1 -0
 Nothing removes P2M mappings of a running domain yet,
+             * so this cannot happen.

... the necessary P2M mapping may never have been there.

If VS-stage failed then CAUSE_LOAD_PAGE_FAULT will happen so BUG_ON() won't occur and it will be passed to guest to handle it.

BUG_ON() here catches CAUSE_LOAD_GUEST_PAGE_FAULT (G-stage translation failure).

Also, as I mentioned above I will change BUG_ON() too:

/*
* If during getting of trapped instruction a fault happen in
* G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
* generated. Such faults during this operation is
considered as
* bus
*/
if ( is_load_guest_page_fault(utrap.scause) )
utrap.scause = CAUSE_FETCH_ACCESS;

Quoted 10 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 262

Quoted 7 lines
xen/arch/riscv/traps.c +6 -0
+             * TODO: Revisit once P2M mappings can be removed at runtime.
+             */
+            BUG_ON(is_load_guest_page_fault(utrap.scause));
+
+            utrap.sepc = regs->sepc;
+            utrap.stval = utrap.sepc;

How do you know the fault was at .sepc? A 32-bit insn crossing a page boundary (implying the C extension is available) may well fault only on its higher half.

According to the spec, if stval is written with a nonzero value when an instruction access-fault or page-fault exception occurs on a system with variable-length instructions, then stval will contain the virtual address of the portion of the instruction that caused the fault, while sepc will point to the beginning of the instruction.

So here, we are trying to emulate what real hardware will do in this case. In regs->sepc, we have the start of the instruction that we didn't touch. sepc is filled according to the spec in this case.

Regarding utrap.stval, we know that utrap.sepc points to the correct part of the faulting address, as we are reading the instruction in 16-bit chunks:

HLVX_HU(%[val], %[addr]) ; low 16 bits from sepc
andi %[tmp], %[val], 3
addi %[tmp], %[tmp], -3

bne  %[tmp], zero, 2f           ; if not (insn & 3) == 3 -> 16-bit, end
addi %[addr], %[addr], 2        ; <- addr is now sepc+2
HLVX_HU(%[tmp], %[addr])        ; high 16 bits, possibly from another page

So, if a trap happens while reading the high 16 bits (which may be located on another page), then utrap.sepc, if the read fails, will point to the high part of the instruction, which is what the spec requires.

Does that make sense?

Quoted 31 lines
Quoted 31 lines
xen/arch/riscv/traps.c +30 -0
+            riscv_vcpu_trap_redirect(&utrap);
+
+            return true;
+        }
+
+        *insn_len = INSN_LEN(*insn);
+    }
+
+    return false;
+}
+
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ */
+static int do_mmio(mmio_info_t *info, unsigned long fault_addr,
+                   unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;
+
+    info->gpa = fault_addr;
+    info->len = len;
+
+    switch ( try_handle_mmio(info) )
+    {
+    case IO_HANDLED:
+        return 0;
+    case IO_ABORT:
Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 298

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+        return -EIO;
+    default:
+        return -EOPNOTSUPP;
+    }
+}

And there's no indication of "retry needed", e.g. when something changed between find_mmio_handler() and handle_{read,write}()?

I don't have any specific scenario where it is needed now so I don't know what to say.
And there is no race between find_mmio_handler() and handle_{read,write}() as find_mmio_handler() returns copy of the structure under read_lock():
/*
* Return a copy of the matching handler rather than a pointer into
* vmmio->handlers: a concurrent register_mmio_handler() shifts entries
* up to keep the array sorted, so an escaped pointer could refer to a
* different (or torn) entry once the lock is dropped. The copy stays
* valid as the ops structures are never freed.
*/
static bool find_mmio_handler(struct domain *d, paddr_t gpa,
struct mmio_handler *out)

{
    struct vmmio *vmmio = &d->arch.vmmio;
    struct mmio_handler key = { .addr = gpa };
    const struct mmio_handler *handler;

    read_lock(&vmmio->lock);
    handler = bsearch(&key, vmmio->handlers, vmmio->num_entries,
                      sizeof(*handler), cmp_mmio_handler);
    if ( handler )
        *out = *handler;
    read_unlock(&vmmio->lock);

    return handler != NULL;
}

At the moment, use cases are pretty strainghforward, a device from guest trying to read/write into MMIO and so the result logically could be or it is successfully handled or some issue happened and it is just aborted. As a real hardware will do, I think.

Quoted 41 lines

Also, nit: Blank lines please between non-fall-through case blocks.

Quoted 20 lines
xen/arch/riscv/traps.c +17 -1
  static int emulate_load(unsigned long fault_addr, unsigned long htinst)
  {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    mmio_info_t info = { .is_write = false };
+    unsigned long insn;
+    unsigned int shift = 0, len, insn_len;
+    bool is_unsigned = false;
+    int rc;
+
+    if ( decode_trapped_insn(htinst, &insn, &insn_len) )
+        return 0;
+
+    /* Decode length of MMIO and whether it is a sign- or zero-extending load */
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        len = 1;
+        is_unsigned = true;

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 328

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        len = 2;
+        is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        len = 4;

Already up to here this demonstrates a weakness of the INSN_MASK_* set of #define-s (which I similarly observe in binutils, and I expect it all has the same questionable origin). All INSN_MASK_L* and INSN_MASK_FL* (also INSN_MASK_S* and INSN_MASK_FS*) are identical, allowing for a nice switch() to be used here in principle. That said, with access width nicely encoded in FUNCT3, it's not even clear whether a switch() would end up being needed / efficient.

.......

Quoted 2 lines

Otoh none of these masks cover the pseudoinsns that htinst may supply.

As I answered above we should handle that before this function will call so here we won't deal with htinst at all. Of course, if what I wrote above is correct. I will double check before applying that.

Quoted 3 lines

Further, what about A-extension insns? Some (if not all) of them can plausibly be used on MMIO, I think.

I’m not really sure that the A-extension is actively used for MMIO. At least, Linux doesn’t do that for now, which is why we don’t handle A-extension instructions here.

I think this is related to the fact that MMIO is usually (if not always?) naturally aligned, and naturally aligned loads and stores are guaranteed by RISC-V to execute atomically.

Anyway, since we don’t have a case for this for now, I think we could go with the current emulation. If this turns out not to be true in the future, A-extension support can be added separately.

Quoted 7 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 330

Quoted 3 lines
xen/arch/riscv/traps.c +2 -0
+#ifndef CONFIG_RISCV_32
+    else if ( (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )

First: Better use IS_ENABLED() in favor of #if{,n}def, whenever possible. And then this depends not only on CONFIG_RISCV_32, but also on guest bitness.

Both points taken. The #ifndef will become a condition in the if-chain; the INSN_MATCH_/INSN_MASK_ definitions are unconditional in riscv_encoding.h, so that builds either way.

On guest bitness you're right, and it's worse than the 32-bit-only encodings being reserved in RV32: the compressed RV64 encodings collide with the RV32 single-precision float ones — C.LD and C.FLW are both 0x6000 under mask 0xe003, likewise C.SD/C.FSW, C.LDSP/C.FLWSP and C.SDSP/C.FSWSP. A 32-bit guest doing a c.flw to an emulated MMIO region would be decoded as c.ld, i.e.an 8-byte access with the result written to an integer register.

I'll fold both into a helper returning the guest's effective XLEN
(hstatus.VSXL, or vsstatus.UXL when the trap was taken from VU-mode, and
unconditionally 32 for a RV32 build) and gate the RV64-only cases on it. As a side note, vcpu hstatus setup currently leaves VSXL alone and thus relies on the WARL behaviour of the field; I think Xen should set it explicitly.

/*
* The effective XLEN of the guest at the point of the trap:
hstatus.VSXL for a
* trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode. *
* It is needed to decode a trapped instruction: the encodings which
exist only
* for XLEN=64 must not be recognized for a 32-bit guest. Besides those
simply
* being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
* share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
* C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
*
* IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
* __riscv_xlen == 64 only, the field not existing on RV32 in the first
place.
*/
static unsigned int guest_xlen(const struct cpu_user_regs *regs) {

#ifdef CONFIG_RISCV_32
    return 32;
#else
    unsigned long xl = (regs->sstatus & SSTATUS_SPP)
                       ? MASK_EXTR(regs->hstatus, HSTATUS_VSXL)
                       : MASK_EXTR(csr_read(CSR_VSSTATUS), SSTATUS64_UXL);

    /* 1 encodes XLEN=32, 2 encodes XLEN=64. */
    return (xl == HSTATUS_VSXL_32) ? 32 : 64;

#endif
}

and then use it in emulate_store/load():

    unsigned int xlen = guest_xlen(regs);
    ...
    else if ( (xlen == 64) && ((insn & INSN_MASK_LWU) == INSN_MATCH_LWU) )
    {
        len = 4;
        is_unsigned = true;
    }
    ...
    else if ( (xlen == 64) && ((insn & INSN_MASK_C_LD) == 

INSN_MATCH_C_LD) )

Quoted 23 lines
Quoted 23 lines
xen/arch/riscv/traps.c +22 -0
+    {
+        len = 4;
+        is_unsigned = true;
+    }
+#endif
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        len = 4;
+        insn = RVC_RS2S(insn) << SH_RD;
+    }
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP &&
+              RV_X(insn, SH_RD, 5) )
+        len = 4;
+#ifndef CONFIG_RISCV_32
+    else if ( (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        len = 8;
+    else if ( (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        len = 8;
+        insn = RVC_RS2S(insn) << SH_RD;
+    }
+    else if ( (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 357

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+              RV_X(insn, SH_RD, 5) )
+        len = 8;
+#endif
+    else
+        return -EOPNOTSUPP;

Because you don't permit F/D/Q for guests (yet), FL* and FS* aren't covered, I expect?

At the moment, I wrote this function with handling of MMIO instruction in mind, which are at the moment ld and sd.

Even if to permit F/D/Q then do we really need to trap that instructions? Hypervisor could allow access to FPU to guest and then it will be just a question of context switch to properly save and restore FPU.

Quoted 3 lines

I wonder how easy it is going to be to spot the places needing adjustment once support is to be added. Same perhaps for Zilsd in RV32 guests.

There is a message in handle_guest_page_fault():

    if ( rc )
        domain_crash(current->domain,
                     "%s: unable to handle faulted guest %s addr %#lx\n",
                     __func__,
                     (cause == CAUSE_LOAD_GUEST_PAGE_FAULT) ? "load" : 
"store",
                     addr);

Probably, it isn't enough and we could print here instruction (in hex) before return -EOPNOTSUPP.

Thanks.

~ Oleksii

#125 lore raw

Re: [PATCH v1 16/17] xen/riscv: add guest load emulation for trapped MMIO accesses

Quoted 27 lines · Oleksii Kurochko
Quoted 26 lines · Jan Beulich
Quoted 12 lines · Oleksii Kurochko
xen/arch/riscv/traps.c +8 -0
@@ -210,9 +217,162 @@ static always_inline unsigned long get_faulting_gpa(void)
      return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);
  }
 
+/*
+ * Determine the trapped instruction which caused a guest MMIO trap.
+ *
+ * Returns true if the trap was redirected to the guest, in which case
+ * the caller must stop emulation and return success. Otherwise *insn
+ * and *insn_len are filled in and the caller should continue decoding.
+ */
+static bool decode_trapped_insn(unsigned long htinst, unsigned long *insn,

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 237

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+                                unsigned int *insn_len)
+{
+    if ( htinst & 0x1 )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         */
+        *insn = htinst | INSN_16BIT_MASK;
+        *insn_len = (htinst & BIT(1, UL)) ? INSN_LEN(*insn) : 2;

In the if() you don't use BIT(), while here you do. Please be consistent.

Quoted 6 lines
Quoted 2 lines

Why the use of INSN_LEN(), when due to the earlier assignment it'll always yield 4 here?

ld/sd instruction which we are trapping here at the moment here could be 2 bit and 4 bit depends on C extension so we need to pass correct instruction length to advance_pc() after it is emulated.

Well, fine, but how does that matter? I pointed you at the preceding assignment, which sets bits 0 and 1. With that INSN_LEN() is guaranteed to return (at least) 4 (and it's not presently capable of returning values larger than 4).

Quoted 23 lines
Quoted 2 lines

Finally, how would the caller know whether it looks at a transformed insn or (as fetched below) a "normal" one?

According to the spec ((part from htinst ... ):
On a synchronous exception, if a nonzero value is written, one of the following shall be true about the value:

• Bit 0 is 1, and replacing bit 1 with 1 makes the value into a valid encoding of a standard instruction.
In this case, the instruction that trapped is the same kind as indicated by the register value, and the register value is the transformation of the trapping instruction, as defined later. For example, if bits 1:0 are binary 11 and the register value is the encoding of a standard LW (load word) instruction, then the trapping instruction is LW, and the register value is the transformation of the trapping LW instruction.

• Bit 0 is 1, and replacing bit 1 with 1 makes the value into an instruction encoding that is explicitly designated for a custom instruction (not an unused reserved encoding). This is a custom value. The instruction that trapped is a non-standard instruction. The interpretation of a custom value is not otherwise specified by this standard.

Quoted 5 lines

• The value is one of the special pseudoinstructions defined later, all of which have bits 1:0 equal to 00.

So setting bit 0 to 1 we will guarantee that it is normal "normal" instruction.

Right. Yet my question was how to distinguish the cases. Or are you trying to tell me that distinguishing isn't going to be necessary, anywhere?

Quoted 40 lines
Quoted 11 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 241

Quoted 4 lines
xen/arch/riscv/traps.c +4 -0
+    }
+    else
+    {
+        struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);

Pointer-to-const.

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 242

Quoted 1 line
xen/arch/riscv/traps.c +1 -0
+        struct trap_info utrap = { 0 };

Just {} please.

Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 247

Quoted 4 lines
xen/arch/riscv/traps.c +4 -0
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value.
+         */

How come you get away without dealing with pseudoinsns? The insn pointed at by regs->sepc is of no interest for faults caused by implicit memory accesses originating from VS-stage address translation.

It is really problem but I think it should be resolved much earlier in handle_guest_page_fault(). I will add the following:

/*
* A guest page fault taken on an implicit memory access performed for
* VS-stage address translation (reading a PTE, or updating its A/D
bits)
* reports a pseudoinstruction in htinst rather than a transformed
* instruction. Such a fault can't be emulated: htval holds the guest
* physical address of a VS-stage PTE rather than of any access the
guest
* itself performed (and its two least significant bits are zero
instead
* of matching stval), while the instruction at sepc is unrelated
to the
* access which actually faulted.
*
* Report an access fault to the guest at the original virtual address,
* which is what stval already holds and what hardware would raise
for a

Quoted 16 lines
      * page table walk hitting an inaccessible address.
      */
     if ( (htinst == INSN_PSEUDO_VS_LOAD) || (htinst == 
INSN_PSEUDO_VS_STORE) )
     {
         struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
         struct trap_info utrap = {
             .scause = (htinst == INSN_PSEUDO_VS_LOAD) ? CAUSE_LOAD_ACCESS
                                                       : CAUSE_STORE_ACCESS,
             .sepc = regs->sepc,
             .stval = csr_read(CSR_STVAL),
         };

         riscv_trap_redirect(&utrap);
         return;
     }

That's not what would happen on bare hardware though, aiui. At least I don't think I ever found it being spelled out anywhere what the supposed behavior is when a page table resides in unpopulated space.

Quoted 11 lines
Quoted 11 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void)

Quoted 7 lines
xen/arch/riscv/traps.c +7 -0
+        *insn = riscv_vcpu_unpriv_read(true, regs->sepc, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * A G-stage fault here would mean the P2M mapping of the page
+             * containing the trapped instruction disappeared after it was
+             * fetched.

Does it? What about, again, faults from VS-stage address translation while hardware was trying to fetch an insn? That is ...

Quoted 7 lines
Quoted 4 lines

Review static always_inline unsigned long get_faulting_gpa(void) · line 255

Quoted 2 lines
(quoted diff) +1 -0
 Nothing removes P2M mappings of a running domain yet,
+             * so this cannot happen.

... the necessary P2M mapping may never have been there.

If VS-stage failed then CAUSE_LOAD_PAGE_FAULT will happen so BUG_ON() won't occur and it will be passed to guest to handle it.

Are you sure? So far it was my understanding that CAUSE_LOAD_PAGE_FAULT would happen when VS-stage translation hits e.g. a non-present leaf entry. But got an address translation failure while doing the VS-stage page walk (i.e. failure to translate the address found in a VS-stage PTE to a host address) would raise CAUSE_LOAD_GUEST_PAGE_FAULT.

Quoted 5 lines

BUG_ON() here catches CAUSE_LOAD_GUEST_PAGE_FAULT (G-stage translation failure).

Also, as I mentioned above I will change BUG_ON() too:

Quoted 7 lines

/*
* If during getting of trapped instruction a fault happen in
* G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
* generated. Such faults during this operation is
considered as
* bus
*/

What is "bus" here (dym "bug"?), and why is the sentence unfinished?

Quoted 16 lines
Quoted 9 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 262

Quoted 6 lines
xen/arch/riscv/traps.c +6 -0
+             * TODO: Revisit once P2M mappings can be removed at runtime.
+             */
+            BUG_ON(is_load_guest_page_fault(utrap.scause));
+
+            utrap.sepc = regs->sepc;
+            utrap.stval = utrap.sepc;

How do you know the fault was at .sepc? A 32-bit insn crossing a page boundary (implying the C extension is available) may well fault only on its higher half.

According to the spec, if stval is written with a nonzero value when an instruction access-fault or page-fault exception occurs on a system with variable-length instructions, then stval will contain the virtual address of the portion of the instruction that caused the fault, while sepc will point to the beginning of the instruction.

Quoted 3 lines

So here, we are trying to emulate what real hardware will do in this case. In regs->sepc, we have the start of the instruction that we didn't touch. sepc is filled according to the spec in this case.

Right, but utrap.stval is set to the same value, which is explicitly not in line with what you say above ("will contain the virtual address of the portion of the instruction that caused the fault").

Quoted 11 lines

Regarding utrap.stval, we know that utrap.sepc points to the correct part of the faulting address, as we are reading the instruction in 16-bit chunks:

HLVX_HU(%[val], %[addr]) ; low 16 bits from sepc
andi %[tmp], %[val], 3
addi %[tmp], %[tmp], -3

bne  %[tmp], zero, 2f           ; if not (insn & 3) == 3 -> 16-bit, end
addi %[addr], %[addr], 2        ; <- addr is now sepc+2
HLVX_HU(%[tmp], %[addr])        ; high 16 bits, possibly from another page
Quoted 5 lines

So, if a trap happens while reading the high 16 bits (which may be located on another page), then utrap.sepc, if the read fails, will point to the high part of the instruction, which is what the spec requires.

Does that make sense?

Not really, no. As said above - the code as written guarantees utrap.stval == utrap.sepc, and that cannot always be correct.

Quoted 28 lines
Quoted 19 lines
Quoted 19 lines
xen/arch/riscv/traps.c +19 -0
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ */
+static int do_mmio(mmio_info_t *info, unsigned long fault_addr,
+                   unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;
+
+    info->gpa = fault_addr;
+    info->len = len;
+
+    switch ( try_handle_mmio(info) )
+    {
+    case IO_HANDLED:
+        return 0;
+    case IO_ABORT:
Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 298

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+        return -EIO;
+    default:
+        return -EOPNOTSUPP;
+    }
+}

And there's no indication of "retry needed", e.g. when something changed between find_mmio_handler() and handle_{read,write}()?

Quoted 5 lines

I don't have any specific scenario where it is needed now so I don't know what to say.
And there is no race between find_mmio_handler() and handle_{read,write}() as find_mmio_handler() returns copy of the structure under read_lock():

Oh, right, but that's not visible here at all and requires going back to patch 04 to realize.

Quoted 49 lines
Quoted 38 lines
Quoted 20 lines
xen/arch/riscv/traps.c +17 -1
  static int emulate_load(unsigned long fault_addr, unsigned long htinst)
  {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    mmio_info_t info = { .is_write = false };
+    unsigned long insn;
+    unsigned int shift = 0, len, insn_len;
+    bool is_unsigned = false;
+    int rc;
+
+    if ( decode_trapped_insn(htinst, &insn, &insn_len) )
+        return 0;
+
+    /* Decode length of MMIO and whether it is a sign- or zero-extending load */
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        len = 1;
+        is_unsigned = true;

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 328

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        len = 2;
+        is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        len = 4;

Already up to here this demonstrates a weakness of the INSN_MASK_* set of #define-s (which I similarly observe in binutils, and I expect it all has the same questionable origin). All INSN_MASK_L* and INSN_MASK_FL* (also INSN_MASK_S* and INSN_MASK_FS*) are identical, allowing for a nice switch() to be used here in principle. That said, with access width nicely encoded in FUNCT3, it's not even clear whether a switch() would end up being needed / efficient.

.......

Quoted 2 lines

Otoh none of these masks cover the pseudoinsns that htinst may supply.

As I answered above we should handle that before this function will call so here we won't deal with htinst at all. Of course, if what I wrote above is correct. I will double check before applying that.

Quoted 1 line
Quoted 4 lines
Quoted 2 lines

Further, what about A-extension insns? Some (if not all) of them can plausibly be used on MMIO, I think.

I’m not really sure that the A-extension is actively used for MMIO.

Does the spec preclude their use? I'm unaware of such a restriction.

Quoted 3 lines

At
least, Linux doesn’t do that for now, which is why we don’t handle A-extension instructions here.

Focusing on what present Linux needs is okay, but then remaining gaps should (as said on various other occasions before) be clearly marked.

Quoted 3 lines

I think this is related to the fact that MMIO is usually (if not always?) naturally aligned, and naturally aligned loads and stores are guaranteed by RISC-V to execute atomically.

How does this matter, when a bit or field in MMIO may serve the purpose of e.g. a semaphore?

Quoted 31 lines
Quoted 22 lines
Quoted 22 lines
xen/arch/riscv/traps.c +22 -0
+    {
+        len = 4;
+        is_unsigned = true;
+    }
+#endif
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        len = 4;
+        insn = RVC_RS2S(insn) << SH_RD;
+    }
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP &&
+              RV_X(insn, SH_RD, 5) )
+        len = 4;
+#ifndef CONFIG_RISCV_32
+    else if ( (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        len = 8;
+    else if ( (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        len = 8;
+        insn = RVC_RS2S(insn) << SH_RD;
+    }
+    else if ( (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 357

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+              RV_X(insn, SH_RD, 5) )
+        len = 8;
+#endif
+    else
+        return -EOPNOTSUPP;

Because you don't permit F/D/Q for guests (yet), FL* and FS* aren't covered, I expect?

Quoted 6 lines

At the moment, I wrote this function with handling of MMIO instruction in mind, which are at the moment ld and sd.

Even if to permit F/D/Q then do we really need to trap that instructions? Hypervisor could allow access to FPU to guest and then it will be just a question of context switch to properly save and restore FPU.

And how would you know FPU loads/stores aren't used against MMIO? Later on, once V support is added, even its loads/stores might be used that way. Think of video frame buffer accesses, for example.

Jan

#126 lore raw

Re: [PATCH v1 16/17] xen/riscv: add guest load emulation for trapped MMIO accesses

Quoted 31 lines · Jan Beulich
Quoted 30 lines · Oleksii Kurochko
Quoted 28 lines · Jan Beulich
Quoted 12 lines · Oleksii Kurochko
xen/arch/riscv/traps.c +8 -0
@@ -210,9 +217,162 @@ static always_inline unsigned long get_faulting_gpa(void)
       return (csr_read(CSR_HTVAL) << 2) | (csr_read(CSR_STVAL) & 0x3);
   }
 
+/*
+ * Determine the trapped instruction which caused a guest MMIO trap.
+ *
+ * Returns true if the trap was redirected to the guest, in which case
+ * the caller must stop emulation and return success. Otherwise *insn
+ * and *insn_len are filled in and the caller should continue decoding.
+ */
+static bool decode_trapped_insn(unsigned long htinst, unsigned long *insn,

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 237

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+                                unsigned int *insn_len)
+{
+    if ( htinst & 0x1 )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         */
+        *insn = htinst | INSN_16BIT_MASK;
+        *insn_len = (htinst & BIT(1, UL)) ? INSN_LEN(*insn) : 2;

In the if() you don't use BIT(), while here you do. Please be consistent.

Why the use of INSN_LEN(), when due to the earlier assignment it'll always yield 4 here?

Quoted 8 lines
Quoted 3 lines

ld/sd instruction which we are trapping here at the moment here could be 2 bit and 4 bit depends on C extension so we need to pass correct instruction length to advance_pc() after it is emulated.

Well, fine, but how does that matter? I pointed you at the preceding assignment, which sets bits 0 and 1. With that INSN_LEN() is guaranteed to return (at least) 4 (and it's not presently capable of returning values larger than 4).

Oh, right. But considering that htinst can handle only max 31 bits so it looks like it can't fit more then 32 bits instructions. But I think it is needed ifdef around INSN_LEN to not miss add support for longer instructions or just write now more generic macros (or static inline function).

Quoted 24 lines
Quoted 24 lines
Quoted 3 lines

Finally, how would the caller know whether it looks at a transformed insn or (as fetched below) a "normal" one?

According to the spec ((part from htinst ... ):
On a synchronous exception, if a nonzero value is written, one of the following shall be true about the value:

• Bit 0 is 1, and replacing bit 1 with 1 makes the value into a valid encoding of a standard instruction.
In this case, the instruction that trapped is the same kind as indicated by the register value, and the register value is the transformation of the trapping instruction, as defined later. For example, if bits 1:0 are binary 11 and the register value is the encoding of a standard LW (load word) instruction, then the trapping instruction is LW, and the register value is the transformation of the trapping LW instruction.

• Bit 0 is 1, and replacing bit 1 with 1 makes the value into an instruction encoding that is explicitly designated for a custom instruction (not an unused reserved encoding). This is a custom value. The instruction that trapped is a non-standard instruction. The interpretation of a custom value is not otherwise specified by this standard.

Quoted 8 lines
Quoted 5 lines

• The value is one of the special pseudoinstructions defined later, all of which have bits 1:0 equal to 00.

So setting bit 0 to 1 we will guarantee that it is normal "normal" instruction.

Right. Yet my question was how to distinguish the cases. Or are you trying to tell me that distinguishing isn't going to be necessary, anywhere?

Yes, I don't see for now why such distinguish is necessary. But I will re-check that point.

Quoted 54 lines
Quoted 54 lines
Quoted 12 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 241

Quoted 5 lines
xen/arch/riscv/traps.c +4 -0
+    }
+    else
+    {
+        struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);

Pointer-to-const.

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 242

Quoted 1 line
xen/arch/riscv/traps.c +1 -0
+        struct trap_info utrap = { 0 };

Just {} please.

Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 247

Quoted 4 lines
xen/arch/riscv/traps.c +4 -0
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value.
+         */

How come you get away without dealing with pseudoinsns? The insn pointed at by regs->sepc is of no interest for faults caused by implicit memory accesses originating from VS-stage address translation.

It is really problem but I think it should be resolved much earlier in handle_guest_page_fault(). I will add the following:

/*
* A guest page fault taken on an implicit memory access performed for
* VS-stage address translation (reading a PTE, or updating its A/D
bits)
* reports a pseudoinstruction in htinst rather than a transformed
* instruction. Such a fault can't be emulated: htval holds the guest
* physical address of a VS-stage PTE rather than of any access the
guest
* itself performed (and its two least significant bits are zero
instead
* of matching stval), while the instruction at sepc is unrelated
to the
* access which actually faulted.
*
* Report an access fault to the guest at the original virtual address,
* which is what stval already holds and what hardware would raise
for a

       * page table walk hitting an inaccessible address.
       */
      if ( (htinst == INSN_PSEUDO_VS_LOAD) || (htinst ==
INSN_PSEUDO_VS_STORE) )
      {
          struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
          struct trap_info utrap = {
              .scause = (htinst == INSN_PSEUDO_VS_LOAD) ? CAUSE_LOAD_ACCESS
                                                        : CAUSE_STORE_ACCESS,
              .sepc = regs->sepc,
              .stval = csr_read(CSR_STVAL),
          };
Quoted 7 lines
Quoted 3 lines
          riscv_trap_redirect(&utrap);
          return;
      }

That's not what would happen on bare hardware though, aiui. At least I don't think I ever found it being spelled out anywhere what the supposed behavior is when a page table resides in unpopulated space.

What do you mean here by "unpopulated space"? IIUC, it means that to have things working we should have GVA -> GPA mapping, if there is no such mapping then correspondent access bits aren't set and so a page-fault exception corresponding to the original access type. So not access fault should be here but just correspondent page fault.

If GPA itself is incorrect (it isn't mapped in G-stage) then it looks to me that access fault should be generated. But in this case I think we won't be here (in handle_guest_page_fault() at all) as just a page fault will be generated (so G-stage fault), not guest page fault (VS-fault what is the case in the code above but as I told in prev paragraph access fault is too much in that case and just page fault will be enough and it looks like it is correspond to hardware behavior).

Quoted 17 lines
Quoted 17 lines
Quoted 16 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void)

Quoted 8 lines
xen/arch/riscv/traps.c +7 -0
+        *insn = riscv_vcpu_unpriv_read(true, regs->sepc, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * A G-stage fault here would mean the P2M mapping of the page
+             * containing the trapped instruction disappeared after it was
+             * fetched.

Does it? What about, again, faults from VS-stage address translation while hardware was trying to fetch an insn? That is ...

Review static always_inline unsigned long get_faulting_gpa(void) · line 255

Quoted 2 lines
(quoted diff) +1 -0
 Nothing removes P2M mappings of a running domain yet,
+             * so this cannot happen.

... the necessary P2M mapping may never have been there.

Quoted 8 lines
Quoted 2 lines

If VS-stage failed then CAUSE_LOAD_PAGE_FAULT will happen so BUG_ON() won't occur and it will be passed to guest to handle it.

Are you sure? So far it was my understanding that CAUSE_LOAD_PAGE_FAULT would happen when VS-stage translation hits e.g. a non-present leaf entry. But got an address translation failure while doing the VS-stage page walk (i.e. failure to translate the address found in a VS-stage PTE to a host address) would raise CAUSE_LOAD_GUEST_PAGE_FAULT.

Sorry, you are right. Then what I suggested before instead of BUG_ON() will be enough:
if ( is_load_guest_page_fault(utrap.scause) )
utrap.scause = CAUSE_FETCH_ACCESS;
as if we don't have mapping in G-stage then it looks like guest is trying to reach something wrong.

Quoted 50 lines
Quoted 6 lines

BUG_ON() here catches CAUSE_LOAD_GUEST_PAGE_FAULT (G-stage translation failure).

Also, as I mentioned above I will change BUG_ON() too:

Quoted 7 lines

/*
* If during getting of trapped instruction a fault happen in
* G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
* generated. Such faults during this operation is
considered as
* bus
*/

What is "bus" here (dym "bug"?), and why is the sentence unfinished?

Quoted 16 lines
Quoted 9 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 262

Quoted 6 lines
xen/arch/riscv/traps.c +6 -0
+             * TODO: Revisit once P2M mappings can be removed at runtime.
+             */
+            BUG_ON(is_load_guest_page_fault(utrap.scause));
+
+            utrap.sepc = regs->sepc;
+            utrap.stval = utrap.sepc;

How do you know the fault was at .sepc? A 32-bit insn crossing a page boundary (implying the C extension is available) may well fault only on its higher half.

According to the spec, if stval is written with a nonzero value when an instruction access-fault or page-fault exception occurs on a system with variable-length instructions, then stval will contain the virtual address of the portion of the instruction that caused the fault, while sepc will point to the beginning of the instruction.

Quoted 3 lines

So here, we are trying to emulate what real hardware will do in this case. In regs->sepc, we have the start of the instruction that we didn't touch. sepc is filled according to the spec in this case.

Right, but utrap.stval is set to the same value, which is explicitly not in line with what you say above ("will contain the virtual address of the portion of the instruction that caused the fault").>

Quoted 11 lines

Regarding utrap.stval, we know that utrap.sepc points to the correct part of the faulting address, as we are reading the instruction in 16-bit chunks:

HLVX_HU(%[val], %[addr]) ; low 16 bits from sepc
andi %[tmp], %[val], 3
addi %[tmp], %[tmp], -3

bne  %[tmp], zero, 2f           ; if not (insn & 3) == 3 -> 16-bit, end
addi %[addr], %[addr], 2        ; <- addr is now sepc+2
HLVX_HU(%[tmp], %[addr])        ; high 16 bits, possibly from another page
Quoted 8 lines
Quoted 5 lines

So, if a trap happens while reading the high 16 bits (which may be located on another page), then utrap.sepc, if the read fails, will point to the high part of the instruction, which is what the spec requires.

Does that make sense?

Not really, no. As said above - the code as written guarantees utrap.stval == utrap.sepc, and that cannot always be correct.

Oh, right, utrap.stval = utrap.sepc; should be just dropped utrap.stval already has a correct value (from ex_handler_trap_info()) which should be passed to guest.

Quoted 29 lines
Quoted 29 lines
Quoted 28 lines
Quoted 15 lines
xen/arch/riscv/traps.c +14 -0
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ */
+static int do_mmio(mmio_info_t *info, unsigned long fault_addr,
+                   unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;
+
+    info->gpa = fault_addr;
+    info->len = len;
+

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 298

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    switch ( try_handle_mmio(info) )
+    {
+    case IO_HANDLED:
+        return 0;
+    case IO_ABORT:
+        return -EIO;
+    default:
+        return -EOPNOTSUPP;
+    }
+}

And there's no indication of "retry needed", e.g. when something changed between find_mmio_handler() and handle_{read,write}()?

Quoted 8 lines
Quoted 5 lines

I don't have any specific scenario where it is needed now so I don't know what to say.
And there is no race between find_mmio_handler() and handle_{read,write}() as find_mmio_handler() returns copy of the structure under read_lock():

Oh, right, but that's not visible here at all and requires going back to patch 04 to realize.

I will update the comment above function:

/*
* Check alignment and dispatch a decoded MMIO access to a registered
* handler. On success (0), info->data holds the read value for loads. *
* There is no "retry" outcome to handle: find_mmio_handler() returns a
* copy of the matching handler taken under vmmio->lock and the ops
* structures are never freed, so the lookup result cannot go stale
* between finding the handler and invoking it.
*/

Quoted 50 lines
Quoted 50 lines
Quoted 39 lines
Quoted 21 lines
xen/arch/riscv/traps.c +17 -1
   static int emulate_load(unsigned long fault_addr, unsigned long htinst)
   {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    mmio_info_t info = { .is_write = false };
+    unsigned long insn;
+    unsigned int shift = 0, len, insn_len;
+    bool is_unsigned = false;
+    int rc;
+
+    if ( decode_trapped_insn(htinst, &insn, &insn_len) )
+        return 0;
+
+    /* Decode length of MMIO and whether it is a sign- or zero-extending load */
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        len = 1;
+        is_unsigned = true;

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 328

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        len = 2;
+        is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        len = 4;

Already up to here this demonstrates a weakness of the INSN_MASK_* set of #define-s (which I similarly observe in binutils, and I expect it all has the same questionable origin). All INSN_MASK_L* and INSN_MASK_FL* (also INSN_MASK_S* and INSN_MASK_FS*) are identical, allowing for a nice switch() to be used here in principle. That said, with access width nicely encoded in FUNCT3, it's not even clear whether a switch() would end up being needed / efficient.

.......

Quoted 2 lines

Otoh none of these masks cover the pseudoinsns that htinst may supply.

As I answered above we should handle that before this function will call so here we won't deal with htinst at all. Of course, if what I wrote above is correct. I will double check before applying that.

Quoted 1 line
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Further, what about A-extension insns? Some (if not all) of them can plausibly be used on MMIO, I think.

I’m not really sure that the A-extension is actively used for MMIO.

Does the spec preclude their use? I'm unaware of such a restriction.

Definitely no. In this case hypervisor will tell that we can't emulate this instruction and then extra handling should be added.

Quoted 8 lines
Quoted 4 lines

At
least, Linux doesn’t do that for now, which is why we don’t handle A-extension instructions here.

Focusing on what present Linux needs is okay, but then remaining gaps should (as said on various other occasions before) be clearly marked.

Quoted 6 lines
Quoted 3 lines

I think this is related to the fact that MMIO is usually (if not always?) naturally aligned, and naturally aligned loads and stores are guaranteed by RISC-V to execute atomically.

How does this matter, when a bit or field in MMIO may serve the purpose of e.g. a semaphore?

Then yes it will be an issue and such instruction should be emulated (when such use cases will come into play)

Quoted 35 lines
Quoted 35 lines
Quoted 23 lines
Quoted 23 lines
xen/arch/riscv/traps.c +22 -0
+    {
+        len = 4;
+        is_unsigned = true;
+    }
+#endif
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        len = 4;
+        insn = RVC_RS2S(insn) << SH_RD;
+    }
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP &&
+              RV_X(insn, SH_RD, 5) )
+        len = 4;
+#ifndef CONFIG_RISCV_32
+    else if ( (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        len = 8;
+    else if ( (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        len = 8;
+        insn = RVC_RS2S(insn) << SH_RD;
+    }
+    else if ( (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
Quoted 8 lines

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 357

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+              RV_X(insn, SH_RD, 5) )
+        len = 8;
+#endif
+    else
+        return -EOPNOTSUPP;

Because you don't permit F/D/Q for guests (yet), FL* and FS* aren't covered, I expect?

At the moment, I wrote this function with handling of MMIO instruction in mind, which are at the moment ld and sd.

Quoted 7 lines
Quoted 3 lines

Even if to permit F/D/Q then do we really need to trap that instructions? Hypervisor could allow access to FPU to guest and then it will be just a question of context switch to properly save and restore FPU.

And how would you know FPU loads/stores aren't used against MMIO? Later on, once V support is added, even its loads/stores might be used that way. Think of video frame buffer accesses, for example.

We will get 'return -EOPNOTSUPP' and so guest will be crashed because we don't support such work with MMIO.
And then yes it should be likely to be added in parallel with adding F/D/Q support for guest. At the moment, KVM supports, for example, F/D/Q but doesn't emulate FPU load/store but I agree that with your example it could happen.

~ Oleksii

#127 lore raw

Re: [PATCH v1 16/17] xen/riscv: add guest load emulation for trapped MMIO accesses

Quoted 50 lines · Oleksii Kurochko
Quoted 49 lines · Jan Beulich
Quoted 47 lines · Oleksii Kurochko
Quoted 9 lines · Jan Beulich

xen/arch/riscv/traps.c static always_inline unsigned long get_faulting_gpa(void) · line 247

Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/traps.c +4 -0
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value.
+         */

How come you get away without dealing with pseudoinsns? The insn pointed at by regs->sepc is of no interest for faults caused by implicit memory accesses originating from VS-stage address translation.

It is really problem but I think it should be resolved much earlier in handle_guest_page_fault(). I will add the following:

/*
* A guest page fault taken on an implicit memory access performed for
* VS-stage address translation (reading a PTE, or updating its A/D
bits)
* reports a pseudoinstruction in htinst rather than a transformed
* instruction. Such a fault can't be emulated: htval holds the guest
* physical address of a VS-stage PTE rather than of any access the
guest
* itself performed (and its two least significant bits are zero
instead
* of matching stval), while the instruction at sepc is unrelated
to the
* access which actually faulted.
*
* Report an access fault to the guest at the original virtual address,
* which is what stval already holds and what hardware would raise
for a

       * page table walk hitting an inaccessible address.
       */
      if ( (htinst == INSN_PSEUDO_VS_LOAD) || (htinst ==
INSN_PSEUDO_VS_STORE) )
      {
          struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
          struct trap_info utrap = {
              .scause = (htinst == INSN_PSEUDO_VS_LOAD) ? CAUSE_LOAD_ACCESS
                                                        : CAUSE_STORE_ACCESS,
              .sepc = regs->sepc,
              .stval = csr_read(CSR_STVAL),
          };

          riscv_trap_redirect(&utrap);
          return;
      }
Quoted 5 lines
Quoted 3 lines

That's not what would happen on bare hardware though, aiui. At least I don't think I ever found it being spelled out anywhere what the supposed behavior is when a page table resides in unpopulated space.

What do you mean here by "unpopulated space"?

A physical address range neither populated by RAM nor used by MMIO of any device.

Jan