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