xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ras.c (revision 5b0764a53235d3c77e1ed674e836e1b3fe1a4b1f)
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 = kcalloc(nr_page_pfns, sizeof(*page_pfns), GFP_KERNEL);
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 		return -EOPNOTSUPP;
1511 
1512 	if (amdgpu_sriov_vf(adev))
1513 		return -EOPNOTSUPP;
1514 
1515 	/* skip ras error reset in gpu reset */
1516 	if (amdgpu_in_reset(adev) || amdgpu_ras_in_recovery(adev))
1517 		return -EOPNOTSUPP;
1518 
1519 	if (block_obj->hw_ops->reset_ras_error_count)
1520 		block_obj->hw_ops->reset_ras_error_count(adev);
1521 
1522 	return 0;
1523 }
1524 
1525 int amdgpu_ras_reset_error_status(struct amdgpu_device *adev,
1526 		enum amdgpu_ras_block block)
1527 {
1528 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev, block, 0);
1529 
1530 	if (amdgpu_ras_reset_error_count(adev, block) == -EOPNOTSUPP)
1531 		return 0;
1532 
1533 	if ((block == AMDGPU_RAS_BLOCK__GFX) ||
1534 	    (block == AMDGPU_RAS_BLOCK__MMHUB)) {
1535 		if (block_obj->hw_ops->reset_ras_error_status)
1536 			block_obj->hw_ops->reset_ras_error_status(adev);
1537 	}
1538 
1539 	return 0;
1540 }
1541 
1542 static int amdgpu_uniras_error_inject(struct amdgpu_device *adev,
1543 		struct ras_inject_if *info)
1544 {
1545 	struct ras_cmd_inject_error_req inject_req;
1546 	struct ras_cmd_inject_error_rsp rsp;
1547 
1548 	if (!info)
1549 		return -EINVAL;
1550 
1551 	memset(&inject_req, 0, sizeof(inject_req));
1552 	inject_req.block_id = info->head.block;
1553 	inject_req.subblock_id = info->head.sub_block_index;
1554 	inject_req.address = info->address;
1555 	inject_req.error_type = info->head.type;
1556 	inject_req.instance_mask = info->instance_mask;
1557 	inject_req.method = info->value;
1558 
1559 	return amdgpu_ras_mgr_handle_ras_cmd(adev, RAS_CMD__INJECT_ERROR,
1560 	       &inject_req, sizeof(inject_req), &rsp, sizeof(rsp)) ? -EINVAL : 0;
1561 }
1562 
1563 /* wrapper of psp_ras_trigger_error */
1564 int amdgpu_ras_error_inject(struct amdgpu_device *adev,
1565 		struct ras_inject_if *info)
1566 {
1567 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1568 	struct ta_ras_trigger_error_input block_info = {
1569 		.block_id =  amdgpu_ras_block_to_ta(info->head.block),
1570 		.inject_error_type = amdgpu_ras_error_to_ta(info->head.type),
1571 		.sub_block_index = info->head.sub_block_index,
1572 		.address = info->address,
1573 		.value = info->value,
1574 	};
1575 	int ret = -EINVAL;
1576 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev,
1577 							info->head.block,
1578 							info->head.sub_block_index);
1579 
1580 	if (amdgpu_uniras_enabled(adev))
1581 		return amdgpu_uniras_error_inject(adev, info);
1582 
1583 	/* inject on guest isn't allowed, return success directly */
1584 	if (amdgpu_sriov_vf(adev))
1585 		return 0;
1586 
1587 	if (!obj)
1588 		return -EINVAL;
1589 
1590 	if (!block_obj || !block_obj->hw_ops)	{
1591 		dev_dbg_once(adev->dev, "%s doesn't config RAS function\n",
1592 			     get_ras_block_str(&info->head));
1593 		return -EINVAL;
1594 	}
1595 
1596 	/* Calculate XGMI relative offset */
1597 	if (adev->gmc.xgmi.num_physical_nodes > 1 &&
1598 	    info->head.block != AMDGPU_RAS_BLOCK__GFX) {
1599 		block_info.address =
1600 			amdgpu_xgmi_get_relative_phy_addr(adev,
1601 							  block_info.address);
1602 	}
1603 
1604 	if (block_obj->hw_ops->ras_error_inject) {
1605 		if (info->head.block == AMDGPU_RAS_BLOCK__GFX)
1606 			ret = block_obj->hw_ops->ras_error_inject(adev, info, info->instance_mask);
1607 		else /* Special ras_error_inject is defined (e.g: xgmi) */
1608 			ret = block_obj->hw_ops->ras_error_inject(adev, &block_info,
1609 						info->instance_mask);
1610 	} else {
1611 		/* default path */
1612 		ret = psp_ras_trigger_error(&adev->psp, &block_info, info->instance_mask);
1613 	}
1614 
1615 	if (ret)
1616 		dev_err(adev->dev, "ras inject %s failed %d\n",
1617 			get_ras_block_str(&info->head), ret);
1618 
1619 	return ret;
1620 }
1621 
1622 /**
1623  * amdgpu_ras_query_error_count_helper -- Get error counter for specific IP
1624  * @adev: pointer to AMD GPU device
1625  * @ce_count: pointer to an integer to be set to the count of correctible errors.
1626  * @ue_count: pointer to an integer to be set to the count of uncorrectible errors.
1627  * @query_info: pointer to ras_query_if
1628  *
1629  * Return 0 for query success or do nothing, otherwise return an error
1630  * on failures
1631  */
1632 static int amdgpu_ras_query_error_count_helper(struct amdgpu_device *adev,
1633 					       unsigned long *ce_count,
1634 					       unsigned long *ue_count,
1635 					       struct ras_query_if *query_info)
1636 {
1637 	int ret;
1638 
1639 	if (!query_info)
1640 		/* do nothing if query_info is not specified */
1641 		return 0;
1642 
1643 	ret = amdgpu_ras_query_error_status(adev, query_info);
1644 	if (ret)
1645 		return ret;
1646 
1647 	*ce_count += query_info->ce_count;
1648 	*ue_count += query_info->ue_count;
1649 
1650 	/* some hardware/IP supports read to clear
1651 	 * no need to explictly reset the err status after the query call */
1652 	if (amdgpu_ip_version(adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 2) &&
1653 	    amdgpu_ip_version(adev, MP0_HWIP, 0) != IP_VERSION(11, 0, 4)) {
1654 		if (amdgpu_ras_reset_error_status(adev, query_info->head.block))
1655 			dev_warn(adev->dev,
1656 				 "Failed to reset error counter and error status\n");
1657 	}
1658 
1659 	return 0;
1660 }
1661 
1662 /**
1663  * amdgpu_ras_query_error_count -- Get error counts of all IPs or specific IP
1664  * @adev: pointer to AMD GPU device
1665  * @ce_count: pointer to an integer to be set to the count of correctible errors.
1666  * @ue_count: pointer to an integer to be set to the count of uncorrectible
1667  * errors.
1668  * @query_info: pointer to ras_query_if if the query request is only for
1669  * specific ip block; if info is NULL, then the qurey request is for
1670  * all the ip blocks that support query ras error counters/status
1671  *
1672  * If set, @ce_count or @ue_count, count and return the corresponding
1673  * error counts in those integer pointers. Return 0 if the device
1674  * supports RAS. Return -EOPNOTSUPP if the device doesn't support RAS.
1675  */
1676 int amdgpu_ras_query_error_count(struct amdgpu_device *adev,
1677 				 unsigned long *ce_count,
1678 				 unsigned long *ue_count,
1679 				 struct ras_query_if *query_info)
1680 {
1681 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1682 	struct ras_manager *obj;
1683 	unsigned long ce, ue;
1684 	int ret;
1685 
1686 	if (!adev->ras_enabled || !con)
1687 		return -EOPNOTSUPP;
1688 
1689 	/* Don't count since no reporting.
1690 	 */
1691 	if (!ce_count && !ue_count)
1692 		return 0;
1693 
1694 	ce = 0;
1695 	ue = 0;
1696 	if (!query_info) {
1697 		/* query all the ip blocks that support ras query interface */
1698 		list_for_each_entry(obj, &con->head, node) {
1699 			struct ras_query_if info = {
1700 				.head = obj->head,
1701 			};
1702 
1703 			ret = amdgpu_ras_query_error_count_helper(adev, &ce, &ue, &info);
1704 		}
1705 	} else {
1706 		/* query specific ip block */
1707 		ret = amdgpu_ras_query_error_count_helper(adev, &ce, &ue, query_info);
1708 	}
1709 
1710 	if (ret)
1711 		return ret;
1712 
1713 	if (ce_count)
1714 		*ce_count = ce;
1715 
1716 	if (ue_count)
1717 		*ue_count = ue;
1718 
1719 	return 0;
1720 }
1721 /* query/inject/cure end */
1722 
1723 
1724 /* sysfs begin */
1725 
1726 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
1727 		struct ras_badpage *bps, uint32_t count, uint32_t start);
1728 static int amdgpu_uniras_badpages_read(struct amdgpu_device *adev,
1729 		struct ras_badpage *bps, uint32_t count, uint32_t start);
1730 
1731 static char *amdgpu_ras_badpage_flags_str(unsigned int flags)
1732 {
1733 	switch (flags) {
1734 	case AMDGPU_RAS_RETIRE_PAGE_RESERVED:
1735 		return "R";
1736 	case AMDGPU_RAS_RETIRE_PAGE_PENDING:
1737 		return "P";
1738 	case AMDGPU_RAS_RETIRE_PAGE_FAULT:
1739 	default:
1740 		return "F";
1741 	}
1742 }
1743 
1744 /**
1745  * DOC: AMDGPU RAS sysfs gpu_vram_bad_pages Interface
1746  *
1747  * It allows user to read the bad pages of vram on the gpu through
1748  * /sys/class/drm/card[0/1/2...]/device/ras/gpu_vram_bad_pages
1749  *
1750  * It outputs multiple lines, and each line stands for one gpu page.
1751  *
1752  * The format of one line is below,
1753  * gpu pfn : gpu page size : flags
1754  *
1755  * gpu pfn and gpu page size are printed in hex format.
1756  * flags can be one of below character,
1757  *
1758  * R: reserved, this gpu page is reserved and not able to use.
1759  *
1760  * P: pending for reserve, this gpu page is marked as bad, will be reserved
1761  * in next window of page_reserve.
1762  *
1763  * F: unable to reserve. this gpu page can't be reserved due to some reasons.
1764  *
1765  * Examples:
1766  *
1767  * .. code-block:: bash
1768  *
1769  *	0x00000001 : 0x00001000 : R
1770  *	0x00000002 : 0x00001000 : P
1771  *
1772  */
1773 
1774 static ssize_t amdgpu_ras_sysfs_badpages_read(struct file *f,
1775 		struct kobject *kobj, const struct bin_attribute *attr,
1776 		char *buf, loff_t ppos, size_t count)
1777 {
1778 	struct amdgpu_ras *con =
1779 		container_of(attr, struct amdgpu_ras, badpages_attr);
1780 	struct amdgpu_device *adev = con->adev;
1781 	const unsigned int element_size =
1782 		sizeof("0xabcdabcd : 0x12345678 : R\n") - 1;
1783 	unsigned int start = div64_ul(ppos + element_size - 1, element_size);
1784 	unsigned int end = div64_ul(ppos + count - 1, element_size);
1785 	ssize_t s = 0;
1786 	struct ras_badpage *bps = NULL;
1787 	int bps_count = 0, i, status;
1788 	uint64_t address;
1789 
1790 	memset(buf, 0, count);
1791 
1792 	bps_count = end - start;
1793 	bps = kmalloc_objs(*bps, bps_count);
1794 	if (!bps)
1795 		return 0;
1796 
1797 	memset(bps, 0, sizeof(*bps) * bps_count);
1798 
1799 	if (amdgpu_uniras_enabled(adev))
1800 		bps_count = amdgpu_uniras_badpages_read(adev, bps, bps_count, start);
1801 	else
1802 		bps_count = amdgpu_ras_badpages_read(adev, bps, bps_count, start);
1803 
1804 	if (bps_count <= 0) {
1805 		kfree(bps);
1806 		return 0;
1807 	}
1808 
1809 	for (i = 0; i < bps_count; i++) {
1810 		address = ((uint64_t)bps[i].bp) << AMDGPU_GPU_PAGE_SHIFT;
1811 
1812 		bps[i].size = AMDGPU_GPU_PAGE_SIZE;
1813 
1814 		status = amdgpu_vram_mgr_query_page_status(&adev->mman.vram_mgr,
1815 					address);
1816 		if (status == -EBUSY)
1817 			bps[i].flags = AMDGPU_RAS_RETIRE_PAGE_PENDING;
1818 		else if (status == -ENOENT)
1819 			bps[i].flags = AMDGPU_RAS_RETIRE_PAGE_FAULT;
1820 		else
1821 			bps[i].flags = AMDGPU_RAS_RETIRE_PAGE_RESERVED;
1822 
1823 		if ((bps[i].flags != AMDGPU_RAS_RETIRE_PAGE_RESERVED) &&
1824 		    amdgpu_ras_check_critical_address(adev, address))
1825 			bps[i].flags = AMDGPU_RAS_RETIRE_PAGE_RESERVED;
1826 
1827 		s += scnprintf(&buf[s], element_size + 1,
1828 				"0x%08x : 0x%08x : %1s\n",
1829 				bps[i].bp,
1830 				bps[i].size,
1831 				amdgpu_ras_badpage_flags_str(bps[i].flags));
1832 	}
1833 
1834 	kfree(bps);
1835 
1836 	return s;
1837 }
1838 
1839 static ssize_t amdgpu_ras_sysfs_features_read(struct device *dev,
1840 		struct device_attribute *attr, char *buf)
1841 {
1842 	struct amdgpu_ras *con =
1843 		container_of(attr, struct amdgpu_ras, features_attr);
1844 	u64 ras_features;
1845 
1846 	ras_features = amdgpu_uniras_enabled(con->adev) ?
1847 		amdgpu_uniras_get_ras_caps(con->adev) : con->features;
1848 
1849 	return sysfs_emit(buf, "feature mask: 0x%llx\n", ras_features);
1850 }
1851 
1852 static bool amdgpu_ras_get_version_info(struct amdgpu_device *adev, u32 *major,
1853 			u32 *minor, u32 *rev)
1854 {
1855 	int i;
1856 
1857 	if (!adev || !major || !minor || !rev || !amdgpu_uniras_enabled(adev))
1858 		return false;
1859 
1860 	for (i = 0; i < adev->num_ip_blocks; i++) {
1861 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_RAS) {
1862 			*major = adev->ip_blocks[i].version->major;
1863 			*minor = adev->ip_blocks[i].version->minor;
1864 			*rev = adev->ip_blocks[i].version->rev;
1865 			return true;
1866 		}
1867 	}
1868 
1869 	return false;
1870 }
1871 
1872 static ssize_t amdgpu_ras_sysfs_version_show(struct device *dev,
1873 		struct device_attribute *attr, char *buf)
1874 {
1875 	struct amdgpu_ras *con =
1876 		container_of(attr, struct amdgpu_ras, version_attr);
1877 	u32 major, minor, rev;
1878 	ssize_t size = 0;
1879 
1880 	size += sysfs_emit_at(buf, size, "table version: 0x%x\n",
1881 			con->eeprom_control.tbl_hdr.version);
1882 
1883 	if (amdgpu_ras_get_version_info(con->adev, &major, &minor, &rev))
1884 		size += sysfs_emit_at(buf, size, "ras version: %u.%u.%u\n",
1885 			major, minor, rev);
1886 
1887 	return size;
1888 }
1889 
1890 static ssize_t amdgpu_ras_sysfs_schema_show(struct device *dev,
1891 		struct device_attribute *attr, char *buf)
1892 {
1893 	struct amdgpu_ras *con =
1894 		container_of(attr, struct amdgpu_ras, schema_attr);
1895 	return sysfs_emit(buf, "schema: 0x%x\n", con->schema);
1896 }
1897 
1898 static struct {
1899 	enum ras_event_type type;
1900 	const char *name;
1901 } dump_event[] = {
1902 	{RAS_EVENT_TYPE_FATAL, "Fatal Error"},
1903 	{RAS_EVENT_TYPE_POISON_CREATION, "Poison Creation"},
1904 	{RAS_EVENT_TYPE_POISON_CONSUMPTION, "Poison Consumption"},
1905 };
1906 
1907 static ssize_t amdgpu_ras_sysfs_event_state_show(struct device *dev,
1908 						 struct device_attribute *attr, char *buf)
1909 {
1910 	struct amdgpu_ras *con =
1911 		container_of(attr, struct amdgpu_ras, event_state_attr);
1912 	struct ras_event_manager *event_mgr = con->event_mgr;
1913 	struct ras_event_state *event_state;
1914 	int i, size = 0;
1915 
1916 	if (!event_mgr)
1917 		return -EINVAL;
1918 
1919 	size += sysfs_emit_at(buf, size, "current seqno: %llu\n", atomic64_read(&event_mgr->seqno));
1920 	for (i = 0; i < ARRAY_SIZE(dump_event); i++) {
1921 		event_state = &event_mgr->event_state[dump_event[i].type];
1922 		size += sysfs_emit_at(buf, size, "%s: count:%llu, last_seqno:%llu\n",
1923 				      dump_event[i].name,
1924 				      atomic64_read(&event_state->count),
1925 				      event_state->last_seqno);
1926 	}
1927 
1928 	return (ssize_t)size;
1929 }
1930 
1931 static void amdgpu_ras_sysfs_remove_bad_page_node(struct amdgpu_device *adev)
1932 {
1933 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1934 
1935 	if (adev->dev->kobj.sd)
1936 		sysfs_remove_file_from_group(&adev->dev->kobj,
1937 				&con->badpages_attr.attr,
1938 				RAS_FS_NAME);
1939 }
1940 
1941 static int amdgpu_ras_sysfs_remove_dev_attr_node(struct amdgpu_device *adev)
1942 {
1943 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1944 	struct attribute *attrs[] = {
1945 		&con->features_attr.attr,
1946 		&con->version_attr.attr,
1947 		&con->schema_attr.attr,
1948 		&con->event_state_attr.attr,
1949 		NULL
1950 	};
1951 	struct attribute_group group = {
1952 		.name = RAS_FS_NAME,
1953 		.attrs = attrs,
1954 	};
1955 
1956 	if (adev->dev->kobj.sd)
1957 		sysfs_remove_group(&adev->dev->kobj, &group);
1958 
1959 	return 0;
1960 }
1961 
1962 int amdgpu_ras_sysfs_create(struct amdgpu_device *adev,
1963 		struct ras_common_if *head)
1964 {
1965 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
1966 
1967 	if (!obj || obj->attr_inuse)
1968 		return -EINVAL;
1969 
1970 	if (amdgpu_sriov_vf(adev) && !amdgpu_virt_ras_telemetry_block_en(adev, head->block))
1971 		return 0;
1972 
1973 	get_obj(obj);
1974 
1975 	snprintf(obj->fs_data.sysfs_name, sizeof(obj->fs_data.sysfs_name),
1976 		"%s_err_count", head->name);
1977 
1978 	obj->sysfs_attr = (struct device_attribute){
1979 		.attr = {
1980 			.name = obj->fs_data.sysfs_name,
1981 			.mode = S_IRUGO,
1982 		},
1983 			.show = amdgpu_ras_sysfs_read,
1984 	};
1985 	sysfs_attr_init(&obj->sysfs_attr.attr);
1986 
1987 	if (sysfs_add_file_to_group(&adev->dev->kobj,
1988 				&obj->sysfs_attr.attr,
1989 				RAS_FS_NAME)) {
1990 		put_obj(obj);
1991 		return -EINVAL;
1992 	}
1993 
1994 	obj->attr_inuse = 1;
1995 
1996 	return 0;
1997 }
1998 
1999 int amdgpu_ras_sysfs_remove(struct amdgpu_device *adev,
2000 		struct ras_common_if *head)
2001 {
2002 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
2003 
2004 	if (!obj || !obj->attr_inuse)
2005 		return -EINVAL;
2006 
2007 	if (adev->dev->kobj.sd)
2008 		sysfs_remove_file_from_group(&adev->dev->kobj,
2009 				&obj->sysfs_attr.attr,
2010 				RAS_FS_NAME);
2011 	obj->attr_inuse = 0;
2012 	put_obj(obj);
2013 
2014 	return 0;
2015 }
2016 
2017 static int amdgpu_ras_sysfs_remove_all(struct amdgpu_device *adev)
2018 {
2019 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2020 	struct ras_manager *obj, *tmp;
2021 
2022 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
2023 		amdgpu_ras_sysfs_remove(adev, &obj->head);
2024 	}
2025 
2026 	if (amdgpu_bad_page_threshold != 0)
2027 		amdgpu_ras_sysfs_remove_bad_page_node(adev);
2028 
2029 	amdgpu_ras_sysfs_remove_dev_attr_node(adev);
2030 
2031 	return 0;
2032 }
2033 /* sysfs end */
2034 
2035 /**
2036  * DOC: AMDGPU RAS Reboot Behavior for Unrecoverable Errors
2037  *
2038  * Normally when there is an uncorrectable error, the driver will reset
2039  * the GPU to recover.  However, in the event of an unrecoverable error,
2040  * the driver provides an interface to reboot the system automatically
2041  * in that event.
2042  *
2043  * The following file in debugfs provides that interface:
2044  * /sys/kernel/debug/dri/[0/1/2...]/ras/auto_reboot
2045  *
2046  * Usage:
2047  *
2048  * .. code-block:: bash
2049  *
2050  *	echo true > .../ras/auto_reboot
2051  *
2052  */
2053 /* debugfs begin */
2054 static struct dentry *amdgpu_ras_debugfs_create_ctrl_node(struct amdgpu_device *adev)
2055 {
2056 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2057 	struct amdgpu_ras_eeprom_control *eeprom = &con->eeprom_control;
2058 	struct drm_minor  *minor = adev_to_drm(adev)->primary;
2059 	struct dentry     *dir;
2060 
2061 	dir = debugfs_create_dir(RAS_FS_NAME, minor->debugfs_root);
2062 	debugfs_create_file("ras_ctrl", S_IWUGO | S_IRUGO, dir, adev,
2063 			    &amdgpu_ras_debugfs_ctrl_ops);
2064 	debugfs_create_file("ras_eeprom_reset", S_IWUGO | S_IRUGO, dir, adev,
2065 			    &amdgpu_ras_debugfs_eeprom_ops);
2066 	debugfs_create_u32("bad_page_cnt_threshold", 0444, dir,
2067 			   &con->bad_page_cnt_threshold);
2068 	debugfs_create_u32("ras_num_recs", 0444, dir, &eeprom->ras_num_recs);
2069 	debugfs_create_x32("ras_hw_enabled", 0444, dir, &adev->ras_hw_enabled);
2070 	debugfs_create_x32("ras_enabled", 0444, dir, &adev->ras_enabled);
2071 	debugfs_create_file("ras_eeprom_size", S_IRUGO, dir, adev,
2072 			    &amdgpu_ras_debugfs_eeprom_size_ops);
2073 	con->de_ras_eeprom_table = debugfs_create_file("ras_eeprom_table",
2074 						       S_IRUGO, dir, adev,
2075 						       &amdgpu_ras_debugfs_eeprom_table_ops);
2076 	amdgpu_ras_debugfs_set_ret_size(&con->eeprom_control);
2077 
2078 	/*
2079 	 * After one uncorrectable error happens, usually GPU recovery will
2080 	 * be scheduled. But due to the known problem in GPU recovery failing
2081 	 * to bring GPU back, below interface provides one direct way to
2082 	 * user to reboot system automatically in such case within
2083 	 * ERREVENT_ATHUB_INTERRUPT generated. Normal GPU recovery routine
2084 	 * will never be called.
2085 	 */
2086 	debugfs_create_bool("auto_reboot", S_IWUGO | S_IRUGO, dir, &con->reboot);
2087 
2088 	/*
2089 	 * User could set this not to clean up hardware's error count register
2090 	 * of RAS IPs during ras recovery.
2091 	 */
2092 	debugfs_create_bool("disable_ras_err_cnt_harvest", 0644, dir,
2093 			    &con->disable_ras_err_cnt_harvest);
2094 	return dir;
2095 }
2096 
2097 static void amdgpu_ras_debugfs_create(struct amdgpu_device *adev,
2098 				      struct ras_fs_if *head,
2099 				      struct dentry *dir)
2100 {
2101 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &head->head);
2102 
2103 	if (!obj || !dir)
2104 		return;
2105 
2106 	get_obj(obj);
2107 
2108 	memcpy(obj->fs_data.debugfs_name,
2109 			head->debugfs_name,
2110 			sizeof(obj->fs_data.debugfs_name));
2111 
2112 	debugfs_create_file(obj->fs_data.debugfs_name, S_IWUGO | S_IRUGO, dir,
2113 			    obj, &amdgpu_ras_debugfs_ops);
2114 }
2115 
2116 void amdgpu_ras_debugfs_create_all(struct amdgpu_device *adev)
2117 {
2118 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2119 	struct dentry *dir;
2120 	struct ras_manager *obj;
2121 	struct ras_fs_if fs_info;
2122 
2123 	/*
2124 	 * it won't be called in resume path, no need to check
2125 	 * suspend and gpu reset status
2126 	 */
2127 	if (!IS_ENABLED(CONFIG_DEBUG_FS) || !con)
2128 		return;
2129 
2130 	dir = amdgpu_ras_debugfs_create_ctrl_node(adev);
2131 
2132 	list_for_each_entry(obj, &con->head, node) {
2133 		if (amdgpu_ras_is_supported(adev, obj->head.block) &&
2134 			(obj->attr_inuse == 1)) {
2135 			snprintf(fs_info.debugfs_name, sizeof(fs_info.debugfs_name),
2136 					"%s_err_inject",
2137 					get_ras_block_str(&obj->head));
2138 			fs_info.head = obj->head;
2139 			amdgpu_ras_debugfs_create(adev, &fs_info, dir);
2140 		}
2141 	}
2142 }
2143 
2144 /* debugfs end */
2145 
2146 /* ras fs */
2147 static const BIN_ATTR(gpu_vram_bad_pages, S_IRUGO,
2148 		      amdgpu_ras_sysfs_badpages_read, NULL, 0);
2149 static DEVICE_ATTR(features, S_IRUGO,
2150 		amdgpu_ras_sysfs_features_read, NULL);
2151 static DEVICE_ATTR(version, 0444,
2152 		amdgpu_ras_sysfs_version_show, NULL);
2153 static DEVICE_ATTR(schema, 0444,
2154 		amdgpu_ras_sysfs_schema_show, NULL);
2155 static DEVICE_ATTR(event_state, 0444,
2156 		   amdgpu_ras_sysfs_event_state_show, NULL);
2157 static int amdgpu_ras_fs_init(struct amdgpu_device *adev)
2158 {
2159 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2160 	struct attribute_group group = {
2161 		.name = RAS_FS_NAME,
2162 	};
2163 	struct attribute *attrs[] = {
2164 		&con->features_attr.attr,
2165 		&con->version_attr.attr,
2166 		&con->schema_attr.attr,
2167 		&con->event_state_attr.attr,
2168 		NULL
2169 	};
2170 	const struct bin_attribute *bin_attrs[] = {
2171 		NULL,
2172 		NULL,
2173 	};
2174 	int r;
2175 
2176 	group.attrs = attrs;
2177 
2178 	/* add features entry */
2179 	con->features_attr = dev_attr_features;
2180 	sysfs_attr_init(attrs[0]);
2181 
2182 	/* add version entry */
2183 	con->version_attr = dev_attr_version;
2184 	sysfs_attr_init(attrs[1]);
2185 
2186 	/* add schema entry */
2187 	con->schema_attr = dev_attr_schema;
2188 	sysfs_attr_init(attrs[2]);
2189 
2190 	/* add event_state entry */
2191 	con->event_state_attr = dev_attr_event_state;
2192 	sysfs_attr_init(attrs[3]);
2193 
2194 	if (amdgpu_bad_page_threshold != 0) {
2195 		/* add bad_page_features entry */
2196 		con->badpages_attr = bin_attr_gpu_vram_bad_pages;
2197 		sysfs_bin_attr_init(&con->badpages_attr);
2198 		bin_attrs[0] = &con->badpages_attr;
2199 		group.bin_attrs = bin_attrs;
2200 	}
2201 
2202 	r = sysfs_create_group(&adev->dev->kobj, &group);
2203 	if (r)
2204 		dev_err(adev->dev, "Failed to create RAS sysfs group!");
2205 
2206 	return 0;
2207 }
2208 
2209 static int amdgpu_ras_fs_fini(struct amdgpu_device *adev)
2210 {
2211 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2212 	struct ras_manager *con_obj, *ip_obj, *tmp;
2213 
2214 	if (!con)
2215 		return 0;
2216 
2217 	if (IS_ENABLED(CONFIG_DEBUG_FS)) {
2218 		list_for_each_entry_safe(con_obj, tmp, &con->head, node) {
2219 			ip_obj = amdgpu_ras_find_obj(adev, &con_obj->head);
2220 			if (ip_obj)
2221 				put_obj(ip_obj);
2222 		}
2223 	}
2224 
2225 	amdgpu_ras_sysfs_remove_all(adev);
2226 	return 0;
2227 }
2228 /* ras fs end */
2229 
2230 /* ih begin */
2231 
2232 /* For the hardware that cannot enable bif ring for both ras_controller_irq
2233  * and ras_err_evnet_athub_irq ih cookies, the driver has to poll status
2234  * register to check whether the interrupt is triggered or not, and properly
2235  * ack the interrupt if it is there
2236  */
2237 void amdgpu_ras_interrupt_fatal_error_handler(struct amdgpu_device *adev)
2238 {
2239 	/* Fatal error events are handled on host side */
2240 	if (amdgpu_sriov_vf(adev))
2241 		return;
2242 	/*
2243 	 * If the current interrupt is caused by a non-fatal RAS error, skip
2244 	 * check for fatal error. For fatal errors, FED status of all devices
2245 	 * in XGMI hive gets set when the first device gets fatal error
2246 	 * interrupt. The error gets propagated to other devices as well, so
2247 	 * make sure to ack the interrupt regardless of FED status.
2248 	 */
2249 	if (!amdgpu_ras_get_fed_status(adev) &&
2250 	    amdgpu_ras_is_err_state(adev, AMDGPU_RAS_BLOCK__ANY))
2251 		return;
2252 
2253 	if (amdgpu_uniras_enabled(adev)) {
2254 		amdgpu_ras_mgr_handle_fatal_interrupt(adev, NULL);
2255 		return;
2256 	}
2257 
2258 	if (adev->nbio.ras &&
2259 	    adev->nbio.ras->handle_ras_controller_intr_no_bifring)
2260 		adev->nbio.ras->handle_ras_controller_intr_no_bifring(adev);
2261 
2262 	if (adev->nbio.ras &&
2263 	    adev->nbio.ras->handle_ras_err_event_athub_intr_no_bifring)
2264 		adev->nbio.ras->handle_ras_err_event_athub_intr_no_bifring(adev);
2265 }
2266 
2267 static void amdgpu_ras_interrupt_poison_consumption_handler(struct ras_manager *obj,
2268 				struct amdgpu_iv_entry *entry)
2269 {
2270 	bool poison_stat = false;
2271 	struct amdgpu_device *adev = obj->adev;
2272 	struct amdgpu_ras_block_object *block_obj =
2273 		amdgpu_ras_get_ras_block(adev, obj->head.block, 0);
2274 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2275 	enum ras_event_type type = RAS_EVENT_TYPE_POISON_CONSUMPTION;
2276 	u64 event_id;
2277 	int ret;
2278 
2279 	if (!block_obj || !con)
2280 		return;
2281 
2282 	ret = amdgpu_ras_mark_ras_event(adev, type);
2283 	if (ret)
2284 		return;
2285 
2286 	amdgpu_ras_set_err_poison(adev, block_obj->ras_comm.block);
2287 	/* both query_poison_status and handle_poison_consumption are optional,
2288 	 * but at least one of them should be implemented if we need poison
2289 	 * consumption handler
2290 	 */
2291 	if (block_obj->hw_ops && block_obj->hw_ops->query_poison_status) {
2292 		poison_stat = block_obj->hw_ops->query_poison_status(adev);
2293 		if (!poison_stat) {
2294 			/* Not poison consumption interrupt, no need to handle it */
2295 			dev_info(adev->dev, "No RAS poison status in %s poison IH.\n",
2296 					block_obj->ras_comm.name);
2297 
2298 			return;
2299 		}
2300 	}
2301 
2302 	amdgpu_umc_poison_handler(adev, obj->head.block, 0);
2303 
2304 	if (block_obj->hw_ops && block_obj->hw_ops->handle_poison_consumption)
2305 		poison_stat = block_obj->hw_ops->handle_poison_consumption(adev);
2306 
2307 	/* gpu reset is fallback for failed and default cases.
2308 	 * For RMA case, amdgpu_umc_poison_handler will handle gpu reset.
2309 	 */
2310 	if (poison_stat && !amdgpu_ras_is_rma(adev)) {
2311 		event_id = amdgpu_ras_acquire_event_id(adev, type);
2312 		RAS_EVENT_LOG(adev, event_id,
2313 			      "GPU reset for %s RAS poison consumption is issued!\n",
2314 			      block_obj->ras_comm.name);
2315 		amdgpu_ras_reset_gpu(adev);
2316 	}
2317 
2318 	if (!poison_stat)
2319 		amdgpu_gfx_poison_consumption_handler(adev, entry);
2320 }
2321 
2322 static void amdgpu_ras_interrupt_poison_creation_handler(struct ras_manager *obj,
2323 				struct amdgpu_iv_entry *entry)
2324 {
2325 	struct amdgpu_device *adev = obj->adev;
2326 	enum ras_event_type type = RAS_EVENT_TYPE_POISON_CREATION;
2327 	u64 event_id;
2328 	int ret;
2329 
2330 	ret = amdgpu_ras_mark_ras_event(adev, type);
2331 	if (ret)
2332 		return;
2333 
2334 	event_id = amdgpu_ras_acquire_event_id(adev, type);
2335 	RAS_EVENT_LOG(adev, event_id, "Poison is created\n");
2336 
2337 }
2338 
2339 static void amdgpu_ras_interrupt_umc_handler(struct ras_manager *obj,
2340 				struct amdgpu_iv_entry *entry)
2341 {
2342 	struct ras_ih_data *data = &obj->ih_data;
2343 	struct ras_err_data err_data;
2344 	int ret;
2345 
2346 	if (!data->cb)
2347 		return;
2348 
2349 	ret = amdgpu_ras_error_data_init(&err_data);
2350 	if (ret)
2351 		return;
2352 
2353 	/* Let IP handle its data, maybe we need get the output
2354 	 * from the callback to update the error type/count, etc
2355 	 */
2356 	amdgpu_ras_set_fed(obj->adev, true);
2357 	ret = data->cb(obj->adev, &err_data, entry);
2358 	/* ue will trigger an interrupt, and in that case
2359 	 * we need do a reset to recovery the whole system.
2360 	 * But leave IP do that recovery, here we just dispatch
2361 	 * the error.
2362 	 */
2363 	if (ret == AMDGPU_RAS_SUCCESS) {
2364 		/* these counts could be left as 0 if
2365 		 * some blocks do not count error number
2366 		 */
2367 		obj->err_data.ue_count += err_data.ue_count;
2368 		obj->err_data.ce_count += err_data.ce_count;
2369 	}
2370 
2371 	amdgpu_ras_error_data_fini(&err_data);
2372 }
2373 
2374 static void amdgpu_ras_interrupt_handler(struct ras_manager *obj)
2375 {
2376 	struct ras_ih_data *data = &obj->ih_data;
2377 	struct amdgpu_iv_entry entry;
2378 
2379 	while (data->rptr != data->wptr) {
2380 		rmb();
2381 		memcpy(&entry, &data->ring[data->rptr],
2382 				data->element_size);
2383 
2384 		wmb();
2385 		data->rptr = (data->aligned_element_size +
2386 				data->rptr) % data->ring_size;
2387 
2388 		if (amdgpu_ras_is_poison_mode_supported(obj->adev)) {
2389 			if (obj->head.block == AMDGPU_RAS_BLOCK__UMC)
2390 				amdgpu_ras_interrupt_poison_creation_handler(obj, &entry);
2391 			else
2392 				amdgpu_ras_interrupt_poison_consumption_handler(obj, &entry);
2393 		} else {
2394 			if (obj->head.block == AMDGPU_RAS_BLOCK__UMC)
2395 				amdgpu_ras_interrupt_umc_handler(obj, &entry);
2396 			else
2397 				dev_warn(obj->adev->dev,
2398 					"No RAS interrupt handler for non-UMC block with poison disabled.\n");
2399 		}
2400 	}
2401 }
2402 
2403 static void amdgpu_ras_interrupt_process_handler(struct work_struct *work)
2404 {
2405 	struct ras_ih_data *data =
2406 		container_of(work, struct ras_ih_data, ih_work);
2407 	struct ras_manager *obj =
2408 		container_of(data, struct ras_manager, ih_data);
2409 
2410 	amdgpu_ras_interrupt_handler(obj);
2411 }
2412 
2413 int amdgpu_ras_interrupt_dispatch(struct amdgpu_device *adev,
2414 		struct ras_dispatch_if *info)
2415 {
2416 	struct ras_manager *obj;
2417 	struct ras_ih_data *data;
2418 
2419 	if (amdgpu_uniras_enabled(adev)) {
2420 		struct ras_ih_info ih_info;
2421 
2422 		memset(&ih_info, 0, sizeof(ih_info));
2423 		ih_info.block = info->head.block;
2424 		return amdgpu_ras_mgr_dispatch_interrupt(adev, &ih_info);
2425 	}
2426 
2427 	obj = amdgpu_ras_find_obj(adev, &info->head);
2428 	if (!obj)
2429 		return -EINVAL;
2430 
2431 	data = &obj->ih_data;
2432 
2433 	if (data->inuse == 0)
2434 		return 0;
2435 
2436 	/* Might be overflow... */
2437 	memcpy(&data->ring[data->wptr], info->entry,
2438 			data->element_size);
2439 
2440 	wmb();
2441 	data->wptr = (data->aligned_element_size +
2442 			data->wptr) % data->ring_size;
2443 
2444 	schedule_work(&data->ih_work);
2445 
2446 	return 0;
2447 }
2448 
2449 int amdgpu_ras_interrupt_remove_handler(struct amdgpu_device *adev,
2450 		struct ras_common_if *head)
2451 {
2452 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
2453 	struct ras_ih_data *data;
2454 
2455 	if (!obj)
2456 		return -EINVAL;
2457 
2458 	data = &obj->ih_data;
2459 	if (data->inuse == 0)
2460 		return 0;
2461 
2462 	cancel_work_sync(&data->ih_work);
2463 
2464 	kfree(data->ring);
2465 	memset(data, 0, sizeof(*data));
2466 	put_obj(obj);
2467 
2468 	return 0;
2469 }
2470 
2471 int amdgpu_ras_interrupt_add_handler(struct amdgpu_device *adev,
2472 		struct ras_common_if *head)
2473 {
2474 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
2475 	struct ras_ih_data *data;
2476 	struct amdgpu_ras_block_object *ras_obj;
2477 
2478 	if (!obj) {
2479 		/* in case we registe the IH before enable ras feature */
2480 		obj = amdgpu_ras_create_obj(adev, head);
2481 		if (!obj)
2482 			return -EINVAL;
2483 	} else
2484 		get_obj(obj);
2485 
2486 	ras_obj = container_of(head, struct amdgpu_ras_block_object, ras_comm);
2487 
2488 	data = &obj->ih_data;
2489 	/* add the callback.etc */
2490 	*data = (struct ras_ih_data) {
2491 		.inuse = 0,
2492 		.cb = ras_obj->ras_cb,
2493 		.element_size = sizeof(struct amdgpu_iv_entry),
2494 		.rptr = 0,
2495 		.wptr = 0,
2496 	};
2497 
2498 	INIT_WORK(&data->ih_work, amdgpu_ras_interrupt_process_handler);
2499 
2500 	data->aligned_element_size = ALIGN(data->element_size, 8);
2501 	/* the ring can store 64 iv entries. */
2502 	data->ring_size = 64 * data->aligned_element_size;
2503 	data->ring = kmalloc(data->ring_size, GFP_KERNEL);
2504 	if (!data->ring) {
2505 		put_obj(obj);
2506 		return -ENOMEM;
2507 	}
2508 
2509 	/* IH is ready */
2510 	data->inuse = 1;
2511 
2512 	return 0;
2513 }
2514 
2515 static int amdgpu_ras_interrupt_remove_all(struct amdgpu_device *adev)
2516 {
2517 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2518 	struct ras_manager *obj, *tmp;
2519 
2520 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
2521 		amdgpu_ras_interrupt_remove_handler(adev, &obj->head);
2522 	}
2523 
2524 	return 0;
2525 }
2526 /* ih end */
2527 
2528 /* traversal all IPs except NBIO to query error counter */
2529 static void amdgpu_ras_log_on_err_counter(struct amdgpu_device *adev, enum ras_event_type type)
2530 {
2531 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2532 	struct ras_manager *obj;
2533 
2534 	if (!adev->ras_enabled || !con)
2535 		return;
2536 
2537 	list_for_each_entry(obj, &con->head, node) {
2538 		struct ras_query_if info = {
2539 			.head = obj->head,
2540 		};
2541 
2542 		/*
2543 		 * PCIE_BIF IP has one different isr by ras controller
2544 		 * interrupt, the specific ras counter query will be
2545 		 * done in that isr. So skip such block from common
2546 		 * sync flood interrupt isr calling.
2547 		 */
2548 		if (info.head.block == AMDGPU_RAS_BLOCK__PCIE_BIF)
2549 			continue;
2550 
2551 		/*
2552 		 * this is a workaround for aldebaran, skip send msg to
2553 		 * smu to get ecc_info table due to smu handle get ecc
2554 		 * info table failed temporarily.
2555 		 * should be removed until smu fix handle ecc_info table.
2556 		 */
2557 		if ((info.head.block == AMDGPU_RAS_BLOCK__UMC) &&
2558 		    (amdgpu_ip_version(adev, MP1_HWIP, 0) ==
2559 		     IP_VERSION(13, 0, 2)))
2560 			continue;
2561 
2562 		amdgpu_ras_query_error_status_with_event(adev, &info, type);
2563 
2564 		if (amdgpu_ip_version(adev, MP0_HWIP, 0) !=
2565 			    IP_VERSION(11, 0, 2) &&
2566 		    amdgpu_ip_version(adev, MP0_HWIP, 0) !=
2567 			    IP_VERSION(11, 0, 4) &&
2568 		    amdgpu_ip_version(adev, MP0_HWIP, 0) !=
2569 			    IP_VERSION(13, 0, 0)) {
2570 			if (amdgpu_ras_reset_error_status(adev, info.head.block))
2571 				dev_warn(adev->dev, "Failed to reset error counter and error status");
2572 		}
2573 	}
2574 }
2575 
2576 /* Parse RdRspStatus and WrRspStatus */
2577 static void amdgpu_ras_error_status_query(struct amdgpu_device *adev,
2578 					  struct ras_query_if *info)
2579 {
2580 	struct amdgpu_ras_block_object *block_obj;
2581 	/*
2582 	 * Only two block need to query read/write
2583 	 * RspStatus at current state
2584 	 */
2585 	if ((info->head.block != AMDGPU_RAS_BLOCK__GFX) &&
2586 		(info->head.block != AMDGPU_RAS_BLOCK__MMHUB))
2587 		return;
2588 
2589 	block_obj = amdgpu_ras_get_ras_block(adev,
2590 					info->head.block,
2591 					info->head.sub_block_index);
2592 
2593 	if (!block_obj || !block_obj->hw_ops) {
2594 		dev_dbg_once(adev->dev, "%s doesn't config RAS function\n",
2595 			     get_ras_block_str(&info->head));
2596 		return;
2597 	}
2598 
2599 	if (block_obj->hw_ops->query_ras_error_status)
2600 		block_obj->hw_ops->query_ras_error_status(adev);
2601 
2602 }
2603 
2604 static void amdgpu_ras_query_err_status(struct amdgpu_device *adev)
2605 {
2606 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2607 	struct ras_manager *obj;
2608 
2609 	if (!adev->ras_enabled || !con)
2610 		return;
2611 
2612 	list_for_each_entry(obj, &con->head, node) {
2613 		struct ras_query_if info = {
2614 			.head = obj->head,
2615 		};
2616 
2617 		amdgpu_ras_error_status_query(adev, &info);
2618 	}
2619 }
2620 
2621 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
2622 		struct ras_badpage *bps, uint32_t count, uint32_t start)
2623 {
2624 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2625 	struct ras_err_handler_data *data;
2626 	int r = 0;
2627 	uint32_t i;
2628 
2629 	if (!con || !con->eh_data || !bps || !count)
2630 		return -EINVAL;
2631 
2632 	mutex_lock(&con->recovery_lock);
2633 	data = con->eh_data;
2634 	if (start < data->count) {
2635 		for (i = start; i < data->count; i++) {
2636 			if (!data->bps[i].ts)
2637 				continue;
2638 
2639 			/* U64_MAX is used to mark the record as invalid */
2640 			if (data->bps[i].retired_page == U64_MAX)
2641 				continue;
2642 
2643 			bps[r].bp = data->bps[i].retired_page;
2644 			r++;
2645 			if (r >= count)
2646 				break;
2647 		}
2648 	}
2649 	mutex_unlock(&con->recovery_lock);
2650 
2651 	return r;
2652 }
2653 
2654 static int amdgpu_uniras_badpages_read(struct amdgpu_device *adev,
2655 		struct ras_badpage *bps, uint32_t count, uint32_t start)
2656 {
2657 	struct ras_cmd_bad_pages_info_req cmd_input;
2658 	struct ras_cmd_bad_pages_info_rsp *output;
2659 	uint32_t group, start_group, end_group;
2660 	uint32_t pos, pos_in_group;
2661 	int r = 0, i;
2662 
2663 	if (!bps || !count)
2664 		return -EINVAL;
2665 
2666 	output = kmalloc_obj(*output);
2667 	if (!output)
2668 		return -ENOMEM;
2669 
2670 	memset(&cmd_input, 0, sizeof(cmd_input));
2671 
2672 	start_group = start / RAS_CMD_MAX_BAD_PAGES_PER_GROUP;
2673 	end_group = (start + count + RAS_CMD_MAX_BAD_PAGES_PER_GROUP - 1) /
2674 				RAS_CMD_MAX_BAD_PAGES_PER_GROUP;
2675 
2676 	pos = start;
2677 	for (group = start_group; group < end_group; group++) {
2678 		memset(output, 0, sizeof(*output));
2679 		cmd_input.group_index = group;
2680 		if (amdgpu_ras_mgr_handle_ras_cmd(adev, RAS_CMD__GET_BAD_PAGES,
2681 			&cmd_input, sizeof(cmd_input), output, sizeof(*output)))
2682 			goto out;
2683 
2684 		if (pos >= output->bp_total_cnt)
2685 			goto out;
2686 
2687 		pos_in_group = pos - group * RAS_CMD_MAX_BAD_PAGES_PER_GROUP;
2688 		for (i = pos_in_group; i < output->bp_in_group; i++, pos++) {
2689 			if (!output->records[i].ts)
2690 				continue;
2691 
2692 			bps[r].bp = output->records[i].retired_page;
2693 			r++;
2694 			if (r >= count)
2695 				goto out;
2696 		}
2697 	}
2698 
2699 out:
2700 	kfree(output);
2701 	return r;
2702 }
2703 
2704 static void amdgpu_ras_set_fed_all(struct amdgpu_device *adev,
2705 				   struct amdgpu_hive_info *hive, bool status)
2706 {
2707 	struct amdgpu_device *tmp_adev;
2708 
2709 	if (hive) {
2710 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head)
2711 			amdgpu_ras_set_fed(tmp_adev, status);
2712 	} else {
2713 		amdgpu_ras_set_fed(adev, status);
2714 	}
2715 }
2716 
2717 bool amdgpu_ras_in_recovery(struct amdgpu_device *adev)
2718 {
2719 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
2720 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
2721 	int hive_ras_recovery = 0;
2722 
2723 	if (hive) {
2724 		hive_ras_recovery = atomic_read(&hive->ras_recovery);
2725 		amdgpu_put_xgmi_hive(hive);
2726 	}
2727 
2728 	if (ras && (atomic_read(&ras->in_recovery) || hive_ras_recovery))
2729 		return true;
2730 
2731 	return false;
2732 }
2733 
2734 static enum ras_event_type amdgpu_ras_get_fatal_error_event(struct amdgpu_device *adev)
2735 {
2736 	if (amdgpu_ras_intr_triggered())
2737 		return RAS_EVENT_TYPE_FATAL;
2738 	else
2739 		return RAS_EVENT_TYPE_POISON_CONSUMPTION;
2740 }
2741 
2742 static void amdgpu_ras_do_recovery(struct work_struct *work)
2743 {
2744 	struct amdgpu_ras *ras =
2745 		container_of(work, struct amdgpu_ras, recovery_work);
2746 	struct amdgpu_device *remote_adev = NULL;
2747 	struct amdgpu_device *adev = ras->adev;
2748 	struct list_head device_list, *device_list_handle =  NULL;
2749 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
2750 	unsigned int error_query_mode;
2751 	enum ras_event_type type;
2752 
2753 	if (hive) {
2754 		atomic_set(&hive->ras_recovery, 1);
2755 
2756 		/* If any device which is part of the hive received RAS fatal
2757 		 * error interrupt, set fatal error status on all. This
2758 		 * condition will need a recovery, and flag will be cleared
2759 		 * as part of recovery.
2760 		 */
2761 		list_for_each_entry(remote_adev, &hive->device_list,
2762 				    gmc.xgmi.head)
2763 			if (amdgpu_ras_get_fed_status(remote_adev)) {
2764 				amdgpu_ras_set_fed_all(adev, hive, true);
2765 				break;
2766 			}
2767 	}
2768 	if (!ras->disable_ras_err_cnt_harvest) {
2769 
2770 		/* Build list of devices to query RAS related errors */
2771 		if  (hive && adev->gmc.xgmi.num_physical_nodes > 1) {
2772 			device_list_handle = &hive->device_list;
2773 		} else {
2774 			INIT_LIST_HEAD(&device_list);
2775 			list_add_tail(&adev->gmc.xgmi.head, &device_list);
2776 			device_list_handle = &device_list;
2777 		}
2778 
2779 		if (amdgpu_ras_get_error_query_mode(adev, &error_query_mode)) {
2780 			if (error_query_mode == AMDGPU_RAS_FIRMWARE_ERROR_QUERY &&
2781 			    (ras->gpu_reset_flags & AMDGPU_RAS_GPU_RESET_MODE1_RESET)) {
2782 				/* wait 500ms to ensure pmfw polling mca bank info done */
2783 				msleep(500);
2784 			}
2785 		}
2786 
2787 		type = amdgpu_ras_get_fatal_error_event(adev);
2788 		list_for_each_entry(remote_adev,
2789 				device_list_handle, gmc.xgmi.head) {
2790 			if (amdgpu_uniras_enabled(remote_adev)) {
2791 				amdgpu_ras_mgr_update_ras_ecc(remote_adev);
2792 			} else {
2793 				amdgpu_ras_query_err_status(remote_adev);
2794 				amdgpu_ras_log_on_err_counter(remote_adev, type);
2795 			}
2796 		}
2797 
2798 	}
2799 
2800 	if (amdgpu_device_should_recover_gpu(ras->adev)) {
2801 		struct amdgpu_reset_context reset_context;
2802 		memset(&reset_context, 0, sizeof(reset_context));
2803 
2804 		reset_context.method = AMD_RESET_METHOD_NONE;
2805 		reset_context.reset_req_dev = adev;
2806 		reset_context.src = AMDGPU_RESET_SRC_RAS;
2807 		set_bit(AMDGPU_SKIP_COREDUMP, &reset_context.flags);
2808 
2809 		/* Perform full reset in fatal error mode */
2810 		if (!amdgpu_ras_is_poison_mode_supported(ras->adev))
2811 			set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
2812 		else {
2813 			clear_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
2814 
2815 			if (ras->gpu_reset_flags & AMDGPU_RAS_GPU_RESET_MODE2_RESET) {
2816 				ras->gpu_reset_flags &= ~AMDGPU_RAS_GPU_RESET_MODE2_RESET;
2817 				reset_context.method = AMD_RESET_METHOD_MODE2;
2818 			}
2819 
2820 			/* Fatal error occurs in poison mode, mode1 reset is used to
2821 			 * recover gpu.
2822 			 */
2823 			if (ras->gpu_reset_flags & AMDGPU_RAS_GPU_RESET_MODE1_RESET) {
2824 				ras->gpu_reset_flags &= ~AMDGPU_RAS_GPU_RESET_MODE1_RESET;
2825 				set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
2826 
2827 				psp_fatal_error_recovery_quirk(&adev->psp);
2828 			}
2829 		}
2830 
2831 		amdgpu_device_gpu_recover(ras->adev, NULL, &reset_context);
2832 	}
2833 	atomic_set(&ras->in_recovery, 0);
2834 	if (hive) {
2835 		atomic_set(&hive->ras_recovery, 0);
2836 		amdgpu_put_xgmi_hive(hive);
2837 	}
2838 }
2839 
2840 /* alloc/realloc bps array */
2841 static int amdgpu_ras_realloc_eh_data_space(struct amdgpu_device *adev,
2842 		struct ras_err_handler_data *data, int pages)
2843 {
2844 	unsigned int old_space = data->count + data->space_left;
2845 	unsigned int new_space = old_space + pages;
2846 	unsigned int align_space = ALIGN(new_space, 512);
2847 	void *bps = kmalloc_objs(*data->bps, align_space);
2848 
2849 	if (!bps) {
2850 		return -ENOMEM;
2851 	}
2852 
2853 	if (data->bps) {
2854 		memcpy(bps, data->bps,
2855 				data->count * sizeof(*data->bps));
2856 		kfree(data->bps);
2857 	}
2858 
2859 	data->bps = bps;
2860 	data->space_left += align_space - old_space;
2861 	return 0;
2862 }
2863 
2864 static bool __check_record_in_range(struct amdgpu_device *adev,
2865 			struct eeprom_table_record *bps, int count)
2866 {
2867 	int i;
2868 
2869 	for (i = 0; i < count; i++) {
2870 		if (bps[i].retired_page >=
2871 			(adev->gmc.real_vram_size >> AMDGPU_GPU_PAGE_SHIFT)) {
2872 			dev_warn(adev->dev,
2873 				"Recorded address out of range: 0x%llx, 0x%llx, 0x%x, 0x%x\n",
2874 				bps[i].address, bps[i].retired_page,
2875 				bps[i].mem_channel, bps[i].mcumc_id);
2876 			return false;
2877 		}
2878 	}
2879 
2880 	return true;
2881 }
2882 
2883 static int __amdgpu_ras_restore_bad_pages(struct amdgpu_device *adev,
2884 					struct eeprom_table_record *bps, int count)
2885 {
2886 	int j;
2887 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2888 	struct ras_err_handler_data *data = con->eh_data;
2889 
2890 	if (!__check_record_in_range(adev, bps, count))
2891 		return 0;
2892 
2893 	for (j = 0; j < count; j++) {
2894 		if (!data->space_left &&
2895 		    amdgpu_ras_realloc_eh_data_space(adev, data, 256)) {
2896 			return -ENOMEM;
2897 		}
2898 
2899 		if (amdgpu_ras_check_bad_page_unlock(con,
2900 			bps[j].retired_page << AMDGPU_GPU_PAGE_SHIFT)) {
2901 			/* set to U64_MAX to mark it as invalid */
2902 			data->bps[data->count].retired_page = U64_MAX;
2903 			data->count++;
2904 			data->space_left--;
2905 			continue;
2906 		}
2907 
2908 		amdgpu_ras_reserve_page(adev, bps[j].retired_page);
2909 
2910 		memcpy(&data->bps[data->count], &(bps[j]),
2911 				sizeof(struct eeprom_table_record));
2912 		data->count++;
2913 		data->space_left--;
2914 		con->bad_page_num++;
2915 	}
2916 
2917 	return 0;
2918 }
2919 
2920 static int __amdgpu_ras_convert_rec_array_from_rom(struct amdgpu_device *adev,
2921 				struct eeprom_table_record *bps, struct ras_err_data *err_data,
2922 				enum amdgpu_memory_partition nps)
2923 {
2924 	/*old asics just have pa in eeprom*/
2925 	memcpy(err_data->err_addr, bps,
2926 		sizeof(struct eeprom_table_record) * adev->umc.retire_unit);
2927 
2928 	return __amdgpu_ras_restore_bad_pages(adev, err_data->err_addr, adev->umc.retire_unit);
2929 }
2930 
2931 /* it deal with vram only. */
2932 int amdgpu_ras_add_bad_pages(struct amdgpu_device *adev,
2933 		struct eeprom_table_record *bps, int pages, bool from_rom)
2934 {
2935 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2936 	struct ras_err_data err_data;
2937 	struct amdgpu_ras_eeprom_control *control =
2938 			&adev->psp.ras_context.ras->eeprom_control;
2939 	enum amdgpu_memory_partition nps = AMDGPU_NPS1_PARTITION_MODE;
2940 	int ret = 0;
2941 	uint32_t i = 0;
2942 
2943 	if (!con || !con->eh_data || !bps || pages <= 0)
2944 		return 0;
2945 
2946 	if (from_rom) {
2947 		err_data.err_addr =
2948 			kzalloc_objs(struct eeprom_table_record,
2949 				     adev->umc.retire_unit);
2950 		if (!err_data.err_addr) {
2951 			dev_warn(adev->dev, "Failed to alloc UMC error address record in mca2pa conversion!\n");
2952 			return -ENOMEM;
2953 		}
2954 
2955 		if (adev->gmc.gmc_funcs->query_mem_partition_mode)
2956 			nps = adev->gmc.gmc_funcs->query_mem_partition_mode(adev);
2957 	}
2958 
2959 	mutex_lock(&con->recovery_lock);
2960 
2961 	if (from_rom) {
2962 		/* there is no pa recs in V3, so skip pa recs processing */
2963 		if (control->tbl_hdr.version < RAS_TABLE_VER_V3) {
2964 			for (i = 0; i < pages; i++) {
2965 				if (control->ras_num_recs - i >= adev->umc.retire_unit) {
2966 					if ((bps[i].address == bps[i + 1].address) &&
2967 						(bps[i].mem_channel == bps[i + 1].mem_channel)) {
2968 						/* deal with retire_unit records a time */
2969 						ret = __amdgpu_ras_convert_rec_array_from_rom(adev,
2970 										&bps[i], &err_data, nps);
2971 						i += (adev->umc.retire_unit - 1);
2972 					} else {
2973 						break;
2974 					}
2975 				} else {
2976 					break;
2977 				}
2978 			}
2979 		}
2980 		for (; i < pages; i++)
2981 			bps[i].retired_page &= ~(UMC_NPS_MASK << UMC_NPS_SHIFT);
2982 
2983 		con->eh_data->count_saved = con->eh_data->count;
2984 	} else {
2985 		ret = __amdgpu_ras_restore_bad_pages(adev, bps, pages);
2986 	}
2987 
2988 	if (from_rom)
2989 		kfree(err_data.err_addr);
2990 	mutex_unlock(&con->recovery_lock);
2991 
2992 	return ret;
2993 }
2994 
2995 /*
2996  * write error record array to eeprom, the function should be
2997  * protected by recovery_lock
2998  * new_cnt: new added UE count, excluding reserved bad pages, can be NULL
2999  */
3000 int amdgpu_ras_save_bad_pages(struct amdgpu_device *adev,
3001 		unsigned long *new_cnt)
3002 {
3003 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3004 	struct ras_err_handler_data *data;
3005 	struct amdgpu_ras_eeprom_control *control;
3006 	int save_count, unit_num;
3007 
3008 	if (!con || !con->eh_data) {
3009 		if (new_cnt)
3010 			*new_cnt = 0;
3011 
3012 		return 0;
3013 	}
3014 
3015 	if (!con->eeprom_control.is_eeprom_valid) {
3016 		dev_warn(adev->dev,
3017 			"Failed to save EEPROM table data because of EEPROM data corruption!");
3018 		if (new_cnt)
3019 			*new_cnt = 0;
3020 
3021 		return 0;
3022 	}
3023 
3024 	mutex_lock(&con->recovery_lock);
3025 	control = &con->eeprom_control;
3026 	data = con->eh_data;
3027 	unit_num = data->count / adev->umc.retire_unit - control->ras_num_recs;
3028 
3029 	save_count = con->bad_page_num - control->ras_num_bad_pages;
3030 	mutex_unlock(&con->recovery_lock);
3031 
3032 	if (new_cnt)
3033 		*new_cnt = unit_num;
3034 
3035 	/* only new entries are saved */
3036 	if (unit_num && save_count) {
3037 		/*old asics only save pa to eeprom like before*/
3038 		if (amdgpu_ras_eeprom_append(control,
3039 				&data->bps[data->count_saved], unit_num)) {
3040 			dev_err(adev->dev, "Failed to save EEPROM table data!");
3041 			return -EIO;
3042 		}
3043 
3044 		dev_info(adev->dev, "Saved %d pages to EEPROM table.\n", save_count);
3045 		data->count_saved = data->count;
3046 	}
3047 
3048 	return 0;
3049 }
3050 
3051 /*
3052  * read error record array in eeprom and reserve enough space for
3053  * storing new bad pages
3054  */
3055 static int amdgpu_ras_load_bad_pages(struct amdgpu_device *adev)
3056 {
3057 	struct amdgpu_ras_eeprom_control *control =
3058 		&adev->psp.ras_context.ras->eeprom_control;
3059 	struct eeprom_table_record *bps;
3060 	int ret;
3061 
3062 	/* no bad page record, skip eeprom access */
3063 	if (control->ras_num_recs == 0 || amdgpu_bad_page_threshold == 0)
3064 		return 0;
3065 
3066 	bps = kzalloc_objs(*bps, control->ras_num_recs);
3067 	if (!bps)
3068 		return -ENOMEM;
3069 
3070 	ret = amdgpu_ras_eeprom_read(control, bps, control->ras_num_recs);
3071 	if (ret) {
3072 		dev_err(adev->dev, "Failed to load EEPROM table records!");
3073 	} else {
3074 		ret = amdgpu_ras_add_bad_pages(adev, bps, control->ras_num_recs, true);
3075 		if (ret)
3076 			goto out;
3077 
3078 		ret = amdgpu_ras_eeprom_check(control);
3079 		if (ret)
3080 			goto out;
3081 
3082 		/* HW not usable */
3083 		if (amdgpu_ras_is_rma(adev))
3084 			ret = -EHWPOISON;
3085 	}
3086 
3087 out:
3088 	kfree(bps);
3089 	return ret;
3090 }
3091 
3092 static int amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
3093 				uint64_t addr)
3094 {
3095 	struct ras_err_handler_data *data = con->eh_data;
3096 	struct amdgpu_device *adev = con->adev;
3097 	int i;
3098 
3099 	if ((addr >= adev->gmc.mc_vram_size &&
3100 	    adev->gmc.mc_vram_size) ||
3101 	    (addr >= RAS_UMC_INJECT_ADDR_LIMIT))
3102 		return -EINVAL;
3103 
3104 	addr >>= AMDGPU_GPU_PAGE_SHIFT;
3105 	for (i = 0; i < data->count; i++)
3106 		if (addr == data->bps[i].retired_page)
3107 			return 1;
3108 
3109 	return 0;
3110 }
3111 
3112 /*
3113  * check if an address belongs to bad page
3114  *
3115  * Note: this check is only for umc block
3116  */
3117 static int amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
3118 				uint64_t addr)
3119 {
3120 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3121 	int ret = 0;
3122 
3123 	if (!con || !con->eh_data)
3124 		return ret;
3125 
3126 	mutex_lock(&con->recovery_lock);
3127 	ret = amdgpu_ras_check_bad_page_unlock(con, addr);
3128 	mutex_unlock(&con->recovery_lock);
3129 	return ret;
3130 }
3131 
3132 static void amdgpu_ras_validate_threshold(struct amdgpu_device *adev,
3133 					  uint32_t max_count)
3134 {
3135 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3136 
3137 	/*
3138 	 * amdgpu_bad_page_threshold is used to config
3139 	 * the threshold for the number of bad pages.
3140 	 * -1:  Threshold is set to default value
3141 	 *      Driver will issue a warning message when threshold is reached
3142 	 *      and continue runtime services.
3143 	 * 0:   Disable bad page retirement
3144 	 *      Driver will not retire bad pages
3145 	 *      which is intended for debugging purpose.
3146 	 * -2:  Threshold is determined by a formula
3147 	 *      that assumes 1 bad page per 100M of local memory.
3148 	 *      Driver will continue runtime services when threhold is reached.
3149 	 * 0 < threshold < max number of bad page records in EEPROM,
3150 	 *      A user-defined threshold is set
3151 	 *      Driver will halt runtime services when this custom threshold is reached.
3152 	 */
3153 	if (amdgpu_bad_page_threshold == -2) {
3154 		u64 val = adev->gmc.mc_vram_size;
3155 
3156 		do_div(val, RAS_BAD_PAGE_COVER);
3157 		con->bad_page_cnt_threshold = min(lower_32_bits(val),
3158 						  max_count);
3159 	} else if (amdgpu_bad_page_threshold == -1) {
3160 		con->bad_page_cnt_threshold = ((con->reserved_pages_in_bytes) >> 21) << 4;
3161 	} else {
3162 		con->bad_page_cnt_threshold = min_t(int, max_count,
3163 						    amdgpu_bad_page_threshold);
3164 	}
3165 }
3166 
3167 int amdgpu_ras_init_badpage_info(struct amdgpu_device *adev)
3168 {
3169 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3170 	struct amdgpu_ras_eeprom_control *control;
3171 	int ret;
3172 
3173 	if (!con || amdgpu_sriov_vf(adev))
3174 		return 0;
3175 
3176 	/*
3177 	 * For the reset-on-init path (e.g. an NPS memory partition,
3178 	 * switch) the RAS IP block hw_init has not been enabled and
3179 	 * the amdgpu_uniras_enabled return false, check amdgpu ras
3180 	 * context uniras_enabled flag, eeprom init will be called
3181 	 * during RAS IP block hw_init.
3182 	 */
3183 	if (amdgpu_uniras_enabled(adev) || con->uniras_enabled)
3184 		return 0;
3185 
3186 	control = &con->eeprom_control;
3187 
3188 	ret = amdgpu_ras_eeprom_init(control);
3189 	control->is_eeprom_valid = !ret;
3190 
3191 	if (control->ras_num_recs && control->is_eeprom_valid) {
3192 		ret = amdgpu_ras_load_bad_pages(adev);
3193 		if (ret) {
3194 			control->is_eeprom_valid = false;
3195 			return 0;
3196 		}
3197 
3198 		amdgpu_dpm_send_hbm_bad_pages_num(
3199 			adev, control->ras_num_bad_pages);
3200 
3201 		if (con->update_channel_flag == true) {
3202 			amdgpu_dpm_send_hbm_bad_channel_flag(
3203 				adev, control->bad_channel_bitmap);
3204 			con->update_channel_flag = false;
3205 		}
3206 	}
3207 
3208 	return 0;
3209 }
3210 
3211 int amdgpu_ras_recovery_init(struct amdgpu_device *adev, bool init_bp_info)
3212 {
3213 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3214 	struct ras_err_handler_data **data;
3215 	u32  max_eeprom_records_count = 0;
3216 	int ret;
3217 
3218 	if (!con || amdgpu_sriov_vf(adev))
3219 		return 0;
3220 
3221 	/* Allow access to RAS EEPROM via debugfs, when the ASIC
3222 	 * supports RAS and debugfs is enabled, but when
3223 	 * adev->ras_enabled is unset, i.e. when "ras_enable"
3224 	 * module parameter is set to 0.
3225 	 */
3226 	con->adev = adev;
3227 
3228 	if (!adev->ras_enabled)
3229 		return 0;
3230 
3231 	data = &con->eh_data;
3232 	*data = kzalloc_obj(**data);
3233 	if (!*data) {
3234 		ret = -ENOMEM;
3235 		goto out;
3236 	}
3237 
3238 	mutex_init(&con->recovery_lock);
3239 	INIT_WORK(&con->recovery_work, amdgpu_ras_do_recovery);
3240 	atomic_set(&con->in_recovery, 0);
3241 	con->eeprom_control.bad_channel_bitmap = 0;
3242 
3243 	max_eeprom_records_count = amdgpu_ras_eeprom_max_record_count(&con->eeprom_control);
3244 	amdgpu_ras_validate_threshold(adev, max_eeprom_records_count);
3245 
3246 	if (init_bp_info) {
3247 		ret = amdgpu_ras_init_badpage_info(adev);
3248 		if (ret)
3249 			goto free;
3250 	}
3251 
3252 	mutex_init(&con->page_rsv_lock);
3253 	mutex_init(&con->page_retirement_lock);
3254 
3255 #ifdef CONFIG_X86_MCE_AMD
3256 	if ((adev->asic_type == CHIP_ALDEBARAN) &&
3257 	    (adev->gmc.xgmi.connected_to_cpu))
3258 		amdgpu_register_bad_pages_mca_notifier(adev);
3259 #endif
3260 	return 0;
3261 
3262 free:
3263 	kfree((*data)->bps);
3264 	kfree(*data);
3265 	con->eh_data = NULL;
3266 out:
3267 	dev_warn(adev->dev, "Failed to initialize ras recovery! (%d)\n", ret);
3268 
3269 	/*
3270 	 * Except error threshold exceeding case, other failure cases in this
3271 	 * function would not fail amdgpu driver init.
3272 	 */
3273 	if (!amdgpu_ras_is_rma(adev))
3274 		ret = 0;
3275 	else
3276 		ret = -EINVAL;
3277 
3278 	return ret;
3279 }
3280 
3281 static int amdgpu_ras_recovery_fini(struct amdgpu_device *adev)
3282 {
3283 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3284 	struct ras_err_handler_data *data = con->eh_data;
3285 
3286 	/* recovery_init failed to init it, fini is useless */
3287 	if (!data)
3288 		return 0;
3289 
3290 	mutex_destroy(&con->page_rsv_lock);
3291 
3292 	cancel_work_sync(&con->recovery_work);
3293 
3294 	mutex_lock(&con->recovery_lock);
3295 	con->eh_data = NULL;
3296 	kfree(data->bps);
3297 	kfree(data);
3298 	mutex_unlock(&con->recovery_lock);
3299 
3300 	amdgpu_ras_critical_region_init(adev);
3301 #ifdef CONFIG_X86_MCE_AMD
3302 	amdgpu_unregister_bad_pages_mca_notifier(adev);
3303 #endif
3304 	return 0;
3305 }
3306 /* recovery end */
3307 
3308 static bool amdgpu_ras_asic_supported(struct amdgpu_device *adev)
3309 {
3310 	if (amdgpu_sriov_vf(adev)) {
3311 		switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
3312 		case IP_VERSION(13, 0, 2):
3313 		case IP_VERSION(13, 0, 6):
3314 		case IP_VERSION(13, 0, 12):
3315 		case IP_VERSION(13, 0, 14):
3316 		case IP_VERSION(13, 0, 15):
3317 			return true;
3318 		default:
3319 			return false;
3320 		}
3321 	}
3322 
3323 	if (adev->asic_type == CHIP_IP_DISCOVERY) {
3324 		switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
3325 		case IP_VERSION(13, 0, 0):
3326 		case IP_VERSION(13, 0, 6):
3327 		case IP_VERSION(13, 0, 10):
3328 		case IP_VERSION(13, 0, 12):
3329 		case IP_VERSION(13, 0, 14):
3330 		case IP_VERSION(13, 0, 15):
3331 		case IP_VERSION(14, 0, 3):
3332 		case IP_VERSION(15, 0, 8):
3333 			return true;
3334 		default:
3335 			return false;
3336 		}
3337 	}
3338 
3339 	return adev->asic_type == CHIP_VEGA10 ||
3340 		adev->asic_type == CHIP_VEGA20 ||
3341 		adev->asic_type == CHIP_ARCTURUS ||
3342 		adev->asic_type == CHIP_ALDEBARAN ||
3343 		adev->asic_type == CHIP_SIENNA_CICHLID;
3344 }
3345 
3346 /*
3347  * this is workaround for vega20 workstation sku,
3348  * force enable gfx ras, ignore vbios gfx ras flag
3349  * due to GC EDC can not write
3350  */
3351 static void amdgpu_ras_get_quirks(struct amdgpu_device *adev)
3352 {
3353 	struct atom_context *ctx = adev->mode_info.atom_context;
3354 
3355 	if (!ctx)
3356 		return;
3357 
3358 	if (strnstr(ctx->vbios_pn, "D16406",
3359 		    sizeof(ctx->vbios_pn)) ||
3360 		strnstr(ctx->vbios_pn, "D36002",
3361 			sizeof(ctx->vbios_pn)))
3362 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__GFX);
3363 }
3364 
3365 /* Query ras capablity via atomfirmware interface */
3366 static void amdgpu_ras_query_ras_capablity_from_vbios(struct amdgpu_device *adev)
3367 {
3368 	/* mem_ecc cap */
3369 	if (amdgpu_atomfirmware_mem_ecc_supported(adev)) {
3370 		dev_info(adev->dev, "MEM ECC is active.\n");
3371 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__UMC |
3372 					 1 << AMDGPU_RAS_BLOCK__DF);
3373 	} else {
3374 		dev_info(adev->dev, "MEM ECC is not presented.\n");
3375 	}
3376 
3377 	/* sram_ecc cap */
3378 	if (amdgpu_atomfirmware_sram_ecc_supported(adev)) {
3379 		dev_info(adev->dev, "SRAM ECC is active.\n");
3380 		if (!amdgpu_sriov_vf(adev))
3381 			adev->ras_hw_enabled |= ~(1 << AMDGPU_RAS_BLOCK__UMC |
3382 						  1 << AMDGPU_RAS_BLOCK__DF);
3383 		else
3384 			adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__PCIE_BIF |
3385 						 1 << AMDGPU_RAS_BLOCK__SDMA |
3386 						 1 << AMDGPU_RAS_BLOCK__GFX);
3387 
3388 		/*
3389 		 * VCN/JPEG RAS can be supported on both bare metal and
3390 		 * SRIOV environment
3391 		 */
3392 		if (amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(2, 6, 0) ||
3393 		    amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(4, 0, 0) ||
3394 		    amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(4, 0, 3) ||
3395 		    amdgpu_ip_version(adev, VCN_HWIP, 0) == IP_VERSION(5, 0, 1))
3396 			adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__VCN |
3397 						 1 << AMDGPU_RAS_BLOCK__JPEG);
3398 		else
3399 			adev->ras_hw_enabled &= ~(1 << AMDGPU_RAS_BLOCK__VCN |
3400 						  1 << AMDGPU_RAS_BLOCK__JPEG);
3401 
3402 		/*
3403 		 * XGMI RAS is not supported if xgmi num physical nodes
3404 		 * is zero
3405 		 */
3406 		if (!adev->gmc.xgmi.num_physical_nodes)
3407 			adev->ras_hw_enabled &= ~(1 << AMDGPU_RAS_BLOCK__XGMI_WAFL);
3408 	} else {
3409 		dev_info(adev->dev, "SRAM ECC is not presented.\n");
3410 	}
3411 }
3412 
3413 /* Query poison mode from umc/df IP callbacks */
3414 static void amdgpu_ras_query_poison_mode(struct amdgpu_device *adev)
3415 {
3416 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3417 	bool df_poison, umc_poison;
3418 
3419 	/* poison setting is useless on SRIOV guest */
3420 	if (amdgpu_sriov_vf(adev) || !con)
3421 		return;
3422 
3423 	/* Init poison supported flag, the default value is false */
3424 	if (adev->gmc.xgmi.connected_to_cpu ||
3425 	    adev->gmc.is_app_apu) {
3426 		/* enabled by default when GPU is connected to CPU */
3427 		con->poison_supported = true;
3428 	} else if (adev->df.funcs &&
3429 	    adev->df.funcs->query_ras_poison_mode &&
3430 	    adev->umc.ras &&
3431 	    adev->umc.ras->query_ras_poison_mode) {
3432 		df_poison =
3433 			adev->df.funcs->query_ras_poison_mode(adev);
3434 		umc_poison =
3435 			adev->umc.ras->query_ras_poison_mode(adev);
3436 
3437 		/* Only poison is set in both DF and UMC, we can support it */
3438 		if (df_poison && umc_poison)
3439 			con->poison_supported = true;
3440 		else if (df_poison != umc_poison)
3441 			dev_warn(adev->dev,
3442 				"Poison setting is inconsistent in DF/UMC(%d:%d)!\n",
3443 				df_poison, umc_poison);
3444 	}
3445 }
3446 
3447 /*
3448  * check hardware's ras ability which will be saved in hw_supported.
3449  * if hardware does not support ras, we can skip some ras initializtion and
3450  * forbid some ras operations from IP.
3451  * if software itself, say boot parameter, limit the ras ability. We still
3452  * need allow IP do some limited operations, like disable. In such case,
3453  * we have to initialize ras as normal. but need check if operation is
3454  * allowed or not in each function.
3455  */
3456 static void amdgpu_ras_check_supported(struct amdgpu_device *adev)
3457 {
3458 	adev->ras_hw_enabled = adev->ras_enabled = 0;
3459 
3460 	if (!amdgpu_ras_asic_supported(adev))
3461 		return;
3462 
3463 	if (amdgpu_sriov_vf(adev)) {
3464 		if (amdgpu_virt_get_ras_capability(adev))
3465 			goto init_ras_enabled_flag;
3466 	}
3467 
3468 	/* query ras capability from psp */
3469 	if (amdgpu_psp_get_ras_capability(&adev->psp))
3470 		goto init_ras_enabled_flag;
3471 
3472 	/* query ras capablity from bios */
3473 	if (!adev->gmc.xgmi.connected_to_cpu && !adev->gmc.is_app_apu) {
3474 		amdgpu_ras_query_ras_capablity_from_vbios(adev);
3475 	} else {
3476 		/* driver only manages a few IP blocks RAS feature
3477 		 * when GPU is connected cpu through XGMI */
3478 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__GFX |
3479 					   1 << AMDGPU_RAS_BLOCK__SDMA |
3480 					   1 << AMDGPU_RAS_BLOCK__MMHUB);
3481 	}
3482 
3483 	/* apply asic specific settings (vega20 only for now) */
3484 	amdgpu_ras_get_quirks(adev);
3485 
3486 	/* query poison mode from umc/df ip callback */
3487 	amdgpu_ras_query_poison_mode(adev);
3488 
3489 init_ras_enabled_flag:
3490 	/* hw_supported needs to be aligned with RAS block mask. */
3491 	adev->ras_hw_enabled &= AMDGPU_RAS_BLOCK_MASK;
3492 
3493 	adev->ras_enabled = amdgpu_ras_enable == 0 ? 0 :
3494 		(uint32_t)(adev->ras_hw_enabled & amdgpu_ras_mask);
3495 
3496 	/* bad page feature is not applicable to specific app platform */
3497 	if (adev->gmc.is_app_apu &&
3498 	    amdgpu_ip_version(adev, UMC_HWIP, 0) == IP_VERSION(12, 0, 0))
3499 		amdgpu_bad_page_threshold = 0;
3500 }
3501 
3502 static void amdgpu_ras_counte_dw(struct work_struct *work)
3503 {
3504 	struct amdgpu_ras *con = container_of(work, struct amdgpu_ras,
3505 					      ras_counte_delay_work.work);
3506 	struct amdgpu_device *adev = con->adev;
3507 	struct drm_device *dev = adev_to_drm(adev);
3508 	unsigned long ce_count, ue_count;
3509 	int res;
3510 
3511 	res = pm_runtime_get_sync(dev->dev);
3512 	if (res < 0)
3513 		goto Out;
3514 
3515 	/* Cache new values.
3516 	 */
3517 	if (amdgpu_ras_query_error_count(adev, &ce_count, &ue_count, NULL) == 0) {
3518 		atomic_set(&con->ras_ce_count, ce_count);
3519 		atomic_set(&con->ras_ue_count, ue_count);
3520 	}
3521 
3522 Out:
3523 	pm_runtime_put_autosuspend(dev->dev);
3524 }
3525 
3526 static int amdgpu_get_ras_schema(struct amdgpu_device *adev)
3527 {
3528 	return  amdgpu_ras_is_poison_mode_supported(adev) ? AMDGPU_RAS_ERROR__POISON : 0 |
3529 			AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE |
3530 			AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE |
3531 			AMDGPU_RAS_ERROR__PARITY;
3532 }
3533 
3534 static void ras_event_mgr_init(struct ras_event_manager *mgr)
3535 {
3536 	struct ras_event_state *event_state;
3537 	int i;
3538 
3539 	memset(mgr, 0, sizeof(*mgr));
3540 	atomic64_set(&mgr->seqno, 0);
3541 
3542 	for (i = 0; i < ARRAY_SIZE(mgr->event_state); i++) {
3543 		event_state = &mgr->event_state[i];
3544 		event_state->last_seqno = RAS_EVENT_INVALID_ID;
3545 		atomic64_set(&event_state->count, 0);
3546 	}
3547 }
3548 
3549 static void amdgpu_ras_event_mgr_init(struct amdgpu_device *adev)
3550 {
3551 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
3552 	struct amdgpu_hive_info *hive;
3553 
3554 	if (!ras)
3555 		return;
3556 
3557 	hive = amdgpu_get_xgmi_hive(adev);
3558 	ras->event_mgr = hive ? &hive->event_mgr : &ras->__event_mgr;
3559 
3560 	/* init event manager with node 0 on xgmi system */
3561 	if (!amdgpu_reset_in_recovery(adev)) {
3562 		if (!hive || adev->gmc.xgmi.node_id == 0)
3563 			ras_event_mgr_init(ras->event_mgr);
3564 	}
3565 
3566 	if (hive)
3567 		amdgpu_put_xgmi_hive(hive);
3568 }
3569 
3570 static void amdgpu_ras_init_reserved_vram_size(struct amdgpu_device *adev)
3571 {
3572 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3573 
3574 	if (!con || (adev->flags & AMD_IS_APU))
3575 		return;
3576 
3577 	switch (amdgpu_ip_version(adev, MP0_HWIP, 0)) {
3578 	case IP_VERSION(13, 0, 2):
3579 	case IP_VERSION(13, 0, 6):
3580 	case IP_VERSION(13, 0, 12):
3581 	case IP_VERSION(13, 0, 15):
3582 		con->reserved_pages_in_bytes = AMDGPU_RAS_RESERVED_VRAM_SIZE_DEFAULT;
3583 		break;
3584 	case IP_VERSION(13, 0, 14):
3585 		con->reserved_pages_in_bytes = (AMDGPU_RAS_RESERVED_VRAM_SIZE_DEFAULT << 1);
3586 		break;
3587 	default:
3588 		break;
3589 	}
3590 }
3591 
3592 int amdgpu_ras_init(struct amdgpu_device *adev)
3593 {
3594 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3595 	struct ras_module_param param = {0};
3596 	int r;
3597 
3598 	if (con)
3599 		return 0;
3600 
3601 	con = kzalloc(sizeof(*con) +
3602 			sizeof(struct ras_manager) * AMDGPU_RAS_BLOCK_COUNT +
3603 			sizeof(struct ras_manager) * AMDGPU_RAS_MCA_BLOCK_COUNT,
3604 			GFP_KERNEL);
3605 	if (!con)
3606 		return -ENOMEM;
3607 
3608 	con->adev = adev;
3609 	INIT_DELAYED_WORK(&con->ras_counte_delay_work, amdgpu_ras_counte_dw);
3610 	atomic_set(&con->ras_ce_count, 0);
3611 	atomic_set(&con->ras_ue_count, 0);
3612 
3613 	con->objs = (struct ras_manager *)(con + 1);
3614 
3615 	amdgpu_ras_set_context(adev, con);
3616 
3617 	amdgpu_ras_check_supported(adev);
3618 
3619 	param.ras_feature_enable = amdgpu_ras_enable;
3620 	param.ras_feature_mask = amdgpu_ras_mask;
3621 	param.ras_bad_page_threshold = amdgpu_bad_page_threshold;
3622 	amdgpu_ras_mgr_sw_init(adev, &param);
3623 
3624 	if (!con->uniras_enabled &&
3625 	    (!adev->ras_enabled || adev->asic_type == CHIP_VEGA10)) {
3626 		/* set gfx block ras context feature for VEGA20 Gaming
3627 		 * send ras disable cmd to ras ta during ras late init.
3628 		 */
3629 		if (!adev->ras_enabled && adev->asic_type == CHIP_VEGA20) {
3630 			con->features |= BIT(AMDGPU_RAS_BLOCK__GFX);
3631 
3632 			return 0;
3633 		}
3634 
3635 		r = 0;
3636 		goto release_con;
3637 	}
3638 
3639 	con->update_channel_flag = false;
3640 	con->features = 0;
3641 	con->schema = 0;
3642 	INIT_LIST_HEAD(&con->head);
3643 	/* Might need get this flag from vbios. */
3644 	con->flags = RAS_DEFAULT_FLAGS;
3645 
3646 	/* initialize nbio ras function ahead of any other
3647 	 * ras functions so hardware fatal error interrupt
3648 	 * can be enabled as early as possible */
3649 	switch (amdgpu_ip_version(adev, NBIO_HWIP, 0)) {
3650 	case IP_VERSION(7, 4, 0):
3651 	case IP_VERSION(7, 4, 1):
3652 	case IP_VERSION(7, 4, 4):
3653 		if (!adev->gmc.xgmi.connected_to_cpu)
3654 			adev->nbio.ras = &nbio_v7_4_ras;
3655 		break;
3656 	case IP_VERSION(4, 3, 0):
3657 		if (adev->ras_hw_enabled & (1 << AMDGPU_RAS_BLOCK__DF))
3658 			/* unlike other generation of nbio ras,
3659 			 * nbio v4_3 only support fatal error interrupt
3660 			 * to inform software that DF is freezed due to
3661 			 * system fatal error event. driver should not
3662 			 * enable nbio ras in such case. Instead,
3663 			 * check DF RAS */
3664 			adev->nbio.ras = &nbio_v4_3_ras;
3665 		break;
3666 	case IP_VERSION(6, 3, 1):
3667 		if (adev->ras_hw_enabled & (1 << AMDGPU_RAS_BLOCK__DF))
3668 			/* unlike other generation of nbio ras,
3669 			 * nbif v6_3_1 only support fatal error interrupt
3670 			 * to inform software that DF is freezed due to
3671 			 * system fatal error event. driver should not
3672 			 * enable nbio ras in such case. Instead,
3673 			 * check DF RAS
3674 			 */
3675 			adev->nbio.ras = &nbif_v6_3_1_ras;
3676 		break;
3677 	case IP_VERSION(7, 9, 0):
3678 	case IP_VERSION(7, 9, 1):
3679 		if (!adev->gmc.is_app_apu)
3680 			adev->nbio.ras = &nbio_v7_9_ras;
3681 		break;
3682 	default:
3683 		/* nbio ras is not available */
3684 		break;
3685 	}
3686 
3687 	/* nbio ras block needs to be enabled ahead of other ras blocks
3688 	 * to handle fatal error */
3689 	r = amdgpu_nbio_ras_sw_init(adev);
3690 	if (r)
3691 		goto release_con;
3692 
3693 	if (adev->nbio.ras &&
3694 	    adev->nbio.ras->init_ras_controller_interrupt) {
3695 		r = adev->nbio.ras->init_ras_controller_interrupt(adev);
3696 		if (r)
3697 			goto release_con;
3698 	}
3699 
3700 	if (adev->nbio.ras &&
3701 	    adev->nbio.ras->init_ras_err_event_athub_interrupt) {
3702 		r = adev->nbio.ras->init_ras_err_event_athub_interrupt(adev);
3703 		if (r)
3704 			goto release_con;
3705 	}
3706 
3707 	/* Packed socket_id to ras feature mask bits[31:29] */
3708 	if (adev->smuio.funcs &&
3709 	    adev->smuio.funcs->get_socket_id)
3710 		con->features |= ((adev->smuio.funcs->get_socket_id(adev)) <<
3711 					AMDGPU_RAS_FEATURES_SOCKETID_SHIFT);
3712 
3713 	/* Get RAS schema for particular SOC */
3714 	con->schema = amdgpu_get_ras_schema(adev);
3715 
3716 	amdgpu_ras_init_reserved_vram_size(adev);
3717 
3718 	if (amdgpu_ras_fs_init(adev)) {
3719 		r = -EINVAL;
3720 		goto release_con;
3721 	}
3722 
3723 	con->init_task_pid = task_pid_nr(current);
3724 	get_task_comm(con->init_task_comm, current);
3725 
3726 	mutex_init(&con->critical_region_lock);
3727 	INIT_LIST_HEAD(&con->critical_region_head);
3728 
3729 	dev_info(adev->dev, "RAS INFO: ras initialized successfully, "
3730 		 "hardware ability[%x] ras_mask[%x]\n",
3731 		 adev->ras_hw_enabled, adev->ras_enabled);
3732 
3733 	return 0;
3734 release_con:
3735 	amdgpu_ras_set_context(adev, NULL);
3736 	kfree(con);
3737 
3738 	return r;
3739 }
3740 
3741 int amdgpu_persistent_edc_harvesting_supported(struct amdgpu_device *adev)
3742 {
3743 	if (adev->gmc.xgmi.connected_to_cpu ||
3744 	    adev->gmc.is_app_apu)
3745 		return 1;
3746 	return 0;
3747 }
3748 
3749 static int amdgpu_persistent_edc_harvesting(struct amdgpu_device *adev,
3750 					struct ras_common_if *ras_block)
3751 {
3752 	struct ras_query_if info = {
3753 		.head = *ras_block,
3754 	};
3755 
3756 	if (!amdgpu_persistent_edc_harvesting_supported(adev))
3757 		return 0;
3758 
3759 	if (amdgpu_ras_query_error_status(adev, &info) != 0)
3760 		drm_warn(adev_to_drm(adev), "RAS init query failure");
3761 
3762 	if (amdgpu_ras_reset_error_status(adev, ras_block->block) != 0)
3763 		drm_warn(adev_to_drm(adev), "RAS init harvest reset failure");
3764 
3765 	return 0;
3766 }
3767 
3768 bool amdgpu_ras_is_poison_mode_supported(struct amdgpu_device *adev)
3769 {
3770        struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3771 
3772        if (!con)
3773                return false;
3774 
3775        return con->poison_supported;
3776 }
3777 
3778 /* helper function to handle common stuff in ip late init phase */
3779 int amdgpu_ras_block_late_init(struct amdgpu_device *adev,
3780 			 struct ras_common_if *ras_block)
3781 {
3782 	struct amdgpu_ras_block_object *ras_obj = NULL;
3783 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3784 	struct ras_query_if *query_info;
3785 	unsigned long ue_count, ce_count;
3786 	int r;
3787 
3788 	/* disable RAS feature per IP block if it is not supported */
3789 	if (!amdgpu_ras_is_supported(adev, ras_block->block)) {
3790 		amdgpu_ras_feature_enable_on_boot(adev, ras_block, 0);
3791 		return 0;
3792 	}
3793 
3794 	r = amdgpu_ras_feature_enable_on_boot(adev, ras_block, 1);
3795 	if (r) {
3796 		if (adev->in_suspend || amdgpu_reset_in_recovery(adev)) {
3797 			/* in resume phase, if fail to enable ras,
3798 			 * clean up all ras fs nodes, and disable ras */
3799 			goto cleanup;
3800 		} else
3801 			return r;
3802 	}
3803 
3804 	/* check for errors on warm reset edc persisant supported ASIC */
3805 	amdgpu_persistent_edc_harvesting(adev, ras_block);
3806 
3807 	/* in resume phase, no need to create ras fs node */
3808 	if (adev->in_suspend || amdgpu_reset_in_recovery(adev))
3809 		return 0;
3810 
3811 	ras_obj = container_of(ras_block, struct amdgpu_ras_block_object, ras_comm);
3812 	if (ras_obj->ras_cb || (ras_obj->hw_ops &&
3813 	    (ras_obj->hw_ops->query_poison_status ||
3814 	    ras_obj->hw_ops->handle_poison_consumption))) {
3815 		r = amdgpu_ras_interrupt_add_handler(adev, ras_block);
3816 		if (r)
3817 			goto cleanup;
3818 	}
3819 
3820 	if (amdgpu_uniras_enabled(adev) || (ras_obj->hw_ops &&
3821 	   (ras_obj->hw_ops->query_ras_error_count ||
3822 	    ras_obj->hw_ops->query_ras_error_status)) ||
3823 	    amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 14) ||
3824 	    amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 12) ||
3825 	    amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 6)  ||
3826 	    amdgpu_ip_version(adev, MP0_HWIP, 0) == IP_VERSION(13, 0, 15)) {
3827 		r = amdgpu_ras_sysfs_create(adev, ras_block);
3828 		if (r)
3829 			goto interrupt;
3830 
3831 		/* Those are the cached values at init.
3832 		 */
3833 		query_info = kzalloc_obj(*query_info);
3834 		if (!query_info)
3835 			return -ENOMEM;
3836 		memcpy(&query_info->head, ras_block, sizeof(struct ras_common_if));
3837 
3838 		if (amdgpu_ras_query_error_count(adev, &ce_count, &ue_count, query_info) == 0) {
3839 			atomic_set(&con->ras_ce_count, ce_count);
3840 			atomic_set(&con->ras_ue_count, ue_count);
3841 		}
3842 
3843 		kfree(query_info);
3844 	}
3845 
3846 	return 0;
3847 
3848 interrupt:
3849 	if (ras_obj->ras_cb)
3850 		amdgpu_ras_interrupt_remove_handler(adev, ras_block);
3851 cleanup:
3852 	amdgpu_ras_feature_enable(adev, ras_block, 0);
3853 	return r;
3854 }
3855 
3856 static int amdgpu_ras_block_late_init_default(struct amdgpu_device *adev,
3857 			 struct ras_common_if *ras_block)
3858 {
3859 	return amdgpu_ras_block_late_init(adev, ras_block);
3860 }
3861 
3862 /* helper function to remove ras fs node and interrupt handler */
3863 void amdgpu_ras_block_late_fini(struct amdgpu_device *adev,
3864 			  struct ras_common_if *ras_block)
3865 {
3866 	struct amdgpu_ras_block_object *ras_obj;
3867 	if (!ras_block)
3868 		return;
3869 
3870 	amdgpu_ras_sysfs_remove(adev, ras_block);
3871 
3872 	ras_obj = container_of(ras_block, struct amdgpu_ras_block_object, ras_comm);
3873 	if (ras_obj->ras_cb)
3874 		amdgpu_ras_interrupt_remove_handler(adev, ras_block);
3875 }
3876 
3877 static void amdgpu_ras_block_late_fini_default(struct amdgpu_device *adev,
3878 			  struct ras_common_if *ras_block)
3879 {
3880 	return amdgpu_ras_block_late_fini(adev, ras_block);
3881 }
3882 
3883 /* do some init work after IP late init as dependence.
3884  * and it runs in resume/gpu reset/booting up cases.
3885  */
3886 void amdgpu_ras_resume(struct amdgpu_device *adev)
3887 {
3888 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3889 	struct ras_manager *obj, *tmp;
3890 
3891 	if (!adev->ras_enabled || !con) {
3892 		/* clean ras context for VEGA20 Gaming after send ras disable cmd */
3893 		amdgpu_release_ras_context(adev);
3894 
3895 		return;
3896 	}
3897 
3898 	amdgpu_ras_mgr_set_debug_mode(adev, false);
3899 
3900 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
3901 		/* Set up all other IPs which are not implemented. There is a
3902 		 * tricky thing that IP's actual ras error type should be
3903 		 * MULTI_UNCORRECTABLE, but as driver does not handle it, so
3904 		 * ERROR_NONE make sense anyway.
3905 		 */
3906 		amdgpu_ras_enable_all_features(adev, 1);
3907 
3908 		/* We enable ras on all hw_supported block, but as boot
3909 		 * parameter might disable some of them and one or more IP has
3910 		 * not implemented yet. So we disable them on behalf.
3911 		 */
3912 		list_for_each_entry_safe(obj, tmp, &con->head, node) {
3913 			if (!amdgpu_ras_is_supported(adev, obj->head.block)) {
3914 				amdgpu_ras_feature_enable(adev, &obj->head, 0);
3915 				/* there should be no any reference. */
3916 				WARN_ON(alive_obj(obj));
3917 			}
3918 		}
3919 	}
3920 }
3921 
3922 void amdgpu_ras_suspend(struct amdgpu_device *adev)
3923 {
3924 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3925 	struct amdgpu_ras_block_list *node;
3926 	struct amdgpu_ras_block_object *obj;
3927 
3928 	if (!adev->ras_enabled || !con)
3929 		return;
3930 
3931 	/* run per-block ras_suspend before tearing down the RAS context */
3932 	list_for_each_entry(node, &adev->ras_list, node) {
3933 		if (!node->active)
3934 			continue;
3935 
3936 		obj = node->ras_obj;
3937 		if (obj && obj->ras_suspend)
3938 			obj->ras_suspend(adev, &obj->ras_comm);
3939 		node->active = false;
3940 	}
3941 
3942 	amdgpu_ras_disable_all_features(adev, 0);
3943 	/* Make sure all ras objects are disabled. */
3944 	if (AMDGPU_RAS_GET_FEATURES(con->features))
3945 		amdgpu_ras_disable_all_features(adev, 1);
3946 }
3947 
3948 int amdgpu_ras_late_init(struct amdgpu_device *adev)
3949 {
3950 	struct amdgpu_ras_block_list *node, *tmp;
3951 	struct amdgpu_ras_block_object *obj;
3952 	int r;
3953 
3954 	amdgpu_ras_event_mgr_init(adev);
3955 
3956 	/* Guest side doesn't need init ras feature */
3957 	if (amdgpu_sriov_vf(adev) && !amdgpu_sriov_ras_telemetry_en(adev))
3958 		return 0;
3959 
3960 	list_for_each_entry_safe(node, tmp, &adev->ras_list, node) {
3961 		obj = node->ras_obj;
3962 		if (!obj) {
3963 			dev_warn(adev->dev, "Warning: abnormal ras list node.\n");
3964 			continue;
3965 		}
3966 
3967 		if (!amdgpu_ras_is_supported(adev, obj->ras_comm.block))
3968 			continue;
3969 
3970 		if (obj->ras_late_init) {
3971 			r = obj->ras_late_init(adev, &obj->ras_comm);
3972 			if (r) {
3973 				dev_err(adev->dev, "%s failed to execute ras_late_init! ret:%d\n",
3974 					obj->ras_comm.name, r);
3975 				return r;
3976 			}
3977 		} else {
3978 			r = amdgpu_ras_block_late_init_default(adev, &obj->ras_comm);
3979 			if (r) {
3980 				dev_err(adev->dev, "%s failed to execute ras_block_late_init_default! ret:%d\n",
3981 					obj->ras_comm.name, r);
3982 				return r;
3983 			}
3984 		}
3985 		node->active = true;
3986 	}
3987 
3988 	amdgpu_ras_check_bad_page_status(adev);
3989 
3990 	return 0;
3991 }
3992 
3993 /* do some fini work before IP fini as dependence */
3994 int amdgpu_ras_pre_fini(struct amdgpu_device *adev)
3995 {
3996 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
3997 
3998 	if (!adev->ras_enabled || !con)
3999 		return 0;
4000 
4001 
4002 	/* Need disable ras on all IPs here before ip [hw/sw]fini */
4003 	if (AMDGPU_RAS_GET_FEATURES(con->features))
4004 		amdgpu_ras_disable_all_features(adev, 0);
4005 	amdgpu_ras_recovery_fini(adev);
4006 	return 0;
4007 }
4008 
4009 int amdgpu_ras_fini(struct amdgpu_device *adev)
4010 {
4011 	struct amdgpu_ras_block_list *ras_node, *tmp;
4012 	struct amdgpu_ras_block_object *obj = NULL;
4013 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4014 
4015 	amdgpu_ras_mgr_sw_fini(adev);
4016 
4017 	amdgpu_ras_fs_fini(adev);
4018 
4019 	if (!adev->ras_enabled || !con)
4020 		return 0;
4021 
4022 	amdgpu_ras_critical_region_fini(adev);
4023 	mutex_destroy(&con->critical_region_lock);
4024 
4025 	list_for_each_entry_safe(ras_node, tmp, &adev->ras_list, node) {
4026 		if (ras_node->ras_obj) {
4027 			obj = ras_node->ras_obj;
4028 			/* fall back to default cleanup if ras_suspend already ran */
4029 			if (ras_node->active && obj->ras_fini)
4030 				obj->ras_fini(adev, &obj->ras_comm);
4031 			else
4032 				amdgpu_ras_block_late_fini_default(adev, &obj->ras_comm);
4033 			ras_node->active = false;
4034 		}
4035 
4036 		/* Clear ras blocks from ras_list and free ras block list node */
4037 		list_del(&ras_node->node);
4038 		kfree(ras_node);
4039 	}
4040 
4041 	amdgpu_ras_interrupt_remove_all(adev);
4042 
4043 	WARN(AMDGPU_RAS_GET_FEATURES(con->features), "Feature mask is not cleared");
4044 
4045 	if (AMDGPU_RAS_GET_FEATURES(con->features))
4046 		amdgpu_ras_disable_all_features(adev, 0);
4047 
4048 	cancel_delayed_work_sync(&con->ras_counte_delay_work);
4049 
4050 	amdgpu_ras_set_context(adev, NULL);
4051 	kfree(con);
4052 
4053 	return 0;
4054 }
4055 
4056 bool amdgpu_ras_get_fed_status(struct amdgpu_device *adev)
4057 {
4058 	struct amdgpu_ras *ras;
4059 
4060 	ras = amdgpu_ras_get_context(adev);
4061 	if (!ras)
4062 		return false;
4063 
4064 	return test_bit(AMDGPU_RAS_BLOCK__LAST, &ras->ras_err_state);
4065 }
4066 
4067 void amdgpu_ras_set_fed(struct amdgpu_device *adev, bool status)
4068 {
4069 	struct amdgpu_ras *ras;
4070 
4071 	ras = amdgpu_ras_get_context(adev);
4072 	if (ras) {
4073 		if (status)
4074 			set_bit(AMDGPU_RAS_BLOCK__LAST, &ras->ras_err_state);
4075 		else
4076 			clear_bit(AMDGPU_RAS_BLOCK__LAST, &ras->ras_err_state);
4077 	}
4078 }
4079 
4080 void amdgpu_ras_clear_err_state(struct amdgpu_device *adev)
4081 {
4082 	struct amdgpu_ras *ras;
4083 
4084 	ras = amdgpu_ras_get_context(adev);
4085 	if (ras) {
4086 		ras->ras_err_state = 0;
4087 		ras->gpu_reset_flags = 0;
4088 	}
4089 }
4090 
4091 void amdgpu_ras_set_err_poison(struct amdgpu_device *adev,
4092 			       enum amdgpu_ras_block block)
4093 {
4094 	struct amdgpu_ras *ras;
4095 
4096 	ras = amdgpu_ras_get_context(adev);
4097 	if (ras)
4098 		set_bit(block, &ras->ras_err_state);
4099 }
4100 
4101 bool amdgpu_ras_is_err_state(struct amdgpu_device *adev, int block)
4102 {
4103 	struct amdgpu_ras *ras;
4104 
4105 	ras = amdgpu_ras_get_context(adev);
4106 	if (ras) {
4107 		if (block == AMDGPU_RAS_BLOCK__ANY)
4108 			return (ras->ras_err_state != 0);
4109 		else
4110 			return test_bit(block, &ras->ras_err_state) ||
4111 			       test_bit(AMDGPU_RAS_BLOCK__LAST,
4112 					&ras->ras_err_state);
4113 	}
4114 
4115 	return false;
4116 }
4117 
4118 static struct ras_event_manager *__get_ras_event_mgr(struct amdgpu_device *adev)
4119 {
4120 	struct amdgpu_ras *ras;
4121 
4122 	ras = amdgpu_ras_get_context(adev);
4123 	if (!ras)
4124 		return NULL;
4125 
4126 	return ras->event_mgr;
4127 }
4128 
4129 int amdgpu_ras_mark_ras_event_caller(struct amdgpu_device *adev, enum ras_event_type type,
4130 				     const void *caller)
4131 {
4132 	struct ras_event_manager *event_mgr;
4133 	struct ras_event_state *event_state;
4134 	int ret = 0;
4135 
4136 	if (amdgpu_uniras_enabled(adev))
4137 		return 0;
4138 
4139 	if (type >= RAS_EVENT_TYPE_COUNT) {
4140 		ret = -EINVAL;
4141 		goto out;
4142 	}
4143 
4144 	event_mgr = __get_ras_event_mgr(adev);
4145 	if (!event_mgr) {
4146 		ret = -EINVAL;
4147 		goto out;
4148 	}
4149 
4150 	event_state = &event_mgr->event_state[type];
4151 	event_state->last_seqno = atomic64_inc_return(&event_mgr->seqno);
4152 	atomic64_inc(&event_state->count);
4153 
4154 out:
4155 	if (ret && caller)
4156 		dev_warn(adev->dev, "failed mark ras event (%d) in %ps, ret:%d\n",
4157 			 (int)type, caller, ret);
4158 
4159 	return ret;
4160 }
4161 
4162 u64 amdgpu_ras_acquire_event_id(struct amdgpu_device *adev, enum ras_event_type type)
4163 {
4164 	struct ras_event_manager *event_mgr;
4165 	u64 id;
4166 
4167 	if (type >= RAS_EVENT_TYPE_COUNT)
4168 		return RAS_EVENT_INVALID_ID;
4169 
4170 	switch (type) {
4171 	case RAS_EVENT_TYPE_FATAL:
4172 	case RAS_EVENT_TYPE_POISON_CREATION:
4173 	case RAS_EVENT_TYPE_POISON_CONSUMPTION:
4174 		event_mgr = __get_ras_event_mgr(adev);
4175 		if (!event_mgr)
4176 			return RAS_EVENT_INVALID_ID;
4177 
4178 		id = event_mgr->event_state[type].last_seqno;
4179 		break;
4180 	case RAS_EVENT_TYPE_INVALID:
4181 	default:
4182 		id = RAS_EVENT_INVALID_ID;
4183 		break;
4184 	}
4185 
4186 	return id;
4187 }
4188 
4189 int amdgpu_ras_global_ras_isr(struct amdgpu_device *adev)
4190 {
4191 	if (atomic_cmpxchg(&amdgpu_ras_in_intr, 0, 1) == 0) {
4192 		struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4193 		enum ras_event_type type = RAS_EVENT_TYPE_FATAL;
4194 		u64 event_id = RAS_EVENT_INVALID_ID;
4195 
4196 		if (amdgpu_uniras_enabled(adev))
4197 			return 0;
4198 
4199 		if (!amdgpu_ras_mark_ras_event(adev, type))
4200 			event_id = amdgpu_ras_acquire_event_id(adev, type);
4201 
4202 		RAS_EVENT_LOG(adev, event_id, "uncorrectable hardware error"
4203 			      "(ERREVENT_ATHUB_INTERRUPT) detected!\n");
4204 
4205 		amdgpu_ras_set_fed(adev, true);
4206 		ras->gpu_reset_flags |= AMDGPU_RAS_GPU_RESET_MODE1_RESET;
4207 		amdgpu_ras_reset_gpu(adev);
4208 	}
4209 
4210 	return -EBUSY;
4211 }
4212 
4213 bool amdgpu_ras_need_emergency_restart(struct amdgpu_device *adev)
4214 {
4215 	if (adev->asic_type == CHIP_VEGA20 &&
4216 	    adev->pm.fw_version <= 0x283400) {
4217 		return !(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) &&
4218 				amdgpu_ras_intr_triggered();
4219 	}
4220 
4221 	return false;
4222 }
4223 
4224 void amdgpu_release_ras_context(struct amdgpu_device *adev)
4225 {
4226 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4227 
4228 	if (!con)
4229 		return;
4230 
4231 	if (!adev->ras_enabled && con->features & BIT(AMDGPU_RAS_BLOCK__GFX)) {
4232 		con->features &= ~BIT(AMDGPU_RAS_BLOCK__GFX);
4233 		amdgpu_ras_set_context(adev, NULL);
4234 		kfree(con);
4235 	}
4236 }
4237 
4238 #ifdef CONFIG_X86_MCE_AMD
4239 static struct amdgpu_device *find_adev(uint32_t node_id)
4240 {
4241 	int i;
4242 	struct amdgpu_device *adev = NULL;
4243 
4244 	for (i = 0; i < mce_adev_list.num_gpu; i++) {
4245 		adev = mce_adev_list.devs[i];
4246 
4247 		if (adev && adev->gmc.xgmi.connected_to_cpu &&
4248 		    adev->gmc.xgmi.physical_node_id == node_id)
4249 			break;
4250 		adev = NULL;
4251 	}
4252 
4253 	return adev;
4254 }
4255 
4256 #define GET_MCA_IPID_GPUID(m)	(((m) >> 44) & 0xF)
4257 #define GET_UMC_INST(m)		(((m) >> 21) & 0x7)
4258 #define GET_CHAN_INDEX(m)	((((m) >> 12) & 0x3) | (((m) >> 18) & 0x4))
4259 #define GPU_ID_OFFSET		8
4260 
4261 static int amdgpu_bad_page_notifier(struct notifier_block *nb,
4262 				    unsigned long val, void *data)
4263 {
4264 	struct mce *m = (struct mce *)data;
4265 	struct amdgpu_device *adev = NULL;
4266 	uint32_t gpu_id = 0;
4267 	uint32_t umc_inst = 0, ch_inst = 0;
4268 
4269 	/*
4270 	 * If the error was generated in UMC_V2, which belongs to GPU UMCs,
4271 	 * and error occurred in DramECC (Extended error code = 0) then only
4272 	 * process the error, else bail out.
4273 	 */
4274 	if (!m || !((smca_get_bank_type(m->extcpu, m->bank) == SMCA_UMC_V2) &&
4275 		    (XEC(m->status, 0x3f) == 0x0)))
4276 		return NOTIFY_DONE;
4277 
4278 	/*
4279 	 * If it is correctable error, return.
4280 	 */
4281 	if (mce_is_correctable(m))
4282 		return NOTIFY_OK;
4283 
4284 	/*
4285 	 * GPU Id is offset by GPU_ID_OFFSET in MCA_IPID_UMC register.
4286 	 */
4287 	gpu_id = GET_MCA_IPID_GPUID(m->ipid) - GPU_ID_OFFSET;
4288 
4289 	adev = find_adev(gpu_id);
4290 	if (!adev) {
4291 		DRM_WARN("%s: Unable to find adev for gpu_id: %d\n", __func__,
4292 								gpu_id);
4293 		return NOTIFY_DONE;
4294 	}
4295 
4296 	/*
4297 	 * If it is uncorrectable error, then find out UMC instance and
4298 	 * channel index.
4299 	 */
4300 	umc_inst = GET_UMC_INST(m->ipid);
4301 	ch_inst = GET_CHAN_INDEX(m->ipid);
4302 
4303 	dev_info(adev->dev, "Uncorrectable error detected in UMC inst: %d, chan_idx: %d",
4304 			     umc_inst, ch_inst);
4305 
4306 	if (!amdgpu_umc_page_retirement_mca(adev, m->addr, ch_inst, umc_inst))
4307 		return NOTIFY_OK;
4308 	else
4309 		return NOTIFY_DONE;
4310 }
4311 
4312 static struct notifier_block amdgpu_bad_page_nb = {
4313 	.notifier_call  = amdgpu_bad_page_notifier,
4314 	.priority       = MCE_PRIO_UC,
4315 };
4316 
4317 static void amdgpu_register_bad_pages_mca_notifier(struct amdgpu_device *adev)
4318 {
4319 	/*
4320 	 * Add the adev to the mce_adev_list.
4321 	 * During mode2 reset, amdgpu device is temporarily
4322 	 * removed from the mgpu_info list which can cause
4323 	 * page retirement to fail.
4324 	 * Use this list instead of mgpu_info to find the amdgpu
4325 	 * device on which the UMC error was reported.
4326 	 */
4327 	if (mce_adev_list.num_gpu >= MAX_GPU_INSTANCE) {
4328 		dev_warn_ratelimited(adev->dev,
4329 			"mce_adev_list full, skip notifier registration (max=%d)\n",
4330 			MAX_GPU_INSTANCE);
4331 		return;
4332 	}
4333 
4334 	mce_adev_list.devs[mce_adev_list.num_gpu++] = adev;
4335 
4336 	/*
4337 	 * Register the x86 notifier only once
4338 	 * with MCE subsystem.
4339 	 */
4340 	if (notifier_registered == false) {
4341 		mce_register_decode_chain(&amdgpu_bad_page_nb);
4342 		notifier_registered = true;
4343 	}
4344 }
4345 static void amdgpu_unregister_bad_pages_mca_notifier(struct amdgpu_device *adev)
4346 {
4347 	int i, j;
4348 
4349 	if (!notifier_registered && !mce_adev_list.num_gpu)
4350 		return;
4351 	for (i = 0, j = 0; i < mce_adev_list.num_gpu; i++) {
4352 		if (mce_adev_list.devs[i] == adev)
4353 			mce_adev_list.devs[i] = NULL;
4354 		if (!mce_adev_list.devs[i])
4355 			++j;
4356 	}
4357 
4358 	if (j == mce_adev_list.num_gpu) {
4359 		mce_adev_list.num_gpu = 0;
4360 		/* Unregister x86 notifier with MCE subsystem. */
4361 		if (notifier_registered) {
4362 			mce_unregister_decode_chain(&amdgpu_bad_page_nb);
4363 			notifier_registered = false;
4364 		}
4365 	}
4366 }
4367 #endif
4368 
4369 struct amdgpu_ras *amdgpu_ras_get_context(struct amdgpu_device *adev)
4370 {
4371 	if (!adev)
4372 		return NULL;
4373 
4374 	return adev->psp.ras_context.ras;
4375 }
4376 
4377 int amdgpu_ras_set_context(struct amdgpu_device *adev, struct amdgpu_ras *ras_con)
4378 {
4379 	if (!adev)
4380 		return -EINVAL;
4381 
4382 	adev->psp.ras_context.ras = ras_con;
4383 	return 0;
4384 }
4385 
4386 /* check if ras is supported on block, say, sdma, gfx */
4387 int amdgpu_ras_is_supported(struct amdgpu_device *adev,
4388 		unsigned int block)
4389 {
4390 	int ret = 0;
4391 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4392 
4393 	if (block >= AMDGPU_RAS_BLOCK_COUNT)
4394 		return 0;
4395 
4396 	ret = ras && (adev->ras_enabled & (1 << block));
4397 
4398 	/* For the special asic with mem ecc enabled but sram ecc
4399 	 * not enabled, even if the ras block is not supported on
4400 	 * .ras_enabled, if the asic supports poison mode and the
4401 	 * ras block has ras configuration, it can be considered
4402 	 * that the ras block supports ras function.
4403 	 */
4404 	if (!ret &&
4405 	    (block == AMDGPU_RAS_BLOCK__GFX ||
4406 	     block == AMDGPU_RAS_BLOCK__SDMA ||
4407 	     block == AMDGPU_RAS_BLOCK__VCN ||
4408 	     block == AMDGPU_RAS_BLOCK__JPEG) &&
4409 		(amdgpu_ras_mask & BIT_ULL(block)) &&
4410 	    amdgpu_ras_is_poison_mode_supported(adev) &&
4411 	    amdgpu_ras_get_ras_block(adev, block, 0))
4412 		ret = 1;
4413 
4414 	return ret;
4415 }
4416 
4417 int amdgpu_ras_reset_gpu(struct amdgpu_device *adev)
4418 {
4419 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4420 
4421 	/* mode1 is the only selection for RMA status */
4422 	if (amdgpu_ras_is_rma(adev)) {
4423 		ras->gpu_reset_flags = 0;
4424 		ras->gpu_reset_flags |= AMDGPU_RAS_GPU_RESET_MODE1_RESET;
4425 	}
4426 
4427 	if (atomic_cmpxchg(&ras->in_recovery, 0, 1) == 0) {
4428 		struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
4429 		int hive_ras_recovery = 0;
4430 
4431 		if (hive) {
4432 			hive_ras_recovery = atomic_read(&hive->ras_recovery);
4433 			amdgpu_put_xgmi_hive(hive);
4434 		}
4435 		/* In the case of multiple GPUs, after a GPU has started
4436 		 * resetting all GPUs on hive, other GPUs do not need to
4437 		 * trigger GPU reset again.
4438 		 */
4439 		if (!hive_ras_recovery)
4440 			amdgpu_reset_domain_schedule(ras->adev->reset_domain, &ras->recovery_work);
4441 		else
4442 			atomic_set(&ras->in_recovery, 0);
4443 	} else {
4444 		flush_work(&ras->recovery_work);
4445 		amdgpu_reset_domain_schedule(ras->adev->reset_domain, &ras->recovery_work);
4446 	}
4447 
4448 	return 0;
4449 }
4450 
4451 bool amdgpu_ras_get_error_query_mode(struct amdgpu_device *adev,
4452 				     unsigned int *error_query_mode)
4453 {
4454 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4455 
4456 	if (!con) {
4457 		*error_query_mode = AMDGPU_RAS_INVALID_ERROR_QUERY;
4458 		return false;
4459 	}
4460 
4461 	if (amdgpu_sriov_vf(adev)) {
4462 		*error_query_mode = AMDGPU_RAS_VIRT_ERROR_COUNT_QUERY;
4463 	} else if (amdgpu_uniras_enabled(adev)) {
4464 		*error_query_mode = amdgpu_ras_mgr_get_debug_mode(adev) ?
4465 			AMDGPU_RAS_DIRECT_ERROR_QUERY :
4466 			AMDGPU_RAS_FIRMWARE_ERROR_QUERY;
4467 	} else {
4468 		*error_query_mode = AMDGPU_RAS_DIRECT_ERROR_QUERY;
4469 	}
4470 
4471 	return true;
4472 }
4473 
4474 /* Register each ip ras block into amdgpu ras */
4475 int amdgpu_ras_register_ras_block(struct amdgpu_device *adev,
4476 		struct amdgpu_ras_block_object *ras_block_obj)
4477 {
4478 	struct amdgpu_ras_block_list *ras_node;
4479 	if (!adev || !ras_block_obj)
4480 		return -EINVAL;
4481 
4482 	ras_node = kzalloc_obj(*ras_node);
4483 	if (!ras_node)
4484 		return -ENOMEM;
4485 
4486 	INIT_LIST_HEAD(&ras_node->node);
4487 	ras_node->ras_obj = ras_block_obj;
4488 	list_add_tail(&ras_node->node, &adev->ras_list);
4489 
4490 	return 0;
4491 }
4492 
4493 void amdgpu_ras_get_error_type_name(uint32_t err_type, char *err_type_name)
4494 {
4495 	if (!err_type_name)
4496 		return;
4497 
4498 	switch (err_type) {
4499 	case AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE:
4500 		sprintf(err_type_name, "correctable");
4501 		break;
4502 	case AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE:
4503 		sprintf(err_type_name, "uncorrectable");
4504 		break;
4505 	default:
4506 		sprintf(err_type_name, "unknown");
4507 		break;
4508 	}
4509 }
4510 
4511 bool amdgpu_ras_inst_get_memory_id_field(struct amdgpu_device *adev,
4512 					 const struct amdgpu_ras_err_status_reg_entry *reg_entry,
4513 					 uint32_t instance,
4514 					 uint32_t *memory_id)
4515 {
4516 	uint32_t err_status_lo_data, err_status_lo_offset;
4517 
4518 	if (!reg_entry)
4519 		return false;
4520 
4521 	err_status_lo_offset =
4522 		AMDGPU_RAS_REG_ENTRY_OFFSET(reg_entry->hwip, instance,
4523 					    reg_entry->seg_lo, reg_entry->reg_lo);
4524 	err_status_lo_data = RREG32(err_status_lo_offset);
4525 
4526 	if ((reg_entry->flags & AMDGPU_RAS_ERR_STATUS_VALID) &&
4527 	    !REG_GET_FIELD(err_status_lo_data, ERR_STATUS_LO, ERR_STATUS_VALID_FLAG))
4528 		return false;
4529 
4530 	*memory_id = REG_GET_FIELD(err_status_lo_data, ERR_STATUS_LO, MEMORY_ID);
4531 
4532 	return true;
4533 }
4534 
4535 bool amdgpu_ras_inst_get_err_cnt_field(struct amdgpu_device *adev,
4536 				       const struct amdgpu_ras_err_status_reg_entry *reg_entry,
4537 				       uint32_t instance,
4538 				       unsigned long *err_cnt)
4539 {
4540 	uint32_t err_status_hi_data, err_status_hi_offset;
4541 
4542 	if (!reg_entry)
4543 		return false;
4544 
4545 	err_status_hi_offset =
4546 		AMDGPU_RAS_REG_ENTRY_OFFSET(reg_entry->hwip, instance,
4547 					    reg_entry->seg_hi, reg_entry->reg_hi);
4548 	err_status_hi_data = RREG32(err_status_hi_offset);
4549 
4550 	if ((reg_entry->flags & AMDGPU_RAS_ERR_INFO_VALID) &&
4551 	    !REG_GET_FIELD(err_status_hi_data, ERR_STATUS_HI, ERR_INFO_VALID_FLAG))
4552 		/* keep the check here in case we need to refer to the result later */
4553 		dev_dbg(adev->dev, "Invalid err_info field\n");
4554 
4555 	/* read err count */
4556 	*err_cnt = REG_GET_FIELD(err_status_hi_data, ERR_STATUS, ERR_CNT);
4557 
4558 	return true;
4559 }
4560 
4561 void amdgpu_ras_inst_query_ras_error_count(struct amdgpu_device *adev,
4562 					   const struct amdgpu_ras_err_status_reg_entry *reg_list,
4563 					   uint32_t reg_list_size,
4564 					   const struct amdgpu_ras_memory_id_entry *mem_list,
4565 					   uint32_t mem_list_size,
4566 					   uint32_t instance,
4567 					   uint32_t err_type,
4568 					   unsigned long *err_count)
4569 {
4570 	uint32_t memory_id;
4571 	unsigned long err_cnt;
4572 	char err_type_name[16];
4573 	uint32_t i, j;
4574 
4575 	for (i = 0; i < reg_list_size; i++) {
4576 		/* query memory_id from err_status_lo */
4577 		if (!amdgpu_ras_inst_get_memory_id_field(adev, &reg_list[i],
4578 							 instance, &memory_id))
4579 			continue;
4580 
4581 		/* query err_cnt from err_status_hi */
4582 		if (!amdgpu_ras_inst_get_err_cnt_field(adev, &reg_list[i],
4583 						       instance, &err_cnt) ||
4584 		    !err_cnt)
4585 			continue;
4586 
4587 		*err_count += err_cnt;
4588 
4589 		/* log the errors */
4590 		amdgpu_ras_get_error_type_name(err_type, err_type_name);
4591 		if (!mem_list) {
4592 			/* memory_list is not supported */
4593 			dev_info(adev->dev,
4594 				 "%ld %s hardware errors detected in %s, instance: %d, memory_id: %d\n",
4595 				 err_cnt, err_type_name,
4596 				 reg_list[i].block_name,
4597 				 instance, memory_id);
4598 		} else {
4599 			for (j = 0; j < mem_list_size; j++) {
4600 				if (memory_id == mem_list[j].memory_id) {
4601 					dev_info(adev->dev,
4602 						 "%ld %s hardware errors detected in %s, instance: %d, memory block: %s\n",
4603 						 err_cnt, err_type_name,
4604 						 reg_list[i].block_name,
4605 						 instance, mem_list[j].name);
4606 					break;
4607 				}
4608 			}
4609 		}
4610 	}
4611 }
4612 
4613 void amdgpu_ras_inst_reset_ras_error_count(struct amdgpu_device *adev,
4614 					   const struct amdgpu_ras_err_status_reg_entry *reg_list,
4615 					   uint32_t reg_list_size,
4616 					   uint32_t instance)
4617 {
4618 	uint32_t err_status_lo_offset, err_status_hi_offset;
4619 	uint32_t i;
4620 
4621 	for (i = 0; i < reg_list_size; i++) {
4622 		err_status_lo_offset =
4623 			AMDGPU_RAS_REG_ENTRY_OFFSET(reg_list[i].hwip, instance,
4624 						    reg_list[i].seg_lo, reg_list[i].reg_lo);
4625 		err_status_hi_offset =
4626 			AMDGPU_RAS_REG_ENTRY_OFFSET(reg_list[i].hwip, instance,
4627 						    reg_list[i].seg_hi, reg_list[i].reg_hi);
4628 		WREG32(err_status_lo_offset, 0);
4629 		WREG32(err_status_hi_offset, 0);
4630 	}
4631 }
4632 
4633 int amdgpu_ras_error_data_init(struct ras_err_data *err_data)
4634 {
4635 	memset(err_data, 0, sizeof(*err_data));
4636 
4637 	INIT_LIST_HEAD(&err_data->err_node_list);
4638 
4639 	return 0;
4640 }
4641 
4642 static void amdgpu_ras_error_node_release(struct ras_err_node *err_node)
4643 {
4644 	if (!err_node)
4645 		return;
4646 
4647 	list_del(&err_node->node);
4648 	kvfree(err_node);
4649 }
4650 
4651 void amdgpu_ras_error_data_fini(struct ras_err_data *err_data)
4652 {
4653 	struct ras_err_node *err_node, *tmp;
4654 
4655 	list_for_each_entry_safe(err_node, tmp, &err_data->err_node_list, node)
4656 		amdgpu_ras_error_node_release(err_node);
4657 }
4658 
4659 static struct ras_err_node *amdgpu_ras_error_find_node_by_id(struct ras_err_data *err_data,
4660 							     struct amdgpu_smuio_mcm_config_info *mcm_info)
4661 {
4662 	struct ras_err_node *err_node;
4663 	struct amdgpu_smuio_mcm_config_info *ref_id;
4664 
4665 	if (!err_data || !mcm_info)
4666 		return NULL;
4667 
4668 	for_each_ras_error(err_node, err_data) {
4669 		ref_id = &err_node->err_info.mcm_info;
4670 
4671 		if (mcm_info->socket_id == ref_id->socket_id &&
4672 		    mcm_info->die_id == ref_id->die_id)
4673 			return err_node;
4674 	}
4675 
4676 	return NULL;
4677 }
4678 
4679 static struct ras_err_node *amdgpu_ras_error_node_new(void)
4680 {
4681 	struct ras_err_node *err_node;
4682 
4683 	err_node = kvzalloc_obj(*err_node);
4684 	if (!err_node)
4685 		return NULL;
4686 
4687 	INIT_LIST_HEAD(&err_node->node);
4688 
4689 	return err_node;
4690 }
4691 
4692 static int ras_err_info_cmp(void *priv, const struct list_head *a, const struct list_head *b)
4693 {
4694 	struct ras_err_node *nodea = container_of(a, struct ras_err_node, node);
4695 	struct ras_err_node *nodeb = container_of(b, struct ras_err_node, node);
4696 	struct amdgpu_smuio_mcm_config_info *infoa = &nodea->err_info.mcm_info;
4697 	struct amdgpu_smuio_mcm_config_info *infob = &nodeb->err_info.mcm_info;
4698 
4699 	if (unlikely(infoa->socket_id != infob->socket_id))
4700 		return infoa->socket_id - infob->socket_id;
4701 	else
4702 		return infoa->die_id - infob->die_id;
4703 
4704 	return 0;
4705 }
4706 
4707 static struct ras_err_info *amdgpu_ras_error_get_info(struct ras_err_data *err_data,
4708 				struct amdgpu_smuio_mcm_config_info *mcm_info)
4709 {
4710 	struct ras_err_node *err_node;
4711 
4712 	err_node = amdgpu_ras_error_find_node_by_id(err_data, mcm_info);
4713 	if (err_node)
4714 		return &err_node->err_info;
4715 
4716 	err_node = amdgpu_ras_error_node_new();
4717 	if (!err_node)
4718 		return NULL;
4719 
4720 	memcpy(&err_node->err_info.mcm_info, mcm_info, sizeof(*mcm_info));
4721 
4722 	err_data->err_list_count++;
4723 	list_add_tail(&err_node->node, &err_data->err_node_list);
4724 	list_sort(NULL, &err_data->err_node_list, ras_err_info_cmp);
4725 
4726 	return &err_node->err_info;
4727 }
4728 
4729 int amdgpu_ras_error_statistic_ue_count(struct ras_err_data *err_data,
4730 					struct amdgpu_smuio_mcm_config_info *mcm_info,
4731 					u64 count)
4732 {
4733 	struct ras_err_info *err_info;
4734 
4735 	if (!err_data || !mcm_info)
4736 		return -EINVAL;
4737 
4738 	if (!count)
4739 		return 0;
4740 
4741 	err_info = amdgpu_ras_error_get_info(err_data, mcm_info);
4742 	if (!err_info)
4743 		return -EINVAL;
4744 
4745 	err_info->ue_count += count;
4746 	err_data->ue_count += count;
4747 
4748 	return 0;
4749 }
4750 
4751 int amdgpu_ras_error_statistic_ce_count(struct ras_err_data *err_data,
4752 					struct amdgpu_smuio_mcm_config_info *mcm_info,
4753 					u64 count)
4754 {
4755 	struct ras_err_info *err_info;
4756 
4757 	if (!err_data || !mcm_info)
4758 		return -EINVAL;
4759 
4760 	if (!count)
4761 		return 0;
4762 
4763 	err_info = amdgpu_ras_error_get_info(err_data, mcm_info);
4764 	if (!err_info)
4765 		return -EINVAL;
4766 
4767 	err_info->ce_count += count;
4768 	err_data->ce_count += count;
4769 
4770 	return 0;
4771 }
4772 
4773 #define mmMP0_SMN_C2PMSG_92	0x1609C
4774 #define mmMP0_SMN_C2PMSG_126	0x160BE
4775 static void amdgpu_ras_boot_time_error_reporting(struct amdgpu_device *adev,
4776 						 u32 instance)
4777 {
4778 	u32 socket_id, aid_id, hbm_id;
4779 	u32 fw_status;
4780 	u32 boot_error;
4781 	u64 reg_addr;
4782 
4783 	/* The pattern for smn addressing in other SOC could be different from
4784 	 * the one for aqua_vanjaram. We should revisit the code if the pattern
4785 	 * is changed. In such case, replace the aqua_vanjaram implementation
4786 	 * with more common helper */
4787 	reg_addr = (mmMP0_SMN_C2PMSG_92 << 2) +
4788 		   amdgpu_reg_get_smn_base64(adev, MP0_HWIP, instance);
4789 	fw_status = amdgpu_device_indirect_rreg_ext(adev, reg_addr);
4790 
4791 	reg_addr = (mmMP0_SMN_C2PMSG_126 << 2) +
4792 		   amdgpu_reg_get_smn_base64(adev, MP0_HWIP, instance);
4793 	boot_error = amdgpu_device_indirect_rreg_ext(adev, reg_addr);
4794 
4795 	socket_id = AMDGPU_RAS_GPU_ERR_SOCKET_ID(boot_error);
4796 	aid_id = AMDGPU_RAS_GPU_ERR_AID_ID(boot_error);
4797 	hbm_id = ((1 == AMDGPU_RAS_GPU_ERR_HBM_ID(boot_error)) ? 0 : 1);
4798 
4799 	if (AMDGPU_RAS_GPU_ERR_MEM_TRAINING(boot_error))
4800 		dev_info(adev->dev,
4801 			 "socket: %d, aid: %d, hbm: %d, fw_status: 0x%x, memory training failed\n",
4802 			 socket_id, aid_id, hbm_id, fw_status);
4803 
4804 	if (AMDGPU_RAS_GPU_ERR_FW_LOAD(boot_error))
4805 		dev_info(adev->dev,
4806 			 "socket: %d, aid: %d, fw_status: 0x%x, firmware load failed at boot time\n",
4807 			 socket_id, aid_id, fw_status);
4808 
4809 	if (AMDGPU_RAS_GPU_ERR_WAFL_LINK_TRAINING(boot_error))
4810 		dev_info(adev->dev,
4811 			 "socket: %d, aid: %d, fw_status: 0x%x, wafl link training failed\n",
4812 			 socket_id, aid_id, fw_status);
4813 
4814 	if (AMDGPU_RAS_GPU_ERR_XGMI_LINK_TRAINING(boot_error))
4815 		dev_info(adev->dev,
4816 			 "socket: %d, aid: %d, fw_status: 0x%x, xgmi link training failed\n",
4817 			 socket_id, aid_id, fw_status);
4818 
4819 	if (AMDGPU_RAS_GPU_ERR_USR_CP_LINK_TRAINING(boot_error))
4820 		dev_info(adev->dev,
4821 			 "socket: %d, aid: %d, fw_status: 0x%x, usr cp link training failed\n",
4822 			 socket_id, aid_id, fw_status);
4823 
4824 	if (AMDGPU_RAS_GPU_ERR_USR_DP_LINK_TRAINING(boot_error))
4825 		dev_info(adev->dev,
4826 			 "socket: %d, aid: %d, fw_status: 0x%x, usr dp link training failed\n",
4827 			 socket_id, aid_id, fw_status);
4828 
4829 	if (AMDGPU_RAS_GPU_ERR_HBM_MEM_TEST(boot_error))
4830 		dev_info(adev->dev,
4831 			 "socket: %d, aid: %d, hbm: %d, fw_status: 0x%x, hbm memory test failed\n",
4832 			 socket_id, aid_id, hbm_id, fw_status);
4833 
4834 	if (AMDGPU_RAS_GPU_ERR_HBM_BIST_TEST(boot_error))
4835 		dev_info(adev->dev,
4836 			 "socket: %d, aid: %d, hbm: %d, fw_status: 0x%x, hbm bist test failed\n",
4837 			 socket_id, aid_id, hbm_id, fw_status);
4838 
4839 	if (AMDGPU_RAS_GPU_ERR_DATA_ABORT(boot_error))
4840 		dev_info(adev->dev,
4841 			 "socket: %d, aid: %d, fw_status: 0x%x, data abort exception\n",
4842 			 socket_id, aid_id, fw_status);
4843 
4844 	if (AMDGPU_RAS_GPU_ERR_GENERIC(boot_error))
4845 		dev_info(adev->dev,
4846 			 "socket: %d, aid: %d, fw_status: 0x%x, Boot Controller Generic Error\n",
4847 			 socket_id, aid_id, fw_status);
4848 }
4849 
4850 static bool amdgpu_ras_boot_error_detected(struct amdgpu_device *adev,
4851 					   u32 instance)
4852 {
4853 	u64 reg_addr;
4854 	u32 reg_data;
4855 	int retry_loop;
4856 
4857 	reg_addr = (mmMP0_SMN_C2PMSG_92 << 2) +
4858 		   amdgpu_reg_get_smn_base64(adev, MP0_HWIP, instance);
4859 
4860 	for (retry_loop = 0; retry_loop < AMDGPU_RAS_BOOT_STATUS_POLLING_LIMIT; retry_loop++) {
4861 		reg_data = amdgpu_device_indirect_rreg_ext(adev, reg_addr);
4862 		if ((reg_data & AMDGPU_RAS_BOOT_STATUS_MASK) == AMDGPU_RAS_BOOT_STEADY_STATUS)
4863 			return false;
4864 		else
4865 			msleep(1);
4866 	}
4867 
4868 	return true;
4869 }
4870 
4871 void amdgpu_ras_query_boot_status(struct amdgpu_device *adev, u32 num_instances)
4872 {
4873 	u32 i;
4874 
4875 	for (i = 0; i < num_instances; i++) {
4876 		if (amdgpu_ras_boot_error_detected(adev, i))
4877 			amdgpu_ras_boot_time_error_reporting(adev, i);
4878 	}
4879 }
4880 
4881 int amdgpu_ras_reserve_page(struct amdgpu_device *adev, uint64_t pfn)
4882 {
4883 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4884 	struct amdgpu_vram_mgr *mgr = &adev->mman.vram_mgr;
4885 	uint64_t start = pfn << AMDGPU_GPU_PAGE_SHIFT;
4886 	int ret = 0;
4887 
4888 	if (pfn >= (adev->gmc.real_vram_size >> AMDGPU_GPU_PAGE_SHIFT)) {
4889 		dev_warn(adev->dev, "Ignoring out-of-range bad page 0x%llx", start);
4890 		return 0;
4891 	}
4892 
4893 	if (amdgpu_ras_check_critical_address(adev, start))
4894 		return 0;
4895 
4896 	mutex_lock(&con->page_rsv_lock);
4897 	ret = amdgpu_vram_mgr_query_page_status(mgr, start);
4898 	if (ret == -ENOENT)
4899 		ret = amdgpu_vram_mgr_reserve_range(mgr, start, AMDGPU_GPU_PAGE_SIZE);
4900 	mutex_unlock(&con->page_rsv_lock);
4901 
4902 	return ret;
4903 }
4904 
4905 void amdgpu_ras_event_log_print(struct amdgpu_device *adev, u64 event_id,
4906 				const char *fmt, ...)
4907 {
4908 	struct va_format vaf;
4909 	va_list args;
4910 
4911 	va_start(args, fmt);
4912 	vaf.fmt = fmt;
4913 	vaf.va = &args;
4914 
4915 	if (RAS_EVENT_ID_IS_VALID(event_id))
4916 		dev_printk(KERN_INFO, adev->dev, "{%llu}%pV", event_id, &vaf);
4917 	else
4918 		dev_printk(KERN_INFO, adev->dev, "%pV", &vaf);
4919 
4920 	va_end(args);
4921 }
4922 
4923 bool amdgpu_ras_is_rma(struct amdgpu_device *adev)
4924 {
4925 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4926 
4927 	if (amdgpu_uniras_enabled(adev))
4928 		return amdgpu_ras_mgr_is_rma(adev);
4929 
4930 	if (!con)
4931 		return false;
4932 
4933 	return con->is_rma;
4934 }
4935 
4936 int amdgpu_ras_add_critical_region(struct amdgpu_device *adev,
4937 			struct amdgpu_bo *bo)
4938 {
4939 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4940 	struct amdgpu_vram_mgr_resource *vres;
4941 	struct ras_critical_region *region;
4942 	struct gpu_buddy_block *block;
4943 	int ret = 0;
4944 
4945 	if (!bo || !bo->tbo.resource)
4946 		return -EINVAL;
4947 
4948 	vres = to_amdgpu_vram_mgr_resource(bo->tbo.resource);
4949 
4950 	mutex_lock(&con->critical_region_lock);
4951 
4952 	/* Check if the bo had been recorded */
4953 	list_for_each_entry(region, &con->critical_region_head, node)
4954 		if (region->bo == bo)
4955 			goto out;
4956 
4957 	/* Record new critical amdgpu bo */
4958 	list_for_each_entry(block, &vres->blocks, link) {
4959 		region = kzalloc_obj(*region);
4960 		if (!region) {
4961 			ret = -ENOMEM;
4962 			goto out;
4963 		}
4964 		region->bo = bo;
4965 		region->start = amdgpu_vram_mgr_block_start(block);
4966 		region->size = amdgpu_vram_mgr_block_size(block);
4967 		list_add_tail(&region->node, &con->critical_region_head);
4968 	}
4969 
4970 out:
4971 	mutex_unlock(&con->critical_region_lock);
4972 
4973 	return ret;
4974 }
4975 
4976 static void amdgpu_ras_critical_region_init(struct amdgpu_device *adev)
4977 {
4978 	amdgpu_ras_add_critical_region(adev, adev->mman.resv_region[AMDGPU_RESV_FW].bo);
4979 }
4980 
4981 static void amdgpu_ras_critical_region_fini(struct amdgpu_device *adev)
4982 {
4983 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4984 	struct ras_critical_region *region, *tmp;
4985 
4986 	mutex_lock(&con->critical_region_lock);
4987 	list_for_each_entry_safe(region, tmp, &con->critical_region_head, node) {
4988 		list_del(&region->node);
4989 		kfree(region);
4990 	}
4991 	mutex_unlock(&con->critical_region_lock);
4992 }
4993 
4994 bool amdgpu_ras_check_critical_address(struct amdgpu_device *adev, uint64_t addr)
4995 {
4996 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
4997 	struct ras_critical_region *region;
4998 	bool ret = false;
4999 
5000 	mutex_lock(&con->critical_region_lock);
5001 	list_for_each_entry(region, &con->critical_region_head, node) {
5002 		if ((region->start <= addr) &&
5003 		    (addr < (region->start + region->size))) {
5004 			ret = true;
5005 			break;
5006 		}
5007 	}
5008 	mutex_unlock(&con->critical_region_lock);
5009 
5010 	return ret;
5011 }
5012 
5013 void amdgpu_ras_pre_reset(struct amdgpu_device *adev,
5014 					  struct list_head *device_list)
5015 {
5016 	struct amdgpu_device *tmp_adev = NULL;
5017 
5018 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5019 		if (amdgpu_uniras_enabled(tmp_adev))
5020 			amdgpu_ras_mgr_pre_reset(tmp_adev);
5021 	}
5022 }
5023 
5024 void amdgpu_ras_post_reset(struct amdgpu_device *adev,
5025 					  struct list_head *device_list)
5026 {
5027 	struct amdgpu_device *tmp_adev = NULL;
5028 
5029 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5030 		if (amdgpu_uniras_enabled(tmp_adev))
5031 			amdgpu_ras_mgr_post_reset(tmp_adev);
5032 	}
5033 }
5034 
5035 int amdgpu_ras_resume_after_reset(struct amdgpu_device *adev)
5036 {
5037 	int r;
5038 
5039 	r = amdgpu_ras_mgr_resume_after_reset(adev);
5040 	if (r)
5041 		return r;
5042 
5043 	return amdgpu_cper_deferred_init(adev);
5044 }
5045 
5046 uint64_t amdgpu_uniras_get_ras_caps(struct amdgpu_device *adev)
5047 {
5048 	struct ras_cmd_get_ras_cap_req req = {0};
5049 	struct ras_cmd_get_ras_cap_rsp rsp = {0};
5050 	union ras_feature feature = {0};
5051 	u32 socket_id = 0;
5052 
5053 	if (amdgpu_ras_mgr_handle_ras_cmd(adev, RAS_CMD__GET_RAS_CAP,
5054 			&req, sizeof(struct ras_cmd_get_ras_cap_req),
5055 			&rsp, sizeof(struct ras_cmd_get_ras_cap_rsp)))
5056 		return 0;
5057 
5058 	if (adev->smuio.funcs && adev->smuio.funcs->get_socket_id)
5059 		socket_id = adev->smuio.funcs->get_socket_id(adev);
5060 
5061 	if (amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(12, 1, 0))
5062 		return AMDGPU_RAS_GET_FEATURES(lower_32_bits(rsp.ras_block_mask)) |
5063 		       (socket_id << AMDGPU_RAS_FEATURES_SOCKETID_SHIFT);
5064 
5065 	feature.block_mask = rsp.ras_block_mask;
5066 	feature.en = !!adev->ras_enabled;
5067 	feature.tag = socket_id;
5068 
5069 	return feature.value;
5070 }
5071