GNU Linux-libre 4.9.337-gnu1
[releases.git] / arch / x86 / kernel / cpu / microcode / intel.c
1 /*
2  * Intel CPU Microcode Update Driver for Linux
3  *
4  * Copyright (C) 2000-2006 Tigran Aivazian <tigran@aivazian.fsnet.co.uk>
5  *               2006 Shaohua Li <shaohua.li@intel.com>
6  *
7  * Intel CPU microcode early update for Linux
8  *
9  * Copyright (C) 2012 Fenghua Yu <fenghua.yu@intel.com>
10  *                    H Peter Anvin" <hpa@zytor.com>
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version
15  * 2 of the License, or (at your option) any later version.
16  */
17
18 /*
19  * This needs to be before all headers so that pr_debug in printk.h doesn't turn
20  * printk calls into no_printk().
21  *
22  *#define DEBUG
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/slab.h>
33 #include <linux/cpu.h>
34 #include <linux/mm.h>
35
36 #include <asm/microcode_intel.h>
37 #include <asm/intel-family.h>
38 #include <asm/processor.h>
39 #include <asm/tlbflush.h>
40 #include <asm/setup.h>
41 #include <asm/msr.h>
42
43 /* last level cache size per core */
44 static int llc_size_per_core;
45
46 /*
47  * Temporary microcode blobs pointers storage. We note here during early load
48  * the pointers to microcode blobs we've got from whatever storage (detached
49  * initrd, builtin). Later on, we put those into final storage
50  * mc_saved_data.mc_saved.
51  *
52  * Important: those are offsets from the beginning of initrd or absolute
53  * addresses within the kernel image when built-in.
54  */
55 static unsigned long mc_tmp_ptrs[MAX_UCODE_COUNT];
56
57 static struct mc_saved_data {
58         unsigned int num_saved;
59         struct microcode_intel **mc_saved;
60 } mc_saved_data;
61
62 /* Microcode blobs within the initrd. 0 if builtin. */
63 static struct ucode_blobs {
64         unsigned long start;
65         bool valid;
66 } blobs;
67
68 /* Go through saved patches and find the one suitable for the current CPU. */
69 static enum ucode_state
70 find_microcode_patch(struct microcode_intel **saved,
71                      unsigned int num_saved, struct ucode_cpu_info *uci)
72 {
73         struct microcode_intel *ucode_ptr, *new_mc = NULL;
74         struct microcode_header_intel *mc_hdr;
75         int new_rev, ret, i;
76
77         new_rev = uci->cpu_sig.rev;
78
79         for (i = 0; i < num_saved; i++) {
80                 ucode_ptr = saved[i];
81                 mc_hdr    = (struct microcode_header_intel *)ucode_ptr;
82
83                 ret = has_newer_microcode(ucode_ptr,
84                                           uci->cpu_sig.sig,
85                                           uci->cpu_sig.pf,
86                                           new_rev);
87                 if (!ret)
88                         continue;
89
90                 new_rev = mc_hdr->rev;
91                 new_mc  = ucode_ptr;
92         }
93
94         if (!new_mc)
95                 return UCODE_NFOUND;
96
97         uci->mc = (struct microcode_intel *)new_mc;
98         return UCODE_OK;
99 }
100
101 static inline void
102 copy_ptrs(struct microcode_intel **mc_saved, unsigned long *mc_ptrs,
103           unsigned long off, int num_saved)
104 {
105         int i;
106
107         for (i = 0; i < num_saved; i++)
108                 mc_saved[i] = (struct microcode_intel *)(mc_ptrs[i] + off);
109 }
110
111 #ifdef CONFIG_X86_32
112 static void
113 microcode_phys(struct microcode_intel **mc_saved_tmp, struct mc_saved_data *mcs)
114 {
115         int i;
116         struct microcode_intel ***mc_saved;
117
118         mc_saved = (struct microcode_intel ***)__pa_nodebug(&mcs->mc_saved);
119
120         for (i = 0; i < mcs->num_saved; i++) {
121                 struct microcode_intel *p;
122
123                 p = *(struct microcode_intel **)__pa_nodebug(mcs->mc_saved + i);
124                 mc_saved_tmp[i] = (struct microcode_intel *)__pa_nodebug(p);
125         }
126 }
127 #endif
128
129 static enum ucode_state
130 load_microcode(struct mc_saved_data *mcs, unsigned long *mc_ptrs,
131                unsigned long offset, struct ucode_cpu_info *uci)
132 {
133         struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
134         unsigned int count = mcs->num_saved;
135
136         if (!mcs->mc_saved) {
137                 copy_ptrs(mc_saved_tmp, mc_ptrs, offset, count);
138
139                 return find_microcode_patch(mc_saved_tmp, count, uci);
140         } else {
141 #ifdef CONFIG_X86_32
142                 microcode_phys(mc_saved_tmp, mcs);
143                 return find_microcode_patch(mc_saved_tmp, count, uci);
144 #else
145                 return find_microcode_patch(mcs->mc_saved, count, uci);
146 #endif
147         }
148 }
149
150 static int
151 save_microcode(struct mc_saved_data *mcs,
152                struct microcode_intel **mc_saved_src,
153                unsigned int num_saved)
154 {
155         int i, j;
156         struct microcode_intel **saved_ptr;
157         int ret;
158
159         if (!num_saved)
160                 return -EINVAL;
161
162         /*
163          * Copy new microcode data.
164          */
165         saved_ptr = kcalloc(num_saved, sizeof(struct microcode_intel *), GFP_KERNEL);
166         if (!saved_ptr)
167                 return -ENOMEM;
168
169         for (i = 0; i < num_saved; i++) {
170                 struct microcode_header_intel *mc_hdr;
171                 struct microcode_intel *mc;
172                 unsigned long size;
173
174                 if (!mc_saved_src[i]) {
175                         ret = -EINVAL;
176                         goto err;
177                 }
178
179                 mc     = mc_saved_src[i];
180                 mc_hdr = &mc->hdr;
181                 size   = get_totalsize(mc_hdr);
182
183                 saved_ptr[i] = kmemdup(mc, size, GFP_KERNEL);
184                 if (!saved_ptr[i]) {
185                         ret = -ENOMEM;
186                         goto err;
187                 }
188         }
189
190         /*
191          * Point to newly saved microcode.
192          */
193         mcs->mc_saved  = saved_ptr;
194         mcs->num_saved = num_saved;
195
196         return 0;
197
198 err:
199         for (j = 0; j <= i; j++)
200                 kfree(saved_ptr[j]);
201         kfree(saved_ptr);
202
203         return ret;
204 }
205
206 /*
207  * A microcode patch in ucode_ptr is saved into mc_saved
208  * - if it has matching signature and newer revision compared to an existing
209  *   patch mc_saved.
210  * - or if it is a newly discovered microcode patch.
211  *
212  * The microcode patch should have matching model with CPU.
213  *
214  * Returns: The updated number @num_saved of saved microcode patches.
215  */
216 static unsigned int _save_mc(struct microcode_intel **mc_saved,
217                              u8 *ucode_ptr, unsigned int num_saved)
218 {
219         struct microcode_header_intel *mc_hdr, *mc_saved_hdr;
220         unsigned int sig, pf;
221         int found = 0, i;
222
223         mc_hdr = (struct microcode_header_intel *)ucode_ptr;
224
225         for (i = 0; i < num_saved; i++) {
226                 mc_saved_hdr = (struct microcode_header_intel *)mc_saved[i];
227                 sig          = mc_saved_hdr->sig;
228                 pf           = mc_saved_hdr->pf;
229
230                 if (!find_matching_signature(ucode_ptr, sig, pf))
231                         continue;
232
233                 found = 1;
234
235                 if (mc_hdr->rev <= mc_saved_hdr->rev)
236                         continue;
237
238                 /*
239                  * Found an older ucode saved earlier. Replace it with
240                  * this newer one.
241                  */
242                 mc_saved[i] = (struct microcode_intel *)ucode_ptr;
243                 break;
244         }
245
246         /* Newly detected microcode, save it to memory. */
247         if (i >= num_saved && !found)
248                 mc_saved[num_saved++] = (struct microcode_intel *)ucode_ptr;
249
250         return num_saved;
251 }
252
253 /*
254  * Get microcode matching with BSP's model. Only CPUs with the same model as
255  * BSP can stay in the platform.
256  */
257 static enum ucode_state __init
258 get_matching_model_microcode(unsigned long start, void *data, size_t size,
259                              struct mc_saved_data *mcs, unsigned long *mc_ptrs,
260                              struct ucode_cpu_info *uci)
261 {
262         struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
263         struct microcode_header_intel *mc_header;
264         unsigned int num_saved = mcs->num_saved;
265         enum ucode_state state = UCODE_OK;
266         unsigned int leftover = size;
267         u8 *ucode_ptr = data;
268         unsigned int mc_size;
269         int i;
270
271         while (leftover && num_saved < ARRAY_SIZE(mc_saved_tmp)) {
272
273                 if (leftover < sizeof(mc_header))
274                         break;
275
276                 mc_header = (struct microcode_header_intel *)ucode_ptr;
277
278                 mc_size = get_totalsize(mc_header);
279                 if (!mc_size || mc_size > leftover ||
280                         microcode_sanity_check(ucode_ptr, 0) < 0)
281                         break;
282
283                 leftover -= mc_size;
284
285                 /*
286                  * Since APs with same family and model as the BSP may boot in
287                  * the platform, we need to find and save microcode patches
288                  * with the same family and model as the BSP.
289                  */
290                 if (!find_matching_signature(mc_header, uci->cpu_sig.sig,
291                                              uci->cpu_sig.pf)) {
292                         ucode_ptr += mc_size;
293                         continue;
294                 }
295
296                 num_saved = _save_mc(mc_saved_tmp, ucode_ptr, num_saved);
297
298                 ucode_ptr += mc_size;
299         }
300
301         if (leftover) {
302                 state = UCODE_ERROR;
303                 return state;
304         }
305
306         if (!num_saved) {
307                 state = UCODE_NFOUND;
308                 return state;
309         }
310
311         for (i = 0; i < num_saved; i++)
312                 mc_ptrs[i] = (unsigned long)mc_saved_tmp[i] - start;
313
314         mcs->num_saved = num_saved;
315
316         return state;
317 }
318
319 static int collect_cpu_info_early(struct ucode_cpu_info *uci)
320 {
321         unsigned int val[2];
322         unsigned int family, model;
323         struct cpu_signature csig;
324         unsigned int eax, ebx, ecx, edx;
325
326         csig.sig = 0;
327         csig.pf = 0;
328         csig.rev = 0;
329
330         memset(uci, 0, sizeof(*uci));
331
332         eax = 0x00000001;
333         ecx = 0;
334         native_cpuid(&eax, &ebx, &ecx, &edx);
335         csig.sig = eax;
336
337         family = x86_family(csig.sig);
338         model  = x86_model(csig.sig);
339
340         if ((model >= 5) || (family > 6)) {
341                 /* get processor flags from MSR 0x17 */
342                 native_rdmsr(MSR_IA32_PLATFORM_ID, val[0], val[1]);
343                 csig.pf = 1 << ((val[1] >> 18) & 7);
344         }
345
346         csig.rev = intel_get_microcode_revision();
347
348         uci->cpu_sig = csig;
349         uci->valid = 1;
350
351         return 0;
352 }
353
354 static void show_saved_mc(void)
355 {
356 #ifdef DEBUG
357         int i, j;
358         unsigned int sig, pf, rev, total_size, data_size, date;
359         struct ucode_cpu_info uci;
360
361         if (!mc_saved_data.num_saved) {
362                 pr_debug("no microcode data saved.\n");
363                 return;
364         }
365         pr_debug("Total microcode saved: %d\n", mc_saved_data.num_saved);
366
367         collect_cpu_info_early(&uci);
368
369         sig = uci.cpu_sig.sig;
370         pf = uci.cpu_sig.pf;
371         rev = uci.cpu_sig.rev;
372         pr_debug("CPU: sig=0x%x, pf=0x%x, rev=0x%x\n", sig, pf, rev);
373
374         for (i = 0; i < mc_saved_data.num_saved; i++) {
375                 struct microcode_header_intel *mc_saved_header;
376                 struct extended_sigtable *ext_header;
377                 int ext_sigcount;
378                 struct extended_signature *ext_sig;
379
380                 mc_saved_header = (struct microcode_header_intel *)
381                                   mc_saved_data.mc_saved[i];
382                 sig = mc_saved_header->sig;
383                 pf = mc_saved_header->pf;
384                 rev = mc_saved_header->rev;
385                 total_size = get_totalsize(mc_saved_header);
386                 data_size = get_datasize(mc_saved_header);
387                 date = mc_saved_header->date;
388
389                 pr_debug("mc_saved[%d]: sig=0x%x, pf=0x%x, rev=0x%x, total size=0x%x, date = %04x-%02x-%02x\n",
390                          i, sig, pf, rev, total_size,
391                          date & 0xffff,
392                          date >> 24,
393                          (date >> 16) & 0xff);
394
395                 /* Look for ext. headers: */
396                 if (total_size <= data_size + MC_HEADER_SIZE)
397                         continue;
398
399                 ext_header = (void *) mc_saved_header + data_size + MC_HEADER_SIZE;
400                 ext_sigcount = ext_header->count;
401                 ext_sig = (void *)ext_header + EXT_HEADER_SIZE;
402
403                 for (j = 0; j < ext_sigcount; j++) {
404                         sig = ext_sig->sig;
405                         pf = ext_sig->pf;
406
407                         pr_debug("\tExtended[%d]: sig=0x%x, pf=0x%x\n",
408                                  j, sig, pf);
409
410                         ext_sig++;
411                 }
412
413         }
414 #endif
415 }
416
417 /*
418  * Save this mc into mc_saved_data. So it will be loaded early when a CPU is
419  * hot added or resumes.
420  *
421  * Please make sure this mc should be a valid microcode patch before calling
422  * this function.
423  */
424 static void save_mc_for_early(u8 *mc)
425 {
426         /* Synchronization during CPU hotplug. */
427         static DEFINE_MUTEX(x86_cpu_microcode_mutex);
428
429         struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
430         unsigned int mc_saved_count_init;
431         unsigned int num_saved;
432         struct microcode_intel **mc_saved;
433         int ret, i;
434
435         mutex_lock(&x86_cpu_microcode_mutex);
436
437         mc_saved_count_init = mc_saved_data.num_saved;
438         num_saved = mc_saved_data.num_saved;
439         mc_saved = mc_saved_data.mc_saved;
440
441         if (mc_saved && num_saved)
442                 memcpy(mc_saved_tmp, mc_saved,
443                        num_saved * sizeof(struct microcode_intel *));
444         /*
445          * Save the microcode patch mc in mc_save_tmp structure if it's a newer
446          * version.
447          */
448         num_saved = _save_mc(mc_saved_tmp, mc, num_saved);
449
450         /*
451          * Save the mc_save_tmp in global mc_saved_data.
452          */
453         ret = save_microcode(&mc_saved_data, mc_saved_tmp, num_saved);
454         if (ret) {
455                 pr_err("Cannot save microcode patch.\n");
456                 goto out;
457         }
458
459         show_saved_mc();
460
461         /*
462          * Free old saved microcode data.
463          */
464         if (mc_saved) {
465                 for (i = 0; i < mc_saved_count_init; i++)
466                         kfree(mc_saved[i]);
467                 kfree(mc_saved);
468         }
469
470 out:
471         mutex_unlock(&x86_cpu_microcode_mutex);
472 }
473
474 static bool __init load_builtin_intel_microcode(struct cpio_data *cp)
475 {
476 #ifdef CONFIG_X86_64
477         unsigned int eax = 0x00000001, ebx, ecx = 0, edx;
478         char name[30];
479
480         native_cpuid(&eax, &ebx, &ecx, &edx);
481
482         sprintf(name, "/*(DEBLOBBED)*/",
483                       x86_family(eax), x86_model(eax), x86_stepping(eax));
484
485         return get_builtin_firmware(cp, name);
486 #else
487         return false;
488 #endif
489 }
490
491 /*
492  * Print ucode update info.
493  */
494 static void
495 print_ucode_info(struct ucode_cpu_info *uci, unsigned int date)
496 {
497         pr_info_once("microcode updated early to revision 0x%x, date = %04x-%02x-%02x\n",
498                      uci->cpu_sig.rev,
499                      date & 0xffff,
500                      date >> 24,
501                      (date >> 16) & 0xff);
502 }
503
504 #ifdef CONFIG_X86_32
505
506 static int delay_ucode_info;
507 static int current_mc_date;
508
509 /*
510  * Print early updated ucode info after printk works. This is delayed info dump.
511  */
512 void show_ucode_info_early(void)
513 {
514         struct ucode_cpu_info uci;
515
516         if (delay_ucode_info) {
517                 collect_cpu_info_early(&uci);
518                 print_ucode_info(&uci, current_mc_date);
519                 delay_ucode_info = 0;
520         }
521 }
522
523 /*
524  * At this point, we can not call printk() yet. Keep microcode patch number in
525  * mc_saved_data.mc_saved and delay printing microcode info in
526  * show_ucode_info_early() until printk() works.
527  */
528 static void print_ucode(struct ucode_cpu_info *uci)
529 {
530         struct microcode_intel *mc;
531         int *delay_ucode_info_p;
532         int *current_mc_date_p;
533
534         mc = uci->mc;
535         if (!mc)
536                 return;
537
538         delay_ucode_info_p = (int *)__pa_nodebug(&delay_ucode_info);
539         current_mc_date_p = (int *)__pa_nodebug(&current_mc_date);
540
541         *delay_ucode_info_p = 1;
542         *current_mc_date_p = mc->hdr.date;
543 }
544 #else
545
546 /*
547  * Flush global tlb. We only do this in x86_64 where paging has been enabled
548  * already and PGE should be enabled as well.
549  */
550 static inline void flush_tlb_early(void)
551 {
552         __native_flush_tlb_global_irq_disabled();
553 }
554
555 static inline void print_ucode(struct ucode_cpu_info *uci)
556 {
557         struct microcode_intel *mc;
558
559         mc = uci->mc;
560         if (!mc)
561                 return;
562
563         print_ucode_info(uci, mc->hdr.date);
564 }
565 #endif
566
567 static int apply_microcode_early(struct ucode_cpu_info *uci, bool early)
568 {
569         struct microcode_intel *mc;
570         u32 rev;
571
572         mc = uci->mc;
573         if (!mc)
574                 return 0;
575
576         /*
577          * Save us the MSR write below - which is a particular expensive
578          * operation - when the other hyperthread has updated the microcode
579          * already.
580          */
581         rev = intel_get_microcode_revision();
582         if (rev >= mc->hdr.rev) {
583                 uci->cpu_sig.rev = rev;
584                 return 0;
585         }
586
587         /* write microcode via MSR 0x79 */
588         native_wrmsrl(MSR_IA32_UCODE_WRITE, (unsigned long)mc->bits);
589
590         rev = intel_get_microcode_revision();
591         if (rev != mc->hdr.rev)
592                 return -1;
593
594 #ifdef CONFIG_X86_64
595         /* Flush global tlb. This is precaution. */
596         flush_tlb_early();
597 #endif
598         uci->cpu_sig.rev = rev;
599
600         if (early)
601                 print_ucode(uci);
602         else
603                 print_ucode_info(uci, mc->hdr.date);
604
605         return 0;
606 }
607
608 /*
609  * This function converts microcode patch offsets previously stored in
610  * mc_tmp_ptrs to pointers and stores the pointers in mc_saved_data.
611  */
612 int __init save_microcode_in_initrd_intel(void)
613 {
614         struct microcode_intel *mc_saved[MAX_UCODE_COUNT];
615         unsigned int count = mc_saved_data.num_saved;
616         unsigned long offset = 0;
617         int ret;
618
619         if (!count)
620                 return 0;
621
622         /*
623          * We have found a valid initrd but it might've been relocated in the
624          * meantime so get its updated address.
625          */
626         if (IS_ENABLED(CONFIG_BLK_DEV_INITRD) && blobs.valid)
627                 offset = initrd_start;
628
629         copy_ptrs(mc_saved, mc_tmp_ptrs, offset, count);
630
631         ret = save_microcode(&mc_saved_data, mc_saved, count);
632         if (ret)
633                 pr_err("Cannot save microcode patches from initrd.\n");
634         else
635                 show_saved_mc();
636
637         return ret;
638 }
639
640 static __init enum ucode_state
641 __scan_microcode_initrd(struct cpio_data *cd, struct ucode_blobs *blbp)
642 {
643 #ifdef CONFIG_BLK_DEV_INITRD
644         static __initdata char ucode_name[] = "/*(DEBLOBBED)*/";
645         char *p = IS_ENABLED(CONFIG_X86_32) ? (char *)__pa_nodebug(ucode_name)
646                                                     : ucode_name;
647 # ifdef CONFIG_X86_32
648         unsigned long start = 0, size;
649         struct boot_params *params;
650
651         params = (struct boot_params *)__pa_nodebug(&boot_params);
652         size   = params->hdr.ramdisk_size;
653
654         /*
655          * Set start only if we have an initrd image. We cannot use initrd_start
656          * because it is not set that early yet.
657          */
658         start = (size ? params->hdr.ramdisk_image : 0);
659
660 # else /* CONFIG_X86_64 */
661         unsigned long start = 0, size;
662
663         size  = (u64)boot_params.ext_ramdisk_size << 32;
664         size |= boot_params.hdr.ramdisk_size;
665
666         if (size) {
667                 start  = (u64)boot_params.ext_ramdisk_image << 32;
668                 start |= boot_params.hdr.ramdisk_image;
669
670                 start += PAGE_OFFSET;
671         }
672 # endif
673
674         *cd = find_cpio_data(p, (void *)start, size, NULL);
675         if (cd->data) {
676                 blbp->start = start;
677                 blbp->valid = true;
678
679                 return UCODE_OK;
680         } else
681 #endif /* CONFIG_BLK_DEV_INITRD */
682                 return UCODE_ERROR;
683 }
684
685 static __init enum ucode_state
686 scan_microcode(struct mc_saved_data *mcs, unsigned long *mc_ptrs,
687                struct ucode_cpu_info *uci, struct ucode_blobs *blbp)
688 {
689         struct cpio_data cd = { NULL, 0, "" };
690         enum ucode_state ret;
691
692         /* try built-in microcode first */
693         if (load_builtin_intel_microcode(&cd))
694                 /*
695                  * Invalidate blobs as we might've gotten an initrd too,
696                  * supplied by the boot loader, by mistake or simply forgotten
697                  * there. That's fine, we ignore it since we've found builtin
698                  * microcode already.
699                  */
700                 blbp->valid = false;
701         else {
702                 ret = __scan_microcode_initrd(&cd, blbp);
703                 if (ret != UCODE_OK)
704                         return ret;
705         }
706
707         return get_matching_model_microcode(blbp->start, cd.data, cd.size,
708                                             mcs, mc_ptrs, uci);
709 }
710
711 static void __init
712 _load_ucode_intel_bsp(struct mc_saved_data *mcs, unsigned long *mc_ptrs,
713                       struct ucode_blobs *blbp)
714 {
715         struct ucode_cpu_info uci;
716         enum ucode_state ret;
717
718         collect_cpu_info_early(&uci);
719
720         ret = scan_microcode(mcs, mc_ptrs, &uci, blbp);
721         if (ret != UCODE_OK)
722                 return;
723
724         ret = load_microcode(mcs, mc_ptrs, blbp->start, &uci);
725         if (ret != UCODE_OK)
726                 return;
727
728         apply_microcode_early(&uci, true);
729 }
730
731 void __init load_ucode_intel_bsp(void)
732 {
733         struct ucode_blobs *blobs_p;
734         struct mc_saved_data *mcs;
735         unsigned long *ptrs;
736
737 #ifdef CONFIG_X86_32
738         mcs     = (struct mc_saved_data *)__pa_nodebug(&mc_saved_data);
739         ptrs    = (unsigned long *)__pa_nodebug(&mc_tmp_ptrs);
740         blobs_p = (struct ucode_blobs *)__pa_nodebug(&blobs);
741 #else
742         mcs     = &mc_saved_data;
743         ptrs    = mc_tmp_ptrs;
744         blobs_p = &blobs;
745 #endif
746
747         _load_ucode_intel_bsp(mcs, ptrs, blobs_p);
748 }
749
750 void load_ucode_intel_ap(void)
751 {
752         struct ucode_blobs *blobs_p;
753         unsigned long *ptrs, start = 0;
754         struct mc_saved_data *mcs;
755         struct ucode_cpu_info uci;
756         enum ucode_state ret;
757
758 #ifdef CONFIG_X86_32
759         mcs     = (struct mc_saved_data *)__pa_nodebug(&mc_saved_data);
760         ptrs    = (unsigned long *)__pa_nodebug(mc_tmp_ptrs);
761         blobs_p = (struct ucode_blobs *)__pa_nodebug(&blobs);
762 #else
763         mcs     = &mc_saved_data;
764         ptrs    = mc_tmp_ptrs;
765         blobs_p = &blobs;
766 #endif
767
768         /*
769          * If there is no valid ucode previously saved in memory, no need to
770          * update ucode on this AP.
771          */
772         if (!mcs->num_saved)
773                 return;
774
775         if (blobs_p->valid) {
776                 start = blobs_p->start;
777
778                 /*
779                  * Pay attention to CONFIG_RANDOMIZE_MEMORY=y as it shuffles
780                  * physmem mapping too and there we have the initrd.
781                  */
782                 start += PAGE_OFFSET - __PAGE_OFFSET_BASE;
783         }
784
785         collect_cpu_info_early(&uci);
786         ret = load_microcode(mcs, ptrs, start, &uci);
787         if (ret != UCODE_OK)
788                 return;
789
790         apply_microcode_early(&uci, true);
791 }
792
793 void reload_ucode_intel(void)
794 {
795         struct ucode_cpu_info uci;
796         enum ucode_state ret;
797
798         if (!mc_saved_data.num_saved)
799                 return;
800
801         collect_cpu_info_early(&uci);
802
803         ret = find_microcode_patch(mc_saved_data.mc_saved,
804                                    mc_saved_data.num_saved, &uci);
805         if (ret != UCODE_OK)
806                 return;
807
808         apply_microcode_early(&uci, false);
809 }
810
811 static int collect_cpu_info(int cpu_num, struct cpu_signature *csig)
812 {
813         static struct cpu_signature prev;
814         struct cpuinfo_x86 *c = &cpu_data(cpu_num);
815         unsigned int val[2];
816
817         memset(csig, 0, sizeof(*csig));
818
819         csig->sig = cpuid_eax(0x00000001);
820
821         if ((c->x86_model >= 5) || (c->x86 > 6)) {
822                 /* get processor flags from MSR 0x17 */
823                 rdmsr(MSR_IA32_PLATFORM_ID, val[0], val[1]);
824                 csig->pf = 1 << ((val[1] >> 18) & 7);
825         }
826
827         csig->rev = c->microcode;
828
829         /* No extra locking on prev, races are harmless. */
830         if (csig->sig != prev.sig || csig->pf != prev.pf || csig->rev != prev.rev) {
831                 pr_info("sig=0x%x, pf=0x%x, revision=0x%x\n",
832                         csig->sig, csig->pf, csig->rev);
833                 prev = *csig;
834         }
835
836         return 0;
837 }
838
839 /*
840  * return 0 - no update found
841  * return 1 - found update
842  */
843 static int get_matching_mc(struct microcode_intel *mc, int cpu)
844 {
845         struct cpu_signature cpu_sig;
846         unsigned int csig, cpf, crev;
847
848         collect_cpu_info(cpu, &cpu_sig);
849
850         csig = cpu_sig.sig;
851         cpf = cpu_sig.pf;
852         crev = cpu_sig.rev;
853
854         return has_newer_microcode(mc, csig, cpf, crev);
855 }
856
857 static int apply_microcode_intel(int cpu)
858 {
859         struct microcode_intel *mc;
860         struct ucode_cpu_info *uci;
861         struct cpuinfo_x86 *c = &cpu_data(cpu);
862         static int prev_rev;
863         u32 rev;
864
865         /* We should bind the task to the CPU */
866         if (WARN_ON(raw_smp_processor_id() != cpu))
867                 return -1;
868
869         uci = ucode_cpu_info + cpu;
870         mc = uci->mc;
871         if (!mc)
872                 return 0;
873
874         /*
875          * Microcode on this CPU could be updated earlier. Only apply the
876          * microcode patch in mc when it is newer than the one on this
877          * CPU.
878          */
879         if (!get_matching_mc(mc, cpu))
880                 return 0;
881
882         /*
883          * Save us the MSR write below - which is a particular expensive
884          * operation - when the other hyperthread has updated the microcode
885          * already.
886          */
887         rev = intel_get_microcode_revision();
888         if (rev >= mc->hdr.rev)
889                 goto out;
890
891         /* write microcode via MSR 0x79 */
892         wrmsrl(MSR_IA32_UCODE_WRITE, (unsigned long)mc->bits);
893
894         rev = intel_get_microcode_revision();
895
896         if (rev != mc->hdr.rev) {
897                 pr_err("CPU%d update to revision 0x%x failed\n",
898                        cpu, mc->hdr.rev);
899                 return -1;
900         }
901
902         if (rev != prev_rev) {
903                 pr_info("updated to revision 0x%x, date = %04x-%02x-%02x\n",
904                         rev,
905                         mc->hdr.date & 0xffff,
906                         mc->hdr.date >> 24,
907                         (mc->hdr.date >> 16) & 0xff);
908                 prev_rev = rev;
909         }
910
911 out:
912         uci->cpu_sig.rev = rev;
913         c->microcode     = rev;
914
915         /* Update boot_cpu_data's revision too, if we're on the BSP: */
916         if (c->cpu_index == boot_cpu_data.cpu_index)
917                 boot_cpu_data.microcode = rev;
918
919         return 0;
920 }
921
922 static enum ucode_state generic_load_microcode(int cpu, void *data, size_t size,
923                                 int (*get_ucode_data)(void *, const void *, size_t))
924 {
925         struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
926         u8 *ucode_ptr = data, *new_mc = NULL, *mc = NULL;
927         int new_rev = uci->cpu_sig.rev;
928         unsigned int leftover = size;
929         enum ucode_state state = UCODE_OK;
930         unsigned int curr_mc_size = 0;
931         unsigned int csig, cpf;
932
933         while (leftover) {
934                 struct microcode_header_intel mc_header;
935                 unsigned int mc_size;
936
937                 if (leftover < sizeof(mc_header)) {
938                         pr_err("error! Truncated header in microcode data file\n");
939                         break;
940                 }
941
942                 if (get_ucode_data(&mc_header, ucode_ptr, sizeof(mc_header)))
943                         break;
944
945                 mc_size = get_totalsize(&mc_header);
946                 if (!mc_size || mc_size > leftover) {
947                         pr_err("error! Bad data in microcode data file\n");
948                         break;
949                 }
950
951                 /* For performance reasons, reuse mc area when possible */
952                 if (!mc || mc_size > curr_mc_size) {
953                         vfree(mc);
954                         mc = vmalloc(mc_size);
955                         if (!mc)
956                                 break;
957                         curr_mc_size = mc_size;
958                 }
959
960                 if (get_ucode_data(mc, ucode_ptr, mc_size) ||
961                     microcode_sanity_check(mc, 1) < 0) {
962                         break;
963                 }
964
965                 csig = uci->cpu_sig.sig;
966                 cpf = uci->cpu_sig.pf;
967                 if (has_newer_microcode(mc, csig, cpf, new_rev)) {
968                         vfree(new_mc);
969                         new_rev = mc_header.rev;
970                         new_mc  = mc;
971                         mc = NULL;      /* trigger new vmalloc */
972                 }
973
974                 ucode_ptr += mc_size;
975                 leftover  -= mc_size;
976         }
977
978         vfree(mc);
979
980         if (leftover) {
981                 vfree(new_mc);
982                 state = UCODE_ERROR;
983                 goto out;
984         }
985
986         if (!new_mc) {
987                 state = UCODE_NFOUND;
988                 goto out;
989         }
990
991         vfree(uci->mc);
992         uci->mc = (struct microcode_intel *)new_mc;
993
994         /*
995          * If early loading microcode is supported, save this mc into
996          * permanent memory. So it will be loaded early when a CPU is hot added
997          * or resumes.
998          */
999         save_mc_for_early(new_mc);
1000
1001         pr_debug("CPU%d found a matching microcode update with version 0x%x (current=0x%x)\n",
1002                  cpu, new_rev, uci->cpu_sig.rev);
1003 out:
1004         return state;
1005 }
1006
1007 static int get_ucode_fw(void *to, const void *from, size_t n)
1008 {
1009         memcpy(to, from, n);
1010         return 0;
1011 }
1012
1013 static bool is_blacklisted(unsigned int cpu)
1014 {
1015         struct cpuinfo_x86 *c = &cpu_data(cpu);
1016
1017         /*
1018          * Late loading on model 79 with microcode revision less than 0x0b000021
1019          * and LLC size per core bigger than 2.5MB may result in a system hang.
1020          * This behavior is documented in item BDF90, #334165 (Intel Xeon
1021          * Processor E7-8800/4800 v4 Product Family).
1022          */
1023         if (c->x86 == 6 &&
1024             c->x86_model == INTEL_FAM6_BROADWELL_X &&
1025             c->x86_stepping == 0x01 &&
1026             llc_size_per_core > 2621440 &&
1027             c->microcode < 0x0b000021) {
1028                 pr_err_once("Erratum BDF90: late loading with revision < 0x0b000021 (0x%x) disabled.\n", c->microcode);
1029                 pr_err_once("Please consider either early loading through initrd/built-in or a potential BIOS update.\n");
1030                 return true;
1031         }
1032
1033         return false;
1034 }
1035
1036 static enum ucode_state request_microcode_fw(int cpu, struct device *device,
1037                                              bool refresh_fw)
1038 {
1039         char name[30];
1040         struct cpuinfo_x86 *c = &cpu_data(cpu);
1041         const struct firmware *firmware;
1042         enum ucode_state ret;
1043
1044         if (is_blacklisted(cpu))
1045                 return UCODE_NFOUND;
1046
1047         sprintf(name, "/*(DEBLOBBED)*/",
1048                 c->x86, c->x86_model, c->x86_stepping);
1049
1050         if (reject_firmware_direct(&firmware, name, device)) {
1051                 pr_debug("data file %s load failed\n", name);
1052                 return UCODE_NFOUND;
1053         }
1054
1055         ret = generic_load_microcode(cpu, (void *)firmware->data,
1056                                      firmware->size, &get_ucode_fw);
1057
1058         release_firmware(firmware);
1059
1060         return ret;
1061 }
1062
1063 static int get_ucode_user(void *to, const void *from, size_t n)
1064 {
1065         return copy_from_user(to, from, n);
1066 }
1067
1068 static enum ucode_state
1069 request_microcode_user(int cpu, const void __user *buf, size_t size)
1070 {
1071         if (is_blacklisted(cpu))
1072                 return UCODE_NFOUND;
1073
1074         return generic_load_microcode(cpu, (void *)buf, size, &get_ucode_user);
1075 }
1076
1077 static void microcode_fini_cpu(int cpu)
1078 {
1079         struct ucode_cpu_info *uci = ucode_cpu_info + cpu;
1080
1081         vfree(uci->mc);
1082         uci->mc = NULL;
1083 }
1084
1085 static struct microcode_ops microcode_intel_ops = {
1086         .request_microcode_user           = request_microcode_user,
1087         .request_microcode_fw             = request_microcode_fw,
1088         .collect_cpu_info                 = collect_cpu_info,
1089         .apply_microcode                  = apply_microcode_intel,
1090         .microcode_fini_cpu               = microcode_fini_cpu,
1091 };
1092
1093 static int __init calc_llc_size_per_core(struct cpuinfo_x86 *c)
1094 {
1095         u64 llc_size = c->x86_cache_size * 1024ULL;
1096
1097         do_div(llc_size, c->x86_max_cores);
1098
1099         return (int)llc_size;
1100 }
1101
1102 struct microcode_ops * __init init_intel_microcode(void)
1103 {
1104         struct cpuinfo_x86 *c = &boot_cpu_data;
1105
1106         if (c->x86_vendor != X86_VENDOR_INTEL || c->x86 < 6 ||
1107             cpu_has(c, X86_FEATURE_IA64)) {
1108                 pr_err("Intel CPU family 0x%x not supported\n", c->x86);
1109                 return NULL;
1110         }
1111
1112         llc_size_per_core = calc_llc_size_per_core(c);
1113
1114         return &microcode_intel_ops;
1115 }
1116