Merge tag 'riscv-for-linus-6.7-rc1' of git://git.kernel.org/pub/scm/linux/kernel...
[sfrench/cifs-2.6.git] / arch / riscv / kernel / cpufeature.c
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/ctype.h>
12 #include <linux/log2.h>
13 #include <linux/memory.h>
14 #include <linux/module.h>
15 #include <linux/of.h>
16 #include <asm/acpi.h>
17 #include <asm/alternative.h>
18 #include <asm/cacheflush.h>
19 #include <asm/cpufeature.h>
20 #include <asm/hwcap.h>
21 #include <asm/hwprobe.h>
22 #include <asm/patch.h>
23 #include <asm/processor.h>
24 #include <asm/vector.h>
25
26 #include "copy-unaligned.h"
27
28 #define NUM_ALPHA_EXTS ('z' - 'a' + 1)
29
30 #define MISALIGNED_ACCESS_JIFFIES_LG2 1
31 #define MISALIGNED_BUFFER_SIZE 0x4000
32 #define MISALIGNED_COPY_SIZE ((MISALIGNED_BUFFER_SIZE / 2) - 0x80)
33
34 unsigned long elf_hwcap __read_mostly;
35
36 /* Host ISA bitmap */
37 static DECLARE_BITMAP(riscv_isa, RISCV_ISA_EXT_MAX) __read_mostly;
38
39 /* Per-cpu ISA extensions. */
40 struct riscv_isainfo hart_isa[NR_CPUS];
41
42 /* Performance information */
43 DEFINE_PER_CPU(long, misaligned_access_speed);
44
45 /**
46  * riscv_isa_extension_base() - Get base extension word
47  *
48  * @isa_bitmap: ISA bitmap to use
49  * Return: base extension word as unsigned long value
50  *
51  * NOTE: If isa_bitmap is NULL then Host ISA bitmap will be used.
52  */
53 unsigned long riscv_isa_extension_base(const unsigned long *isa_bitmap)
54 {
55         if (!isa_bitmap)
56                 return riscv_isa[0];
57         return isa_bitmap[0];
58 }
59 EXPORT_SYMBOL_GPL(riscv_isa_extension_base);
60
61 /**
62  * __riscv_isa_extension_available() - Check whether given extension
63  * is available or not
64  *
65  * @isa_bitmap: ISA bitmap to use
66  * @bit: bit position of the desired extension
67  * Return: true or false
68  *
69  * NOTE: If isa_bitmap is NULL then Host ISA bitmap will be used.
70  */
71 bool __riscv_isa_extension_available(const unsigned long *isa_bitmap, int bit)
72 {
73         const unsigned long *bmap = (isa_bitmap) ? isa_bitmap : riscv_isa;
74
75         if (bit >= RISCV_ISA_EXT_MAX)
76                 return false;
77
78         return test_bit(bit, bmap) ? true : false;
79 }
80 EXPORT_SYMBOL_GPL(__riscv_isa_extension_available);
81
82 static bool riscv_isa_extension_check(int id)
83 {
84         switch (id) {
85         case RISCV_ISA_EXT_ZICBOM:
86                 if (!riscv_cbom_block_size) {
87                         pr_err("Zicbom detected in ISA string, disabling as no cbom-block-size found\n");
88                         return false;
89                 } else if (!is_power_of_2(riscv_cbom_block_size)) {
90                         pr_err("Zicbom disabled as cbom-block-size present, but is not a power-of-2\n");
91                         return false;
92                 }
93                 return true;
94         case RISCV_ISA_EXT_ZICBOZ:
95                 if (!riscv_cboz_block_size) {
96                         pr_err("Zicboz detected in ISA string, disabling as no cboz-block-size found\n");
97                         return false;
98                 } else if (!is_power_of_2(riscv_cboz_block_size)) {
99                         pr_err("Zicboz disabled as cboz-block-size present, but is not a power-of-2\n");
100                         return false;
101                 }
102                 return true;
103         }
104
105         return true;
106 }
107
108 #define __RISCV_ISA_EXT_DATA(_name, _id) {      \
109         .name = #_name,                         \
110         .property = #_name,                     \
111         .id = _id,                              \
112 }
113
114 /*
115  * The canonical order of ISA extension names in the ISA string is defined in
116  * chapter 27 of the unprivileged specification.
117  *
118  * Ordinarily, for in-kernel data structures, this order is unimportant but
119  * isa_ext_arr defines the order of the ISA string in /proc/cpuinfo.
120  *
121  * The specification uses vague wording, such as should, when it comes to
122  * ordering, so for our purposes the following rules apply:
123  *
124  * 1. All multi-letter extensions must be separated from other extensions by an
125  *    underscore.
126  *
127  * 2. Additional standard extensions (starting with 'Z') must be sorted after
128  *    single-letter extensions and before any higher-privileged extensions.
129  *
130  * 3. The first letter following the 'Z' conventionally indicates the most
131  *    closely related alphabetical extension category, IMAFDQLCBKJTPVH.
132  *    If multiple 'Z' extensions are named, they must be ordered first by
133  *    category, then alphabetically within a category.
134  *
135  * 3. Standard supervisor-level extensions (starting with 'S') must be listed
136  *    after standard unprivileged extensions.  If multiple supervisor-level
137  *    extensions are listed, they must be ordered alphabetically.
138  *
139  * 4. Standard machine-level extensions (starting with 'Zxm') must be listed
140  *    after any lower-privileged, standard extensions.  If multiple
141  *    machine-level extensions are listed, they must be ordered
142  *    alphabetically.
143  *
144  * 5. Non-standard extensions (starting with 'X') must be listed after all
145  *    standard extensions. If multiple non-standard extensions are listed, they
146  *    must be ordered alphabetically.
147  *
148  * An example string following the order is:
149  *    rv64imadc_zifoo_zigoo_zafoo_sbar_scar_zxmbaz_xqux_xrux
150  *
151  * New entries to this struct should follow the ordering rules described above.
152  */
153 const struct riscv_isa_ext_data riscv_isa_ext[] = {
154         __RISCV_ISA_EXT_DATA(i, RISCV_ISA_EXT_i),
155         __RISCV_ISA_EXT_DATA(m, RISCV_ISA_EXT_m),
156         __RISCV_ISA_EXT_DATA(a, RISCV_ISA_EXT_a),
157         __RISCV_ISA_EXT_DATA(f, RISCV_ISA_EXT_f),
158         __RISCV_ISA_EXT_DATA(d, RISCV_ISA_EXT_d),
159         __RISCV_ISA_EXT_DATA(q, RISCV_ISA_EXT_q),
160         __RISCV_ISA_EXT_DATA(c, RISCV_ISA_EXT_c),
161         __RISCV_ISA_EXT_DATA(b, RISCV_ISA_EXT_b),
162         __RISCV_ISA_EXT_DATA(k, RISCV_ISA_EXT_k),
163         __RISCV_ISA_EXT_DATA(j, RISCV_ISA_EXT_j),
164         __RISCV_ISA_EXT_DATA(p, RISCV_ISA_EXT_p),
165         __RISCV_ISA_EXT_DATA(v, RISCV_ISA_EXT_v),
166         __RISCV_ISA_EXT_DATA(h, RISCV_ISA_EXT_h),
167         __RISCV_ISA_EXT_DATA(zicbom, RISCV_ISA_EXT_ZICBOM),
168         __RISCV_ISA_EXT_DATA(zicboz, RISCV_ISA_EXT_ZICBOZ),
169         __RISCV_ISA_EXT_DATA(zicntr, RISCV_ISA_EXT_ZICNTR),
170         __RISCV_ISA_EXT_DATA(zicond, RISCV_ISA_EXT_ZICOND),
171         __RISCV_ISA_EXT_DATA(zicsr, RISCV_ISA_EXT_ZICSR),
172         __RISCV_ISA_EXT_DATA(zifencei, RISCV_ISA_EXT_ZIFENCEI),
173         __RISCV_ISA_EXT_DATA(zihintpause, RISCV_ISA_EXT_ZIHINTPAUSE),
174         __RISCV_ISA_EXT_DATA(zihpm, RISCV_ISA_EXT_ZIHPM),
175         __RISCV_ISA_EXT_DATA(zba, RISCV_ISA_EXT_ZBA),
176         __RISCV_ISA_EXT_DATA(zbb, RISCV_ISA_EXT_ZBB),
177         __RISCV_ISA_EXT_DATA(zbs, RISCV_ISA_EXT_ZBS),
178         __RISCV_ISA_EXT_DATA(smaia, RISCV_ISA_EXT_SMAIA),
179         __RISCV_ISA_EXT_DATA(smstateen, RISCV_ISA_EXT_SMSTATEEN),
180         __RISCV_ISA_EXT_DATA(ssaia, RISCV_ISA_EXT_SSAIA),
181         __RISCV_ISA_EXT_DATA(sscofpmf, RISCV_ISA_EXT_SSCOFPMF),
182         __RISCV_ISA_EXT_DATA(sstc, RISCV_ISA_EXT_SSTC),
183         __RISCV_ISA_EXT_DATA(svinval, RISCV_ISA_EXT_SVINVAL),
184         __RISCV_ISA_EXT_DATA(svnapot, RISCV_ISA_EXT_SVNAPOT),
185         __RISCV_ISA_EXT_DATA(svpbmt, RISCV_ISA_EXT_SVPBMT),
186 };
187
188 const size_t riscv_isa_ext_count = ARRAY_SIZE(riscv_isa_ext);
189
190 static void __init riscv_parse_isa_string(unsigned long *this_hwcap, struct riscv_isainfo *isainfo,
191                                           unsigned long *isa2hwcap, const char *isa)
192 {
193         /*
194          * For all possible cpus, we have already validated in
195          * the boot process that they at least contain "rv" and
196          * whichever of "32"/"64" this kernel supports, and so this
197          * section can be skipped.
198          */
199         isa += 4;
200
201         while (*isa) {
202                 const char *ext = isa++;
203                 const char *ext_end = isa;
204                 bool ext_long = false, ext_err = false;
205
206                 switch (*ext) {
207                 case 's':
208                         /*
209                          * Workaround for invalid single-letter 's' & 'u' (QEMU).
210                          * No need to set the bit in riscv_isa as 's' & 'u' are
211                          * not valid ISA extensions. It works unless the first
212                          * multi-letter extension in the ISA string begins with
213                          * "Su" and is not prefixed with an underscore.
214                          */
215                         if (ext[-1] != '_' && ext[1] == 'u') {
216                                 ++isa;
217                                 ext_err = true;
218                                 break;
219                         }
220                         fallthrough;
221                 case 'S':
222                 case 'x':
223                 case 'X':
224                 case 'z':
225                 case 'Z':
226                         /*
227                          * Before attempting to parse the extension itself, we find its end.
228                          * As multi-letter extensions must be split from other multi-letter
229                          * extensions with an "_", the end of a multi-letter extension will
230                          * either be the null character or the "_" at the start of the next
231                          * multi-letter extension.
232                          *
233                          * Next, as the extensions version is currently ignored, we
234                          * eliminate that portion. This is done by parsing backwards from
235                          * the end of the extension, removing any numbers. This may be a
236                          * major or minor number however, so the process is repeated if a
237                          * minor number was found.
238                          *
239                          * ext_end is intended to represent the first character *after* the
240                          * name portion of an extension, but will be decremented to the last
241                          * character itself while eliminating the extensions version number.
242                          * A simple re-increment solves this problem.
243                          */
244                         ext_long = true;
245                         for (; *isa && *isa != '_'; ++isa)
246                                 if (unlikely(!isalnum(*isa)))
247                                         ext_err = true;
248
249                         ext_end = isa;
250                         if (unlikely(ext_err))
251                                 break;
252
253                         if (!isdigit(ext_end[-1]))
254                                 break;
255
256                         while (isdigit(*--ext_end))
257                                 ;
258
259                         if (tolower(ext_end[0]) != 'p' || !isdigit(ext_end[-1])) {
260                                 ++ext_end;
261                                 break;
262                         }
263
264                         while (isdigit(*--ext_end))
265                                 ;
266
267                         ++ext_end;
268                         break;
269                 default:
270                         /*
271                          * Things are a little easier for single-letter extensions, as they
272                          * are parsed forwards.
273                          *
274                          * After checking that our starting position is valid, we need to
275                          * ensure that, when isa was incremented at the start of the loop,
276                          * that it arrived at the start of the next extension.
277                          *
278                          * If we are already on a non-digit, there is nothing to do. Either
279                          * we have a multi-letter extension's _, or the start of an
280                          * extension.
281                          *
282                          * Otherwise we have found the current extension's major version
283                          * number. Parse past it, and a subsequent p/minor version number
284                          * if present. The `p` extension must not appear immediately after
285                          * a number, so there is no fear of missing it.
286                          *
287                          */
288                         if (unlikely(!isalpha(*ext))) {
289                                 ext_err = true;
290                                 break;
291                         }
292
293                         if (!isdigit(*isa))
294                                 break;
295
296                         while (isdigit(*++isa))
297                                 ;
298
299                         if (tolower(*isa) != 'p')
300                                 break;
301
302                         if (!isdigit(*++isa)) {
303                                 --isa;
304                                 break;
305                         }
306
307                         while (isdigit(*++isa))
308                                 ;
309
310                         break;
311                 }
312
313                 /*
314                  * The parser expects that at the start of an iteration isa points to the
315                  * first character of the next extension. As we stop parsing an extension
316                  * on meeting a non-alphanumeric character, an extra increment is needed
317                  * where the succeeding extension is a multi-letter prefixed with an "_".
318                  */
319                 if (*isa == '_')
320                         ++isa;
321
322 #define SET_ISA_EXT_MAP(name, bit)                                              \
323                 do {                                                            \
324                         if ((ext_end - ext == strlen(name)) &&                  \
325                              !strncasecmp(ext, name, strlen(name)) &&           \
326                              riscv_isa_extension_check(bit))                    \
327                                 set_bit(bit, isainfo->isa);                     \
328                 } while (false)                                                 \
329
330                 if (unlikely(ext_err))
331                         continue;
332                 if (!ext_long) {
333                         int nr = tolower(*ext) - 'a';
334
335                         if (riscv_isa_extension_check(nr)) {
336                                 *this_hwcap |= isa2hwcap[nr];
337                                 set_bit(nr, isainfo->isa);
338                         }
339                 } else {
340                         for (int i = 0; i < riscv_isa_ext_count; i++)
341                                 SET_ISA_EXT_MAP(riscv_isa_ext[i].name,
342                                                 riscv_isa_ext[i].id);
343                 }
344 #undef SET_ISA_EXT_MAP
345         }
346 }
347
348 static void __init riscv_fill_hwcap_from_isa_string(unsigned long *isa2hwcap)
349 {
350         struct device_node *node;
351         const char *isa;
352         int rc;
353         struct acpi_table_header *rhct;
354         acpi_status status;
355         unsigned int cpu;
356
357         if (!acpi_disabled) {
358                 status = acpi_get_table(ACPI_SIG_RHCT, 0, &rhct);
359                 if (ACPI_FAILURE(status))
360                         return;
361         }
362
363         for_each_possible_cpu(cpu) {
364                 struct riscv_isainfo *isainfo = &hart_isa[cpu];
365                 unsigned long this_hwcap = 0;
366
367                 if (acpi_disabled) {
368                         node = of_cpu_device_node_get(cpu);
369                         if (!node) {
370                                 pr_warn("Unable to find cpu node\n");
371                                 continue;
372                         }
373
374                         rc = of_property_read_string(node, "riscv,isa", &isa);
375                         of_node_put(node);
376                         if (rc) {
377                                 pr_warn("Unable to find \"riscv,isa\" devicetree entry\n");
378                                 continue;
379                         }
380                 } else {
381                         rc = acpi_get_riscv_isa(rhct, cpu, &isa);
382                         if (rc < 0) {
383                                 pr_warn("Unable to get ISA for the hart - %d\n", cpu);
384                                 continue;
385                         }
386                 }
387
388                 riscv_parse_isa_string(&this_hwcap, isainfo, isa2hwcap, isa);
389
390                 /*
391                  * These ones were as they were part of the base ISA when the
392                  * port & dt-bindings were upstreamed, and so can be set
393                  * unconditionally where `i` is in riscv,isa on DT systems.
394                  */
395                 if (acpi_disabled) {
396                         set_bit(RISCV_ISA_EXT_ZICSR, isainfo->isa);
397                         set_bit(RISCV_ISA_EXT_ZIFENCEI, isainfo->isa);
398                         set_bit(RISCV_ISA_EXT_ZICNTR, isainfo->isa);
399                         set_bit(RISCV_ISA_EXT_ZIHPM, isainfo->isa);
400                 }
401
402                 /*
403                  * All "okay" hart should have same isa. Set HWCAP based on
404                  * common capabilities of every "okay" hart, in case they don't
405                  * have.
406                  */
407                 if (elf_hwcap)
408                         elf_hwcap &= this_hwcap;
409                 else
410                         elf_hwcap = this_hwcap;
411
412                 if (bitmap_empty(riscv_isa, RISCV_ISA_EXT_MAX))
413                         bitmap_copy(riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
414                 else
415                         bitmap_and(riscv_isa, riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
416         }
417
418         if (!acpi_disabled && rhct)
419                 acpi_put_table((struct acpi_table_header *)rhct);
420 }
421
422 static int __init riscv_fill_hwcap_from_ext_list(unsigned long *isa2hwcap)
423 {
424         unsigned int cpu;
425
426         for_each_possible_cpu(cpu) {
427                 unsigned long this_hwcap = 0;
428                 struct device_node *cpu_node;
429                 struct riscv_isainfo *isainfo = &hart_isa[cpu];
430
431                 cpu_node = of_cpu_device_node_get(cpu);
432                 if (!cpu_node) {
433                         pr_warn("Unable to find cpu node\n");
434                         continue;
435                 }
436
437                 if (!of_property_present(cpu_node, "riscv,isa-extensions")) {
438                         of_node_put(cpu_node);
439                         continue;
440                 }
441
442                 for (int i = 0; i < riscv_isa_ext_count; i++) {
443                         if (of_property_match_string(cpu_node, "riscv,isa-extensions",
444                                                      riscv_isa_ext[i].property) < 0)
445                                 continue;
446
447                         if (!riscv_isa_extension_check(riscv_isa_ext[i].id))
448                                 continue;
449
450                         /* Only single letter extensions get set in hwcap */
451                         if (strnlen(riscv_isa_ext[i].name, 2) == 1)
452                                 this_hwcap |= isa2hwcap[riscv_isa_ext[i].id];
453
454                         set_bit(riscv_isa_ext[i].id, isainfo->isa);
455                 }
456
457                 of_node_put(cpu_node);
458
459                 /*
460                  * All "okay" harts should have same isa. Set HWCAP based on
461                  * common capabilities of every "okay" hart, in case they don't.
462                  */
463                 if (elf_hwcap)
464                         elf_hwcap &= this_hwcap;
465                 else
466                         elf_hwcap = this_hwcap;
467
468                 if (bitmap_empty(riscv_isa, RISCV_ISA_EXT_MAX))
469                         bitmap_copy(riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
470                 else
471                         bitmap_and(riscv_isa, riscv_isa, isainfo->isa, RISCV_ISA_EXT_MAX);
472         }
473
474         if (bitmap_empty(riscv_isa, RISCV_ISA_EXT_MAX))
475                 return -ENOENT;
476
477         return 0;
478 }
479
480 #ifdef CONFIG_RISCV_ISA_FALLBACK
481 bool __initdata riscv_isa_fallback = true;
482 #else
483 bool __initdata riscv_isa_fallback;
484 static int __init riscv_isa_fallback_setup(char *__unused)
485 {
486         riscv_isa_fallback = true;
487         return 1;
488 }
489 early_param("riscv_isa_fallback", riscv_isa_fallback_setup);
490 #endif
491
492 void __init riscv_fill_hwcap(void)
493 {
494         char print_str[NUM_ALPHA_EXTS + 1];
495         unsigned long isa2hwcap[26] = {0};
496         int i, j;
497
498         isa2hwcap['i' - 'a'] = COMPAT_HWCAP_ISA_I;
499         isa2hwcap['m' - 'a'] = COMPAT_HWCAP_ISA_M;
500         isa2hwcap['a' - 'a'] = COMPAT_HWCAP_ISA_A;
501         isa2hwcap['f' - 'a'] = COMPAT_HWCAP_ISA_F;
502         isa2hwcap['d' - 'a'] = COMPAT_HWCAP_ISA_D;
503         isa2hwcap['c' - 'a'] = COMPAT_HWCAP_ISA_C;
504         isa2hwcap['v' - 'a'] = COMPAT_HWCAP_ISA_V;
505
506         if (!acpi_disabled) {
507                 riscv_fill_hwcap_from_isa_string(isa2hwcap);
508         } else {
509                 int ret = riscv_fill_hwcap_from_ext_list(isa2hwcap);
510
511                 if (ret && riscv_isa_fallback) {
512                         pr_info("Falling back to deprecated \"riscv,isa\"\n");
513                         riscv_fill_hwcap_from_isa_string(isa2hwcap);
514                 }
515         }
516
517         /*
518          * We don't support systems with F but without D, so mask those out
519          * here.
520          */
521         if ((elf_hwcap & COMPAT_HWCAP_ISA_F) && !(elf_hwcap & COMPAT_HWCAP_ISA_D)) {
522                 pr_info("This kernel does not support systems with F but not D\n");
523                 elf_hwcap &= ~COMPAT_HWCAP_ISA_F;
524         }
525
526         if (elf_hwcap & COMPAT_HWCAP_ISA_V) {
527                 riscv_v_setup_vsize();
528                 /*
529                  * ISA string in device tree might have 'v' flag, but
530                  * CONFIG_RISCV_ISA_V is disabled in kernel.
531                  * Clear V flag in elf_hwcap if CONFIG_RISCV_ISA_V is disabled.
532                  */
533                 if (!IS_ENABLED(CONFIG_RISCV_ISA_V))
534                         elf_hwcap &= ~COMPAT_HWCAP_ISA_V;
535         }
536
537         memset(print_str, 0, sizeof(print_str));
538         for (i = 0, j = 0; i < NUM_ALPHA_EXTS; i++)
539                 if (riscv_isa[0] & BIT_MASK(i))
540                         print_str[j++] = (char)('a' + i);
541         pr_info("riscv: base ISA extensions %s\n", print_str);
542
543         memset(print_str, 0, sizeof(print_str));
544         for (i = 0, j = 0; i < NUM_ALPHA_EXTS; i++)
545                 if (elf_hwcap & BIT_MASK(i))
546                         print_str[j++] = (char)('a' + i);
547         pr_info("riscv: ELF capabilities %s\n", print_str);
548 }
549
550 unsigned long riscv_get_elf_hwcap(void)
551 {
552         unsigned long hwcap;
553
554         hwcap = (elf_hwcap & ((1UL << RISCV_ISA_EXT_BASE) - 1));
555
556         if (!riscv_v_vstate_ctrl_user_allowed())
557                 hwcap &= ~COMPAT_HWCAP_ISA_V;
558
559         return hwcap;
560 }
561
562 void check_unaligned_access(int cpu)
563 {
564         u64 start_cycles, end_cycles;
565         u64 word_cycles;
566         u64 byte_cycles;
567         int ratio;
568         unsigned long start_jiffies, now;
569         struct page *page;
570         void *dst;
571         void *src;
572         long speed = RISCV_HWPROBE_MISALIGNED_SLOW;
573
574         page = alloc_pages(GFP_NOWAIT, get_order(MISALIGNED_BUFFER_SIZE));
575         if (!page) {
576                 pr_warn("Can't alloc pages to measure memcpy performance");
577                 return;
578         }
579
580         /* Make an unaligned destination buffer. */
581         dst = (void *)((unsigned long)page_address(page) | 0x1);
582         /* Unalign src as well, but differently (off by 1 + 2 = 3). */
583         src = dst + (MISALIGNED_BUFFER_SIZE / 2);
584         src += 2;
585         word_cycles = -1ULL;
586         /* Do a warmup. */
587         __riscv_copy_words_unaligned(dst, src, MISALIGNED_COPY_SIZE);
588         preempt_disable();
589         start_jiffies = jiffies;
590         while ((now = jiffies) == start_jiffies)
591                 cpu_relax();
592
593         /*
594          * For a fixed amount of time, repeatedly try the function, and take
595          * the best time in cycles as the measurement.
596          */
597         while (time_before(jiffies, now + (1 << MISALIGNED_ACCESS_JIFFIES_LG2))) {
598                 start_cycles = get_cycles64();
599                 /* Ensure the CSR read can't reorder WRT to the copy. */
600                 mb();
601                 __riscv_copy_words_unaligned(dst, src, MISALIGNED_COPY_SIZE);
602                 /* Ensure the copy ends before the end time is snapped. */
603                 mb();
604                 end_cycles = get_cycles64();
605                 if ((end_cycles - start_cycles) < word_cycles)
606                         word_cycles = end_cycles - start_cycles;
607         }
608
609         byte_cycles = -1ULL;
610         __riscv_copy_bytes_unaligned(dst, src, MISALIGNED_COPY_SIZE);
611         start_jiffies = jiffies;
612         while ((now = jiffies) == start_jiffies)
613                 cpu_relax();
614
615         while (time_before(jiffies, now + (1 << MISALIGNED_ACCESS_JIFFIES_LG2))) {
616                 start_cycles = get_cycles64();
617                 mb();
618                 __riscv_copy_bytes_unaligned(dst, src, MISALIGNED_COPY_SIZE);
619                 mb();
620                 end_cycles = get_cycles64();
621                 if ((end_cycles - start_cycles) < byte_cycles)
622                         byte_cycles = end_cycles - start_cycles;
623         }
624
625         preempt_enable();
626
627         /* Don't divide by zero. */
628         if (!word_cycles || !byte_cycles) {
629                 pr_warn("cpu%d: rdtime lacks granularity needed to measure unaligned access speed\n",
630                         cpu);
631
632                 goto out;
633         }
634
635         if (word_cycles < byte_cycles)
636                 speed = RISCV_HWPROBE_MISALIGNED_FAST;
637
638         ratio = div_u64((byte_cycles * 100), word_cycles);
639         pr_info("cpu%d: Ratio of byte access time to unaligned word access is %d.%02d, unaligned accesses are %s\n",
640                 cpu,
641                 ratio / 100,
642                 ratio % 100,
643                 (speed == RISCV_HWPROBE_MISALIGNED_FAST) ? "fast" : "slow");
644
645         per_cpu(misaligned_access_speed, cpu) = speed;
646
647 out:
648         __free_pages(page, get_order(MISALIGNED_BUFFER_SIZE));
649 }
650
651 static int check_unaligned_access_boot_cpu(void)
652 {
653         check_unaligned_access(0);
654         return 0;
655 }
656
657 arch_initcall(check_unaligned_access_boot_cpu);
658
659 void riscv_user_isa_enable(void)
660 {
661         if (riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_ZICBOZ))
662                 csr_set(CSR_SENVCFG, ENVCFG_CBZE);
663 }
664
665 #ifdef CONFIG_RISCV_ALTERNATIVE
666 /*
667  * Alternative patch sites consider 48 bits when determining when to patch
668  * the old instruction sequence with the new. These bits are broken into a
669  * 16-bit vendor ID and a 32-bit patch ID. A non-zero vendor ID means the
670  * patch site is for an erratum, identified by the 32-bit patch ID. When
671  * the vendor ID is zero, the patch site is for a cpufeature. cpufeatures
672  * further break down patch ID into two 16-bit numbers. The lower 16 bits
673  * are the cpufeature ID and the upper 16 bits are used for a value specific
674  * to the cpufeature and patch site. If the upper 16 bits are zero, then it
675  * implies no specific value is specified. cpufeatures that want to control
676  * patching on a per-site basis will provide non-zero values and implement
677  * checks here. The checks return true when patching should be done, and
678  * false otherwise.
679  */
680 static bool riscv_cpufeature_patch_check(u16 id, u16 value)
681 {
682         if (!value)
683                 return true;
684
685         switch (id) {
686         case RISCV_ISA_EXT_ZICBOZ:
687                 /*
688                  * Zicboz alternative applications provide the maximum
689                  * supported block size order, or zero when it doesn't
690                  * matter. If the current block size exceeds the maximum,
691                  * then the alternative cannot be applied.
692                  */
693                 return riscv_cboz_block_size <= (1U << value);
694         }
695
696         return false;
697 }
698
699 void __init_or_module riscv_cpufeature_patch_func(struct alt_entry *begin,
700                                                   struct alt_entry *end,
701                                                   unsigned int stage)
702 {
703         struct alt_entry *alt;
704         void *oldptr, *altptr;
705         u16 id, value;
706
707         if (stage == RISCV_ALTERNATIVES_EARLY_BOOT)
708                 return;
709
710         for (alt = begin; alt < end; alt++) {
711                 if (alt->vendor_id != 0)
712                         continue;
713
714                 id = PATCH_ID_CPUFEATURE_ID(alt->patch_id);
715
716                 if (id >= RISCV_ISA_EXT_MAX) {
717                         WARN(1, "This extension id:%d is not in ISA extension list", id);
718                         continue;
719                 }
720
721                 if (!__riscv_isa_extension_available(NULL, id))
722                         continue;
723
724                 value = PATCH_ID_CPUFEATURE_VALUE(alt->patch_id);
725                 if (!riscv_cpufeature_patch_check(id, value))
726                         continue;
727
728                 oldptr = ALT_OLD_PTR(alt);
729                 altptr = ALT_ALT_PTR(alt);
730
731                 mutex_lock(&text_mutex);
732                 patch_text_nosync(oldptr, altptr, alt->alt_len);
733                 riscv_alternative_fix_offsets(oldptr, alt->alt_len, oldptr - altptr);
734                 mutex_unlock(&text_mutex);
735         }
736 }
737 #endif