Skip to contentSkip to conversation

Fix AES/PAES CPACF register update on faults

PATCH New Andrew Holden 1 participant 4 messages Nov 20 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

v2 cover Fix AES/PAES CPACF register update on faults

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/[email protected]/

---

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
Signature · 1 line
2.56.0
#1 lore raw

PATCH v2 1/3 target/s390x: export access_prepare() and byte accessors

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

---
 target/s390x/s390x-internal.h | 25 +++++++++++++++++++++++++
 target/s390x/tcg/mem_helper.c | 33 ++++++++-------------------------
 2 files changed, 33 insertions(+), 25 deletions(-)
target/s390x/s390x-internal.h +25 -0
index da60b2b1fd..c97d399c99 100644
@@ -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);
 
target/s390x/tcg/mem_helper.c +8 -25
index 414e6838c8..5144f036ad 100644
@@ -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;
Signature · 1 line
2.56.0
#2 lore raw

PATCH v2 2/3 target/s390x/tcg: update regs and IV/tweak per block in CPACF AES/PAES

In reply to 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.

---
 target/s390x/tcg/cpacf_aes.c | 380 ++++++++++++++++++++++++-----------
 1 file changed, 259 insertions(+), 121 deletions(-)
target/s390x/tcg/cpacf_aes.c +259 -121
index 92884c4120..117d43040b 100644
@@ -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;
 }
Signature · 1 line
2.56.0
#3 lore raw

PATCH v2 3/3 tests/s390x/tcg: Add cpacf clear key register update tests

In reply to Andrew Holden

From: Harald Freudenberger <[email protected]>

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.

---
 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
tests/tcg/s390x/cpacf-km-ecb-fault.c new file +368 -0
new file mode 100644
index 0000000000..3fe7df1f04
@@ -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;
+}
tests/tcg/s390x/cpacf-km-xts-fault.c new file +511 -0

511 lines not on this page · raw message

tests/tcg/s390x/cpacf-kmc-cbc-fault.c new file +472 -0

472 lines not on this page · raw message

tests/tcg/s390x/cpacf-kmctr-ctr-fault.c new file +414 -0

414 lines not on this page · raw message

tests/tcg/s390x/cpacf.h +77 -26

160 lines not on this page · raw message

tests/tcg/s390x/meson.build +4 -0
index f2328d9e5c..693c7d2a64 100644
@@ -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': {},
Signature · 1 line
2.56.0