[PATCH 3.16 53/76] x86: Implement array_index_mask_nospec
From: Ben Hutchings
Date: Sun Mar 11 2018 - 23:28:58 EST
3.16.56-rc1 review patch. If anyone has any objections, please let me know.
------------------
From: Dan Williams <dan.j.williams@xxxxxxxxx>
commit babdde2698d482b6c0de1eab4f697cf5856c5859 upstream.
array_index_nospec() uses a mask to sanitize user controllable array
indexes, i.e. generate a 0 mask if 'index' >= 'size', and a ~0 mask
otherwise. While the default array_index_mask_nospec() handles the
carry-bit from the (index - size) result in software.
The x86 array_index_mask_nospec() does the same, but the carry-bit is
handled in the processor CF flag without conditional instructions in the
control flow.
Suggested-by: Linus Torvalds <torvalds@xxxxxxxxxxxxxxxxxxxx>
Signed-off-by: Dan Williams <dan.j.williams@xxxxxxxxx>
Signed-off-by: Thomas Gleixner <tglx@xxxxxxxxxxxxx>
Cc: linux-arch@xxxxxxxxxxxxxxx
Cc: kernel-hardening@xxxxxxxxxxxxxxxxxx
Cc: gregkh@xxxxxxxxxxxxxxxxxxx
Cc: alan@xxxxxxxxxxxxxxx
Link: https://lkml.kernel.org/r/151727414808.33451.1873237130672785331.stgit@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[bwh: Backported to 3.16: adjust context]
Signed-off-by: Ben Hutchings <ben@xxxxxxxxxxxxxxx>
---
arch/x86/include/asm/barrier.h | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
--- a/arch/x86/include/asm/barrier.h
+++ b/arch/x86/include/asm/barrier.h
@@ -25,6 +25,30 @@
#endif
/**
+ * array_index_mask_nospec() - generate a mask that is ~0UL when the
+ * bounds check succeeds and 0 otherwise
+ * @index: array element index
+ * @size: number of elements in array
+ *
+ * Returns:
+ * 0 - (index < size)
+ */
+static inline unsigned long array_index_mask_nospec(unsigned long index,
+ unsigned long size)
+{
+ unsigned long mask;
+
+ asm ("cmp %1,%2; sbb %0,%0;"
+ :"=r" (mask)
+ :"r"(size),"r" (index)
+ :"cc");
+ return mask;
+}
+
+/* Override the default implementation from linux/nospec.h. */
+#define array_index_mask_nospec array_index_mask_nospec
+
+/**
* read_barrier_depends - Flush all pending reads that subsequents reads
* depend on.
*