xref: /linux/arch/riscv/kernel/cpufeature.c (revision c2a96b7f187fb6a455836d4a6e113947ff11de97)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copied from arch/arm64/kernel/cpufeature.c
4  *
5  * Copyright (C) 2015 ARM Ltd.
6  * Copyright (C) 2017 SiFive
7  */
8 
9 #include <linux/acpi.h>
10 #include <linux/bitmap.h>
11 #include <linux/cpu.h>
12 #include <linux/cpuhotplug.h>
13 #include <linux/ctype.h>
14 #include <linux/log2.h>
15 #include <linux/memory.h>
16 #include <linux/module.h>
17 #include <linux/of.h>
18 #include <asm/acpi.h>
19 #include <asm/alternative.h>
20 #include <asm/cacheflush.h>
21 #include <asm/cpufeature.h>
22 #include <asm/hwcap.h>
23 #include <asm/patch.h>
24 #include <asm/processor.h>
25 #include <asm/sbi.h>
26 #include <asm/vector.h>
27 
28 #define NUM_ALPHA_EXTS ('z' - 'a' + 1)
29 
30 unsigned long elf_hwcap __read_mostly;
31 
32 /* Host ISA bitmap */
33 static DECLARE_BITMAP(riscv_isa, RISCV_ISA_EXT_MAX) __read_mostly;
34 
35 /* Per-cpu ISA extensions. */
36 struct riscv_isainfo hart_isa[NR_CPUS];
37 
38 /**
39  * riscv_isa_extension_base() - Get base extension word
40  *
41  * @isa_bitmap: ISA bitmap to use
42  * Return: base extension word as unsigned long value
43  *
44  * NOTE: If isa_bitmap is NULL then Host ISA bitmap will be used.
45  */
46 unsigned long riscv_isa_extension_base(const unsigned long *isa_bitmap)
47 {
48 	if (!isa_bitmap)
49 		return riscv_isa[0];
50 	return isa_bitmap[0];
51 }
52 EXPORT_SYMBOL_GPL(riscv_isa_extension_base);
53 
54 /**
55  * __riscv_isa_extension_available() - Check whether given extension
56  * is available or not
57  *
58  * @isa_bitmap: ISA bitmap to use
59  * @bit: bit position of the desired extension
60  * Return: true or false
61  *
62  * NOTE: If isa_bitmap is NULL then Host ISA bitmap will be used.
63  */
64 bool __riscv_isa_extension_available(const unsigned long *isa_bitmap, unsigned int bit)
65 {
66 	const unsigned long *bmap = (isa_bitmap) ? isa_bitmap : riscv_isa;
67 
68 	if (bit >= RISCV_ISA_EXT_MAX)
69 		return false;
70 
71 	return test_bit(bit, bmap) ? true : false;
72 }
73 EXPORT_SYMBOL_GPL(__riscv_isa_extension_available);
74 
75 static int riscv_ext_zicbom_validate(const struct riscv_isa_ext_data *data,
76 				     const unsigned long *isa_bitmap)
77 {
78 	if (!riscv_cbom_block_size) {
79 		pr_err("Zicbom detected in ISA string, disabling as no cbom-block-size found\n");
80 		return -EINVAL;
81 	}
82 	if (!is_power_of_2(riscv_cbom_block_size)) {
83 		pr_err("Zicbom disabled as cbom-block-size present, but is not a power-of-2\n");
84 		return -EINVAL;
85 	}
86 	return 0;
87 }
88 
89 static int riscv_ext_zicboz_validate(const struct riscv_isa_ext_data *data,
90 				     const unsigned long *isa_bitmap)
91 {
92 	if (!riscv_cboz_block_size) {
93 		pr_err("Zicboz detected in ISA string, disabling as no cboz-block-size found\n");
94 		return -EINVAL;
95 	}
96 	if (!is_power_of_2(riscv_cboz_block_size)) {
97 		pr_err("Zicboz disabled as cboz-block-size present, but is not a power-of-2\n");
98 		return -EINVAL;
99 	}
100 	return 0;
101 }
102 
103 #define _RISCV_ISA_EXT_DATA(_name, _id, _subset_exts, _subset_exts_size, _validate) {	\
104 	.name = #_name,									\
105 	.property = #_name,								\
106 	.id = _id,									\
107 	.subset_ext_ids = _subset_exts,							\
108 	.subset_ext_size = _subset_exts_size,						\
109 	.validate = _validate								\
110 }
111 
112 #define __RISCV_ISA_EXT_DATA(_name, _id) _RISCV_ISA_EXT_DATA(_name, _id, NULL, 0, NULL)
113 
114 #define __RISCV_ISA_EXT_DATA_VALIDATE(_name, _id, _validate) \
115 			_RISCV_ISA_EXT_DATA(_name, _id, NULL, 0, _validate)
116 
117 /* Used to declare pure "lasso" extension (Zk for instance) */
118 #define __RISCV_ISA_EXT_BUNDLE(_name, _bundled_exts) \
119 	_RISCV_ISA_EXT_DATA(_name, RISCV_ISA_EXT_INVALID, _bundled_exts, \
120 			    ARRAY_SIZE(_bundled_exts), NULL)
121 
122 /* Used to declare extensions that are a superset of other extensions (Zvbb for instance) */
123 #define __RISCV_ISA_EXT_SUPERSET(_name, _id, _sub_exts) \
124 	_RISCV_ISA_EXT_DATA(_name, _id, _sub_exts, ARRAY_SIZE(_sub_exts), NULL)
125 #define __RISCV_ISA_EXT_SUPERSET_VALIDATE(_name, _id, _sub_exts, _validate) \
126 	_RISCV_ISA_EXT_DATA(_name, _id, _sub_exts, ARRAY_SIZE(_sub_exts), _validate)
127 
128 static int riscv_ext_zca_depends(const struct riscv_isa_ext_data *data,
129 				 const unsigned long *isa_bitmap)
130 {
131 	if (__riscv_isa_extension_available(isa_bitmap, RISCV_ISA_EXT_ZCA))
132 		return 0;
133 
134 	return -EPROBE_DEFER;
135 }
136 static int riscv_ext_zcd_validate(const struct riscv_isa_ext_data *data,
137 				  const unsigned long *isa_bitmap)
138 {
139 	if (__riscv_isa_extension_available(isa_bitmap, RISCV_ISA_EXT_ZCA) &&
140 	    __riscv_isa_extension_available(isa_bitmap, RISCV_ISA_EXT_d))
141 		return 0;
142 
143 	return -EPROBE_DEFER;
144 }
145 
146 static int riscv_ext_zcf_validate(const struct riscv_isa_ext_data *data,
147 				  const unsigned long *isa_bitmap)
148 {
149 	if (IS_ENABLED(CONFIG_64BIT))
150 		return -EINVAL;
151 
152 	if (__riscv_isa_extension_available(isa_bitmap, RISCV_ISA_EXT_ZCA) &&
153 	    __riscv_isa_extension_available(isa_bitmap, RISCV_ISA_EXT_f))
154 		return 0;
155 
156 	return -EPROBE_DEFER;
157 }
158 
159 static const unsigned int riscv_zk_bundled_exts[] = {
160 	RISCV_ISA_EXT_ZBKB,
161 	RISCV_ISA_EXT_ZBKC,
162 	RISCV_ISA_EXT_ZBKX,
163 	RISCV_ISA_EXT_ZKND,
164 	RISCV_ISA_EXT_ZKNE,
165 	RISCV_ISA_EXT_ZKR,
166 	RISCV_ISA_EXT_ZKT,
167 };
168 
169 static const unsigned int riscv_zkn_bundled_exts[] = {
170 	RISCV_ISA_EXT_ZBKB,
171 	RISCV_ISA_EXT_ZBKC,
172 	RISCV_ISA_EXT_ZBKX,
173 	RISCV_ISA_EXT_ZKND,
174 	RISCV_ISA_EXT_ZKNE,
175 	RISCV_ISA_EXT_ZKNH,
176 };
177 
178 static const unsigned int riscv_zks_bundled_exts[] = {
179 	RISCV_ISA_EXT_ZBKB,
180 	RISCV_ISA_EXT_ZBKC,
181 	RISCV_ISA_EXT_ZKSED,
182 	RISCV_ISA_EXT_ZKSH
183 };
184 
185 #define RISCV_ISA_EXT_ZVKN	\
186 	RISCV_ISA_EXT_ZVKNED,	\
187 	RISCV_ISA_EXT_ZVKNHB,	\
188 	RISCV_ISA_EXT_ZVKB,	\
189 	RISCV_ISA_EXT_ZVKT
190 
191 static const unsigned int riscv_zvkn_bundled_exts[] = {
192 	RISCV_ISA_EXT_ZVKN
193 };
194 
195 static const unsigned int riscv_zvknc_bundled_exts[] = {
196 	RISCV_ISA_EXT_ZVKN,
197 	RISCV_ISA_EXT_ZVBC
198 };
199 
200 static const unsigned int riscv_zvkng_bundled_exts[] = {
201 	RISCV_ISA_EXT_ZVKN,
202 	RISCV_ISA_EXT_ZVKG
203 };
204 
205 #define RISCV_ISA_EXT_ZVKS	\
206 	RISCV_ISA_EXT_ZVKSED,	\
207 	RISCV_ISA_EXT_ZVKSH,	\
208 	RISCV_ISA_EXT_ZVKB,	\
209 	RISCV_ISA_EXT_ZVKT
210 
211 static const unsigned int riscv_zvks_bundled_exts[] = {
212 	RISCV_ISA_EXT_ZVKS
213 };
214 
215 static const unsigned int riscv_zvksc_bundled_exts[] = {
216 	RISCV_ISA_EXT_ZVKS,
217 	RISCV_ISA_EXT_ZVBC
218 };
219 
220 static const unsigned int riscv_zvksg_bundled_exts[] = {
221 	RISCV_ISA_EXT_ZVKS,
222 	RISCV_ISA_EXT_ZVKG
223 };
224 
225 static const unsigned int riscv_zvbb_exts[] = {
226 	RISCV_ISA_EXT_ZVKB
227 };
228 
229 #define RISCV_ISA_EXT_ZVE64F_IMPLY_LIST	\
230 	RISCV_ISA_EXT_ZVE64X,		\
231 	RISCV_ISA_EXT_ZVE32F,		\
232 	RISCV_ISA_EXT_ZVE32X
233 
234 #define RISCV_ISA_EXT_ZVE64D_IMPLY_LIST	\
235 	RISCV_ISA_EXT_ZVE64F,		\
236 	RISCV_ISA_EXT_ZVE64F_IMPLY_LIST
237 
238 #define RISCV_ISA_EXT_V_IMPLY_LIST	\
239 	RISCV_ISA_EXT_ZVE64D,		\
240 	RISCV_ISA_EXT_ZVE64D_IMPLY_LIST
241 
242 static const unsigned int riscv_zve32f_exts[] = {
243 	RISCV_ISA_EXT_ZVE32X
244 };
245 
246 static const unsigned int riscv_zve64f_exts[] = {
247 	RISCV_ISA_EXT_ZVE64F_IMPLY_LIST
248 };
249 
250 static const unsigned int riscv_zve64d_exts[] = {
251 	RISCV_ISA_EXT_ZVE64D_IMPLY_LIST
252 };
253 
254 static const unsigned int riscv_v_exts[] = {
255 	RISCV_ISA_EXT_V_IMPLY_LIST
256 };
257 
258 static const unsigned int riscv_zve64x_exts[] = {
259 	RISCV_ISA_EXT_ZVE32X,
260 	RISCV_ISA_EXT_ZVE64X
261 };
262 
263 /*
264  * While the [ms]envcfg CSRs were not defined until version 1.12 of the RISC-V
265  * privileged ISA, the existence of the CSRs is implied by any extension which
266  * specifies [ms]envcfg bit(s). Hence, we define a custom ISA extension for the
267  * existence of the CSR, and treat it as a subset of those other extensions.
268  */
269 static const unsigned int riscv_xlinuxenvcfg_exts[] = {
270 	RISCV_ISA_EXT_XLINUXENVCFG
271 };
272 
273 /*
274  * Zc* spec states that:
275  * - C always implies Zca
276  * - C+F implies Zcf (RV32 only)
277  * - C+D implies Zcd
278  *
279  * These extensions will be enabled and then validated depending on the
280  * availability of F/D RV32.
281  */
282 static const unsigned int riscv_c_exts[] = {
283 	RISCV_ISA_EXT_ZCA,
284 	RISCV_ISA_EXT_ZCF,
285 	RISCV_ISA_EXT_ZCD,
286 };
287 
288 /*
289  * The canonical order of ISA extension names in the ISA string is defined in
290  * chapter 27 of the unprivileged specification.
291  *
292  * Ordinarily, for in-kernel data structures, this order is unimportant but
293  * isa_ext_arr defines the order of the ISA string in /proc/cpuinfo.
294  *
295  * The specification uses vague wording, such as should, when it comes to
296  * ordering, so for our purposes the following rules apply:
297  *
298  * 1. All multi-letter extensions must be separated from other extensions by an
299  *    underscore.
300  *
301  * 2. Additional standard extensions (starting with 'Z') must be sorted after
302  *    single-letter extensions and before any higher-privileged extensions.
303  *
304  * 3. The first letter following the 'Z' conventionally indicates the most
305  *    closely related alphabetical extension category, IMAFDQLCBKJTPVH.
306  *    If multiple 'Z' extensions are named, they must be ordered first by
307  *    category, then alphabetically within a category.
308  *
309  * 3. Standard supervisor-level extensions (starting with 'S') must be listed
310  *    after standard unprivileged extensions.  If multiple supervisor-level
311  *    extensions are listed, they must be ordered alphabetically.
312  *
313  * 4. Standard machine-level extensions (starting with 'Zxm') must be listed
314  *    after any lower-privileged, standard extensions.  If multiple
315  *    machine-level extensions are listed, they must be ordered
316  *    alphabetically.
317  *
318  * 5. Non-standard extensions (starting with 'X') must be listed after all
319  *    standard extensions. If multiple non-standard extensions are listed, they
320  *    must be ordered alphabetically.
321  *
322  * An example string following the order is:
323  *    rv64imadc_zifoo_zigoo_zafoo_sbar_scar_zxmbaz_xqux_xrux
324  *
325  * New entries to this struct should follow the ordering rules described above.
326  */
327 const struct riscv_isa_ext_data riscv_isa_ext[] = {
328 	__RISCV_ISA_EXT_DATA(i, RISCV_ISA_EXT_i),
329 	__RISCV_ISA_EXT_DATA(m, RISCV_ISA_EXT_m),
330 	__RISCV_ISA_EXT_DATA(a, RISCV_ISA_EXT_a),
331 	__RISCV_ISA_EXT_DATA(f, RISCV_ISA_EXT_f),
332 	__RISCV_ISA_EXT_DATA(d, RISCV_ISA_EXT_d),
333 	__RISCV_ISA_EXT_DATA(q, RISCV_ISA_EXT_q),
334 	__RISCV_ISA_EXT_SUPERSET(c, RISCV_ISA_EXT_c, riscv_c_exts),
335 	__RISCV_ISA_EXT_SUPERSET(v, RISCV_ISA_EXT_v, riscv_v_exts),
336 	__RISCV_ISA_EXT_DATA(h, RISCV_ISA_EXT_h),
337 	__RISCV_ISA_EXT_SUPERSET_VALIDATE(zicbom, RISCV_ISA_EXT_ZICBOM, riscv_xlinuxenvcfg_exts,
338 					  riscv_ext_zicbom_validate),
339 	__RISCV_ISA_EXT_SUPERSET_VALIDATE(zicboz, RISCV_ISA_EXT_ZICBOZ, riscv_xlinuxenvcfg_exts,
340 					  riscv_ext_zicboz_validate),
341 	__RISCV_ISA_EXT_DATA(zicntr, RISCV_ISA_EXT_ZICNTR),
342 	__RISCV_ISA_EXT_DATA(zicond, RISCV_ISA_EXT_ZICOND),
343 	__RISCV_ISA_EXT_DATA(zicsr, RISCV_ISA_EXT_ZICSR),
344 	__RISCV_ISA_EXT_DATA(zifencei, RISCV_ISA_EXT_ZIFENCEI),
345 	__RISCV_ISA_EXT_DATA(zihintntl, RISCV_ISA_EXT_ZIHINTNTL),
346 	__RISCV_ISA_EXT_DATA(zihintpause, RISCV_ISA_EXT_ZIHINTPAUSE),
347 	__RISCV_ISA_EXT_DATA(zihpm, RISCV_ISA_EXT_ZIHPM),
348 	__RISCV_ISA_EXT_DATA(zimop, RISCV_ISA_EXT_ZIMOP),
349 	__RISCV_ISA_EXT_DATA(zacas, RISCV_ISA_EXT_ZACAS),
350 	__RISCV_ISA_EXT_DATA(zawrs, RISCV_ISA_EXT_ZAWRS),
351 	__RISCV_ISA_EXT_DATA(zfa, RISCV_ISA_EXT_ZFA),
352 	__RISCV_ISA_EXT_DATA(zfh, RISCV_ISA_EXT_ZFH),
353 	__RISCV_ISA_EXT_DATA(zfhmin, RISCV_ISA_EXT_ZFHMIN),
354 	__RISCV_ISA_EXT_DATA(zca, RISCV_ISA_EXT_ZCA),
355 	__RISCV_ISA_EXT_DATA_VALIDATE(zcb, RISCV_ISA_EXT_ZCB, riscv_ext_zca_depends),
356 	__RISCV_ISA_EXT_DATA_VALIDATE(zcd, RISCV_ISA_EXT_ZCD, riscv_ext_zcd_validate),
357 	__RISCV_ISA_EXT_DATA_VALIDATE(zcf, RISCV_ISA_EXT_ZCF, riscv_ext_zcf_validate),
358 	__RISCV_ISA_EXT_DATA_VALIDATE(zcmop, RISCV_ISA_EXT_ZCMOP, riscv_ext_zca_depends),
359 	__RISCV_ISA_EXT_DATA(zba, RISCV_ISA_EXT_ZBA),
360 	__RISCV_ISA_EXT_DATA(zbb, RISCV_ISA_EXT_ZBB),
361 	__RISCV_ISA_EXT_DATA(zbc, RISCV_ISA_EXT_ZBC),
362 	__RISCV_ISA_EXT_DATA(zbkb, RISCV_ISA_EXT_ZBKB),
363 	__RISCV_ISA_EXT_DATA(zbkc, RISCV_ISA_EXT_ZBKC),
364 	__RISCV_ISA_EXT_DATA(zbkx, RISCV_ISA_EXT_ZBKX),
365 	__RISCV_ISA_EXT_DATA(zbs, RISCV_ISA_EXT_ZBS),
366 	__RISCV_ISA_EXT_BUNDLE(zk, riscv_zk_bundled_exts),
367 	__RISCV_ISA_EXT_BUNDLE(zkn, riscv_zkn_bundled_exts),
368 	__RISCV_ISA_EXT_DATA(zknd, RISCV_ISA_EXT_ZKND),
369 	__RISCV_ISA_EXT_DATA(zkne, RISCV_ISA_EXT_ZKNE),
370 	__RISCV_ISA_EXT_DATA(zknh, RISCV_ISA_EXT_ZKNH),
371 	__RISCV_ISA_EXT_DATA(zkr, RISCV_ISA_EXT_ZKR),
372 	__RISCV_ISA_EXT_BUNDLE(zks, riscv_zks_bundled_exts),
373 	__RISCV_ISA_EXT_DATA(zkt, RISCV_ISA_EXT_ZKT),
374 	__RISCV_ISA_EXT_DATA(zksed, RISCV_ISA_EXT_ZKSED),
375 	__RISCV_ISA_EXT_DATA(zksh, RISCV_ISA_EXT_ZKSH),
376 	__RISCV_ISA_EXT_DATA(ztso, RISCV_ISA_EXT_ZTSO),
377 	__RISCV_ISA_EXT_SUPERSET(zvbb, RISCV_ISA_EXT_ZVBB, riscv_zvbb_exts),
378 	__RISCV_ISA_EXT_DATA(zvbc, RISCV_ISA_EXT_ZVBC),
379 	__RISCV_ISA_EXT_SUPERSET(zve32f, RISCV_ISA_EXT_ZVE32F, riscv_zve32f_exts),
380 	__RISCV_ISA_EXT_DATA(zve32x, RISCV_ISA_EXT_ZVE32X),
381 	__RISCV_ISA_EXT_SUPERSET(zve64d, RISCV_ISA_EXT_ZVE64D, riscv_zve64d_exts),
382 	__RISCV_ISA_EXT_SUPERSET(zve64f, RISCV_ISA_EXT_ZVE64F, riscv_zve64f_exts),
383 	__RISCV_ISA_EXT_SUPERSET(zve64x, RISCV_ISA_EXT_ZVE64X, riscv_zve64x_exts),
384 	__RISCV_ISA_EXT_DATA(zvfh, RISCV_ISA_EXT_ZVFH),
385 	__RISCV_ISA_EXT_DATA(zvfhmin, RISCV_ISA_EXT_ZVFHMIN),
386 	__RISCV_ISA_EXT_DATA(zvkb, RISCV_ISA_EXT_ZVKB),
387 	__RISCV_ISA_EXT_DATA(zvkg, RISCV_ISA_EXT_ZVKG),
388 	__RISCV_ISA_EXT_BUNDLE(zvkn, riscv_zvkn_bundled_exts),
389 	__RISCV_ISA_EXT_BUNDLE(zvknc, riscv_zvknc_bundled_exts),
390 	__RISCV_ISA_EXT_DATA(zvkned, RISCV_ISA_EXT_ZVKNED),
391 	__RISCV_ISA_EXT_BUNDLE(zvkng, riscv_zvkng_bundled_exts),
392 	__RISCV_ISA_EXT_DATA(zvknha, RISCV_ISA_EXT_ZVKNHA),
393 	__RISCV_ISA_EXT_DATA(zvknhb, RISCV_ISA_EXT_ZVKNHB),
394 	__RISCV_ISA_EXT_BUNDLE(zvks, riscv_zvks_bundled_exts),
395 	__RISCV_ISA_EXT_BUNDLE(zvksc, riscv_zvksc_bundled_exts),
396 	__RISCV_ISA_EXT_DATA(zvksed, RISCV_ISA_EXT_ZVKSED),
397 	__RISCV_ISA_EXT_DATA(zvksh, RISCV_ISA_EXT_ZVKSH),
398 	__RISCV_ISA_EXT_BUNDLE(zvksg, riscv_zvksg_bundled_exts),
399 	__RISCV_ISA_EXT_DATA(zvkt, RISCV_ISA_EXT_ZVKT),
400 	__RISCV_ISA_EXT_DATA(smaia, RISCV_ISA_EXT_SMAIA),
401 	__RISCV_ISA_EXT_DATA(smstateen, RISCV_ISA_EXT_SMSTATEEN),
402 	__RISCV_ISA_EXT_DATA(ssaia, RISCV_ISA_EXT_SSAIA),
403 	__RISCV_ISA_EXT_DATA(sscofpmf, RISCV_ISA_EXT_SSCOFPMF),
404 	__RISCV_ISA_EXT_DATA(sstc, RISCV_ISA_EXT_SSTC),
405 	__RISCV_ISA_EXT_DATA(svinval, RISCV_ISA_EXT_SVINVAL),
406 	__RISCV_ISA_EXT_DATA(svnapot, RISCV_ISA_EXT_SVNAPOT),
407 	__RISCV_ISA_EXT_DATA(svpbmt, RISCV_ISA_EXT_SVPBMT),
408 	__RISCV_ISA_EXT_DATA(xandespmu, RISCV_ISA_EXT_XANDESPMU),
409 };
410 
411 const size_t riscv_isa_ext_count = ARRAY_SIZE(riscv_isa_ext);
412 
413 static void riscv_isa_set_ext(const struct riscv_isa_ext_data *ext, unsigned long *bitmap)
414 {
415 	if (ext->id != RISCV_ISA_EXT_INVALID)
416 		set_bit(ext->id, bitmap);
417 
418 	for (int i = 0; i < ext->subset_ext_size; i++) {
419 		if (ext->subset_ext_ids[i] != RISCV_ISA_EXT_INVALID)
420 			set_bit(ext->subset_ext_ids[i], bitmap);
421 	}
422 }
423 
424 static const struct riscv_isa_ext_data *riscv_get_isa_ext_data(unsigned int ext_id)
425 {
426 	for (int i = 0; i < riscv_isa_ext_count; i++) {
427 		if (riscv_isa_ext[i].id == ext_id)
428 			return &riscv_isa_ext[i];
429 	}
430 
431 	return NULL;
432 }
433 
434 /*
435  * "Resolve" a source ISA bitmap into one that matches kernel configuration as
436  * well as correct extension dependencies. Some extensions depends on specific
437  * kernel configuration to be usable (V needs CONFIG_RISCV_ISA_V for instance)
438  * and this function will actually validate all the extensions provided in
439  * source_isa into the resolved_isa based on extensions validate() callbacks.
440  */
441 static void __init riscv_resolve_isa(unsigned long *source_isa,
442 				     unsigned long *resolved_isa, unsigned long *this_hwcap,
443 				     unsigned long *isa2hwcap)
444 {
445 	bool loop;
446 	const struct riscv_isa_ext_data *ext;
447 	DECLARE_BITMAP(prev_resolved_isa, RISCV_ISA_EXT_MAX);
448 	int max_loop_count = riscv_isa_ext_count, ret;
449 	unsigned int bit;
450 
451 	do {
452 		loop = false;
453 		if (max_loop_count-- < 0) {
454 			pr_err("Failed to reach a stable ISA state\n");
455 			return;
456 		}
457 		bitmap_copy(prev_resolved_isa, resolved_isa, RISCV_ISA_EXT_MAX);
458 		for_each_set_bit(bit, source_isa, RISCV_ISA_EXT_MAX) {
459 			ext = riscv_get_isa_ext_data(bit);
460 			if (!ext)
461 				continue;
462 
463 			if (ext->validate) {
464 				ret = ext->validate(ext, resolved_isa);
465 				if (ret == -EPROBE_DEFER) {
466 					loop = true;
467 					continue;
468 				} else if (ret) {
469 					/* Disable the extension entirely */
470 					clear_bit(ext->id, source_isa);
471 					continue;
472 				}
473 			}
474 
475 			set_bit(ext->id, resolved_isa);
476 			/* No need to keep it in source isa now that it is enabled */
477 			clear_bit(ext->id, source_isa);
478 
479 			/* Single letter extensions get set in hwcap */
480 			if (ext->id < RISCV_ISA_EXT_BASE)
481 				*this_hwcap |= isa2hwcap[ext->id];
482 		}
483 	} while (loop && memcmp(prev_resolved_isa, resolved_isa, sizeof(prev_resolved_isa)));
484 }
485 
486 static void __init match_isa_ext(const char *name, const char *name_end, unsigned long *bitmap)
487 {
488 	for (int i = 0; i < riscv_isa_ext_count; i++) {
489 		const struct riscv_isa_ext_data *ext = &riscv_isa_ext[i];
490 
491 		if ((name_end - name == strlen(ext->name)) &&
492 		    !strncasecmp(name, ext->name, name_end - name)) {
493 			riscv_isa_set_ext(ext, bitmap);
494 			break;
495 		}
496 	}
497 }
498 
499 static void __init riscv_parse_isa_string(const char *isa, unsigned long *bitmap)
500 {
501 	/*
502 	 * For all possible cpus, we have already validated in
503 	 * the boot process that they at least contain "rv" and
504 	 * whichever of "32"/"64" this kernel supports, and so this
505 	 * section can be skipped.
506 	 */
507 	isa += 4;
508 
509 	while (*isa) {
510 		const char *ext = isa++;
511 		const char *ext_end = isa;
512 		bool ext_err = false;
513 
514 		switch (*ext) {
515 		case 's':
516 			/*
517 			 * Workaround for invalid single-letter 's' & 'u' (QEMU).
518 			 * No need to set the bit in riscv_isa as 's' & 'u' are
519 			 * not valid ISA extensions. It works unless the first
520 			 * multi-letter extension in the ISA string begins with
521 			 * "Su" and is not prefixed with an underscore.
522 			 */
523 			if (ext[-1] != '_' && ext[1] == 'u') {
524 				++isa;
525 				ext_err = true;
526 				break;
527 			}
528 			fallthrough;
529 		case 'S':
530 		case 'x':
531 		case 'X':
532 		case 'z':
533 		case 'Z':
534 			/*
535 			 * Before attempting to parse the extension itself, we find its end.
536 			 * As multi-letter extensions must be split from other multi-letter
537 			 * extensions with an "_", the end of a multi-letter extension will
538 			 * either be the null character or the "_" at the start of the next
539 			 * multi-letter extension.
540 			 *
541 			 * Next, as the extensions version is currently ignored, we
542 			 * eliminate that portion. This is done by parsing backwards from
543 			 * the end of the extension, removing any numbers. This may be a
544 			 * major or minor number however, so the process is repeated if a
545 			 * minor number was found.
546 			 *
547 			 * ext_end is intended to represent the first character *after* the
548 			 * name portion of an extension, but will be decremented to the last
549 			 * character itself while eliminating the extensions version number.
550 			 * A simple re-increment solves this problem.
551 			 */
552 			for (; *isa && *isa != '_'; ++isa)
553 				if (unlikely(!isalnum(*isa)))
554 					ext_err = true;
555 
556 			ext_end = isa;
557 			if (unlikely(ext_err))
558 				break;
559 
560 			if (!isdigit(ext_end[-1]))
561 				break;
562 
563 			while (isdigit(*--ext_end))
564 				;
565 
566 			if (tolower(ext_end[0]) != 'p' || !isdigit(ext_end[-1])) {
567 				++ext_end;
568 				break;
569 			}
570 
571 			while (isdigit(*--ext_end))
572 				;
573 
574 			++ext_end;
575 			break;
576 		default:
577 			/*
578 			 * Things are a little easier for single-letter extensions, as they
579 			 * are parsed forwards.
580 			 *
581 			 * After checking that our starting position is valid, we need to
582 			 * ensure that, when isa was incremented at the start of the loop,
583 			 * that it arrived at the start of the next extension.
584 			 *
585 			 * If we are already on a non-digit, there is nothing to do. Either
586 			 * we have a multi-letter extension's _, or the start of an
587 			 * extension.
588 			 *
589 			 * Otherwise we have found the current extension's major version
590 			 * number. Parse past it, and a subsequent p/minor version number
591 			 * if present. The `p` extension must not appear immediately after
592 			 * a number, so there is no fear of missing it.
593 			 *
594 			 */
595 			if (unlikely(!isalpha(*ext))) {
596 				ext_err = true;
597 				break;
598 			}
599 
600 			if (!isdigit(*isa))
601 				break;
602 
603 			while (isdigit(*++isa))
604 				;
605 
606 			if (tolower(*isa) != 'p')
607 				break;
608 
609 			if (!isdigit(*++isa)) {
610 				--isa;
611 				break;
612 			}
613 
614 			while (isdigit(*++isa))
615 				;
616 
617 			break;
618 		}
619 
620 		/*
621 		 * The parser expects that at the start of an iteration isa points to the
622 		 * first character of the next extension. As we stop parsing an extension
623 		 * on meeting a non-alphanumeric character, an extra increment is needed
624 		 * where the succeeding extension is a multi-letter prefixed with an "_".
625 		 */
626 		if (*isa == '_')
627 			++isa;
628 
629 		if (unlikely(ext_err))
630 			continue;
631 
632 		match_isa_ext(ext, ext_end, bitmap);
633 	}
634 }
635 
636 static void __init riscv_fill_hwcap_from_isa_string(unsigned long *isa2hwcap)
637 {
638 	struct device_node *node;
639 	const char *isa;
640 	int rc;
641 	struct acpi_table_header *rhct;
642 	acpi_status status;
643 	unsigned int cpu;
644 	u64 boot_vendorid;
645 	u64 boot_archid;
646 
647 	if (!acpi_disabled) {
648 		status = acpi_get_table(ACPI_SIG_RHCT, 0, &rhct);
649 		if (ACPI_FAILURE(status))
650 			return;
651 	}
652 
653 	boot_vendorid = riscv_get_mvendorid();
654 	boot_archid = riscv_get_marchid();
655 
656 	for_each_possible_cpu(cpu) {
657 		struct riscv_isainfo *isainfo = &hart_isa[cpu];
658 		unsigned long this_hwcap = 0;
659 		DECLARE_BITMAP(source_isa, RISCV_ISA_EXT_MAX) = { 0 };
660 
661 		if (acpi_disabled) {
662 			node = of_cpu_device_node_get(cpu);
663 			if (!node) {
664 				pr_warn("Unable to find cpu node\n");
665 				continue;
666 			}
667 
668 			rc = of_property_read_string(node, "riscv,isa", &isa);
669 			of_node_put(node);
670 			if (rc) {
671 				pr_warn("Unable to find \"riscv,isa\" devicetree entry\n");
672 				continue;
673 			}
674 		} else {
675 			rc = acpi_get_riscv_isa(rhct, cpu, &isa);
676 			if (rc < 0) {
677 				pr_warn("Unable to get ISA for the hart - %d\n", cpu);
678 				continue;
679 			}
680 		}
681 
682 		riscv_parse_isa_string(isa, source_isa);
683 
684 		/*
685 		 * These ones were as they were part of the base ISA when the
686 		 * port & dt-bindings were upstreamed, and so can be set
687 		 * unconditionally where `i` is in riscv,isa on DT systems.
688 		 */
689 		if (acpi_disabled) {
690 			set_bit(RISCV_ISA_EXT_ZICSR, source_isa);
691 			set_bit(RISCV_ISA_EXT_ZIFENCEI, source_isa);
692 			set_bit(RISCV_ISA_EXT_ZICNTR, source_isa);
693 			set_bit(RISCV_ISA_EXT_ZIHPM, source_isa);
694 		}
695 
696 		/*
697 		 * "V" in ISA strings is ambiguous in practice: it should mean
698 		 * just the standard V-1.0 but vendors aren't well behaved.
699 		 * Many vendors with T-Head CPU cores which implement the 0.7.1
700 		 * version of the vector specification put "v" into their DTs.
701 		 * CPU cores with the ratified spec will contain non-zero
702 		 * marchid.
703 		 */
704 		if (acpi_disabled && boot_vendorid == THEAD_VENDOR_ID && boot_archid == 0x0) {
705 			this_hwcap &= ~isa2hwcap[RISCV_ISA_EXT_v];
706 			clear_bit(RISCV_ISA_EXT_v, source_isa);
707 		}
708 
709 		riscv_resolve_isa(source_isa, isainfo->isa, &this_hwcap, isa2hwcap);
710 
711 		/*
712 		 * All "okay" hart should have same isa. Set HWCAP based on
713 		 * common capabilities of every "okay" hart, in case they don't
714 		 * have.
715 		 */
716 		if (elf_hwcap)
717 			elf_hwcap &= this_hwcap;
718 		else
719 			elf_hwcap = this_hwcap;
720 
721 		if (bitmap_empty(riscv_isa, RISCV_ISA_EXT_MAX))
722 			bitmap_copy(riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
723 		else
724 			bitmap_and(riscv_isa, riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
725 	}
726 
727 	if (!acpi_disabled && rhct)
728 		acpi_put_table((struct acpi_table_header *)rhct);
729 }
730 
731 static int __init riscv_fill_hwcap_from_ext_list(unsigned long *isa2hwcap)
732 {
733 	unsigned int cpu;
734 
735 	for_each_possible_cpu(cpu) {
736 		unsigned long this_hwcap = 0;
737 		struct device_node *cpu_node;
738 		struct riscv_isainfo *isainfo = &hart_isa[cpu];
739 		DECLARE_BITMAP(source_isa, RISCV_ISA_EXT_MAX) = { 0 };
740 
741 		cpu_node = of_cpu_device_node_get(cpu);
742 		if (!cpu_node) {
743 			pr_warn("Unable to find cpu node\n");
744 			continue;
745 		}
746 
747 		if (!of_property_present(cpu_node, "riscv,isa-extensions")) {
748 			of_node_put(cpu_node);
749 			continue;
750 		}
751 
752 		for (int i = 0; i < riscv_isa_ext_count; i++) {
753 			const struct riscv_isa_ext_data *ext = &riscv_isa_ext[i];
754 
755 			if (of_property_match_string(cpu_node, "riscv,isa-extensions",
756 						     ext->property) < 0)
757 				continue;
758 
759 			riscv_isa_set_ext(ext, source_isa);
760 		}
761 
762 		riscv_resolve_isa(source_isa, isainfo->isa, &this_hwcap, isa2hwcap);
763 
764 		of_node_put(cpu_node);
765 
766 		/*
767 		 * All "okay" harts should have same isa. Set HWCAP based on
768 		 * common capabilities of every "okay" hart, in case they don't.
769 		 */
770 		if (elf_hwcap)
771 			elf_hwcap &= this_hwcap;
772 		else
773 			elf_hwcap = this_hwcap;
774 
775 		if (bitmap_empty(riscv_isa, RISCV_ISA_EXT_MAX))
776 			bitmap_copy(riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
777 		else
778 			bitmap_and(riscv_isa, riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
779 	}
780 
781 	if (bitmap_empty(riscv_isa, RISCV_ISA_EXT_MAX))
782 		return -ENOENT;
783 
784 	return 0;
785 }
786 
787 #ifdef CONFIG_RISCV_ISA_FALLBACK
788 bool __initdata riscv_isa_fallback = true;
789 #else
790 bool __initdata riscv_isa_fallback;
791 static int __init riscv_isa_fallback_setup(char *__unused)
792 {
793 	riscv_isa_fallback = true;
794 	return 1;
795 }
796 early_param("riscv_isa_fallback", riscv_isa_fallback_setup);
797 #endif
798 
799 void __init riscv_fill_hwcap(void)
800 {
801 	char print_str[NUM_ALPHA_EXTS + 1];
802 	unsigned long isa2hwcap[26] = {0};
803 	int i, j;
804 
805 	isa2hwcap['i' - 'a'] = COMPAT_HWCAP_ISA_I;
806 	isa2hwcap['m' - 'a'] = COMPAT_HWCAP_ISA_M;
807 	isa2hwcap['a' - 'a'] = COMPAT_HWCAP_ISA_A;
808 	isa2hwcap['f' - 'a'] = COMPAT_HWCAP_ISA_F;
809 	isa2hwcap['d' - 'a'] = COMPAT_HWCAP_ISA_D;
810 	isa2hwcap['c' - 'a'] = COMPAT_HWCAP_ISA_C;
811 	isa2hwcap['v' - 'a'] = COMPAT_HWCAP_ISA_V;
812 
813 	if (!acpi_disabled) {
814 		riscv_fill_hwcap_from_isa_string(isa2hwcap);
815 	} else {
816 		int ret = riscv_fill_hwcap_from_ext_list(isa2hwcap);
817 
818 		if (ret && riscv_isa_fallback) {
819 			pr_info("Falling back to deprecated \"riscv,isa\"\n");
820 			riscv_fill_hwcap_from_isa_string(isa2hwcap);
821 		}
822 	}
823 
824 	/*
825 	 * We don't support systems with F but without D, so mask those out
826 	 * here.
827 	 */
828 	if ((elf_hwcap & COMPAT_HWCAP_ISA_F) && !(elf_hwcap & COMPAT_HWCAP_ISA_D)) {
829 		pr_info("This kernel does not support systems with F but not D\n");
830 		elf_hwcap &= ~COMPAT_HWCAP_ISA_F;
831 	}
832 
833 	if (__riscv_isa_extension_available(NULL, RISCV_ISA_EXT_ZVE32X)) {
834 		/*
835 		 * This cannot fail when called on the boot hart
836 		 */
837 		riscv_v_setup_vsize();
838 	}
839 
840 	if (elf_hwcap & COMPAT_HWCAP_ISA_V) {
841 		/*
842 		 * ISA string in device tree might have 'v' flag, but
843 		 * CONFIG_RISCV_ISA_V is disabled in kernel.
844 		 * Clear V flag in elf_hwcap if CONFIG_RISCV_ISA_V is disabled.
845 		 */
846 		if (!IS_ENABLED(CONFIG_RISCV_ISA_V))
847 			elf_hwcap &= ~COMPAT_HWCAP_ISA_V;
848 	}
849 
850 	memset(print_str, 0, sizeof(print_str));
851 	for (i = 0, j = 0; i < NUM_ALPHA_EXTS; i++)
852 		if (riscv_isa[0] & BIT_MASK(i))
853 			print_str[j++] = (char)('a' + i);
854 	pr_info("riscv: base ISA extensions %s\n", print_str);
855 
856 	memset(print_str, 0, sizeof(print_str));
857 	for (i = 0, j = 0; i < NUM_ALPHA_EXTS; i++)
858 		if (elf_hwcap & BIT_MASK(i))
859 			print_str[j++] = (char)('a' + i);
860 	pr_info("riscv: ELF capabilities %s\n", print_str);
861 }
862 
863 unsigned long riscv_get_elf_hwcap(void)
864 {
865 	unsigned long hwcap;
866 
867 	hwcap = (elf_hwcap & ((1UL << RISCV_ISA_EXT_BASE) - 1));
868 
869 	if (!riscv_v_vstate_ctrl_user_allowed())
870 		hwcap &= ~COMPAT_HWCAP_ISA_V;
871 
872 	return hwcap;
873 }
874 
875 void riscv_user_isa_enable(void)
876 {
877 	if (riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_ZICBOZ))
878 		csr_set(CSR_ENVCFG, ENVCFG_CBZE);
879 }
880 
881 #ifdef CONFIG_RISCV_ALTERNATIVE
882 /*
883  * Alternative patch sites consider 48 bits when determining when to patch
884  * the old instruction sequence with the new. These bits are broken into a
885  * 16-bit vendor ID and a 32-bit patch ID. A non-zero vendor ID means the
886  * patch site is for an erratum, identified by the 32-bit patch ID. When
887  * the vendor ID is zero, the patch site is for a cpufeature. cpufeatures
888  * further break down patch ID into two 16-bit numbers. The lower 16 bits
889  * are the cpufeature ID and the upper 16 bits are used for a value specific
890  * to the cpufeature and patch site. If the upper 16 bits are zero, then it
891  * implies no specific value is specified. cpufeatures that want to control
892  * patching on a per-site basis will provide non-zero values and implement
893  * checks here. The checks return true when patching should be done, and
894  * false otherwise.
895  */
896 static bool riscv_cpufeature_patch_check(u16 id, u16 value)
897 {
898 	if (!value)
899 		return true;
900 
901 	switch (id) {
902 	case RISCV_ISA_EXT_ZICBOZ:
903 		/*
904 		 * Zicboz alternative applications provide the maximum
905 		 * supported block size order, or zero when it doesn't
906 		 * matter. If the current block size exceeds the maximum,
907 		 * then the alternative cannot be applied.
908 		 */
909 		return riscv_cboz_block_size <= (1U << value);
910 	}
911 
912 	return false;
913 }
914 
915 void __init_or_module riscv_cpufeature_patch_func(struct alt_entry *begin,
916 						  struct alt_entry *end,
917 						  unsigned int stage)
918 {
919 	struct alt_entry *alt;
920 	void *oldptr, *altptr;
921 	u16 id, value;
922 
923 	if (stage == RISCV_ALTERNATIVES_EARLY_BOOT)
924 		return;
925 
926 	for (alt = begin; alt < end; alt++) {
927 		if (alt->vendor_id != 0)
928 			continue;
929 
930 		id = PATCH_ID_CPUFEATURE_ID(alt->patch_id);
931 
932 		if (id >= RISCV_ISA_EXT_MAX) {
933 			WARN(1, "This extension id:%d is not in ISA extension list", id);
934 			continue;
935 		}
936 
937 		if (!__riscv_isa_extension_available(NULL, id))
938 			continue;
939 
940 		value = PATCH_ID_CPUFEATURE_VALUE(alt->patch_id);
941 		if (!riscv_cpufeature_patch_check(id, value))
942 			continue;
943 
944 		oldptr = ALT_OLD_PTR(alt);
945 		altptr = ALT_ALT_PTR(alt);
946 
947 		mutex_lock(&text_mutex);
948 		patch_text_nosync(oldptr, altptr, alt->alt_len);
949 		riscv_alternative_fix_offsets(oldptr, alt->alt_len, oldptr - altptr);
950 		mutex_unlock(&text_mutex);
951 	}
952 }
953 #endif
954