xref: /linux/arch/x86/kernel/cpu/microcode/amd.c (revision 7b49a3fb69e785a2425c8dc7dbd0779a0a4c0eb2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  AMD CPU Microcode Update Driver for Linux
4  *
5  *  This driver allows to upgrade microcode on F10h AMD
6  *  CPUs and later.
7  *
8  *  Copyright (C) 2008-2011 Advanced Micro Devices Inc.
9  *	          2013-2018 Borislav Petkov <bp@alien8.de>
10  *
11  *  Author: Peter Oruba <peter.oruba@amd.com>
12  *
13  *  Based on work by:
14  *  Tigran Aivazian <aivazian.tigran@gmail.com>
15  *
16  *  early loader:
17  *  Copyright (C) 2013 Advanced Micro Devices, Inc.
18  *
19  *  Author: Jacob Shin <jacob.shin@amd.com>
20  *  Fixes: Borislav Petkov <bp@suse.de>
21  */
22 #define pr_fmt(fmt) "microcode: " fmt
23 
24 #include <linux/earlycpio.h>
25 #include <linux/firmware.h>
26 #include <linux/bsearch.h>
27 #include <linux/uaccess.h>
28 #include <linux/vmalloc.h>
29 #include <linux/initrd.h>
30 #include <linux/kernel.h>
31 #include <linux/pci.h>
32 
33 #include <crypto/sha2.h>
34 
35 #include <asm/microcode.h>
36 #include <asm/processor.h>
37 #include <asm/cpuid/api.h>
38 #include <asm/cmdline.h>
39 #include <asm/setup.h>
40 #include <asm/cpu.h>
41 #include <asm/msr.h>
42 #include <asm/tlb.h>
43 
44 #include "internal.h"
45 
46 struct ucode_patch {
47 	struct list_head plist;
48 	void *data;
49 	unsigned int size;
50 	u32 patch_id;
51 	u16 equiv_cpu;
52 };
53 
54 static LIST_HEAD(microcode_cache);
55 
56 #define UCODE_MAGIC			0x00414d44
57 #define UCODE_EQUIV_CPU_TABLE_TYPE	0x00000000
58 #define UCODE_UCODE_TYPE		0x00000001
59 
60 #define SECTION_HDR_SIZE		8
61 #define CONTAINER_HDR_SZ		12
62 
63 struct equiv_cpu_entry {
64 	u32	installed_cpu;
65 	u32	fixed_errata_mask;
66 	u32	fixed_errata_compare;
67 	u16	equiv_cpu;
68 	u16	res;
69 } __packed;
70 
71 struct microcode_header_amd {
72 	u32	data_code;
73 	u32	patch_id;
74 	u16	mc_patch_data_id;
75 	u8	mc_patch_data_len;
76 	u8	init_flag;
77 	u32	mc_patch_data_checksum;
78 	u32	nb_dev_id;
79 	u32	sb_dev_id;
80 	u16	processor_rev_id;
81 	u8	nb_rev_id;
82 	u8	sb_rev_id;
83 	u8	bios_api_rev;
84 	u8	reserved1[3];
85 	u32	match_reg[8];
86 } __packed;
87 
88 struct microcode_amd {
89 	struct microcode_header_amd	hdr;
90 	unsigned int			mpb[];
91 };
92 
93 static struct equiv_cpu_table {
94 	unsigned int num_entries;
95 	struct equiv_cpu_entry *entry;
96 } equiv_table;
97 
98 union zen_patch_rev {
99 	struct {
100 		__u32 rev	 : 8,
101 		      stepping	 : 4,
102 		      model	 : 4,
103 		      __reserved : 4,
104 		      ext_model	 : 4,
105 		      ext_fam	 : 8;
106 	};
107 	__u32 ucode_rev;
108 };
109 
110 union cpuid_1_eax {
111 	struct {
112 		__u32 stepping    : 4,
113 		      model	  : 4,
114 		      family	  : 4,
115 		      __reserved0 : 4,
116 		      ext_model   : 4,
117 		      ext_fam     : 8,
118 		      __reserved1 : 4;
119 	};
120 	__u32 full;
121 };
122 
123 /*
124  * This points to the current valid container of microcode patches which we will
125  * save from the initrd/builtin before jettisoning its contents. @mc is the
126  * microcode patch we found to match.
127  */
128 struct cont_desc {
129 	struct microcode_amd *mc;
130 	u32		     psize;
131 	u8		     *data;
132 	size_t		     size;
133 };
134 
135 /*
136  * Microcode patch container file is prepended to the initrd in cpio
137  * format. See Documentation/arch/x86/microcode.rst
138  */
139 static const char
140 ucode_path[] __maybe_unused = "kernel/x86/microcode/AuthenticAMD.bin";
141 
142 /*
143  * This is CPUID(1).EAX on the BSP. It is used in two ways:
144  *
145  * 1. To ignore the equivalence table on Zen1 and newer.
146  *
147  * 2. To match which patches to load because the patch revision ID
148  *    already contains the f/m/s for which the microcode is destined
149  *    for.
150  */
151 static u32 bsp_cpuid_1_eax __ro_after_init;
152 
153 static bool sha_check = true;
154 
155 struct patch_digest {
156 	u32 patch_id;
157 	u8 sha256[SHA256_DIGEST_SIZE];
158 };
159 
160 #include "amd_shas.c"
161 
162 static int cmp_id(const void *key, const void *elem)
163 {
164 	struct patch_digest *pd = (struct patch_digest *)elem;
165 	u32 patch_id = *(u32 *)key;
166 
167 	if (patch_id == pd->patch_id)
168 		return 0;
169 	else if (patch_id < pd->patch_id)
170 		return -1;
171 	else
172 		return 1;
173 }
174 
175 static u32 cpuid_to_ucode_rev(unsigned int val)
176 {
177 	union zen_patch_rev p = {};
178 	union cpuid_1_eax c;
179 
180 	c.full = val;
181 
182 	p.stepping  = c.stepping;
183 	p.model     = c.model;
184 	p.ext_model = c.ext_model;
185 	p.ext_fam   = c.ext_fam;
186 
187 	return p.ucode_rev;
188 }
189 
190 static u32 get_cutoff_revision(u32 rev)
191 {
192 	switch (rev >> 8) {
193 	case 0x80012: return 0x8001277; break;
194 	case 0x80082: return 0x800820f; break;
195 	case 0x83010: return 0x830107c; break;
196 	case 0x86001: return 0x860010e; break;
197 	case 0x86081: return 0x8608108; break;
198 	case 0x87010: return 0x8701034; break;
199 	case 0x8a000: return 0x8a0000a; break;
200 	case 0xa0010: return 0xa00107a; break;
201 	case 0xa0011: return 0xa0011da; break;
202 	case 0xa0012: return 0xa001243; break;
203 	case 0xa0082: return 0xa00820e; break;
204 	case 0xa1011: return 0xa101153; break;
205 	case 0xa1012: return 0xa10124e; break;
206 	case 0xa1081: return 0xa108109; break;
207 	case 0xa2010: return 0xa20102f; break;
208 	case 0xa2012: return 0xa201212; break;
209 	case 0xa4041: return 0xa404109; break;
210 	case 0xa5000: return 0xa500013; break;
211 	case 0xa6012: return 0xa60120a; break;
212 	case 0xa7041: return 0xa704109; break;
213 	case 0xa7052: return 0xa705208; break;
214 	case 0xa7080: return 0xa708009; break;
215 	case 0xa70c0: return 0xa70C009; break;
216 	case 0xaa001: return 0xaa00116; break;
217 	case 0xaa002: return 0xaa00218; break;
218 	case 0xb0021: return 0xb002146; break;
219 	case 0xb0081: return 0xb008111; break;
220 	case 0xb1010: return 0xb101046; break;
221 	case 0xb2040: return 0xb204031; break;
222 	case 0xb4040: return 0xb404031; break;
223 	case 0xb4041: return 0xb404101; break;
224 	case 0xb6000: return 0xb600031; break;
225 	case 0xb6080: return 0xb608031; break;
226 	case 0xb7000: return 0xb700031; break;
227 	default: break;
228 
229 	}
230 	return 0;
231 }
232 
233 static bool need_sha_check(u32 cur_rev)
234 {
235 	u32 cutoff;
236 
237 	if (!cur_rev) {
238 		cur_rev = cpuid_to_ucode_rev(bsp_cpuid_1_eax);
239 		pr_info_once("No current revision, generating the lowest one: 0x%x\n", cur_rev);
240 	}
241 
242 	cutoff = get_cutoff_revision(cur_rev);
243 	if (cutoff)
244 		return cur_rev <= cutoff;
245 
246 	pr_info("You should not be seeing this. Please send the following couple of lines to x86-<at>-kernel.org\n");
247 	pr_info("CPUID(1).EAX: 0x%x, current revision: 0x%x\n", bsp_cpuid_1_eax, cur_rev);
248 	return true;
249 }
250 
251 static bool cpu_has_entrysign(void)
252 {
253 	unsigned int fam   = x86_family(bsp_cpuid_1_eax);
254 	unsigned int model = x86_model(bsp_cpuid_1_eax);
255 
256 	if (fam == 0x17 || fam == 0x19)
257 		return true;
258 
259 	if (fam == 0x1a) {
260 		if (model <= 0x2f ||
261 		    (0x40 <= model && model <= 0x4f) ||
262 		    (0x60 <= model && model <= 0x7f))
263 			return true;
264 	}
265 
266 	return false;
267 }
268 
269 static bool verify_sha256_digest(u32 patch_id, u32 cur_rev, const u8 *data, unsigned int len)
270 {
271 	struct patch_digest *pd = NULL;
272 	u8 digest[SHA256_DIGEST_SIZE];
273 	int i;
274 
275 	if (!cpu_has_entrysign())
276 		return true;
277 
278 	if (!need_sha_check(cur_rev))
279 		return true;
280 
281 	if (!sha_check)
282 		return true;
283 
284 	pd = bsearch(&patch_id, phashes, ARRAY_SIZE(phashes), sizeof(struct patch_digest), cmp_id);
285 	if (!pd) {
286 		pr_err("No sha256 digest for patch ID: 0x%x found\n", patch_id);
287 		return false;
288 	}
289 
290 	sha256(data, len, digest);
291 
292 	if (memcmp(digest, pd->sha256, sizeof(digest))) {
293 		pr_err("Patch 0x%x SHA256 digest mismatch!\n", patch_id);
294 
295 		for (i = 0; i < SHA256_DIGEST_SIZE; i++)
296 			pr_cont("0x%x ", digest[i]);
297 		pr_info("\n");
298 
299 		return false;
300 	}
301 
302 	return true;
303 }
304 
305 static union cpuid_1_eax ucode_rev_to_cpuid(unsigned int val)
306 {
307 	union zen_patch_rev p;
308 	union cpuid_1_eax c;
309 
310 	p.ucode_rev = val;
311 	c.full = 0;
312 
313 	c.stepping  = p.stepping;
314 	c.model     = p.model;
315 	c.ext_model = p.ext_model;
316 	c.family    = 0xf;
317 	c.ext_fam   = p.ext_fam;
318 
319 	return c;
320 }
321 
322 static u32 get_patch_level(void)
323 {
324 	u32 rev, dummy __always_unused;
325 
326 	if (IS_ENABLED(CONFIG_MICROCODE_DBG) && hypervisor_present) {
327 		int cpu = smp_processor_id();
328 
329 		if (!microcode_rev[cpu]) {
330 			if (!base_rev)
331 				base_rev = cpuid_to_ucode_rev(bsp_cpuid_1_eax);
332 
333 			microcode_rev[cpu] = base_rev;
334 
335 			ucode_dbg("CPU%d, base_rev: 0x%x\n", cpu, base_rev);
336 		}
337 
338 		return microcode_rev[cpu];
339 	}
340 
341 	native_rdmsr(MSR_AMD64_PATCH_LEVEL, rev, dummy);
342 
343 	return rev;
344 }
345 
346 static u16 find_equiv_id(struct equiv_cpu_table *et, u32 sig)
347 {
348 	unsigned int i;
349 
350 	/* Zen and newer do not need an equivalence table. */
351 	if (x86_family(bsp_cpuid_1_eax) >= 0x17)
352 		return 0;
353 
354 	if (!et || !et->num_entries)
355 		return 0;
356 
357 	for (i = 0; i < et->num_entries; i++) {
358 		struct equiv_cpu_entry *e = &et->entry[i];
359 
360 		if (sig == e->installed_cpu)
361 			return e->equiv_cpu;
362 	}
363 	return 0;
364 }
365 
366 /*
367  * Check whether there is a valid microcode container file at the beginning
368  * of @buf of size @buf_size.
369  */
370 static bool verify_container(const u8 *buf, size_t buf_size)
371 {
372 	u32 cont_magic;
373 
374 	if (buf_size <= CONTAINER_HDR_SZ) {
375 		ucode_dbg("Truncated microcode container header.\n");
376 		return false;
377 	}
378 
379 	cont_magic = *(const u32 *)buf;
380 	if (cont_magic != UCODE_MAGIC) {
381 		ucode_dbg("Invalid magic value (0x%08x).\n", cont_magic);
382 		return false;
383 	}
384 
385 	return true;
386 }
387 
388 /*
389  * Check whether there is a valid, non-truncated CPU equivalence table at the
390  * beginning of @buf of size @buf_size.
391  */
392 static bool verify_equivalence_table(const u8 *buf, size_t buf_size)
393 {
394 	const u32 *hdr = (const u32 *)buf;
395 	u32 cont_type, equiv_tbl_len;
396 
397 	if (!verify_container(buf, buf_size))
398 		return false;
399 
400 	/* Zen and newer do not need an equivalence table. */
401 	if (x86_family(bsp_cpuid_1_eax) >= 0x17)
402 		return true;
403 
404 	cont_type = hdr[1];
405 	if (cont_type != UCODE_EQUIV_CPU_TABLE_TYPE) {
406 		ucode_dbg("Wrong microcode container equivalence table type: %u.\n",
407 			  cont_type);
408 		return false;
409 	}
410 
411 	buf_size -= CONTAINER_HDR_SZ;
412 
413 	equiv_tbl_len = hdr[2];
414 	if (equiv_tbl_len < sizeof(struct equiv_cpu_entry) ||
415 	    buf_size < equiv_tbl_len) {
416 		ucode_dbg("Truncated equivalence table.\n");
417 		return false;
418 	}
419 
420 	return true;
421 }
422 
423 /*
424  * Check whether there is a valid, non-truncated microcode patch section at the
425  * beginning of @buf of size @buf_size.
426  *
427  * On success, @sh_psize returns the patch size according to the section header,
428  * to the caller.
429  */
430 static bool __verify_patch_section(const u8 *buf, size_t buf_size, u32 *sh_psize)
431 {
432 	u32 p_type, p_size;
433 	const u32 *hdr;
434 
435 	if (buf_size < SECTION_HDR_SIZE) {
436 		ucode_dbg("Truncated patch section.\n");
437 		return false;
438 	}
439 
440 	hdr = (const u32 *)buf;
441 	p_type = hdr[0];
442 	p_size = hdr[1];
443 
444 	if (p_type != UCODE_UCODE_TYPE) {
445 		ucode_dbg("Invalid type field (0x%x) in container file section header.\n",
446 			  p_type);
447 		return false;
448 	}
449 
450 	if (p_size < sizeof(struct microcode_header_amd)) {
451 		ucode_dbg("Patch of size %u too short.\n", p_size);
452 		return false;
453 	}
454 
455 	*sh_psize = p_size;
456 
457 	return true;
458 }
459 
460 /*
461  * Check whether the passed remaining file @buf_size is large enough to contain
462  * a patch of the indicated @sh_psize (and also whether this size does not
463  * exceed the per-family maximum). @sh_psize is the size read from the section
464  * header.
465  */
466 static bool __verify_patch_size(u32 sh_psize, size_t buf_size)
467 {
468 	u8 family = x86_family(bsp_cpuid_1_eax);
469 	u32 max_size;
470 
471 	if (family >= 0x15)
472 		goto ret;
473 
474 #define F1XH_MPB_MAX_SIZE 2048
475 #define F14H_MPB_MAX_SIZE 1824
476 
477 	switch (family) {
478 	case 0x10 ... 0x12:
479 		max_size = F1XH_MPB_MAX_SIZE;
480 		break;
481 	case 0x14:
482 		max_size = F14H_MPB_MAX_SIZE;
483 		break;
484 	default:
485 		WARN(1, "%s: WTF family: 0x%x\n", __func__, family);
486 		return false;
487 	}
488 
489 	if (sh_psize > max_size)
490 		return false;
491 
492 ret:
493 	/* Working with the whole buffer so < is ok. */
494 	return sh_psize <= buf_size;
495 }
496 
497 /*
498  * Verify the patch in @buf.
499  *
500  * Returns:
501  * negative: on error
502  * positive: patch is not for this family, skip it
503  * 0: success
504  */
505 static int verify_patch(const u8 *buf, size_t buf_size, u32 *patch_size)
506 {
507 	u8 family = x86_family(bsp_cpuid_1_eax);
508 	struct microcode_header_amd *mc_hdr;
509 	u32 cur_rev, cutoff, patch_rev;
510 	u32 sh_psize;
511 	u16 proc_id;
512 	u8 patch_fam;
513 
514 	if (!__verify_patch_section(buf, buf_size, &sh_psize))
515 		return -1;
516 
517 	/*
518 	 * The section header length is not included in this indicated size
519 	 * but is present in the leftover file length so we need to subtract
520 	 * it before passing this value to the function below.
521 	 */
522 	buf_size -= SECTION_HDR_SIZE;
523 
524 	/*
525 	 * Check if the remaining buffer is big enough to contain a patch of
526 	 * size sh_psize, as the section claims.
527 	 */
528 	if (buf_size < sh_psize) {
529 		ucode_dbg("Patch of size %u truncated.\n", sh_psize);
530 		return -1;
531 	}
532 
533 	if (!__verify_patch_size(sh_psize, buf_size)) {
534 		ucode_dbg("Per-family patch size mismatch.\n");
535 		return -1;
536 	}
537 
538 	*patch_size = sh_psize;
539 
540 	mc_hdr	= (struct microcode_header_amd *)(buf + SECTION_HDR_SIZE);
541 	if (mc_hdr->nb_dev_id || mc_hdr->sb_dev_id) {
542 		pr_err("Patch-ID 0x%08x: chipset-specific code unsupported.\n", mc_hdr->patch_id);
543 		return -1;
544 	}
545 
546 	proc_id	= mc_hdr->processor_rev_id;
547 	patch_fam = 0xf + (proc_id >> 12);
548 
549 	if (patch_fam != family)
550 		return 1;
551 
552 	cur_rev = get_patch_level();
553 
554 	/* No cutoff revision means old/unaffected by signing algorithm weakness => matches */
555 	cutoff = get_cutoff_revision(cur_rev);
556 	if (!cutoff)
557 		goto ok;
558 
559 	patch_rev = mc_hdr->patch_id;
560 
561 	ucode_dbg("cur_rev: 0x%x, cutoff: 0x%x, patch_rev: 0x%x\n",
562 		  cur_rev, cutoff, patch_rev);
563 
564 	if (cur_rev <= cutoff && patch_rev <= cutoff)
565 		goto ok;
566 
567 	if (cur_rev > cutoff && patch_rev > cutoff)
568 		goto ok;
569 
570 	return 1;
571 
572 ok:
573 	ucode_dbg("Patch-ID 0x%08x: family: 0x%x\n", mc_hdr->patch_id, patch_fam);
574 
575 	return 0;
576 }
577 
578 static bool mc_patch_matches(struct microcode_amd *mc, u16 eq_id)
579 {
580 	/* Zen and newer do not need an equivalence table. */
581 	if (x86_family(bsp_cpuid_1_eax) >= 0x17)
582 		return ucode_rev_to_cpuid(mc->hdr.patch_id).full == bsp_cpuid_1_eax;
583 	else
584 		return eq_id == mc->hdr.processor_rev_id;
585 }
586 
587 /*
588  * This scans the ucode blob for the proper container as we can have multiple
589  * containers glued together.
590  *
591  * Returns the amount of bytes consumed while scanning. @desc contains all the
592  * data we're going to use in later stages of the application.
593  */
594 static size_t parse_container(u8 *ucode, size_t size, struct cont_desc *desc)
595 {
596 	struct equiv_cpu_table table;
597 	size_t orig_size = size;
598 	u32 *hdr = (u32 *)ucode;
599 	u16 eq_id;
600 	u8 *buf;
601 
602 	if (!verify_equivalence_table(ucode, size))
603 		return 0;
604 
605 	buf = ucode;
606 
607 	table.entry = (struct equiv_cpu_entry *)(buf + CONTAINER_HDR_SZ);
608 	table.num_entries = hdr[2] / sizeof(struct equiv_cpu_entry);
609 
610 	/*
611 	 * Find the equivalence ID of our CPU in this table. Even if this table
612 	 * doesn't contain a patch for the CPU, scan through the whole container
613 	 * so that it can be skipped in case there are other containers appended.
614 	 */
615 	eq_id = find_equiv_id(&table, bsp_cpuid_1_eax);
616 
617 	buf  += hdr[2] + CONTAINER_HDR_SZ;
618 	size -= hdr[2] + CONTAINER_HDR_SZ;
619 
620 	/*
621 	 * Scan through the rest of the container to find where it ends. We do
622 	 * some basic sanity-checking too.
623 	 */
624 	while (size > 0) {
625 		struct microcode_amd *mc;
626 		u32 patch_size;
627 		int ret;
628 
629 		ret = verify_patch(buf, size, &patch_size);
630 		if (ret < 0) {
631 			/*
632 			 * Patch verification failed, skip to the next container, if
633 			 * there is one. Before exit, check whether that container has
634 			 * found a patch already. If so, use it.
635 			 */
636 			goto out;
637 		} else if (ret > 0) {
638 			goto skip;
639 		}
640 
641 		mc = (struct microcode_amd *)(buf + SECTION_HDR_SIZE);
642 
643 		if (mc_patch_matches(mc, eq_id)) {
644 			desc->psize = patch_size;
645 			desc->mc = mc;
646 
647 			ucode_dbg(" match: size: %d\n", patch_size);
648 		}
649 
650 skip:
651 		/* Skip patch section header too: */
652 		buf  += patch_size + SECTION_HDR_SIZE;
653 		size -= patch_size + SECTION_HDR_SIZE;
654 	}
655 
656 out:
657 	/*
658 	 * If we have found a patch (desc->mc), it means we're looking at the
659 	 * container which has a patch for this CPU so return 0 to mean, @ucode
660 	 * already points to the proper container. Otherwise, we return the size
661 	 * we scanned so that we can advance to the next container in the
662 	 * buffer.
663 	 */
664 	if (desc->mc) {
665 		desc->data = ucode;
666 		desc->size = orig_size - size;
667 
668 		return 0;
669 	}
670 
671 	return orig_size - size;
672 }
673 
674 /*
675  * Scan the ucode blob for the proper container as we can have multiple
676  * containers glued together.
677  */
678 static void scan_containers(u8 *ucode, size_t size, struct cont_desc *desc)
679 {
680 	while (size) {
681 		size_t s = parse_container(ucode, size, desc);
682 		if (!s)
683 			return;
684 
685 		/* catch wraparound */
686 		if (size >= s) {
687 			ucode += s;
688 			size  -= s;
689 		} else {
690 			return;
691 		}
692 	}
693 }
694 
695 static bool __apply_microcode_amd(struct microcode_amd *mc, u32 *cur_rev,
696 				  unsigned int psize)
697 {
698 	unsigned long p_addr = (unsigned long)&mc->hdr.data_code;
699 
700 	if (!verify_sha256_digest(mc->hdr.patch_id, *cur_rev, (const u8 *)p_addr, psize))
701 		return false;
702 
703 	native_wrmsrq(MSR_AMD64_PATCH_LOADER, p_addr);
704 
705 	if (x86_family(bsp_cpuid_1_eax) == 0x17) {
706 		unsigned long p_addr_end = p_addr + psize - 1;
707 
708 		invlpg(p_addr);
709 
710 		/*
711 		 * Flush next page too if patch image is crossing a page
712 		 * boundary.
713 		 */
714 		if (p_addr >> PAGE_SHIFT != p_addr_end >> PAGE_SHIFT)
715 			invlpg(p_addr_end);
716 	}
717 
718 	if (IS_ENABLED(CONFIG_MICROCODE_DBG) && hypervisor_present)
719 		microcode_rev[smp_processor_id()] = mc->hdr.patch_id;
720 
721 	/* verify patch application was successful */
722 	*cur_rev = get_patch_level();
723 
724 	ucode_dbg("updated rev: 0x%x\n", *cur_rev);
725 
726 	if (*cur_rev != mc->hdr.patch_id)
727 		return false;
728 
729 	return true;
730 }
731 
732 static bool get_builtin_microcode(struct cpio_data *cp)
733 {
734 	char fw_name[36] = "amd-ucode/microcode_amd.bin";
735 	u8 family = x86_family(bsp_cpuid_1_eax);
736 	struct firmware fw;
737 
738 	if (IS_ENABLED(CONFIG_X86_32))
739 		return false;
740 
741 	if (family >= 0x15)
742 		snprintf(fw_name, sizeof(fw_name),
743 			 "amd-ucode/microcode_amd_fam%02hhxh.bin", family);
744 
745 	if (firmware_request_builtin(&fw, fw_name)) {
746 		cp->size = fw.size;
747 		cp->data = (void *)fw.data;
748 		return true;
749 	}
750 
751 	return false;
752 }
753 
754 static bool __init find_blobs_in_containers(struct cpio_data *ret)
755 {
756 	struct cpio_data cp;
757 	bool found;
758 
759 	if (!get_builtin_microcode(&cp))
760 		cp = find_microcode_in_initrd(ucode_path);
761 
762 	found = cp.data && cp.size;
763 	if (found)
764 		*ret = cp;
765 
766 	return found;
767 }
768 
769 /*
770  * Early load occurs before we can vmalloc(). So we look for the microcode
771  * patch container file in initrd, traverse equivalent cpu table, look for a
772  * matching microcode patch, and update, all in initrd memory in place.
773  * When vmalloc() is available for use later -- on 64-bit during first AP load,
774  * and on 32-bit during save_microcode_in_initrd() -- we can call
775  * load_microcode_amd() to save equivalent cpu table and microcode patches in
776  * kernel heap memory.
777  */
778 void __init load_ucode_amd_bsp(struct early_load_data *ed, unsigned int cpuid_1_eax)
779 {
780 	struct cont_desc desc = { };
781 	struct microcode_amd *mc;
782 	struct cpio_data cp = { };
783 	char buf[4];
784 	u32 rev;
785 
786 	if (cmdline_find_option(boot_command_line, "microcode.amd_sha_check", buf, 4)) {
787 		if (!strncmp(buf, "off", 3)) {
788 			sha_check = false;
789 			pr_warn_once("It is a very very bad idea to disable the blobs SHA check!\n");
790 			add_taint(TAINT_CPU_OUT_OF_SPEC, LOCKDEP_STILL_OK);
791 		}
792 	}
793 
794 	bsp_cpuid_1_eax = cpuid_1_eax;
795 
796 	rev = get_patch_level();
797 	ed->old_rev = rev;
798 
799 	/* Needed in load_microcode_amd() */
800 	ucode_cpu_info[0].cpu_sig.sig = cpuid_1_eax;
801 
802 	if (!find_blobs_in_containers(&cp))
803 		return;
804 
805 	scan_containers(cp.data, cp.size, &desc);
806 
807 	mc = desc.mc;
808 	if (!mc)
809 		return;
810 
811 	/*
812 	 * Allow application of the same revision to pick up SMT-specific
813 	 * changes even if the revision of the other SMT thread is already
814 	 * up-to-date.
815 	 */
816 	if (ed->old_rev > mc->hdr.patch_id)
817 		return;
818 
819 	if (__apply_microcode_amd(mc, &rev, desc.psize))
820 		ed->new_rev = rev;
821 }
822 
823 static inline bool patch_cpus_equivalent(struct ucode_patch *p,
824 					 struct ucode_patch *n,
825 					 bool ignore_stepping)
826 {
827 	/* Zen and newer hardcode the f/m/s in the patch ID */
828         if (x86_family(bsp_cpuid_1_eax) >= 0x17) {
829 		union cpuid_1_eax p_cid = ucode_rev_to_cpuid(p->patch_id);
830 		union cpuid_1_eax n_cid = ucode_rev_to_cpuid(n->patch_id);
831 
832 		if (ignore_stepping) {
833 			p_cid.stepping = 0;
834 			n_cid.stepping = 0;
835 		}
836 
837 		return p_cid.full == n_cid.full;
838 	} else {
839 		return p->equiv_cpu == n->equiv_cpu;
840 	}
841 }
842 
843 /*
844  * a small, trivial cache of per-family ucode patches
845  */
846 static struct ucode_patch *cache_find_patch(struct ucode_cpu_info *uci, u16 equiv_cpu)
847 {
848 	struct ucode_patch *p;
849 	struct ucode_patch n;
850 
851 	n.equiv_cpu = equiv_cpu;
852 	n.patch_id  = uci->cpu_sig.rev;
853 
854 	list_for_each_entry(p, &microcode_cache, plist)
855 		if (patch_cpus_equivalent(p, &n, false))
856 			return p;
857 
858 	return NULL;
859 }
860 
861 static inline int patch_newer(struct ucode_patch *p, struct ucode_patch *n)
862 {
863 	/* Zen and newer hardcode the f/m/s in the patch ID */
864         if (x86_family(bsp_cpuid_1_eax) >= 0x17) {
865 		union zen_patch_rev zp, zn;
866 
867 		zp.ucode_rev = p->patch_id;
868 		zn.ucode_rev = n->patch_id;
869 
870 		if (zn.stepping != zp.stepping)
871 			return -1;
872 
873 		return zn.rev > zp.rev;
874 	} else {
875 		return n->patch_id > p->patch_id;
876 	}
877 }
878 
879 static void update_cache(struct ucode_patch *new_patch)
880 {
881 	struct ucode_patch *p;
882 	int ret;
883 
884 	list_for_each_entry(p, &microcode_cache, plist) {
885 		if (patch_cpus_equivalent(p, new_patch, true)) {
886 			ret = patch_newer(p, new_patch);
887 			if (ret < 0)
888 				continue;
889 			else if (!ret) {
890 				/* we already have the latest patch */
891 				kfree(new_patch->data);
892 				kfree(new_patch);
893 				return;
894 			}
895 
896 			list_replace(&p->plist, &new_patch->plist);
897 			kfree(p->data);
898 			kfree(p);
899 			return;
900 		}
901 	}
902 	/* no patch found, add it */
903 	list_add_tail(&new_patch->plist, &microcode_cache);
904 }
905 
906 static void free_cache(void)
907 {
908 	struct ucode_patch *p, *tmp;
909 
910 	list_for_each_entry_safe(p, tmp, &microcode_cache, plist) {
911 		__list_del(p->plist.prev, p->plist.next);
912 		kfree(p->data);
913 		kfree(p);
914 	}
915 }
916 
917 static struct ucode_patch *find_patch(unsigned int cpu)
918 {
919 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
920 	u16 equiv_id = 0;
921 
922 	uci->cpu_sig.rev = get_patch_level();
923 
924 	if (x86_family(bsp_cpuid_1_eax) < 0x17) {
925 		equiv_id = find_equiv_id(&equiv_table, uci->cpu_sig.sig);
926 		if (!equiv_id)
927 			return NULL;
928 	}
929 
930 	return cache_find_patch(uci, equiv_id);
931 }
932 
933 void reload_ucode_amd(unsigned int cpu)
934 {
935 	u32 rev, dummy __always_unused;
936 	struct microcode_amd *mc;
937 	struct ucode_patch *p;
938 
939 	p = find_patch(cpu);
940 	if (!p)
941 		return;
942 
943 	mc = p->data;
944 
945 	rev = get_patch_level();
946 	if (rev < mc->hdr.patch_id) {
947 		if (__apply_microcode_amd(mc, &rev, p->size))
948 			pr_info_once("reload revision: 0x%08x\n", rev);
949 	}
950 }
951 
952 static int collect_cpu_info_amd(int cpu, struct cpu_signature *csig)
953 {
954 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
955 	struct ucode_patch *p;
956 
957 	csig->sig = cpuid_eax(0x00000001);
958 	csig->rev = get_patch_level();
959 
960 	/*
961 	 * a patch could have been loaded early, set uci->mc so that
962 	 * mc_bp_resume() can call apply_microcode()
963 	 */
964 	p = find_patch(cpu);
965 	if (p && (p->patch_id == csig->rev))
966 		uci->mc = p->data;
967 
968 	return 0;
969 }
970 
971 static enum ucode_state apply_microcode_amd(int cpu)
972 {
973 	struct cpuinfo_x86 *c = &cpu_data(cpu);
974 	struct microcode_amd *mc_amd;
975 	struct ucode_cpu_info *uci;
976 	struct ucode_patch *p;
977 	enum ucode_state ret;
978 	u32 rev;
979 
980 	BUG_ON(raw_smp_processor_id() != cpu);
981 
982 	uci = ucode_cpu_info + cpu;
983 
984 	p = find_patch(cpu);
985 	if (!p)
986 		return UCODE_NFOUND;
987 
988 	rev = uci->cpu_sig.rev;
989 
990 	mc_amd  = p->data;
991 	uci->mc = p->data;
992 
993 	/* need to apply patch? */
994 	if (rev > mc_amd->hdr.patch_id) {
995 		ret = UCODE_OK;
996 		goto out;
997 	}
998 
999 	if (!__apply_microcode_amd(mc_amd, &rev, p->size)) {
1000 		pr_err("CPU%d: update failed for patch_level=0x%08x\n",
1001 			cpu, mc_amd->hdr.patch_id);
1002 		return UCODE_ERROR;
1003 	}
1004 
1005 	rev = mc_amd->hdr.patch_id;
1006 	ret = UCODE_UPDATED;
1007 
1008 out:
1009 	uci->cpu_sig.rev = rev;
1010 	c->microcode	 = rev;
1011 
1012 	/* Update boot_cpu_data's revision too, if we're on the BSP: */
1013 	if (c->cpu_index == boot_cpu_data.cpu_index)
1014 		boot_cpu_data.microcode = rev;
1015 
1016 	return ret;
1017 }
1018 
1019 void load_ucode_amd_ap(unsigned int cpuid_1_eax)
1020 {
1021 	unsigned int cpu = smp_processor_id();
1022 
1023 	ucode_cpu_info[cpu].cpu_sig.sig = cpuid_1_eax;
1024 	apply_microcode_amd(cpu);
1025 }
1026 
1027 static size_t install_equiv_cpu_table(const u8 *buf, size_t buf_size)
1028 {
1029 	u32 equiv_tbl_len;
1030 	const u32 *hdr;
1031 
1032 	if (!verify_equivalence_table(buf, buf_size))
1033 		return 0;
1034 
1035 	hdr = (const u32 *)buf;
1036 	equiv_tbl_len = hdr[2];
1037 
1038 	/* Zen and newer do not need an equivalence table. */
1039 	if (x86_family(bsp_cpuid_1_eax) >= 0x17)
1040 		goto out;
1041 
1042 	equiv_table.entry = vmalloc(equiv_tbl_len);
1043 	if (!equiv_table.entry) {
1044 		pr_err("failed to allocate equivalent CPU table\n");
1045 		return 0;
1046 	}
1047 
1048 	memcpy(equiv_table.entry, buf + CONTAINER_HDR_SZ, equiv_tbl_len);
1049 	equiv_table.num_entries = equiv_tbl_len / sizeof(struct equiv_cpu_entry);
1050 
1051 out:
1052 	/* add header length */
1053 	return equiv_tbl_len + CONTAINER_HDR_SZ;
1054 }
1055 
1056 static void free_equiv_cpu_table(void)
1057 {
1058 	if (x86_family(bsp_cpuid_1_eax) >= 0x17)
1059 		return;
1060 
1061 	vfree(equiv_table.entry);
1062 	memset(&equiv_table, 0, sizeof(equiv_table));
1063 }
1064 
1065 static void cleanup(void)
1066 {
1067 	free_equiv_cpu_table();
1068 	free_cache();
1069 }
1070 
1071 /*
1072  * Return a non-negative value even if some of the checks failed so that
1073  * we can skip over the next patch. If we return a negative value, we
1074  * signal a grave error like a memory allocation has failed and the
1075  * driver cannot continue functioning normally. In such cases, we tear
1076  * down everything we've used up so far and exit.
1077  */
1078 static int verify_and_add_patch(u8 family, u8 *fw, unsigned int leftover,
1079 				unsigned int *patch_size)
1080 {
1081 	struct microcode_header_amd *mc_hdr;
1082 	struct ucode_patch *patch;
1083 	u16 proc_id;
1084 	int ret;
1085 
1086 	ret = verify_patch(fw, leftover, patch_size);
1087 	if (ret)
1088 		return ret;
1089 
1090 	patch = kzalloc_obj(*patch);
1091 	if (!patch) {
1092 		pr_err("Patch allocation failure.\n");
1093 		return -EINVAL;
1094 	}
1095 
1096 	patch->data = kmemdup(fw + SECTION_HDR_SIZE, *patch_size, GFP_KERNEL);
1097 	if (!patch->data) {
1098 		pr_err("Patch data allocation failure.\n");
1099 		kfree(patch);
1100 		return -EINVAL;
1101 	}
1102 	patch->size = *patch_size;
1103 
1104 	mc_hdr      = (struct microcode_header_amd *)(fw + SECTION_HDR_SIZE);
1105 	proc_id     = mc_hdr->processor_rev_id;
1106 
1107 	INIT_LIST_HEAD(&patch->plist);
1108 	patch->patch_id  = mc_hdr->patch_id;
1109 	patch->equiv_cpu = proc_id;
1110 
1111 	ucode_dbg("%s: Adding patch_id: 0x%08x, proc_id: 0x%04x\n",
1112 		 __func__, patch->patch_id, proc_id);
1113 
1114 	/* ... and add to cache. */
1115 	update_cache(patch);
1116 
1117 	return 0;
1118 }
1119 
1120 /* Scan the blob in @data and add microcode patches to the cache. */
1121 static enum ucode_state __load_microcode_amd(u8 family, const u8 *data, size_t size)
1122 {
1123 	u8 *fw = (u8 *)data;
1124 	size_t offset;
1125 
1126 	offset = install_equiv_cpu_table(data, size);
1127 	if (!offset)
1128 		return UCODE_ERROR;
1129 
1130 	fw   += offset;
1131 	size -= offset;
1132 
1133 	if (*(u32 *)fw != UCODE_UCODE_TYPE) {
1134 		pr_err("invalid type field in container file section header\n");
1135 		free_equiv_cpu_table();
1136 		return UCODE_ERROR;
1137 	}
1138 
1139 	while (size > 0) {
1140 		unsigned int crnt_size = 0;
1141 		int ret;
1142 
1143 		ret = verify_and_add_patch(family, fw, size, &crnt_size);
1144 		if (ret < 0)
1145 			return UCODE_ERROR;
1146 
1147 		fw   +=  crnt_size + SECTION_HDR_SIZE;
1148 		size -= (crnt_size + SECTION_HDR_SIZE);
1149 	}
1150 
1151 	return UCODE_OK;
1152 }
1153 
1154 static enum ucode_state _load_microcode_amd(u8 family, const u8 *data, size_t size)
1155 {
1156 	enum ucode_state ret;
1157 
1158 	/* free old equiv table */
1159 	free_equiv_cpu_table();
1160 
1161 	ret = __load_microcode_amd(family, data, size);
1162 	if (ret != UCODE_OK)
1163 		cleanup();
1164 
1165 	return ret;
1166 }
1167 
1168 static enum ucode_state load_microcode_amd(u8 family, const u8 *data, size_t size)
1169 {
1170 	struct cpuinfo_x86 *c;
1171 	unsigned int nid, cpu;
1172 	struct ucode_patch *p;
1173 	enum ucode_state ret;
1174 
1175 	ret = _load_microcode_amd(family, data, size);
1176 	if (ret != UCODE_OK)
1177 		return ret;
1178 
1179 	for_each_node_with_cpus(nid) {
1180 		cpu = cpumask_first(cpumask_of_node(nid));
1181 		c = &cpu_data(cpu);
1182 
1183 		p = find_patch(cpu);
1184 		if (!p)
1185 			continue;
1186 
1187 		if (c->microcode >= p->patch_id)
1188 			continue;
1189 
1190 		ret = UCODE_NEW;
1191 	}
1192 
1193 	return ret;
1194 }
1195 
1196 static int __init save_microcode_in_initrd(void)
1197 {
1198 	struct cpuinfo_x86 *c = &boot_cpu_data;
1199 	struct cont_desc desc = { 0 };
1200 	unsigned int cpuid_1_eax;
1201 	enum ucode_state ret;
1202 	struct cpio_data cp;
1203 
1204 	if (microcode_loader_disabled() || c->x86_vendor != X86_VENDOR_AMD || c->x86 < 0x10)
1205 		return 0;
1206 
1207 	cpuid_1_eax = native_cpuid_eax(1);
1208 
1209 	if (!find_blobs_in_containers(&cp))
1210 		return -EINVAL;
1211 
1212 	scan_containers(cp.data, cp.size, &desc);
1213 	if (!desc.mc)
1214 		return -EINVAL;
1215 
1216 	ret = _load_microcode_amd(x86_family(cpuid_1_eax), desc.data, desc.size);
1217 	if (ret > UCODE_UPDATED)
1218 		return -EINVAL;
1219 
1220 	return 0;
1221 }
1222 early_initcall(save_microcode_in_initrd);
1223 
1224 /*
1225  * AMD microcode firmware naming convention, up to family 15h they are in
1226  * the legacy file:
1227  *
1228  *    amd-ucode/microcode_amd.bin
1229  *
1230  * This legacy file is always smaller than 2K in size.
1231  *
1232  * Beginning with family 15h, they are in family-specific firmware files:
1233  *
1234  *    amd-ucode/microcode_amd_fam15h.bin
1235  *    amd-ucode/microcode_amd_fam16h.bin
1236  *    ...
1237  *
1238  * These might be larger than 2K.
1239  */
1240 static enum ucode_state request_microcode_amd(int cpu, struct device *device)
1241 {
1242 	char fw_name[36] = "amd-ucode/microcode_amd.bin";
1243 	struct cpuinfo_x86 *c = &cpu_data(cpu);
1244 	enum ucode_state ret = UCODE_NFOUND;
1245 	const struct firmware *fw;
1246 
1247 	if (force_minrev)
1248 		return UCODE_NFOUND;
1249 
1250 	if (c->x86 >= 0x15)
1251 		snprintf(fw_name, sizeof(fw_name), "amd-ucode/microcode_amd_fam%.2xh.bin", c->x86);
1252 
1253 	if (request_firmware_direct(&fw, (const char *)fw_name, device)) {
1254 		ucode_dbg("failed to load file %s\n", fw_name);
1255 		goto out;
1256 	}
1257 
1258 	ret = UCODE_ERROR;
1259 	if (!verify_container(fw->data, fw->size))
1260 		goto fw_release;
1261 
1262 	ret = load_microcode_amd(c->x86, fw->data, fw->size);
1263 
1264  fw_release:
1265 	release_firmware(fw);
1266 
1267  out:
1268 	return ret;
1269 }
1270 
1271 static void microcode_fini_cpu_amd(int cpu)
1272 {
1273 	struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
1274 
1275 	uci->mc = NULL;
1276 }
1277 
1278 static void finalize_late_load_amd(int result)
1279 {
1280 	if (result)
1281 		cleanup();
1282 }
1283 
1284 static struct microcode_ops microcode_amd_ops = {
1285 	.request_microcode_fw	= request_microcode_amd,
1286 	.collect_cpu_info	= collect_cpu_info_amd,
1287 	.apply_microcode	= apply_microcode_amd,
1288 	.microcode_fini_cpu	= microcode_fini_cpu_amd,
1289 	.finalize_late_load	= finalize_late_load_amd,
1290 	.nmi_safe		= true,
1291 };
1292 
1293 struct microcode_ops * __init init_amd_microcode(void)
1294 {
1295 	struct cpuinfo_x86 *c = &boot_cpu_data;
1296 
1297 	if (c->x86_vendor != X86_VENDOR_AMD || c->x86 < 0x10) {
1298 		pr_warn("AMD CPU family 0x%x not supported\n", c->x86);
1299 		return NULL;
1300 	}
1301 	return &microcode_amd_ops;
1302 }
1303 
1304 void __exit exit_amd_microcode(void)
1305 {
1306 	cleanup();
1307 }
1308