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