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