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