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