xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c (revision 7b1166dee847d5018c1f3cc781218e806078f752)
1 /*
2  * Copyright 2018 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  *
23  */
24 #include <linux/debugfs.h>
25 #include <linux/list.h>
26 #include <linux/module.h>
27 #include <linux/uaccess.h>
28 #include <linux/reboot.h>
29 #include <linux/syscalls.h>
30 #include <linux/pm_runtime.h>
31 #include <linux/list_sort.h>
32 
33 #include "amdgpu.h"
34 #include "amdgpu_ras.h"
35 #include "amdgpu_atomfirmware.h"
36 #include "amdgpu_xgmi.h"
37 #include "ivsrcid/nbio/irqsrcs_nbif_7_4.h"
38 #include "nbio_v4_3.h"
39 #include "nbif_v6_3_1.h"
40 #include "nbio_v7_9.h"
41 #include "atom.h"
42 #include "amdgpu_reset.h"
43 #include "amdgpu_psp.h"
44 
45 #ifdef CONFIG_X86_MCE_AMD
46 #include <asm/mce.h>
47 
48 static bool notifier_registered;
49 #endif
50 static const char *RAS_FS_NAME = "ras";
51 
52 const char *ras_error_string[] = {
53 	"none",
54 	"parity",
55 	"single_correctable",
56 	"multi_uncorrectable",
57 	"poison",
58 };
59 
60 const char *ras_block_string[] = {
61 	"umc",
62 	"sdma",
63 	"gfx",
64 	"mmhub",
65 	"athub",
66 	"pcie_bif",
67 	"hdp",
68 	"xgmi_wafl",
69 	"df",
70 	"smn",
71 	"sem",
72 	"mp0",
73 	"mp1",
74 	"fuse",
75 	"mca",
76 	"vcn",
77 	"jpeg",
78 	"ih",
79 	"mpio",
80 	"mmsch",
81 };
82 
83 const char *ras_mca_block_string[] = {
84 	"mca_mp0",
85 	"mca_mp1",
86 	"mca_mpio",
87 	"mca_iohc",
88 };
89 
90 struct amdgpu_ras_block_list {
91 	/* ras block link */
92 	struct list_head node;
93 
94 	struct amdgpu_ras_block_object *ras_obj;
95 };
96 
97 const char *get_ras_block_str(struct ras_common_if *ras_block)
98 {
99 	if (!ras_block)
100 		return "NULL";
101 
102 	if (ras_block->block >= AMDGPU_RAS_BLOCK_COUNT ||
103 	    ras_block->block >= ARRAY_SIZE(ras_block_string))
104 		return "OUT OF RANGE";
105 
106 	if (ras_block->block == AMDGPU_RAS_BLOCK__MCA)
107 		return ras_mca_block_string[ras_block->sub_block_index];
108 
109 	return ras_block_string[ras_block->block];
110 }
111 
112 #define ras_block_str(_BLOCK_) \
113 	(((_BLOCK_) < ARRAY_SIZE(ras_block_string)) ? ras_block_string[_BLOCK_] : "Out Of Range")
114 
115 #define ras_err_str(i) (ras_error_string[ffs(i)])
116 
117 #define RAS_DEFAULT_FLAGS (AMDGPU_RAS_FLAG_INIT_BY_VBIOS)
118 
119 /* inject address is 52 bits */
120 #define	RAS_UMC_INJECT_ADDR_LIMIT	(0x1ULL << 52)
121 
122 /* typical ECC bad page rate is 1 bad page per 100MB VRAM */
123 #define RAS_BAD_PAGE_COVER              (100 * 1024 * 1024ULL)
124 
125 #define MAX_UMC_POISON_POLLING_TIME_ASYNC  300  //ms
126 
127 #define AMDGPU_RAS_RETIRE_PAGE_INTERVAL 100  //ms
128 
129 #define MAX_FLUSH_RETIRE_DWORK_TIMES  100
130 
131 enum amdgpu_ras_retire_page_reservation {
132 	AMDGPU_RAS_RETIRE_PAGE_RESERVED,
133 	AMDGPU_RAS_RETIRE_PAGE_PENDING,
134 	AMDGPU_RAS_RETIRE_PAGE_FAULT,
135 };
136 
137 atomic_t amdgpu_ras_in_intr = ATOMIC_INIT(0);
138 
139 static bool amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
140 				uint64_t addr);
141 static bool amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
142 				uint64_t addr);
143 #ifdef CONFIG_X86_MCE_AMD
144 static void amdgpu_register_bad_pages_mca_notifier(struct amdgpu_device *adev);
145 struct mce_notifier_adev_list {
146 	struct amdgpu_device *devs[MAX_GPU_INSTANCE];
147 	int num_gpu;
148 };
149 static struct mce_notifier_adev_list mce_adev_list;
150 #endif
151 
152 void amdgpu_ras_set_error_query_ready(struct amdgpu_device *adev, bool ready)
153 {
154 	if (adev && amdgpu_ras_get_context(adev))
155 		amdgpu_ras_get_context(adev)->error_query_ready = ready;
156 }
157 
158 static bool amdgpu_ras_get_error_query_ready(struct amdgpu_device *adev)
159 {
160 	if (adev && amdgpu_ras_get_context(adev))
161 		return amdgpu_ras_get_context(adev)->error_query_ready;
162 
163 	return false;
164 }
165 
166 static int amdgpu_reserve_page_direct(struct amdgpu_device *adev, uint64_t address)
167 {
168 	struct ras_err_data err_data;
169 	struct eeprom_table_record err_rec;
170 	int ret;
171 
172 	if ((address >= adev->gmc.mc_vram_size) ||
173 	    (address >= RAS_UMC_INJECT_ADDR_LIMIT)) {
174 		dev_warn(adev->dev,
175 		         "RAS WARN: input address 0x%llx is invalid.\n",
176 		         address);
177 		return -EINVAL;
178 	}
179 
180 	if (amdgpu_ras_check_bad_page(adev, address)) {
181 		dev_warn(adev->dev,
182 			 "RAS WARN: 0x%llx has already been marked as bad page!\n",
183 			 address);
184 		return 0;
185 	}
186 
187 	ret = amdgpu_ras_error_data_init(&err_data);
188 	if (ret)
189 		return ret;
190 
191 	memset(&err_rec, 0x0, sizeof(struct eeprom_table_record));
192 	err_data.err_addr = &err_rec;
193 	amdgpu_umc_fill_error_record(&err_data, address, address, 0, 0);
194 
195 	if (amdgpu_bad_page_threshold != 0) {
196 		amdgpu_ras_add_bad_pages(adev, err_data.err_addr,
197 					 err_data.err_addr_cnt, false);
198 		amdgpu_ras_save_bad_pages(adev, NULL);
199 	}
200 
201 	amdgpu_ras_error_data_fini(&err_data);
202 
203 	dev_warn(adev->dev, "WARNING: THIS IS ONLY FOR TEST PURPOSES AND WILL CORRUPT RAS EEPROM\n");
204 	dev_warn(adev->dev, "Clear EEPROM:\n");
205 	dev_warn(adev->dev, "    echo 1 > /sys/kernel/debug/dri/0/ras/ras_eeprom_reset\n");
206 
207 	return 0;
208 }
209 
210 static ssize_t amdgpu_ras_debugfs_read(struct file *f, char __user *buf,
211 					size_t size, loff_t *pos)
212 {
213 	struct ras_manager *obj = (struct ras_manager *)file_inode(f)->i_private;
214 	struct ras_query_if info = {
215 		.head = obj->head,
216 	};
217 	ssize_t s;
218 	char val[128];
219 
220 	if (amdgpu_ras_query_error_status(obj->adev, &info))
221 		return -EINVAL;
222 
223 	/* Hardware counter will be reset automatically after the query on Vega20 and Arcturus */
224 	if (amdgpu_ip_version(obj->adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 2) &&
225 	    amdgpu_ip_version(obj->adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 4)) {
226 		if (amdgpu_ras_reset_error_status(obj->adev, info.head.block))
227 			dev_warn(obj->adev->dev, "Failed to reset error counter and error status");
228 	}
229 
230 	s = snprintf(val, sizeof(val), "%s: %lu\n%s: %lu\n",
231 			"ue", info.ue_count,
232 			"ce", info.ce_count);
233 	if (*pos >= s)
234 		return 0;
235 
236 	s -= *pos;
237 	s = min_t(u64, s, size);
238 
239 
240 	if (copy_to_user(buf, &val[*pos], s))
241 		return -EINVAL;
242 
243 	*pos += s;
244 
245 	return s;
246 }
247 
248 static const struct file_operations amdgpu_ras_debugfs_ops = {
249 	.owner = THIS_MODULE,
250 	.read = amdgpu_ras_debugfs_read,
251 	.write = NULL,
252 	.llseek = default_llseek
253 };
254 
255 static int amdgpu_ras_find_block_id_by_name(const char *name, int *block_id)
256 {
257 	int i;
258 
259 	for (i = 0; i < ARRAY_SIZE(ras_block_string); i++) {
260 		*block_id = i;
261 		if (strcmp(name, ras_block_string[i]) == 0)
262 			return 0;
263 	}
264 	return -EINVAL;
265 }
266 
267 static int amdgpu_ras_debugfs_ctrl_parse_data(struct file *f,
268 		const char __user *buf, size_t size,
269 		loff_t *pos, struct ras_debug_if *data)
270 {
271 	ssize_t s = min_t(u64, 64, size);
272 	char str[65];
273 	char block_name[33];
274 	char err[9] = "ue";
275 	int op = -1;
276 	int block_id;
277 	uint32_t sub_block;
278 	u64 address, value;
279 	/* default value is 0 if the mask is not set by user */
280 	u32 instance_mask = 0;
281 
282 	if (*pos)
283 		return -EINVAL;
284 	*pos = size;
285 
286 	memset(str, 0, sizeof(str));
287 	memset(data, 0, sizeof(*data));
288 
289 	if (copy_from_user(str, buf, s))
290 		return -EINVAL;
291 
292 	if (sscanf(str, "disable %32s", block_name) == 1)
293 		op = 0;
294 	else if (sscanf(str, "enable %32s %8s", block_name, err) == 2)
295 		op = 1;
296 	else if (sscanf(str, "inject %32s %8s", block_name, err) == 2)
297 		op = 2;
298 	else if (strstr(str, "retire_page") != NULL)
299 		op = 3;
300 	else if (str[0] && str[1] && str[2] && str[3])
301 		/* ascii string, but commands are not matched. */
302 		return -EINVAL;
303 
304 	if (op != -1) {
305 		if (op == 3) {
306 			if (sscanf(str, "%*s 0x%llx", &address) != 1 &&
307 			    sscanf(str, "%*s %llu", &address) != 1)
308 				return -EINVAL;
309 
310 			data->op = op;
311 			data->inject.address = address;
312 
313 			return 0;
314 		}
315 
316 		if (amdgpu_ras_find_block_id_by_name(block_name, &block_id))
317 			return -EINVAL;
318 
319 		data->head.block = block_id;
320 		/* only ue, ce and poison errors are supported */
321 		if (!memcmp("ue", err, 2))
322 			data->head.type = AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE;
323 		else if (!memcmp("ce", err, 2))
324 			data->head.type = AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE;
325 		else if (!memcmp("poison", err, 6))
326 			data->head.type = AMDGPU_RAS_ERROR__POISON;
327 		else
328 			return -EINVAL;
329 
330 		data->op = op;
331 
332 		if (op == 2) {
333 			if (sscanf(str, "%*s %*s %*s 0x%x 0x%llx 0x%llx 0x%x",
334 				   &sub_block, &address, &value, &instance_mask) != 4 &&
335 			    sscanf(str, "%*s %*s %*s %u %llu %llu %u",
336 				   &sub_block, &address, &value, &instance_mask) != 4 &&
337 				sscanf(str, "%*s %*s %*s 0x%x 0x%llx 0x%llx",
338 				   &sub_block, &address, &value) != 3 &&
339 			    sscanf(str, "%*s %*s %*s %u %llu %llu",
340 				   &sub_block, &address, &value) != 3)
341 				return -EINVAL;
342 			data->head.sub_block_index = sub_block;
343 			data->inject.address = address;
344 			data->inject.value = value;
345 			data->inject.instance_mask = instance_mask;
346 		}
347 	} else {
348 		if (size < sizeof(*data))
349 			return -EINVAL;
350 
351 		if (copy_from_user(data, buf, sizeof(*data)))
352 			return -EINVAL;
353 	}
354 
355 	return 0;
356 }
357 
358 static void amdgpu_ras_instance_mask_check(struct amdgpu_device *adev,
359 				struct ras_debug_if *data)
360 {
361 	int num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
362 	uint32_t mask, inst_mask = data->inject.instance_mask;
363 
364 	/* no need to set instance mask if there is only one instance */
365 	if (num_xcc <= 1 && inst_mask) {
366 		data->inject.instance_mask = 0;
367 		dev_dbg(adev->dev,
368 			"RAS inject mask(0x%x) isn't supported and force it to 0.\n",
369 			inst_mask);
370 
371 		return;
372 	}
373 
374 	switch (data->head.block) {
375 	case AMDGPU_RAS_BLOCK__GFX:
376 		mask = GENMASK(num_xcc - 1, 0);
377 		break;
378 	case AMDGPU_RAS_BLOCK__SDMA:
379 		mask = GENMASK(adev->sdma.num_instances - 1, 0);
380 		break;
381 	case AMDGPU_RAS_BLOCK__VCN:
382 	case AMDGPU_RAS_BLOCK__JPEG:
383 		mask = GENMASK(adev->vcn.num_vcn_inst - 1, 0);
384 		break;
385 	default:
386 		mask = inst_mask;
387 		break;
388 	}
389 
390 	/* remove invalid bits in instance mask */
391 	data->inject.instance_mask &= mask;
392 	if (inst_mask != data->inject.instance_mask)
393 		dev_dbg(adev->dev,
394 			"Adjust RAS inject mask 0x%x to 0x%x\n",
395 			inst_mask, data->inject.instance_mask);
396 }
397 
398 /**
399  * DOC: AMDGPU RAS debugfs control interface
400  *
401  * The control interface accepts struct ras_debug_if which has two members.
402  *
403  * First member: ras_debug_if::head or ras_debug_if::inject.
404  *
405  * head is used to indicate which IP block will be under control.
406  *
407  * head has four members, they are block, type, sub_block_index, name.
408  * block: which IP will be under control.
409  * type: what kind of error will be enabled/disabled/injected.
410  * sub_block_index: some IPs have subcomponets. say, GFX, sDMA.
411  * name: the name of IP.
412  *
413  * inject has three more members than head, they are address, value and mask.
414  * As their names indicate, inject operation will write the
415  * value to the address.
416  *
417  * The second member: struct ras_debug_if::op.
418  * It has three kinds of operations.
419  *
420  * - 0: disable RAS on the block. Take ::head as its data.
421  * - 1: enable RAS on the block. Take ::head as its data.
422  * - 2: inject errors on the block. Take ::inject as its data.
423  *
424  * How to use the interface?
425  *
426  * In a program
427  *
428  * Copy the struct ras_debug_if in your code and initialize it.
429  * Write the struct to the control interface.
430  *
431  * From shell
432  *
433  * .. code-block:: bash
434  *
435  *	echo "disable <block>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
436  *	echo "enable  <block> <error>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
437  *	echo "inject  <block> <error> <sub-block> <address> <value> <mask>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
438  *
439  * Where N, is the card which you want to affect.
440  *
441  * "disable" requires only the block.
442  * "enable" requires the block and error type.
443  * "inject" requires the block, error type, address, and value.
444  *
445  * The block is one of: umc, sdma, gfx, etc.
446  *	see ras_block_string[] for details
447  *
448  * The error type is one of: ue, ce and poison where,
449  *	ue is multi-uncorrectable
450  *	ce is single-correctable
451  *	poison is poison
452  *
453  * The sub-block is a the sub-block index, pass 0 if there is no sub-block.
454  * The address and value are hexadecimal numbers, leading 0x is optional.
455  * The mask means instance mask, is optional, default value is 0x1.
456  *
457  * For instance,
458  *
459  * .. code-block:: bash
460  *
461  *	echo inject umc ue 0x0 0x0 0x0 > /sys/kernel/debug/dri/0/ras/ras_ctrl
462  *	echo inject umc ce 0 0 0 3 > /sys/kernel/debug/dri/0/ras/ras_ctrl
463  *	echo disable umc > /sys/kernel/debug/dri/0/ras/ras_ctrl
464  *
465  * How to check the result of the operation?
466  *
467  * To check disable/enable, see "ras" features at,
468  * /sys/class/drm/card[0/1/2...]/device/ras/features
469  *
470  * To check inject, see the corresponding error count at,
471  * /sys/class/drm/card[0/1/2...]/device/ras/[gfx|sdma|umc|...]_err_count
472  *
473  * .. note::
474  *	Operations are only allowed on blocks which are supported.
475  *	Check the "ras" mask at /sys/module/amdgpu/parameters/ras_mask
476  *	to see which blocks support RAS on a particular asic.
477  *
478  */
479 static ssize_t amdgpu_ras_debugfs_ctrl_write(struct file *f,
480 					     const char __user *buf,
481 					     size_t size, loff_t *pos)
482 {
483 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
484 	struct ras_debug_if data;
485 	int ret = 0;
486 
487 	if (!amdgpu_ras_get_error_query_ready(adev)) {
488 		dev_warn(adev->dev, "RAS WARN: error injection "
489 				"currently inaccessible\n");
490 		return size;
491 	}
492 
493 	ret = amdgpu_ras_debugfs_ctrl_parse_data(f, buf, size, pos, &data);
494 	if (ret)
495 		return ret;
496 
497 	if (data.op == 3) {
498 		ret = amdgpu_reserve_page_direct(adev, data.inject.address);
499 		if (!ret)
500 			return size;
501 		else
502 			return ret;
503 	}
504 
505 	if (!amdgpu_ras_is_supported(adev, data.head.block))
506 		return -EINVAL;
507 
508 	switch (data.op) {
509 	case 0:
510 		ret = amdgpu_ras_feature_enable(adev, &data.head, 0);
511 		break;
512 	case 1:
513 		ret = amdgpu_ras_feature_enable(adev, &data.head, 1);
514 		break;
515 	case 2:
516 		if ((data.inject.address >= adev->gmc.mc_vram_size &&
517 		    adev->gmc.mc_vram_size) ||
518 		    (data.inject.address >= RAS_UMC_INJECT_ADDR_LIMIT)) {
519 			dev_warn(adev->dev, "RAS WARN: input address "
520 					"0x%llx is invalid.",
521 					data.inject.address);
522 			ret = -EINVAL;
523 			break;
524 		}
525 
526 		/* umc ce/ue error injection for a bad page is not allowed */
527 		if ((data.head.block == AMDGPU_RAS_BLOCK__UMC) &&
528 		    amdgpu_ras_check_bad_page(adev, data.inject.address)) {
529 			dev_warn(adev->dev, "RAS WARN: inject: 0x%llx has "
530 				 "already been marked as bad!\n",
531 				 data.inject.address);
532 			break;
533 		}
534 
535 		amdgpu_ras_instance_mask_check(adev, &data);
536 
537 		/* data.inject.address is offset instead of absolute gpu address */
538 		ret = amdgpu_ras_error_inject(adev, &data.inject);
539 		break;
540 	default:
541 		ret = -EINVAL;
542 		break;
543 	}
544 
545 	if (ret)
546 		return ret;
547 
548 	return size;
549 }
550 
551 /**
552  * DOC: AMDGPU RAS debugfs EEPROM table reset interface
553  *
554  * Some boards contain an EEPROM which is used to persistently store a list of
555  * bad pages which experiences ECC errors in vram.  This interface provides
556  * a way to reset the EEPROM, e.g., after testing error injection.
557  *
558  * Usage:
559  *
560  * .. code-block:: bash
561  *
562  *	echo 1 > ../ras/ras_eeprom_reset
563  *
564  * will reset EEPROM table to 0 entries.
565  *
566  */
567 static ssize_t amdgpu_ras_debugfs_eeprom_write(struct file *f,
568 					       const char __user *buf,
569 					       size_t size, loff_t *pos)
570 {
571 	struct amdgpu_device *adev =
572 		(struct amdgpu_device *)file_inode(f)->i_private;
573 	int ret;
574 
575 	ret = amdgpu_ras_eeprom_reset_table(
576 		&(amdgpu_ras_get_context(adev)->eeprom_control));
577 
578 	if (!ret) {
579 		/* Something was written to EEPROM.
580 		 */
581 		amdgpu_ras_get_context(adev)->flags = RAS_DEFAULT_FLAGS;
582 		return size;
583 	} else {
584 		return ret;
585 	}
586 }
587 
588 static const struct file_operations amdgpu_ras_debugfs_ctrl_ops = {
589 	.owner = THIS_MODULE,
590 	.read = NULL,
591 	.write = amdgpu_ras_debugfs_ctrl_write,
592 	.llseek = default_llseek
593 };
594 
595 static const struct file_operations amdgpu_ras_debugfs_eeprom_ops = {
596 	.owner = THIS_MODULE,
597 	.read = NULL,
598 	.write = amdgpu_ras_debugfs_eeprom_write,
599 	.llseek = default_llseek
600 };
601 
602 /**
603  * DOC: AMDGPU RAS sysfs Error Count Interface
604  *
605  * It allows the user to read the error count for each IP block on the gpu through
606  * /sys/class/drm/card[0/1/2...]/device/ras/[gfx/sdma/...]_err_count
607  *
608  * It outputs the multiple lines which report the uncorrected (ue) and corrected
609  * (ce) error counts.
610  *
611  * The format of one line is below,
612  *
613  * [ce|ue]: count
614  *
615  * Example:
616  *
617  * .. code-block:: bash
618  *
619  *	ue: 0
620  *	ce: 1
621  *
622  */
623 static ssize_t amdgpu_ras_sysfs_read(struct device *dev,
624 		struct device_attribute *attr, char *buf)
625 {
626 	struct ras_manager *obj = container_of(attr, struct ras_manager, sysfs_attr);
627 	struct ras_query_if info = {
628 		.head = obj->head,
629 	};
630 
631 	if (!amdgpu_ras_get_error_query_ready(obj->adev))
632 		return sysfs_emit(buf, "Query currently inaccessible\n");
633 
634 	if (amdgpu_ras_query_error_status(obj->adev, &info))
635 		return -EINVAL;
636 
637 	if (amdgpu_ip_version(obj->adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 2) &&
638 	    amdgpu_ip_version(obj->adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 4)) {
639 		if (amdgpu_ras_reset_error_status(obj->adev, info.head.block))
640 			dev_warn(obj->adev->dev, "Failed to reset error counter and error status");
641 	}
642 
643 	if (info.head.block == AMDGPU_RAS_BLOCK__UMC)
644 		return sysfs_emit(buf, "%s: %lu\n%s: %lu\n%s: %lu\n", "ue", info.ue_count,
645 				"ce", info.ce_count, "de", info.de_count);
646 	else
647 		return sysfs_emit(buf, "%s: %lu\n%s: %lu\n", "ue", info.ue_count,
648 				"ce", info.ce_count);
649 }
650 
651 /* obj begin */
652 
653 #define get_obj(obj) do { (obj)->use++; } while (0)
654 #define alive_obj(obj) ((obj)->use)
655 
656 static inline void put_obj(struct ras_manager *obj)
657 {
658 	if (obj && (--obj->use == 0)) {
659 		list_del(&obj->node);
660 		amdgpu_ras_error_data_fini(&obj->err_data);
661 	}
662 
663 	if (obj && (obj->use < 0))
664 		DRM_ERROR("RAS ERROR: Unbalance obj(%s) use\n", get_ras_block_str(&obj->head));
665 }
666 
667 /* make one obj and return it. */
668 static struct ras_manager *amdgpu_ras_create_obj(struct amdgpu_device *adev,
669 		struct ras_common_if *head)
670 {
671 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
672 	struct ras_manager *obj;
673 
674 	if (!adev->ras_enabled || !con)
675 		return NULL;
676 
677 	if (head->block >= AMDGPU_RAS_BLOCK_COUNT)
678 		return NULL;
679 
680 	if (head->block == AMDGPU_RAS_BLOCK__MCA) {
681 		if (head->sub_block_index >= AMDGPU_RAS_MCA_BLOCK__LAST)
682 			return NULL;
683 
684 		obj = &con->objs[AMDGPU_RAS_BLOCK__LAST + head->sub_block_index];
685 	} else
686 		obj = &con->objs[head->block];
687 
688 	/* already exist. return obj? */
689 	if (alive_obj(obj))
690 		return NULL;
691 
692 	if (amdgpu_ras_error_data_init(&obj->err_data))
693 		return NULL;
694 
695 	obj->head = *head;
696 	obj->adev = adev;
697 	list_add(&obj->node, &con->head);
698 	get_obj(obj);
699 
700 	return obj;
701 }
702 
703 /* return an obj equal to head, or the first when head is NULL */
704 struct ras_manager *amdgpu_ras_find_obj(struct amdgpu_device *adev,
705 		struct ras_common_if *head)
706 {
707 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
708 	struct ras_manager *obj;
709 	int i;
710 
711 	if (!adev->ras_enabled || !con)
712 		return NULL;
713 
714 	if (head) {
715 		if (head->block >= AMDGPU_RAS_BLOCK_COUNT)
716 			return NULL;
717 
718 		if (head->block == AMDGPU_RAS_BLOCK__MCA) {
719 			if (head->sub_block_index >= AMDGPU_RAS_MCA_BLOCK__LAST)
720 				return NULL;
721 
722 			obj = &con->objs[AMDGPU_RAS_BLOCK__LAST + head->sub_block_index];
723 		} else
724 			obj = &con->objs[head->block];
725 
726 		if (alive_obj(obj))
727 			return obj;
728 	} else {
729 		for (i = 0; i < AMDGPU_RAS_BLOCK_COUNT + AMDGPU_RAS_MCA_BLOCK_COUNT; i++) {
730 			obj = &con->objs[i];
731 			if (alive_obj(obj))
732 				return obj;
733 		}
734 	}
735 
736 	return NULL;
737 }
738 /* obj end */
739 
740 /* feature ctl begin */
741 static int amdgpu_ras_is_feature_allowed(struct amdgpu_device *adev,
742 					 struct ras_common_if *head)
743 {
744 	return adev->ras_hw_enabled & BIT(head->block);
745 }
746 
747 static int amdgpu_ras_is_feature_enabled(struct amdgpu_device *adev,
748 		struct ras_common_if *head)
749 {
750 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
751 
752 	return con->features & BIT(head->block);
753 }
754 
755 /*
756  * if obj is not created, then create one.
757  * set feature enable flag.
758  */
759 static int __amdgpu_ras_feature_enable(struct amdgpu_device *adev,
760 		struct ras_common_if *head, int enable)
761 {
762 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
763 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
764 
765 	/* If hardware does not support ras, then do not create obj.
766 	 * But if hardware support ras, we can create the obj.
767 	 * Ras framework checks con->hw_supported to see if it need do
768 	 * corresponding initialization.
769 	 * IP checks con->support to see if it need disable ras.
770 	 */
771 	if (!amdgpu_ras_is_feature_allowed(adev, head))
772 		return 0;
773 
774 	if (enable) {
775 		if (!obj) {
776 			obj = amdgpu_ras_create_obj(adev, head);
777 			if (!obj)
778 				return -EINVAL;
779 		} else {
780 			/* In case we create obj somewhere else */
781 			get_obj(obj);
782 		}
783 		con->features |= BIT(head->block);
784 	} else {
785 		if (obj && amdgpu_ras_is_feature_enabled(adev, head)) {
786 			con->features &= ~BIT(head->block);
787 			put_obj(obj);
788 		}
789 	}
790 
791 	return 0;
792 }
793 
794 /* wrapper of psp_ras_enable_features */
795 int amdgpu_ras_feature_enable(struct amdgpu_device *adev,
796 		struct ras_common_if *head, bool enable)
797 {
798 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
799 	union ta_ras_cmd_input *info;
800 	int ret;
801 
802 	if (!con)
803 		return -EINVAL;
804 
805 	/* For non-gfx ip, do not enable ras feature if it is not allowed */
806 	/* For gfx ip, regardless of feature support status, */
807 	/* Force issue enable or disable ras feature commands */
808 	if (head->block != AMDGPU_RAS_BLOCK__GFX &&
809 	    !amdgpu_ras_is_feature_allowed(adev, head))
810 		return 0;
811 
812 	/* Only enable gfx ras feature from host side */
813 	if (head->block == AMDGPU_RAS_BLOCK__GFX &&
814 	    !amdgpu_sriov_vf(adev) &&
815 	    !amdgpu_ras_intr_triggered()) {
816 		info = kzalloc(sizeof(union ta_ras_cmd_input), GFP_KERNEL);
817 		if (!info)
818 			return -ENOMEM;
819 
820 		if (!enable) {
821 			info->disable_features = (struct ta_ras_disable_features_input) {
822 				.block_id =  amdgpu_ras_block_to_ta(head->block),
823 				.error_type = amdgpu_ras_error_to_ta(head->type),
824 			};
825 		} else {
826 			info->enable_features = (struct ta_ras_enable_features_input) {
827 				.block_id =  amdgpu_ras_block_to_ta(head->block),
828 				.error_type = amdgpu_ras_error_to_ta(head->type),
829 			};
830 		}
831 
832 		ret = psp_ras_enable_features(&adev->psp, info, enable);
833 		if (ret) {
834 			dev_err(adev->dev, "ras %s %s failed poison:%d ret:%d\n",
835 				enable ? "enable":"disable",
836 				get_ras_block_str(head),
837 				amdgpu_ras_is_poison_mode_supported(adev), ret);
838 			kfree(info);
839 			return ret;
840 		}
841 
842 		kfree(info);
843 	}
844 
845 	/* setup the obj */
846 	__amdgpu_ras_feature_enable(adev, head, enable);
847 
848 	return 0;
849 }
850 
851 /* Only used in device probe stage and called only once. */
852 int amdgpu_ras_feature_enable_on_boot(struct amdgpu_device *adev,
853 		struct ras_common_if *head, bool enable)
854 {
855 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
856 	int ret;
857 
858 	if (!con)
859 		return -EINVAL;
860 
861 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
862 		if (enable) {
863 			/* There is no harm to issue a ras TA cmd regardless of
864 			 * the currecnt ras state.
865 			 * If current state == target state, it will do nothing
866 			 * But sometimes it requests driver to reset and repost
867 			 * with error code -EAGAIN.
868 			 */
869 			ret = amdgpu_ras_feature_enable(adev, head, 1);
870 			/* With old ras TA, we might fail to enable ras.
871 			 * Log it and just setup the object.
872 			 * TODO need remove this WA in the future.
873 			 */
874 			if (ret == -EINVAL) {
875 				ret = __amdgpu_ras_feature_enable(adev, head, 1);
876 				if (!ret)
877 					dev_info(adev->dev,
878 						"RAS INFO: %s setup object\n",
879 						get_ras_block_str(head));
880 			}
881 		} else {
882 			/* setup the object then issue a ras TA disable cmd.*/
883 			ret = __amdgpu_ras_feature_enable(adev, head, 1);
884 			if (ret)
885 				return ret;
886 
887 			/* gfx block ras disable cmd must send to ras-ta */
888 			if (head->block == AMDGPU_RAS_BLOCK__GFX)
889 				con->features |= BIT(head->block);
890 
891 			ret = amdgpu_ras_feature_enable(adev, head, 0);
892 
893 			/* clean gfx block ras features flag */
894 			if (adev->ras_enabled && head->block == AMDGPU_RAS_BLOCK__GFX)
895 				con->features &= ~BIT(head->block);
896 		}
897 	} else
898 		ret = amdgpu_ras_feature_enable(adev, head, enable);
899 
900 	return ret;
901 }
902 
903 static int amdgpu_ras_disable_all_features(struct amdgpu_device *adev,
904 		bool bypass)
905 {
906 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
907 	struct ras_manager *obj, *tmp;
908 
909 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
910 		/* bypass psp.
911 		 * aka just release the obj and corresponding flags
912 		 */
913 		if (bypass) {
914 			if (__amdgpu_ras_feature_enable(adev, &obj->head, 0))
915 				break;
916 		} else {
917 			if (amdgpu_ras_feature_enable(adev, &obj->head, 0))
918 				break;
919 		}
920 	}
921 
922 	return con->features;
923 }
924 
925 static int amdgpu_ras_enable_all_features(struct amdgpu_device *adev,
926 		bool bypass)
927 {
928 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
929 	int i;
930 	const enum amdgpu_ras_error_type default_ras_type = AMDGPU_RAS_ERROR__NONE;
931 
932 	for (i = 0; i < AMDGPU_RAS_BLOCK_COUNT; i++) {
933 		struct ras_common_if head = {
934 			.block = i,
935 			.type = default_ras_type,
936 			.sub_block_index = 0,
937 		};
938 
939 		if (i == AMDGPU_RAS_BLOCK__MCA)
940 			continue;
941 
942 		if (bypass) {
943 			/*
944 			 * bypass psp. vbios enable ras for us.
945 			 * so just create the obj
946 			 */
947 			if (__amdgpu_ras_feature_enable(adev, &head, 1))
948 				break;
949 		} else {
950 			if (amdgpu_ras_feature_enable(adev, &head, 1))
951 				break;
952 		}
953 	}
954 
955 	for (i = 0; i < AMDGPU_RAS_MCA_BLOCK_COUNT; i++) {
956 		struct ras_common_if head = {
957 			.block = AMDGPU_RAS_BLOCK__MCA,
958 			.type = default_ras_type,
959 			.sub_block_index = i,
960 		};
961 
962 		if (bypass) {
963 			/*
964 			 * bypass psp. vbios enable ras for us.
965 			 * so just create the obj
966 			 */
967 			if (__amdgpu_ras_feature_enable(adev, &head, 1))
968 				break;
969 		} else {
970 			if (amdgpu_ras_feature_enable(adev, &head, 1))
971 				break;
972 		}
973 	}
974 
975 	return con->features;
976 }
977 /* feature ctl end */
978 
979 static int amdgpu_ras_block_match_default(struct amdgpu_ras_block_object *block_obj,
980 		enum amdgpu_ras_block block)
981 {
982 	if (!block_obj)
983 		return -EINVAL;
984 
985 	if (block_obj->ras_comm.block == block)
986 		return 0;
987 
988 	return -EINVAL;
989 }
990 
991 static struct amdgpu_ras_block_object *amdgpu_ras_get_ras_block(struct amdgpu_device *adev,
992 					enum amdgpu_ras_block block, uint32_t sub_block_index)
993 {
994 	struct amdgpu_ras_block_list *node, *tmp;
995 	struct amdgpu_ras_block_object *obj;
996 
997 	if (block >= AMDGPU_RAS_BLOCK__LAST)
998 		return NULL;
999 
1000 	list_for_each_entry_safe(node, tmp, &adev->ras_list, node) {
1001 		if (!node->ras_obj) {
1002 			dev_warn(adev->dev, "Warning: abnormal ras list node.\n");
1003 			continue;
1004 		}
1005 
1006 		obj = node->ras_obj;
1007 		if (obj->ras_block_match) {
1008 			if (obj->ras_block_match(obj, block, sub_block_index) == 0)
1009 				return obj;
1010 		} else {
1011 			if (amdgpu_ras_block_match_default(obj, block) == 0)
1012 				return obj;
1013 		}
1014 	}
1015 
1016 	return NULL;
1017 }
1018 
1019 static void amdgpu_ras_get_ecc_info(struct amdgpu_device *adev, struct ras_err_data *err_data)
1020 {
1021 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1022 	int ret = 0;
1023 
1024 	/*
1025 	 * choosing right query method according to
1026 	 * whether smu support query error information
1027 	 */
1028 	ret = amdgpu_dpm_get_ecc_info(adev, (void *)&(ras->umc_ecc));
1029 	if (ret == -EOPNOTSUPP) {
1030 		if (adev->umc.ras && adev->umc.ras->ras_block.hw_ops &&
1031 			adev->umc.ras->ras_block.hw_ops->query_ras_error_count)
1032 			adev->umc.ras->ras_block.hw_ops->query_ras_error_count(adev, err_data);
1033 
1034 		/* umc query_ras_error_address is also responsible for clearing
1035 		 * error status
1036 		 */
1037 		if (adev->umc.ras && adev->umc.ras->ras_block.hw_ops &&
1038 		    adev->umc.ras->ras_block.hw_ops->query_ras_error_address)
1039 			adev->umc.ras->ras_block.hw_ops->query_ras_error_address(adev, err_data);
1040 	} else if (!ret) {
1041 		if (adev->umc.ras &&
1042 			adev->umc.ras->ecc_info_query_ras_error_count)
1043 			adev->umc.ras->ecc_info_query_ras_error_count(adev, err_data);
1044 
1045 		if (adev->umc.ras &&
1046 			adev->umc.ras->ecc_info_query_ras_error_address)
1047 			adev->umc.ras->ecc_info_query_ras_error_address(adev, err_data);
1048 	}
1049 }
1050 
1051 static void amdgpu_ras_error_print_error_data(struct amdgpu_device *adev,
1052 					      struct ras_manager *ras_mgr,
1053 					      struct ras_err_data *err_data,
1054 					      struct ras_query_context *qctx,
1055 					      const char *blk_name,
1056 					      bool is_ue,
1057 					      bool is_de)
1058 {
1059 	struct amdgpu_smuio_mcm_config_info *mcm_info;
1060 	struct ras_err_node *err_node;
1061 	struct ras_err_info *err_info;
1062 	u64 event_id = qctx->evid.event_id;
1063 
1064 	if (is_ue) {
1065 		for_each_ras_error(err_node, err_data) {
1066 			err_info = &err_node->err_info;
1067 			mcm_info = &err_info->mcm_info;
1068 			if (err_info->ue_count) {
1069 				RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d, "
1070 					      "%lld new uncorrectable hardware errors detected in %s block\n",
1071 					      mcm_info->socket_id,
1072 					      mcm_info->die_id,
1073 					      err_info->ue_count,
1074 					      blk_name);
1075 			}
1076 		}
1077 
1078 		for_each_ras_error(err_node, &ras_mgr->err_data) {
1079 			err_info = &err_node->err_info;
1080 			mcm_info = &err_info->mcm_info;
1081 			RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d, "
1082 				      "%lld uncorrectable hardware errors detected in total in %s block\n",
1083 				      mcm_info->socket_id, mcm_info->die_id, err_info->ue_count, blk_name);
1084 		}
1085 
1086 	} else {
1087 		if (is_de) {
1088 			for_each_ras_error(err_node, err_data) {
1089 				err_info = &err_node->err_info;
1090 				mcm_info = &err_info->mcm_info;
1091 				if (err_info->de_count) {
1092 					RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d, "
1093 						      "%lld new deferred hardware errors detected in %s block\n",
1094 						      mcm_info->socket_id,
1095 						      mcm_info->die_id,
1096 						      err_info->de_count,
1097 						      blk_name);
1098 				}
1099 			}
1100 
1101 			for_each_ras_error(err_node, &ras_mgr->err_data) {
1102 				err_info = &err_node->err_info;
1103 				mcm_info = &err_info->mcm_info;
1104 				RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d, "
1105 					      "%lld deferred hardware errors detected in total in %s block\n",
1106 					      mcm_info->socket_id, mcm_info->die_id,
1107 					      err_info->de_count, blk_name);
1108 			}
1109 		} else {
1110 			for_each_ras_error(err_node, err_data) {
1111 				err_info = &err_node->err_info;
1112 				mcm_info = &err_info->mcm_info;
1113 				if (err_info->ce_count) {
1114 					RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d, "
1115 						      "%lld new correctable hardware errors detected in %s block\n",
1116 						      mcm_info->socket_id,
1117 						      mcm_info->die_id,
1118 						      err_info->ce_count,
1119 						      blk_name);
1120 				}
1121 			}
1122 
1123 			for_each_ras_error(err_node, &ras_mgr->err_data) {
1124 				err_info = &err_node->err_info;
1125 				mcm_info = &err_info->mcm_info;
1126 				RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d, "
1127 					      "%lld correctable hardware errors detected in total in %s block\n",
1128 					      mcm_info->socket_id, mcm_info->die_id,
1129 					      err_info->ce_count, blk_name);
1130 			}
1131 		}
1132 	}
1133 }
1134 
1135 static inline bool err_data_has_source_info(struct ras_err_data *data)
1136 {
1137 	return !list_empty(&data->err_node_list);
1138 }
1139 
1140 static void amdgpu_ras_error_generate_report(struct amdgpu_device *adev,
1141 					     struct ras_query_if *query_if,
1142 					     struct ras_err_data *err_data,
1143 					     struct ras_query_context *qctx)
1144 {
1145 	struct ras_manager *ras_mgr = amdgpu_ras_find_obj(adev, &query_if->head);
1146 	const char *blk_name = get_ras_block_str(&query_if->head);
1147 	u64 event_id = qctx->evid.event_id;
1148 
1149 	if (err_data->ce_count) {
1150 		if (err_data_has_source_info(err_data)) {
1151 			amdgpu_ras_error_print_error_data(adev, ras_mgr, err_data, qctx,
1152 							  blk_name, false, false);
1153 		} else if (!adev->aid_mask &&
1154 			   adev->smuio.funcs &&
1155 			   adev->smuio.funcs->get_socket_id &&
1156 			   adev->smuio.funcs->get_die_id) {
1157 			RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d "
1158 				      "%ld correctable hardware errors "
1159 				      "detected in %s block\n",
1160 				      adev->smuio.funcs->get_socket_id(adev),
1161 				      adev->smuio.funcs->get_die_id(adev),
1162 				      ras_mgr->err_data.ce_count,
1163 				      blk_name);
1164 		} else {
1165 			RAS_EVENT_LOG(adev, event_id, "%ld correctable hardware errors "
1166 				      "detected in %s block\n",
1167 				      ras_mgr->err_data.ce_count,
1168 				      blk_name);
1169 		}
1170 	}
1171 
1172 	if (err_data->ue_count) {
1173 		if (err_data_has_source_info(err_data)) {
1174 			amdgpu_ras_error_print_error_data(adev, ras_mgr, err_data, qctx,
1175 							  blk_name, true, false);
1176 		} else if (!adev->aid_mask &&
1177 			   adev->smuio.funcs &&
1178 			   adev->smuio.funcs->get_socket_id &&
1179 			   adev->smuio.funcs->get_die_id) {
1180 			RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d "
1181 				      "%ld uncorrectable hardware errors "
1182 				      "detected in %s block\n",
1183 				      adev->smuio.funcs->get_socket_id(adev),
1184 				      adev->smuio.funcs->get_die_id(adev),
1185 				      ras_mgr->err_data.ue_count,
1186 				      blk_name);
1187 		} else {
1188 			RAS_EVENT_LOG(adev, event_id, "%ld uncorrectable hardware errors "
1189 				      "detected in %s block\n",
1190 				      ras_mgr->err_data.ue_count,
1191 				      blk_name);
1192 		}
1193 	}
1194 
1195 	if (err_data->de_count) {
1196 		if (err_data_has_source_info(err_data)) {
1197 			amdgpu_ras_error_print_error_data(adev, ras_mgr, err_data, qctx,
1198 							  blk_name, false, true);
1199 		} else if (!adev->aid_mask &&
1200 			   adev->smuio.funcs &&
1201 			   adev->smuio.funcs->get_socket_id &&
1202 			   adev->smuio.funcs->get_die_id) {
1203 			RAS_EVENT_LOG(adev, event_id, "socket: %d, die: %d "
1204 				      "%ld deferred hardware errors "
1205 				      "detected in %s block\n",
1206 				      adev->smuio.funcs->get_socket_id(adev),
1207 				      adev->smuio.funcs->get_die_id(adev),
1208 				      ras_mgr->err_data.de_count,
1209 				      blk_name);
1210 		} else {
1211 			RAS_EVENT_LOG(adev, event_id, "%ld deferred hardware errors "
1212 				      "detected in %s block\n",
1213 				      ras_mgr->err_data.de_count,
1214 				      blk_name);
1215 		}
1216 	}
1217 }
1218 
1219 static void amdgpu_ras_virt_error_generate_report(struct amdgpu_device *adev,
1220 						  struct ras_query_if *query_if,
1221 						  struct ras_err_data *err_data,
1222 						  struct ras_query_context *qctx)
1223 {
1224 	unsigned long new_ue, new_ce, new_de;
1225 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &query_if->head);
1226 	const char *blk_name = get_ras_block_str(&query_if->head);
1227 	u64 event_id = qctx->evid.event_id;
1228 
1229 	new_ce = err_data->ce_count - obj->err_data.ce_count;
1230 	new_ue = err_data->ue_count - obj->err_data.ue_count;
1231 	new_de = err_data->de_count - obj->err_data.de_count;
1232 
1233 	if (new_ce) {
1234 		RAS_EVENT_LOG(adev, event_id, "%lu correctable hardware errors "
1235 			      "detected in %s block\n",
1236 			      new_ce,
1237 			      blk_name);
1238 	}
1239 
1240 	if (new_ue) {
1241 		RAS_EVENT_LOG(adev, event_id, "%lu uncorrectable hardware errors "
1242 			      "detected in %s block\n",
1243 			      new_ue,
1244 			      blk_name);
1245 	}
1246 
1247 	if (new_de) {
1248 		RAS_EVENT_LOG(adev, event_id, "%lu deferred hardware errors "
1249 			      "detected in %s block\n",
1250 			      new_de,
1251 			      blk_name);
1252 	}
1253 }
1254 
1255 static void amdgpu_rasmgr_error_data_statistic_update(struct ras_manager *obj, struct ras_err_data *err_data)
1256 {
1257 	struct ras_err_node *err_node;
1258 	struct ras_err_info *err_info;
1259 
1260 	if (err_data_has_source_info(err_data)) {
1261 		for_each_ras_error(err_node, err_data) {
1262 			err_info = &err_node->err_info;
1263 			amdgpu_ras_error_statistic_de_count(&obj->err_data,
1264 					&err_info->mcm_info, err_info->de_count);
1265 			amdgpu_ras_error_statistic_ce_count(&obj->err_data,
1266 					&err_info->mcm_info, err_info->ce_count);
1267 			amdgpu_ras_error_statistic_ue_count(&obj->err_data,
1268 					&err_info->mcm_info, err_info->ue_count);
1269 		}
1270 	} else {
1271 		/* for legacy asic path which doesn't has error source info */
1272 		obj->err_data.ue_count += err_data->ue_count;
1273 		obj->err_data.ce_count += err_data->ce_count;
1274 		obj->err_data.de_count += err_data->de_count;
1275 	}
1276 }
1277 
1278 static void amdgpu_ras_mgr_virt_error_data_statistics_update(struct ras_manager *obj,
1279 							     struct ras_err_data *err_data)
1280 {
1281 	/* Host reports absolute counts */
1282 	obj->err_data.ue_count = err_data->ue_count;
1283 	obj->err_data.ce_count = err_data->ce_count;
1284 	obj->err_data.de_count = err_data->de_count;
1285 }
1286 
1287 static struct ras_manager *get_ras_manager(struct amdgpu_device *adev, enum amdgpu_ras_block blk)
1288 {
1289 	struct ras_common_if head;
1290 
1291 	memset(&head, 0, sizeof(head));
1292 	head.block = blk;
1293 
1294 	return amdgpu_ras_find_obj(adev, &head);
1295 }
1296 
1297 int amdgpu_ras_bind_aca(struct amdgpu_device *adev, enum amdgpu_ras_block blk,
1298 			const struct aca_info *aca_info, void *data)
1299 {
1300 	struct ras_manager *obj;
1301 
1302 	/* in resume phase, no need to create aca fs node */
1303 	if (adev->in_suspend || amdgpu_reset_in_recovery(adev))
1304 		return 0;
1305 
1306 	obj = get_ras_manager(adev, blk);
1307 	if (!obj)
1308 		return -EINVAL;
1309 
1310 	return amdgpu_aca_add_handle(adev, &obj->aca_handle, ras_block_str(blk), aca_info, data);
1311 }
1312 
1313 int amdgpu_ras_unbind_aca(struct amdgpu_device *adev, enum amdgpu_ras_block blk)
1314 {
1315 	struct ras_manager *obj;
1316 
1317 	obj = get_ras_manager(adev, blk);
1318 	if (!obj)
1319 		return -EINVAL;
1320 
1321 	amdgpu_aca_remove_handle(&obj->aca_handle);
1322 
1323 	return 0;
1324 }
1325 
1326 static int amdgpu_aca_log_ras_error_data(struct amdgpu_device *adev, enum amdgpu_ras_block blk,
1327 					 enum aca_error_type type, struct ras_err_data *err_data,
1328 					 struct ras_query_context *qctx)
1329 {
1330 	struct ras_manager *obj;
1331 
1332 	obj = get_ras_manager(adev, blk);
1333 	if (!obj)
1334 		return -EINVAL;
1335 
1336 	return amdgpu_aca_get_error_data(adev, &obj->aca_handle, type, err_data, qctx);
1337 }
1338 
1339 ssize_t amdgpu_ras_aca_sysfs_read(struct device *dev, struct device_attribute *attr,
1340 				  struct aca_handle *handle, char *buf, void *data)
1341 {
1342 	struct ras_manager *obj = container_of(handle, struct ras_manager, aca_handle);
1343 	struct ras_query_if info = {
1344 		.head = obj->head,
1345 	};
1346 
1347 	if (!amdgpu_ras_get_error_query_ready(obj->adev))
1348 		return sysfs_emit(buf, "Query currently inaccessible\n");
1349 
1350 	if (amdgpu_ras_query_error_status(obj->adev, &info))
1351 		return -EINVAL;
1352 
1353 	return sysfs_emit(buf, "%s: %lu\n%s: %lu\n%s: %lu\n", "ue", info.ue_count,
1354 			  "ce", info.ce_count, "de", info.de_count);
1355 }
1356 
1357 static int amdgpu_ras_query_error_status_helper(struct amdgpu_device *adev,
1358 						struct ras_query_if *info,
1359 						struct ras_err_data *err_data,
1360 						struct ras_query_context *qctx,
1361 						unsigned int error_query_mode)
1362 {
1363 	enum amdgpu_ras_block blk = info ? info->head.block : AMDGPU_RAS_BLOCK_COUNT;
1364 	struct amdgpu_ras_block_object *block_obj = NULL;
1365 	int ret;
1366 
1367 	if (blk == AMDGPU_RAS_BLOCK_COUNT)
1368 		return -EINVAL;
1369 
1370 	if (error_query_mode == AMDGPU_RAS_INVALID_ERROR_QUERY)
1371 		return -EINVAL;
1372 
1373 	if (error_query_mode == AMDGPU_RAS_VIRT_ERROR_COUNT_QUERY) {
1374 		return amdgpu_virt_req_ras_err_count(adev, blk, err_data);
1375 	} else if (error_query_mode == AMDGPU_RAS_DIRECT_ERROR_QUERY) {
1376 		if (info->head.block == AMDGPU_RAS_BLOCK__UMC) {
1377 			amdgpu_ras_get_ecc_info(adev, err_data);
1378 		} else {
1379 			block_obj = amdgpu_ras_get_ras_block(adev, info->head.block, 0);
1380 			if (!block_obj || !block_obj->hw_ops) {
1381 				dev_dbg_once(adev->dev, "%s doesn't config RAS function\n",
1382 					     get_ras_block_str(&info->head));
1383 				return -EINVAL;
1384 			}
1385 
1386 			if (block_obj->hw_ops->query_ras_error_count)
1387 				block_obj->hw_ops->query_ras_error_count(adev, err_data);
1388 
1389 			if ((info->head.block == AMDGPU_RAS_BLOCK__SDMA) ||
1390 			    (info->head.block == AMDGPU_RAS_BLOCK__GFX) ||
1391 			    (info->head.block == AMDGPU_RAS_BLOCK__MMHUB)) {
1392 				if (block_obj->hw_ops->query_ras_error_status)
1393 					block_obj->hw_ops->query_ras_error_status(adev);
1394 			}
1395 		}
1396 	} else {
1397 		if (amdgpu_aca_is_enabled(adev)) {
1398 			ret = amdgpu_aca_log_ras_error_data(adev, blk, ACA_ERROR_TYPE_UE, err_data, qctx);
1399 			if (ret)
1400 				return ret;
1401 
1402 			ret = amdgpu_aca_log_ras_error_data(adev, blk, ACA_ERROR_TYPE_CE, err_data, qctx);
1403 			if (ret)
1404 				return ret;
1405 
1406 			ret = amdgpu_aca_log_ras_error_data(adev, blk, ACA_ERROR_TYPE_DEFERRED, err_data, qctx);
1407 			if (ret)
1408 				return ret;
1409 		} else {
1410 			/* FIXME: add code to check return value later */
1411 			amdgpu_mca_smu_log_ras_error(adev, blk, AMDGPU_MCA_ERROR_TYPE_UE, err_data, qctx);
1412 			amdgpu_mca_smu_log_ras_error(adev, blk, AMDGPU_MCA_ERROR_TYPE_CE, err_data, qctx);
1413 		}
1414 	}
1415 
1416 	return 0;
1417 }
1418 
1419 /* query/inject/cure begin */
1420 static int amdgpu_ras_query_error_status_with_event(struct amdgpu_device *adev,
1421 						    struct ras_query_if *info,
1422 						    enum ras_event_type type)
1423 {
1424 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1425 	struct ras_err_data err_data;
1426 	struct ras_query_context qctx;
1427 	unsigned int error_query_mode;
1428 	int ret;
1429 
1430 	if (!obj)
1431 		return -EINVAL;
1432 
1433 	ret = amdgpu_ras_error_data_init(&err_data);
1434 	if (ret)
1435 		return ret;
1436 
1437 	if (!amdgpu_ras_get_error_query_mode(adev, &error_query_mode))
1438 		return -EINVAL;
1439 
1440 	memset(&qctx, 0, sizeof(qctx));
1441 	qctx.evid.type = type;
1442 	qctx.evid.event_id = amdgpu_ras_acquire_event_id(adev, type);
1443 
1444 	if (!down_read_trylock(&adev->reset_domain->sem)) {
1445 		ret = -EIO;
1446 		goto out_fini_err_data;
1447 	}
1448 
1449 	ret = amdgpu_ras_query_error_status_helper(adev, info,
1450 						   &err_data,
1451 						   &qctx,
1452 						   error_query_mode);
1453 	up_read(&adev->reset_domain->sem);
1454 	if (ret)
1455 		goto out_fini_err_data;
1456 
1457 	if (error_query_mode != AMDGPU_RAS_VIRT_ERROR_COUNT_QUERY) {
1458 		amdgpu_rasmgr_error_data_statistic_update(obj, &err_data);
1459 		amdgpu_ras_error_generate_report(adev, info, &err_data, &qctx);
1460 	} else {
1461 		/* Host provides absolute error counts. First generate the report
1462 		 * using the previous VF internal count against new host count.
1463 		 * Then Update VF internal count.
1464 		 */
1465 		amdgpu_ras_virt_error_generate_report(adev, info, &err_data, &qctx);
1466 		amdgpu_ras_mgr_virt_error_data_statistics_update(obj, &err_data);
1467 	}
1468 
1469 	info->ue_count = obj->err_data.ue_count;
1470 	info->ce_count = obj->err_data.ce_count;
1471 	info->de_count = obj->err_data.de_count;
1472 
1473 out_fini_err_data:
1474 	amdgpu_ras_error_data_fini(&err_data);
1475 
1476 	return ret;
1477 }
1478 
1479 int amdgpu_ras_query_error_status(struct amdgpu_device *adev, struct ras_query_if *info)
1480 {
1481 	return amdgpu_ras_query_error_status_with_event(adev, info, RAS_EVENT_TYPE_INVALID);
1482 }
1483 
1484 int amdgpu_ras_reset_error_count(struct amdgpu_device *adev,
1485 		enum amdgpu_ras_block block)
1486 {
1487 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev, block, 0);
1488 	const struct amdgpu_mca_smu_funcs *mca_funcs = adev->mca.mca_funcs;
1489 	const struct aca_smu_funcs *smu_funcs = adev->aca.smu_funcs;
1490 
1491 	if (!block_obj || !block_obj->hw_ops) {
1492 		dev_dbg_once(adev->dev, "%s doesn't config RAS function\n",
1493 				ras_block_str(block));
1494 		return -EOPNOTSUPP;
1495 	}
1496 
1497 	if (!amdgpu_ras_is_supported(adev, block) ||
1498 	    !amdgpu_ras_get_aca_debug_mode(adev))
1499 		return -EOPNOTSUPP;
1500 
1501 	if (amdgpu_sriov_vf(adev))
1502 		return -EOPNOTSUPP;
1503 
1504 	/* skip ras error reset in gpu reset */
1505 	if ((amdgpu_in_reset(adev) || amdgpu_ras_in_recovery(adev)) &&
1506 	    ((smu_funcs && smu_funcs->set_debug_mode) ||
1507 	     (mca_funcs && mca_funcs->mca_set_debug_mode)))
1508 		return -EOPNOTSUPP;
1509 
1510 	if (block_obj->hw_ops->reset_ras_error_count)
1511 		block_obj->hw_ops->reset_ras_error_count(adev);
1512 
1513 	return 0;
1514 }
1515 
1516 int amdgpu_ras_reset_error_status(struct amdgpu_device *adev,
1517 		enum amdgpu_ras_block block)
1518 {
1519 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev, block, 0);
1520 
1521 	if (amdgpu_ras_reset_error_count(adev, block) == -EOPNOTSUPP)
1522 		return 0;
1523 
1524 	if ((block == AMDGPU_RAS_BLOCK__GFX) ||
1525 	    (block == AMDGPU_RAS_BLOCK__MMHUB)) {
1526 		if (block_obj->hw_ops->reset_ras_error_status)
1527 			block_obj->hw_ops->reset_ras_error_status(adev);
1528 	}
1529 
1530 	return 0;
1531 }
1532 
1533 /* wrapper of psp_ras_trigger_error */
1534 int amdgpu_ras_error_inject(struct amdgpu_device *adev,
1535 		struct ras_inject_if *info)
1536 {
1537 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1538 	struct ta_ras_trigger_error_input block_info = {
1539 		.block_id =  amdgpu_ras_block_to_ta(info->head.block),
1540 		.inject_error_type = amdgpu_ras_error_to_ta(info->head.type),
1541 		.sub_block_index = info->head.sub_block_index,
1542 		.address = info->address,
1543 		.value = info->value,
1544 	};
1545 	int ret = -EINVAL;
1546 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev,
1547 							info->head.block,
1548 							info->head.sub_block_index);
1549 
1550 	/* inject on guest isn't allowed, return success directly */
1551 	if (amdgpu_sriov_vf(adev))
1552 		return 0;
1553 
1554 	if (!obj)
1555 		return -EINVAL;
1556 
1557 	if (!block_obj || !block_obj->hw_ops)	{
1558 		dev_dbg_once(adev->dev, "%s doesn't config RAS function\n",
1559 			     get_ras_block_str(&info->head));
1560 		return -EINVAL;
1561 	}
1562 
1563 	/* Calculate XGMI relative offset */
1564 	if (adev->gmc.xgmi.num_physical_nodes > 1 &&
1565 	    info->head.block != AMDGPU_RAS_BLOCK__GFX) {
1566 		block_info.address =
1567 			amdgpu_xgmi_get_relative_phy_addr(adev,
1568 							  block_info.address);
1569 	}
1570 
1571 	if (block_obj->hw_ops->ras_error_inject) {
1572 		if (info->head.block == AMDGPU_RAS_BLOCK__GFX)
1573 			ret = block_obj->hw_ops->ras_error_inject(adev, info, info->instance_mask);
1574 		else /* Special ras_error_inject is defined (e.g: xgmi) */
1575 			ret = block_obj->hw_ops->ras_error_inject(adev, &block_info,
1576 						info->instance_mask);
1577 	} else {
1578 		/* default path */
1579 		ret = psp_ras_trigger_error(&adev->psp, &block_info, info->instance_mask);
1580 	}
1581 
1582 	if (ret)
1583 		dev_err(adev->dev, "ras inject %s failed %d\n",
1584 			get_ras_block_str(&info->head), ret);
1585 
1586 	return ret;
1587 }
1588 
1589 /**
1590  * amdgpu_ras_query_error_count_helper -- Get error counter for specific IP
1591  * @adev: pointer to AMD GPU device
1592  * @ce_count: pointer to an integer to be set to the count of correctible errors.
1593  * @ue_count: pointer to an integer to be set to the count of uncorrectible errors.
1594  * @query_info: pointer to ras_query_if
1595  *
1596  * Return 0 for query success or do nothing, otherwise return an error
1597  * on failures
1598  */
1599 static int amdgpu_ras_query_error_count_helper(struct amdgpu_device *adev,
1600 					       unsigned long *ce_count,
1601 					       unsigned long *ue_count,
1602 					       struct ras_query_if *query_info)
1603 {
1604 	int ret;
1605 
1606 	if (!query_info)
1607 		/* do nothing if query_info is not specified */
1608 		return 0;
1609 
1610 	ret = amdgpu_ras_query_error_status(adev, query_info);
1611 	if (ret)
1612 		return ret;
1613 
1614 	*ce_count += query_info->ce_count;
1615 	*ue_count += query_info->ue_count;
1616 
1617 	/* some hardware/IP supports read to clear
1618 	 * no need to explictly reset the err status after the query call */
1619 	if (amdgpu_ip_version(adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 2) &&
1620 	    amdgpu_ip_version(adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 4)) {
1621 		if (amdgpu_ras_reset_error_status(adev, query_info->head.block))
1622 			dev_warn(adev->dev,
1623 				 "Failed to reset error counter and error status\n");
1624 	}
1625 
1626 	return 0;
1627 }
1628 
1629 /**
1630  * amdgpu_ras_query_error_count -- Get error counts of all IPs or specific IP
1631  * @adev: pointer to AMD GPU device
1632  * @ce_count: pointer to an integer to be set to the count of correctible errors.
1633  * @ue_count: pointer to an integer to be set to the count of uncorrectible
1634  * errors.
1635  * @query_info: pointer to ras_query_if if the query request is only for
1636  * specific ip block; if info is NULL, then the qurey request is for
1637  * all the ip blocks that support query ras error counters/status
1638  *
1639  * If set, @ce_count or @ue_count, count and return the corresponding
1640  * error counts in those integer pointers. Return 0 if the device
1641  * supports RAS. Return -EOPNOTSUPP if the device doesn't support RAS.
1642  */
1643 int amdgpu_ras_query_error_count(struct amdgpu_device *adev,
1644 				 unsigned long *ce_count,
1645 				 unsigned long *ue_count,
1646 				 struct ras_query_if *query_info)
1647 {
1648 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1649 	struct ras_manager *obj;
1650 	unsigned long ce, ue;
1651 	int ret;
1652 
1653 	if (!adev->ras_enabled || !con)
1654 		return -EOPNOTSUPP;
1655 
1656 	/* Don't count since no reporting.
1657 	 */
1658 	if (!ce_count && !ue_count)
1659 		return 0;
1660 
1661 	ce = 0;
1662 	ue = 0;
1663 	if (!query_info) {
1664 		/* query all the ip blocks that support ras query interface */
1665 		list_for_each_entry(obj, &con->head, node) {
1666 			struct ras_query_if info = {
1667 				.head = obj->head,
1668 			};
1669 
1670 			ret = amdgpu_ras_query_error_count_helper(adev, &ce, &ue, &info);
1671 		}
1672 	} else {
1673 		/* query specific ip block */
1674 		ret = amdgpu_ras_query_error_count_helper(adev, &ce, &ue, query_info);
1675 	}
1676 
1677 	if (ret)
1678 		return ret;
1679 
1680 	if (ce_count)
1681 		*ce_count = ce;
1682 
1683 	if (ue_count)
1684 		*ue_count = ue;
1685 
1686 	return 0;
1687 }
1688 /* query/inject/cure end */
1689 
1690 
1691 /* sysfs begin */
1692 
1693 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
1694 		struct ras_badpage **bps, unsigned int *count);
1695 
1696 static char *amdgpu_ras_badpage_flags_str(unsigned int flags)
1697 {
1698 	switch (flags) {
1699 	case AMDGPU_RAS_RETIRE_PAGE_RESERVED:
1700 		return "R";
1701 	case AMDGPU_RAS_RETIRE_PAGE_PENDING:
1702 		return "P";
1703 	case AMDGPU_RAS_RETIRE_PAGE_FAULT:
1704 	default:
1705 		return "F";
1706 	}
1707 }
1708 
1709 /**
1710  * DOC: AMDGPU RAS sysfs gpu_vram_bad_pages Interface
1711  *
1712  * It allows user to read the bad pages of vram on the gpu through
1713  * /sys/class/drm/card[0/1/2...]/device/ras/gpu_vram_bad_pages
1714  *
1715  * It outputs multiple lines, and each line stands for one gpu page.
1716  *
1717  * The format of one line is below,
1718  * gpu pfn : gpu page size : flags
1719  *
1720  * gpu pfn and gpu page size are printed in hex format.
1721  * flags can be one of below character,
1722  *
1723  * R: reserved, this gpu page is reserved and not able to use.
1724  *
1725  * P: pending for reserve, this gpu page is marked as bad, will be reserved
1726  * in next window of page_reserve.
1727  *
1728  * F: unable to reserve. this gpu page can't be reserved due to some reasons.
1729  *
1730  * Examples:
1731  *
1732  * .. code-block:: bash
1733  *
1734  *	0x00000001 : 0x00001000 : R
1735  *	0x00000002 : 0x00001000 : P
1736  *
1737  */
1738 
1739 static ssize_t amdgpu_ras_sysfs_badpages_read(struct file *f,
1740 		struct kobject *kobj, const struct bin_attribute *attr,
1741 		char *buf, loff_t ppos, size_t count)
1742 {
1743 	struct amdgpu_ras *con =
1744 		container_of(attr, struct amdgpu_ras, badpages_attr);
1745 	struct amdgpu_device *adev = con->adev;
1746 	const unsigned int element_size =
1747 		sizeof("0xabcdabcd : 0x12345678 : R\n") - 1;
1748 	unsigned int start = div64_ul(ppos + element_size - 1, element_size);
1749 	unsigned int end = div64_ul(ppos + count - 1, element_size);
1750 	ssize_t s = 0;
1751 	struct ras_badpage *bps = NULL;
1752 	unsigned int bps_count = 0;
1753 
1754 	memset(buf, 0, count);
1755 
1756 	if (amdgpu_ras_badpages_read(adev, &bps, &bps_count))
1757 		return 0;
1758 
1759 	for (; start < end && start < bps_count; start++)
1760 		s += scnprintf(&buf[s], element_size + 1,
1761 				"0x%08x : 0x%08x : %1s\n",
1762 				bps[start].bp,
1763 				bps[start].size,
1764 				amdgpu_ras_badpage_flags_str(bps[start].flags));
1765 
1766 	kfree(bps);
1767 
1768 	return s;
1769 }
1770 
1771 static ssize_t amdgpu_ras_sysfs_features_read(struct device *dev,
1772 		struct device_attribute *attr, char *buf)
1773 {
1774 	struct amdgpu_ras *con =
1775 		container_of(attr, struct amdgpu_ras, features_attr);
1776 
1777 	return sysfs_emit(buf, "feature mask: 0x%x\n", con->features);
1778 }
1779 
1780 static ssize_t amdgpu_ras_sysfs_version_show(struct device *dev,
1781 		struct device_attribute *attr, char *buf)
1782 {
1783 	struct amdgpu_ras *con =
1784 		container_of(attr, struct amdgpu_ras, version_attr);
1785 	return sysfs_emit(buf, "table version: 0x%x\n", con->eeprom_control.tbl_hdr.version);
1786 }
1787 
1788 static ssize_t amdgpu_ras_sysfs_schema_show(struct device *dev,
1789 		struct device_attribute *attr, char *buf)
1790 {
1791 	struct amdgpu_ras *con =
1792 		container_of(attr, struct amdgpu_ras, schema_attr);
1793 	return sysfs_emit(buf, "schema: 0x%x\n", con->schema);
1794 }
1795 
1796 static struct {
1797 	enum ras_event_type type;
1798 	const char *name;
1799 } dump_event[] = {
1800 	{RAS_EVENT_TYPE_FATAL, "Fatal Error"},
1801 	{RAS_EVENT_TYPE_POISON_CREATION, "Poison Creation"},
1802 	{RAS_EVENT_TYPE_POISON_CONSUMPTION, "Poison Consumption"},
1803 };
1804 
1805 static ssize_t amdgpu_ras_sysfs_event_state_show(struct device *dev,
1806 						 struct device_attribute *attr, char *buf)
1807 {
1808 	struct amdgpu_ras *con =
1809 		container_of(attr, struct amdgpu_ras, event_state_attr);
1810 	struct ras_event_manager *event_mgr = con->event_mgr;
1811 	struct ras_event_state *event_state;
1812 	int i, size = 0;
1813 
1814 	if (!event_mgr)
1815 		return -EINVAL;
1816 
1817 	size += sysfs_emit_at(buf, size, "current seqno: %llu\n", atomic64_read(&event_mgr->seqno));
1818 	for (i = 0; i < ARRAY_SIZE(dump_event); i++) {
1819 		event_state = &event_mgr->event_state[dump_event[i].type];
1820 		size += sysfs_emit_at(buf, size, "%s: count:%llu, last_seqno:%llu\n",
1821 				      dump_event[i].name,
1822 				      atomic64_read(&event_state->count),
1823 				      event_state->last_seqno);
1824 	}
1825 
1826 	return (ssize_t)size;
1827 }
1828 
1829 static void amdgpu_ras_sysfs_remove_bad_page_node(struct amdgpu_device *adev)
1830 {
1831 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1832 
1833 	if (adev->dev->kobj.sd)
1834 		sysfs_remove_file_from_group(&adev->dev->kobj,
1835 				&con->badpages_attr.attr,
1836 				RAS_FS_NAME);
1837 }
1838 
1839 static int amdgpu_ras_sysfs_remove_dev_attr_node(struct amdgpu_device *adev)
1840 {
1841 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1842 	struct attribute *attrs[] = {
1843 		&con->features_attr.attr,
1844 		&con->version_attr.attr,
1845 		&con->schema_attr.attr,
1846 		&con->event_state_attr.attr,
1847 		NULL
1848 	};
1849 	struct attribute_group group = {
1850 		.name = RAS_FS_NAME,
1851 		.attrs = attrs,
1852 	};
1853 
1854 	if (adev->dev->kobj.sd)
1855 		sysfs_remove_group(&adev->dev->kobj, &group);
1856 
1857 	return 0;
1858 }
1859 
1860 int amdgpu_ras_sysfs_create(struct amdgpu_device *adev,
1861 		struct ras_common_if *head)
1862 {
1863 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
1864 
1865 	if (amdgpu_aca_is_enabled(adev))
1866 		return 0;
1867 
1868 	if (!obj || obj->attr_inuse)
1869 		return -EINVAL;
1870 
1871 	if (amdgpu_sriov_vf(adev) && !amdgpu_virt_ras_telemetry_block_en(adev, head->block))
1872 		return 0;
1873 
1874 	get_obj(obj);
1875 
1876 	snprintf(obj->fs_data.sysfs_name, sizeof(obj->fs_data.sysfs_name),
1877 		"%s_err_count", head->name);
1878 
1879 	obj->sysfs_attr = (struct device_attribute){
1880 		.attr = {
1881 			.name = obj->fs_data.sysfs_name,
1882 			.mode = S_IRUGO,
1883 		},
1884 			.show = amdgpu_ras_sysfs_read,
1885 	};
1886 	sysfs_attr_init(&obj->sysfs_attr.attr);
1887 
1888 	if (sysfs_add_file_to_group(&adev->dev->kobj,
1889 				&obj->sysfs_attr.attr,
1890 				RAS_FS_NAME)) {
1891 		put_obj(obj);
1892 		return -EINVAL;
1893 	}
1894 
1895 	obj->attr_inuse = 1;
1896 
1897 	return 0;
1898 }
1899 
1900 int amdgpu_ras_sysfs_remove(struct amdgpu_device *adev,
1901 		struct ras_common_if *head)
1902 {
1903 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
1904 
1905 	if (amdgpu_aca_is_enabled(adev))
1906 		return 0;
1907 
1908 	if (!obj || !obj->attr_inuse)
1909 		return -EINVAL;
1910 
1911 	if (adev->dev->kobj.sd)
1912 		sysfs_remove_file_from_group(&adev->dev->kobj,
1913 				&obj->sysfs_attr.attr,
1914 				RAS_FS_NAME);
1915 	obj->attr_inuse = 0;
1916 	put_obj(obj);
1917 
1918 	return 0;
1919 }
1920 
1921 static int amdgpu_ras_sysfs_remove_all(struct amdgpu_device *adev)
1922 {
1923 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1924 	struct ras_manager *obj, *tmp;
1925 
1926 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
1927 		amdgpu_ras_sysfs_remove(adev, &obj->head);
1928 	}
1929 
1930 	if (amdgpu_bad_page_threshold != 0)
1931 		amdgpu_ras_sysfs_remove_bad_page_node(adev);
1932 
1933 	amdgpu_ras_sysfs_remove_dev_attr_node(adev);
1934 
1935 	return 0;
1936 }
1937 /* sysfs end */
1938 
1939 /**
1940  * DOC: AMDGPU RAS Reboot Behavior for Unrecoverable Errors
1941  *
1942  * Normally when there is an uncorrectable error, the driver will reset
1943  * the GPU to recover.  However, in the event of an unrecoverable error,
1944  * the driver provides an interface to reboot the system automatically
1945  * in that event.
1946  *
1947  * The following file in debugfs provides that interface:
1948  * /sys/kernel/debug/dri/[0/1/2...]/ras/auto_reboot
1949  *
1950  * Usage:
1951  *
1952  * .. code-block:: bash
1953  *
1954  *	echo true > .../ras/auto_reboot
1955  *
1956  */
1957 /* debugfs begin */
1958 static struct dentry *amdgpu_ras_debugfs_create_ctrl_node(struct amdgpu_device *adev)
1959 {
1960 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1961 	struct amdgpu_ras_eeprom_control *eeprom = &con->eeprom_control;
1962 	struct drm_minor  *minor = adev_to_drm(adev)->primary;
1963 	struct dentry     *dir;
1964 
1965 	dir = debugfs_create_dir(RAS_FS_NAME, minor->debugfs_root);
1966 	debugfs_create_file("ras_ctrl", S_IWUGO | S_IRUGO, dir, adev,
1967 			    &amdgpu_ras_debugfs_ctrl_ops);
1968 	debugfs_create_file("ras_eeprom_reset", S_IWUGO | S_IRUGO, dir, adev,
1969 			    &amdgpu_ras_debugfs_eeprom_ops);
1970 	debugfs_create_u32("bad_page_cnt_threshold", 0444, dir,
1971 			   &con->bad_page_cnt_threshold);
1972 	debugfs_create_u32("ras_num_recs", 0444, dir, &eeprom->ras_num_recs);
1973 	debugfs_create_x32("ras_hw_enabled", 0444, dir, &adev->ras_hw_enabled);
1974 	debugfs_create_x32("ras_enabled", 0444, dir, &adev->ras_enabled);
1975 	debugfs_create_file("ras_eeprom_size", S_IRUGO, dir, adev,
1976 			    &amdgpu_ras_debugfs_eeprom_size_ops);
1977 	con->de_ras_eeprom_table = debugfs_create_file("ras_eeprom_table",
1978 						       S_IRUGO, dir, adev,
1979 						       &amdgpu_ras_debugfs_eeprom_table_ops);
1980 	amdgpu_ras_debugfs_set_ret_size(&con->eeprom_control);
1981 
1982 	/*
1983 	 * After one uncorrectable error happens, usually GPU recovery will
1984 	 * be scheduled. But due to the known problem in GPU recovery failing
1985 	 * to bring GPU back, below interface provides one direct way to
1986 	 * user to reboot system automatically in such case within
1987 	 * ERREVENT_ATHUB_INTERRUPT generated. Normal GPU recovery routine
1988 	 * will never be called.
1989 	 */
1990 	debugfs_create_bool("auto_reboot", S_IWUGO | S_IRUGO, dir, &con->reboot);
1991 
1992 	/*
1993 	 * User could set this not to clean up hardware's error count register
1994 	 * of RAS IPs during ras recovery.
1995 	 */
1996 	debugfs_create_bool("disable_ras_err_cnt_harvest", 0644, dir,
1997 			    &con->disable_ras_err_cnt_harvest);
1998 	return dir;
1999 }
2000 
2001 static void amdgpu_ras_debugfs_create(struct amdgpu_device *adev,
2002 				      struct ras_fs_if *head,
2003 				      struct dentry *dir)
2004 {
2005 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &head->head);
2006 
2007 	if (!obj || !dir)
2008 		return;
2009 
2010 	get_obj(obj);
2011 
2012 	memcpy(obj->fs_data.debugfs_name,
2013 			head->debugfs_name,
2014 			sizeof(obj->fs_data.debugfs_name));
2015 
2016 	debugfs_create_file(obj->fs_data.debugfs_name, S_IWUGO | S_IRUGO, dir,
2017 			    obj, &amdgpu_ras_debugfs_ops);
2018 }
2019 
2020 static bool amdgpu_ras_aca_is_supported(struct amdgpu_device *adev)
2021 {
2022 	bool ret;
2023 
2024 	switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
2025 	case IP_VERSION(13, 0, 6):
2026 	case IP_VERSION(13, 0, 12):
2027 	case IP_VERSION(13, 0, 14):
2028 		ret = true;
2029 		break;
2030 	default:
2031 		ret = false;
2032 		break;
2033 	}
2034 
2035 	return ret;
2036 }
2037 
2038 void amdgpu_ras_debugfs_create_all(struct amdgpu_device *adev)
2039 {
2040 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2041 	struct dentry *dir;
2042 	struct ras_manager *obj;
2043 	struct ras_fs_if fs_info;
2044 
2045 	/*
2046 	 * it won't be called in resume path, no need to check
2047 	 * suspend and gpu reset status
2048 	 */
2049 	if (!IS_ENABLED(CONFIG_DEBUG_FS) || !con)
2050 		return;
2051 
2052 	dir = amdgpu_ras_debugfs_create_ctrl_node(adev);
2053 
2054 	list_for_each_entry(obj, &con->head, node) {
2055 		if (amdgpu_ras_is_supported(adev, obj->head.block) &&
2056 			(obj->attr_inuse == 1)) {
2057 			sprintf(fs_info.debugfs_name, "%s_err_inject",
2058 					get_ras_block_str(&obj->head));
2059 			fs_info.head = obj->head;
2060 			amdgpu_ras_debugfs_create(adev, &fs_info, dir);
2061 		}
2062 	}
2063 
2064 	if (amdgpu_ras_aca_is_supported(adev)) {
2065 		if (amdgpu_aca_is_enabled(adev))
2066 			amdgpu_aca_smu_debugfs_init(adev, dir);
2067 		else
2068 			amdgpu_mca_smu_debugfs_init(adev, dir);
2069 	}
2070 }
2071 
2072 /* debugfs end */
2073 
2074 /* ras fs */
2075 static const BIN_ATTR(gpu_vram_bad_pages, S_IRUGO,
2076 		      amdgpu_ras_sysfs_badpages_read, NULL, 0);
2077 static DEVICE_ATTR(features, S_IRUGO,
2078 		amdgpu_ras_sysfs_features_read, NULL);
2079 static DEVICE_ATTR(version, 0444,
2080 		amdgpu_ras_sysfs_version_show, NULL);
2081 static DEVICE_ATTR(schema, 0444,
2082 		amdgpu_ras_sysfs_schema_show, NULL);
2083 static DEVICE_ATTR(event_state, 0444,
2084 		   amdgpu_ras_sysfs_event_state_show, NULL);
2085 static int amdgpu_ras_fs_init(struct amdgpu_device *adev)
2086 {
2087 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2088 	struct attribute_group group = {
2089 		.name = RAS_FS_NAME,
2090 	};
2091 	struct attribute *attrs[] = {
2092 		&con->features_attr.attr,
2093 		&con->version_attr.attr,
2094 		&con->schema_attr.attr,
2095 		&con->event_state_attr.attr,
2096 		NULL
2097 	};
2098 	const struct bin_attribute *bin_attrs[] = {
2099 		NULL,
2100 		NULL,
2101 	};
2102 	int r;
2103 
2104 	group.attrs = attrs;
2105 
2106 	/* add features entry */
2107 	con->features_attr = dev_attr_features;
2108 	sysfs_attr_init(attrs[0]);
2109 
2110 	/* add version entry */
2111 	con->version_attr = dev_attr_version;
2112 	sysfs_attr_init(attrs[1]);
2113 
2114 	/* add schema entry */
2115 	con->schema_attr = dev_attr_schema;
2116 	sysfs_attr_init(attrs[2]);
2117 
2118 	/* add event_state entry */
2119 	con->event_state_attr = dev_attr_event_state;
2120 	sysfs_attr_init(attrs[3]);
2121 
2122 	if (amdgpu_bad_page_threshold != 0) {
2123 		/* add bad_page_features entry */
2124 		con->badpages_attr = bin_attr_gpu_vram_bad_pages;
2125 		sysfs_bin_attr_init(&con->badpages_attr);
2126 		bin_attrs[0] = &con->badpages_attr;
2127 		group.bin_attrs_new = bin_attrs;
2128 	}
2129 
2130 	r = sysfs_create_group(&adev->dev->kobj, &group);
2131 	if (r)
2132 		dev_err(adev->dev, "Failed to create RAS sysfs group!");
2133 
2134 	return 0;
2135 }
2136 
2137 static int amdgpu_ras_fs_fini(struct amdgpu_device *adev)
2138 {
2139 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2140 	struct ras_manager *con_obj, *ip_obj, *tmp;
2141 
2142 	if (IS_ENABLED(CONFIG_DEBUG_FS)) {
2143 		list_for_each_entry_safe(con_obj, tmp, &con->head, node) {
2144 			ip_obj = amdgpu_ras_find_obj(adev, &con_obj->head);
2145 			if (ip_obj)
2146 				put_obj(ip_obj);
2147 		}
2148 	}
2149 
2150 	amdgpu_ras_sysfs_remove_all(adev);
2151 	return 0;
2152 }
2153 /* ras fs end */
2154 
2155 /* ih begin */
2156 
2157 /* For the hardware that cannot enable bif ring for both ras_controller_irq
2158  * and ras_err_evnet_athub_irq ih cookies, the driver has to poll status
2159  * register to check whether the interrupt is triggered or not, and properly
2160  * ack the interrupt if it is there
2161  */
2162 void amdgpu_ras_interrupt_fatal_error_handler(struct amdgpu_device *adev)
2163 {
2164 	/* Fatal error events are handled on host side */
2165 	if (amdgpu_sriov_vf(adev))
2166 		return;
2167 	/*
2168 	 * If the current interrupt is caused by a non-fatal RAS error, skip
2169 	 * check for fatal error. For fatal errors, FED status of all devices
2170 	 * in XGMI hive gets set when the first device gets fatal error
2171 	 * interrupt. The error gets propagated to other devices as well, so
2172 	 * make sure to ack the interrupt regardless of FED status.
2173 	 */
2174 	if (!amdgpu_ras_get_fed_status(adev) &&
2175 	    amdgpu_ras_is_err_state(adev, AMDGPU_RAS_BLOCK__ANY))
2176 		return;
2177 
2178 	if (adev->nbio.ras &&
2179 	    adev->nbio.ras->handle_ras_controller_intr_no_bifring)
2180 		adev->nbio.ras->handle_ras_controller_intr_no_bifring(adev);
2181 
2182 	if (adev->nbio.ras &&
2183 	    adev->nbio.ras->handle_ras_err_event_athub_intr_no_bifring)
2184 		adev->nbio.ras->handle_ras_err_event_athub_intr_no_bifring(adev);
2185 }
2186 
2187 static void amdgpu_ras_interrupt_poison_consumption_handler(struct ras_manager *obj,
2188 				struct amdgpu_iv_entry *entry)
2189 {
2190 	bool poison_stat = false;
2191 	struct amdgpu_device *adev = obj->adev;
2192 	struct amdgpu_ras_block_object *block_obj =
2193 		amdgpu_ras_get_ras_block(adev, obj->head.block, 0);
2194 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2195 	enum ras_event_type type = RAS_EVENT_TYPE_POISON_CONSUMPTION;
2196 	u64 event_id;
2197 	int ret;
2198 
2199 	if (!block_obj || !con)
2200 		return;
2201 
2202 	ret = amdgpu_ras_mark_ras_event(adev, type);
2203 	if (ret)
2204 		return;
2205 
2206 	amdgpu_ras_set_err_poison(adev, block_obj->ras_comm.block);
2207 	/* both query_poison_status and handle_poison_consumption are optional,
2208 	 * but at least one of them should be implemented if we need poison
2209 	 * consumption handler
2210 	 */
2211 	if (block_obj->hw_ops && block_obj->hw_ops->query_poison_status) {
2212 		poison_stat = block_obj->hw_ops->query_poison_status(adev);
2213 		if (!poison_stat) {
2214 			/* Not poison consumption interrupt, no need to handle it */
2215 			dev_info(adev->dev, "No RAS poison status in %s poison IH.\n",
2216 					block_obj->ras_comm.name);
2217 
2218 			return;
2219 		}
2220 	}
2221 
2222 	amdgpu_umc_poison_handler(adev, obj->head.block, 0);
2223 
2224 	if (block_obj->hw_ops && block_obj->hw_ops->handle_poison_consumption)
2225 		poison_stat = block_obj->hw_ops->handle_poison_consumption(adev);
2226 
2227 	/* gpu reset is fallback for failed and default cases.
2228 	 * For RMA case, amdgpu_umc_poison_handler will handle gpu reset.
2229 	 */
2230 	if (poison_stat && !amdgpu_ras_is_rma(adev)) {
2231 		event_id = amdgpu_ras_acquire_event_id(adev, type);
2232 		RAS_EVENT_LOG(adev, event_id,
2233 			      "GPU reset for %s RAS poison consumption is issued!\n",
2234 			      block_obj->ras_comm.name);
2235 		amdgpu_ras_reset_gpu(adev);
2236 	}
2237 
2238 	if (!poison_stat)
2239 		amdgpu_gfx_poison_consumption_handler(adev, entry);
2240 }
2241 
2242 static void amdgpu_ras_interrupt_poison_creation_handler(struct ras_manager *obj,
2243 				struct amdgpu_iv_entry *entry)
2244 {
2245 	struct amdgpu_device *adev = obj->adev;
2246 	enum ras_event_type type = RAS_EVENT_TYPE_POISON_CREATION;
2247 	u64 event_id;
2248 	int ret;
2249 
2250 	ret = amdgpu_ras_mark_ras_event(adev, type);
2251 	if (ret)
2252 		return;
2253 
2254 	event_id = amdgpu_ras_acquire_event_id(adev, type);
2255 	RAS_EVENT_LOG(adev, event_id, "Poison is created\n");
2256 
2257 	if (amdgpu_ip_version(obj->adev, UMC_HWIP, 0) >= IP_VERSION(12, 0, 0)) {
2258 		struct amdgpu_ras *con = amdgpu_ras_get_context(obj->adev);
2259 
2260 		atomic_inc(&con->page_retirement_req_cnt);
2261 		atomic_inc(&con->poison_creation_count);
2262 
2263 		wake_up(&con->page_retirement_wq);
2264 	}
2265 }
2266 
2267 static void amdgpu_ras_interrupt_umc_handler(struct ras_manager *obj,
2268 				struct amdgpu_iv_entry *entry)
2269 {
2270 	struct ras_ih_data *data = &obj->ih_data;
2271 	struct ras_err_data err_data;
2272 	int ret;
2273 
2274 	if (!data->cb)
2275 		return;
2276 
2277 	ret = amdgpu_ras_error_data_init(&err_data);
2278 	if (ret)
2279 		return;
2280 
2281 	/* Let IP handle its data, maybe we need get the output
2282 	 * from the callback to update the error type/count, etc
2283 	 */
2284 	amdgpu_ras_set_fed(obj->adev, true);
2285 	ret = data->cb(obj->adev, &err_data, entry);
2286 	/* ue will trigger an interrupt, and in that case
2287 	 * we need do a reset to recovery the whole system.
2288 	 * But leave IP do that recovery, here we just dispatch
2289 	 * the error.
2290 	 */
2291 	if (ret == AMDGPU_RAS_SUCCESS) {
2292 		/* these counts could be left as 0 if
2293 		 * some blocks do not count error number
2294 		 */
2295 		obj->err_data.ue_count += err_data.ue_count;
2296 		obj->err_data.ce_count += err_data.ce_count;
2297 		obj->err_data.de_count += err_data.de_count;
2298 	}
2299 
2300 	amdgpu_ras_error_data_fini(&err_data);
2301 }
2302 
2303 static void amdgpu_ras_interrupt_handler(struct ras_manager *obj)
2304 {
2305 	struct ras_ih_data *data = &obj->ih_data;
2306 	struct amdgpu_iv_entry entry;
2307 
2308 	while (data->rptr != data->wptr) {
2309 		rmb();
2310 		memcpy(&entry, &data->ring[data->rptr],
2311 				data->element_size);
2312 
2313 		wmb();
2314 		data->rptr = (data->aligned_element_size +
2315 				data->rptr) % data->ring_size;
2316 
2317 		if (amdgpu_ras_is_poison_mode_supported(obj->adev)) {
2318 			if (obj->head.block == AMDGPU_RAS_BLOCK__UMC)
2319 				amdgpu_ras_interrupt_poison_creation_handler(obj, &entry);
2320 			else
2321 				amdgpu_ras_interrupt_poison_consumption_handler(obj, &entry);
2322 		} else {
2323 			if (obj->head.block == AMDGPU_RAS_BLOCK__UMC)
2324 				amdgpu_ras_interrupt_umc_handler(obj, &entry);
2325 			else
2326 				dev_warn(obj->adev->dev,
2327 					"No RAS interrupt handler for non-UMC block with poison disabled.\n");
2328 		}
2329 	}
2330 }
2331 
2332 static void amdgpu_ras_interrupt_process_handler(struct work_struct *work)
2333 {
2334 	struct ras_ih_data *data =
2335 		container_of(work, struct ras_ih_data, ih_work);
2336 	struct ras_manager *obj =
2337 		container_of(data, struct ras_manager, ih_data);
2338 
2339 	amdgpu_ras_interrupt_handler(obj);
2340 }
2341 
2342 int amdgpu_ras_interrupt_dispatch(struct amdgpu_device *adev,
2343 		struct ras_dispatch_if *info)
2344 {
2345 	struct ras_manager *obj;
2346 	struct ras_ih_data *data;
2347 
2348 	obj = amdgpu_ras_find_obj(adev, &info->head);
2349 	if (!obj)
2350 		return -EINVAL;
2351 
2352 	data = &obj->ih_data;
2353 
2354 	if (data->inuse == 0)
2355 		return 0;
2356 
2357 	/* Might be overflow... */
2358 	memcpy(&data->ring[data->wptr], info->entry,
2359 			data->element_size);
2360 
2361 	wmb();
2362 	data->wptr = (data->aligned_element_size +
2363 			data->wptr) % data->ring_size;
2364 
2365 	schedule_work(&data->ih_work);
2366 
2367 	return 0;
2368 }
2369 
2370 int amdgpu_ras_interrupt_remove_handler(struct amdgpu_device *adev,
2371 		struct ras_common_if *head)
2372 {
2373 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
2374 	struct ras_ih_data *data;
2375 
2376 	if (!obj)
2377 		return -EINVAL;
2378 
2379 	data = &obj->ih_data;
2380 	if (data->inuse == 0)
2381 		return 0;
2382 
2383 	cancel_work_sync(&data->ih_work);
2384 
2385 	kfree(data->ring);
2386 	memset(data, 0, sizeof(*data));
2387 	put_obj(obj);
2388 
2389 	return 0;
2390 }
2391 
2392 int amdgpu_ras_interrupt_add_handler(struct amdgpu_device *adev,
2393 		struct ras_common_if *head)
2394 {
2395 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
2396 	struct ras_ih_data *data;
2397 	struct amdgpu_ras_block_object *ras_obj;
2398 
2399 	if (!obj) {
2400 		/* in case we registe the IH before enable ras feature */
2401 		obj = amdgpu_ras_create_obj(adev, head);
2402 		if (!obj)
2403 			return -EINVAL;
2404 	} else
2405 		get_obj(obj);
2406 
2407 	ras_obj = container_of(head, struct amdgpu_ras_block_object, ras_comm);
2408 
2409 	data = &obj->ih_data;
2410 	/* add the callback.etc */
2411 	*data = (struct ras_ih_data) {
2412 		.inuse = 0,
2413 		.cb = ras_obj->ras_cb,
2414 		.element_size = sizeof(struct amdgpu_iv_entry),
2415 		.rptr = 0,
2416 		.wptr = 0,
2417 	};
2418 
2419 	INIT_WORK(&data->ih_work, amdgpu_ras_interrupt_process_handler);
2420 
2421 	data->aligned_element_size = ALIGN(data->element_size, 8);
2422 	/* the ring can store 64 iv entries. */
2423 	data->ring_size = 64 * data->aligned_element_size;
2424 	data->ring = kmalloc(data->ring_size, GFP_KERNEL);
2425 	if (!data->ring) {
2426 		put_obj(obj);
2427 		return -ENOMEM;
2428 	}
2429 
2430 	/* IH is ready */
2431 	data->inuse = 1;
2432 
2433 	return 0;
2434 }
2435 
2436 static int amdgpu_ras_interrupt_remove_all(struct amdgpu_device *adev)
2437 {
2438 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2439 	struct ras_manager *obj, *tmp;
2440 
2441 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
2442 		amdgpu_ras_interrupt_remove_handler(adev, &obj->head);
2443 	}
2444 
2445 	return 0;
2446 }
2447 /* ih end */
2448 
2449 /* traversal all IPs except NBIO to query error counter */
2450 static void amdgpu_ras_log_on_err_counter(struct amdgpu_device *adev, enum ras_event_type type)
2451 {
2452 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2453 	struct ras_manager *obj;
2454 
2455 	if (!adev->ras_enabled || !con)
2456 		return;
2457 
2458 	list_for_each_entry(obj, &con->head, node) {
2459 		struct ras_query_if info = {
2460 			.head = obj->head,
2461 		};
2462 
2463 		/*
2464 		 * PCIE_BIF IP has one different isr by ras controller
2465 		 * interrupt, the specific ras counter query will be
2466 		 * done in that isr. So skip such block from common
2467 		 * sync flood interrupt isr calling.
2468 		 */
2469 		if (info.head.block == AMDGPU_RAS_BLOCK__PCIE_BIF)
2470 			continue;
2471 
2472 		/*
2473 		 * this is a workaround for aldebaran, skip send msg to
2474 		 * smu to get ecc_info table due to smu handle get ecc
2475 		 * info table failed temporarily.
2476 		 * should be removed until smu fix handle ecc_info table.
2477 		 */
2478 		if ((info.head.block == AMDGPU_RAS_BLOCK__UMC) &&
2479 		    (amdgpu_ip_version(adev, MP1_HWIP, 0) ==
2480 		     IP_VERSION(13, 0, 2)))
2481 			continue;
2482 
2483 		amdgpu_ras_query_error_status_with_event(adev, &info, type);
2484 
2485 		if (amdgpu_ip_version(adev, MP0_HWIP, 0) !=
2486 			    IP_VERSION(11, 0, 2) &&
2487 		    amdgpu_ip_version(adev, MP0_HWIP, 0) !=
2488 			    IP_VERSION(11, 0, 4) &&
2489 		    amdgpu_ip_version(adev, MP0_HWIP, 0) !=
2490 			    IP_VERSION(13, 0, 0)) {
2491 			if (amdgpu_ras_reset_error_status(adev, info.head.block))
2492 				dev_warn(adev->dev, "Failed to reset error counter and error status");
2493 		}
2494 	}
2495 }
2496 
2497 /* Parse RdRspStatus and WrRspStatus */
2498 static void amdgpu_ras_error_status_query(struct amdgpu_device *adev,
2499 					  struct ras_query_if *info)
2500 {
2501 	struct amdgpu_ras_block_object *block_obj;
2502 	/*
2503 	 * Only two block need to query read/write
2504 	 * RspStatus at current state
2505 	 */
2506 	if ((info->head.block != AMDGPU_RAS_BLOCK__GFX) &&
2507 		(info->head.block != AMDGPU_RAS_BLOCK__MMHUB))
2508 		return;
2509 
2510 	block_obj = amdgpu_ras_get_ras_block(adev,
2511 					info->head.block,
2512 					info->head.sub_block_index);
2513 
2514 	if (!block_obj || !block_obj->hw_ops) {
2515 		dev_dbg_once(adev->dev, "%s doesn't config RAS function\n",
2516 			     get_ras_block_str(&info->head));
2517 		return;
2518 	}
2519 
2520 	if (block_obj->hw_ops->query_ras_error_status)
2521 		block_obj->hw_ops->query_ras_error_status(adev);
2522 
2523 }
2524 
2525 static void amdgpu_ras_query_err_status(struct amdgpu_device *adev)
2526 {
2527 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2528 	struct ras_manager *obj;
2529 
2530 	if (!adev->ras_enabled || !con)
2531 		return;
2532 
2533 	list_for_each_entry(obj, &con->head, node) {
2534 		struct ras_query_if info = {
2535 			.head = obj->head,
2536 		};
2537 
2538 		amdgpu_ras_error_status_query(adev, &info);
2539 	}
2540 }
2541 
2542 /* recovery begin */
2543 
2544 /* return 0 on success.
2545  * caller need free bps.
2546  */
2547 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
2548 		struct ras_badpage **bps, unsigned int *count)
2549 {
2550 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2551 	struct ras_err_handler_data *data;
2552 	int i = 0;
2553 	int ret = 0, status;
2554 
2555 	if (!con || !con->eh_data || !bps || !count)
2556 		return -EINVAL;
2557 
2558 	mutex_lock(&con->recovery_lock);
2559 	data = con->eh_data;
2560 	if (!data || data->count == 0) {
2561 		*bps = NULL;
2562 		ret = -EINVAL;
2563 		goto out;
2564 	}
2565 
2566 	*bps = kmalloc(sizeof(struct ras_badpage) * data->count, GFP_KERNEL);
2567 	if (!*bps) {
2568 		ret = -ENOMEM;
2569 		goto out;
2570 	}
2571 
2572 	for (; i < data->count; i++) {
2573 		(*bps)[i] = (struct ras_badpage){
2574 			.bp = data->bps[i].retired_page,
2575 			.size = AMDGPU_GPU_PAGE_SIZE,
2576 			.flags = AMDGPU_RAS_RETIRE_PAGE_RESERVED,
2577 		};
2578 		status = amdgpu_vram_mgr_query_page_status(&adev->mman.vram_mgr,
2579 				data->bps[i].retired_page << AMDGPU_GPU_PAGE_SHIFT);
2580 		if (status == -EBUSY)
2581 			(*bps)[i].flags = AMDGPU_RAS_RETIRE_PAGE_PENDING;
2582 		else if (status == -ENOENT)
2583 			(*bps)[i].flags = AMDGPU_RAS_RETIRE_PAGE_FAULT;
2584 	}
2585 
2586 	*count = data->count;
2587 out:
2588 	mutex_unlock(&con->recovery_lock);
2589 	return ret;
2590 }
2591 
2592 static void amdgpu_ras_set_fed_all(struct amdgpu_device *adev,
2593 				   struct amdgpu_hive_info *hive, bool status)
2594 {
2595 	struct amdgpu_device *tmp_adev;
2596 
2597 	if (hive) {
2598 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head)
2599 			amdgpu_ras_set_fed(tmp_adev, status);
2600 	} else {
2601 		amdgpu_ras_set_fed(adev, status);
2602 	}
2603 }
2604 
2605 bool amdgpu_ras_in_recovery(struct amdgpu_device *adev)
2606 {
2607 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
2608 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
2609 	int hive_ras_recovery = 0;
2610 
2611 	if (hive) {
2612 		hive_ras_recovery = atomic_read(&hive->ras_recovery);
2613 		amdgpu_put_xgmi_hive(hive);
2614 	}
2615 
2616 	if (ras && (atomic_read(&ras->in_recovery) || hive_ras_recovery))
2617 		return true;
2618 
2619 	return false;
2620 }
2621 
2622 static enum ras_event_type amdgpu_ras_get_fatal_error_event(struct amdgpu_device *adev)
2623 {
2624 	if (amdgpu_ras_intr_triggered())
2625 		return RAS_EVENT_TYPE_FATAL;
2626 	else
2627 		return RAS_EVENT_TYPE_POISON_CONSUMPTION;
2628 }
2629 
2630 static void amdgpu_ras_do_recovery(struct work_struct *work)
2631 {
2632 	struct amdgpu_ras *ras =
2633 		container_of(work, struct amdgpu_ras, recovery_work);
2634 	struct amdgpu_device *remote_adev = NULL;
2635 	struct amdgpu_device *adev = ras->adev;
2636 	struct list_head device_list, *device_list_handle =  NULL;
2637 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
2638 	enum ras_event_type type;
2639 
2640 	if (hive) {
2641 		atomic_set(&hive->ras_recovery, 1);
2642 
2643 		/* If any device which is part of the hive received RAS fatal
2644 		 * error interrupt, set fatal error status on all. This
2645 		 * condition will need a recovery, and flag will be cleared
2646 		 * as part of recovery.
2647 		 */
2648 		list_for_each_entry(remote_adev, &hive->device_list,
2649 				    gmc.xgmi.head)
2650 			if (amdgpu_ras_get_fed_status(remote_adev)) {
2651 				amdgpu_ras_set_fed_all(adev, hive, true);
2652 				break;
2653 			}
2654 	}
2655 	if (!ras->disable_ras_err_cnt_harvest) {
2656 
2657 		/* Build list of devices to query RAS related errors */
2658 		if  (hive && adev->gmc.xgmi.num_physical_nodes > 1) {
2659 			device_list_handle = &hive->device_list;
2660 		} else {
2661 			INIT_LIST_HEAD(&device_list);
2662 			list_add_tail(&adev->gmc.xgmi.head, &device_list);
2663 			device_list_handle = &device_list;
2664 		}
2665 
2666 		type = amdgpu_ras_get_fatal_error_event(adev);
2667 		list_for_each_entry(remote_adev,
2668 				device_list_handle, gmc.xgmi.head) {
2669 			amdgpu_ras_query_err_status(remote_adev);
2670 			amdgpu_ras_log_on_err_counter(remote_adev, type);
2671 		}
2672 
2673 	}
2674 
2675 	if (amdgpu_device_should_recover_gpu(ras->adev)) {
2676 		struct amdgpu_reset_context reset_context;
2677 		memset(&reset_context, 0, sizeof(reset_context));
2678 
2679 		reset_context.method = AMD_RESET_METHOD_NONE;
2680 		reset_context.reset_req_dev = adev;
2681 		reset_context.src = AMDGPU_RESET_SRC_RAS;
2682 		set_bit(AMDGPU_SKIP_COREDUMP, &reset_context.flags);
2683 
2684 		/* Perform full reset in fatal error mode */
2685 		if (!amdgpu_ras_is_poison_mode_supported(ras->adev))
2686 			set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
2687 		else {
2688 			clear_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
2689 
2690 			if (ras->gpu_reset_flags & AMDGPU_RAS_GPU_RESET_MODE2_RESET) {
2691 				ras->gpu_reset_flags &= ~AMDGPU_RAS_GPU_RESET_MODE2_RESET;
2692 				reset_context.method = AMD_RESET_METHOD_MODE2;
2693 			}
2694 
2695 			/* Fatal error occurs in poison mode, mode1 reset is used to
2696 			 * recover gpu.
2697 			 */
2698 			if (ras->gpu_reset_flags & AMDGPU_RAS_GPU_RESET_MODE1_RESET) {
2699 				ras->gpu_reset_flags &= ~AMDGPU_RAS_GPU_RESET_MODE1_RESET;
2700 				set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
2701 
2702 				psp_fatal_error_recovery_quirk(&adev->psp);
2703 			}
2704 		}
2705 
2706 		amdgpu_device_gpu_recover(ras->adev, NULL, &reset_context);
2707 	}
2708 	atomic_set(&ras->in_recovery, 0);
2709 	if (hive) {
2710 		atomic_set(&hive->ras_recovery, 0);
2711 		amdgpu_put_xgmi_hive(hive);
2712 	}
2713 }
2714 
2715 /* alloc/realloc bps array */
2716 static int amdgpu_ras_realloc_eh_data_space(struct amdgpu_device *adev,
2717 		struct ras_err_handler_data *data, int pages)
2718 {
2719 	unsigned int old_space = data->count + data->space_left;
2720 	unsigned int new_space = old_space + pages;
2721 	unsigned int align_space = ALIGN(new_space, 512);
2722 	void *bps = kmalloc(align_space * sizeof(*data->bps), GFP_KERNEL);
2723 
2724 	if (!bps) {
2725 		return -ENOMEM;
2726 	}
2727 
2728 	if (data->bps) {
2729 		memcpy(bps, data->bps,
2730 				data->count * sizeof(*data->bps));
2731 		kfree(data->bps);
2732 	}
2733 
2734 	data->bps = bps;
2735 	data->space_left += align_space - old_space;
2736 	return 0;
2737 }
2738 
2739 static int amdgpu_ras_mca2pa_by_idx(struct amdgpu_device *adev,
2740 			struct eeprom_table_record *bps,
2741 			struct ras_err_data *err_data)
2742 {
2743 	struct ta_ras_query_address_input addr_in;
2744 	uint32_t socket = 0;
2745 	int ret = 0;
2746 
2747 	if (adev->smuio.funcs && adev->smuio.funcs->get_socket_id)
2748 		socket = adev->smuio.funcs->get_socket_id(adev);
2749 
2750 	/* reinit err_data */
2751 	err_data->err_addr_cnt = 0;
2752 	err_data->err_addr_len = adev->umc.retire_unit;
2753 
2754 	memset(&addr_in, 0, sizeof(addr_in));
2755 	addr_in.ma.err_addr = bps->address;
2756 	addr_in.ma.socket_id = socket;
2757 	addr_in.ma.ch_inst = bps->mem_channel;
2758 	/* tell RAS TA the node instance is not used */
2759 	addr_in.ma.node_inst = TA_RAS_INV_NODE;
2760 
2761 	if (adev->umc.ras && adev->umc.ras->convert_ras_err_addr)
2762 		ret = adev->umc.ras->convert_ras_err_addr(adev, err_data,
2763 				&addr_in, NULL, false);
2764 
2765 	return ret;
2766 }
2767 
2768 static int amdgpu_ras_mca2pa(struct amdgpu_device *adev,
2769 			struct eeprom_table_record *bps,
2770 			struct ras_err_data *err_data)
2771 {
2772 	struct ta_ras_query_address_input addr_in;
2773 	uint32_t die_id, socket = 0;
2774 
2775 	if (adev->smuio.funcs && adev->smuio.funcs->get_socket_id)
2776 		socket = adev->smuio.funcs->get_socket_id(adev);
2777 
2778 	/* although die id is gotten from PA in nps1 mode, the id is
2779 	 * fitable for any nps mode
2780 	 */
2781 	if (adev->umc.ras && adev->umc.ras->get_die_id_from_pa)
2782 		die_id = adev->umc.ras->get_die_id_from_pa(adev, bps->address,
2783 					bps->retired_page << AMDGPU_GPU_PAGE_SHIFT);
2784 	else
2785 		return -EINVAL;
2786 
2787 	/* reinit err_data */
2788 	err_data->err_addr_cnt = 0;
2789 	err_data->err_addr_len = adev->umc.retire_unit;
2790 
2791 	memset(&addr_in, 0, sizeof(addr_in));
2792 	addr_in.ma.err_addr = bps->address;
2793 	addr_in.ma.ch_inst = bps->mem_channel;
2794 	addr_in.ma.umc_inst = bps->mcumc_id;
2795 	addr_in.ma.node_inst = die_id;
2796 	addr_in.ma.socket_id = socket;
2797 
2798 	if (adev->umc.ras && adev->umc.ras->convert_ras_err_addr)
2799 		return adev->umc.ras->convert_ras_err_addr(adev, err_data,
2800 					&addr_in, NULL, false);
2801 	else
2802 		return  -EINVAL;
2803 }
2804 
2805 static int __amdgpu_ras_restore_bad_pages(struct amdgpu_device *adev,
2806 					struct eeprom_table_record *bps, int count)
2807 {
2808 	int j;
2809 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2810 	struct ras_err_handler_data *data = con->eh_data;
2811 
2812 	for (j = 0; j < count; j++) {
2813 		if (amdgpu_ras_check_bad_page_unlock(con,
2814 			bps[j].retired_page << AMDGPU_GPU_PAGE_SHIFT))
2815 			continue;
2816 
2817 		if (!data->space_left &&
2818 		    amdgpu_ras_realloc_eh_data_space(adev, data, 256)) {
2819 			return -ENOMEM;
2820 		}
2821 
2822 		amdgpu_ras_reserve_page(adev, bps[j].retired_page);
2823 
2824 		memcpy(&data->bps[data->count], &(bps[j]),
2825 				sizeof(struct eeprom_table_record));
2826 		data->count++;
2827 		data->space_left--;
2828 	}
2829 
2830 	return 0;
2831 }
2832 
2833 static int __amdgpu_ras_convert_rec_array_from_rom(struct amdgpu_device *adev,
2834 				struct eeprom_table_record *bps, struct ras_err_data *err_data,
2835 				enum amdgpu_memory_partition nps)
2836 {
2837 	int i = 0;
2838 	enum amdgpu_memory_partition save_nps;
2839 
2840 	save_nps = (bps[0].retired_page >> UMC_NPS_SHIFT) & UMC_NPS_MASK;
2841 
2842 	/*old asics just have pa in eeprom*/
2843 	if (IP_VERSION_MAJ(amdgpu_ip_version(adev, UMC_HWIP, 0)) < 12) {
2844 		memcpy(err_data->err_addr, bps,
2845 			sizeof(struct eeprom_table_record) * adev->umc.retire_unit);
2846 		goto out;
2847 	}
2848 
2849 	for (i = 0; i < adev->umc.retire_unit; i++)
2850 		bps[i].retired_page &= ~(UMC_NPS_MASK << UMC_NPS_SHIFT);
2851 
2852 	if (save_nps) {
2853 		if (save_nps == nps) {
2854 			if (amdgpu_umc_pages_in_a_row(adev, err_data,
2855 					bps[0].retired_page << AMDGPU_GPU_PAGE_SHIFT))
2856 				return -EINVAL;
2857 		} else {
2858 			if (amdgpu_ras_mca2pa_by_idx(adev, &bps[0], err_data))
2859 				return -EINVAL;
2860 		}
2861 	} else {
2862 		if (amdgpu_ras_mca2pa(adev, &bps[0], err_data)) {
2863 			if (nps == AMDGPU_NPS1_PARTITION_MODE)
2864 				memcpy(err_data->err_addr, bps,
2865 					sizeof(struct eeprom_table_record) * adev->umc.retire_unit);
2866 			else
2867 				return -EOPNOTSUPP;
2868 		}
2869 	}
2870 
2871 out:
2872 	return __amdgpu_ras_restore_bad_pages(adev, err_data->err_addr, adev->umc.retire_unit);
2873 }
2874 
2875 static int __amdgpu_ras_convert_rec_from_rom(struct amdgpu_device *adev,
2876 				struct eeprom_table_record *bps, struct ras_err_data *err_data,
2877 				enum amdgpu_memory_partition nps)
2878 {
2879 	enum amdgpu_memory_partition save_nps;
2880 
2881 	save_nps = (bps->retired_page >> UMC_NPS_SHIFT) & UMC_NPS_MASK;
2882 	bps->retired_page &= ~(UMC_NPS_MASK << UMC_NPS_SHIFT);
2883 
2884 	if (save_nps == nps) {
2885 		if (amdgpu_umc_pages_in_a_row(adev, err_data,
2886 				bps->retired_page << AMDGPU_GPU_PAGE_SHIFT))
2887 			return -EINVAL;
2888 	} else {
2889 		if (amdgpu_ras_mca2pa_by_idx(adev, bps, err_data))
2890 			return -EINVAL;
2891 	}
2892 
2893 	return __amdgpu_ras_restore_bad_pages(adev, err_data->err_addr,
2894 									adev->umc.retire_unit);
2895 }
2896 
2897 /* it deal with vram only. */
2898 int amdgpu_ras_add_bad_pages(struct amdgpu_device *adev,
2899 		struct eeprom_table_record *bps, int pages, bool from_rom)
2900 {
2901 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2902 	struct ras_err_data err_data;
2903 	struct amdgpu_ras_eeprom_control *control =
2904 			&adev->psp.ras_context.ras->eeprom_control;
2905 	enum amdgpu_memory_partition nps = AMDGPU_NPS1_PARTITION_MODE;
2906 	int ret = 0;
2907 	uint32_t i = 0;
2908 
2909 	if (!con || !con->eh_data || !bps || pages <= 0)
2910 		return 0;
2911 
2912 	if (from_rom) {
2913 		err_data.err_addr =
2914 			kcalloc(adev->umc.retire_unit,
2915 				sizeof(struct eeprom_table_record), GFP_KERNEL);
2916 		if (!err_data.err_addr) {
2917 			dev_warn(adev->dev, "Failed to alloc UMC error address record in mca2pa conversion!\n");
2918 			return -ENOMEM;
2919 		}
2920 
2921 		if (adev->gmc.gmc_funcs->query_mem_partition_mode)
2922 			nps = adev->gmc.gmc_funcs->query_mem_partition_mode(adev);
2923 	}
2924 
2925 	mutex_lock(&con->recovery_lock);
2926 
2927 	if (from_rom) {
2928 		/* there is no pa recs in V3, so skip pa recs processing */
2929 		if (control->tbl_hdr.version < RAS_TABLE_VER_V3) {
2930 			for (i = 0; i < pages; i++) {
2931 				if (control->ras_num_recs - i >= adev->umc.retire_unit) {
2932 					if ((bps[i].address == bps[i + 1].address) &&
2933 						(bps[i].mem_channel == bps[i + 1].mem_channel)) {
2934 						/* deal with retire_unit records a time */
2935 						ret = __amdgpu_ras_convert_rec_array_from_rom(adev,
2936 										&bps[i], &err_data, nps);
2937 						if (ret)
2938 							control->ras_num_bad_pages -= adev->umc.retire_unit;
2939 						i += (adev->umc.retire_unit - 1);
2940 					} else {
2941 						break;
2942 					}
2943 				} else {
2944 					break;
2945 				}
2946 			}
2947 		}
2948 		for (; i < pages; i++) {
2949 			ret = __amdgpu_ras_convert_rec_from_rom(adev,
2950 				&bps[i], &err_data, nps);
2951 			if (ret)
2952 				control->ras_num_bad_pages -= adev->umc.retire_unit;
2953 		}
2954 	} else {
2955 		ret = __amdgpu_ras_restore_bad_pages(adev, bps, pages);
2956 	}
2957 
2958 	if (from_rom)
2959 		kfree(err_data.err_addr);
2960 	mutex_unlock(&con->recovery_lock);
2961 
2962 	return ret;
2963 }
2964 
2965 /*
2966  * write error record array to eeprom, the function should be
2967  * protected by recovery_lock
2968  * new_cnt: new added UE count, excluding reserved bad pages, can be NULL
2969  */
2970 int amdgpu_ras_save_bad_pages(struct amdgpu_device *adev,
2971 		unsigned long *new_cnt)
2972 {
2973 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2974 	struct ras_err_handler_data *data;
2975 	struct amdgpu_ras_eeprom_control *control;
2976 	int save_count, unit_num, bad_page_num, i;
2977 
2978 	if (!con || !con->eh_data) {
2979 		if (new_cnt)
2980 			*new_cnt = 0;
2981 
2982 		return 0;
2983 	}
2984 
2985 	mutex_lock(&con->recovery_lock);
2986 	control = &con->eeprom_control;
2987 	data = con->eh_data;
2988 	bad_page_num = control->ras_num_bad_pages;
2989 	save_count = data->count - bad_page_num;
2990 	mutex_unlock(&con->recovery_lock);
2991 
2992 	unit_num = save_count / adev->umc.retire_unit;
2993 	if (new_cnt)
2994 		*new_cnt = unit_num;
2995 
2996 	/* only new entries are saved */
2997 	if (save_count > 0) {
2998 		/*old asics only save pa to eeprom like before*/
2999 		if (IP_VERSION_MAJ(amdgpu_ip_version(adev, UMC_HWIP, 0)) < 12) {
3000 			if (amdgpu_ras_eeprom_append(control,
3001 					&data->bps[bad_page_num], save_count)) {
3002 				dev_err(adev->dev, "Failed to save EEPROM table data!");
3003 				return -EIO;
3004 			}
3005 		} else {
3006 			for (i = 0; i < unit_num; i++) {
3007 				if (amdgpu_ras_eeprom_append(control,
3008 						&data->bps[bad_page_num +
3009 						i * adev->umc.retire_unit], 1)) {
3010 					dev_err(adev->dev, "Failed to save EEPROM table data!");
3011 					return -EIO;
3012 				}
3013 			}
3014 		}
3015 
3016 		dev_info(adev->dev, "Saved %d pages to EEPROM table.\n", save_count);
3017 	}
3018 
3019 	return 0;
3020 }
3021 
3022 /*
3023  * read error record array in eeprom and reserve enough space for
3024  * storing new bad pages
3025  */
3026 static int amdgpu_ras_load_bad_pages(struct amdgpu_device *adev)
3027 {
3028 	struct amdgpu_ras_eeprom_control *control =
3029 		&adev->psp.ras_context.ras->eeprom_control;
3030 	struct eeprom_table_record *bps;
3031 	int ret, i = 0;
3032 
3033 	/* no bad page record, skip eeprom access */
3034 	if (control->ras_num_recs == 0 || amdgpu_bad_page_threshold == 0)
3035 		return 0;
3036 
3037 	bps = kcalloc(control->ras_num_recs, sizeof(*bps), GFP_KERNEL);
3038 	if (!bps)
3039 		return -ENOMEM;
3040 
3041 	ret = amdgpu_ras_eeprom_read(control, bps, control->ras_num_recs);
3042 	if (ret) {
3043 		dev_err(adev->dev, "Failed to load EEPROM table records!");
3044 	} else {
3045 		if (adev->umc.ras && adev->umc.ras->convert_ras_err_addr) {
3046 			/*In V3, there is no pa recs, and some cases(when address==0) may be parsed
3047 			as pa recs, so add verion check to avoid it.
3048 			*/
3049 			if (control->tbl_hdr.version < RAS_TABLE_VER_V3) {
3050 				for (i = 0; i < control->ras_num_recs; i++) {
3051 					if ((control->ras_num_recs - i) >= adev->umc.retire_unit) {
3052 						if ((bps[i].address == bps[i + 1].address) &&
3053 							(bps[i].mem_channel == bps[i + 1].mem_channel)) {
3054 							control->ras_num_pa_recs += adev->umc.retire_unit;
3055 							i += (adev->umc.retire_unit - 1);
3056 						} else {
3057 							control->ras_num_mca_recs +=
3058 										(control->ras_num_recs - i);
3059 							break;
3060 						}
3061 					} else {
3062 						control->ras_num_mca_recs += (control->ras_num_recs - i);
3063 						break;
3064 					}
3065 				}
3066 			} else {
3067 				control->ras_num_mca_recs = control->ras_num_recs;
3068 			}
3069 		}
3070 
3071 		ret = amdgpu_ras_eeprom_check(control);
3072 		if (ret)
3073 			goto out;
3074 
3075 		/* HW not usable */
3076 		if (amdgpu_ras_is_rma(adev)) {
3077 			ret = -EHWPOISON;
3078 			goto out;
3079 		}
3080 
3081 		ret = amdgpu_ras_add_bad_pages(adev, bps, control->ras_num_recs, true);
3082 	}
3083 
3084 out:
3085 	kfree(bps);
3086 	return ret;
3087 }
3088 
3089 static bool amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
3090 				uint64_t addr)
3091 {
3092 	struct ras_err_handler_data *data = con->eh_data;
3093 	int i;
3094 
3095 	addr >>= AMDGPU_GPU_PAGE_SHIFT;
3096 	for (i = 0; i < data->count; i++)
3097 		if (addr == data->bps[i].retired_page)
3098 			return true;
3099 
3100 	return false;
3101 }
3102 
3103 /*
3104  * check if an address belongs to bad page
3105  *
3106  * Note: this check is only for umc block
3107  */
3108 static bool amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
3109 				uint64_t addr)
3110 {
3111 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3112 	bool ret = false;
3113 
3114 	if (!con || !con->eh_data)
3115 		return ret;
3116 
3117 	mutex_lock(&con->recovery_lock);
3118 	ret = amdgpu_ras_check_bad_page_unlock(con, addr);
3119 	mutex_unlock(&con->recovery_lock);
3120 	return ret;
3121 }
3122 
3123 static void amdgpu_ras_validate_threshold(struct amdgpu_device *adev,
3124 					  uint32_t max_count)
3125 {
3126 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3127 
3128 	/*
3129 	 * amdgpu_bad_page_threshold is used to config
3130 	 * the threshold for the number of bad pages.
3131 	 * -1:  Threshold is set to default value
3132 	 *      Driver will issue a warning message when threshold is reached
3133 	 *      and continue runtime services.
3134 	 * 0:   Disable bad page retirement
3135 	 *      Driver will not retire bad pages
3136 	 *      which is intended for debugging purpose.
3137 	 * -2:  Threshold is determined by a formula
3138 	 *      that assumes 1 bad page per 100M of local memory.
3139 	 *      Driver will continue runtime services when threhold is reached.
3140 	 * 0 < threshold < max number of bad page records in EEPROM,
3141 	 *      A user-defined threshold is set
3142 	 *      Driver will halt runtime services when this custom threshold is reached.
3143 	 */
3144 	if (amdgpu_bad_page_threshold == -2) {
3145 		u64 val = adev->gmc.mc_vram_size;
3146 
3147 		do_div(val, RAS_BAD_PAGE_COVER);
3148 		con->bad_page_cnt_threshold = min(lower_32_bits(val),
3149 						  max_count);
3150 	} else if (amdgpu_bad_page_threshold == -1) {
3151 		con->bad_page_cnt_threshold = ((con->reserved_pages_in_bytes) >> 21) << 4;
3152 	} else {
3153 		con->bad_page_cnt_threshold = min_t(int, max_count,
3154 						    amdgpu_bad_page_threshold);
3155 	}
3156 }
3157 
3158 int amdgpu_ras_put_poison_req(struct amdgpu_device *adev,
3159 		enum amdgpu_ras_block block, uint16_t pasid,
3160 		pasid_notify pasid_fn, void *data, uint32_t reset)
3161 {
3162 	int ret = 0;
3163 	struct ras_poison_msg poison_msg;
3164 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3165 
3166 	memset(&poison_msg, 0, sizeof(poison_msg));
3167 	poison_msg.block = block;
3168 	poison_msg.pasid = pasid;
3169 	poison_msg.reset = reset;
3170 	poison_msg.pasid_fn = pasid_fn;
3171 	poison_msg.data = data;
3172 
3173 	ret = kfifo_put(&con->poison_fifo, poison_msg);
3174 	if (!ret) {
3175 		dev_err(adev->dev, "Poison message fifo is full!\n");
3176 		return -ENOSPC;
3177 	}
3178 
3179 	return 0;
3180 }
3181 
3182 static int amdgpu_ras_get_poison_req(struct amdgpu_device *adev,
3183 		struct ras_poison_msg *poison_msg)
3184 {
3185 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3186 
3187 	return kfifo_get(&con->poison_fifo, poison_msg);
3188 }
3189 
3190 static void amdgpu_ras_ecc_log_init(struct ras_ecc_log_info *ecc_log)
3191 {
3192 	mutex_init(&ecc_log->lock);
3193 
3194 	INIT_RADIX_TREE(&ecc_log->de_page_tree, GFP_KERNEL);
3195 	ecc_log->de_queried_count = 0;
3196 	ecc_log->prev_de_queried_count = 0;
3197 }
3198 
3199 static void amdgpu_ras_ecc_log_fini(struct ras_ecc_log_info *ecc_log)
3200 {
3201 	struct radix_tree_iter iter;
3202 	void __rcu **slot;
3203 	struct ras_ecc_err *ecc_err;
3204 
3205 	mutex_lock(&ecc_log->lock);
3206 	radix_tree_for_each_slot(slot, &ecc_log->de_page_tree, &iter, 0) {
3207 		ecc_err = radix_tree_deref_slot(slot);
3208 		kfree(ecc_err->err_pages.pfn);
3209 		kfree(ecc_err);
3210 		radix_tree_iter_delete(&ecc_log->de_page_tree, &iter, slot);
3211 	}
3212 	mutex_unlock(&ecc_log->lock);
3213 
3214 	mutex_destroy(&ecc_log->lock);
3215 	ecc_log->de_queried_count = 0;
3216 	ecc_log->prev_de_queried_count = 0;
3217 }
3218 
3219 static bool amdgpu_ras_schedule_retirement_dwork(struct amdgpu_ras *con,
3220 				uint32_t delayed_ms)
3221 {
3222 	int ret;
3223 
3224 	mutex_lock(&con->umc_ecc_log.lock);
3225 	ret = radix_tree_tagged(&con->umc_ecc_log.de_page_tree,
3226 			UMC_ECC_NEW_DETECTED_TAG);
3227 	mutex_unlock(&con->umc_ecc_log.lock);
3228 
3229 	if (ret)
3230 		schedule_delayed_work(&con->page_retirement_dwork,
3231 			msecs_to_jiffies(delayed_ms));
3232 
3233 	return ret ? true : false;
3234 }
3235 
3236 static void amdgpu_ras_do_page_retirement(struct work_struct *work)
3237 {
3238 	struct amdgpu_ras *con = container_of(work, struct amdgpu_ras,
3239 					      page_retirement_dwork.work);
3240 	struct amdgpu_device *adev = con->adev;
3241 	struct ras_err_data err_data;
3242 	unsigned long err_cnt;
3243 
3244 	/* If gpu reset is ongoing, delay retiring the bad pages */
3245 	if (amdgpu_in_reset(adev) || amdgpu_ras_in_recovery(adev)) {
3246 		amdgpu_ras_schedule_retirement_dwork(con,
3247 				AMDGPU_RAS_RETIRE_PAGE_INTERVAL * 3);
3248 		return;
3249 	}
3250 
3251 	amdgpu_ras_error_data_init(&err_data);
3252 
3253 	amdgpu_umc_handle_bad_pages(adev, &err_data);
3254 	err_cnt = err_data.err_addr_cnt;
3255 
3256 	amdgpu_ras_error_data_fini(&err_data);
3257 
3258 	if (err_cnt && amdgpu_ras_is_rma(adev))
3259 		amdgpu_ras_reset_gpu(adev);
3260 
3261 	amdgpu_ras_schedule_retirement_dwork(con,
3262 			AMDGPU_RAS_RETIRE_PAGE_INTERVAL);
3263 }
3264 
3265 static int amdgpu_ras_poison_creation_handler(struct amdgpu_device *adev,
3266 				uint32_t poison_creation_count)
3267 {
3268 	int ret = 0;
3269 	struct ras_ecc_log_info *ecc_log;
3270 	struct ras_query_if info;
3271 	uint32_t timeout = 0;
3272 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
3273 	uint64_t de_queried_count;
3274 	uint32_t new_detect_count, total_detect_count;
3275 	uint32_t need_query_count = poison_creation_count;
3276 	bool query_data_timeout = false;
3277 	enum ras_event_type type = RAS_EVENT_TYPE_POISON_CREATION;
3278 
3279 	memset(&info, 0, sizeof(info));
3280 	info.head.block = AMDGPU_RAS_BLOCK__UMC;
3281 
3282 	ecc_log = &ras->umc_ecc_log;
3283 	total_detect_count = 0;
3284 	do {
3285 		ret = amdgpu_ras_query_error_status_with_event(adev, &info, type);
3286 		if (ret)
3287 			return ret;
3288 
3289 		de_queried_count = ecc_log->de_queried_count;
3290 		if (de_queried_count > ecc_log->prev_de_queried_count) {
3291 			new_detect_count = de_queried_count - ecc_log->prev_de_queried_count;
3292 			ecc_log->prev_de_queried_count = de_queried_count;
3293 			timeout = 0;
3294 		} else {
3295 			new_detect_count = 0;
3296 		}
3297 
3298 		if (new_detect_count) {
3299 			total_detect_count += new_detect_count;
3300 		} else {
3301 			if (!timeout && need_query_count)
3302 				timeout = MAX_UMC_POISON_POLLING_TIME_ASYNC;
3303 
3304 			if (timeout) {
3305 				if (!--timeout) {
3306 					query_data_timeout = true;
3307 					break;
3308 				}
3309 				msleep(1);
3310 			}
3311 		}
3312 	} while (total_detect_count < need_query_count);
3313 
3314 	if (query_data_timeout) {
3315 		dev_warn(adev->dev, "Can't find deferred error! count: %u\n",
3316 			(need_query_count - total_detect_count));
3317 		return -ENOENT;
3318 	}
3319 
3320 	if (total_detect_count)
3321 		schedule_delayed_work(&ras->page_retirement_dwork, 0);
3322 
3323 	return 0;
3324 }
3325 
3326 static void amdgpu_ras_clear_poison_fifo(struct amdgpu_device *adev)
3327 {
3328 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3329 	struct ras_poison_msg msg;
3330 	int ret;
3331 
3332 	do {
3333 		ret = kfifo_get(&con->poison_fifo, &msg);
3334 	} while (ret);
3335 }
3336 
3337 static int amdgpu_ras_poison_consumption_handler(struct amdgpu_device *adev,
3338 			uint32_t msg_count, uint32_t *gpu_reset)
3339 {
3340 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3341 	uint32_t reset_flags = 0, reset = 0;
3342 	struct ras_poison_msg msg;
3343 	int ret, i;
3344 
3345 	kgd2kfd_set_sram_ecc_flag(adev->kfd.dev);
3346 
3347 	for (i = 0; i < msg_count; i++) {
3348 		ret = amdgpu_ras_get_poison_req(adev, &msg);
3349 		if (!ret)
3350 			continue;
3351 
3352 		if (msg.pasid_fn)
3353 			msg.pasid_fn(adev, msg.pasid, msg.data);
3354 
3355 		reset_flags |= msg.reset;
3356 	}
3357 
3358 	/* for RMA, amdgpu_ras_poison_creation_handler will trigger gpu reset */
3359 	if (reset_flags && !amdgpu_ras_is_rma(adev)) {
3360 		if (reset_flags & AMDGPU_RAS_GPU_RESET_MODE1_RESET)
3361 			reset = AMDGPU_RAS_GPU_RESET_MODE1_RESET;
3362 		else if (reset_flags & AMDGPU_RAS_GPU_RESET_MODE2_RESET)
3363 			reset = AMDGPU_RAS_GPU_RESET_MODE2_RESET;
3364 		else
3365 			reset = reset_flags;
3366 
3367 		flush_delayed_work(&con->page_retirement_dwork);
3368 
3369 		con->gpu_reset_flags |= reset;
3370 		amdgpu_ras_reset_gpu(adev);
3371 
3372 		*gpu_reset = reset;
3373 
3374 		/* Wait for gpu recovery to complete */
3375 		flush_work(&con->recovery_work);
3376 	}
3377 
3378 	return 0;
3379 }
3380 
3381 static int amdgpu_ras_page_retirement_thread(void *param)
3382 {
3383 	struct amdgpu_device *adev = (struct amdgpu_device *)param;
3384 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3385 	uint32_t poison_creation_count, msg_count;
3386 	uint32_t gpu_reset;
3387 	int ret;
3388 
3389 	while (!kthread_should_stop()) {
3390 
3391 		wait_event_interruptible(con->page_retirement_wq,
3392 				kthread_should_stop() ||
3393 				atomic_read(&con->page_retirement_req_cnt));
3394 
3395 		if (kthread_should_stop())
3396 			break;
3397 
3398 		gpu_reset = 0;
3399 
3400 		do {
3401 			poison_creation_count = atomic_read(&con->poison_creation_count);
3402 			ret = amdgpu_ras_poison_creation_handler(adev, poison_creation_count);
3403 			if (ret == -EIO)
3404 				break;
3405 
3406 			if (poison_creation_count) {
3407 				atomic_sub(poison_creation_count, &con->poison_creation_count);
3408 				atomic_sub(poison_creation_count, &con->page_retirement_req_cnt);
3409 			}
3410 		} while (atomic_read(&con->poison_creation_count));
3411 
3412 		if (ret != -EIO) {
3413 			msg_count = kfifo_len(&con->poison_fifo);
3414 			if (msg_count) {
3415 				ret = amdgpu_ras_poison_consumption_handler(adev,
3416 						msg_count, &gpu_reset);
3417 				if ((ret != -EIO) &&
3418 				    (gpu_reset != AMDGPU_RAS_GPU_RESET_MODE1_RESET))
3419 					atomic_sub(msg_count, &con->page_retirement_req_cnt);
3420 			}
3421 		}
3422 
3423 		if ((ret == -EIO) || (gpu_reset == AMDGPU_RAS_GPU_RESET_MODE1_RESET)) {
3424 			/* gpu mode-1 reset is ongoing or just completed ras mode-1 reset */
3425 			/* Clear poison creation request */
3426 			atomic_set(&con->poison_creation_count, 0);
3427 
3428 			/* Clear poison fifo */
3429 			amdgpu_ras_clear_poison_fifo(adev);
3430 
3431 			/* Clear all poison requests */
3432 			atomic_set(&con->page_retirement_req_cnt, 0);
3433 
3434 			if (ret == -EIO) {
3435 				/* Wait for mode-1 reset to complete */
3436 				down_read(&adev->reset_domain->sem);
3437 				up_read(&adev->reset_domain->sem);
3438 			}
3439 
3440 			/* Wake up work to save bad pages to eeprom */
3441 			schedule_delayed_work(&con->page_retirement_dwork, 0);
3442 		} else if (gpu_reset) {
3443 			/* gpu just completed mode-2 reset or other reset */
3444 			/* Clear poison consumption messages cached in fifo */
3445 			msg_count = kfifo_len(&con->poison_fifo);
3446 			if (msg_count) {
3447 				amdgpu_ras_clear_poison_fifo(adev);
3448 				atomic_sub(msg_count, &con->page_retirement_req_cnt);
3449 			}
3450 
3451 			/* Wake up work to save bad pages to eeprom */
3452 			schedule_delayed_work(&con->page_retirement_dwork, 0);
3453 		}
3454 	}
3455 
3456 	return 0;
3457 }
3458 
3459 int amdgpu_ras_init_badpage_info(struct amdgpu_device *adev)
3460 {
3461 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3462 	struct amdgpu_ras_eeprom_control *control;
3463 	int ret;
3464 
3465 	if (!con || amdgpu_sriov_vf(adev))
3466 		return 0;
3467 
3468 	control = &con->eeprom_control;
3469 	ret = amdgpu_ras_eeprom_init(control);
3470 	if (ret)
3471 		return ret;
3472 
3473 	if (!adev->umc.ras || !adev->umc.ras->convert_ras_err_addr)
3474 		control->ras_num_pa_recs = control->ras_num_recs;
3475 
3476 	if (adev->umc.ras &&
3477 	    adev->umc.ras->get_retire_flip_bits)
3478 		adev->umc.ras->get_retire_flip_bits(adev);
3479 
3480 	if (control->ras_num_recs) {
3481 		ret = amdgpu_ras_load_bad_pages(adev);
3482 		if (ret)
3483 			return ret;
3484 
3485 		amdgpu_dpm_send_hbm_bad_pages_num(
3486 			adev, control->ras_num_bad_pages);
3487 
3488 		if (con->update_channel_flag == true) {
3489 			amdgpu_dpm_send_hbm_bad_channel_flag(
3490 				adev, control->bad_channel_bitmap);
3491 			con->update_channel_flag = false;
3492 		}
3493 
3494 		/* The format action is only applied to new ASICs */
3495 		if (IP_VERSION_MAJ(amdgpu_ip_version(adev, UMC_HWIP, 0)) >= 12 &&
3496 		    control->tbl_hdr.version < RAS_TABLE_VER_V3)
3497 			if (!amdgpu_ras_eeprom_reset_table(control))
3498 				if (amdgpu_ras_save_bad_pages(adev, NULL))
3499 					dev_warn(adev->dev, "Failed to format RAS EEPROM data in V3 version!\n");
3500 	}
3501 
3502 	return ret;
3503 }
3504 
3505 int amdgpu_ras_recovery_init(struct amdgpu_device *adev, bool init_bp_info)
3506 {
3507 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3508 	struct ras_err_handler_data **data;
3509 	u32  max_eeprom_records_count = 0;
3510 	int ret;
3511 
3512 	if (!con || amdgpu_sriov_vf(adev))
3513 		return 0;
3514 
3515 	/* Allow access to RAS EEPROM via debugfs, when the ASIC
3516 	 * supports RAS and debugfs is enabled, but when
3517 	 * adev->ras_enabled is unset, i.e. when "ras_enable"
3518 	 * module parameter is set to 0.
3519 	 */
3520 	con->adev = adev;
3521 
3522 	if (!adev->ras_enabled)
3523 		return 0;
3524 
3525 	data = &con->eh_data;
3526 	*data = kzalloc(sizeof(**data), GFP_KERNEL);
3527 	if (!*data) {
3528 		ret = -ENOMEM;
3529 		goto out;
3530 	}
3531 
3532 	mutex_init(&con->recovery_lock);
3533 	INIT_WORK(&con->recovery_work, amdgpu_ras_do_recovery);
3534 	atomic_set(&con->in_recovery, 0);
3535 	con->eeprom_control.bad_channel_bitmap = 0;
3536 
3537 	max_eeprom_records_count = amdgpu_ras_eeprom_max_record_count(&con->eeprom_control);
3538 	amdgpu_ras_validate_threshold(adev, max_eeprom_records_count);
3539 
3540 	if (init_bp_info) {
3541 		ret = amdgpu_ras_init_badpage_info(adev);
3542 		if (ret)
3543 			goto free;
3544 	}
3545 
3546 	mutex_init(&con->page_rsv_lock);
3547 	INIT_KFIFO(con->poison_fifo);
3548 	mutex_init(&con->page_retirement_lock);
3549 	init_waitqueue_head(&con->page_retirement_wq);
3550 	atomic_set(&con->page_retirement_req_cnt, 0);
3551 	atomic_set(&con->poison_creation_count, 0);
3552 	con->page_retirement_thread =
3553 		kthread_run(amdgpu_ras_page_retirement_thread, adev, "umc_page_retirement");
3554 	if (IS_ERR(con->page_retirement_thread)) {
3555 		con->page_retirement_thread = NULL;
3556 		dev_warn(adev->dev, "Failed to create umc_page_retirement thread!!!\n");
3557 	}
3558 
3559 	INIT_DELAYED_WORK(&con->page_retirement_dwork, amdgpu_ras_do_page_retirement);
3560 	amdgpu_ras_ecc_log_init(&con->umc_ecc_log);
3561 #ifdef CONFIG_X86_MCE_AMD
3562 	if ((adev->asic_type == CHIP_ALDEBARAN) &&
3563 	    (adev->gmc.xgmi.connected_to_cpu))
3564 		amdgpu_register_bad_pages_mca_notifier(adev);
3565 #endif
3566 	return 0;
3567 
3568 free:
3569 	kfree((*data)->bps);
3570 	kfree(*data);
3571 	con->eh_data = NULL;
3572 out:
3573 	dev_warn(adev->dev, "Failed to initialize ras recovery! (%d)\n", ret);
3574 
3575 	/*
3576 	 * Except error threshold exceeding case, other failure cases in this
3577 	 * function would not fail amdgpu driver init.
3578 	 */
3579 	if (!amdgpu_ras_is_rma(adev))
3580 		ret = 0;
3581 	else
3582 		ret = -EINVAL;
3583 
3584 	return ret;
3585 }
3586 
3587 static int amdgpu_ras_recovery_fini(struct amdgpu_device *adev)
3588 {
3589 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3590 	struct ras_err_handler_data *data = con->eh_data;
3591 	int max_flush_timeout = MAX_FLUSH_RETIRE_DWORK_TIMES;
3592 	bool ret;
3593 
3594 	/* recovery_init failed to init it, fini is useless */
3595 	if (!data)
3596 		return 0;
3597 
3598 	/* Save all cached bad pages to eeprom */
3599 	do {
3600 		flush_delayed_work(&con->page_retirement_dwork);
3601 		ret = amdgpu_ras_schedule_retirement_dwork(con, 0);
3602 	} while (ret && max_flush_timeout--);
3603 
3604 	if (con->page_retirement_thread)
3605 		kthread_stop(con->page_retirement_thread);
3606 
3607 	atomic_set(&con->page_retirement_req_cnt, 0);
3608 	atomic_set(&con->poison_creation_count, 0);
3609 
3610 	mutex_destroy(&con->page_rsv_lock);
3611 
3612 	cancel_work_sync(&con->recovery_work);
3613 
3614 	cancel_delayed_work_sync(&con->page_retirement_dwork);
3615 
3616 	amdgpu_ras_ecc_log_fini(&con->umc_ecc_log);
3617 
3618 	mutex_lock(&con->recovery_lock);
3619 	con->eh_data = NULL;
3620 	kfree(data->bps);
3621 	kfree(data);
3622 	mutex_unlock(&con->recovery_lock);
3623 
3624 	return 0;
3625 }
3626 /* recovery end */
3627 
3628 static bool amdgpu_ras_asic_supported(struct amdgpu_device *adev)
3629 {
3630 	if (amdgpu_sriov_vf(adev)) {
3631 		switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
3632 		case IP_VERSION(13, 0, 2):
3633 		case IP_VERSION(13, 0, 6):
3634 		case IP_VERSION(13, 0, 12):
3635 		case IP_VERSION(13, 0, 14):
3636 			return true;
3637 		default:
3638 			return false;
3639 		}
3640 	}
3641 
3642 	if (adev->asic_type == CHIP_IP_DISCOVERY) {
3643 		switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
3644 		case IP_VERSION(13, 0, 0):
3645 		case IP_VERSION(13, 0, 6):
3646 		case IP_VERSION(13, 0, 10):
3647 		case IP_VERSION(13, 0, 12):
3648 		case IP_VERSION(13, 0, 14):
3649 		case IP_VERSION(14, 0, 3):
3650 			return true;
3651 		default:
3652 			return false;
3653 		}
3654 	}
3655 
3656 	return adev->asic_type == CHIP_VEGA10 ||
3657 		adev->asic_type == CHIP_VEGA20 ||
3658 		adev->asic_type == CHIP_ARCTURUS ||
3659 		adev->asic_type == CHIP_ALDEBARAN ||
3660 		adev->asic_type == CHIP_SIENNA_CICHLID;
3661 }
3662 
3663 /*
3664  * this is workaround for vega20 workstation sku,
3665  * force enable gfx ras, ignore vbios gfx ras flag
3666  * due to GC EDC can not write
3667  */
3668 static void amdgpu_ras_get_quirks(struct amdgpu_device *adev)
3669 {
3670 	struct atom_context *ctx = adev->mode_info.atom_context;
3671 
3672 	if (!ctx)
3673 		return;
3674 
3675 	if (strnstr(ctx->vbios_pn, "D16406",
3676 		    sizeof(ctx->vbios_pn)) ||
3677 		strnstr(ctx->vbios_pn, "D36002",
3678 			sizeof(ctx->vbios_pn)))
3679 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__GFX);
3680 }
3681 
3682 /* Query ras capablity via atomfirmware interface */
3683 static void amdgpu_ras_query_ras_capablity_from_vbios(struct amdgpu_device *adev)
3684 {
3685 	/* mem_ecc cap */
3686 	if (amdgpu_atomfirmware_mem_ecc_supported(adev)) {
3687 		dev_info(adev->dev, "MEM ECC is active.\n");
3688 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__UMC |
3689 					 1 << AMDGPU_RAS_BLOCK__DF);
3690 	} else {
3691 		dev_info(adev->dev, "MEM ECC is not presented.\n");
3692 	}
3693 
3694 	/* sram_ecc cap */
3695 	if (amdgpu_atomfirmware_sram_ecc_supported(adev)) {
3696 		dev_info(adev->dev, "SRAM ECC is active.\n");
3697 		if (!amdgpu_sriov_vf(adev))
3698 			adev->ras_hw_enabled |= ~(1 << AMDGPU_RAS_BLOCK__UMC |
3699 						  1 << AMDGPU_RAS_BLOCK__DF);
3700 		else
3701 			adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__PCIE_BIF |
3702 						 1 << AMDGPU_RAS_BLOCK__SDMA |
3703 						 1 << AMDGPU_RAS_BLOCK__GFX);
3704 
3705 		/*
3706 		 * VCN/JPEG RAS can be supported on both bare metal and
3707 		 * SRIOV environment
3708 		 */
3709 		if (amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(2, 6, 0) ||
3710 		    amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(4, 0, 0) ||
3711 		    amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(4, 0, 3))
3712 			adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__VCN |
3713 						 1 << AMDGPU_RAS_BLOCK__JPEG);
3714 		else
3715 			adev->ras_hw_enabled &= ~(1 << AMDGPU_RAS_BLOCK__VCN |
3716 						  1 << AMDGPU_RAS_BLOCK__JPEG);
3717 
3718 		/*
3719 		 * XGMI RAS is not supported if xgmi num physical nodes
3720 		 * is zero
3721 		 */
3722 		if (!adev->gmc.xgmi.num_physical_nodes)
3723 			adev->ras_hw_enabled &= ~(1 << AMDGPU_RAS_BLOCK__XGMI_WAFL);
3724 	} else {
3725 		dev_info(adev->dev, "SRAM ECC is not presented.\n");
3726 	}
3727 }
3728 
3729 /* Query poison mode from umc/df IP callbacks */
3730 static void amdgpu_ras_query_poison_mode(struct amdgpu_device *adev)
3731 {
3732 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3733 	bool df_poison, umc_poison;
3734 
3735 	/* poison setting is useless on SRIOV guest */
3736 	if (amdgpu_sriov_vf(adev) || !con)
3737 		return;
3738 
3739 	/* Init poison supported flag, the default value is false */
3740 	if (adev->gmc.xgmi.connected_to_cpu ||
3741 	    adev->gmc.is_app_apu) {
3742 		/* enabled by default when GPU is connected to CPU */
3743 		con->poison_supported = true;
3744 	} else if (adev->df.funcs &&
3745 	    adev->df.funcs->query_ras_poison_mode &&
3746 	    adev->umc.ras &&
3747 	    adev->umc.ras->query_ras_poison_mode) {
3748 		df_poison =
3749 			adev->df.funcs->query_ras_poison_mode(adev);
3750 		umc_poison =
3751 			adev->umc.ras->query_ras_poison_mode(adev);
3752 
3753 		/* Only poison is set in both DF and UMC, we can support it */
3754 		if (df_poison && umc_poison)
3755 			con->poison_supported = true;
3756 		else if (df_poison != umc_poison)
3757 			dev_warn(adev->dev,
3758 				"Poison setting is inconsistent in DF/UMC(%d:%d)!\n",
3759 				df_poison, umc_poison);
3760 	}
3761 }
3762 
3763 /*
3764  * check hardware's ras ability which will be saved in hw_supported.
3765  * if hardware does not support ras, we can skip some ras initializtion and
3766  * forbid some ras operations from IP.
3767  * if software itself, say boot parameter, limit the ras ability. We still
3768  * need allow IP do some limited operations, like disable. In such case,
3769  * we have to initialize ras as normal. but need check if operation is
3770  * allowed or not in each function.
3771  */
3772 static void amdgpu_ras_check_supported(struct amdgpu_device *adev)
3773 {
3774 	adev->ras_hw_enabled = adev->ras_enabled = 0;
3775 
3776 	if (!amdgpu_ras_asic_supported(adev))
3777 		return;
3778 
3779 	if (amdgpu_sriov_vf(adev)) {
3780 		if (amdgpu_virt_get_ras_capability(adev))
3781 			goto init_ras_enabled_flag;
3782 	}
3783 
3784 	/* query ras capability from psp */
3785 	if (amdgpu_psp_get_ras_capability(&adev->psp))
3786 		goto init_ras_enabled_flag;
3787 
3788 	/* query ras capablity from bios */
3789 	if (!adev->gmc.xgmi.connected_to_cpu && !adev->gmc.is_app_apu) {
3790 		amdgpu_ras_query_ras_capablity_from_vbios(adev);
3791 	} else {
3792 		/* driver only manages a few IP blocks RAS feature
3793 		 * when GPU is connected cpu through XGMI */
3794 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__GFX |
3795 					   1 << AMDGPU_RAS_BLOCK__SDMA |
3796 					   1 << AMDGPU_RAS_BLOCK__MMHUB);
3797 	}
3798 
3799 	/* apply asic specific settings (vega20 only for now) */
3800 	amdgpu_ras_get_quirks(adev);
3801 
3802 	/* query poison mode from umc/df ip callback */
3803 	amdgpu_ras_query_poison_mode(adev);
3804 
3805 init_ras_enabled_flag:
3806 	/* hw_supported needs to be aligned with RAS block mask. */
3807 	adev->ras_hw_enabled &= AMDGPU_RAS_BLOCK_MASK;
3808 
3809 	adev->ras_enabled = amdgpu_ras_enable == 0 ? 0 :
3810 		adev->ras_hw_enabled & amdgpu_ras_mask;
3811 
3812 	/* aca is disabled by default except for psp v13_0_6/v13_0_12/v13_0_14 */
3813 	if (!amdgpu_sriov_vf(adev)) {
3814 		adev->aca.is_enabled =
3815 			(amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 6) ||
3816 			amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 12) ||
3817 			amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 14));
3818 	}
3819 
3820 	/* bad page feature is not applicable to specific app platform */
3821 	if (adev->gmc.is_app_apu &&
3822 	    amdgpu_ip_version(adev, UMC_HWIP, 0) == IP_VERSION(12, 0, 0))
3823 		amdgpu_bad_page_threshold = 0;
3824 }
3825 
3826 static void amdgpu_ras_counte_dw(struct work_struct *work)
3827 {
3828 	struct amdgpu_ras *con = container_of(work, struct amdgpu_ras,
3829 					      ras_counte_delay_work.work);
3830 	struct amdgpu_device *adev = con->adev;
3831 	struct drm_device *dev = adev_to_drm(adev);
3832 	unsigned long ce_count, ue_count;
3833 	int res;
3834 
3835 	res = pm_runtime_get_sync(dev->dev);
3836 	if (res < 0)
3837 		goto Out;
3838 
3839 	/* Cache new values.
3840 	 */
3841 	if (amdgpu_ras_query_error_count(adev, &ce_count, &ue_count, NULL) == 0) {
3842 		atomic_set(&con->ras_ce_count, ce_count);
3843 		atomic_set(&con->ras_ue_count, ue_count);
3844 	}
3845 
3846 	pm_runtime_mark_last_busy(dev->dev);
3847 Out:
3848 	pm_runtime_put_autosuspend(dev->dev);
3849 }
3850 
3851 static int amdgpu_get_ras_schema(struct amdgpu_device *adev)
3852 {
3853 	return  amdgpu_ras_is_poison_mode_supported(adev) ? AMDGPU_RAS_ERROR__POISON : 0 |
3854 			AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE |
3855 			AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE |
3856 			AMDGPU_RAS_ERROR__PARITY;
3857 }
3858 
3859 static void ras_event_mgr_init(struct ras_event_manager *mgr)
3860 {
3861 	struct ras_event_state *event_state;
3862 	int i;
3863 
3864 	memset(mgr, 0, sizeof(*mgr));
3865 	atomic64_set(&mgr->seqno, 0);
3866 
3867 	for (i = 0; i < ARRAY_SIZE(mgr->event_state); i++) {
3868 		event_state = &mgr->event_state[i];
3869 		event_state->last_seqno = RAS_EVENT_INVALID_ID;
3870 		atomic64_set(&event_state->count, 0);
3871 	}
3872 }
3873 
3874 static void amdgpu_ras_event_mgr_init(struct amdgpu_device *adev)
3875 {
3876 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
3877 	struct amdgpu_hive_info *hive;
3878 
3879 	if (!ras)
3880 		return;
3881 
3882 	hive = amdgpu_get_xgmi_hive(adev);
3883 	ras->event_mgr = hive ? &hive->event_mgr : &ras->__event_mgr;
3884 
3885 	/* init event manager with node 0 on xgmi system */
3886 	if (!amdgpu_reset_in_recovery(adev)) {
3887 		if (!hive || adev->gmc.xgmi.node_id == 0)
3888 			ras_event_mgr_init(ras->event_mgr);
3889 	}
3890 
3891 	if (hive)
3892 		amdgpu_put_xgmi_hive(hive);
3893 }
3894 
3895 static void amdgpu_ras_init_reserved_vram_size(struct amdgpu_device *adev)
3896 {
3897 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3898 
3899 	if (!con || (adev->flags & AMD_IS_APU))
3900 		return;
3901 
3902 	switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
3903 	case IP_VERSION(13, 0, 2):
3904 	case IP_VERSION(13, 0, 6):
3905 	case IP_VERSION(13, 0, 12):
3906 		con->reserved_pages_in_bytes = AMDGPU_RAS_RESERVED_VRAM_SIZE_DEFAULT;
3907 		break;
3908 	case IP_VERSION(13, 0, 14):
3909 		con->reserved_pages_in_bytes = (AMDGPU_RAS_RESERVED_VRAM_SIZE_DEFAULT << 1);
3910 		break;
3911 	default:
3912 		break;
3913 	}
3914 }
3915 
3916 int amdgpu_ras_init(struct amdgpu_device *adev)
3917 {
3918 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3919 	int r;
3920 
3921 	if (con)
3922 		return 0;
3923 
3924 	con = kzalloc(sizeof(*con) +
3925 			sizeof(struct ras_manager) * AMDGPU_RAS_BLOCK_COUNT +
3926 			sizeof(struct ras_manager) * AMDGPU_RAS_MCA_BLOCK_COUNT,
3927 			GFP_KERNEL);
3928 	if (!con)
3929 		return -ENOMEM;
3930 
3931 	con->adev = adev;
3932 	INIT_DELAYED_WORK(&con->ras_counte_delay_work, amdgpu_ras_counte_dw);
3933 	atomic_set(&con->ras_ce_count, 0);
3934 	atomic_set(&con->ras_ue_count, 0);
3935 
3936 	con->objs = (struct ras_manager *)(con + 1);
3937 
3938 	amdgpu_ras_set_context(adev, con);
3939 
3940 	amdgpu_ras_check_supported(adev);
3941 
3942 	if (!adev->ras_enabled || adev->asic_type == CHIP_VEGA10) {
3943 		/* set gfx block ras context feature for VEGA20 Gaming
3944 		 * send ras disable cmd to ras ta during ras late init.
3945 		 */
3946 		if (!adev->ras_enabled && adev->asic_type == CHIP_VEGA20) {
3947 			con->features |= BIT(AMDGPU_RAS_BLOCK__GFX);
3948 
3949 			return 0;
3950 		}
3951 
3952 		r = 0;
3953 		goto release_con;
3954 	}
3955 
3956 	con->update_channel_flag = false;
3957 	con->features = 0;
3958 	con->schema = 0;
3959 	INIT_LIST_HEAD(&con->head);
3960 	/* Might need get this flag from vbios. */
3961 	con->flags = RAS_DEFAULT_FLAGS;
3962 
3963 	/* initialize nbio ras function ahead of any other
3964 	 * ras functions so hardware fatal error interrupt
3965 	 * can be enabled as early as possible */
3966 	switch (amdgpu_ip_version(adev, NBIO_HWIP, 0)) {
3967 	case IP_VERSION(7, 4, 0):
3968 	case IP_VERSION(7, 4, 1):
3969 	case IP_VERSION(7, 4, 4):
3970 		if (!adev->gmc.xgmi.connected_to_cpu)
3971 			adev->nbio.ras = &nbio_v7_4_ras;
3972 		break;
3973 	case IP_VERSION(4, 3, 0):
3974 		if (adev->ras_hw_enabled & (1 << AMDGPU_RAS_BLOCK__DF))
3975 			/* unlike other generation of nbio ras,
3976 			 * nbio v4_3 only support fatal error interrupt
3977 			 * to inform software that DF is freezed due to
3978 			 * system fatal error event. driver should not
3979 			 * enable nbio ras in such case. Instead,
3980 			 * check DF RAS */
3981 			adev->nbio.ras = &nbio_v4_3_ras;
3982 		break;
3983 	case IP_VERSION(6, 3, 1):
3984 		if (adev->ras_hw_enabled & (1 << AMDGPU_RAS_BLOCK__DF))
3985 			/* unlike other generation of nbio ras,
3986 			 * nbif v6_3_1 only support fatal error interrupt
3987 			 * to inform software that DF is freezed due to
3988 			 * system fatal error event. driver should not
3989 			 * enable nbio ras in such case. Instead,
3990 			 * check DF RAS
3991 			 */
3992 			adev->nbio.ras = &nbif_v6_3_1_ras;
3993 		break;
3994 	case IP_VERSION(7, 9, 0):
3995 	case IP_VERSION(7, 9, 1):
3996 		if (!adev->gmc.is_app_apu)
3997 			adev->nbio.ras = &nbio_v7_9_ras;
3998 		break;
3999 	default:
4000 		/* nbio ras is not available */
4001 		break;
4002 	}
4003 
4004 	/* nbio ras block needs to be enabled ahead of other ras blocks
4005 	 * to handle fatal error */
4006 	r = amdgpu_nbio_ras_sw_init(adev);
4007 	if (r)
4008 		return r;
4009 
4010 	if (adev->nbio.ras &&
4011 	    adev->nbio.ras->init_ras_controller_interrupt) {
4012 		r = adev->nbio.ras->init_ras_controller_interrupt(adev);
4013 		if (r)
4014 			goto release_con;
4015 	}
4016 
4017 	if (adev->nbio.ras &&
4018 	    adev->nbio.ras->init_ras_err_event_athub_interrupt) {
4019 		r = adev->nbio.ras->init_ras_err_event_athub_interrupt(adev);
4020 		if (r)
4021 			goto release_con;
4022 	}
4023 
4024 	/* Packed socket_id to ras feature mask bits[31:29] */
4025 	if (adev->smuio.funcs &&
4026 	    adev->smuio.funcs->get_socket_id)
4027 		con->features |= ((adev->smuio.funcs->get_socket_id(adev)) <<
4028 					AMDGPU_RAS_FEATURES_SOCKETID_SHIFT);
4029 
4030 	/* Get RAS schema for particular SOC */
4031 	con->schema = amdgpu_get_ras_schema(adev);
4032 
4033 	amdgpu_ras_init_reserved_vram_size(adev);
4034 
4035 	if (amdgpu_ras_fs_init(adev)) {
4036 		r = -EINVAL;
4037 		goto release_con;
4038 	}
4039 
4040 	if (amdgpu_ras_aca_is_supported(adev)) {
4041 		if (amdgpu_aca_is_enabled(adev))
4042 			r = amdgpu_aca_init(adev);
4043 		else
4044 			r = amdgpu_mca_init(adev);
4045 		if (r)
4046 			goto release_con;
4047 	}
4048 
4049 	dev_info(adev->dev, "RAS INFO: ras initialized successfully, "
4050 		 "hardware ability[%x] ras_mask[%x]\n",
4051 		 adev->ras_hw_enabled, adev->ras_enabled);
4052 
4053 	return 0;
4054 release_con:
4055 	amdgpu_ras_set_context(adev, NULL);
4056 	kfree(con);
4057 
4058 	return r;
4059 }
4060 
4061 int amdgpu_persistent_edc_harvesting_supported(struct amdgpu_device *adev)
4062 {
4063 	if (adev->gmc.xgmi.connected_to_cpu ||
4064 	    adev->gmc.is_app_apu)
4065 		return 1;
4066 	return 0;
4067 }
4068 
4069 static int amdgpu_persistent_edc_harvesting(struct amdgpu_device *adev,
4070 					struct ras_common_if *ras_block)
4071 {
4072 	struct ras_query_if info = {
4073 		.head = *ras_block,
4074 	};
4075 
4076 	if (!amdgpu_persistent_edc_harvesting_supported(adev))
4077 		return 0;
4078 
4079 	if (amdgpu_ras_query_error_status(adev, &info) != 0)
4080 		DRM_WARN("RAS init harvest failure");
4081 
4082 	if (amdgpu_ras_reset_error_status(adev, ras_block->block) != 0)
4083 		DRM_WARN("RAS init harvest reset failure");
4084 
4085 	return 0;
4086 }
4087 
4088 bool amdgpu_ras_is_poison_mode_supported(struct amdgpu_device *adev)
4089 {
4090        struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4091 
4092        if (!con)
4093                return false;
4094 
4095        return con->poison_supported;
4096 }
4097 
4098 /* helper function to handle common stuff in ip late init phase */
4099 int amdgpu_ras_block_late_init(struct amdgpu_device *adev,
4100 			 struct ras_common_if *ras_block)
4101 {
4102 	struct amdgpu_ras_block_object *ras_obj = NULL;
4103 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4104 	struct ras_query_if *query_info;
4105 	unsigned long ue_count, ce_count;
4106 	int r;
4107 
4108 	/* disable RAS feature per IP block if it is not supported */
4109 	if (!amdgpu_ras_is_supported(adev, ras_block->block)) {
4110 		amdgpu_ras_feature_enable_on_boot(adev, ras_block, 0);
4111 		return 0;
4112 	}
4113 
4114 	r = amdgpu_ras_feature_enable_on_boot(adev, ras_block, 1);
4115 	if (r) {
4116 		if (adev->in_suspend || amdgpu_reset_in_recovery(adev)) {
4117 			/* in resume phase, if fail to enable ras,
4118 			 * clean up all ras fs nodes, and disable ras */
4119 			goto cleanup;
4120 		} else
4121 			return r;
4122 	}
4123 
4124 	/* check for errors on warm reset edc persisant supported ASIC */
4125 	amdgpu_persistent_edc_harvesting(adev, ras_block);
4126 
4127 	/* in resume phase, no need to create ras fs node */
4128 	if (adev->in_suspend || amdgpu_reset_in_recovery(adev))
4129 		return 0;
4130 
4131 	ras_obj = container_of(ras_block, struct amdgpu_ras_block_object, ras_comm);
4132 	if (ras_obj->ras_cb || (ras_obj->hw_ops &&
4133 	    (ras_obj->hw_ops->query_poison_status ||
4134 	    ras_obj->hw_ops->handle_poison_consumption))) {
4135 		r = amdgpu_ras_interrupt_add_handler(adev, ras_block);
4136 		if (r)
4137 			goto cleanup;
4138 	}
4139 
4140 	if (ras_obj->hw_ops &&
4141 	    (ras_obj->hw_ops->query_ras_error_count ||
4142 	     ras_obj->hw_ops->query_ras_error_status)) {
4143 		r = amdgpu_ras_sysfs_create(adev, ras_block);
4144 		if (r)
4145 			goto interrupt;
4146 
4147 		/* Those are the cached values at init.
4148 		 */
4149 		query_info = kzalloc(sizeof(*query_info), GFP_KERNEL);
4150 		if (!query_info)
4151 			return -ENOMEM;
4152 		memcpy(&query_info->head, ras_block, sizeof(struct ras_common_if));
4153 
4154 		if (amdgpu_ras_query_error_count(adev, &ce_count, &ue_count, query_info) == 0) {
4155 			atomic_set(&con->ras_ce_count, ce_count);
4156 			atomic_set(&con->ras_ue_count, ue_count);
4157 		}
4158 
4159 		kfree(query_info);
4160 	}
4161 
4162 	return 0;
4163 
4164 interrupt:
4165 	if (ras_obj->ras_cb)
4166 		amdgpu_ras_interrupt_remove_handler(adev, ras_block);
4167 cleanup:
4168 	amdgpu_ras_feature_enable(adev, ras_block, 0);
4169 	return r;
4170 }
4171 
4172 static int amdgpu_ras_block_late_init_default(struct amdgpu_device *adev,
4173 			 struct ras_common_if *ras_block)
4174 {
4175 	return amdgpu_ras_block_late_init(adev, ras_block);
4176 }
4177 
4178 /* helper function to remove ras fs node and interrupt handler */
4179 void amdgpu_ras_block_late_fini(struct amdgpu_device *adev,
4180 			  struct ras_common_if *ras_block)
4181 {
4182 	struct amdgpu_ras_block_object *ras_obj;
4183 	if (!ras_block)
4184 		return;
4185 
4186 	amdgpu_ras_sysfs_remove(adev, ras_block);
4187 
4188 	ras_obj = container_of(ras_block, struct amdgpu_ras_block_object, ras_comm);
4189 	if (ras_obj->ras_cb)
4190 		amdgpu_ras_interrupt_remove_handler(adev, ras_block);
4191 }
4192 
4193 static void amdgpu_ras_block_late_fini_default(struct amdgpu_device *adev,
4194 			  struct ras_common_if *ras_block)
4195 {
4196 	return amdgpu_ras_block_late_fini(adev, ras_block);
4197 }
4198 
4199 /* do some init work after IP late init as dependence.
4200  * and it runs in resume/gpu reset/booting up cases.
4201  */
4202 void amdgpu_ras_resume(struct amdgpu_device *adev)
4203 {
4204 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4205 	struct ras_manager *obj, *tmp;
4206 
4207 	if (!adev->ras_enabled || !con) {
4208 		/* clean ras context for VEGA20 Gaming after send ras disable cmd */
4209 		amdgpu_release_ras_context(adev);
4210 
4211 		return;
4212 	}
4213 
4214 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
4215 		/* Set up all other IPs which are not implemented. There is a
4216 		 * tricky thing that IP's actual ras error type should be
4217 		 * MULTI_UNCORRECTABLE, but as driver does not handle it, so
4218 		 * ERROR_NONE make sense anyway.
4219 		 */
4220 		amdgpu_ras_enable_all_features(adev, 1);
4221 
4222 		/* We enable ras on all hw_supported block, but as boot
4223 		 * parameter might disable some of them and one or more IP has
4224 		 * not implemented yet. So we disable them on behalf.
4225 		 */
4226 		list_for_each_entry_safe(obj, tmp, &con->head, node) {
4227 			if (!amdgpu_ras_is_supported(adev, obj->head.block)) {
4228 				amdgpu_ras_feature_enable(adev, &obj->head, 0);
4229 				/* there should be no any reference. */
4230 				WARN_ON(alive_obj(obj));
4231 			}
4232 		}
4233 	}
4234 }
4235 
4236 void amdgpu_ras_suspend(struct amdgpu_device *adev)
4237 {
4238 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4239 
4240 	if (!adev->ras_enabled || !con)
4241 		return;
4242 
4243 	amdgpu_ras_disable_all_features(adev, 0);
4244 	/* Make sure all ras objects are disabled. */
4245 	if (AMDGPU_RAS_GET_FEATURES(con->features))
4246 		amdgpu_ras_disable_all_features(adev, 1);
4247 }
4248 
4249 int amdgpu_ras_late_init(struct amdgpu_device *adev)
4250 {
4251 	struct amdgpu_ras_block_list *node, *tmp;
4252 	struct amdgpu_ras_block_object *obj;
4253 	int r;
4254 
4255 	amdgpu_ras_event_mgr_init(adev);
4256 
4257 	if (amdgpu_ras_aca_is_supported(adev)) {
4258 		if (amdgpu_reset_in_recovery(adev)) {
4259 			if (amdgpu_aca_is_enabled(adev))
4260 				r = amdgpu_aca_reset(adev);
4261 			else
4262 				r = amdgpu_mca_reset(adev);
4263 			if (r)
4264 				return r;
4265 		}
4266 
4267 		if (!amdgpu_sriov_vf(adev)) {
4268 			if (amdgpu_aca_is_enabled(adev))
4269 				amdgpu_ras_set_aca_debug_mode(adev, false);
4270 			else
4271 				amdgpu_ras_set_mca_debug_mode(adev, false);
4272 		}
4273 	}
4274 
4275 	/* Guest side doesn't need init ras feature */
4276 	if (amdgpu_sriov_vf(adev) && !amdgpu_sriov_ras_telemetry_en(adev))
4277 		return 0;
4278 
4279 	list_for_each_entry_safe(node, tmp, &adev->ras_list, node) {
4280 		obj = node->ras_obj;
4281 		if (!obj) {
4282 			dev_warn(adev->dev, "Warning: abnormal ras list node.\n");
4283 			continue;
4284 		}
4285 
4286 		if (!amdgpu_ras_is_supported(adev, obj->ras_comm.block))
4287 			continue;
4288 
4289 		if (obj->ras_late_init) {
4290 			r = obj->ras_late_init(adev, &obj->ras_comm);
4291 			if (r) {
4292 				dev_err(adev->dev, "%s failed to execute ras_late_init! ret:%d\n",
4293 					obj->ras_comm.name, r);
4294 				return r;
4295 			}
4296 		} else
4297 			amdgpu_ras_block_late_init_default(adev, &obj->ras_comm);
4298 	}
4299 
4300 	return 0;
4301 }
4302 
4303 /* do some fini work before IP fini as dependence */
4304 int amdgpu_ras_pre_fini(struct amdgpu_device *adev)
4305 {
4306 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4307 
4308 	if (!adev->ras_enabled || !con)
4309 		return 0;
4310 
4311 
4312 	/* Need disable ras on all IPs here before ip [hw/sw]fini */
4313 	if (AMDGPU_RAS_GET_FEATURES(con->features))
4314 		amdgpu_ras_disable_all_features(adev, 0);
4315 	amdgpu_ras_recovery_fini(adev);
4316 	return 0;
4317 }
4318 
4319 int amdgpu_ras_fini(struct amdgpu_device *adev)
4320 {
4321 	struct amdgpu_ras_block_list *ras_node, *tmp;
4322 	struct amdgpu_ras_block_object *obj = NULL;
4323 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4324 
4325 	if (!adev->ras_enabled || !con)
4326 		return 0;
4327 
4328 	list_for_each_entry_safe(ras_node, tmp, &adev->ras_list, node) {
4329 		if (ras_node->ras_obj) {
4330 			obj = ras_node->ras_obj;
4331 			if (amdgpu_ras_is_supported(adev, obj->ras_comm.block) &&
4332 			    obj->ras_fini)
4333 				obj->ras_fini(adev, &obj->ras_comm);
4334 			else
4335 				amdgpu_ras_block_late_fini_default(adev, &obj->ras_comm);
4336 		}
4337 
4338 		/* Clear ras blocks from ras_list and free ras block list node */
4339 		list_del(&ras_node->node);
4340 		kfree(ras_node);
4341 	}
4342 
4343 	amdgpu_ras_fs_fini(adev);
4344 	amdgpu_ras_interrupt_remove_all(adev);
4345 
4346 	if (amdgpu_ras_aca_is_supported(adev)) {
4347 		if (amdgpu_aca_is_enabled(adev))
4348 			amdgpu_aca_fini(adev);
4349 		else
4350 			amdgpu_mca_fini(adev);
4351 	}
4352 
4353 	WARN(AMDGPU_RAS_GET_FEATURES(con->features), "Feature mask is not cleared");
4354 
4355 	if (AMDGPU_RAS_GET_FEATURES(con->features))
4356 		amdgpu_ras_disable_all_features(adev, 0);
4357 
4358 	cancel_delayed_work_sync(&con->ras_counte_delay_work);
4359 
4360 	amdgpu_ras_set_context(adev, NULL);
4361 	kfree(con);
4362 
4363 	return 0;
4364 }
4365 
4366 bool amdgpu_ras_get_fed_status(struct amdgpu_device *adev)
4367 {
4368 	struct amdgpu_ras *ras;
4369 
4370 	ras = amdgpu_ras_get_context(adev);
4371 	if (!ras)
4372 		return false;
4373 
4374 	return test_bit(AMDGPU_RAS_BLOCK__LAST, &ras->ras_err_state);
4375 }
4376 
4377 void amdgpu_ras_set_fed(struct amdgpu_device *adev, bool status)
4378 {
4379 	struct amdgpu_ras *ras;
4380 
4381 	ras = amdgpu_ras_get_context(adev);
4382 	if (ras) {
4383 		if (status)
4384 			set_bit(AMDGPU_RAS_BLOCK__LAST, &ras->ras_err_state);
4385 		else
4386 			clear_bit(AMDGPU_RAS_BLOCK__LAST, &ras->ras_err_state);
4387 	}
4388 }
4389 
4390 void amdgpu_ras_clear_err_state(struct amdgpu_device *adev)
4391 {
4392 	struct amdgpu_ras *ras;
4393 
4394 	ras = amdgpu_ras_get_context(adev);
4395 	if (ras)
4396 		ras->ras_err_state = 0;
4397 }
4398 
4399 void amdgpu_ras_set_err_poison(struct amdgpu_device *adev,
4400 			       enum amdgpu_ras_block block)
4401 {
4402 	struct amdgpu_ras *ras;
4403 
4404 	ras = amdgpu_ras_get_context(adev);
4405 	if (ras)
4406 		set_bit(block, &ras->ras_err_state);
4407 }
4408 
4409 bool amdgpu_ras_is_err_state(struct amdgpu_device *adev, int block)
4410 {
4411 	struct amdgpu_ras *ras;
4412 
4413 	ras = amdgpu_ras_get_context(adev);
4414 	if (ras) {
4415 		if (block == AMDGPU_RAS_BLOCK__ANY)
4416 			return (ras->ras_err_state != 0);
4417 		else
4418 			return test_bit(block, &ras->ras_err_state) ||
4419 			       test_bit(AMDGPU_RAS_BLOCK__LAST,
4420 					&ras->ras_err_state);
4421 	}
4422 
4423 	return false;
4424 }
4425 
4426 static struct ras_event_manager *__get_ras_event_mgr(struct amdgpu_device *adev)
4427 {
4428 	struct amdgpu_ras *ras;
4429 
4430 	ras = amdgpu_ras_get_context(adev);
4431 	if (!ras)
4432 		return NULL;
4433 
4434 	return ras->event_mgr;
4435 }
4436 
4437 int amdgpu_ras_mark_ras_event_caller(struct amdgpu_device *adev, enum ras_event_type type,
4438 				     const void *caller)
4439 {
4440 	struct ras_event_manager *event_mgr;
4441 	struct ras_event_state *event_state;
4442 	int ret = 0;
4443 
4444 	if (type >= RAS_EVENT_TYPE_COUNT) {
4445 		ret = -EINVAL;
4446 		goto out;
4447 	}
4448 
4449 	event_mgr = __get_ras_event_mgr(adev);
4450 	if (!event_mgr) {
4451 		ret = -EINVAL;
4452 		goto out;
4453 	}
4454 
4455 	event_state = &event_mgr->event_state[type];
4456 	event_state->last_seqno = atomic64_inc_return(&event_mgr->seqno);
4457 	atomic64_inc(&event_state->count);
4458 
4459 out:
4460 	if (ret && caller)
4461 		dev_warn(adev->dev, "failed mark ras event (%d) in %ps, ret:%d\n",
4462 			 (int)type, caller, ret);
4463 
4464 	return ret;
4465 }
4466 
4467 u64 amdgpu_ras_acquire_event_id(struct amdgpu_device *adev, enum ras_event_type type)
4468 {
4469 	struct ras_event_manager *event_mgr;
4470 	u64 id;
4471 
4472 	if (type >= RAS_EVENT_TYPE_COUNT)
4473 		return RAS_EVENT_INVALID_ID;
4474 
4475 	switch (type) {
4476 	case RAS_EVENT_TYPE_FATAL:
4477 	case RAS_EVENT_TYPE_POISON_CREATION:
4478 	case RAS_EVENT_TYPE_POISON_CONSUMPTION:
4479 		event_mgr = __get_ras_event_mgr(adev);
4480 		if (!event_mgr)
4481 			return RAS_EVENT_INVALID_ID;
4482 
4483 		id = event_mgr->event_state[type].last_seqno;
4484 		break;
4485 	case RAS_EVENT_TYPE_INVALID:
4486 	default:
4487 		id = RAS_EVENT_INVALID_ID;
4488 		break;
4489 	}
4490 
4491 	return id;
4492 }
4493 
4494 void amdgpu_ras_global_ras_isr(struct amdgpu_device *adev)
4495 {
4496 	if (atomic_cmpxchg(&amdgpu_ras_in_intr, 0, 1) == 0) {
4497 		struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4498 		enum ras_event_type type = RAS_EVENT_TYPE_FATAL;
4499 		u64 event_id;
4500 
4501 		if (amdgpu_ras_mark_ras_event(adev, type)) {
4502 			dev_err(adev->dev,
4503 				"uncorrectable hardware error (ERREVENT_ATHUB_INTERRUPT) detected!\n");
4504 			return;
4505 		}
4506 
4507 		event_id = amdgpu_ras_acquire_event_id(adev, type);
4508 
4509 		RAS_EVENT_LOG(adev, event_id, "uncorrectable hardware error"
4510 			      "(ERREVENT_ATHUB_INTERRUPT) detected!\n");
4511 
4512 		amdgpu_ras_set_fed(adev, true);
4513 		ras->gpu_reset_flags |= AMDGPU_RAS_GPU_RESET_MODE1_RESET;
4514 		amdgpu_ras_reset_gpu(adev);
4515 	}
4516 }
4517 
4518 bool amdgpu_ras_need_emergency_restart(struct amdgpu_device *adev)
4519 {
4520 	if (adev->asic_type == CHIP_VEGA20 &&
4521 	    adev->pm.fw_version <= 0x283400) {
4522 		return !(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) &&
4523 				amdgpu_ras_intr_triggered();
4524 	}
4525 
4526 	return false;
4527 }
4528 
4529 void amdgpu_release_ras_context(struct amdgpu_device *adev)
4530 {
4531 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4532 
4533 	if (!con)
4534 		return;
4535 
4536 	if (!adev->ras_enabled && con->features & BIT(AMDGPU_RAS_BLOCK__GFX)) {
4537 		con->features &= ~BIT(AMDGPU_RAS_BLOCK__GFX);
4538 		amdgpu_ras_set_context(adev, NULL);
4539 		kfree(con);
4540 	}
4541 }
4542 
4543 #ifdef CONFIG_X86_MCE_AMD
4544 static struct amdgpu_device *find_adev(uint32_t node_id)
4545 {
4546 	int i;
4547 	struct amdgpu_device *adev = NULL;
4548 
4549 	for (i = 0; i < mce_adev_list.num_gpu; i++) {
4550 		adev = mce_adev_list.devs[i];
4551 
4552 		if (adev && adev->gmc.xgmi.connected_to_cpu &&
4553 		    adev->gmc.xgmi.physical_node_id == node_id)
4554 			break;
4555 		adev = NULL;
4556 	}
4557 
4558 	return adev;
4559 }
4560 
4561 #define GET_MCA_IPID_GPUID(m)	(((m) >> 44) & 0xF)
4562 #define GET_UMC_INST(m)		(((m) >> 21) & 0x7)
4563 #define GET_CHAN_INDEX(m)	((((m) >> 12) & 0x3) | (((m) >> 18) & 0x4))
4564 #define GPU_ID_OFFSET		8
4565 
4566 static int amdgpu_bad_page_notifier(struct notifier_block *nb,
4567 				    unsigned long val, void *data)
4568 {
4569 	struct mce *m = (struct mce *)data;
4570 	struct amdgpu_device *adev = NULL;
4571 	uint32_t gpu_id = 0;
4572 	uint32_t umc_inst = 0, ch_inst = 0;
4573 
4574 	/*
4575 	 * If the error was generated in UMC_V2, which belongs to GPU UMCs,
4576 	 * and error occurred in DramECC (Extended error code = 0) then only
4577 	 * process the error, else bail out.
4578 	 */
4579 	if (!m || !((smca_get_bank_type(m->extcpu, m->bank) == SMCA_UMC_V2) &&
4580 		    (XEC(m->status, 0x3f) == 0x0)))
4581 		return NOTIFY_DONE;
4582 
4583 	/*
4584 	 * If it is correctable error, return.
4585 	 */
4586 	if (mce_is_correctable(m))
4587 		return NOTIFY_OK;
4588 
4589 	/*
4590 	 * GPU Id is offset by GPU_ID_OFFSET in MCA_IPID_UMC register.
4591 	 */
4592 	gpu_id = GET_MCA_IPID_GPUID(m->ipid) - GPU_ID_OFFSET;
4593 
4594 	adev = find_adev(gpu_id);
4595 	if (!adev) {
4596 		DRM_WARN("%s: Unable to find adev for gpu_id: %d\n", __func__,
4597 								gpu_id);
4598 		return NOTIFY_DONE;
4599 	}
4600 
4601 	/*
4602 	 * If it is uncorrectable error, then find out UMC instance and
4603 	 * channel index.
4604 	 */
4605 	umc_inst = GET_UMC_INST(m->ipid);
4606 	ch_inst = GET_CHAN_INDEX(m->ipid);
4607 
4608 	dev_info(adev->dev, "Uncorrectable error detected in UMC inst: %d, chan_idx: %d",
4609 			     umc_inst, ch_inst);
4610 
4611 	if (!amdgpu_umc_page_retirement_mca(adev, m->addr, ch_inst, umc_inst))
4612 		return NOTIFY_OK;
4613 	else
4614 		return NOTIFY_DONE;
4615 }
4616 
4617 static struct notifier_block amdgpu_bad_page_nb = {
4618 	.notifier_call  = amdgpu_bad_page_notifier,
4619 	.priority       = MCE_PRIO_UC,
4620 };
4621 
4622 static void amdgpu_register_bad_pages_mca_notifier(struct amdgpu_device *adev)
4623 {
4624 	/*
4625 	 * Add the adev to the mce_adev_list.
4626 	 * During mode2 reset, amdgpu device is temporarily
4627 	 * removed from the mgpu_info list which can cause
4628 	 * page retirement to fail.
4629 	 * Use this list instead of mgpu_info to find the amdgpu
4630 	 * device on which the UMC error was reported.
4631 	 */
4632 	mce_adev_list.devs[mce_adev_list.num_gpu++] = adev;
4633 
4634 	/*
4635 	 * Register the x86 notifier only once
4636 	 * with MCE subsystem.
4637 	 */
4638 	if (notifier_registered == false) {
4639 		mce_register_decode_chain(&amdgpu_bad_page_nb);
4640 		notifier_registered = true;
4641 	}
4642 }
4643 #endif
4644 
4645 struct amdgpu_ras *amdgpu_ras_get_context(struct amdgpu_device *adev)
4646 {
4647 	if (!adev)
4648 		return NULL;
4649 
4650 	return adev->psp.ras_context.ras;
4651 }
4652 
4653 int amdgpu_ras_set_context(struct amdgpu_device *adev, struct amdgpu_ras *ras_con)
4654 {
4655 	if (!adev)
4656 		return -EINVAL;
4657 
4658 	adev->psp.ras_context.ras = ras_con;
4659 	return 0;
4660 }
4661 
4662 /* check if ras is supported on block, say, sdma, gfx */
4663 int amdgpu_ras_is_supported(struct amdgpu_device *adev,
4664 		unsigned int block)
4665 {
4666 	int ret = 0;
4667 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4668 
4669 	if (block >= AMDGPU_RAS_BLOCK_COUNT)
4670 		return 0;
4671 
4672 	ret = ras && (adev->ras_enabled & (1 << block));
4673 
4674 	/* For the special asic with mem ecc enabled but sram ecc
4675 	 * not enabled, even if the ras block is not supported on
4676 	 * .ras_enabled, if the asic supports poison mode and the
4677 	 * ras block has ras configuration, it can be considered
4678 	 * that the ras block supports ras function.
4679 	 */
4680 	if (!ret &&
4681 	    (block == AMDGPU_RAS_BLOCK__GFX ||
4682 	     block == AMDGPU_RAS_BLOCK__SDMA ||
4683 	     block == AMDGPU_RAS_BLOCK__VCN ||
4684 	     block == AMDGPU_RAS_BLOCK__JPEG) &&
4685 		(amdgpu_ras_mask & (1 << block)) &&
4686 	    amdgpu_ras_is_poison_mode_supported(adev) &&
4687 	    amdgpu_ras_get_ras_block(adev, block, 0))
4688 		ret = 1;
4689 
4690 	return ret;
4691 }
4692 
4693 int amdgpu_ras_reset_gpu(struct amdgpu_device *adev)
4694 {
4695 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4696 
4697 	/* mode1 is the only selection for RMA status */
4698 	if (amdgpu_ras_is_rma(adev)) {
4699 		ras->gpu_reset_flags = 0;
4700 		ras->gpu_reset_flags |= AMDGPU_RAS_GPU_RESET_MODE1_RESET;
4701 	}
4702 
4703 	if (atomic_cmpxchg(&ras->in_recovery, 0, 1) == 0) {
4704 		struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
4705 		int hive_ras_recovery = 0;
4706 
4707 		if (hive) {
4708 			hive_ras_recovery = atomic_read(&hive->ras_recovery);
4709 			amdgpu_put_xgmi_hive(hive);
4710 		}
4711 		/* In the case of multiple GPUs, after a GPU has started
4712 		 * resetting all GPUs on hive, other GPUs do not need to
4713 		 * trigger GPU reset again.
4714 		 */
4715 		if (!hive_ras_recovery)
4716 			amdgpu_reset_domain_schedule(ras->adev->reset_domain, &ras->recovery_work);
4717 		else
4718 			atomic_set(&ras->in_recovery, 0);
4719 	} else {
4720 		flush_work(&ras->recovery_work);
4721 		amdgpu_reset_domain_schedule(ras->adev->reset_domain, &ras->recovery_work);
4722 	}
4723 
4724 	return 0;
4725 }
4726 
4727 int amdgpu_ras_set_mca_debug_mode(struct amdgpu_device *adev, bool enable)
4728 {
4729 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4730 	int ret = 0;
4731 
4732 	if (con) {
4733 		ret = amdgpu_mca_smu_set_debug_mode(adev, enable);
4734 		if (!ret)
4735 			con->is_aca_debug_mode = enable;
4736 	}
4737 
4738 	return ret;
4739 }
4740 
4741 int amdgpu_ras_set_aca_debug_mode(struct amdgpu_device *adev, bool enable)
4742 {
4743 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4744 	int ret = 0;
4745 
4746 	if (con) {
4747 		if (amdgpu_aca_is_enabled(adev))
4748 			ret = amdgpu_aca_smu_set_debug_mode(adev, enable);
4749 		else
4750 			ret = amdgpu_mca_smu_set_debug_mode(adev, enable);
4751 		if (!ret)
4752 			con->is_aca_debug_mode = enable;
4753 	}
4754 
4755 	return ret;
4756 }
4757 
4758 bool amdgpu_ras_get_aca_debug_mode(struct amdgpu_device *adev)
4759 {
4760 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4761 	const struct aca_smu_funcs *smu_funcs = adev->aca.smu_funcs;
4762 	const struct amdgpu_mca_smu_funcs *mca_funcs = adev->mca.mca_funcs;
4763 
4764 	if (!con)
4765 		return false;
4766 
4767 	if ((amdgpu_aca_is_enabled(adev) && smu_funcs && smu_funcs->set_debug_mode) ||
4768 	    (!amdgpu_aca_is_enabled(adev) && mca_funcs && mca_funcs->mca_set_debug_mode))
4769 		return con->is_aca_debug_mode;
4770 	else
4771 		return true;
4772 }
4773 
4774 bool amdgpu_ras_get_error_query_mode(struct amdgpu_device *adev,
4775 				     unsigned int *error_query_mode)
4776 {
4777 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4778 	const struct amdgpu_mca_smu_funcs *mca_funcs = adev->mca.mca_funcs;
4779 	const struct aca_smu_funcs *smu_funcs = adev->aca.smu_funcs;
4780 
4781 	if (!con) {
4782 		*error_query_mode = AMDGPU_RAS_INVALID_ERROR_QUERY;
4783 		return false;
4784 	}
4785 
4786 	if (amdgpu_sriov_vf(adev)) {
4787 		*error_query_mode = AMDGPU_RAS_VIRT_ERROR_COUNT_QUERY;
4788 	} else if ((smu_funcs && smu_funcs->set_debug_mode) || (mca_funcs && mca_funcs->mca_set_debug_mode)) {
4789 		*error_query_mode =
4790 			(con->is_aca_debug_mode) ? AMDGPU_RAS_DIRECT_ERROR_QUERY : AMDGPU_RAS_FIRMWARE_ERROR_QUERY;
4791 	} else {
4792 		*error_query_mode = AMDGPU_RAS_DIRECT_ERROR_QUERY;
4793 	}
4794 
4795 	return true;
4796 }
4797 
4798 /* Register each ip ras block into amdgpu ras */
4799 int amdgpu_ras_register_ras_block(struct amdgpu_device *adev,
4800 		struct amdgpu_ras_block_object *ras_block_obj)
4801 {
4802 	struct amdgpu_ras_block_list *ras_node;
4803 	if (!adev || !ras_block_obj)
4804 		return -EINVAL;
4805 
4806 	ras_node = kzalloc(sizeof(*ras_node), GFP_KERNEL);
4807 	if (!ras_node)
4808 		return -ENOMEM;
4809 
4810 	INIT_LIST_HEAD(&ras_node->node);
4811 	ras_node->ras_obj = ras_block_obj;
4812 	list_add_tail(&ras_node->node, &adev->ras_list);
4813 
4814 	return 0;
4815 }
4816 
4817 void amdgpu_ras_get_error_type_name(uint32_t err_type, char *err_type_name)
4818 {
4819 	if (!err_type_name)
4820 		return;
4821 
4822 	switch (err_type) {
4823 	case AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE:
4824 		sprintf(err_type_name, "correctable");
4825 		break;
4826 	case AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE:
4827 		sprintf(err_type_name, "uncorrectable");
4828 		break;
4829 	default:
4830 		sprintf(err_type_name, "unknown");
4831 		break;
4832 	}
4833 }
4834 
4835 bool amdgpu_ras_inst_get_memory_id_field(struct amdgpu_device *adev,
4836 					 const struct amdgpu_ras_err_status_reg_entry *reg_entry,
4837 					 uint32_t instance,
4838 					 uint32_t *memory_id)
4839 {
4840 	uint32_t err_status_lo_data, err_status_lo_offset;
4841 
4842 	if (!reg_entry)
4843 		return false;
4844 
4845 	err_status_lo_offset =
4846 		AMDGPU_RAS_REG_ENTRY_OFFSET(reg_entry->hwip, instance,
4847 					    reg_entry->seg_lo, reg_entry->reg_lo);
4848 	err_status_lo_data = RREG32(err_status_lo_offset);
4849 
4850 	if ((reg_entry->flags & AMDGPU_RAS_ERR_STATUS_VALID) &&
4851 	    !REG_GET_FIELD(err_status_lo_data, ERR_STATUS_LO, ERR_STATUS_VALID_FLAG))
4852 		return false;
4853 
4854 	*memory_id = REG_GET_FIELD(err_status_lo_data, ERR_STATUS_LO, MEMORY_ID);
4855 
4856 	return true;
4857 }
4858 
4859 bool amdgpu_ras_inst_get_err_cnt_field(struct amdgpu_device *adev,
4860 				       const struct amdgpu_ras_err_status_reg_entry *reg_entry,
4861 				       uint32_t instance,
4862 				       unsigned long *err_cnt)
4863 {
4864 	uint32_t err_status_hi_data, err_status_hi_offset;
4865 
4866 	if (!reg_entry)
4867 		return false;
4868 
4869 	err_status_hi_offset =
4870 		AMDGPU_RAS_REG_ENTRY_OFFSET(reg_entry->hwip, instance,
4871 					    reg_entry->seg_hi, reg_entry->reg_hi);
4872 	err_status_hi_data = RREG32(err_status_hi_offset);
4873 
4874 	if ((reg_entry->flags & AMDGPU_RAS_ERR_INFO_VALID) &&
4875 	    !REG_GET_FIELD(err_status_hi_data, ERR_STATUS_HI, ERR_INFO_VALID_FLAG))
4876 		/* keep the check here in case we need to refer to the result later */
4877 		dev_dbg(adev->dev, "Invalid err_info field\n");
4878 
4879 	/* read err count */
4880 	*err_cnt = REG_GET_FIELD(err_status_hi_data, ERR_STATUS, ERR_CNT);
4881 
4882 	return true;
4883 }
4884 
4885 void amdgpu_ras_inst_query_ras_error_count(struct amdgpu_device *adev,
4886 					   const struct amdgpu_ras_err_status_reg_entry *reg_list,
4887 					   uint32_t reg_list_size,
4888 					   const struct amdgpu_ras_memory_id_entry *mem_list,
4889 					   uint32_t mem_list_size,
4890 					   uint32_t instance,
4891 					   uint32_t err_type,
4892 					   unsigned long *err_count)
4893 {
4894 	uint32_t memory_id;
4895 	unsigned long err_cnt;
4896 	char err_type_name[16];
4897 	uint32_t i, j;
4898 
4899 	for (i = 0; i < reg_list_size; i++) {
4900 		/* query memory_id from err_status_lo */
4901 		if (!amdgpu_ras_inst_get_memory_id_field(adev, &reg_list[i],
4902 							 instance, &memory_id))
4903 			continue;
4904 
4905 		/* query err_cnt from err_status_hi */
4906 		if (!amdgpu_ras_inst_get_err_cnt_field(adev, &reg_list[i],
4907 						       instance, &err_cnt) ||
4908 		    !err_cnt)
4909 			continue;
4910 
4911 		*err_count += err_cnt;
4912 
4913 		/* log the errors */
4914 		amdgpu_ras_get_error_type_name(err_type, err_type_name);
4915 		if (!mem_list) {
4916 			/* memory_list is not supported */
4917 			dev_info(adev->dev,
4918 				 "%ld %s hardware errors detected in %s, instance: %d, memory_id: %d\n",
4919 				 err_cnt, err_type_name,
4920 				 reg_list[i].block_name,
4921 				 instance, memory_id);
4922 		} else {
4923 			for (j = 0; j < mem_list_size; j++) {
4924 				if (memory_id == mem_list[j].memory_id) {
4925 					dev_info(adev->dev,
4926 						 "%ld %s hardware errors detected in %s, instance: %d, memory block: %s\n",
4927 						 err_cnt, err_type_name,
4928 						 reg_list[i].block_name,
4929 						 instance, mem_list[j].name);
4930 					break;
4931 				}
4932 			}
4933 		}
4934 	}
4935 }
4936 
4937 void amdgpu_ras_inst_reset_ras_error_count(struct amdgpu_device *adev,
4938 					   const struct amdgpu_ras_err_status_reg_entry *reg_list,
4939 					   uint32_t reg_list_size,
4940 					   uint32_t instance)
4941 {
4942 	uint32_t err_status_lo_offset, err_status_hi_offset;
4943 	uint32_t i;
4944 
4945 	for (i = 0; i < reg_list_size; i++) {
4946 		err_status_lo_offset =
4947 			AMDGPU_RAS_REG_ENTRY_OFFSET(reg_list[i].hwip, instance,
4948 						    reg_list[i].seg_lo, reg_list[i].reg_lo);
4949 		err_status_hi_offset =
4950 			AMDGPU_RAS_REG_ENTRY_OFFSET(reg_list[i].hwip, instance,
4951 						    reg_list[i].seg_hi, reg_list[i].reg_hi);
4952 		WREG32(err_status_lo_offset, 0);
4953 		WREG32(err_status_hi_offset, 0);
4954 	}
4955 }
4956 
4957 int amdgpu_ras_error_data_init(struct ras_err_data *err_data)
4958 {
4959 	memset(err_data, 0, sizeof(*err_data));
4960 
4961 	INIT_LIST_HEAD(&err_data->err_node_list);
4962 
4963 	return 0;
4964 }
4965 
4966 static void amdgpu_ras_error_node_release(struct ras_err_node *err_node)
4967 {
4968 	if (!err_node)
4969 		return;
4970 
4971 	list_del(&err_node->node);
4972 	kvfree(err_node);
4973 }
4974 
4975 void amdgpu_ras_error_data_fini(struct ras_err_data *err_data)
4976 {
4977 	struct ras_err_node *err_node, *tmp;
4978 
4979 	list_for_each_entry_safe(err_node, tmp, &err_data->err_node_list, node)
4980 		amdgpu_ras_error_node_release(err_node);
4981 }
4982 
4983 static struct ras_err_node *amdgpu_ras_error_find_node_by_id(struct ras_err_data *err_data,
4984 							     struct amdgpu_smuio_mcm_config_info *mcm_info)
4985 {
4986 	struct ras_err_node *err_node;
4987 	struct amdgpu_smuio_mcm_config_info *ref_id;
4988 
4989 	if (!err_data || !mcm_info)
4990 		return NULL;
4991 
4992 	for_each_ras_error(err_node, err_data) {
4993 		ref_id = &err_node->err_info.mcm_info;
4994 
4995 		if (mcm_info->socket_id == ref_id->socket_id &&
4996 		    mcm_info->die_id == ref_id->die_id)
4997 			return err_node;
4998 	}
4999 
5000 	return NULL;
5001 }
5002 
5003 static struct ras_err_node *amdgpu_ras_error_node_new(void)
5004 {
5005 	struct ras_err_node *err_node;
5006 
5007 	err_node = kvzalloc(sizeof(*err_node), GFP_KERNEL);
5008 	if (!err_node)
5009 		return NULL;
5010 
5011 	INIT_LIST_HEAD(&err_node->node);
5012 
5013 	return err_node;
5014 }
5015 
5016 static int ras_err_info_cmp(void *priv, const struct list_head *a, const struct list_head *b)
5017 {
5018 	struct ras_err_node *nodea = container_of(a, struct ras_err_node, node);
5019 	struct ras_err_node *nodeb = container_of(b, struct ras_err_node, node);
5020 	struct amdgpu_smuio_mcm_config_info *infoa = &nodea->err_info.mcm_info;
5021 	struct amdgpu_smuio_mcm_config_info *infob = &nodeb->err_info.mcm_info;
5022 
5023 	if (unlikely(infoa->socket_id != infob->socket_id))
5024 		return infoa->socket_id - infob->socket_id;
5025 	else
5026 		return infoa->die_id - infob->die_id;
5027 
5028 	return 0;
5029 }
5030 
5031 static struct ras_err_info *amdgpu_ras_error_get_info(struct ras_err_data *err_data,
5032 				struct amdgpu_smuio_mcm_config_info *mcm_info)
5033 {
5034 	struct ras_err_node *err_node;
5035 
5036 	err_node = amdgpu_ras_error_find_node_by_id(err_data, mcm_info);
5037 	if (err_node)
5038 		return &err_node->err_info;
5039 
5040 	err_node = amdgpu_ras_error_node_new();
5041 	if (!err_node)
5042 		return NULL;
5043 
5044 	memcpy(&err_node->err_info.mcm_info, mcm_info, sizeof(*mcm_info));
5045 
5046 	err_data->err_list_count++;
5047 	list_add_tail(&err_node->node, &err_data->err_node_list);
5048 	list_sort(NULL, &err_data->err_node_list, ras_err_info_cmp);
5049 
5050 	return &err_node->err_info;
5051 }
5052 
5053 int amdgpu_ras_error_statistic_ue_count(struct ras_err_data *err_data,
5054 					struct amdgpu_smuio_mcm_config_info *mcm_info,
5055 					u64 count)
5056 {
5057 	struct ras_err_info *err_info;
5058 
5059 	if (!err_data || !mcm_info)
5060 		return -EINVAL;
5061 
5062 	if (!count)
5063 		return 0;
5064 
5065 	err_info = amdgpu_ras_error_get_info(err_data, mcm_info);
5066 	if (!err_info)
5067 		return -EINVAL;
5068 
5069 	err_info->ue_count += count;
5070 	err_data->ue_count += count;
5071 
5072 	return 0;
5073 }
5074 
5075 int amdgpu_ras_error_statistic_ce_count(struct ras_err_data *err_data,
5076 					struct amdgpu_smuio_mcm_config_info *mcm_info,
5077 					u64 count)
5078 {
5079 	struct ras_err_info *err_info;
5080 
5081 	if (!err_data || !mcm_info)
5082 		return -EINVAL;
5083 
5084 	if (!count)
5085 		return 0;
5086 
5087 	err_info = amdgpu_ras_error_get_info(err_data, mcm_info);
5088 	if (!err_info)
5089 		return -EINVAL;
5090 
5091 	err_info->ce_count += count;
5092 	err_data->ce_count += count;
5093 
5094 	return 0;
5095 }
5096 
5097 int amdgpu_ras_error_statistic_de_count(struct ras_err_data *err_data,
5098 					struct amdgpu_smuio_mcm_config_info *mcm_info,
5099 					u64 count)
5100 {
5101 	struct ras_err_info *err_info;
5102 
5103 	if (!err_data || !mcm_info)
5104 		return -EINVAL;
5105 
5106 	if (!count)
5107 		return 0;
5108 
5109 	err_info = amdgpu_ras_error_get_info(err_data, mcm_info);
5110 	if (!err_info)
5111 		return -EINVAL;
5112 
5113 	err_info->de_count += count;
5114 	err_data->de_count += count;
5115 
5116 	return 0;
5117 }
5118 
5119 #define mmMP0_SMN_C2PMSG_92	0x1609C
5120 #define mmMP0_SMN_C2PMSG_126	0x160BE
5121 static void amdgpu_ras_boot_time_error_reporting(struct amdgpu_device *adev,
5122 						 u32 instance)
5123 {
5124 	u32 socket_id, aid_id, hbm_id;
5125 	u32 fw_status;
5126 	u32 boot_error;
5127 	u64 reg_addr;
5128 
5129 	/* The pattern for smn addressing in other SOC could be different from
5130 	 * the one for aqua_vanjaram. We should revisit the code if the pattern
5131 	 * is changed. In such case, replace the aqua_vanjaram implementation
5132 	 * with more common helper */
5133 	reg_addr = (mmMP0_SMN_C2PMSG_92 << 2) +
5134 		   aqua_vanjaram_encode_ext_smn_addressing(instance);
5135 	fw_status = amdgpu_device_indirect_rreg_ext(adev, reg_addr);
5136 
5137 	reg_addr = (mmMP0_SMN_C2PMSG_126 << 2) +
5138 		   aqua_vanjaram_encode_ext_smn_addressing(instance);
5139 	boot_error = amdgpu_device_indirect_rreg_ext(adev, reg_addr);
5140 
5141 	socket_id = AMDGPU_RAS_GPU_ERR_SOCKET_ID(boot_error);
5142 	aid_id = AMDGPU_RAS_GPU_ERR_AID_ID(boot_error);
5143 	hbm_id = ((1 == AMDGPU_RAS_GPU_ERR_HBM_ID(boot_error)) ? 0 : 1);
5144 
5145 	if (AMDGPU_RAS_GPU_ERR_MEM_TRAINING(boot_error))
5146 		dev_info(adev->dev,
5147 			 "socket: %d, aid: %d, hbm: %d, fw_status: 0x%x, memory training failed\n",
5148 			 socket_id, aid_id, hbm_id, fw_status);
5149 
5150 	if (AMDGPU_RAS_GPU_ERR_FW_LOAD(boot_error))
5151 		dev_info(adev->dev,
5152 			 "socket: %d, aid: %d, fw_status: 0x%x, firmware load failed at boot time\n",
5153 			 socket_id, aid_id, fw_status);
5154 
5155 	if (AMDGPU_RAS_GPU_ERR_WAFL_LINK_TRAINING(boot_error))
5156 		dev_info(adev->dev,
5157 			 "socket: %d, aid: %d, fw_status: 0x%x, wafl link training failed\n",
5158 			 socket_id, aid_id, fw_status);
5159 
5160 	if (AMDGPU_RAS_GPU_ERR_XGMI_LINK_TRAINING(boot_error))
5161 		dev_info(adev->dev,
5162 			 "socket: %d, aid: %d, fw_status: 0x%x, xgmi link training failed\n",
5163 			 socket_id, aid_id, fw_status);
5164 
5165 	if (AMDGPU_RAS_GPU_ERR_USR_CP_LINK_TRAINING(boot_error))
5166 		dev_info(adev->dev,
5167 			 "socket: %d, aid: %d, fw_status: 0x%x, usr cp link training failed\n",
5168 			 socket_id, aid_id, fw_status);
5169 
5170 	if (AMDGPU_RAS_GPU_ERR_USR_DP_LINK_TRAINING(boot_error))
5171 		dev_info(adev->dev,
5172 			 "socket: %d, aid: %d, fw_status: 0x%x, usr dp link training failed\n",
5173 			 socket_id, aid_id, fw_status);
5174 
5175 	if (AMDGPU_RAS_GPU_ERR_HBM_MEM_TEST(boot_error))
5176 		dev_info(adev->dev,
5177 			 "socket: %d, aid: %d, hbm: %d, fw_status: 0x%x, hbm memory test failed\n",
5178 			 socket_id, aid_id, hbm_id, fw_status);
5179 
5180 	if (AMDGPU_RAS_GPU_ERR_HBM_BIST_TEST(boot_error))
5181 		dev_info(adev->dev,
5182 			 "socket: %d, aid: %d, hbm: %d, fw_status: 0x%x, hbm bist test failed\n",
5183 			 socket_id, aid_id, hbm_id, fw_status);
5184 
5185 	if (AMDGPU_RAS_GPU_ERR_DATA_ABORT(boot_error))
5186 		dev_info(adev->dev,
5187 			 "socket: %d, aid: %d, fw_status: 0x%x, data abort exception\n",
5188 			 socket_id, aid_id, fw_status);
5189 
5190 	if (AMDGPU_RAS_GPU_ERR_GENERIC(boot_error))
5191 		dev_info(adev->dev,
5192 			 "socket: %d, aid: %d, fw_status: 0x%x, Boot Controller Generic Error\n",
5193 			 socket_id, aid_id, fw_status);
5194 }
5195 
5196 static bool amdgpu_ras_boot_error_detected(struct amdgpu_device *adev,
5197 					   u32 instance)
5198 {
5199 	u64 reg_addr;
5200 	u32 reg_data;
5201 	int retry_loop;
5202 
5203 	reg_addr = (mmMP0_SMN_C2PMSG_92 << 2) +
5204 		   aqua_vanjaram_encode_ext_smn_addressing(instance);
5205 
5206 	for (retry_loop = 0; retry_loop < AMDGPU_RAS_BOOT_STATUS_POLLING_LIMIT; retry_loop++) {
5207 		reg_data = amdgpu_device_indirect_rreg_ext(adev, reg_addr);
5208 		if ((reg_data & AMDGPU_RAS_BOOT_STATUS_MASK) == AMDGPU_RAS_BOOT_STEADY_STATUS)
5209 			return false;
5210 		else
5211 			msleep(1);
5212 	}
5213 
5214 	return true;
5215 }
5216 
5217 void amdgpu_ras_query_boot_status(struct amdgpu_device *adev, u32 num_instances)
5218 {
5219 	u32 i;
5220 
5221 	for (i = 0; i < num_instances; i++) {
5222 		if (amdgpu_ras_boot_error_detected(adev, i))
5223 			amdgpu_ras_boot_time_error_reporting(adev, i);
5224 	}
5225 }
5226 
5227 int amdgpu_ras_reserve_page(struct amdgpu_device *adev, uint64_t pfn)
5228 {
5229 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
5230 	struct amdgpu_vram_mgr *mgr = &adev->mman.vram_mgr;
5231 	uint64_t start = pfn << AMDGPU_GPU_PAGE_SHIFT;
5232 	int ret = 0;
5233 
5234 	mutex_lock(&con->page_rsv_lock);
5235 	ret = amdgpu_vram_mgr_query_page_status(mgr, start);
5236 	if (ret == -ENOENT)
5237 		ret = amdgpu_vram_mgr_reserve_range(mgr, start, AMDGPU_GPU_PAGE_SIZE);
5238 	mutex_unlock(&con->page_rsv_lock);
5239 
5240 	return ret;
5241 }
5242 
5243 void amdgpu_ras_event_log_print(struct amdgpu_device *adev, u64 event_id,
5244 				const char *fmt, ...)
5245 {
5246 	struct va_format vaf;
5247 	va_list args;
5248 
5249 	va_start(args, fmt);
5250 	vaf.fmt = fmt;
5251 	vaf.va = &args;
5252 
5253 	if (RAS_EVENT_ID_IS_VALID(event_id))
5254 		dev_printk(KERN_INFO, adev->dev, "{%llu}%pV", event_id, &vaf);
5255 	else
5256 		dev_printk(KERN_INFO, adev->dev, "%pV", &vaf);
5257 
5258 	va_end(args);
5259 }
5260 
5261 bool amdgpu_ras_is_rma(struct amdgpu_device *adev)
5262 {
5263 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
5264 
5265 	if (!con)
5266 		return false;
5267 
5268 	return con->is_rma;
5269 }
5270