xref: /linux/arch/x86/kernel/cpu/microcode/intel.c (revision ff5ccdb8d5bd242f1064c6f7996603e47e28d095)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Intel 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  *
8  * Intel CPU microcode early update for Linux
9  *
10  * Copyright (C) 2012 Fenghua Yu <fenghua.yu@intel.com>
11  *		      H Peter Anvin" <hpa@zytor.com>
12  */
13 #define pr_fmt(fmt) "microcode: " fmt
14 #include <linux/earlycpio.h>
15 #include <linux/firmware.h>
16 #include <linux/pci_ids.h>
17 #include <linux/uaccess.h>
18 #include <linux/initrd.h>
19 #include <linux/kernel.h>
20 #include <linux/delay.h>
21 #include <linux/slab.h>
22 #include <linux/cpu.h>
23 #include <linux/uio.h>
24 #include <linux/io.h>
25 #include <linux/mm.h>
26 
27 #include <asm/cpu_device_id.h>
28 #include <asm/cpuid/api.h>
29 #include <asm/processor.h>
30 #include <asm/tlbflush.h>
31 #include <asm/setup.h>
32 #include <asm/msr.h>
33 
34 #include "internal.h"
35 
36 static const char ucode_path[] = "kernel/x86/microcode/GenuineIntel.bin";
37 
38 #define UCODE_BSP_LOADED	((struct microcode_intel *)0x1UL)
39 
40 /* Defines for the microcode staging mailbox interface */
41 #define MBOX_REG_NUM		4
42 #define MBOX_REG_SIZE		sizeof(u32)
43 
44 #define MBOX_CONTROL_OFFSET	0x0
45 #define MBOX_STATUS_OFFSET	0x4
46 #define MBOX_WRDATA_OFFSET	0x8
47 #define MBOX_RDDATA_OFFSET	0xc
48 
49 #define MASK_MBOX_CTRL_ABORT	BIT(0)
50 #define MASK_MBOX_CTRL_GO	BIT(31)
51 
52 #define MASK_MBOX_STATUS_ERROR	BIT(2)
53 #define MASK_MBOX_STATUS_READY	BIT(31)
54 
55 #define MASK_MBOX_RESP_SUCCESS	BIT(0)
56 #define MASK_MBOX_RESP_PROGRESS	BIT(1)
57 #define MASK_MBOX_RESP_ERROR	BIT(2)
58 
59 #define MBOX_CMD_LOAD		0x3
60 #define MBOX_OBJ_STAGING	0xb
61 #define MBOX_HEADER(size)	((PCI_VENDOR_ID_INTEL)    | \
62 				 (MBOX_OBJ_STAGING << 16) | \
63 				 ((u64)((size) / sizeof(u32)) << 32))
64 
65 /* The size of each mailbox header */
66 #define MBOX_HEADER_SIZE	sizeof(u64)
67 /* The size of staging hardware response */
68 #define MBOX_RESPONSE_SIZE	sizeof(u64)
69 
70 #define MBOX_XACTION_TIMEOUT_MS	(10 * MSEC_PER_SEC)
71 
72 /* Current microcode patch used in early patching on the APs. */
73 static struct microcode_intel *ucode_patch_va __read_mostly;
74 static struct microcode_intel *ucode_patch_late __read_mostly;
75 
76 /* last level cache size per core */
77 static unsigned int llc_size_per_core __ro_after_init;
78 
79 /* microcode format is extended from prescott processors */
80 struct extended_signature {
81 	unsigned int	sig;
82 	unsigned int	pf;
83 	unsigned int	cksum;
84 };
85 
86 struct extended_sigtable {
87 	unsigned int			count;
88 	unsigned int			cksum;
89 	unsigned int			reserved[3];
90 	struct extended_signature	sigs[];
91 };
92 
93 /**
94  * struct staging_state - Track the current staging process state
95  *
96  * @mmio_base:		MMIO base address for staging
97  * @ucode_len:		Total size of the microcode image
98  * @chunk_size:		Size of each data piece
99  * @bytes_sent:		Total bytes transmitted so far
100  * @offset:		Current offset in the microcode image
101  */
102 struct staging_state {
103 	void __iomem		*mmio_base;
104 	unsigned int		ucode_len;
105 	unsigned int		chunk_size;
106 	unsigned int		bytes_sent;
107 	unsigned int		offset;
108 };
109 
110 #define DEFAULT_UCODE_TOTALSIZE (DEFAULT_UCODE_DATASIZE + MC_HEADER_SIZE)
111 #define EXT_HEADER_SIZE		(sizeof(struct extended_sigtable))
112 #define EXT_SIGNATURE_SIZE	(sizeof(struct extended_signature))
113 
114 static inline unsigned int get_totalsize(struct microcode_header_intel *hdr)
115 {
116 	return hdr->datasize ? hdr->totalsize : DEFAULT_UCODE_TOTALSIZE;
117 }
118 
119 static inline unsigned int exttable_size(struct extended_sigtable *et)
120 {
121 	return et->count * EXT_SIGNATURE_SIZE + EXT_HEADER_SIZE;
122 }
123 
124 
125 /*
126  * Use CPUID to generate a "vfm" value. Useful before cpuinfo_x86
127  * structures are populated.
128  */
129 static u32 intel_cpuid_vfm(void)
130 {
131 	u32 eax   = cpuid_eax(1);
132 	u32 fam   = x86_family(eax);
133 	u32 model = x86_model(eax);
134 
135 	return IFM(fam, model);
136 }
137 
138 u32 intel_get_platform_id(void)
139 {
140 	unsigned int val[2];
141 
142 	if (x86_hypervisor_present)
143 		return 0;
144 
145 	/*
146 	 * This can be called early. Use CPUID directly instead of
147 	 * relying on cpuinfo_x86 which may not be fully initialized.
148 	 * The PII does not have MSR_IA32_PLATFORM_ID. Everything
149 	 * before _it_ has no microcode (for Linux at least).
150 	 */
151 	if (intel_cpuid_vfm() <= INTEL_PENTIUM_II_KLAMATH)
152 		return 0;
153 
154 	/* get processor flags from MSR 0x17 */
155 	native_rdmsr(MSR_IA32_PLATFORM_ID, val[0], val[1]);
156 
157 	return (val[1] >> 18) & 7;
158 }
159 
160 void intel_collect_cpu_info(struct cpu_signature *sig)
161 {
162 	sig->sig = cpuid_eax(1);
163 	sig->rev = intel_get_microcode_revision();
164 	sig->pf  = 1 << intel_get_platform_id();
165 }
166 EXPORT_SYMBOL_GPL(intel_collect_cpu_info);
167 
168 static inline bool cpu_signatures_match(struct cpu_signature *s1, unsigned int sig2,
169 					unsigned int pf2)
170 {
171 	if (s1->sig != sig2)
172 		return false;
173 
174 	/*
175 	 * Consider an empty mask to match everything. This
176 	 * should only occur for one CPU model, the PII.
177 	 */
178 	if (!pf2)
179 		return true;
180 
181 	/* Is the CPU's platform ID in the signature mask? */
182 	return s1->pf & pf2;
183 }
184 
185 bool intel_find_matching_signature(void *mc, struct cpu_signature *sig)
186 {
187 	struct microcode_header_intel *mc_hdr = mc;
188 	struct extended_signature *ext_sig;
189 	struct extended_sigtable *ext_hdr;
190 	int i;
191 
192 	if (cpu_signatures_match(sig, mc_hdr->sig, mc_hdr->pf))
193 		return true;
194 
195 	/* Look for ext. headers: */
196 	if (get_totalsize(mc_hdr) <= intel_microcode_get_datasize(mc_hdr) + MC_HEADER_SIZE)
197 		return false;
198 
199 	ext_hdr = mc + intel_microcode_get_datasize(mc_hdr) + MC_HEADER_SIZE;
200 	ext_sig = (void *)ext_hdr + EXT_HEADER_SIZE;
201 
202 	for (i = 0; i < ext_hdr->count; i++) {
203 		if (cpu_signatures_match(sig, ext_sig->sig, ext_sig->pf))
204 			return true;
205 		ext_sig++;
206 	}
207 	return 0;
208 }
209 EXPORT_SYMBOL_GPL(intel_find_matching_signature);
210 
211 /**
212  * intel_microcode_sanity_check() - Sanity check microcode file.
213  * @mc: Pointer to the microcode file contents.
214  * @print_err: Display failure reason if true, silent if false.
215  * @hdr_type: Type of file, i.e. normal microcode file or In Field Scan file.
216  *            Validate if the microcode header type matches with the type
217  *            specified here.
218  *
219  * Validate certain header fields and verify if computed checksum matches
220  * with the one specified in the header.
221  *
222  * Return: 0 if the file passes all the checks, -EINVAL if any of the checks
223  * fail.
224  */
225 int intel_microcode_sanity_check(void *mc, bool print_err, int hdr_type)
226 {
227 	unsigned long total_size, data_size, ext_table_size;
228 	struct microcode_header_intel *mc_header = mc;
229 	struct extended_sigtable *ext_header = NULL;
230 	u32 sum, orig_sum, ext_sigcount = 0, i;
231 	struct extended_signature *ext_sig;
232 
233 	total_size = get_totalsize(mc_header);
234 	data_size = intel_microcode_get_datasize(mc_header);
235 
236 	if (data_size + MC_HEADER_SIZE > total_size) {
237 		if (print_err)
238 			pr_err("Error: bad microcode data file size.\n");
239 		return -EINVAL;
240 	}
241 
242 	if (mc_header->ldrver != 1 || mc_header->hdrver != hdr_type) {
243 		if (print_err)
244 			pr_err("Error: invalid/unknown microcode update format. Header type %d\n",
245 			       mc_header->hdrver);
246 		return -EINVAL;
247 	}
248 
249 	ext_table_size = total_size - (MC_HEADER_SIZE + data_size);
250 	if (ext_table_size) {
251 		u32 ext_table_sum = 0;
252 		u32 *ext_tablep;
253 
254 		if (ext_table_size < EXT_HEADER_SIZE ||
255 		    ((ext_table_size - EXT_HEADER_SIZE) % EXT_SIGNATURE_SIZE)) {
256 			if (print_err)
257 				pr_err("Error: truncated extended signature table.\n");
258 			return -EINVAL;
259 		}
260 
261 		ext_header = mc + MC_HEADER_SIZE + data_size;
262 		if (ext_table_size != exttable_size(ext_header)) {
263 			if (print_err)
264 				pr_err("Error: extended signature table size mismatch.\n");
265 			return -EFAULT;
266 		}
267 
268 		ext_sigcount = ext_header->count;
269 
270 		/*
271 		 * Check extended table checksum: the sum of all dwords that
272 		 * comprise a valid table must be 0.
273 		 */
274 		ext_tablep = (u32 *)ext_header;
275 
276 		i = ext_table_size / sizeof(u32);
277 		while (i--)
278 			ext_table_sum += ext_tablep[i];
279 
280 		if (ext_table_sum) {
281 			if (print_err)
282 				pr_warn("Bad extended signature table checksum, aborting.\n");
283 			return -EINVAL;
284 		}
285 	}
286 
287 	/*
288 	 * Calculate the checksum of update data and header. The checksum of
289 	 * valid update data and header including the extended signature table
290 	 * must be 0.
291 	 */
292 	orig_sum = 0;
293 	i = (MC_HEADER_SIZE + data_size) / sizeof(u32);
294 	while (i--)
295 		orig_sum += ((u32 *)mc)[i];
296 
297 	if (orig_sum) {
298 		if (print_err)
299 			pr_err("Bad microcode data checksum, aborting.\n");
300 		return -EINVAL;
301 	}
302 
303 	if (!ext_table_size)
304 		return 0;
305 
306 	/*
307 	 * Check extended signature checksum: 0 => valid.
308 	 */
309 	for (i = 0; i < ext_sigcount; i++) {
310 		ext_sig = (void *)ext_header + EXT_HEADER_SIZE +
311 			  EXT_SIGNATURE_SIZE * i;
312 
313 		sum = (mc_header->sig + mc_header->pf + mc_header->cksum) -
314 		      (ext_sig->sig + ext_sig->pf + ext_sig->cksum);
315 		if (sum) {
316 			if (print_err)
317 				pr_err("Bad extended signature checksum, aborting.\n");
318 			return -EINVAL;
319 		}
320 	}
321 	return 0;
322 }
323 EXPORT_SYMBOL_GPL(intel_microcode_sanity_check);
324 
325 static void update_ucode_pointer(struct microcode_intel *mc)
326 {
327 	kvfree(ucode_patch_va);
328 
329 	/*
330 	 * Save the virtual address for early loading and for eventual free
331 	 * on late loading.
332 	 */
333 	ucode_patch_va = mc;
334 }
335 
336 static void save_microcode_patch(struct microcode_intel *patch)
337 {
338 	unsigned int size = get_totalsize(&patch->hdr);
339 	struct microcode_intel *mc;
340 
341 	mc = kvmemdup(patch, size, GFP_KERNEL);
342 	if (mc)
343 		update_ucode_pointer(mc);
344 	else
345 		pr_err("Unable to allocate microcode memory size: %u\n", size);
346 }
347 
348 /* Scan blob for microcode matching the boot CPUs family, model, stepping */
349 static __init struct microcode_intel *scan_microcode(void *data, size_t size,
350 						     struct ucode_cpu_info *uci,
351 						     bool save)
352 {
353 	struct microcode_header_intel *mc_header;
354 	struct microcode_intel *patch = NULL;
355 	u32 cur_rev = uci->cpu_sig.rev;
356 	unsigned int mc_size;
357 
358 	for (; size >= sizeof(struct microcode_header_intel); size -= mc_size, data += mc_size) {
359 		mc_header = (struct microcode_header_intel *)data;
360 
361 		mc_size = get_totalsize(mc_header);
362 		if (!mc_size || mc_size > size ||
363 		    intel_microcode_sanity_check(data, false, MC_HEADER_TYPE_MICROCODE) < 0)
364 			break;
365 
366 		if (!intel_find_matching_signature(data, &uci->cpu_sig))
367 			continue;
368 
369 		/*
370 		 * For saving the early microcode, find the matching revision which
371 		 * was loaded on the BSP.
372 		 *
373 		 * On the BSP during early boot, find a newer revision than
374 		 * actually loaded in the CPU.
375 		 */
376 		if (save) {
377 			if (cur_rev != mc_header->rev)
378 				continue;
379 		} else if (cur_rev >= mc_header->rev) {
380 			continue;
381 		}
382 
383 		patch = data;
384 		cur_rev = mc_header->rev;
385 	}
386 
387 	return size ? NULL : patch;
388 }
389 
390 static inline u32 read_mbox_dword(void __iomem *mmio_base)
391 {
392 	u32 dword = readl(mmio_base + MBOX_RDDATA_OFFSET);
393 
394 	/* Acknowledge read completion to the staging hardware */
395 	writel(0, mmio_base + MBOX_RDDATA_OFFSET);
396 	return dword;
397 }
398 
399 static inline void write_mbox_dword(void __iomem *mmio_base, u32 dword)
400 {
401 	writel(dword, mmio_base + MBOX_WRDATA_OFFSET);
402 }
403 
404 static inline u64 read_mbox_header(void __iomem *mmio_base)
405 {
406 	u32 high, low;
407 
408 	low  = read_mbox_dword(mmio_base);
409 	high = read_mbox_dword(mmio_base);
410 
411 	return ((u64)high << 32) | low;
412 }
413 
414 static inline void write_mbox_header(void __iomem *mmio_base, u64 value)
415 {
416 	write_mbox_dword(mmio_base, value);
417 	write_mbox_dword(mmio_base, value >> 32);
418 }
419 
420 static void write_mbox_data(void __iomem *mmio_base, u32 *chunk, unsigned int chunk_bytes)
421 {
422 	int i;
423 
424 	/*
425 	 * The MMIO space is mapped as Uncached (UC). Each write arrives
426 	 * at the device as an individual transaction in program order.
427 	 * The device can then reassemble the sequence accordingly.
428 	 */
429 	for (i = 0; i < chunk_bytes / sizeof(u32); i++)
430 		write_mbox_dword(mmio_base, chunk[i]);
431 }
432 
433 /*
434  * Prepare for a new microcode transfer: reset hardware and record the
435  * image size.
436  */
437 static void init_stage(struct staging_state *ss)
438 {
439 	ss->ucode_len = get_totalsize(&ucode_patch_late->hdr);
440 
441 	/*
442 	 * Abort any ongoing process, effectively resetting the device.
443 	 * Unlike regular mailbox data processing requests, this
444 	 * operation does not require a status check.
445 	 */
446 	writel(MASK_MBOX_CTRL_ABORT, ss->mmio_base + MBOX_CONTROL_OFFSET);
447 }
448 
449 /*
450  * Update the chunk size and decide whether another chunk can be sent.
451  * This accounts for remaining data and retry limits.
452  */
453 static bool can_send_next_chunk(struct staging_state *ss, int *err)
454 {
455 	/* A page size or remaining bytes if this is the final chunk */
456 	ss->chunk_size = min(PAGE_SIZE, ss->ucode_len - ss->offset);
457 
458 	/*
459 	 * Each microcode image is divided into chunks, each at most
460 	 * one page size. A 10-chunk image would typically require 10
461 	 * transactions.
462 	 *
463 	 * However, the hardware managing the mailbox has limited
464 	 * resources and may not cache the entire image, potentially
465 	 * requesting the same chunk multiple times.
466 	 *
467 	 * To tolerate this behavior, allow up to twice the expected
468 	 * number of transactions (i.e., a 10-chunk image can take up to
469 	 * 20 attempts).
470 	 *
471 	 * If the number of attempts exceeds this limit, treat it as
472 	 * exceeding the maximum allowed transfer size.
473 	 */
474 	if (ss->bytes_sent + ss->chunk_size > ss->ucode_len * 2) {
475 		*err = -EMSGSIZE;
476 		return false;
477 	}
478 
479 	*err = 0;
480 	return true;
481 }
482 
483 /*
484  * The hardware indicates completion by returning a sentinel end offset.
485  */
486 static inline bool is_end_offset(u32 offset)
487 {
488 	return offset == UINT_MAX;
489 }
490 
491 /*
492  * Determine whether staging is complete: either the hardware signaled
493  * the end offset, or no more transactions are permitted (retry limit
494  * reached).
495  */
496 static inline bool staging_is_complete(struct staging_state *ss, int *err)
497 {
498 	return is_end_offset(ss->offset) || !can_send_next_chunk(ss, err);
499 }
500 
501 /*
502  * Wait for the hardware to complete a transaction.
503  * Return 0 on success, or an error code on failure.
504  */
505 static int wait_for_transaction(struct staging_state *ss)
506 {
507 	u32 timeout, status;
508 
509 	/* Allow time for hardware to complete the operation: */
510 	for (timeout = 0; timeout < MBOX_XACTION_TIMEOUT_MS; timeout++) {
511 		msleep(1);
512 
513 		status = readl(ss->mmio_base + MBOX_STATUS_OFFSET);
514 		/* Break out early if the hardware is ready: */
515 		if (status & MASK_MBOX_STATUS_READY)
516 			break;
517 	}
518 
519 	/* Check for explicit error response */
520 	if (status & MASK_MBOX_STATUS_ERROR)
521 		return -EIO;
522 
523 	/*
524 	 * Hardware has neither responded to the action nor signaled any
525 	 * error. Treat this as a timeout.
526 	 */
527 	if (!(status & MASK_MBOX_STATUS_READY))
528 		return -ETIMEDOUT;
529 
530 	return 0;
531 }
532 
533 /*
534  * Transmit a chunk of the microcode image to the hardware.
535  * Return 0 on success, or an error code on failure.
536  */
537 static int send_data_chunk(struct staging_state *ss, void *ucode_ptr)
538 {
539 	u32 *src_chunk = ucode_ptr + ss->offset;
540 	u16 mbox_size;
541 
542 	/*
543 	 * Write a 'request' mailbox object in this order:
544 	 *  1. Mailbox header includes total size
545 	 *  2. Command header specifies the load operation
546 	 *  3. Data section contains a microcode chunk
547 	 *
548 	 * Thus, the mailbox size is two headers plus the chunk size.
549 	 */
550 	mbox_size = MBOX_HEADER_SIZE * 2 + ss->chunk_size;
551 	write_mbox_header(ss->mmio_base, MBOX_HEADER(mbox_size));
552 	write_mbox_header(ss->mmio_base, MBOX_CMD_LOAD);
553 	write_mbox_data(ss->mmio_base, src_chunk, ss->chunk_size);
554 	ss->bytes_sent += ss->chunk_size;
555 
556 	/* Notify the hardware that the mailbox is ready for processing. */
557 	writel(MASK_MBOX_CTRL_GO, ss->mmio_base + MBOX_CONTROL_OFFSET);
558 
559 	return wait_for_transaction(ss);
560 }
561 
562 /*
563  * Retrieve the next offset from the hardware response.
564  * Return 0 on success, or an error code on failure.
565  */
566 static int fetch_next_offset(struct staging_state *ss)
567 {
568 	const u64 expected_header = MBOX_HEADER(MBOX_HEADER_SIZE + MBOX_RESPONSE_SIZE);
569 	u32 offset, status;
570 	u64 header;
571 
572 	/*
573 	 * The 'response' mailbox returns three fields, in order:
574 	 *  1. Header
575 	 *  2. Next offset in the microcode image
576 	 *  3. Status flags
577 	 */
578 	header = read_mbox_header(ss->mmio_base);
579 	offset = read_mbox_dword(ss->mmio_base);
580 	status = read_mbox_dword(ss->mmio_base);
581 
582 	/* All valid responses must start with the expected header. */
583 	if (header != expected_header) {
584 		pr_err_once("staging: invalid response header (0x%llx)\n", header);
585 		return -EBADR;
586 	}
587 
588 	/*
589 	 * Verify the offset: If not at the end marker, it must not
590 	 * exceed the microcode image length.
591 	 */
592 	if (!is_end_offset(offset) && offset > ss->ucode_len) {
593 		pr_err_once("staging: invalid offset (%u) past the image end (%u)\n",
594 			    offset, ss->ucode_len);
595 		return -EINVAL;
596 	}
597 
598 	/* Hardware may report errors explicitly in the status field */
599 	if (status & MASK_MBOX_RESP_ERROR)
600 		return -EPROTO;
601 
602 	ss->offset = offset;
603 	return 0;
604 }
605 
606 /*
607  * Handle the staging process using the mailbox MMIO interface. The
608  * microcode image is transferred in chunks until completion.
609  * Return 0 on success or an error code on failure.
610  */
611 static int do_stage(u64 mmio_pa)
612 {
613 	struct staging_state ss = {};
614 	int err;
615 
616 	ss.mmio_base = ioremap(mmio_pa, MBOX_REG_NUM * MBOX_REG_SIZE);
617 	if (WARN_ON_ONCE(!ss.mmio_base))
618 		return -EADDRNOTAVAIL;
619 
620 	init_stage(&ss);
621 
622 	/* Perform the staging process while within the retry limit */
623 	while (!staging_is_complete(&ss, &err)) {
624 		/* Send a chunk of microcode each time: */
625 		err = send_data_chunk(&ss, ucode_patch_late);
626 		if (err)
627 			break;
628 		/*
629 		 * Then, ask the hardware which piece of the image it
630 		 * needs next. The same piece may be sent more than once.
631 		 */
632 		err = fetch_next_offset(&ss);
633 		if (err)
634 			break;
635 	}
636 
637 	iounmap(ss.mmio_base);
638 
639 	return err;
640 }
641 
642 static void stage_microcode(void)
643 {
644 	unsigned int pkg_id = UINT_MAX;
645 	int cpu, err;
646 	u64 mmio_pa;
647 
648 	if (!IS_ALIGNED(get_totalsize(&ucode_patch_late->hdr), sizeof(u32))) {
649 		pr_err("Microcode image 32-bit misaligned (0x%x), staging failed.\n",
650 			get_totalsize(&ucode_patch_late->hdr));
651 		return;
652 	}
653 
654 	lockdep_assert_cpus_held();
655 
656 	/*
657 	 * The MMIO address is unique per package, and all the SMT
658 	 * primary threads are online here. Find each MMIO space by
659 	 * their package IDs to avoid duplicate staging.
660 	 */
661 	for_each_cpu(cpu, cpu_primary_thread_mask) {
662 		if (topology_logical_package_id(cpu) == pkg_id)
663 			continue;
664 
665 		pkg_id = topology_logical_package_id(cpu);
666 
667 		err = rdmsrq_on_cpu(cpu, MSR_IA32_MCU_STAGING_MBOX_ADDR, &mmio_pa);
668 		if (WARN_ON_ONCE(err))
669 			return;
670 
671 		err = do_stage(mmio_pa);
672 		if (err) {
673 			pr_err("Error: staging failed (%d) for CPU%d at package %u.\n",
674 			       err, cpu, pkg_id);
675 			return;
676 		}
677 	}
678 
679 	pr_info("Staging of patch revision 0x%x succeeded.\n", ucode_patch_late->hdr.rev);
680 }
681 
682 static enum ucode_state __apply_microcode(struct ucode_cpu_info *uci,
683 					  struct microcode_intel *mc,
684 					  u32 *cur_rev)
685 {
686 	u32 rev;
687 
688 	if (!mc)
689 		return UCODE_NFOUND;
690 
691 	/*
692 	 * Save us the MSR write below - which is a particular expensive
693 	 * operation - when the other hyperthread has updated the microcode
694 	 * already.
695 	 */
696 	*cur_rev = intel_get_microcode_revision();
697 	if (*cur_rev >= mc->hdr.rev) {
698 		uci->cpu_sig.rev = *cur_rev;
699 		return UCODE_OK;
700 	}
701 
702 	/* write microcode via MSR 0x79 */
703 	native_wrmsrq(MSR_IA32_UCODE_WRITE, (unsigned long)mc->bits);
704 
705 	rev = intel_get_microcode_revision();
706 	if (rev != mc->hdr.rev)
707 		return UCODE_ERROR;
708 
709 	uci->cpu_sig.rev = rev;
710 	return UCODE_UPDATED;
711 }
712 
713 static enum ucode_state apply_microcode_early(struct ucode_cpu_info *uci)
714 {
715 	struct microcode_intel *mc = uci->mc;
716 	u32 cur_rev;
717 
718 	return __apply_microcode(uci, mc, &cur_rev);
719 }
720 
721 static __init bool load_builtin_intel_microcode(struct cpio_data *cp)
722 {
723 	unsigned int eax = 1, ebx, ecx = 0, edx;
724 	struct firmware fw;
725 	char name[30];
726 
727 	if (IS_ENABLED(CONFIG_X86_32))
728 		return false;
729 
730 	native_cpuid(&eax, &ebx, &ecx, &edx);
731 
732 	sprintf(name, "intel-ucode/%02x-%02x-%02x",
733 		x86_family(eax), x86_model(eax), x86_stepping(eax));
734 
735 	if (firmware_request_builtin(&fw, name)) {
736 		cp->size = fw.size;
737 		cp->data = (void *)fw.data;
738 		return true;
739 	}
740 	return false;
741 }
742 
743 static __init struct microcode_intel *get_microcode_blob(struct ucode_cpu_info *uci, bool save)
744 {
745 	struct cpio_data cp;
746 
747 	intel_collect_cpu_info(&uci->cpu_sig);
748 
749 	if (!load_builtin_intel_microcode(&cp))
750 		cp = find_microcode_in_initrd(ucode_path);
751 
752 	if (!(cp.data && cp.size))
753 		return NULL;
754 
755 	return scan_microcode(cp.data, cp.size, uci, save);
756 }
757 
758 /*
759  * Invoked from an early init call to save the microcode blob which was
760  * selected during early boot when mm was not usable. The microcode must be
761  * saved because initrd is going away. It's an early init call so the APs
762  * just can use the pointer and do not have to scan initrd/builtin firmware
763  * again.
764  */
765 static int __init save_builtin_microcode(void)
766 {
767 	struct ucode_cpu_info uci;
768 
769 	if (xchg(&ucode_patch_va, NULL) != UCODE_BSP_LOADED)
770 		return 0;
771 
772 	if (microcode_loader_disabled() || boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
773 		return 0;
774 
775 	uci.mc = get_microcode_blob(&uci, true);
776 	if (uci.mc)
777 		save_microcode_patch(uci.mc);
778 	return 0;
779 }
780 early_initcall(save_builtin_microcode);
781 
782 /* Load microcode on BSP from initrd or builtin blobs */
783 void __init load_ucode_intel_bsp(struct early_load_data *ed)
784 {
785 	struct ucode_cpu_info uci;
786 
787 	uci.mc = get_microcode_blob(&uci, false);
788 	ed->old_rev = uci.cpu_sig.rev;
789 
790 	if (uci.mc && apply_microcode_early(&uci) == UCODE_UPDATED) {
791 		ucode_patch_va = UCODE_BSP_LOADED;
792 		ed->new_rev = uci.cpu_sig.rev;
793 	}
794 }
795 
796 void load_ucode_intel_ap(void)
797 {
798 	struct ucode_cpu_info uci;
799 
800 	uci.mc = ucode_patch_va;
801 	if (uci.mc)
802 		apply_microcode_early(&uci);
803 }
804 
805 /* Reload microcode on resume */
806 void reload_ucode_intel(void)
807 {
808 	struct ucode_cpu_info uci = { .mc = ucode_patch_va, };
809 
810 	if (uci.mc)
811 		apply_microcode_early(&uci);
812 }
813 
814 static int collect_cpu_info(int cpu_num, struct cpu_signature *csig)
815 {
816 	intel_collect_cpu_info(csig);
817 	return 0;
818 }
819 
820 static enum ucode_state apply_microcode_late(int cpu)
821 {
822 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
823 	struct microcode_intel *mc = ucode_patch_late;
824 	enum ucode_state ret;
825 	u32 cur_rev;
826 
827 	if (WARN_ON_ONCE(smp_processor_id() != cpu))
828 		return UCODE_ERROR;
829 
830 	ret = __apply_microcode(uci, mc, &cur_rev);
831 	if (ret != UCODE_UPDATED && ret != UCODE_OK)
832 		return ret;
833 
834 	cpu_data(cpu).microcode	 = uci->cpu_sig.rev;
835 	if (!cpu)
836 		boot_cpu_data.microcode = uci->cpu_sig.rev;
837 
838 	return ret;
839 }
840 
841 static bool ucode_validate_minrev(struct microcode_header_intel *mc_header)
842 {
843 	int cur_rev = boot_cpu_data.microcode;
844 
845 	/*
846 	 * When late-loading, ensure the header declares a minimum revision
847 	 * required to perform a late-load. The previously reserved field
848 	 * is 0 in older microcode blobs.
849 	 */
850 	if (!mc_header->min_req_ver) {
851 		pr_info("Unsafe microcode update: Microcode header does not specify a required min version\n");
852 		return false;
853 	}
854 
855 	/*
856 	 * Check whether the current revision is either greater or equal to
857 	 * to the minimum revision specified in the header.
858 	 */
859 	if (cur_rev < mc_header->min_req_ver) {
860 		pr_info("Unsafe microcode update: Current revision 0x%x too old\n", cur_rev);
861 		pr_info("Current should be at 0x%x or higher. Use early loading instead\n", mc_header->min_req_ver);
862 		return false;
863 	}
864 	return true;
865 }
866 
867 static enum ucode_state parse_microcode_blobs(int cpu, struct iov_iter *iter)
868 {
869 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
870 	bool is_safe, new_is_safe = false;
871 	int cur_rev = uci->cpu_sig.rev;
872 	unsigned int curr_mc_size = 0;
873 	u8 *new_mc = NULL, *mc = NULL;
874 
875 	while (iov_iter_count(iter)) {
876 		struct microcode_header_intel mc_header;
877 		unsigned int mc_size, data_size;
878 		u8 *data;
879 
880 		if (!copy_from_iter_full(&mc_header, sizeof(mc_header), iter)) {
881 			pr_err("error! Truncated or inaccessible header in microcode data file\n");
882 			goto fail;
883 		}
884 
885 		mc_size = get_totalsize(&mc_header);
886 		if (mc_size < sizeof(mc_header)) {
887 			pr_err("error! Bad data in microcode data file (totalsize too small)\n");
888 			goto fail;
889 		}
890 		data_size = mc_size - sizeof(mc_header);
891 		if (data_size > iov_iter_count(iter)) {
892 			pr_err("error! Bad data in microcode data file (truncated file?)\n");
893 			goto fail;
894 		}
895 
896 		/* For performance reasons, reuse mc area when possible */
897 		if (!mc || mc_size > curr_mc_size) {
898 			kvfree(mc);
899 			mc = kvmalloc(mc_size, GFP_KERNEL);
900 			if (!mc)
901 				goto fail;
902 			curr_mc_size = mc_size;
903 		}
904 
905 		memcpy(mc, &mc_header, sizeof(mc_header));
906 		data = mc + sizeof(mc_header);
907 		if (!copy_from_iter_full(data, data_size, iter) ||
908 		    intel_microcode_sanity_check(mc, true, MC_HEADER_TYPE_MICROCODE) < 0)
909 			goto fail;
910 
911 		if (cur_rev >= mc_header.rev)
912 			continue;
913 
914 		if (!intel_find_matching_signature(mc, &uci->cpu_sig))
915 			continue;
916 
917 		is_safe = ucode_validate_minrev(&mc_header);
918 		if (force_minrev && !is_safe)
919 			continue;
920 
921 		kvfree(new_mc);
922 		cur_rev = mc_header.rev;
923 		new_mc  = mc;
924 		new_is_safe = is_safe;
925 		mc = NULL;
926 	}
927 
928 	if (iov_iter_count(iter))
929 		goto fail;
930 
931 	kvfree(mc);
932 	if (!new_mc)
933 		return UCODE_NFOUND;
934 
935 	ucode_patch_late = (struct microcode_intel *)new_mc;
936 	return new_is_safe ? UCODE_NEW_SAFE : UCODE_NEW;
937 
938 fail:
939 	kvfree(mc);
940 	kvfree(new_mc);
941 	return UCODE_ERROR;
942 }
943 
944 static bool is_blacklisted(unsigned int cpu)
945 {
946 	struct cpuinfo_x86 *c = &cpu_data(cpu);
947 
948 	/*
949 	 * Late loading on model 79 with microcode revision less than 0x0b000021
950 	 * and LLC size per core bigger than 2.5MB may result in a system hang.
951 	 * This behavior is documented in item BDX90, #334165 (Intel Xeon
952 	 * Processor E7-8800/4800 v4 Product Family).
953 	 */
954 	if (c->x86_vfm == INTEL_BROADWELL_X &&
955 	    c->x86_stepping == 0x01 &&
956 	    llc_size_per_core > 2621440 &&
957 	    c->microcode < 0x0b000021) {
958 		pr_err_once("Erratum BDX90: late loading with revision < 0x0b000021 (0x%x) disabled.\n", c->microcode);
959 		pr_err_once("Please consider either early loading through initrd/built-in or a potential BIOS update.\n");
960 		return true;
961 	}
962 
963 	return false;
964 }
965 
966 static enum ucode_state request_microcode_fw(int cpu, struct device *device)
967 {
968 	struct cpuinfo_x86 *c = &cpu_data(cpu);
969 	const struct firmware *firmware;
970 	struct iov_iter iter;
971 	enum ucode_state ret;
972 	struct kvec kvec;
973 	char name[30];
974 
975 	if (is_blacklisted(cpu))
976 		return UCODE_NFOUND;
977 
978 	sprintf(name, "intel-ucode/%02x-%02x-%02x",
979 		c->x86, c->x86_model, c->x86_stepping);
980 
981 	if (request_firmware_direct(&firmware, name, device)) {
982 		pr_debug("data file %s load failed\n", name);
983 		return UCODE_NFOUND;
984 	}
985 
986 	kvec.iov_base = (void *)firmware->data;
987 	kvec.iov_len = firmware->size;
988 	iov_iter_kvec(&iter, ITER_SOURCE, &kvec, 1, firmware->size);
989 	ret = parse_microcode_blobs(cpu, &iter);
990 
991 	release_firmware(firmware);
992 
993 	return ret;
994 }
995 
996 static void finalize_late_load(int result)
997 {
998 	if (!result)
999 		update_ucode_pointer(ucode_patch_late);
1000 	else
1001 		kvfree(ucode_patch_late);
1002 	ucode_patch_late = NULL;
1003 }
1004 
1005 static struct microcode_ops microcode_intel_ops = {
1006 	.request_microcode_fw	= request_microcode_fw,
1007 	.collect_cpu_info	= collect_cpu_info,
1008 	.apply_microcode	= apply_microcode_late,
1009 	.finalize_late_load	= finalize_late_load,
1010 	.stage_microcode	= stage_microcode,
1011 	.use_nmi		= IS_ENABLED(CONFIG_X86_64),
1012 };
1013 
1014 static __init void calc_llc_size_per_core(struct cpuinfo_x86 *c)
1015 {
1016 	u64 llc_size = c->x86_cache_size * 1024ULL;
1017 
1018 	do_div(llc_size, topology_num_cores_per_package());
1019 	llc_size_per_core = (unsigned int)llc_size;
1020 }
1021 
1022 static __init bool staging_available(void)
1023 {
1024 	u64 val;
1025 
1026 	val = x86_read_arch_cap_msr();
1027 	if (!(val & ARCH_CAP_MCU_ENUM))
1028 		return false;
1029 
1030 	rdmsrq(MSR_IA32_MCU_ENUMERATION, val);
1031 	return !!(val & MCU_STAGING);
1032 }
1033 
1034 struct microcode_ops * __init init_intel_microcode(void)
1035 {
1036 	struct cpuinfo_x86 *c = &boot_cpu_data;
1037 
1038 	if (c->x86_vendor != X86_VENDOR_INTEL || c->x86 < 6 ||
1039 	    cpu_has(c, X86_FEATURE_IA64)) {
1040 		pr_err("Intel CPU family 0x%x not supported\n", c->x86);
1041 		return NULL;
1042 	}
1043 
1044 	if (staging_available()) {
1045 		microcode_intel_ops.use_staging = true;
1046 		pr_info("Enabled staging feature.\n");
1047 	}
1048 
1049 	calc_llc_size_per_core(c);
1050 
1051 	return &microcode_intel_ops;
1052 }
1053