GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / acpi / apei / ghes.c
1 /*
2  * APEI Generic Hardware Error Source support
3  *
4  * Generic Hardware Error Source provides a way to report platform
5  * hardware errors (such as that from chipset). It works in so called
6  * "Firmware First" mode, that is, hardware errors are reported to
7  * firmware firstly, then reported to Linux by firmware. This way,
8  * some non-standard hardware error registers or non-standard hardware
9  * link can be checked by firmware to produce more hardware error
10  * information for Linux.
11  *
12  * For more information about Generic Hardware Error Source, please
13  * refer to ACPI Specification version 4.0, section 17.3.2.6
14  *
15  * Copyright 2010,2011 Intel Corp.
16  *   Author: Huang Ying <ying.huang@intel.com>
17  *
18  * This program is free software; you can redistribute it and/or
19  * modify it under the terms of the GNU General Public License version
20  * 2 as published by the Free Software Foundation;
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  */
27
28 #include <linux/kernel.h>
29 #include <linux/moduleparam.h>
30 #include <linux/init.h>
31 #include <linux/acpi.h>
32 #include <linux/io.h>
33 #include <linux/interrupt.h>
34 #include <linux/timer.h>
35 #include <linux/cper.h>
36 #include <linux/platform_device.h>
37 #include <linux/mutex.h>
38 #include <linux/ratelimit.h>
39 #include <linux/vmalloc.h>
40 #include <linux/irq_work.h>
41 #include <linux/llist.h>
42 #include <linux/genalloc.h>
43 #include <linux/pci.h>
44 #include <linux/aer.h>
45 #include <linux/nmi.h>
46 #include <linux/sched/clock.h>
47 #include <linux/uuid.h>
48 #include <linux/ras.h>
49
50 #include <acpi/actbl1.h>
51 #include <acpi/ghes.h>
52 #include <acpi/apei.h>
53 #include <asm/fixmap.h>
54 #include <asm/tlbflush.h>
55 #include <ras/ras_event.h>
56
57 #include "apei-internal.h"
58
59 #define GHES_PFX        "GHES: "
60
61 #define GHES_ESTATUS_MAX_SIZE           65536
62 #define GHES_ESOURCE_PREALLOC_MAX_SIZE  65536
63
64 #define GHES_ESTATUS_POOL_MIN_ALLOC_ORDER 3
65
66 /* This is just an estimation for memory pool allocation */
67 #define GHES_ESTATUS_CACHE_AVG_SIZE     512
68
69 #define GHES_ESTATUS_CACHES_SIZE        4
70
71 #define GHES_ESTATUS_IN_CACHE_MAX_NSEC  10000000000ULL
72 /* Prevent too many caches are allocated because of RCU */
73 #define GHES_ESTATUS_CACHE_ALLOCED_MAX  (GHES_ESTATUS_CACHES_SIZE * 3 / 2)
74
75 #define GHES_ESTATUS_CACHE_LEN(estatus_len)                     \
76         (sizeof(struct ghes_estatus_cache) + (estatus_len))
77 #define GHES_ESTATUS_FROM_CACHE(estatus_cache)                  \
78         ((struct acpi_hest_generic_status *)                            \
79          ((struct ghes_estatus_cache *)(estatus_cache) + 1))
80
81 #define GHES_ESTATUS_NODE_LEN(estatus_len)                      \
82         (sizeof(struct ghes_estatus_node) + (estatus_len))
83 #define GHES_ESTATUS_FROM_NODE(estatus_node)                    \
84         ((struct acpi_hest_generic_status *)                            \
85          ((struct ghes_estatus_node *)(estatus_node) + 1))
86
87 static inline bool is_hest_type_generic_v2(struct ghes *ghes)
88 {
89         return ghes->generic->header.type == ACPI_HEST_TYPE_GENERIC_ERROR_V2;
90 }
91
92 /*
93  * This driver isn't really modular, however for the time being,
94  * continuing to use module_param is the easiest way to remain
95  * compatible with existing boot arg use cases.
96  */
97 bool ghes_disable;
98 module_param_named(disable, ghes_disable, bool, 0);
99
100 /*
101  * All error sources notified with HED (Hardware Error Device) share a
102  * single notifier callback, so they need to be linked and checked one
103  * by one. This holds true for NMI too.
104  *
105  * RCU is used for these lists, so ghes_list_mutex is only used for
106  * list changing, not for traversing.
107  */
108 static LIST_HEAD(ghes_hed);
109 static DEFINE_MUTEX(ghes_list_mutex);
110
111 /*
112  * Because the memory area used to transfer hardware error information
113  * from BIOS to Linux can be determined only in NMI, IRQ or timer
114  * handler, but general ioremap can not be used in atomic context, so
115  * the fixmap is used instead.
116  *
117  * These 2 spinlocks are used to prevent the fixmap entries from being used
118  * simultaneously.
119  */
120 static DEFINE_RAW_SPINLOCK(ghes_ioremap_lock_nmi);
121 static DEFINE_SPINLOCK(ghes_ioremap_lock_irq);
122
123 static struct gen_pool *ghes_estatus_pool;
124 static unsigned long ghes_estatus_pool_size_request;
125
126 static struct ghes_estatus_cache *ghes_estatus_caches[GHES_ESTATUS_CACHES_SIZE];
127 static atomic_t ghes_estatus_cache_alloced;
128
129 static int ghes_panic_timeout __read_mostly = 30;
130
131 static void __iomem *ghes_ioremap_pfn_nmi(u64 pfn)
132 {
133         phys_addr_t paddr;
134         pgprot_t prot;
135
136         paddr = pfn << PAGE_SHIFT;
137         prot = arch_apei_get_mem_attribute(paddr);
138         __set_fixmap(FIX_APEI_GHES_NMI, paddr, prot);
139
140         return (void __iomem *) fix_to_virt(FIX_APEI_GHES_NMI);
141 }
142
143 static void __iomem *ghes_ioremap_pfn_irq(u64 pfn)
144 {
145         phys_addr_t paddr;
146         pgprot_t prot;
147
148         paddr = pfn << PAGE_SHIFT;
149         prot = arch_apei_get_mem_attribute(paddr);
150         __set_fixmap(FIX_APEI_GHES_IRQ, paddr, prot);
151
152         return (void __iomem *) fix_to_virt(FIX_APEI_GHES_IRQ);
153 }
154
155 static void ghes_iounmap_nmi(void)
156 {
157         clear_fixmap(FIX_APEI_GHES_NMI);
158 }
159
160 static void ghes_iounmap_irq(void)
161 {
162         clear_fixmap(FIX_APEI_GHES_IRQ);
163 }
164
165 static int ghes_estatus_pool_init(void)
166 {
167         ghes_estatus_pool = gen_pool_create(GHES_ESTATUS_POOL_MIN_ALLOC_ORDER, -1);
168         if (!ghes_estatus_pool)
169                 return -ENOMEM;
170         return 0;
171 }
172
173 static void ghes_estatus_pool_free_chunk(struct gen_pool *pool,
174                                               struct gen_pool_chunk *chunk,
175                                               void *data)
176 {
177         vfree((void *)chunk->start_addr);
178 }
179
180 static void ghes_estatus_pool_exit(void)
181 {
182         gen_pool_for_each_chunk(ghes_estatus_pool,
183                                 ghes_estatus_pool_free_chunk, NULL);
184         gen_pool_destroy(ghes_estatus_pool);
185 }
186
187 static int ghes_estatus_pool_expand(unsigned long len)
188 {
189         unsigned long size, addr;
190
191         ghes_estatus_pool_size_request += PAGE_ALIGN(len);
192         size = gen_pool_size(ghes_estatus_pool);
193         if (size >= ghes_estatus_pool_size_request)
194                 return 0;
195
196         addr = (unsigned long)vmalloc(PAGE_ALIGN(len));
197         if (!addr)
198                 return -ENOMEM;
199
200         /*
201          * New allocation must be visible in all pgd before it can be found by
202          * an NMI allocating from the pool.
203          */
204         vmalloc_sync_mappings();
205
206         return gen_pool_add(ghes_estatus_pool, addr, PAGE_ALIGN(len), -1);
207 }
208
209 static int map_gen_v2(struct ghes *ghes)
210 {
211         return apei_map_generic_address(&ghes->generic_v2->read_ack_register);
212 }
213
214 static void unmap_gen_v2(struct ghes *ghes)
215 {
216         apei_unmap_generic_address(&ghes->generic_v2->read_ack_register);
217 }
218
219 static struct ghes *ghes_new(struct acpi_hest_generic *generic)
220 {
221         struct ghes *ghes;
222         unsigned int error_block_length;
223         int rc;
224
225         ghes = kzalloc(sizeof(*ghes), GFP_KERNEL);
226         if (!ghes)
227                 return ERR_PTR(-ENOMEM);
228
229         ghes->generic = generic;
230         if (is_hest_type_generic_v2(ghes)) {
231                 rc = map_gen_v2(ghes);
232                 if (rc)
233                         goto err_free;
234         }
235
236         rc = apei_map_generic_address(&generic->error_status_address);
237         if (rc)
238                 goto err_unmap_read_ack_addr;
239         error_block_length = generic->error_block_length;
240         if (error_block_length > GHES_ESTATUS_MAX_SIZE) {
241                 pr_warning(FW_WARN GHES_PFX
242                            "Error status block length is too long: %u for "
243                            "generic hardware error source: %d.\n",
244                            error_block_length, generic->header.source_id);
245                 error_block_length = GHES_ESTATUS_MAX_SIZE;
246         }
247         ghes->estatus = kmalloc(error_block_length, GFP_KERNEL);
248         if (!ghes->estatus) {
249                 rc = -ENOMEM;
250                 goto err_unmap_status_addr;
251         }
252
253         return ghes;
254
255 err_unmap_status_addr:
256         apei_unmap_generic_address(&generic->error_status_address);
257 err_unmap_read_ack_addr:
258         if (is_hest_type_generic_v2(ghes))
259                 unmap_gen_v2(ghes);
260 err_free:
261         kfree(ghes);
262         return ERR_PTR(rc);
263 }
264
265 static void ghes_fini(struct ghes *ghes)
266 {
267         kfree(ghes->estatus);
268         apei_unmap_generic_address(&ghes->generic->error_status_address);
269         if (is_hest_type_generic_v2(ghes))
270                 unmap_gen_v2(ghes);
271 }
272
273 static inline int ghes_severity(int severity)
274 {
275         switch (severity) {
276         case CPER_SEV_INFORMATIONAL:
277                 return GHES_SEV_NO;
278         case CPER_SEV_CORRECTED:
279                 return GHES_SEV_CORRECTED;
280         case CPER_SEV_RECOVERABLE:
281                 return GHES_SEV_RECOVERABLE;
282         case CPER_SEV_FATAL:
283                 return GHES_SEV_PANIC;
284         default:
285                 /* Unknown, go panic */
286                 return GHES_SEV_PANIC;
287         }
288 }
289
290 static void ghes_copy_tofrom_phys(void *buffer, u64 paddr, u32 len,
291                                   int from_phys)
292 {
293         void __iomem *vaddr;
294         unsigned long flags = 0;
295         int in_nmi = in_nmi();
296         u64 offset;
297         u32 trunk;
298
299         while (len > 0) {
300                 offset = paddr - (paddr & PAGE_MASK);
301                 if (in_nmi) {
302                         raw_spin_lock(&ghes_ioremap_lock_nmi);
303                         vaddr = ghes_ioremap_pfn_nmi(paddr >> PAGE_SHIFT);
304                 } else {
305                         spin_lock_irqsave(&ghes_ioremap_lock_irq, flags);
306                         vaddr = ghes_ioremap_pfn_irq(paddr >> PAGE_SHIFT);
307                 }
308                 trunk = PAGE_SIZE - offset;
309                 trunk = min(trunk, len);
310                 if (from_phys)
311                         memcpy_fromio(buffer, vaddr + offset, trunk);
312                 else
313                         memcpy_toio(vaddr + offset, buffer, trunk);
314                 len -= trunk;
315                 paddr += trunk;
316                 buffer += trunk;
317                 if (in_nmi) {
318                         ghes_iounmap_nmi();
319                         raw_spin_unlock(&ghes_ioremap_lock_nmi);
320                 } else {
321                         ghes_iounmap_irq();
322                         spin_unlock_irqrestore(&ghes_ioremap_lock_irq, flags);
323                 }
324         }
325 }
326
327 static int ghes_read_estatus(struct ghes *ghes, int silent)
328 {
329         struct acpi_hest_generic *g = ghes->generic;
330         u64 buf_paddr;
331         u32 len;
332         int rc;
333
334         rc = apei_read(&buf_paddr, &g->error_status_address);
335         if (rc) {
336                 if (!silent && printk_ratelimit())
337                         pr_warning(FW_WARN GHES_PFX
338 "Failed to read error status block address for hardware error source: %d.\n",
339                                    g->header.source_id);
340                 return -EIO;
341         }
342         if (!buf_paddr)
343                 return -ENOENT;
344
345         ghes_copy_tofrom_phys(ghes->estatus, buf_paddr,
346                               sizeof(*ghes->estatus), 1);
347         if (!ghes->estatus->block_status)
348                 return -ENOENT;
349
350         ghes->buffer_paddr = buf_paddr;
351         ghes->flags |= GHES_TO_CLEAR;
352
353         rc = -EIO;
354         len = cper_estatus_len(ghes->estatus);
355         if (len < sizeof(*ghes->estatus))
356                 goto err_read_block;
357         if (len > ghes->generic->error_block_length)
358                 goto err_read_block;
359         if (cper_estatus_check_header(ghes->estatus))
360                 goto err_read_block;
361         ghes_copy_tofrom_phys(ghes->estatus + 1,
362                               buf_paddr + sizeof(*ghes->estatus),
363                               len - sizeof(*ghes->estatus), 1);
364         if (cper_estatus_check(ghes->estatus))
365                 goto err_read_block;
366         rc = 0;
367
368 err_read_block:
369         if (rc && !silent && printk_ratelimit())
370                 pr_warning(FW_WARN GHES_PFX
371                            "Failed to read error status block!\n");
372         return rc;
373 }
374
375 static void ghes_clear_estatus(struct ghes *ghes)
376 {
377         ghes->estatus->block_status = 0;
378         if (!(ghes->flags & GHES_TO_CLEAR))
379                 return;
380         ghes_copy_tofrom_phys(ghes->estatus, ghes->buffer_paddr,
381                               sizeof(ghes->estatus->block_status), 0);
382         ghes->flags &= ~GHES_TO_CLEAR;
383 }
384
385 static void ghes_handle_memory_failure(struct acpi_hest_generic_data *gdata, int sev)
386 {
387 #ifdef CONFIG_ACPI_APEI_MEMORY_FAILURE
388         unsigned long pfn;
389         int flags = -1;
390         int sec_sev = ghes_severity(gdata->error_severity);
391         struct cper_sec_mem_err *mem_err = acpi_hest_get_payload(gdata);
392
393         if (!(mem_err->validation_bits & CPER_MEM_VALID_PA))
394                 return;
395
396         pfn = mem_err->physical_addr >> PAGE_SHIFT;
397         if (!pfn_valid(pfn)) {
398                 pr_warn_ratelimited(FW_WARN GHES_PFX
399                 "Invalid address in generic error data: %#llx\n",
400                 mem_err->physical_addr);
401                 return;
402         }
403
404         /* iff following two events can be handled properly by now */
405         if (sec_sev == GHES_SEV_CORRECTED &&
406             (gdata->flags & CPER_SEC_ERROR_THRESHOLD_EXCEEDED))
407                 flags = MF_SOFT_OFFLINE;
408         if (sev == GHES_SEV_RECOVERABLE && sec_sev == GHES_SEV_RECOVERABLE)
409                 flags = 0;
410
411         if (flags != -1)
412                 memory_failure_queue(pfn, 0, flags);
413 #endif
414 }
415
416 static void ghes_do_proc(struct ghes *ghes,
417                          const struct acpi_hest_generic_status *estatus)
418 {
419         int sev, sec_sev;
420         struct acpi_hest_generic_data *gdata;
421         guid_t *sec_type;
422         guid_t *fru_id = &NULL_UUID_LE;
423         char *fru_text = "";
424
425         sev = ghes_severity(estatus->error_severity);
426         apei_estatus_for_each_section(estatus, gdata) {
427                 sec_type = (guid_t *)gdata->section_type;
428                 sec_sev = ghes_severity(gdata->error_severity);
429                 if (gdata->validation_bits & CPER_SEC_VALID_FRU_ID)
430                         fru_id = (guid_t *)gdata->fru_id;
431
432                 if (gdata->validation_bits & CPER_SEC_VALID_FRU_TEXT)
433                         fru_text = gdata->fru_text;
434
435                 if (guid_equal(sec_type, &CPER_SEC_PLATFORM_MEM)) {
436                         struct cper_sec_mem_err *mem_err = acpi_hest_get_payload(gdata);
437
438                         ghes_edac_report_mem_error(ghes, sev, mem_err);
439
440                         arch_apei_report_mem_error(sev, mem_err);
441                         ghes_handle_memory_failure(gdata, sev);
442                 }
443 #ifdef CONFIG_ACPI_APEI_PCIEAER
444                 else if (guid_equal(sec_type, &CPER_SEC_PCIE)) {
445                         struct cper_sec_pcie *pcie_err = acpi_hest_get_payload(gdata);
446
447                         if (sev == GHES_SEV_RECOVERABLE &&
448                             sec_sev == GHES_SEV_RECOVERABLE &&
449                             pcie_err->validation_bits & CPER_PCIE_VALID_DEVICE_ID &&
450                             pcie_err->validation_bits & CPER_PCIE_VALID_AER_INFO) {
451                                 unsigned int devfn;
452                                 int aer_severity;
453
454                                 devfn = PCI_DEVFN(pcie_err->device_id.device,
455                                                   pcie_err->device_id.function);
456                                 aer_severity = cper_severity_to_aer(gdata->error_severity);
457
458                                 /*
459                                  * If firmware reset the component to contain
460                                  * the error, we must reinitialize it before
461                                  * use, so treat it as a fatal AER error.
462                                  */
463                                 if (gdata->flags & CPER_SEC_RESET)
464                                         aer_severity = AER_FATAL;
465
466                                 aer_recover_queue(pcie_err->device_id.segment,
467                                                   pcie_err->device_id.bus,
468                                                   devfn, aer_severity,
469                                                   (struct aer_capability_regs *)
470                                                   pcie_err->aer_info);
471                         }
472
473                 }
474 #endif
475                 else if (guid_equal(sec_type, &CPER_SEC_PROC_ARM)) {
476                         struct cper_sec_proc_arm *err = acpi_hest_get_payload(gdata);
477
478                         log_arm_hw_error(err);
479                 } else {
480                         void *err = acpi_hest_get_payload(gdata);
481
482                         log_non_standard_event(sec_type, fru_id, fru_text,
483                                                sec_sev, err,
484                                                gdata->error_data_length);
485                 }
486         }
487 }
488
489 static void __ghes_print_estatus(const char *pfx,
490                                  const struct acpi_hest_generic *generic,
491                                  const struct acpi_hest_generic_status *estatus)
492 {
493         static atomic_t seqno;
494         unsigned int curr_seqno;
495         char pfx_seq[64];
496
497         if (pfx == NULL) {
498                 if (ghes_severity(estatus->error_severity) <=
499                     GHES_SEV_CORRECTED)
500                         pfx = KERN_WARNING;
501                 else
502                         pfx = KERN_ERR;
503         }
504         curr_seqno = atomic_inc_return(&seqno);
505         snprintf(pfx_seq, sizeof(pfx_seq), "%s{%u}" HW_ERR, pfx, curr_seqno);
506         printk("%s""Hardware error from APEI Generic Hardware Error Source: %d\n",
507                pfx_seq, generic->header.source_id);
508         cper_estatus_print(pfx_seq, estatus);
509 }
510
511 static int ghes_print_estatus(const char *pfx,
512                               const struct acpi_hest_generic *generic,
513                               const struct acpi_hest_generic_status *estatus)
514 {
515         /* Not more than 2 messages every 5 seconds */
516         static DEFINE_RATELIMIT_STATE(ratelimit_corrected, 5*HZ, 2);
517         static DEFINE_RATELIMIT_STATE(ratelimit_uncorrected, 5*HZ, 2);
518         struct ratelimit_state *ratelimit;
519
520         if (ghes_severity(estatus->error_severity) <= GHES_SEV_CORRECTED)
521                 ratelimit = &ratelimit_corrected;
522         else
523                 ratelimit = &ratelimit_uncorrected;
524         if (__ratelimit(ratelimit)) {
525                 __ghes_print_estatus(pfx, generic, estatus);
526                 return 1;
527         }
528         return 0;
529 }
530
531 /*
532  * GHES error status reporting throttle, to report more kinds of
533  * errors, instead of just most frequently occurred errors.
534  */
535 static int ghes_estatus_cached(struct acpi_hest_generic_status *estatus)
536 {
537         u32 len;
538         int i, cached = 0;
539         unsigned long long now;
540         struct ghes_estatus_cache *cache;
541         struct acpi_hest_generic_status *cache_estatus;
542
543         len = cper_estatus_len(estatus);
544         rcu_read_lock();
545         for (i = 0; i < GHES_ESTATUS_CACHES_SIZE; i++) {
546                 cache = rcu_dereference(ghes_estatus_caches[i]);
547                 if (cache == NULL)
548                         continue;
549                 if (len != cache->estatus_len)
550                         continue;
551                 cache_estatus = GHES_ESTATUS_FROM_CACHE(cache);
552                 if (memcmp(estatus, cache_estatus, len))
553                         continue;
554                 atomic_inc(&cache->count);
555                 now = sched_clock();
556                 if (now - cache->time_in < GHES_ESTATUS_IN_CACHE_MAX_NSEC)
557                         cached = 1;
558                 break;
559         }
560         rcu_read_unlock();
561         return cached;
562 }
563
564 static struct ghes_estatus_cache *ghes_estatus_cache_alloc(
565         struct acpi_hest_generic *generic,
566         struct acpi_hest_generic_status *estatus)
567 {
568         int alloced;
569         u32 len, cache_len;
570         struct ghes_estatus_cache *cache;
571         struct acpi_hest_generic_status *cache_estatus;
572
573         alloced = atomic_add_return(1, &ghes_estatus_cache_alloced);
574         if (alloced > GHES_ESTATUS_CACHE_ALLOCED_MAX) {
575                 atomic_dec(&ghes_estatus_cache_alloced);
576                 return NULL;
577         }
578         len = cper_estatus_len(estatus);
579         cache_len = GHES_ESTATUS_CACHE_LEN(len);
580         cache = (void *)gen_pool_alloc(ghes_estatus_pool, cache_len);
581         if (!cache) {
582                 atomic_dec(&ghes_estatus_cache_alloced);
583                 return NULL;
584         }
585         cache_estatus = GHES_ESTATUS_FROM_CACHE(cache);
586         memcpy(cache_estatus, estatus, len);
587         cache->estatus_len = len;
588         atomic_set(&cache->count, 0);
589         cache->generic = generic;
590         cache->time_in = sched_clock();
591         return cache;
592 }
593
594 static void ghes_estatus_cache_free(struct ghes_estatus_cache *cache)
595 {
596         u32 len;
597
598         len = cper_estatus_len(GHES_ESTATUS_FROM_CACHE(cache));
599         len = GHES_ESTATUS_CACHE_LEN(len);
600         gen_pool_free(ghes_estatus_pool, (unsigned long)cache, len);
601         atomic_dec(&ghes_estatus_cache_alloced);
602 }
603
604 static void ghes_estatus_cache_rcu_free(struct rcu_head *head)
605 {
606         struct ghes_estatus_cache *cache;
607
608         cache = container_of(head, struct ghes_estatus_cache, rcu);
609         ghes_estatus_cache_free(cache);
610 }
611
612 static void ghes_estatus_cache_add(
613         struct acpi_hest_generic *generic,
614         struct acpi_hest_generic_status *estatus)
615 {
616         int i, slot = -1, count;
617         unsigned long long now, duration, period, max_period = 0;
618         struct ghes_estatus_cache *cache, *slot_cache = NULL, *new_cache;
619
620         new_cache = ghes_estatus_cache_alloc(generic, estatus);
621         if (new_cache == NULL)
622                 return;
623         rcu_read_lock();
624         now = sched_clock();
625         for (i = 0; i < GHES_ESTATUS_CACHES_SIZE; i++) {
626                 cache = rcu_dereference(ghes_estatus_caches[i]);
627                 if (cache == NULL) {
628                         slot = i;
629                         slot_cache = NULL;
630                         break;
631                 }
632                 duration = now - cache->time_in;
633                 if (duration >= GHES_ESTATUS_IN_CACHE_MAX_NSEC) {
634                         slot = i;
635                         slot_cache = cache;
636                         break;
637                 }
638                 count = atomic_read(&cache->count);
639                 period = duration;
640                 do_div(period, (count + 1));
641                 if (period > max_period) {
642                         max_period = period;
643                         slot = i;
644                         slot_cache = cache;
645                 }
646         }
647         /* new_cache must be put into array after its contents are written */
648         smp_wmb();
649         if (slot != -1 && cmpxchg(ghes_estatus_caches + slot,
650                                   slot_cache, new_cache) == slot_cache) {
651                 if (slot_cache)
652                         call_rcu(&slot_cache->rcu, ghes_estatus_cache_rcu_free);
653         } else
654                 ghes_estatus_cache_free(new_cache);
655         rcu_read_unlock();
656 }
657
658 static int ghes_ack_error(struct acpi_hest_generic_v2 *gv2)
659 {
660         int rc;
661         u64 val = 0;
662
663         rc = apei_read(&val, &gv2->read_ack_register);
664         if (rc)
665                 return rc;
666
667         val &= gv2->read_ack_preserve << gv2->read_ack_register.bit_offset;
668         val |= gv2->read_ack_write    << gv2->read_ack_register.bit_offset;
669
670         return apei_write(val, &gv2->read_ack_register);
671 }
672
673 static void __ghes_panic(struct ghes *ghes)
674 {
675         __ghes_print_estatus(KERN_EMERG, ghes->generic, ghes->estatus);
676
677         ghes_clear_estatus(ghes);
678
679         /* reboot to log the error! */
680         if (!panic_timeout)
681                 panic_timeout = ghes_panic_timeout;
682         panic("Fatal hardware error!");
683 }
684
685 static int ghes_proc(struct ghes *ghes)
686 {
687         int rc;
688
689         rc = ghes_read_estatus(ghes, 0);
690         if (rc)
691                 goto out;
692
693         if (ghes_severity(ghes->estatus->error_severity) >= GHES_SEV_PANIC) {
694                 __ghes_panic(ghes);
695         }
696
697         if (!ghes_estatus_cached(ghes->estatus)) {
698                 if (ghes_print_estatus(NULL, ghes->generic, ghes->estatus))
699                         ghes_estatus_cache_add(ghes->generic, ghes->estatus);
700         }
701         ghes_do_proc(ghes, ghes->estatus);
702
703 out:
704         ghes_clear_estatus(ghes);
705
706         if (rc == -ENOENT)
707                 return rc;
708
709         /*
710          * GHESv2 type HEST entries introduce support for error acknowledgment,
711          * so only acknowledge the error if this support is present.
712          */
713         if (is_hest_type_generic_v2(ghes))
714                 return ghes_ack_error(ghes->generic_v2);
715
716         return rc;
717 }
718
719 static void ghes_add_timer(struct ghes *ghes)
720 {
721         struct acpi_hest_generic *g = ghes->generic;
722         unsigned long expire;
723
724         if (!g->notify.poll_interval) {
725                 pr_warning(FW_WARN GHES_PFX "Poll interval is 0 for generic hardware error source: %d, disabled.\n",
726                            g->header.source_id);
727                 return;
728         }
729         expire = jiffies + msecs_to_jiffies(g->notify.poll_interval);
730         ghes->timer.expires = round_jiffies_relative(expire);
731         add_timer(&ghes->timer);
732 }
733
734 static void ghes_poll_func(unsigned long data)
735 {
736         struct ghes *ghes = (void *)data;
737
738         ghes_proc(ghes);
739         if (!(ghes->flags & GHES_EXITING))
740                 ghes_add_timer(ghes);
741 }
742
743 static irqreturn_t ghes_irq_func(int irq, void *data)
744 {
745         struct ghes *ghes = data;
746         int rc;
747
748         rc = ghes_proc(ghes);
749         if (rc)
750                 return IRQ_NONE;
751
752         return IRQ_HANDLED;
753 }
754
755 static int ghes_notify_hed(struct notifier_block *this, unsigned long event,
756                            void *data)
757 {
758         struct ghes *ghes;
759         int ret = NOTIFY_DONE;
760
761         rcu_read_lock();
762         list_for_each_entry_rcu(ghes, &ghes_hed, list) {
763                 if (!ghes_proc(ghes))
764                         ret = NOTIFY_OK;
765         }
766         rcu_read_unlock();
767
768         return ret;
769 }
770
771 static struct notifier_block ghes_notifier_hed = {
772         .notifier_call = ghes_notify_hed,
773 };
774
775 #ifdef CONFIG_ACPI_APEI_SEA
776 static LIST_HEAD(ghes_sea);
777
778 /*
779  * Return 0 only if one of the SEA error sources successfully reported an error
780  * record sent from the firmware.
781  */
782 int ghes_notify_sea(void)
783 {
784         struct ghes *ghes;
785         int ret = -ENOENT;
786
787         rcu_read_lock();
788         list_for_each_entry_rcu(ghes, &ghes_sea, list) {
789                 if (!ghes_proc(ghes))
790                         ret = 0;
791         }
792         rcu_read_unlock();
793         return ret;
794 }
795
796 static void ghes_sea_add(struct ghes *ghes)
797 {
798         mutex_lock(&ghes_list_mutex);
799         list_add_rcu(&ghes->list, &ghes_sea);
800         mutex_unlock(&ghes_list_mutex);
801 }
802
803 static void ghes_sea_remove(struct ghes *ghes)
804 {
805         mutex_lock(&ghes_list_mutex);
806         list_del_rcu(&ghes->list);
807         mutex_unlock(&ghes_list_mutex);
808         synchronize_rcu();
809 }
810 #else /* CONFIG_ACPI_APEI_SEA */
811 static inline void ghes_sea_add(struct ghes *ghes) { }
812 static inline void ghes_sea_remove(struct ghes *ghes) { }
813 #endif /* CONFIG_ACPI_APEI_SEA */
814
815 #ifdef CONFIG_HAVE_ACPI_APEI_NMI
816 /*
817  * printk is not safe in NMI context.  So in NMI handler, we allocate
818  * required memory from lock-less memory allocator
819  * (ghes_estatus_pool), save estatus into it, put them into lock-less
820  * list (ghes_estatus_llist), then delay printk into IRQ context via
821  * irq_work (ghes_proc_irq_work).  ghes_estatus_size_request record
822  * required pool size by all NMI error source.
823  */
824 static struct llist_head ghes_estatus_llist;
825 static struct irq_work ghes_proc_irq_work;
826
827 /*
828  * NMI may be triggered on any CPU, so ghes_in_nmi is used for
829  * having only one concurrent reader.
830  */
831 static atomic_t ghes_in_nmi = ATOMIC_INIT(0);
832
833 static LIST_HEAD(ghes_nmi);
834
835 static void ghes_proc_in_irq(struct irq_work *irq_work)
836 {
837         struct llist_node *llnode, *next;
838         struct ghes_estatus_node *estatus_node;
839         struct acpi_hest_generic *generic;
840         struct acpi_hest_generic_status *estatus;
841         u32 len, node_len;
842
843         llnode = llist_del_all(&ghes_estatus_llist);
844         /*
845          * Because the time order of estatus in list is reversed,
846          * revert it back to proper order.
847          */
848         llnode = llist_reverse_order(llnode);
849         while (llnode) {
850                 next = llnode->next;
851                 estatus_node = llist_entry(llnode, struct ghes_estatus_node,
852                                            llnode);
853                 estatus = GHES_ESTATUS_FROM_NODE(estatus_node);
854                 len = cper_estatus_len(estatus);
855                 node_len = GHES_ESTATUS_NODE_LEN(len);
856                 ghes_do_proc(estatus_node->ghes, estatus);
857                 if (!ghes_estatus_cached(estatus)) {
858                         generic = estatus_node->generic;
859                         if (ghes_print_estatus(NULL, generic, estatus))
860                                 ghes_estatus_cache_add(generic, estatus);
861                 }
862                 gen_pool_free(ghes_estatus_pool, (unsigned long)estatus_node,
863                               node_len);
864                 llnode = next;
865         }
866 }
867
868 static void ghes_print_queued_estatus(void)
869 {
870         struct llist_node *llnode;
871         struct ghes_estatus_node *estatus_node;
872         struct acpi_hest_generic *generic;
873         struct acpi_hest_generic_status *estatus;
874         u32 len, node_len;
875
876         llnode = llist_del_all(&ghes_estatus_llist);
877         /*
878          * Because the time order of estatus in list is reversed,
879          * revert it back to proper order.
880          */
881         llnode = llist_reverse_order(llnode);
882         while (llnode) {
883                 estatus_node = llist_entry(llnode, struct ghes_estatus_node,
884                                            llnode);
885                 estatus = GHES_ESTATUS_FROM_NODE(estatus_node);
886                 len = cper_estatus_len(estatus);
887                 node_len = GHES_ESTATUS_NODE_LEN(len);
888                 generic = estatus_node->generic;
889                 ghes_print_estatus(NULL, generic, estatus);
890                 llnode = llnode->next;
891         }
892 }
893
894 /* Save estatus for further processing in IRQ context */
895 static void __process_error(struct ghes *ghes)
896 {
897 #ifdef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
898         u32 len, node_len;
899         struct ghes_estatus_node *estatus_node;
900         struct acpi_hest_generic_status *estatus;
901
902         if (ghes_estatus_cached(ghes->estatus))
903                 return;
904
905         len = cper_estatus_len(ghes->estatus);
906         node_len = GHES_ESTATUS_NODE_LEN(len);
907
908         estatus_node = (void *)gen_pool_alloc(ghes_estatus_pool, node_len);
909         if (!estatus_node)
910                 return;
911
912         estatus_node->ghes = ghes;
913         estatus_node->generic = ghes->generic;
914         estatus = GHES_ESTATUS_FROM_NODE(estatus_node);
915         memcpy(estatus, ghes->estatus, len);
916         llist_add(&estatus_node->llnode, &ghes_estatus_llist);
917 #endif
918 }
919
920 static int ghes_notify_nmi(unsigned int cmd, struct pt_regs *regs)
921 {
922         struct ghes *ghes;
923         int sev, ret = NMI_DONE;
924
925         if (!atomic_add_unless(&ghes_in_nmi, 1, 1))
926                 return ret;
927
928         list_for_each_entry_rcu(ghes, &ghes_nmi, list) {
929                 if (ghes_read_estatus(ghes, 1)) {
930                         ghes_clear_estatus(ghes);
931                         continue;
932                 } else {
933                         ret = NMI_HANDLED;
934                 }
935
936                 sev = ghes_severity(ghes->estatus->error_severity);
937                 if (sev >= GHES_SEV_PANIC) {
938                         ghes_print_queued_estatus();
939                         __ghes_panic(ghes);
940                 }
941
942                 if (!(ghes->flags & GHES_TO_CLEAR))
943                         continue;
944
945                 __process_error(ghes);
946                 ghes_clear_estatus(ghes);
947         }
948
949 #ifdef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
950         if (ret == NMI_HANDLED)
951                 irq_work_queue(&ghes_proc_irq_work);
952 #endif
953         atomic_dec(&ghes_in_nmi);
954         return ret;
955 }
956
957 static unsigned long ghes_esource_prealloc_size(
958         const struct acpi_hest_generic *generic)
959 {
960         unsigned long block_length, prealloc_records, prealloc_size;
961
962         block_length = min_t(unsigned long, generic->error_block_length,
963                              GHES_ESTATUS_MAX_SIZE);
964         prealloc_records = max_t(unsigned long,
965                                  generic->records_to_preallocate, 1);
966         prealloc_size = min_t(unsigned long, block_length * prealloc_records,
967                               GHES_ESOURCE_PREALLOC_MAX_SIZE);
968
969         return prealloc_size;
970 }
971
972 static void ghes_estatus_pool_shrink(unsigned long len)
973 {
974         ghes_estatus_pool_size_request -= PAGE_ALIGN(len);
975 }
976
977 static void ghes_nmi_add(struct ghes *ghes)
978 {
979         unsigned long len;
980
981         len = ghes_esource_prealloc_size(ghes->generic);
982         ghes_estatus_pool_expand(len);
983         mutex_lock(&ghes_list_mutex);
984         if (list_empty(&ghes_nmi))
985                 register_nmi_handler(NMI_LOCAL, ghes_notify_nmi, 0, "ghes");
986         list_add_rcu(&ghes->list, &ghes_nmi);
987         mutex_unlock(&ghes_list_mutex);
988 }
989
990 static void ghes_nmi_remove(struct ghes *ghes)
991 {
992         unsigned long len;
993
994         mutex_lock(&ghes_list_mutex);
995         list_del_rcu(&ghes->list);
996         if (list_empty(&ghes_nmi))
997                 unregister_nmi_handler(NMI_LOCAL, "ghes");
998         mutex_unlock(&ghes_list_mutex);
999         /*
1000          * To synchronize with NMI handler, ghes can only be
1001          * freed after NMI handler finishes.
1002          */
1003         synchronize_rcu();
1004         len = ghes_esource_prealloc_size(ghes->generic);
1005         ghes_estatus_pool_shrink(len);
1006 }
1007
1008 static void ghes_nmi_init_cxt(void)
1009 {
1010         init_irq_work(&ghes_proc_irq_work, ghes_proc_in_irq);
1011 }
1012 #else /* CONFIG_HAVE_ACPI_APEI_NMI */
1013 static inline void ghes_nmi_add(struct ghes *ghes) { }
1014 static inline void ghes_nmi_remove(struct ghes *ghes) { }
1015 static inline void ghes_nmi_init_cxt(void) { }
1016 #endif /* CONFIG_HAVE_ACPI_APEI_NMI */
1017
1018 static int ghes_probe(struct platform_device *ghes_dev)
1019 {
1020         struct acpi_hest_generic *generic;
1021         struct ghes *ghes = NULL;
1022
1023         int rc = -EINVAL;
1024
1025         generic = *(struct acpi_hest_generic **)ghes_dev->dev.platform_data;
1026         if (!generic->enabled)
1027                 return -ENODEV;
1028
1029         switch (generic->notify.type) {
1030         case ACPI_HEST_NOTIFY_POLLED:
1031         case ACPI_HEST_NOTIFY_EXTERNAL:
1032         case ACPI_HEST_NOTIFY_SCI:
1033         case ACPI_HEST_NOTIFY_GSIV:
1034         case ACPI_HEST_NOTIFY_GPIO:
1035                 break;
1036
1037         case ACPI_HEST_NOTIFY_SEA:
1038                 if (!IS_ENABLED(CONFIG_ACPI_APEI_SEA)) {
1039                         pr_warn(GHES_PFX "Generic hardware error source: %d notified via SEA is not supported\n",
1040                                 generic->header.source_id);
1041                         rc = -ENOTSUPP;
1042                         goto err;
1043                 }
1044                 break;
1045         case ACPI_HEST_NOTIFY_NMI:
1046                 if (!IS_ENABLED(CONFIG_HAVE_ACPI_APEI_NMI)) {
1047                         pr_warn(GHES_PFX "Generic hardware error source: %d notified via NMI interrupt is not supported!\n",
1048                                 generic->header.source_id);
1049                         goto err;
1050                 }
1051                 break;
1052         case ACPI_HEST_NOTIFY_LOCAL:
1053                 pr_warning(GHES_PFX "Generic hardware error source: %d notified via local interrupt is not supported!\n",
1054                            generic->header.source_id);
1055                 goto err;
1056         default:
1057                 pr_warning(FW_WARN GHES_PFX "Unknown notification type: %u for generic hardware error source: %d\n",
1058                            generic->notify.type, generic->header.source_id);
1059                 goto err;
1060         }
1061
1062         rc = -EIO;
1063         if (generic->error_block_length <
1064             sizeof(struct acpi_hest_generic_status)) {
1065                 pr_warning(FW_BUG GHES_PFX "Invalid error block length: %u for generic hardware error source: %d\n",
1066                            generic->error_block_length,
1067                            generic->header.source_id);
1068                 goto err;
1069         }
1070         ghes = ghes_new(generic);
1071         if (IS_ERR(ghes)) {
1072                 rc = PTR_ERR(ghes);
1073                 ghes = NULL;
1074                 goto err;
1075         }
1076
1077         rc = ghes_edac_register(ghes, &ghes_dev->dev);
1078         if (rc < 0)
1079                 goto err;
1080
1081         switch (generic->notify.type) {
1082         case ACPI_HEST_NOTIFY_POLLED:
1083                 setup_deferrable_timer(&ghes->timer, ghes_poll_func,
1084                                        (unsigned long)ghes);
1085                 ghes_add_timer(ghes);
1086                 break;
1087         case ACPI_HEST_NOTIFY_EXTERNAL:
1088                 /* External interrupt vector is GSI */
1089                 rc = acpi_gsi_to_irq(generic->notify.vector, &ghes->irq);
1090                 if (rc) {
1091                         pr_err(GHES_PFX "Failed to map GSI to IRQ for generic hardware error source: %d\n",
1092                                generic->header.source_id);
1093                         goto err_edac_unreg;
1094                 }
1095                 rc = request_irq(ghes->irq, ghes_irq_func, IRQF_SHARED,
1096                                  "GHES IRQ", ghes);
1097                 if (rc) {
1098                         pr_err(GHES_PFX "Failed to register IRQ for generic hardware error source: %d\n",
1099                                generic->header.source_id);
1100                         goto err_edac_unreg;
1101                 }
1102                 break;
1103
1104         case ACPI_HEST_NOTIFY_SCI:
1105         case ACPI_HEST_NOTIFY_GSIV:
1106         case ACPI_HEST_NOTIFY_GPIO:
1107                 mutex_lock(&ghes_list_mutex);
1108                 if (list_empty(&ghes_hed))
1109                         register_acpi_hed_notifier(&ghes_notifier_hed);
1110                 list_add_rcu(&ghes->list, &ghes_hed);
1111                 mutex_unlock(&ghes_list_mutex);
1112                 break;
1113
1114         case ACPI_HEST_NOTIFY_SEA:
1115                 ghes_sea_add(ghes);
1116                 break;
1117         case ACPI_HEST_NOTIFY_NMI:
1118                 ghes_nmi_add(ghes);
1119                 break;
1120         default:
1121                 BUG();
1122         }
1123         platform_set_drvdata(ghes_dev, ghes);
1124
1125         /* Handle any pending errors right away */
1126         ghes_proc(ghes);
1127
1128         return 0;
1129 err_edac_unreg:
1130         ghes_edac_unregister(ghes);
1131 err:
1132         if (ghes) {
1133                 ghes_fini(ghes);
1134                 kfree(ghes);
1135         }
1136         return rc;
1137 }
1138
1139 static int ghes_remove(struct platform_device *ghes_dev)
1140 {
1141         struct ghes *ghes;
1142         struct acpi_hest_generic *generic;
1143
1144         ghes = platform_get_drvdata(ghes_dev);
1145         generic = ghes->generic;
1146
1147         ghes->flags |= GHES_EXITING;
1148         switch (generic->notify.type) {
1149         case ACPI_HEST_NOTIFY_POLLED:
1150                 del_timer_sync(&ghes->timer);
1151                 break;
1152         case ACPI_HEST_NOTIFY_EXTERNAL:
1153                 free_irq(ghes->irq, ghes);
1154                 break;
1155
1156         case ACPI_HEST_NOTIFY_SCI:
1157         case ACPI_HEST_NOTIFY_GSIV:
1158         case ACPI_HEST_NOTIFY_GPIO:
1159                 mutex_lock(&ghes_list_mutex);
1160                 list_del_rcu(&ghes->list);
1161                 if (list_empty(&ghes_hed))
1162                         unregister_acpi_hed_notifier(&ghes_notifier_hed);
1163                 mutex_unlock(&ghes_list_mutex);
1164                 synchronize_rcu();
1165                 break;
1166
1167         case ACPI_HEST_NOTIFY_SEA:
1168                 ghes_sea_remove(ghes);
1169                 break;
1170         case ACPI_HEST_NOTIFY_NMI:
1171                 ghes_nmi_remove(ghes);
1172                 break;
1173         default:
1174                 BUG();
1175                 break;
1176         }
1177
1178         ghes_fini(ghes);
1179
1180         ghes_edac_unregister(ghes);
1181
1182         kfree(ghes);
1183
1184         platform_set_drvdata(ghes_dev, NULL);
1185
1186         return 0;
1187 }
1188
1189 static struct platform_driver ghes_platform_driver = {
1190         .driver         = {
1191                 .name   = "GHES",
1192         },
1193         .probe          = ghes_probe,
1194         .remove         = ghes_remove,
1195 };
1196
1197 static int __init ghes_init(void)
1198 {
1199         int rc;
1200
1201         if (acpi_disabled)
1202                 return -ENODEV;
1203
1204         switch (hest_disable) {
1205         case HEST_NOT_FOUND:
1206                 return -ENODEV;
1207         case HEST_DISABLED:
1208                 pr_info(GHES_PFX "HEST is not enabled!\n");
1209                 return -EINVAL;
1210         default:
1211                 break;
1212         }
1213
1214         if (ghes_disable) {
1215                 pr_info(GHES_PFX "GHES is not enabled!\n");
1216                 return -EINVAL;
1217         }
1218
1219         ghes_nmi_init_cxt();
1220
1221         rc = ghes_estatus_pool_init();
1222         if (rc)
1223                 goto err;
1224
1225         rc = ghes_estatus_pool_expand(GHES_ESTATUS_CACHE_AVG_SIZE *
1226                                       GHES_ESTATUS_CACHE_ALLOCED_MAX);
1227         if (rc)
1228                 goto err_pool_exit;
1229
1230         rc = platform_driver_register(&ghes_platform_driver);
1231         if (rc)
1232                 goto err_pool_exit;
1233
1234         rc = apei_osc_setup();
1235         if (rc == 0 && osc_sb_apei_support_acked)
1236                 pr_info(GHES_PFX "APEI firmware first mode is enabled by APEI bit and WHEA _OSC.\n");
1237         else if (rc == 0 && !osc_sb_apei_support_acked)
1238                 pr_info(GHES_PFX "APEI firmware first mode is enabled by WHEA _OSC.\n");
1239         else if (rc && osc_sb_apei_support_acked)
1240                 pr_info(GHES_PFX "APEI firmware first mode is enabled by APEI bit.\n");
1241         else
1242                 pr_info(GHES_PFX "Failed to enable APEI firmware first mode.\n");
1243
1244         return 0;
1245 err_pool_exit:
1246         ghes_estatus_pool_exit();
1247 err:
1248         return rc;
1249 }
1250 device_initcall(ghes_init);