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