mce: acpi/apei: Soft-offline a page on firmware GHES notification
[linux-2.6-block.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  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30  */
31
32 #include <linux/kernel.h>
33 #include <linux/module.h>
34 #include <linux/init.h>
35 #include <linux/acpi.h>
36 #include <linux/acpi_io.h>
37 #include <linux/io.h>
38 #include <linux/interrupt.h>
39 #include <linux/timer.h>
40 #include <linux/cper.h>
41 #include <linux/kdebug.h>
42 #include <linux/platform_device.h>
43 #include <linux/mutex.h>
44 #include <linux/ratelimit.h>
45 #include <linux/vmalloc.h>
46 #include <linux/irq_work.h>
47 #include <linux/llist.h>
48 #include <linux/genalloc.h>
49 #include <linux/pci.h>
50 #include <linux/aer.h>
51
52 #include <acpi/ghes.h>
53 #include <asm/mce.h>
54 #include <asm/tlbflush.h>
55 #include <asm/nmi.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 bool ghes_disable;
88 module_param_named(disable, ghes_disable, bool, 0);
89
90 static int ghes_panic_timeout   __read_mostly = 30;
91
92 /*
93  * All error sources notified with SCI shares one notifier function,
94  * so they need to be linked and checked one by one.  This is applied
95  * to NMI too.
96  *
97  * RCU is used for these lists, so ghes_list_mutex is only used for
98  * list changing, not for traversing.
99  */
100 static LIST_HEAD(ghes_sci);
101 static LIST_HEAD(ghes_nmi);
102 static DEFINE_MUTEX(ghes_list_mutex);
103
104 /*
105  * NMI may be triggered on any CPU, so ghes_nmi_lock is used for
106  * mutual exclusion.
107  */
108 static DEFINE_RAW_SPINLOCK(ghes_nmi_lock);
109
110 /*
111  * Because the memory area used to transfer hardware error information
112  * from BIOS to Linux can be determined only in NMI, IRQ or timer
113  * handler, but general ioremap can not be used in atomic context, so
114  * a special version of atomic ioremap is implemented for that.
115  */
116
117 /*
118  * Two virtual pages are used, one for NMI context, the other for
119  * IRQ/PROCESS context
120  */
121 #define GHES_IOREMAP_PAGES              2
122 #define GHES_IOREMAP_NMI_PAGE(base)     (base)
123 #define GHES_IOREMAP_IRQ_PAGE(base)     ((base) + PAGE_SIZE)
124
125 /* virtual memory area for atomic ioremap */
126 static struct vm_struct *ghes_ioremap_area;
127 /*
128  * These 2 spinlock is used to prevent atomic ioremap virtual memory
129  * area from being mapped simultaneously.
130  */
131 static DEFINE_RAW_SPINLOCK(ghes_ioremap_lock_nmi);
132 static DEFINE_SPINLOCK(ghes_ioremap_lock_irq);
133
134 /*
135  * printk is not safe in NMI context.  So in NMI handler, we allocate
136  * required memory from lock-less memory allocator
137  * (ghes_estatus_pool), save estatus into it, put them into lock-less
138  * list (ghes_estatus_llist), then delay printk into IRQ context via
139  * irq_work (ghes_proc_irq_work).  ghes_estatus_size_request record
140  * required pool size by all NMI error source.
141  */
142 static struct gen_pool *ghes_estatus_pool;
143 static unsigned long ghes_estatus_pool_size_request;
144 static struct llist_head ghes_estatus_llist;
145 static struct irq_work ghes_proc_irq_work;
146
147 struct ghes_estatus_cache *ghes_estatus_caches[GHES_ESTATUS_CACHES_SIZE];
148 static atomic_t ghes_estatus_cache_alloced;
149
150 static int ghes_ioremap_init(void)
151 {
152         ghes_ioremap_area = __get_vm_area(PAGE_SIZE * GHES_IOREMAP_PAGES,
153                 VM_IOREMAP, VMALLOC_START, VMALLOC_END);
154         if (!ghes_ioremap_area) {
155                 pr_err(GHES_PFX "Failed to allocate virtual memory area for atomic ioremap.\n");
156                 return -ENOMEM;
157         }
158
159         return 0;
160 }
161
162 static void ghes_ioremap_exit(void)
163 {
164         free_vm_area(ghes_ioremap_area);
165 }
166
167 static void __iomem *ghes_ioremap_pfn_nmi(u64 pfn)
168 {
169         unsigned long vaddr;
170
171         vaddr = (unsigned long)GHES_IOREMAP_NMI_PAGE(ghes_ioremap_area->addr);
172         ioremap_page_range(vaddr, vaddr + PAGE_SIZE,
173                            pfn << PAGE_SHIFT, PAGE_KERNEL);
174
175         return (void __iomem *)vaddr;
176 }
177
178 static void __iomem *ghes_ioremap_pfn_irq(u64 pfn)
179 {
180         unsigned long vaddr;
181
182         vaddr = (unsigned long)GHES_IOREMAP_IRQ_PAGE(ghes_ioremap_area->addr);
183         ioremap_page_range(vaddr, vaddr + PAGE_SIZE,
184                            pfn << PAGE_SHIFT, PAGE_KERNEL);
185
186         return (void __iomem *)vaddr;
187 }
188
189 static void ghes_iounmap_nmi(void __iomem *vaddr_ptr)
190 {
191         unsigned long vaddr = (unsigned long __force)vaddr_ptr;
192         void *base = ghes_ioremap_area->addr;
193
194         BUG_ON(vaddr != (unsigned long)GHES_IOREMAP_NMI_PAGE(base));
195         unmap_kernel_range_noflush(vaddr, PAGE_SIZE);
196         __flush_tlb_one(vaddr);
197 }
198
199 static void ghes_iounmap_irq(void __iomem *vaddr_ptr)
200 {
201         unsigned long vaddr = (unsigned long __force)vaddr_ptr;
202         void *base = ghes_ioremap_area->addr;
203
204         BUG_ON(vaddr != (unsigned long)GHES_IOREMAP_IRQ_PAGE(base));
205         unmap_kernel_range_noflush(vaddr, PAGE_SIZE);
206         __flush_tlb_one(vaddr);
207 }
208
209 static int ghes_estatus_pool_init(void)
210 {
211         ghes_estatus_pool = gen_pool_create(GHES_ESTATUS_POOL_MIN_ALLOC_ORDER, -1);
212         if (!ghes_estatus_pool)
213                 return -ENOMEM;
214         return 0;
215 }
216
217 static void ghes_estatus_pool_free_chunk_page(struct gen_pool *pool,
218                                               struct gen_pool_chunk *chunk,
219                                               void *data)
220 {
221         free_page(chunk->start_addr);
222 }
223
224 static void ghes_estatus_pool_exit(void)
225 {
226         gen_pool_for_each_chunk(ghes_estatus_pool,
227                                 ghes_estatus_pool_free_chunk_page, NULL);
228         gen_pool_destroy(ghes_estatus_pool);
229 }
230
231 static int ghes_estatus_pool_expand(unsigned long len)
232 {
233         unsigned long i, pages, size, addr;
234         int ret;
235
236         ghes_estatus_pool_size_request += PAGE_ALIGN(len);
237         size = gen_pool_size(ghes_estatus_pool);
238         if (size >= ghes_estatus_pool_size_request)
239                 return 0;
240         pages = (ghes_estatus_pool_size_request - size) / PAGE_SIZE;
241         for (i = 0; i < pages; i++) {
242                 addr = __get_free_page(GFP_KERNEL);
243                 if (!addr)
244                         return -ENOMEM;
245                 ret = gen_pool_add(ghes_estatus_pool, addr, PAGE_SIZE, -1);
246                 if (ret)
247                         return ret;
248         }
249
250         return 0;
251 }
252
253 static void ghes_estatus_pool_shrink(unsigned long len)
254 {
255         ghes_estatus_pool_size_request -= PAGE_ALIGN(len);
256 }
257
258 static struct ghes *ghes_new(struct acpi_hest_generic *generic)
259 {
260         struct ghes *ghes;
261         unsigned int error_block_length;
262         int rc;
263
264         ghes = kzalloc(sizeof(*ghes), GFP_KERNEL);
265         if (!ghes)
266                 return ERR_PTR(-ENOMEM);
267         ghes->generic = generic;
268         rc = apei_map_generic_address(&generic->error_status_address);
269         if (rc)
270                 goto err_free;
271         error_block_length = generic->error_block_length;
272         if (error_block_length > GHES_ESTATUS_MAX_SIZE) {
273                 pr_warning(FW_WARN GHES_PFX
274                            "Error status block length is too long: %u for "
275                            "generic hardware error source: %d.\n",
276                            error_block_length, generic->header.source_id);
277                 error_block_length = GHES_ESTATUS_MAX_SIZE;
278         }
279         ghes->estatus = kmalloc(error_block_length, GFP_KERNEL);
280         if (!ghes->estatus) {
281                 rc = -ENOMEM;
282                 goto err_unmap;
283         }
284
285         return ghes;
286
287 err_unmap:
288         apei_unmap_generic_address(&generic->error_status_address);
289 err_free:
290         kfree(ghes);
291         return ERR_PTR(rc);
292 }
293
294 static void ghes_fini(struct ghes *ghes)
295 {
296         kfree(ghes->estatus);
297         apei_unmap_generic_address(&ghes->generic->error_status_address);
298 }
299
300 static inline int ghes_severity(int severity)
301 {
302         switch (severity) {
303         case CPER_SEV_INFORMATIONAL:
304                 return GHES_SEV_NO;
305         case CPER_SEV_CORRECTED:
306                 return GHES_SEV_CORRECTED;
307         case CPER_SEV_RECOVERABLE:
308                 return GHES_SEV_RECOVERABLE;
309         case CPER_SEV_FATAL:
310                 return GHES_SEV_PANIC;
311         default:
312                 /* Unknown, go panic */
313                 return GHES_SEV_PANIC;
314         }
315 }
316
317 static void ghes_copy_tofrom_phys(void *buffer, u64 paddr, u32 len,
318                                   int from_phys)
319 {
320         void __iomem *vaddr;
321         unsigned long flags = 0;
322         int in_nmi = in_nmi();
323         u64 offset;
324         u32 trunk;
325
326         while (len > 0) {
327                 offset = paddr - (paddr & PAGE_MASK);
328                 if (in_nmi) {
329                         raw_spin_lock(&ghes_ioremap_lock_nmi);
330                         vaddr = ghes_ioremap_pfn_nmi(paddr >> PAGE_SHIFT);
331                 } else {
332                         spin_lock_irqsave(&ghes_ioremap_lock_irq, flags);
333                         vaddr = ghes_ioremap_pfn_irq(paddr >> PAGE_SHIFT);
334                 }
335                 trunk = PAGE_SIZE - offset;
336                 trunk = min(trunk, len);
337                 if (from_phys)
338                         memcpy_fromio(buffer, vaddr + offset, trunk);
339                 else
340                         memcpy_toio(vaddr + offset, buffer, trunk);
341                 len -= trunk;
342                 paddr += trunk;
343                 buffer += trunk;
344                 if (in_nmi) {
345                         ghes_iounmap_nmi(vaddr);
346                         raw_spin_unlock(&ghes_ioremap_lock_nmi);
347                 } else {
348                         ghes_iounmap_irq(vaddr);
349                         spin_unlock_irqrestore(&ghes_ioremap_lock_irq, flags);
350                 }
351         }
352 }
353
354 static int ghes_read_estatus(struct ghes *ghes, int silent)
355 {
356         struct acpi_hest_generic *g = ghes->generic;
357         u64 buf_paddr;
358         u32 len;
359         int rc;
360
361         rc = apei_read(&buf_paddr, &g->error_status_address);
362         if (rc) {
363                 if (!silent && printk_ratelimit())
364                         pr_warning(FW_WARN GHES_PFX
365 "Failed to read error status block address for hardware error source: %d.\n",
366                                    g->header.source_id);
367                 return -EIO;
368         }
369         if (!buf_paddr)
370                 return -ENOENT;
371
372         ghes_copy_tofrom_phys(ghes->estatus, buf_paddr,
373                               sizeof(*ghes->estatus), 1);
374         if (!ghes->estatus->block_status)
375                 return -ENOENT;
376
377         ghes->buffer_paddr = buf_paddr;
378         ghes->flags |= GHES_TO_CLEAR;
379
380         rc = -EIO;
381         len = apei_estatus_len(ghes->estatus);
382         if (len < sizeof(*ghes->estatus))
383                 goto err_read_block;
384         if (len > ghes->generic->error_block_length)
385                 goto err_read_block;
386         if (apei_estatus_check_header(ghes->estatus))
387                 goto err_read_block;
388         ghes_copy_tofrom_phys(ghes->estatus + 1,
389                               buf_paddr + sizeof(*ghes->estatus),
390                               len - sizeof(*ghes->estatus), 1);
391         if (apei_estatus_check(ghes->estatus))
392                 goto err_read_block;
393         rc = 0;
394
395 err_read_block:
396         if (rc && !silent && printk_ratelimit())
397                 pr_warning(FW_WARN GHES_PFX
398                            "Failed to read error status block!\n");
399         return rc;
400 }
401
402 static void ghes_clear_estatus(struct ghes *ghes)
403 {
404         ghes->estatus->block_status = 0;
405         if (!(ghes->flags & GHES_TO_CLEAR))
406                 return;
407         ghes_copy_tofrom_phys(ghes->estatus, ghes->buffer_paddr,
408                               sizeof(ghes->estatus->block_status), 0);
409         ghes->flags &= ~GHES_TO_CLEAR;
410 }
411
412 static void ghes_handle_memory_failure(struct acpi_hest_generic_data *gdata, int sev)
413 {
414 #ifdef CONFIG_ACPI_APEI_MEMORY_FAILURE
415         unsigned long pfn;
416         int sec_sev = ghes_severity(gdata->error_severity);
417         struct cper_sec_mem_err *mem_err;
418         mem_err = (struct cper_sec_mem_err *)(gdata + 1);
419
420         if (sec_sev == GHES_SEV_CORRECTED &&
421             (gdata->flags & CPER_SEC_ERROR_THRESHOLD_EXCEEDED) &&
422             (mem_err->validation_bits & CPER_MEM_VALID_PHYSICAL_ADDRESS)) {
423                 pfn = mem_err->physical_addr >> PAGE_SHIFT;
424                 if (pfn_valid(pfn))
425                         memory_failure_queue(pfn, 0, MF_SOFT_OFFLINE);
426                 else if (printk_ratelimit())
427                         pr_warn(FW_WARN GHES_PFX
428                         "Invalid address in generic error data: %#llx\n",
429                         mem_err->physical_addr);
430         }
431         if (sev == GHES_SEV_RECOVERABLE &&
432             sec_sev == GHES_SEV_RECOVERABLE &&
433             mem_err->validation_bits & CPER_MEM_VALID_PHYSICAL_ADDRESS) {
434                 pfn = mem_err->physical_addr >> PAGE_SHIFT;
435                 memory_failure_queue(pfn, 0, 0);
436         }
437 #endif
438 }
439
440 static void ghes_do_proc(struct ghes *ghes,
441                          const struct acpi_hest_generic_status *estatus)
442 {
443         int sev, sec_sev;
444         struct acpi_hest_generic_data *gdata;
445
446         sev = ghes_severity(estatus->error_severity);
447         apei_estatus_for_each_section(estatus, gdata) {
448                 sec_sev = ghes_severity(gdata->error_severity);
449                 if (!uuid_le_cmp(*(uuid_le *)gdata->section_type,
450                                  CPER_SEC_PLATFORM_MEM)) {
451                         struct cper_sec_mem_err *mem_err;
452                         mem_err = (struct cper_sec_mem_err *)(gdata+1);
453                         ghes_edac_report_mem_error(ghes, sev, mem_err);
454
455 #ifdef CONFIG_X86_MCE
456                         apei_mce_report_mem_error(sev == GHES_SEV_CORRECTED,
457                                                   mem_err);
458 #endif
459                         ghes_handle_memory_failure(gdata, sev);
460                 }
461 #ifdef CONFIG_ACPI_APEI_PCIEAER
462                 else if (!uuid_le_cmp(*(uuid_le *)gdata->section_type,
463                                       CPER_SEC_PCIE)) {
464                         struct cper_sec_pcie *pcie_err;
465                         pcie_err = (struct cper_sec_pcie *)(gdata+1);
466                         if (sev == GHES_SEV_RECOVERABLE &&
467                             sec_sev == GHES_SEV_RECOVERABLE &&
468                             pcie_err->validation_bits & CPER_PCIE_VALID_DEVICE_ID &&
469                             pcie_err->validation_bits & CPER_PCIE_VALID_AER_INFO) {
470                                 unsigned int devfn;
471                                 int aer_severity;
472                                 devfn = PCI_DEVFN(pcie_err->device_id.device,
473                                                   pcie_err->device_id.function);
474                                 aer_severity = cper_severity_to_aer(sev);
475                                 aer_recover_queue(pcie_err->device_id.segment,
476                                                   pcie_err->device_id.bus,
477                                                   devfn, aer_severity,
478                                                   (struct aer_capability_regs *)
479                                                   pcie_err->aer_info);
480                         }
481
482                 }
483 #endif
484         }
485 }
486
487 static void __ghes_print_estatus(const char *pfx,
488                                  const struct acpi_hest_generic *generic,
489                                  const struct acpi_hest_generic_status *estatus)
490 {
491         static atomic_t seqno;
492         unsigned int curr_seqno;
493         char pfx_seq[64];
494
495         if (pfx == NULL) {
496                 if (ghes_severity(estatus->error_severity) <=
497                     GHES_SEV_CORRECTED)
498                         pfx = KERN_WARNING;
499                 else
500                         pfx = KERN_ERR;
501         }
502         curr_seqno = atomic_inc_return(&seqno);
503         snprintf(pfx_seq, sizeof(pfx_seq), "%s{%u}" HW_ERR, pfx, curr_seqno);
504         printk("%s""Hardware error from APEI Generic Hardware Error Source: %d\n",
505                pfx_seq, generic->header.source_id);
506         apei_estatus_print(pfx_seq, estatus);
507 }
508
509 static int ghes_print_estatus(const char *pfx,
510                               const struct acpi_hest_generic *generic,
511                               const struct acpi_hest_generic_status *estatus)
512 {
513         /* Not more than 2 messages every 5 seconds */
514         static DEFINE_RATELIMIT_STATE(ratelimit_corrected, 5*HZ, 2);
515         static DEFINE_RATELIMIT_STATE(ratelimit_uncorrected, 5*HZ, 2);
516         struct ratelimit_state *ratelimit;
517
518         if (ghes_severity(estatus->error_severity) <= GHES_SEV_CORRECTED)
519                 ratelimit = &ratelimit_corrected;
520         else
521                 ratelimit = &ratelimit_uncorrected;
522         if (__ratelimit(ratelimit)) {
523                 __ghes_print_estatus(pfx, generic, estatus);
524                 return 1;
525         }
526         return 0;
527 }
528
529 /*
530  * GHES error status reporting throttle, to report more kinds of
531  * errors, instead of just most frequently occurred errors.
532  */
533 static int ghes_estatus_cached(struct acpi_hest_generic_status *estatus)
534 {
535         u32 len;
536         int i, cached = 0;
537         unsigned long long now;
538         struct ghes_estatus_cache *cache;
539         struct acpi_hest_generic_status *cache_estatus;
540
541         len = apei_estatus_len(estatus);
542         rcu_read_lock();
543         for (i = 0; i < GHES_ESTATUS_CACHES_SIZE; i++) {
544                 cache = rcu_dereference(ghes_estatus_caches[i]);
545                 if (cache == NULL)
546                         continue;
547                 if (len != cache->estatus_len)
548                         continue;
549                 cache_estatus = GHES_ESTATUS_FROM_CACHE(cache);
550                 if (memcmp(estatus, cache_estatus, len))
551                         continue;
552                 atomic_inc(&cache->count);
553                 now = sched_clock();
554                 if (now - cache->time_in < GHES_ESTATUS_IN_CACHE_MAX_NSEC)
555                         cached = 1;
556                 break;
557         }
558         rcu_read_unlock();
559         return cached;
560 }
561
562 static struct ghes_estatus_cache *ghes_estatus_cache_alloc(
563         struct acpi_hest_generic *generic,
564         struct acpi_hest_generic_status *estatus)
565 {
566         int alloced;
567         u32 len, cache_len;
568         struct ghes_estatus_cache *cache;
569         struct acpi_hest_generic_status *cache_estatus;
570
571         alloced = atomic_add_return(1, &ghes_estatus_cache_alloced);
572         if (alloced > GHES_ESTATUS_CACHE_ALLOCED_MAX) {
573                 atomic_dec(&ghes_estatus_cache_alloced);
574                 return NULL;
575         }
576         len = apei_estatus_len(estatus);
577         cache_len = GHES_ESTATUS_CACHE_LEN(len);
578         cache = (void *)gen_pool_alloc(ghes_estatus_pool, cache_len);
579         if (!cache) {
580                 atomic_dec(&ghes_estatus_cache_alloced);
581                 return NULL;
582         }
583         cache_estatus = GHES_ESTATUS_FROM_CACHE(cache);
584         memcpy(cache_estatus, estatus, len);
585         cache->estatus_len = len;
586         atomic_set(&cache->count, 0);
587         cache->generic = generic;
588         cache->time_in = sched_clock();
589         return cache;
590 }
591
592 static void ghes_estatus_cache_free(struct ghes_estatus_cache *cache)
593 {
594         u32 len;
595
596         len = apei_estatus_len(GHES_ESTATUS_FROM_CACHE(cache));
597         len = GHES_ESTATUS_CACHE_LEN(len);
598         gen_pool_free(ghes_estatus_pool, (unsigned long)cache, len);
599         atomic_dec(&ghes_estatus_cache_alloced);
600 }
601
602 static void ghes_estatus_cache_rcu_free(struct rcu_head *head)
603 {
604         struct ghes_estatus_cache *cache;
605
606         cache = container_of(head, struct ghes_estatus_cache, rcu);
607         ghes_estatus_cache_free(cache);
608 }
609
610 static void ghes_estatus_cache_add(
611         struct acpi_hest_generic *generic,
612         struct acpi_hest_generic_status *estatus)
613 {
614         int i, slot = -1, count;
615         unsigned long long now, duration, period, max_period = 0;
616         struct ghes_estatus_cache *cache, *slot_cache = NULL, *new_cache;
617
618         new_cache = ghes_estatus_cache_alloc(generic, estatus);
619         if (new_cache == NULL)
620                 return;
621         rcu_read_lock();
622         now = sched_clock();
623         for (i = 0; i < GHES_ESTATUS_CACHES_SIZE; i++) {
624                 cache = rcu_dereference(ghes_estatus_caches[i]);
625                 if (cache == NULL) {
626                         slot = i;
627                         slot_cache = NULL;
628                         break;
629                 }
630                 duration = now - cache->time_in;
631                 if (duration >= GHES_ESTATUS_IN_CACHE_MAX_NSEC) {
632                         slot = i;
633                         slot_cache = cache;
634                         break;
635                 }
636                 count = atomic_read(&cache->count);
637                 period = duration;
638                 do_div(period, (count + 1));
639                 if (period > max_period) {
640                         max_period = period;
641                         slot = i;
642                         slot_cache = cache;
643                 }
644         }
645         /* new_cache must be put into array after its contents are written */
646         smp_wmb();
647         if (slot != -1 && cmpxchg(ghes_estatus_caches + slot,
648                                   slot_cache, new_cache) == slot_cache) {
649                 if (slot_cache)
650                         call_rcu(&slot_cache->rcu, ghes_estatus_cache_rcu_free);
651         } else
652                 ghes_estatus_cache_free(new_cache);
653         rcu_read_unlock();
654 }
655
656 static int ghes_proc(struct ghes *ghes)
657 {
658         int rc;
659
660         rc = ghes_read_estatus(ghes, 0);
661         if (rc)
662                 goto out;
663         if (!ghes_estatus_cached(ghes->estatus)) {
664                 if (ghes_print_estatus(NULL, ghes->generic, ghes->estatus))
665                         ghes_estatus_cache_add(ghes->generic, ghes->estatus);
666         }
667         ghes_do_proc(ghes, ghes->estatus);
668 out:
669         ghes_clear_estatus(ghes);
670         return 0;
671 }
672
673 static void ghes_add_timer(struct ghes *ghes)
674 {
675         struct acpi_hest_generic *g = ghes->generic;
676         unsigned long expire;
677
678         if (!g->notify.poll_interval) {
679                 pr_warning(FW_WARN GHES_PFX "Poll interval is 0 for generic hardware error source: %d, disabled.\n",
680                            g->header.source_id);
681                 return;
682         }
683         expire = jiffies + msecs_to_jiffies(g->notify.poll_interval);
684         ghes->timer.expires = round_jiffies_relative(expire);
685         add_timer(&ghes->timer);
686 }
687
688 static void ghes_poll_func(unsigned long data)
689 {
690         struct ghes *ghes = (void *)data;
691
692         ghes_proc(ghes);
693         if (!(ghes->flags & GHES_EXITING))
694                 ghes_add_timer(ghes);
695 }
696
697 static irqreturn_t ghes_irq_func(int irq, void *data)
698 {
699         struct ghes *ghes = data;
700         int rc;
701
702         rc = ghes_proc(ghes);
703         if (rc)
704                 return IRQ_NONE;
705
706         return IRQ_HANDLED;
707 }
708
709 static int ghes_notify_sci(struct notifier_block *this,
710                                   unsigned long event, void *data)
711 {
712         struct ghes *ghes;
713         int ret = NOTIFY_DONE;
714
715         rcu_read_lock();
716         list_for_each_entry_rcu(ghes, &ghes_sci, list) {
717                 if (!ghes_proc(ghes))
718                         ret = NOTIFY_OK;
719         }
720         rcu_read_unlock();
721
722         return ret;
723 }
724
725 static struct llist_node *llist_nodes_reverse(struct llist_node *llnode)
726 {
727         struct llist_node *next, *tail = NULL;
728
729         while (llnode) {
730                 next = llnode->next;
731                 llnode->next = tail;
732                 tail = llnode;
733                 llnode = next;
734         }
735
736         return tail;
737 }
738
739 static void ghes_proc_in_irq(struct irq_work *irq_work)
740 {
741         struct llist_node *llnode, *next;
742         struct ghes_estatus_node *estatus_node;
743         struct acpi_hest_generic *generic;
744         struct acpi_hest_generic_status *estatus;
745         u32 len, node_len;
746
747         llnode = llist_del_all(&ghes_estatus_llist);
748         /*
749          * Because the time order of estatus in list is reversed,
750          * revert it back to proper order.
751          */
752         llnode = llist_nodes_reverse(llnode);
753         while (llnode) {
754                 next = llnode->next;
755                 estatus_node = llist_entry(llnode, struct ghes_estatus_node,
756                                            llnode);
757                 estatus = GHES_ESTATUS_FROM_NODE(estatus_node);
758                 len = apei_estatus_len(estatus);
759                 node_len = GHES_ESTATUS_NODE_LEN(len);
760                 ghes_do_proc(estatus_node->ghes, estatus);
761                 if (!ghes_estatus_cached(estatus)) {
762                         generic = estatus_node->generic;
763                         if (ghes_print_estatus(NULL, generic, estatus))
764                                 ghes_estatus_cache_add(generic, estatus);
765                 }
766                 gen_pool_free(ghes_estatus_pool, (unsigned long)estatus_node,
767                               node_len);
768                 llnode = next;
769         }
770 }
771
772 static void ghes_print_queued_estatus(void)
773 {
774         struct llist_node *llnode;
775         struct ghes_estatus_node *estatus_node;
776         struct acpi_hest_generic *generic;
777         struct acpi_hest_generic_status *estatus;
778         u32 len, node_len;
779
780         llnode = llist_del_all(&ghes_estatus_llist);
781         /*
782          * Because the time order of estatus in list is reversed,
783          * revert it back to proper order.
784          */
785         llnode = llist_nodes_reverse(llnode);
786         while (llnode) {
787                 estatus_node = llist_entry(llnode, struct ghes_estatus_node,
788                                            llnode);
789                 estatus = GHES_ESTATUS_FROM_NODE(estatus_node);
790                 len = apei_estatus_len(estatus);
791                 node_len = GHES_ESTATUS_NODE_LEN(len);
792                 generic = estatus_node->generic;
793                 ghes_print_estatus(NULL, generic, estatus);
794                 llnode = llnode->next;
795         }
796 }
797
798 static int ghes_notify_nmi(unsigned int cmd, struct pt_regs *regs)
799 {
800         struct ghes *ghes, *ghes_global = NULL;
801         int sev, sev_global = -1;
802         int ret = NMI_DONE;
803
804         raw_spin_lock(&ghes_nmi_lock);
805         list_for_each_entry_rcu(ghes, &ghes_nmi, list) {
806                 if (ghes_read_estatus(ghes, 1)) {
807                         ghes_clear_estatus(ghes);
808                         continue;
809                 }
810                 sev = ghes_severity(ghes->estatus->error_severity);
811                 if (sev > sev_global) {
812                         sev_global = sev;
813                         ghes_global = ghes;
814                 }
815                 ret = NMI_HANDLED;
816         }
817
818         if (ret == NMI_DONE)
819                 goto out;
820
821         if (sev_global >= GHES_SEV_PANIC) {
822                 oops_begin();
823                 ghes_print_queued_estatus();
824                 __ghes_print_estatus(KERN_EMERG, ghes_global->generic,
825                                      ghes_global->estatus);
826                 /* reboot to log the error! */
827                 if (panic_timeout == 0)
828                         panic_timeout = ghes_panic_timeout;
829                 panic("Fatal hardware error!");
830         }
831
832         list_for_each_entry_rcu(ghes, &ghes_nmi, list) {
833 #ifdef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
834                 u32 len, node_len;
835                 struct ghes_estatus_node *estatus_node;
836                 struct acpi_hest_generic_status *estatus;
837 #endif
838                 if (!(ghes->flags & GHES_TO_CLEAR))
839                         continue;
840 #ifdef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
841                 if (ghes_estatus_cached(ghes->estatus))
842                         goto next;
843                 /* Save estatus for further processing in IRQ context */
844                 len = apei_estatus_len(ghes->estatus);
845                 node_len = GHES_ESTATUS_NODE_LEN(len);
846                 estatus_node = (void *)gen_pool_alloc(ghes_estatus_pool,
847                                                       node_len);
848                 if (estatus_node) {
849                         estatus_node->ghes = ghes;
850                         estatus_node->generic = ghes->generic;
851                         estatus = GHES_ESTATUS_FROM_NODE(estatus_node);
852                         memcpy(estatus, ghes->estatus, len);
853                         llist_add(&estatus_node->llnode, &ghes_estatus_llist);
854                 }
855 next:
856 #endif
857                 ghes_clear_estatus(ghes);
858         }
859 #ifdef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
860         irq_work_queue(&ghes_proc_irq_work);
861 #endif
862
863 out:
864         raw_spin_unlock(&ghes_nmi_lock);
865         return ret;
866 }
867
868 static struct notifier_block ghes_notifier_sci = {
869         .notifier_call = ghes_notify_sci,
870 };
871
872 static unsigned long ghes_esource_prealloc_size(
873         const struct acpi_hest_generic *generic)
874 {
875         unsigned long block_length, prealloc_records, prealloc_size;
876
877         block_length = min_t(unsigned long, generic->error_block_length,
878                              GHES_ESTATUS_MAX_SIZE);
879         prealloc_records = max_t(unsigned long,
880                                  generic->records_to_preallocate, 1);
881         prealloc_size = min_t(unsigned long, block_length * prealloc_records,
882                               GHES_ESOURCE_PREALLOC_MAX_SIZE);
883
884         return prealloc_size;
885 }
886
887 static int ghes_probe(struct platform_device *ghes_dev)
888 {
889         struct acpi_hest_generic *generic;
890         struct ghes *ghes = NULL;
891         unsigned long len;
892         int rc = -EINVAL;
893
894         generic = *(struct acpi_hest_generic **)ghes_dev->dev.platform_data;
895         if (!generic->enabled)
896                 return -ENODEV;
897
898         switch (generic->notify.type) {
899         case ACPI_HEST_NOTIFY_POLLED:
900         case ACPI_HEST_NOTIFY_EXTERNAL:
901         case ACPI_HEST_NOTIFY_SCI:
902         case ACPI_HEST_NOTIFY_NMI:
903                 break;
904         case ACPI_HEST_NOTIFY_LOCAL:
905                 pr_warning(GHES_PFX "Generic hardware error source: %d notified via local interrupt is not supported!\n",
906                            generic->header.source_id);
907                 goto err;
908         default:
909                 pr_warning(FW_WARN GHES_PFX "Unknown notification type: %u for generic hardware error source: %d\n",
910                            generic->notify.type, generic->header.source_id);
911                 goto err;
912         }
913
914         rc = -EIO;
915         if (generic->error_block_length <
916             sizeof(struct acpi_hest_generic_status)) {
917                 pr_warning(FW_BUG GHES_PFX "Invalid error block length: %u for generic hardware error source: %d\n",
918                            generic->error_block_length,
919                            generic->header.source_id);
920                 goto err;
921         }
922         ghes = ghes_new(generic);
923         if (IS_ERR(ghes)) {
924                 rc = PTR_ERR(ghes);
925                 ghes = NULL;
926                 goto err;
927         }
928
929         rc = ghes_edac_register(ghes, &ghes_dev->dev);
930         if (rc < 0)
931                 goto err;
932
933         switch (generic->notify.type) {
934         case ACPI_HEST_NOTIFY_POLLED:
935                 ghes->timer.function = ghes_poll_func;
936                 ghes->timer.data = (unsigned long)ghes;
937                 init_timer_deferrable(&ghes->timer);
938                 ghes_add_timer(ghes);
939                 break;
940         case ACPI_HEST_NOTIFY_EXTERNAL:
941                 /* External interrupt vector is GSI */
942                 rc = acpi_gsi_to_irq(generic->notify.vector, &ghes->irq);
943                 if (rc) {
944                         pr_err(GHES_PFX "Failed to map GSI to IRQ for generic hardware error source: %d\n",
945                                generic->header.source_id);
946                         goto err_edac_unreg;
947                 }
948                 rc = request_irq(ghes->irq, ghes_irq_func, 0, "GHES IRQ", ghes);
949                 if (rc) {
950                         pr_err(GHES_PFX "Failed to register IRQ for generic hardware error source: %d\n",
951                                generic->header.source_id);
952                         goto err_edac_unreg;
953                 }
954                 break;
955         case ACPI_HEST_NOTIFY_SCI:
956                 mutex_lock(&ghes_list_mutex);
957                 if (list_empty(&ghes_sci))
958                         register_acpi_hed_notifier(&ghes_notifier_sci);
959                 list_add_rcu(&ghes->list, &ghes_sci);
960                 mutex_unlock(&ghes_list_mutex);
961                 break;
962         case ACPI_HEST_NOTIFY_NMI:
963                 len = ghes_esource_prealloc_size(generic);
964                 ghes_estatus_pool_expand(len);
965                 mutex_lock(&ghes_list_mutex);
966                 if (list_empty(&ghes_nmi))
967                         register_nmi_handler(NMI_LOCAL, ghes_notify_nmi, 0,
968                                                 "ghes");
969                 list_add_rcu(&ghes->list, &ghes_nmi);
970                 mutex_unlock(&ghes_list_mutex);
971                 break;
972         default:
973                 BUG();
974         }
975         platform_set_drvdata(ghes_dev, ghes);
976
977         return 0;
978 err_edac_unreg:
979         ghes_edac_unregister(ghes);
980 err:
981         if (ghes) {
982                 ghes_fini(ghes);
983                 kfree(ghes);
984         }
985         return rc;
986 }
987
988 static int ghes_remove(struct platform_device *ghes_dev)
989 {
990         struct ghes *ghes;
991         struct acpi_hest_generic *generic;
992         unsigned long len;
993
994         ghes = platform_get_drvdata(ghes_dev);
995         generic = ghes->generic;
996
997         ghes->flags |= GHES_EXITING;
998         switch (generic->notify.type) {
999         case ACPI_HEST_NOTIFY_POLLED:
1000                 del_timer_sync(&ghes->timer);
1001                 break;
1002         case ACPI_HEST_NOTIFY_EXTERNAL:
1003                 free_irq(ghes->irq, ghes);
1004                 break;
1005         case ACPI_HEST_NOTIFY_SCI:
1006                 mutex_lock(&ghes_list_mutex);
1007                 list_del_rcu(&ghes->list);
1008                 if (list_empty(&ghes_sci))
1009                         unregister_acpi_hed_notifier(&ghes_notifier_sci);
1010                 mutex_unlock(&ghes_list_mutex);
1011                 break;
1012         case ACPI_HEST_NOTIFY_NMI:
1013                 mutex_lock(&ghes_list_mutex);
1014                 list_del_rcu(&ghes->list);
1015                 if (list_empty(&ghes_nmi))
1016                         unregister_nmi_handler(NMI_LOCAL, "ghes");
1017                 mutex_unlock(&ghes_list_mutex);
1018                 /*
1019                  * To synchronize with NMI handler, ghes can only be
1020                  * freed after NMI handler finishes.
1021                  */
1022                 synchronize_rcu();
1023                 len = ghes_esource_prealloc_size(generic);
1024                 ghes_estatus_pool_shrink(len);
1025                 break;
1026         default:
1027                 BUG();
1028                 break;
1029         }
1030
1031         ghes_fini(ghes);
1032
1033         ghes_edac_unregister(ghes);
1034
1035         kfree(ghes);
1036
1037         platform_set_drvdata(ghes_dev, NULL);
1038
1039         return 0;
1040 }
1041
1042 static struct platform_driver ghes_platform_driver = {
1043         .driver         = {
1044                 .name   = "GHES",
1045                 .owner  = THIS_MODULE,
1046         },
1047         .probe          = ghes_probe,
1048         .remove         = ghes_remove,
1049 };
1050
1051 static int __init ghes_init(void)
1052 {
1053         int rc;
1054
1055         if (acpi_disabled)
1056                 return -ENODEV;
1057
1058         if (hest_disable) {
1059                 pr_info(GHES_PFX "HEST is not enabled!\n");
1060                 return -EINVAL;
1061         }
1062
1063         if (ghes_disable) {
1064                 pr_info(GHES_PFX "GHES is not enabled!\n");
1065                 return -EINVAL;
1066         }
1067
1068         init_irq_work(&ghes_proc_irq_work, ghes_proc_in_irq);
1069
1070         rc = ghes_ioremap_init();
1071         if (rc)
1072                 goto err;
1073
1074         rc = ghes_estatus_pool_init();
1075         if (rc)
1076                 goto err_ioremap_exit;
1077
1078         rc = ghes_estatus_pool_expand(GHES_ESTATUS_CACHE_AVG_SIZE *
1079                                       GHES_ESTATUS_CACHE_ALLOCED_MAX);
1080         if (rc)
1081                 goto err_pool_exit;
1082
1083         rc = platform_driver_register(&ghes_platform_driver);
1084         if (rc)
1085                 goto err_pool_exit;
1086
1087         rc = apei_osc_setup();
1088         if (rc == 0 && osc_sb_apei_support_acked)
1089                 pr_info(GHES_PFX "APEI firmware first mode is enabled by APEI bit and WHEA _OSC.\n");
1090         else if (rc == 0 && !osc_sb_apei_support_acked)
1091                 pr_info(GHES_PFX "APEI firmware first mode is enabled by WHEA _OSC.\n");
1092         else if (rc && osc_sb_apei_support_acked)
1093                 pr_info(GHES_PFX "APEI firmware first mode is enabled by APEI bit.\n");
1094         else
1095                 pr_info(GHES_PFX "Failed to enable APEI firmware first mode.\n");
1096
1097         return 0;
1098 err_pool_exit:
1099         ghes_estatus_pool_exit();
1100 err_ioremap_exit:
1101         ghes_ioremap_exit();
1102 err:
1103         return rc;
1104 }
1105
1106 static void __exit ghes_exit(void)
1107 {
1108         platform_driver_unregister(&ghes_platform_driver);
1109         ghes_estatus_pool_exit();
1110         ghes_ioremap_exit();
1111 }
1112
1113 module_init(ghes_init);
1114 module_exit(ghes_exit);
1115
1116 MODULE_AUTHOR("Huang Ying");
1117 MODULE_DESCRIPTION("APEI Generic Hardware Error Source support");
1118 MODULE_LICENSE("GPL");
1119 MODULE_ALIAS("platform:GHES");