xref: /linux-6.15/arch/x86/kernel/cpu/microcode/core.c (revision 8f849ff6)
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/cpumask.h>
27 #include <linux/kernel.h>
28 #include <linux/delay.h>
29 #include <linux/mutex.h>
30 #include <linux/cpu.h>
31 #include <linux/nmi.h>
32 #include <linux/fs.h>
33 #include <linux/mm.h>
34 
35 #include <asm/apic.h>
36 #include <asm/cpu_device_id.h>
37 #include <asm/perf_event.h>
38 #include <asm/processor.h>
39 #include <asm/cmdline.h>
40 #include <asm/setup.h>
41 
42 #include "internal.h"
43 
44 #define DRIVER_VERSION	"2.2"
45 
46 static struct microcode_ops	*microcode_ops;
47 bool dis_ucode_ldr = true;
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_bsp(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_ap(cpuid_1_eax);
177 		break;
178 	default:
179 		break;
180 	}
181 }
182 
183 struct cpio_data __init find_microcode_in_initrd(const char *path)
184 {
185 #ifdef CONFIG_BLK_DEV_INITRD
186 	unsigned long start = 0;
187 	size_t size;
188 
189 #ifdef CONFIG_X86_32
190 	size = boot_params.hdr.ramdisk_size;
191 	/* Early load on BSP has a temporary mapping. */
192 	if (size)
193 		start = initrd_start_early;
194 
195 #else /* CONFIG_X86_64 */
196 	size  = (unsigned long)boot_params.ext_ramdisk_size << 32;
197 	size |= boot_params.hdr.ramdisk_size;
198 
199 	if (size) {
200 		start  = (unsigned long)boot_params.ext_ramdisk_image << 32;
201 		start |= boot_params.hdr.ramdisk_image;
202 		start += PAGE_OFFSET;
203 	}
204 #endif
205 
206 	/*
207 	 * Fixup the start address: after reserve_initrd() runs, initrd_start
208 	 * has the virtual address of the beginning of the initrd. It also
209 	 * possibly relocates the ramdisk. In either case, initrd_start contains
210 	 * the updated address so use that instead.
211 	 */
212 	if (initrd_start)
213 		start = initrd_start;
214 
215 	return find_cpio_data(path, (void *)start, size, NULL);
216 #else /* !CONFIG_BLK_DEV_INITRD */
217 	return (struct cpio_data){ NULL, 0, "" };
218 #endif
219 }
220 
221 static void reload_early_microcode(unsigned int cpu)
222 {
223 	int vendor, family;
224 
225 	vendor = x86_cpuid_vendor();
226 	family = x86_cpuid_family();
227 
228 	switch (vendor) {
229 	case X86_VENDOR_INTEL:
230 		if (family >= 6)
231 			reload_ucode_intel();
232 		break;
233 	case X86_VENDOR_AMD:
234 		if (family >= 0x10)
235 			reload_ucode_amd(cpu);
236 		break;
237 	default:
238 		break;
239 	}
240 }
241 
242 /* fake device for request_firmware */
243 static struct platform_device	*microcode_pdev;
244 
245 #ifdef CONFIG_MICROCODE_LATE_LOADING
246 /*
247  * Late loading dance. Why the heavy-handed stomp_machine effort?
248  *
249  * - HT siblings must be idle and not execute other code while the other sibling
250  *   is loading microcode in order to avoid any negative interactions caused by
251  *   the loading.
252  *
253  * - In addition, microcode update on the cores must be serialized until this
254  *   requirement can be relaxed in the future. Right now, this is conservative
255  *   and good.
256  */
257 enum sibling_ctrl {
258 	/* Spinwait with timeout */
259 	SCTRL_WAIT,
260 	/* Invoke the microcode_apply() callback */
261 	SCTRL_APPLY,
262 	/* Proceed without invoking the microcode_apply() callback */
263 	SCTRL_DONE,
264 };
265 
266 struct microcode_ctrl {
267 	enum sibling_ctrl	ctrl;
268 	enum ucode_state	result;
269 	unsigned int		ctrl_cpu;
270 	bool			nmi_enabled;
271 };
272 
273 DEFINE_STATIC_KEY_FALSE(microcode_nmi_handler_enable);
274 static DEFINE_PER_CPU(struct microcode_ctrl, ucode_ctrl);
275 static atomic_t late_cpus_in, offline_in_nmi;
276 static unsigned int loops_per_usec;
277 static cpumask_t cpu_offline_mask;
278 
279 static noinstr bool wait_for_cpus(atomic_t *cnt)
280 {
281 	unsigned int timeout, loops;
282 
283 	WARN_ON_ONCE(raw_atomic_dec_return(cnt) < 0);
284 
285 	for (timeout = 0; timeout < USEC_PER_SEC; timeout++) {
286 		if (!raw_atomic_read(cnt))
287 			return true;
288 
289 		for (loops = 0; loops < loops_per_usec; loops++)
290 			cpu_relax();
291 
292 		/* If invoked directly, tickle the NMI watchdog */
293 		if (!microcode_ops->use_nmi && !(timeout % USEC_PER_MSEC)) {
294 			instrumentation_begin();
295 			touch_nmi_watchdog();
296 			instrumentation_end();
297 		}
298 	}
299 	/* Prevent the late comers from making progress and let them time out */
300 	raw_atomic_inc(cnt);
301 	return false;
302 }
303 
304 static noinstr bool wait_for_ctrl(void)
305 {
306 	unsigned int timeout, loops;
307 
308 	for (timeout = 0; timeout < USEC_PER_SEC; timeout++) {
309 		if (raw_cpu_read(ucode_ctrl.ctrl) != SCTRL_WAIT)
310 			return true;
311 
312 		for (loops = 0; loops < loops_per_usec; loops++)
313 			cpu_relax();
314 
315 		/* If invoked directly, tickle the NMI watchdog */
316 		if (!microcode_ops->use_nmi && !(timeout % USEC_PER_MSEC)) {
317 			instrumentation_begin();
318 			touch_nmi_watchdog();
319 			instrumentation_end();
320 		}
321 	}
322 	return false;
323 }
324 
325 /*
326  * Protected against instrumentation up to the point where the primary
327  * thread completed the update. See microcode_nmi_handler() for details.
328  */
329 static noinstr bool load_secondary_wait(unsigned int ctrl_cpu)
330 {
331 	/* Initial rendezvous to ensure that all CPUs have arrived */
332 	if (!wait_for_cpus(&late_cpus_in)) {
333 		raw_cpu_write(ucode_ctrl.result, UCODE_TIMEOUT);
334 		return false;
335 	}
336 
337 	/*
338 	 * Wait for primary threads to complete. If one of them hangs due
339 	 * to the update, there is no way out. This is non-recoverable
340 	 * because the CPU might hold locks or resources and confuse the
341 	 * scheduler, watchdogs etc. There is no way to safely evacuate the
342 	 * machine.
343 	 */
344 	if (wait_for_ctrl())
345 		return true;
346 
347 	instrumentation_begin();
348 	panic("Microcode load: Primary CPU %d timed out\n", ctrl_cpu);
349 	instrumentation_end();
350 }
351 
352 /*
353  * Protected against instrumentation up to the point where the primary
354  * thread completed the update. See microcode_nmi_handler() for details.
355  */
356 static noinstr void load_secondary(unsigned int cpu)
357 {
358 	unsigned int ctrl_cpu = raw_cpu_read(ucode_ctrl.ctrl_cpu);
359 	enum ucode_state ret;
360 
361 	if (!load_secondary_wait(ctrl_cpu)) {
362 		instrumentation_begin();
363 		pr_err_once("load: %d CPUs timed out\n",
364 			    atomic_read(&late_cpus_in) - 1);
365 		instrumentation_end();
366 		return;
367 	}
368 
369 	/* Primary thread completed. Allow to invoke instrumentable code */
370 	instrumentation_begin();
371 	/*
372 	 * If the primary succeeded then invoke the apply() callback,
373 	 * otherwise copy the state from the primary thread.
374 	 */
375 	if (this_cpu_read(ucode_ctrl.ctrl) == SCTRL_APPLY)
376 		ret = microcode_ops->apply_microcode(cpu);
377 	else
378 		ret = per_cpu(ucode_ctrl.result, ctrl_cpu);
379 
380 	this_cpu_write(ucode_ctrl.result, ret);
381 	this_cpu_write(ucode_ctrl.ctrl, SCTRL_DONE);
382 	instrumentation_end();
383 }
384 
385 static void __load_primary(unsigned int cpu)
386 {
387 	struct cpumask *secondaries = topology_sibling_cpumask(cpu);
388 	enum sibling_ctrl ctrl;
389 	enum ucode_state ret;
390 	unsigned int sibling;
391 
392 	/* Initial rendezvous to ensure that all CPUs have arrived */
393 	if (!wait_for_cpus(&late_cpus_in)) {
394 		this_cpu_write(ucode_ctrl.result, UCODE_TIMEOUT);
395 		pr_err_once("load: %d CPUs timed out\n", atomic_read(&late_cpus_in) - 1);
396 		return;
397 	}
398 
399 	ret = microcode_ops->apply_microcode(cpu);
400 	this_cpu_write(ucode_ctrl.result, ret);
401 	this_cpu_write(ucode_ctrl.ctrl, SCTRL_DONE);
402 
403 	/*
404 	 * If the update was successful, let the siblings run the apply()
405 	 * callback. If not, tell them it's done. This also covers the
406 	 * case where the CPU has uniform loading at package or system
407 	 * scope implemented but does not advertise it.
408 	 */
409 	if (ret == UCODE_UPDATED || ret == UCODE_OK)
410 		ctrl = SCTRL_APPLY;
411 	else
412 		ctrl = SCTRL_DONE;
413 
414 	for_each_cpu(sibling, secondaries) {
415 		if (sibling != cpu)
416 			per_cpu(ucode_ctrl.ctrl, sibling) = ctrl;
417 	}
418 }
419 
420 static bool kick_offline_cpus(unsigned int nr_offl)
421 {
422 	unsigned int cpu, timeout;
423 
424 	for_each_cpu(cpu, &cpu_offline_mask) {
425 		/* Enable the rendezvous handler and send NMI */
426 		per_cpu(ucode_ctrl.nmi_enabled, cpu) = true;
427 		apic_send_nmi_to_offline_cpu(cpu);
428 	}
429 
430 	/* Wait for them to arrive */
431 	for (timeout = 0; timeout < (USEC_PER_SEC / 2); timeout++) {
432 		if (atomic_read(&offline_in_nmi) == nr_offl)
433 			return true;
434 		udelay(1);
435 	}
436 	/* Let the others time out */
437 	return false;
438 }
439 
440 static void release_offline_cpus(void)
441 {
442 	unsigned int cpu;
443 
444 	for_each_cpu(cpu, &cpu_offline_mask)
445 		per_cpu(ucode_ctrl.ctrl, cpu) = SCTRL_DONE;
446 }
447 
448 static void load_primary(unsigned int cpu)
449 {
450 	unsigned int nr_offl = cpumask_weight(&cpu_offline_mask);
451 	bool proceed = true;
452 
453 	/* Kick soft-offlined SMT siblings if required */
454 	if (!cpu && nr_offl)
455 		proceed = kick_offline_cpus(nr_offl);
456 
457 	/* If the soft-offlined CPUs did not respond, abort */
458 	if (proceed)
459 		__load_primary(cpu);
460 
461 	/* Unconditionally release soft-offlined SMT siblings if required */
462 	if (!cpu && nr_offl)
463 		release_offline_cpus();
464 }
465 
466 /*
467  * Minimal stub rendezvous handler for soft-offlined CPUs which participate
468  * in the NMI rendezvous to protect against a concurrent NMI on affected
469  * CPUs.
470  */
471 void noinstr microcode_offline_nmi_handler(void)
472 {
473 	if (!raw_cpu_read(ucode_ctrl.nmi_enabled))
474 		return;
475 	raw_cpu_write(ucode_ctrl.nmi_enabled, false);
476 	raw_cpu_write(ucode_ctrl.result, UCODE_OFFLINE);
477 	raw_atomic_inc(&offline_in_nmi);
478 	wait_for_ctrl();
479 }
480 
481 static noinstr bool microcode_update_handler(void)
482 {
483 	unsigned int cpu = raw_smp_processor_id();
484 
485 	if (raw_cpu_read(ucode_ctrl.ctrl_cpu) == cpu) {
486 		instrumentation_begin();
487 		load_primary(cpu);
488 		instrumentation_end();
489 	} else {
490 		load_secondary(cpu);
491 	}
492 
493 	instrumentation_begin();
494 	touch_nmi_watchdog();
495 	instrumentation_end();
496 
497 	return true;
498 }
499 
500 /*
501  * Protection against instrumentation is required for CPUs which are not
502  * safe against an NMI which is delivered to the secondary SMT sibling
503  * while the primary thread updates the microcode. Instrumentation can end
504  * up in #INT3, #DB and #PF. The IRET from those exceptions reenables NMI
505  * which is the opposite of what the NMI rendezvous is trying to achieve.
506  *
507  * The primary thread is safe versus instrumentation as the actual
508  * microcode update handles this correctly. It's only the sibling code
509  * path which must be NMI safe until the primary thread completed the
510  * update.
511  */
512 bool noinstr microcode_nmi_handler(void)
513 {
514 	if (!raw_cpu_read(ucode_ctrl.nmi_enabled))
515 		return false;
516 
517 	raw_cpu_write(ucode_ctrl.nmi_enabled, false);
518 	return microcode_update_handler();
519 }
520 
521 static int load_cpus_stopped(void *unused)
522 {
523 	if (microcode_ops->use_nmi) {
524 		/* Enable the NMI handler and raise NMI */
525 		this_cpu_write(ucode_ctrl.nmi_enabled, true);
526 		apic->send_IPI(smp_processor_id(), NMI_VECTOR);
527 	} else {
528 		/* Just invoke the handler directly */
529 		microcode_update_handler();
530 	}
531 	return 0;
532 }
533 
534 static int load_late_stop_cpus(void)
535 {
536 	unsigned int cpu, updated = 0, failed = 0, timedout = 0, siblings = 0;
537 	unsigned int nr_offl, offline = 0;
538 	int old_rev = boot_cpu_data.microcode;
539 	struct cpuinfo_x86 prev_info;
540 
541 	pr_err("Attempting late microcode loading - it is dangerous and taints the kernel.\n");
542 	pr_err("You should switch to early loading, if possible.\n");
543 
544 	atomic_set(&late_cpus_in, num_online_cpus());
545 	atomic_set(&offline_in_nmi, 0);
546 	loops_per_usec = loops_per_jiffy / (TICK_NSEC / 1000);
547 
548 	/*
549 	 * Take a snapshot before the microcode update in order to compare and
550 	 * check whether any bits changed after an update.
551 	 */
552 	store_cpu_caps(&prev_info);
553 
554 	if (microcode_ops->use_nmi)
555 		static_branch_enable_cpuslocked(&microcode_nmi_handler_enable);
556 
557 	stop_machine_cpuslocked(load_cpus_stopped, NULL, cpu_online_mask);
558 
559 	if (microcode_ops->use_nmi)
560 		static_branch_disable_cpuslocked(&microcode_nmi_handler_enable);
561 
562 	/* Analyze the results */
563 	for_each_cpu_and(cpu, cpu_present_mask, &cpus_booted_once_mask) {
564 		switch (per_cpu(ucode_ctrl.result, cpu)) {
565 		case UCODE_UPDATED:	updated++; break;
566 		case UCODE_TIMEOUT:	timedout++; break;
567 		case UCODE_OK:		siblings++; break;
568 		case UCODE_OFFLINE:	offline++; break;
569 		default:		failed++; break;
570 		}
571 	}
572 
573 	if (microcode_ops->finalize_late_load)
574 		microcode_ops->finalize_late_load(!updated);
575 
576 	if (!updated) {
577 		/* Nothing changed. */
578 		if (!failed && !timedout)
579 			return 0;
580 
581 		nr_offl = cpumask_weight(&cpu_offline_mask);
582 		if (offline < nr_offl) {
583 			pr_warn("%u offline siblings did not respond.\n",
584 				nr_offl - atomic_read(&offline_in_nmi));
585 			return -EIO;
586 		}
587 		pr_err("update failed: %u CPUs failed %u CPUs timed out\n",
588 		       failed, timedout);
589 		return -EIO;
590 	}
591 
592 	add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK);
593 	pr_info("load: updated on %u primary CPUs with %u siblings\n", updated, siblings);
594 	if (failed || timedout) {
595 		pr_err("load incomplete. %u CPUs timed out or failed\n",
596 		       num_online_cpus() - (updated + siblings));
597 	}
598 	pr_info("revision: 0x%x -> 0x%x\n", old_rev, boot_cpu_data.microcode);
599 	microcode_check(&prev_info);
600 
601 	return updated + siblings == num_online_cpus() ? 0 : -EIO;
602 }
603 
604 /*
605  * This function does two things:
606  *
607  * 1) Ensure that all required CPUs which are present and have been booted
608  *    once are online.
609  *
610  *    To pass this check, all primary threads must be online.
611  *
612  *    If the microcode load is not safe against NMI then all SMT threads
613  *    must be online as well because they still react to NMIs when they are
614  *    soft-offlined and parked in one of the play_dead() variants. So if a
615  *    NMI hits while the primary thread updates the microcode the resulting
616  *    behaviour is undefined. The default play_dead() implementation on
617  *    modern CPUs uses MWAIT, which is also not guaranteed to be safe
618  *    against a microcode update which affects MWAIT.
619  *
620  *    As soft-offlined CPUs still react on NMIs, the SMT sibling
621  *    restriction can be lifted when the vendor driver signals to use NMI
622  *    for rendezvous and the APIC provides a mechanism to send an NMI to a
623  *    soft-offlined CPU. The soft-offlined CPUs are then able to
624  *    participate in the rendezvous in a trivial stub handler.
625  *
626  * 2) Initialize the per CPU control structure and create a cpumask
627  *    which contains "offline"; secondary threads, so they can be handled
628  *    correctly by a control CPU.
629  */
630 static bool setup_cpus(void)
631 {
632 	struct microcode_ctrl ctrl = { .ctrl = SCTRL_WAIT, .result = -1, };
633 	bool allow_smt_offline;
634 	unsigned int cpu;
635 
636 	allow_smt_offline = microcode_ops->nmi_safe ||
637 		(microcode_ops->use_nmi && apic->nmi_to_offline_cpu);
638 
639 	cpumask_clear(&cpu_offline_mask);
640 
641 	for_each_cpu_and(cpu, cpu_present_mask, &cpus_booted_once_mask) {
642 		/*
643 		 * Offline CPUs sit in one of the play_dead() functions
644 		 * with interrupts disabled, but they still react on NMIs
645 		 * and execute arbitrary code. Also MWAIT being updated
646 		 * while the offline CPU sits there is not necessarily safe
647 		 * on all CPU variants.
648 		 *
649 		 * Mark them in the offline_cpus mask which will be handled
650 		 * by CPU0 later in the update process.
651 		 *
652 		 * Ensure that the primary thread is online so that it is
653 		 * guaranteed that all cores are updated.
654 		 */
655 		if (!cpu_online(cpu)) {
656 			if (topology_is_primary_thread(cpu) || !allow_smt_offline) {
657 				pr_err("CPU %u not online, loading aborted\n", cpu);
658 				return false;
659 			}
660 			cpumask_set_cpu(cpu, &cpu_offline_mask);
661 			per_cpu(ucode_ctrl, cpu) = ctrl;
662 			continue;
663 		}
664 
665 		/*
666 		 * Initialize the per CPU state. This is core scope for now,
667 		 * but prepared to take package or system scope into account.
668 		 */
669 		ctrl.ctrl_cpu = cpumask_first(topology_sibling_cpumask(cpu));
670 		per_cpu(ucode_ctrl, cpu) = ctrl;
671 	}
672 	return true;
673 }
674 
675 static int load_late_locked(void)
676 {
677 	if (!setup_cpus())
678 		return -EBUSY;
679 
680 	switch (microcode_ops->request_microcode_fw(0, &microcode_pdev->dev)) {
681 	case UCODE_NEW:
682 		return load_late_stop_cpus();
683 	case UCODE_NFOUND:
684 		return -ENOENT;
685 	default:
686 		return -EBADFD;
687 	}
688 }
689 
690 static ssize_t reload_store(struct device *dev,
691 			    struct device_attribute *attr,
692 			    const char *buf, size_t size)
693 {
694 	unsigned long val;
695 	ssize_t ret;
696 
697 	ret = kstrtoul(buf, 0, &val);
698 	if (ret || val != 1)
699 		return -EINVAL;
700 
701 	cpus_read_lock();
702 	ret = load_late_locked();
703 	cpus_read_unlock();
704 
705 	return ret ? : size;
706 }
707 
708 static DEVICE_ATTR_WO(reload);
709 #endif
710 
711 static ssize_t version_show(struct device *dev,
712 			struct device_attribute *attr, char *buf)
713 {
714 	struct ucode_cpu_info *uci = ucode_cpu_info + dev->id;
715 
716 	return sprintf(buf, "0x%x\n", uci->cpu_sig.rev);
717 }
718 
719 static ssize_t processor_flags_show(struct device *dev,
720 			struct device_attribute *attr, char *buf)
721 {
722 	struct ucode_cpu_info *uci = ucode_cpu_info + dev->id;
723 
724 	return sprintf(buf, "0x%x\n", uci->cpu_sig.pf);
725 }
726 
727 static DEVICE_ATTR_RO(version);
728 static DEVICE_ATTR_RO(processor_flags);
729 
730 static struct attribute *mc_default_attrs[] = {
731 	&dev_attr_version.attr,
732 	&dev_attr_processor_flags.attr,
733 	NULL
734 };
735 
736 static const struct attribute_group mc_attr_group = {
737 	.attrs			= mc_default_attrs,
738 	.name			= "microcode",
739 };
740 
741 static void microcode_fini_cpu(int cpu)
742 {
743 	if (microcode_ops->microcode_fini_cpu)
744 		microcode_ops->microcode_fini_cpu(cpu);
745 }
746 
747 /**
748  * microcode_bsp_resume - Update boot CPU microcode during resume.
749  */
750 void microcode_bsp_resume(void)
751 {
752 	int cpu = smp_processor_id();
753 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
754 
755 	if (uci->mc)
756 		microcode_ops->apply_microcode(cpu);
757 	else
758 		reload_early_microcode(cpu);
759 }
760 
761 static struct syscore_ops mc_syscore_ops = {
762 	.resume	= microcode_bsp_resume,
763 };
764 
765 static int mc_cpu_online(unsigned int cpu)
766 {
767 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
768 	struct device *dev = get_cpu_device(cpu);
769 
770 	memset(uci, 0, sizeof(*uci));
771 
772 	microcode_ops->collect_cpu_info(cpu, &uci->cpu_sig);
773 	cpu_data(cpu).microcode = uci->cpu_sig.rev;
774 	if (!cpu)
775 		boot_cpu_data.microcode = uci->cpu_sig.rev;
776 
777 	if (sysfs_create_group(&dev->kobj, &mc_attr_group))
778 		pr_err("Failed to create group for CPU%d\n", cpu);
779 	return 0;
780 }
781 
782 static int mc_cpu_down_prep(unsigned int cpu)
783 {
784 	struct device *dev = get_cpu_device(cpu);
785 
786 	microcode_fini_cpu(cpu);
787 	sysfs_remove_group(&dev->kobj, &mc_attr_group);
788 	return 0;
789 }
790 
791 static struct attribute *cpu_root_microcode_attrs[] = {
792 #ifdef CONFIG_MICROCODE_LATE_LOADING
793 	&dev_attr_reload.attr,
794 #endif
795 	NULL
796 };
797 
798 static const struct attribute_group cpu_root_microcode_group = {
799 	.name  = "microcode",
800 	.attrs = cpu_root_microcode_attrs,
801 };
802 
803 static int __init microcode_init(void)
804 {
805 	struct device *dev_root;
806 	struct cpuinfo_x86 *c = &boot_cpu_data;
807 	int error;
808 
809 	if (dis_ucode_ldr)
810 		return -EINVAL;
811 
812 	if (c->x86_vendor == X86_VENDOR_INTEL)
813 		microcode_ops = init_intel_microcode();
814 	else if (c->x86_vendor == X86_VENDOR_AMD)
815 		microcode_ops = init_amd_microcode();
816 	else
817 		pr_err("no support for this CPU vendor\n");
818 
819 	if (!microcode_ops)
820 		return -ENODEV;
821 
822 	microcode_pdev = platform_device_register_simple("microcode", -1, NULL, 0);
823 	if (IS_ERR(microcode_pdev))
824 		return PTR_ERR(microcode_pdev);
825 
826 	dev_root = bus_get_dev_root(&cpu_subsys);
827 	if (dev_root) {
828 		error = sysfs_create_group(&dev_root->kobj, &cpu_root_microcode_group);
829 		put_device(dev_root);
830 		if (error) {
831 			pr_err("Error creating microcode group!\n");
832 			goto out_pdev;
833 		}
834 	}
835 
836 	register_syscore_ops(&mc_syscore_ops);
837 	cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/microcode:online",
838 			  mc_cpu_online, mc_cpu_down_prep);
839 
840 	pr_info("Microcode Update Driver: v%s.", DRIVER_VERSION);
841 
842 	return 0;
843 
844  out_pdev:
845 	platform_device_unregister(microcode_pdev);
846 	return error;
847 
848 }
849 late_initcall(microcode_init);
850