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