All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v2 0/3] Fix AES/PAES CPACF register update on faults
@ 2026-11-20 13:14 Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 1/3] target/s390x: export access_prepare() and byte accessors Andrew Holden
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: Andrew Holden @ 2026-11-20 13:14 UTC (permalink / raw)
  To: qemu-devel, iii, freude
  Cc: qemu-s390x, richard.henderson, david, cohuck, farman, mjrosato,
	Andrew Holden

This series fixes how the CPACF AES helpers (ECB, CBC, CTR, XTS, with
both clear key and protected keys) behave when a guest memory access
faults in the middle of an instruction. A fault could leave a block
partially written, and the registers, CBC IV and XTS tweak not matching
the completed blocks, so the instruction would not continue where it
stopped.

Each block is now probed with access_prepare() before anything is 
written, which applies to the source, destination, and IV/tweak. The
registers are now updated last, so a fault leaves the block unwritten
and a re-invocation redoes it. Block copying is handled by
aes_read_block() and aes_write_block(), shared by the clear-key and
prot-key functions. 

The IV/tweak range is probed before the block is written, so a fault on
this is unlikely. The data and IV stores are still two separate steps
however. If the IV/tweak store fails after the data store, e.g. because
another thread changed the page post-probe, a re-invocation would not
redo the block cleanly when the source and destination overlap.
Currently, I can't make the two stores a single operation.

Testing:
qemu-s390x and qemu-system-s390x build, with current cpacf tests
passing, along with four fault tests written by Harald Freudenberger -
these were built and excercised in linux-user mode, targeting the
relevant instructions.

Notes:
  - Prot-key functions are covered by existing cpacf tests, but no fault
    test currently exist. 
  - Access helpers declared in s390x-internal.h - is this acceptable?

---
Changelog:
v2:
  - Probe src, dst, and IV/tweak ranges with access_prepare() before
    writing, so a fault leaves block unwritten, incl. block that crosses
    page boundary.
  - Share AES w/r block helper for all functions.
  - Extend fix to prot-key functions.
  - Squash each cipher mode fix commits into one.
  - Include testcases in this series

Links:
v1: https://lore.kernel.org/qemu-devel/20261008154455.369004-1-andy0x48@linux.ibm.com/

---

Andrew Holden (2):
  target/s390x: export access_prepare() and byte accessors
  target/s390x/tcg: update regs and IV/tweak per block in CPACF AES/PAES

Harald Freudenberger (1):
  tests/s390x/tcg: Add cpacf clear key register update tests

 target/s390x/s390x-internal.h           |  25 ++
 target/s390x/tcg/cpacf_aes.c            | 380 ++++++++++++------
 target/s390x/tcg/mem_helper.c           |  33 +-
 tests/tcg/s390x/cpacf-km-ecb-fault.c    | 368 +++++++++++++++++
 tests/tcg/s390x/cpacf-km-xts-fault.c    | 511 ++++++++++++++++++++++++
 tests/tcg/s390x/cpacf-kmc-cbc-fault.c   | 472 ++++++++++++++++++++++
 tests/tcg/s390x/cpacf-kmctr-ctr-fault.c | 414 +++++++++++++++++++
 tests/tcg/s390x/cpacf.h                 | 103 +++--
 tests/tcg/s390x/meson.build             |   4 +
 9 files changed, 2138 insertions(+), 172 deletions(-)
 create mode 100644 tests/tcg/s390x/cpacf-km-ecb-fault.c
 create mode 100644 tests/tcg/s390x/cpacf-km-xts-fault.c
 create mode 100644 tests/tcg/s390x/cpacf-kmc-cbc-fault.c
 create mode 100644 tests/tcg/s390x/cpacf-kmctr-ctr-fault.c

-- 
2.56.0



^ permalink raw reply	[flat|nested] 4+ messages in thread

* [PATCH v2 1/3] target/s390x: export access_prepare() and byte accessors
  2026-11-20 13:14 [PATCH v2 0/3] Fix AES/PAES CPACF register update on faults Andrew Holden
@ 2026-11-20 13:14 ` Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 2/3] target/s390x/tcg: update regs and IV/tweak per block in CPACF AES/PAES Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 3/3] tests/s390x/tcg: Add cpacf clear key register update tests Andrew Holden
  2 siblings, 0 replies; 4+ messages in thread
From: Andrew Holden @ 2026-11-20 13:14 UTC (permalink / raw)
  To: qemu-devel, iii, freude
  Cc: qemu-s390x, richard.henderson, david, cohuck, farman, mjrosato,
	Andrew Holden

The helpers are needed by CPACF AES for a partial completion fix. There
is no functional change with this modification.

Signed-off-by: Andrew Holden <andy0x48@linux.ibm.com>
---
 target/s390x/s390x-internal.h | 25 +++++++++++++++++++++++++
 target/s390x/tcg/mem_helper.c | 33 ++++++++-------------------------
 2 files changed, 33 insertions(+), 25 deletions(-)

diff --git a/target/s390x/s390x-internal.h b/target/s390x/s390x-internal.h
index da60b2b1fd..c97d399c99 100644
--- a/target/s390x/s390x-internal.h
+++ b/target/s390x/s390x-internal.h
@@ -368,6 +368,31 @@ void ioinst_handle_sal(S390CPU *cpu, uint64_t reg1, uintptr_t ra);
 
 
 /* mem_helper.c */
+
+/* An access covers at most 4096 bytes and therefore at most two pages. */
+typedef struct S390Access {
+    vaddr vaddr1;
+    vaddr vaddr2;
+    void *haddr1;
+    void *haddr2;
+    uint16_t size1;
+    uint16_t size2;
+    /*
+     * If we can't access the host page directly, we'll have to do I/O access
+     * via ld/st helpers. These are internal details, so we store the
+     * mmu idx to do the access here instead of passing it around in the
+     * helpers.
+     */
+    int mmu_idx;
+} S390Access;
+
+void access_prepare(S390Access *ret, CPUS390XState *env, vaddr vaddr,
+                    int size, MMUAccessType access_type, int mmu_idx,
+                    uintptr_t ra);
+uint8_t access_get_byte(CPUS390XState *env, S390Access *access, int offset,
+                        uintptr_t ra);
+void access_set_byte(CPUS390XState *env, S390Access *access, int offset,
+                     uint8_t byte, uintptr_t ra);
 void probe_write_access(CPUS390XState *env, uint64_t addr, uint64_t len,
                         uintptr_t ra);
 
diff --git a/target/s390x/tcg/mem_helper.c b/target/s390x/tcg/mem_helper.c
index 414e6838c8..5144f036ad 100644
--- a/target/s390x/tcg/mem_helper.c
+++ b/target/s390x/tcg/mem_helper.c
@@ -126,23 +126,6 @@ static inline void cpu_stsize_data_ra(CPUS390XState *env, uint64_t addr,
     }
 }
 
-/* An access covers at most 4096 bytes and therefore at most two pages. */
-typedef struct S390Access {
-    vaddr vaddr1;
-    vaddr vaddr2;
-    void *haddr1;
-    void *haddr2;
-    uint16_t size1;
-    uint16_t size2;
-    /*
-     * If we can't access the host page directly, we'll have to do I/O access
-     * via ld/st helpers. These are internal details, so we store the
-     * mmu idx to do the access here instead of passing it around in the
-     * helpers.
-     */
-    int mmu_idx;
-} S390Access;
-
 /*
  * With nonfault=1, return the PGM_ exception that would have been injected
  * into the guest; return 0 if no exception was detected.
@@ -219,10 +202,10 @@ static int access_prepare_nf(S390Access *access, CPUS390XState *env,
     return 0;
 }
 
-static inline void access_prepare(S390Access *ret, CPUS390XState *env,
-                                  vaddr vaddr, int size,
-                                  MMUAccessType access_type, int mmu_idx,
-                                  uintptr_t ra)
+void access_prepare(S390Access *ret, CPUS390XState *env,
+                    vaddr vaddr, int size,
+                    MMUAccessType access_type, int mmu_idx,
+                    uintptr_t ra)
 {
     int exc = access_prepare_nf(ret, env, false, vaddr, size,
                                 access_type, mmu_idx, ra);
@@ -257,8 +240,8 @@ static void access_memset(CPUS390XState *env, S390Access *desta,
     clear_helper_retaddr();
 }
 
-static uint8_t access_get_byte(CPUS390XState *env, S390Access *access,
-                               int offset, uintptr_t ra)
+uint8_t access_get_byte(CPUS390XState *env, S390Access *access,
+                        int offset, uintptr_t ra)
 {
     vaddr vaddr = access->vaddr1;
     void *haddr = access->haddr1;
@@ -277,8 +260,8 @@ static uint8_t access_get_byte(CPUS390XState *env, S390Access *access,
     }
 }
 
-static void access_set_byte(CPUS390XState *env, S390Access *access,
-                            int offset, uint8_t byte, uintptr_t ra)
+void access_set_byte(CPUS390XState *env, S390Access *access,
+                     int offset, uint8_t byte, uintptr_t ra)
 {
     vaddr vaddr = access->vaddr1;
     void *haddr = access->haddr1;
-- 
2.56.0



^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [PATCH v2 2/3] target/s390x/tcg: update regs and IV/tweak per block in CPACF AES/PAES
  2026-11-20 13:14 [PATCH v2 0/3] Fix AES/PAES CPACF register update on faults Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 1/3] target/s390x: export access_prepare() and byte accessors Andrew Holden
@ 2026-11-20 13:14 ` Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 3/3] tests/s390x/tcg: Add cpacf clear key register update tests Andrew Holden
  2 siblings, 0 replies; 4+ messages in thread
From: Andrew Holden @ 2026-11-20 13:14 UTC (permalink / raw)
  To: qemu-devel, iii, freude
  Cc: qemu-s390x, richard.henderson, david, cohuck, farman, mjrosato,
	Andrew Holden

The CPACF AES and PAES helpers (ECB, CBC, CTR, and XTS) updated the guest
registers, and the CBC IV and XTS tweak, only after the whole block
loop. A guest fault unwinds out of the helper, so the registers kept
their start-of-instruction values, with the instruction having
restarted at the first block instead of resuming after the last
completed block, as expected regarding PoP. A block crossing a page
boundary could also be partly written before the fault.

Probe the source, destination, and IV/tweak of each block with
access_prepare() before any data is written, then update the registers
last, a fault leaves the block untouched and a re-invocation would
redo this. aes_read_block() and aes_write_block() do all the copying
for each mode. Addresses are wrapped per block.

The IV/tweak write is probed first but it is not atomic with the data
write. It's unlikely a fault happens between the data store and
IV/tweak, but it could happen due to a specific thread unmapping, page
change, etc., and only matters when source and destination overlap.

Signed-off-by: Andrew Holden <andy0x48@linux.ibm.com>
---
 target/s390x/tcg/cpacf_aes.c | 380 ++++++++++++++++++++++++-----------
 1 file changed, 259 insertions(+), 121 deletions(-)

diff --git a/target/s390x/tcg/cpacf_aes.c b/target/s390x/tcg/cpacf_aes.c
index 92884c4120..117d43040b 100644
--- a/target/s390x/tcg/cpacf_aes.c
+++ b/target/s390x/tcg/cpacf_aes.c
@@ -12,6 +12,7 @@
 #include "tcg_s390x.h"
 #include "accel/tcg/cpu-ldst-common.h"
 #include "accel/tcg/cpu-mmu-index.h"
+#include "accel/tcg/helper-retaddr.h"
 #include "crypto/aes.h"
 #include "crypto/aes-helpers.h"
 #include "target/s390x/tcg/cpacf-arch.h"
@@ -19,23 +20,40 @@
 #include "target/s390x/tcg/crypto_helper.h"
 
 /*
- * read exactly one AES block from guest memory into a local buffer
+ * probe one AES block at guest address, which is wrapped according to current
+ * addressing mode, since access_prepare() only wraps second page.
  */
-static inline void aes_read_block(CPUS390XState *env, const int mmu_idx,
-                                  const uintptr_t ra, uint64_t guest_addr,
-                                  uint8_t *buf)
+static inline void aes_prepare_block(CPUS390XState *env, const int mmu_idx,
+                                     const uintptr_t ra, S390Access *acc,
+                                     uint64_t addr, MMUAccessType type)
 {
-    read_guest_wrap_u8(env, mmu_idx, ra, guest_addr, buf, AES_BLOCK_SIZE);
+    uint64_t waddr;
+    waddr = wrap_address(env, addr);
+    access_prepare(acc, env, waddr, AES_BLOCK_SIZE, type, mmu_idx, ra);
 }
 
 /*
- * write exactly one AES block from local buffer to guest memory
+ * read exactly one AES block from a prepared access into a local buffer.
  */
-static void aes_write_block(CPUS390XState *env, const int mmu_idx,
-                            const uintptr_t ra, uint64_t guest_addr,
-                            uint8_t *buf)
+static inline void aes_read_block(CPUS390XState *env, const uintptr_t ra,
+                                  S390Access *acc, uint8_t *buf)
 {
-    write_guest_wrap_u8(env, mmu_idx, ra, guest_addr, buf, AES_BLOCK_SIZE);
+    /* gather block */
+    for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+        buf[i] = access_get_byte(env, acc, i, ra);
+    }
+}
+
+/*
+ * write exactly one AES block from a local buffer to a prepared access.
+ */
+static inline void aes_write_block(CPUS390XState *env, const uintptr_t ra,
+                                   S390Access *acc, uint8_t *buf)
+{
+    /* scatter block */
+    for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+        access_set_byte(env, acc, i, buf[i], ra);
+    }
 }
 
 /*
@@ -62,8 +80,9 @@ int cpacf_aes_ecb(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 {
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
+    S390Access srca, dsta;
     uint8_t key[32];
     AES_KEY exkey;
 
@@ -116,23 +135,37 @@ int cpacf_aes_ecb(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source and destination access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
         if (mod) {
             AES_decrypt(in, out, &exkey);
         } else {
             AES_encrypt(in, out, &exkey);
         }
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        aes_write_block(env, ra, &dsta, out);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -143,9 +176,10 @@ int cpacf_aes_cbc(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 {
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
     uint8_t key[32], iv[AES_BLOCK_SIZE];
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
+    S390Access srca, dsta, iva;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KMC);
@@ -202,7 +236,21 @@ int cpacf_aes_cbc(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source, destination, and iv access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+        aes_prepare_block(env, mmu_idx, ra, &iva, param_addr,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
         if (mod) {
             /* decrypt in => out */
             AES_cbc_decrypt(in, out, iv, &exkey);
@@ -210,20 +258,22 @@ int cpacf_aes_cbc(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
             /* encrypt in => out */
             AES_cbc_encrypt(in, out, iv, &exkey);
         }
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        /* scatter block to destination */
+        aes_write_block(env, ra, &dsta, out);
+        /* write back running iv */
+        aes_write_block(env, ra, &iva, iv);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    /* update iv in param block */
-    write_guest_wrap_u8(env, mmu_idx, ra, param_addr, iv, AES_BLOCK_SIZE);
-
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -235,9 +285,10 @@ int cpacf_aes_ctr(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 {
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
     uint8_t ctr[AES_BLOCK_SIZE], key[32];
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
+    S390Access srca, dsta, ctra;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KMCTR);
@@ -286,26 +337,39 @@ int cpacf_aes_ctr(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        /* read in nonce/ctr => ctr */
-        aes_read_block(env, mmu_idx, ra, *ctr_ptr_reg + done, ctr);
-        /* read in one block of input data => in */
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source, counter, and destination access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &ctra, *ctr_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
+        aes_read_block(env, ra, &ctra, ctr);
         /* encrypt ctr and xor with in => out */
         AES_ctr_encrypt(in, out, ctr, &exkey);
-        /* write out the processed block */
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        aes_write_block(env, ra, &dsta, out);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *ctr_ptr_reg = deposit64(*ctr_ptr_reg, 0, addr_reg_size,
+                                 *ctr_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *ctr_ptr_reg = deposit64(*ctr_ptr_reg, 0, addr_reg_size,
-                             *ctr_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -369,9 +433,10 @@ int cpacf_aes_xts(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 {
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
     uint8_t key[32], tweak[AES_BLOCK_SIZE];
+    S390Access srca, dsta, tweaka;
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KM);
@@ -425,8 +490,21 @@ int cpacf_aes_xts(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        /* fetch one AES block into in  */
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source, destination, and tweak access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+        aes_prepare_block(env, mmu_idx, ra, &tweaka, param_addr + keysize,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
         if (mod) {
             /* decrypt in => out */
             AES_xts_decrypt(in, out, tweak, &exkey);
@@ -436,22 +514,22 @@ int cpacf_aes_xts(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
         }
         /* prep tweak for next round */
         AES_xts_prep_next_tweak(tweak);
-        /* write out this processed block from out */
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        /* scatter block to destination */
+        aes_write_block(env, ra, &dsta, out);
+        /* write back running tweak */
+        aes_write_block(env, ra, &tweaka, tweak);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    /* update tweak in param block */
-    write_guest_wrap_u8(env, mmu_idx, ra,
-                        param_addr + keysize, tweak, AES_BLOCK_SIZE);
-
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -537,9 +615,10 @@ int cpacf_paes_ecb(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 {
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
     uint8_t key[32], wkvp[32];
+    S390Access srca, dsta;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KM);
@@ -602,23 +681,37 @@ int cpacf_paes_ecb(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source and destination access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
         if (mod) {
             AES_decrypt(in, out, &exkey);
         } else {
             AES_encrypt(in, out, &exkey);
         }
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        aes_write_block(env, ra, &dsta, out);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -630,8 +723,9 @@ int cpacf_paes_cbc(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
     uint8_t key[32], wkvp[32], iv[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
+    S390Access srca, dsta, iva;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KMC);
@@ -699,7 +793,21 @@ int cpacf_paes_cbc(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source, destination, and iv access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+        aes_prepare_block(env, mmu_idx, ra, &iva, param_addr,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
         if (mod) {
             /* decrypt in => out */
             AES_cbc_decrypt(in, out, iv, &exkey);
@@ -707,20 +815,22 @@ int cpacf_paes_cbc(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
             /* encrypt in => out */
             AES_cbc_encrypt(in, out, iv, &exkey);
         }
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        /* scatter block to destination */
+        aes_write_block(env, ra, &dsta, out);
+        /* write back running iv */
+        aes_write_block(env, ra, &iva, iv);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    /* update iv in param block */
-    write_guest_wrap_u8(env, mmu_idx, ra, param_addr, iv, AES_BLOCK_SIZE);
-
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -733,8 +843,9 @@ int cpacf_paes_ctr(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
     uint8_t ctr[AES_BLOCK_SIZE], key[32], wkvp[32];
-    uint64_t len = *src_len_reg, done = 0;
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
+    S390Access srca, dsta, ctra;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KMCTR);
@@ -793,26 +904,39 @@ int cpacf_paes_ctr(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        /* read in nonce/ctr => ctr */
-        aes_read_block(env, mmu_idx, ra, *ctr_ptr_reg + done, ctr);
-        /* read in one block of input data => in */
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source, counter, and destination access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &ctra, *ctr_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
+        aes_read_block(env, ra, &ctra, ctr);
         /* encrypt ctr and xor with in => out */
         AES_ctr_encrypt(in, out, ctr, &exkey);
-        /* write out the processed block */
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        aes_write_block(env, ra, &dsta, out);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *ctr_ptr_reg = deposit64(*ctr_ptr_reg, 0, addr_reg_size,
+                                 *ctr_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *ctr_ptr_reg = deposit64(*ctr_ptr_reg, 0, addr_reg_size,
-                             *ctr_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
 
@@ -888,8 +1012,9 @@ int cpacf_paes_xts(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
     enum { MAX_BLOCKS_PER_RUN = 8192 / AES_BLOCK_SIZE };
     uint8_t in[AES_BLOCK_SIZE], out[AES_BLOCK_SIZE];
     uint8_t key[32], wkvp[32], tweak[AES_BLOCK_SIZE];
-    uint64_t len = *src_len_reg, done = 0;
+    S390Access srca, dsta, tweaka;
     int i, keysize, addr_reg_size;
+    uint64_t len = *src_len_reg;
     AES_KEY exkey;
 
     g_assert(type == S390_FEAT_TYPE_KM);
@@ -954,8 +1079,22 @@ int cpacf_paes_xts(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
 
     /* process up to MAX_BLOCKS_PER_RUN aes blocks */
     for (i = 0; i < MAX_BLOCKS_PER_RUN && len >= AES_BLOCK_SIZE; i++) {
-        /* fetch one AES block into in */
-        aes_read_block(env, mmu_idx, ra, *src_ptr_reg + done, in);
+        /* probe source, destination, and tweak access */
+        aes_prepare_block(env, mmu_idx, ra, &srca, *src_ptr_reg,
+                          MMU_DATA_LOAD);
+        aes_prepare_block(env, mmu_idx, ra, &dsta, *dst_ptr_reg,
+                          MMU_DATA_STORE);
+        aes_prepare_block(env, mmu_idx, ra, &tweaka,
+                          param_addr + keysize + sizeof(wkvp),
+                          MMU_DATA_STORE);
+
+        /*
+         * linux-user: the accessors below use host pointers. Record ra so a
+         * fault from a racing unmap of the probed page is unwound correctly.
+         */
+        set_helper_retaddr(ra);
+
+        aes_read_block(env, ra, &srca, in);
         if (mod) {
             /* decrypt in => out */
             AES_xts_decrypt(in, out, tweak, &exkey);
@@ -965,22 +1104,21 @@ int cpacf_paes_xts(CPUS390XState *env, const int mmu_idx, uintptr_t ra,
         }
         /* prep tweak for next round */
         AES_xts_prep_next_tweak(tweak);
-        /* write out this processed block from out */
-        aes_write_block(env, mmu_idx, ra, *dst_ptr_reg + done, out);
+        /* scatter block to destination */
+        aes_write_block(env, ra, &dsta, out);
+        /* write back running tweak */
+        aes_write_block(env, ra, &tweaka, tweak);
+
+        clear_helper_retaddr();
+
+        /* update registers at end of each iteration */
+        *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
+                                 *src_ptr_reg + AES_BLOCK_SIZE);
+        *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
+                                 *dst_ptr_reg + AES_BLOCK_SIZE);
+        *src_len_reg -= AES_BLOCK_SIZE;
         len -= AES_BLOCK_SIZE;
-        done += AES_BLOCK_SIZE;
     }
 
-    /* update tweak in param block */
-    write_guest_wrap_u8(env, mmu_idx, ra,
-                        param_addr + keysize + sizeof(wkvp),
-                        tweak, AES_BLOCK_SIZE);
-
-    *src_ptr_reg = deposit64(*src_ptr_reg, 0, addr_reg_size,
-                             *src_ptr_reg + done);
-    *dst_ptr_reg = deposit64(*dst_ptr_reg, 0, addr_reg_size,
-                             *dst_ptr_reg + done);
-    *src_len_reg -= done;
-
     return !len ? 0 : 3;
 }
-- 
2.56.0



^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [PATCH v2 3/3] tests/s390x/tcg: Add cpacf clear key register update tests
  2026-11-20 13:14 [PATCH v2 0/3] Fix AES/PAES CPACF register update on faults Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 1/3] target/s390x: export access_prepare() and byte accessors Andrew Holden
  2026-11-20 13:14 ` [PATCH v2 2/3] target/s390x/tcg: update regs and IV/tweak per block in CPACF AES/PAES Andrew Holden
@ 2026-11-20 13:14 ` Andrew Holden
  2 siblings, 0 replies; 4+ messages in thread
From: Andrew Holden @ 2026-11-20 13:14 UTC (permalink / raw)
  To: qemu-devel, iii, freude
  Cc: qemu-s390x, richard.henderson, david, cohuck, farman, mjrosato,
	Andrew Holden

From: Harald Freudenberger <freude@linux.ibm.com>

Add simple test cases for the 4 clear key cpacf implementation
functions cpacf_aes_ecb(), cpacf_aes_cbc(), cpacf_aes_ctr() and
cpacf_aes_xts() which shall test if the register update and memory
update during processing of data within the cpacf instruction (km,
kmc, kmctr) emulation is correct. See details about how the test cases
are designed and actually work testcase code. Note that as there is a
signal handler evaluating the registers on the enforced address
violation the cpacf.h inline function needs to use pinned registers.

Signed-off-by: Harald Freudenberger <freude@linux.ibm.com>
Signed-off-by: Andrew Holden <andy0x48@linux.ibm.com>
---
 tests/tcg/s390x/cpacf-km-ecb-fault.c    | 368 +++++++++++++++++
 tests/tcg/s390x/cpacf-km-xts-fault.c    | 511 ++++++++++++++++++++++++
 tests/tcg/s390x/cpacf-kmc-cbc-fault.c   | 472 ++++++++++++++++++++++
 tests/tcg/s390x/cpacf-kmctr-ctr-fault.c | 414 +++++++++++++++++++
 tests/tcg/s390x/cpacf.h                 | 103 +++--
 tests/tcg/s390x/meson.build             |   4 +
 6 files changed, 1846 insertions(+), 26 deletions(-)
 create mode 100644 tests/tcg/s390x/cpacf-km-ecb-fault.c
 create mode 100644 tests/tcg/s390x/cpacf-km-xts-fault.c
 create mode 100644 tests/tcg/s390x/cpacf-kmc-cbc-fault.c
 create mode 100644 tests/tcg/s390x/cpacf-kmctr-ctr-fault.c

diff --git a/tests/tcg/s390x/cpacf-km-ecb-fault.c b/tests/tcg/s390x/cpacf-km-ecb-fault.c
new file mode 100644
index 0000000000..3fe7df1f04
--- /dev/null
+++ b/tests/tcg/s390x/cpacf-km-ecb-fault.c
@@ -0,0 +1,368 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * Test for register update correctness in cpacf_aes_ecb (KM AES-128 ECB).
+ *
+ * All the CPACF instructions are designed in a way that on exit
+ * the registers are updated so that on incomplete processing (partial
+ * completion) the instruction can just be re-invoked. The QEMU emulation
+ * of the CPACF instructions needs to obey that rule as well.
+ * This testcase checks the correct update of the register values by
+ * triggering a page protection fault in the middle of the data. The
+ * signal handler then checks for the expected register values. After
+ * that the page is enabled for reading, causing the OS to restart the
+ * instruction which continues to process the remaining data. Finally
+ * the encryption result is checked to match the expectations.
+ *
+ * Test sequence:
+ *  1. Allocate two contiguous, page-aligned source pages filled with
+ *     pseudo-random data and two matching destination pages.
+ *  2. Reference run: encrypt both source pages with cpacf_km AES-128 ECB
+ *     into the reference destination buffer (no faults).
+ *  3. Fault run:
+ *     a. Protect the second source page (PROT_NONE).
+ *     b. Install a SIGSEGV handler.
+ *     c. Call cpacf_km over both pages (2 * PAGE_SIZE bytes).
+ *     d. On the SIGSEGV verify:
+ *          - si_addr lies within the second source page.
+ *          - R4 (src address) equals exactly the start of the second source
+ *            page (all blocks of page 1 were already consumed).
+ *          - R5 (remaining src length) equals exactly PAGE_SIZE.
+ *          - R2 (dst address) equals exactly dst_fault + PAGE_SIZE.
+ *     e. Restore PROT_READ on the second source page and return from the
+ *        handler so KM re-executes from the updated registers and finishes.
+ *  4. Compare the fault-run output to the reference output; they must match.
+ *
+ * cpacf_km() in cpacf.h uses pinned registers R2/R4/R5 for its operands,
+ * so the signal handler can read them reliably via ucontext_t.
+ *
+ * Usage: cpacf-km-ecb-fault [-v]
+ *   -v  verbose: print details about each step and every register check.
+ */
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "cpacf.h"
+
+/* AES-128 key used for all encryptions in this test */
+static const uint8_t aes128key[16] = {
+    0xed, 0xfd, 0xb2, 0x57, 0xcb, 0x37, 0xcd, 0xf1,
+    0x82, 0xc5, 0x45, 0x5b, 0x0c, 0x0e, 0xfe, 0xbb
+};
+
+/* Page size, determined at runtime */
+static long page_size;
+
+/* Verbose flag: set by -v on the command line */
+static int verbose;
+
+/*
+ * State shared between main() and the SIGSEGV handler.
+ * volatile prevents the compiler from optimising away accesses.
+ */
+static volatile int           sigsegv_count; /* how many times handler fired */
+static volatile int           sigsegv_pass;  /* 1 = all register checks fine */
+static volatile unsigned long expected_src;  /* exact expected R4 value */
+static volatile unsigned long expected_dst;  /* exact expected R2 value */
+
+/*
+ * SIGSEGV handler.
+ *
+ * At fault time the KM instruction has already advanced its operand registers
+ * past all fully processed blocks. For the second-page fault:
+ *   R2 = dst_fault + PAGE_SIZE  (destination pointer into second output page)
+ *   R4 = src_pages + PAGE_SIZE  (source pointer at start of second source page)
+ *   R5 = PAGE_SIZE              (exactly one page of source data remaining)
+ * Note that this requires using the inline function cpacf_km() from cpacf.h
+ * which uses pinned registers for the parameters and this has to be in
+ * alignment with the code here.
+ *
+ * After verifying these values the handler restores read permission on the
+ * second source page and returns. The signal return mechanism re-executes
+ * the KM instruction from the updated register state, completing the run.
+ */
+static void sigsegv_handler(int sig, siginfo_t *si, void *uctx_arg)
+{
+    /*
+     * No printf within signal handler, but write() can be used. So this
+     * little sig_printf() macro is a replacement to fprintf(stderr, ...)
+     */
+#define sig_printf(...) do { \
+        char printfbuf[256]; \
+        int len = snprintf(printfbuf, sizeof(printfbuf), __VA_ARGS__); \
+        write(STDERR_FILENO, printfbuf, len); \
+    } while (0)
+
+    ucontext_t *uc = (ucontext_t *)uctx_arg;
+    unsigned long r2, r4, r5;
+    int pass = 1;
+
+    sigsegv_count++;
+
+    /*
+     * On s390x, glibc's mcontext_t exposes the GPRs as gregs[].
+     */
+    r2 = uc->uc_mcontext.gregs[2];  /* KM destination address register */
+    r4 = uc->uc_mcontext.gregs[4];  /* KM source address register      */
+    r5 = uc->uc_mcontext.gregs[5];  /* KM source length register       */
+
+    if (verbose) {
+        sig_printf("  SIGSEGV #%d: si_addr=0x%lx\n",
+                   sigsegv_count, (unsigned long)si->si_addr);
+        sig_printf("    R2 (dst addr):  0x%lx  (expected 0x%lx)\n",
+                   r2, expected_dst);
+        sig_printf("    R4 (src addr):  0x%lx  (expected 0x%lx)\n",
+                   r4, expected_src);
+        sig_printf("    R5 (src len):   0x%lx  (expected 0x%lx = PAGE_SIZE)\n",
+                   r5, (unsigned long)page_size);
+    }
+
+    /* R4 must point exactly to the start of the second source page */
+    if (r4 != expected_src) {
+        sig_printf("FAIL: R4 (src addr) = 0x%lx, expected 0x%lx\n",
+                   r4, expected_src);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R4 check: PASS\n");
+    }
+
+    /* R5 must equal exactly PAGE_SIZE (one full page remaining) */
+    if (r5 != (unsigned long)page_size) {
+        sig_printf("FAIL: R5 (src len) = 0x%lx, expected PAGE_SIZE = 0x%lx\n",
+                   r5, (unsigned long)page_size);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R5 check: PASS\n");
+    }
+
+    /* R2 must point exactly to dst_fault + PAGE_SIZE */
+    if (r2 != expected_dst) {
+        sig_printf("FAIL: R2 (dst addr) = 0x%lx, expected 0x%lx\n",
+                   r2, expected_dst);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R2 check: PASS\n");
+    }
+
+    sigsegv_pass = pass;
+
+    if (verbose) {
+        sig_printf("  restoring PROT_READ on page at 0x%lx, resuming KM\n",
+                   expected_src);
+    }
+
+    /* Restore read access so the restarted KM can read the second page */
+    mprotect((void *)expected_src, page_size, PROT_READ);
+
+#undef sig_printf
+}
+
+int main(int argc, char *argv[])
+{
+    struct sigaction sa, old_sa;
+    uint8_t *src_pages, *dst_ref, *dst_fault;
+    uint8_t param[16];       /* AES-128 parameter block (key only for ECB) */
+    unsigned long cc;
+    int rc = 0;
+
+    if (argc == 2 && strcmp(argv[1], "-v") == 0) {
+        verbose = 1;
+    } else if (argc > 1) {
+        fprintf(stderr, "usage: %s [-v]\n", argv[0]);
+        return EXIT_FAILURE;
+    }
+
+    page_size = getpagesize();
+
+    if (verbose) {
+        printf("page_size = %ld (0x%lx)\n", page_size, page_size);
+    }
+
+    /*
+     * Allocate two contiguous page-aligned source pages and fill them with
+     * a deterministic pseudo-random pattern so the test is reproducible.
+     */
+    src_pages = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (src_pages == MAP_FAILED) {
+        perror("mmap src_pages");
+        return EXIT_FAILURE;
+    }
+    for (long i = 0; i < 2 * page_size; i++) {
+        src_pages[i] = (uint8_t)(i * 37 + 13);
+    }
+
+    /* Reference destination: two contiguous pages, initially zeroed */
+    dst_ref = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_ref == MAP_FAILED) {
+        perror("mmap dst_ref");
+        munmap(src_pages, 2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    /* Fault-run destination: two contiguous pages, initially zeroed */
+    dst_fault = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_fault == MAP_FAILED) {
+        perror("mmap dst_fault");
+        munmap(src_pages, 2 * page_size);
+        munmap(dst_ref,   2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    if (verbose) {
+        printf("src_pages: [0x%lx, 0x%lx)  page1=[0x%lx, 0x%lx)  page2=[0x%lx, 0x%lx)\n",
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + 2 * page_size),
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + 2 * page_size));
+        printf("dst_ref:   [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_ref,
+               (unsigned long)(dst_ref + 2 * page_size));
+        printf("dst_fault: [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_fault,
+               (unsigned long)(dst_fault + 2 * page_size));
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Reference run: encrypt both pages with no fault injection.         */
+    /* ------------------------------------------------------------------ */
+
+    if (verbose) {
+        printf("reference run: cpacf_km AES-128 ECB over 2 pages (no faults)\n");
+    }
+
+    memcpy(param, aes128key, sizeof(aes128key));
+    cpacf_km(CPACF_KM_AES_128, param, dst_ref, src_pages, 2 * page_size, &cc);
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: reference run unexpected cc=%lu\n", cc);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("reference run: done, cc=0\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Fault run: protect second source page, run KM over both pages.     */
+    /* ------------------------------------------------------------------ */
+
+    /* Record the exact register values we expect at fault time */
+    expected_src = (unsigned long)(src_pages + page_size);
+    expected_dst = (unsigned long)(dst_fault + page_size);
+    sigsegv_count = 0;
+    sigsegv_pass  = 1;   /* handler sets to 0 on any check failure */
+
+    if (verbose) {
+        printf("fault run: expecting SIGSEGV when KM reaches src page2 at 0x%lx\n",
+               expected_src);
+        printf("fault run: expected register state at fault:\n");
+        printf("  R2 (dst addr) = 0x%lx\n", expected_dst);
+        printf("  R4 (src addr) = 0x%lx\n", expected_src);
+        printf("  R5 (src len)  = 0x%lx\n", (unsigned long)page_size);
+    }
+
+    /* Install SIGSEGV handler */
+    memset(&sa, 0, sizeof(sa));
+    sa.sa_sigaction = sigsegv_handler;
+    sa.sa_flags     = SA_SIGINFO;
+    sigemptyset(&sa.sa_mask);
+    if (sigaction(SIGSEGV, &sa, &old_sa) != 0) {
+        perror("sigaction");
+        rc = 1;
+        goto out;
+    }
+
+    /* Protect the second source page to provoke a fault during KM */
+    if (mprotect(src_pages + page_size, page_size, PROT_NONE) != 0) {
+        perror("mprotect PROT_NONE");
+        sigaction(SIGSEGV, &old_sa, NULL);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("fault run: second src page protected, starting cpacf_km\n");
+    }
+
+    /*
+     * Encrypt both pages with a single cpacf_km call.
+     *
+     * The first PAGE_SIZE bytes (page 1) are processed normally; the
+     * registers are advanced block-by-block inside cpacf_aes_ecb. On the
+     * first read of the second source page the CPU takes a protection fault.
+     * The signal handler verifies R2/R4/R5 and restores PROT_READ. On
+     * return from the handler the KM instruction is restarted with the
+     * already-advanced registers so it processes only the second page and
+     * completes with CC=0.
+     *
+     * The brc 1,0b loop inside cpacf_km handles the unrelated CC=3
+     * (partial-completion) case and is not triggered by the page fault.
+     */
+    memcpy(param, aes128key, sizeof(aes128key));
+    cpacf_km(CPACF_KM_AES_128, param, dst_fault, src_pages, 2 * page_size, &cc);
+
+    /* Restore the original SIGSEGV disposition */
+    sigaction(SIGSEGV, &old_sa, NULL);
+
+    if (verbose) {
+        printf("fault run: cpacf_km returned, cc=%lu, SIGSEGV count=%d\n",
+               cc, sigsegv_count);
+    }
+
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: fault run unexpected cc=%lu\n", cc);
+        rc = 1;
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: signal handler must have fired exactly once.               */
+    /* ------------------------------------------------------------------ */
+    if (sigsegv_count != 1) {
+        fprintf(stderr, "FAIL: expected 1 SIGSEGV, got %d\n", sigsegv_count);
+        rc = 1;
+    } else if (verbose) {
+        printf("check: SIGSEGV count = %d (expected 1): PASS\n", sigsegv_count);
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: register values inside the handler were correct.           */
+    /* ------------------------------------------------------------------ */
+    if (!sigsegv_pass) {
+        fprintf(stderr, "FAIL: register value check in SIGSEGV handler failed\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: register values in SIGSEGV handler: PASS\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: fault-run ciphertext matches the reference ciphertext.     */
+    /* ------------------------------------------------------------------ */
+    if (memcmp(dst_ref, dst_fault, 2 * page_size) != 0) {
+        fprintf(stderr, "FAIL: fault-run ciphertext does not match reference\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: fault-run ciphertext matches reference ciphertext: PASS\n");
+    }
+
+    if (rc == 0) {
+        printf("cpacf-km-ecb-fault: all checks passed\n");
+    }
+
+out:
+    munmap(src_pages, 2 * page_size);
+    munmap(dst_ref,   2 * page_size);
+    munmap(dst_fault, 2 * page_size);
+
+    return rc ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/tests/tcg/s390x/cpacf-km-xts-fault.c b/tests/tcg/s390x/cpacf-km-xts-fault.c
new file mode 100644
index 0000000000..1d0e70f910
--- /dev/null
+++ b/tests/tcg/s390x/cpacf-km-xts-fault.c
@@ -0,0 +1,511 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * Test for register and tweak update correctness in cpacf_aes_xts
+ * (KM AES-128 XTS).
+ *
+ * All the CPACF instructions are designed in a way that on exit
+ * the registers and associated memory (like a running XTS tweak) are
+ * updated so that on incomplete processing (partial completion) the
+ * instruction can just be re-invoked. The QEMU emulation of the CPACF
+ * instructions needs to obey that rule as well.
+ * This testcase checks the correct update of the register values and
+ * tweak in memory by triggering a page protection fault in the middle
+ * of the data. The signal handler then checks for the expected register
+ * and memory values. After that the page is enabled for reading,
+ * causing the OS to restart the instruction which continues to process
+ * the remaining data. Finally the encryption result is checked to
+ * match the expectations.
+ *
+ * Test sequence:
+ *  1. Allocate two contiguous, page-aligned source pages filled with
+ *     pseudo-random data and two matching destination pages.
+ *  2. Compute the initial XTS tweak value by encrypting a sector number
+ *     block with key2 using plain AES-128 ECB (as specified by XTS-AES).
+ *  3. Reference run - two steps to capture the intermediate tweak:
+ *     a. Encrypt page 1 only with cpacf_km KM_XTS_128 into dst_ref.
+ *        After this call param_ref[16..31] contains the running tweak for
+ *        the first block of page 2. Save this as expected_tweak[].
+ *     b. Encrypt page 2 with the same parameter block (tweak already
+ *        advanced) into dst_ref + PAGE_SIZE.
+ *  4. Fault run:
+ *     a. Protect the second source page (PROT_NONE).
+ *     b. Install a SIGSEGV handler.
+ *     c. Call cpacf_km with KM_XTS_128 over both pages in one shot.
+ *     d. On the SIGSEGV verify:
+ *          - R4 (src address) equals exactly the start of the second source
+ *            page (all blocks of page 1 were already consumed).
+ *          - R5 (remaining src length) equals exactly PAGE_SIZE.
+ *          - R2 (dst address) equals exactly dst_fault + PAGE_SIZE.
+ *          - param_fault[16..31] equals expected_tweak[], proving that
+ *            cpacf_aes_xts wrote the correct advanced tweak back into the
+ *            parameter block before the fault.
+ *     e. Restore PROT_READ on the second source page and return from the
+ *        handler so KM re-executes from the updated registers and tweak,
+ *        finishing the second page.
+ *  5. Compare the fault-run output to the reference output; they must match.
+ *
+ * cpacf_km() in cpacf.h uses pinned registers R2/R4/R5 for its operands,
+ * so the signal handler can read them reliably via ucontext_t.
+ *
+ * Usage: cpacf-km-xts-fault [-v]
+ *   -v  verbose: print details about each step and every check.
+ */
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "cpacf.h"
+
+#define AES_BLOCK_SIZE  16
+
+/*
+ * XTS-128 uses two AES-128 keys.
+ *   key1 is used to encrypt/decrypt the data blocks.
+ *   key2 is used once to derive the initial tweak from the sector number.
+ */
+static const uint8_t xts128key1[16] = {
+    0xa1, 0xb9, 0x0c, 0xba, 0x3f, 0x06, 0xac, 0x35,
+    0x3b, 0x2c, 0x34, 0x38, 0x76, 0x08, 0x17, 0x62
+};
+static const uint8_t xts128key2[16] = {
+    0x09, 0x09, 0x23, 0x02, 0x6e, 0x91, 0x77, 0x18,
+    0x15, 0xf2, 0x9d, 0xab, 0x01, 0x93, 0x2f, 0x2f
+};
+/* Sector number block used to derive the initial tweak */
+static const uint8_t xts128sect[16] = {
+    0x4f, 0xae, 0xf7, 0x11, 0x7c, 0xda, 0x59, 0xc6,
+    0x6e, 0x4b, 0x92, 0x01, 0x3e, 0x76, 0x8a, 0xd5
+};
+
+/* Page size, determined at runtime */
+static long page_size;
+
+/* Verbose flag: set by -v on the command line */
+static int verbose;
+
+/*
+ * State shared between main() and the SIGSEGV handler.
+ * volatile prevents the compiler from optimising away accesses.
+ */
+static volatile int           sigsegv_count; /* how many times handler fired */
+static volatile int           sigsegv_pass;  /* 1 = all checks passed */
+static volatile unsigned long expected_src;  /* exact expected R4 value */
+static volatile unsigned long expected_dst;  /* exact expected R2 value */
+static volatile uint8_t *fault_param;        /* param block used in fault run */
+static uint8_t           expected_tweak[AES_BLOCK_SIZE]; /* tweak after pg 1 */
+
+/*
+ * SIGSEGV handler.
+ *
+ * At fault time the KM instruction has already processed all blocks of the
+ * first source page and updated registers and parameter block accordingly.
+ * For the second-page fault:
+ *   R2 = dst_fault + PAGE_SIZE   (destination pointer into second output page)
+ *   R4 = src_pages + PAGE_SIZE   (src pointer at start of second source page)
+ *   R5 = PAGE_SIZE               (exactly one page of source data remaining)
+ *   fault_param[keysize..keysize+15] = tweak for first block of page 2
+ *
+ * After verifying these values the handler restores read permission on the
+ * second source page and returns. The signal return mechanism re-executes
+ * the KM instruction from the updated register state and tweak, completing
+ * the second page.
+ */
+static void sigsegv_handler(int sig, siginfo_t *si, void *uctx_arg)
+{
+    /*
+     * No printf within signal handler, but write() can be used. So this
+     * little sig_printf() macro is a replacement to fprintf(stderr, ...)
+     */
+#define sig_printf(...) do { \
+        char printfbuf[256]; \
+        int len = snprintf(printfbuf, sizeof(printfbuf), __VA_ARGS__); \
+        write(STDERR_FILENO, printfbuf, len); \
+    } while (0)
+
+    ucontext_t *uc = (ucontext_t *)uctx_arg;
+    unsigned long r2, r4, r5;
+    int pass = 1;
+
+    sigsegv_count++;
+
+    /*
+     * On s390x, glibc's mcontext_t exposes the GPRs as gregs[].
+     */
+    r2 = uc->uc_mcontext.gregs[2];  /* KM destination address register */
+    r4 = uc->uc_mcontext.gregs[4];  /* KM source address register      */
+    r5 = uc->uc_mcontext.gregs[5];  /* KM source length register       */
+
+    if (verbose) {
+        sig_printf("  SIGSEGV #%d: si_addr=0x%lx\n",
+                   sigsegv_count, (unsigned long)si->si_addr);
+        sig_printf("    R2 (dst addr):  0x%lx  (expected 0x%lx)\n",
+                   r2, expected_dst);
+        sig_printf("    R4 (src addr):  0x%lx  (expected 0x%lx)\n",
+                   r4, expected_src);
+        sig_printf("    R5 (src len):   0x%lx  (expected 0x%lx = PAGE_SIZE)\n",
+                   r5, (unsigned long)page_size);
+        /* tweak is at param[keysize..keysize+15]; keysize=16 for XTS-128 */
+        sig_printf("    tweak in param block: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", ((uint8_t *)fault_param)[AES_BLOCK_SIZE + i]);
+        }
+        sig_printf("\n");
+        sig_printf("    expected tweak:       ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", expected_tweak[i]);
+        }
+        sig_printf("\n");
+    }
+
+    /* R4 must point exactly to the start of the second source page */
+    if (r4 != expected_src) {
+        sig_printf("FAIL: R4 (src addr) = 0x%lx, expected 0x%lx\n",
+                   r4, expected_src);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R4 check: PASS\n");
+    }
+
+    /* R5 must equal exactly PAGE_SIZE (one full page remaining) */
+    if (r5 != (unsigned long)page_size) {
+        sig_printf("FAIL: R5 (src len) = 0x%lx, expected PAGE_SIZE = 0x%lx\n",
+                   r5, (unsigned long)page_size);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R5 check: PASS\n");
+    }
+
+    /* R2 must point exactly to dst_fault + PAGE_SIZE */
+    if (r2 != expected_dst) {
+        sig_printf("FAIL: R2 (dst addr) = 0x%lx, expected 0x%lx\n",
+                   r2, expected_dst);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R2 check: PASS\n");
+    }
+
+    /*
+     * The tweak at fault_param[AES_BLOCK_SIZE..2*AES_BLOCK_SIZE-1] must
+     * equal expected_tweak[], i.e. the tweak that cpacf_aes_xts wrote back
+     * after processing the last block of page 1 (= tweak for first block of
+     * page 2).
+     */
+    if (memcmp((void *)(fault_param + AES_BLOCK_SIZE),
+               expected_tweak, AES_BLOCK_SIZE) != 0) {
+        sig_printf("FAIL: tweak in param block at fault does not match expected tweak\n");
+        sig_printf("  got:      ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", ((uint8_t *)fault_param)[AES_BLOCK_SIZE + i]);
+        }
+        sig_printf("\n  expected: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", expected_tweak[i]);
+        }
+        sig_printf("\n");
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    tweak check: PASS\n");
+    }
+
+    sigsegv_pass = pass;
+
+    if (verbose) {
+        sig_printf("  restoring PROT_READ on page at 0x%lx, resuming KM\n",
+                   expected_src);
+    }
+
+    /* Restore read access so the restarted KM can read the second page */
+    mprotect((void *)expected_src, page_size, PROT_READ);
+
+#undef sig_printf
+}
+
+/*
+ * Build a KM XTS-128 parameter block at buf[]:
+ *   buf[0..15]  = key1
+ *   buf[16..31] = initial tweak (computed from sector number)
+ *
+ * The initial tweak is derived by encrypting the sector number block with
+ * key2 using plain AES-128 ECB, as specified by the XTS-AES standard.
+ */
+static int build_xts128_param(uint8_t *buf)
+{
+    uint8_t key2_param[16];
+    unsigned long cc = 0;
+
+    memcpy(key2_param, xts128key2, sizeof(xts128key2));
+    cpacf_km(CPACF_KM_AES_128, key2_param, buf + AES_BLOCK_SIZE,
+             xts128sect, AES_BLOCK_SIZE, &cc);
+    if (cc != 0) {
+        return -1;
+    }
+    memcpy(buf, xts128key1, sizeof(xts128key1));
+    return 0;
+}
+
+int main(int argc, char *argv[])
+{
+    struct sigaction sa, old_sa;
+    uint8_t *src_pages, *dst_ref, *dst_fault;
+    /* KM XTS-128 parameter block: [key1(16)][tweak(16)] = 32 bytes */
+    uint8_t param_ref[32];
+    uint8_t param_fault[32];
+    unsigned long cc;
+    int rc = 0;
+
+    if (argc == 2 && strcmp(argv[1], "-v") == 0) {
+        verbose = 1;
+    } else if (argc > 1) {
+        fprintf(stderr, "usage: %s [-v]\n", argv[0]);
+        return EXIT_FAILURE;
+    }
+
+    page_size = getpagesize();
+
+    if (verbose) {
+        printf("page_size = %ld (0x%lx)\n", page_size, page_size);
+    }
+
+    /*
+     * Allocate two contiguous page-aligned source pages and fill them with
+     * a deterministic pseudo-random pattern so the test is reproducible.
+     */
+    src_pages = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (src_pages == MAP_FAILED) {
+        perror("mmap src_pages");
+        return EXIT_FAILURE;
+    }
+    for (long i = 0; i < 2 * page_size; i++) {
+        src_pages[i] = (uint8_t)(i * 37 + 13);
+    }
+
+    /* Reference destination: two contiguous pages, initially zeroed */
+    dst_ref = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_ref == MAP_FAILED) {
+        perror("mmap dst_ref");
+        munmap(src_pages, 2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    /* Fault-run destination: two contiguous pages, initially zeroed */
+    dst_fault = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_fault == MAP_FAILED) {
+        perror("mmap dst_fault");
+        munmap(src_pages, 2 * page_size);
+        munmap(dst_ref,   2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    if (verbose) {
+        printf("src_pages: [0x%lx, 0x%lx)  page1=[0x%lx, 0x%lx)  page2=[0x%lx, 0x%lx)\n",
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + 2 * page_size),
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + 2 * page_size));
+        printf("dst_ref:   [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_ref,
+               (unsigned long)(dst_ref + 2 * page_size));
+        printf("dst_fault: [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_fault,
+               (unsigned long)(dst_fault + 2 * page_size));
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Reference run - step 1: encrypt page 1 only.                       */
+    /*                                                                     */
+    /* After this call param_ref[16..31] contains the running tweak for   */
+    /* the first block of page 2. Save it as expected_tweak[] so the      */
+    /* signal handler can verify the fault-run param block matches.       */
+    /* ------------------------------------------------------------------ */
+
+    if (build_xts128_param(param_ref) != 0) {
+        fprintf(stderr, "FAIL: initial tweak derivation failed\n");
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("reference run step 1: cpacf_km KM_XTS_128, page 1 only\n");
+        printf("  initial tweak: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            printf("%02x", param_ref[AES_BLOCK_SIZE + i]);
+        }
+        printf("\n");
+    }
+
+    cpacf_km(CPACF_KM_XTS_128, param_ref, dst_ref, src_pages, page_size, &cc);
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: reference run step 1 unexpected cc=%lu\n", cc);
+        rc = 1;
+        goto out;
+    }
+
+    /* Capture the running tweak after page 1 - this is in param_ref[16..31] */
+    memcpy(expected_tweak, param_ref + AES_BLOCK_SIZE, AES_BLOCK_SIZE);
+
+    if (verbose) {
+        printf("reference run step 1: done, cc=0\n");
+        printf("  running tweak after page 1 (= expected_tweak): ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            printf("%02x", expected_tweak[i]);
+        }
+        printf("\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Reference run - step 2: encrypt page 2 with the advanced tweak.   */
+    /* param_ref already holds the updated tweak from step 1.             */
+    /* ------------------------------------------------------------------ */
+
+    if (verbose) {
+        printf("reference run step 2: cpacf_km KM_XTS_128, page 2 only\n");
+    }
+
+    cpacf_km(CPACF_KM_XTS_128, param_ref, dst_ref + page_size,
+             src_pages + page_size, page_size, &cc);
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: reference run step 2 unexpected cc=%lu\n", cc);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("reference run step 2: done, cc=0\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Fault run: protect second source page, run KM over both pages.     */
+    /* ------------------------------------------------------------------ */
+
+    if (build_xts128_param(param_fault) != 0) {
+        fprintf(stderr, "FAIL: fault param derivation failed\n");
+        rc = 1;
+        goto out;
+    }
+
+    /* Record the exact values we expect at fault time */
+    expected_src  = (unsigned long)(src_pages + page_size);
+    expected_dst  = (unsigned long)(dst_fault + page_size);
+    fault_param   = param_fault;
+    sigsegv_count = 0;
+    sigsegv_pass  = 1;   /* handler sets to 0 on any check failure */
+
+    if (verbose) {
+        printf("fault run: expecting SIGSEGV when KM reaches src page2 at 0x%lx\n",
+               expected_src);
+        printf("fault run: expected register state at fault:\n");
+        printf("  R2 (dst addr) = 0x%lx\n", expected_dst);
+        printf("  R4 (src addr) = 0x%lx\n", expected_src);
+        printf("  R5 (src len)  = 0x%lx\n", (unsigned long)page_size);
+        printf("fault run: expected tweak in param block at fault: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            printf("%02x", expected_tweak[i]);
+        }
+        printf("\n");
+    }
+
+    /* Install SIGSEGV handler */
+    memset(&sa, 0, sizeof(sa));
+    sa.sa_sigaction = sigsegv_handler;
+    sa.sa_flags     = SA_SIGINFO;
+    sigemptyset(&sa.sa_mask);
+    if (sigaction(SIGSEGV, &sa, &old_sa) != 0) {
+        perror("sigaction");
+        rc = 1;
+        goto out;
+    }
+
+    /* Protect the second source page to provoke a fault during KM */
+    if (mprotect(src_pages + page_size, page_size, PROT_NONE) != 0) {
+        perror("mprotect PROT_NONE");
+        sigaction(SIGSEGV, &old_sa, NULL);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("fault run: second src page protected, starting cpacf_km\n");
+    }
+
+    /*
+     * Encrypt both pages with a single cpacf_km XTS call.
+     *
+     * Page 1 is processed normally; registers and the tweak in param_fault
+     * are advanced block-by-block inside cpacf_aes_xts. On the first read
+     * of the second source page the CPU takes a protection fault.
+     * The signal handler verifies R2/R4/R5 and the tweak, then restores
+     * PROT_READ. On return from the handler the KM instruction is restarted
+     * with the already-advanced registers and correct tweak, so it processes
+     * only the second page and completes with CC=0.
+     *
+     * The brc 1,0b loop inside cpacf_km handles the unrelated CC=3
+     * (partial-completion) case and is not triggered by the page fault.
+     */
+    cpacf_km(CPACF_KM_XTS_128, param_fault, dst_fault,
+             src_pages, 2 * page_size, &cc);
+
+    /* Restore the original SIGSEGV disposition */
+    sigaction(SIGSEGV, &old_sa, NULL);
+
+    if (verbose) {
+        printf("fault run: cpacf_km returned, cc=%lu, SIGSEGV count=%d\n",
+               cc, sigsegv_count);
+    }
+
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: fault run unexpected cc=%lu\n", cc);
+        rc = 1;
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: signal handler must have fired exactly once.               */
+    /* ------------------------------------------------------------------ */
+    if (sigsegv_count != 1) {
+        fprintf(stderr, "FAIL: expected 1 SIGSEGV, got %d\n", sigsegv_count);
+        rc = 1;
+    } else if (verbose) {
+        printf("check: SIGSEGV count = %d (expected 1): PASS\n", sigsegv_count);
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: register and tweak checks inside the handler were correct. */
+    /* ------------------------------------------------------------------ */
+    if (!sigsegv_pass) {
+        fprintf(stderr, "FAIL: register/tweak check in SIGSEGV handler failed\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: register and tweak values in SIGSEGV handler: PASS\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: fault-run ciphertext matches the reference ciphertext.     */
+    /* ------------------------------------------------------------------ */
+    if (memcmp(dst_ref, dst_fault, 2 * page_size) != 0) {
+        fprintf(stderr, "FAIL: fault-run ciphertext does not match reference\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: fault-run ciphertext matches reference ciphertext: PASS\n");
+    }
+
+    if (rc == 0) {
+        printf("cpacf-km-xts-fault: all checks passed\n");
+    }
+
+out:
+    munmap(src_pages, 2 * page_size);
+    munmap(dst_ref,   2 * page_size);
+    munmap(dst_fault, 2 * page_size);
+
+    return rc ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/tests/tcg/s390x/cpacf-kmc-cbc-fault.c b/tests/tcg/s390x/cpacf-kmc-cbc-fault.c
new file mode 100644
index 0000000000..27e15c80ed
--- /dev/null
+++ b/tests/tcg/s390x/cpacf-kmc-cbc-fault.c
@@ -0,0 +1,472 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * Test for register and IV update correctness in cpacf_aes_cbc
+ * (KMC AES-128 CBC).
+ *
+ * All the CPACF instructions are designed in a way that on exit
+ * the registers and associated memory (like an IV) are updated so
+ * that on incomplete processing (partial completion) the instruction
+ * can just be re-invoked. The QEMU emulation of the CPACF instructions
+ * needs to obey that rule as well.
+ * This testcase checks the correct update of the register values and
+ * IV in memory by triggering a page protection fault in the middle of
+ * the data. The signal handler then checks for the expected register
+ * and memory values. After that the page is enabled for reading,
+ * causing the OS to restart the instruction which continues to process
+ * the remaining data. Finally the encryption result is checked to
+ * match the expectations.
+ *
+ * Test sequence:
+ *  1. Allocate two contiguous, page-aligned source pages filled with
+ *     pseudo-random data and two matching destination pages.
+ *  2. Reference run - two steps to capture the intermediate IV:
+ *     a. Encrypt page 1 only with cpacf_kmc AES-128 CBC into dst_ref.
+ *        After this call the IV in the parameter block has been updated
+ *        to the running IV after the last block of page 1. Save this IV
+ *        as expected_iv[].
+ *     b. Encrypt page 2 with the same parameter block (IV already advanced)
+ *        into dst_ref + PAGE_SIZE.
+ *  3. Fault run:
+ *     a. Protect the second source page (PROT_NONE).
+ *     b. Install a SIGSEGV handler.
+ *     c. Call cpacf_kmc over both pages in one shot (2 * PAGE_SIZE bytes).
+ *     d. On the SIGSEGV verify:
+ *          - R4 (src address) equals exactly the start of the second source
+ *            page (all blocks of page 1 were already consumed).
+ *          - R5 (remaining src length) equals exactly PAGE_SIZE.
+ *          - R2 (dst address) equals exactly dst_fault + PAGE_SIZE.
+ *          - The IV at param_fault[0..15] equals expected_iv[], proving
+ *            that cpacf_aes_cbc wrote the correct running IV back into the
+ *            parameter block before the fault.
+ *     e. Restore PROT_READ on the second source page and return from the
+ *        handler so KMC re-executes from the updated registers and IV,
+ *        finishing the second page.
+ *  4. Compare the fault-run output to the reference output; they must match.
+ *
+ * cpacf_kmc() in cpacf.h uses pinned registers R2/R4/R5 for its operands,
+ * so the signal handler can read them reliably via ucontext_t.
+ *
+ * Usage: cpacf-kmc-cbc-fault [-v]
+ *   -v  verbose: print details about each step and every check.
+ */
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "cpacf.h"
+
+#define AES_BLOCK_SIZE  16
+
+/* AES-128 key and initial IV used for all encryptions in this test */
+static const uint8_t aes128key[16] = {
+    0x1f, 0x8e, 0x49, 0x73, 0x95, 0x3f, 0x3f, 0xb0,
+    0xbd, 0x6b, 0x16, 0x66, 0x2e, 0x9a, 0x3c, 0x17
+};
+static const uint8_t initial_iv[16] = {
+    0x2f, 0xe2, 0xb3, 0x33, 0xce, 0xda, 0x8f, 0x98,
+    0xf4, 0xa9, 0x9b, 0x40, 0xd2, 0xcd, 0x34, 0xa8
+};
+
+/* Page size, determined at runtime */
+static long page_size;
+
+/* Verbose flag: set by -v on the command line */
+static int verbose;
+
+/*
+ * State shared between main() and the SIGSEGV handler.
+ * volatile prevents the compiler from optimising away accesses.
+ */
+static volatile int           sigsegv_count; /* how many times handler fired */
+static volatile int           sigsegv_pass;  /* 1 = all checks passed */
+static volatile unsigned long expected_src;  /* exact expected R4 value */
+static volatile unsigned long expected_dst;  /* exact expected R2 value */
+static volatile uint8_t      *fault_param;   /* param block used in fault run */
+static uint8_t                expected_iv[AES_BLOCK_SIZE]; /* IV after page 1 */
+
+/*
+ * SIGSEGV handler.
+ *
+ * At fault time the KMC instruction has already processed all blocks of the
+ * first source page and updated registers and parameter block accordingly.
+ * For the second-page fault:
+ *   R2 = dst_fault + PAGE_SIZE  (destination pointer into second output page)
+ *   R4 = src_pages + PAGE_SIZE  (source pointer at start of second source page)
+ *   R5 = PAGE_SIZE              (exactly one page of source data remaining)
+ *   fault_param[0..15]          (IV in param block = running IV after page 1)
+ *
+ * After verifying these values the handler restores read permission on the
+ * second source page and returns. The signal return mechanism re-executes
+ * the KMC instruction from the updated register state and IV, completing
+ * the second page.
+ */
+static void sigsegv_handler(int sig, siginfo_t *si, void *uctx_arg)
+{
+    /*
+     * No printf within signal handler, but write() can be used. So this
+     * little sig_printf() macro is a replacement to fprintf(stderr, ...)
+     */
+#define sig_printf(...) do { \
+        char printfbuf[256]; \
+        int len = snprintf(printfbuf, sizeof(printfbuf), __VA_ARGS__); \
+        write(STDERR_FILENO, printfbuf, len); \
+    } while (0)
+
+    ucontext_t *uc = (ucontext_t *)uctx_arg;
+    unsigned long r2, r4, r5;
+    int pass = 1;
+
+    sigsegv_count++;
+
+    /*
+     * On s390x, glibc's mcontext_t exposes the GPRs as gregs[].
+     */
+    r2 = uc->uc_mcontext.gregs[2];  /* KMC destination address register */
+    r4 = uc->uc_mcontext.gregs[4];  /* KMC source address register      */
+    r5 = uc->uc_mcontext.gregs[5];  /* KMC source length register       */
+
+    if (verbose) {
+        sig_printf("  SIGSEGV #%d: si_addr=0x%lx\n",
+                   sigsegv_count, (unsigned long)si->si_addr);
+        sig_printf("    R2 (dst addr):  0x%lx  (expected 0x%lx)\n",
+                   r2, expected_dst);
+        sig_printf("    R4 (src addr):  0x%lx  (expected 0x%lx)\n",
+                   r4, expected_src);
+        sig_printf("    R5 (src len):   0x%lx  (expected 0x%lx = PAGE_SIZE)\n",
+                   r5, (unsigned long)page_size);
+        sig_printf("    IV in param block: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", ((uint8_t *)fault_param)[i]);
+        }
+        sig_printf("\n");
+        sig_printf("    expected IV:       ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", expected_iv[i]);
+        }
+        sig_printf("\n");
+    }
+
+    /* R4 must point exactly to the start of the second source page */
+    if (r4 != expected_src) {
+        sig_printf("FAIL: R4 (src addr) = 0x%lx, expected 0x%lx\n",
+                   r4, expected_src);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R4 check: PASS\n");
+    }
+
+    /* R5 must equal exactly PAGE_SIZE (one full page remaining) */
+    if (r5 != (unsigned long)page_size) {
+        sig_printf("FAIL: R5 (src len) = 0x%lx, expected PAGE_SIZE = 0x%lx\n",
+                   r5, (unsigned long)page_size);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R5 check: PASS\n");
+    }
+
+    /* R2 must point exactly to dst_fault + PAGE_SIZE */
+    if (r2 != expected_dst) {
+        sig_printf("FAIL: R2 (dst addr) = 0x%lx, expected 0x%lx\n",
+                   r2, expected_dst);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R2 check: PASS\n");
+    }
+
+    /*
+     * The IV at param_fault[0..15] must equal expected_iv[], i.e. the
+     * running IV that cpacf_aes_cbc wrote back after consuming page 1.
+     */
+    if (memcmp((void *)fault_param, expected_iv, AES_BLOCK_SIZE) != 0) {
+        sig_printf("FAIL: IV in param block at fault does not match expected IV\n");
+        sig_printf("  got:      ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", ((uint8_t *)fault_param)[i]);
+        }
+        sig_printf("\n  expected: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            sig_printf("%02x", expected_iv[i]);
+        }
+        sig_printf("\n");
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    IV check: PASS\n");
+    }
+
+    sigsegv_pass = pass;
+
+    if (verbose) {
+        sig_printf("  restoring PROT_READ on page at 0x%lx, resuming KMC\n",
+                   expected_src);
+    }
+
+    /* Restore read access so the restarted KMC can read the second page */
+    mprotect((void *)expected_src, page_size, PROT_READ);
+
+#undef sig_printf
+}
+
+/*
+ * Build a KMC AES-128 parameter block at buf[]:
+ *   buf[0..15]  = iv
+ *   buf[16..31] = key
+ */
+static void build_param(uint8_t *buf, const uint8_t *iv, const uint8_t *key)
+{
+    memcpy(buf,      iv,  AES_BLOCK_SIZE);
+    memcpy(buf + AES_BLOCK_SIZE, key, 16);
+}
+
+int main(int argc, char *argv[])
+{
+    struct sigaction sa, old_sa;
+    uint8_t *src_pages, *dst_ref, *dst_fault;
+    /* parameter blocks: [IV(16)][key(16)] = 32 bytes */
+    uint8_t param_ref[32];
+    uint8_t param_fault[32];
+    unsigned long cc;
+    int rc = 0;
+
+    if (argc == 2 && strcmp(argv[1], "-v") == 0) {
+        verbose = 1;
+    } else if (argc > 1) {
+        fprintf(stderr, "usage: %s [-v]\n", argv[0]);
+        return EXIT_FAILURE;
+    }
+
+    page_size = getpagesize();
+
+    if (verbose) {
+        printf("page_size = %ld (0x%lx)\n", page_size, page_size);
+    }
+
+    /*
+     * Allocate two contiguous page-aligned source pages and fill them with
+     * a deterministic pseudo-random pattern so the test is reproducible.
+     */
+    src_pages = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (src_pages == MAP_FAILED) {
+        perror("mmap src_pages");
+        return EXIT_FAILURE;
+    }
+    for (long i = 0; i < 2 * page_size; i++) {
+        src_pages[i] = (uint8_t)(i * 37 + 13);
+    }
+
+    /* Reference destination: two contiguous pages, initially zeroed */
+    dst_ref = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_ref == MAP_FAILED) {
+        perror("mmap dst_ref");
+        munmap(src_pages, 2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    /* Fault-run destination: two contiguous pages, initially zeroed */
+    dst_fault = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_fault == MAP_FAILED) {
+        perror("mmap dst_fault");
+        munmap(src_pages, 2 * page_size);
+        munmap(dst_ref,   2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    if (verbose) {
+        printf("src_pages: [0x%lx, 0x%lx)  page1=[0x%lx, 0x%lx)  page2=[0x%lx, 0x%lx)\n",
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + 2 * page_size),
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + 2 * page_size));
+        printf("dst_ref:   [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_ref,
+               (unsigned long)(dst_ref + 2 * page_size));
+        printf("dst_fault: [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_fault,
+               (unsigned long)(dst_fault + 2 * page_size));
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Reference run - step 1: encrypt page 1 only.                       */
+    /*                                                                     */
+    /* After this call param_ref[0..15] contains the running IV after the  */
+    /* last block of page 1. Save it as expected_iv[] so the signal handler*/
+    /* can verify the fault-run param block contains the same value.       */
+    /* ------------------------------------------------------------------ */
+
+    build_param(param_ref, initial_iv, aes128key);
+
+    if (verbose) {
+        printf("reference run step 1: cpacf_kmc AES-128 CBC, page 1 only\n");
+    }
+
+    cpacf_kmc(CPACF_KMC_AES_128, param_ref, dst_ref, src_pages, page_size, &cc);
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: reference run step 1 unexpected cc=%lu\n", cc);
+        rc = 1;
+        goto out;
+    }
+
+    /* Capture the running IV after page 1 - this is in param_ref[0..15] */
+    memcpy(expected_iv, param_ref, AES_BLOCK_SIZE);
+
+    if (verbose) {
+        printf("reference run step 1: done, cc=0\n");
+        printf("  running IV after page 1 (= expected_iv): ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            printf("%02x", expected_iv[i]);
+        }
+        printf("\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Reference run - step 2: encrypt page 2 with the advanced IV.       */
+    /* param_ref already holds the updated IV from step 1.                */
+    /* ------------------------------------------------------------------ */
+
+    if (verbose) {
+        printf("reference run step 2: cpacf_kmc AES-128 CBC, page 2 only\n");
+    }
+
+    cpacf_kmc(CPACF_KMC_AES_128, param_ref, dst_ref + page_size,
+              src_pages + page_size, page_size, &cc);
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: reference run step 2 unexpected cc=%lu\n", cc);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("reference run step 2: done, cc=0\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Fault run: protect second source page, run KMC over both pages.    */
+    /* ------------------------------------------------------------------ */
+
+    build_param(param_fault, initial_iv, aes128key);
+
+    /* Record the exact values we expect at fault time */
+    expected_src  = (unsigned long)(src_pages + page_size);
+    expected_dst  = (unsigned long)(dst_fault + page_size);
+    fault_param   = param_fault;
+    sigsegv_count = 0;
+    sigsegv_pass  = 1;   /* handler sets to 0 on any check failure */
+
+    if (verbose) {
+        printf("fault run: expecting SIGSEGV when KMC reaches src page2 at 0x%lx\n",
+               expected_src);
+        printf("fault run: expected register state at fault:\n");
+        printf("  R2 (dst addr) = 0x%lx\n", expected_dst);
+        printf("  R4 (src addr) = 0x%lx\n", expected_src);
+        printf("  R5 (src len)  = 0x%lx\n", (unsigned long)page_size);
+        printf("fault run: expected IV in param block at fault: ");
+        for (int i = 0; i < AES_BLOCK_SIZE; i++) {
+            printf("%02x", expected_iv[i]);
+        }
+        printf("\n");
+    }
+
+    /* Install SIGSEGV handler */
+    memset(&sa, 0, sizeof(sa));
+    sa.sa_sigaction = sigsegv_handler;
+    sa.sa_flags     = SA_SIGINFO;
+    sigemptyset(&sa.sa_mask);
+    if (sigaction(SIGSEGV, &sa, &old_sa) != 0) {
+        perror("sigaction");
+        rc = 1;
+        goto out;
+    }
+
+    /* Protect the second source page to provoke a fault during KMC */
+    if (mprotect(src_pages + page_size, page_size, PROT_NONE) != 0) {
+        perror("mprotect PROT_NONE");
+        sigaction(SIGSEGV, &old_sa, NULL);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("fault run: second src page protected, starting cpacf_kmc\n");
+    }
+
+    /*
+     * Encrypt both pages with a single cpacf_kmc call.
+     *
+     * Page 1 is processed normally; registers and the IV in param_fault
+     * are advanced block-by-block inside cpacf_aes_cbc. On the first read
+     * of the second source page the CPU takes a protection fault.
+     * The signal handler verifies R2/R4/R5 and the IV, then restores
+     * PROT_READ. On return from the handler the KMC instruction is
+     * restarted with the already-advanced registers and correct IV, so it
+     * processes only the second page and completes with CC=0.
+     *
+     * The brc 1,0b loop inside cpacf_kmc handles the unrelated CC=3
+     * (partial-completion) case and is not triggered by the page fault.
+     */
+    cpacf_kmc(CPACF_KMC_AES_128, param_fault, dst_fault,
+              src_pages, 2 * page_size, &cc);
+
+    /* Restore the original SIGSEGV disposition */
+    sigaction(SIGSEGV, &old_sa, NULL);
+
+    if (verbose) {
+        printf("fault run: cpacf_kmc returned, cc=%lu, SIGSEGV count=%d\n",
+               cc, sigsegv_count);
+    }
+
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: fault run unexpected cc=%lu\n", cc);
+        rc = 1;
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: signal handler must have fired exactly once.               */
+    /* ------------------------------------------------------------------ */
+    if (sigsegv_count != 1) {
+        fprintf(stderr, "FAIL: expected 1 SIGSEGV, got %d\n", sigsegv_count);
+        rc = 1;
+    } else if (verbose) {
+        printf("check: SIGSEGV count = %d (expected 1): PASS\n", sigsegv_count);
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: register and IV checks inside the handler were correct.    */
+    /* ------------------------------------------------------------------ */
+    if (!sigsegv_pass) {
+        fprintf(stderr, "FAIL: register/IV check in SIGSEGV handler failed\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: register and IV values in SIGSEGV handler: PASS\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: fault-run ciphertext matches the reference ciphertext.     */
+    /* ------------------------------------------------------------------ */
+    if (memcmp(dst_ref, dst_fault, 2 * page_size) != 0) {
+        fprintf(stderr, "FAIL: fault-run ciphertext does not match reference\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: fault-run ciphertext matches reference ciphertext: PASS\n");
+    }
+
+    if (rc == 0) {
+        printf("cpacf-kmc-cbc-fault: all checks passed\n");
+    }
+
+out:
+    munmap(src_pages, 2 * page_size);
+    munmap(dst_ref,   2 * page_size);
+    munmap(dst_fault, 2 * page_size);
+
+    return rc ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/tests/tcg/s390x/cpacf-kmctr-ctr-fault.c b/tests/tcg/s390x/cpacf-kmctr-ctr-fault.c
new file mode 100644
index 0000000000..70e7fcf7c7
--- /dev/null
+++ b/tests/tcg/s390x/cpacf-kmctr-ctr-fault.c
@@ -0,0 +1,414 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * Test for register update correctness in cpacf_aes_ctr (KMCTR AES-128 CTR).
+ *
+ * All the CPACF instructions are designed in a way that on exit
+ * the registers are updated so that on incomplete processing (partial
+ * completion) the instruction can just be re-invoked. The QEMU emulation
+ * of the CPACF instructions needs to obey that rule as well.
+ * This testcase checks the correct update of the register values by
+ * triggering a page protection fault in the middle of the data. The
+ * signal handler then checks for the expected register values. After
+ * that the page is enabled for reading, causing the OS to restart the
+ * instruction which continues to process the remaining data. Finally
+ * the encryption result is checked to match the expectations.
+ *
+ * Test sequence:
+ *  1. Allocate two contiguous, page-aligned source pages filled with
+ *     pseudo-random data, two matching destination pages, and two
+ *     counter pages filled with sequential counter blocks.
+ *  2. Reference run: encrypt both source pages with cpacf_kmctr AES-128 CTR
+ *     into dst_ref (no faults).
+ *  3. Fault run:
+ *     a. Protect the second source page (PROT_NONE).
+ *     b. Install a SIGSEGV handler.
+ *     c. Call cpacf_kmctr over both pages in one shot (2 * PAGE_SIZE bytes).
+ *     d. On the SIGSEGV verify:
+ *          - R4 (src address) equals exactly the start of the second source
+ *            page (all blocks of page 1 were already consumed).
+ *          - R5 (remaining src length) equals exactly PAGE_SIZE.
+ *          - R2 (dst address) equals exactly dst_fault + PAGE_SIZE.
+ *          - R6 (counter address) equals exactly ctr_pages + PAGE_SIZE,
+ *            proving that cpacf_aes_ctr advanced the counter pointer
+ *            block-by-block through page 1.
+ *     e. Restore PROT_READ on the second source page and return from the
+ *        handler so KMCTR re-executes from the updated registers,
+ *        finishing the second page.
+ *  4. Compare the fault-run output to the reference output; they must match.
+ *
+ * cpacf_km() in cpacf.h uses pinned registers R2/R4/R5 for its operands,
+ * so the signal handler can read them reliably via ucontext_t.
+ *
+ * Usage: cpacf-kmctr-ctr-fault [-v]
+ *   -v  verbose: print details about each step and every check.
+ */
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <ucontext.h>
+#include <unistd.h>
+#include "cpacf.h"
+
+#define AES_BLOCK_SIZE  16
+
+/* AES-128 key used for all encryptions in this test */
+static const uint8_t aes128key[16] = {
+    0xcc, 0x22, 0xda, 0x78, 0x7f, 0x37, 0x57, 0x11,
+    0xc7, 0x63, 0x02, 0xbe, 0xf0, 0x97, 0x9d, 0x8e
+};
+
+/* Page size, determined at runtime */
+static long page_size;
+
+/* Verbose flag: set by -v on the command line */
+static int verbose;
+
+/*
+ * State shared between main() and the SIGSEGV handler.
+ * volatile prevents the compiler from optimising away accesses.
+ */
+static volatile int           sigsegv_count;  /* how many times handler fired */
+static volatile int           sigsegv_pass;   /* 1 = all checks passed */
+static volatile unsigned long expected_src;   /* exact expected R4 value */
+static volatile unsigned long expected_dst;   /* exact expected R2 value */
+static volatile unsigned long expected_ctr;   /* exact expected R6 value */
+
+/*
+ * SIGSEGV handler.
+ *
+ * At fault time the KMCTR instruction has already processed all blocks of the
+ * first source page and advanced all four operand registers accordingly.
+ * For the second-page fault:
+ *   R2 = dst_fault + PAGE_SIZE   (destination pointer into second output page)
+ *   R4 = src_pages + PAGE_SIZE   (source ptr at start of second source page)
+ *   R5 = PAGE_SIZE               (exactly one page of source data remaining)
+ *   R6 = ctr_pages + PAGE_SIZE   (counter ptr at start of second counter page)
+ *
+ * After verifying these values the handler restores read permission on the
+ * second source page and returns. The signal return mechanism re-executes
+ * the KMCTR instruction from the updated register state, completing the run.
+ */
+static void sigsegv_handler(int sig, siginfo_t *si, void *uctx_arg)
+{
+    /*
+     * No printf within signal handler, but write() can be used. So this
+     * little sig_printf() macro is a replacement to fprintf(stderr, ...)
+     */
+#define sig_printf(...) do { \
+        char printfbuf[256]; \
+        int len = snprintf(printfbuf, sizeof(printfbuf), __VA_ARGS__); \
+        write(STDERR_FILENO, printfbuf, len); \
+    } while (0)
+
+    ucontext_t *uc = (ucontext_t *)uctx_arg;
+    unsigned long r2, r4, r5, r6;
+    int pass = 1;
+
+    sigsegv_count++;
+
+    /*
+     * On s390x, glibc's mcontext_t exposes the GPRs as gregs[].
+     */
+    r2 = uc->uc_mcontext.gregs[2];  /* KMCTR destination address register */
+    r4 = uc->uc_mcontext.gregs[4];  /* KMCTR source address register      */
+    r5 = uc->uc_mcontext.gregs[5];  /* KMCTR source length register       */
+    r6 = uc->uc_mcontext.gregs[6];  /* KMCTR counter address register     */
+
+    if (verbose) {
+        sig_printf("  SIGSEGV #%d: si_addr=0x%lx\n",
+                   sigsegv_count, (unsigned long)si->si_addr);
+        sig_printf("    R2 (dst addr):  0x%lx  (expected 0x%lx)\n",
+                   r2, expected_dst);
+        sig_printf("    R4 (src addr):  0x%lx  (expected 0x%lx)\n",
+                   r4, expected_src);
+        sig_printf("    R5 (src len):   0x%lx  (expected 0x%lx = PAGE_SIZE)\n",
+                   r5, (unsigned long)page_size);
+        sig_printf("    R6 (ctr addr):  0x%lx  (expected 0x%lx)\n",
+                   r6, expected_ctr);
+    }
+
+    /* R4 must point exactly to the start of the second source page */
+    if (r4 != expected_src) {
+        sig_printf("FAIL: R4 (src addr) = 0x%lx, expected 0x%lx\n",
+                   r4, expected_src);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R4 check: PASS\n");
+    }
+
+    /* R5 must equal exactly PAGE_SIZE (one full page remaining) */
+    if (r5 != (unsigned long)page_size) {
+        sig_printf("FAIL: R5 (src len) = 0x%lx, expected PAGE_SIZE = 0x%lx\n",
+                   r5, (unsigned long)page_size);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R5 check: PASS\n");
+    }
+
+    /* R2 must point exactly to dst_fault + PAGE_SIZE */
+    if (r2 != expected_dst) {
+        sig_printf("FAIL: R2 (dst addr) = 0x%lx, expected 0x%lx\n",
+                   r2, expected_dst);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R2 check: PASS\n");
+    }
+
+    /* R6 must point exactly to ctr_pages + PAGE_SIZE */
+    if (r6 != expected_ctr) {
+        sig_printf("FAIL: R6 (ctr addr) = 0x%lx, expected 0x%lx\n",
+                   r6, expected_ctr);
+        pass = 0;
+    } else if (verbose) {
+        sig_printf("    R6 check: PASS\n");
+    }
+
+    sigsegv_pass = pass;
+
+    if (verbose) {
+        sig_printf("  restoring PROT_READ on page at 0x%lx, resuming KMCTR\n",
+                   expected_src);
+    }
+
+    /* Restore read access so the restarted KMCTR can read the second page */
+    mprotect((void *)expected_src, page_size, PROT_READ);
+
+#undef sig_printf
+}
+
+int main(int argc, char *argv[])
+{
+    struct sigaction sa, old_sa;
+    uint8_t *src_pages, *dst_ref, *dst_fault, *ctr_pages;
+    /* KMCTR AES-128 parameter block: key only (16 bytes) */
+    uint8_t param[16];
+    unsigned long cc;
+    int rc = 0;
+
+    if (argc == 2 && strcmp(argv[1], "-v") == 0) {
+        verbose = 1;
+    } else if (argc > 1) {
+        fprintf(stderr, "usage: %s [-v]\n", argv[0]);
+        return EXIT_FAILURE;
+    }
+
+    page_size = getpagesize();
+
+    if (verbose) {
+        printf("page_size = %ld (0x%lx)\n", page_size, page_size);
+    }
+
+    /*
+     * Allocate two contiguous page-aligned source pages and fill them with
+     * a deterministic pseudo-random pattern so the test is reproducible.
+     */
+    src_pages = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (src_pages == MAP_FAILED) {
+        perror("mmap src_pages");
+        return EXIT_FAILURE;
+    }
+    for (long i = 0; i < 2 * page_size; i++) {
+        src_pages[i] = (uint8_t)(i * 37 + 13);
+    }
+
+    /*
+     * Allocate two contiguous counter pages. Each AES_BLOCK_SIZE-aligned
+     * slot holds one counter block. Fill with a deterministic pattern that
+     * serves as distinct counter values for each block position.
+     */
+    ctr_pages = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (ctr_pages == MAP_FAILED) {
+        perror("mmap ctr_pages");
+        munmap(src_pages, 2 * page_size);
+        return EXIT_FAILURE;
+    }
+    for (long i = 0; i < 2 * page_size; i++) {
+        ctr_pages[i] = (uint8_t)(i * 7 + 5);
+    }
+
+    /* Reference destination: two contiguous pages, initially zeroed */
+    dst_ref = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_ref == MAP_FAILED) {
+        perror("mmap dst_ref");
+        munmap(src_pages, 2 * page_size);
+        munmap(ctr_pages, 2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    /* Fault-run destination: two contiguous pages, initially zeroed */
+    dst_fault = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE,
+                     MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (dst_fault == MAP_FAILED) {
+        perror("mmap dst_fault");
+        munmap(src_pages, 2 * page_size);
+        munmap(ctr_pages, 2 * page_size);
+        munmap(dst_ref,   2 * page_size);
+        return EXIT_FAILURE;
+    }
+
+    if (verbose) {
+        printf("src_pages: [0x%lx, 0x%lx)  page1=[0x%lx, 0x%lx)  page2=[0x%lx, 0x%lx)\n",
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + 2 * page_size),
+               (unsigned long)src_pages,
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + page_size),
+               (unsigned long)(src_pages + 2 * page_size));
+        printf("ctr_pages: [0x%lx, 0x%lx)\n",
+               (unsigned long)ctr_pages,
+               (unsigned long)(ctr_pages + 2 * page_size));
+        printf("dst_ref:   [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_ref,
+               (unsigned long)(dst_ref + 2 * page_size));
+        printf("dst_fault: [0x%lx, 0x%lx)\n",
+               (unsigned long)dst_fault,
+               (unsigned long)(dst_fault + 2 * page_size));
+    }
+
+    /* Build parameter block: key only for KMCTR AES-128 */
+    memcpy(param, aes128key, sizeof(aes128key));
+
+    /* ------------------------------------------------------------------ */
+    /* Reference run: encrypt both pages with no fault injection.         */
+    /* ------------------------------------------------------------------ */
+
+    if (verbose) {
+        printf("reference run: cpacf_kmctr AES-128 CTR over 2 pages (no faults)\n");
+    }
+
+    cpacf_kmctr(CPACF_KMCTR_AES_128, param, dst_ref,
+                src_pages, 2 * page_size, ctr_pages, &cc);
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: reference run unexpected cc=%lu\n", cc);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("reference run: done, cc=0\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Fault run: protect second source page, run KMCTR over both pages.  */
+    /* ------------------------------------------------------------------ */
+
+    /* Record the exact register values we expect at fault time */
+    expected_src  = (unsigned long)(src_pages + page_size);
+    expected_dst  = (unsigned long)(dst_fault + page_size);
+    expected_ctr  = (unsigned long)(ctr_pages + page_size);
+    sigsegv_count = 0;
+    sigsegv_pass  = 1;   /* handler sets to 0 on any check failure */
+
+    if (verbose) {
+        printf("fault run: expecting SIGSEGV when KMCTR reaches src page2 at 0x%lx\n",
+               expected_src);
+        printf("fault run: expected register state at fault:\n");
+        printf("  R2 (dst addr) = 0x%lx\n", expected_dst);
+        printf("  R4 (src addr) = 0x%lx\n", expected_src);
+        printf("  R5 (src len)  = 0x%lx\n", (unsigned long)page_size);
+        printf("  R6 (ctr addr) = 0x%lx\n", expected_ctr);
+    }
+
+    /* Install SIGSEGV handler */
+    memset(&sa, 0, sizeof(sa));
+    sa.sa_sigaction = sigsegv_handler;
+    sa.sa_flags     = SA_SIGINFO;
+    sigemptyset(&sa.sa_mask);
+    if (sigaction(SIGSEGV, &sa, &old_sa) != 0) {
+        perror("sigaction");
+        rc = 1;
+        goto out;
+    }
+
+    /* Protect the second source page to provoke a fault during KMCTR */
+    if (mprotect(src_pages + page_size, page_size, PROT_NONE) != 0) {
+        perror("mprotect PROT_NONE");
+        sigaction(SIGSEGV, &old_sa, NULL);
+        rc = 1;
+        goto out;
+    }
+
+    if (verbose) {
+        printf("fault run: second src page protected, starting cpacf_kmctr\n");
+    }
+
+    /*
+     * Encrypt both pages with a single cpacf_kmctr call.
+     *
+     * Page 1 is processed normally; registers are advanced block-by-block
+     * inside cpacf_aes_ctr. On the first read of the second source page the
+     * CPU takes a protection fault. The signal handler verifies R2/R4/R5/R6
+     * and restores PROT_READ. On return from the handler the KMCTR instruction
+     * is restarted with the already-advanced registers so it processes only
+     * the second page and completes with CC=0.
+     *
+     * The brc 1,0b loop inside cpacf_kmctr handles the unrelated CC=3
+     * (partial-completion) case and is not triggered by the page fault.
+     */
+    memcpy(param, aes128key, sizeof(aes128key));
+    cpacf_kmctr(CPACF_KMCTR_AES_128, param, dst_fault,
+                src_pages, 2 * page_size, ctr_pages, &cc);
+
+    /* Restore the original SIGSEGV disposition */
+    sigaction(SIGSEGV, &old_sa, NULL);
+
+    if (verbose) {
+        printf("fault run: cpacf_kmctr returned, cc=%lu, SIGSEGV count=%d\n",
+               cc, sigsegv_count);
+    }
+
+    if (cc != 0) {
+        fprintf(stderr, "FAIL: fault run unexpected cc=%lu\n", cc);
+        rc = 1;
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: signal handler must have fired exactly once.               */
+    /* ------------------------------------------------------------------ */
+    if (sigsegv_count != 1) {
+        fprintf(stderr, "FAIL: expected 1 SIGSEGV, got %d\n", sigsegv_count);
+        rc = 1;
+    } else if (verbose) {
+        printf("check: SIGSEGV count = %d (expected 1): PASS\n", sigsegv_count);
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: register checks inside the handler were correct.           */
+    /* ------------------------------------------------------------------ */
+    if (!sigsegv_pass) {
+        fprintf(stderr, "FAIL: register check in SIGSEGV handler failed\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: register values in SIGSEGV handler: PASS\n");
+    }
+
+    /* ------------------------------------------------------------------ */
+    /* Verify: fault-run ciphertext matches the reference ciphertext.     */
+    /* ------------------------------------------------------------------ */
+    if (memcmp(dst_ref, dst_fault, 2 * page_size) != 0) {
+        fprintf(stderr, "FAIL: fault-run ciphertext does not match reference\n");
+        rc = 1;
+    } else if (verbose) {
+        printf("check: fault-run ciphertext matches reference ciphertext: PASS\n");
+    }
+
+    if (rc == 0) {
+        printf("cpacf-kmctr-ctr-fault: all checks passed\n");
+    }
+
+out:
+    munmap(src_pages, 2 * page_size);
+    munmap(ctr_pages, 2 * page_size);
+    munmap(dst_ref,   2 * page_size);
+    munmap(dst_fault, 2 * page_size);
+
+    return rc ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/tests/tcg/s390x/cpacf.h b/tests/tcg/s390x/cpacf.h
index c0578abd09..e89641b31d 100644
--- a/tests/tcg/s390x/cpacf.h
+++ b/tests/tcg/s390x/cpacf.h
@@ -60,15 +60,30 @@ static inline void encrypt_clrkey(uint8_t *key, int keysize)
  * encryption/decryption funcs
  */
 static inline int cpacf_km(unsigned long func, void *param,
-                           uint8_t *dest, const uint8_t *src, long src_len,
-                           unsigned long *cc)
+                            uint8_t *dest, const uint8_t *src, long src_len,
+                            unsigned long *cc)
 {
-    union register_pair d, s;
+    /*
+     * Pin the operand registers to known hardware numbers so that
+     * testcases have a clear understanding what's stored in each
+     * register:
+     *   R2  - destination address       (even of dst pair, gregs[2])
+     *   R3  - odd half of dst pair      (gregs[3], not used by KM but must be
+     *          reserved so the compiler does not place another variable there)
+     *   R4  - source address            (even of src pair, gregs[4])
+     *   R5  - source length             (odd  of src pair, gregs[5])
+     *
+     * KM R2, R4: R2 is updated (dst addr advances), R4/R5 are updated
+     * (src addr / remaining length).  R3 is not modified by KM but we
+     * list it as an output operand to prevent the compiler from allocating
+     * it to another variable that would be clobbered by the instruction.
+     */
+    register unsigned long r2 asm("r2") = (unsigned long)dest;
+    register unsigned long r3 asm("r3");   /* odd half of dst pair; reserved  */
+    register unsigned long r4 asm("r4") = (unsigned long)src;
+    register unsigned long r5 asm("r5") = (unsigned long)src_len;
 
     *cc = 0;
-    d.even = (unsigned long)dest;
-    s.even = (unsigned long)src;
-    s.odd  = (unsigned long)src_len;
     asm volatile(
                  "      lgr     0,%[fc]\n"
                  "      lgr     1,%[pba]\n"
@@ -79,12 +94,13 @@ static inline int cpacf_km(unsigned long func, void *param,
                  "      agsi    %[__cc],1\n"
                  "1:    agsi    %[__cc],1\n"
                  "2:\n"
-                 : [src] "+&d" (s.pair), [dst] "+&d" (d.pair), [__cc] "+Q" (*cc)
+                 : [dst] "+r" (r2), "=r" (r3), [src] "+r" (r4), "+r" (r5),
+                   [__cc] "+Q" (*cc)
                  : [fc] "d" (func), [pba] "d" ((unsigned long)param),
                    [opc] "i" (CPACF_KM)
                  : "cc", "memory", "0", "1");
 
-    return src_len - s.odd;
+    return src_len - (long)r5;
 }
 
 /**
@@ -99,15 +115,30 @@ static inline int cpacf_km(unsigned long func, void *param,
  * encryption/decryption funcs
  */
 static inline int cpacf_kmc(unsigned long func, void *param,
-                            uint8_t *dest, const uint8_t *src, long src_len,
-                            unsigned long *cc)
+                             uint8_t *dest, const uint8_t *src, long src_len,
+                             unsigned long *cc)
 {
-    union register_pair d, s;
+    /*
+     * Pin the operand registers to known hardware numbers so that
+     * testcases have a clear understanding what's stored in each
+     * register:
+     *   R2  - destination address       (even of dst pair, gregs[2])
+     *   R3  - odd half of dst pair      (gregs[3], not used by KMC but must be
+     *          reserved so the compiler does not place another variable there)
+     *   R4  - source address            (even of src pair, gregs[4])
+     *   R5  - source length             (odd  of src pair, gregs[5])
+     *
+     * KMC R2, R4: R2 is updated (dst addr advances), R4/R5 are updated
+     * (src addr / remaining length). R3 is not modified by KMC but we
+     * list it as an output operand to prevent the compiler from allocating
+     * it to another variable that would be clobbered by the instruction.
+     */
+    register unsigned long r2 asm("r2") = (unsigned long)dest;
+    register unsigned long r3 asm("r3");   /* odd half of dst pair; reserved */
+    register unsigned long r4 asm("r4") = (unsigned long)src;
+    register unsigned long r5 asm("r5") = (unsigned long)src_len;
 
     *cc = 0;
-    d.even = (unsigned long)dest;
-    s.even = (unsigned long)src;
-    s.odd  = (unsigned long)src_len;
     asm volatile(
                  "      lgr     0,%[fc]\n"
                  "      lgr     1,%[pba]\n"
@@ -118,12 +149,13 @@ static inline int cpacf_kmc(unsigned long func, void *param,
                  "      agsi    %[__cc],1\n"
                  "1:    agsi    %[__cc],1\n"
                  "2:\n"
-                 : [src] "+&d" (s.pair), [dst] "+&d" (d.pair), [__cc] "+Q" (*cc)
+                 : [dst] "+r" (r2), "=r" (r3), [src] "+r" (r4), "+r" (r5),
+                   [__cc] "+Q" (*cc)
                  : [fc] "d" (func), [pba] "d" ((unsigned long)param),
                    [opc] "i" (CPACF_KMC)
                  : "cc", "memory", "0", "1");
 
-    return src_len - s.odd;
+    return src_len - (long)r5;
 }
 
 /**
@@ -272,16 +304,33 @@ static inline int cpacf_kmac_x(unsigned long *func, void *param,
  * encryption/decryption funcs
  */
 static inline int cpacf_kmctr(unsigned long func, void *param, uint8_t *dest,
-                              const uint8_t *src, long src_len,
-                              uint8_t *counter, unsigned long *cc)
+                               const uint8_t *src, long src_len,
+                               uint8_t *counter, unsigned long *cc)
 {
-    union register_pair d, s, c;
+    /*
+     * Pin the operand registers to known hardware numbers so that
+     * testcases have a clear understanding what's stored in each
+     * register:
+     *   R2  - destination address       (even of dst pair, gregs[2])
+     *   R3  - odd half of dst pair      (gregs[3], not used by KMCTR)
+     *   R4  - source address            (even of src pair, gregs[4])
+     *   R5  - source length             (odd  of src pair, gregs[5])
+     *   R6  - counter address           (even of ctr pair, gregs[6])
+     *   R7  - odd half of ctr pair      (gregs[7], not used by KMCTR)
+     *
+     * KMCTR R2, R4, R6: R2 is updated (dst addr advances), R4/R5 are updated
+     * (src addr / remaining length), R6 is updated (ctr addr advances).
+     * R3 and R7 are not modified by KMCTR but are listed as output operands
+     * to prevent the compiler from allocating them to other variables.
+     */
+    register unsigned long r2 asm("r2") = (unsigned long)dest;
+    register unsigned long r3 asm("r3");   /* odd half of dst pair; reserved  */
+    register unsigned long r4 asm("r4") = (unsigned long)src;
+    register unsigned long r5 asm("r5") = (unsigned long)src_len;
+    register unsigned long r6 asm("r6") = (unsigned long)counter;
+    register unsigned long r7 asm("r7");   /* odd half of ctr pair; reserved  */
 
     *cc = 0;
-    d.even = (unsigned long)dest;
-    s.even = (unsigned long)src;
-    s.odd  = (unsigned long)src_len;
-    c.even = (unsigned long)counter;
     asm volatile(
                  "      lgr     0,%[fc]\n"
                  "      lgr     1,%[pba]\n"
@@ -292,13 +341,15 @@ static inline int cpacf_kmctr(unsigned long func, void *param, uint8_t *dest,
                  "      agsi    %[__cc],1\n"
                  "1:    agsi    %[__cc],1\n"
                  "2:\n"
-                 : [src] "+&d" (s.pair), [dst] "+&d" (d.pair),
-                   [ctr] "+&d" (c.pair), [__cc] "+Q" (*cc)
+                 : [dst] "+r" (r2), "=r" (r3),
+                   [src] "+r" (r4), "+r" (r5),
+                   [ctr] "+r" (r6), "=r" (r7),
+                   [__cc] "+Q" (*cc)
                  : [fc] "d" (func), [pba] "d" ((unsigned long)param),
                    [opc] "i" (CPACF_KMCTR)
                  : "cc", "memory", "0", "1");
 
-    return src_len - s.odd;
+    return src_len - (long)r5;
 }
 
 /**
diff --git a/tests/tcg/s390x/meson.build b/tests/tcg/s390x/meson.build
index f2328d9e5c..693c7d2a64 100644
--- a/tests/tcg/s390x/meson.build
+++ b/tests/tcg/s390x/meson.build
@@ -78,9 +78,13 @@ tests += {
   'cpacf-kimd.c': {},
   'cpacf-klmd.c': {},
   'cpacf-km.c': {},
+  'cpacf-km-ecb-fault.c': {},
+  'cpacf-km-xts-fault.c': {},
   'cpacf-kmac.c': {},
   'cpacf-kmc.c': {},
+  'cpacf-kmc-cbc-fault.c': {},
   'cpacf-kmctr.c': {},
+  'cpacf-kmctr-ctr-fault.c': {},
   'cpacf-pcc.c': {},
   'cpacf-pckmo.c': {},
   'cpacf-prno.c': {},
-- 
2.56.0



^ permalink raw reply related	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2026-11-20 13:16 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-20 13:14 [PATCH v2 0/3] Fix AES/PAES CPACF register update on faults Andrew Holden
2026-11-20 13:14 ` [PATCH v2 1/3] target/s390x: export access_prepare() and byte accessors Andrew Holden
2026-11-20 13:14 ` [PATCH v2 2/3] target/s390x/tcg: update regs and IV/tweak per block in CPACF AES/PAES Andrew Holden
2026-11-20 13:14 ` [PATCH v2 3/3] tests/s390x/tcg: Add cpacf clear key register update tests Andrew Holden

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.