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