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