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