From eb6f18cc6ee4a3902c373c4bb505c7fcc3450615 Mon Sep 17 00:00:00 2001
From: Cezary Sobczak <cezary.sobczak@3mdeb.com>
Date: Thu, 24 Mar 2022 00:23:14 +0100
Subject: [PATCH] riscv: fix build with binutils 2.38

Original patch:
https://lore.kernel.org/all/YhCvlHomlT2js3uO@ubuntu01/T/

From version 2.38, binutils default to ISA spec version 20191213. This
means that the csr read/write (csrr*/csrw*) instructions and fence.i
instruction has separated from the `I` extension, become two standalone
extensions: Zicsr and Zifencei.

The fix is to specify those extensions explicitely in -march. However as
older binutils version do not support this, we first need to detect
that.

Fixes:
| cache.c: Assembler messages:
| cache.c:12: Error: unrecognized opcode `fence.i'
| arch/riscv/cpu/mtrap.S: Assembler messages:
| arch/riscv/cpu/mtrap.S:65: Error: unrecognized opcode `csrr a0,scause'
| arch/riscv/cpu/mtrap.S:66: Error: unrecognized opcode `csrr a1,sepc'
| arch/riscv/cpu/mtrap.S:67: Error: unrecognized opcode `csrr a2,stval'
| arch/riscv/cpu/mtrap.S:70: Error: unrecognized opcode `csrw sepc,a0'

Signed-off-by: Cezary Sobczak <cezary.sobczak@3mdeb.com>
---
 arch/riscv/Makefile | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/arch/riscv/Makefile b/arch/riscv/Makefile
index 0b80eb8d8645..6b3dc6e514d8 100644
--- a/arch/riscv/Makefile
+++ b/arch/riscv/Makefile
@@ -24,8 +24,16 @@ ifeq ($(CONFIG_CMODEL_MEDANY),y)
 	CMODEL = medany
 endif
 
-ARCH_FLAGS = -march=$(ARCH_BASE)$(ARCH_A)$(ARCH_C) -mabi=$(ABI) \
-	     -mcmodel=$(CMODEL)
+RISCV_MARCH = $(ARCH_BASE)$(ARCH_A)$(ARCH_C)
+
+# Newer binutils versions default to ISA spec version 20191213 which moves some
+# instructions from the I extension to the Zicsr and Zifencei extensions.
+toolchain-need-zicsr-zifencei := $(call cc-option-yn, -mabi=$(ABI) -march=$(RISCV_MARCH)_zicsr_zifencei)
+ifeq ($(toolchain-need-zicsr-zifencei),y)
+	RISCV_MARCH := $(RISCV_MARCH)_zicsr_zifencei
+endif
+
+ARCH_FLAGS = -march=$(RISCV_MARCH) -mabi=$(ABI) -mcmodel=$(CMODEL)
 
 PLATFORM_CPPFLAGS	+= $(ARCH_FLAGS)
 CFLAGS_EFI		+= $(ARCH_FLAGS)
-- 
2.25.1

