PCI/AER: Clear only ERR_FATAL status bits during fatal recovery
[sfrench/cifs-2.6.git] / drivers / pci / pcie / aer.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Implement the AER root port service driver. The driver registers an IRQ
4  * handler. When a root port triggers an AER interrupt, the IRQ handler
5  * collects root port status and schedules work.
6  *
7  * Copyright (C) 2006 Intel Corp.
8  *      Tom Long Nguyen (tom.l.nguyen@intel.com)
9  *      Zhang Yanmin (yanmin.zhang@intel.com)
10  *
11  * (C) Copyright 2009 Hewlett-Packard Development Company, L.P.
12  *    Andrew Patterson <andrew.patterson@hp.com>
13  */
14
15 #include <linux/cper.h>
16 #include <linux/pci.h>
17 #include <linux/pci-acpi.h>
18 #include <linux/sched.h>
19 #include <linux/kernel.h>
20 #include <linux/errno.h>
21 #include <linux/pm.h>
22 #include <linux/init.h>
23 #include <linux/interrupt.h>
24 #include <linux/delay.h>
25 #include <linux/kfifo.h>
26 #include <linux/slab.h>
27 #include <acpi/apei.h>
28 #include <ras/ras_event.h>
29
30 #include "../pci.h"
31 #include "portdrv.h"
32
33 #define AER_ERROR_SOURCES_MAX           100
34
35 #define AER_MAX_TYPEOF_COR_ERRS         16      /* as per PCI_ERR_COR_STATUS */
36 #define AER_MAX_TYPEOF_UNCOR_ERRS       26      /* as per PCI_ERR_UNCOR_STATUS*/
37
38 struct aer_err_source {
39         unsigned int status;
40         unsigned int id;
41 };
42
43 struct aer_rpc {
44         struct pci_dev *rpd;            /* Root Port device */
45         struct work_struct dpc_handler;
46         struct aer_err_source e_sources[AER_ERROR_SOURCES_MAX];
47         struct aer_err_info e_info;
48         unsigned short prod_idx;        /* Error Producer Index */
49         unsigned short cons_idx;        /* Error Consumer Index */
50         int isr;
51         spinlock_t e_lock;              /*
52                                          * Lock access to Error Status/ID Regs
53                                          * and error producer/consumer index
54                                          */
55         struct mutex rpc_mutex;         /*
56                                          * only one thread could do
57                                          * recovery on the same
58                                          * root port hierarchy
59                                          */
60 };
61
62 /* AER stats for the device */
63 struct aer_stats {
64
65         /*
66          * Fields for all AER capable devices. They indicate the errors
67          * "as seen by this device". Note that this may mean that if an
68          * end point is causing problems, the AER counters may increment
69          * at its link partner (e.g. root port) because the errors will be
70          * "seen" by the link partner and not the the problematic end point
71          * itself (which may report all counters as 0 as it never saw any
72          * problems).
73          */
74         /* Counters for different type of correctable errors */
75         u64 dev_cor_errs[AER_MAX_TYPEOF_COR_ERRS];
76         /* Counters for different type of fatal uncorrectable errors */
77         u64 dev_fatal_errs[AER_MAX_TYPEOF_UNCOR_ERRS];
78         /* Counters for different type of nonfatal uncorrectable errors */
79         u64 dev_nonfatal_errs[AER_MAX_TYPEOF_UNCOR_ERRS];
80         /* Total number of ERR_COR sent by this device */
81         u64 dev_total_cor_errs;
82         /* Total number of ERR_FATAL sent by this device */
83         u64 dev_total_fatal_errs;
84         /* Total number of ERR_NONFATAL sent by this device */
85         u64 dev_total_nonfatal_errs;
86
87         /*
88          * Fields for Root ports & root complex event collectors only, these
89          * indicate the total number of ERR_COR, ERR_FATAL, and ERR_NONFATAL
90          * messages received by the root port / event collector, INCLUDING the
91          * ones that are generated internally (by the rootport itself)
92          */
93         u64 rootport_total_cor_errs;
94         u64 rootport_total_fatal_errs;
95         u64 rootport_total_nonfatal_errs;
96 };
97
98 #define AER_LOG_TLP_MASKS               (PCI_ERR_UNC_POISON_TLP|        \
99                                         PCI_ERR_UNC_ECRC|               \
100                                         PCI_ERR_UNC_UNSUP|              \
101                                         PCI_ERR_UNC_COMP_ABORT|         \
102                                         PCI_ERR_UNC_UNX_COMP|           \
103                                         PCI_ERR_UNC_MALF_TLP)
104
105 #define SYSTEM_ERROR_INTR_ON_MESG_MASK  (PCI_EXP_RTCTL_SECEE|   \
106                                         PCI_EXP_RTCTL_SENFEE|   \
107                                         PCI_EXP_RTCTL_SEFEE)
108 #define ROOT_PORT_INTR_ON_MESG_MASK     (PCI_ERR_ROOT_CMD_COR_EN|       \
109                                         PCI_ERR_ROOT_CMD_NONFATAL_EN|   \
110                                         PCI_ERR_ROOT_CMD_FATAL_EN)
111 #define ERR_COR_ID(d)                   (d & 0xffff)
112 #define ERR_UNCOR_ID(d)                 (d >> 16)
113
114 static int pcie_aer_disable;
115
116 void pci_no_aer(void)
117 {
118         pcie_aer_disable = 1;
119 }
120
121 bool pci_aer_available(void)
122 {
123         return !pcie_aer_disable && pci_msi_enabled();
124 }
125
126 #ifdef CONFIG_PCIE_ECRC
127
128 #define ECRC_POLICY_DEFAULT 0           /* ECRC set by BIOS */
129 #define ECRC_POLICY_OFF     1           /* ECRC off for performance */
130 #define ECRC_POLICY_ON      2           /* ECRC on for data integrity */
131
132 static int ecrc_policy = ECRC_POLICY_DEFAULT;
133
134 static const char *ecrc_policy_str[] = {
135         [ECRC_POLICY_DEFAULT] = "bios",
136         [ECRC_POLICY_OFF] = "off",
137         [ECRC_POLICY_ON] = "on"
138 };
139
140 /**
141  * enable_ercr_checking - enable PCIe ECRC checking for a device
142  * @dev: the PCI device
143  *
144  * Returns 0 on success, or negative on failure.
145  */
146 static int enable_ecrc_checking(struct pci_dev *dev)
147 {
148         int pos;
149         u32 reg32;
150
151         if (!pci_is_pcie(dev))
152                 return -ENODEV;
153
154         pos = dev->aer_cap;
155         if (!pos)
156                 return -ENODEV;
157
158         pci_read_config_dword(dev, pos + PCI_ERR_CAP, &reg32);
159         if (reg32 & PCI_ERR_CAP_ECRC_GENC)
160                 reg32 |= PCI_ERR_CAP_ECRC_GENE;
161         if (reg32 & PCI_ERR_CAP_ECRC_CHKC)
162                 reg32 |= PCI_ERR_CAP_ECRC_CHKE;
163         pci_write_config_dword(dev, pos + PCI_ERR_CAP, reg32);
164
165         return 0;
166 }
167
168 /**
169  * disable_ercr_checking - disables PCIe ECRC checking for a device
170  * @dev: the PCI device
171  *
172  * Returns 0 on success, or negative on failure.
173  */
174 static int disable_ecrc_checking(struct pci_dev *dev)
175 {
176         int pos;
177         u32 reg32;
178
179         if (!pci_is_pcie(dev))
180                 return -ENODEV;
181
182         pos = dev->aer_cap;
183         if (!pos)
184                 return -ENODEV;
185
186         pci_read_config_dword(dev, pos + PCI_ERR_CAP, &reg32);
187         reg32 &= ~(PCI_ERR_CAP_ECRC_GENE | PCI_ERR_CAP_ECRC_CHKE);
188         pci_write_config_dword(dev, pos + PCI_ERR_CAP, reg32);
189
190         return 0;
191 }
192
193 /**
194  * pcie_set_ecrc_checking - set/unset PCIe ECRC checking for a device based on global policy
195  * @dev: the PCI device
196  */
197 void pcie_set_ecrc_checking(struct pci_dev *dev)
198 {
199         switch (ecrc_policy) {
200         case ECRC_POLICY_DEFAULT:
201                 return;
202         case ECRC_POLICY_OFF:
203                 disable_ecrc_checking(dev);
204                 break;
205         case ECRC_POLICY_ON:
206                 enable_ecrc_checking(dev);
207                 break;
208         default:
209                 return;
210         }
211 }
212
213 /**
214  * pcie_ecrc_get_policy - parse kernel command-line ecrc option
215  */
216 void pcie_ecrc_get_policy(char *str)
217 {
218         int i;
219
220         for (i = 0; i < ARRAY_SIZE(ecrc_policy_str); i++)
221                 if (!strncmp(str, ecrc_policy_str[i],
222                              strlen(ecrc_policy_str[i])))
223                         break;
224         if (i >= ARRAY_SIZE(ecrc_policy_str))
225                 return;
226
227         ecrc_policy = i;
228 }
229 #endif  /* CONFIG_PCIE_ECRC */
230
231 #ifdef CONFIG_ACPI_APEI
232 static inline int hest_match_pci(struct acpi_hest_aer_common *p,
233                                  struct pci_dev *pci)
234 {
235         return   ACPI_HEST_SEGMENT(p->bus) == pci_domain_nr(pci->bus) &&
236                  ACPI_HEST_BUS(p->bus)     == pci->bus->number &&
237                  p->device                 == PCI_SLOT(pci->devfn) &&
238                  p->function               == PCI_FUNC(pci->devfn);
239 }
240
241 static inline bool hest_match_type(struct acpi_hest_header *hest_hdr,
242                                 struct pci_dev *dev)
243 {
244         u16 hest_type = hest_hdr->type;
245         u8 pcie_type = pci_pcie_type(dev);
246
247         if ((hest_type == ACPI_HEST_TYPE_AER_ROOT_PORT &&
248                 pcie_type == PCI_EXP_TYPE_ROOT_PORT) ||
249             (hest_type == ACPI_HEST_TYPE_AER_ENDPOINT &&
250                 pcie_type == PCI_EXP_TYPE_ENDPOINT) ||
251             (hest_type == ACPI_HEST_TYPE_AER_BRIDGE &&
252                 (dev->class >> 16) == PCI_BASE_CLASS_BRIDGE))
253                 return true;
254         return false;
255 }
256
257 struct aer_hest_parse_info {
258         struct pci_dev *pci_dev;
259         int firmware_first;
260 };
261
262 static int hest_source_is_pcie_aer(struct acpi_hest_header *hest_hdr)
263 {
264         if (hest_hdr->type == ACPI_HEST_TYPE_AER_ROOT_PORT ||
265             hest_hdr->type == ACPI_HEST_TYPE_AER_ENDPOINT ||
266             hest_hdr->type == ACPI_HEST_TYPE_AER_BRIDGE)
267                 return 1;
268         return 0;
269 }
270
271 static int aer_hest_parse(struct acpi_hest_header *hest_hdr, void *data)
272 {
273         struct aer_hest_parse_info *info = data;
274         struct acpi_hest_aer_common *p;
275         int ff;
276
277         if (!hest_source_is_pcie_aer(hest_hdr))
278                 return 0;
279
280         p = (struct acpi_hest_aer_common *)(hest_hdr + 1);
281         ff = !!(p->flags & ACPI_HEST_FIRMWARE_FIRST);
282
283         /*
284          * If no specific device is supplied, determine whether
285          * FIRMWARE_FIRST is set for *any* PCIe device.
286          */
287         if (!info->pci_dev) {
288                 info->firmware_first |= ff;
289                 return 0;
290         }
291
292         /* Otherwise, check the specific device */
293         if (p->flags & ACPI_HEST_GLOBAL) {
294                 if (hest_match_type(hest_hdr, info->pci_dev))
295                         info->firmware_first = ff;
296         } else
297                 if (hest_match_pci(p, info->pci_dev))
298                         info->firmware_first = ff;
299
300         return 0;
301 }
302
303 static void aer_set_firmware_first(struct pci_dev *pci_dev)
304 {
305         int rc;
306         struct aer_hest_parse_info info = {
307                 .pci_dev        = pci_dev,
308                 .firmware_first = 0,
309         };
310
311         rc = apei_hest_parse(aer_hest_parse, &info);
312
313         if (rc)
314                 pci_dev->__aer_firmware_first = 0;
315         else
316                 pci_dev->__aer_firmware_first = info.firmware_first;
317         pci_dev->__aer_firmware_first_valid = 1;
318 }
319
320 int pcie_aer_get_firmware_first(struct pci_dev *dev)
321 {
322         if (!pci_is_pcie(dev))
323                 return 0;
324
325         if (pcie_ports_native)
326                 return 0;
327
328         if (!dev->__aer_firmware_first_valid)
329                 aer_set_firmware_first(dev);
330         return dev->__aer_firmware_first;
331 }
332 #define PCI_EXP_AER_FLAGS       (PCI_EXP_DEVCTL_CERE | PCI_EXP_DEVCTL_NFERE | \
333                                  PCI_EXP_DEVCTL_FERE | PCI_EXP_DEVCTL_URRE)
334
335 static bool aer_firmware_first;
336
337 /**
338  * aer_acpi_firmware_first - Check if APEI should control AER.
339  */
340 bool aer_acpi_firmware_first(void)
341 {
342         static bool parsed = false;
343         struct aer_hest_parse_info info = {
344                 .pci_dev        = NULL, /* Check all PCIe devices */
345                 .firmware_first = 0,
346         };
347
348         if (pcie_ports_native)
349                 return false;
350
351         if (!parsed) {
352                 apei_hest_parse(aer_hest_parse, &info);
353                 aer_firmware_first = info.firmware_first;
354                 parsed = true;
355         }
356         return aer_firmware_first;
357 }
358 #endif
359
360 #define PCI_EXP_AER_FLAGS       (PCI_EXP_DEVCTL_CERE | PCI_EXP_DEVCTL_NFERE | \
361                                  PCI_EXP_DEVCTL_FERE | PCI_EXP_DEVCTL_URRE)
362
363 int pci_enable_pcie_error_reporting(struct pci_dev *dev)
364 {
365         if (pcie_aer_get_firmware_first(dev))
366                 return -EIO;
367
368         if (!dev->aer_cap)
369                 return -EIO;
370
371         return pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_AER_FLAGS);
372 }
373 EXPORT_SYMBOL_GPL(pci_enable_pcie_error_reporting);
374
375 int pci_disable_pcie_error_reporting(struct pci_dev *dev)
376 {
377         if (pcie_aer_get_firmware_first(dev))
378                 return -EIO;
379
380         return pcie_capability_clear_word(dev, PCI_EXP_DEVCTL,
381                                           PCI_EXP_AER_FLAGS);
382 }
383 EXPORT_SYMBOL_GPL(pci_disable_pcie_error_reporting);
384
385 int pci_cleanup_aer_uncorrect_error_status(struct pci_dev *dev)
386 {
387         int pos;
388         u32 status;
389
390         pos = dev->aer_cap;
391         if (!pos)
392                 return -EIO;
393
394         pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
395         if (status)
396                 pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status);
397
398         return 0;
399 }
400 EXPORT_SYMBOL_GPL(pci_cleanup_aer_uncorrect_error_status);
401
402 void pci_aer_clear_fatal_status(struct pci_dev *dev)
403 {
404         int pos;
405         u32 status, sev;
406
407         pos = dev->aer_cap;
408         if (!pos)
409                 return;
410
411         /* Clear status bits for ERR_FATAL errors only */
412         pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
413         pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, &sev);
414         status &= sev;
415         if (status)
416                 pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status);
417 }
418
419 int pci_cleanup_aer_error_status_regs(struct pci_dev *dev)
420 {
421         int pos;
422         u32 status;
423         int port_type;
424
425         if (!pci_is_pcie(dev))
426                 return -ENODEV;
427
428         pos = dev->aer_cap;
429         if (!pos)
430                 return -EIO;
431
432         port_type = pci_pcie_type(dev);
433         if (port_type == PCI_EXP_TYPE_ROOT_PORT) {
434                 pci_read_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, &status);
435                 pci_write_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, status);
436         }
437
438         pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS, &status);
439         pci_write_config_dword(dev, pos + PCI_ERR_COR_STATUS, status);
440
441         pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
442         pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status);
443
444         return 0;
445 }
446
447 void pci_aer_init(struct pci_dev *dev)
448 {
449         dev->aer_cap = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
450
451         if (dev->aer_cap)
452                 dev->aer_stats = kzalloc(sizeof(struct aer_stats), GFP_KERNEL);
453
454         pci_cleanup_aer_error_status_regs(dev);
455 }
456
457 void pci_aer_exit(struct pci_dev *dev)
458 {
459         kfree(dev->aer_stats);
460         dev->aer_stats = NULL;
461 }
462
463 #define AER_AGENT_RECEIVER              0
464 #define AER_AGENT_REQUESTER             1
465 #define AER_AGENT_COMPLETER             2
466 #define AER_AGENT_TRANSMITTER           3
467
468 #define AER_AGENT_REQUESTER_MASK(t)     ((t == AER_CORRECTABLE) ?       \
469         0 : (PCI_ERR_UNC_COMP_TIME|PCI_ERR_UNC_UNSUP))
470 #define AER_AGENT_COMPLETER_MASK(t)     ((t == AER_CORRECTABLE) ?       \
471         0 : PCI_ERR_UNC_COMP_ABORT)
472 #define AER_AGENT_TRANSMITTER_MASK(t)   ((t == AER_CORRECTABLE) ?       \
473         (PCI_ERR_COR_REP_ROLL|PCI_ERR_COR_REP_TIMER) : 0)
474
475 #define AER_GET_AGENT(t, e)                                             \
476         ((e & AER_AGENT_COMPLETER_MASK(t)) ? AER_AGENT_COMPLETER :      \
477         (e & AER_AGENT_REQUESTER_MASK(t)) ? AER_AGENT_REQUESTER :       \
478         (e & AER_AGENT_TRANSMITTER_MASK(t)) ? AER_AGENT_TRANSMITTER :   \
479         AER_AGENT_RECEIVER)
480
481 #define AER_PHYSICAL_LAYER_ERROR        0
482 #define AER_DATA_LINK_LAYER_ERROR       1
483 #define AER_TRANSACTION_LAYER_ERROR     2
484
485 #define AER_PHYSICAL_LAYER_ERROR_MASK(t) ((t == AER_CORRECTABLE) ?      \
486         PCI_ERR_COR_RCVR : 0)
487 #define AER_DATA_LINK_LAYER_ERROR_MASK(t) ((t == AER_CORRECTABLE) ?     \
488         (PCI_ERR_COR_BAD_TLP|                                           \
489         PCI_ERR_COR_BAD_DLLP|                                           \
490         PCI_ERR_COR_REP_ROLL|                                           \
491         PCI_ERR_COR_REP_TIMER) : PCI_ERR_UNC_DLP)
492
493 #define AER_GET_LAYER_ERROR(t, e)                                       \
494         ((e & AER_PHYSICAL_LAYER_ERROR_MASK(t)) ? AER_PHYSICAL_LAYER_ERROR : \
495         (e & AER_DATA_LINK_LAYER_ERROR_MASK(t)) ? AER_DATA_LINK_LAYER_ERROR : \
496         AER_TRANSACTION_LAYER_ERROR)
497
498 /*
499  * AER error strings
500  */
501 static const char *aer_error_severity_string[] = {
502         "Uncorrected (Non-Fatal)",
503         "Uncorrected (Fatal)",
504         "Corrected"
505 };
506
507 static const char *aer_error_layer[] = {
508         "Physical Layer",
509         "Data Link Layer",
510         "Transaction Layer"
511 };
512
513 static const char *aer_correctable_error_string[AER_MAX_TYPEOF_COR_ERRS] = {
514         "RxErr",                        /* Bit Position 0       */
515         NULL,
516         NULL,
517         NULL,
518         NULL,
519         NULL,
520         "BadTLP",                       /* Bit Position 6       */
521         "BadDLLP",                      /* Bit Position 7       */
522         "Rollover",                     /* Bit Position 8       */
523         NULL,
524         NULL,
525         NULL,
526         "Timeout",                      /* Bit Position 12      */
527         "NonFatalErr",                  /* Bit Position 13      */
528         "CorrIntErr",                   /* Bit Position 14      */
529         "HeaderOF",                     /* Bit Position 15      */
530 };
531
532 static const char *aer_uncorrectable_error_string[AER_MAX_TYPEOF_UNCOR_ERRS] = {
533         "Undefined",                    /* Bit Position 0       */
534         NULL,
535         NULL,
536         NULL,
537         "DLP",                          /* Bit Position 4       */
538         "SDES",                         /* Bit Position 5       */
539         NULL,
540         NULL,
541         NULL,
542         NULL,
543         NULL,
544         NULL,
545         "TLP",                          /* Bit Position 12      */
546         "FCP",                          /* Bit Position 13      */
547         "CmpltTO",                      /* Bit Position 14      */
548         "CmpltAbrt",                    /* Bit Position 15      */
549         "UnxCmplt",                     /* Bit Position 16      */
550         "RxOF",                         /* Bit Position 17      */
551         "MalfTLP",                      /* Bit Position 18      */
552         "ECRC",                         /* Bit Position 19      */
553         "UnsupReq",                     /* Bit Position 20      */
554         "ACSViol",                      /* Bit Position 21      */
555         "UncorrIntErr",                 /* Bit Position 22      */
556         "BlockedTLP",                   /* Bit Position 23      */
557         "AtomicOpBlocked",              /* Bit Position 24      */
558         "TLPBlockedErr",                /* Bit Position 25      */
559 };
560
561 static const char *aer_agent_string[] = {
562         "Receiver ID",
563         "Requester ID",
564         "Completer ID",
565         "Transmitter ID"
566 };
567
568 #define aer_stats_dev_attr(name, stats_array, strings_array,            \
569                            total_string, total_field)                   \
570         static ssize_t                                                  \
571         name##_show(struct device *dev, struct device_attribute *attr,  \
572                      char *buf)                                         \
573 {                                                                       \
574         unsigned int i;                                                 \
575         char *str = buf;                                                \
576         struct pci_dev *pdev = to_pci_dev(dev);                         \
577         u64 *stats = pdev->aer_stats->stats_array;                      \
578                                                                         \
579         for (i = 0; i < ARRAY_SIZE(strings_array); i++) {               \
580                 if (strings_array[i])                                   \
581                         str += sprintf(str, "%s %llu\n",                \
582                                        strings_array[i], stats[i]);     \
583                 else if (stats[i])                                      \
584                         str += sprintf(str, #stats_array "_bit[%d] %llu\n",\
585                                        i, stats[i]);                    \
586         }                                                               \
587         str += sprintf(str, "TOTAL_%s %llu\n", total_string,            \
588                        pdev->aer_stats->total_field);                   \
589         return str-buf;                                                 \
590 }                                                                       \
591 static DEVICE_ATTR_RO(name)
592
593 aer_stats_dev_attr(aer_dev_correctable, dev_cor_errs,
594                    aer_correctable_error_string, "ERR_COR",
595                    dev_total_cor_errs);
596 aer_stats_dev_attr(aer_dev_fatal, dev_fatal_errs,
597                    aer_uncorrectable_error_string, "ERR_FATAL",
598                    dev_total_fatal_errs);
599 aer_stats_dev_attr(aer_dev_nonfatal, dev_nonfatal_errs,
600                    aer_uncorrectable_error_string, "ERR_NONFATAL",
601                    dev_total_nonfatal_errs);
602
603 #define aer_stats_rootport_attr(name, field)                            \
604         static ssize_t                                                  \
605         name##_show(struct device *dev, struct device_attribute *attr,  \
606                      char *buf)                                         \
607 {                                                                       \
608         struct pci_dev *pdev = to_pci_dev(dev);                         \
609         return sprintf(buf, "%llu\n", pdev->aer_stats->field);          \
610 }                                                                       \
611 static DEVICE_ATTR_RO(name)
612
613 aer_stats_rootport_attr(aer_rootport_total_err_cor,
614                          rootport_total_cor_errs);
615 aer_stats_rootport_attr(aer_rootport_total_err_fatal,
616                          rootport_total_fatal_errs);
617 aer_stats_rootport_attr(aer_rootport_total_err_nonfatal,
618                          rootport_total_nonfatal_errs);
619
620 static struct attribute *aer_stats_attrs[] __ro_after_init = {
621         &dev_attr_aer_dev_correctable.attr,
622         &dev_attr_aer_dev_fatal.attr,
623         &dev_attr_aer_dev_nonfatal.attr,
624         &dev_attr_aer_rootport_total_err_cor.attr,
625         &dev_attr_aer_rootport_total_err_fatal.attr,
626         &dev_attr_aer_rootport_total_err_nonfatal.attr,
627         NULL
628 };
629
630 static umode_t aer_stats_attrs_are_visible(struct kobject *kobj,
631                                            struct attribute *a, int n)
632 {
633         struct device *dev = kobj_to_dev(kobj);
634         struct pci_dev *pdev = to_pci_dev(dev);
635
636         if (!pdev->aer_stats)
637                 return 0;
638
639         if ((a == &dev_attr_aer_rootport_total_err_cor.attr ||
640              a == &dev_attr_aer_rootport_total_err_fatal.attr ||
641              a == &dev_attr_aer_rootport_total_err_nonfatal.attr) &&
642             pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT)
643                 return 0;
644
645         return a->mode;
646 }
647
648 const struct attribute_group aer_stats_attr_group = {
649         .attrs  = aer_stats_attrs,
650         .is_visible = aer_stats_attrs_are_visible,
651 };
652
653 static void pci_dev_aer_stats_incr(struct pci_dev *pdev,
654                                    struct aer_err_info *info)
655 {
656         int status, i, max = -1;
657         u64 *counter = NULL;
658         struct aer_stats *aer_stats = pdev->aer_stats;
659
660         if (!aer_stats)
661                 return;
662
663         switch (info->severity) {
664         case AER_CORRECTABLE:
665                 aer_stats->dev_total_cor_errs++;
666                 counter = &aer_stats->dev_cor_errs[0];
667                 max = AER_MAX_TYPEOF_COR_ERRS;
668                 break;
669         case AER_NONFATAL:
670                 aer_stats->dev_total_nonfatal_errs++;
671                 counter = &aer_stats->dev_nonfatal_errs[0];
672                 max = AER_MAX_TYPEOF_UNCOR_ERRS;
673                 break;
674         case AER_FATAL:
675                 aer_stats->dev_total_fatal_errs++;
676                 counter = &aer_stats->dev_fatal_errs[0];
677                 max = AER_MAX_TYPEOF_UNCOR_ERRS;
678                 break;
679         }
680
681         status = (info->status & ~info->mask);
682         for (i = 0; i < max; i++)
683                 if (status & (1 << i))
684                         counter[i]++;
685 }
686
687 static void pci_rootport_aer_stats_incr(struct pci_dev *pdev,
688                                  struct aer_err_source *e_src)
689 {
690         struct aer_stats *aer_stats = pdev->aer_stats;
691
692         if (!aer_stats)
693                 return;
694
695         if (e_src->status & PCI_ERR_ROOT_COR_RCV)
696                 aer_stats->rootport_total_cor_errs++;
697
698         if (e_src->status & PCI_ERR_ROOT_UNCOR_RCV) {
699                 if (e_src->status & PCI_ERR_ROOT_FATAL_RCV)
700                         aer_stats->rootport_total_fatal_errs++;
701                 else
702                         aer_stats->rootport_total_nonfatal_errs++;
703         }
704 }
705
706 static void __print_tlp_header(struct pci_dev *dev,
707                                struct aer_header_log_regs *t)
708 {
709         pci_err(dev, "  TLP Header: %08x %08x %08x %08x\n",
710                 t->dw0, t->dw1, t->dw2, t->dw3);
711 }
712
713 static void __aer_print_error(struct pci_dev *dev,
714                               struct aer_err_info *info)
715 {
716         int i, status;
717         const char *errmsg = NULL;
718         status = (info->status & ~info->mask);
719
720         for (i = 0; i < 32; i++) {
721                 if (!(status & (1 << i)))
722                         continue;
723
724                 if (info->severity == AER_CORRECTABLE)
725                         errmsg = i < ARRAY_SIZE(aer_correctable_error_string) ?
726                                 aer_correctable_error_string[i] : NULL;
727                 else
728                         errmsg = i < ARRAY_SIZE(aer_uncorrectable_error_string) ?
729                                 aer_uncorrectable_error_string[i] : NULL;
730
731                 if (errmsg)
732                         pci_err(dev, "   [%2d] %-22s%s\n", i, errmsg,
733                                 info->first_error == i ? " (First)" : "");
734                 else
735                         pci_err(dev, "   [%2d] Unknown Error Bit%s\n",
736                                 i, info->first_error == i ? " (First)" : "");
737         }
738         pci_dev_aer_stats_incr(dev, info);
739 }
740
741 void aer_print_error(struct pci_dev *dev, struct aer_err_info *info)
742 {
743         int layer, agent;
744         int id = ((dev->bus->number << 8) | dev->devfn);
745
746         if (!info->status) {
747                 pci_err(dev, "PCIe Bus Error: severity=%s, type=Inaccessible, (Unregistered Agent ID)\n",
748                         aer_error_severity_string[info->severity]);
749                 goto out;
750         }
751
752         layer = AER_GET_LAYER_ERROR(info->severity, info->status);
753         agent = AER_GET_AGENT(info->severity, info->status);
754
755         pci_err(dev, "PCIe Bus Error: severity=%s, type=%s, (%s)\n",
756                 aer_error_severity_string[info->severity],
757                 aer_error_layer[layer], aer_agent_string[agent]);
758
759         pci_err(dev, "  device [%04x:%04x] error status/mask=%08x/%08x\n",
760                 dev->vendor, dev->device,
761                 info->status, info->mask);
762
763         __aer_print_error(dev, info);
764
765         if (info->tlp_header_valid)
766                 __print_tlp_header(dev, &info->tlp);
767
768 out:
769         if (info->id && info->error_dev_num > 1 && info->id == id)
770                 pci_err(dev, "  Error of this Agent is reported first\n");
771
772         trace_aer_event(dev_name(&dev->dev), (info->status & ~info->mask),
773                         info->severity, info->tlp_header_valid, &info->tlp);
774 }
775
776 static void aer_print_port_info(struct pci_dev *dev, struct aer_err_info *info)
777 {
778         u8 bus = info->id >> 8;
779         u8 devfn = info->id & 0xff;
780
781         pci_info(dev, "AER: %s%s error received: %04x:%02x:%02x.%d\n",
782                 info->multi_error_valid ? "Multiple " : "",
783                 aer_error_severity_string[info->severity],
784                 pci_domain_nr(dev->bus), bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
785 }
786
787 #ifdef CONFIG_ACPI_APEI_PCIEAER
788 int cper_severity_to_aer(int cper_severity)
789 {
790         switch (cper_severity) {
791         case CPER_SEV_RECOVERABLE:
792                 return AER_NONFATAL;
793         case CPER_SEV_FATAL:
794                 return AER_FATAL;
795         default:
796                 return AER_CORRECTABLE;
797         }
798 }
799 EXPORT_SYMBOL_GPL(cper_severity_to_aer);
800
801 void cper_print_aer(struct pci_dev *dev, int aer_severity,
802                     struct aer_capability_regs *aer)
803 {
804         int layer, agent, tlp_header_valid = 0;
805         u32 status, mask;
806         struct aer_err_info info;
807
808         if (aer_severity == AER_CORRECTABLE) {
809                 status = aer->cor_status;
810                 mask = aer->cor_mask;
811         } else {
812                 status = aer->uncor_status;
813                 mask = aer->uncor_mask;
814                 tlp_header_valid = status & AER_LOG_TLP_MASKS;
815         }
816
817         layer = AER_GET_LAYER_ERROR(aer_severity, status);
818         agent = AER_GET_AGENT(aer_severity, status);
819
820         memset(&info, 0, sizeof(info));
821         info.severity = aer_severity;
822         info.status = status;
823         info.mask = mask;
824         info.first_error = PCI_ERR_CAP_FEP(aer->cap_control);
825
826         pci_err(dev, "aer_status: 0x%08x, aer_mask: 0x%08x\n", status, mask);
827         __aer_print_error(dev, &info);
828         pci_err(dev, "aer_layer=%s, aer_agent=%s\n",
829                 aer_error_layer[layer], aer_agent_string[agent]);
830
831         if (aer_severity != AER_CORRECTABLE)
832                 pci_err(dev, "aer_uncor_severity: 0x%08x\n",
833                         aer->uncor_severity);
834
835         if (tlp_header_valid)
836                 __print_tlp_header(dev, &aer->header_log);
837
838         trace_aer_event(dev_name(&dev->dev), (status & ~mask),
839                         aer_severity, tlp_header_valid, &aer->header_log);
840 }
841 #endif
842
843 /**
844  * add_error_device - list device to be handled
845  * @e_info: pointer to error info
846  * @dev: pointer to pci_dev to be added
847  */
848 static int add_error_device(struct aer_err_info *e_info, struct pci_dev *dev)
849 {
850         if (e_info->error_dev_num < AER_MAX_MULTI_ERR_DEVICES) {
851                 e_info->dev[e_info->error_dev_num] = dev;
852                 e_info->error_dev_num++;
853                 return 0;
854         }
855         return -ENOSPC;
856 }
857
858 /**
859  * is_error_source - check whether the device is source of reported error
860  * @dev: pointer to pci_dev to be checked
861  * @e_info: pointer to reported error info
862  */
863 static bool is_error_source(struct pci_dev *dev, struct aer_err_info *e_info)
864 {
865         int pos;
866         u32 status, mask;
867         u16 reg16;
868
869         /*
870          * When bus id is equal to 0, it might be a bad id
871          * reported by root port.
872          */
873         if ((PCI_BUS_NUM(e_info->id) != 0) &&
874             !(dev->bus->bus_flags & PCI_BUS_FLAGS_NO_AERSID)) {
875                 /* Device ID match? */
876                 if (e_info->id == ((dev->bus->number << 8) | dev->devfn))
877                         return true;
878
879                 /* Continue id comparing if there is no multiple error */
880                 if (!e_info->multi_error_valid)
881                         return false;
882         }
883
884         /*
885          * When either
886          *      1) bus id is equal to 0. Some ports might lose the bus
887          *              id of error source id;
888          *      2) bus flag PCI_BUS_FLAGS_NO_AERSID is set
889          *      3) There are multiple errors and prior ID comparing fails;
890          * We check AER status registers to find possible reporter.
891          */
892         if (atomic_read(&dev->enable_cnt) == 0)
893                 return false;
894
895         /* Check if AER is enabled */
896         pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &reg16);
897         if (!(reg16 & PCI_EXP_AER_FLAGS))
898                 return false;
899
900         pos = dev->aer_cap;
901         if (!pos)
902                 return false;
903
904         /* Check if error is recorded */
905         if (e_info->severity == AER_CORRECTABLE) {
906                 pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS, &status);
907                 pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK, &mask);
908         } else {
909                 pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
910                 pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, &mask);
911         }
912         if (status & ~mask)
913                 return true;
914
915         return false;
916 }
917
918 static int find_device_iter(struct pci_dev *dev, void *data)
919 {
920         struct aer_err_info *e_info = (struct aer_err_info *)data;
921
922         if (is_error_source(dev, e_info)) {
923                 /* List this device */
924                 if (add_error_device(e_info, dev)) {
925                         /* We cannot handle more... Stop iteration */
926                         /* TODO: Should print error message here? */
927                         return 1;
928                 }
929
930                 /* If there is only a single error, stop iteration */
931                 if (!e_info->multi_error_valid)
932                         return 1;
933         }
934         return 0;
935 }
936
937 /**
938  * find_source_device - search through device hierarchy for source device
939  * @parent: pointer to Root Port pci_dev data structure
940  * @e_info: including detailed error information such like id
941  *
942  * Return true if found.
943  *
944  * Invoked by DPC when error is detected at the Root Port.
945  * Caller of this function must set id, severity, and multi_error_valid of
946  * struct aer_err_info pointed by @e_info properly.  This function must fill
947  * e_info->error_dev_num and e_info->dev[], based on the given information.
948  */
949 static bool find_source_device(struct pci_dev *parent,
950                 struct aer_err_info *e_info)
951 {
952         struct pci_dev *dev = parent;
953         int result;
954
955         /* Must reset in this function */
956         e_info->error_dev_num = 0;
957
958         /* Is Root Port an agent that sends error message? */
959         result = find_device_iter(dev, e_info);
960         if (result)
961                 return true;
962
963         pci_walk_bus(parent->subordinate, find_device_iter, e_info);
964
965         if (!e_info->error_dev_num) {
966                 pci_printk(KERN_DEBUG, parent, "can't find device of ID%04x\n",
967                            e_info->id);
968                 return false;
969         }
970         return true;
971 }
972
973 /**
974  * handle_error_source - handle logging error into an event log
975  * @dev: pointer to pci_dev data structure of error source device
976  * @info: comprehensive error information
977  *
978  * Invoked when an error being detected by Root Port.
979  */
980 static void handle_error_source(struct pci_dev *dev, struct aer_err_info *info)
981 {
982         int pos;
983
984         if (info->severity == AER_CORRECTABLE) {
985                 /*
986                  * Correctable error does not need software intervention.
987                  * No need to go through error recovery process.
988                  */
989                 pos = dev->aer_cap;
990                 if (pos)
991                         pci_write_config_dword(dev, pos + PCI_ERR_COR_STATUS,
992                                         info->status);
993         } else if (info->severity == AER_NONFATAL)
994                 pcie_do_nonfatal_recovery(dev);
995         else if (info->severity == AER_FATAL)
996                 pcie_do_fatal_recovery(dev, PCIE_PORT_SERVICE_AER);
997 }
998
999 #ifdef CONFIG_ACPI_APEI_PCIEAER
1000
1001 #define AER_RECOVER_RING_ORDER          4
1002 #define AER_RECOVER_RING_SIZE           (1 << AER_RECOVER_RING_ORDER)
1003
1004 struct aer_recover_entry {
1005         u8      bus;
1006         u8      devfn;
1007         u16     domain;
1008         int     severity;
1009         struct aer_capability_regs *regs;
1010 };
1011
1012 static DEFINE_KFIFO(aer_recover_ring, struct aer_recover_entry,
1013                     AER_RECOVER_RING_SIZE);
1014
1015 static void aer_recover_work_func(struct work_struct *work)
1016 {
1017         struct aer_recover_entry entry;
1018         struct pci_dev *pdev;
1019
1020         while (kfifo_get(&aer_recover_ring, &entry)) {
1021                 pdev = pci_get_domain_bus_and_slot(entry.domain, entry.bus,
1022                                                    entry.devfn);
1023                 if (!pdev) {
1024                         pr_err("AER recover: Can not find pci_dev for %04x:%02x:%02x:%x\n",
1025                                entry.domain, entry.bus,
1026                                PCI_SLOT(entry.devfn), PCI_FUNC(entry.devfn));
1027                         continue;
1028                 }
1029                 cper_print_aer(pdev, entry.severity, entry.regs);
1030                 if (entry.severity == AER_NONFATAL)
1031                         pcie_do_nonfatal_recovery(pdev);
1032                 else if (entry.severity == AER_FATAL)
1033                         pcie_do_fatal_recovery(pdev, PCIE_PORT_SERVICE_AER);
1034                 pci_dev_put(pdev);
1035         }
1036 }
1037
1038 /*
1039  * Mutual exclusion for writers of aer_recover_ring, reader side don't
1040  * need lock, because there is only one reader and lock is not needed
1041  * between reader and writer.
1042  */
1043 static DEFINE_SPINLOCK(aer_recover_ring_lock);
1044 static DECLARE_WORK(aer_recover_work, aer_recover_work_func);
1045
1046 void aer_recover_queue(int domain, unsigned int bus, unsigned int devfn,
1047                        int severity, struct aer_capability_regs *aer_regs)
1048 {
1049         unsigned long flags;
1050         struct aer_recover_entry entry = {
1051                 .bus            = bus,
1052                 .devfn          = devfn,
1053                 .domain         = domain,
1054                 .severity       = severity,
1055                 .regs           = aer_regs,
1056         };
1057
1058         spin_lock_irqsave(&aer_recover_ring_lock, flags);
1059         if (kfifo_put(&aer_recover_ring, entry))
1060                 schedule_work(&aer_recover_work);
1061         else
1062                 pr_err("AER recover: Buffer overflow when recovering AER for %04x:%02x:%02x:%x\n",
1063                        domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
1064         spin_unlock_irqrestore(&aer_recover_ring_lock, flags);
1065 }
1066 EXPORT_SYMBOL_GPL(aer_recover_queue);
1067 #endif
1068
1069 /**
1070  * aer_get_device_error_info - read error status from dev and store it to info
1071  * @dev: pointer to the device expected to have a error record
1072  * @info: pointer to structure to store the error record
1073  *
1074  * Return 1 on success, 0 on error.
1075  *
1076  * Note that @info is reused among all error devices. Clear fields properly.
1077  */
1078 int aer_get_device_error_info(struct pci_dev *dev, struct aer_err_info *info)
1079 {
1080         int pos, temp;
1081
1082         /* Must reset in this function */
1083         info->status = 0;
1084         info->tlp_header_valid = 0;
1085
1086         pos = dev->aer_cap;
1087
1088         /* The device might not support AER */
1089         if (!pos)
1090                 return 0;
1091
1092         if (info->severity == AER_CORRECTABLE) {
1093                 pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS,
1094                         &info->status);
1095                 pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK,
1096                         &info->mask);
1097                 if (!(info->status & ~info->mask))
1098                         return 0;
1099         } else if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE ||
1100                 info->severity == AER_NONFATAL) {
1101
1102                 /* Link is still healthy for IO reads */
1103                 pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS,
1104                         &info->status);
1105                 pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK,
1106                         &info->mask);
1107                 if (!(info->status & ~info->mask))
1108                         return 0;
1109
1110                 /* Get First Error Pointer */
1111                 pci_read_config_dword(dev, pos + PCI_ERR_CAP, &temp);
1112                 info->first_error = PCI_ERR_CAP_FEP(temp);
1113
1114                 if (info->status & AER_LOG_TLP_MASKS) {
1115                         info->tlp_header_valid = 1;
1116                         pci_read_config_dword(dev,
1117                                 pos + PCI_ERR_HEADER_LOG, &info->tlp.dw0);
1118                         pci_read_config_dword(dev,
1119                                 pos + PCI_ERR_HEADER_LOG + 4, &info->tlp.dw1);
1120                         pci_read_config_dword(dev,
1121                                 pos + PCI_ERR_HEADER_LOG + 8, &info->tlp.dw2);
1122                         pci_read_config_dword(dev,
1123                                 pos + PCI_ERR_HEADER_LOG + 12, &info->tlp.dw3);
1124                 }
1125         }
1126
1127         return 1;
1128 }
1129
1130 static inline void aer_process_err_devices(struct aer_err_info *e_info)
1131 {
1132         int i;
1133
1134         /* Report all before handle them, not to lost records by reset etc. */
1135         for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) {
1136                 if (aer_get_device_error_info(e_info->dev[i], e_info))
1137                         aer_print_error(e_info->dev[i], e_info);
1138         }
1139         for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) {
1140                 if (aer_get_device_error_info(e_info->dev[i], e_info))
1141                         handle_error_source(e_info->dev[i], e_info);
1142         }
1143 }
1144
1145 /**
1146  * aer_isr_one_error - consume an error detected by root port
1147  * @rpc: pointer to the root port which holds an error
1148  * @e_src: pointer to an error source
1149  */
1150 static void aer_isr_one_error(struct aer_rpc *rpc,
1151                 struct aer_err_source *e_src)
1152 {
1153         struct pci_dev *pdev = rpc->rpd;
1154         struct aer_err_info *e_info = &rpc->e_info;
1155
1156         pci_rootport_aer_stats_incr(pdev, e_src);
1157
1158         /*
1159          * There is a possibility that both correctable error and
1160          * uncorrectable error being logged. Report correctable error first.
1161          */
1162         if (e_src->status & PCI_ERR_ROOT_COR_RCV) {
1163                 e_info->id = ERR_COR_ID(e_src->id);
1164                 e_info->severity = AER_CORRECTABLE;
1165
1166                 if (e_src->status & PCI_ERR_ROOT_MULTI_COR_RCV)
1167                         e_info->multi_error_valid = 1;
1168                 else
1169                         e_info->multi_error_valid = 0;
1170                 aer_print_port_info(pdev, e_info);
1171
1172                 if (find_source_device(pdev, e_info))
1173                         aer_process_err_devices(e_info);
1174         }
1175
1176         if (e_src->status & PCI_ERR_ROOT_UNCOR_RCV) {
1177                 e_info->id = ERR_UNCOR_ID(e_src->id);
1178
1179                 if (e_src->status & PCI_ERR_ROOT_FATAL_RCV)
1180                         e_info->severity = AER_FATAL;
1181                 else
1182                         e_info->severity = AER_NONFATAL;
1183
1184                 if (e_src->status & PCI_ERR_ROOT_MULTI_UNCOR_RCV)
1185                         e_info->multi_error_valid = 1;
1186                 else
1187                         e_info->multi_error_valid = 0;
1188
1189                 aer_print_port_info(pdev, e_info);
1190
1191                 if (find_source_device(pdev, e_info))
1192                         aer_process_err_devices(e_info);
1193         }
1194 }
1195
1196 /**
1197  * get_e_source - retrieve an error source
1198  * @rpc: pointer to the root port which holds an error
1199  * @e_src: pointer to store retrieved error source
1200  *
1201  * Return 1 if an error source is retrieved, otherwise 0.
1202  *
1203  * Invoked by DPC handler to consume an error.
1204  */
1205 static int get_e_source(struct aer_rpc *rpc, struct aer_err_source *e_src)
1206 {
1207         unsigned long flags;
1208
1209         /* Lock access to Root error producer/consumer index */
1210         spin_lock_irqsave(&rpc->e_lock, flags);
1211         if (rpc->prod_idx == rpc->cons_idx) {
1212                 spin_unlock_irqrestore(&rpc->e_lock, flags);
1213                 return 0;
1214         }
1215
1216         *e_src = rpc->e_sources[rpc->cons_idx];
1217         rpc->cons_idx++;
1218         if (rpc->cons_idx == AER_ERROR_SOURCES_MAX)
1219                 rpc->cons_idx = 0;
1220         spin_unlock_irqrestore(&rpc->e_lock, flags);
1221
1222         return 1;
1223 }
1224
1225 /**
1226  * aer_isr - consume errors detected by root port
1227  * @work: definition of this work item
1228  *
1229  * Invoked, as DPC, when root port records new detected error
1230  */
1231 static void aer_isr(struct work_struct *work)
1232 {
1233         struct aer_rpc *rpc = container_of(work, struct aer_rpc, dpc_handler);
1234         struct aer_err_source uninitialized_var(e_src);
1235
1236         mutex_lock(&rpc->rpc_mutex);
1237         while (get_e_source(rpc, &e_src))
1238                 aer_isr_one_error(rpc, &e_src);
1239         mutex_unlock(&rpc->rpc_mutex);
1240 }
1241
1242 /**
1243  * aer_irq - Root Port's ISR
1244  * @irq: IRQ assigned to Root Port
1245  * @context: pointer to Root Port data structure
1246  *
1247  * Invoked when Root Port detects AER messages.
1248  */
1249 irqreturn_t aer_irq(int irq, void *context)
1250 {
1251         unsigned int status, id;
1252         struct pcie_device *pdev = (struct pcie_device *)context;
1253         struct aer_rpc *rpc = get_service_data(pdev);
1254         int next_prod_idx;
1255         unsigned long flags;
1256         int pos;
1257
1258         pos = pdev->port->aer_cap;
1259         /*
1260          * Must lock access to Root Error Status Reg, Root Error ID Reg,
1261          * and Root error producer/consumer index
1262          */
1263         spin_lock_irqsave(&rpc->e_lock, flags);
1264
1265         /* Read error status */
1266         pci_read_config_dword(pdev->port, pos + PCI_ERR_ROOT_STATUS, &status);
1267         if (!(status & (PCI_ERR_ROOT_UNCOR_RCV|PCI_ERR_ROOT_COR_RCV))) {
1268                 spin_unlock_irqrestore(&rpc->e_lock, flags);
1269                 return IRQ_NONE;
1270         }
1271
1272         /* Read error source and clear error status */
1273         pci_read_config_dword(pdev->port, pos + PCI_ERR_ROOT_ERR_SRC, &id);
1274         pci_write_config_dword(pdev->port, pos + PCI_ERR_ROOT_STATUS, status);
1275
1276         /* Store error source for later DPC handler */
1277         next_prod_idx = rpc->prod_idx + 1;
1278         if (next_prod_idx == AER_ERROR_SOURCES_MAX)
1279                 next_prod_idx = 0;
1280         if (next_prod_idx == rpc->cons_idx) {
1281                 /*
1282                  * Error Storm Condition - possibly the same error occurred.
1283                  * Drop the error.
1284                  */
1285                 spin_unlock_irqrestore(&rpc->e_lock, flags);
1286                 return IRQ_HANDLED;
1287         }
1288         rpc->e_sources[rpc->prod_idx].status =  status;
1289         rpc->e_sources[rpc->prod_idx].id = id;
1290         rpc->prod_idx = next_prod_idx;
1291         spin_unlock_irqrestore(&rpc->e_lock, flags);
1292
1293         /*  Invoke DPC handler */
1294         schedule_work(&rpc->dpc_handler);
1295
1296         return IRQ_HANDLED;
1297 }
1298 EXPORT_SYMBOL_GPL(aer_irq);
1299
1300 static int set_device_error_reporting(struct pci_dev *dev, void *data)
1301 {
1302         bool enable = *((bool *)data);
1303         int type = pci_pcie_type(dev);
1304
1305         if ((type == PCI_EXP_TYPE_ROOT_PORT) ||
1306             (type == PCI_EXP_TYPE_UPSTREAM) ||
1307             (type == PCI_EXP_TYPE_DOWNSTREAM)) {
1308                 if (enable)
1309                         pci_enable_pcie_error_reporting(dev);
1310                 else
1311                         pci_disable_pcie_error_reporting(dev);
1312         }
1313
1314         if (enable)
1315                 pcie_set_ecrc_checking(dev);
1316
1317         return 0;
1318 }
1319
1320 /**
1321  * set_downstream_devices_error_reporting - enable/disable the error reporting  bits on the root port and its downstream ports.
1322  * @dev: pointer to root port's pci_dev data structure
1323  * @enable: true = enable error reporting, false = disable error reporting.
1324  */
1325 static void set_downstream_devices_error_reporting(struct pci_dev *dev,
1326                                                    bool enable)
1327 {
1328         set_device_error_reporting(dev, &enable);
1329
1330         if (!dev->subordinate)
1331                 return;
1332         pci_walk_bus(dev->subordinate, set_device_error_reporting, &enable);
1333 }
1334
1335 /**
1336  * aer_enable_rootport - enable Root Port's interrupts when receiving messages
1337  * @rpc: pointer to a Root Port data structure
1338  *
1339  * Invoked when PCIe bus loads AER service driver.
1340  */
1341 static void aer_enable_rootport(struct aer_rpc *rpc)
1342 {
1343         struct pci_dev *pdev = rpc->rpd;
1344         int aer_pos;
1345         u16 reg16;
1346         u32 reg32;
1347
1348         /* Clear PCIe Capability's Device Status */
1349         pcie_capability_read_word(pdev, PCI_EXP_DEVSTA, &reg16);
1350         pcie_capability_write_word(pdev, PCI_EXP_DEVSTA, reg16);
1351
1352         /* Disable system error generation in response to error messages */
1353         pcie_capability_clear_word(pdev, PCI_EXP_RTCTL,
1354                                    SYSTEM_ERROR_INTR_ON_MESG_MASK);
1355
1356         aer_pos = pdev->aer_cap;
1357         /* Clear error status */
1358         pci_read_config_dword(pdev, aer_pos + PCI_ERR_ROOT_STATUS, &reg32);
1359         pci_write_config_dword(pdev, aer_pos + PCI_ERR_ROOT_STATUS, reg32);
1360         pci_read_config_dword(pdev, aer_pos + PCI_ERR_COR_STATUS, &reg32);
1361         pci_write_config_dword(pdev, aer_pos + PCI_ERR_COR_STATUS, reg32);
1362         pci_read_config_dword(pdev, aer_pos + PCI_ERR_UNCOR_STATUS, &reg32);
1363         pci_write_config_dword(pdev, aer_pos + PCI_ERR_UNCOR_STATUS, reg32);
1364
1365         /*
1366          * Enable error reporting for the root port device and downstream port
1367          * devices.
1368          */
1369         set_downstream_devices_error_reporting(pdev, true);
1370
1371         /* Enable Root Port's interrupt in response to error messages */
1372         pci_read_config_dword(pdev, aer_pos + PCI_ERR_ROOT_COMMAND, &reg32);
1373         reg32 |= ROOT_PORT_INTR_ON_MESG_MASK;
1374         pci_write_config_dword(pdev, aer_pos + PCI_ERR_ROOT_COMMAND, reg32);
1375 }
1376
1377 /**
1378  * aer_disable_rootport - disable Root Port's interrupts when receiving messages
1379  * @rpc: pointer to a Root Port data structure
1380  *
1381  * Invoked when PCIe bus unloads AER service driver.
1382  */
1383 static void aer_disable_rootport(struct aer_rpc *rpc)
1384 {
1385         struct pci_dev *pdev = rpc->rpd;
1386         u32 reg32;
1387         int pos;
1388
1389         /*
1390          * Disable error reporting for the root port device and downstream port
1391          * devices.
1392          */
1393         set_downstream_devices_error_reporting(pdev, false);
1394
1395         pos = pdev->aer_cap;
1396         /* Disable Root's interrupt in response to error messages */
1397         pci_read_config_dword(pdev, pos + PCI_ERR_ROOT_COMMAND, &reg32);
1398         reg32 &= ~ROOT_PORT_INTR_ON_MESG_MASK;
1399         pci_write_config_dword(pdev, pos + PCI_ERR_ROOT_COMMAND, reg32);
1400
1401         /* Clear Root's error status reg */
1402         pci_read_config_dword(pdev, pos + PCI_ERR_ROOT_STATUS, &reg32);
1403         pci_write_config_dword(pdev, pos + PCI_ERR_ROOT_STATUS, reg32);
1404 }
1405
1406 /**
1407  * aer_alloc_rpc - allocate Root Port data structure
1408  * @dev: pointer to the pcie_dev data structure
1409  *
1410  * Invoked when Root Port's AER service is loaded.
1411  */
1412 static struct aer_rpc *aer_alloc_rpc(struct pcie_device *dev)
1413 {
1414         struct aer_rpc *rpc;
1415
1416         rpc = kzalloc(sizeof(struct aer_rpc), GFP_KERNEL);
1417         if (!rpc)
1418                 return NULL;
1419
1420         /* Initialize Root lock access, e_lock, to Root Error Status Reg */
1421         spin_lock_init(&rpc->e_lock);
1422
1423         rpc->rpd = dev->port;
1424         INIT_WORK(&rpc->dpc_handler, aer_isr);
1425         mutex_init(&rpc->rpc_mutex);
1426
1427         /* Use PCIe bus function to store rpc into PCIe device */
1428         set_service_data(dev, rpc);
1429
1430         return rpc;
1431 }
1432
1433 /**
1434  * aer_remove - clean up resources
1435  * @dev: pointer to the pcie_dev data structure
1436  *
1437  * Invoked when PCI Express bus unloads or AER probe fails.
1438  */
1439 static void aer_remove(struct pcie_device *dev)
1440 {
1441         struct aer_rpc *rpc = get_service_data(dev);
1442
1443         if (rpc) {
1444                 /* If register interrupt service, it must be free. */
1445                 if (rpc->isr)
1446                         free_irq(dev->irq, dev);
1447
1448                 flush_work(&rpc->dpc_handler);
1449                 aer_disable_rootport(rpc);
1450                 kfree(rpc);
1451                 set_service_data(dev, NULL);
1452         }
1453 }
1454
1455 /**
1456  * aer_probe - initialize resources
1457  * @dev: pointer to the pcie_dev data structure
1458  *
1459  * Invoked when PCI Express bus loads AER service driver.
1460  */
1461 static int aer_probe(struct pcie_device *dev)
1462 {
1463         int status;
1464         struct aer_rpc *rpc;
1465         struct device *device = &dev->port->dev;
1466
1467         /* Alloc rpc data structure */
1468         rpc = aer_alloc_rpc(dev);
1469         if (!rpc) {
1470                 dev_printk(KERN_DEBUG, device, "alloc AER rpc failed\n");
1471                 aer_remove(dev);
1472                 return -ENOMEM;
1473         }
1474
1475         /* Request IRQ ISR */
1476         status = request_irq(dev->irq, aer_irq, IRQF_SHARED, "aerdrv", dev);
1477         if (status) {
1478                 dev_printk(KERN_DEBUG, device, "request AER IRQ %d failed\n",
1479                            dev->irq);
1480                 aer_remove(dev);
1481                 return status;
1482         }
1483
1484         rpc->isr = 1;
1485
1486         aer_enable_rootport(rpc);
1487         dev_info(device, "AER enabled with IRQ %d\n", dev->irq);
1488         return 0;
1489 }
1490
1491 /**
1492  * aer_root_reset - reset link on Root Port
1493  * @dev: pointer to Root Port's pci_dev data structure
1494  *
1495  * Invoked by Port Bus driver when performing link reset at Root Port.
1496  */
1497 static pci_ers_result_t aer_root_reset(struct pci_dev *dev)
1498 {
1499         u32 reg32;
1500         int pos;
1501
1502         pos = dev->aer_cap;
1503
1504         /* Disable Root's interrupt in response to error messages */
1505         pci_read_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, &reg32);
1506         reg32 &= ~ROOT_PORT_INTR_ON_MESG_MASK;
1507         pci_write_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, reg32);
1508
1509         pci_reset_bridge_secondary_bus(dev);
1510         pci_printk(KERN_DEBUG, dev, "Root Port link has been reset\n");
1511
1512         /* Clear Root Error Status */
1513         pci_read_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, &reg32);
1514         pci_write_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, reg32);
1515
1516         /* Enable Root Port's interrupt in response to error messages */
1517         pci_read_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, &reg32);
1518         reg32 |= ROOT_PORT_INTR_ON_MESG_MASK;
1519         pci_write_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND, reg32);
1520
1521         return PCI_ERS_RESULT_RECOVERED;
1522 }
1523
1524 /**
1525  * aer_error_resume - clean up corresponding error status bits
1526  * @dev: pointer to Root Port's pci_dev data structure
1527  *
1528  * Invoked by Port Bus driver during nonfatal recovery.
1529  */
1530 static void aer_error_resume(struct pci_dev *dev)
1531 {
1532         int pos;
1533         u32 status, mask;
1534         u16 reg16;
1535
1536         /* Clean up Root device status */
1537         pcie_capability_read_word(dev, PCI_EXP_DEVSTA, &reg16);
1538         pcie_capability_write_word(dev, PCI_EXP_DEVSTA, reg16);
1539
1540         /* Clean AER Root Error Status */
1541         pos = dev->aer_cap;
1542         pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
1543         pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_SEVER, &mask);
1544         status &= ~mask; /* Clear corresponding nonfatal bits */
1545         pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status);
1546 }
1547
1548 static struct pcie_port_service_driver aerdriver = {
1549         .name           = "aer",
1550         .port_type      = PCI_EXP_TYPE_ROOT_PORT,
1551         .service        = PCIE_PORT_SERVICE_AER,
1552
1553         .probe          = aer_probe,
1554         .remove         = aer_remove,
1555         .error_resume   = aer_error_resume,
1556         .reset_link     = aer_root_reset,
1557 };
1558
1559 /**
1560  * aer_service_init - register AER root service driver
1561  *
1562  * Invoked when AER root service driver is loaded.
1563  */
1564 static int __init aer_service_init(void)
1565 {
1566         if (!pci_aer_available() || aer_acpi_firmware_first())
1567                 return -ENXIO;
1568         return pcie_port_service_register(&aerdriver);
1569 }
1570 device_initcall(aer_service_init);