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