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