1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2023 SiFive
4 * Author: Andy Chiu <andy.chiu@sifive.com>
6 #include <linux/export.h>
7 #include <linux/sched/signal.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/sched.h>
11 #include <linux/uaccess.h>
13 #include <asm/thread_info.h>
14 #include <asm/processor.h>
16 #include <asm/vector.h>
19 #include <asm/ptrace.h>
22 unsigned long riscv_v_vsize __read_mostly;
23 EXPORT_SYMBOL_GPL(riscv_v_vsize);
25 int riscv_v_setup_vsize(void)
27 unsigned long this_vsize;
29 /* There are 32 vector registers with vlenb length. */
31 this_vsize = csr_read(CSR_VLENB) * 32;
35 riscv_v_vsize = this_vsize;
39 if (riscv_v_vsize != this_vsize) {
40 WARN(1, "RISCV_ISA_V only supports one vlenb on SMP systems");
47 static bool insn_is_vector(u32 insn_buf)
49 u32 opcode = insn_buf & __INSN_OPCODE_MASK;
53 * All V-related instructions, including CSR operations are 4-Byte. So,
54 * do not handle if the instruction length is not 4-Byte.
56 if (unlikely(GET_INSN_LENGTH(insn_buf) != 4))
60 case RVV_OPCODE_VECTOR:
64 width = RVV_EXRACT_VL_VS_WIDTH(insn_buf);
65 if (width == RVV_VL_VS_WIDTH_8 || width == RVV_VL_VS_WIDTH_16 ||
66 width == RVV_VL_VS_WIDTH_32 || width == RVV_VL_VS_WIDTH_64)
70 case RVG_OPCODE_SYSTEM:
71 csr = RVG_EXTRACT_SYSTEM_CSR(insn_buf);
72 if ((csr >= CSR_VSTART && csr <= CSR_VCSR) ||
73 (csr >= CSR_VL && csr <= CSR_VLENB))
80 static int riscv_v_thread_zalloc(void)
84 datap = kzalloc(riscv_v_vsize, GFP_KERNEL);
88 current->thread.vstate.datap = datap;
89 memset(¤t->thread.vstate, 0, offsetof(struct __riscv_v_ext_state,
94 bool riscv_v_first_use_handler(struct pt_regs *regs)
96 u32 __user *epc = (u32 __user *)regs->epc;
97 u32 insn = (u32)regs->badaddr;
99 /* Do not handle if V is not supported, or disabled */
100 if (!(ELF_HWCAP & COMPAT_HWCAP_ISA_V))
103 /* If V has been enabled then it is not the first-use trap */
104 if (riscv_v_vstate_query(regs))
107 /* Get the instruction */
109 if (__get_user(insn, epc))
113 /* Filter out non-V instructions */
114 if (!insn_is_vector(insn))
117 /* Sanity check. datap should be null by the time of the first-use trap */
118 WARN_ON(current->thread.vstate.datap);
121 * Now we sure that this is a V instruction. And it executes in the
122 * context where VS has been off. So, try to allocate the user's V
123 * context and resume execution.
125 if (riscv_v_thread_zalloc()) {
129 riscv_v_vstate_on(regs);