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