Skip to contentSkip to conversation

Random corruption on SpacemiT K1 with RVV and THP

DISCUSSION Aurelien Jarno 7 participants 18 messages Aug 30 – Nov 13 2 messages not in the archive

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

Dear all,

For the last weeks, I have been tracking a random memory corruption and relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

Using glibc 2.44 instead of glibc 2.43, which does a lot of string operations through vector instructions, increases the probability to have corruption, makes it a bit more reproducible, but it always seems to manifest as a GCC ICE. It typically happens withing one hour when running on the 8 cores instead of every 1 or 2 days. From there I have been able to determine the following things:

- Disabling vector instructions (by patching the DTB to remove "v", "zvhf" and "zvtk") fixes the issue

- Disabling THP (by setting /sys/kernel/mm/transparent_hugepage/enabled to never instead of always) also seems to fix the issue. Keeping it enabled with defrag=never or use_zero_page=0 doesn't change anything.

- The issue is reproducible with or without swap enabled.

I have not been able to reproduce the issue on other non RVV boards (Unmatched, VF2) nor on a SpacemiT K3 board.

I am not really sure how to debug that further. I tried a few ways to reproduce the issue with a small C code around the glibc memset code (including triggering unaligned accesses and page faults), but failed to do so. I therefore welcome any idea about the issue or how to debug it further.

Thanks
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#1 lore raw

Re: Random corruption on SpacemiT K1 with RVV

Dear all,

I have done some small progress on that issue. Help is still wanted and would be appreciated.

Quoted 9 lines · Aurelien Jarno

Dear all,

For the last weeks, I have been tracking a random memory corruption and relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

I have been able to rule out OpenSBI from the issue, I have checked there is not trap top OpenSBI when the problem happens.

Quoted 10 lines

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

I have identified that the 0xff comes from the poisoning done for v0 in __riscv_v_vstate_discard(), which should only happen for a syscall. Indeed changing the value to different ones propagates to the above error message.

Furthermore I have found that changing CONFIG_RISCV_ISA_V_PREEMPTIVE doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD changes the number of broken bytes.

Disabling the vectored user code entirely with the following patch seems to prevent the issue (or make it sufficiently rare that I have not encountered it):

arch/riscv/lib/riscv_v_helpers.c +1 -1
@@ -25,7 +25,7 @@ asmlinkage int enter_vector_usercopy(void *dst, void *src, size_t n,
        size_t remain, copied;
 
        /* skip has_vector() check because it has been done by the asm  */
-       if (!may_use_simd())
+       if (!may_use_simd() || true)
                goto fallback;
 
        kernel_vector_begin();

Overall, while the corruption happens randomly, the corruption itself seems to be deterministic, and the data source of the corruption is identified. But I don't understand how those values propagate to user space. It is not clear to me if it is a bug somewhere in the context switching code, or a bug in __asm_vector_usercopy_sum_enabled fixup code, with the values just being the one at the entry of the function. Also I can't completely rule out a CPU bug.

Quoted 6 lines

Using glibc 2.44 instead of glibc 2.43, which does a lot of string operations through vector instructions, increases the probability to have corruption, makes it a bit more reproducible, but it always seems to manifest as a GCC ICE. It typically happens withing one hour when running on the 8 cores instead of every 1 or 2 days. From there I have been able to determine the following things:

I have stopped using glibc 2.44 as a reproducer, and it generate different type of crashes, and there could be another set of bugs on top of the one I am trying to identify. This however means it takes a lot of time to test any change.

Quoted 6 lines

- Disabling vector instructions (by patching the DTB to remove "v", "zvhf" and "zvtk") fixes the issue

- Disabling THP (by setting /sys/kernel/mm/transparent_hugepage/enabled to never instead of always) also seems to fix the issue. Keeping it enabled with defrag=never or use_zero_page=0 doesn't change anything.

I don't think this is a good direction, my impression is that it just changes timing a bit, which just hide the issue, or require different condition to trigger it.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#2 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

[Added Andy and Karl in Cc: as they have been involved in the vectored user copy code and fighting similar issues]

Hi,

Some more progress on that topic.

Quoted 30 lines · Aurelien Jarno

Dear all,

I have done some small progress on that issue. Help is still wanted and would be appreciated.

Quoted 9 lines · Aurelien Jarno

Dear all,

For the last weeks, I have been tracking a random memory corruption and relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

I have been able to rule out OpenSBI from the issue, I have checked there is not trap top OpenSBI when the problem happens.

Quoted 10 lines

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

Quoted 8 lines

I have identified that the 0xff comes from the poisoning done for v0 in __riscv_v_vstate_discard(), which should only happen for a syscall. Indeed changing the value to different ones propagates to the above error message.

Furthermore I have found that changing CONFIG_RISCV_ISA_V_PREEMPTIVE doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD changes the number of broken bytes.

The values from __riscv_v_vstate_discard() end-up there because they are the last values written to the vector registers. I have added some poisoning in __asm_vector_usercopy_sum_enabled before the loop, and those values appear instead. Using different values per vector register, I have found that the corruption comes from a partial load of the vle8.v instruction, while the result of the poisoning and the partial load are then both written by the vse8.v:

loop:
vsetvli iVL, iNum, e8, ELEM_LMUL_SETTING, ta, ma fixup vle8.v vData, (pSrc), 10f
sub iNum, iNum, iVL
add pSrc, pSrc, iVL
fixup vse8.v vData, (pDst), 11f
add pDst, pDst, iVL
bnez iNum, loop

One hypothesis could be that for some reason, an exception (page table fault, irq, ...), the vle8.v instruction is interrupted, and only partially loads the vector register from memory. This stops at a 16-byte boundary (at least on the K1), and the remaining part of the v0-v7 register is left with the previous value (with the original kernel that is the poisoning done in __riscv_v_vstate_discard). In theory when the instruction is interrupted, vstart is set to a non-zero value (for instance 16), and it should get re-executed after the exception. In practice, in some very rare cases, it doesn't happen and the next executed instruction is the following sub.

That said with exceptions and vector context switches, the explanation is likely way more complex. [1] gives a possible different scenario, involving an interrupt or a fault between the vsetvli and vle8.v/vse8.v instructions. However it doesn't fix the issue, neither patch [2] (in that case tested with CONFIG_RISCV_ISA_V_PREEMPTIVE=y).

Quoted 3 lines

Disabling the vectored user code entirely with the following patch seems to prevent the issue (or make it sufficiently rare that I have not encountered it):

A much better way to do that is setting RISCV_ISA_V_UCOPY_THRESHOLD=-1.

I also tried the same kernel on a K3, and it appears to improve stability, getting rid of issues that I attributed to thermal issues. (due to the absence of fan driver, I run the fan as a fixed speed ~4000rpm). The symptoms are however quite different, it's GCC crashes with "The bug is not reproducible, so it is likely a hardware or OS problem.".

Regards
Aurelien

[1] https://lore.kernel.org/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#3 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi,

Some more update, even if the progress is quite low.

Quoted 23 lines · Aurelien Jarno

[Added Andy and Karl in Cc: as they have been involved in the vectored user copy code and fighting similar issues]

Hi,

Some more progress on that topic.

Quoted 15 lines · Aurelien Jarno

Dear all,

I have done some small progress on that issue. Help is still wanted and would be appreciated.

Quoted 9 lines · Aurelien Jarno

Dear all,

For the last weeks, I have been tracking a random memory corruption and relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

I have been able to also reproduce the issue with the vendor OpenSBI. It is also reproducible with linux 7.2.6.

Quoted 31 lines
Quoted 14 lines

I have been able to rule out OpenSBI from the issue, I have checked there is not trap to OpenSBI when the problem happens.

Quoted 10 lines

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

Quoted 8 lines

I have identified that the 0xff comes from the poisoning done for v0 in __riscv_v_vstate_discard(), which should only happen for a syscall. Indeed changing the value to different ones propagates to the above error message.

Furthermore I have found that changing CONFIG_RISCV_ISA_V_PREEMPTIVE doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD changes the number of broken bytes.

The values from __riscv_v_vstate_discard() end-up there because they are the last values written to the vector registers. I have added some poisoning in __asm_vector_usercopy_sum_enabled before the loop, and those values appear instead. Using different values per vector register, I have found that the corruption comes from a partial load of the vle8.v instruction, while the result of the poisoning and the partial load are then both written by the vse8.v:

Quoted 8 lines

loop:
vsetvli iVL, iNum, e8, ELEM_LMUL_SETTING, ta, ma fixup vle8.v vData, (pSrc), 10f
sub iNum, iNum, iVL
add pSrc, pSrc, iVL
fixup vse8.v vData, (pDst), 11f
add pDst, pDst, iVL
bnez iNum, loop

I have instrumented that code, basically adding a function to check the copy afterwards (only using scalar instructions), and report values in case of errors. So far I have been able to catch the issue 4 times that way (including one where I haven't seen any visible consequence on the userland).

This is what I observed:
- The issue always happens for the first bytes of the user copy, which in all cases were supposed to be up to 4096 bytes long.
- On the first iteration of the loop only the first 16 bytes are loaded by the vle8.v instruction but the full 256 bytes are written to the destination by the vse8.v instrution.
- On the second iteration of the loop, the vle8.v causes a trap, which ends up in the 10f fixup. At fixup level, vl=0x100, vlenb=0x20, vstart=0x0 and vtype=0xc3.
- Considering the 2 first iterations of the loop (i.e. 512 bytes), neither the source nor destination addresses cross a page.

All that said, it is what I can *observe*. I have no idea if the first iteration of the loop also goes through fixup or not. Also in addition to precise traps (which definitely happen for the second iteration), IRQ could happen at any moment. I use CONFIG_RISCV_ISA_V_PREEMPTIVE=n for my test, in order to limit the code paths to review, so during that copy preempt is disabled, but IRQ is not.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
maintainer
#4 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Quoted 3 lines · On Tue, 15 Sep 2026 14:14:10 PDT (-0700), [email protected] wrote:

Hi,

Some more update, even if the progress is quite low.

Well, thanks for digging into this.

Quoted 48 lines · Aurelien Jarno
Quoted 16 lines

[Added Andy and Karl in Cc: as they have been involved in the vectored user copy code and fighting similar issues]

Hi,

Some more progress on that topic.

Quoted 9 lines · Aurelien Jarno

Dear all,

I have done some small progress on that issue. Help is still wanted and would be appreciated.

Quoted 4 lines · Aurelien Jarno

Dear all,

For the last weeks, I have been tracking a random memory corruption and
relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

I have been able to also reproduce the issue with the vendor OpenSBI. It is also reproducible with linux 7.2.6.

Quoted 18 lines
Quoted 8 lines

I have been able to rule out OpenSBI from the issue, I have checked there is not trap to OpenSBI when the problem happens.

Quoted 6 lines

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

Quoted 6 lines
Quoted 1 line

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

I have identified that the 0xff comes from the poisoning done for v0 in
__riscv_v_vstate_discard(), which should only happen for a syscall. Indeed changing the value to different ones propagates to the above error message.

Furthermore I have found that changing CONFIG_RISCV_ISA_V_PREEMPTIVE doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD changes the number of broken bytes.

The values from __riscv_v_vstate_discard() end-up there because they are the last values written to the vector registers. I have added some poisoning in __asm_vector_usercopy_sum_enabled before the loop, and those values appear instead. Using different values per vector register, I have found that the corruption comes from a partial load of the vle8.v instruction, while the result of the poisoning and the partial load are then both written by the vse8.v:

Quoted 8 lines

loop:
vsetvli iVL, iNum, e8, ELEM_LMUL_SETTING, ta, ma fixup vle8.v vData, (pSrc), 10f
sub iNum, iNum, iVL
add pSrc, pSrc, iVL
fixup vse8.v vData, (pDst), 11f
add pDst, pDst, iVL
bnez iNum, loop

Quoted 8 lines

I have instrumented that code, basically adding a function to check the copy afterwards (only using scalar instructions), and report values in case of errors. So far I have been able to catch the issue 4 times that way (including one where I haven't seen any visible consequence on the userland).

This is what I observed:
- The issue always happens for the first bytes of the user copy, which in all cases were supposed to be up to 4096 bytes long.
- On the first iteration of the loop only the first 16 bytes are loaded by the vle8.v instruction but the full 256 bytes are written to the destination by the vse8.v instrution.

That sounds like some sort of trap handling issue: something's filling out the first word of the vector, but then not the rest, but then not triggering a restart of the instruction. We talked some on IRC and it sounds like that trap isn't getting into Linux, so it's possible something in M-mode is mangling it -- this is where we start to get into vstart/idempotent instruction territory and that's not well tested by running on QEMU, so it wouldn't be super surprising we're just stumbling into a bug there.

I have a K3 that I've been meaning to play around with, I'm going to go try to see if I can get it running and reproduce this one.

Quoted 14 lines

- On the second iteration of the loop, the vle8.v causes a trap, which ends up in the 10f fixup. At fixup level, vl=0x100, vlenb=0x20, vstart=0x0 and vtype=0xc3.
- Considering the 2 first iterations of the loop (i.e. 512 bytes), neither the source nor destination addresses cross a page.

All that said, it is what I can *observe*. I have no idea if the first iteration of the loop also goes through fixup or not. Also in addition to precise traps (which definitely happen for the second iteration), IRQ could happen at any moment. I use CONFIG_RISCV_ISA_V_PREEMPTIVE=n for my test, in order to limit the code paths to review, so during that copy preempt is disabled, but IRQ is not.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#5 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi Palmer,

Thanks for your answer.

Quoted 87 lines · Palmer Dabbelt
Quoted 3 lines · On Tue, 15 Sep 2026 14:14:10 PDT (-0700), [email protected] wrote:

Hi,

Some more update, even if the progress is quite low.

Well, thanks for digging into this.

Quoted 73 lines · Aurelien Jarno
Quoted 14 lines

[Added Andy and Karl in Cc: as they have been involved in the vectored user copy code and fighting similar issues]

Hi,

Some more progress on that topic.

Quoted 2 lines · Aurelien Jarno

Dear all,

Quoted 1 line

I have done some small progress on that issue. Help is still

wanted and > would be appreciated.

Quoted 3 lines
Quoted 3 lines · Aurelien Jarno

Dear all,

Quoted 1 line
Quoted 1 line

For the last weeks, I have been tracking a random memory

Quoted 8 lines

corruption and

Quoted 1 line
Quoted 1 line

relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V

Jupiter). It > > started upgrading to glibc 2.43, which does memset() through vector > > instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 > > kernel, but I have also been able to reproduce it with a vanilla 7.2.2 > > kernel, using a similar configuration to the Debian kernel. The board > > uses OpenSBI 1.9 and the vendor U-Boot.

I have been able to also reproduce the issue with the vendor OpenSBI. It is also reproducible with linux 7.2.6.

Quoted 30 lines
Quoted 1 line

I have been able to rule out OpenSBI from the issue, I have

checked > there is not trap to OpenSBI when the problem happens.

Quoted 1 line
Quoted 1 line
Quoted 1 line

Typically it manifests itself with the following kind of

error, when > > running g++ from GCC 16 as part of building software
(e.g. OpenJDK, > > Blender, Dolfin, Qt6): > > > > Assembler
messages:

Quoted 3 lines
Quoted 3 lines

{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

Quoted 1 line
Quoted 1 line

The broken chars are 0xff and it seems there are always 240

(but with > > poor statistics). Sometimes it instead causes a GCC ICE instead.

Quoted 1 line
Quoted 1 line

I have identified that the 0xff comes from the poisoning done

for v0 in

Quoted 1 line

__riscv_v_vstate_discard(), which should only happen for a

syscall. > Indeed changing the value to different ones propagates to the above > error message.

Quoted 1 line
Quoted 1 line

Furthermore I have found that changing

CONFIG_RISCV_ISA_V_PREEMPTIVE > doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD > changes the number of broken bytes.

The values from __riscv_v_vstate_discard() end-up there because they are the last values written to the vector registers. I have added some poisoning in __asm_vector_usercopy_sum_enabled before the loop, and those values appear instead. Using different values per vector register, I have found that the corruption comes from a partial load of the vle8.v instruction, while the result of the poisoning and the partial load are
then both written by the vse8.v:

Quoted 8 lines

loop:
vsetvli iVL, iNum, e8, ELEM_LMUL_SETTING, ta, ma fixup vle8.v vData, (pSrc), 10f
sub iNum, iNum, iVL
add pSrc, pSrc, iVL
fixup vse8.v vData, (pDst), 11f
add pDst, pDst, iVL
bnez iNum, loop

I have instrumented that code, basically adding a function to check the copy afterwards (only using scalar instructions), and report values in case of errors. So far I have been able to catch the issue 4 times that way (including one where I haven't seen any visible consequence on the userland).

Quoted 6 lines

This is what I observed:
- The issue always happens for the first bytes of the user copy, which in all cases were supposed to be up to 4096 bytes long.
- On the first iteration of the loop only the first 16 bytes are loaded by the vle8.v instruction but the full 256 bytes are written to the destination by the vse8.v instrution.

Quoted 3 lines

That sounds like some sort of trap handling issue: something's filling out the first word of the vector, but then not the rest, but then not triggering a restart of the instruction. We talked some on IRC and it sounds like that

Yes, it's really looks like the instruction is interrupted but not restarted, instead the following instruction is executed.

Quoted 2 lines

trap isn't getting into Linux, so it's possible something in M-mode is mangling it -- this is where we start to get into vstart/idempotent

If you mean sbi_misaligned_v_ld_emulator() and sbi_misaligned_v_st_emulator(), I have already ruled the mout. They are not called because both userland (glibc 2.43) and kernel (vector user copy) are using e8, so there are no possible alignment issues.

Quoted 2 lines

instruction territory and that's not well tested by running on QEMU, so it wouldn't be super surprising we're just stumbling into a bug there.

I don't think it's a vstart issue. If vstart were wrongly restored to 0, the whole vector would be loaded again, inefficient but correct. If vstart were restored to another wrong value, the end of vector would also be loaded, overriding the values from riscv_v_vstate_discard(). The only vstart case that could explain that is vstart >= vl, but I don't think this is allowed.

Quoted 2 lines

I have a K3 that I've been meaning to play around with, I'm going to go try to see if I can get it running and reproduce this one.

Just to be clear, I only observed corruption in the vectored user copy code on the K1. But the K3 is affected by similar random corruption than the K1 that disappear when disabling the vector unit. I believe that the corruption happens at multiple places, and that by chance on the K1 it can be observed on the vectored user copy.

To reproduce the issue, I use on a Debian installation (or on the
original Bianbu installation) the following commands in a loop:
- sbuild -d sid blender
- sbuild -d sid --build-dep-resolver=aptitude --extra-repository="deb http://deb.debian.org/debian experimental main" --add-depends "libc6 (>= 2.44)" blender

The second command uses glibc 2.44, which uses more vector instructions via ifunc, so it crashes faster. Still it can takes a few hours until it happens. On the K1 it takes on average 5 hours, sometimes it takes up to 18 hours before I can reproduce the issue.

Quoted 6 lines
Quoted 6 lines

- On the second iteration of the loop, the vle8.v causes a trap, which ends up in the 10f fixup. At fixup level, vl=0x100, vlenb=0x20, vstart=0x0 and vtype=0xc3.
- Considering the 2 first iterations of the loop (i.e. 512 bytes), neither the source nor destination addresses cross a page.

Quoted 6 lines
Quoted 6 lines

All that said, it is what I can *observe*. I have no idea if the first iteration of the loop also goes through fixup or not. Also in addition to precise traps (which definitely happen for the second iteration), IRQ could happen at any moment. I use CONFIG_RISCV_ISA_V_PREEMPTIVE=n for my test, in order to limit the code paths to review, so during that copy preempt is disabled, but IRQ is not.

I tried disabling the IRQ around the vectored user copy, but it didn't change anything.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#6 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

In reply to Aurelien Jarno

Hi Aurelien,

Sorry for replying late. I did run a compilation test with vectorized glibc in qemu after seeing this thread shortly, but then focus on something else as it didn't catch any corruption we've seen here.

Quoted 23 lines · Aurelien Jarno

[Added Andy and Karl in Cc: as they have been involved in the vectored user copy code and fighting similar issues]

Hi,

Some more progress on that topic.

Quoted 15 lines · Aurelien Jarno

Dear all,

I have done some small progress on that issue. Help is still wanted and would be appreciated.

Quoted 9 lines · Aurelien Jarno

Dear all,

For the last weeks, I have been tracking a random memory corruption and relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

The KVM fix, which is in 7.3 now, is irrelavant to this bug (see below), because the fix targets preemptible kernel-mode vector, but we can trigger this bug with CONFIG_RISCV_ISA_V_PREEMPTIVE unset. Nontheless, if we want to test on the latest code, feel free to grab the series at
[3] and boot with riscv_novstateopt to preseve the context poisoning behavior.

Quoted 15 lines
Quoted 15 lines

I have been able to rule out OpenSBI from the issue, I have checked there is not trap top OpenSBI when the problem happens.

Quoted 10 lines

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

Quoted 8 lines
Quoted 8 lines

I have identified that the 0xff comes from the poisoning done for v0 in __riscv_v_vstate_discard(), which should only happen for a syscall. Indeed changing the value to different ones propagates to the above error message.

Furthermore I have found that changing CONFIG_RISCV_ISA_V_PREEMPTIVE doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD changes the number of broken bytes.

Turnning off CONFIG_RISCV_ISA_V_PREEMPTIVE makes the ucopy fall back to the scalar copy on a page fault, because faulthandler_disabled() would return true after kernel_vector_begin(). So if we are suspecting a corruption at vector restart, then it is not, there is no restarting of such instruction.

The only possible way to have a restarted vector ld/st here under !CONFIG_RISCV_ISA_V_PREEMPTIVE is then an irq restart. I don't know if you test this code with !CONFIG_RISCV_ISA_V_PREEMPTIVE **and** with irqs_disabled() == true in the user copy code. If we still observed a corruption under this case, then it suggests that the corruption happens even eariler. It is then either the faulting instruction itself, or the corruption happens even eariler.

Quoted 5 lines

The values from __riscv_v_vstate_discard() end-up there because they are the last values written to the vector registers. I have added some poisoning in __asm_vector_usercopy_sum_enabled before the loop, and those values appear instead. Using different values per vector register,

Do you know what is the address of corrupted data? If it always starts at a page boundary (e.g offset 0x00000 for THP) then it suggests a strong correlation with fault handling.

Quoted 44 lines

I have found that the corruption comes from a partial load of the vle8.v instruction, while the result of the poisoning and the partial load are then both written by the vse8.v:

loop:
vsetvli iVL, iNum, e8, ELEM_LMUL_SETTING, ta, ma fixup vle8.v vData, (pSrc), 10f
sub iNum, iNum, iVL
add pSrc, pSrc, iVL
fixup vse8.v vData, (pDst), 11f
add pDst, pDst, iVL
bnez iNum, loop

One hypothesis could be that for some reason, an exception (page table fault, irq, ...), the vle8.v instruction is interrupted, and only partially loads the vector register from memory. This stops at a 16-byte boundary (at least on the K1), and the remaining part of the v0-v7 register is left with the previous value (with the original kernel that is the poisoning done in __riscv_v_vstate_discard). In theory when the instruction is interrupted, vstart is set to a non-zero value (for instance 16), and it should get re-executed after the exception. In practice, in some very rare cases, it doesn't happen and the next executed instruction is the following sub.

That said with exceptions and vector context switches, the explanation is likely way more complex. [1] gives a possible different scenario, involving an interrupt or a fault between the vsetvli and vle8.v/vse8.v instructions. However it doesn't fix the issue, neither patch [2] (in that case tested with CONFIG_RISCV_ISA_V_PREEMPTIVE=y).

Quoted 3 lines

Disabling the vectored user code entirely with the following patch seems to prevent the issue (or make it sufficiently rare that I have not encountered it):

A much better way to do that is setting RISCV_ISA_V_UCOPY_THRESHOLD=-1.

I also tried the same kernel on a K3, and it appears to improve stability, getting rid of issues that I attributed to thermal issues. (due to the absence of fan driver, I run the fan as a fixed speed ~4000rpm). The symptoms are however quite different, it's GCC crashes with "The bug is not reproducible, so it is likely a hardware or OS problem.".

Quoted 6 lines

Regards
Aurelien

[1] https://lore.kernel.org/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

[3] https://lore.kernel.org/all/[email protected]/

Quoted 3 lines
Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#7 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi Andy,

Quoted 5 lines · Andy Chiu

Hi Aurelien,

Sorry for replying late. I did run a compilation test with vectorized glibc in qemu after seeing this thread shortly, but then focus on something else as it didn't catch any corruption we've seen here.

Thanks for your feedback. Note that at this stage I have not been able to reproduce the issue with QEMU. I guess it's very timing dependent, also I am not sure if QEMU simulates partially executed instructions (outside of page faults).

Quoted 25 lines · Aurelien Jarno
Quoted 23 lines

[Added Andy and Karl in Cc: as they have been involved in the vectored user copy code and fighting similar issues]

Hi,

Some more progress on that topic.

Quoted 15 lines · Aurelien Jarno

Dear all,

I have done some small progress on that issue. Help is still wanted and would be appreciated.

Quoted 9 lines · Aurelien Jarno

Dear all,

For the last weeks, I have been tracking a random memory corruption and relatively rare on SpacemiT K1 (Banana Pi F3 and Milk-V Jupiter). It started upgrading to glibc 2.43, which does memset() through vector instructions. It is reproducible using the Debian 7.1.7-1~bpo13+1 kernel, but I have also been able to reproduce it with a vanilla 7.2.2 kernel, using a similar configuration to the Debian kernel. The board uses OpenSBI 1.9 and the vendor U-Boot.

Quoted 6 lines

The KVM fix, which is in 7.3 now, is irrelavant to this bug (see below), because the fix targets preemptible kernel-mode vector, but we can trigger this bug with CONFIG_RISCV_ISA_V_PREEMPTIVE unset. Nontheless, if we want to test on the latest code, feel free to grab the series at
[3] and boot with riscv_novstateopt to preseve the context poisoning behavior.

Thanks, I'll try that.

Quoted 30 lines
Quoted 15 lines
Quoted 15 lines

I have been able to rule out OpenSBI from the issue, I have checked there is not trap top OpenSBI when the problem happens.

Quoted 10 lines

Typically it manifests itself with the following kind of error, when running g++ from GCC 16 as part of building software (e.g. OpenJDK, Blender, Dolfin, Qt6):

Assembler messages:
{standard input}:284588: Error: unknown pseudo-op: `.uleb1'
{standard input}:284588: Error: unrecognized opcode `ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿvl874'

The broken chars are 0xff and it seems there are always 240 (but with poor statistics). Sometimes it instead causes a GCC ICE instead.

Quoted 8 lines
Quoted 8 lines

I have identified that the 0xff comes from the poisoning done for v0 in __riscv_v_vstate_discard(), which should only happen for a syscall. Indeed changing the value to different ones propagates to the above error message.

Furthermore I have found that changing CONFIG_RISCV_ISA_V_PREEMPTIVE doesn't change anything, and that changing RISCV_ISA_V_UCOPY_THRESHOLD changes the number of broken bytes.

Turnning off CONFIG_RISCV_ISA_V_PREEMPTIVE makes the ucopy fall back to the scalar copy on a page fault, because faulthandler_disabled() would return true after kernel_vector_begin(). So if we are suspecting a corruption at vector restart, then it is not, there is no restarting of such instruction.

Quoted 7 lines

The only possible way to have a restarted vector ld/st here under !CONFIG_RISCV_ISA_V_PREEMPTIVE is then an irq restart. I don't know if you test this code with !CONFIG_RISCV_ISA_V_PREEMPTIVE **and** with irqs_disabled() == true in the user copy code. If we still observed a corruption under this case, then it suggests that the corruption happens even eariler. It is then either the faulting instruction itself, or the corruption happens even eariler.

I have already tried with both CONFIG_RISCV_ISA_V_PREEMPTIVE=n and wrapping the vectored user copy call in between local_irq_save(flags) and local_irq_restore(flags). The problem is still reproducible.

I have also tried to instrument the vectored user copy code by saving the insret crs before and after the vle8.v instruction to detect a possible interrupted instruction (as suggested on IRC), but adding this code seems to have "fixed" the issue.

Quoted 8 lines
Quoted 4 lines

The values from __riscv_v_vstate_discard() end-up there because they are the last values written to the vector registers. I have added some poisoning in __asm_vector_usercopy_sum_enabled before the loop, and those values appear instead. Using different values per vector register,

Do you know what is the address of corrupted data? If it always starts at a page boundary (e.g offset 0x00000 for THP) then it suggests a strong correlation with fault handling.

On the K1, for the few cases I captured, none of them involved 4k page crossing on either source or destination. The only invariant I have found is that for some reason the first iteration of the loop only loads 16 bytes, and write 256 bytes. The second iteration of the loop then goes to the load fixup and exits.

On the K3, I have never observed a corruption at the vector user copy, but I still observed rare memory corruptions causing gcc to crash, and which disappeared when disabling vector instructions at the device tree level, like on the K1. But that could be two different issues linked to vector instructions.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#8 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Quoted 5 lines · Aurelien Jarno

Thanks for your feedback. Note that at this stage I have not been able to reproduce the issue with QEMU. I guess it's very timing dependent, also I am not sure if QEMU simulates partially executed instructions (outside of page faults).

Hello Aurelien, Andy,

I tested this with a local TCG diagnostic change. It did not reproduce the K1 failure, but it answers the partial-instruction question.

My LLM agent helped me running these tests.

In stock TCG at 7074591d7954, vle8.v can leave partial state on a memory fault, but the vector helper runs atomically with respect to guest interrupts [1,2]. Stock QEMU therefore cannot take an asynchronous interrupt partway through this load.

In a bare-metal test at VLEN=256 and LMUL=8, a page fault after element 16 left vstart=16 and a snapshot containing 16 source bytes followed by 240 poison bytes. After the missing page was mapped, QEMU resumed the load and completed the copy correctly.

I then added a hook to QEMU vector-load which performs 16 elements, sets vstart=16, raises a timer interrupt, and resumes at the same vle8.v. The bare-metal test completed 262,145 such restarts and 67,108,864 copied bytes without a mismatch.

I also booted Linux 388b607d107c with:

CONFIG_RISCV_ISA_V=y
CONFIG_RISCV_ISA_V_UCOPY_THRESHOLD=1
CONFIG_RISCV_ISA_V_PREEMPTIVE=n

With the hook restricted to S-mode loads with SUM and SIE set, a checked pipe test completed 90,308,608 bytes across copy_from_user() and copy_to_user(), including demand-faulting source and destination pages. The hook logged at least 327,680 forced interruptions at vstart=16, without a byte mismatch.

As a negative control, I made one load read 16 elements and then retire as if all 256 had completed. That produced the 16-source/240-poison signature in bare metal, and the Linux checker reported exactly 240 differing bytes. This is an injected symptom, but confirms that the test detects the reported failure shape.

Correct QEMU fault recovery and forced interrupt restart therefore did not produce the corruption. Reaching the 16/240 result required deliberately modelling a load that completed early without a trap. That fits the observed first load/store pair, but does not establish its cause. Your IRQ-disabled result also makes a normal asynchronous restart a poor fit.

The normal Linux load-fault path exits before vse8.v and falls back to the scalar copy [3,4]. Do you have the original trap PC, cause and fault address for the second-iteration fault? Those values could show whether an unexpected synchronous trap is involved.

Thanks,
Karl

[1] https://gitlab.com/qemu-project/qemu/-/blob/7074591d7954876951f84c15b994a43251d5a3c1/target/riscv/tcg/vector_helper.c#L403
[2] https://gitlab.com/qemu-project/qemu/-/blob/7074591d7954876951f84c15b994a43251d5a3c1/accel/tcg/cpu-exec.c#L930
[3] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/riscv/lib/uaccess_vector.S?h=v7.2#n38
[4] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/riscv/lib/riscv_v_helpers.c?h=v7.2#n23

#9 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi Karl,

Quoted 47 lines · Karl Mehltretter
Quoted 5 lines · Aurelien Jarno

Thanks for your feedback. Note that at this stage I have not been able to reproduce the issue with QEMU. I guess it's very timing dependent, also I am not sure if QEMU simulates partially executed instructions (outside of page faults).

Hello Aurelien, Andy,

I tested this with a local TCG diagnostic change. It did not reproduce the K1 failure, but it answers the partial-instruction question.

My LLM agent helped me running these tests.

In stock TCG at 7074591d7954, vle8.v can leave partial state on a memory fault, but the vector helper runs atomically with respect to guest interrupts [1,2]. Stock QEMU therefore cannot take an asynchronous interrupt partway through this load.

In a bare-metal test at VLEN=256 and LMUL=8, a page fault after element 16 left vstart=16 and a snapshot containing 16 source bytes followed by 240 poison bytes. After the missing page was mapped, QEMU resumed the load and completed the copy correctly.

I then added a hook to QEMU vector-load which performs 16 elements, sets vstart=16, raises a timer interrupt, and resumes at the same vle8.v. The bare-metal test completed 262,145 such restarts and 67,108,864 copied bytes without a mismatch.

I also booted Linux 388b607d107c with:

CONFIG_RISCV_ISA_V=y
CONFIG_RISCV_ISA_V_UCOPY_THRESHOLD=1
CONFIG_RISCV_ISA_V_PREEMPTIVE=n

With the hook restricted to S-mode loads with SUM and SIE set, a checked pipe test completed 90,308,608 bytes across copy_from_user() and copy_to_user(), including demand-faulting source and destination pages. The hook logged at least 327,680 forced interruptions at vstart=16, without a byte mismatch.

As a negative control, I made one load read 16 elements and then retire as if all 256 had completed. That produced the 16-source/240-poison signature in bare metal, and the Linux checker reported exactly 240 differing bytes. This is an injected symptom, but confirms that the test detects the reported failure shape.

Quoted 6 lines

Correct QEMU fault recovery and forced interrupt restart therefore did not produce the corruption. Reaching the 16/240 result required deliberately modelling a load that completed early without a trap. That fits the observed first load/store pair, but does not establish its cause. Your IRQ-disabled result also makes a normal asynchronous restart a poor fit.

Thanks for all those extensive tests.

Quoted 4 lines

The normal Linux load-fault path exits before vse8.v and falls back to the scalar copy [3,4]. Do you have the original trap PC, cause and fault address for the second-iteration fault? Those values could show whether an unexpected synchronous trap is involved.

Unfortunately the issue is quite rare, so I have not found a way to trace all that information when the issue happens.

That said Han Gao pointed me to this patch:
https://lore.kernel.org/linux-riscv/20260807-vector_fpu_regs_status_rmw_fix-v1-1-0c16848b60db@intel.com/

I have been testing it, and so far it seems to fix my issue with both CONFIG_RISCV_ISA_V_PREEMPTIVE enable and disabled. Or maybe it just hides the issue by changing the timing, as at this point, I haven't fully understood how the bug fixed by this patch can completely explain my observations.

I still observe a few GCC crashes, on both the K3, but more rarely, but without this corruption pattern, just as non reproducible ICE in GCC. It is likely a different issue.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#10 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi,

Quoted 67 lines · Aurelien Jarno

Hi Karl,

Quoted 47 lines · Karl Mehltretter
Quoted 5 lines · Aurelien Jarno

Thanks for your feedback. Note that at this stage I have not been able to reproduce the issue with QEMU. I guess it's very timing dependent, also I am not sure if QEMU simulates partially executed instructions (outside of page faults).

Hello Aurelien, Andy,

I tested this with a local TCG diagnostic change. It did not reproduce the K1 failure, but it answers the partial-instruction question.

My LLM agent helped me running these tests.

In stock TCG at 7074591d7954, vle8.v can leave partial state on a memory fault, but the vector helper runs atomically with respect to guest interrupts [1,2]. Stock QEMU therefore cannot take an asynchronous interrupt partway through this load.

In a bare-metal test at VLEN=256 and LMUL=8, a page fault after element 16 left vstart=16 and a snapshot containing 16 source bytes followed by 240 poison bytes. After the missing page was mapped, QEMU resumed the load and completed the copy correctly.

I then added a hook to QEMU vector-load which performs 16 elements, sets vstart=16, raises a timer interrupt, and resumes at the same vle8.v. The bare-metal test completed 262,145 such restarts and 67,108,864 copied bytes without a mismatch.

I also booted Linux 388b607d107c with:

CONFIG_RISCV_ISA_V=y
CONFIG_RISCV_ISA_V_UCOPY_THRESHOLD=1
CONFIG_RISCV_ISA_V_PREEMPTIVE=n

With the hook restricted to S-mode loads with SUM and SIE set, a checked pipe test completed 90,308,608 bytes across copy_from_user() and copy_to_user(), including demand-faulting source and destination pages. The hook logged at least 327,680 forced interruptions at vstart=16, without a byte mismatch.

As a negative control, I made one load read 16 elements and then retire as if all 256 had completed. That produced the 16-source/240-poison signature in bare metal, and the Linux checker reported exactly 240 differing bytes. This is an injected symptom, but confirms that the test detects the reported failure shape.

Quoted 6 lines

Correct QEMU fault recovery and forced interrupt restart therefore did not produce the corruption. Reaching the 16/240 result required deliberately modelling a load that completed early without a trap. That fits the observed first load/store pair, but does not establish its cause. Your IRQ-disabled result also makes a normal asynchronous restart a poor fit.

Thanks for all those extensive tests.

Quoted 4 lines

The normal Linux load-fault path exits before vse8.v and falls back to the scalar copy [3,4]. Do you have the original trap PC, cause and fault address for the second-iteration fault? Those values could show whether an unexpected synchronous trap is involved.

Unfortunately the issue is quite rare, so I have not found a way to trace all that information when the issue happens.

Quoted 8 lines

That said Han Gao pointed me to this patch:
https://lore.kernel.org/linux-riscv/20260807-vector_fpu_regs_status_rmw_fix-v1-1-0c16848b60db@intel.com/

I have been testing it, and so far it seems to fix my issue with both CONFIG_RISCV_ISA_V_PREEMPTIVE enable and disabled. Or maybe it just hides the issue by changing the timing, as at this point, I haven't fully understood how the bug fixed by this patch can completely explain my observations.

Unfortunately, I have been able to reproduce the issue, even with this patch applied. It just significantly reduces the frequency of the issue.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#11 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Quoted 6 lines · Aurelien Jarno

Hi,

On 2026-09-25 06:40, Aurelien Jarno wrote:

[...]

Quoted 8 lines

That said Han Gao pointed me to this patch:
https://lore.kernel.org/linux-riscv/20260807-vector_fpu_regs_status_rmw_fix-v1-1-0c16848b60db@intel.com/

I have been testing it, and so far it seems to fix my issue with both CONFIG_RISCV_ISA_V_PREEMPTIVE enable and disabled. Or maybe it just hides the issue by changing the timing, as at this point, I haven't fully understood how the bug fixed by this patch can completely explain my observations.

I don't know how that would cause what you have observed either, but it does superficially appears to fix a real bug.

Quoted 3 lines

Unfortunately, I have been able to reproduce the issue, even with this patch applied. It just significantly reduces the frequency of the issue.

But this, I suppose, is still useful information that we just *might* be on the right track.

Can you perhaps try this hacked together patch below and see if it does anything? I just put guard(preempt)() or something around a bunch of places I could find that access regs->status. It should apply to 7.1 and 7.2 as is. (The coding style is deliberately horrible to minimize diff lines and discourage others from shipping it)

(This adds some more widely-scoped guards, and AFAICT /replaces/ the above linked patch from Guobin Zhang.)

vvv DO NOT USE EXCEPT FOR TESTING vvv

arch/riscv/include/asm/switch_to.h +4 -0
index 04f10a949066..6486f9fe0ac5 100644
@@ -6,6 +6,7 @@
 #ifndef _ASM_RISCV_SWITCH_TO_H
 #define _ASM_RISCV_SWITCH_TO_H
 
+#include <linux/cleanup.h>
 #include <linux/jump_label.h>
 #include <linux/sched/task_stack.h>
 #include <linux/mm_types.h>
@@ -28,12 +29,14 @@ static inline void __fstate_clean(struct pt_regs *regs)
 static inline void fstate_off(struct task_struct *task,
 			      struct pt_regs *regs)
 {
+	guard(preempt)();
 	regs->status = (regs->status & ~SR_FS) | SR_FS_OFF;
 }
 
 static inline void fstate_save(struct task_struct *task,
 			       struct pt_regs *regs)
 {
+	guard(preempt)();
 	if ((regs->status & SR_FS) == SR_FS_DIRTY) {
 		__fstate_save(task);
 		__fstate_clean(regs);
@@ -43,6 +46,7 @@ static inline void fstate_save(struct task_struct *task,
 static inline void fstate_restore(struct task_struct *task,
 				  struct pt_regs *regs)
 {
+	guard(preempt)();
 	if ((regs->status & SR_FS) != SR_FS_OFF) {
 		__fstate_restore(task);
 		__fstate_clean(regs);
arch/riscv/include/asm/vector.h +6 -0
index fffe72a77208..30fc51713542 100644
@@ -97,11 +97,13 @@ static inline void __riscv_v_vstate_dirty(struct pt_regs *regs)
 
 static inline void riscv_v_vstate_off(struct pt_regs *regs)
 {
+	guard(preempt)();
 	regs->status = __riscv_v_vstate_or(regs->status, OFF);
 }
 
 static inline void riscv_v_vstate_on(struct pt_regs *regs)
 {
+	guard(preempt)();
 	regs->status = __riscv_v_vstate_or(regs->status, INITIAL);
 }
 
@@ -302,6 +304,7 @@ static inline void __riscv_v_vstate_discard(void)
 
 static inline void riscv_v_vstate_discard(struct pt_regs *regs)
 {
+	guard(preempt)();
 	if (riscv_v_vstate_query(regs)) {
 		__riscv_v_vstate_discard();
 		__riscv_v_vstate_dirty(regs);
@@ -311,6 +314,7 @@ static inline void riscv_v_vstate_discard(struct pt_regs *regs)
 static inline void riscv_v_vstate_save(struct __riscv_v_ext_state *vstate,
 				       struct pt_regs *regs)
 {
+	guard(preempt)();
 	if (__riscv_v_vstate_check(regs->status, DIRTY)) {
 		__riscv_v_vstate_save(vstate, vstate->datap);
 		__riscv_v_vstate_clean(regs);
@@ -320,6 +324,7 @@ static inline void riscv_v_vstate_save(struct __riscv_v_ext_state *vstate,
 static inline void riscv_v_vstate_restore(struct __riscv_v_ext_state *vstate,
 					  struct pt_regs *regs)
 {
+	guard(preempt)();
 	if (riscv_v_vstate_query(regs)) {
 		__riscv_v_vstate_restore(vstate, vstate->datap);
 		__riscv_v_vstate_clean(regs);
@@ -329,6 +334,7 @@ static inline void riscv_v_vstate_restore(struct __riscv_v_ext_state *vstate,
 static inline void riscv_v_vstate_set_restore(struct task_struct *task,
 					      struct pt_regs *regs)
 {
+	guard(preempt)();
 	if (riscv_v_vstate_query(regs)) {
 		set_tsk_thread_flag(task, TIF_RISCV_V_DEFER_RESTORE);
 		riscv_v_vstate_on(regs);
arch/riscv/kernel/process.c +1 -0
index b2df7f72241a..45963c7baebe 100644
@@ -144,6 +144,7 @@ early_initcall(compat_mode_detect);
 void start_thread(struct pt_regs *regs, unsigned long pc,
 	unsigned long sp)
 {
+	guard(preempt)();
 	regs->status = SR_PIE;
 	if (has_fpu()) {
 		regs->status |= SR_FS_INITIAL;
arch/riscv/kernel/signal.c +3 -0
index 59784dc117e4..623cc35d567c 100644
@@ -6,6 +6,7 @@
  * Copyright (C) 2012 Regents of the University of California
  */
 
+#include <linux/cleanup.h>
 #include <linux/compat.h>
 #include <linux/signal.h>
 #include <linux/uaccess.h>
@@ -76,6 +77,7 @@ static long save_v_state(struct pt_regs *regs, void __user *sc_vec)
 	void __user *datap;
 	long err;
 
+	scoped_guard(preempt)
 	if (!IS_ENABLED(CONFIG_RISCV_ISA_V) ||
 	    !((has_vector() || has_xtheadvector()) &&
 	    riscv_v_vstate_query(regs)))
@@ -287,6 +289,7 @@ static size_t get_rt_frame_size(bool cal_all)
 	frame_size = sizeof(*frame);
 
 	if (has_vector() || has_xtheadvector()) {
+		scoped_guard(preempt)
 		if (cal_all || riscv_v_vstate_query(task_pt_regs(current)))
 			total_context_size += riscv_v_sc_size;
 	}
arch/riscv/kernel/vector.c +2 -0
index b112166d51e9..27078b70b65b 100644
@@ -3,6 +3,7 @@
  * Copyright (C) 2023 SiFive
  * Author: Andy Chiu <[email protected]>
  */
+#include <linux/cleanup.h>
 #include <linux/export.h>
 #include <linux/sched/signal.h>
 #include <linux/types.h>
@@ -194,6 +195,7 @@ bool riscv_v_first_use_handler(struct pt_regs *regs)
 	if (!riscv_v_vstate_ctrl_user_allowed())
 		return false;
 
+	scoped_guard(preempt)
 	/* If V has been enabled then it is not the first-use trap */
 	if (riscv_v_vstate_query(regs))
 		return false;

^^^ DO NOT USE EXCEPT FOR TESTING ^^^

#12 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi,

Some small update on that. Sorry it takes time, it's just the bug happens sporadically and I need a lot of testing to reach some conclusion (and when I can't reproduce the bug, I am still not sure it is not there).

Quoted 25 lines · Vivian Wang
Quoted 6 lines · Aurelien Jarno

Hi,

On 2026-09-25 06:40, Aurelien Jarno wrote:

[...]

Quoted 8 lines

That said Han Gao pointed me to this patch:
https://lore.kernel.org/linux-riscv/20260807-vector_fpu_regs_status_rmw_fix-v1-1-0c16848b60db@intel.com/

I have been testing it, and so far it seems to fix my issue with both CONFIG_RISCV_ISA_V_PREEMPTIVE enable and disabled. Or maybe it just hides the issue by changing the timing, as at this point, I haven't fully understood how the bug fixed by this patch can completely explain my observations.

I don't know how that would cause what you have observed either, but it does superficially appears to fix a real bug.

Quoted 3 lines

Unfortunately, I have been able to reproduce the issue, even with this patch applied. It just significantly reduces the frequency of the issue.

But this, I suppose, is still useful information that we just *might* be on the right track.

Quoted 8 lines

Can you perhaps try this hacked together patch below and see if it does anything? I just put guard(preempt)() or something around a bunch of places I could find that access regs->status. It should apply to 7.1 and 7.2 as is. (The coding style is deliberately horrible to minimize diff lines and discourage others from shipping it)

(This adds some more widely-scoped guards, and AFAICT /replaces/ the above linked patch from Guobin Zhang.)

Unfortunately that doesn't fix the problem. I am still able to reproduce it with this patch :(

I also have tried with a 7.3 kernel, and I am still able to reproduce the issue on both the K1 (the above usercopy issue or the not reproducible GCC ICE) and the K3 (only not reproducible GCC ICE).

Disabling vector extension in the device tree fixes the issue in both cases. However the LLVM JIT doesn't care if it is enabled or not, it just matches by mvendorid / marchid / mimpid so you just get a SIGILL.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#13 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi,

I have finally been able to capture the last few exceptions happening for one event where the vectored user copy code is corrupting data. That was on the SpacemiT K1.

I added a hook to handle_exception(), activated only when __asm_vector_usercopy_sum_enabled is running, and recording CPU state at the beginning of the exception, in per-CPU 16-entry tables. On the OpenSBI side, I also instrumented sbi_trap_handler() to log the CAUSE_MISALIGNED_LOAD and CAUSE_LOAD_ACCESS cases. This only fires during the kernel boot when it tries to measure speed of unaligned accesses.

The case I captured was a 4096-byte long copy, from 0x2a883310 (userland) to 0xffffffd701e54000 (kernel), presumably from a write syscall. The copy is considered successful, i.e it exits with a0=0. That said after the copy, the source and the destination start to differ after the first 16 bytes, at address 0xffffffd701e54010.

The copy started on CPU 5 and ended on CPU 5, and there was only a single exception between the start and the end, so it wasn't rescheduled.

The exception happened with epc=0xffffffff80e09204, which corresponds to the location of the "vle8.v v0,(a1)" instruction. I recorded:
- cause=0xd
- badaddr=0x2a883410
- a0=0xffffffd701e54100
- a1=0x2a883410
- a2=0xf00
- vl=0x100
- vstart=0x0
- vtype=0xc3

As you can see, the exception happened during the second iteration of the loop. It is not clear to me why the first iteration didn't trigger a page fault, as both 0x2a883310 and 0x2a883410 are on the same 4k page. I have also logged the content of v0 at the time of the exception, and I can clearly see that only the first 16 bytes (out of 32 bytes) got loaded during the previous iteration. Its content matches the error reported by GNU as on the userland side.

Then the remaining of the loop continued without exception to copy 4096 bytes in total.

At this stage, I do not have any other explanation than a CPU bug. That said, I have noticed that the problem started when userland started to use the vector extension, and with the above, I do not have any explanation for the link between the two. I'll try to capture another corruption event (it takes ages) to see if it can help refine the explanation.

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
#14 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi, Aurelien,

Thank you for your continued efforts.

Quoted 35 lines · Aurelien Jarno

Hi,

I have finally been able to capture the last few exceptions happening for one event where the vectored user copy code is corrupting data. That was on the SpacemiT K1.

I added a hook to handle_exception(), activated only when __asm_vector_usercopy_sum_enabled is running, and recording CPU state at the beginning of the exception, in per-CPU 16-entry tables. On the OpenSBI side, I also instrumented sbi_trap_handler() to log the CAUSE_MISALIGNED_LOAD and CAUSE_LOAD_ACCESS cases. This only fires during the kernel boot when it tries to measure speed of unaligned accesses.

The case I captured was a 4096-byte long copy, from 0x2a883310 (userland) to 0xffffffd701e54000 (kernel), presumably from a write syscall. The copy is considered successful, i.e it exits with a0=0. That said after the copy, the source and the destination start to differ after the first 16 bytes, at address 0xffffffd701e54010.

The copy started on CPU 5 and ended on CPU 5, and there was only a single exception between the start and the end, so it wasn't rescheduled.

The exception happened with epc=0xffffffff80e09204, which corresponds to the location of the "vle8.v v0,(a1)" instruction. I recorded:
- cause=0xd
- badaddr=0x2a883410
- a0=0xffffffd701e54100
- a1=0x2a883410
- a2=0xf00
- vl=0x100
- vstart=0x0
- vtype=0xc3

Quoted 7 lines

As you can see, the exception happened during the second iteration of the loop. It is not clear to me why the first iteration didn't trigger a page fault, as both 0x2a883310 and 0x2a883410 are on the same 4k page. I have also logged the content of v0 at the time of the exception, and I can clearly see that only the first 16 bytes (out of 32 bytes) got loaded during the previous iteration. Its content matches the error reported by GNU as on the userland side.

From the information you provided, the issue does indeed seem quite strange. Could you please share your debug patch with me? I'll try to further locate and analyze the issue on my side.

Quoted 11 lines

Then the remaining of the loop continued without exception to copy 4096 bytes in total.

At this stage, I do not have any other explanation than a CPU bug. That said, I have noticed that the problem started when userland started to use the vector extension, and with the above, I do not have any explanation for the link between the two. I'll try to capture another corruption event (it takes ages) to see if it can help refine the explanation.

Quoted 3 lines

Regards
Aurelien

Best Regards,
kevin.z.m

#15 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

Hi Kevin,

Quoted 47 lines · kevin zhang

Hi, Aurelien,

Thank you for your continued efforts.

Quoted 35 lines · Aurelien Jarno

Hi,

I have finally been able to capture the last few exceptions happening for one event where the vectored user copy code is corrupting data. That was on the SpacemiT K1.

I added a hook to handle_exception(), activated only when __asm_vector_usercopy_sum_enabled is running, and recording CPU state at the beginning of the exception, in per-CPU 16-entry tables. On the OpenSBI side, I also instrumented sbi_trap_handler() to log the CAUSE_MISALIGNED_LOAD and CAUSE_LOAD_ACCESS cases. This only fires during the kernel boot when it tries to measure speed of unaligned accesses.

The case I captured was a 4096-byte long copy, from 0x2a883310 (userland) to 0xffffffd701e54000 (kernel), presumably from a write syscall. The copy is considered successful, i.e it exits with a0=0. That said after the copy, the source and the destination start to differ after the first 16 bytes, at address 0xffffffd701e54010.

The copy started on CPU 5 and ended on CPU 5, and there was only a single exception between the start and the end, so it wasn't rescheduled.

The exception happened with epc=0xffffffff80e09204, which corresponds to the location of the "vle8.v v0,(a1)" instruction. I recorded:
- cause=0xd
- badaddr=0x2a883410
- a0=0xffffffd701e54100
- a1=0x2a883410
- a2=0xf00
- vl=0x100
- vstart=0x0
- vtype=0xc3

Quoted 7 lines

As you can see, the exception happened during the second iteration of the loop. It is not clear to me why the first iteration didn't trigger a page fault, as both 0x2a883310 and 0x2a883410 are on the same 4k page. I have also logged the content of v0 at the time of the exception, and I can clearly see that only the first 16 bytes (out of 32 bytes) got loaded during the previous iteration. Its content matches the error reported by GNU as on the userland side.

Quoted 3 lines

From the information you provided, the issue does indeed seem quite strange. Could you please share your debug patch with me? I'll try to further locate and analyze the issue on my side.

Please find attached the patch used on top of v7.3. It is not very clean as it was only done for debug purpose and grew organically. I have also attached the kernel config I used, based on the Debian one (hence the many modules that are useless for the K1).

With the patch, the issue is happening way more rarely, it took me more than one week building blender in a loop to get a failure. During that time I also caught 2 failures not linked to the usercopy code, but still causing GCC to fail in a similar way than on the K3, and as the Fedora guys also experience:

https://forge.fedoraproject.org/riscv/planning/issues/36

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
arch/riscv/include/asm/trap_trace.h new file +12 -0
new file mode 100644
index 0000000000000..a7a3d5824ea34
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _ASM_RISCV_TRAP_TRACE_H
+#define _ASM_RISCV_TRAP_TRACE_H
+
+struct pt_regs;
+
+void riscv_trap_trace(struct pt_regs *regs);
+void riscv_trap_trace_dump_cpu(unsigned int cpu);
+void riscv_trap_trace_enable(void);
+void riscv_trap_trace_disable(void);
+
+#endif
arch/riscv/kernel/Makefile +1 -0
index ebe1c3588177b..e00e452cd345c 100644
@@ -72,6 +72,7 @@ obj-y	+= vendor_extensions.o
 obj-y	+= vendor_extensions/
 obj-y	+= probes/
 obj-y	+= tests/
+obj-y	+= trap_trace.o
 obj-$(CONFIG_MMU) += vdso.o vdso/
 obj-$(CONFIG_RISCV_USER_CFI) += vdso_cfi/
 
arch/riscv/kernel/entry.S +3 -0
index 61b7a77166971..bb923f421da76 100644
@@ -210,6 +210,9 @@ SYM_CODE_START(handle_exception)
 	/* Load the kernel shadow call stack pointer if coming from userspace */
 	scs_load_current_if_from_user s1, s5
 
+	move a0, sp
+	call riscv_trap_trace
+
 #ifdef CONFIG_RISCV_ISA_V_PREEMPTIVE
 	move a0, sp
 	call riscv_v_context_nesting_start
arch/riscv/kernel/trap_trace.c new file +142 -0

142 lines not on this page · raw message

arch/riscv/lib/riscv_v_helpers.c +27 -5
index 7bbdfc6d4552d..585c6d59908ff 100644
@@ -13,26 +13,48 @@
 #include <asm/asm-prototypes.h>
 #endif
 
+#include <asm/trap_trace.h>
+
 #ifdef CONFIG_MMU
 size_t riscv_v_usercopy_threshold = CONFIG_RISCV_ISA_V_UCOPY_THRESHOLD;
-int __asm_vector_usercopy(void *dst, void *src, size_t n);
-int __asm_vector_usercopy_sum_enabled(void *dst, void *src, size_t n);
+int __asm_vector_usercopy(void *dst, void *src, size_t n, uint64_t *dbg);
+int __asm_vector_usercopy_sum_enabled(void *dst, void *src, size_t n, uint64_t *dbg);
+int __asm_usercopy_check(void *dst, void *src, size_t n);
+int __asm_usercopy_check_sum_enabled(void *dst, void *src, size_t n);
 int fallback_scalar_usercopy(void *dst, void *src, size_t n);
 int fallback_scalar_usercopy_sum_enabled(void *dst, void *src, size_t n);
 asmlinkage int enter_vector_usercopy(void *dst, void *src, size_t n,
 				     bool enable_sum)
 {
-	size_t remain, copied;
+	size_t remain, copied, checked;
+
+	/* 0 => cpu@start */
+	/* 1 => cpu@end */
+	uint64_t dbg[2];
+
 
 	/* skip has_vector() check because it has been done by the asm  */
 	if (!may_use_simd())
 		goto fallback;
 
 	kernel_vector_begin();
-	remain = enable_sum ? __asm_vector_usercopy(dst, src, n) :
-			      __asm_vector_usercopy_sum_enabled(dst, src, n);
+	riscv_trap_trace_enable();
+	remain = enable_sum ? __asm_vector_usercopy(dst, src, n, dbg) :
+			      __asm_vector_usercopy_sum_enabled(dst, src, n, dbg);
+	riscv_trap_trace_disable();
 	kernel_vector_end();
 
+	copied = n - remain;
+	checked = enable_sum ? __asm_usercopy_check(dst, src, copied) : __asm_usercopy_check_sum_enabled(dst, src, copied);
+
+	if (checked == -1) {
+		pr_warn("RVV usercopy check can't be performed for dst=%px src=%px n=%zu remain=%zu copied=%zu enable_sum=%i\n", dst, src, n, remain, copied, enable_sum);
+	} else if (checked != copied) {
+		pr_err("RVV usercopy copied wrong data at %zu for for dst=%px src=%px n=%zu remain=%zu copied=%zu enable_sum=%i\n", checked, dst, src, n, remain, copied, enable_sum);
+		pr_err("Starting on CPU %llu, ended on CPU %llu\n", dbg[0], dbg[1]);
+		riscv_trap_trace_dump_cpu(dbg[0]);
+	}
+
 	if (remain) {
 		copied = n - remain;
 		dst += copied;
arch/riscv/lib/uaccess_vector.S +44 -1

66 lines not on this page · raw message

#16 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

In reply to kevin zhang

[resent with a better compression to get it accepted on the list]

Hi Kevin,

Quoted 47 lines · kevin zhang

Hi, Aurelien,

Thank you for your continued efforts.

Quoted 35 lines · Aurelien Jarno

Hi,

I have finally been able to capture the last few exceptions happening for one event where the vectored user copy code is corrupting data. That was on the SpacemiT K1.

I added a hook to handle_exception(), activated only when __asm_vector_usercopy_sum_enabled is running, and recording CPU state at the beginning of the exception, in per-CPU 16-entry tables. On the OpenSBI side, I also instrumented sbi_trap_handler() to log the CAUSE_MISALIGNED_LOAD and CAUSE_LOAD_ACCESS cases. This only fires during the kernel boot when it tries to measure speed of unaligned accesses.

The case I captured was a 4096-byte long copy, from 0x2a883310 (userland) to 0xffffffd701e54000 (kernel), presumably from a write syscall. The copy is considered successful, i.e it exits with a0=0. That said after the copy, the source and the destination start to differ after the first 16 bytes, at address 0xffffffd701e54010.

The copy started on CPU 5 and ended on CPU 5, and there was only a single exception between the start and the end, so it wasn't rescheduled.

The exception happened with epc=0xffffffff80e09204, which corresponds to the location of the "vle8.v v0,(a1)" instruction. I recorded:
- cause=0xd
- badaddr=0x2a883410
- a0=0xffffffd701e54100
- a1=0x2a883410
- a2=0xf00
- vl=0x100
- vstart=0x0
- vtype=0xc3

Quoted 7 lines

As you can see, the exception happened during the second iteration of the loop. It is not clear to me why the first iteration didn't trigger a page fault, as both 0x2a883310 and 0x2a883410 are on the same 4k page. I have also logged the content of v0 at the time of the exception, and I can clearly see that only the first 16 bytes (out of 32 bytes) got loaded during the previous iteration. Its content matches the error reported by GNU as on the userland side.

Quoted 3 lines

From the information you provided, the issue does indeed seem quite strange. Could you please share your debug patch with me? I'll try to further locate and analyze the issue on my side.

Please find attached the patch used on top of v7.3. It is not very clean as it was only done for debug purpose and grew organically. I have also attached the kernel config I used, based on the Debian one (hence the many modules that are useless for the K1).

With the patch, the issue is happening way more rarely, it took me more than one week building blender in a loop to get a failure. During that time I also caught 2 failures not linked to the usercopy code, but still causing GCC to fail in a similar way than on the K3, and as the Fedora guys also experience:

https://forge.fedoraproject.org/riscv/planning/issues/36

Regards
Aurelien

Signature · 2 lines
Aurelien Jarno                          GPG: 4096R/1DDD8C9B
[email protected]                     http://aurel32.net
arch/riscv/include/asm/trap_trace.h new file +12 -0
new file mode 100644
index 0000000000000..a7a3d5824ea34
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _ASM_RISCV_TRAP_TRACE_H
+#define _ASM_RISCV_TRAP_TRACE_H
+
+struct pt_regs;
+
+void riscv_trap_trace(struct pt_regs *regs);
+void riscv_trap_trace_dump_cpu(unsigned int cpu);
+void riscv_trap_trace_enable(void);
+void riscv_trap_trace_disable(void);
+
+#endif
arch/riscv/kernel/Makefile +1 -0
index ebe1c3588177b..e00e452cd345c 100644
@@ -72,6 +72,7 @@ obj-y	+= vendor_extensions.o
 obj-y	+= vendor_extensions/
 obj-y	+= probes/
 obj-y	+= tests/
+obj-y	+= trap_trace.o
 obj-$(CONFIG_MMU) += vdso.o vdso/
 obj-$(CONFIG_RISCV_USER_CFI) += vdso_cfi/
 
arch/riscv/kernel/entry.S +3 -0
index 61b7a77166971..bb923f421da76 100644
@@ -210,6 +210,9 @@ SYM_CODE_START(handle_exception)
 	/* Load the kernel shadow call stack pointer if coming from userspace */
 	scs_load_current_if_from_user s1, s5
 
+	move a0, sp
+	call riscv_trap_trace
+
 #ifdef CONFIG_RISCV_ISA_V_PREEMPTIVE
 	move a0, sp
 	call riscv_v_context_nesting_start
arch/riscv/kernel/trap_trace.c new file +142 -0

142 lines not on this page · raw message

arch/riscv/lib/riscv_v_helpers.c +27 -5
index 7bbdfc6d4552d..585c6d59908ff 100644
@@ -13,26 +13,48 @@
 #include <asm/asm-prototypes.h>
 #endif
 
+#include <asm/trap_trace.h>
+
 #ifdef CONFIG_MMU
 size_t riscv_v_usercopy_threshold = CONFIG_RISCV_ISA_V_UCOPY_THRESHOLD;
-int __asm_vector_usercopy(void *dst, void *src, size_t n);
-int __asm_vector_usercopy_sum_enabled(void *dst, void *src, size_t n);
+int __asm_vector_usercopy(void *dst, void *src, size_t n, uint64_t *dbg);
+int __asm_vector_usercopy_sum_enabled(void *dst, void *src, size_t n, uint64_t *dbg);
+int __asm_usercopy_check(void *dst, void *src, size_t n);
+int __asm_usercopy_check_sum_enabled(void *dst, void *src, size_t n);
 int fallback_scalar_usercopy(void *dst, void *src, size_t n);
 int fallback_scalar_usercopy_sum_enabled(void *dst, void *src, size_t n);
 asmlinkage int enter_vector_usercopy(void *dst, void *src, size_t n,
 				     bool enable_sum)
 {
-	size_t remain, copied;
+	size_t remain, copied, checked;
+
+	/* 0 => cpu@start */
+	/* 1 => cpu@end */
+	uint64_t dbg[2];
+
 
 	/* skip has_vector() check because it has been done by the asm  */
 	if (!may_use_simd())
 		goto fallback;
 
 	kernel_vector_begin();
-	remain = enable_sum ? __asm_vector_usercopy(dst, src, n) :
-			      __asm_vector_usercopy_sum_enabled(dst, src, n);
+	riscv_trap_trace_enable();
+	remain = enable_sum ? __asm_vector_usercopy(dst, src, n, dbg) :
+			      __asm_vector_usercopy_sum_enabled(dst, src, n, dbg);
+	riscv_trap_trace_disable();
 	kernel_vector_end();
 
+	copied = n - remain;
+	checked = enable_sum ? __asm_usercopy_check(dst, src, copied) : __asm_usercopy_check_sum_enabled(dst, src, copied);
+
+	if (checked == -1) {
+		pr_warn("RVV usercopy check can't be performed for dst=%px src=%px n=%zu remain=%zu copied=%zu enable_sum=%i\n", dst, src, n, remain, copied, enable_sum);
+	} else if (checked != copied) {
+		pr_err("RVV usercopy copied wrong data at %zu for for dst=%px src=%px n=%zu remain=%zu copied=%zu enable_sum=%i\n", checked, dst, src, n, remain, copied, enable_sum);
+		pr_err("Starting on CPU %llu, ended on CPU %llu\n", dbg[0], dbg[1]);
+		riscv_trap_trace_dump_cpu(dbg[0]);
+	}
+
 	if (remain) {
 		copied = n - remain;
 		dst += copied;
arch/riscv/lib/uaccess_vector.S +44 -1

66 lines not on this page · raw message

#19 lore raw

Re: Random corruption on SpacemiT K1 (and K3) with RVV

In reply to a message not in the archive

Hi Aurelien,

Quoted 2 lines · Aurelien Jarno

You mention "all", but you sent the mail only to Kevin and me. Is it wanted?

No, a mistake in my git send-email options, sorry. Adding everyone back. For the lists: my first mail had a userspace reproducer (again at the end of this one): two threads do vle8.v (e8, m8) from a shared memfd mapping while two other threads madvise(MADV_DONTNEED) it. Some loads retire with only their first 16*n bytes written, without a trap. Its "k" mode does the same through write() and gives Aurelien's usercopy signature on a stock 6.18 kernel. Aurelien can reproduce both on his side; not (yet) on the K3.

Quoted 2 lines

I am not sure you can conclude anything from vstart != 0. The RVV spec leaves a lot of freedom on the vstart mechanism.

Agreed. All it shows is that the kernel never resumed one of these loads with a nonzero vstart. A restart from vstart = 0 reloads everything, so either way the S-mode trap handling can't produce a partial load.

Quoted 1 line

Have you been able to trace that further at the SBI level?

No. The kernel here does remote fences through SBI, so I can't remove M-mode from the path on the K1.

Quoted 3 lines

The remote TLB shootdown causes an M-mode IPI on the hart where the vector load instruction is running, but on that hart it doesn't run concurrently with the vector load instruction.

Agreed for the IPI. But the PTE is cleared in memory before the IPI is sent. If the later beats of the load are translated again (e.g. a micro-TLB miss inside the instruction) and the walk sees the cleared PTE, the load should fault with vstart > 0; dropping the fault and retiring would match your trace (no fault on the bad load, a fault on the next iteration on the same page). Only zapping the page being read triggers it here; zapping all the other pages of the mapping doesn't.

I tried to test this by timing an immediate retry of a bad load (a page fault makes it slow), but the probe itself suppresses the problem: on v7.4-rc1 + THP, adding two rdtime, or one extra vle8.v, after each batch of 4096 loads takes the rate from 25/240 process runs to 0/360. rdtime is native here (~8 ns), so no M-mode trap. Moving a vector store in the same place gives 3/120. The bad state seems to depend on the exact instruction stream, which also points below the kernel.

Quoted 2 lines

I even have the *feeling* that once the problem happened, it then happens more often.

Same here: a process either never hits, or enters a state where one page keeps hitting (up to ~100/s per thread) while the zapping goes on. It stops when the zapping pauses and resumes with it. Fresh exec'd processes enter it ~10x more often than forked ones, mostly in their first seconds. I haven't compared reboots.

Quoted 2 lines

Did you chose to pin the two process on a different clusters as it doesn't reproduce at all when on the same cluster?

No, each process keeps its 4 threads on one cluster; the second process is only there for throughput. Zappers on the other cluster: 6/80 runs, vs 7/80 with everything on one cluster ("k" mode, 20 s runs). So the cluster doesn't matter.

Frederic

(Claude, an AI assistant, helped write and run these tests.)

---8<--- k1-vload-repro.c ---
// SPDX-License-Identifier: GPL-2.0
/*
* k1-vload-repro: RVV unit-stride loads that retire without writing all
* their elements (seen on SpacemiT K1), while another hart zaps the PTE
* of the page being read.
*
* Each round runs two fresh processes at once (fork + exec of this
* binary), one per 4-CPU cluster. In each process, 2 pinned workers load
* 32*LMUL bytes (vle8.v, e8) from a 16-page shared memfd mapping into a
* v16 group that they first fill with 0xa5, and compare with the
* expected bytes in vector registers. 2 other pinned threads call
* madvise(MADV_DONTNEED) on the mapping in a loop (the page cache keeps
* the data, so every refault returns the same bytes).
*
* A hit is a load whose tail still holds the 0xa5 fill: the instruction
* retired without writing its last elements, and no trap was taken.
* A process either never hits or enters a state where it hits often,
* usually within its first seconds, hence many short runs.
*
* Build: gcc -O2 -march=rv64gcv -pthread -o k1-vload-repro k1-vload-repro.c

 * Run:   ./k1-vload-repro [rounds [seconds [lmul|k]]]   (default 60 5 8)
 *        "k": the workers write() 4 KiB from the mapping into a pipe and
 *        read it back instead, i.e. the kernel's vector copy_from_user
 *        does the loads (a bad copy holds stale register contents).
 *        On a BPI-F3: ~1-15 % of process runs hit with m8 (more on
 *        v7.4-rc1 with THP than on 6.18), ~10 % with "k" and 20 s runs.

*/
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>

#define PG 4096
#define NPAGES 16
#define LEN (NPAGES * PG)
#define FILL 0xa5

static uint8_t *src, ref[LEN];
static _Atomic int stop;
static _Atomic unsigned long hits;
static int base_cpu, lmul = 8;

static void pin(int cpu)

{
	cpu_set_t s;

	CPU_ZERO(&s);
	CPU_SET(cpu % 8, &s);
	sched_setaffinity(0, sizeof(s), &s);
}

/*
* 'iters' loads of 32 * LMUL bytes from s, each into a v16 group filled
* with FILL first; returns the failing iteration (v16 stored to out) or -1. */
#define VCHECK(NAME, LMUL) \
static long NAME(const uint8_t *s, const uint8_t *r, long iters, uint8_t *out) \

{									\
	long left = iters, bad;						\
	size_t vl;							\
									\
	asm volatile("vsetvli %[vl], %[n], e8, " LMUL ", ta, ma\n\t"	\
		     "vle8.v v8, (%[r])\n\t"				\
		     "1:\n\t"						\
		     "vmv.v.x v16, %[fill]\n\t"				\
		     "vle8.v v16, (%[s])\n\t"				\
		     "vmsne.vv v0, v16, v8\n\t"				\
		     "vcpop.m %[bad], v0\n\t"				\
		     "bnez %[bad], 2f\n\t"				\
		     "addi %[left], %[left], -1\n\t"			\
		     "bnez %[left], 1b\n\t"				\
		     "j 3f\n"						\
		     "2:\n\t"						\
		     "vse8.v v16, (%[out])\n"				\
		     "3:\n"						\
		     : [vl] "=&r"(vl), [left] "+r"(left), [bad] "=&r"(bad) \
		     : [n] "r"((size_t)256), [s] "r"(s), [r] "r"(r),	\
		       [out] "r"(out), [fill] "r"((long)FILL)		\
		     : "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", \
		       "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", \
		       "v22", "v23");					\
	return bad ? iters - left : -1;					\
}

VCHECK(vcheck_m1, "m1")
VCHECK(vcheck_m2, "m2")
VCHECK(vcheck_m4, "m4")
VCHECK(vcheck_m8, "m8")

static long vcheck(const uint8_t *s, const uint8_t *r, long iters, uint8_t *out)

{
	switch (lmul) {
	case 1: return vcheck_m1(s, r, iters, out);
	case 2: return vcheck_m2(s, r, iters, out);
	case 4: return vcheck_m4(s, r, iters, out);
	default: return vcheck_m8(s, r, iters, out);
	}
}

static void *worker(void *arg)

{
	int w = (int)(long)arg, nb = 32 * lmul;
	unsigned int seed = 12345 + w;
	uint8_t out[256];

	pin(base_cpu + w);
	while (!stop) {
		/* 256 B inside one page, 16 B aligned */
		size_t o = (size_t)(rand_r(&seed) % (NPAGES - 1)) * PG +
			   ((size_t)(rand_r(&seed) % (PG - 256 + 16)) & ~(size_t)15);

		if (vcheck(src + o, ref + o, 4096, out) < 0)
			continue;
		int first = -1, nfill = 0, nother = 0;

		for (int i = 0; i < nb; i++) {
			if (out[i] == ref[o + i])
				continue;
			if (first < 0)
				first = i;
			if (out[i] == FILL)
				nfill++;
			else
				nother++;
		}
		if (atomic_fetch_add(&hits, 1) < 5)
			printf("  HIT cpu %d va %p: elements %d..%d not loaded "
			       "(%d bytes still 0x%02x, %d other)\n",
			       sched_getcpu(), (void *)(src + o), first, nb - 1,
			       nfill, FILL, nother);
	}
	return NULL;
}

/*
* Kernel mode: write() 4 KiB from the mapping into a pipe and read it back.
* The kernel's copy_from_user uses vector loads above 768 bytes. A bad
* copy holds whatever was in the vector registers instead of the data:
* 0xff if the thread had live vector state (poisoned at syscall entry by
* __riscv_v_vstate_discard()), otherwise stale data from an earlier copy. */
static uint8_t kfill = 0xff;

static void *kworker(void *arg)

{
	int w = (int)(long)arg, p[2];
	unsigned int seed = 12345 + w;
	static __thread uint8_t buf[4096];

	pin(base_cpu + w);
	if (pipe(p))
		return NULL;
	while (!stop) {
		size_t o = (size_t)(rand_r(&seed) % ((NPAGES - 1) * PG)) & ~(size_t)15;

		if (write(p[1], src + o, 4096) != 4096 || read(p[0], buf, 4096) != 4096)
			break;
		if (!memcmp(buf, ref + o, 4096))
			continue;
		int first = -1, last = 0, nff = 0;

		for (int i = 0; i < 4096; i++)
			if (buf[i] != ref[o + i]) {
				if (first < 0)
					first = i;
				last = i;
				nff += buf[i] == kfill;
			}
		if (atomic_fetch_add(&hits, 1) < 5)
			printf("  HIT cpu %d va %p: write() copied wrong bytes %d..%d "
			       "(%d of them 0x%02x, the rest stale data)\n",
			       sched_getcpu(), (void *)(src + o), first, last, nff,
			       kfill);
	}
	return NULL;
}

static void *zapper(void *arg)

{
	pin(base_cpu + 2 + (int)(long)arg);
	while (!stop)
		madvise(src, LEN, MADV_DONTNEED);
	return NULL;
}

static int child(int secs)

{
	int fd = memfd_create("k1-vload", 0);

	if (fd < 0 || write(fd, ref, LEN) != LEN) {
		perror("memfd");
		return 2;
	}
	src = mmap(NULL, LEN, PROT_READ, MAP_SHARED, fd, 0);
	if (src == MAP_FAILED) {
		perror("mmap");
		return 2;
	}
	pthread_t t[4];

	for (long i = 0; i < 2; i++)
		pthread_create(&t[i], NULL, lmul ? worker : kworker, (void *)i);
	for (long i = 0; i < 2; i++)
		pthread_create(&t[2 + i], NULL, zapper, (void *)i);
	sleep(secs);
	stop = 1;
	for (int i = 0; i < 4; i++)
		pthread_join(t[i], NULL);
	return hits ? 1 : 0;
}

int main(int argc, char **argv)

{
	setvbuf(stdout, NULL, _IOLBF, 0);
	for (int i = 0; i < LEN; i++)
		ref[i] = (uint8_t)(((i * 2654435761u) >> 13) ^ i);
	/* child: k1-vload-repro --child CPU SECONDS LMUL */
	if (argc == 5 && !strcmp(argv[1], "--child")) {
		base_cpu = atoi(argv[2]);
		lmul = argv[4][0] == 'k' ? 0 : atoi(argv[4]);
		return child(atoi(argv[3]));
	}

	int rounds = argc > 1 ? atoi(argv[1]) : 60;
	int secs = argc > 2 ? atoi(argv[2]) : 5;
	const char *lm = argc > 3 ? argv[3] : "8";
	int bad_runs = 0;

	printf("%d rounds of %d s, %s%s\n", rounds, secs,
	       lm[0] == 'k' ? "kernel copy_from_user" : "LMUL=", lm[0] == 'k' ? "" : lm);
	for (int r = 0; r < rounds; r++) {
		pid_t p[2];

		/*
		 * A fresh exec'd process per run: forked children (sharing the
		 * parent's layout) hit about 10x less often.
		 */
		for (int c = 0; c < 2; c++) {
			char cb[8], sb[16];

			snprintf(cb, sizeof(cb), "%d", c * 4);
			snprintf(sb, sizeof(sb), "%d", secs);
			p[c] = fork();
			if (p[c] == 0) {
				execl("/proc/self/exe", argv[0], "--child", cb, sb, lm,
				      (char *)NULL);
				_exit(2);
			}
		}
		for (int c = 0; c < 2; c++) {
			int st;

			waitpid(p[c], &st, 0);
			int bad = WIFEXITED(st) && WEXITSTATUS(st) == 1;

			bad_runs += bad;
			if (bad)
				printf("round %d, cpus %d-%d: CORRUPTED LOADS\n",
				       r + 1, c * 4, c * 4 + 3);
		}
	}
	printf("%d of %d process runs had corrupted vector loads\n",
	       bad_runs, 2 * rounds);
	return bad_runs ? 1 : 0;
}