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