xref: /linux-6.15/arch/x86/kernel/cpu/microcode/core.c (revision a7939f01)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * CPU Microcode Update Driver for Linux
4  *
5  * Copyright (C) 2000-2006 Tigran Aivazian <[email protected]>
6  *	      2006	Shaohua Li <[email protected]>
7  *	      2013-2016	Borislav Petkov <[email protected]>
8  *
9  * X86 CPU microcode early update for Linux:
10  *
11  *	Copyright (C) 2012 Fenghua Yu <[email protected]>
12  *			   H Peter Anvin" <[email protected]>
13  *		  (C) 2015 Borislav Petkov <[email protected]>
14  *
15  * This driver allows to upgrade microcode on x86 processors.
16  */
17 
18 #define pr_fmt(fmt) "microcode: " fmt
19 
20 #include <linux/platform_device.h>
21 #include <linux/stop_machine.h>
22 #include <linux/syscore_ops.h>
23 #include <linux/miscdevice.h>
24 #include <linux/capability.h>
25 #include <linux/firmware.h>
26 #include <linux/kernel.h>
27 #include <linux/delay.h>
28 #include <linux/mutex.h>
29 #include <linux/cpu.h>
30 #include <linux/nmi.h>
31 #include <linux/fs.h>
32 #include <linux/mm.h>
33 
34 #include <asm/cpu_device_id.h>
35 #include <asm/perf_event.h>
36 #include <asm/processor.h>
37 #include <asm/cmdline.h>
38 #include <asm/setup.h>
39 
40 #include "internal.h"
41 
42 #define DRIVER_VERSION	"2.2"
43 
44 static struct microcode_ops	*microcode_ops;
45 bool dis_ucode_ldr = true;
46 
47 bool initrd_gone;
48 
49 /*
50  * Synchronization.
51  *
52  * All non cpu-hotplug-callback call sites use:
53  *
54  * - cpus_read_lock/unlock() to synchronize with
55  *   the cpu-hotplug-callback call sites.
56  *
57  * We guarantee that only a single cpu is being
58  * updated at any particular moment of time.
59  */
60 struct ucode_cpu_info		ucode_cpu_info[NR_CPUS];
61 
62 struct cpu_info_ctx {
63 	struct cpu_signature	*cpu_sig;
64 	int			err;
65 };
66 
67 /*
68  * Those patch levels cannot be updated to newer ones and thus should be final.
69  */
70 static u32 final_levels[] = {
71 	0x01000098,
72 	0x0100009f,
73 	0x010000af,
74 	0, /* T-101 terminator */
75 };
76 
77 /*
78  * Check the current patch level on this CPU.
79  *
80  * Returns:
81  *  - true: if update should stop
82  *  - false: otherwise
83  */
84 static bool amd_check_current_patch_level(void)
85 {
86 	u32 lvl, dummy, i;
87 	u32 *levels;
88 
89 	native_rdmsr(MSR_AMD64_PATCH_LEVEL, lvl, dummy);
90 
91 	levels = final_levels;
92 
93 	for (i = 0; levels[i]; i++) {
94 		if (lvl == levels[i])
95 			return true;
96 	}
97 	return false;
98 }
99 
100 static bool __init check_loader_disabled_bsp(void)
101 {
102 	static const char *__dis_opt_str = "dis_ucode_ldr";
103 	const char *cmdline = boot_command_line;
104 	const char *option  = __dis_opt_str;
105 
106 	/*
107 	 * CPUID(1).ECX[31]: reserved for hypervisor use. This is still not
108 	 * completely accurate as xen pv guests don't see that CPUID bit set but
109 	 * that's good enough as they don't land on the BSP path anyway.
110 	 */
111 	if (native_cpuid_ecx(1) & BIT(31))
112 		return true;
113 
114 	if (x86_cpuid_vendor() == X86_VENDOR_AMD) {
115 		if (amd_check_current_patch_level())
116 			return true;
117 	}
118 
119 	if (cmdline_find_option_bool(cmdline, option) <= 0)
120 		dis_ucode_ldr = false;
121 
122 	return dis_ucode_ldr;
123 }
124 
125 void __init load_ucode_bsp(void)
126 {
127 	unsigned int cpuid_1_eax;
128 	bool intel = true;
129 
130 	if (!have_cpuid_p())
131 		return;
132 
133 	cpuid_1_eax = native_cpuid_eax(1);
134 
135 	switch (x86_cpuid_vendor()) {
136 	case X86_VENDOR_INTEL:
137 		if (x86_family(cpuid_1_eax) < 6)
138 			return;
139 		break;
140 
141 	case X86_VENDOR_AMD:
142 		if (x86_family(cpuid_1_eax) < 0x10)
143 			return;
144 		intel = false;
145 		break;
146 
147 	default:
148 		return;
149 	}
150 
151 	if (check_loader_disabled_bsp())
152 		return;
153 
154 	if (intel)
155 		load_ucode_intel_bsp();
156 	else
157 		load_ucode_amd_early(cpuid_1_eax);
158 }
159 
160 void load_ucode_ap(void)
161 {
162 	unsigned int cpuid_1_eax;
163 
164 	if (dis_ucode_ldr)
165 		return;
166 
167 	cpuid_1_eax = native_cpuid_eax(1);
168 
169 	switch (x86_cpuid_vendor()) {
170 	case X86_VENDOR_INTEL:
171 		if (x86_family(cpuid_1_eax) >= 6)
172 			load_ucode_intel_ap();
173 		break;
174 	case X86_VENDOR_AMD:
175 		if (x86_family(cpuid_1_eax) >= 0x10)
176 			load_ucode_amd_early(cpuid_1_eax);
177 		break;
178 	default:
179 		break;
180 	}
181 }
182 
183 /* Temporary workaround until find_microcode_in_initrd() is __init */
184 static int __init mark_initrd_gone(void)
185 {
186 	initrd_gone = true;
187 	return 0;
188 }
189 fs_initcall(mark_initrd_gone);
190 
191 struct cpio_data find_microcode_in_initrd(const char *path)
192 {
193 #ifdef CONFIG_BLK_DEV_INITRD
194 	unsigned long start = 0;
195 	size_t size;
196 
197 #ifdef CONFIG_X86_32
198 	size = boot_params.hdr.ramdisk_size;
199 	/* Early load on BSP has a temporary mapping. */
200 	if (size)
201 		start = initrd_start_early;
202 
203 #else /* CONFIG_X86_64 */
204 	size  = (unsigned long)boot_params.ext_ramdisk_size << 32;
205 	size |= boot_params.hdr.ramdisk_size;
206 
207 	if (size) {
208 		start  = (unsigned long)boot_params.ext_ramdisk_image << 32;
209 		start |= boot_params.hdr.ramdisk_image;
210 		start += PAGE_OFFSET;
211 	}
212 #endif
213 
214 	/*
215 	 * Fixup the start address: after reserve_initrd() runs, initrd_start
216 	 * has the virtual address of the beginning of the initrd. It also
217 	 * possibly relocates the ramdisk. In either case, initrd_start contains
218 	 * the updated address so use that instead.
219 	 *
220 	 * initrd_gone is for the hotplug case where we've thrown out initrd
221 	 * already.
222 	 */
223 	if (initrd_gone)
224 		return (struct cpio_data){ NULL, 0, "" };
225 	if (initrd_start)
226 		start = initrd_start;
227 
228 	return find_cpio_data(path, (void *)start, size, NULL);
229 #else /* !CONFIG_BLK_DEV_INITRD */
230 	return (struct cpio_data){ NULL, 0, "" };
231 #endif
232 }
233 
234 static void reload_early_microcode(unsigned int cpu)
235 {
236 	int vendor, family;
237 
238 	vendor = x86_cpuid_vendor();
239 	family = x86_cpuid_family();
240 
241 	switch (vendor) {
242 	case X86_VENDOR_INTEL:
243 		if (family >= 6)
244 			reload_ucode_intel();
245 		break;
246 	case X86_VENDOR_AMD:
247 		if (family >= 0x10)
248 			reload_ucode_amd(cpu);
249 		break;
250 	default:
251 		break;
252 	}
253 }
254 
255 /* fake device for request_firmware */
256 static struct platform_device	*microcode_pdev;
257 
258 #ifdef CONFIG_MICROCODE_LATE_LOADING
259 /*
260  * Late loading dance. Why the heavy-handed stomp_machine effort?
261  *
262  * - HT siblings must be idle and not execute other code while the other sibling
263  *   is loading microcode in order to avoid any negative interactions caused by
264  *   the loading.
265  *
266  * - In addition, microcode update on the cores must be serialized until this
267  *   requirement can be relaxed in the future. Right now, this is conservative
268  *   and good.
269  */
270 #define SPINUNIT 100 /* 100 nsec */
271 
272 static int check_online_cpus(void)
273 {
274 	unsigned int cpu;
275 
276 	/*
277 	 * Make sure all CPUs are online.  It's fine for SMT to be disabled if
278 	 * all the primary threads are still online.
279 	 */
280 	for_each_present_cpu(cpu) {
281 		if (topology_is_primary_thread(cpu) && !cpu_online(cpu)) {
282 			pr_err("Not all CPUs online, aborting microcode update.\n");
283 			return -EINVAL;
284 		}
285 	}
286 
287 	return 0;
288 }
289 
290 static atomic_t late_cpus_in;
291 static atomic_t late_cpus_out;
292 
293 static int __wait_for_cpus(atomic_t *t, long long timeout)
294 {
295 	int all_cpus = num_online_cpus();
296 
297 	atomic_inc(t);
298 
299 	while (atomic_read(t) < all_cpus) {
300 		if (timeout < SPINUNIT) {
301 			pr_err("Timeout while waiting for CPUs rendezvous, remaining: %d\n",
302 				all_cpus - atomic_read(t));
303 			return 1;
304 		}
305 
306 		ndelay(SPINUNIT);
307 		timeout -= SPINUNIT;
308 
309 		touch_nmi_watchdog();
310 	}
311 	return 0;
312 }
313 
314 /*
315  * Returns:
316  * < 0 - on error
317  *   0 - success (no update done or microcode was updated)
318  */
319 static int __reload_late(void *info)
320 {
321 	int cpu = smp_processor_id();
322 	enum ucode_state err;
323 	int ret = 0;
324 
325 	/*
326 	 * Wait for all CPUs to arrive. A load will not be attempted unless all
327 	 * CPUs show up.
328 	 * */
329 	if (__wait_for_cpus(&late_cpus_in, NSEC_PER_SEC))
330 		return -1;
331 
332 	/*
333 	 * On an SMT system, it suffices to load the microcode on one sibling of
334 	 * the core because the microcode engine is shared between the threads.
335 	 * Synchronization still needs to take place so that no concurrent
336 	 * loading attempts happen on multiple threads of an SMT core. See
337 	 * below.
338 	 */
339 	if (cpumask_first(topology_sibling_cpumask(cpu)) == cpu)
340 		err = microcode_ops->apply_microcode(cpu);
341 	else
342 		goto wait_for_siblings;
343 
344 	if (err >= UCODE_NFOUND) {
345 		if (err == UCODE_ERROR) {
346 			pr_warn("Error reloading microcode on CPU %d\n", cpu);
347 			ret = -1;
348 		}
349 	}
350 
351 wait_for_siblings:
352 	if (__wait_for_cpus(&late_cpus_out, NSEC_PER_SEC))
353 		panic("Timeout during microcode update!\n");
354 
355 	/*
356 	 * At least one thread has completed update on each core.
357 	 * For others, simply call the update to make sure the
358 	 * per-cpu cpuinfo can be updated with right microcode
359 	 * revision.
360 	 */
361 	if (cpumask_first(topology_sibling_cpumask(cpu)) != cpu)
362 		err = microcode_ops->apply_microcode(cpu);
363 
364 	return ret;
365 }
366 
367 /*
368  * Reload microcode late on all CPUs. Wait for a sec until they
369  * all gather together.
370  */
371 static int microcode_reload_late(void)
372 {
373 	int old = boot_cpu_data.microcode, ret;
374 	struct cpuinfo_x86 prev_info;
375 
376 	pr_err("Attempting late microcode loading - it is dangerous and taints the kernel.\n");
377 	pr_err("You should switch to early loading, if possible.\n");
378 
379 	atomic_set(&late_cpus_in,  0);
380 	atomic_set(&late_cpus_out, 0);
381 
382 	/*
383 	 * Take a snapshot before the microcode update in order to compare and
384 	 * check whether any bits changed after an update.
385 	 */
386 	store_cpu_caps(&prev_info);
387 
388 	ret = stop_machine_cpuslocked(__reload_late, NULL, cpu_online_mask);
389 
390 	if (microcode_ops->finalize_late_load)
391 		microcode_ops->finalize_late_load(ret);
392 
393 	if (!ret) {
394 		pr_info("Reload succeeded, microcode revision: 0x%x -> 0x%x\n",
395 			old, boot_cpu_data.microcode);
396 		microcode_check(&prev_info);
397 	} else {
398 		pr_info("Reload failed, current microcode revision: 0x%x\n",
399 			boot_cpu_data.microcode);
400 	}
401 
402 	return ret;
403 }
404 
405 static ssize_t reload_store(struct device *dev,
406 			    struct device_attribute *attr,
407 			    const char *buf, size_t size)
408 {
409 	enum ucode_state tmp_ret = UCODE_OK;
410 	int bsp = boot_cpu_data.cpu_index;
411 	unsigned long val;
412 	ssize_t ret = 0;
413 
414 	ret = kstrtoul(buf, 0, &val);
415 	if (ret || val != 1)
416 		return -EINVAL;
417 
418 	cpus_read_lock();
419 
420 	ret = check_online_cpus();
421 	if (ret)
422 		goto put;
423 
424 	tmp_ret = microcode_ops->request_microcode_fw(bsp, &microcode_pdev->dev);
425 	if (tmp_ret != UCODE_NEW)
426 		goto put;
427 
428 	ret = microcode_reload_late();
429 put:
430 	cpus_read_unlock();
431 
432 	if (ret == 0)
433 		ret = size;
434 
435 	add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK);
436 
437 	return ret;
438 }
439 
440 static DEVICE_ATTR_WO(reload);
441 #endif
442 
443 static ssize_t version_show(struct device *dev,
444 			struct device_attribute *attr, char *buf)
445 {
446 	struct ucode_cpu_info *uci = ucode_cpu_info + dev->id;
447 
448 	return sprintf(buf, "0x%x\n", uci->cpu_sig.rev);
449 }
450 
451 static ssize_t processor_flags_show(struct device *dev,
452 			struct device_attribute *attr, char *buf)
453 {
454 	struct ucode_cpu_info *uci = ucode_cpu_info + dev->id;
455 
456 	return sprintf(buf, "0x%x\n", uci->cpu_sig.pf);
457 }
458 
459 static DEVICE_ATTR_RO(version);
460 static DEVICE_ATTR_RO(processor_flags);
461 
462 static struct attribute *mc_default_attrs[] = {
463 	&dev_attr_version.attr,
464 	&dev_attr_processor_flags.attr,
465 	NULL
466 };
467 
468 static const struct attribute_group mc_attr_group = {
469 	.attrs			= mc_default_attrs,
470 	.name			= "microcode",
471 };
472 
473 static void microcode_fini_cpu(int cpu)
474 {
475 	if (microcode_ops->microcode_fini_cpu)
476 		microcode_ops->microcode_fini_cpu(cpu);
477 }
478 
479 /**
480  * microcode_bsp_resume - Update boot CPU microcode during resume.
481  */
482 void microcode_bsp_resume(void)
483 {
484 	int cpu = smp_processor_id();
485 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
486 
487 	if (uci->mc)
488 		microcode_ops->apply_microcode(cpu);
489 	else
490 		reload_early_microcode(cpu);
491 }
492 
493 static struct syscore_ops mc_syscore_ops = {
494 	.resume	= microcode_bsp_resume,
495 };
496 
497 static int mc_cpu_starting(unsigned int cpu)
498 {
499 	enum ucode_state err = microcode_ops->apply_microcode(cpu);
500 
501 	pr_debug("%s: CPU%d, err: %d\n", __func__, cpu, err);
502 
503 	return err == UCODE_ERROR;
504 }
505 
506 static int mc_cpu_online(unsigned int cpu)
507 {
508 	struct device *dev = get_cpu_device(cpu);
509 
510 	if (sysfs_create_group(&dev->kobj, &mc_attr_group))
511 		pr_err("Failed to create group for CPU%d\n", cpu);
512 	return 0;
513 }
514 
515 static int mc_cpu_down_prep(unsigned int cpu)
516 {
517 	struct device *dev;
518 
519 	dev = get_cpu_device(cpu);
520 
521 	microcode_fini_cpu(cpu);
522 
523 	/* Suspend is in progress, only remove the interface */
524 	sysfs_remove_group(&dev->kobj, &mc_attr_group);
525 	pr_debug("%s: CPU%d\n", __func__, cpu);
526 
527 	return 0;
528 }
529 
530 static void setup_online_cpu(struct work_struct *work)
531 {
532 	int cpu = smp_processor_id();
533 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
534 
535 	memset(uci, 0, sizeof(*uci));
536 
537 	microcode_ops->collect_cpu_info(cpu, &uci->cpu_sig);
538 	cpu_data(cpu).microcode = uci->cpu_sig.rev;
539 	if (!cpu)
540 		boot_cpu_data.microcode = uci->cpu_sig.rev;
541 	mc_cpu_online(cpu);
542 }
543 
544 static struct attribute *cpu_root_microcode_attrs[] = {
545 #ifdef CONFIG_MICROCODE_LATE_LOADING
546 	&dev_attr_reload.attr,
547 #endif
548 	NULL
549 };
550 
551 static const struct attribute_group cpu_root_microcode_group = {
552 	.name  = "microcode",
553 	.attrs = cpu_root_microcode_attrs,
554 };
555 
556 static int __init microcode_init(void)
557 {
558 	struct device *dev_root;
559 	struct cpuinfo_x86 *c = &boot_cpu_data;
560 	int error;
561 
562 	if (dis_ucode_ldr)
563 		return -EINVAL;
564 
565 	if (c->x86_vendor == X86_VENDOR_INTEL)
566 		microcode_ops = init_intel_microcode();
567 	else if (c->x86_vendor == X86_VENDOR_AMD)
568 		microcode_ops = init_amd_microcode();
569 	else
570 		pr_err("no support for this CPU vendor\n");
571 
572 	if (!microcode_ops)
573 		return -ENODEV;
574 
575 	microcode_pdev = platform_device_register_simple("microcode", -1, NULL, 0);
576 	if (IS_ERR(microcode_pdev))
577 		return PTR_ERR(microcode_pdev);
578 
579 	dev_root = bus_get_dev_root(&cpu_subsys);
580 	if (dev_root) {
581 		error = sysfs_create_group(&dev_root->kobj, &cpu_root_microcode_group);
582 		put_device(dev_root);
583 		if (error) {
584 			pr_err("Error creating microcode group!\n");
585 			goto out_pdev;
586 		}
587 	}
588 
589 	/* Do per-CPU setup */
590 	schedule_on_each_cpu(setup_online_cpu);
591 
592 	register_syscore_ops(&mc_syscore_ops);
593 	cpuhp_setup_state_nocalls(CPUHP_AP_MICROCODE_LOADER, "x86/microcode:starting",
594 				  mc_cpu_starting, NULL);
595 	cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/microcode:online",
596 				  mc_cpu_online, mc_cpu_down_prep);
597 
598 	pr_info("Microcode Update Driver: v%s.", DRIVER_VERSION);
599 
600 	return 0;
601 
602  out_pdev:
603 	platform_device_unregister(microcode_pdev);
604 	return error;
605 
606 }
607 late_initcall(microcode_init);
608