Skip to contentSkip to conversation

ARM Scalable Vector Extension (SVE)

PATCH Superseded Dave Martin 9 participants 109 messages Oct 10, 2017 – Oct 18, 2017 4 messages not in the archive

Subsystems (9)
Documentation Arm (32-bit) VFS arm64 +5 more subsystems

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover ARM Scalable Vector Extension (SVE)

This series implements Linux kernel support for the ARM Scalable Vector Extension (SVE). [1] It supersedes the previous v2: see [3] for link. See the individual patches for details of changes.

The patches apply on v4.14-rc4.
For convenience, a git tree is available. [4]

To reduce spam, some people may not been copied on the entire series. For those who did not receive the whole series, it can be found in the linux-arm-kernel archive. [2]

*Note* The final two patches (27-28) of the series are still RFC -- before committing to this ABI it would be good to get feedback on whether the approach makes sense and whether it suitable for other architectures. These two patches are not required by the rest of the series and can be revised or merged later.

Support for use of SVE by KVM guests is not currently included. Instead, such use will be trapped and reflected to the guest as undefined instruction execution. SVE is hidden from the view of the CPU feature registers visible to guests, so that guests will not expect it to work.

This series has been build- and boot-tested on the ARM FVP Base model with and without the SVE plugin. Because there is no hardware with SVE support yet, testing of the SVE functionality has only been performed on the model.

Regression testing of v3 is under way.

Series summary:

* Patches 1-5 contain some individual bits of preparatory spadework, which are indirectly related to SVE.

Dave Martin (5):
regset: Add support for dynamically sized regsets
arm64: KVM: Hide unsupported AArch64 CPU features from guests
arm64: efi: Add missing Kconfig dependency on KERNEL_MODE_NEON
arm64: Port deprecated instruction emulation to new sysctl interface
arm64: fpsimd: Simplify uses of {set,clear}_ti_thread_flag()

Non-trivial changes among these are:

* Patch 1: updates the regset core code to handle regsets whose size is not fixed at compile time. This avoids bloating coredumps even though the maximum theoretical SVE regset size is large.

* Patch 2: extends KVM to modify the ARM architectural ID registers seen by guests, by trapping and emulating certain registers. For SVE this is a temporary measure, but it may be useful for other architecture extensions. This patch may also be built on in the future, since the only registers currently emulated are those required for hiding SVE.

* Patches 6-10 add SVE-specific system register and structure layout definitions, and the low-level boot code and accessors needed for making use of SVE.

Dave Martin (5):
arm64/sve: System register and exception syndrome definitions arm64/sve: Low-level SVE architectural state manipulation functions arm64/sve: Kconfig update and conditional compilation support arm64/sve: Signal frame and context structure definition arm64/sve: Low-level CPU setup

* Patches 11-13 implement the core context management facilities to provide each user task with its own SVE register context, signal handling facilities, and sane programmer's model interoperation between SVE and FPSIMD.

Dave Martin (3):
arm64/sve: Core task context handling
arm64/sve: Support vector length resetting for new processes arm64/sve: Signal handling support

* Patches 14 and 16 provide backend logic for detecting and making use of the different SVE vector lengths supported by the hardware.

* Patch 15 moves around code in cpufeatures.c to fit.

Dave Martin (3):
arm64/sve: Backend logic for setting the vector length
arm64: cpufeature: Move sys_caps_initialised declarations arm64/sve: Probe SVE capabilities and usable vector lengths

* Patches 17-18 update the kernel-mode NEON / EFI FPSIMD frameworks to interoperate correctly with SVE.

Dave Martin (2):
arm64/sve: Preserve SVE registers around kernel-mode NEON use arm64/sve: Preserve SVE registers around EFI runtime service calls

* Patches 19-21 implement the userspace frontend for managing SVE, comprising ptrace, some new arch-specific prctl() calls, and a new sysctl for init-time setup.

Dave Martin (3):
arm64/sve: ptrace and ELF coredump support
arm64/sve: Add prctl controls for userspace vector length management arm64/sve: Add sysctl to set the default vector length for new
processes

* Patches 22-24 provide stub KVM extensions for using KVM only on the host, while denying guest access. (A future series will extend this with full support for SVE in guests.)

Dave Martin (3):
arm64/sve: KVM: Prevent guests from using SVE arm64/sve: KVM: Treat guest SVE use as undefined instruction
execution
arm64/sve: KVM: Hide SVE from CPU features exposed to guests

And finally:

* Patch 25 disengages the safety catch, enabling the kernel SVE runtime support and allowing userspace to use SVE.

Dave Martin (1):
arm64/sve: Detect SVE and activate runtime support

* Patch 26 adds some basic documentation.

Dave Martin (1):
arm64/sve: Add documentation

* Patches 27-28 (which may be considered RFC) propose a mechanism to report the maximum runtime signal frame size to userspace.

Dave Martin (2):
arm64: signal: Report signal frame size to userspace via auxv arm64/sve: signal: Include SVE when computing AT_MINSIGSTKSZ

References:

[1] ARM Scalable Vector Extension
https://community.arm.com/groups/processors/blog/2016/08/22/technology-update-the-scalable-vector-extension-sve-for-the-armv8-a-architecture

[2] linux-arm-kernel October 2017 Archives by thread
http://lists.infradead.org/pipermail/linux-arm-kernel/2017-October/thread.html

[3] [PATCH v2 00/28] ARM Scalable Vector Extension (SVE)
http://lists.infradead.org/pipermail/linux-arm-kernel/2017-August/529575.html

[4] http://linux-arm.org/git?p=linux-dm.git;a=shortlog;h=refs/heads/sve/v3

    git://linux-arm.org/linux-dm.git sve/v3

Full series and diffstat:

Dave Martin (28):
regset: Add support for dynamically sized regsets
arm64: KVM: Hide unsupported AArch64 CPU features from guests
arm64: efi: Add missing Kconfig dependency on KERNEL_MODE_NEON
arm64: Port deprecated instruction emulation to new sysctl interface
arm64: fpsimd: Simplify uses of {set,clear}_ti_thread_flag() arm64/sve: System register and exception syndrome definitions arm64/sve: Low-level SVE architectural state manipulation functions arm64/sve: Kconfig update and conditional compilation support arm64/sve: Signal frame and context structure definition arm64/sve: Low-level CPU setup
arm64/sve: Core task context handling
arm64/sve: Support vector length resetting for new processes arm64/sve: Signal handling support
arm64/sve: Backend logic for setting the vector length
arm64: cpufeature: Move sys_caps_initialised declarations arm64/sve: Probe SVE capabilities and usable vector lengths arm64/sve: Preserve SVE registers around kernel-mode NEON use arm64/sve: Preserve SVE registers around EFI runtime service calls arm64/sve: ptrace and ELF coredump support
arm64/sve: Add prctl controls for userspace vector length management arm64/sve: Add sysctl to set the default vector length for new
processes
arm64/sve: KVM: Prevent guests from using SVE
arm64/sve: KVM: Treat guest SVE use as undefined instruction execution arm64/sve: KVM: Hide SVE from CPU features exposed to guests arm64/sve: Detect SVE and activate runtime support arm64/sve: Add documentation
arm64: signal: Report signal frame size to userspace via auxv arm64/sve: signal: Include SVE when computing AT_MINSIGSTKSZ

 Documentation/arm64/cpu-feature-registers.txt |   6 +-
 Documentation/arm64/sve.txt                   | 484 ++++++++++++++
 arch/arm/include/asm/kvm_host.h               |   3 +
 arch/arm64/Kconfig                            |  12 +
 arch/arm64/include/asm/cpu.h                  |   4 +
 arch/arm64/include/asm/cpucaps.h              |   3 +-
 arch/arm64/include/asm/cpufeature.h           |  42 ++
 arch/arm64/include/asm/elf.h                  |   5 +
 arch/arm64/include/asm/esr.h                  |   3 +-
 arch/arm64/include/asm/fpsimd.h               |  73 +-
 arch/arm64/include/asm/fpsimdmacros.h         | 148 ++++
 arch/arm64/include/asm/kvm_arm.h              |   5 +-
 arch/arm64/include/asm/kvm_host.h             |  11 +
 arch/arm64/include/asm/processor.h            |  10 +
 arch/arm64/include/asm/sysreg.h               |  24 +
 arch/arm64/include/asm/thread_info.h          |   2 +
 arch/arm64/include/asm/traps.h                |   2 +
 arch/arm64/include/uapi/asm/auxvec.h          |   3 +-
 arch/arm64/include/uapi/asm/hwcap.h           |   1 +
 arch/arm64/include/uapi/asm/ptrace.h          | 138 ++++
 arch/arm64/include/uapi/asm/sigcontext.h      | 120 +++-
 arch/arm64/kernel/armv8_deprecated.c          |  15 +-
 arch/arm64/kernel/cpufeature.c                |  97 ++-
 arch/arm64/kernel/cpuinfo.c                   |   7 +
 arch/arm64/kernel/entry-fpsimd.S              |  17 +
 arch/arm64/kernel/entry.S                     |  14 +-
 arch/arm64/kernel/fpsimd.c                    | 927 +++++++++++++++++++++++++-
 arch/arm64/kernel/head.S                      |  13 +-
 arch/arm64/kernel/process.c                   |  14 +-
 arch/arm64/kernel/ptrace.c                    | 271 +++++++-
 arch/arm64/kernel/signal.c                    | 222 +++++-
 arch/arm64/kernel/signal32.c                  |   2 +-
 arch/arm64/kernel/traps.c                     |   7 +-
 arch/arm64/kvm/handle_exit.c                  |   8 +
 arch/arm64/kvm/hyp/switch.c                   |  12 +-
 arch/arm64/kvm/sys_regs.c                     | 292 ++++++--
 fs/binfmt_elf.c                               |   6 +-
 include/linux/regset.h                        |  67 +-
 include/uapi/linux/elf.h                      |   1 +
 include/uapi/linux/prctl.h                    |   9 +
 kernel/sys.c                                  |  12 +
 virt/kvm/arm/arm.c                            |   3 +
 42 files changed, 2970 insertions(+), 145 deletions(-)
 create mode 100644 Documentation/arm64/sve.txt
Signature · 1 line
2.1.4
#1 lore raw

PATCH v3 1/28 regset: Add support for dynamically sized regsets

Currently the regset API doesn't allow for the possibility that regsets (or at least, the amount of meaningful data in a regset) may change in size.

In particular, this results in useless padding being added to coredumps in a regset's current size is smaller than its theoretical maximum size.

This patch adds a get_size() function to struct user_regset. Individual regset implementations can implement this function to return the current size of the regset data. A regset_size() function is added to provide callers with an abstract interface for determining the size of a regset without needing to know whether the regset is dynamically sized or not.

The only affected user of this interface is the ELF coredump code:
This patch ports ELF coredump to dump regsets with their actual size in the coredump. This has no effect except for new regsets that are dynamically sized and provide a get_size() implementation.

---
 fs/binfmt_elf.c        |  6 ++---
 include/linux/regset.h | 67 ++++++++++++++++++++++++++++++++++++++++++++------
 2 files changed, 63 insertions(+), 10 deletions(-)
fs/binfmt_elf.c +3 -3
index 73b01e4..35aa03f 100644
@@ -1699,7 +1699,7 @@ static int fill_thread_core_info(struct elf_thread_core_info *t,
 				 long signr, size_t *total)
 {
 	unsigned int i;
-	unsigned int regset_size = view->regsets[0].n * view->regsets[0].size;
+	unsigned int size = regset_size(t->task, &view->regsets[0]);
 
 	/*
 	 * NT_PRSTATUS is the one special case, because the regset data
@@ -1708,7 +1708,7 @@ static int fill_thread_core_info(struct elf_thread_core_info *t,
 	 * We assume that regset 0 is NT_PRSTATUS.
 	 */
 	fill_prstatus(&t->prstatus, t->task, signr);
-	(void) view->regsets[0].get(t->task, &view->regsets[0], 0, regset_size,
+	(void) view->regsets[0].get(t->task, &view->regsets[0], 0, size,
 				    &t->prstatus.pr_reg, NULL);
 
 	fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
@@ -1728,7 +1728,7 @@ static int fill_thread_core_info(struct elf_thread_core_info *t,
 		if (regset->core_note_type && regset->get &&
 		    (!regset->active || regset->active(t->task, regset))) {
 			int ret;
-			size_t size = regset->n * regset->size;
+			size_t size = regset_size(t->task, regset);
 			void *data = kmalloc(size, GFP_KERNEL);
 			if (unlikely(!data))
 				return 0;
include/linux/regset.h +60 -7

96 lines not on this page · raw message

Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 1/28
#2 lore raw

Re: [PATCH v3 01/28] regset: Add support for dynamically sized regsets

Quoted 20 lines · Dave P Martin

Currently the regset API doesn't allow for the possibility that regsets (or at least, the amount of meaningful data in a regset) may change in size.

In particular, this results in useless padding being added to coredumps in a regset's current size is smaller than its theoretical maximum size.

This patch adds a get_size() function to struct user_regset. Individual regset implementations can implement this function to return the current size of the regset data. A regset_size() function is added to provide callers with an abstract interface for determining the size of a regset without needing to know whether the regset is dynamically sized or not.

The only affected user of this interface is the ELF coredump code:
This patch ports ELF coredump to dump regsets with their actual size in the coredump. This has no effect except for new regsets that are dynamically sized and provide a get_size() implementation.

Quoted 6 lines
---
 fs/binfmt_elf.c        |  6 ++---
 include/linux/regset.h | 67 ++++++++++++++++++++++++++++++++++++++++++++------
 2 files changed, 63 insertions(+), 10 deletions(-)

The patch looks fine to me:

However, you'd probably need an ack from the filesystem maintainers (cc'ed; patch below for reference).

Quoted 143 lines
fs/binfmt_elf.c +3 -3
index 73b01e4..35aa03f 100644
@@ -1699,7 +1699,7 @@ static int fill_thread_core_info(struct elf_thread_core_info *t,
 				 long signr, size_t *total)
 {
 	unsigned int i;
-	unsigned int regset_size = view->regsets[0].n * view->regsets[0].size;
+	unsigned int size = regset_size(t->task, &view->regsets[0]);
 
 	/*
 	 * NT_PRSTATUS is the one special case, because the regset data
@@ -1708,7 +1708,7 @@ static int fill_thread_core_info(struct elf_thread_core_info *t,
 	 * We assume that regset 0 is NT_PRSTATUS.
 	 */
 	fill_prstatus(&t->prstatus, t->task, signr);
-	(void) view->regsets[0].get(t->task, &view->regsets[0], 0, regset_size,
+	(void) view->regsets[0].get(t->task, &view->regsets[0], 0, size,
 				    &t->prstatus.pr_reg, NULL);
 
 	fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
@@ -1728,7 +1728,7 @@ static int fill_thread_core_info(struct elf_thread_core_info *t,
 		if (regset->core_note_type && regset->get &&
 		    (!regset->active || regset->active(t->task, regset))) {
 			int ret;
-			size_t size = regset->n * regset->size;
+			size_t size = regset_size(t->task, regset);
 			void *data = kmalloc(size, GFP_KERNEL);
 			if (unlikely(!data))
 				return 0;
include/linux/regset.h +60 -7
index 8e0c9fe..494ceda 100644
@@ -107,6 +107,28 @@ typedef int user_regset_writeback_fn(struct task_struct *target,
 				     int immediate);
 
 /**
+ * user_regset_get_size_fn - type of @get_size function in &struct user_regset
+ * @target:	thread being examined
+ * @regset:	regset being examined
+ *
+ * This call is optional; usually the pointer is %NULL.
+ *
+ * When provided, this function must return the current size of regset
+ * data, as observed by the @get function in &struct user_regset.  The
+ * value returned must be a multiple of @size.  The returned size is
+ * required to be valid only until the next time (if any) @regset is
+ * modified for @target.
+ *
+ * This function is intended for dynamically sized regsets.  A regset
+ * that is statically sized does not need to implement it.
+ *
+ * This function should not be called directly: instead, callers should
+ * call regset_size() to determine the current size of a regset.
+ */
+typedef unsigned int user_regset_get_size_fn(struct task_struct *target,
+					     const struct user_regset *regset);
+
+/**
  * struct user_regset - accessible thread CPU state
  * @n:			Number of slots (registers).
  * @size:		Size in bytes of a slot (register).
@@ -117,19 +139,33 @@ typedef int user_regset_writeback_fn(struct task_struct *target,
  * @set:		Function to store values.
  * @active:		Function to report if regset is active, or %NULL.
  * @writeback:		Function to write data back to user memory, or %NULL.
+ * @get_size:		Function to return the regset's size, or %NULL.
  *
  * This data structure describes a machine resource we call a register set.
  * This is part of the state of an individual thread, not necessarily
  * actual CPU registers per se.  A register set consists of a number of
  * similar slots, given by @n.  Each slot is @size bytes, and aligned to
- * @align bytes (which is at least @size).
+ * @align bytes (which is at least @size).  For dynamically-sized
+ * regsets, @n must contain the maximum possible number of slots for the
+ * regset, and @get_size must point to a function that returns the
+ * current regset size.
  *
- * These functions must be called only on the current thread or on a
- * thread that is in %TASK_STOPPED or %TASK_TRACED state, that we are
- * guaranteed will not be woken up and return to user mode, and that we
- * have called wait_task_inactive() on.  (The target thread always might
- * wake up for SIGKILL while these functions are working, in which case
- * that thread's user_regset state might be scrambled.)
+ * Callers that need to know only the current size of the regset and do
+ * not care about its internal structure should call regset_size()
+ * instead of inspecting @n or calling @get_size.
+ *
+ * For backward compatibility, the @get and @set methods must pad to, or
+ * accept, @n * @size bytes, even if the current regset size is smaller.
+ * The precise semantics of these operations depend on the regset being
+ * accessed.
+ *
+ * The functions to which &struct user_regset members point must be
+ * called only on the current thread or on a thread that is in
+ * %TASK_STOPPED or %TASK_TRACED state, that we are guaranteed will not
+ * be woken up and return to user mode, and that we have called
+ * wait_task_inactive() on.  (The target thread always might wake up for
+ * SIGKILL while these functions are working, in which case that
+ * thread's user_regset state might be scrambled.)
  *
  * The @pos argument must be aligned according to @align; the @count
  * argument must be a multiple of @size.  These functions are not
@@ -156,6 +192,7 @@ struct user_regset {
 	user_regset_set_fn		*set;
 	user_regset_active_fn		*active;
 	user_regset_writeback_fn	*writeback;
+	user_regset_get_size_fn		*get_size;
 	unsigned int			n;
 	unsigned int 			size;
 	unsigned int 			align;
@@ -371,5 +408,21 @@ static inline int copy_regset_from_user(struct task_struct *target,
 	return regset->set(target, regset, offset, size, NULL, data);
 }
 
+/**
+ * regset_size - determine the current size of a regset
+ * @target:	thread to be examined
+ * @regset:	regset to be examined
+ *
+ * Note that the returned size is valid only until the next time
+ * (if any) @regset is modified for @target.
+ */
+static inline unsigned int regset_size(struct task_struct *target,
+				       const struct user_regset *regset)
+{
+	if (!regset->get_size)
+		return regset->n * regset->size;
+	else
+		return regset->get_size(target, regset);
+}
 
 #endif	/* <linux/regset.h> */
Signature · 7 lines
2.1.4


_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
#3 lore raw

Re: [PATCH v3 01/28] regset: Add support for dynamically sized regsets

Quoted 28 lines · Catalin Marinas
Quoted 20 lines · Dave P Martin

Currently the regset API doesn't allow for the possibility that regsets (or at least, the amount of meaningful data in a regset) may change in size.

In particular, this results in useless padding being added to coredumps in a regset's current size is smaller than its theoretical maximum size.

This patch adds a get_size() function to struct user_regset. Individual regset implementations can implement this function to return the current size of the regset data. A regset_size() function is added to provide callers with an abstract interface for determining the size of a regset without needing to know whether the regset is dynamically sized or not.

The only affected user of this interface is the ELF coredump code:
This patch ports ELF coredump to dump regsets with their actual size in the coredump. This has no effect except for new regsets that are dynamically sized and provide a get_size() implementation.

Quoted 6 lines
---
 fs/binfmt_elf.c        |  6 ++---
 include/linux/regset.h | 67 ++++++++++++++++++++++++++++++++++++++++++++------
 2 files changed, 63 insertions(+), 10 deletions(-)
Quoted 6 lines

The patch looks fine to me:

However, you'd probably need an ack from the filesystem maintainers (cc'ed; patch below for reference).

Apologies for that -- I manually added Ccs to this patch in previous postings, and predictably lost them in the respin.

I'll add Cc lines in the commit message, since there will be a further re-spin of the series to apply the Documentation changes requested by Szabolcs that I missed.

I don't currently have any pending fixes to _this_ patch, so it's still worth reviewing.

Cheers
---Dave

[...]

#4 lore raw

PATCH v3 2/28 arm64: KVM: Hide unsupported AArch64 CPU features from guests

In reply to Dave Martin

Currently, a guest kernel sees the true CPU feature registers (ID_*_EL1) when it reads them using MRS instructions. This means that the guest will observe features that are present in the hardware but the host doesn't understand or doesn't provide support for. A guest may legimitately try to use such a feature as per the architecture, but use of the feature may trap instead of working normally, triggering undef injection into the guest.

This is not a problem for the host, but the guest may go wrong when running on newer hardware than the host knows about.

This patch hides from guest VMs any AArch64-specific CPU features that the host doesn't support, by exposing to the guest the sanitised versions of the registers computed by the cpufeatures framework, instead of the true hardware registers. To achieve this, HCR_EL2.TID3 is now set for AArch64 guests, and emulation code is added to KVM to report the sanitised versions of the affected registers in response to MRS and register reads from userspace.

The affected registers are removed from invariant_sys_regs[] (since the invariant_sys_regs handling is no longer quite correct for them) and added to sys_reg_desgs[], with appropriate access(), get_user() and set_user() methods. No runtime vcpu storage is allocated for the registers: instead, they are read on demand from the cpufeatures framework. This may need modification in the future if there is a need for userspace to customise the features visible to the guest.

Attempts by userspace to write the registers are handled similarly to the current invariant_sys_regs handling: writes are permitted, but only if they don't attempt to change the value. This is sufficient to support VM snapshot/restore from userspace.

Because of the additional registers, restoring a VM on an older kernel may not work unless userspace knows how to handle the extra VM registers exposed to the KVM user ABI by this patch.

Under the principle of least damage, this patch makes no attempt to handle any of the other registers currently in invariant_sys_regs[], or to emulate registers for AArch32: however, these could be handled in a similar way in future, as necessary.

---
 arch/arm64/include/asm/sysreg.h |   3 +
 arch/arm64/kvm/hyp/switch.c     |   6 +
 arch/arm64/kvm/sys_regs.c       | 282 +++++++++++++++++++++++++++++++++-------
 3 files changed, 246 insertions(+), 45 deletions(-)
arch/arm64/include/asm/sysreg.h +3 -0
index f707fed..480ecd6 100644
@@ -149,6 +149,9 @@
 #define SYS_ID_AA64DFR0_EL1		sys_reg(3, 0, 0, 5, 0)
 #define SYS_ID_AA64DFR1_EL1		sys_reg(3, 0, 0, 5, 1)
 
+#define SYS_ID_AA64AFR0_EL1		sys_reg(3, 0, 0, 5, 4)
+#define SYS_ID_AA64AFR1_EL1		sys_reg(3, 0, 0, 5, 5)
+
 #define SYS_ID_AA64ISAR0_EL1		sys_reg(3, 0, 0, 6, 0)
 #define SYS_ID_AA64ISAR1_EL1		sys_reg(3, 0, 0, 6, 1)
 
arch/arm64/kvm/hyp/switch.c +6 -0
index 945e79c..35a90b8 100644
@@ -81,11 +81,17 @@ static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu)
 	 * it will cause an exception.
 	 */
 	val = vcpu->arch.hcr_el2;
+
 	if (!(val & HCR_RW) && system_supports_fpsimd()) {
 		write_sysreg(1 << 30, fpexc32_el2);
 		isb();
 	}
+
+	if (val & HCR_RW) /* for AArch64 only: */
+		val |= HCR_TID3; /* TID3: trap feature register accesses */
+
 	write_sysreg(val, hcr_el2);
+
 	/* Trap on AArch32 cp15 c15 accesses (EL1 or EL0) */
 	write_sysreg(1 << 15, hstr_el2);
 	/*
arch/arm64/kvm/sys_regs.c +237 -45

330 lines not on this page · raw message

Signature · 1 line
2.1.4
maintainer Acked-by on v3 2/28
#5 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

Quoted 43 lines · Dave P Martin

Currently, a guest kernel sees the true CPU feature registers (ID_*_EL1) when it reads them using MRS instructions. This means that the guest will observe features that are present in the hardware but the host doesn't understand or doesn't provide support for. A guest may legimitately try to use such a feature as per the architecture, but use of the feature may trap instead of working normally, triggering undef injection into the guest.

This is not a problem for the host, but the guest may go wrong when running on newer hardware than the host knows about.

This patch hides from guest VMs any AArch64-specific CPU features that the host doesn't support, by exposing to the guest the sanitised versions of the registers computed by the cpufeatures framework, instead of the true hardware registers. To achieve this, HCR_EL2.TID3 is now set for AArch64 guests, and emulation code is added to KVM to report the sanitised versions of the affected registers in response to MRS and register reads from userspace.

The affected registers are removed from invariant_sys_regs[] (since the invariant_sys_regs handling is no longer quite correct for them) and added to sys_reg_desgs[], with appropriate access(), get_user() and set_user() methods. No runtime vcpu storage is allocated for the registers: instead, they are read on demand from the cpufeatures framework. This may need modification in the future if there is a need for userspace to customise the features visible to the guest.

Attempts by userspace to write the registers are handled similarly to the current invariant_sys_regs handling: writes are permitted, but only if they don't attempt to change the value. This is sufficient to support VM snapshot/restore from userspace.

Because of the additional registers, restoring a VM on an older kernel may not work unless userspace knows how to handle the extra VM registers exposed to the KVM user ABI by this patch.

Under the principle of least damage, this patch makes no attempt to handle any of the other registers currently in invariant_sys_regs[], or to emulate registers for AArch32: however, these could be handled in a similar way in future, as necessary.

Quoted 7 lines
---
 arch/arm64/include/asm/sysreg.h |   3 +
 arch/arm64/kvm/hyp/switch.c     |   6 +
 arch/arm64/kvm/sys_regs.c       | 282 +++++++++++++++++++++++++++++++++-------
 3 files changed, 246 insertions(+), 45 deletions(-)
Reviewed-by on v3 2/28
#6 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

In reply to Dave Martin

[+ Christoffer]

Quoted 419 lines · Dave Martin

Currently, a guest kernel sees the true CPU feature registers (ID_*_EL1) when it reads them using MRS instructions. This means that the guest will observe features that are present in the hardware but the host doesn't understand or doesn't provide support for. A guest may legimitately try to use such a feature as per the architecture, but use of the feature may trap instead of working normally, triggering undef injection into the guest.

This is not a problem for the host, but the guest may go wrong when running on newer hardware than the host knows about.

This patch hides from guest VMs any AArch64-specific CPU features that the host doesn't support, by exposing to the guest the sanitised versions of the registers computed by the cpufeatures framework, instead of the true hardware registers. To achieve this, HCR_EL2.TID3 is now set for AArch64 guests, and emulation code is added to KVM to report the sanitised versions of the affected registers in response to MRS and register reads from userspace.

The affected registers are removed from invariant_sys_regs[] (since the invariant_sys_regs handling is no longer quite correct for them) and added to sys_reg_desgs[], with appropriate access(), get_user() and set_user() methods. No runtime vcpu storage is allocated for the registers: instead, they are read on demand from the cpufeatures framework. This may need modification in the future if there is a need for userspace to customise the features visible to the guest.

Attempts by userspace to write the registers are handled similarly to the current invariant_sys_regs handling: writes are permitted, but only if they don't attempt to change the value. This is sufficient to support VM snapshot/restore from userspace.

Because of the additional registers, restoring a VM on an older kernel may not work unless userspace knows how to handle the extra VM registers exposed to the KVM user ABI by this patch.

Under the principle of least damage, this patch makes no attempt to handle any of the other registers currently in invariant_sys_regs[], or to emulate registers for AArch32: however, these could be handled in a similar way in future, as necessary.

---
 arch/arm64/include/asm/sysreg.h |   3 +
 arch/arm64/kvm/hyp/switch.c     |   6 +
 arch/arm64/kvm/sys_regs.c       | 282 +++++++++++++++++++++++++++++++++-------
 3 files changed, 246 insertions(+), 45 deletions(-)
arch/arm64/include/asm/sysreg.h +3 -0
index f707fed..480ecd6 100644
@@ -149,6 +149,9 @@
 #define SYS_ID_AA64DFR0_EL1		sys_reg(3, 0, 0, 5, 0)
 #define SYS_ID_AA64DFR1_EL1		sys_reg(3, 0, 0, 5, 1)
 
+#define SYS_ID_AA64AFR0_EL1		sys_reg(3, 0, 0, 5, 4)
+#define SYS_ID_AA64AFR1_EL1		sys_reg(3, 0, 0, 5, 5)
+
 #define SYS_ID_AA64ISAR0_EL1		sys_reg(3, 0, 0, 6, 0)
 #define SYS_ID_AA64ISAR1_EL1		sys_reg(3, 0, 0, 6, 1)
 
arch/arm64/kvm/hyp/switch.c +6 -0
index 945e79c..35a90b8 100644
@@ -81,11 +81,17 @@ static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu)
 	 * it will cause an exception.
 	 */
 	val = vcpu->arch.hcr_el2;
+
 	if (!(val & HCR_RW) && system_supports_fpsimd()) {
 		write_sysreg(1 << 30, fpexc32_el2);
 		isb();
 	}
+
+	if (val & HCR_RW) /* for AArch64 only: */
+		val |= HCR_TID3; /* TID3: trap feature register accesses */
+
 	write_sysreg(val, hcr_el2);
+
 	/* Trap on AArch32 cp15 c15 accesses (EL1 or EL0) */
 	write_sysreg(1 << 15, hstr_el2);
 	/*
arch/arm64/kvm/sys_regs.c +230 -45
index 2e070d3..b1f7552 100644
@@ -892,6 +892,137 @@ static bool access_cntp_cval(struct kvm_vcpu *vcpu,
 	return true;
 }
 
+/* Read a sanitised cpufeature ID register by sys_reg_desc */
+static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
+{
+	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
+			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+
+	return raz ? 0 : read_sanitised_ftr_reg(id);
+}
+
+/* cpufeature ID register access trap handlers */
+
+static bool __access_id_reg(struct kvm_vcpu *vcpu,
+			    struct sys_reg_params *p,
+			    const struct sys_reg_desc *r,
+			    bool raz)
+{
+	if (p->is_write)
+		return write_to_read_only(vcpu, p, r);
+
+	p->regval = read_id_reg(r, raz);
+	return true;
+}
+
+static bool access_id_reg(struct kvm_vcpu *vcpu,
+			  struct sys_reg_params *p,
+			  const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, false);
+}
+
+static bool access_raz_id_reg(struct kvm_vcpu *vcpu,
+			      struct sys_reg_params *p,
+			      const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, true);
+}
+
+static int reg_from_user(u64 *val, const void __user *uaddr, u64 id);
+static int reg_to_user(void __user *uaddr, const u64 *val, u64 id);
+static u64 sys_reg_to_index(const struct sys_reg_desc *reg);
+
+/*
+ * cpufeature ID register user accessors
+ *
+ * For now, these registers are immutable for userspace, so no values
+ * are stored, and for set_id_reg() we don't allow the effective value
+ * to be changed.
+ */
+static int __get_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	const u64 val = read_id_reg(rd, raz);
+
+	return reg_to_user(uaddr, &val, id);
+}
+
+static int __set_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	int err;
+	u64 val;
+
+	err = reg_from_user(&val, uaddr, id);
+	if (err)
+		return err;
+
+	/* This is what we mean by invariant: you can't change it. */
+	if (val != read_id_reg(rd, raz))
+		return -EINVAL;
+
+	return 0;
+}
+
+static int get_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, false);
+}
+
+static int set_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, false);
+}
+
+static int get_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, true);
+}
+
+static int set_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, true);
+}
+
+/* sys_reg_desc initialiser for known cpufeature ID registers */
+#define ID_SANITISED(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access	= access_id_reg,		\
+	.get_user = get_id_reg,			\
+	.set_user = set_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for architecturally unallocated cpufeature ID
+ * register with encoding Op0=3, Op1=0, CRn=0, CRm=crm, Op2=op2
+ * (1 <= crm < 8, 0 <= Op2 < 8).
+ */
+#define ID_UNALLOCATED(crm, op2) {			\
+	Op0(3), Op1(0), CRn(0), CRm(crm), Op2(op2),	\
+	.access = access_raz_id_reg,			\
+	.get_user = get_raz_id_reg,			\
+	.set_user = set_raz_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for known ID registers that we hide from guests.
+ * For now, these are exposed just like unallocated ID regs: they appear
+ * RAZ for the guest.
+ */
+#define ID_HIDDEN(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access = access_raz_id_reg,		\
+	.get_user = get_raz_id_reg,		\
+	.set_user = set_raz_id_reg,		\
+}
+
 /*
  * Architected system registers.
  * Important: Must be sorted ascending by Op0, Op1, CRn, CRm, Op2
@@ -944,6 +1075,84 @@ static const struct sys_reg_desc sys_reg_descs[] = {
 	{ SYS_DESC(SYS_DBGVCR32_EL2), NULL, reset_val, DBGVCR32_EL2, 0 },
 
 	{ SYS_DESC(SYS_MPIDR_EL1), NULL, reset_mpidr, MPIDR_EL1 },
+
+	/*
+	 * ID regs: all ID_SANITISED() entries here must have corresponding
+	 * entries in arm64_ftr_regs[].
+	 */
+
+	/* AArch64 mappings of the AArch32 ID registers */
+	/* CRm=1 */
+	ID_SANITISED(ID_PFR0_EL1),
+	ID_SANITISED(ID_PFR1_EL1),
+	ID_SANITISED(ID_DFR0_EL1),
+	ID_HIDDEN(ID_AFR0_EL1),
+	ID_SANITISED(ID_MMFR0_EL1),
+	ID_SANITISED(ID_MMFR1_EL1),
+	ID_SANITISED(ID_MMFR2_EL1),
+	ID_SANITISED(ID_MMFR3_EL1),
+
+	/* CRm=2 */
+	ID_SANITISED(ID_ISAR0_EL1),
+	ID_SANITISED(ID_ISAR1_EL1),
+	ID_SANITISED(ID_ISAR2_EL1),
+	ID_SANITISED(ID_ISAR3_EL1),
+	ID_SANITISED(ID_ISAR4_EL1),
+	ID_SANITISED(ID_ISAR5_EL1),
+	ID_SANITISED(ID_MMFR4_EL1),
+	ID_UNALLOCATED(2,7),
+
+	/* CRm=3 */
+	ID_SANITISED(MVFR0_EL1),
+	ID_SANITISED(MVFR1_EL1),
+	ID_SANITISED(MVFR2_EL1),
+	ID_UNALLOCATED(3,3),
+	ID_UNALLOCATED(3,4),
+	ID_UNALLOCATED(3,5),
+	ID_UNALLOCATED(3,6),
+	ID_UNALLOCATED(3,7),
+
+	/* AArch64 ID registers */
+	/* CRm=4 */
+	ID_SANITISED(ID_AA64PFR0_EL1),
+	ID_SANITISED(ID_AA64PFR1_EL1),
+	ID_UNALLOCATED(4,2),
+	ID_UNALLOCATED(4,3),
+	ID_UNALLOCATED(4,4),
+	ID_UNALLOCATED(4,5),
+	ID_UNALLOCATED(4,6),
+	ID_UNALLOCATED(4,7),
+
+	/* CRm=5 */
+	ID_SANITISED(ID_AA64DFR0_EL1),
+	ID_SANITISED(ID_AA64DFR1_EL1),
+	ID_UNALLOCATED(5,2),
+	ID_UNALLOCATED(5,3),
+	ID_HIDDEN(ID_AA64AFR0_EL1),
+	ID_HIDDEN(ID_AA64AFR1_EL1),
+	ID_UNALLOCATED(5,6),
+	ID_UNALLOCATED(5,7),
+
+	/* CRm=6 */
+	ID_SANITISED(ID_AA64ISAR0_EL1),
+	ID_SANITISED(ID_AA64ISAR1_EL1),
+	ID_UNALLOCATED(6,2),
+	ID_UNALLOCATED(6,3),
+	ID_UNALLOCATED(6,4),
+	ID_UNALLOCATED(6,5),
+	ID_UNALLOCATED(6,6),
+	ID_UNALLOCATED(6,7),
+
+	/* CRm=7 */
+	ID_SANITISED(ID_AA64MMFR0_EL1),
+	ID_SANITISED(ID_AA64MMFR1_EL1),
+	ID_SANITISED(ID_AA64MMFR2_EL1),
+	ID_UNALLOCATED(7,3),
+	ID_UNALLOCATED(7,4),
+	ID_UNALLOCATED(7,5),
+	ID_UNALLOCATED(7,6),
+	ID_UNALLOCATED(7,7),
+
 	{ SYS_DESC(SYS_SCTLR_EL1), access_vm_reg, reset_val, SCTLR_EL1, 0x00C50078 },
 	{ SYS_DESC(SYS_CPACR_EL1), NULL, reset_val, CPACR_EL1, 0 },
 	{ SYS_DESC(SYS_TTBR0_EL1), access_vm_reg, reset_unknown, TTBR0_EL1 },
@@ -1790,8 +1999,8 @@ static const struct sys_reg_desc *index_to_sys_reg_desc(struct kvm_vcpu *vcpu,
 	if (!r)
 		r = find_reg(&params, sys_reg_descs, ARRAY_SIZE(sys_reg_descs));
 
-	/* Not saved in the sys_reg array? */
-	if (r && !r->reg)
+	/* Not saved in the sys_reg array and not otherwise accessible? */
+	if (r && !(r->reg || r->get_user))
 		r = NULL;
 
 	return r;
@@ -1815,20 +2024,6 @@ static const struct sys_reg_desc *index_to_sys_reg_desc(struct kvm_vcpu *vcpu,
 FUNCTION_INVARIANT(midr_el1)
 FUNCTION_INVARIANT(ctr_el0)
 FUNCTION_INVARIANT(revidr_el1)
-FUNCTION_INVARIANT(id_pfr0_el1)
-FUNCTION_INVARIANT(id_pfr1_el1)
-FUNCTION_INVARIANT(id_dfr0_el1)
-FUNCTION_INVARIANT(id_afr0_el1)
-FUNCTION_INVARIANT(id_mmfr0_el1)
-FUNCTION_INVARIANT(id_mmfr1_el1)
-FUNCTION_INVARIANT(id_mmfr2_el1)
-FUNCTION_INVARIANT(id_mmfr3_el1)
-FUNCTION_INVARIANT(id_isar0_el1)
-FUNCTION_INVARIANT(id_isar1_el1)
-FUNCTION_INVARIANT(id_isar2_el1)
-FUNCTION_INVARIANT(id_isar3_el1)
-FUNCTION_INVARIANT(id_isar4_el1)
-FUNCTION_INVARIANT(id_isar5_el1)
 FUNCTION_INVARIANT(clidr_el1)
 FUNCTION_INVARIANT(aidr_el1)
 
@@ -1836,20 +2031,6 @@ FUNCTION_INVARIANT(aidr_el1)
 static struct sys_reg_desc invariant_sys_regs[] = {
 	{ SYS_DESC(SYS_MIDR_EL1), NULL, get_midr_el1 },
 	{ SYS_DESC(SYS_REVIDR_EL1), NULL, get_revidr_el1 },
-	{ SYS_DESC(SYS_ID_PFR0_EL1), NULL, get_id_pfr0_el1 },
-	{ SYS_DESC(SYS_ID_PFR1_EL1), NULL, get_id_pfr1_el1 },
-	{ SYS_DESC(SYS_ID_DFR0_EL1), NULL, get_id_dfr0_el1 },
-	{ SYS_DESC(SYS_ID_AFR0_EL1), NULL, get_id_afr0_el1 },
-	{ SYS_DESC(SYS_ID_MMFR0_EL1), NULL, get_id_mmfr0_el1 },
-	{ SYS_DESC(SYS_ID_MMFR1_EL1), NULL, get_id_mmfr1_el1 },
-	{ SYS_DESC(SYS_ID_MMFR2_EL1), NULL, get_id_mmfr2_el1 },
-	{ SYS_DESC(SYS_ID_MMFR3_EL1), NULL, get_id_mmfr3_el1 },
-	{ SYS_DESC(SYS_ID_ISAR0_EL1), NULL, get_id_isar0_el1 },
-	{ SYS_DESC(SYS_ID_ISAR1_EL1), NULL, get_id_isar1_el1 },
-	{ SYS_DESC(SYS_ID_ISAR2_EL1), NULL, get_id_isar2_el1 },
-	{ SYS_DESC(SYS_ID_ISAR3_EL1), NULL, get_id_isar3_el1 },
-	{ SYS_DESC(SYS_ID_ISAR4_EL1), NULL, get_id_isar4_el1 },
-	{ SYS_DESC(SYS_ID_ISAR5_EL1), NULL, get_id_isar5_el1 },
 	{ SYS_DESC(SYS_CLIDR_EL1), NULL, get_clidr_el1 },
 	{ SYS_DESC(SYS_AIDR_EL1), NULL, get_aidr_el1 },
 	{ SYS_DESC(SYS_CTR_EL0), NULL, get_ctr_el0 },
@@ -2079,12 +2260,31 @@ static bool copy_reg_to_user(const struct sys_reg_desc *reg, u64 __user **uind)
 	return true;
 }
 
+static int walk_one_sys_reg(const struct sys_reg_desc *rd,
+			    u64 __user **uind,
+			    unsigned int *total)
+{
+	/*
+	 * Ignore registers we trap but don't save,
+	 * and for which no custom user accessor is provided.
+	 */
+	if (!(rd->reg || rd->get_user))
+		return 0;
+
+	if (!copy_reg_to_user(rd, uind))
+		return -EFAULT;
+
+	(*total)++;
+	return 0;
+}
+
 /* Assumed ordered tables, see kvm_sys_reg_table_init. */
 static int walk_sys_regs(struct kvm_vcpu *vcpu, u64 __user *uind)
 {
 	const struct sys_reg_desc *i1, *i2, *end1, *end2;
 	unsigned int total = 0;
 	size_t num;
+	int err;
 
 	/* We check for duplicates here, to allow arch-specific overrides. */
 	i1 = get_target_table(vcpu->arch.target, true, &num);
@@ -2098,21 +2298,13 @@ static int walk_sys_regs(struct kvm_vcpu *vcpu, u64 __user *uind)
 	while (i1 || i2) {
 		int cmp = cmp_sys_reg(i1, i2);
 		/* target-specific overrides generic entry. */
-		if (cmp <= 0) {
-			/* Ignore registers we trap but don't save. */
-			if (i1->reg) {
-				if (!copy_reg_to_user(i1, &uind))
-					return -EFAULT;
-				total++;
-			}
-		} else {
-			/* Ignore registers we trap but don't save. */
-			if (i2->reg) {
-				if (!copy_reg_to_user(i2, &uind))
-					return -EFAULT;
-				total++;
-			}
-		}

arch/arm64/kvm/sys_regs.c static int walk_sys_regs(struct kvm_vcpu *vcpu, u64 __user *uind) · line 2310

Quoted 10 lines
arch/arm64/kvm/sys_regs.c +7 -0
+		if (cmp <= 0)
+			err = walk_one_sys_reg(i1, &uind, &total);
+		else
+			err = walk_one_sys_reg(i2, &uind, &total);
+
+		if (err)
+			return err;
 
 		if (cmp <= 0 && ++i1 == end1)
 			i1 = NULL;
	M.
Signature · 1 line
Jazz is not dead. It just smells funny...
#7 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

In reply to Dave Martin
Quoted 72 lines · Dave Martin

Currently, a guest kernel sees the true CPU feature registers (ID_*_EL1) when it reads them using MRS instructions. This means that the guest will observe features that are present in the hardware but the host doesn't understand or doesn't provide support for. A guest may legimitately try to use such a feature as per the architecture, but use of the feature may trap instead of working normally, triggering undef injection into the guest.

This is not a problem for the host, but the guest may go wrong when running on newer hardware than the host knows about.

This patch hides from guest VMs any AArch64-specific CPU features that the host doesn't support, by exposing to the guest the sanitised versions of the registers computed by the cpufeatures framework, instead of the true hardware registers. To achieve this, HCR_EL2.TID3 is now set for AArch64 guests, and emulation code is added to KVM to report the sanitised versions of the affected registers in response to MRS and register reads from userspace.

The affected registers are removed from invariant_sys_regs[] (since the invariant_sys_regs handling is no longer quite correct for them) and added to sys_reg_desgs[], with appropriate access(), get_user() and set_user() methods. No runtime vcpu storage is allocated for the registers: instead, they are read on demand from the cpufeatures framework. This may need modification in the future if there is a need for userspace to customise the features visible to the guest.

Attempts by userspace to write the registers are handled similarly to the current invariant_sys_regs handling: writes are permitted, but only if they don't attempt to change the value. This is sufficient to support VM snapshot/restore from userspace.

Because of the additional registers, restoring a VM on an older kernel may not work unless userspace knows how to handle the extra VM registers exposed to the KVM user ABI by this patch.

Under the principle of least damage, this patch makes no attempt to handle any of the other registers currently in invariant_sys_regs[], or to emulate registers for AArch32: however, these could be handled in a similar way in future, as necessary.

---
 arch/arm64/include/asm/sysreg.h |   3 +
 arch/arm64/kvm/hyp/switch.c     |   6 +
 arch/arm64/kvm/sys_regs.c       | 282 +++++++++++++++++++++++++++++++++-------
 3 files changed, 246 insertions(+), 45 deletions(-)
arch/arm64/include/asm/sysreg.h +3 -0
index f707fed..480ecd6 100644
@@ -149,6 +149,9 @@
 #define SYS_ID_AA64DFR0_EL1		sys_reg(3, 0, 0, 5, 0)
 #define SYS_ID_AA64DFR1_EL1		sys_reg(3, 0, 0, 5, 1)
 
+#define SYS_ID_AA64AFR0_EL1		sys_reg(3, 0, 0, 5, 4)
+#define SYS_ID_AA64AFR1_EL1		sys_reg(3, 0, 0, 5, 5)
+
 #define SYS_ID_AA64ISAR0_EL1		sys_reg(3, 0, 0, 6, 0)
 #define SYS_ID_AA64ISAR1_EL1		sys_reg(3, 0, 0, 6, 1)
 
arch/arm64/kvm/hyp/switch.c +0 -0
index 945e79c..35a90b8 100644
@@ -81,11 +81,17 @@ static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu)
 	 * it will cause an exception.
 	 */

arch/arm64/kvm/hyp/switch.c static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu) · line 92

Quoted 10 lines
arch/arm64/kvm/hyp/switch.c +5 -0
 	val = vcpu->arch.hcr_el2;
+
 	if (!(val & HCR_RW) && system_supports_fpsimd()) {
 		write_sysreg(1 << 30, fpexc32_el2);
 		isb();
 	}
+
+	if (val & HCR_RW) /* for AArch64 only: */
+		val |= HCR_TID3; /* TID3: trap feature register accesses */
+

Since we're setting this for all 64-bit VMs, can we not set this in vcpu_reset_hcr instead?

Quoted 127 lines
arch/arm64/kvm/hyp/switch.c +1 -0
 	write_sysreg(val, hcr_el2);
+
 	/* Trap on AArch32 cp15 c15 accesses (EL1 or EL0) */
 	write_sysreg(1 << 15, hstr_el2);
 	/*
arch/arm64/kvm/sys_regs.c +114 -0
index 2e070d3..b1f7552 100644
@@ -892,6 +892,137 @@ static bool access_cntp_cval(struct kvm_vcpu *vcpu,
 	return true;
 }
 
+/* Read a sanitised cpufeature ID register by sys_reg_desc */
+static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
+{
+	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
+			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+
+	return raz ? 0 : read_sanitised_ftr_reg(id);
+}
+
+/* cpufeature ID register access trap handlers */
+
+static bool __access_id_reg(struct kvm_vcpu *vcpu,
+			    struct sys_reg_params *p,
+			    const struct sys_reg_desc *r,
+			    bool raz)
+{
+	if (p->is_write)
+		return write_to_read_only(vcpu, p, r);
+
+	p->regval = read_id_reg(r, raz);
+	return true;
+}
+
+static bool access_id_reg(struct kvm_vcpu *vcpu,
+			  struct sys_reg_params *p,
+			  const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, false);
+}
+
+static bool access_raz_id_reg(struct kvm_vcpu *vcpu,
+			      struct sys_reg_params *p,
+			      const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, true);
+}
+
+static int reg_from_user(u64 *val, const void __user *uaddr, u64 id);
+static int reg_to_user(void __user *uaddr, const u64 *val, u64 id);
+static u64 sys_reg_to_index(const struct sys_reg_desc *reg);
+
+/*
+ * cpufeature ID register user accessors
+ *
+ * For now, these registers are immutable for userspace, so no values
+ * are stored, and for set_id_reg() we don't allow the effective value
+ * to be changed.
+ */
+static int __get_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	const u64 val = read_id_reg(rd, raz);
+
+	return reg_to_user(uaddr, &val, id);
+}
+
+static int __set_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	int err;
+	u64 val;
+
+	err = reg_from_user(&val, uaddr, id);
+	if (err)
+		return err;
+
+	/* This is what we mean by invariant: you can't change it. */
+	if (val != read_id_reg(rd, raz))
+		return -EINVAL;
+
+	return 0;
+}
+
+static int get_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, false);
+}
+
+static int set_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, false);
+}
+
+static int get_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, true);
+}
+
+static int set_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, true);
+}
+
+/* sys_reg_desc initialiser for known cpufeature ID registers */
+#define ID_SANITISED(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access	= access_id_reg,		\
+	.get_user = get_id_reg,			\
+	.set_user = set_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for architecturally unallocated cpufeature ID
+ * register with encoding Op0=3, Op1=0, CRn=0, CRm=crm, Op2=op2
+ * (1 <= crm < 8, 0 <= Op2 < 8).
+ */
+#define ID_UNALLOCATED(crm, op2) {			\
+	Op0(3), Op1(0), CRn(0), CRm(crm), Op2(op2),	\

arch/arm64/kvm/sys_regs.c static bool access_cntp_cval(struct kvm_vcpu *vcpu, · line 1018

Quoted 10 lines
arch/arm64/kvm/sys_regs.c +10 -0
+	.access = access_raz_id_reg,			\
+	.get_user = get_raz_id_reg,			\
+	.set_user = set_raz_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for known ID registers that we hide from guests.
+ * For now, these are exposed just like unallocated ID regs: they appear
+ * RAZ for the guest.
+ */

What is a hidden ID register as opposed to an unallocated one?

Shouldn't one of them presumably cause an undefined exception in the guest?

Quoted 211 lines
arch/arm64/kvm/sys_regs.c +113 -45
+#define ID_HIDDEN(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access = access_raz_id_reg,		\
+	.get_user = get_raz_id_reg,		\
+	.set_user = set_raz_id_reg,		\
+}
+
 /*
  * Architected system registers.
  * Important: Must be sorted ascending by Op0, Op1, CRn, CRm, Op2
@@ -944,6 +1075,84 @@ static const struct sys_reg_desc sys_reg_descs[] = {
 	{ SYS_DESC(SYS_DBGVCR32_EL2), NULL, reset_val, DBGVCR32_EL2, 0 },
 
 	{ SYS_DESC(SYS_MPIDR_EL1), NULL, reset_mpidr, MPIDR_EL1 },
+
+	/*
+	 * ID regs: all ID_SANITISED() entries here must have corresponding
+	 * entries in arm64_ftr_regs[].
+	 */
+
+	/* AArch64 mappings of the AArch32 ID registers */
+	/* CRm=1 */
+	ID_SANITISED(ID_PFR0_EL1),
+	ID_SANITISED(ID_PFR1_EL1),
+	ID_SANITISED(ID_DFR0_EL1),
+	ID_HIDDEN(ID_AFR0_EL1),
+	ID_SANITISED(ID_MMFR0_EL1),
+	ID_SANITISED(ID_MMFR1_EL1),
+	ID_SANITISED(ID_MMFR2_EL1),
+	ID_SANITISED(ID_MMFR3_EL1),
+
+	/* CRm=2 */
+	ID_SANITISED(ID_ISAR0_EL1),
+	ID_SANITISED(ID_ISAR1_EL1),
+	ID_SANITISED(ID_ISAR2_EL1),
+	ID_SANITISED(ID_ISAR3_EL1),
+	ID_SANITISED(ID_ISAR4_EL1),
+	ID_SANITISED(ID_ISAR5_EL1),
+	ID_SANITISED(ID_MMFR4_EL1),
+	ID_UNALLOCATED(2,7),
+
+	/* CRm=3 */
+	ID_SANITISED(MVFR0_EL1),
+	ID_SANITISED(MVFR1_EL1),
+	ID_SANITISED(MVFR2_EL1),
+	ID_UNALLOCATED(3,3),
+	ID_UNALLOCATED(3,4),
+	ID_UNALLOCATED(3,5),
+	ID_UNALLOCATED(3,6),
+	ID_UNALLOCATED(3,7),
+
+	/* AArch64 ID registers */
+	/* CRm=4 */
+	ID_SANITISED(ID_AA64PFR0_EL1),
+	ID_SANITISED(ID_AA64PFR1_EL1),
+	ID_UNALLOCATED(4,2),
+	ID_UNALLOCATED(4,3),
+	ID_UNALLOCATED(4,4),
+	ID_UNALLOCATED(4,5),
+	ID_UNALLOCATED(4,6),
+	ID_UNALLOCATED(4,7),
+
+	/* CRm=5 */
+	ID_SANITISED(ID_AA64DFR0_EL1),
+	ID_SANITISED(ID_AA64DFR1_EL1),
+	ID_UNALLOCATED(5,2),
+	ID_UNALLOCATED(5,3),
+	ID_HIDDEN(ID_AA64AFR0_EL1),
+	ID_HIDDEN(ID_AA64AFR1_EL1),
+	ID_UNALLOCATED(5,6),
+	ID_UNALLOCATED(5,7),
+
+	/* CRm=6 */
+	ID_SANITISED(ID_AA64ISAR0_EL1),
+	ID_SANITISED(ID_AA64ISAR1_EL1),
+	ID_UNALLOCATED(6,2),
+	ID_UNALLOCATED(6,3),
+	ID_UNALLOCATED(6,4),
+	ID_UNALLOCATED(6,5),
+	ID_UNALLOCATED(6,6),
+	ID_UNALLOCATED(6,7),
+
+	/* CRm=7 */
+	ID_SANITISED(ID_AA64MMFR0_EL1),
+	ID_SANITISED(ID_AA64MMFR1_EL1),
+	ID_SANITISED(ID_AA64MMFR2_EL1),
+	ID_UNALLOCATED(7,3),
+	ID_UNALLOCATED(7,4),
+	ID_UNALLOCATED(7,5),
+	ID_UNALLOCATED(7,6),
+	ID_UNALLOCATED(7,7),
+
 	{ SYS_DESC(SYS_SCTLR_EL1), access_vm_reg, reset_val, SCTLR_EL1, 0x00C50078 },
 	{ SYS_DESC(SYS_CPACR_EL1), NULL, reset_val, CPACR_EL1, 0 },
 	{ SYS_DESC(SYS_TTBR0_EL1), access_vm_reg, reset_unknown, TTBR0_EL1 },
@@ -1790,8 +1999,8 @@ static const struct sys_reg_desc *index_to_sys_reg_desc(struct kvm_vcpu *vcpu,
 	if (!r)
 		r = find_reg(&params, sys_reg_descs, ARRAY_SIZE(sys_reg_descs));
 
-	/* Not saved in the sys_reg array? */
-	if (r && !r->reg)
+	/* Not saved in the sys_reg array and not otherwise accessible? */
+	if (r && !(r->reg || r->get_user))
 		r = NULL;
 
 	return r;
@@ -1815,20 +2024,6 @@ static const struct sys_reg_desc *index_to_sys_reg_desc(struct kvm_vcpu *vcpu,
 FUNCTION_INVARIANT(midr_el1)
 FUNCTION_INVARIANT(ctr_el0)
 FUNCTION_INVARIANT(revidr_el1)
-FUNCTION_INVARIANT(id_pfr0_el1)
-FUNCTION_INVARIANT(id_pfr1_el1)
-FUNCTION_INVARIANT(id_dfr0_el1)
-FUNCTION_INVARIANT(id_afr0_el1)
-FUNCTION_INVARIANT(id_mmfr0_el1)
-FUNCTION_INVARIANT(id_mmfr1_el1)
-FUNCTION_INVARIANT(id_mmfr2_el1)
-FUNCTION_INVARIANT(id_mmfr3_el1)
-FUNCTION_INVARIANT(id_isar0_el1)
-FUNCTION_INVARIANT(id_isar1_el1)
-FUNCTION_INVARIANT(id_isar2_el1)
-FUNCTION_INVARIANT(id_isar3_el1)
-FUNCTION_INVARIANT(id_isar4_el1)
-FUNCTION_INVARIANT(id_isar5_el1)
 FUNCTION_INVARIANT(clidr_el1)
 FUNCTION_INVARIANT(aidr_el1)
 
@@ -1836,20 +2031,6 @@ FUNCTION_INVARIANT(aidr_el1)
 static struct sys_reg_desc invariant_sys_regs[] = {
 	{ SYS_DESC(SYS_MIDR_EL1), NULL, get_midr_el1 },
 	{ SYS_DESC(SYS_REVIDR_EL1), NULL, get_revidr_el1 },
-	{ SYS_DESC(SYS_ID_PFR0_EL1), NULL, get_id_pfr0_el1 },
-	{ SYS_DESC(SYS_ID_PFR1_EL1), NULL, get_id_pfr1_el1 },
-	{ SYS_DESC(SYS_ID_DFR0_EL1), NULL, get_id_dfr0_el1 },
-	{ SYS_DESC(SYS_ID_AFR0_EL1), NULL, get_id_afr0_el1 },
-	{ SYS_DESC(SYS_ID_MMFR0_EL1), NULL, get_id_mmfr0_el1 },
-	{ SYS_DESC(SYS_ID_MMFR1_EL1), NULL, get_id_mmfr1_el1 },
-	{ SYS_DESC(SYS_ID_MMFR2_EL1), NULL, get_id_mmfr2_el1 },
-	{ SYS_DESC(SYS_ID_MMFR3_EL1), NULL, get_id_mmfr3_el1 },
-	{ SYS_DESC(SYS_ID_ISAR0_EL1), NULL, get_id_isar0_el1 },
-	{ SYS_DESC(SYS_ID_ISAR1_EL1), NULL, get_id_isar1_el1 },
-	{ SYS_DESC(SYS_ID_ISAR2_EL1), NULL, get_id_isar2_el1 },
-	{ SYS_DESC(SYS_ID_ISAR3_EL1), NULL, get_id_isar3_el1 },
-	{ SYS_DESC(SYS_ID_ISAR4_EL1), NULL, get_id_isar4_el1 },
-	{ SYS_DESC(SYS_ID_ISAR5_EL1), NULL, get_id_isar5_el1 },
 	{ SYS_DESC(SYS_CLIDR_EL1), NULL, get_clidr_el1 },
 	{ SYS_DESC(SYS_AIDR_EL1), NULL, get_aidr_el1 },
 	{ SYS_DESC(SYS_CTR_EL0), NULL, get_ctr_el0 },
@@ -2079,12 +2260,31 @@ static bool copy_reg_to_user(const struct sys_reg_desc *reg, u64 __user **uind)
 	return true;
 }
 
+static int walk_one_sys_reg(const struct sys_reg_desc *rd,
+			    u64 __user **uind,
+			    unsigned int *total)
+{
+	/*
+	 * Ignore registers we trap but don't save,
+	 * and for which no custom user accessor is provided.
+	 */
+	if (!(rd->reg || rd->get_user))
+		return 0;
+
+	if (!copy_reg_to_user(rd, uind))
+		return -EFAULT;
+
+	(*total)++;
+	return 0;
+}
+
 /* Assumed ordered tables, see kvm_sys_reg_table_init. */
 static int walk_sys_regs(struct kvm_vcpu *vcpu, u64 __user *uind)
 {
 	const struct sys_reg_desc *i1, *i2, *end1, *end2;
 	unsigned int total = 0;
 	size_t num;
+	int err;
 
 	/* We check for duplicates here, to allow arch-specific overrides. */
 	i1 = get_target_table(vcpu->arch.target, true, &num);
@@ -2098,21 +2298,13 @@ static int walk_sys_regs(struct kvm_vcpu *vcpu, u64 __user *uind)
 	while (i1 || i2) {
 		int cmp = cmp_sys_reg(i1, i2);
 		/* target-specific overrides generic entry. */
-		if (cmp <= 0) {
-			/* Ignore registers we trap but don't save. */
-			if (i1->reg) {
-				if (!copy_reg_to_user(i1, &uind))
-					return -EFAULT;
-				total++;
-			}
-		} else {
-			/* Ignore registers we trap but don't save. */
-			if (i2->reg) {
-				if (!copy_reg_to_user(i2, &uind))
-					return -EFAULT;
-				total++;
-			}
-		}
+		if (cmp <= 0)
+			err = walk_one_sys_reg(i1, &uind, &total);
+		else
+			err = walk_one_sys_reg(i2, &uind, &total);
+
+		if (err)
+			return err;
 
 		if (cmp <= 0 && ++i1 == end1)
 			i1 = NULL;
Signature · 1 line
2.1.4

Thanks,
-Christoffer

#8 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

Quoted 218 lines · Christoffer Dall
Quoted 72 lines · Dave Martin

Currently, a guest kernel sees the true CPU feature registers (ID_*_EL1) when it reads them using MRS instructions. This means that the guest will observe features that are present in the hardware but the host doesn't understand or doesn't provide support for. A guest may legimitately try to use such a feature as per the architecture, but use of the feature may trap instead of working normally, triggering undef injection into the guest.

This is not a problem for the host, but the guest may go wrong when running on newer hardware than the host knows about.

This patch hides from guest VMs any AArch64-specific CPU features that the host doesn't support, by exposing to the guest the sanitised versions of the registers computed by the cpufeatures framework, instead of the true hardware registers. To achieve this, HCR_EL2.TID3 is now set for AArch64 guests, and emulation code is added to KVM to report the sanitised versions of the affected registers in response to MRS and register reads from userspace.

The affected registers are removed from invariant_sys_regs[] (since the invariant_sys_regs handling is no longer quite correct for them) and added to sys_reg_desgs[], with appropriate access(), get_user() and set_user() methods. No runtime vcpu storage is allocated for the registers: instead, they are read on demand from the cpufeatures framework. This may need modification in the future if there is a need for userspace to customise the features visible to the guest.

Attempts by userspace to write the registers are handled similarly to the current invariant_sys_regs handling: writes are permitted, but only if they don't attempt to change the value. This is sufficient to support VM snapshot/restore from userspace.

Because of the additional registers, restoring a VM on an older kernel may not work unless userspace knows how to handle the extra VM registers exposed to the KVM user ABI by this patch.

Under the principle of least damage, this patch makes no attempt to handle any of the other registers currently in invariant_sys_regs[], or to emulate registers for AArch32: however, these could be handled in a similar way in future, as necessary.

---
 arch/arm64/include/asm/sysreg.h |   3 +
 arch/arm64/kvm/hyp/switch.c     |   6 +
 arch/arm64/kvm/sys_regs.c       | 282 +++++++++++++++++++++++++++++++++-------
 3 files changed, 246 insertions(+), 45 deletions(-)
arch/arm64/include/asm/sysreg.h +3 -0
index f707fed..480ecd6 100644
@@ -149,6 +149,9 @@
 #define SYS_ID_AA64DFR0_EL1		sys_reg(3, 0, 0, 5, 0)
 #define SYS_ID_AA64DFR1_EL1		sys_reg(3, 0, 0, 5, 1)
 
+#define SYS_ID_AA64AFR0_EL1		sys_reg(3, 0, 0, 5, 4)
+#define SYS_ID_AA64AFR1_EL1		sys_reg(3, 0, 0, 5, 5)
+
 #define SYS_ID_AA64ISAR0_EL1		sys_reg(3, 0, 0, 6, 0)
 #define SYS_ID_AA64ISAR1_EL1		sys_reg(3, 0, 0, 6, 1)
 
arch/arm64/kvm/hyp/switch.c +0 -0
index 945e79c..35a90b8 100644
@@ -81,11 +81,17 @@ static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu)
 	 * it will cause an exception.
 	 */

arch/arm64/kvm/hyp/switch.c static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu) · line 92

Quoted 10 lines
arch/arm64/kvm/hyp/switch.c +5 -0
 	val = vcpu->arch.hcr_el2;
+
 	if (!(val & HCR_RW) && system_supports_fpsimd()) {
 		write_sysreg(1 << 30, fpexc32_el2);
 		isb();
 	}
+
+	if (val & HCR_RW) /* for AArch64 only: */
+		val |= HCR_TID3; /* TID3: trap feature register accesses */
+

Since we're setting this for all 64-bit VMs, can we not set this in vcpu_reset_hcr instead?

Quoted 131 lines
arch/arm64/kvm/hyp/switch.c +1 -0
 	write_sysreg(val, hcr_el2);
+
 	/* Trap on AArch32 cp15 c15 accesses (EL1 or EL0) */
 	write_sysreg(1 << 15, hstr_el2);
 	/*
arch/arm64/kvm/sys_regs.c +118 -0
index 2e070d3..b1f7552 100644
@@ -892,6 +892,137 @@ static bool access_cntp_cval(struct kvm_vcpu *vcpu,
 	return true;
 }
 
+/* Read a sanitised cpufeature ID register by sys_reg_desc */
+static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
+{
+	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
+			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+
+	return raz ? 0 : read_sanitised_ftr_reg(id);
+}
+
+/* cpufeature ID register access trap handlers */
+
+static bool __access_id_reg(struct kvm_vcpu *vcpu,
+			    struct sys_reg_params *p,
+			    const struct sys_reg_desc *r,
+			    bool raz)
+{
+	if (p->is_write)
+		return write_to_read_only(vcpu, p, r);
+
+	p->regval = read_id_reg(r, raz);
+	return true;
+}
+
+static bool access_id_reg(struct kvm_vcpu *vcpu,
+			  struct sys_reg_params *p,
+			  const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, false);
+}
+
+static bool access_raz_id_reg(struct kvm_vcpu *vcpu,
+			      struct sys_reg_params *p,
+			      const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, true);
+}
+
+static int reg_from_user(u64 *val, const void __user *uaddr, u64 id);
+static int reg_to_user(void __user *uaddr, const u64 *val, u64 id);
+static u64 sys_reg_to_index(const struct sys_reg_desc *reg);
+
+/*
+ * cpufeature ID register user accessors
+ *
+ * For now, these registers are immutable for userspace, so no values
+ * are stored, and for set_id_reg() we don't allow the effective value
+ * to be changed.
+ */
+static int __get_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	const u64 val = read_id_reg(rd, raz);
+
+	return reg_to_user(uaddr, &val, id);
+}
+
+static int __set_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	int err;
+	u64 val;
+
+	err = reg_from_user(&val, uaddr, id);
+	if (err)
+		return err;
+
+	/* This is what we mean by invariant: you can't change it. */
+	if (val != read_id_reg(rd, raz))
+		return -EINVAL;
+
+	return 0;
+}
+
+static int get_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, false);
+}
+
+static int set_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, false);
+}
+
+static int get_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, true);
+}
+
+static int set_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, true);
+}
+
+/* sys_reg_desc initialiser for known cpufeature ID registers */
+#define ID_SANITISED(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access	= access_id_reg,		\
+	.get_user = get_id_reg,			\
+	.set_user = set_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for architecturally unallocated cpufeature ID
+ * register with encoding Op0=3, Op1=0, CRn=0, CRm=crm, Op2=op2
+ * (1 <= crm < 8, 0 <= Op2 < 8).
+ */
+#define ID_UNALLOCATED(crm, op2) {			\
+	Op0(3), Op1(0), CRn(0), CRm(crm), Op2(op2),	\
+	.access = access_raz_id_reg,			\
+	.get_user = get_raz_id_reg,			\
+	.set_user = set_raz_id_reg,			\
+}
Quoted 8 lines

arch/arm64/kvm/sys_regs.c static bool access_cntp_cval(struct kvm_vcpu *vcpu, · line 1018

Quoted 6 lines
arch/arm64/kvm/sys_regs.c +6 -0
+
+/*
+ * sys_reg_desc initialiser for known ID registers that we hide from guests.
+ * For now, these are exposed just like unallocated ID regs: they appear
+ * RAZ for the guest.
+ */

What is a hidden ID register as opposed to an unallocated one?

A hidden register is one where all the features have been removed (RAZ), making it similar to an unallocated one.

Quoted 2 lines

Shouldn't one of them presumably cause an undefined exception in the guest?

No, that'd be a violation of the architecture. The unallocated ID registers are required to be RAZ (see table D9-2 in D9.3.1), so that software can probe for feature without running the risk of getting an UNDEF.

Thanks,

	M.
Signature · 1 line
Jazz is not dead. It just smells funny...
#9 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

Quoted 231 lines · Marc Zyngier
Quoted 218 lines · Christoffer Dall
Quoted 72 lines · Dave Martin

Currently, a guest kernel sees the true CPU feature registers (ID_*_EL1) when it reads them using MRS instructions. This means that the guest will observe features that are present in the hardware but the host doesn't understand or doesn't provide support for. A guest may legimitately try to use such a feature as per the architecture, but use of the feature may trap instead of working normally, triggering undef injection into the guest.

This is not a problem for the host, but the guest may go wrong when running on newer hardware than the host knows about.

This patch hides from guest VMs any AArch64-specific CPU features that the host doesn't support, by exposing to the guest the sanitised versions of the registers computed by the cpufeatures framework, instead of the true hardware registers. To achieve this, HCR_EL2.TID3 is now set for AArch64 guests, and emulation code is added to KVM to report the sanitised versions of the affected registers in response to MRS and register reads from userspace.

The affected registers are removed from invariant_sys_regs[] (since the invariant_sys_regs handling is no longer quite correct for them) and added to sys_reg_desgs[], with appropriate access(), get_user() and set_user() methods. No runtime vcpu storage is allocated for the registers: instead, they are read on demand from the cpufeatures framework. This may need modification in the future if there is a need for userspace to customise the features visible to the guest.

Attempts by userspace to write the registers are handled similarly to the current invariant_sys_regs handling: writes are permitted, but only if they don't attempt to change the value. This is sufficient to support VM snapshot/restore from userspace.

Because of the additional registers, restoring a VM on an older kernel may not work unless userspace knows how to handle the extra VM registers exposed to the KVM user ABI by this patch.

Under the principle of least damage, this patch makes no attempt to handle any of the other registers currently in invariant_sys_regs[], or to emulate registers for AArch32: however, these could be handled in a similar way in future, as necessary.

---
 arch/arm64/include/asm/sysreg.h |   3 +
 arch/arm64/kvm/hyp/switch.c     |   6 +
 arch/arm64/kvm/sys_regs.c       | 282 +++++++++++++++++++++++++++++++++-------
 3 files changed, 246 insertions(+), 45 deletions(-)
arch/arm64/include/asm/sysreg.h +3 -0
index f707fed..480ecd6 100644
@@ -149,6 +149,9 @@
 #define SYS_ID_AA64DFR0_EL1		sys_reg(3, 0, 0, 5, 0)
 #define SYS_ID_AA64DFR1_EL1		sys_reg(3, 0, 0, 5, 1)
 
+#define SYS_ID_AA64AFR0_EL1		sys_reg(3, 0, 0, 5, 4)
+#define SYS_ID_AA64AFR1_EL1		sys_reg(3, 0, 0, 5, 5)
+
 #define SYS_ID_AA64ISAR0_EL1		sys_reg(3, 0, 0, 6, 0)
 #define SYS_ID_AA64ISAR1_EL1		sys_reg(3, 0, 0, 6, 1)
 
arch/arm64/kvm/hyp/switch.c +0 -0
index 945e79c..35a90b8 100644
@@ -81,11 +81,17 @@ static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu)
 	 * it will cause an exception.
 	 */

arch/arm64/kvm/hyp/switch.c static void __hyp_text __activate_traps(struct kvm_vcpu *vcpu) · line 92

Quoted 10 lines
arch/arm64/kvm/hyp/switch.c +5 -0
 	val = vcpu->arch.hcr_el2;
+
 	if (!(val & HCR_RW) && system_supports_fpsimd()) {
 		write_sysreg(1 << 30, fpexc32_el2);
 		isb();
 	}
+
+	if (val & HCR_RW) /* for AArch64 only: */
+		val |= HCR_TID3; /* TID3: trap feature register accesses */
+

Since we're setting this for all 64-bit VMs, can we not set this in vcpu_reset_hcr instead?

Quoted 131 lines
arch/arm64/kvm/hyp/switch.c +1 -0
 	write_sysreg(val, hcr_el2);
+
 	/* Trap on AArch32 cp15 c15 accesses (EL1 or EL0) */
 	write_sysreg(1 << 15, hstr_el2);
 	/*
arch/arm64/kvm/sys_regs.c +118 -0
index 2e070d3..b1f7552 100644
@@ -892,6 +892,137 @@ static bool access_cntp_cval(struct kvm_vcpu *vcpu,
 	return true;
 }
 
+/* Read a sanitised cpufeature ID register by sys_reg_desc */
+static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
+{
+	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
+			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+
+	return raz ? 0 : read_sanitised_ftr_reg(id);
+}
+
+/* cpufeature ID register access trap handlers */
+
+static bool __access_id_reg(struct kvm_vcpu *vcpu,
+			    struct sys_reg_params *p,
+			    const struct sys_reg_desc *r,
+			    bool raz)
+{
+	if (p->is_write)
+		return write_to_read_only(vcpu, p, r);
+
+	p->regval = read_id_reg(r, raz);
+	return true;
+}
+
+static bool access_id_reg(struct kvm_vcpu *vcpu,
+			  struct sys_reg_params *p,
+			  const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, false);
+}
+
+static bool access_raz_id_reg(struct kvm_vcpu *vcpu,
+			      struct sys_reg_params *p,
+			      const struct sys_reg_desc *r)
+{
+	return __access_id_reg(vcpu, p, r, true);
+}
+
+static int reg_from_user(u64 *val, const void __user *uaddr, u64 id);
+static int reg_to_user(void __user *uaddr, const u64 *val, u64 id);
+static u64 sys_reg_to_index(const struct sys_reg_desc *reg);
+
+/*
+ * cpufeature ID register user accessors
+ *
+ * For now, these registers are immutable for userspace, so no values
+ * are stored, and for set_id_reg() we don't allow the effective value
+ * to be changed.
+ */
+static int __get_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	const u64 val = read_id_reg(rd, raz);
+
+	return reg_to_user(uaddr, &val, id);
+}
+
+static int __set_id_reg(const struct sys_reg_desc *rd, void __user *uaddr,
+			bool raz)
+{
+	const u64 id = sys_reg_to_index(rd);
+	int err;
+	u64 val;
+
+	err = reg_from_user(&val, uaddr, id);
+	if (err)
+		return err;
+
+	/* This is what we mean by invariant: you can't change it. */
+	if (val != read_id_reg(rd, raz))
+		return -EINVAL;
+
+	return 0;
+}
+
+static int get_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, false);
+}
+
+static int set_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+		      const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, false);
+}
+
+static int get_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __get_id_reg(rd, uaddr, true);
+}
+
+static int set_raz_id_reg(struct kvm_vcpu *vcpu, const struct sys_reg_desc *rd,
+			  const struct kvm_one_reg *reg, void __user *uaddr)
+{
+	return __set_id_reg(rd, uaddr, true);
+}
+
+/* sys_reg_desc initialiser for known cpufeature ID registers */
+#define ID_SANITISED(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access	= access_id_reg,		\
+	.get_user = get_id_reg,			\
+	.set_user = set_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for architecturally unallocated cpufeature ID
+ * register with encoding Op0=3, Op1=0, CRn=0, CRm=crm, Op2=op2
+ * (1 <= crm < 8, 0 <= Op2 < 8).
+ */
+#define ID_UNALLOCATED(crm, op2) {			\
+	Op0(3), Op1(0), CRn(0), CRm(crm), Op2(op2),	\
+	.access = access_raz_id_reg,			\
+	.get_user = get_raz_id_reg,			\
+	.set_user = set_raz_id_reg,			\
+}
Quoted 8 lines

arch/arm64/kvm/sys_regs.c static bool access_cntp_cval(struct kvm_vcpu *vcpu, · line 1018

Quoted 6 lines
arch/arm64/kvm/sys_regs.c +6 -0
+
+/*
+ * sys_reg_desc initialiser for known ID registers that we hide from guests.
+ * For now, these are exposed just like unallocated ID regs: they appear
+ * RAZ for the guest.
+ */

What is a hidden ID register as opposed to an unallocated one?

A hidden register is one where all the features have been removed (RAZ), making it similar to an unallocated one.

Quoted 7 lines
Quoted 2 lines

Shouldn't one of them presumably cause an undefined exception in the guest?

No, that'd be a violation of the architecture. The unallocated ID registers are required to be RAZ (see table D9-2 in D9.3.1), so that software can probe for feature without running the risk of getting an UNDEF.

Then I'm not really sure why we need the two defines. Is that just to make it clear what the different rationales for dealing with various registers in the same way are?

Thanks,
-Christoffer

#10 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

Quoted 3 lines · Christoffer Dall
Quoted 2 lines · Marc Zyngier
Quoted 1 line · Christoffer Dall

On Tue, Oct 10, 2017 at 07:38:19PM +0100, Dave Martin wrote:

[...]

Quoted 34 lines
Quoted 34 lines
Quoted 19 lines
Quoted 19 lines
arch/arm64/kvm/sys_regs.c +19 -0
+/* sys_reg_desc initialiser for known cpufeature ID registers */
+#define ID_SANITISED(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access	= access_id_reg,		\
+	.get_user = get_id_reg,			\
+	.set_user = set_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for architecturally unallocated cpufeature ID
+ * register with encoding Op0=3, Op1=0, CRn=0, CRm=crm, Op2=op2
+ * (1 <= crm < 8, 0 <= Op2 < 8).
+ */
+#define ID_UNALLOCATED(crm, op2) {			\
+	Op0(3), Op1(0), CRn(0), CRm(crm), Op2(op2),	\
+	.access = access_raz_id_reg,			\
+	.get_user = get_raz_id_reg,			\
+	.set_user = set_raz_id_reg,			\
+}
Quoted 8 lines

arch/arm64/kvm/sys_regs.c static bool access_cntp_cval(struct kvm_vcpu *vcpu, · line 1018

Quoted 6 lines
arch/arm64/kvm/sys_regs.c +6 -0
+
+/*
+ * sys_reg_desc initialiser for known ID registers that we hide from guests.
+ * For now, these are exposed just like unallocated ID regs: they appear
+ * RAZ for the guest.
+ */

What is a hidden ID register as opposed to an unallocated one?

A hidden register is one where all the features have been removed (RAZ), making it similar to an unallocated one.

Quoted 2 lines

Shouldn't one of them presumably cause an undefined exception in the guest?

Quoted 7 lines
Quoted 4 lines

No, that'd be a violation of the architecture. The unallocated ID registers are required to be RAZ (see table D9-2 in D9.3.1), so that software can probe for feature without running the risk of getting an UNDEF.

Then I'm not really sure why we need the two defines. Is that just to make it clear what the different rationales for dealing with various registers in the same way are?

Basically yes.

ID_HIDDEN() means we are bodging around something that we don't know how to sanitise, whereas ID_UNALLOCATED() means that we follow the architecture in returning zero for reads (maybe following an older architecture version than the silicon).

ID_HIDDEN()s may need to evolve SoC-specific quirkage if we need to expose non-architectural SoC-specific features via the mechanism. These should never simply be exposed unless the architecture is tightened in the future in such a way as to make this safe (unlikely).

ID_UNALLOCATED()s OTOH will mostly turn into ID_SANITISED() as the architecture gains new features. The architecture could allocate new IMP DEF feature regs though, in which case they would become ID_HIDDEN() as soon as we know about them.

The distinction is drawn in attempt to help maintainers: the future maintenance requirements for IN_UNALLOCATED()s will differ from ID_HIDDEN()s.

Cheers
---Dave

#11 lore raw

Re: [PATCH v3 02/28] arm64: KVM: Hide unsupported AArch64 CPU features from guests

Quoted 67 lines · Dave Martin
Quoted 3 lines · Christoffer Dall
Quoted 2 lines · Marc Zyngier
Quoted 1 line · Christoffer Dall

On Tue, Oct 10, 2017 at 07:38:19PM +0100, Dave Martin wrote:

[...]

Quoted 34 lines
Quoted 34 lines
Quoted 19 lines
Quoted 19 lines
arch/arm64/kvm/sys_regs.c +19 -0
+/* sys_reg_desc initialiser for known cpufeature ID registers */
+#define ID_SANITISED(name) {			\
+	SYS_DESC(SYS_##name),			\
+	.access	= access_id_reg,		\
+	.get_user = get_id_reg,			\
+	.set_user = set_id_reg,			\
+}
+
+/*
+ * sys_reg_desc initialiser for architecturally unallocated cpufeature ID
+ * register with encoding Op0=3, Op1=0, CRn=0, CRm=crm, Op2=op2
+ * (1 <= crm < 8, 0 <= Op2 < 8).
+ */
+#define ID_UNALLOCATED(crm, op2) {			\
+	Op0(3), Op1(0), CRn(0), CRm(crm), Op2(op2),	\
+	.access = access_raz_id_reg,			\
+	.get_user = get_raz_id_reg,			\
+	.set_user = set_raz_id_reg,			\
+}
Quoted 8 lines

arch/arm64/kvm/sys_regs.c static bool access_cntp_cval(struct kvm_vcpu *vcpu, · line 1018

Quoted 6 lines
arch/arm64/kvm/sys_regs.c +6 -0
+
+/*
+ * sys_reg_desc initialiser for known ID registers that we hide from guests.
+ * For now, these are exposed just like unallocated ID regs: they appear
+ * RAZ for the guest.
+ */

What is a hidden ID register as opposed to an unallocated one?

A hidden register is one where all the features have been removed (RAZ), making it similar to an unallocated one.

Quoted 2 lines

Shouldn't one of them presumably cause an undefined exception in the guest?

Quoted 7 lines
Quoted 4 lines

No, that'd be a violation of the architecture. The unallocated ID registers are required to be RAZ (see table D9-2 in D9.3.1), so that software can probe for feature without running the risk of getting an UNDEF.

Then I'm not really sure why we need the two defines. Is that just to make it clear what the different rationales for dealing with various registers in the same way are?

Basically yes.

ID_HIDDEN() means we are bodging around something that we don't know how to sanitise, whereas ID_UNALLOCATED() means that we follow the architecture in returning zero for reads (maybe following an older architecture version than the silicon).

ID_HIDDEN()s may need to evolve SoC-specific quirkage if we need to expose non-architectural SoC-specific features via the mechanism. These should never simply be exposed unless the architecture is tightened in the future in such a way as to make this safe (unlikely).

ID_UNALLOCATED()s OTOH will mostly turn into ID_SANITISED() as the architecture gains new features. The architecture could allocate new IMP DEF feature regs though, in which case they would become ID_HIDDEN() as soon as we know about them.

Quoted 4 lines

The distinction is drawn in attempt to help maintainers: the future maintenance requirements for IN_UNALLOCATED()s will differ from ID_HIDDEN()s.

Thanks for the explanation.
-Christoffer

#12 lore raw

PATCH v3 3/28 arm64: efi: Add missing Kconfig dependency on KERNEL_MODE_NEON

In reply to Dave Martin

The EFI runtime services ABI permits calls to EFI to clobber certain FPSIMD/NEON registers, as per the AArch64 procedure call standard.

Saving/restoring the clobbered registers around such calls needs KERNEL_MODE_NEON, but the dependency is missing from Kconfig.

This patch adds the missing dependency.

This will aid bisection of the patches implementing support for the ARM Scalable Vector Extension (SVE).

---
 arch/arm64/Kconfig | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +1 -0
index 0df64a6..ca711ac 100644
@@ -1063,6 +1063,7 @@ config EFI_STUB
 config EFI
 	bool "UEFI runtime support"
 	depends on OF && !CPU_BIG_ENDIAN
+	depends on KERNEL_MODE_NEON
 	select LIBFDT
 	select UCS2_STRING
 	select EFI_PARAMS_FROM_FDT
Signature · 1 line
2.1.4
maintainer Acked-by on v3 3/28
#13 lore raw

Re: [PATCH v3 03/28] arm64: efi: Add missing Kconfig dependency on KERNEL_MODE_NEON

Quoted 23 lines · Dave P Martin

The EFI runtime services ABI permits calls to EFI to clobber certain FPSIMD/NEON registers, as per the AArch64 procedure call standard.

Saving/restoring the clobbered registers around such calls needs KERNEL_MODE_NEON, but the dependency is missing from Kconfig.

This patch adds the missing dependency.

This will aid bisection of the patches implementing support for the ARM Scalable Vector Extension (SVE).

---
 arch/arm64/Kconfig | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +0 -0
index 0df64a6..ca711ac 100644

arch/arm64/Kconfig config EFI_STUB · line 1069

Quoted 7 lines
arch/arm64/Kconfig +1 -0
@@ -1063,6 +1063,7 @@ config EFI_STUB
 config EFI
 	bool "UEFI runtime support"
 	depends on OF && !CPU_BIG_ENDIAN
+	depends on KERNEL_MODE_NEON
 	select LIBFDT
 	select UCS2_STRING
 	select EFI_PARAMS_FROM_FDT

We could've used select KERNEL_MODE_NEON since it's a feature needed by EFI but this works for me as well as KERNEL_MODE_NEON is def_bool y already. Either way:

#14 lore raw

Re: [PATCH v3 03/28] arm64: efi: Add missing Kconfig dependency on KERNEL_MODE_NEON

Quoted 36 lines · Catalin Marinas
Quoted 23 lines · Dave P Martin

The EFI runtime services ABI permits calls to EFI to clobber certain FPSIMD/NEON registers, as per the AArch64 procedure call standard.

Saving/restoring the clobbered registers around such calls needs KERNEL_MODE_NEON, but the dependency is missing from Kconfig.

This patch adds the missing dependency.

This will aid bisection of the patches implementing support for the ARM Scalable Vector Extension (SVE).

---
 arch/arm64/Kconfig | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +0 -0
index 0df64a6..ca711ac 100644

arch/arm64/Kconfig config EFI_STUB · line 1069

Quoted 7 lines
arch/arm64/Kconfig +1 -0
@@ -1063,6 +1063,7 @@ config EFI_STUB
 config EFI
 	bool "UEFI runtime support"
 	depends on OF && !CPU_BIG_ENDIAN
+	depends on KERNEL_MODE_NEON
 	select LIBFDT
 	select UCS2_STRING
 	select EFI_PARAMS_FROM_FDT

We could've used select KERNEL_MODE_NEON since it's a feature needed by EFI but this works for me as well as KERNEL_MODE_NEON is def_bool y already. Either way:

Quoted 1 line

Agreed. I assumed this is moot anyway, since KERNEL_MODE_NEON will rarely/never be deselected in practice.

Cheers
---Dave

#15 lore raw

PATCH v3 4/28 arm64: Port deprecated instruction emulation to new sysctl interface

In reply to Dave Martin

Currently, armv8_deprected.c takes charge of the "abi" sysctl directory, which makes life difficult for other code that wants to register sysctls in the same directory.

There is a "new" [1] sysctl registration interface that removes the need to define ctl_tables for parent directories explicitly, which is ideal here.

This patch ports register_insn_emulation_sysctl() over to the register_sysctl() interface and removes the redundant ctl_table for "abi".

[1] fea478d4101a (sysctl: Add register_sysctl for normal sysctl users)
The commit message notes an intent to port users of the pre-existing interfaces over to register_sysctl(), though the number of users of the new interface currently appears negligible.

---
 arch/arm64/kernel/armv8_deprecated.c | 15 +++------------
 1 file changed, 3 insertions(+), 12 deletions(-)
arch/arm64/kernel/armv8_deprecated.c +3 -12
index d06fbe4..f6e828d 100644
@@ -228,15 +228,7 @@ static int emulation_proc_handler(struct ctl_table *table, int write,
 	return ret;
 }
 
-static struct ctl_table ctl_abi[] = {
-	{
-		.procname = "abi",
-		.mode = 0555,
-	},
-	{ }
-};
-
-static void __init register_insn_emulation_sysctl(struct ctl_table *table)
+static void __init register_insn_emulation_sysctl(void)
 {
 	unsigned long flags;
 	int i = 0;
@@ -262,8 +254,7 @@ static void __init register_insn_emulation_sysctl(struct ctl_table *table)
 	}
 	raw_spin_unlock_irqrestore(&insn_emulation_lock, flags);
 
-	table->child = insns_sysctl;
-	register_sysctl_table(table);
+	register_sysctl("abi", insns_sysctl);
 }
 
 /*
@@ -644,7 +635,7 @@ static int __init armv8_deprecated_init(void)
 	cpuhp_setup_state_nocalls(CPUHP_AP_ARM64_ISNDEP_STARTING,
 				  "arm64/isndep:starting",
 				  run_all_insn_set_hw_mode, NULL);
-	register_insn_emulation_sysctl(ctl_abi);
+	register_insn_emulation_sysctl();
 
 	return 0;
 }
Signature · 1 line
2.1.4
maintainer Reviewed-by on v3 4/28
#16 lore raw

Re: [PATCH v3 04/28] arm64: Port deprecated instruction emulation to new sysctl interface

Quoted 15 lines · Dave P Martin

Currently, armv8_deprected.c takes charge of the "abi" sysctl directory, which makes life difficult for other code that wants to register sysctls in the same directory.

There is a "new" [1] sysctl registration interface that removes the need to define ctl_tables for parent directories explicitly, which is ideal here.

This patch ports register_insn_emulation_sysctl() over to the register_sysctl() interface and removes the redundant ctl_table for "abi".

Quoted 8 lines

[1] fea478d4101a (sysctl: Add register_sysctl for normal sysctl users)
The commit message notes an intent to port users of the pre-existing interfaces over to register_sysctl(), though the number of users of the new interface currently appears negligible.

---
 arch/arm64/kernel/armv8_deprecated.c | 15 +++------------
 1 file changed, 3 insertions(+), 12 deletions(-)
#17 lore raw

PATCH v3 5/28 arm64: fpsimd: Simplify uses of {set, clear}_ti_thread_flag()

In reply to Dave Martin

The existing FPSIMD context switch code contains a couple of instances of {set,clear}_ti_thread(task_thread_info(task)). Since there are thread flag manipulators that operate directly on task_struct, this verbosity isn't strictly needed.

For consistency, this patch simplifies the affected calls. This should have no impact on behaviour.

---
 arch/arm64/kernel/fpsimd.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
arch/arm64/kernel/fpsimd.c +2 -4
index 5d547de..7a865c8 100644
@@ -159,11 +159,9 @@ void fpsimd_thread_switch(struct task_struct *next)
 
 		if (__this_cpu_read(fpsimd_last_state) == st
 		    && st->cpu == smp_processor_id())
-			clear_ti_thread_flag(task_thread_info(next),
-					     TIF_FOREIGN_FPSTATE);
+			clear_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE);
 		else
-			set_ti_thread_flag(task_thread_info(next),
-					   TIF_FOREIGN_FPSTATE);
+			set_tsk_thread_flag(next, TIF_FOREIGN_FPSTATE);
 	}
 }
 
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 5/28
#18 lore raw

Re: [PATCH v3 05/28] arm64: fpsimd: Simplify uses of {set, clear}_ti_thread_flag()

Quoted 11 lines · Dave P Martin

The existing FPSIMD context switch code contains a couple of instances of {set,clear}_ti_thread(task_thread_info(task)). Since there are thread flag manipulators that operate directly on task_struct, this verbosity isn't strictly needed.

For consistency, this patch simplifies the affected calls. This should have no impact on behaviour.

#19 lore raw

PATCH v3 6/28 arm64/sve: System register and exception syndrome definitions

In reply to Dave Martin

The SVE architecture adds some system registers, ID register fields and a dedicated ESR exception class.

This patch adds the appropriate definitions that will be needed by the kernel.

---
 arch/arm64/include/asm/esr.h     |  3 ++-
 arch/arm64/include/asm/kvm_arm.h |  1 +
 arch/arm64/include/asm/sysreg.h  | 21 +++++++++++++++++++++
 arch/arm64/kernel/traps.c        |  1 +
 4 files changed, 25 insertions(+), 1 deletion(-)
arch/arm64/include/asm/esr.h +2 -1
index 66ed8b6..014d7d8 100644
@@ -43,7 +43,8 @@
 #define ESR_ELx_EC_HVC64	(0x16)
 #define ESR_ELx_EC_SMC64	(0x17)
 #define ESR_ELx_EC_SYS64	(0x18)
-/* Unallocated EC: 0x19 - 0x1E */
+#define ESR_ELx_EC_SVE		(0x19)
+/* Unallocated EC: 0x1A - 0x1E */
 #define ESR_ELx_EC_IMP_DEF	(0x1f)
 #define ESR_ELx_EC_IABT_LOW	(0x20)
 #define ESR_ELx_EC_IABT_CUR	(0x21)
arch/arm64/include/asm/kvm_arm.h +1 -0
index 61d694c..dbf0537 100644
@@ -185,6 +185,7 @@
 #define CPTR_EL2_TCPAC	(1 << 31)
 #define CPTR_EL2_TTA	(1 << 20)
 #define CPTR_EL2_TFP	(1 << CPTR_EL2_TFP_SHIFT)
+#define CPTR_EL2_TZ	(1 << 8)
 #define CPTR_EL2_DEFAULT	0x000033ff
 
 /* Hyp Debug Configuration Register bits */
arch/arm64/include/asm/sysreg.h +21 -0
index 480ecd6..36fe2ae 100644
@@ -145,6 +145,7 @@
 
 #define SYS_ID_AA64PFR0_EL1		sys_reg(3, 0, 0, 4, 0)
 #define SYS_ID_AA64PFR1_EL1		sys_reg(3, 0, 0, 4, 1)
+#define SYS_ID_AA64ZFR0_EL1		sys_reg(3, 0, 0, 4, 4)
 
 #define SYS_ID_AA64DFR0_EL1		sys_reg(3, 0, 0, 5, 0)
 #define SYS_ID_AA64DFR1_EL1		sys_reg(3, 0, 0, 5, 1)
@@ -163,6 +164,8 @@
 #define SYS_ACTLR_EL1			sys_reg(3, 0, 1, 0, 1)
 #define SYS_CPACR_EL1			sys_reg(3, 0, 1, 0, 2)
 
+#define SYS_ZCR_EL1			sys_reg(3, 0, 1, 2, 0)
+
 #define SYS_TTBR0_EL1			sys_reg(3, 0, 2, 0, 0)
 #define SYS_TTBR1_EL1			sys_reg(3, 0, 2, 0, 1)
 #define SYS_TCR_EL1			sys_reg(3, 0, 2, 0, 2)
@@ -253,6 +256,8 @@
 
 #define SYS_PMCCFILTR_EL0		sys_reg (3, 3, 14, 15, 7)
 
+#define SYS_ZCR_EL2			sys_reg(3, 4, 1, 2, 0)
+
 #define SYS_DACR32_EL2			sys_reg(3, 4, 3, 0, 0)
 #define SYS_IFSR32_EL2			sys_reg(3, 4, 5, 0, 1)
 #define SYS_FPEXC32_EL2			sys_reg(3, 4, 5, 3, 0)
@@ -335,6 +340,7 @@
 #define ID_AA64ISAR1_DPB_SHIFT		0
 
 /* id_aa64pfr0 */
+#define ID_AA64PFR0_SVE_SHIFT		32
 #define ID_AA64PFR0_GIC_SHIFT		24
 #define ID_AA64PFR0_ASIMD_SHIFT		20
 #define ID_AA64PFR0_FP_SHIFT		16
@@ -343,6 +349,7 @@
 #define ID_AA64PFR0_EL1_SHIFT		4
 #define ID_AA64PFR0_EL0_SHIFT		0
 
+#define ID_AA64PFR0_SVE			0x1
 #define ID_AA64PFR0_FP_NI		0xf
 #define ID_AA64PFR0_FP_SUPPORTED	0x0
 #define ID_AA64PFR0_ASIMD_NI		0xf
@@ -444,6 +451,20 @@
 #endif
 
 
+/*
+ * The ZCR_ELx_LEN_* definitions intentionally include bits [8:4] which
+ * are reserved by the SVE architecture for future expansion of the LEN
+ * field, with compatible semantics.
+ */
+#define ZCR_ELx_LEN_SHIFT	0
+#define ZCR_ELx_LEN_SIZE	9
+#define ZCR_ELx_LEN_MASK	0x1ff
+
+#define CPACR_EL1_ZEN_EL1EN	(1 << 16) /* enable EL1 access */
+#define CPACR_EL1_ZEN_EL0EN	(1 << 17) /* enable EL0 access, if EL1EN set */
+#define CPACR_EL1_ZEN		(CPACR_EL1_ZEN_EL1EN | CPACR_EL1_ZEN_EL0EN)
+
+
 /* Safe value for MPIDR_EL1: Bit31:RES1, Bit30:U:0, Bit24:MT:0 */
 #define SYS_MPIDR_SAFE_VAL		(1UL << 31)
 
arch/arm64/kernel/traps.c +1 -0
index 5ea4b85..f202932 100644
@@ -603,6 +603,7 @@ static const char *esr_class_str[] = {
 	[ESR_ELx_EC_HVC64]		= "HVC (AArch64)",
 	[ESR_ELx_EC_SMC64]		= "SMC (AArch64)",
 	[ESR_ELx_EC_SYS64]		= "MSR/MRS (AArch64)",
+	[ESR_ELx_EC_SVE]		= "SVE",
 	[ESR_ELx_EC_IMP_DEF]		= "EL3 IMP DEF",
 	[ESR_ELx_EC_IABT_LOW]		= "IABT (lower EL)",
 	[ESR_ELx_EC_IABT_CUR]		= "IABT (current EL)",
Signature · 1 line
2.1.4
maintainer Reviewed-by on v3 6/28
#20 lore raw

Re: [PATCH v3 06/28] arm64/sve: System register and exception syndrome definitions

Quoted 8 lines · Dave P Martin

The SVE architecture adds some system registers, ID register fields and a dedicated ESR exception class.

This patch adds the appropriate definitions that will be needed by the kernel.

#21 lore raw

PATCH v3 7/28 arm64/sve: Low-level SVE architectural state manipulation functions

In reply to Dave Martin

Manipulating the SVE architectural state, including the vector and predicate registers, first-fault register and the vector length, requires the use of dedicated instructions added by SVE.

This patch adds suitable assembly functions for saving and restoring the SVE registers and querying the vector length. Setting of the vector length is done as part of register restore.

Since people building kernels may not all get an SVE-enabled toolchain for a while, this patch uses macros that generate explicit opcodes in place of assembler mnemonics.

---
 arch/arm64/include/asm/fpsimd.h       |   5 ++
 arch/arm64/include/asm/fpsimdmacros.h | 148 ++++++++++++++++++++++++++++++++++
 arch/arm64/kernel/entry-fpsimd.S      |  17 ++++
 3 files changed, 170 insertions(+)
arch/arm64/include/asm/fpsimd.h +5 -0
index 410c481..026a7c7 100644
@@ -67,6 +67,11 @@ extern void fpsimd_update_current_state(struct fpsimd_state *state);
 
 extern void fpsimd_flush_task_state(struct task_struct *target);
 
+extern void sve_save_state(void *state, u32 *pfpsr);
+extern void sve_load_state(void const *state, u32 const *pfpsr,
+			   unsigned long vq_minus_1);
+extern unsigned int sve_get_vl(void);
+
 /* For use by EFI runtime services calls only */
 extern void __efi_fpsimd_begin(void);
 extern void __efi_fpsimd_end(void);
arch/arm64/include/asm/fpsimdmacros.h +148 -0

151 lines not on this page · raw message

arch/arm64/kernel/entry-fpsimd.S +17 -0
index 6a27cd6..73f17bf 100644
@@ -41,3 +41,20 @@ ENTRY(fpsimd_load_state)
 	fpsimd_restore x0, 8
 	ret
 ENDPROC(fpsimd_load_state)
+
+#ifdef CONFIG_ARM64_SVE
+ENTRY(sve_save_state)
+	sve_save 0, x1, 2
+	ret
+ENDPROC(sve_save_state)
+
+ENTRY(sve_load_state)
+	sve_load 0, x1, x2, 3
+	ret
+ENDPROC(sve_load_state)
+
+ENTRY(sve_get_vl)
+	_sve_rdvl	0, 1
+	ret
+ENDPROC(sve_get_vl)
+#endif /* CONFIG_ARM64_SVE */
Signature · 1 line
2.1.4
maintainer Acked-by on v3 7/28
#22 lore raw

Re: [PATCH v3 07/28] arm64/sve: Low-level SVE architectural state manipulation functions

Quoted 8 lines · Dave P Martin

Manipulating the SVE architectural state, including the vector and predicate registers, first-fault register and the vector length, requires the use of dedicated instructions added by SVE.

This patch adds suitable assembly functions for saving and restoring the SVE registers and querying the vector length. Setting of the vector length is done as part of register restore.

Quoted 6 lines

Since people building kernels may not all get an SVE-enabled toolchain for a while, this patch uses macros that generate explicit opcodes in place of assembler mnemonics.

(not adding reviewed-by as I haven't checked the instruction encodings, I just trust you to be correct ;))

#23 lore raw

Re: [PATCH v3 07/28] arm64/sve: Low-level SVE architectural state manipulation functions

Quoted 13 lines · Catalin Marinas
Quoted 12 lines · Dave P Martin

Manipulating the SVE architectural state, including the vector and predicate registers, first-fault register and the vector length, requires the use of dedicated instructions added by SVE.

This patch adds suitable assembly functions for saving and restoring the SVE registers and querying the vector length. Setting of the vector length is done as part of register restore.

Since people building kernels may not all get an SVE-enabled toolchain for a while, this patch uses macros that generate explicit opcodes in place of assembler mnemonics.

Quoted 7 lines
Quoted 2 lines

(not adding reviewed-by as I haven't checked the instruction encodings, I just trust you to be correct ;))

Agreed, I am sometimes correct.

Better, Alex _did_ check the encodings against binutils :)

#24 lore raw

PATCH v3 8/28 arm64/sve: Kconfig update and conditional compilation support

In reply to Dave Martin

This patch adds CONFIG_ARM64_SVE to control building of SVE support into the kernel, and adds a stub predicate system_supports_sve() to control conditional compilation and runtime SVE support.

system_supports_sve() just returns false for now: it will be replaced with a non-trivial implementation in a later patch, once SVE support is complete enough to be enabled safely.

---
 arch/arm64/Kconfig                  | 11 +++++++++++
 arch/arm64/include/asm/cpufeature.h |  5 +++++
 2 files changed, 16 insertions(+)
arch/arm64/Kconfig +11 -0
index ca711ac..9b3a50e 100644
@@ -975,6 +975,17 @@ config ARM64_PMEM
 
 endmenu
 
+config ARM64_SVE
+	bool "ARM Scalable Vector Extension support"
+	default y
+	help
+	  The Scalable Vector Extension (SVE) is an extension to the AArch64
+	  execution state which complements and extends the SIMD functionality
+	  of the base architecture to support much larger vectors and to enable
+	  additional vectorisation opportunities.
+
+	  To enable use of this extension on CPUs that implement it, say Y.
+
 config ARM64_MODULE_CMODEL_LARGE
 	bool
 
arch/arm64/include/asm/cpufeature.h +5 -0
index 428ee1f..4ea3441 100644
@@ -262,6 +262,11 @@ static inline bool system_uses_ttbr0_pan(void)
 		!cpus_have_const_cap(ARM64_HAS_PAN);
 }
 
+static inline bool system_supports_sve(void)
+{
+	return false;
+}
+
 #endif /* __ASSEMBLY__ */
 
 #endif
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 8/28
#25 lore raw

Re: [PATCH v3 08/28] arm64/sve: Kconfig update and conditional compilation support

Quoted 10 lines · Dave P Martin

This patch adds CONFIG_ARM64_SVE to control building of SVE support into the kernel, and adds a stub predicate system_supports_sve() to control conditional compilation and runtime SVE support.

system_supports_sve() just returns false for now: it will be replaced with a non-trivial implementation in a later patch, once SVE support is complete enough to be enabled safely.

#26 lore raw

PATCH v3 9/28 arm64/sve: Signal frame and context structure definition

In reply to Dave Martin

This patch defines the representation that will be used for the SVE register state in the signal frame, and implements support for saving and restoring the SVE registers around signals.

The same layout will also be used for the in-kernel task state.

Due to the variability of the SVE vector length, it is not possible to define a fixed C struct to describe all the registers. Instead, Macros are defined in sigcontext.h to facilitate access to the parts of the structure.

---

Changes since v2
----------------

Requested by Catalin Marinas:

* Rewrite the SVE_VQ_BYTES and SVE_VQ_MAX definitions in decimal, to avoid any resemblance to masks or bitfields.

---
 arch/arm64/include/uapi/asm/sigcontext.h | 117 ++++++++++++++++++++++++++++++-
 1 file changed, 116 insertions(+), 1 deletion(-)
arch/arm64/include/uapi/asm/sigcontext.h +116 -1
index f0a76b9..7654a81 100644
@@ -16,6 +16,8 @@
 #ifndef _UAPI__ASM_SIGCONTEXT_H
 #define _UAPI__ASM_SIGCONTEXT_H
 
+#ifndef __ASSEMBLY__
+
 #include <linux/types.h>
 
 /*
@@ -41,10 +43,11 @@ struct sigcontext {
  *
  *	0x210		fpsimd_context
  *	 0x10		esr_context
+ *	0x8a0		sve_context (vl <= 64) (optional)
  *	 0x20		extra_context (optional)
  *	 0x10		terminator (null _aarch64_ctx)
  *
- *	0xdb0		(reserved for future allocation)
+ *	0x510		(reserved for future allocation)
  *
  * New records that can exceed this space need to be opt-in for userspace, so
  * that an expanded signal frame is not generated unexpectedly.  The mechanism
@@ -116,4 +119,116 @@ struct extra_context {
 	__u32 __reserved[3];
 };
 
+#define SVE_MAGIC	0x53564501
+
+struct sve_context {
+	struct _aarch64_ctx head;
+	__u16 vl;
+	__u16 __reserved[3];
+};
+
+#endif /* !__ASSEMBLY__ */
+
+/*
+ * The SVE architecture leaves space for future expansion of the
+ * vector length beyond its initial architectural limit of 2048 bits
+ * (16 quadwords).
+ */
+#define SVE_VQ_BYTES		16	/* number of bytes per quadword */
+
+#define SVE_VQ_MIN		1
+#define SVE_VQ_MAX		512
+
+#define SVE_VL_MIN		(SVE_VQ_MIN * SVE_VQ_BYTES)
+#define SVE_VL_MAX		(SVE_VQ_MAX * SVE_VQ_BYTES)
+
+#define SVE_NUM_ZREGS		32
+#define SVE_NUM_PREGS		16
+
+#define sve_vl_valid(vl) \
+	((vl) % SVE_VQ_BYTES == 0 && (vl) >= SVE_VL_MIN && (vl) <= SVE_VL_MAX)
+#define sve_vq_from_vl(vl)	((vl) / SVE_VQ_BYTES)
+#define sve_vl_from_vq(vq)	((vq) * SVE_VQ_BYTES)
+
+/*
+ * If the SVE registers are currently live for the thread at signal delivery,
+ * sve_context.head.size >=
+ *	SVE_SIG_CONTEXT_SIZE(sve_vq_from_vl(sve_context.vl))
+ * and the register data may be accessed using the SVE_SIG_*() macros.
+ *
+ * If sve_context.head.size <
+ *	SVE_SIG_CONTEXT_SIZE(sve_vq_from_vl(sve_context.vl)),
+ * the SVE registers were not live for the thread and no register data
+ * is included: in this case, the SVE_SIG_*() macros should not be
+ * used except for this check.
+ *
+ * The same convention applies when returning from a signal: a caller
+ * will need to remove or resize the sve_context block if it wants to
+ * make the SVE registers live when they were previously non-live or
+ * vice-versa.  This may require the the caller to allocate fresh
+ * memory and/or move other context blocks in the signal frame.
+ *
+ * Changing the vector length during signal return is not permitted:
+ * sve_context.vl must equal the thread's current vector length when
+ * doing a sigreturn.
+ *
+ *
+ * Note: for all these macros, the "vq" argument denotes the SVE
+ * vector length in quadwords (i.e., units of 128 bits).
+ *
+ * The correct way to obtain vq is to use sve_vq_from_vl(vl).  The
+ * result is valid if and only if sve_vl_valid(vl) is true.  This is
+ * guaranteed for a struct sve_context written by the kernel.
+ *
+ *
+ * Additional macros describe the contents and layout of the payload.
+ * For each, SVE_SIG_x_OFFSET(args) is the start offset relative to
+ * the start of struct sve_context, and SVE_SIG_x_SIZE(args) is the
+ * size in bytes:
+ *
+ *	x	type				description
+ *	-	----				-----------
+ *	REGS					the entire SVE context
+ *
+ *	ZREGS	__uint128_t[SVE_NUM_ZREGS][vq]	all Z-registers
+ *	ZREG	__uint128_t[vq]			individual Z-register Zn
+ *
+ *	PREGS	uint16_t[SVE_NUM_PREGS][vq]	all P-registers
+ *	PREG	uint16_t[vq]			individual P-register Pn
+ *
+ *	FFR	uint16_t[vq]			first-fault status register
+ *
+ * Additional data might be appended in the future.
+ */
+
+#define SVE_SIG_ZREG_SIZE(vq)	((__u32)(vq) * SVE_VQ_BYTES)
+#define SVE_SIG_PREG_SIZE(vq)	((__u32)(vq) * (SVE_VQ_BYTES / 8))
+#define SVE_SIG_FFR_SIZE(vq)	SVE_SIG_PREG_SIZE(vq)
+
+#define SVE_SIG_REGS_OFFSET					\
+	((sizeof(struct sve_context) + (SVE_VQ_BYTES - 1))	\
+		/ SVE_VQ_BYTES * SVE_VQ_BYTES)
+
+#define SVE_SIG_ZREGS_OFFSET	SVE_SIG_REGS_OFFSET
+#define SVE_SIG_ZREG_OFFSET(vq, n) \
+	(SVE_SIG_ZREGS_OFFSET + SVE_SIG_ZREG_SIZE(vq) * (n))
+#define SVE_SIG_ZREGS_SIZE(vq) \
+	(SVE_SIG_ZREG_OFFSET(vq, SVE_NUM_ZREGS) - SVE_SIG_ZREGS_OFFSET)
+
+#define SVE_SIG_PREGS_OFFSET(vq) \
+	(SVE_SIG_ZREGS_OFFSET + SVE_SIG_ZREGS_SIZE(vq))
+#define SVE_SIG_PREG_OFFSET(vq, n) \
+	(SVE_SIG_PREGS_OFFSET(vq) + SVE_SIG_PREG_SIZE(vq) * (n))
+#define SVE_SIG_PREGS_SIZE(vq) \
+	(SVE_SIG_PREG_OFFSET(vq, SVE_NUM_PREGS) - SVE_SIG_PREGS_OFFSET(vq))
+
+#define SVE_SIG_FFR_OFFSET(vq) \
+	(SVE_SIG_PREGS_OFFSET(vq) + SVE_SIG_PREGS_SIZE(vq))
+
+#define SVE_SIG_REGS_SIZE(vq) \
+	(SVE_SIG_FFR_OFFSET(vq) + SVE_SIG_FFR_SIZE(vq) - SVE_SIG_REGS_OFFSET)
+
+#define SVE_SIG_CONTEXT_SIZE(vq) (SVE_SIG_REGS_OFFSET + SVE_SIG_REGS_SIZE(vq))
+
+
 #endif /* _UAPI__ASM_SIGCONTEXT_H */
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 9/28
#27 lore raw

Re: [PATCH v3 09/28] arm64/sve: Signal frame and context structure definition

Quoted 6 lines · Dave P Martin

This patch defines the representation that will be used for the SVE register state in the signal frame, and implements support for saving and restoring the SVE registers around signals.

The same layout will also be used for the in-kernel task state.

Quoted 7 lines

Due to the variability of the SVE vector length, it is not possible to define a fixed C struct to describe all the registers. Instead, Macros are defined in sigcontext.h to facilitate access to the parts of the structure.

#28 lore raw

PATCH v3 10/28 arm64/sve: Low-level CPU setup

In reply to Dave Martin

To enable the kernel to use SVE, SVE traps from EL1 to EL2 must be disabled. To take maximum advantage of the hardware, the full available vector length also needs to be enabled for EL1 by programming ZCR_EL2.LEN. (The kernel will program ZCR_EL1.LEN as required, but this cannot override the limit set by ZCR_EL2.)

Traps from EL0 to EL1 are also left enabled by virtue of setting the relevant CPACR bit at its default (RES0) value.

This patch makes the appropriate changes to the primary and secondary CPU initialisation code.

Cc Catalin Marinas <[email protected]>
Cc Alex Bennée <[email protected]>

---

Dropped Alex Bennée's Reviewed-by, since there is a non-trivial change to the logic here.

Changes since v2
----------------

Requested by Catalin Marinas:

* Removed the asm logic to enable SVE for EL1 from __cpu_setup, since the kernel doesn't need SVE so early.

Instead, this logic is moved to C code called via cpufeatures in "arm64/sve: Probe SVE capabilities and usable vector lengths" and wired up for the arm64_cpu_capabilities enable() method in "arm64/sve: Detect SVE and activate runtime support".

---
 arch/arm64/kernel/head.S | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
arch/arm64/kernel/head.S +12 -1
index 0b243ec..bb6e3f2 100644
@@ -517,8 +517,19 @@ CPU_LE(	movk	x0, #0x30d0, lsl #16	)	// Clear EE and E0E on LE systems
 	mov	x0, #0x33ff
 	msr	cptr_el2, x0			// Disable copro. traps to EL2
 
+	/* SVE register access */
+	mrs	x1, id_aa64pfr0_el1
+	ubfx	x1, x1, #ID_AA64PFR0_SVE_SHIFT, #4
+	cbz	x1, 7f
+
+	bic	x0, x0, #CPTR_EL2_TZ		// Also disable SVE traps
+	msr	cptr_el2, x0			// Disable copro. traps to EL2
+	isb
+	mov	x1, #ZCR_ELx_LEN_MASK		// SVE: Enable full vector
+	msr_s	SYS_ZCR_EL2, x1			// length for EL1.
+
 	/* Hypervisor stub */
-	adr_l	x0, __hyp_stub_vectors
+7:	adr_l	x0, __hyp_stub_vectors
 	msr	vbar_el2, x0
 
 	/* spsr */
Signature · 1 line
2.1.4
maintainer Reviewed-by on v3 10/28
#29 lore raw

Re: [PATCH v3 10/28] arm64/sve: Low-level CPU setup

Quoted 9 lines · Dave P Martin

To enable the kernel to use SVE, SVE traps from EL1 to EL2 must be disabled. To take maximum advantage of the hardware, the full available vector length also needs to be enabled for EL1 by programming ZCR_EL2.LEN. (The kernel will program ZCR_EL1.LEN as required, but this cannot override the limit set by ZCR_EL2.)

Traps from EL0 to EL1 are also left enabled by virtue of setting the relevant CPACR bit at its default (RES0) value.

Quoted 6 lines

This patch makes the appropriate changes to the primary and secondary CPU initialisation code.

Cc Catalin Marinas <[email protected]>
Cc Alex Bennée <[email protected]>
#30 lore raw

PATCH v3 11/28 arm64/sve: Core task context handling

In reply to Dave Martin

This patch adds the core support for switching and managing the SVE architectural state of user tasks.

Calls to the existing FPSIMD low-level save/restore functions are factored out as new functions task_fpsimd_{save,load}(), since SVE now dynamically may or may not need to be handled at these points depending on the kernel configuration, hardware features discovered at boot, and the runtime state of the task. To make these decisions as fast as possible, const cpucaps are used where feasible, via the system_supports_sve() helper.

The SVE registers are only tracked for threads that have explicitly used SVE, indicated by the new thread flag TIF_SVE. Otherwise, the FPSIMD view of the architectural state is stored in thread.fpsimd_state as usual.

When in use, the SVE registers are not stored directly in thread_struct due to their potentially large and variable size. Because the task_struct slab allocator must be configured very early during kernel boot, it is also tricky to configure it correctly to match the maximum vector length provided by the hardware, since this depends on examining secondary CPUs as well as the primary. Instead, a pointer sve_state in thread_struct points to a dynamically allocated buffer containing the SVE register data, and code is added to allocate, duplicate and free this buffer at appropriate times.

TIF_SVE is set when taking an SVE access trap from userspace, if suitable hardware support has been detected. This enables SVE for the thread: a subsequent return to userspace will disable the trap accordingly. If such a trap is taken without sufficient hardware support, SIGILL is sent to the thread instead as if an undefined instruction had been executed: this may happen if userspace tries to use SVE in a system where not all CPUs support it for example.

The kernel may clear TIF_SVE and disable SVE for the thread whenever an explicit syscall is made by userspace, though this is considered an optimisation opportunity rather than a deterministic
guarantee: the kernel may not do this on every syscall, but it is permitted to do so. For backwards compatibility reasons and conformance with the spirit of the base AArch64 procedure call standard, the subset of the SVE register state that aliases the FPSIMD registers is still preserved across a syscall even if this happens.

TIF_SVE is also cleared, and SVE disabled, on exec: this is an obvious slow path and a hint that we are running a new binary that may not use SVE.

Code is added to sync data between thread.fpsimd_state and thread.sve_state whenever enabling/disabling SVE, in a manner consistent with the SVE architectural programmer's model.

Cc Ard Biesheuvel <[email protected]>
Cc Alex Bennée <[email protected]>

---

Changes since v2
----------------

Changes requested by Catalin Marinas:

* [bugfix] Enabled IRQs during SVE access traps

There is no special reason why interrupts have to be disabled in do_sve_acc(), and the original intention was to enable them -- I missed this while developing the series.

This patch avoids IRQ blackout while allocating thread.sve_state and saving/restoring.

This also protects us against kzalloc() sleeping, which was a bug here previously since this function was running in atomic context. Relying on GFP_ATOMIC here doen't seem justifiable.

The code is currently suboptimal in the case where no context switch occurs, since it adds a store-reload roundtrip that is not strictly necessary. However, avoiding this leads to violation of some assumptions which would require additional refactoring or code duplication to resolve, particularly regarding the setting of ZCR_EL1.LEN.

For now, I prefer to have code that works initially, and let the dust settle for a bit.

This may be refactored better later.

* Added WARN_ON(in_softirq() && !irqs_disabled()) to task_fpsimd_{load,save}(), to flag up attempts to call these functions when softirqs could occur. This is far from being everything we could check, but masking of softirqs is the most crucial requirement.

This will guard against maintenance accidents that call these functions in inappropriate situations.

* Provided an explicit helper fpsimd_preserve_current_state_discard_sve() to ensure that task vector state is stored to memory and unconditionally discard sve. This gets the parent task into the right state such that fork just requires a memcpy of thread_struct followed by NULLing dst-> thread.sve_state.

With this, fpsimd_dup_sve() has nothing to do any more, so this function has been deleted from the patch.

task_fpsimd_save() is factored out with a backend __task_fpsimd_save(bool force_discard), which is used in the few places where it is appropriate.

For now, this breaks fpsimd_preserve_current_state() for SVE tasks, but there is no way for SVE tasks to exist yet: so just WARN(). This issue is resolved by "arm64/sve: Signal handling support".

Miscellaneous:

* Added comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

* Added comments explaining the role of TIF_SVE.

* Added a WARN_ON() check in task_fpsimd_save to confirm that the VL currently configured in ZCR_EL1.LEN is correct for current.

This was identified as a maintenance risk when working on enabling IRQs in do_sve_acc().

The new logic flags and avoids potential buffer overruns on sve_state that could otherwise occur if the VL is wrong. In this case, we simply skip the save. The task state will be corrupted, but that's better than corrupting kernel memory.

Since the task state is now wrong, it can't resume: just inject a SIGKILL instead. We can't BUG(), since this problem may be detected in softirq context where BUG() panics the kernel -- so force_signal_inject() is called instead. "bad mode" is a confusing thing to print for this, so force_signal_inject() is updated to print the more general "unknown or unrecoverable error" for such signals:
there is no other call to force_signal_inject() with signal==SIGKILL today.

---
 arch/arm64/include/asm/fpsimd.h      |  17 ++
 arch/arm64/include/asm/processor.h   |   2 +
 arch/arm64/include/asm/thread_info.h |   1 +
 arch/arm64/include/asm/traps.h       |   2 +
 arch/arm64/kernel/entry.S            |  14 +-
 arch/arm64/kernel/fpsimd.c           | 342 ++++++++++++++++++++++++++++++++++-
 arch/arm64/kernel/process.c          |  14 +-
 arch/arm64/kernel/traps.c            |   6 +-
 8 files changed, 388 insertions(+), 10 deletions(-)
arch/arm64/include/asm/fpsimd.h +17 -0
index 026a7c7..b1409de 100644
@@ -20,6 +20,8 @@
 
 #ifndef __ASSEMBLY__
 
+#include <linux/stddef.h>
+
 /*
  * FP/SIMD storage area has:
  *  - FPSR and FPCR
@@ -62,6 +64,7 @@ extern void fpsimd_thread_switch(struct task_struct *next);
 extern void fpsimd_flush_thread(void);
 
 extern void fpsimd_preserve_current_state(void);
+extern void fpsimd_preserve_current_state_discard_sve(void);
 extern void fpsimd_restore_current_state(void);
 extern void fpsimd_update_current_state(struct fpsimd_state *state);
 
@@ -72,6 +75,20 @@ extern void sve_load_state(void const *state, u32 const *pfpsr,
 			   unsigned long vq_minus_1);
 extern unsigned int sve_get_vl(void);
 
+#ifdef CONFIG_ARM64_SVE
+
+extern size_t sve_state_size(struct task_struct const *task);
+
+extern void sve_alloc(struct task_struct *task);
+extern void fpsimd_release_thread(struct task_struct *task);
+
+#else /* ! CONFIG_ARM64_SVE */
+
+static void __maybe_unused sve_alloc(struct task_struct *task) { }
+static void __maybe_unused fpsimd_release_thread(struct task_struct *task) { }
+
+#endif /* ! CONFIG_ARM64_SVE */
+
 /* For use by EFI runtime services calls only */
 extern void __efi_fpsimd_begin(void);
 extern void __efi_fpsimd_end(void);
arch/arm64/include/asm/processor.h +2 -0
index 29adab8..4831d28 100644
@@ -85,6 +85,8 @@ struct thread_struct {
 	unsigned long		tp2_value;
 #endif
 	struct fpsimd_state	fpsimd_state;
+	void			*sve_state;	/* SVE registers, if any */
+	unsigned int		sve_vl;		/* SVE vector length */
 	unsigned long		fault_address;	/* fault info */
 	unsigned long		fault_code;	/* ESR_EL1 value */
 	struct debug_info	debug;		/* debugging */
arch/arm64/include/asm/thread_info.h +1 -0
index ddded64..04dbf50 100644
@@ -92,6 +92,7 @@ void arch_setup_new_exec(void);
 #define TIF_RESTORE_SIGMASK	20
 #define TIF_SINGLESTEP		21
 #define TIF_32BIT		22	/* 32bit process */
+#define TIF_SVE			23	/* Scalable Vector Extension in use */
 
 #define _TIF_SIGPENDING		(1 << TIF_SIGPENDING)
 #define _TIF_NEED_RESCHED	(1 << TIF_NEED_RESCHED)
arch/arm64/include/asm/traps.h +2 -0
index d131501..69e1aaf 100644
@@ -34,6 +34,8 @@ struct undef_hook {
 
 void register_undef_hook(struct undef_hook *hook);
 void unregister_undef_hook(struct undef_hook *hook);
+void force_signal_inject(int signal, int code, struct pt_regs *regs,
+			 unsigned long address);
 
 void arm64_notify_segfault(struct pt_regs *regs, unsigned long addr);
 
arch/arm64/kernel/entry.S +13 -1
index e1c59d4..6718780 100644
@@ -607,6 +607,8 @@ el0_sync:
 	b.eq	el0_ia
 	cmp	x24, #ESR_ELx_EC_FP_ASIMD	// FP/ASIMD access
 	b.eq	el0_fpsimd_acc
+	cmp	x24, #ESR_ELx_EC_SVE		// SVE access
+	b.eq	el0_sve_acc
 	cmp	x24, #ESR_ELx_EC_FP_EXC64	// FP/ASIMD exception
 	b.eq	el0_fpsimd_exc
 	cmp	x24, #ESR_ELx_EC_SYS64		// configurable trap
@@ -705,9 +707,19 @@ el0_fpsimd_acc:
 	mov	x1, sp
 	bl	do_fpsimd_acc
 	b	ret_to_user
+el0_sve_acc:
+	/*
+	 * Scalable Vector Extension access
+	 */
+	enable_dbg_and_irq
+	ct_user_exit
+	mov	x0, x25
+	mov	x1, sp
+	bl	do_sve_acc
+	b	ret_to_user
 el0_fpsimd_exc:
 	/*
-	 * Floating Point or Advanced SIMD exception
+	 * Floating Point, Advanced SIMD or SVE exception
 	 */
 	enable_dbg
 	ct_user_exit
arch/arm64/kernel/fpsimd.c +337 -5

418 lines not on this page · raw message

arch/arm64/kernel/process.c +13 -1
index 2dc0f84..8195682 100644
@@ -239,13 +239,25 @@ void flush_thread(void)
 
 void release_thread(struct task_struct *dead_task)
 {
+	fpsimd_release_thread(dead_task);
 }
 
 int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)
 {
+	/*
+	 * For SVE, dst and src must not end up with aliases of the same
+	 * sve_state.  Because we are definitely in a syscall here, SVE state
+	 * can be discarded unconditionally without violating the user ABI.
+	 * dst's sve_state pointer can then be zapped with no ill effects.
+	 *
+	 * src can safely retain its sve_state memory for later use.
+	 */
 	if (current->mm)
-		fpsimd_preserve_current_state();
+		fpsimd_preserve_current_state_discard_sve();
 	*dst = *src;
+
+	dst->thread.sve_state = NULL;
+
 	return 0;
 }
 
arch/arm64/kernel/traps.c +3 -3
index f202932..bf54885 100644
@@ -358,8 +358,8 @@ static int call_undef_hook(struct pt_regs *regs)
 	return fn ? fn(regs, instr) : 1;
 }
 
-static void force_signal_inject(int signal, int code, struct pt_regs *regs,
-				unsigned long address)
+void force_signal_inject(int signal, int code, struct pt_regs *regs,
+			 unsigned long address)
 {
 	siginfo_t info;
 	void __user *pc = (void __user *)instruction_pointer(regs);
@@ -373,7 +373,7 @@ static void force_signal_inject(int signal, int code, struct pt_regs *regs,
 		desc = "illegal memory access";
 		break;
 	default:
-		desc = "bad mode";
+		desc = "unknown or unrecoverable error";
 		break;
 	}
 
Signature · 1 line
2.1.4
maintainer
#31 lore raw

Re: [PATCH v3 11/28] arm64/sve: Core task context handling

Quoted 9 lines · Dave P Martin
arch/arm64/include/asm/fpsimd.h +1 -0
index 026a7c7..b1409de 100644
@@ -72,6 +75,20 @@ extern void sve_load_state(void const *state, u32 const *pfpsr,
 			   unsigned long vq_minus_1);
 extern unsigned int sve_get_vl(void);
 
+#ifdef CONFIG_ARM64_SVE

arch/arm64/include/asm/fpsimd.h extern void sve_load_state(void const *state, u32 const *pfpsr, · line 88

Quoted 10 lines
arch/arm64/include/asm/fpsimd.h +10 -0
+
+extern size_t sve_state_size(struct task_struct const *task);
+
+extern void sve_alloc(struct task_struct *task);
+extern void fpsimd_release_thread(struct task_struct *task);
+
+#else /* ! CONFIG_ARM64_SVE */
+
+static void __maybe_unused sve_alloc(struct task_struct *task) { }
+static void __maybe_unused fpsimd_release_thread(struct task_struct *task) { }

Nitpick: usually we just add static inline functions here rather than __maybe_unused.

Quoted 14 lines
arch/arm64/include/asm/processor.h +2 -0
index 29adab8..4831d28 100644
@@ -39,6 +47,8 @@
 #define FPEXC_IDF	(1 << 7)
 
 /*
+ * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
+ *
  * In order to reduce the number of times the FPSIMD state is needlessly saved
  * and restored, we need to keep track of two things:
  * (a) for each task, we need to remember which CPU was the last one to have

arch/arm64/include/asm/processor.h line 116

Quoted 8 lines
arch/arm64/include/asm/processor.h +5 -0
@@ -99,6 +109,287 @@
  */
 static DEFINE_PER_CPU(struct fpsimd_state *, fpsimd_last_state);
 
+static void sve_free(struct task_struct *task)
+{
+	kfree(task->thread.sve_state);
+	task->thread.sve_state = NULL;
+}

I think we need a WARN_ON if TIF_SVE is still set here (and the callers making sure it is cleared). I haven't checked the code paths via fpsimd_release_thread() but wondering what happens if we get an interrupt between freeing the state and making the pointer NULL, with some context switching in a preemptible kernel.

Alternatively, always clear TIF_SVE here before freeing (also wondering whether we should make sve_state NULL before the actual freeing but I think TIF_SVE clearing should suffice).

Quoted 36 lines
arch/arm64/include/asm/processor.h +36 -0
+/*
+ * TIF_SVE controls whether a task can use SVE without trapping while
+ * in userspace, and also the way a task's FPSIMD/SVE state is stored
+ * in thread_struct.
+ *
+ * The kernel uses this flag to track whether a user task is actively
+ * using SVE, and therefore whether full SVE register state needs to
+ * be tracked.  If not, the cheaper FPSIMD context handling code can
+ * be used instead of the more costly SVE equivalents.
+ *
+ *  * TIF_SVE set:
+ *
+ *    The task can execute SVE instructions while in userspace without
+ *    trapping to the kernel.
+ *
+ *    When stored, Z0-Z31 (incorporating Vn in bits[127:0] or the
+ *    corresponding Zn), P0-P15 and FFR are encoded in in
+ *    task->thread.sve_state, formatted appropriately for vector
+ *    length task->thread.sve_vl.
+ *
+ *    task->thread.sve_state must point to a valid buffer at least
+ *    sve_state_size(task) bytes in size.
+ *
+ *    During any syscall, the kernel may optionally clear TIF_SVE and
+ *    discard the vector state except for the FPSIMD subset.
+ *
+ *  * TIF_SVE clear:
+ *
+ *    An attempt by the user task to execute an SVE instruction causes
+ *    do_sve_acc() to be called, which does some preparation and then
+ *    sets TIF_SVE.
+ *
+ *    When stored, FPSIMD registers V0-V31 are encoded in
+ *    task->fpsimd_state; bits [max : 128] for each of Z0-Z31 are
+ *    logically zero but not stored anywhere; P0-P15 and FFR are not
+ *    stored and have unspecified values from userspace's point of

arch/arm64/include/asm/processor.h line 162

Quoted 10 lines
arch/arm64/include/asm/processor.h +10 -0
+ *    view.  For hygiene purposes, the kernel zeroes them on next use,
+ *    but userspace is discouraged from relying on this.
+ *
+ *    task->thread.sve_state does not need to be non-NULL, valid or any
+ *    particular size: it must not be dereferenced.
+ *
+ *  * FPSR and FPCR are always stored in task->fpsimd_state irrespctive of
+ *    whether TIF_SVE is clear or set, since these are not vector length
+ *    dependent.
+ */

This looks fine, thanks for adding the description.

Signature · 1 line
Catalin
#32 lore raw

Re: [PATCH v3 11/28] arm64/sve: Core task context handling

Quoted 9 lines · Catalin Marinas
Quoted 8 lines · Dave P Martin
arch/arm64/include/asm/fpsimd.h +0 -0
index 026a7c7..b1409de 100644
@@ -72,6 +75,20 @@ extern void sve_load_state(void const *state, u32 const *pfpsr,
 			   unsigned long vq_minus_1);
 extern unsigned int sve_get_vl(void);
 
Quoted 14 lines

arch/arm64/include/asm/fpsimd.h extern void sve_load_state(void const *state, u32 const *pfpsr, · line 88

Quoted 11 lines
arch/arm64/include/asm/fpsimd.h +11 -0
+#ifdef CONFIG_ARM64_SVE
+
+extern size_t sve_state_size(struct task_struct const *task);
+
+extern void sve_alloc(struct task_struct *task);
+extern void fpsimd_release_thread(struct task_struct *task);
+
+#else /* ! CONFIG_ARM64_SVE */
+
+static void __maybe_unused sve_alloc(struct task_struct *task) { }
+static void __maybe_unused fpsimd_release_thread(struct task_struct *task) { }

Nitpick: usually we just add static inline functions here rather than __maybe_unused.

Fair enough -- come to think of it I've already converted some other instances of this at Ard's request.

Quoted 18 lines
Quoted 18 lines
arch/arm64/include/asm/processor.h +2 -0
index 29adab8..4831d28 100644
@@ -39,6 +47,8 @@
 #define FPEXC_IDF	(1 << 7)
 
 /*
+ * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
+ *
  * In order to reduce the number of times the FPSIMD state is needlessly saved
  * and restored, we need to keep track of two things:
  * (a) for each task, we need to remember which CPU was the last one to have
@@ -99,6 +109,287 @@
  */
 static DEFINE_PER_CPU(struct fpsimd_state *, fpsimd_last_state);
 
Quoted 11 lines

arch/arm64/include/asm/processor.h line 116

Quoted 5 lines
arch/arm64/include/asm/processor.h +5 -0
+static void sve_free(struct task_struct *task)
+{
+	kfree(task->thread.sve_state);
+	task->thread.sve_state = NULL;
+}

I think we need a WARN_ON if TIF_SVE is still set here (and the callers making sure it is cleared). I haven't checked the code paths via fpsimd_release_thread() but wondering what happens if we get an interrupt between freeing the state and making the pointer NULL, with some context switching in a preemptible kernel.

Having a WARN_ON() here may be a decent way to sanity-check that we don't ever have sve_state NULL with TIF_SVE set. This is a lot more economical than putting a WARN_ON() at each dereference of sve_state (of which there are quite a few). sve_free() is also a slow path.

Currently, there are two callsites: sve_set_vector_length(), where we test_and_clear_tsk_thread_flags(task, TIF_SVE) before calling sve_free(); and fpsimd_release_thread() where we "don't care" because the thread is dying.

Looking more closely though, is the release_thread() path preemptible? I can't see anything in the scheduler core to ensure this, nor any general reason why it should be needed.

In which case preemption during thread exit after sve_free() could result in a NULL deference in fpsimd_thread_switch().

So, I think my favoured approach is:

sve_release_thread()

{
	local_bh_disable();
	fpsimd_flush_task_state(current);
	clear_thread_flag(TIF_SVE);
	local_bh_enable();

	sve_free();
}

The local_bh stuff is cumbersome here, and could be replaced with barrier()s to force the order of fpsimd_flusk_task_state() versus clearing TIF_SVE. Or should the barrier really be in fpsimd_flush_task_state()? Disabling softirqs avoids the need to answer such questions...

Then:

sve_free(task)

{
	WARN_ON(test_thread_flag(TIF_SVE));

	barrier();
	kfree(task->thread.sve_state);
	tash->thread.sve_state = NULL;
}

I'm assuming here that kfree() can't be called safely from atomic context, but this is unclear. I would expect to be able to free GFP_ATOMIC memory from atomic context (though sve_statue is GFP_KERNEL, so dunno).

Quoted 3 lines

Alternatively, always clear TIF_SVE here before freeing (also wondering whether we should make sve_state NULL before the actual freeing but I think TIF_SVE clearing should suffice).

Could do. I feel that the current placement of the TIF_SVE clearing in sve_set_vector_length() feels "more natural", but this is a pretty flimsy argument. How strongly do you feel about this?

[...]

Quoted 1 line
Quoted 1 line
arch/arm64/include/asm/processor.h +1 -0
+ *  * TIF_SVE set:

[...]

Quoted 21 lines
Quoted 12 lines

+ * * TIF_SVE clear:
+ *

+ *    An attempt by the user task to execute an SVE instruction causes
+ *    do_sve_acc() to be called, which does some preparation and then
+ *    sets TIF_SVE.
+ *
+ *    When stored, FPSIMD registers V0-V31 are encoded in
+ *    task->fpsimd_state; bits [max : 128] for each of Z0-Z31 are
+ *    logically zero but not stored anywhere; P0-P15 and FFR are not
+ *    stored and have unspecified values from userspace's point of
+ *    view.  For hygiene purposes, the kernel zeroes them on next use,
+ *    but userspace is discouraged from relying on this.
Quoted 8 lines

+ *
+ * task->thread.sve_state does not need to be non-NULL, valid or any
+ * particular size: it must not be dereferenced.
+ *
+ * * FPSR and FPCR are always stored in task->fpsimd_state irrespctive of
+ * whether TIF_SVE is clear or set, since these are not vector length
+ * dependent.
+ */

Quoted 1 line

This looks fine, thanks for adding the description.

OK, thanks for checking it.

Cheers
---Dave

maintainer
#33 lore raw

Re: [PATCH v3 11/28] arm64/sve: Core task context handling

Quoted 79 lines · Dave P Martin
Quoted 18 lines · Catalin Marinas
Quoted 17 lines · Dave P Martin
arch/arm64/include/asm/processor.h +2 -0
index 29adab8..4831d28 100644
@@ -39,6 +47,8 @@
 #define FPEXC_IDF	(1 << 7)
 
 /*
+ * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
+ *
  * In order to reduce the number of times the FPSIMD state is needlessly saved
  * and restored, we need to keep track of two things:
  * (a) for each task, we need to remember which CPU was the last one to have
@@ -99,6 +109,287 @@
  */
 static DEFINE_PER_CPU(struct fpsimd_state *, fpsimd_last_state);
 
Quoted 11 lines

arch/arm64/include/asm/processor.h line 116

Quoted 5 lines
arch/arm64/include/asm/processor.h +5 -0
+static void sve_free(struct task_struct *task)
+{
+	kfree(task->thread.sve_state);
+	task->thread.sve_state = NULL;
+}

I think we need a WARN_ON if TIF_SVE is still set here (and the callers making sure it is cleared). I haven't checked the code paths via fpsimd_release_thread() but wondering what happens if we get an interrupt between freeing the state and making the pointer NULL, with some context switching in a preemptible kernel.

Having a WARN_ON() here may be a decent way to sanity-check that we don't ever have sve_state NULL with TIF_SVE set. This is a lot more economical than putting a WARN_ON() at each dereference of sve_state (of which there are quite a few). sve_free() is also a slow path.

Currently, there are two callsites: sve_set_vector_length(), where we test_and_clear_tsk_thread_flags(task, TIF_SVE) before calling sve_free(); and fpsimd_release_thread() where we "don't care" because the thread is dying.

Looking more closely though, is the release_thread() path preemptible? I can't see anything in the scheduler core to ensure this, nor any general reason why it should be needed.

In which case preemption during thread exit after sve_free() could result in a NULL deference in fpsimd_thread_switch().

So, I think my favoured approach is:

sve_release_thread()

{
	local_bh_disable();
	fpsimd_flush_task_state(current);
	clear_thread_flag(TIF_SVE);
	local_bh_enable();

	sve_free();
}

The local_bh stuff is cumbersome here, and could be replaced with barrier()s to force the order of fpsimd_flusk_task_state() versus clearing TIF_SVE. Or should the barrier really be in fpsimd_flush_task_state()? Disabling softirqs avoids the need to answer such questions...

Then:

sve_free(task)

{
	WARN_ON(test_thread_flag(TIF_SVE));

	barrier();
	kfree(task->thread.sve_state);
	tash->thread.sve_state = NULL;
}
Quoted 4 lines

I'm assuming here that kfree() can't be called safely from atomic context, but this is unclear. I would expect to be able to free GFP_ATOMIC memory from atomic context (though sve_statue is GFP_KERNEL, so dunno).

The kfree should be fine.

Alternative proposal: free the SVE state in arch_release_task_struct(). This is called via the RCU mechanism and the task is no longer current, so no preemption issues.

Quoted 7 lines
Quoted 3 lines

Alternatively, always clear TIF_SVE here before freeing (also wondering whether we should make sve_state NULL before the actual freeing but I think TIF_SVE clearing should suffice).

Could do. I feel that the current placement of the TIF_SVE clearing in sve_set_vector_length() feels "more natural", but this is a pretty flimsy argument. How strongly do you feel about this?

I agree with you, keep the TIF_SVE clearing in sve_set_vector_length().

Signature · 1 line
Catalin
#34 lore raw

Re: [PATCH v3 11/28] arm64/sve: Core task context handling

Quoted 85 lines · Catalin Marinas
Quoted 79 lines · Dave P Martin
Quoted 18 lines · Catalin Marinas
Quoted 17 lines · Dave P Martin
arch/arm64/include/asm/processor.h +2 -0
index 29adab8..4831d28 100644
@@ -39,6 +47,8 @@
 #define FPEXC_IDF	(1 << 7)
 
 /*
+ * (Note: in this discussion, statements about FPSIMD apply equally to SVE.)
+ *
  * In order to reduce the number of times the FPSIMD state is needlessly saved
  * and restored, we need to keep track of two things:
  * (a) for each task, we need to remember which CPU was the last one to have
@@ -99,6 +109,287 @@
  */
 static DEFINE_PER_CPU(struct fpsimd_state *, fpsimd_last_state);
 
Quoted 11 lines

arch/arm64/include/asm/processor.h line 116

Quoted 5 lines
arch/arm64/include/asm/processor.h +5 -0
+static void sve_free(struct task_struct *task)
+{
+	kfree(task->thread.sve_state);
+	task->thread.sve_state = NULL;
+}

I think we need a WARN_ON if TIF_SVE is still set here (and the callers making sure it is cleared). I haven't checked the code paths via fpsimd_release_thread() but wondering what happens if we get an interrupt between freeing the state and making the pointer NULL, with some context switching in a preemptible kernel.

Having a WARN_ON() here may be a decent way to sanity-check that we don't ever have sve_state NULL with TIF_SVE set. This is a lot more economical than putting a WARN_ON() at each dereference of sve_state (of which there are quite a few). sve_free() is also a slow path.

Currently, there are two callsites: sve_set_vector_length(), where we test_and_clear_tsk_thread_flags(task, TIF_SVE) before calling sve_free(); and fpsimd_release_thread() where we "don't care" because the thread is dying.

Looking more closely though, is the release_thread() path preemptible? I can't see anything in the scheduler core to ensure this, nor any general reason why it should be needed.

In which case preemption during thread exit after sve_free() could result in a NULL deference in fpsimd_thread_switch().

So, I think my favoured approach is:

sve_release_thread()

{
	local_bh_disable();
	fpsimd_flush_task_state(current);
	clear_thread_flag(TIF_SVE);
	local_bh_enable();

	sve_free();
}

The local_bh stuff is cumbersome here, and could be replaced with barrier()s to force the order of fpsimd_flusk_task_state() versus clearing TIF_SVE. Or should the barrier really be in fpsimd_flush_task_state()? Disabling softirqs avoids the need to answer such questions...

Then:

sve_free(task)

{
	WARN_ON(test_thread_flag(TIF_SVE));

	barrier();
	kfree(task->thread.sve_state);
	tash->thread.sve_state = NULL;
}
Quoted 4 lines

I'm assuming here that kfree() can't be called safely from atomic context, but this is unclear. I would expect to be able to free GFP_ATOMIC memory from atomic context (though sve_statue is GFP_KERNEL, so dunno).

Quoted 5 lines

The kfree should be fine.

Alternative proposal: free the SVE state in arch_release_task_struct(). This is called via the RCU mechanism and the task is no longer current, so no preemption issues.

Heh, I wasn't aware of that option. That would be better, since there's no value in the task still being schedulable while we do the freeing.

Only SuperH seems to have a real version of that function, but it frees some dynamically allocated state, which sounds familiar.

I'll take a look at moving over to this.

Quoted 10 lines
Quoted 8 lines
Quoted 4 lines

Alternatively, always clear TIF_SVE here before freeing (also wondering whether we should make sve_state NULL before the actual freeing but I think TIF_SVE clearing should suffice).

Could do. I feel that the current placement of the TIF_SVE clearing in sve_set_vector_length() feels "more natural", but this is a pretty flimsy argument. How strongly do you feel about this?

I agree with you, keep the TIF_SVE clearing in sve_set_vector_length().

OK, will do

Cheers
---Dave

#35 lore raw

PATCH v3 12/28 arm64/sve: Support vector length resetting for new processes

In reply to Dave Martin

It's desirable to be able to reset the vector length to some sane default for new processes, since the new binary and its libraries processes may or may not be SVE-aware.

This patch tracks the desired post-exec vector length (if any) in a new thread member sve_vl_onexec, and adds a new thread flag TIF_SVE_VL_INHERIT to control whether to inherit or reset the vector length. Currently these are inactive. Subsequent patches will provide the capability to configure them.

---
 arch/arm64/include/asm/processor.h   |  1 +
 arch/arm64/include/asm/thread_info.h |  1 +
 arch/arm64/kernel/fpsimd.c           | 16 ++++++++++++----
 3 files changed, 14 insertions(+), 4 deletions(-)
arch/arm64/include/asm/processor.h +1 -0
index 4831d28..3faceac 100644
@@ -87,6 +87,7 @@ struct thread_struct {
 	struct fpsimd_state	fpsimd_state;
 	void			*sve_state;	/* SVE registers, if any */
 	unsigned int		sve_vl;		/* SVE vector length */
+	unsigned int		sve_vl_onexec;	/* SVE vl after next exec */
 	unsigned long		fault_address;	/* fault info */
 	unsigned long		fault_code;	/* ESR_EL1 value */
 	struct debug_info	debug;		/* debugging */
arch/arm64/include/asm/thread_info.h +1 -0
index 04dbf50..c6400fc 100644
@@ -93,6 +93,7 @@ void arch_setup_new_exec(void);
 #define TIF_SINGLESTEP		21
 #define TIF_32BIT		22	/* 32bit process */
 #define TIF_SVE			23	/* Scalable Vector Extension in use */
+#define TIF_SVE_VL_INHERIT	24	/* Inherit sve_vl_onexec across exec */
 
 #define _TIF_SIGPENDING		(1 << TIF_SIGPENDING)
 #define _TIF_NEED_RESCHED	(1 << TIF_NEED_RESCHED)
arch/arm64/kernel/fpsimd.c +12 -4
index e60d451..aabeaee 100644
@@ -109,6 +109,9 @@
  */
 static DEFINE_PER_CPU(struct fpsimd_state *, fpsimd_last_state);
 
+/* Default VL for tasks that don't set it explicitly: */
+static int sve_default_vl = SVE_VL_MIN;
+
 static void sve_free(struct task_struct *task)
 {
 	kfree(task->thread.sve_state);
@@ -480,15 +483,20 @@ void fpsimd_flush_thread(void)
 		 * If a bug causes this to go wrong, we make some noise and
 		 * try to fudge thread.sve_vl to a safe value here.
 		 */
-		vl = current->thread.sve_vl;
-
-		if (vl == 0)
-			vl = SVE_VL_MIN;
+		vl = current->thread.sve_vl_onexec ?
+			current->thread.sve_vl_onexec : sve_default_vl;
 
 		if (WARN_ON(!sve_vl_valid(vl)))
 			vl = SVE_VL_MIN;
 
 		current->thread.sve_vl = vl;
+
+		/*
+		 * If the task is not set to inherit, ensure that the vector
+		 * length will be reset by a subsequent exec:
+		 */
+		if (!test_thread_flag(TIF_SVE_VL_INHERIT))
+			current->thread.sve_vl_onexec = 0;
 	}
 
 	set_thread_flag(TIF_FOREIGN_FPSTATE);
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 12/28
#36 lore raw

Re: [PATCH v3 12/28] arm64/sve: Support vector length resetting for new processes

Quoted 4 lines · Dave P Martin

It's desirable to be able to reset the vector length to some sane default for new processes, since the new binary and its libraries processes may or may not be SVE-aware.

Quoted 8 lines

This patch tracks the desired post-exec vector length (if any) in a new thread member sve_vl_onexec, and adds a new thread flag TIF_SVE_VL_INHERIT to control whether to inherit or reset the vector length. Currently these are inactive. Subsequent patches will provide the capability to configure them.

#37 lore raw

PATCH v3 13/28 arm64/sve: Signal handling support

In reply to Dave Martin

This patch implements support for saving and restoring the SVE registers around signals.

A fixed-size header struct sve_context is always included in the signal frame encoding the thread's vector length at the time of signal delivery, optionally followed by a variable-layout structure encoding the SVE registers.

Because of the need to preserve backwards compatibility, the FPSIMD view of the SVE registers is always dumped as a struct fpsimd_context in the usual way, in addition to any sve_context.

The SVE vector registers are dumped in full, including bits 127:0 of each register which alias the corresponding FPSIMD vector registers in the hardware. To avoid any ambiguity about which alias to restore during sigreturn, the kernel always restores bits 127:0 of each SVE vector register from the fpsimd_context in the signal frame (which must be present): userspace needs to take this into account if it wants to modify the SVE vector register contents on return from a signal.

FPSR and FPCR, which are used by both FPSIMD and SVE, are not included in sve_context because they are always present in fpsimd_context anyway.

For signal delivery, a new helper fpsimd_signal_preserve_current_state() is added to update _both_ the FPSIMD and SVE views in the task struct, to make it easier to populate this information into the signal frame. Because of the redundancy between the two views of the state, only one is updated otherwise. In order to avoid racing with a pending discard of the SVE state, this flush is hoisted before the sigframe layout phase, so that the layout and population phases see a consistent view of the thread.

Cc Alex Bennée <[email protected]>
Cc Ard Biesheuvel <[email protected]>

---

Dropped Alex Bennée's Reviewed-by due to refactoring that affects this patch. The changes are straightforward here, but deserve a second look.

Changes since v2
----------------

* fpsimd_preserve_current_state() family of functions refactored to allow arch_dup_task_struct() to forcibly discard the SVE state.

This change shouldn't affect signal handling behviour.

---
 arch/arm64/include/asm/fpsimd.h |   1 +
 arch/arm64/kernel/fpsimd.c      |  66 ++++++++++++---
 arch/arm64/kernel/signal.c      | 173 ++++++++++++++++++++++++++++++++++++++--
 arch/arm64/kernel/signal32.c    |   2 +-
 4 files changed, 221 insertions(+), 21 deletions(-)
arch/arm64/include/asm/fpsimd.h +1 -0
index b1409de..52e01c5 100644
@@ -63,6 +63,7 @@ extern void fpsimd_load_state(struct fpsimd_state *state);
 extern void fpsimd_thread_switch(struct task_struct *next);
 extern void fpsimd_flush_thread(void);
 
+extern void fpsimd_signal_preserve_current_state(void);
 extern void fpsimd_preserve_current_state(void);
 extern void fpsimd_preserve_current_state_discard_sve(void);
 extern void fpsimd_restore_current_state(void);
arch/arm64/kernel/fpsimd.c +54 -12

99 lines not on this page · raw message

arch/arm64/kernel/signal.c +165 -8

243 lines not on this page · raw message

arch/arm64/kernel/signal32.c +1 -1
index e09bf5d..22711ee 100644
@@ -239,7 +239,7 @@ static int compat_preserve_vfp_context(struct compat_vfp_sigframe __user *frame)
 	 * Note that this also saves V16-31, which aren't visible
 	 * in AArch32.
 	 */
-	fpsimd_preserve_current_state();
+	fpsimd_signal_preserve_current_state();
 
 	/* Place structure header on the stack */
 	__put_user_error(magic, &frame->magic, err);
Signature · 1 line
2.1.4
maintainer Reviewed-by on v3 13/28
#38 lore raw

Re: [PATCH v3 13/28] arm64/sve: Signal handling support

Quoted 23 lines · Dave P Martin
arch/arm64/kernel/fpsimd.c +15 -0
index aabeaee..fa4ed34 100644
@@ -310,6 +310,32 @@ static void fpsimd_to_sve(struct task_struct *task)
 		       sizeof(fst->vregs[i]));
 }
 
+/*
+ * Transfer the SVE state in task->thread.sve_state to
+ * task->thread.fpsimd_state.
+ *
+ * Task can be a non-runnable task, or current.  In the latter case,
+ * softirqs (and preemption) must be disabled.
+ * task->thread.sve_state must point to at least sve_state_size(task)
+ * bytes of allocated kernel memory.
+ * task->thread.sve_state must be up to date before calling this function.
+ */
+static void sve_to_fpsimd(struct task_struct *task)
+{
+	unsigned int vq;
+	void const *sst = task->thread.sve_state;
+	struct fpsimd_state *fst = &task->thread.fpsimd_state;

arch/arm64/kernel/fpsimd.c static void fpsimd_to_sve(struct task_struct *task) · line 337

Quoted 10 lines
arch/arm64/kernel/fpsimd.c +10 -0
+	unsigned int i;
+
+	if (!system_supports_sve())
+		return;
+
+	vq = sve_vq_from_vl(task->thread.sve_vl);
+	for (i = 0; i < 32; ++i)
+		memcpy(&fst->vregs[i], ZREG(sst, vq, i),
+		       sizeof(fst->vregs[i]));
+}

Nit: could we actually just do an assignment with some pointer casting? It looks like we invoke memcpy for every 16 bytes (same for fpsimd_to_sve).

Otherwise:

#39 lore raw

Re: [PATCH v3 13/28] arm64/sve: Signal handling support

Quoted 30 lines · Catalin Marinas
Quoted 29 lines · Dave P Martin
arch/arm64/kernel/fpsimd.c +21 -0
index aabeaee..fa4ed34 100644
@@ -310,6 +310,32 @@ static void fpsimd_to_sve(struct task_struct *task)
 		       sizeof(fst->vregs[i]));
 }
 
+/*
+ * Transfer the SVE state in task->thread.sve_state to
+ * task->thread.fpsimd_state.
+ *
+ * Task can be a non-runnable task, or current.  In the latter case,
+ * softirqs (and preemption) must be disabled.
+ * task->thread.sve_state must point to at least sve_state_size(task)
+ * bytes of allocated kernel memory.
+ * task->thread.sve_state must be up to date before calling this function.
+ */
+static void sve_to_fpsimd(struct task_struct *task)
+{
+	unsigned int vq;
+	void const *sst = task->thread.sve_state;
+	struct fpsimd_state *fst = &task->thread.fpsimd_state;
+	unsigned int i;
+
+	if (!system_supports_sve())
+		return;
+
+	vq = sve_vq_from_vl(task->thread.sve_vl);
Quoted 8 lines

arch/arm64/kernel/fpsimd.c static void fpsimd_to_sve(struct task_struct *task) · line 337

Quoted 4 lines
arch/arm64/kernel/fpsimd.c +4 -0
+	for (i = 0; i < 32; ++i)
+		memcpy(&fst->vregs[i], ZREG(sst, vq, i),
+		       sizeof(fst->vregs[i]));
+}

Nit: could we actually just do an assignment with some pointer casting? It looks like we invoke memcpy for every 16 bytes (same for fpsimd_to_sve).

I was uneasy about what the type of ZREG(sst, vq, i) ought to be. In any case, memest() is magic: my oldskool GCC (5.3.0) generates:

ffff000008084c70 <sve_to_fpsimd>:

ffff000008084c70:       14000004        b       ffff000008084c80 <sve_to_fpsimd+0x10>
ffff000008084c74:       d503201f        nop
ffff000008084c78:       d65f03c0        ret
ffff000008084c7c:       d503201f        nop
ffff000008084c80:       f0007d61        adrp    x1, ffff000009033000 <reset_devices>
ffff000008084c84:       f942a021        ldr     x1, [x1,#1344]
ffff000008084c88:       36b001c1        tbz     w1, #22, ffff000008084cc0 <sve_to_fpsimd+0x50>
ffff000008084c8c:       b94ca805        ldr     w5, [x0,#3240]
ffff000008084c90:       912a0001        add     x1, x0, #0xa80
ffff000008084c94:       91320004        add     x4, x0, #0xc80
ffff000008084c98:       f9465006        ldr     x6, [x0,#3232]
ffff000008084c9c:       121c6ca5        and     w5, w5, #0xfffffff0
ffff000008084ca0:       52800000        mov     w0, #0x0                        // #0
ffff000008084ca4:       8b2040c2        add     x2, x6, w0, uxtw
ffff000008084ca8:       0b050000        add     w0, w0, w5
ffff000008084cac:       a9400c42        ldp     x2, x3, [x2]
ffff000008084cb0:       a8810c22        stp     x2, x3, [x1],#16
ffff000008084cb4:       eb01009f        cmp     x4, x1
ffff000008084cb8:       54ffff61        b.ne    ffff000008084ca4 <sve_to_fpsimd+0x34>
ffff000008084cbc:       d65f03c0        ret
ffff000008084cc0:       d65f03c0        ret
ffff000008084cc4:       d503201f        nop

Without volatile, I think assigning a single object and doing a memcpy() are equivalent to the compiler: which it actually uses depends solely on optimisation considerations.

(But then I'm not a language lawyer ... not a professional one anyway).

Are you concerned compilers may mess this up?

Cheers
---Dave

maintainer
#40 lore raw

Re: [PATCH v3 13/28] arm64/sve: Signal handling support

Quoted 68 lines · Dave P Martin
Quoted 30 lines · Catalin Marinas
Quoted 29 lines · Dave P Martin
arch/arm64/kernel/fpsimd.c +21 -0
index aabeaee..fa4ed34 100644
@@ -310,6 +310,32 @@ static void fpsimd_to_sve(struct task_struct *task)
 		       sizeof(fst->vregs[i]));
 }
 
+/*
+ * Transfer the SVE state in task->thread.sve_state to
+ * task->thread.fpsimd_state.
+ *
+ * Task can be a non-runnable task, or current.  In the latter case,
+ * softirqs (and preemption) must be disabled.
+ * task->thread.sve_state must point to at least sve_state_size(task)
+ * bytes of allocated kernel memory.
+ * task->thread.sve_state must be up to date before calling this function.
+ */
+static void sve_to_fpsimd(struct task_struct *task)
+{
+	unsigned int vq;
+	void const *sst = task->thread.sve_state;
+	struct fpsimd_state *fst = &task->thread.fpsimd_state;
+	unsigned int i;
+
+	if (!system_supports_sve())
+		return;
+
+	vq = sve_vq_from_vl(task->thread.sve_vl);
Quoted 8 lines

arch/arm64/kernel/fpsimd.c static void fpsimd_to_sve(struct task_struct *task) · line 337

Quoted 4 lines
arch/arm64/kernel/fpsimd.c +4 -0
+	for (i = 0; i < 32; ++i)
+		memcpy(&fst->vregs[i], ZREG(sst, vq, i),
+		       sizeof(fst->vregs[i]));
+}

Nit: could we actually just do an assignment with some pointer casting? It looks like we invoke memcpy for every 16 bytes (same for fpsimd_to_sve).

I was uneasy about what the type of ZREG(sst, vq, i) ought to be. In any case, memest() is magic: my oldskool GCC (5.3.0) generates:

ffff000008084c70 <sve_to_fpsimd>:

ffff000008084c70:       14000004        b       ffff000008084c80 <sve_to_fpsimd+0x10>
ffff000008084c74:       d503201f        nop
ffff000008084c78:       d65f03c0        ret
ffff000008084c7c:       d503201f        nop
ffff000008084c80:       f0007d61        adrp    x1, ffff000009033000 <reset_devices>
ffff000008084c84:       f942a021        ldr     x1, [x1,#1344]
ffff000008084c88:       36b001c1        tbz     w1, #22, ffff000008084cc0 <sve_to_fpsimd+0x50>
ffff000008084c8c:       b94ca805        ldr     w5, [x0,#3240]
ffff000008084c90:       912a0001        add     x1, x0, #0xa80
ffff000008084c94:       91320004        add     x4, x0, #0xc80
ffff000008084c98:       f9465006        ldr     x6, [x0,#3232]
ffff000008084c9c:       121c6ca5        and     w5, w5, #0xfffffff0
ffff000008084ca0:       52800000        mov     w0, #0x0                        // #0
ffff000008084ca4:       8b2040c2        add     x2, x6, w0, uxtw
ffff000008084ca8:       0b050000        add     w0, w0, w5
ffff000008084cac:       a9400c42        ldp     x2, x3, [x2]
ffff000008084cb0:       a8810c22        stp     x2, x3, [x1],#16
ffff000008084cb4:       eb01009f        cmp     x4, x1
ffff000008084cb8:       54ffff61        b.ne    ffff000008084ca4 <sve_to_fpsimd+0x34>
ffff000008084cbc:       d65f03c0        ret
ffff000008084cc0:       d65f03c0        ret
ffff000008084cc4:       d503201f        nop
Quoted 7 lines

Without volatile, I think assigning a single object and doing a memcpy() are equivalent to the compiler: which it actually uses depends solely on optimisation considerations.

(But then I'm not a language lawyer ... not a professional one anyway).

Are you concerned compilers may mess this up?

That's fine, please ignore my comment then. I was worried that gcc would always generate a call to the memcpy implementation rather than inlining it.

Signature · 1 line
Catalin
#41 lore raw

Re: [PATCH v3 13/28] arm64/sve: Signal handling support

Quoted 73 lines · Catalin Marinas
Quoted 72 lines · Dave P Martin
Quoted 30 lines · Catalin Marinas
Quoted 29 lines · Dave P Martin
arch/arm64/kernel/fpsimd.c +21 -0
index aabeaee..fa4ed34 100644
@@ -310,6 +310,32 @@ static void fpsimd_to_sve(struct task_struct *task)
 		       sizeof(fst->vregs[i]));
 }
 
+/*
+ * Transfer the SVE state in task->thread.sve_state to
+ * task->thread.fpsimd_state.
+ *
+ * Task can be a non-runnable task, or current.  In the latter case,
+ * softirqs (and preemption) must be disabled.
+ * task->thread.sve_state must point to at least sve_state_size(task)
+ * bytes of allocated kernel memory.
+ * task->thread.sve_state must be up to date before calling this function.
+ */
+static void sve_to_fpsimd(struct task_struct *task)
+{
+	unsigned int vq;
+	void const *sst = task->thread.sve_state;
+	struct fpsimd_state *fst = &task->thread.fpsimd_state;
+	unsigned int i;
+
+	if (!system_supports_sve())
+		return;
+
+	vq = sve_vq_from_vl(task->thread.sve_vl);
Quoted 8 lines

arch/arm64/kernel/fpsimd.c static void fpsimd_to_sve(struct task_struct *task) · line 337

Quoted 4 lines
arch/arm64/kernel/fpsimd.c +4 -0
+	for (i = 0; i < 32; ++i)
+		memcpy(&fst->vregs[i], ZREG(sst, vq, i),
+		       sizeof(fst->vregs[i]));
+}

Nit: could we actually just do an assignment with some pointer casting? It looks like we invoke memcpy for every 16 bytes (same for fpsimd_to_sve).

I was uneasy about what the type of ZREG(sst, vq, i) ought to be. In any case, memest() is magic: my oldskool GCC (5.3.0) generates:

ffff000008084c70 <sve_to_fpsimd>:

ffff000008084c70:       14000004        b       ffff000008084c80 <sve_to_fpsimd+0x10>
ffff000008084c74:       d503201f        nop
ffff000008084c78:       d65f03c0        ret
ffff000008084c7c:       d503201f        nop
ffff000008084c80:       f0007d61        adrp    x1, ffff000009033000 <reset_devices>
ffff000008084c84:       f942a021        ldr     x1, [x1,#1344]
ffff000008084c88:       36b001c1        tbz     w1, #22, ffff000008084cc0 <sve_to_fpsimd+0x50>
ffff000008084c8c:       b94ca805        ldr     w5, [x0,#3240]
ffff000008084c90:       912a0001        add     x1, x0, #0xa80
ffff000008084c94:       91320004        add     x4, x0, #0xc80
ffff000008084c98:       f9465006        ldr     x6, [x0,#3232]
ffff000008084c9c:       121c6ca5        and     w5, w5, #0xfffffff0
ffff000008084ca0:       52800000        mov     w0, #0x0                        // #0
ffff000008084ca4:       8b2040c2        add     x2, x6, w0, uxtw
ffff000008084ca8:       0b050000        add     w0, w0, w5
ffff000008084cac:       a9400c42        ldp     x2, x3, [x2]
ffff000008084cb0:       a8810c22        stp     x2, x3, [x1],#16
ffff000008084cb4:       eb01009f        cmp     x4, x1
ffff000008084cb8:       54ffff61        b.ne    ffff000008084ca4 <sve_to_fpsimd+0x34>
ffff000008084cbc:       d65f03c0        ret
ffff000008084cc0:       d65f03c0        ret
ffff000008084cc4:       d503201f        nop

Without volatile, I think assigning a single object and doing a memcpy() are equivalent to the compiler: which it actually uses depends solely on optimisation considerations.

Quoted 7 lines
Quoted 3 lines

(But then I'm not a language lawyer ... not a professional one anyway).

Are you concerned compilers may mess this up?

That's fine, please ignore my comment then. I was worried that gcc would always generate a call to the memcpy implementation rather than inlining it.

OK. I'll keep an eye on this, but in any case it won't impact the FPSIMD-only case.

Cheers
---Dave

#42 lore raw

PATCH v3 14/28 arm64/sve: Backend logic for setting the vector length

In reply to Dave Martin

This patch implements the core logic for changing a task's vector length on request from userspace. This will be used by the ptrace and prctl frontends that are implemented in later patches.

The SVE architecture permits, but does not require, implementations to support vector lengths that are not a power of two. To handle this, logic is added to check a requested vector length against a possibly sparse bitmap of available vector lengths at runtime, so that the best supported value can be chosen.

---

Changes since v2
----------------

Bug fixes:

* sve_set_vector_length() sets or clears TIF_SVE_VL_INHERIT based on the incoming flags, but it is erroneously always set/cleared for current, instead of for the requested task.

Fixed these operations to operate on the target task.

Without this fix, a PTRACE_SETREGSET for NT_ARM_SVE will change the vector length inheritance mode of the caller instead of that of the target task.

* Fixed sve_set_vector_length() to guard against softirq instead of just preemption. This is now done by sve_set_vector_length() itself instead of its caller, not least because sve_free() should probably not be called from atomic context.

(Bug detected by the extra WARN_ON()s in task_fpsimd_{load,save}().)

Miscellaneous:

* Add comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

---
 arch/arm64/include/asm/fpsimd.h |   8 +++
 arch/arm64/kernel/fpsimd.c      | 137 +++++++++++++++++++++++++++++++++++++++-
 include/uapi/linux/prctl.h      |   5 ++
 3 files changed, 149 insertions(+), 1 deletion(-)
arch/arm64/include/asm/fpsimd.h +8 -0
index 52e01c5..7dd3939 100644
@@ -20,6 +20,7 @@
 
 #ifndef __ASSEMBLY__
 
+#include <linux/cache.h>
 #include <linux/stddef.h>
 
 /*
@@ -71,17 +72,24 @@ extern void fpsimd_update_current_state(struct fpsimd_state *state);
 
 extern void fpsimd_flush_task_state(struct task_struct *target);
 
+/* Maximum VL that SVE VL-agnostic software can transparently support */
+#define SVE_VL_ARCH_MAX 0x100
+
 extern void sve_save_state(void *state, u32 *pfpsr);
 extern void sve_load_state(void const *state, u32 const *pfpsr,
 			   unsigned long vq_minus_1);
 extern unsigned int sve_get_vl(void);
 
+extern int __ro_after_init sve_max_vl;
+
 #ifdef CONFIG_ARM64_SVE
 
 extern size_t sve_state_size(struct task_struct const *task);
 
 extern void sve_alloc(struct task_struct *task);
 extern void fpsimd_release_thread(struct task_struct *task);
+extern int sve_set_vector_length(struct task_struct *task,
+				 unsigned long vl, unsigned long flags);
 
 #else /* ! CONFIG_ARM64_SVE */
 
arch/arm64/kernel/fpsimd.c +136 -1

181 lines not on this page · raw message

include/uapi/linux/prctl.h +5 -0
index a8d0759..1b64901 100644
@@ -197,4 +197,9 @@ struct prctl_mm_map {
 # define PR_CAP_AMBIENT_LOWER		3
 # define PR_CAP_AMBIENT_CLEAR_ALL	4
 
+/* arm64 Scalable Vector Extension controls */
+# define PR_SVE_SET_VL_ONEXEC		(1 << 18) /* defer effect until exec */
+# define PR_SVE_VL_LEN_MASK		0xffff
+# define PR_SVE_VL_INHERIT		(1 << 17) /* inherit across exec */
+
 #endif /* _LINUX_PRCTL_H */
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 14/28
#43 lore raw

Re: [PATCH v3 14/28] arm64/sve: Backend logic for setting the vector length

Quoted 4 lines · Dave P Martin

This patch implements the core logic for changing a task's vector length on request from userspace. This will be used by the ptrace and prctl frontends that are implemented in later patches.

Quoted 8 lines

The SVE architecture permits, but does not require, implementations to support vector lengths that are not a power of two. To handle this, logic is added to check a requested vector length against a possibly sparse bitmap of available vector lengths at runtime, so that the best supported value can be chosen.

#44 lore raw

PATCH v3 15/28 arm64: cpufeature: Move sys_caps_initialised declarations

In reply to Dave Martin

update_cpu_features() currently cannot tell whether it is being called during early or late secondary boot. This doesn't desperately matter for anything it currently does.

However, SVE will need to know here whether the set of available vector lengths is fixed of still to be determined when booting a CPU so that it can be updated appropriately.

This patch simply moves the sys_caps_initialised stuff to the top of the file so that it can be more widely. There doesn't seem to be a more obvious place to put it.

---
 arch/arm64/kernel/cpufeature.c | 30 +++++++++++++++---------------
 1 file changed, 15 insertions(+), 15 deletions(-)
arch/arm64/kernel/cpufeature.c +15 -15
index 21e2c95..92a9502 100644
@@ -51,6 +51,21 @@ unsigned int compat_elf_hwcap2 __read_mostly;
 DECLARE_BITMAP(cpu_hwcaps, ARM64_NCAPS);
 EXPORT_SYMBOL(cpu_hwcaps);
 
+/*
+ * Flag to indicate if we have computed the system wide
+ * capabilities based on the boot time active CPUs. This
+ * will be used to determine if a new booting CPU should
+ * go through the verification process to make sure that it
+ * supports the system capabilities, without using a hotplug
+ * notifier.
+ */
+static bool sys_caps_initialised;
+
+static inline void set_sys_caps_initialised(void)
+{
+	sys_caps_initialised = true;
+}
+
 static int dump_cpu_hwcaps(struct notifier_block *self, unsigned long v, void *p)
 {
 	/* file-wide pr_fmt adds "CPU features: " prefix */
@@ -1041,21 +1056,6 @@ void __init enable_cpu_capabilities(const struct arm64_cpu_capabilities *caps)
 }
 
 /*
- * Flag to indicate if we have computed the system wide
- * capabilities based on the boot time active CPUs. This
- * will be used to determine if a new booting CPU should
- * go through the verification process to make sure that it
- * supports the system capabilities, without using a hotplug
- * notifier.
- */
-static bool sys_caps_initialised;
-
-static inline void set_sys_caps_initialised(void)
-{
-	sys_caps_initialised = true;
-}
-
-/*
  * Check for CPU features that are used in early boot
  * based on the Boot CPU value.
  */
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Acked-by on v3 15/28
#45 lore raw

Re: [PATCH v3 15/28] arm64: cpufeature: Move sys_caps_initialised declarations

Quoted 8 lines · Dave P Martin

update_cpu_features() currently cannot tell whether it is being called during early or late secondary boot. This doesn't desperately matter for anything it currently does.

However, SVE will need to know here whether the set of available vector lengths is fixed of still to be determined when booting a CPU so that it can be updated appropriately.

Quoted 7 lines

This patch simply moves the sys_caps_initialised stuff to the top of the file so that it can be more widely. There doesn't seem to be a more obvious place to put it.

#46 lore raw

PATCH v3 16/28 arm64/sve: Probe SVE capabilities and usable vector lengths

In reply to Dave Martin

This patch uses the cpufeatures framework to determine common SVE capabilities and vector lengths, and configures the runtime SVE support code appropriately.

ZCR_ELx is not really a feature register, but it is convenient to use it as a template for recording the maximum vector length supported by a CPU, using the LEN field. This field is similar to a feature field in that it is a contiguous bitfield for which we want to determine the minimum system-wide value. This patch adds ZCR as a pseudo-register in cpuinfo/cpufeatures, with appropriate custom code to populate it. Finding the minimum supported value of the LEN field is left to the cpufeatures framework in the usual way.

The meaning of ID_AA64ZFR0_EL1 is not architecturally defined yet, so for now we just require it to be zero.

Note that much of this code is dormant and SVE still won't be used yet, since system_supports_sve() remains hardwired to false.

Cc Alex Bennée <[email protected]>
Cc Suzuki K Poulose <[email protected]>

---

Dropped Alex Bennée's Reviewed-by, since there is new logic in this patch.

Changes since v2
----------------

Bug fixes:

* Got rid of dynamic allocation of the shadow vector length map during secondary boot. Secondary CPU boot takes place in atomic context, and relying on GFP_ATOMIC here doesn't seem justified.

Instead, the needed additional bitmap is allocated statically. Only one shadow map is needed, because CPUs don't boot concurrently.

Requested by Alex Bennée:

* Reflowed untidy comment above read_zcr_features()

* Added comments to read_zcr_features() to explain what it's trying to do (which is otherwise not readily apparent).

Requested by Catalin Marinas:

* Moved disabling of the EL1 SVE trap to the cpufeatures C code. This allows addition of new assembler in __cpu_setup to be avoided.

Miscellaneous:

* Added comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

---
 arch/arm64/include/asm/cpu.h        |   4 ++
 arch/arm64/include/asm/cpufeature.h |  36 ++++++++++++
 arch/arm64/include/asm/fpsimd.h     |  14 +++++
 arch/arm64/kernel/cpufeature.c      |  50 ++++++++++++++++
 arch/arm64/kernel/cpuinfo.c         |   6 ++
 arch/arm64/kernel/fpsimd.c          | 114 +++++++++++++++++++++++++++++++++++-
 6 files changed, 221 insertions(+), 3 deletions(-)
arch/arm64/include/asm/cpu.h +4 -0
index 889226b..8839227 100644
@@ -41,6 +41,7 @@ struct cpuinfo_arm64 {
 	u64		reg_id_aa64mmfr2;
 	u64		reg_id_aa64pfr0;
 	u64		reg_id_aa64pfr1;
+	u64		reg_id_aa64zfr0;
 
 	u32		reg_id_dfr0;
 	u32		reg_id_isar0;
@@ -59,6 +60,9 @@ struct cpuinfo_arm64 {
 	u32		reg_mvfr0;
 	u32		reg_mvfr1;
 	u32		reg_mvfr2;
+
+	/* pseudo-ZCR for recording maximum ZCR_EL1 LEN value: */
+	u64		reg_zcr;
 };
 
 DECLARE_PER_CPU(struct cpuinfo_arm64, cpu_data);
arch/arm64/include/asm/cpufeature.h +36 -0
index 4ea3441..51be8e8 100644
@@ -10,7 +10,9 @@
 #define __ASM_CPUFEATURE_H
 
 #include <asm/cpucaps.h>
+#include <asm/fpsimd.h>
 #include <asm/hwcap.h>
+#include <asm/sigcontext.h>
 #include <asm/sysreg.h>
 
 /*
@@ -223,6 +225,13 @@ static inline bool id_aa64pfr0_32bit_el0(u64 pfr0)
 	return val == ID_AA64PFR0_EL0_32BIT_64BIT;
 }
 
+static inline bool id_aa64pfr0_sve(u64 pfr0)
+{
+	u32 val = cpuid_feature_extract_unsigned_field(pfr0, ID_AA64PFR0_SVE_SHIFT);
+
+	return val > 0;
+}
+
 void __init setup_cpu_features(void);
 
 void update_cpu_capabilities(const struct arm64_cpu_capabilities *caps,
@@ -267,6 +276,33 @@ static inline bool system_supports_sve(void)
 	return false;
 }
 
+/*
+ * Read the pseudo-ZCR used by cpufeatures to identify the supported SVE
+ * vector length.
+ *
+ * Use only if SVE is present.
+ * This function clobbers the SVE vector length.
+ */
+static u64 __maybe_unused read_zcr_features(void)
+{
+	u64 zcr;
+	unsigned int vq_max;
+
+	/*
+	 * Set the maximum possible VL, and write zeroes to all other
+	 * bits to see if they stick.
+	 */
+	sve_kernel_enable(NULL);
+	write_sysreg_s(ZCR_ELx_LEN_MASK, SYS_ZCR_EL1);
+
+	zcr = read_sysreg_s(SYS_ZCR_EL1);
+	zcr &= ~(u64)ZCR_ELx_LEN_MASK; /* find sticky 1s outside LEN field */
+	vq_max = sve_vq_from_vl(sve_get_vl());
+	zcr |= vq_max - 1; /* set LEN field to maximum effective value */
+
+	return zcr;
+}
+
 #endif /* __ASSEMBLY__ */
 
 #endif
arch/arm64/include/asm/fpsimd.h +14 -0
index 7dd3939..bad72fd 100644
@@ -79,6 +79,7 @@ extern void sve_save_state(void *state, u32 *pfpsr);
 extern void sve_load_state(void const *state, u32 const *pfpsr,
 			   unsigned long vq_minus_1);
 extern unsigned int sve_get_vl(void);
+extern int sve_kernel_enable(void *);
 
 extern int __ro_after_init sve_max_vl;
 
@@ -91,10 +92,23 @@ extern void fpsimd_release_thread(struct task_struct *task);
 extern int sve_set_vector_length(struct task_struct *task,
 				 unsigned long vl, unsigned long flags);
 
+/*
+ * Probing and setup functions.
+ * Calls to these functions must be serialised with one another.
+ */
+extern void __init sve_init_vq_map(void);
+extern void sve_update_vq_map(void);
+extern int sve_verify_vq_map(void);
+extern void __init sve_setup(void);
+
 #else /* ! CONFIG_ARM64_SVE */
 
 static void __maybe_unused sve_alloc(struct task_struct *task) { }
 static void __maybe_unused fpsimd_release_thread(struct task_struct *task) { }
+static void __maybe_unused sve_init_vq_map(void) { }
+static void __maybe_unused sve_update_vq_map(void) { }
+static int __maybe_unused sve_verify_vq_map(void) { return 0; }
+static void __maybe_unused sve_setup(void) { }
 
 #endif /* ! CONFIG_ARM64_SVE */
 
arch/arm64/kernel/cpufeature.c +50 -0

118 lines not on this page · raw message

arch/arm64/kernel/cpuinfo.c +6 -0
index 3118859..be260e8 100644
@@ -19,6 +19,7 @@
 #include <asm/cpu.h>
 #include <asm/cputype.h>
 #include <asm/cpufeature.h>
+#include <asm/fpsimd.h>
 
 #include <linux/bitops.h>
 #include <linux/bug.h>
@@ -326,6 +327,7 @@ static void __cpuinfo_store_cpu(struct cpuinfo_arm64 *info)
 	info->reg_id_aa64mmfr2 = read_cpuid(ID_AA64MMFR2_EL1);
 	info->reg_id_aa64pfr0 = read_cpuid(ID_AA64PFR0_EL1);
 	info->reg_id_aa64pfr1 = read_cpuid(ID_AA64PFR1_EL1);
+	info->reg_id_aa64zfr0 = read_cpuid(ID_AA64ZFR0_EL1);
 
 	/* Update the 32bit ID registers only if AArch32 is implemented */
 	if (id_aa64pfr0_32bit_el0(info->reg_id_aa64pfr0)) {
@@ -348,6 +350,10 @@ static void __cpuinfo_store_cpu(struct cpuinfo_arm64 *info)
 		info->reg_mvfr2 = read_cpuid(MVFR2_EL1);
 	}
 
+	if (IS_ENABLED(CONFIG_ARM64_SVE) &&
+	    id_aa64pfr0_sve(info->reg_id_aa64pfr0))
+		info->reg_zcr = read_zcr_features();
+
 	cpuinfo_detect_icache_policy(info);
 }
 
arch/arm64/kernel/fpsimd.c +111 -3

142 lines not on this page · raw message

Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 16/28
#47 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 17 lines · Dave P Martin

This patch uses the cpufeatures framework to determine common SVE capabilities and vector lengths, and configures the runtime SVE support code appropriately.

ZCR_ELx is not really a feature register, but it is convenient to use it as a template for recording the maximum vector length supported by a CPU, using the LEN field. This field is similar to a feature field in that it is a contiguous bitfield for which we want to determine the minimum system-wide value. This patch adds ZCR as a pseudo-register in cpuinfo/cpufeatures, with appropriate custom code to populate it. Finding the minimum supported value of the LEN field is left to the cpufeatures framework in the usual way.

The meaning of ID_AA64ZFR0_EL1 is not architecturally defined yet, so for now we just require it to be zero.

Quoted 6 lines

Note that much of this code is dormant and SVE still won't be used yet, since system_supports_sve() remains hardwired to false.

Cc Alex Bennée <[email protected]>
Cc Suzuki K Poulose <[email protected]>
reviewer Reviewed-by on v3 16/28
#48 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

In reply to Dave Martin
Quoted 58 lines · Dave Martin

This patch uses the cpufeatures framework to determine common SVE capabilities and vector lengths, and configures the runtime SVE support code appropriately.

ZCR_ELx is not really a feature register, but it is convenient to use it as a template for recording the maximum vector length supported by a CPU, using the LEN field. This field is similar to a feature field in that it is a contiguous bitfield for which we want to determine the minimum system-wide value. This patch adds ZCR as a pseudo-register in cpuinfo/cpufeatures, with appropriate custom code to populate it. Finding the minimum supported value of the LEN field is left to the cpufeatures framework in the usual way.

The meaning of ID_AA64ZFR0_EL1 is not architecturally defined yet, so for now we just require it to be zero.

Note that much of this code is dormant and SVE still won't be used yet, since system_supports_sve() remains hardwired to false.

Cc Alex Bennée <[email protected]>
Cc Suzuki K Poulose <[email protected]>

---

Dropped Alex Bennée's Reviewed-by, since there is new logic in this patch.

Changes since v2
----------------

Bug fixes:

* Got rid of dynamic allocation of the shadow vector length map during secondary boot. Secondary CPU boot takes place in atomic context, and relying on GFP_ATOMIC here doesn't seem justified.

Instead, the needed additional bitmap is allocated statically. Only one shadow map is needed, because CPUs don't boot concurrently.

Requested by Alex Bennée:

* Reflowed untidy comment above read_zcr_features()

* Added comments to read_zcr_features() to explain what it's trying to do (which is otherwise not readily apparent).

Requested by Catalin Marinas:

* Moved disabling of the EL1 SVE trap to the cpufeatures C code. This allows addition of new assembler in __cpu_setup to be avoided.

Miscellaneous:

* Added comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

...

Quoted 4 lines
arch/arm64/kernel/cpufeature.c +0 -0
index 92a9502..c5acf38 100644

...

arch/arm64/kernel/cpufeature.c void update_cpu_features(int cpu, · line 698

Quoted 11 lines
arch/arm64/kernel/cpufeature.c +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
  					info->reg_mvfr2, boot->reg_mvfr2);
  	}
 
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

#49 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 86 lines · Suzuki K Poulose
Quoted 58 lines · Dave Martin

This patch uses the cpufeatures framework to determine common SVE capabilities and vector lengths, and configures the runtime SVE support code appropriately.

ZCR_ELx is not really a feature register, but it is convenient to use it as a template for recording the maximum vector length supported by a CPU, using the LEN field. This field is similar to a feature field in that it is a contiguous bitfield for which we want to determine the minimum system-wide value. This patch adds ZCR as a pseudo-register in cpuinfo/cpufeatures, with appropriate custom code to populate it. Finding the minimum supported value of the LEN field is left to the cpufeatures framework in the usual way.

The meaning of ID_AA64ZFR0_EL1 is not architecturally defined yet, so for now we just require it to be zero.

Note that much of this code is dormant and SVE still won't be used yet, since system_supports_sve() remains hardwired to false.

Cc Alex Bennée <[email protected]>
Cc Suzuki K Poulose <[email protected]>

---

Dropped Alex Bennée's Reviewed-by, since there is new logic in this patch.

Changes since v2
----------------

Bug fixes:

* Got rid of dynamic allocation of the shadow vector length map during secondary boot. Secondary CPU boot takes place in atomic context, and relying on GFP_ATOMIC here doesn't seem justified.

Instead, the needed additional bitmap is allocated statically. Only one shadow map is needed, because CPUs don't boot concurrently.

Requested by Alex Bennée:

* Reflowed untidy comment above read_zcr_features()

* Added comments to read_zcr_features() to explain what it's trying to do (which is otherwise not readily apparent).

Requested by Catalin Marinas:

* Moved disabling of the EL1 SVE trap to the cpufeatures C code. This allows addition of new assembler in __cpu_setup to be avoided.

Miscellaneous:

* Added comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

...

Quoted 4 lines
arch/arm64/kernel/cpufeature.c +0 -0
index 92a9502..c5acf38 100644

...

arch/arm64/kernel/cpufeature.c void update_cpu_features(int cpu, · line 697

Quoted 10 lines
arch/arm64/kernel/cpufeature.c +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
 					info->reg_mvfr2, boot->reg_mvfr2);
 	}
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

Quoted 1 line

I think I prefer to avoid adding extra code to optimise the "broken SoC design" case.

Maybe we could revisit this later if needed.

Can you suggest some code? Maybe the check is simpler than I think.

#50 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 87 lines · Dave Martin
Quoted 86 lines · Suzuki K Poulose
Quoted 58 lines · Dave Martin

This patch uses the cpufeatures framework to determine common SVE capabilities and vector lengths, and configures the runtime SVE support code appropriately.

ZCR_ELx is not really a feature register, but it is convenient to use it as a template for recording the maximum vector length supported by a CPU, using the LEN field. This field is similar to a feature field in that it is a contiguous bitfield for which we want to determine the minimum system-wide value. This patch adds ZCR as a pseudo-register in cpuinfo/cpufeatures, with appropriate custom code to populate it. Finding the minimum supported value of the LEN field is left to the cpufeatures framework in the usual way.

The meaning of ID_AA64ZFR0_EL1 is not architecturally defined yet, so for now we just require it to be zero.

Note that much of this code is dormant and SVE still won't be used yet, since system_supports_sve() remains hardwired to false.

Cc Alex Bennée <[email protected]>
Cc Suzuki K Poulose <[email protected]>

---

Dropped Alex Bennée's Reviewed-by, since there is new logic in this patch.

Changes since v2
----------------

Bug fixes:

* Got rid of dynamic allocation of the shadow vector length map during secondary boot. Secondary CPU boot takes place in atomic context, and relying on GFP_ATOMIC here doesn't seem justified.

Instead, the needed additional bitmap is allocated statically. Only one shadow map is needed, because CPUs don't boot concurrently.

Requested by Alex Bennée:

* Reflowed untidy comment above read_zcr_features()

* Added comments to read_zcr_features() to explain what it's trying to do (which is otherwise not readily apparent).

Requested by Catalin Marinas:

* Moved disabling of the EL1 SVE trap to the cpufeatures C code. This allows addition of new assembler in __cpu_setup to be avoided.

Miscellaneous:

* Added comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

...

Quoted 4 lines
arch/arm64/kernel/cpufeature.c +0 -0
index 92a9502..c5acf38 100644

...

arch/arm64/kernel/cpufeature.c void update_cpu_features(int cpu, · line 697

Quoted 10 lines
arch/arm64/kernel/cpufeature.c +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
  					info->reg_mvfr2, boot->reg_mvfr2);
  	}
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

Quoted 5 lines
Quoted 1 line

I think I prefer to avoid adding extra code to optimise the "broken SoC design" case.

Sure.

Quoted 3 lines

Maybe we could revisit this later if needed.

Can you suggest some code? Maybe the check is simpler than I think.

Something like :

if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_IDAA64PFR0)) &&

    id_aa64pfr0_sve(id_aa64pfr0)) {
    ...
}

should be enough.

Or even we could hack it to :

if (id_aa64pfr0_sve(id_aa64pfr0 | read_sanitised_ftr_reg(SYS_IDAA64PFR0)))

As I mentioned, the code as such is fine. Its just that we try to detect if the SVE is already moot and skip the steps for this CPU.

Cheers
Suzuki

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm

#51 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 3 lines · Suzuki K Poulose
Quoted 2 lines · Dave Martin
Quoted 1 line · Suzuki K Poulose

On 10/10/17 19:38, Dave Martin wrote:

[...]

Quoted 36 lines
Quoted 17 lines
Quoted 17 lines

arch/arm64/kernel/cpufeature.c void update_cpu_features(int cpu, · line 697

Quoted 10 lines
arch/arm64/kernel/cpufeature.c +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
 					info->reg_mvfr2, boot->reg_mvfr2);
 	}
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

Quoted 5 lines
Quoted 1 line

I think I prefer to avoid adding extra code to optimise the "broken SoC design" case.

Sure.

Quoted 3 lines

Maybe we could revisit this later if needed.

Can you suggest some code? Maybe the check is simpler than I think.

Something like :

if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_IDAA64PFR0)) &&

    id_aa64pfr0_sve(id_aa64pfr0)) {
    ...
}
Quoted 8 lines

should be enough.

Or even we could hack it to :

if (id_aa64pfr0_sve(id_aa64pfr0 | read_sanitised_ftr_reg(SYS_IDAA64PFR0)))

As I mentioned, the code as such is fine. Its just that we try to detect if the SVE is already moot and skip the steps for this CPU.

How about the following, keeping the outer if(id_aa64pfr0_sve(int->reg_id_aa64pfr0)) from my current code:

- if (!sys_caps_initialised)
+ /* Probe vector lengths, unless we already gave up on SVE */
+ if (id_aa64pfr0_sve(read_sanitised_ftr_reg(ID_AA64PFR0_SVE)) &&
+ !sys_caps_initialised)

			sve_update_vq_map();

Cheers
---Dave

#52 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 59 lines · Dave Martin
Quoted 3 lines · Suzuki K Poulose
Quoted 2 lines · Dave Martin
Quoted 1 line · Suzuki K Poulose

On 10/10/17 19:38, Dave Martin wrote:

[...]

Quoted 36 lines
Quoted 17 lines
Quoted 17 lines

arch/arm64/kernel/cpufeature.c void update_cpu_features(int cpu, · line 697

Quoted 10 lines
arch/arm64/kernel/cpufeature.c +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
  					info->reg_mvfr2, boot->reg_mvfr2);
  	}
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

Quoted 5 lines
Quoted 1 line

I think I prefer to avoid adding extra code to optimise the "broken SoC design" case.

Sure.

Quoted 3 lines

Maybe we could revisit this later if needed.

Can you suggest some code? Maybe the check is simpler than I think.

Something like :

if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_IDAA64PFR0)) &&

     id_aa64pfr0_sve(id_aa64pfr0)) {
     ...
}
Quoted 8 lines

should be enough.

Or even we could hack it to :

if (id_aa64pfr0_sve(id_aa64pfr0 | read_sanitised_ftr_reg(SYS_IDAA64PFR0)))

As I mentioned, the code as such is fine. Its just that we try to detect if the SVE is already moot and skip the steps for this CPU.

How about the following, keeping the outer if(id_aa64pfr0_sve(int->reg_id_aa64pfr0)) from my current code:

(quoted diff) +3 -1
-		if (!sys_caps_initialised)
+		/* Probe vector lengths, unless we already gave up on SVE */
+		if (id_aa64pfr0_sve(read_sanitised_ftr_reg(ID_AA64PFR0_SVE)) &&
+		    !sys_caps_initialised)
Quoted 1 line
			sve_update_vq_map();

Yep, that looks neater.

Cheers
Suzuki

#53 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 56 lines · Suzuki K Poulose
Quoted 55 lines · Dave Martin
Quoted 3 lines · Suzuki K Poulose
Quoted 2 lines · Dave Martin
Quoted 1 line · Suzuki K Poulose

On 10/10/17 19:38, Dave Martin wrote:

[...]

Quoted 36 lines
Quoted 17 lines
Quoted 17 lines

arch/arm64/kernel/cpufeature.c void update_cpu_features(int cpu, · line 697

Quoted 10 lines
arch/arm64/kernel/cpufeature.c +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
 					info->reg_mvfr2, boot->reg_mvfr2);
 	}
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

Quoted 5 lines
Quoted 1 line

I think I prefer to avoid adding extra code to optimise the "broken SoC design" case.

Sure.

Quoted 3 lines

Maybe we could revisit this later if needed.

Can you suggest some code? Maybe the check is simpler than I think.

Something like :

if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_IDAA64PFR0)) &&

    id_aa64pfr0_sve(id_aa64pfr0)) {
    ...
}
Quoted 8 lines

should be enough.

Or even we could hack it to :

if (id_aa64pfr0_sve(id_aa64pfr0 | read_sanitised_ftr_reg(SYS_IDAA64PFR0)))

As I mentioned, the code as such is fine. Its just that we try to detect if the SVE is already moot and skip the steps for this CPU.

How about the following, keeping the outer if(id_aa64pfr0_sve(int->reg_id_aa64pfr0)) from my current code:

Quoted 7 lines
Quoted 5 lines
(quoted diff) +3 -1
-		if (!sys_caps_initialised)
+		/* Probe vector lengths, unless we already gave up on SVE */
+		if (id_aa64pfr0_sve(read_sanitised_ftr_reg(ID_AA64PFR0_SVE)) &&
+		    !sys_caps_initialised)
			sve_update_vq_map();

Yep, that looks neater.

Sorry, that should have been

	if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1)) &&

(Disturbingly, the original does build and then hits a BUG(), because ID_AA64PFR0_SVE happens to be defined).

With the above, are you happy for me to apply your Reviewed-by, or would you prefer to wait for the respin?

Cheers
---Dave

reviewer Reviewed-by
#54 lore raw

Re: [PATCH v3 16/28] arm64/sve: Probe SVE capabilities and usable vector lengths

Quoted 65 lines · Dave Martin
Quoted 56 lines · Suzuki K Poulose
Quoted 55 lines · Dave Martin
Quoted 3 lines · Suzuki K Poulose
Quoted 2 lines · Dave Martin
Quoted 1 line · Suzuki K Poulose

On 10/10/17 19:38, Dave Martin wrote:

[...]

Quoted 36 lines
Quoted 17 lines
Quoted 17 lines

Review void update_cpu_features(int cpu, · line 697

Quoted 10 lines
(quoted diff) +7 -0
@@ -670,6 +689,14 @@ void update_cpu_features(int cpu,
  					info->reg_mvfr2, boot->reg_mvfr2);
  	}
+	if (id_aa64pfr0_sve(info->reg_id_aa64pfr0)) {
+		taint |= check_update_ftr_reg(SYS_ZCR_EL1, cpu,
+					info->reg_zcr, boot->reg_zcr);
+
+		if (!sys_caps_initialised)
+			sve_update_vq_map();
+	}

nit: I am not sure if we should also check if the "current" sanitised value of the id_aa64pfr0 also supports sve and skip the update if it isn't. The code is as such fine without the check, its just that we can avoid computing the map. It is in the CPU boot up path and hence is not performance critical. So, either way we are fine.

Quoted 5 lines
Quoted 1 line

I think I prefer to avoid adding extra code to optimise the "broken SoC design" case.

Sure.

Quoted 3 lines

Maybe we could revisit this later if needed.

Can you suggest some code? Maybe the check is simpler than I think.

Something like :

if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_IDAA64PFR0)) &&

     id_aa64pfr0_sve(id_aa64pfr0)) {
     ...
}
Quoted 8 lines

should be enough.

Or even we could hack it to :

if (id_aa64pfr0_sve(id_aa64pfr0 | read_sanitised_ftr_reg(SYS_IDAA64PFR0)))

As I mentioned, the code as such is fine. Its just that we try to detect if the SVE is already moot and skip the steps for this CPU.

How about the following, keeping the outer if(id_aa64pfr0_sve(int->reg_id_aa64pfr0)) from my current code:

Quoted 7 lines
Quoted 5 lines
(quoted diff) +3 -1
-		if (!sys_caps_initialised)
+		/* Probe vector lengths, unless we already gave up on SVE */
+		if (id_aa64pfr0_sve(read_sanitised_ftr_reg(ID_AA64PFR0_SVE)) &&
+		    !sys_caps_initialised)
			sve_update_vq_map();

Yep, that looks neater.

Quoted 6 lines

Sorry, that should have been

	if (id_aa64pfr0_sve(read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1)) &&

(Disturbingly, the original does build and then hits a BUG(), because ID_AA64PFR0_SVE happens to be defined).

Ouch ! I didn't notice that ;-). Good to see the BUG() catching such mistakes.

Quoted 4 lines

With the above, are you happy for me to apply your Reviewed-by, or would you prefer to wait for the respin?

With the changes as we discussed above, please feel free to add :

#55 lore raw

PATCH v3 17/28 arm64/sve: Preserve SVE registers around kernel-mode NEON use

In reply to Dave Martin

Kernel-mode NEON will corrupt the SVE vector registers, due to the way they alias the FPSIMD vector registers in the hardware.

This patch ensures that any live SVE register content for the task is saved by kernel_neon_begin(). The data will be restored in the usual way on return to userspace.

---
 arch/arm64/kernel/fpsimd.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
arch/arm64/kernel/fpsimd.c +4 -2
index 5673f50..b1d383a 100644
@@ -909,8 +909,10 @@ void kernel_neon_begin(void)
 	__this_cpu_write(kernel_neon_busy, true);
 
 	/* Save unsaved task fpsimd state, if any: */
-	if (current->mm && !test_and_set_thread_flag(TIF_FOREIGN_FPSTATE))
-		fpsimd_save_state(&current->thread.fpsimd_state);
+	if (current->mm) {
+		task_fpsimd_save();
+		set_thread_flag(TIF_FOREIGN_FPSTATE);
+	}
 
 	/* Invalidate any task state remaining in the fpsimd regs: */
 	__this_cpu_write(fpsimd_last_state, NULL);
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 17/28
#56 lore raw

Re: [PATCH v3 17/28] arm64/sve: Preserve SVE registers around kernel-mode NEON use

Quoted 10 lines · Dave P Martin

Kernel-mode NEON will corrupt the SVE vector registers, due to the way they alias the FPSIMD vector registers in the hardware.

This patch ensures that any live SVE register content for the task is saved by kernel_neon_begin(). The data will be restored in the usual way on return to userspace.

#57 lore raw

PATCH v3 18/28 arm64/sve: Preserve SVE registers around EFI runtime service calls

In reply to Dave Martin

The EFI runtime services ABI allows EFI to make free use of the FPSIMD registers during EFI runtime service calls, subject to the callee-save requirements of the AArch64 procedure call standard.

However, the SVE architecture allows upper bits of the SVE vector registers to be zeroed as a side-effect of FPSIMD V-register writes. This means that the SVE vector registers must be saved in their entirety in order to avoid data loss: non-SVE-aware EFI implementations cannot restore them correctly.

The non-IRQ case is already handled gracefully by kernel_neon_begin(). For the IRQ case, this patch allocates a suitable per-CPU stash buffer for the full SVE register state and uses it to preserve the affected registers around EFI calls. It is currently unclear how the EFI runtime services ABI will be clarified with respect to SVE, so it safest to assume that the predicate registers and FFR must be saved and restored too.

No attempt is made to restore the restore the vector length after a call, for now. It is deemed rather insane for EFI to change it, and contemporary EFI implementations certainly won't.

---

Changes since v2
----------------

Miscellaneous:

* Applied a BUG_ON removal that was split into the wrong patch in v2.

* Fixed overindentation of panic() call in sve_efi_setup().

---
 arch/arm64/kernel/fpsimd.c | 67 +++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 61 insertions(+), 6 deletions(-)
arch/arm64/kernel/fpsimd.c +61 -6
index b1d383a..c194627 100644
@@ -121,11 +121,13 @@ static int sve_default_vl = -1;
 int __ro_after_init sve_max_vl = -1;
 /* Set of available vector lengths, as vq_to_bit(vq): */
 static __ro_after_init DECLARE_BITMAP(sve_vq_map, SVE_VQ_MAX);
+static void __percpu *efi_sve_state;
 
 #else /* ! CONFIG_ARM64_SVE */
 
 /* Dummy declaration for code that will be optimised out: */
 extern __ro_after_init DECLARE_BITMAP(sve_vq_map, SVE_VQ_MAX);
+extern void __percpu *efi_sve_state;
 
 #endif /* ! CONFIG_ARM64_SVE */
 
@@ -562,6 +564,30 @@ int sve_verify_vq_map(void)
 	return ret;
 }
 
+static void __init sve_efi_setup(void)
+{
+	if (!IS_ENABLED(CONFIG_EFI))
+		return;
+
+	/*
+	 * alloc_percpu() warns and prints a backtrace if this goes wrong.
+	 * This is evidence of a crippled system and we are returning void,
+	 * so no attempt is made to handle this situation here.
+	 */
+	if (!sve_vl_valid(sve_max_vl))
+		goto fail;
+
+	efi_sve_state = __alloc_percpu(
+		SVE_SIG_REGS_SIZE(sve_vq_from_vl(sve_max_vl)), SVE_VQ_BYTES);
+	if (!efi_sve_state)
+		goto fail;
+
+	return;
+
+fail:
+	panic("Cannot allocate percpu memory for EFI SVE save/restore");
+}
+
 /*
  * Enable SVE for EL1.
  * Intended for use by the cpufeatures code during CPU boot.
@@ -609,6 +635,8 @@ void __init sve_setup(void)
 		sve_max_vl);
 	pr_info("SVE: default vector length %u bytes per vector\n",
 		sve_default_vl);
+
+	sve_efi_setup();
 }
 
 void fpsimd_release_thread(struct task_struct *dead_task)
@@ -950,6 +978,7 @@ EXPORT_SYMBOL(kernel_neon_end);
 
 static DEFINE_PER_CPU(struct fpsimd_state, efi_fpsimd_state);
 static DEFINE_PER_CPU(bool, efi_fpsimd_state_used);
+static DEFINE_PER_CPU(bool, efi_sve_state_used);
 
 /*
  * EFI runtime services support functions
@@ -975,10 +1004,24 @@ void __efi_fpsimd_begin(void)
 
 	WARN_ON(preemptible());
 
-	if (may_use_simd())
+	if (may_use_simd()) {
 		kernel_neon_begin();
-	else {
-		fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
+	} else {
+		/*
+		 * If !efi_sve_state, SVE can't be in use yet and doesn't need
+		 * preserving:
+		 */
+		if (system_supports_sve() && likely(efi_sve_state)) {
+			char *sve_state = this_cpu_ptr(efi_sve_state);
+
+			__this_cpu_write(efi_sve_state_used, true);
+
+			sve_save_state(sve_state + sve_ffr_offset(sve_max_vl),
+				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr);
+		} else {
+			fpsimd_save_state(this_cpu_ptr(&efi_fpsimd_state));
+		}
+
 		__this_cpu_write(efi_fpsimd_state_used, true);
 	}
 }
@@ -991,10 +1034,22 @@ void __efi_fpsimd_end(void)
 	if (!system_supports_fpsimd())
 		return;
 
-	if (__this_cpu_xchg(efi_fpsimd_state_used, false))
-		fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
-	else
+	if (!__this_cpu_xchg(efi_fpsimd_state_used, false)) {
 		kernel_neon_end();
+	} else {
+		if (system_supports_sve() &&
+		    likely(__this_cpu_read(efi_sve_state_used))) {
+			char const *sve_state = this_cpu_ptr(efi_sve_state);
+
+			sve_load_state(sve_state + sve_ffr_offset(sve_max_vl),
+				       &this_cpu_ptr(&efi_fpsimd_state)->fpsr,
+				       sve_vq_from_vl(sve_get_vl()) - 1);
+
+			__this_cpu_write(efi_sve_state_used, false);
+		} else {
+			fpsimd_load_state(this_cpu_ptr(&efi_fpsimd_state));
+		}
+	}
 }
 
 #endif /* CONFIG_EFI */
Signature · 1 line
2.1.4
maintainer Reviewed-by on v3 18/28
#58 lore raw

Re: [PATCH v3 18/28] arm64/sve: Preserve SVE registers around EFI runtime service calls

Quoted 18 lines · Dave P Martin

The EFI runtime services ABI allows EFI to make free use of the FPSIMD registers during EFI runtime service calls, subject to the callee-save requirements of the AArch64 procedure call standard.

However, the SVE architecture allows upper bits of the SVE vector registers to be zeroed as a side-effect of FPSIMD V-register writes. This means that the SVE vector registers must be saved in their entirety in order to avoid data loss: non-SVE-aware EFI implementations cannot restore them correctly.

The non-IRQ case is already handled gracefully by kernel_neon_begin(). For the IRQ case, this patch allocates a suitable per-CPU stash buffer for the full SVE register state and uses it to preserve the affected registers around EFI calls. It is currently unclear how the EFI runtime services ABI will be clarified with respect to SVE, so it safest to assume that the predicate registers and FFR must be saved and restored too.

Quoted 7 lines

No attempt is made to restore the restore the vector length after a call, for now. It is deemed rather insane for EFI to change it, and contemporary EFI implementations certainly won't.

#59 lore raw

PATCH v3 19/28 arm64/sve: ptrace and ELF coredump support

In reply to Dave Martin

This patch defines and implements a new regset NT_ARM_SVE, which describes a thread's SVE register state. This allows a debugger to manipulate the SVE state, as well as being included in ELF coredumps for post-mortem debugging.

Because the regset size and layout are dependent on the thread's current vector length, it is not possible to define a C struct to describe the regset contents as is done for existing regsets. Instead, and for the same reasons, NT_ARM_SVE is based on the freeform variable-layout approach used for the SVE signal frame.

Additionally, to reduce debug overhead when debugging threads that might or might not have live SVE register state, NT_ARM_SVE may be presented in one of two different formats: the old struct user_fpsimd_state format is embedded for describing the state of a thread with no live SVE state, whereas a new variable-layout structure is embedded for describing live SVE state. This avoids a debugger needing to poll NT_PRFPREG in addition to NT_ARM_SVE, and allows existing userspace code to handle the non-SVE case without too much modification.

For this to work, NT_ARM_SVE is defined with a fixed-format header of type struct user_sve_header, which the recipient can use to figure out the content, size and layout of the reset of the regset. Accessor macros are defined to allow the vector-length-dependent parts of the regset to be manipulated.

Cc Alex Bennée <[email protected]>
Cc Okamoto Takayuki <[email protected]>

---

Dropped Alex Bennée's reviewed-by, since bug fixes have been applied.

Changes since v2
----------------

Bug fixes:

* Initialised user_sve_header.sve_max_vl properly in sve_init_header_from_task(). (Reported by Okamoto Takayuki.)

This bug was introduced by the refactoring since v1 to remove BUG_ON()s. A WARN_ON() was introduced to fix up the error case here, but the code for the non-error case was lost.

This resulted in userspace seeing max_size == 0 when reading NT_ARM_SVE with PTRACE_GETREGSET. NT_ARM_SVE would also get truncated in coredmups (though I've not tested that).

This fix ensures that max_size is initialised, and only overrides the value written if it would be garbage.

* In sve_set(), the flags for sve_set_vector_length() are shifted into the correct position. Without this, a PTRACE_SETREGSET for NT_ARM_SVE may reject valid flags (including flags read via PTRACE_GETREGSET) with -EINVAL: thus, legitimate uses including save/restore may not work.

Miscellaneous:

* Clarified comment in ptrace.h about keeping flags in sync with prctl.h so that it won't be misinterpreted as applying to SVE_PT_REGS_{MASK, FPSIMD,SVE} (which deliberately have no prctl equivalent).

* Added comments explaining the intent, purpose and basic constraints for fpsimd.c helpers.

---
 arch/arm64/include/asm/fpsimd.h      |  13 +-
 arch/arm64/include/uapi/asm/ptrace.h | 138 ++++++++++++++++++
 arch/arm64/kernel/fpsimd.c           |  60 ++++++++
 arch/arm64/kernel/ptrace.c           | 271 +++++++++++++++++++++++++++++++++--
 include/uapi/linux/elf.h             |   1 +
 5 files changed, 474 insertions(+), 9 deletions(-)
arch/arm64/include/asm/fpsimd.h +12 -1
index bad72fd..ee6db38 100644
@@ -38,13 +38,16 @@ struct fpsimd_state {
 			__uint128_t vregs[32];
 			u32 fpsr;
 			u32 fpcr;
+			/*
+			 * For ptrace compatibility, pad to next 128-bit
+			 * boundary here if extending this struct.
+			 */
 		};
 	};
 	/* the id of the last cpu to have restored this state */
 	unsigned int cpu;
 };
 
-
 #if defined(__KERNEL__) && defined(CONFIG_COMPAT)
 /* Masks for extracting the FPSR and FPCR from the FPSCR */
 #define VFP_FPSCR_STAT_MASK	0xf800009f
@@ -89,6 +92,10 @@ extern size_t sve_state_size(struct task_struct const *task);
 
 extern void sve_alloc(struct task_struct *task);
 extern void fpsimd_release_thread(struct task_struct *task);
+extern void fpsimd_sync_to_sve(struct task_struct *task);
+extern void sve_sync_to_fpsimd(struct task_struct *task);
+extern void sve_sync_from_fpsimd_zeropad(struct task_struct *task);
+
 extern int sve_set_vector_length(struct task_struct *task,
 				 unsigned long vl, unsigned long flags);
 
@@ -105,6 +112,10 @@ extern void __init sve_setup(void);
 
 static void __maybe_unused sve_alloc(struct task_struct *task) { }
 static void __maybe_unused fpsimd_release_thread(struct task_struct *task) { }
+static void __maybe_unused sve_sync_to_fpsimd(struct task_struct *task) { }
+static void __maybe_unused sve_sync_from_fpsimd_zeropad(
+	struct task_struct *task) { }
+
 static void __maybe_unused sve_init_vq_map(void) { }
 static void __maybe_unused sve_update_vq_map(void) { }
 static int __maybe_unused sve_verify_vq_map(void) { return 0; }
arch/arm64/include/uapi/asm/ptrace.h +138 -0

156 lines not on this page · raw message

arch/arm64/kernel/fpsimd.c +60 -0

66 lines not on this page · raw message

arch/arm64/kernel/ptrace.c +263 -8

326 lines not on this page · raw message

include/uapi/linux/elf.h +1 -0
index b5280db..735b8f4 100644
@@ -416,6 +416,7 @@ typedef struct elf64_shdr {
 #define NT_ARM_HW_BREAK	0x402		/* ARM hardware breakpoint registers */
 #define NT_ARM_HW_WATCH	0x403		/* ARM hardware watchpoint registers */
 #define NT_ARM_SYSTEM_CALL	0x404	/* ARM system call number */
+#define NT_ARM_SVE	0x405		/* ARM Scalable Vector Extension registers */
 #define NT_METAG_CBUF	0x500		/* Metag catch buffer registers */
 #define NT_METAG_RPIPE	0x501		/* Metag read pipeline state */
 #define NT_METAG_TLS	0x502		/* Metag TLS pointer */
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer
#60 lore raw

Re: [PATCH v3 19/28] arm64/sve: ptrace and ELF coredump support

Quoted 5 lines · Dave P Martin
arch/arm64/kernel/ptrace.c +1 -0
@@ -702,6 +737,211 @@ static int system_call_set(struct task_struct *target,
 	return ret;
 }
 
+#ifdef CONFIG_ARM64_SVE

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 750

Quoted 10 lines
arch/arm64/kernel/ptrace.c +10 -0
+
+static void sve_init_header_from_task(struct user_sve_header *header,
+				      struct task_struct *target)
+{
+	unsigned int vq;
+
+	memset(header, 0, sizeof(*header));
+
+	header->flags = test_tsk_thread_flag(target, TIF_SVE) ?
+		SVE_PT_REGS_SVE : SVE_PT_REGS_FPSIMD;

For PTRACE_SYSCALL, we may or may not have TIF_SVE depending on what happened with the target. Just a thought: shall we clear TIF_SVE (and sync it to fpsimd) in syscall_trace_enter()?

Quoted 14 lines
arch/arm64/kernel/ptrace.c +14 -0
+	if (test_tsk_thread_flag(target, TIF_SVE_VL_INHERIT))
+		header->flags |= SVE_PT_VL_INHERIT;
+
+	header->vl = target->thread.sve_vl;
+	vq = sve_vq_from_vl(header->vl);
+
+	header->max_vl = sve_max_vl;
+	if (WARN_ON(!sve_vl_valid(sve_max_vl)))
+		header->max_vl = header->vl;
+
+	header->size = SVE_PT_SIZE(vq, header->flags);
+	header->max_size = SVE_PT_SIZE(sve_vq_from_vl(header->max_vl),
+				      SVE_PT_REGS_SVE);
+}

[...]

Quoted 34 lines
arch/arm64/kernel/ptrace.c +34 -0
+static int sve_set(struct task_struct *target,
+		   const struct user_regset *regset,
+		   unsigned int pos, unsigned int count,
+		   const void *kbuf, const void __user *ubuf)
+{
+	int ret;
+	struct user_sve_header header;
+	unsigned int vq;
+	unsigned long start, end;
+
+	if (!system_supports_sve())
+		return -EINVAL;
+
+	/* Header */
+	if (count < sizeof(header))
+		return -EINVAL;
+	ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &header,
+				 0, sizeof(header));
+	if (ret)
+		goto out;
+
+	/*
+	 * Apart from PT_SVE_REGS_MASK, all PT_SVE_* flags are consumed by
+	 * sve_set_vector_length(), which will also validate them for us:
+	 */
+	ret = sve_set_vector_length(target, header.vl,
+		((unsigned long)header.flags & ~SVE_PT_REGS_MASK) << 16);
+	if (ret)
+		goto out;
+
+	/* Actual VL set may be less than the user asked for: */
+	vq = sve_vq_from_vl(target->thread.sve_vl);
+
+	/* Registers: FPSIMD-only case */

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 894

Quoted 10 lines
arch/arm64/kernel/ptrace.c +10 -0
+
+	BUILD_BUG_ON(SVE_PT_FPSIMD_OFFSET != sizeof(header));
+	if ((header.flags & SVE_PT_REGS_MASK) == SVE_PT_REGS_FPSIMD) {
+		sve_sync_to_fpsimd(target);
+
+		ret = __fpr_set(target, regset, pos, count, kbuf, ubuf,
+				SVE_PT_FPSIMD_OFFSET);
+		clear_tsk_thread_flag(target, TIF_SVE);
+		goto out;
+	}

__fpr_set() already calls sve_sync_to_fpsimd(). Anyway, do you actually need this since we are going to override the FPSIMD state anyway here.

Quoted 5 lines
arch/arm64/kernel/ptrace.c +5 -0
+
+	/* Otherwise: full SVE case */
+
+	/*
+	 * If setting a different VL from the requested VL and there is

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 909

Quoted 10 lines
arch/arm64/kernel/ptrace.c +10 -0
+	 * register data, the data layout will be wrong: don't even
+	 * try to set the registers in this case.
+	 */
+	if (count && vq != sve_vq_from_vl(header.vl)) {
+		ret = -EIO;
+		goto out;
+	}
+
+	sve_alloc(target);
+	fpsimd_sync_to_sve(target);

Similarly here, it's a full SVE case, so we are going to override it anyway.

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 910

Quoted 1 line
arch/arm64/kernel/ptrace.c +1 -0
+	set_tsk_thread_flag(target, TIF_SVE);

This has the side-effect of enabling TIF_SVE even for PTRACE_SYSCALL which may be cleared in some circumstances. It may not be an issue though.

Signature · 1 line
Catalin
#61 lore raw

Re: [PATCH v3 19/28] arm64/sve: ptrace and ELF coredump support

Quoted 5 lines · Catalin Marinas
Quoted 4 lines · Dave P Martin
arch/arm64/kernel/ptrace.c +0 -0
@@ -702,6 +737,211 @@ static int system_call_set(struct task_struct *target,
 	return ret;
 }
 
Quoted 15 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 750

Quoted 11 lines
arch/arm64/kernel/ptrace.c +11 -0
+#ifdef CONFIG_ARM64_SVE
+
+static void sve_init_header_from_task(struct user_sve_header *header,
+				      struct task_struct *target)
+{
+	unsigned int vq;
+
+	memset(header, 0, sizeof(*header));
+
+	header->flags = test_tsk_thread_flag(target, TIF_SVE) ?
+		SVE_PT_REGS_SVE : SVE_PT_REGS_FPSIMD;

For PTRACE_SYSCALL, we may or may not have TIF_SVE depending on what happened with the target. Just a thought: shall we clear TIF_SVE (and sync it to fpsimd) in syscall_trace_enter()?

I'm not so sure: if we were to do that, a syscall that is cancelled by writing -1 to REGSET_SYSCALL could still discard the SVE registers as a side-effect.

The target committed to discard by executing SVC, but my feeling is that cancellation of a syscall in this way shouldn't have avoidable side-effects for the target. But the semantics of cancelled syscalls are a bit of a grey area, so I can see potential arguments on both sides.

The current approach at least saves a bit of code. What do you think?

Quoted 53 lines
Quoted 14 lines
arch/arm64/kernel/ptrace.c +14 -0
+	if (test_tsk_thread_flag(target, TIF_SVE_VL_INHERIT))
+		header->flags |= SVE_PT_VL_INHERIT;
+
+	header->vl = target->thread.sve_vl;
+	vq = sve_vq_from_vl(header->vl);
+
+	header->max_vl = sve_max_vl;
+	if (WARN_ON(!sve_vl_valid(sve_max_vl)))
+		header->max_vl = header->vl;
+
+	header->size = SVE_PT_SIZE(vq, header->flags);
+	header->max_size = SVE_PT_SIZE(sve_vq_from_vl(header->max_vl),
+				      SVE_PT_REGS_SVE);
+}

[...]

Quoted 38 lines
arch/arm64/kernel/ptrace.c +38 -0
+static int sve_set(struct task_struct *target,
+		   const struct user_regset *regset,
+		   unsigned int pos, unsigned int count,
+		   const void *kbuf, const void __user *ubuf)
+{
+	int ret;
+	struct user_sve_header header;
+	unsigned int vq;
+	unsigned long start, end;
+
+	if (!system_supports_sve())
+		return -EINVAL;
+
+	/* Header */
+	if (count < sizeof(header))
+		return -EINVAL;
+	ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &header,
+				 0, sizeof(header));
+	if (ret)
+		goto out;
+
+	/*
+	 * Apart from PT_SVE_REGS_MASK, all PT_SVE_* flags are consumed by
+	 * sve_set_vector_length(), which will also validate them for us:
+	 */
+	ret = sve_set_vector_length(target, header.vl,
+		((unsigned long)header.flags & ~SVE_PT_REGS_MASK) << 16);
+	if (ret)
+		goto out;
+
+	/* Actual VL set may be less than the user asked for: */
+	vq = sve_vq_from_vl(target->thread.sve_vl);
+
+	/* Registers: FPSIMD-only case */
+
+	BUILD_BUG_ON(SVE_PT_FPSIMD_OFFSET != sizeof(header));
+	if ((header.flags & SVE_PT_REGS_MASK) == SVE_PT_REGS_FPSIMD) {
+		sve_sync_to_fpsimd(target);
Quoted 8 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 894

Quoted 6 lines
arch/arm64/kernel/ptrace.c +6 -0
+
+		ret = __fpr_set(target, regset, pos, count, kbuf, ubuf,
+				SVE_PT_FPSIMD_OFFSET);
+		clear_tsk_thread_flag(target, TIF_SVE);
+		goto out;
+	}

__fpr_set() already calls sve_sync_to_fpsimd(). Anyway, do you actually

Yes, the call to sve_sync_to_fpsimd() is superfluous here -- I think that I realised that all callers of __fpr_set() need this to happen, but never deleted the explicit call from sve_set().

I'll delete it.

Looking more closely at __fpr_set() though, I think it needs this change too, because the sync is unintentionally placed after reading thread.fpsimd_state instead of before:

@@ -652,11 +652,12 @@ static int __fpr_set(struct task_struct *target,
unsigned int start_pos)

 {
        int ret;

- struct user_fpsimd_state newstate =
- target->thread.fpsimd_state.user_fpsimd;
+ struct user_fpsimd_state newstate;

        sve_sync_to_fpsimd(target);

+ newstate = target->thread.fpsimd_state.user_fpsimd;
+
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &newstate,
[...]

(Or were you confident that this was already OK? Maybe I'm confusing myself.)

Quoted 1 line

need this since we are going to override the FPSIMD state anyway here.

The underlying reason for this is the issue of what should happen for short regset writes. Historically, writes through fpr_set() can be truncated arbitrarily, and the rest of fpsimd_state will remain unchanged.

The issue is that if TIF_SVE is set, fpsimd_state can be stale for target. If the initial sve_sync_to_fpsimd() is removed in sve_set() above, then we may resurrect old values for the untouched registers, instead of simply leaving them unmodified.

Should I add comments explaining the purpose? I guess it is rather non-obvious.

Of course, I don't know whether userspace should really rely on partial regset writes doing anything sane, but I figured the implemented behaviour is at least less surprising with respect to the fpr_set() behavior.

No legacy software can be relying on NT_ARM_SVE at all, so the behaviour here may not matter that much. My idea was to reduce the invasiveness of porting ptrace clients to use NT_ARM_SVE.

Quoted 11 lines
Quoted 11 lines
arch/arm64/kernel/ptrace.c +10 -0
+
+	/* Otherwise: full SVE case */
+
+	/*
+	 * If setting a different VL from the requested VL and there is
+	 * register data, the data layout will be wrong: don't even
+	 * try to set the registers in this case.
+	 */
+	if (count && vq != sve_vq_from_vl(header.vl)) {
+		ret = -EIO;
Quoted 8 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 909

Quoted 5 lines
arch/arm64/kernel/ptrace.c +5 -0
+		goto out;
+	}
+
+	sve_alloc(target);
+	fpsimd_sync_to_sve(target);

Similarly here, it's a full SVE case, so we are going to override it anyway.

The argument here is similar: target->sve_state might already be allocated and if so it could contain data that doesn't match the user task's idea of what's in the V-regs. (In fact, sve_alloc() currently zeroes sve_state, but that's still different from the current V-regs.)

There is no possibility of legacy software relying on this code path, so we could say that a short write to NT_ARM_SVE with PT_SVE_REGS_SVE in flags zeroes any trailing data instead of preserving it.

Either way, I don't intend to document the behaviour of partial writes to NT_ARM_SVE. From a userspace point of view, I leave it unspecified.

Quoted 5 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 910

Quoted 1 line
arch/arm64/kernel/ptrace.c +1 -0
+	set_tsk_thread_flag(target, TIF_SVE);

This has the side-effect of enabling TIF_SVE even for PTRACE_SYSCALL which may be cleared in some circumstances. It may not be an issue though.

I would argue that this is correct behaviour: the syscall enter trap and exit traps should both behave as if they are outside the syscall, allowing the debugger to simulate the effect of inserting any instructions the target could have inserted before or after the SVC. This may include simulating SVE instructions or modifying SVE regs, which would require TIF_SVE to get set.

If the tracer doesn't cancel the syscall at the enter trap, then a real syscall will execute and that may cause the SVE state to be discarded in the usual way in the case of preemption or blocking: it seems cleaner for the debug illusion that this decision isn't made differently just because the target is being traced.

(Spoiler alert though: the syscall exit trap will force the target to be scheduled out, which will force discard with the current task_fpsimd_save() behaviour ... but that could be changed in the future, and I prefer not to document any sort of guarantee here.)

Does this make sense? There may be issues or corner cases here that I didn't spot...

Cheers
---Dave

maintainer
#62 lore raw

Re: [PATCH v3 19/28] arm64/sve: ptrace and ELF coredump support

Quoted 26 lines · Dave P Martin
Quoted 5 lines · Catalin Marinas
Quoted 4 lines · Dave P Martin
arch/arm64/kernel/ptrace.c +0 -0
@@ -702,6 +737,211 @@ static int system_call_set(struct task_struct *target,
 	return ret;
 }
 
Quoted 15 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 750

Quoted 11 lines
arch/arm64/kernel/ptrace.c +11 -0
+#ifdef CONFIG_ARM64_SVE
+
+static void sve_init_header_from_task(struct user_sve_header *header,
+				      struct task_struct *target)
+{
+	unsigned int vq;
+
+	memset(header, 0, sizeof(*header));
+
+	header->flags = test_tsk_thread_flag(target, TIF_SVE) ?
+		SVE_PT_REGS_SVE : SVE_PT_REGS_FPSIMD;

For PTRACE_SYSCALL, we may or may not have TIF_SVE depending on what happened with the target. Just a thought: shall we clear TIF_SVE (and sync it to fpsimd) in syscall_trace_enter()?

I'm not so sure: if we were to do that, a syscall that is cancelled by writing -1 to REGSET_SYSCALL could still discard the SVE registers as a side-effect.

Quoted 5 lines

The target committed to discard by executing SVC, but my feeling is that cancellation of a syscall in this way shouldn't have avoidable side-effects for the target. But the semantics of cancelled syscalls are a bit of a grey area, so I can see potential arguments on both sides.

We already can't guarantee this - if the task invoking a syscall gets preempted before syscall_trace_enter(), TIF_SVE will be cleared. Are you reinstating TIF_SVE if the syscall was cancelled?

So my comment was more about consistency on presenting the SVE state to the debugger handling PTRACE_SYSCALL.

Quoted 40 lines
Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/ptrace.c +5 -0
+	/* Registers: FPSIMD-only case */
+
+	BUILD_BUG_ON(SVE_PT_FPSIMD_OFFSET != sizeof(header));
+	if ((header.flags & SVE_PT_REGS_MASK) == SVE_PT_REGS_FPSIMD) {
+		sve_sync_to_fpsimd(target);
Quoted 8 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 894

Quoted 6 lines
arch/arm64/kernel/ptrace.c +6 -0
+
+		ret = __fpr_set(target, regset, pos, count, kbuf, ubuf,
+				SVE_PT_FPSIMD_OFFSET);
+		clear_tsk_thread_flag(target, TIF_SVE);
+		goto out;
+	}

__fpr_set() already calls sve_sync_to_fpsimd(). Anyway, do you actually

Yes, the call to sve_sync_to_fpsimd() is superfluous here -- I think that I realised that all callers of __fpr_set() need this to happen, but never deleted the explicit call from sve_set().

I'll delete it.

Looking more closely at __fpr_set() though, I think it needs this change too, because the sync is unintentionally placed after reading thread.fpsimd_state instead of before:

(quoted diff) +3 -2
@@ -652,11 +652,12 @@ static int __fpr_set(struct task_struct *target,
                     unsigned int start_pos)
 {
        int ret;
-       struct user_fpsimd_state newstate =
-               target->thread.fpsimd_state.user_fpsimd;
+       struct user_fpsimd_state newstate;
 
        sve_sync_to_fpsimd(target);
 
+       newstate = target->thread.fpsimd_state.user_fpsimd;
+
        ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &newstate,
[...]
Quoted 2 lines

(Or were you confident that this was already OK? Maybe I'm confusing myself.)

With the sve_sync_to_fpsimd() called before __fpr_set(), it was ok. Once you removed that you indeed need the change to __fpr_set().

Quoted 6 lines
Quoted 1 line

need this since we are going to override the FPSIMD state anyway here.

The underlying reason for this is the issue of what should happen for short regset writes. Historically, writes through fpr_set() can be truncated arbitrarily, and the rest of fpsimd_state will remain unchanged.

Ah, I forgot about this.

Quoted 7 lines

The issue is that if TIF_SVE is set, fpsimd_state can be stale for target. If the initial sve_sync_to_fpsimd() is removed in sve_set() above, then we may resurrect old values for the untouched registers, instead of simply leaving them unmodified.

Should I add comments explaining the purpose? I guess it is rather non-obvious.

Yes, please.

Quoted 6 lines
Quoted 5 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 910

Quoted 1 line
arch/arm64/kernel/ptrace.c +1 -0
+	set_tsk_thread_flag(target, TIF_SVE);

This has the side-effect of enabling TIF_SVE even for PTRACE_SYSCALL which may be cleared in some circumstances. It may not be an issue though.

Quoted 6 lines

I would argue that this is correct behaviour: the syscall enter trap and exit traps should both behave as if they are outside the syscall, allowing the debugger to simulate the effect of inserting any instructions the target could have inserted before or after the SVC. This may include simulating SVE instructions or modifying SVE regs, which would require TIF_SVE to get set.

I'm ok with this approach but I'm not sure we can guarantee it with preemption enabled.

Quoted 10 lines

If the tracer doesn't cancel the syscall at the enter trap, then a real syscall will execute and that may cause the SVE state to be discarded in the usual way in the case of preemption or blocking: it seems cleaner for the debug illusion that this decision isn't made differently just because the target is being traced.

(Spoiler alert though: the syscall exit trap will force the target to be scheduled out, which will force discard with the current task_fpsimd_save() behaviour ... but that could be changed in the future, and I prefer not to document any sort of guarantee here.)

If such state isn't guaranteed, then the de-facto ABI is that the debugger cannot simulate any SVE instruction via NO_SYSCALL since the SVE state may be discarded. So it can only rely on what's guaranteed and changing the behaviour later won't actually help.

Signature · 1 line
Catalin
#63 lore raw

Re: [PATCH v3 19/28] arm64/sve: ptrace and ELF coredump support

Quoted 33 lines · Catalin Marinas
Quoted 26 lines · Dave P Martin
Quoted 5 lines · Catalin Marinas
Quoted 4 lines · Dave P Martin
arch/arm64/kernel/ptrace.c +0 -0
@@ -702,6 +737,211 @@ static int system_call_set(struct task_struct *target,
 	return ret;
 }
 
Quoted 15 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 750

Quoted 11 lines
arch/arm64/kernel/ptrace.c +11 -0
+#ifdef CONFIG_ARM64_SVE
+
+static void sve_init_header_from_task(struct user_sve_header *header,
+				      struct task_struct *target)
+{
+	unsigned int vq;
+
+	memset(header, 0, sizeof(*header));
+
+	header->flags = test_tsk_thread_flag(target, TIF_SVE) ?
+		SVE_PT_REGS_SVE : SVE_PT_REGS_FPSIMD;

For PTRACE_SYSCALL, we may or may not have TIF_SVE depending on what happened with the target. Just a thought: shall we clear TIF_SVE (and sync it to fpsimd) in syscall_trace_enter()?

I'm not so sure: if we were to do that, a syscall that is cancelled by writing -1 to REGSET_SYSCALL could still discard the SVE registers as a side-effect.

Quoted 5 lines

The target committed to discard by executing SVC, but my feeling is that cancellation of a syscall in this way shouldn't have avoidable side-effects for the target. But the semantics of cancelled syscalls are a bit of a grey area, so I can see potential arguments on both sides.

Quoted 6 lines

We already can't guarantee this - if the task invoking a syscall gets preempted before syscall_trace_enter(), TIF_SVE will be cleared. Are you reinstating TIF_SVE if the syscall was cancelled?

So my comment was more about consistency on presenting the SVE state to the debugger handling PTRACE_SYSCALL.

See the end of this reply.

Quoted 40 lines
Quoted 40 lines
Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/ptrace.c +5 -0
+	/* Registers: FPSIMD-only case */
+
+	BUILD_BUG_ON(SVE_PT_FPSIMD_OFFSET != sizeof(header));
+	if ((header.flags & SVE_PT_REGS_MASK) == SVE_PT_REGS_FPSIMD) {
+		sve_sync_to_fpsimd(target);
Quoted 8 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 894

Quoted 6 lines
arch/arm64/kernel/ptrace.c +6 -0
+
+		ret = __fpr_set(target, regset, pos, count, kbuf, ubuf,
+				SVE_PT_FPSIMD_OFFSET);
+		clear_tsk_thread_flag(target, TIF_SVE);
+		goto out;
+	}

__fpr_set() already calls sve_sync_to_fpsimd(). Anyway, do you actually

Yes, the call to sve_sync_to_fpsimd() is superfluous here -- I think that I realised that all callers of __fpr_set() need this to happen, but never deleted the explicit call from sve_set().

I'll delete it.

Looking more closely at __fpr_set() though, I think it needs this change too, because the sync is unintentionally placed after reading thread.fpsimd_state instead of before:

(quoted diff) +3 -2
@@ -652,11 +652,12 @@ static int __fpr_set(struct task_struct *target,
                     unsigned int start_pos)
 {
        int ret;
-       struct user_fpsimd_state newstate =
-               target->thread.fpsimd_state.user_fpsimd;
+       struct user_fpsimd_state newstate;
 
        sve_sync_to_fpsimd(target);
 
+       newstate = target->thread.fpsimd_state.user_fpsimd;
+
        ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &newstate,
[...]
Quoted 5 lines
Quoted 2 lines

(Or were you confident that this was already OK? Maybe I'm confusing myself.)

With the sve_sync_to_fpsimd() called before __fpr_set(), it was ok. Once you removed that you indeed need the change to __fpr_set().

Hmmm, yes. Anyway, I've applied the above fix, so I think this should be fine now.

Quoted 14 lines
Quoted 6 lines
Quoted 1 line

need this since we are going to override the FPSIMD state anyway here.

The underlying reason for this is the issue of what should happen for short regset writes. Historically, writes through fpr_set() can be truncated arbitrarily, and the rest of fpsimd_state will remain unchanged.

Ah, I forgot about this.

Quoted 5 lines

The issue is that if TIF_SVE is set, fpsimd_state can be stale for target. If the initial sve_sync_to_fpsimd() is removed in sve_set() above, then we may resurrect old values for the untouched registers, instead of simply leaving them unmodified.

Quoted 4 lines
Quoted 2 lines

Should I add comments explaining the purpose? I guess it is rather non-obvious.

Yes, please.

Will do. It's pretty yucky.

Quoted 14 lines
Quoted 7 lines
Quoted 6 lines

arch/arm64/kernel/ptrace.c static int system_call_set(struct task_struct *target, · line 910

Quoted 2 lines
arch/arm64/kernel/ptrace.c +1 -0
+	set_tsk_thread_flag(target, TIF_SVE);

This has the side-effect of enabling TIF_SVE even for PTRACE_SYSCALL which may be cleared in some circumstances. It may not be an issue though.

Quoted 6 lines

I would argue that this is correct behaviour: the syscall enter trap and exit traps should both behave as if they are outside the syscall, allowing the debugger to simulate the effect of inserting any instructions the target could have inserted before or after the SVC. This may include simulating SVE instructions or modifying SVE regs, which would require TIF_SVE to get set.

Quoted 2 lines

I'm ok with this approach but I'm not sure we can guarantee it with preemption enabled.

Hmmm, I think I'm guilty of inventing a spurious argument here.

Apparently gdb does not do syscall cancelling.

Strace does though.
(See http://man7.org/linux/man-pages/man1/strace.1.html, search for "syscall tampering" ;)

However, it never tries to skip a syscall entirelity AFAICT:
instead, it only attempts to fake what occurs during the syscall, such as bailing out with a predetermined return value.

Quoted 11 lines
Quoted 10 lines

If the tracer doesn't cancel the syscall at the enter trap, then a real syscall will execute and that may cause the SVE state to be discarded in the usual way in the case of preemption or blocking: it seems cleaner for the debug illusion that this decision isn't made differently just because the target is being traced.

(Spoiler alert though: the syscall exit trap will force the target to be scheduled out, which will force discard with the current task_fpsimd_save() behaviour ... but that could be changed in the future, and I prefer not to document any sort of guarantee here.)

Quoted 4 lines

If such state isn't guaranteed, then the de-facto ABI is that the debugger cannot simulate any SVE instruction via NO_SYSCALL since the SVE state may be discarded. So it can only rely on what's guaranteed and changing the behaviour later won't actually help.

I think you're right.

Simulating the content of the syscall does work though, and doesn't depend on whether SVE discard occurs or not.

If the tracer sets the SVE regs at the syscall enter/exit traps, they could still be discarded again before the tracee reenters userspace, but that's no different from what happens in a real syscall.

So I think my overall argument would be:

ptrace should be as orthogonal as possible to SVE discard.

Currently ptrace neither assumes that SVE discard will happen or that it won't: it just does what the tracer asks for and tries to be safe with either and doesn't try to hide the effects from the tracer or tracee.

I worry that introducing more interdependencies between ptrace and the fpsimd.c code will complicate maintenance rather than making it easier.

Does that may my position clearer?

If we go with this, I should add a note to the documentation explaining how NT_ARM_SVE writes interact with ptrace syscall traps.

The alternative would be to forcibly discard SVE in syscall_trace_enter(), but this doesn't seem to simplify the NT_ARM_SVE implementation at all -- that code needs to work for all types of ptrace-stop, not just syscall traps: other that syscall traps, SVE is potentially live for the tracee and must not be discarded. So I'm still not clear on what the gain is.

Cheers
---Dave

#64 lore raw

PATCH v3 20/28 arm64/sve: Add prctl controls for userspace vector length management

In reply to Dave Martin

This patch adds two arm64-specific prctls, to permit userspace to control its vector length:

* PR_SVE_SET_VL: set the thread's SVE vector length and vector length inheritance mode.

* PR_SVE_GET_VL: get the same information.

Although these calls shadow instruction set features in the SVE architecture, these prctls provide additional control: the vector length inheritance mode is Linux-specific and nothing to do with the architecture, and the architecture does not permit EL0 to set its own vector length directly. Both can be used in portable tools without requiring the use of SVE instructions.

---

Dropped Alex Bennée's Reviewed-by, since there are non-trivial changes since v2.

Changes since v2
----------------

Bug fixes:

* Remove preempt_disable() from sve_set_current_vl(), since it's
(a) wrong, and (b) moved to sve_set_vector_length().

This was a legacy from before migration to allowing kernel_neon_begin() in softirq.

ABI changes:

* Changed return value of PR_SVE_SET_VL to encode the vector length deferred for the next exec, when PR_SVE_SET_VL_ONEXEC is passed.

This allows a caller to probe for supported VLs without changing the current VL.

Without this change, the return value is not very informative in this case, since the current VL doesn't change.

Without PR_SVE_SET_VL_ONEXEC, the new current VL is returned, as in v2.

---
 arch/arm64/include/asm/fpsimd.h    | 14 +++++++++++
 arch/arm64/include/asm/processor.h |  4 +++
 arch/arm64/kernel/fpsimd.c         | 50 ++++++++++++++++++++++++++++++++++++++
 include/uapi/linux/prctl.h         |  4 +++
 kernel/sys.c                       | 12 +++++++++
 5 files changed, 84 insertions(+)
arch/arm64/include/asm/fpsimd.h +14 -0
index ee6db38..3cfdfbe 100644
@@ -17,6 +17,7 @@
 #define __ASM_FP_H
 
 #include <asm/ptrace.h>
+#include <asm/errno.h>
 
 #ifndef __ASSEMBLY__
 
@@ -99,6 +100,9 @@ extern void sve_sync_from_fpsimd_zeropad(struct task_struct *task);
 extern int sve_set_vector_length(struct task_struct *task,
 				 unsigned long vl, unsigned long flags);
 
+extern int sve_set_current_vl(unsigned long arg);
+extern int sve_get_current_vl(void);
+
 /*
  * Probing and setup functions.
  * Calls to these functions must be serialised with one another.
@@ -116,6 +120,16 @@ static void __maybe_unused sve_sync_to_fpsimd(struct task_struct *task) { }
 static void __maybe_unused sve_sync_from_fpsimd_zeropad(
 	struct task_struct *task) { }
 
+static int __maybe_unused sve_set_current_vl(unsigned long arg)
+{
+	return -EINVAL;
+}
+
+static int __maybe_unused sve_get_current_vl(void)
+{
+	return -EINVAL;
+}
+
 static void __maybe_unused sve_init_vq_map(void) { }
 static void __maybe_unused sve_update_vq_map(void) { }
 static int __maybe_unused sve_verify_vq_map(void) { return 0; }
arch/arm64/include/asm/processor.h +4 -0
index 3faceac..df66452 100644
@@ -197,4 +197,8 @@ static inline void spin_lock_prefetch(const void *ptr)
 int cpu_enable_pan(void *__unused);
 int cpu_enable_cache_maint_trap(void *__unused);
 
+/* Userspace interface for PR_SVE_{SET,GET}_VL prctl()s: */
+#define SVE_SET_VL(arg)	sve_set_current_vl(arg)
+#define SVE_GET_VL()	sve_get_current_vl()
+
 #endif /* __ASM_PROCESSOR_H */
arch/arm64/kernel/fpsimd.c +50 -0

62 lines not on this page · raw message

include/uapi/linux/prctl.h +4 -0
index 1b64901..1ef9370 100644
@@ -198,7 +198,11 @@ struct prctl_mm_map {
 # define PR_CAP_AMBIENT_CLEAR_ALL	4
 
 /* arm64 Scalable Vector Extension controls */
+/* Flag values must be kept in sync with ptrace NT_ARM_SVE interface */
+#define PR_SVE_SET_VL			48	/* set task vector length */
 # define PR_SVE_SET_VL_ONEXEC		(1 << 18) /* defer effect until exec */
+#define PR_SVE_GET_VL			49	/* get task vector length */
+/* Bits common to PR_SVE_SET_VL and PR_SVE_GET_VL */
 # define PR_SVE_VL_LEN_MASK		0xffff
 # define PR_SVE_VL_INHERIT		(1 << 17) /* inherit across exec */
 
kernel/sys.c +12 -0
index 9aebc29..c541916 100644
@@ -110,6 +110,12 @@
 #ifndef SET_FP_MODE
 # define SET_FP_MODE(a,b)	(-EINVAL)
 #endif
+#ifndef SVE_SET_VL
+# define SVE_SET_VL(a)		(-EINVAL)
+#endif
+#ifndef SVE_GET_VL
+# define SVE_GET_VL()		(-EINVAL)
+#endif
 
 /*
  * this is where the system-wide overflow UID and GID are defined, for
@@ -2385,6 +2391,12 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 	case PR_GET_FP_MODE:
 		error = GET_FP_MODE(me);
 		break;
+	case PR_SVE_SET_VL:
+		error = SVE_SET_VL(arg2);
+		break;
+	case PR_SVE_GET_VL:
+		error = SVE_GET_VL();
+		break;
 	default:
 		error = -EINVAL;
 		break;
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 20/28
#65 lore raw

Re: [PATCH v3 20/28] arm64/sve: Add prctl controls for userspace vector length management

Quoted 15 lines · Dave P Martin

This patch adds two arm64-specific prctls, to permit userspace to control its vector length:

* PR_SVE_SET_VL: set the thread's SVE vector length and vector length inheritance mode.

* PR_SVE_GET_VL: get the same information.

Although these calls shadow instruction set features in the SVE architecture, these prctls provide additional control: the vector length inheritance mode is Linux-specific and nothing to do with the architecture, and the architecture does not permit EL0 to set its own vector length directly. Both can be used in portable tools without requiring the use of SVE instructions.

Quoted 2 lines
#66 lore raw

PATCH v3 21/28 arm64/sve: Add sysctl to set the default vector length for new processes

In reply to Dave Martin

Because of the effect of SVE on the size of the signal frame, the default vector length used for new processes involves a tradeoff between performance of SVE-enabled software on the one hand, and reliability of non-SVE-aware software on the other hand.

For this reason, the best choice depends on the repertoire of userspace software in use and is thus best left up to distro maintainers, sysadmins and developers.

If CONFIG_SYSCTL is enabled, this patch exposes the default vector length in /proc/sys/abi/sve_default_vector_length, where boot scripts or the adventurous can poke it.

In common with other arm64 ABI sysctls, this control is currently
global: setting it requires CAP_SYS_ADMIN in the root user namespace, but the value set is effective for subsequent execs in all namespaces. The control only affects _new_ processes, however:
changing it does not affect the vector length of any existing process.

The intended usage model is that if userspace is known to be fully SVE-tolerant (or a developer is curious to find out) then init scripts can crank this up during startup.

---
 arch/arm64/kernel/fpsimd.c | 62 +++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 61 insertions(+), 1 deletion(-)
arch/arm64/kernel/fpsimd.c +61 -1
index 2c23e4a..a9cb794 100644
@@ -35,6 +35,7 @@
 #include <linux/sched/signal.h>
 #include <linux/signal.h>
 #include <linux/slab.h>
+#include <linux/sysctl.h>
 
 #include <asm/fpsimd.h>
 #include <asm/cputype.h>
@@ -345,6 +346,65 @@ static unsigned int find_supported_vector_length(unsigned int vl)
 	return sve_vl_from_vq(bit_to_vq(bit));
 }
 
+#ifdef CONFIG_SYSCTL
+
+static int sve_proc_do_default_vl(struct ctl_table *table, int write,
+				  void __user *buffer, size_t *lenp,
+				  loff_t *ppos)
+{
+	int ret;
+	int vl = sve_default_vl;
+	struct ctl_table tmp_table = {
+		.data = &vl,
+		.maxlen = sizeof(vl),
+	};
+
+	ret = proc_dointvec(&tmp_table, write, buffer, lenp, ppos);
+	if (ret || !write)
+		return ret;
+
+	/* Writing -1 has the special meaning "set to max": */
+	if (vl == -1) {
+		/* Fail safe if sve_max_vl wasn't initialised */
+		if (WARN_ON(!sve_vl_valid(sve_max_vl)))
+			vl = SVE_VL_MIN;
+		else
+			vl = sve_max_vl;
+
+		goto chosen;
+	}
+
+	if (!sve_vl_valid(vl))
+		return -EINVAL;
+
+	vl = find_supported_vector_length(vl);
+chosen:
+	sve_default_vl = vl;
+	return 0;
+}
+
+static struct ctl_table sve_default_vl_table[] = {
+	{
+		.procname	= "sve_default_vector_length",
+		.mode		= 0644,
+		.proc_handler	= sve_proc_do_default_vl,
+	},
+	{ }
+};
+
+static int __init sve_sysctl_init(void)
+{
+	if (system_supports_sve())
+		if (!register_sysctl("abi", sve_default_vl_table))
+			return -EINVAL;
+
+	return 0;
+}
+
+#else /* ! CONFIG_SYSCTL */
+static int __init sve_sysctl_init(void) { return 0; }
+#endif /* ! CONFIG_SYSCTL */
+
 #define ZREG(sve_state, vq, n) ((char *)(sve_state) +		\
 	(SVE_SIG_ZREG_OFFSET(vq, n) - SVE_SIG_REGS_OFFSET))
 
@@ -1232,6 +1292,6 @@ static int __init fpsimd_init(void)
 	if (!(elf_hwcap & HWCAP_ASIMD))
 		pr_notice("Advanced SIMD is not implemented\n");
 
-	return 0;
+	return sve_sysctl_init();
 }
 core_initcall(fpsimd_init);
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
maintainer Reviewed-by on v3 21/28
#67 lore raw

Re: [PATCH v3 21/28] arm64/sve: Add sysctl to set the default vector length for new processes

Quoted 20 lines · Dave P Martin

Because of the effect of SVE on the size of the signal frame, the default vector length used for new processes involves a tradeoff between performance of SVE-enabled software on the one hand, and reliability of non-SVE-aware software on the other hand.

For this reason, the best choice depends on the repertoire of userspace software in use and is thus best left up to distro maintainers, sysadmins and developers.

If CONFIG_SYSCTL is enabled, this patch exposes the default vector length in /proc/sys/abi/sve_default_vector_length, where boot scripts or the adventurous can poke it.

In common with other arm64 ABI sysctls, this control is currently
global: setting it requires CAP_SYS_ADMIN in the root user namespace, but the value set is effective for subsequent execs in all namespaces. The control only affects _new_ processes, however:
changing it does not affect the vector length of any existing process.

Quoted 6 lines

The intended usage model is that if userspace is known to be fully SVE-tolerant (or a developer is curious to find out) then init scripts can crank this up during startup.

#68 lore raw

PATCH v3 22/28 arm64/sve: KVM: Prevent guests from using SVE

In reply to Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

---
 arch/arm/include/asm/kvm_host.h   |  3 +++
 arch/arm64/include/asm/fpsimd.h   |  1 +
 arch/arm64/include/asm/kvm_arm.h  |  4 +++-
 arch/arm64/include/asm/kvm_host.h | 11 +++++++++++
 arch/arm64/kernel/fpsimd.c        | 31 +++++++++++++++++++++++++++++--
 arch/arm64/kvm/hyp/switch.c       |  6 +++---
 virt/kvm/arm/arm.c                |  3 +++
 7 files changed, 53 insertions(+), 6 deletions(-)
arch/arm/include/asm/kvm_host.h +3 -0
index 4a879f6..242151e 100644
@@ -293,4 +293,7 @@ int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
 int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
 			       struct kvm_device_attr *attr);
 
+/* All host FP/SIMD state is restored on guest exit, so nothing to save: */
+static inline void kvm_fpsimd_flush_cpu_state(void) {}
+
 #endif /* __ARM_KVM_HOST_H__ */
arch/arm64/include/asm/fpsimd.h +1 -0
index 3cfdfbe..10b2824 100644
@@ -75,6 +75,7 @@ extern void fpsimd_restore_current_state(void);
 extern void fpsimd_update_current_state(struct fpsimd_state *state);
 
 extern void fpsimd_flush_task_state(struct task_struct *target);
+extern void sve_flush_cpu_state(void);
 
 /* Maximum VL that SVE VL-agnostic software can transparently support */
 #define SVE_VL_ARCH_MAX 0x100
arch/arm64/include/asm/kvm_arm.h +3 -1
index dbf0537..7f069ff 100644
@@ -186,7 +186,8 @@
 #define CPTR_EL2_TTA	(1 << 20)
 #define CPTR_EL2_TFP	(1 << CPTR_EL2_TFP_SHIFT)
 #define CPTR_EL2_TZ	(1 << 8)
-#define CPTR_EL2_DEFAULT	0x000033ff
+#define CPTR_EL2_RES1	0x000032ff /* known RES1 bits in CPTR_EL2 */
+#define CPTR_EL2_DEFAULT	CPTR_EL2_RES1
 
 /* Hyp Debug Configuration Register bits */
 #define MDCR_EL2_TPMS		(1 << 14)
@@ -237,5 +238,6 @@
 
 #define CPACR_EL1_FPEN		(3 << 20)
 #define CPACR_EL1_TTA		(1 << 28)
+#define CPACR_EL1_DEFAULT	(CPACR_EL1_FPEN | CPACR_EL1_ZEN_EL1EN)
 
 #endif /* __ARM64_KVM_ARM_H__ */
arch/arm64/include/asm/kvm_host.h +11 -0
index e923b58..674912d 100644
@@ -25,6 +25,7 @@
 #include <linux/types.h>
 #include <linux/kvm_types.h>
 #include <asm/cpufeature.h>
+#include <asm/fpsimd.h>
 #include <asm/kvm.h>
 #include <asm/kvm_asm.h>
 #include <asm/kvm_mmio.h>
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)
 		  "PARange is %d bits, unsupported configuration!", parange);
 }
 
+/*
+ * All host FP/SIMD state is restored on guest exit, so nothing needs
+ * doing here except in the SVE case:
+*/
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();
+}
+
 #endif /* __ARM64_KVM_HOST_H__ */
arch/arm64/kernel/fpsimd.c +29 -2
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)
 	t->thread.fpsimd_state.cpu = NR_CPUS;
 }
 
+static inline void fpsimd_flush_cpu_state(void)
+{
+	__this_cpu_write(fpsimd_last_state, NULL);
+}
+
+/*
+ * Invalidate any task SVE state currently held in this CPU's regs.
+ *
+ * This is used to prevent the kernel from trying to reuse SVE register data
+ * that is detroyed by KVM guest enter/exit.  This function should go away when
+ * KVM SVE support is implemented.  Don't use it for anything else.
+ */
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */
+
 #ifdef CONFIG_KERNEL_MODE_NEON
 
 DEFINE_PER_CPU(bool, kernel_neon_busy);
@@ -1113,7 +1140,7 @@ void kernel_neon_begin(void)
 	}
 
 	/* Invalidate any task state remaining in the fpsimd regs: */
-	__this_cpu_write(fpsimd_last_state, NULL);
+	fpsimd_flush_cpu_state();
 
 	preempt_disable();
 
@@ -1234,7 +1261,7 @@ static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
 	case CPU_PM_ENTER:
 		if (current->mm)
 			task_fpsimd_save();
-		this_cpu_write(fpsimd_last_state, NULL);
+		fpsimd_flush_cpu_state();
 		break;
 	case CPU_PM_EXIT:
 		if (current->mm)
arch/arm64/kvm/hyp/switch.c +3 -3
index 35a90b8..951f3eb 100644
@@ -48,7 +48,7 @@ static void __hyp_text __activate_traps_vhe(void)
 
 	val = read_sysreg(cpacr_el1);
 	val |= CPACR_EL1_TTA;
-	val &= ~CPACR_EL1_FPEN;
+	val &= ~(CPACR_EL1_FPEN | CPACR_EL1_ZEN);
 	write_sysreg(val, cpacr_el1);
 
 	write_sysreg(__kvm_hyp_vector, vbar_el1);
@@ -59,7 +59,7 @@ static void __hyp_text __activate_traps_nvhe(void)
 	u64 val;
 
 	val = CPTR_EL2_DEFAULT;
-	val |= CPTR_EL2_TTA | CPTR_EL2_TFP;
+	val |= CPTR_EL2_TTA | CPTR_EL2_TFP | CPTR_EL2_TZ;
 	write_sysreg(val, cptr_el2);
 }
 
@@ -117,7 +117,7 @@ static void __hyp_text __deactivate_traps_vhe(void)
 
 	write_sysreg(mdcr_el2, mdcr_el2);
 	write_sysreg(HCR_HOST_VHE_FLAGS, hcr_el2);
-	write_sysreg(CPACR_EL1_FPEN, cpacr_el1);
+	write_sysreg(CPACR_EL1_DEFAULT, cpacr_el1);
 	write_sysreg(vectors, vbar_el1);
 }
 
virt/kvm/arm/arm.c +3 -0
index b9f68e4..4d3cf9c 100644
@@ -652,6 +652,9 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
 		 */
 		preempt_disable();
 
+		/* Flush FP/SIMD state that can't survive guest entry/exit */
+		kvm_fpsimd_flush_cpu_state();
+
 		kvm_pmu_flush_hwstate(vcpu);
 
 		kvm_timer_flush_hwstate(vcpu);
Signature · 1 line
2.1.4
#69 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

[+ Christoffer]

Quoted 90 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

---
 arch/arm/include/asm/kvm_host.h   |  3 +++
 arch/arm64/include/asm/fpsimd.h   |  1 +
 arch/arm64/include/asm/kvm_arm.h  |  4 +++-
 arch/arm64/include/asm/kvm_host.h | 11 +++++++++++
 arch/arm64/kernel/fpsimd.c        | 31 +++++++++++++++++++++++++++++--
 arch/arm64/kvm/hyp/switch.c       |  6 +++---
 virt/kvm/arm/arm.c                |  3 +++
 7 files changed, 53 insertions(+), 6 deletions(-)
arch/arm/include/asm/kvm_host.h +3 -0
index 4a879f6..242151e 100644
@@ -293,4 +293,7 @@ int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
 int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
 			       struct kvm_device_attr *attr);
 
+/* All host FP/SIMD state is restored on guest exit, so nothing to save: */
+static inline void kvm_fpsimd_flush_cpu_state(void) {}
+
 #endif /* __ARM_KVM_HOST_H__ */
arch/arm64/include/asm/fpsimd.h +1 -0
index 3cfdfbe..10b2824 100644
@@ -75,6 +75,7 @@ extern void fpsimd_restore_current_state(void);
 extern void fpsimd_update_current_state(struct fpsimd_state *state);
 
 extern void fpsimd_flush_task_state(struct task_struct *target);
+extern void sve_flush_cpu_state(void);
 
 /* Maximum VL that SVE VL-agnostic software can transparently support */
 #define SVE_VL_ARCH_MAX 0x100
arch/arm64/include/asm/kvm_arm.h +3 -1
index dbf0537..7f069ff 100644
@@ -186,7 +186,8 @@
 #define CPTR_EL2_TTA	(1 << 20)
 #define CPTR_EL2_TFP	(1 << CPTR_EL2_TFP_SHIFT)
 #define CPTR_EL2_TZ	(1 << 8)
-#define CPTR_EL2_DEFAULT	0x000033ff
+#define CPTR_EL2_RES1	0x000032ff /* known RES1 bits in CPTR_EL2 */
+#define CPTR_EL2_DEFAULT	CPTR_EL2_RES1
 
 /* Hyp Debug Configuration Register bits */
 #define MDCR_EL2_TPMS		(1 << 14)
@@ -237,5 +238,6 @@
 
 #define CPACR_EL1_FPEN		(3 << 20)
 #define CPACR_EL1_TTA		(1 << 28)
+#define CPACR_EL1_DEFAULT	(CPACR_EL1_FPEN | CPACR_EL1_ZEN_EL1EN)
 
 #endif /* __ARM64_KVM_ARM_H__ */
arch/arm64/include/asm/kvm_host.h +1 -0
index e923b58..674912d 100644
@@ -25,6 +25,7 @@
 #include <linux/types.h>
 #include <linux/kvm_types.h>
 #include <asm/cpufeature.h>
+#include <asm/fpsimd.h>
 #include <asm/kvm.h>
 #include <asm/kvm_asm.h>
 #include <asm/kvm_mmio.h>
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)
 		  "PARange is %d bits, unsupported configuration!", parange);

arch/arm64/include/asm/kvm_host.h static inline void __cpu_init_stage2(void) · line 395

Quoted 10 lines
arch/arm64/include/asm/kvm_host.h +8 -0
 }
 
+/*
+ * All host FP/SIMD state is restored on guest exit, so nothing needs
+ * doing here except in the SVE case:
+*/
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();

Hmmm. How does this work if...

Quoted 27 lines
arch/arm64/include/asm/kvm_host.h +2 -0
+}
+
 #endif /* __ARM64_KVM_HOST_H__ */
arch/arm64/kernel/fpsimd.c +16 -0
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)
 	t->thread.fpsimd_state.cpu = NR_CPUS;
 }
 
+static inline void fpsimd_flush_cpu_state(void)
+{
+	__this_cpu_write(fpsimd_last_state, NULL);
+}
+
+/*
+ * Invalidate any task SVE state currently held in this CPU's regs.
+ *
+ * This is used to prevent the kernel from trying to reuse SVE register data
+ * that is detroyed by KVM guest enter/exit.  This function should go away when
+ * KVM SVE support is implemented.  Don't use it for anything else.
+ */
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);

arch/arm64/kernel/fpsimd.c void fpsimd_flush_task_state(struct task_struct *t) · line 1101

Quoted 10 lines
arch/arm64/kernel/fpsimd.c +10 -0
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */

... CONFIG_ARM64_SVE is not set? Fixing this should just be a matter of moving the #ifdef/#endif inside the function...

Quoted 59 lines
arch/arm64/kernel/fpsimd.c +3 -2
+
 #ifdef CONFIG_KERNEL_MODE_NEON
 
 DEFINE_PER_CPU(bool, kernel_neon_busy);
@@ -1113,7 +1140,7 @@ void kernel_neon_begin(void)
 	}
 
 	/* Invalidate any task state remaining in the fpsimd regs: */
-	__this_cpu_write(fpsimd_last_state, NULL);
+	fpsimd_flush_cpu_state();
 
 	preempt_disable();
 
@@ -1234,7 +1261,7 @@ static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
 	case CPU_PM_ENTER:
 		if (current->mm)
 			task_fpsimd_save();
-		this_cpu_write(fpsimd_last_state, NULL);
+		fpsimd_flush_cpu_state();
 		break;
 	case CPU_PM_EXIT:
 		if (current->mm)
arch/arm64/kvm/hyp/switch.c +3 -3
index 35a90b8..951f3eb 100644
@@ -48,7 +48,7 @@ static void __hyp_text __activate_traps_vhe(void)
 
 	val = read_sysreg(cpacr_el1);
 	val |= CPACR_EL1_TTA;
-	val &= ~CPACR_EL1_FPEN;
+	val &= ~(CPACR_EL1_FPEN | CPACR_EL1_ZEN);
 	write_sysreg(val, cpacr_el1);
 
 	write_sysreg(__kvm_hyp_vector, vbar_el1);
@@ -59,7 +59,7 @@ static void __hyp_text __activate_traps_nvhe(void)
 	u64 val;
 
 	val = CPTR_EL2_DEFAULT;
-	val |= CPTR_EL2_TTA | CPTR_EL2_TFP;
+	val |= CPTR_EL2_TTA | CPTR_EL2_TFP | CPTR_EL2_TZ;
 	write_sysreg(val, cptr_el2);
 }
 
@@ -117,7 +117,7 @@ static void __hyp_text __deactivate_traps_vhe(void)
 
 	write_sysreg(mdcr_el2, mdcr_el2);
 	write_sysreg(HCR_HOST_VHE_FLAGS, hcr_el2);
-	write_sysreg(CPACR_EL1_FPEN, cpacr_el1);
+	write_sysreg(CPACR_EL1_DEFAULT, cpacr_el1);
 	write_sysreg(vectors, vbar_el1);
 }
 
virt/kvm/arm/arm.c +0 -0
index b9f68e4..4d3cf9c 100644

virt/kvm/arm/arm.c int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run) · line 660

Quoted 9 lines
virt/kvm/arm/arm.c +3 -0
@@ -652,6 +652,9 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
 		 */
 		preempt_disable();
 
+		/* Flush FP/SIMD state that can't survive guest entry/exit */
+		kvm_fpsimd_flush_cpu_state();
+
 		kvm_pmu_flush_hwstate(vcpu);
 
 		kvm_timer_flush_hwstate(vcpu);

Thanks,

	M.
Signature · 1 line
Jazz is not dead. It just smells funny...
#70 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 25 lines · Marc Zyngier

[+ Christoffer]

Quoted 22 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

---

[...]

Quoted 4 lines
Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +0 -0
index e923b58..674912d 100644

[...]

Quoted 1 line
Quoted 1 line
arch/arm64/include/asm/kvm_host.h +0 -0
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)

[...]

Quoted 6 lines

arch/arm64/include/asm/kvm_host.h static inline void __cpu_init_stage2(void) · line 395

Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +4 -0
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();

Hmmm. How does this work if...

!IS_ENABLED(CONFIG_ARM64_SVE) implies !system_supports_sve(), so if CONFIG_ARM64_SVE is not set, the call is optimised away.

[...]

Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/fpsimd.c +0 -0
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)

[...]

Quoted 9 lines
Quoted 9 lines
arch/arm64/kernel/fpsimd.c +9 -0
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
Quoted 8 lines

arch/arm64/kernel/fpsimd.c void fpsimd_flush_task_state(struct task_struct *t) · line 1101

Quoted 5 lines
arch/arm64/kernel/fpsimd.c +5 -0
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */

... CONFIG_ARM64_SVE is not set? Fixing this should just be a matter of moving the #ifdef/#endif inside the function...

Because sve_flush_cpu_state() is not in the same compilation unit it can't be static, and that means the compiler won't remove it automatically if it's unused -- hence the #ifdef.

Because the call site is optimised away, there is no link failure.

Don't we rely on this sort of thing all over the place?

Cheers
---Dave

#71 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 78 lines · Dave Martin
Quoted 25 lines · Marc Zyngier

[+ Christoffer]

Quoted 22 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

---

[...]

Quoted 4 lines
Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +0 -0
index e923b58..674912d 100644

[...]

Quoted 1 line
Quoted 1 line
arch/arm64/include/asm/kvm_host.h +0 -0
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)

[...]

Quoted 6 lines

arch/arm64/include/asm/kvm_host.h static inline void __cpu_init_stage2(void) · line 395

Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +4 -0
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();

Hmmm. How does this work if...

!IS_ENABLED(CONFIG_ARM64_SVE) implies !system_supports_sve(), so if CONFIG_ARM64_SVE is not set, the call is optimised away.

[...]

Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/fpsimd.c +0 -0
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)

[...]

Quoted 9 lines
Quoted 9 lines
arch/arm64/kernel/fpsimd.c +9 -0
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
Quoted 8 lines

arch/arm64/kernel/fpsimd.c void fpsimd_flush_task_state(struct task_struct *t) · line 1101

Quoted 5 lines
arch/arm64/kernel/fpsimd.c +5 -0
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */

... CONFIG_ARM64_SVE is not set? Fixing this should just be a matter of moving the #ifdef/#endif inside the function...

Quoted 7 lines

Because sve_flush_cpu_state() is not in the same compilation unit it can't be static, and that means the compiler won't remove it automatically if it's unused -- hence the #ifdef.

Because the call site is optimised away, there is no link failure.

Don't we rely on this sort of thing all over the place?

Dunno. It just feels weird. But if you are sure that it won't break, fine by me. I guess we'll find out pretty quickly how this fares, specially with older toolchains.

	M.
Signature · 1 line
Jazz is not dead. It just smells funny...
#72 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 83 lines · Marc Zyngier
Quoted 82 lines · Dave Martin
Quoted 25 lines · Marc Zyngier

[+ Christoffer]

Quoted 22 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

---

[...]

Quoted 4 lines
Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +0 -0
index e923b58..674912d 100644

[...]

Quoted 1 line
Quoted 1 line
arch/arm64/include/asm/kvm_host.h +0 -0
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)

[...]

Quoted 6 lines

arch/arm64/include/asm/kvm_host.h static inline void __cpu_init_stage2(void) · line 395

Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +4 -0
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();

Hmmm. How does this work if...

!IS_ENABLED(CONFIG_ARM64_SVE) implies !system_supports_sve(), so if CONFIG_ARM64_SVE is not set, the call is optimised away.

[...]

Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/fpsimd.c +0 -0
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)

[...]

Quoted 9 lines
Quoted 9 lines
arch/arm64/kernel/fpsimd.c +9 -0
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
Quoted 8 lines

arch/arm64/kernel/fpsimd.c void fpsimd_flush_task_state(struct task_struct *t) · line 1101

Quoted 5 lines
arch/arm64/kernel/fpsimd.c +5 -0
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */

... CONFIG_ARM64_SVE is not set? Fixing this should just be a matter of moving the #ifdef/#endif inside the function...

Because sve_flush_cpu_state() is not in the same compilation unit it can't be static, and that means the compiler won't remove it automatically if it's unused -- hence the #ifdef.

Quoted 6 lines
Quoted 3 lines

Because the call site is optimised away, there is no link failure.

Don't we rely on this sort of thing all over the place?

Dunno. It just feels weird. But if you are sure that it won't break, fine by me. I guess we'll find out pretty quickly how this fares, specially with older toolchains.

I thought this was why the kernel doesn't support building with -O0. There are many instances of this in the series, not just here.

Let me know if you feel this isn't good enough though.

Do you have any other comments on this patch?

Cheers
---Dave

Acked-by
#73 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 87 lines · Dave Martin
Quoted 86 lines · Marc Zyngier
Quoted 85 lines · Dave Martin
Quoted 25 lines · Marc Zyngier

[+ Christoffer]

Quoted 22 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

---

[...]

Quoted 4 lines
Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +0 -0
index e923b58..674912d 100644

[...]

Quoted 1 line
Quoted 1 line
arch/arm64/include/asm/kvm_host.h +0 -0
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)

[...]

Quoted 6 lines

arch/arm64/include/asm/kvm_host.h static inline void __cpu_init_stage2(void) · line 395

Quoted 4 lines
arch/arm64/include/asm/kvm_host.h +4 -0
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();

Hmmm. How does this work if...

!IS_ENABLED(CONFIG_ARM64_SVE) implies !system_supports_sve(), so if CONFIG_ARM64_SVE is not set, the call is optimised away.

[...]

Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/fpsimd.c +0 -0
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)

[...]

Quoted 9 lines
Quoted 9 lines
arch/arm64/kernel/fpsimd.c +9 -0
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
Quoted 8 lines

arch/arm64/kernel/fpsimd.c void fpsimd_flush_task_state(struct task_struct *t) · line 1101

Quoted 5 lines
arch/arm64/kernel/fpsimd.c +5 -0
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */

... CONFIG_ARM64_SVE is not set? Fixing this should just be a matter of moving the #ifdef/#endif inside the function...

Because sve_flush_cpu_state() is not in the same compilation unit it can't be static, and that means the compiler won't remove it automatically if it's unused -- hence the #ifdef.

Because the call site is optimised away, there is no link failure.

Don't we rely on this sort of thing all over the place?

Quoted 8 lines
Quoted 3 lines

Dunno. It just feels weird. But if you are sure that it won't break, fine by me. I guess we'll find out pretty quickly how this fares, specially with older toolchains.

I thought this was why the kernel doesn't support building with -O0. There are many instances of this in the series, not just here.

Let me know if you feel this isn't good enough though.

That's OK to me. As I said, we'll find out pretty quickly if anything breaks unexpectedly.

Quoted 1 line

Do you have any other comments on this patch?

None. You can add my:

	M.
Signature · 1 line
Jazz is not dead. It just smells funny...
#74 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 7 lines · Marc Zyngier
Quoted 6 lines · Dave Martin
Quoted 5 lines · Marc Zyngier
Quoted 4 lines · Dave Martin
Quoted 3 lines · Marc Zyngier

[+ Christoffer]

On 10/10/17 19:38, Dave Martin wrote:

[...]

Quoted 44 lines
Quoted 44 lines
Quoted 43 lines
Quoted 33 lines
Quoted 1 line

Hmmm. How does this work if...

!IS_ENABLED(CONFIG_ARM64_SVE) implies !system_supports_sve(), so if CONFIG_ARM64_SVE is not set, the call is optimised away.

[...]

Quoted 5 lines
Quoted 5 lines
arch/arm64/kernel/fpsimd.c +0 -0
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)

[...]

Quoted 9 lines
Quoted 9 lines
arch/arm64/kernel/fpsimd.c +9 -0
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
Quoted 8 lines

arch/arm64/kernel/fpsimd.c void fpsimd_flush_task_state(struct task_struct *t) · line 1101

Quoted 5 lines
arch/arm64/kernel/fpsimd.c +5 -0
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */

... CONFIG_ARM64_SVE is not set? Fixing this should just be a matter of moving the #ifdef/#endif inside the function...

Quoted 7 lines

Because sve_flush_cpu_state() is not in the same compilation unit it can't be static, and that means the compiler won't remove it automatically if it's unused -- hence the #ifdef.

Because the call site is optimised away, there is no link failure.

Don't we rely on this sort of thing all over the place?

Dunno. It just feels weird. But if you are sure that it won't break, fine by me. I guess we'll find out pretty quickly how this fares, specially with older toolchains.

Quoted 7 lines
Quoted 4 lines

I thought this was why the kernel doesn't support building with -O0. There are many instances of this in the series, not just here.

Let me know if you feel this isn't good enough though.

That's OK to me. As I said, we'll find out pretty quickly if anything breaks unexpectedly.

Yup

Quoted 5 lines
Quoted 2 lines

Do you have any other comments on this patch?

None. You can add my:

OK, thanks for the input.

Cheers
---Dave

maintainer Acked-by on v3 22/28
#75 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

In reply to Dave Martin
Quoted 17 lines · Dave P Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

Quoted 4 lines
#76 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

In reply to Dave Martin
Quoted 11 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

I don't understand this paragraph, beginning from ", so this...".

Quoted 1 line

From reading the code, what I think is the reason for having to flush

the SVE state (and mark the host state invalid) is that even though we disallow SVE usage in the guest, the guest can use the normal FP state, and while we always fully preserve the host state, this could still corrupt some additional SVE state not properly preserved for the host. Is that correct?

Quoted 5 lines

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

Otherwise the patch itself looks good to me.

Thanks,
-Christoffer

Quoted 195 lines
---
 arch/arm/include/asm/kvm_host.h   |  3 +++
 arch/arm64/include/asm/fpsimd.h   |  1 +
 arch/arm64/include/asm/kvm_arm.h  |  4 +++-
 arch/arm64/include/asm/kvm_host.h | 11 +++++++++++
 arch/arm64/kernel/fpsimd.c        | 31 +++++++++++++++++++++++++++++--
 arch/arm64/kvm/hyp/switch.c       |  6 +++---
 virt/kvm/arm/arm.c                |  3 +++
 7 files changed, 53 insertions(+), 6 deletions(-)
arch/arm/include/asm/kvm_host.h +3 -0
index 4a879f6..242151e 100644
@@ -293,4 +293,7 @@ int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu,
 int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu,
 			       struct kvm_device_attr *attr);
 
+/* All host FP/SIMD state is restored on guest exit, so nothing to save: */
+static inline void kvm_fpsimd_flush_cpu_state(void) {}
+
 #endif /* __ARM_KVM_HOST_H__ */
arch/arm64/include/asm/fpsimd.h +1 -0
index 3cfdfbe..10b2824 100644
@@ -75,6 +75,7 @@ extern void fpsimd_restore_current_state(void);
 extern void fpsimd_update_current_state(struct fpsimd_state *state);
 
 extern void fpsimd_flush_task_state(struct task_struct *target);
+extern void sve_flush_cpu_state(void);
 
 /* Maximum VL that SVE VL-agnostic software can transparently support */
 #define SVE_VL_ARCH_MAX 0x100
arch/arm64/include/asm/kvm_arm.h +3 -1
index dbf0537..7f069ff 100644
@@ -186,7 +186,8 @@
 #define CPTR_EL2_TTA	(1 << 20)
 #define CPTR_EL2_TFP	(1 << CPTR_EL2_TFP_SHIFT)
 #define CPTR_EL2_TZ	(1 << 8)
-#define CPTR_EL2_DEFAULT	0x000033ff
+#define CPTR_EL2_RES1	0x000032ff /* known RES1 bits in CPTR_EL2 */
+#define CPTR_EL2_DEFAULT	CPTR_EL2_RES1
 
 /* Hyp Debug Configuration Register bits */
 #define MDCR_EL2_TPMS		(1 << 14)
@@ -237,5 +238,6 @@
 
 #define CPACR_EL1_FPEN		(3 << 20)
 #define CPACR_EL1_TTA		(1 << 28)
+#define CPACR_EL1_DEFAULT	(CPACR_EL1_FPEN | CPACR_EL1_ZEN_EL1EN)
 
 #endif /* __ARM64_KVM_ARM_H__ */
arch/arm64/include/asm/kvm_host.h +11 -0
index e923b58..674912d 100644
@@ -25,6 +25,7 @@
 #include <linux/types.h>
 #include <linux/kvm_types.h>
 #include <asm/cpufeature.h>
+#include <asm/fpsimd.h>
 #include <asm/kvm.h>
 #include <asm/kvm_asm.h>
 #include <asm/kvm_mmio.h>
@@ -384,4 +385,14 @@ static inline void __cpu_init_stage2(void)
 		  "PARange is %d bits, unsupported configuration!", parange);
 }
 
+/*
+ * All host FP/SIMD state is restored on guest exit, so nothing needs
+ * doing here except in the SVE case:
+*/
+static inline void kvm_fpsimd_flush_cpu_state(void)
+{
+	if (system_supports_sve())
+		sve_flush_cpu_state();
+}
+
 #endif /* __ARM64_KVM_HOST_H__ */
arch/arm64/kernel/fpsimd.c +29 -2
index a9cb794..6ae3703 100644
@@ -1073,6 +1073,33 @@ void fpsimd_flush_task_state(struct task_struct *t)
 	t->thread.fpsimd_state.cpu = NR_CPUS;
 }
 
+static inline void fpsimd_flush_cpu_state(void)
+{
+	__this_cpu_write(fpsimd_last_state, NULL);
+}
+
+/*
+ * Invalidate any task SVE state currently held in this CPU's regs.
+ *
+ * This is used to prevent the kernel from trying to reuse SVE register data
+ * that is detroyed by KVM guest enter/exit.  This function should go away when
+ * KVM SVE support is implemented.  Don't use it for anything else.
+ */
+#ifdef CONFIG_ARM64_SVE
+void sve_flush_cpu_state(void)
+{
+	struct fpsimd_state *const fpstate = __this_cpu_read(fpsimd_last_state);
+	struct task_struct *tsk;
+
+	if (!fpstate)
+		return;
+
+	tsk = container_of(fpstate, struct task_struct, thread.fpsimd_state);
+	if (test_tsk_thread_flag(tsk, TIF_SVE))
+		fpsimd_flush_cpu_state();
+}
+#endif /* CONFIG_ARM64_SVE */
+
 #ifdef CONFIG_KERNEL_MODE_NEON
 
 DEFINE_PER_CPU(bool, kernel_neon_busy);
@@ -1113,7 +1140,7 @@ void kernel_neon_begin(void)
 	}
 
 	/* Invalidate any task state remaining in the fpsimd regs: */
-	__this_cpu_write(fpsimd_last_state, NULL);
+	fpsimd_flush_cpu_state();
 
 	preempt_disable();
 
@@ -1234,7 +1261,7 @@ static int fpsimd_cpu_pm_notifier(struct notifier_block *self,
 	case CPU_PM_ENTER:
 		if (current->mm)
 			task_fpsimd_save();
-		this_cpu_write(fpsimd_last_state, NULL);
+		fpsimd_flush_cpu_state();
 		break;
 	case CPU_PM_EXIT:
 		if (current->mm)
arch/arm64/kvm/hyp/switch.c +3 -3
index 35a90b8..951f3eb 100644
@@ -48,7 +48,7 @@ static void __hyp_text __activate_traps_vhe(void)
 
 	val = read_sysreg(cpacr_el1);
 	val |= CPACR_EL1_TTA;
-	val &= ~CPACR_EL1_FPEN;
+	val &= ~(CPACR_EL1_FPEN | CPACR_EL1_ZEN);
 	write_sysreg(val, cpacr_el1);
 
 	write_sysreg(__kvm_hyp_vector, vbar_el1);
@@ -59,7 +59,7 @@ static void __hyp_text __activate_traps_nvhe(void)
 	u64 val;
 
 	val = CPTR_EL2_DEFAULT;
-	val |= CPTR_EL2_TTA | CPTR_EL2_TFP;
+	val |= CPTR_EL2_TTA | CPTR_EL2_TFP | CPTR_EL2_TZ;
 	write_sysreg(val, cptr_el2);
 }
 
@@ -117,7 +117,7 @@ static void __hyp_text __deactivate_traps_vhe(void)
 
 	write_sysreg(mdcr_el2, mdcr_el2);
 	write_sysreg(HCR_HOST_VHE_FLAGS, hcr_el2);
-	write_sysreg(CPACR_EL1_FPEN, cpacr_el1);
+	write_sysreg(CPACR_EL1_DEFAULT, cpacr_el1);
 	write_sysreg(vectors, vbar_el1);
 }
 
virt/kvm/arm/arm.c +3 -0
index b9f68e4..4d3cf9c 100644
@@ -652,6 +652,9 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
 		 */
 		preempt_disable();
 
+		/* Flush FP/SIMD state that can't survive guest entry/exit */
+		kvm_fpsimd_flush_cpu_state();
+
 		kvm_pmu_flush_hwstate(vcpu);
 
 		kvm_timer_flush_hwstate(vcpu);
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
#77 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 16 lines · Christoffer Dall
Quoted 11 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

I don't understand this paragraph, beginning from ", so this...".

Quoted 6 lines

From reading the code, what I think is the reason for having to flush the SVE state (and mark the host state invalid) is that even though we disallow SVE usage in the guest, the guest can use the normal FP state, and while we always fully preserve the host state, this could still corrupt some additional SVE state not properly preserved for the host. Is that correct?

Yes, that's right: the guest can't touch the SVE-specific registers Pn/FFR, but FPSIMD accesses to Vn regs cause the high bits of the corresponding SVE Zn registers to be clobbered. In any case, the FPSIMD restore done by KVM after guest exit is sufficient to clobber those bits even if the guest didn't do it.

This is a band-aid for not making the KVM world switch code properly SVE-aware yet.

Does the following wording sound better:

--8<--

On guest exit, high bits of the SVE Zn registers may have been clobbered as a side-effect the execution of FPSIMD instructions in the guest. The existing KVM host FPSIMD restore code is not sufficient to restore these bits, so this patch explicitly marks the CPU as not containing cached vector state for any task, this forcing a reload on the next return to userspace. This is an interim measure, in advance of adding full SVE awareness to KVM.

Because of the duplication of this operation (__this_cpu_write(fpsimd_last_state, NULL)), it is factored out as a new helper fpsimd_flush_cpu_state() to make the purpose clearer.

-->8--

Quoted 7 lines
Quoted 5 lines

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

Otherwise the patch itself looks good to me.

Thanks, let me know about the above wording change though.

---Dave

Reviewed-by
#78 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 45 lines · Dave Martin
Quoted 16 lines · Christoffer Dall
Quoted 11 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

I don't understand this paragraph, beginning from ", so this...".

Quoted 6 lines

From reading the code, what I think is the reason for having to flush the SVE state (and mark the host state invalid) is that even though we disallow SVE usage in the guest, the guest can use the normal FP state, and while we always fully preserve the host state, this could still corrupt some additional SVE state not properly preserved for the host. Is that correct?

Yes, that's right: the guest can't touch the SVE-specific registers Pn/FFR, but FPSIMD accesses to Vn regs cause the high bits of the corresponding SVE Zn registers to be clobbered. In any case, the FPSIMD restore done by KVM after guest exit is sufficient to clobber those bits even if the guest didn't do it.

This is a band-aid for not making the KVM world switch code properly SVE-aware yet.

Does the following wording sound better:

--8<--

On guest exit, high bits of the SVE Zn registers may have been clobbered as a side-effect the execution of FPSIMD instructions in the guest. The existing KVM host FPSIMD restore code is not sufficient to restore these bits, so this patch explicitly marks the CPU as not containing cached vector state for any task, this forcing a reload on the next return to userspace. This is an interim measure, in advance of adding full SVE awareness to KVM.

Quoted 2 lines

Because of the duplication of this operation (__this_cpu_write(fpsimd_last_state, NULL)), it is factored out as

s/it is/is/ (I think)

Quoted 5 lines

a new helper fpsimd_flush_cpu_state() to make the purpose clearer.

-->8--

Quoted 1 line
Quoted 1 line
Quoted 9 lines
Quoted 6 lines
Quoted 4 lines

As a side effect of this refactoring, a this_cpu_write() in fpsimd_cpu_pm_notifier() is changed to __this_cpu_write(). This should be fine, since cpu_pm_enter() is supposed to be called only with interrupts disabled.

Otherwise the patch itself looks good to me.

Thanks, let me know about the above wording change though.

Yes, the wording is good and helps a lot. Thanks for writing that.

#79 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 46 lines · Christoffer Dall
Quoted 45 lines · Dave Martin
Quoted 16 lines · Christoffer Dall
Quoted 11 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

I don't understand this paragraph, beginning from ", so this...".

Quoted 6 lines

From reading the code, what I think is the reason for having to flush the SVE state (and mark the host state invalid) is that even though we disallow SVE usage in the guest, the guest can use the normal FP state, and while we always fully preserve the host state, this could still corrupt some additional SVE state not properly preserved for the host. Is that correct?

Yes, that's right: the guest can't touch the SVE-specific registers Pn/FFR, but FPSIMD accesses to Vn regs cause the high bits of the corresponding SVE Zn registers to be clobbered. In any case, the FPSIMD restore done by KVM after guest exit is sufficient to clobber those bits even if the guest didn't do it.

This is a band-aid for not making the KVM world switch code properly SVE-aware yet.

Does the following wording sound better:

--8<--

On guest exit, high bits of the SVE Zn registers may have been clobbered as a side-effect the execution of FPSIMD instructions in the guest. The existing KVM host FPSIMD restore code is not sufficient to restore these bits, so this patch explicitly marks the CPU as not containing cached vector state for any task, this forcing a reload on the next return to userspace. This is an interim measure, in advance of adding full SVE awareness to KVM.

Quoted 9 lines
Quoted 2 lines

Because of the duplication of this operation (__this_cpu_write(fpsimd_last_state, NULL)), it is factored out as

s/it is/is/ (I think)

Quoted 1 line

a new helper fpsimd_flush_cpu_state() to make the purpose clearer.

Yes, the wording is good and helps a lot. Thanks for writing that.

I think it "it is" is correct, but it's a pretty ghastly sentence...

I'll split it as:

This marking of cached vector state in the CPU as invalid is done using __this_cpu_write(fpsimd_last_state, NULL) in fpsimd.c. Due to the repeated use of this rather obscure operation, it makes sense to factor it out as a separate helper with a clearer name. This patch factors it out as fpsimd_flush_cpu_state().

Quoted 1 line

I'll assume I can keep keep your Reviewed-by, since this change is just clarification.

But if you're not happy, please shout!

Cheers
---Dave

#80 lore raw

Re: [PATCH v3 22/28] arm64/sve: KVM: Prevent guests from using SVE

Quoted 50 lines · Dave Martin
Quoted 49 lines · Christoffer Dall
Quoted 47 lines · Dave Martin
Quoted 16 lines · Christoffer Dall
Quoted 11 lines · Dave Martin

Until KVM has full SVE support, guests must not be allowed to execute SVE instructions.

This patch enables the necessary traps, and also ensures that the traps are disabled again on exit from the guest so that the host can still use SVE if it wants to.

This patch introduces another instance of __this_cpu_write(fpsimd_last_state, NULL), so this flush operation is abstracted out as a separate helper fpsimd_flush_cpu_state(). Other instances are ported appropriately.

I don't understand this paragraph, beginning from ", so this...".

Quoted 6 lines

From reading the code, what I think is the reason for having to flush the SVE state (and mark the host state invalid) is that even though we disallow SVE usage in the guest, the guest can use the normal FP state, and while we always fully preserve the host state, this could still corrupt some additional SVE state not properly preserved for the host. Is that correct?

Yes, that's right: the guest can't touch the SVE-specific registers Pn/FFR, but FPSIMD accesses to Vn regs cause the high bits of the corresponding SVE Zn registers to be clobbered. In any case, the FPSIMD restore done by KVM after guest exit is sufficient to clobber those bits even if the guest didn't do it.

This is a band-aid for not making the KVM world switch code properly SVE-aware yet.

Does the following wording sound better:

--8<--

On guest exit, high bits of the SVE Zn registers may have been clobbered as a side-effect the execution of FPSIMD instructions in the guest. The existing KVM host FPSIMD restore code is not sufficient to restore these bits, so this patch explicitly marks the CPU as not containing cached vector state for any task, this forcing a reload on the next return to userspace. This is an interim measure, in advance of adding full SVE awareness to KVM.

Because of the duplication of this operation (__this_cpu_write(fpsimd_last_state, NULL)), it is factored out as

Quoted 8 lines
Quoted 6 lines

s/it is/is/ (I think)

Quoted 1 line

a new helper fpsimd_flush_cpu_state() to make the purpose clearer.

Yes, the wording is good and helps a lot. Thanks for writing that.

I think it "it is" is correct, but it's a pretty ghastly sentence...

Ah, I missed the comma, before and read it as __this_cpu_write... is factored... but that doesn't make any sense. Sorry, I was just not paying proper attention.

Quoted 9 lines

I'll split it as:

This marking of cached vector state in the CPU as invalid is done using __this_cpu_write(fpsimd_last_state, NULL) in fpsimd.c. Due to the repeated use of this rather obscure operation, it makes sense to factor it out as a separate helper with a clearer name. This patch factors it out as fpsimd_flush_cpu_state().

That's definitely clear.

Quoted 7 lines
Quoted 1 line

I'll assume I can keep keep your Reviewed-by, since this change is just clarification.

But if you're not happy, please shout!

I'm happy - in most aspects of life - indeed keep my reviewed-by.

Thanks,
-Christoffer

#81 lore raw

PATCH v3 23/28 arm64/sve: KVM: Treat guest SVE use as undefined instruction execution

In reply to Dave Martin

When trapping forbidden attempts by a guest to use SVE, we want the guest to see a trap consistent with SVE not being implemented.

This patch injects an undefined instruction exception into the guest in response to such an exception.

---
 arch/arm64/kvm/handle_exit.c | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/arm64/kvm/handle_exit.c +8 -0
index 7debb74..b712479 100644
@@ -147,6 +147,13 @@ static int kvm_handle_unknown_ec(struct kvm_vcpu *vcpu, struct kvm_run *run)
 	return 1;
 }
 
+static int handle_sve(struct kvm_vcpu *vcpu, struct kvm_run *run)
+{
+	/* Until SVE is supported for guests: */
+	kvm_inject_undefined(vcpu);
+	return 1;
+}
+
 static exit_handle_fn arm_exit_handlers[] = {
 	[0 ... ESR_ELx_EC_MAX]	= kvm_handle_unknown_ec,
 	[ESR_ELx_EC_WFx]	= kvm_handle_wfx,
@@ -160,6 +167,7 @@ static exit_handle_fn arm_exit_handlers[] = {
 	[ESR_ELx_EC_HVC64]	= handle_hvc,
 	[ESR_ELx_EC_SMC64]	= handle_smc,
 	[ESR_ELx_EC_SYS64]	= kvm_handle_sys_reg,
+	[ESR_ELx_EC_SVE]	= handle_sve,
 	[ESR_ELx_EC_IABT_LOW]	= kvm_handle_guest_abort,
 	[ESR_ELx_EC_DABT_LOW]	= kvm_handle_guest_abort,
 	[ESR_ELx_EC_SOFTSTP_LOW]= kvm_handle_guest_debug,
Signature · 1 line
2.1.4
maintainer Acked-by on v3 23/28
#82 lore raw

Re: [PATCH v3 23/28] arm64/sve: KVM: Treat guest SVE use as undefined instruction execution

Quoted 8 lines · Dave P Martin

When trapping forbidden attempts by a guest to use SVE, we want the guest to see a trap consistent with SVE not being implemented.

This patch injects an undefined instruction exception into the guest in response to such an exception.

Acked-by on v3 23/28
#83 lore raw

Re: [PATCH v3 23/28] arm64/sve: KVM: Treat guest SVE use as undefined instruction execution

In reply to Dave Martin
Quoted 8 lines · Dave Martin

When trapping forbidden attempts by a guest to use SVE, we want the guest to see a trap consistent with SVE not being implemented.

This patch injects an undefined instruction exception into the guest in response to such an exception.

Quoted 37 lines
---
 arch/arm64/kvm/handle_exit.c | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/arm64/kvm/handle_exit.c +8 -0
index 7debb74..b712479 100644
@@ -147,6 +147,13 @@ static int kvm_handle_unknown_ec(struct kvm_vcpu *vcpu, struct kvm_run *run)
 	return 1;
 }
 
+static int handle_sve(struct kvm_vcpu *vcpu, struct kvm_run *run)
+{
+	/* Until SVE is supported for guests: */
+	kvm_inject_undefined(vcpu);
+	return 1;
+}
+
 static exit_handle_fn arm_exit_handlers[] = {
 	[0 ... ESR_ELx_EC_MAX]	= kvm_handle_unknown_ec,
 	[ESR_ELx_EC_WFx]	= kvm_handle_wfx,
@@ -160,6 +167,7 @@ static exit_handle_fn arm_exit_handlers[] = {
 	[ESR_ELx_EC_HVC64]	= handle_hvc,
 	[ESR_ELx_EC_SMC64]	= handle_smc,
 	[ESR_ELx_EC_SYS64]	= kvm_handle_sys_reg,
+	[ESR_ELx_EC_SVE]	= handle_sve,
 	[ESR_ELx_EC_IABT_LOW]	= kvm_handle_guest_abort,
 	[ESR_ELx_EC_DABT_LOW]	= kvm_handle_guest_abort,
 	[ESR_ELx_EC_SOFTSTP_LOW]= kvm_handle_guest_debug,
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
#84 lore raw

PATCH v3 24/28 arm64/sve: KVM: Hide SVE from CPU features exposed to guests

In reply to Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +11 -1
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));
+
+		val &= ~(0xfUL << ID_AA64PFR0_SVE_SHIFT);
+	}
+
+	return val;
 }
 
 /* cpufeature ID register access trap handlers */
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
Acked-by on v3 24/28
#85 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

[+ Christoffer]

Quoted 48 lines · Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +4 -1
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 914

Quoted 10 lines
arch/arm64/kvm/sys_regs.c +7 -0
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));
+
+		val &= ~(0xfUL << ID_AA64PFR0_SVE_SHIFT);
+	}
+
+	return val;
 }
 
 /* cpufeature ID register access trap handlers */
	M.
Signature · 1 line
Jazz is not dead. It just smells funny...
maintainer Acked-by on v3 24/28
#86 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

In reply to Dave Martin
Quoted 16 lines · Dave P Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

Quoted 6 lines

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

Acked-by on v3 24/28
#87 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

In reply to Dave Martin
Quoted 39 lines · Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +1 -0
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 10 lines
arch/arm64/kvm/sys_regs.c +5 -1
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));

nit: does this really qualify as an error print?

Quoted 11 lines
arch/arm64/kvm/sys_regs.c +5 -0
+
+		val &= ~(0xfUL << ID_AA64PFR0_SVE_SHIFT);
+	}
+
+	return val;
 }
 
 /* cpufeature ID register access trap handlers */
Signature · 1 line
2.1.4

Otherwise:

#88 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

Quoted 45 lines · Christoffer Dall
Quoted 44 lines · Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +2 -0
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
Quoted 7 lines

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 5 lines
arch/arm64/kvm/sys_regs.c +4 -1
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));

nit: does this really qualify as an error print?

I have no strong opinion on this: maz suggested I should add this -- his concern was to make it difficult to ignore.

This is transitional: the main purpose is to circumvent bug reports from people who find that SVE doesn't work in their guests, in the interim before proper KVM support lands upstream.

Marc, do you still agree with this position?

Quoted 7 lines
Quoted 7 lines
arch/arm64/kvm/sys_regs.c +5 -0
+
+		val &= ~(0xfUL << ID_AA64PFR0_SVE_SHIFT);
+	}
+
+	return val;
 }
 
Quoted 7 lines
Quoted 4 lines
arch/arm64/kvm/sys_regs.c +0 -0
 /* cpufeature ID register access trap handlers */
Signature · 1 line
2.1.4

Otherwise:

Thanks -- I'll wait for Marc's response before applying.

Cheers
---Dave

#89 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

Quoted 54 lines · Dave Martin
Quoted 45 lines · Christoffer Dall
Quoted 44 lines · Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +2 -0
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
Quoted 7 lines

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 5 lines
arch/arm64/kvm/sys_regs.c +4 -1
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));

nit: does this really qualify as an error print?

Quoted 8 lines

I have no strong opinion on this: maz suggested I should add this -- his concern was to make it difficult to ignore.

This is transitional: the main purpose is to circumvent bug reports from people who find that SVE doesn't work in their guests, in the interim before proper KVM support lands upstream.

Marc, do you still agree with this position?

As long as this is transitional, I'm OK with this.

	M.
Signature · 5 lines
Jazz is not dead. It just smells funny...
_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
#90 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

Quoted 58 lines · Marc Zyngier
Quoted 57 lines · Dave Martin
Quoted 45 lines · Christoffer Dall
Quoted 44 lines · Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +2 -0
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
Quoted 7 lines

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 5 lines
arch/arm64/kvm/sys_regs.c +4 -1
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));

nit: does this really qualify as an error print?

I have no strong opinion on this: maz suggested I should add this -- his concern was to make it difficult to ignore.

Quoted 7 lines
Quoted 5 lines

This is transitional: the main purpose is to circumvent bug reports from people who find that SVE doesn't work in their guests, in the interim before proper KVM support lands upstream.

Marc, do you still agree with this position?

As long as this is transitional, I'm OK with this.

No argument from me, since it was your request in the first place ;)

Christoffer?

Cheers
---Dave

#91 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

Quoted 63 lines · Dave Martin
Quoted 62 lines · Marc Zyngier
Quoted 61 lines · Dave Martin
Quoted 45 lines · Christoffer Dall
Quoted 44 lines · Dave Martin

KVM guests cannot currently use SVE, because SVE is always configured to trap to EL2.

However, a guest that sees SVE reported as present in ID_AA64PFR0_EL1 may legitimately expect that SVE works and try to use it. Instead of working, the guest will receive an injected undef exception, which may cause the guest to oops or go into a spin.

To avoid misleading the guest into believing that SVE will work, this patch masks out the SVE field from ID_AA64PFR0_EL1 when a guest attempts to read this register. No support is explicitly added for ID_AA64ZFR0_EL1 either, so that is still emulated as reading as zero, which is consistent with SVE not being implemented.

This is a temporary measure, and will be removed in a later series when full KVM support for SVE is implemented.

---
 arch/arm64/kvm/sys_regs.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/arm64/kvm/sys_regs.c +2 -0
index b1f7552..a0ee9b0 100644
@@ -23,6 +23,7 @@
 #include <linux/bsearch.h>
 #include <linux/kvm_host.h>
 #include <linux/mm.h>
+#include <linux/printk.h>
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
Quoted 7 lines

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 5 lines
arch/arm64/kvm/sys_regs.c +4 -1
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));

nit: does this really qualify as an error print?

I have no strong opinion on this: maz suggested I should add this -- his concern was to make it difficult to ignore.

This is transitional: the main purpose is to circumvent bug reports from people who find that SVE doesn't work in their guests, in the interim before proper KVM support lands upstream.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

Marc, do you still agree with this position?

As long as this is transitional, I'm OK with this.

No argument from me, since it was your request in the first place ;)

Christoffer?

No (further) argument from me.

Thanks,
-Christoffer

#92 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

Quoted 5 lines · Christoffer Dall
Quoted 4 lines · Dave Martin
Quoted 3 lines · Marc Zyngier
Quoted 2 lines · Dave Martin
Quoted 1 line · Christoffer Dall

On Tue, Oct 10, 2017 at 07:38:41PM +0100, Dave Martin wrote:

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
arch/arm64/kvm/sys_regs.c +0 -0

[...]

Quoted 23 lines
Quoted 23 lines
Quoted 23 lines
Quoted 22 lines
Quoted 6 lines
Quoted 6 lines
arch/arm64/kvm/sys_regs.c +1 -0
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
 	u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
 			 (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+	u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
Quoted 7 lines

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 5 lines
arch/arm64/kvm/sys_regs.c +4 -1
-	return raz ? 0 : read_sanitised_ftr_reg(id);
+	if (id == SYS_ID_AA64PFR0_EL1) {
+		if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+			pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+				    task_pid_nr(current));

nit: does this really qualify as an error print?

I have no strong opinion on this: maz suggested I should add this -- his concern was to make it difficult to ignore.

This is transitional: the main purpose is to circumvent bug reports from people who find that SVE doesn't work in their guests, in the interim before proper KVM support lands upstream.

Marc, do you still agree with this position?

Quoted 7 lines
Quoted 6 lines
Quoted 1 line

As long as this is transitional, I'm OK with this.

No argument from me, since it was your request in the first place ;)

Christoffer?

No (further) argument from me.

OK, thanks. Can I take that as an Ack?

Cheers
---Dave

#93 lore raw

Re: [PATCH v3 24/28] arm64/sve: KVM: Hide SVE from CPU features exposed to guests

Quoted 38 lines · Dave Martin
Quoted 5 lines · Christoffer Dall
Quoted 4 lines · Dave Martin
Quoted 3 lines · Marc Zyngier
Quoted 2 lines · Dave Martin
Quoted 1 line · Christoffer Dall

On Tue, Oct 10, 2017 at 07:38:41PM +0100, Dave Martin wrote:

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
arch/arm64/kvm/sys_regs.c +0 -0

[...]

Quoted 25 lines
Quoted 25 lines
Quoted 24 lines
Quoted 14 lines
Quoted 6 lines
Quoted 6 lines
arch/arm64/kvm/sys_regs.c +1 -0
@@ -897,8 +898,17 @@ static u64 read_id_reg(struct sys_reg_desc const *r, bool raz)
 {
      u32 id = sys_reg((u32)r->Op0, (u32)r->Op1,
                       (u32)r->CRn, (u32)r->CRm, (u32)r->Op2);
+     u64 val = raz ? 0 : read_sanitised_ftr_reg(id);
 
Quoted 7 lines

arch/arm64/kvm/sys_regs.c static u64 read_id_reg(struct sys_reg_desc const *r, bool raz) · line 906

Quoted 5 lines
arch/arm64/kvm/sys_regs.c +4 -1
-     return raz ? 0 : read_sanitised_ftr_reg(id);
+     if (id == SYS_ID_AA64PFR0_EL1) {
+             if (val & (0xfUL << ID_AA64PFR0_SVE_SHIFT))
+                     pr_err_once("kvm [%i]: SVE unsupported for guests, suppressing\n",
+                                 task_pid_nr(current));

nit: does this really qualify as an error print?

Quoted 8 lines

I have no strong opinion on this: maz suggested I should add this -- his concern was to make it difficult to ignore.

This is transitional: the main purpose is to circumvent bug reports from people who find that SVE doesn't work in their guests, in the interim before proper KVM support lands upstream.

Marc, do you still agree with this position?

As long as this is transitional, I'm OK with this.

Quoted 8 lines
Quoted 5 lines
Quoted 4 lines

No argument from me, since it was your request in the first place ;)

Christoffer?

No (further) argument from me.

OK, thanks. Can I take that as an Ack?

Yes:

#94 lore raw

PATCH v3 25/28 arm64/sve: Detect SVE and activate runtime support

In reply to Dave Martin

This patch enables detection of hardware SVE support via the cpufeatures framework, and reports its presence to the kernel and userspace via the new ARM64_SVE cpucap and HWCAP_SVE hwcap respectively.

Userspace can also detect SVE using ID_AA64PFR0_EL1, using the cpufeatures MRS emulation.

When running on hardware that supports SVE, this enables runtime kernel support for SVE, and allows user tasks to execute SVE instructions and make of the of the SVE-specific user/kernel interface extensions implemented by this series.

Cc Suzuki K Poulose <[email protected]>

---

Dropped Suzuki's Reviewed-by, since there are non-trivial changes.

Changes since v2
----------------

Requested by Catalin Marinas:

* Moved the EL1 SVE trap disable logic to cpufeatures. This requires the trap to be disabled when the ARM64_SVE cpu capability is detected on any booting cpu.

---
 Documentation/arm64/cpu-feature-registers.txt |  6 +++++-
 arch/arm64/include/asm/cpucaps.h              |  3 ++-
 arch/arm64/include/asm/cpufeature.h           |  3 ++-
 arch/arm64/include/uapi/asm/hwcap.h           |  1 +
 arch/arm64/kernel/cpufeature.c                | 17 +++++++++++++++++
 arch/arm64/kernel/cpuinfo.c                   |  1 +
 6 files changed, 28 insertions(+), 3 deletions(-)
Documentation/arm64/cpu-feature-registers.txt +5 -1
index dad411d..d65504c 100644
@@ -132,7 +132,11 @@ infrastructure:
      x--------------------------------------------------x
      | Name                         |  bits   | visible |
      |--------------------------------------------------|
-     | RES0                         | [63-28] |    n    |
+     | RES0                         | [63-36] |    n    |
+     |--------------------------------------------------|
+     | SVE                          | [35-32] |    y    |
+     |--------------------------------------------------|
+     | RES0                         | [31-28] |    n    |
      |--------------------------------------------------|
      | GIC                          | [27-24] |    n    |
      |--------------------------------------------------|
arch/arm64/include/asm/cpucaps.h +2 -1
index 8da6216..2ff7c5e 100644
@@ -40,7 +40,8 @@
 #define ARM64_WORKAROUND_858921			19
 #define ARM64_WORKAROUND_CAVIUM_30115		20
 #define ARM64_HAS_DCPOP				21
+#define ARM64_SVE				22
 
-#define ARM64_NCAPS				22
+#define ARM64_NCAPS				23
 
 #endif /* __ASM_CPUCAPS_H */
arch/arm64/include/asm/cpufeature.h +2 -1
index 51be8e8..9ac1418 100644
@@ -273,7 +273,8 @@ static inline bool system_uses_ttbr0_pan(void)
 
 static inline bool system_supports_sve(void)
 {
-	return false;
+	return IS_ENABLED(CONFIG_ARM64_SVE) &&
+		cpus_have_const_cap(ARM64_SVE);
 }
 
 /*
arch/arm64/include/uapi/asm/hwcap.h +1 -0
index 4b9344c..c6e1e45 100644
@@ -36,5 +36,6 @@
 #define HWCAP_FCMA		(1 << 14)
 #define HWCAP_LRCPC		(1 << 15)
 #define HWCAP_DCPOP		(1 << 16)
+#define HWCAP_SVE		(1 << 17)
 
 #endif /* _UAPI__ASM_HWCAP_H */
arch/arm64/kernel/cpufeature.c +17 -0
index c5acf38..06aa958 100644
@@ -141,6 +141,7 @@ static const struct arm64_ftr_bits ftr_id_aa64isar1[] = {
 };
 
 static const struct arm64_ftr_bits ftr_id_aa64pfr0[] = {
+	ARM64_FTR_BITS(FTR_VISIBLE, FTR_STRICT, FTR_LOWER_SAFE, ID_AA64PFR0_SVE_SHIFT, 4, 0),
 	ARM64_FTR_BITS(FTR_HIDDEN, FTR_STRICT, FTR_EXACT, ID_AA64PFR0_GIC_SHIFT, 4, 0),
 	S_ARM64_FTR_BITS(FTR_VISIBLE, FTR_STRICT, FTR_LOWER_SAFE, ID_AA64PFR0_ASIMD_SHIFT, 4, ID_AA64PFR0_ASIMD_NI),
 	S_ARM64_FTR_BITS(FTR_VISIBLE, FTR_STRICT, FTR_LOWER_SAFE, ID_AA64PFR0_FP_SHIFT, 4, ID_AA64PFR0_FP_NI),
@@ -942,6 +943,19 @@ static const struct arm64_cpu_capabilities arm64_features[] = {
 		.min_field_value = 1,
 	},
 #endif
+#ifdef CONFIG_ARM64_SVE
+	{
+		.desc = "Scalable Vector Extension",
+		.capability = ARM64_SVE,
+		.def_scope = SCOPE_SYSTEM,
+		.sys_reg = SYS_ID_AA64PFR0_EL1,
+		.sign = FTR_UNSIGNED,
+		.field_pos = ID_AA64PFR0_SVE_SHIFT,
+		.min_field_value = ID_AA64PFR0_SVE,
+		.matches = has_cpuid_feature,
+		.enable = sve_kernel_enable,
+	},
+#endif /* CONFIG_ARM64_SVE */
 	{},
 };
 
@@ -974,6 +988,9 @@ static const struct arm64_cpu_capabilities arm64_elf_hwcaps[] = {
 	HWCAP_CAP(SYS_ID_AA64ISAR1_EL1, ID_AA64ISAR1_JSCVT_SHIFT, FTR_UNSIGNED, 1, CAP_HWCAP, HWCAP_JSCVT),
 	HWCAP_CAP(SYS_ID_AA64ISAR1_EL1, ID_AA64ISAR1_FCMA_SHIFT, FTR_UNSIGNED, 1, CAP_HWCAP, HWCAP_FCMA),
 	HWCAP_CAP(SYS_ID_AA64ISAR1_EL1, ID_AA64ISAR1_LRCPC_SHIFT, FTR_UNSIGNED, 1, CAP_HWCAP, HWCAP_LRCPC),
+#ifdef CONFIG_ARM64_SVE
+	HWCAP_CAP(SYS_ID_AA64PFR0_EL1, ID_AA64PFR0_SVE_SHIFT, FTR_UNSIGNED, ID_AA64PFR0_SVE, CAP_HWCAP, HWCAP_SVE),
+#endif
 	{},
 };
 
arch/arm64/kernel/cpuinfo.c +1 -0
index be260e8..9559dde 100644
@@ -70,6 +70,7 @@ static const char *const hwcap_str[] = {
 	"fcma",
 	"lrcpc",
 	"dcpop",
+	"sve",
 	NULL
 };
 
Signature · 1 line
2.1.4
reviewer Reviewed-by on v3 25/28
#95 lore raw

Re: [PATCH v3 25/28] arm64/sve: Detect SVE and activate runtime support

Quoted 8 lines · Dave Martin

This patch enables detection of hardware SVE support via the cpufeatures framework, and reports its presence to the kernel and userspace via the new ARM64_SVE cpucap and HWCAP_SVE hwcap respectively.

Userspace can also detect SVE using ID_AA64PFR0_EL1, using the cpufeatures MRS emulation.

Quoted 7 lines

When running on hardware that supports SVE, this enables runtime kernel support for SVE, and allows user tasks to execute SVE instructions and make of the of the SVE-specific user/kernel interface extensions implemented by this series.

Cc Suzuki K Poulose <[email protected]>

Looks good to me.

maintainer Reviewed-by on v3 25/28
#96 lore raw

Re: [PATCH v3 25/28] arm64/sve: Detect SVE and activate runtime support

In reply to Dave Martin
Quoted 8 lines · Dave P Martin

This patch enables detection of hardware SVE support via the cpufeatures framework, and reports its presence to the kernel and userspace via the new ARM64_SVE cpucap and HWCAP_SVE hwcap respectively.

Userspace can also detect SVE using ID_AA64PFR0_EL1, using the cpufeatures MRS emulation.

Quoted 7 lines

When running on hardware that supports SVE, this enables runtime kernel support for SVE, and allows user tasks to execute SVE instructions and make of the of the SVE-specific user/kernel interface extensions implemented by this series.

Cc Suzuki K Poulose <[email protected]>
#97 lore raw

PATCH v3 26/28 arm64/sve: Add documentation

In reply to Dave Martin

This patch adds basic documentation of the user/kernel interface provided by the for SVE.

Cc Alex Bennée <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Alan Hayward <[email protected]>

---

Changes since v2
----------------

Changes requested by Alan Hayward:

* Added a note that the caller of PTRACE_SETREGSET will need to do a GETREGSET if complete certainty about the resulting VL is desired.

ABI changes:

* Documented the changed return value value semantics for PR_SET_SET_VL when the PR_SVE_SET_VL_ONEXEC flag is passed.

---
 Documentation/arm64/sve.txt              | 484 +++++++++++++++++++++++++++++++
 arch/arm64/include/uapi/asm/sigcontext.h |   3 +
 2 files changed, 487 insertions(+)
 create mode 100644 Documentation/arm64/sve.txt
Documentation/arm64/sve.txt new file +484 -0
new file mode 100644
index 0000000..2e8f009
@@ -0,0 +1,484 @@
+            Scalable Vector Extension support for AArch64 Linux
+            ===================================================
+
+Author: Dave Martin <[email protected]>
+Date:   4 August 2017
+
+This document outlines briefly the interface provided to userspace by Linux in
+order to support use of the ARM Scalable Vector Extension (SVE).
+
+This is an outline of the most important features and issues only and not
+intended to be exhaustive.
+
+This document does not aim to describe the SVE architecture or programmer's
+model.  To aid understanding, a minimal description of relevant programmer's
+model features for SVE is included in Appendix A.
+
+
+1.  General
+-----------
+
+* SVE registers Z0..Z31, P0..P15 and FFR and the current vector length VL, are
+  tracked per-thread.
+
+* The presence of SVE is reported to userspace via HWCAP_SVE in the aux vector
+  AT_HWCAP entry.  Presence of this flag implies the presence of the SVE
+  instructions and registers, and the Linux-specific system interfaces
+  described in this document.  SVE is reported in /proc/cpuinfo as "sve".
+
+* Support for the execution of SVE instructions in userspace can also be
+  detected by reading the CPU ID register ID_AA64PFR0_EL1 using an MRS
+  instruction, and checking that the value of the SVE field is nonzero. [3]
+
+  It does not guarantee the presence of the system interfaces described in the
+  following sections: software that needs to verify that those interfaces are
+  present must check for HWCAP_SVE instead.
+
+* Debuggers should restrict themselves to interacting with the target via the
+  NT_ARM_SVE regset.  The recommended way of detecting support for this regset
+  is to connect to a target process first and then attempt a
+  ptrace(PTRACE_GETREGSET, pid, NT_ARM_SVE, &iov).
+
+
+2.  Vector length terminology
+-----------------------------
+
+The size of an SVE vector (Z) register is referred to as the "vector length".
+
+To avoid confusion about the units used to express vector length, the kernel
+adopts the following conventions:
+
+* Vector length (VL) = size of a Z-register in bytes
+
+* Vector quadwords (VQ) = size of a Z-register in units of 128 bits
+
+(So, VL = 16 * VQ.)
+
+The VQ convention is used where the underlying granularity is important, such
+as in data structure definitions.  In most other situations, the VL convention
+is used.  This is consistent with the meaning of the "VL" pseudo-register in
+the SVE instruction set architecture.
+
+
+3.  System call behaviour
+-------------------------
+
+* On syscall, V0..V31 are preserved (as without SVE).  Thus, bits [127:0] of
+  Z0..Z31 are preserved.  All other bits of Z0..Z31, and all of P0..P15 and FFR
+  become unspecified on return from a syscall.
+
+* The SVE registers are not used to pass arguments to or receive results from
+  any syscall.
+
+* In practice the affected registers/bits will be preserved or will be replaced
+  with zeros on return from a syscall, but userspace should not make
+  assumptions about this.  The kernel behaviour may vary on a case-by-case
+  basis.
+
+
+4.  Signal handling
+-------------------
+
+* A new signal frame record sve_context encodes the SVE registers on signal
+  delivery. [1]
+
+* This record is supplementary to fpsimd_context.  The FPSR and FPCR registers
+  are only present in fpsimd_context.  For convenience, the content of V0..V31
+  is duplicated between sve_context and fpsimd_context.
+
+* The signal frame record for SVE always contains basic metadata, in particular
+  the thread's vector length (in sve_context.vl).
+
+* The SVE registers may or may not be included in the record, depending on
+  whether the registers are live for the thread.  The registers are present if
+  and only if:
+  sve_context.head.size >= SVE_SIG_CONTEXT_SIZE(sve_vq_from_vl(sve_context.vl)).
+
+* If the registers are present, the remainder of the record has a vl-dependent
+  size and layout.  Macros SIG_SVE_* are defined [1] to facilitate access to
+  the members.
+
+* If the SVE context is too big to fit in sigcontext.__reserved[], then extra
+  space is allocated on the stack, an extra_context record is written in
+  __reserved[] referencing this space.  sve_context is then written in the
+  extra space.  Refer to [1] for further details about this mechanism.
+
+
+5.  Signal return
+-----------------
+
+When returning from a signal handler:
+
+* If there is no sve_context record in the signal frame, or if the record is
+  present but contains no register data as desribed in the previous section,
+  then the SVE registers/bits become non-live and take unspecified values.
+
+* If sve_context is present in the signal frame and contains full register
+  data, the SVE registers become live and are populated with the specified
+  data.  However, for backward compatibility reasons, bits [127:0] of Z0..Z31
+  are always restored from the corresponding members of fpsimd_context.vregs[]
+  and not from sve_context.  The remaining bits are restored from sve_context.
+
+* Inclusion of fpsimd_context in the signal frame remains mandatory,
+  irrespective of whether sve_context is present or not.
+
+* The vector length cannot be changed via signal return.  If sve_context.vl in
+  the signal frame does not match the current vector length, the signal return
+  attempt is treated as illegal, resulting in a forced SIGSEGV.
+
+
+6.  prctl extensions
+--------------------
+
+Some new prctl() calls are added to allow programs to manage the SVE vector
+length:
+
+prctl(PR_SVE_SET_VL, unsigned long arg)
+
+    Sets the vector length of the calling thread and related flags, where
+    arg == vl | flags.
+
+    vl is the desired vector length, where sve_vl_valid(vl) must be true.
+
+    flags:
+
+	PR_SVE_SET_VL_INHERIT
+
+	    Inherit the current vector length across execve().  Otherwise, the
+	    vector length is reset to the system default at execve().  (See
+	    Section 9.)
+
+	PR_SVE_SET_VL_ONEXEC
+
+	    Defer the requested vector length change until the next execve().
+	    This allows launching of a new program with a different vector
+	    length, while avoiding runtime side effects in the caller.
+
+	    This also overrides the effect of PR_SVE_SET_VL_INHERIT for the
+	    first execve().
+
+	    Without PR_SVE_SET_VL_ONEXEC, any outstanding deferred vector
+	    length change is cancelled.
+
+    Return value: a nonnegative on success, or a negative value on error:
+	EINVAL: SVE not supported, invalid vector length requested, or
+	    invalid flags.
+
+    On success, the calling thread's vector length is changed to the largest
+    value supported by the system that is less than or equal to vl.
+    If vl == SVE_VL_MAX, the calling thread's vector length is changed to the
+    largest value supported by the system.
+
+    The returned value describes the resulting configuration, encoded as for
+    PR_SVE_GET_VL.  The vector length reported in this value is the new current
+    vector length for this thread if PR_SVE_SET_VL_ONEXEC was not passed in the
+    input arg; otherwise, the reported vector length is the deferred vector
+    length that will be applied at the next exec.
+
+    Changing the vector length causes all of P0..P15, FFR and all bits of
+    Z0..V31 except for Z0 bits [127:0] .. Z31 bits [127:0] to become
+    unspecified.  Calling PR_SVE_SET_VL with vl equal to the thread's current
+    vector length does not constitute a change to the vector length for this
+    purpose.
+
+
+prctl(PR_SVE_GET_VL)
+
+    Gets the vector length of the calling thread.
+
+    The following flag may be OR-ed into the result:
+
+	PR_SVE_SET_VL_INHERIT
+
+	    Vector length will be inherited across execve().
+
+    There is no way to determine whether there is an outstanding deferred
+    vector length change (which would only normally be the case between a
+    fork() or vfork() and the corresponding execve() in typical use).
+
+    To extract the vector length from the result, and it with
+    PR_SVE_VL_LEN_MASK.
+
+    Return value: a nonnegative value on success, or a negative value on error:
+	EINVAL: SVE not supported.
+
+
+7.  ptrace extensions
+---------------------
+
+* A new regset NT_ARM_SVE is defined for use with PTRACE_GETREGSET and
+  PTRACE_SETREGSET.
+
+  Refer to [2] for definitions.
+
+The regset data starts with struct user_sve_header, containing:
+
+    size
+
+	Size of the complete regset, in bytes.
+	This depends on vl and possibly on other things in the future.
+
+	If a call to PTRACE_GETREGSET requests less data than the value of
+	size, the caller can allocate a larger buffer and retry in order to
+	read the complete regset.
+
+    max_size
+
+	Maximum size in bytes that the regset can grow to for the target
+	thread.  The regset won't grow bigger than this even if the target
+	thread changes its vector length etc.
+
+    vl
+
+	Target thread's current vector length, in bytes.
+
+    max_vl
+
+	Maximum possible vector length for the target thread.
+
+    flags
+
+	either
+
+	    SVE_PT_REGS_FPSIMD
+
+		SVE registers are not live (GETREGSET) or are to be made
+		non-live (SETREGSET).
+
+		The payload is of type struct user_fpsimd_state, with the same
+		meaning as for NT_PRFPREG, starting at offset
+		SVE_PT_FPSIMD_OFFSET from the start of user_sve_header.
+
+		Extra data might be appended in the future: the size of the
+		payload should be obtained using SVE_PT_FPSIMD_SIZE(vq, flags).
+
+		vq should be obtained using sve_vq_from_vl(vl).
+
+		or
+
+	    SVE_PT_REGS_SVE
+
+		SVE registers are live (GETREGSET) or are to be made live
+		(SETREGSET).
+
+		The payload contains the SVE register data, starting at offset
+		SVE_PT_SVE_OFFSET from the start of user_sve_header, and with
+		size SVE_PT_SVE_SIZE(vq, flags);
+
+	... OR-ed with zero or more of the following flags, which have the same
+	meaning and behaviour as the corresponding PR_SET_VL_* flags:
+
+	    SVE_PT_VL_INHERIT
+
+	    SVE_PT_VL_ONEXEC (SETREGSET only).
+
+* The effects of changing the vector length and/or flags are equivalent to
+  those documented for PR_SVE_SET_VL.
+
+  The caller must make a further GETREGSET call if it needs to know what VL is
+  actually set by SETREGSET, unless is it known in advance that the requested
+  VL is supported.
+
+* In the SVE_PT_REGS_SVE case, the size and layout of the payload depends on
+  the header fields.  The SVE_PT_SVE_*() macros are provided to facilitate
+  access to the members.
+
+* In either case, for SETREGSET it is permissible to omit the payload, in which
+  case only the vector length and flags are changed (along with any
+  consequences of those changes).
+
+* For SETREGSET, if an SVE_PT_REGS_SVE payload is present and the
+  requested VL is not supported, the effect will be the same as if the
+  payload were omitted, except that an EIO error is reported.  No
+  attempt is made to translate the payload data to the correct layout
+  for the vector length actually set.  The thread's FPSIMD state is
+  preserved, but the remaining bits of the SVE registers become
+  unspecified.  It is up to the caller to translate the payload layout
+  for the actual VL and retry.
+
+* The effect of writing a partial, incomplete payload is unspecified.
+
+
+8.  ELF coredump extensions
+---------------------------
+
+* A NT_ARM_SVE note will be added to each coredump for each thread of the
+  dumped process.  The contents will be equivalent to the data that would have
+  been read if a PTRACE_GETREGSET of NT_ARM_SVE were executed for each thread
+  when the coredump was generated.
+
+
+9.  System runtime configuration
+--------------------------------
+
+* To mitigate the ABI impact of expansion of the signal frame, a policy
+  mechanism is provided for administrators, distro maintainers and developers
+  to set the default vector length for userspace processes:
+
+/proc/cpu/sve_default_vector_length
+
+    Writing the text representation of an integer to this file sets the system
+    default vector length to the specified value, unless the value is greater
+    than the maximum vector length supported by the system in which case the
+    default vector length is set to that maximum.
+
+    The result can be determined by reopening the file and reading its
+    contents.
+
+    At boot, the default vector length is initially set to 64 or the maximum
+    supported vector length, whichever is smaller.  This determines the initial
+    vector length of the init process (PID 1).
+
+    Reading this file returns the current system default vector length.
+
+* At every execve() call, the new vector length of the new process is set to
+  the system default vector length, unless
+
+    * PR_SVE_SET_VL_INHERIT (or equivalently SVE_PT_VL_INHERIT) is set for the
+      calling thread, or
+
+    * a deferred vector length change is pending, established via the
+      PR_SVE_SET_VL_ONEXEC flag (or SVE_PT_VL_ONEXEC).
+
+* Modifying the system default vector length does not affect the vector length
+  of any existing process or thread that does not make an execve() call.
+
+
+Appendix A.  SVE programmer's model (informative)
+=================================================
+
+This section provides a minimal description of the additions made by SVE to the
+ARMv8-A programmer's model that are relevant to this document.
+
+Note: This section is for information only and not intended to be complete or
+to replace any architectural specification.
+
+A.1.  Registers
+---------------
+
+In A64 state, SVE adds the following:
+
+* 32 8VL-bit vector registers Z0..Z31
+  For each Zn, Zn bits [127:0] alias the ARMv8-A vector register Vn.
+
+  A register write using a Vn register name zeros all bits of the corresponding
+  Zn except for bits [127:0].
+
+* 16 VL-bit predicate registers P0..P15
+
+* 1 VL-bit special-purpose predicate register FFR (the "first-fault register")
+
+* a VL "pseudo-register" that determines the size of each vector register
+
+  The SVE instruction set architecture provides no way to write VL directly.
+  Instead, it can be modified only by EL1 and above, by writing appropriate
+  system registers.
+
+* The value of VL can be configured at runtime by EL1 and above:
+  16 <= VL <= VLmax, where VL must be a multiple of 16.
+
+* The maximum vector length is determined by the hardware:
+  16 <= VLmax <= 256.
+
+  (The SVE architecture specifies 256, but permits future architecture
+  revisions to raise this limit.)
+
+* FPSR and FPCR are retained from ARMv8-A, and interact with SVE floating-point
+  operations in a similar way to the way in which they interact with ARMv8
+  floating-point operations.
+
+         8VL-1                       128               0  bit index
+        +----          ////            -----------------+
+     Z0 |                               :       V0      |
+      :                                          :
+     Z7 |                               :       V7      |
+     Z8 |                               :     * V8      |
+      :                                       :  :
+    Z15 |                               :     *V15      |
+    Z16 |                               :      V16      |
+      :                                          :
+    Z31 |                               :      V31      |
+        +----          ////            -----------------+
+                                                 31    0
+         VL-1                  0                +-------+
+        +----       ////      --+          FPSR |       |
+     P0 |                       |               +-------+
+      : |                       |         *FPCR |       |
+    P15 |                       |               +-------+
+        +----       ////      --+
+    FFR |                       |               +-----+
+        +----       ////      --+            VL |     |
+                                                +-----+
+
+(*) callee-save:
+    This only applies to bits [63:0] of Z-/V-registers.
+    FPCR contains callee-save and caller-save bits.  See [4] for details.
+
+
+A.2.  Procedure call standard
+-----------------------------
+
+The ARMv8-A base procedure call standard is extended as follows with respect to
+the additional SVE register state:
+
+* All SVE register bits that are not shared with FP/SIMD are caller-save.
+
+* Z8 bits [63:0] .. Z15 bits [63:0] are callee-save.
+
+  This follows from the way these bits are mapped to V8..V15, which are caller-
+  save in the base procedure call standard.
+
+
+Appendix B.  ARMv8-A FP/SIMD programmer's model
+===============================================
+
+Note: This section is for information only and not intended to be complete or
+to replace any architectural specification.
+
+Refer to [4] for for more information.
+
+ARMv8-A defines the following floating-point / SIMD register state:
+
+* 32 128-bit vector registers V0..V31
+* 2 32-bit status/control registers FPSR, FPCR
+
+         127           0  bit index
+        +---------------+
+     V0 |               |
+      : :               :
+     V7 |               |
+   * V8 |               |
+   :  : :               :
+   *V15 |               |
+    V16 |               |
+      : :               :
+    V31 |               |
+        +---------------+
+
+                 31    0
+                +-------+
+           FPSR |       |
+                +-------+
+          *FPCR |       |
+                +-------+
+
+(*) callee-save:
+    This only applies to bits [63:0] of V-registers.
+    FPCR contains a mixture of callee-save and caller-save bits.
+
+
+References
+==========
+
+[1] arch/arm64/include/uapi/asm/sigcontext.h
+    AArch64 Linux signal ABI definitions
+
+[2] arch/arm64/include/uapi/asm/ptrace.h
+    AArch64 Linux ptrace ABI definitions
+
+[3] linux/Documentation/arm64/cpu-feature-registers.txt
+
+[4] ARM IHI0055C
+    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055c/IHI0055C_beta_aapcs64.pdf
+    http://infocenter.arm.com/help/topic/com.arm.doc.subset.swdev.abi/index.html
+    Procedure Call Standard for the ARM 64-bit Architecture (AArch64)
arch/arm64/include/uapi/asm/sigcontext.h +3 -0
index 7654a81..3c0b484 100644
@@ -133,6 +133,9 @@ struct sve_context {
  * The SVE architecture leaves space for future expansion of the
  * vector length beyond its initial architectural limit of 2048 bits
  * (16 quadwords).
+ *
+ * See linux/Documentation/arm64/sve.txt for a description of the VL/VQ
+ * terminology.
  */
 #define SVE_VQ_BYTES		16	/* number of bytes per quadword */
 
Signature · 6 lines
2.1.4

_______________________________________________
kvmarm mailing list
[email protected]
https://lists.cs.columbia.edu/mailman/listinfo/kvmarm
#98 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

Quoted 23 lines · Dave Martin

This patch adds basic documentation of the user/kernel interface provided by the for SVE.

Cc Alex Bennée <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Alan Hayward <[email protected]>

---

Changes since v2
----------------

Changes requested by Alan Hayward:

* Added a note that the caller of PTRACE_SETREGSET will need to do a GETREGSET if complete certainty about the resulting VL is desired.

ABI changes:

* Documented the changed return value value semantics for PR_SET_SET_VL when the PR_SVE_SET_VL_ONEXEC flag is passed.
---

...

Quoted 17 lines
Documentation/arm64/sve.txt new file +17 -0
+prctl(PR_SVE_SET_VL, unsigned long arg)
+
+    Sets the vector length of the calling thread and related flags, where
+    arg == vl | flags.
+
+    vl is the desired vector length, where sve_vl_valid(vl) must be true.
+
+    flags:
+
+	PR_SVE_SET_VL_INHERIT
+
+	    Inherit the current vector length across execve().  Otherwise, the
+	    vector length is reset to the system default at execve().  (See
+	    Section 9.)
+
+	PR_SVE_SET_VL_ONEXEC
+

Documentation/arm64/sve.txt line 162

Quoted 10 lines
Documentation/arm64/sve.txt new file +10 -0
+	    Defer the requested vector length change until the next execve().
+	    This allows launching of a new program with a different vector
+	    length, while avoiding runtime side effects in the caller.
+
+	    This also overrides the effect of PR_SVE_SET_VL_INHERIT for the
+	    first execve().
+
+	    Without PR_SVE_SET_VL_ONEXEC, any outstanding deferred vector
+	    length change is cancelled.
+

"next execve" is still ambiguous. (execve has process global effect so it may plausibly mean next in the process or next in the calling thread)

"any outstanding deferred vector length change" is ambiguous. (it may be for all threads in a process or in the calling thread only)

Quoted 15 lines
Documentation/arm64/sve.txt new file +15 -0
+    Return value: a nonnegative on success, or a negative value on error:
+	EINVAL: SVE not supported, invalid vector length requested, or
+	    invalid flags.
+
+    On success, the calling thread's vector length is changed to the largest
+    value supported by the system that is less than or equal to vl.
+    If vl == SVE_VL_MAX, the calling thread's vector length is changed to the
+    largest value supported by the system.
+
+    The returned value describes the resulting configuration, encoded as for
+    PR_SVE_GET_VL.  The vector length reported in this value is the new current
+    vector length for this thread if PR_SVE_SET_VL_ONEXEC was not passed in the
+    input arg; otherwise, the reported vector length is the deferred vector
+    length that will be applied at the next exec.
+

...

Documentation/arm64/sve.txt line 319

Quoted 9 lines

+9. System runtime configuration
+--------------------------------

Documentation/arm64/sve.txt new file +7 -0
+
+* To mitigate the ABI impact of expansion of the signal frame, a policy
+  mechanism is provided for administrators, distro maintainers and developers
+  to set the default vector length for userspace processes:
+
+/proc/cpu/sve_default_vector_length
+

still wrong.

A message that is not in the archive (sent off-list or not yet received): [email protected]

#100 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

Quoted 77 lines · Szabolcs Nagy
Quoted 23 lines · Dave Martin

This patch adds basic documentation of the user/kernel interface provided by the for SVE.

Cc Alex Bennée <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Alan Hayward <[email protected]>

---

Changes since v2
----------------

Changes requested by Alan Hayward:

* Added a note that the caller of PTRACE_SETREGSET will need to do a GETREGSET if complete certainty about the resulting VL is desired.

ABI changes:

* Documented the changed return value value semantics for PR_SET_SET_VL when the PR_SVE_SET_VL_ONEXEC flag is passed.
---

...

Quoted 17 lines
(quoted diff) +17 -0
+prctl(PR_SVE_SET_VL, unsigned long arg)
+
+    Sets the vector length of the calling thread and related flags, where
+    arg == vl | flags.
+
+    vl is the desired vector length, where sve_vl_valid(vl) must be true.
+
+    flags:
+
+	PR_SVE_SET_VL_INHERIT
+
+	    Inherit the current vector length across execve().  Otherwise, the
+	    vector length is reset to the system default at execve().  (See
+	    Section 9.)
+
+	PR_SVE_SET_VL_ONEXEC
+

Review

Quoted 10 lines
(quoted diff) +10 -0
+	    Defer the requested vector length change until the next execve().
+	    This allows launching of a new program with a different vector
+	    length, while avoiding runtime side effects in the caller.
+
+	    This also overrides the effect of PR_SVE_SET_VL_INHERIT for the
+	    first execve().
+
+	    Without PR_SVE_SET_VL_ONEXEC, any outstanding deferred vector
+	    length change is cancelled.
+

"next execve" is still ambiguous. (execve has process global effect so it may plausibly mean next in the process or next in the calling thread)

"any outstanding deferred vector length change" is ambiguous. (it may be for all threads in a process or in the calling thread only)

Quoted 15 lines
(quoted diff) +15 -0
+    Return value: a nonnegative on success, or a negative value on error:
+	EINVAL: SVE not supported, invalid vector length requested, or
+	    invalid flags.
+
+    On success, the calling thread's vector length is changed to the largest
+    value supported by the system that is less than or equal to vl.
+    If vl == SVE_VL_MAX, the calling thread's vector length is changed to the
+    largest value supported by the system.
+
+    The returned value describes the resulting configuration, encoded as for
+    PR_SVE_GET_VL.  The vector length reported in this value is the new current
+    vector length for this thread if PR_SVE_SET_VL_ONEXEC was not passed in the
+    input arg; otherwise, the reported vector length is the deferred vector
+    length that will be applied at the next exec.
+

...

Quoted 11 lines

Review

Quoted 9 lines

+9. System runtime configuration
+--------------------------------

(quoted diff) +7 -0
+
+* To mitigate the ABI impact of expansion of the signal frame, a policy
+  mechanism is provided for administrators, distro maintainers and developers
+  to set the default vector length for userspace processes:
+
+/proc/cpu/sve_default_vector_length
+

still wrong.

Dang, sorry, I was focusing on the code and completely missed these documentation changes.

The text actually leaves a fair amount to be desired in some places, now I look again at it.

How does this look:

Documentation/arm64/sve.txt +45 -21
index 2e8f009..27b8833 100644
@@ -75,6 +75,15 @@ the SVE instruction set architecture.
   assumptions about this.  The kernel behaviour may vary on a case-by-case
   basis.
 
+* All other SVE state of a thread, including the currently configured vector
+  length, the state of the PR_SVE_VL_INHERIT flag, and the deferred vector
+  length (if any), is preserved across all syscalls, subject to the specific
+  exceptions for execve() described in section 6.
+
+  In particular, on return from a fork() or clone(), the parent and new child
+  process or thread share identical SVE configuration, matching that of the
+  parent before the call.
+
 
 4.  Signal handling
 -------------------
@@ -136,7 +145,7 @@ length:
 prctl(PR_SVE_SET_VL, unsigned long arg)
 
     Sets the vector length of the calling thread and related flags, where
-    arg == vl | flags.
+    arg == vl | flags.  Other threads of the calling process are unaffected.
 
     vl is the desired vector length, where sve_vl_valid(vl) must be true.
 
@@ -150,36 +159,51 @@ prctl(PR_SVE_SET_VL, unsigned long arg)
 
 	PR_SVE_SET_VL_ONEXEC
 
-	    Defer the requested vector length change until the next execve().
+	    Defer the requested vector length change until the next execve()
+	    performed by this thread.
+
+	    The effect is equivalent to implicit exceution of the following
+	    call immediately after the next execve() (if any) by the thread:
+
+		prctl(PR_SVE_SET_VL, arg & ~PR_SVE_SET_VL_ONEXEC)
+
 	    This allows launching of a new program with a different vector
 	    length, while avoiding runtime side effects in the caller.
 
-	    This also overrides the effect of PR_SVE_SET_VL_INHERIT for the
-	    first execve().
 
-	    Without PR_SVE_SET_VL_ONEXEC, any outstanding deferred vector
-	    length change is cancelled.
+	    Without PR_SVE_SET_VL_ONEXEC, the requested change takes effect
+	    immediately.
+
 
     Return value: a nonnegative on success, or a negative value on error:
 	EINVAL: SVE not supported, invalid vector length requested, or
 	    invalid flags.
 
-    On success, the calling thread's vector length is changed to the largest
-    value supported by the system that is less than or equal to vl.
-    If vl == SVE_VL_MAX, the calling thread's vector length is changed to the
-    largest value supported by the system.
 
-    The returned value describes the resulting configuration, encoded as for
-    PR_SVE_GET_VL.  The vector length reported in this value is the new current
-    vector length for this thread if PR_SVE_SET_VL_ONEXEC was not passed in the
-    input arg; otherwise, the reported vector length is the deferred vector
-    length that will be applied at the next exec.
+    On success:
+
+    * Either the calling thread's vector length or the deferred vector length
+      to be applied at the next execve() by the thread (dependent on whether
+      PR_SVE_SET_VL_ONEXEC is present in arg), is set to the largest value
+      supported by the system that is less than or equal to vl.  If vl ==
+      SVE_VL_MAX, the value set will be the largest value supported by the
+      system.
+
+    * Any previously outstanding deferred vector length change in the calling
+      thread is cancelled.
+
+    * The returned value describes the resulting configuration, encoded as for
+      PR_SVE_GET_VL.  The vector length reported in this value is the new
+      current vector length for this thread if PR_SVE_SET_VL_ONEXEC was not
+      present in arg; otherwise, the reported vector length is the deferred
+      vector length that will be applied at the next execve() by the calling
+      thread.
 
-    Changing the vector length causes all of P0..P15, FFR and all bits of
-    Z0..V31 except for Z0 bits [127:0] .. Z31 bits [127:0] to become
-    unspecified.  Calling PR_SVE_SET_VL with vl equal to the thread's current
-    vector length does not constitute a change to the vector length for this
-    purpose.
+    * Changing the vector length causes all of P0..P15, FFR and all bits of
+      Z0..V31 except for Z0 bits [127:0] .. Z31 bits [127:0] to become
+      unspecified.  Calling PR_SVE_SET_VL with vl equal to the thread's current
+      vector length, or calling PR_SVE_SET_VL with the PR_SVE_SET_VL_ONEXEC
+      flag, does not constitute a change to the vector length for this purpose.
 
 
 prctl(PR_SVE_GET_VL)
@@ -315,7 +339,7 @@ The regset data starts with struct user_sve_header, containing:
   mechanism is provided for administrators, distro maintainers and developers
   to set the default vector length for userspace processes:
 
-/proc/cpu/sve_default_vector_length
+/proc/sys/abi/sve_default_vector_length
 
     Writing the text representation of an integer to this file sets the system
     default vector length to the specified value, unless the value is greater

A message that is not in the archive (sent off-list or not yet received): 20171011110811.GB19485-M5GwZQ6tE7x5pKCnmE3YQBJ8xKzm50AiAL8bYrjMMd8@public.gmane.org

#102 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

Quoted 2 lines · Dave Martin

How does this look:

looks reasonable.

maintainer
#103 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

In reply to Dave Martin
Quoted 11 lines · Dave P Martin

+4. Signal handling
+-------------------

Documentation/arm64/sve.txt new file +9 -0
+
+* A new signal frame record sve_context encodes the SVE registers on signal
+  delivery. [1]
+
+* This record is supplementary to fpsimd_context.  The FPSR and FPCR registers
+  are only present in fpsimd_context.  For convenience, the content of V0..V31
+  is duplicated between sve_context and fpsimd_context.
+
+* The signal frame record for SVE always contains basic metadata, in particular

Documentation/arm64/sve.txt line 99

Quoted 10 lines
Documentation/arm64/sve.txt new file +10 -0
+  the thread's vector length (in sve_context.vl).
+
+* The SVE registers may or may not be included in the record, depending on
+  whether the registers are live for the thread.  The registers are present if
+  and only if:
+  sve_context.head.size >= SVE_SIG_CONTEXT_SIZE(sve_vq_from_vl(sve_context.vl)).
+
+* If the registers are present, the remainder of the record has a vl-dependent
+  size and layout.  Macros SIG_SVE_* are defined [1] to facilitate access to
+  the members.

s/SIG_SVE_/SVE_SIG_/

Documentation/arm64/sve.txt line 104

Quoted 5 lines
Documentation/arm64/sve.txt new file +5 -0
+
+* If the SVE context is too big to fit in sigcontext.__reserved[], then extra
+  space is allocated on the stack, an extra_context record is written in
+  __reserved[] referencing this space.  sve_context is then written in the
+  extra space.  Refer to [1] for further details about this mechanism.

Does this document require that the user stack is sufficiently large or should we cap the vector length (prior to the last two RFC patches)?

Quoted 9 lines
Documentation/arm64/sve.txt new file +9 -0
+
+
+5.  Signal return
+-----------------
+
+When returning from a signal handler:
+
+* If there is no sve_context record in the signal frame, or if the record is
+  present but contains no register data as desribed in the previous section,

Documentation/arm64/sve.txt line 123

Quoted 10 lines
Documentation/arm64/sve.txt new file +10 -0
+  then the SVE registers/bits become non-live and take unspecified values.
+
+* If sve_context is present in the signal frame and contains full register
+  data, the SVE registers become live and are populated with the specified
+  data.  However, for backward compatibility reasons, bits [127:0] of Z0..Z31
+  are always restored from the corresponding members of fpsimd_context.vregs[]
+  and not from sve_context.  The remaining bits are restored from sve_context.
+
+* Inclusion of fpsimd_context in the signal frame remains mandatory,
+  irrespective of whether sve_context is present or not.

Could we relax this? I'm not sure it's worth it.

Signature · 1 line
Catalin
#104 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

Quoted 16 lines · Catalin Marinas
Quoted 15 lines · Dave P Martin

+4. Signal handling
+-------------------

Documentation/arm64/sve.txt new file +13 -0
+
+* A new signal frame record sve_context encodes the SVE registers on signal
+  delivery. [1]
+
+* This record is supplementary to fpsimd_context.  The FPSR and FPCR registers
+  are only present in fpsimd_context.  For convenience, the content of V0..V31
+  is duplicated between sve_context and fpsimd_context.
+
+* The signal frame record for SVE always contains basic metadata, in particular
+  the thread's vector length (in sve_context.vl).
+
+* The SVE registers may or may not be included in the record, depending on
+  whether the registers are live for the thread.  The registers are present if
Quoted 8 lines

Documentation/arm64/sve.txt line 99

Quoted 6 lines
Documentation/arm64/sve.txt new file +6 -0
+  and only if:
+  sve_context.head.size >= SVE_SIG_CONTEXT_SIZE(sve_vq_from_vl(sve_context.vl)).
+
+* If the registers are present, the remainder of the record has a vl-dependent
+  size and layout.  Macros SIG_SVE_* are defined [1] to facilitate access to
+  the members.

s/SIG_SVE_/SVE_SIG_/

Oops, good spot. Fixed.

Quoted 7 lines

Documentation/arm64/sve.txt line 104

Quoted 4 lines
Documentation/arm64/sve.txt new file +4 -0
+* If the SVE context is too big to fit in sigcontext.__reserved[], then extra
+  space is allocated on the stack, an extra_context record is written in
+  __reserved[] referencing this space.  sve_context is then written in the
+  extra space.  Refer to [1] for further details about this mechanism.

Does this document require that the user stack is sufficiently large or should we cap the vector length (prior to the last two RFC patches)?

We don't know how much free stack space there actually is until the signal is delivered.

If the initial user stack at process startup is <8K the user process has more serious problems than can be solved by clamping the vector length.

After process startup we are committed to some VL, and silently clamping it at signal delivery time is a potential programmer's model / ABI break ... there would be no guaranteed way to return from the signal handler successfully. That may not be what you meant though ...?

In the sigaltstack() case we do know how much space there is in advance, but at the time of a sigaltstack() call if any, we may be still be committed to some VL. The thread is allowed to assume the VL is unchanged across syscalls even though the SVE register data is not guaranteed to be preserved.

Possibly sigaltstack() should fail with ENOMEM if ss_size is too small for the maximum VL supported by the system, but strictly speaking that violates POSIX if ss_size >= MINSIGSTKSZ. Also, knowing that the stack is big enough for the kernel-generated still doesn't guarantee that the handler's own stack needs are satisfied, so this check is of limited use.

So, my current policy is an extension of the existing one: the stack must have enough space for the signal frame, or attempted signal delivery will SEGV the task -- the kernel doesn't try to work around this in advance.

This isn't fantastic, but I haven't come up with a better answer so far. I'm open to ideas :)

Quoted 13 lines
Quoted 13 lines
Documentation/arm64/sve.txt new file +13 -0
+
+
+5.  Signal return
+-----------------
+
+When returning from a signal handler:
+
+* If there is no sve_context record in the signal frame, or if the record is
+  present but contains no register data as desribed in the previous section,
+  then the SVE registers/bits become non-live and take unspecified values.
+
+* If sve_context is present in the signal frame and contains full register
+  data, the SVE registers become live and are populated with the specified
Quoted 8 lines

Documentation/arm64/sve.txt line 123

Quoted 6 lines
Documentation/arm64/sve.txt new file +6 -0
+  data.  However, for backward compatibility reasons, bits [127:0] of Z0..Z31
+  are always restored from the corresponding members of fpsimd_context.vregs[]
+  and not from sve_context.  The remaining bits are restored from sve_context.
+
+* Inclusion of fpsimd_context in the signal frame remains mandatory,
+  irrespective of whether sve_context is present or not.

Could we relax this? I'm not sure it's worth it.

It would be cleaner, but I think it's an ABI break. Consider a non-SVE program that gets linked (perhaps dynamically) against a library variant that happens to use SVE:

void segv_handler(...)

{
	/* examine signal frame FPSIMD_MAGIC to print a crash dump */
}

void f(double d, double *p)

{
	some_library_function_that_uses_sve_internally();
	*p = d;
}

segv_handler() could previously safely assume that the FPSIMD_MAGIC block was present in the frame and may now just crash or print garbage if this block isn't found. But even if it does fail safe, functionality is lost -- the crash dump cannot now include the value of d becuase the non-SVE- aware main program doesn't know how to fish it out of the signal frame.

I would be all in favour of getting rid of FPSIMD_MAGIC in this instance and avoiding the duplication and awkward sigreturn semantics, but I don't see how we would get away with it without breaking existing software.

Cheers
---Dave

A message that is not in the archive (sent off-list or not yet received): 20171013171758.GO19485-M5GwZQ6tE7x5pKCnmE3YQBJ8xKzm50AiAL8bYrjMMd8@public.gmane.org

#106 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

Quoted 12 lines · Dave P Martin
Quoted 8 lines · Catalin Marinas

Documentation/arm64/sve.txt line 104

Quoted 4 lines · Dave P Martin
Documentation/arm64/sve.txt new file +4 -0
+* If the SVE context is too big to fit in sigcontext.__reserved[], then extra
+  space is allocated on the stack, an extra_context record is written in
+  __reserved[] referencing this space.  sve_context is then written in the
+  extra space.  Refer to [1] for further details about this mechanism.

Does this document require that the user stack is sufficiently large or should we cap the vector length (prior to the last two RFC patches)?

We don't know how much free stack space there actually is until the signal is delivered.

[...]

Quoted 3 lines

Possibly sigaltstack() should fail with ENOMEM if ss_size is too small for the maximum VL supported by the system, but strictly speaking that violates POSIX if ss_size >= MINSIGSTKSZ.

We also don't know whether the application is going to use SVE or not, so MINSIGSTKSZ could be just fine. I don't have a better idea here without the last two RFC patches. So just ignore my comment.

Quoted 20 lines
Quoted 11 lines
Quoted 11 lines

+5. Signal return
+-----------------

Documentation/arm64/sve.txt new file +9 -0
+
+When returning from a signal handler:
+
+* If there is no sve_context record in the signal frame, or if the record is
+  present but contains no register data as desribed in the previous section,
+  then the SVE registers/bits become non-live and take unspecified values.
+
+* If sve_context is present in the signal frame and contains full register
+  data, the SVE registers become live and are populated with the specified
Quoted 8 lines

Documentation/arm64/sve.txt line 123

Quoted 6 lines
Documentation/arm64/sve.txt new file +6 -0
+  data.  However, for backward compatibility reasons, bits [127:0] of Z0..Z31
+  are always restored from the corresponding members of fpsimd_context.vregs[]
+  and not from sve_context.  The remaining bits are restored from sve_context.
+
+* Inclusion of fpsimd_context in the signal frame remains mandatory,
+  irrespective of whether sve_context is present or not.

Could we relax this? I'm not sure it's worth it.

Quoted 3 lines

It would be cleaner, but I think it's an ABI break. Consider a non-SVE program that gets linked (perhaps dynamically) against a library variant that happens to use SVE:

I agree that in general the kernel always needs to provide user space with FPSIMD_MAGIC. I was wondering whether on sigreturn the kernel may choose not to enforce this. But I'm not sure we have a scenario where it actually matters (IIUC set/getcontext is done in user space anyway).

Signature · 1 line
Catalin

A message that is not in the archive (sent off-list or not yet received): 20171013142421.j32jzisukewxtosx-+1aNUgJU5qkijLcmloz0ER/[email protected]

#108 lore raw

Re: [PATCH v3 26/28] arm64/sve: Add documentation

Quoted 1 line · Catalin Marinas

On Tue, Oct 10, 2017 at 07:38:43PM +0100, Dave P Martin wrote:

[...]

Quoted 7 lines

Documentation/arm64/sve.txt line 104

Quoted 4 lines
Documentation/arm64/sve.txt new file +4 -0
+* If the SVE context is too big to fit in sigcontext.__reserved[], then extra
+  space is allocated on the stack, an extra_context record is written in
+  __reserved[] referencing this space.  sve_context is then written in the
+  extra space.  Refer to [1] for further details about this mechanism.

Does this document require that the user stack is sufficiently large or should we cap the vector length (prior to the last two RFC patches)?

Oh, I think I missed your point here.

I don't think it's worth capping the vector length beyond what the series alread does: the last two patches provide a way to find out how big the signal frame could be, but software still needs porting either way if it enables large vectors via prctl or ptrace.

Conversely, software basing its stack allocations on SIGSTKSZ (16K) will probably get away with it: this seems to be the common choice when allocating stacks. Apart from models, we're not likely to see SVE implementations with huge vector lengths for a while yet.

In any case, /proc/sys/abi/sve_default_vector_length proves a discretionary global clamp that can be set by the distro or admin. This will prevent programs from seeing large frames unless the VL is set explicitly to something > 64 bytes via prctl/ptrace (which current software won't do).

[...]

Cheers
---Dave

#109 lore raw

RFC PATCH v3 27/28 arm64: signal: Report signal frame size to userspace via auxv

In reply to Dave Martin

Stateful CPU architecture extensions may require the signal frame to grow to a size that exceeds the arch's MINSIGSTKSZ #define. However, changing this #define is an ABI break.

To allow userspace the option of determining the signal frame size in a more forwards-compatible way, this patch adds a new auxv entry tagged with AT_MINSIGSTKSZ, which provides the maximum signal frame size that the process can observe during its lifetime.

If AT_MINSIGSTKSZ is absent from the aux vector, the caller can assume that the MINSIGSTKSZ #define is sufficient. This allows for a consistent interface with older kernels that do not provide AT_MINSIGSTKSZ.

The idea is that libc could expose this via sysconf() or some similar mechanism.

There is deliberately no AT_SIGSTKSZ. The kernel knows nothing about userspace's own stack overheads and should not pretend to know.

For arm64:

The primary motivation for this interface is the Scalable Vector Extension, which can require at least 4KB or so of extra space in the signal frame for the largest hardware implementations.

To determine the correct value, a "Christmas tree" mode (via the add_all argument) is added to setup_sigframe_layout(), to simulate addition of all possible records to the signal frame at maximum possible size.

If this procedure goes wrong somehow, resulting in a stupidly large frame layout and hence failure of sigframe_alloc() to allocate a record to the frame, then this is indicative of a kernel bug: the kernel's internal SIGFRAME_MAXSZ is supposed to sanity-check against generting frames that we consider _impossibly_ large. In this case, SIGSTKSZ is returned as a "reasonable guess that is at least bigger than MINSIGSTKSZ" and we WARN().

---
 arch/arm64/include/asm/elf.h         |  5 +++++
 arch/arm64/include/asm/processor.h   |  3 +++
 arch/arm64/include/uapi/asm/auxvec.h |  3 ++-
 arch/arm64/kernel/signal.c           | 39 +++++++++++++++++++++++++++++++-----
 4 files changed, 44 insertions(+), 6 deletions(-)
arch/arm64/include/asm/elf.h +5 -0
index 33be513..8a2708a 100644
@@ -24,6 +24,10 @@
 #include <asm/ptrace.h>
 #include <asm/user.h>
 
+#ifndef __ASSEMBLY__
+#include <asm/processor.h> /* for get_minsigstksz(), used by ARCH_DLINFO */
+#endif
+
 /*
  * AArch64 static relocation types.
  */
@@ -148,6 +152,7 @@ typedef struct user_fpsimd_state elf_fpregset_t;
 do {									\
 	NEW_AUX_ENT(AT_SYSINFO_EHDR,					\
 		    (elf_addr_t)current->mm->context.vdso);		\
+	NEW_AUX_ENT(AT_MINSIGSTKSZ, get_minsigstksz());			\
 } while (0)
 
 #define ARCH_HAS_SETUP_ADDITIONAL_PAGES
arch/arm64/include/asm/processor.h +3 -0
index df66452..18af4bd 100644
@@ -197,6 +197,9 @@ static inline void spin_lock_prefetch(const void *ptr)
 int cpu_enable_pan(void *__unused);
 int cpu_enable_cache_maint_trap(void *__unused);
 
+/* User signal frame size discovery: */
+int get_minsigstksz(void);
+
 /* Userspace interface for PR_SVE_{SET,GET}_VL prctl()s: */
 #define SVE_SET_VL(arg)	sve_set_current_vl(arg)
 #define SVE_GET_VL()	sve_get_current_vl()
arch/arm64/include/uapi/asm/auxvec.h +2 -1
index 4cf0c17..1d45b28 100644
@@ -18,7 +18,8 @@
 
 /* vDSO location */
 #define AT_SYSINFO_EHDR	33
+#define AT_MINSIGSTKSZ	34	/* stack needed for signal delivery */
 
-#define AT_VECTOR_SIZE_ARCH 1 /* entries in ARCH_DLINFO */
+#define AT_VECTOR_SIZE_ARCH 2 /* entries in ARCH_DLINFO */
 
 #endif
arch/arm64/kernel/signal.c +34 -5
index 0d7a71e..3382e87 100644
@@ -567,8 +567,15 @@ asmlinkage long sys_rt_sigreturn(struct pt_regs *regs)
 	return 0;
 }
 
-/* Determine the layout of optional records in the signal frame */
-static int setup_sigframe_layout(struct rt_sigframe_user_layout *user)
+/*
+ * Determine the layout of optional records in the signal frame
+ *
+ * add_all: if true, lays out the biggest possible signal frame for
+ *	this task; otherwise, generates a layout for the current state
+ *	of the task.
+ */
+static int setup_sigframe_layout(struct rt_sigframe_user_layout *user,
+				 bool add_all)
 {
 	int err;
 
@@ -578,7 +585,7 @@ static int setup_sigframe_layout(struct rt_sigframe_user_layout *user)
 		return err;
 
 	/* fault information, if valid */
-	if (current->thread.fault_code) {
+	if (add_all || current->thread.fault_code) {
 		err = sigframe_alloc(user, &user->esr_offset,
 				     sizeof(struct esr_context));
 		if (err)
@@ -600,7 +607,6 @@ static int setup_sigframe_layout(struct rt_sigframe_user_layout *user)
 	return sigframe_alloc_end(user);
 }
 
-
 static int setup_sigframe(struct rt_sigframe_user_layout *user,
 			  struct pt_regs *regs, sigset_t *set)
 {
@@ -698,7 +704,7 @@ static int get_sigframe(struct rt_sigframe_user_layout *user,
 	int err;
 
 	init_user_layout(user);
-	err = setup_sigframe_layout(user);
+	err = setup_sigframe_layout(user, false);
 	if (err)
 		return err;
 
@@ -936,3 +942,26 @@ asmlinkage void do_notify_resume(struct pt_regs *regs,
 		thread_flags = READ_ONCE(current_thread_info()->flags);
 	} while (thread_flags & _TIF_WORK_MASK);
 }
+
+/*
+ * Determine the stack space required for guaranteed signal devliery.
+ * This function is used to populate AT_MINSIGSTKSZ at process startup.
+ */
+int get_minsigstksz(void)
+{
+	struct rt_sigframe_user_layout user;
+	int err;
+
+	init_user_layout(&user);
+	err = setup_sigframe_layout(&user, true);
+
+	if (err) {
+		WARN_ON(1);
+
+		return SIGSTKSZ;
+	} else {
+		return sigframe_size(&user) +
+			round_up(sizeof(struct frame_record), 16) +
+			16; /* max alignment padding */
+	}
+}
Signature · 1 line
2.1.4
#110 lore raw

Re: [RFC PATCH v3 27/28] arm64: signal: Report signal frame size to userspace via auxv

Quoted 9 lines · Dave Martin

Stateful CPU architecture extensions may require the signal frame to grow to a size that exceeds the arch's MINSIGSTKSZ #define. However, changing this #define is an ABI break.

To allow userspace the option of determining the signal frame size in a more forwards-compatible way, this patch adds a new auxv entry tagged with AT_MINSIGSTKSZ, which provides the maximum signal frame size that the process can observe during its lifetime.

Quoted 5 lines

If AT_MINSIGSTKSZ is absent from the aux vector, the caller can assume that the MINSIGSTKSZ #define is sufficient. This allows for a consistent interface with older kernels that do not provide AT_MINSIGSTKSZ.

the posix sigaltstack api shall fail with ENOMEM if smaller than MINSIGSTKSZ stack size is used.

so it is important to note somewhere if AT_MINSIGSTKSZ is intended to be always >= MINSIGSTKSZ define (which is rounded up to 5k) or it may be smaller as it provides the precise value of the largest signal frame.

(i think it makes sense for it to be a precise value, but then users should do the >= check before calling the sigaltstack api, so they should be aware of this issue)

#111 lore raw

Re: [RFC PATCH v3 27/28] arm64: signal: Report signal frame size to userspace via auxv

Quoted 24 lines · Szabolcs Nagy
Quoted 9 lines · Dave Martin

Stateful CPU architecture extensions may require the signal frame to grow to a size that exceeds the arch's MINSIGSTKSZ #define. However, changing this #define is an ABI break.

To allow userspace the option of determining the signal frame size in a more forwards-compatible way, this patch adds a new auxv entry tagged with AT_MINSIGSTKSZ, which provides the maximum signal frame size that the process can observe during its lifetime.

Quoted 5 lines

If AT_MINSIGSTKSZ is absent from the aux vector, the caller can assume that the MINSIGSTKSZ #define is sufficient. This allows for a consistent interface with older kernels that do not provide AT_MINSIGSTKSZ.

the posix sigaltstack api shall fail with ENOMEM if smaller than MINSIGSTKSZ stack size is used.

so it is important to note somewhere if AT_MINSIGSTKSZ is intended to be always >= MINSIGSTKSZ define (which is rounded up to 5k) or it may be smaller as it provides the precise value of the largest signal frame.

Quoted 4 lines

(i think it makes sense for it to be a precise value, but then users should do the >= check before calling the sigaltstack api, so they should be aware of this issue)

This is a good point, and one that I don't have an answer for yet.

POSIX[1] says that sigaltstack() _shall_ return EPERM if ss_size < MINSIGSTKSZ.

I don't know the full rationale behind this.

The ENOMEM return here doesn't guarantee that signal delivery will definitely fail or compromise safety when ss_size or less of stack is available.

A 0 return doesn't guarantee that signal delivery on the registered alternate stack will succeed or be safe.

So while the ENOMEM return has some sanity-check value, it's very limited in its usefulness.

I currently saw no good reason to misrepresent the true signal frame size in AT_MINSIGSTKSZ, so it is currently a precise value that can be < MINSIGSTKSZ (and is, in the default case).

In an ideal world, my preference would be to relax the check in sigaltstack() to check >= AT_MINSIGSTKSZ, but it is technically an ABI break...

We _could_ paper over this by rounding up the AT_MINSIGSTKSZ value reported by the kernel to be always >= MINSIGSTKSZ. This seems ugly, but may be the most pragmatic option.

Thoughts?

Cheers
---Dave

[1] SUSv7 / IEEE Std 1003.1-2008 (2016): sigaltstack
http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaltstack.html

#112 lore raw

RFC PATCH v3 28/28 arm64/sve: signal: Include SVE when computing AT_MINSIGSTKSZ

In reply to Dave Martin

The SVE context block in the signal frame needs to be considered too when computing the maximum possible signal frame size.

Because the size of this block depends on the vector length, this patch computes the size based not on the thread's current vector length but instead on the maximum possible vector length: this determines the maximum size of SVE context block that can be observed in any signal frame for the lifetime of the process.

Cc Ard Biesheuvel <[email protected]>
Cc Alex Bennée <[email protected]>
---
 arch/arm64/kernel/signal.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
arch/arm64/kernel/signal.c +12 -2
index 3382e87..15bc2ad 100644
@@ -595,8 +595,18 @@ static int setup_sigframe_layout(struct rt_sigframe_user_layout *user,
 	if (system_supports_sve()) {
 		unsigned int vq = 0;
 
-		if (test_thread_flag(TIF_SVE))
-			vq = sve_vq_from_vl(current->thread.sve_vl);
+		if (add_all || test_thread_flag(TIF_SVE)) {
+			int vl = sve_max_vl;
+
+			if (!add_all)
+				vl = current->thread.sve_vl;
+
+			/* Fail safe if something wasn't initialised */
+			if (WARN_ON(!sve_vl_valid(vl)))
+				vl = SVE_VL_MIN;
+
+			vq = sve_vq_from_vl(vl);
+		}
 
 		err = sigframe_alloc(user, &user->sve_offset,
 				     SVE_SIG_CONTEXT_SIZE(vq));
Signature · 1 line
2.1.4