1 /*
2  * Copyright 2018 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  *
23  */
24 #include <linux/debugfs.h>
25 #include <linux/list.h>
26 #include <linux/module.h>
27 #include <linux/uaccess.h>
28 #include <linux/reboot.h>
29 #include <linux/syscalls.h>
30 #include <linux/pm_runtime.h>
31 
32 #include "amdgpu.h"
33 #include "amdgpu_ras.h"
34 #include "amdgpu_atomfirmware.h"
35 #include "amdgpu_xgmi.h"
36 #include "ivsrcid/nbio/irqsrcs_nbif_7_4.h"
37 #include "atom.h"
38 #ifdef CONFIG_X86_MCE_AMD
39 #include <asm/mce.h>
40 
41 static bool notifier_registered;
42 #endif
43 static const char *RAS_FS_NAME = "ras";
44 
45 const char *ras_error_string[] = {
46 	"none",
47 	"parity",
48 	"single_correctable",
49 	"multi_uncorrectable",
50 	"poison",
51 };
52 
53 const char *ras_block_string[] = {
54 	"umc",
55 	"sdma",
56 	"gfx",
57 	"mmhub",
58 	"athub",
59 	"pcie_bif",
60 	"hdp",
61 	"xgmi_wafl",
62 	"df",
63 	"smn",
64 	"sem",
65 	"mp0",
66 	"mp1",
67 	"fuse",
68 	"mca",
69 };
70 
71 const char *ras_mca_block_string[] = {
72 	"mca_mp0",
73 	"mca_mp1",
74 	"mca_mpio",
75 	"mca_iohc",
76 };
77 
78 const char *get_ras_block_str(struct ras_common_if *ras_block)
79 {
80 	if (!ras_block)
81 		return "NULL";
82 
83 	if (ras_block->block >= AMDGPU_RAS_BLOCK_COUNT)
84 		return "OUT OF RANGE";
85 
86 	if (ras_block->block == AMDGPU_RAS_BLOCK__MCA)
87 		return ras_mca_block_string[ras_block->sub_block_index];
88 
89 	return ras_block_string[ras_block->block];
90 }
91 
92 #define ras_block_str(_BLOCK_) \
93 	(((_BLOCK_) < ARRAY_SIZE(ras_block_string)) ? ras_block_string[_BLOCK_] : "Out Of Range")
94 
95 #define ras_err_str(i) (ras_error_string[ffs(i)])
96 
97 #define RAS_DEFAULT_FLAGS (AMDGPU_RAS_FLAG_INIT_BY_VBIOS)
98 
99 /* inject address is 52 bits */
100 #define	RAS_UMC_INJECT_ADDR_LIMIT	(0x1ULL << 52)
101 
102 /* typical ECC bad page rate is 1 bad page per 100MB VRAM */
103 #define RAS_BAD_PAGE_COVER              (100 * 1024 * 1024ULL)
104 
105 enum amdgpu_ras_retire_page_reservation {
106 	AMDGPU_RAS_RETIRE_PAGE_RESERVED,
107 	AMDGPU_RAS_RETIRE_PAGE_PENDING,
108 	AMDGPU_RAS_RETIRE_PAGE_FAULT,
109 };
110 
111 atomic_t amdgpu_ras_in_intr = ATOMIC_INIT(0);
112 
113 static bool amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
114 				uint64_t addr);
115 static bool amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
116 				uint64_t addr);
117 #ifdef CONFIG_X86_MCE_AMD
118 static void amdgpu_register_bad_pages_mca_notifier(struct amdgpu_device *adev);
119 struct mce_notifier_adev_list {
120 	struct amdgpu_device *devs[MAX_GPU_INSTANCE];
121 	int num_gpu;
122 };
123 static struct mce_notifier_adev_list mce_adev_list;
124 #endif
125 
126 void amdgpu_ras_set_error_query_ready(struct amdgpu_device *adev, bool ready)
127 {
128 	if (adev && amdgpu_ras_get_context(adev))
129 		amdgpu_ras_get_context(adev)->error_query_ready = ready;
130 }
131 
132 static bool amdgpu_ras_get_error_query_ready(struct amdgpu_device *adev)
133 {
134 	if (adev && amdgpu_ras_get_context(adev))
135 		return amdgpu_ras_get_context(adev)->error_query_ready;
136 
137 	return false;
138 }
139 
140 static int amdgpu_reserve_page_direct(struct amdgpu_device *adev, uint64_t address)
141 {
142 	struct ras_err_data err_data = {0, 0, 0, NULL};
143 	struct eeprom_table_record err_rec;
144 
145 	if ((address >= adev->gmc.mc_vram_size) ||
146 	    (address >= RAS_UMC_INJECT_ADDR_LIMIT)) {
147 		dev_warn(adev->dev,
148 		         "RAS WARN: input address 0x%llx is invalid.\n",
149 		         address);
150 		return -EINVAL;
151 	}
152 
153 	if (amdgpu_ras_check_bad_page(adev, address)) {
154 		dev_warn(adev->dev,
155 			 "RAS WARN: 0x%llx has already been marked as bad page!\n",
156 			 address);
157 		return 0;
158 	}
159 
160 	memset(&err_rec, 0x0, sizeof(struct eeprom_table_record));
161 	err_data.err_addr = &err_rec;
162 	amdgpu_umc_fill_error_record(&err_data, address,
163 			(address >> AMDGPU_GPU_PAGE_SHIFT), 0, 0);
164 
165 	if (amdgpu_bad_page_threshold != 0) {
166 		amdgpu_ras_add_bad_pages(adev, err_data.err_addr,
167 					 err_data.err_addr_cnt);
168 		amdgpu_ras_save_bad_pages(adev);
169 	}
170 
171 	dev_warn(adev->dev, "WARNING: THIS IS ONLY FOR TEST PURPOSES AND WILL CORRUPT RAS EEPROM\n");
172 	dev_warn(adev->dev, "Clear EEPROM:\n");
173 	dev_warn(adev->dev, "    echo 1 > /sys/kernel/debug/dri/0/ras/ras_eeprom_reset\n");
174 
175 	return 0;
176 }
177 
178 static ssize_t amdgpu_ras_debugfs_read(struct file *f, char __user *buf,
179 					size_t size, loff_t *pos)
180 {
181 	struct ras_manager *obj = (struct ras_manager *)file_inode(f)->i_private;
182 	struct ras_query_if info = {
183 		.head = obj->head,
184 	};
185 	ssize_t s;
186 	char val[128];
187 
188 	if (amdgpu_ras_query_error_status(obj->adev, &info))
189 		return -EINVAL;
190 
191 	s = snprintf(val, sizeof(val), "%s: %lu\n%s: %lu\n",
192 			"ue", info.ue_count,
193 			"ce", info.ce_count);
194 	if (*pos >= s)
195 		return 0;
196 
197 	s -= *pos;
198 	s = min_t(u64, s, size);
199 
200 
201 	if (copy_to_user(buf, &val[*pos], s))
202 		return -EINVAL;
203 
204 	*pos += s;
205 
206 	return s;
207 }
208 
209 static const struct file_operations amdgpu_ras_debugfs_ops = {
210 	.owner = THIS_MODULE,
211 	.read = amdgpu_ras_debugfs_read,
212 	.write = NULL,
213 	.llseek = default_llseek
214 };
215 
216 static int amdgpu_ras_find_block_id_by_name(const char *name, int *block_id)
217 {
218 	int i;
219 
220 	for (i = 0; i < ARRAY_SIZE(ras_block_string); i++) {
221 		*block_id = i;
222 		if (strcmp(name, ras_block_string[i]) == 0)
223 			return 0;
224 	}
225 	return -EINVAL;
226 }
227 
228 static int amdgpu_ras_debugfs_ctrl_parse_data(struct file *f,
229 		const char __user *buf, size_t size,
230 		loff_t *pos, struct ras_debug_if *data)
231 {
232 	ssize_t s = min_t(u64, 64, size);
233 	char str[65];
234 	char block_name[33];
235 	char err[9] = "ue";
236 	int op = -1;
237 	int block_id;
238 	uint32_t sub_block;
239 	u64 address, value;
240 
241 	if (*pos)
242 		return -EINVAL;
243 	*pos = size;
244 
245 	memset(str, 0, sizeof(str));
246 	memset(data, 0, sizeof(*data));
247 
248 	if (copy_from_user(str, buf, s))
249 		return -EINVAL;
250 
251 	if (sscanf(str, "disable %32s", block_name) == 1)
252 		op = 0;
253 	else if (sscanf(str, "enable %32s %8s", block_name, err) == 2)
254 		op = 1;
255 	else if (sscanf(str, "inject %32s %8s", block_name, err) == 2)
256 		op = 2;
257 	else if (strstr(str, "retire_page") != NULL)
258 		op = 3;
259 	else if (str[0] && str[1] && str[2] && str[3])
260 		/* ascii string, but commands are not matched. */
261 		return -EINVAL;
262 
263 	if (op != -1) {
264 		if (op == 3) {
265 			if (sscanf(str, "%*s 0x%llx", &address) != 1 &&
266 			    sscanf(str, "%*s %llu", &address) != 1)
267 				return -EINVAL;
268 
269 			data->op = op;
270 			data->inject.address = address;
271 
272 			return 0;
273 		}
274 
275 		if (amdgpu_ras_find_block_id_by_name(block_name, &block_id))
276 			return -EINVAL;
277 
278 		data->head.block = block_id;
279 		/* only ue and ce errors are supported */
280 		if (!memcmp("ue", err, 2))
281 			data->head.type = AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE;
282 		else if (!memcmp("ce", err, 2))
283 			data->head.type = AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE;
284 		else
285 			return -EINVAL;
286 
287 		data->op = op;
288 
289 		if (op == 2) {
290 			if (sscanf(str, "%*s %*s %*s 0x%x 0x%llx 0x%llx",
291 				   &sub_block, &address, &value) != 3 &&
292 			    sscanf(str, "%*s %*s %*s %u %llu %llu",
293 				   &sub_block, &address, &value) != 3)
294 				return -EINVAL;
295 			data->head.sub_block_index = sub_block;
296 			data->inject.address = address;
297 			data->inject.value = value;
298 		}
299 	} else {
300 		if (size < sizeof(*data))
301 			return -EINVAL;
302 
303 		if (copy_from_user(data, buf, sizeof(*data)))
304 			return -EINVAL;
305 	}
306 
307 	return 0;
308 }
309 
310 /**
311  * DOC: AMDGPU RAS debugfs control interface
312  *
313  * The control interface accepts struct ras_debug_if which has two members.
314  *
315  * First member: ras_debug_if::head or ras_debug_if::inject.
316  *
317  * head is used to indicate which IP block will be under control.
318  *
319  * head has four members, they are block, type, sub_block_index, name.
320  * block: which IP will be under control.
321  * type: what kind of error will be enabled/disabled/injected.
322  * sub_block_index: some IPs have subcomponets. say, GFX, sDMA.
323  * name: the name of IP.
324  *
325  * inject has two more members than head, they are address, value.
326  * As their names indicate, inject operation will write the
327  * value to the address.
328  *
329  * The second member: struct ras_debug_if::op.
330  * It has three kinds of operations.
331  *
332  * - 0: disable RAS on the block. Take ::head as its data.
333  * - 1: enable RAS on the block. Take ::head as its data.
334  * - 2: inject errors on the block. Take ::inject as its data.
335  *
336  * How to use the interface?
337  *
338  * In a program
339  *
340  * Copy the struct ras_debug_if in your code and initialize it.
341  * Write the struct to the control interface.
342  *
343  * From shell
344  *
345  * .. code-block:: bash
346  *
347  *	echo "disable <block>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
348  *	echo "enable  <block> <error>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
349  *	echo "inject  <block> <error> <sub-block> <address> <value> > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
350  *
351  * Where N, is the card which you want to affect.
352  *
353  * "disable" requires only the block.
354  * "enable" requires the block and error type.
355  * "inject" requires the block, error type, address, and value.
356  *
357  * The block is one of: umc, sdma, gfx, etc.
358  *	see ras_block_string[] for details
359  *
360  * The error type is one of: ue, ce, where,
361  *	ue is multi-uncorrectable
362  *	ce is single-correctable
363  *
364  * The sub-block is a the sub-block index, pass 0 if there is no sub-block.
365  * The address and value are hexadecimal numbers, leading 0x is optional.
366  *
367  * For instance,
368  *
369  * .. code-block:: bash
370  *
371  *	echo inject umc ue 0x0 0x0 0x0 > /sys/kernel/debug/dri/0/ras/ras_ctrl
372  *	echo inject umc ce 0 0 0 > /sys/kernel/debug/dri/0/ras/ras_ctrl
373  *	echo disable umc > /sys/kernel/debug/dri/0/ras/ras_ctrl
374  *
375  * How to check the result of the operation?
376  *
377  * To check disable/enable, see "ras" features at,
378  * /sys/class/drm/card[0/1/2...]/device/ras/features
379  *
380  * To check inject, see the corresponding error count at,
381  * /sys/class/drm/card[0/1/2...]/device/ras/[gfx|sdma|umc|...]_err_count
382  *
383  * .. note::
384  *	Operations are only allowed on blocks which are supported.
385  *	Check the "ras" mask at /sys/module/amdgpu/parameters/ras_mask
386  *	to see which blocks support RAS on a particular asic.
387  *
388  */
389 static ssize_t amdgpu_ras_debugfs_ctrl_write(struct file *f,
390 					     const char __user *buf,
391 					     size_t size, loff_t *pos)
392 {
393 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
394 	struct ras_debug_if data;
395 	int ret = 0;
396 
397 	if (!amdgpu_ras_get_error_query_ready(adev)) {
398 		dev_warn(adev->dev, "RAS WARN: error injection "
399 				"currently inaccessible\n");
400 		return size;
401 	}
402 
403 	ret = amdgpu_ras_debugfs_ctrl_parse_data(f, buf, size, pos, &data);
404 	if (ret)
405 		return ret;
406 
407 	if (data.op == 3) {
408 		ret = amdgpu_reserve_page_direct(adev, data.inject.address);
409 		if (!ret)
410 			return size;
411 		else
412 			return ret;
413 	}
414 
415 	if (!amdgpu_ras_is_supported(adev, data.head.block))
416 		return -EINVAL;
417 
418 	switch (data.op) {
419 	case 0:
420 		ret = amdgpu_ras_feature_enable(adev, &data.head, 0);
421 		break;
422 	case 1:
423 		ret = amdgpu_ras_feature_enable(adev, &data.head, 1);
424 		break;
425 	case 2:
426 		if ((data.inject.address >= adev->gmc.mc_vram_size) ||
427 		    (data.inject.address >= RAS_UMC_INJECT_ADDR_LIMIT)) {
428 			dev_warn(adev->dev, "RAS WARN: input address "
429 					"0x%llx is invalid.",
430 					data.inject.address);
431 			ret = -EINVAL;
432 			break;
433 		}
434 
435 		/* umc ce/ue error injection for a bad page is not allowed */
436 		if ((data.head.block == AMDGPU_RAS_BLOCK__UMC) &&
437 		    amdgpu_ras_check_bad_page(adev, data.inject.address)) {
438 			dev_warn(adev->dev, "RAS WARN: inject: 0x%llx has "
439 				 "already been marked as bad!\n",
440 				 data.inject.address);
441 			break;
442 		}
443 
444 		/* data.inject.address is offset instead of absolute gpu address */
445 		ret = amdgpu_ras_error_inject(adev, &data.inject);
446 		break;
447 	default:
448 		ret = -EINVAL;
449 		break;
450 	}
451 
452 	if (ret)
453 		return ret;
454 
455 	return size;
456 }
457 
458 /**
459  * DOC: AMDGPU RAS debugfs EEPROM table reset interface
460  *
461  * Some boards contain an EEPROM which is used to persistently store a list of
462  * bad pages which experiences ECC errors in vram.  This interface provides
463  * a way to reset the EEPROM, e.g., after testing error injection.
464  *
465  * Usage:
466  *
467  * .. code-block:: bash
468  *
469  *	echo 1 > ../ras/ras_eeprom_reset
470  *
471  * will reset EEPROM table to 0 entries.
472  *
473  */
474 static ssize_t amdgpu_ras_debugfs_eeprom_write(struct file *f,
475 					       const char __user *buf,
476 					       size_t size, loff_t *pos)
477 {
478 	struct amdgpu_device *adev =
479 		(struct amdgpu_device *)file_inode(f)->i_private;
480 	int ret;
481 
482 	ret = amdgpu_ras_eeprom_reset_table(
483 		&(amdgpu_ras_get_context(adev)->eeprom_control));
484 
485 	if (!ret) {
486 		/* Something was written to EEPROM.
487 		 */
488 		amdgpu_ras_get_context(adev)->flags = RAS_DEFAULT_FLAGS;
489 		return size;
490 	} else {
491 		return ret;
492 	}
493 }
494 
495 static const struct file_operations amdgpu_ras_debugfs_ctrl_ops = {
496 	.owner = THIS_MODULE,
497 	.read = NULL,
498 	.write = amdgpu_ras_debugfs_ctrl_write,
499 	.llseek = default_llseek
500 };
501 
502 static const struct file_operations amdgpu_ras_debugfs_eeprom_ops = {
503 	.owner = THIS_MODULE,
504 	.read = NULL,
505 	.write = amdgpu_ras_debugfs_eeprom_write,
506 	.llseek = default_llseek
507 };
508 
509 /**
510  * DOC: AMDGPU RAS sysfs Error Count Interface
511  *
512  * It allows the user to read the error count for each IP block on the gpu through
513  * /sys/class/drm/card[0/1/2...]/device/ras/[gfx/sdma/...]_err_count
514  *
515  * It outputs the multiple lines which report the uncorrected (ue) and corrected
516  * (ce) error counts.
517  *
518  * The format of one line is below,
519  *
520  * [ce|ue]: count
521  *
522  * Example:
523  *
524  * .. code-block:: bash
525  *
526  *	ue: 0
527  *	ce: 1
528  *
529  */
530 static ssize_t amdgpu_ras_sysfs_read(struct device *dev,
531 		struct device_attribute *attr, char *buf)
532 {
533 	struct ras_manager *obj = container_of(attr, struct ras_manager, sysfs_attr);
534 	struct ras_query_if info = {
535 		.head = obj->head,
536 	};
537 
538 	if (!amdgpu_ras_get_error_query_ready(obj->adev))
539 		return sysfs_emit(buf, "Query currently inaccessible\n");
540 
541 	if (amdgpu_ras_query_error_status(obj->adev, &info))
542 		return -EINVAL;
543 
544 	if (obj->adev->asic_type == CHIP_ALDEBARAN) {
545 		if (amdgpu_ras_reset_error_status(obj->adev, info.head.block))
546 			DRM_WARN("Failed to reset error counter and error status");
547 	}
548 
549 	return sysfs_emit(buf, "%s: %lu\n%s: %lu\n", "ue", info.ue_count,
550 			  "ce", info.ce_count);
551 }
552 
553 /* obj begin */
554 
555 #define get_obj(obj) do { (obj)->use++; } while (0)
556 #define alive_obj(obj) ((obj)->use)
557 
558 static inline void put_obj(struct ras_manager *obj)
559 {
560 	if (obj && (--obj->use == 0))
561 		list_del(&obj->node);
562 	if (obj && (obj->use < 0))
563 		DRM_ERROR("RAS ERROR: Unbalance obj(%s) use\n", get_ras_block_str(&obj->head));
564 }
565 
566 /* make one obj and return it. */
567 static struct ras_manager *amdgpu_ras_create_obj(struct amdgpu_device *adev,
568 		struct ras_common_if *head)
569 {
570 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
571 	struct ras_manager *obj;
572 
573 	if (!adev->ras_enabled || !con)
574 		return NULL;
575 
576 	if (head->block >= AMDGPU_RAS_BLOCK_COUNT)
577 		return NULL;
578 
579 	if (head->block == AMDGPU_RAS_BLOCK__MCA) {
580 		if (head->sub_block_index >= AMDGPU_RAS_MCA_BLOCK__LAST)
581 			return NULL;
582 
583 		obj = &con->objs[AMDGPU_RAS_BLOCK__LAST + head->sub_block_index];
584 	} else
585 		obj = &con->objs[head->block];
586 
587 	/* already exist. return obj? */
588 	if (alive_obj(obj))
589 		return NULL;
590 
591 	obj->head = *head;
592 	obj->adev = adev;
593 	list_add(&obj->node, &con->head);
594 	get_obj(obj);
595 
596 	return obj;
597 }
598 
599 /* return an obj equal to head, or the first when head is NULL */
600 struct ras_manager *amdgpu_ras_find_obj(struct amdgpu_device *adev,
601 		struct ras_common_if *head)
602 {
603 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
604 	struct ras_manager *obj;
605 	int i;
606 
607 	if (!adev->ras_enabled || !con)
608 		return NULL;
609 
610 	if (head) {
611 		if (head->block >= AMDGPU_RAS_BLOCK_COUNT)
612 			return NULL;
613 
614 		if (head->block == AMDGPU_RAS_BLOCK__MCA) {
615 			if (head->sub_block_index >= AMDGPU_RAS_MCA_BLOCK__LAST)
616 				return NULL;
617 
618 			obj = &con->objs[AMDGPU_RAS_BLOCK__LAST + head->sub_block_index];
619 		} else
620 			obj = &con->objs[head->block];
621 
622 		if (alive_obj(obj))
623 			return obj;
624 	} else {
625 		for (i = 0; i < AMDGPU_RAS_BLOCK_COUNT + AMDGPU_RAS_MCA_BLOCK_COUNT; i++) {
626 			obj = &con->objs[i];
627 			if (alive_obj(obj))
628 				return obj;
629 		}
630 	}
631 
632 	return NULL;
633 }
634 /* obj end */
635 
636 /* feature ctl begin */
637 static int amdgpu_ras_is_feature_allowed(struct amdgpu_device *adev,
638 					 struct ras_common_if *head)
639 {
640 	return adev->ras_hw_enabled & BIT(head->block);
641 }
642 
643 static int amdgpu_ras_is_feature_enabled(struct amdgpu_device *adev,
644 		struct ras_common_if *head)
645 {
646 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
647 
648 	return con->features & BIT(head->block);
649 }
650 
651 /*
652  * if obj is not created, then create one.
653  * set feature enable flag.
654  */
655 static int __amdgpu_ras_feature_enable(struct amdgpu_device *adev,
656 		struct ras_common_if *head, int enable)
657 {
658 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
659 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
660 
661 	/* If hardware does not support ras, then do not create obj.
662 	 * But if hardware support ras, we can create the obj.
663 	 * Ras framework checks con->hw_supported to see if it need do
664 	 * corresponding initialization.
665 	 * IP checks con->support to see if it need disable ras.
666 	 */
667 	if (!amdgpu_ras_is_feature_allowed(adev, head))
668 		return 0;
669 
670 	if (enable) {
671 		if (!obj) {
672 			obj = amdgpu_ras_create_obj(adev, head);
673 			if (!obj)
674 				return -EINVAL;
675 		} else {
676 			/* In case we create obj somewhere else */
677 			get_obj(obj);
678 		}
679 		con->features |= BIT(head->block);
680 	} else {
681 		if (obj && amdgpu_ras_is_feature_enabled(adev, head)) {
682 			con->features &= ~BIT(head->block);
683 			put_obj(obj);
684 		}
685 	}
686 
687 	return 0;
688 }
689 
690 /* wrapper of psp_ras_enable_features */
691 int amdgpu_ras_feature_enable(struct amdgpu_device *adev,
692 		struct ras_common_if *head, bool enable)
693 {
694 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
695 	union ta_ras_cmd_input *info;
696 	int ret;
697 
698 	if (!con)
699 		return -EINVAL;
700 
701 	info = kzalloc(sizeof(union ta_ras_cmd_input), GFP_KERNEL);
702 	if (!info)
703 		return -ENOMEM;
704 
705 	if (!enable) {
706 		info->disable_features = (struct ta_ras_disable_features_input) {
707 			.block_id =  amdgpu_ras_block_to_ta(head->block),
708 			.error_type = amdgpu_ras_error_to_ta(head->type),
709 		};
710 	} else {
711 		info->enable_features = (struct ta_ras_enable_features_input) {
712 			.block_id =  amdgpu_ras_block_to_ta(head->block),
713 			.error_type = amdgpu_ras_error_to_ta(head->type),
714 		};
715 	}
716 
717 	/* Do not enable if it is not allowed. */
718 	WARN_ON(enable && !amdgpu_ras_is_feature_allowed(adev, head));
719 
720 	if (!amdgpu_ras_intr_triggered()) {
721 		ret = psp_ras_enable_features(&adev->psp, info, enable);
722 		if (ret) {
723 			dev_err(adev->dev, "ras %s %s failed poison:%d ret:%d\n",
724 				enable ? "enable":"disable",
725 				get_ras_block_str(head),
726 				amdgpu_ras_is_poison_mode_supported(adev), ret);
727 			goto out;
728 		}
729 	}
730 
731 	/* setup the obj */
732 	__amdgpu_ras_feature_enable(adev, head, enable);
733 	ret = 0;
734 out:
735 	kfree(info);
736 	return ret;
737 }
738 
739 /* Only used in device probe stage and called only once. */
740 int amdgpu_ras_feature_enable_on_boot(struct amdgpu_device *adev,
741 		struct ras_common_if *head, bool enable)
742 {
743 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
744 	int ret;
745 
746 	if (!con)
747 		return -EINVAL;
748 
749 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
750 		if (enable) {
751 			/* There is no harm to issue a ras TA cmd regardless of
752 			 * the currecnt ras state.
753 			 * If current state == target state, it will do nothing
754 			 * But sometimes it requests driver to reset and repost
755 			 * with error code -EAGAIN.
756 			 */
757 			ret = amdgpu_ras_feature_enable(adev, head, 1);
758 			/* With old ras TA, we might fail to enable ras.
759 			 * Log it and just setup the object.
760 			 * TODO need remove this WA in the future.
761 			 */
762 			if (ret == -EINVAL) {
763 				ret = __amdgpu_ras_feature_enable(adev, head, 1);
764 				if (!ret)
765 					dev_info(adev->dev,
766 						"RAS INFO: %s setup object\n",
767 						get_ras_block_str(head));
768 			}
769 		} else {
770 			/* setup the object then issue a ras TA disable cmd.*/
771 			ret = __amdgpu_ras_feature_enable(adev, head, 1);
772 			if (ret)
773 				return ret;
774 
775 			/* gfx block ras dsiable cmd must send to ras-ta */
776 			if (head->block == AMDGPU_RAS_BLOCK__GFX)
777 				con->features |= BIT(head->block);
778 
779 			ret = amdgpu_ras_feature_enable(adev, head, 0);
780 
781 			/* clean gfx block ras features flag */
782 			if (adev->ras_enabled && head->block == AMDGPU_RAS_BLOCK__GFX)
783 				con->features &= ~BIT(head->block);
784 		}
785 	} else
786 		ret = amdgpu_ras_feature_enable(adev, head, enable);
787 
788 	return ret;
789 }
790 
791 static int amdgpu_ras_disable_all_features(struct amdgpu_device *adev,
792 		bool bypass)
793 {
794 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
795 	struct ras_manager *obj, *tmp;
796 
797 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
798 		/* bypass psp.
799 		 * aka just release the obj and corresponding flags
800 		 */
801 		if (bypass) {
802 			if (__amdgpu_ras_feature_enable(adev, &obj->head, 0))
803 				break;
804 		} else {
805 			if (amdgpu_ras_feature_enable(adev, &obj->head, 0))
806 				break;
807 		}
808 	}
809 
810 	return con->features;
811 }
812 
813 static int amdgpu_ras_enable_all_features(struct amdgpu_device *adev,
814 		bool bypass)
815 {
816 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
817 	int i;
818 	const enum amdgpu_ras_error_type default_ras_type = AMDGPU_RAS_ERROR__NONE;
819 
820 	for (i = 0; i < AMDGPU_RAS_BLOCK_COUNT; i++) {
821 		struct ras_common_if head = {
822 			.block = i,
823 			.type = default_ras_type,
824 			.sub_block_index = 0,
825 		};
826 
827 		if (i == AMDGPU_RAS_BLOCK__MCA)
828 			continue;
829 
830 		if (bypass) {
831 			/*
832 			 * bypass psp. vbios enable ras for us.
833 			 * so just create the obj
834 			 */
835 			if (__amdgpu_ras_feature_enable(adev, &head, 1))
836 				break;
837 		} else {
838 			if (amdgpu_ras_feature_enable(adev, &head, 1))
839 				break;
840 		}
841 	}
842 
843 	for (i = 0; i < AMDGPU_RAS_MCA_BLOCK_COUNT; i++) {
844 		struct ras_common_if head = {
845 			.block = AMDGPU_RAS_BLOCK__MCA,
846 			.type = default_ras_type,
847 			.sub_block_index = i,
848 		};
849 
850 		if (bypass) {
851 			/*
852 			 * bypass psp. vbios enable ras for us.
853 			 * so just create the obj
854 			 */
855 			if (__amdgpu_ras_feature_enable(adev, &head, 1))
856 				break;
857 		} else {
858 			if (amdgpu_ras_feature_enable(adev, &head, 1))
859 				break;
860 		}
861 	}
862 
863 	return con->features;
864 }
865 /* feature ctl end */
866 
867 static int amdgpu_ras_block_match_default(struct amdgpu_ras_block_object *block_obj,
868 		enum amdgpu_ras_block block)
869 {
870 	if (!block_obj)
871 		return -EINVAL;
872 
873 	if (block_obj->block == block)
874 		return 0;
875 
876 	return -EINVAL;
877 }
878 
879 static struct amdgpu_ras_block_object *amdgpu_ras_get_ras_block(struct amdgpu_device *adev,
880 					enum amdgpu_ras_block block, uint32_t sub_block_index)
881 {
882 	struct amdgpu_ras_block_object *obj, *tmp;
883 
884 	if (block >= AMDGPU_RAS_BLOCK__LAST)
885 		return NULL;
886 
887 	if (!amdgpu_ras_is_supported(adev, block))
888 		return NULL;
889 
890 	list_for_each_entry_safe(obj, tmp, &adev->ras_list, node) {
891 		if (obj->ras_block_match) {
892 			if (obj->ras_block_match(obj, block, sub_block_index) == 0)
893 				return obj;
894 		} else {
895 			if (amdgpu_ras_block_match_default(obj, block) == 0)
896 				return obj;
897 		}
898 	}
899 
900 	return NULL;
901 }
902 
903 static void amdgpu_ras_get_ecc_info(struct amdgpu_device *adev, struct ras_err_data *err_data)
904 {
905 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
906 	int ret = 0;
907 
908 	/*
909 	 * choosing right query method according to
910 	 * whether smu support query error information
911 	 */
912 	ret = amdgpu_dpm_get_ecc_info(adev, (void *)&(ras->umc_ecc));
913 	if (ret == -EOPNOTSUPP) {
914 		if (adev->umc.ras && adev->umc.ras->ras_block.hw_ops &&
915 			adev->umc.ras->ras_block.hw_ops->query_ras_error_count)
916 			adev->umc.ras->ras_block.hw_ops->query_ras_error_count(adev, err_data);
917 
918 		/* umc query_ras_error_address is also responsible for clearing
919 		 * error status
920 		 */
921 		if (adev->umc.ras && adev->umc.ras->ras_block.hw_ops &&
922 		    adev->umc.ras->ras_block.hw_ops->query_ras_error_address)
923 			adev->umc.ras->ras_block.hw_ops->query_ras_error_address(adev, err_data);
924 	} else if (!ret) {
925 		if (adev->umc.ras &&
926 			adev->umc.ras->ecc_info_query_ras_error_count)
927 			adev->umc.ras->ecc_info_query_ras_error_count(adev, err_data);
928 
929 		if (adev->umc.ras &&
930 			adev->umc.ras->ecc_info_query_ras_error_address)
931 			adev->umc.ras->ecc_info_query_ras_error_address(adev, err_data);
932 	}
933 }
934 
935 /* query/inject/cure begin */
936 int amdgpu_ras_query_error_status(struct amdgpu_device *adev,
937 				  struct ras_query_if *info)
938 {
939 	struct amdgpu_ras_block_object *block_obj = NULL;
940 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
941 	struct ras_err_data err_data = {0, 0, 0, NULL};
942 
943 	if (!obj)
944 		return -EINVAL;
945 
946 	if (info->head.block == AMDGPU_RAS_BLOCK__UMC) {
947 		amdgpu_ras_get_ecc_info(adev, &err_data);
948 	} else {
949 		block_obj = amdgpu_ras_get_ras_block(adev, info->head.block, 0);
950 		if (!block_obj || !block_obj->hw_ops)   {
951 			dev_info(adev->dev, "%s doesn't config ras function.\n",
952 					get_ras_block_str(&info->head));
953 			return -EINVAL;
954 		}
955 
956 		if (block_obj->hw_ops->query_ras_error_count)
957 			block_obj->hw_ops->query_ras_error_count(adev, &err_data);
958 
959 		if ((info->head.block == AMDGPU_RAS_BLOCK__SDMA) ||
960 		    (info->head.block == AMDGPU_RAS_BLOCK__GFX) ||
961 		    (info->head.block == AMDGPU_RAS_BLOCK__MMHUB)) {
962 				if (block_obj->hw_ops->query_ras_error_status)
963 					block_obj->hw_ops->query_ras_error_status(adev);
964 			}
965 	}
966 
967 	obj->err_data.ue_count += err_data.ue_count;
968 	obj->err_data.ce_count += err_data.ce_count;
969 
970 	info->ue_count = obj->err_data.ue_count;
971 	info->ce_count = obj->err_data.ce_count;
972 
973 	if (err_data.ce_count) {
974 		if (adev->smuio.funcs &&
975 		    adev->smuio.funcs->get_socket_id &&
976 		    adev->smuio.funcs->get_die_id) {
977 			dev_info(adev->dev, "socket: %d, die: %d "
978 					"%ld correctable hardware errors "
979 					"detected in %s block, no user "
980 					"action is needed.\n",
981 					adev->smuio.funcs->get_socket_id(adev),
982 					adev->smuio.funcs->get_die_id(adev),
983 					obj->err_data.ce_count,
984 					get_ras_block_str(&info->head));
985 		} else {
986 			dev_info(adev->dev, "%ld correctable hardware errors "
987 					"detected in %s block, no user "
988 					"action is needed.\n",
989 					obj->err_data.ce_count,
990 					get_ras_block_str(&info->head));
991 		}
992 	}
993 	if (err_data.ue_count) {
994 		if (adev->smuio.funcs &&
995 		    adev->smuio.funcs->get_socket_id &&
996 		    adev->smuio.funcs->get_die_id) {
997 			dev_info(adev->dev, "socket: %d, die: %d "
998 					"%ld uncorrectable hardware errors "
999 					"detected in %s block\n",
1000 					adev->smuio.funcs->get_socket_id(adev),
1001 					adev->smuio.funcs->get_die_id(adev),
1002 					obj->err_data.ue_count,
1003 					get_ras_block_str(&info->head));
1004 		} else {
1005 			dev_info(adev->dev, "%ld uncorrectable hardware errors "
1006 					"detected in %s block\n",
1007 					obj->err_data.ue_count,
1008 					get_ras_block_str(&info->head));
1009 		}
1010 	}
1011 
1012 	if (!amdgpu_persistent_edc_harvesting_supported(adev))
1013 		amdgpu_ras_reset_error_status(adev, info->head.block);
1014 
1015 	return 0;
1016 }
1017 
1018 int amdgpu_ras_reset_error_status(struct amdgpu_device *adev,
1019 		enum amdgpu_ras_block block)
1020 {
1021 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev, block, 0);
1022 
1023 	if (!amdgpu_ras_is_supported(adev, block))
1024 		return -EINVAL;
1025 
1026 	if (!block_obj || !block_obj->hw_ops)   {
1027 		dev_info(adev->dev, "%s doesn't config ras function.\n",
1028 				ras_block_str(block));
1029 		return -EINVAL;
1030 	}
1031 
1032 	if (block_obj->hw_ops->reset_ras_error_count)
1033 		block_obj->hw_ops->reset_ras_error_count(adev);
1034 
1035 	if ((block == AMDGPU_RAS_BLOCK__GFX) ||
1036 	    (block == AMDGPU_RAS_BLOCK__MMHUB)) {
1037 		if (block_obj->hw_ops->reset_ras_error_status)
1038 			block_obj->hw_ops->reset_ras_error_status(adev);
1039 	}
1040 
1041 	return 0;
1042 }
1043 
1044 /* wrapper of psp_ras_trigger_error */
1045 int amdgpu_ras_error_inject(struct amdgpu_device *adev,
1046 		struct ras_inject_if *info)
1047 {
1048 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1049 	struct ta_ras_trigger_error_input block_info = {
1050 		.block_id =  amdgpu_ras_block_to_ta(info->head.block),
1051 		.inject_error_type = amdgpu_ras_error_to_ta(info->head.type),
1052 		.sub_block_index = info->head.sub_block_index,
1053 		.address = info->address,
1054 		.value = info->value,
1055 	};
1056 	int ret = -EINVAL;
1057 	struct amdgpu_ras_block_object *block_obj = amdgpu_ras_get_ras_block(adev,
1058 							info->head.block,
1059 							info->head.sub_block_index);
1060 
1061 	if (!obj)
1062 		return -EINVAL;
1063 
1064 	if (!block_obj || !block_obj->hw_ops)	{
1065 		dev_info(adev->dev, "%s doesn't config ras function.\n",
1066 					get_ras_block_str(&info->head));
1067 		return -EINVAL;
1068 	}
1069 
1070 	/* Calculate XGMI relative offset */
1071 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
1072 		block_info.address =
1073 			amdgpu_xgmi_get_relative_phy_addr(adev,
1074 							  block_info.address);
1075 	}
1076 
1077 	if (info->head.block == AMDGPU_RAS_BLOCK__GFX) {
1078 		if (block_obj->hw_ops->ras_error_inject)
1079 			ret = block_obj->hw_ops->ras_error_inject(adev, info);
1080 	} else {
1081 		/* If defined special ras_error_inject(e.g: xgmi), implement special ras_error_inject */
1082 		if (block_obj->hw_ops->ras_error_inject)
1083 			ret = block_obj->hw_ops->ras_error_inject(adev, &block_info);
1084 		else  /*If not defined .ras_error_inject, use default ras_error_inject*/
1085 			ret = psp_ras_trigger_error(&adev->psp, &block_info);
1086 	}
1087 
1088 	if (ret)
1089 		dev_err(adev->dev, "ras inject %s failed %d\n",
1090 			get_ras_block_str(&info->head), ret);
1091 
1092 	return ret;
1093 }
1094 
1095 /**
1096  * amdgpu_ras_query_error_count -- Get error counts of all IPs
1097  * @adev: pointer to AMD GPU device
1098  * @ce_count: pointer to an integer to be set to the count of correctible errors.
1099  * @ue_count: pointer to an integer to be set to the count of uncorrectible
1100  * errors.
1101  *
1102  * If set, @ce_count or @ue_count, count and return the corresponding
1103  * error counts in those integer pointers. Return 0 if the device
1104  * supports RAS. Return -EOPNOTSUPP if the device doesn't support RAS.
1105  */
1106 int amdgpu_ras_query_error_count(struct amdgpu_device *adev,
1107 				 unsigned long *ce_count,
1108 				 unsigned long *ue_count)
1109 {
1110 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1111 	struct ras_manager *obj;
1112 	unsigned long ce, ue;
1113 
1114 	if (!adev->ras_enabled || !con)
1115 		return -EOPNOTSUPP;
1116 
1117 	/* Don't count since no reporting.
1118 	 */
1119 	if (!ce_count && !ue_count)
1120 		return 0;
1121 
1122 	ce = 0;
1123 	ue = 0;
1124 	list_for_each_entry(obj, &con->head, node) {
1125 		struct ras_query_if info = {
1126 			.head = obj->head,
1127 		};
1128 		int res;
1129 
1130 		res = amdgpu_ras_query_error_status(adev, &info);
1131 		if (res)
1132 			return res;
1133 
1134 		ce += info.ce_count;
1135 		ue += info.ue_count;
1136 	}
1137 
1138 	if (ce_count)
1139 		*ce_count = ce;
1140 
1141 	if (ue_count)
1142 		*ue_count = ue;
1143 
1144 	return 0;
1145 }
1146 /* query/inject/cure end */
1147 
1148 
1149 /* sysfs begin */
1150 
1151 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
1152 		struct ras_badpage **bps, unsigned int *count);
1153 
1154 static char *amdgpu_ras_badpage_flags_str(unsigned int flags)
1155 {
1156 	switch (flags) {
1157 	case AMDGPU_RAS_RETIRE_PAGE_RESERVED:
1158 		return "R";
1159 	case AMDGPU_RAS_RETIRE_PAGE_PENDING:
1160 		return "P";
1161 	case AMDGPU_RAS_RETIRE_PAGE_FAULT:
1162 	default:
1163 		return "F";
1164 	}
1165 }
1166 
1167 /**
1168  * DOC: AMDGPU RAS sysfs gpu_vram_bad_pages Interface
1169  *
1170  * It allows user to read the bad pages of vram on the gpu through
1171  * /sys/class/drm/card[0/1/2...]/device/ras/gpu_vram_bad_pages
1172  *
1173  * It outputs multiple lines, and each line stands for one gpu page.
1174  *
1175  * The format of one line is below,
1176  * gpu pfn : gpu page size : flags
1177  *
1178  * gpu pfn and gpu page size are printed in hex format.
1179  * flags can be one of below character,
1180  *
1181  * R: reserved, this gpu page is reserved and not able to use.
1182  *
1183  * P: pending for reserve, this gpu page is marked as bad, will be reserved
1184  * in next window of page_reserve.
1185  *
1186  * F: unable to reserve. this gpu page can't be reserved due to some reasons.
1187  *
1188  * Examples:
1189  *
1190  * .. code-block:: bash
1191  *
1192  *	0x00000001 : 0x00001000 : R
1193  *	0x00000002 : 0x00001000 : P
1194  *
1195  */
1196 
1197 static ssize_t amdgpu_ras_sysfs_badpages_read(struct file *f,
1198 		struct kobject *kobj, struct bin_attribute *attr,
1199 		char *buf, loff_t ppos, size_t count)
1200 {
1201 	struct amdgpu_ras *con =
1202 		container_of(attr, struct amdgpu_ras, badpages_attr);
1203 	struct amdgpu_device *adev = con->adev;
1204 	const unsigned int element_size =
1205 		sizeof("0xabcdabcd : 0x12345678 : R\n") - 1;
1206 	unsigned int start = div64_ul(ppos + element_size - 1, element_size);
1207 	unsigned int end = div64_ul(ppos + count - 1, element_size);
1208 	ssize_t s = 0;
1209 	struct ras_badpage *bps = NULL;
1210 	unsigned int bps_count = 0;
1211 
1212 	memset(buf, 0, count);
1213 
1214 	if (amdgpu_ras_badpages_read(adev, &bps, &bps_count))
1215 		return 0;
1216 
1217 	for (; start < end && start < bps_count; start++)
1218 		s += scnprintf(&buf[s], element_size + 1,
1219 				"0x%08x : 0x%08x : %1s\n",
1220 				bps[start].bp,
1221 				bps[start].size,
1222 				amdgpu_ras_badpage_flags_str(bps[start].flags));
1223 
1224 	kfree(bps);
1225 
1226 	return s;
1227 }
1228 
1229 static ssize_t amdgpu_ras_sysfs_features_read(struct device *dev,
1230 		struct device_attribute *attr, char *buf)
1231 {
1232 	struct amdgpu_ras *con =
1233 		container_of(attr, struct amdgpu_ras, features_attr);
1234 
1235 	return scnprintf(buf, PAGE_SIZE, "feature mask: 0x%x\n", con->features);
1236 }
1237 
1238 static void amdgpu_ras_sysfs_remove_bad_page_node(struct amdgpu_device *adev)
1239 {
1240 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1241 
1242 	sysfs_remove_file_from_group(&adev->dev->kobj,
1243 				&con->badpages_attr.attr,
1244 				RAS_FS_NAME);
1245 }
1246 
1247 static int amdgpu_ras_sysfs_remove_feature_node(struct amdgpu_device *adev)
1248 {
1249 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1250 	struct attribute *attrs[] = {
1251 		&con->features_attr.attr,
1252 		NULL
1253 	};
1254 	struct attribute_group group = {
1255 		.name = RAS_FS_NAME,
1256 		.attrs = attrs,
1257 	};
1258 
1259 	sysfs_remove_group(&adev->dev->kobj, &group);
1260 
1261 	return 0;
1262 }
1263 
1264 int amdgpu_ras_sysfs_create(struct amdgpu_device *adev,
1265 		struct ras_fs_if *head)
1266 {
1267 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &head->head);
1268 
1269 	if (!obj || obj->attr_inuse)
1270 		return -EINVAL;
1271 
1272 	get_obj(obj);
1273 
1274 	memcpy(obj->fs_data.sysfs_name,
1275 			head->sysfs_name,
1276 			sizeof(obj->fs_data.sysfs_name));
1277 
1278 	obj->sysfs_attr = (struct device_attribute){
1279 		.attr = {
1280 			.name = obj->fs_data.sysfs_name,
1281 			.mode = S_IRUGO,
1282 		},
1283 			.show = amdgpu_ras_sysfs_read,
1284 	};
1285 	sysfs_attr_init(&obj->sysfs_attr.attr);
1286 
1287 	if (sysfs_add_file_to_group(&adev->dev->kobj,
1288 				&obj->sysfs_attr.attr,
1289 				RAS_FS_NAME)) {
1290 		put_obj(obj);
1291 		return -EINVAL;
1292 	}
1293 
1294 	obj->attr_inuse = 1;
1295 
1296 	return 0;
1297 }
1298 
1299 int amdgpu_ras_sysfs_remove(struct amdgpu_device *adev,
1300 		struct ras_common_if *head)
1301 {
1302 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
1303 
1304 	if (!obj || !obj->attr_inuse)
1305 		return -EINVAL;
1306 
1307 	sysfs_remove_file_from_group(&adev->dev->kobj,
1308 				&obj->sysfs_attr.attr,
1309 				RAS_FS_NAME);
1310 	obj->attr_inuse = 0;
1311 	put_obj(obj);
1312 
1313 	return 0;
1314 }
1315 
1316 static int amdgpu_ras_sysfs_remove_all(struct amdgpu_device *adev)
1317 {
1318 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1319 	struct ras_manager *obj, *tmp;
1320 
1321 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
1322 		amdgpu_ras_sysfs_remove(adev, &obj->head);
1323 	}
1324 
1325 	if (amdgpu_bad_page_threshold != 0)
1326 		amdgpu_ras_sysfs_remove_bad_page_node(adev);
1327 
1328 	amdgpu_ras_sysfs_remove_feature_node(adev);
1329 
1330 	return 0;
1331 }
1332 /* sysfs end */
1333 
1334 /**
1335  * DOC: AMDGPU RAS Reboot Behavior for Unrecoverable Errors
1336  *
1337  * Normally when there is an uncorrectable error, the driver will reset
1338  * the GPU to recover.  However, in the event of an unrecoverable error,
1339  * the driver provides an interface to reboot the system automatically
1340  * in that event.
1341  *
1342  * The following file in debugfs provides that interface:
1343  * /sys/kernel/debug/dri/[0/1/2...]/ras/auto_reboot
1344  *
1345  * Usage:
1346  *
1347  * .. code-block:: bash
1348  *
1349  *	echo true > .../ras/auto_reboot
1350  *
1351  */
1352 /* debugfs begin */
1353 static struct dentry *amdgpu_ras_debugfs_create_ctrl_node(struct amdgpu_device *adev)
1354 {
1355 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1356 	struct drm_minor  *minor = adev_to_drm(adev)->primary;
1357 	struct dentry     *dir;
1358 
1359 	dir = debugfs_create_dir(RAS_FS_NAME, minor->debugfs_root);
1360 	debugfs_create_file("ras_ctrl", S_IWUGO | S_IRUGO, dir, adev,
1361 			    &amdgpu_ras_debugfs_ctrl_ops);
1362 	debugfs_create_file("ras_eeprom_reset", S_IWUGO | S_IRUGO, dir, adev,
1363 			    &amdgpu_ras_debugfs_eeprom_ops);
1364 	debugfs_create_u32("bad_page_cnt_threshold", 0444, dir,
1365 			   &con->bad_page_cnt_threshold);
1366 	debugfs_create_x32("ras_hw_enabled", 0444, dir, &adev->ras_hw_enabled);
1367 	debugfs_create_x32("ras_enabled", 0444, dir, &adev->ras_enabled);
1368 	debugfs_create_file("ras_eeprom_size", S_IRUGO, dir, adev,
1369 			    &amdgpu_ras_debugfs_eeprom_size_ops);
1370 	con->de_ras_eeprom_table = debugfs_create_file("ras_eeprom_table",
1371 						       S_IRUGO, dir, adev,
1372 						       &amdgpu_ras_debugfs_eeprom_table_ops);
1373 	amdgpu_ras_debugfs_set_ret_size(&con->eeprom_control);
1374 
1375 	/*
1376 	 * After one uncorrectable error happens, usually GPU recovery will
1377 	 * be scheduled. But due to the known problem in GPU recovery failing
1378 	 * to bring GPU back, below interface provides one direct way to
1379 	 * user to reboot system automatically in such case within
1380 	 * ERREVENT_ATHUB_INTERRUPT generated. Normal GPU recovery routine
1381 	 * will never be called.
1382 	 */
1383 	debugfs_create_bool("auto_reboot", S_IWUGO | S_IRUGO, dir, &con->reboot);
1384 
1385 	/*
1386 	 * User could set this not to clean up hardware's error count register
1387 	 * of RAS IPs during ras recovery.
1388 	 */
1389 	debugfs_create_bool("disable_ras_err_cnt_harvest", 0644, dir,
1390 			    &con->disable_ras_err_cnt_harvest);
1391 	return dir;
1392 }
1393 
1394 static void amdgpu_ras_debugfs_create(struct amdgpu_device *adev,
1395 				      struct ras_fs_if *head,
1396 				      struct dentry *dir)
1397 {
1398 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &head->head);
1399 
1400 	if (!obj || !dir)
1401 		return;
1402 
1403 	get_obj(obj);
1404 
1405 	memcpy(obj->fs_data.debugfs_name,
1406 			head->debugfs_name,
1407 			sizeof(obj->fs_data.debugfs_name));
1408 
1409 	debugfs_create_file(obj->fs_data.debugfs_name, S_IWUGO | S_IRUGO, dir,
1410 			    obj, &amdgpu_ras_debugfs_ops);
1411 }
1412 
1413 void amdgpu_ras_debugfs_create_all(struct amdgpu_device *adev)
1414 {
1415 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1416 	struct dentry *dir;
1417 	struct ras_manager *obj;
1418 	struct ras_fs_if fs_info;
1419 
1420 	/*
1421 	 * it won't be called in resume path, no need to check
1422 	 * suspend and gpu reset status
1423 	 */
1424 	if (!IS_ENABLED(CONFIG_DEBUG_FS) || !con)
1425 		return;
1426 
1427 	dir = amdgpu_ras_debugfs_create_ctrl_node(adev);
1428 
1429 	list_for_each_entry(obj, &con->head, node) {
1430 		if (amdgpu_ras_is_supported(adev, obj->head.block) &&
1431 			(obj->attr_inuse == 1)) {
1432 			sprintf(fs_info.debugfs_name, "%s_err_inject",
1433 					get_ras_block_str(&obj->head));
1434 			fs_info.head = obj->head;
1435 			amdgpu_ras_debugfs_create(adev, &fs_info, dir);
1436 		}
1437 	}
1438 }
1439 
1440 /* debugfs end */
1441 
1442 /* ras fs */
1443 static BIN_ATTR(gpu_vram_bad_pages, S_IRUGO,
1444 		amdgpu_ras_sysfs_badpages_read, NULL, 0);
1445 static DEVICE_ATTR(features, S_IRUGO,
1446 		amdgpu_ras_sysfs_features_read, NULL);
1447 static int amdgpu_ras_fs_init(struct amdgpu_device *adev)
1448 {
1449 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1450 	struct attribute_group group = {
1451 		.name = RAS_FS_NAME,
1452 	};
1453 	struct attribute *attrs[] = {
1454 		&con->features_attr.attr,
1455 		NULL
1456 	};
1457 	struct bin_attribute *bin_attrs[] = {
1458 		NULL,
1459 		NULL,
1460 	};
1461 	int r;
1462 
1463 	/* add features entry */
1464 	con->features_attr = dev_attr_features;
1465 	group.attrs = attrs;
1466 	sysfs_attr_init(attrs[0]);
1467 
1468 	if (amdgpu_bad_page_threshold != 0) {
1469 		/* add bad_page_features entry */
1470 		bin_attr_gpu_vram_bad_pages.private = NULL;
1471 		con->badpages_attr = bin_attr_gpu_vram_bad_pages;
1472 		bin_attrs[0] = &con->badpages_attr;
1473 		group.bin_attrs = bin_attrs;
1474 		sysfs_bin_attr_init(bin_attrs[0]);
1475 	}
1476 
1477 	r = sysfs_create_group(&adev->dev->kobj, &group);
1478 	if (r)
1479 		dev_err(adev->dev, "Failed to create RAS sysfs group!");
1480 
1481 	return 0;
1482 }
1483 
1484 static int amdgpu_ras_fs_fini(struct amdgpu_device *adev)
1485 {
1486 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1487 	struct ras_manager *con_obj, *ip_obj, *tmp;
1488 
1489 	if (IS_ENABLED(CONFIG_DEBUG_FS)) {
1490 		list_for_each_entry_safe(con_obj, tmp, &con->head, node) {
1491 			ip_obj = amdgpu_ras_find_obj(adev, &con_obj->head);
1492 			if (ip_obj)
1493 				put_obj(ip_obj);
1494 		}
1495 	}
1496 
1497 	amdgpu_ras_sysfs_remove_all(adev);
1498 	return 0;
1499 }
1500 /* ras fs end */
1501 
1502 /* ih begin */
1503 static void amdgpu_ras_interrupt_handler(struct ras_manager *obj)
1504 {
1505 	struct ras_ih_data *data = &obj->ih_data;
1506 	struct amdgpu_iv_entry entry;
1507 	int ret;
1508 	struct ras_err_data err_data = {0, 0, 0, NULL};
1509 
1510 	while (data->rptr != data->wptr) {
1511 		rmb();
1512 		memcpy(&entry, &data->ring[data->rptr],
1513 				data->element_size);
1514 
1515 		wmb();
1516 		data->rptr = (data->aligned_element_size +
1517 				data->rptr) % data->ring_size;
1518 
1519 		if (data->cb) {
1520 			if (amdgpu_ras_is_poison_mode_supported(obj->adev) &&
1521 			    obj->head.block == AMDGPU_RAS_BLOCK__UMC)
1522 				dev_info(obj->adev->dev,
1523 						"Poison is created, no user action is needed.\n");
1524 			else {
1525 				/* Let IP handle its data, maybe we need get the output
1526 				 * from the callback to udpate the error type/count, etc
1527 				 */
1528 				memset(&err_data, 0, sizeof(err_data));
1529 				ret = data->cb(obj->adev, &err_data, &entry);
1530 				/* ue will trigger an interrupt, and in that case
1531 				 * we need do a reset to recovery the whole system.
1532 				 * But leave IP do that recovery, here we just dispatch
1533 				 * the error.
1534 				 */
1535 				if (ret == AMDGPU_RAS_SUCCESS) {
1536 					/* these counts could be left as 0 if
1537 					 * some blocks do not count error number
1538 					 */
1539 					obj->err_data.ue_count += err_data.ue_count;
1540 					obj->err_data.ce_count += err_data.ce_count;
1541 				}
1542 			}
1543 		}
1544 	}
1545 }
1546 
1547 static void amdgpu_ras_interrupt_process_handler(struct work_struct *work)
1548 {
1549 	struct ras_ih_data *data =
1550 		container_of(work, struct ras_ih_data, ih_work);
1551 	struct ras_manager *obj =
1552 		container_of(data, struct ras_manager, ih_data);
1553 
1554 	amdgpu_ras_interrupt_handler(obj);
1555 }
1556 
1557 int amdgpu_ras_interrupt_dispatch(struct amdgpu_device *adev,
1558 		struct ras_dispatch_if *info)
1559 {
1560 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1561 	struct ras_ih_data *data = &obj->ih_data;
1562 
1563 	if (!obj)
1564 		return -EINVAL;
1565 
1566 	if (data->inuse == 0)
1567 		return 0;
1568 
1569 	/* Might be overflow... */
1570 	memcpy(&data->ring[data->wptr], info->entry,
1571 			data->element_size);
1572 
1573 	wmb();
1574 	data->wptr = (data->aligned_element_size +
1575 			data->wptr) % data->ring_size;
1576 
1577 	schedule_work(&data->ih_work);
1578 
1579 	return 0;
1580 }
1581 
1582 int amdgpu_ras_interrupt_remove_handler(struct amdgpu_device *adev,
1583 		struct ras_ih_if *info)
1584 {
1585 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1586 	struct ras_ih_data *data;
1587 
1588 	if (!obj)
1589 		return -EINVAL;
1590 
1591 	data = &obj->ih_data;
1592 	if (data->inuse == 0)
1593 		return 0;
1594 
1595 	cancel_work_sync(&data->ih_work);
1596 
1597 	kfree(data->ring);
1598 	memset(data, 0, sizeof(*data));
1599 	put_obj(obj);
1600 
1601 	return 0;
1602 }
1603 
1604 int amdgpu_ras_interrupt_add_handler(struct amdgpu_device *adev,
1605 		struct ras_ih_if *info)
1606 {
1607 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1608 	struct ras_ih_data *data;
1609 
1610 	if (!obj) {
1611 		/* in case we registe the IH before enable ras feature */
1612 		obj = amdgpu_ras_create_obj(adev, &info->head);
1613 		if (!obj)
1614 			return -EINVAL;
1615 	} else
1616 		get_obj(obj);
1617 
1618 	data = &obj->ih_data;
1619 	/* add the callback.etc */
1620 	*data = (struct ras_ih_data) {
1621 		.inuse = 0,
1622 		.cb = info->cb,
1623 		.element_size = sizeof(struct amdgpu_iv_entry),
1624 		.rptr = 0,
1625 		.wptr = 0,
1626 	};
1627 
1628 	INIT_WORK(&data->ih_work, amdgpu_ras_interrupt_process_handler);
1629 
1630 	data->aligned_element_size = ALIGN(data->element_size, 8);
1631 	/* the ring can store 64 iv entries. */
1632 	data->ring_size = 64 * data->aligned_element_size;
1633 	data->ring = kmalloc(data->ring_size, GFP_KERNEL);
1634 	if (!data->ring) {
1635 		put_obj(obj);
1636 		return -ENOMEM;
1637 	}
1638 
1639 	/* IH is ready */
1640 	data->inuse = 1;
1641 
1642 	return 0;
1643 }
1644 
1645 static int amdgpu_ras_interrupt_remove_all(struct amdgpu_device *adev)
1646 {
1647 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1648 	struct ras_manager *obj, *tmp;
1649 
1650 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
1651 		struct ras_ih_if info = {
1652 			.head = obj->head,
1653 		};
1654 		amdgpu_ras_interrupt_remove_handler(adev, &info);
1655 	}
1656 
1657 	return 0;
1658 }
1659 /* ih end */
1660 
1661 /* traversal all IPs except NBIO to query error counter */
1662 static void amdgpu_ras_log_on_err_counter(struct amdgpu_device *adev)
1663 {
1664 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1665 	struct ras_manager *obj;
1666 
1667 	if (!adev->ras_enabled || !con)
1668 		return;
1669 
1670 	list_for_each_entry(obj, &con->head, node) {
1671 		struct ras_query_if info = {
1672 			.head = obj->head,
1673 		};
1674 
1675 		/*
1676 		 * PCIE_BIF IP has one different isr by ras controller
1677 		 * interrupt, the specific ras counter query will be
1678 		 * done in that isr. So skip such block from common
1679 		 * sync flood interrupt isr calling.
1680 		 */
1681 		if (info.head.block == AMDGPU_RAS_BLOCK__PCIE_BIF)
1682 			continue;
1683 
1684 		/*
1685 		 * this is a workaround for aldebaran, skip send msg to
1686 		 * smu to get ecc_info table due to smu handle get ecc
1687 		 * info table failed temporarily.
1688 		 * should be removed until smu fix handle ecc_info table.
1689 		 */
1690 		if ((info.head.block == AMDGPU_RAS_BLOCK__UMC) &&
1691 			(adev->ip_versions[MP1_HWIP][0] == IP_VERSION(13, 0, 2)))
1692 			continue;
1693 
1694 		amdgpu_ras_query_error_status(adev, &info);
1695 	}
1696 }
1697 
1698 /* Parse RdRspStatus and WrRspStatus */
1699 static void amdgpu_ras_error_status_query(struct amdgpu_device *adev,
1700 					  struct ras_query_if *info)
1701 {
1702 	struct amdgpu_ras_block_object *block_obj;
1703 	/*
1704 	 * Only two block need to query read/write
1705 	 * RspStatus at current state
1706 	 */
1707 	if ((info->head.block != AMDGPU_RAS_BLOCK__GFX) &&
1708 		(info->head.block != AMDGPU_RAS_BLOCK__MMHUB))
1709 		return;
1710 
1711 	block_obj = amdgpu_ras_get_ras_block(adev,
1712 					info->head.block,
1713 					info->head.sub_block_index);
1714 
1715 	if (!block_obj || !block_obj->hw_ops) {
1716 		dev_info(adev->dev, "%s doesn't config ras function.\n",
1717 			get_ras_block_str(&info->head));
1718 		return;
1719 	}
1720 
1721 	if (block_obj->hw_ops->query_ras_error_status)
1722 		block_obj->hw_ops->query_ras_error_status(adev);
1723 
1724 }
1725 
1726 static void amdgpu_ras_query_err_status(struct amdgpu_device *adev)
1727 {
1728 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1729 	struct ras_manager *obj;
1730 
1731 	if (!adev->ras_enabled || !con)
1732 		return;
1733 
1734 	list_for_each_entry(obj, &con->head, node) {
1735 		struct ras_query_if info = {
1736 			.head = obj->head,
1737 		};
1738 
1739 		amdgpu_ras_error_status_query(adev, &info);
1740 	}
1741 }
1742 
1743 /* recovery begin */
1744 
1745 /* return 0 on success.
1746  * caller need free bps.
1747  */
1748 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
1749 		struct ras_badpage **bps, unsigned int *count)
1750 {
1751 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1752 	struct ras_err_handler_data *data;
1753 	int i = 0;
1754 	int ret = 0, status;
1755 
1756 	if (!con || !con->eh_data || !bps || !count)
1757 		return -EINVAL;
1758 
1759 	mutex_lock(&con->recovery_lock);
1760 	data = con->eh_data;
1761 	if (!data || data->count == 0) {
1762 		*bps = NULL;
1763 		ret = -EINVAL;
1764 		goto out;
1765 	}
1766 
1767 	*bps = kmalloc(sizeof(struct ras_badpage) * data->count, GFP_KERNEL);
1768 	if (!*bps) {
1769 		ret = -ENOMEM;
1770 		goto out;
1771 	}
1772 
1773 	for (; i < data->count; i++) {
1774 		(*bps)[i] = (struct ras_badpage){
1775 			.bp = data->bps[i].retired_page,
1776 			.size = AMDGPU_GPU_PAGE_SIZE,
1777 			.flags = AMDGPU_RAS_RETIRE_PAGE_RESERVED,
1778 		};
1779 		status = amdgpu_vram_mgr_query_page_status(&adev->mman.vram_mgr,
1780 				data->bps[i].retired_page);
1781 		if (status == -EBUSY)
1782 			(*bps)[i].flags = AMDGPU_RAS_RETIRE_PAGE_PENDING;
1783 		else if (status == -ENOENT)
1784 			(*bps)[i].flags = AMDGPU_RAS_RETIRE_PAGE_FAULT;
1785 	}
1786 
1787 	*count = data->count;
1788 out:
1789 	mutex_unlock(&con->recovery_lock);
1790 	return ret;
1791 }
1792 
1793 static void amdgpu_ras_do_recovery(struct work_struct *work)
1794 {
1795 	struct amdgpu_ras *ras =
1796 		container_of(work, struct amdgpu_ras, recovery_work);
1797 	struct amdgpu_device *remote_adev = NULL;
1798 	struct amdgpu_device *adev = ras->adev;
1799 	struct list_head device_list, *device_list_handle =  NULL;
1800 
1801 	if (!ras->disable_ras_err_cnt_harvest) {
1802 		struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
1803 
1804 		/* Build list of devices to query RAS related errors */
1805 		if  (hive && adev->gmc.xgmi.num_physical_nodes > 1) {
1806 			device_list_handle = &hive->device_list;
1807 		} else {
1808 			INIT_LIST_HEAD(&device_list);
1809 			list_add_tail(&adev->gmc.xgmi.head, &device_list);
1810 			device_list_handle = &device_list;
1811 		}
1812 
1813 		list_for_each_entry(remote_adev,
1814 				device_list_handle, gmc.xgmi.head) {
1815 			amdgpu_ras_query_err_status(remote_adev);
1816 			amdgpu_ras_log_on_err_counter(remote_adev);
1817 		}
1818 
1819 		amdgpu_put_xgmi_hive(hive);
1820 	}
1821 
1822 	if (amdgpu_device_should_recover_gpu(ras->adev))
1823 		amdgpu_device_gpu_recover(ras->adev, NULL);
1824 	atomic_set(&ras->in_recovery, 0);
1825 }
1826 
1827 /* alloc/realloc bps array */
1828 static int amdgpu_ras_realloc_eh_data_space(struct amdgpu_device *adev,
1829 		struct ras_err_handler_data *data, int pages)
1830 {
1831 	unsigned int old_space = data->count + data->space_left;
1832 	unsigned int new_space = old_space + pages;
1833 	unsigned int align_space = ALIGN(new_space, 512);
1834 	void *bps = kmalloc(align_space * sizeof(*data->bps), GFP_KERNEL);
1835 
1836 	if (!bps) {
1837 		kfree(bps);
1838 		return -ENOMEM;
1839 	}
1840 
1841 	if (data->bps) {
1842 		memcpy(bps, data->bps,
1843 				data->count * sizeof(*data->bps));
1844 		kfree(data->bps);
1845 	}
1846 
1847 	data->bps = bps;
1848 	data->space_left += align_space - old_space;
1849 	return 0;
1850 }
1851 
1852 /* it deal with vram only. */
1853 int amdgpu_ras_add_bad_pages(struct amdgpu_device *adev,
1854 		struct eeprom_table_record *bps, int pages)
1855 {
1856 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1857 	struct ras_err_handler_data *data;
1858 	int ret = 0;
1859 	uint32_t i;
1860 
1861 	if (!con || !con->eh_data || !bps || pages <= 0)
1862 		return 0;
1863 
1864 	mutex_lock(&con->recovery_lock);
1865 	data = con->eh_data;
1866 	if (!data)
1867 		goto out;
1868 
1869 	for (i = 0; i < pages; i++) {
1870 		if (amdgpu_ras_check_bad_page_unlock(con,
1871 			bps[i].retired_page << AMDGPU_GPU_PAGE_SHIFT))
1872 			continue;
1873 
1874 		if (!data->space_left &&
1875 			amdgpu_ras_realloc_eh_data_space(adev, data, 256)) {
1876 			ret = -ENOMEM;
1877 			goto out;
1878 		}
1879 
1880 		amdgpu_vram_mgr_reserve_range(&adev->mman.vram_mgr,
1881 			bps[i].retired_page << AMDGPU_GPU_PAGE_SHIFT,
1882 			AMDGPU_GPU_PAGE_SIZE);
1883 
1884 		memcpy(&data->bps[data->count], &bps[i], sizeof(*data->bps));
1885 		data->count++;
1886 		data->space_left--;
1887 	}
1888 out:
1889 	mutex_unlock(&con->recovery_lock);
1890 
1891 	return ret;
1892 }
1893 
1894 /*
1895  * write error record array to eeprom, the function should be
1896  * protected by recovery_lock
1897  */
1898 int amdgpu_ras_save_bad_pages(struct amdgpu_device *adev)
1899 {
1900 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1901 	struct ras_err_handler_data *data;
1902 	struct amdgpu_ras_eeprom_control *control;
1903 	int save_count;
1904 
1905 	if (!con || !con->eh_data)
1906 		return 0;
1907 
1908 	mutex_lock(&con->recovery_lock);
1909 	control = &con->eeprom_control;
1910 	data = con->eh_data;
1911 	save_count = data->count - control->ras_num_recs;
1912 	mutex_unlock(&con->recovery_lock);
1913 	/* only new entries are saved */
1914 	if (save_count > 0) {
1915 		if (amdgpu_ras_eeprom_append(control,
1916 					     &data->bps[control->ras_num_recs],
1917 					     save_count)) {
1918 			dev_err(adev->dev, "Failed to save EEPROM table data!");
1919 			return -EIO;
1920 		}
1921 
1922 		dev_info(adev->dev, "Saved %d pages to EEPROM table.\n", save_count);
1923 	}
1924 
1925 	return 0;
1926 }
1927 
1928 /*
1929  * read error record array in eeprom and reserve enough space for
1930  * storing new bad pages
1931  */
1932 static int amdgpu_ras_load_bad_pages(struct amdgpu_device *adev)
1933 {
1934 	struct amdgpu_ras_eeprom_control *control =
1935 		&adev->psp.ras_context.ras->eeprom_control;
1936 	struct eeprom_table_record *bps;
1937 	int ret;
1938 
1939 	/* no bad page record, skip eeprom access */
1940 	if (control->ras_num_recs == 0 || amdgpu_bad_page_threshold == 0)
1941 		return 0;
1942 
1943 	bps = kcalloc(control->ras_num_recs, sizeof(*bps), GFP_KERNEL);
1944 	if (!bps)
1945 		return -ENOMEM;
1946 
1947 	ret = amdgpu_ras_eeprom_read(control, bps, control->ras_num_recs);
1948 	if (ret)
1949 		dev_err(adev->dev, "Failed to load EEPROM table records!");
1950 	else
1951 		ret = amdgpu_ras_add_bad_pages(adev, bps, control->ras_num_recs);
1952 
1953 	kfree(bps);
1954 	return ret;
1955 }
1956 
1957 static bool amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
1958 				uint64_t addr)
1959 {
1960 	struct ras_err_handler_data *data = con->eh_data;
1961 	int i;
1962 
1963 	addr >>= AMDGPU_GPU_PAGE_SHIFT;
1964 	for (i = 0; i < data->count; i++)
1965 		if (addr == data->bps[i].retired_page)
1966 			return true;
1967 
1968 	return false;
1969 }
1970 
1971 /*
1972  * check if an address belongs to bad page
1973  *
1974  * Note: this check is only for umc block
1975  */
1976 static bool amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
1977 				uint64_t addr)
1978 {
1979 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1980 	bool ret = false;
1981 
1982 	if (!con || !con->eh_data)
1983 		return ret;
1984 
1985 	mutex_lock(&con->recovery_lock);
1986 	ret = amdgpu_ras_check_bad_page_unlock(con, addr);
1987 	mutex_unlock(&con->recovery_lock);
1988 	return ret;
1989 }
1990 
1991 static void amdgpu_ras_validate_threshold(struct amdgpu_device *adev,
1992 					  uint32_t max_count)
1993 {
1994 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1995 
1996 	/*
1997 	 * Justification of value bad_page_cnt_threshold in ras structure
1998 	 *
1999 	 * Generally, -1 <= amdgpu_bad_page_threshold <= max record length
2000 	 * in eeprom, and introduce two scenarios accordingly.
2001 	 *
2002 	 * Bad page retirement enablement:
2003 	 *    - If amdgpu_bad_page_threshold = -1,
2004 	 *      bad_page_cnt_threshold = typical value by formula.
2005 	 *
2006 	 *    - When the value from user is 0 < amdgpu_bad_page_threshold <
2007 	 *      max record length in eeprom, use it directly.
2008 	 *
2009 	 * Bad page retirement disablement:
2010 	 *    - If amdgpu_bad_page_threshold = 0, bad page retirement
2011 	 *      functionality is disabled, and bad_page_cnt_threshold will
2012 	 *      take no effect.
2013 	 */
2014 
2015 	if (amdgpu_bad_page_threshold < 0) {
2016 		u64 val = adev->gmc.mc_vram_size;
2017 
2018 		do_div(val, RAS_BAD_PAGE_COVER);
2019 		con->bad_page_cnt_threshold = min(lower_32_bits(val),
2020 						  max_count);
2021 	} else {
2022 		con->bad_page_cnt_threshold = min_t(int, max_count,
2023 						    amdgpu_bad_page_threshold);
2024 	}
2025 }
2026 
2027 int amdgpu_ras_recovery_init(struct amdgpu_device *adev)
2028 {
2029 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2030 	struct ras_err_handler_data **data;
2031 	u32  max_eeprom_records_count = 0;
2032 	bool exc_err_limit = false;
2033 	int ret;
2034 
2035 	if (!con)
2036 		return 0;
2037 
2038 	/* Allow access to RAS EEPROM via debugfs, when the ASIC
2039 	 * supports RAS and debugfs is enabled, but when
2040 	 * adev->ras_enabled is unset, i.e. when "ras_enable"
2041 	 * module parameter is set to 0.
2042 	 */
2043 	con->adev = adev;
2044 
2045 	if (!adev->ras_enabled)
2046 		return 0;
2047 
2048 	data = &con->eh_data;
2049 	*data = kmalloc(sizeof(**data), GFP_KERNEL | __GFP_ZERO);
2050 	if (!*data) {
2051 		ret = -ENOMEM;
2052 		goto out;
2053 	}
2054 
2055 	mutex_init(&con->recovery_lock);
2056 	INIT_WORK(&con->recovery_work, amdgpu_ras_do_recovery);
2057 	atomic_set(&con->in_recovery, 0);
2058 
2059 	max_eeprom_records_count = amdgpu_ras_eeprom_max_record_count();
2060 	amdgpu_ras_validate_threshold(adev, max_eeprom_records_count);
2061 
2062 	/* Todo: During test the SMU might fail to read the eeprom through I2C
2063 	 * when the GPU is pending on XGMI reset during probe time
2064 	 * (Mostly after second bus reset), skip it now
2065 	 */
2066 	if (adev->gmc.xgmi.pending_reset)
2067 		return 0;
2068 	ret = amdgpu_ras_eeprom_init(&con->eeprom_control, &exc_err_limit);
2069 	/*
2070 	 * This calling fails when exc_err_limit is true or
2071 	 * ret != 0.
2072 	 */
2073 	if (exc_err_limit || ret)
2074 		goto free;
2075 
2076 	if (con->eeprom_control.ras_num_recs) {
2077 		ret = amdgpu_ras_load_bad_pages(adev);
2078 		if (ret)
2079 			goto free;
2080 
2081 		amdgpu_dpm_send_hbm_bad_pages_num(adev, con->eeprom_control.ras_num_recs);
2082 	}
2083 
2084 #ifdef CONFIG_X86_MCE_AMD
2085 	if ((adev->asic_type == CHIP_ALDEBARAN) &&
2086 	    (adev->gmc.xgmi.connected_to_cpu))
2087 		amdgpu_register_bad_pages_mca_notifier(adev);
2088 #endif
2089 	return 0;
2090 
2091 free:
2092 	kfree((*data)->bps);
2093 	kfree(*data);
2094 	con->eh_data = NULL;
2095 out:
2096 	dev_warn(adev->dev, "Failed to initialize ras recovery! (%d)\n", ret);
2097 
2098 	/*
2099 	 * Except error threshold exceeding case, other failure cases in this
2100 	 * function would not fail amdgpu driver init.
2101 	 */
2102 	if (!exc_err_limit)
2103 		ret = 0;
2104 	else
2105 		ret = -EINVAL;
2106 
2107 	return ret;
2108 }
2109 
2110 static int amdgpu_ras_recovery_fini(struct amdgpu_device *adev)
2111 {
2112 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2113 	struct ras_err_handler_data *data = con->eh_data;
2114 
2115 	/* recovery_init failed to init it, fini is useless */
2116 	if (!data)
2117 		return 0;
2118 
2119 	cancel_work_sync(&con->recovery_work);
2120 
2121 	mutex_lock(&con->recovery_lock);
2122 	con->eh_data = NULL;
2123 	kfree(data->bps);
2124 	kfree(data);
2125 	mutex_unlock(&con->recovery_lock);
2126 
2127 	return 0;
2128 }
2129 /* recovery end */
2130 
2131 static bool amdgpu_ras_asic_supported(struct amdgpu_device *adev)
2132 {
2133 	return adev->asic_type == CHIP_VEGA10 ||
2134 		adev->asic_type == CHIP_VEGA20 ||
2135 		adev->asic_type == CHIP_ARCTURUS ||
2136 		adev->asic_type == CHIP_ALDEBARAN ||
2137 		adev->asic_type == CHIP_SIENNA_CICHLID;
2138 }
2139 
2140 /*
2141  * this is workaround for vega20 workstation sku,
2142  * force enable gfx ras, ignore vbios gfx ras flag
2143  * due to GC EDC can not write
2144  */
2145 static void amdgpu_ras_get_quirks(struct amdgpu_device *adev)
2146 {
2147 	struct atom_context *ctx = adev->mode_info.atom_context;
2148 
2149 	if (!ctx)
2150 		return;
2151 
2152 	if (strnstr(ctx->vbios_version, "D16406",
2153 		    sizeof(ctx->vbios_version)) ||
2154 		strnstr(ctx->vbios_version, "D36002",
2155 			sizeof(ctx->vbios_version)))
2156 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__GFX);
2157 }
2158 
2159 /*
2160  * check hardware's ras ability which will be saved in hw_supported.
2161  * if hardware does not support ras, we can skip some ras initializtion and
2162  * forbid some ras operations from IP.
2163  * if software itself, say boot parameter, limit the ras ability. We still
2164  * need allow IP do some limited operations, like disable. In such case,
2165  * we have to initialize ras as normal. but need check if operation is
2166  * allowed or not in each function.
2167  */
2168 static void amdgpu_ras_check_supported(struct amdgpu_device *adev)
2169 {
2170 	adev->ras_hw_enabled = adev->ras_enabled = 0;
2171 
2172 	if (amdgpu_sriov_vf(adev) || !adev->is_atom_fw ||
2173 	    !amdgpu_ras_asic_supported(adev))
2174 		return;
2175 
2176 	if (!adev->gmc.xgmi.connected_to_cpu) {
2177 		if (amdgpu_atomfirmware_mem_ecc_supported(adev)) {
2178 			dev_info(adev->dev, "MEM ECC is active.\n");
2179 			adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__UMC |
2180 						   1 << AMDGPU_RAS_BLOCK__DF);
2181 		} else {
2182 			dev_info(adev->dev, "MEM ECC is not presented.\n");
2183 		}
2184 
2185 		if (amdgpu_atomfirmware_sram_ecc_supported(adev)) {
2186 			dev_info(adev->dev, "SRAM ECC is active.\n");
2187 			adev->ras_hw_enabled |= ~(1 << AMDGPU_RAS_BLOCK__UMC |
2188 						    1 << AMDGPU_RAS_BLOCK__DF);
2189 		} else {
2190 			dev_info(adev->dev, "SRAM ECC is not presented.\n");
2191 		}
2192 	} else {
2193 		/* driver only manages a few IP blocks RAS feature
2194 		 * when GPU is connected cpu through XGMI */
2195 		adev->ras_hw_enabled |= (1 << AMDGPU_RAS_BLOCK__GFX |
2196 					   1 << AMDGPU_RAS_BLOCK__SDMA |
2197 					   1 << AMDGPU_RAS_BLOCK__MMHUB);
2198 	}
2199 
2200 	amdgpu_ras_get_quirks(adev);
2201 
2202 	/* hw_supported needs to be aligned with RAS block mask. */
2203 	adev->ras_hw_enabled &= AMDGPU_RAS_BLOCK_MASK;
2204 
2205 	adev->ras_enabled = amdgpu_ras_enable == 0 ? 0 :
2206 		adev->ras_hw_enabled & amdgpu_ras_mask;
2207 }
2208 
2209 static void amdgpu_ras_counte_dw(struct work_struct *work)
2210 {
2211 	struct amdgpu_ras *con = container_of(work, struct amdgpu_ras,
2212 					      ras_counte_delay_work.work);
2213 	struct amdgpu_device *adev = con->adev;
2214 	struct drm_device *dev = adev_to_drm(adev);
2215 	unsigned long ce_count, ue_count;
2216 	int res;
2217 
2218 	res = pm_runtime_get_sync(dev->dev);
2219 	if (res < 0)
2220 		goto Out;
2221 
2222 	/* Cache new values.
2223 	 */
2224 	if (amdgpu_ras_query_error_count(adev, &ce_count, &ue_count) == 0) {
2225 		atomic_set(&con->ras_ce_count, ce_count);
2226 		atomic_set(&con->ras_ue_count, ue_count);
2227 	}
2228 
2229 	pm_runtime_mark_last_busy(dev->dev);
2230 Out:
2231 	pm_runtime_put_autosuspend(dev->dev);
2232 }
2233 
2234 int amdgpu_ras_init(struct amdgpu_device *adev)
2235 {
2236 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2237 	int r;
2238 	bool df_poison, umc_poison;
2239 
2240 	if (con)
2241 		return 0;
2242 
2243 	con = kmalloc(sizeof(struct amdgpu_ras) +
2244 			sizeof(struct ras_manager) * AMDGPU_RAS_BLOCK_COUNT +
2245 			sizeof(struct ras_manager) * AMDGPU_RAS_MCA_BLOCK_COUNT,
2246 			GFP_KERNEL|__GFP_ZERO);
2247 	if (!con)
2248 		return -ENOMEM;
2249 
2250 	con->adev = adev;
2251 	INIT_DELAYED_WORK(&con->ras_counte_delay_work, amdgpu_ras_counte_dw);
2252 	atomic_set(&con->ras_ce_count, 0);
2253 	atomic_set(&con->ras_ue_count, 0);
2254 
2255 	con->objs = (struct ras_manager *)(con + 1);
2256 
2257 	amdgpu_ras_set_context(adev, con);
2258 
2259 	amdgpu_ras_check_supported(adev);
2260 
2261 	if (!adev->ras_enabled || adev->asic_type == CHIP_VEGA10) {
2262 		/* set gfx block ras context feature for VEGA20 Gaming
2263 		 * send ras disable cmd to ras ta during ras late init.
2264 		 */
2265 		if (!adev->ras_enabled && adev->asic_type == CHIP_VEGA20) {
2266 			con->features |= BIT(AMDGPU_RAS_BLOCK__GFX);
2267 
2268 			return 0;
2269 		}
2270 
2271 		r = 0;
2272 		goto release_con;
2273 	}
2274 
2275 	con->features = 0;
2276 	INIT_LIST_HEAD(&con->head);
2277 	/* Might need get this flag from vbios. */
2278 	con->flags = RAS_DEFAULT_FLAGS;
2279 
2280 	/* initialize nbio ras function ahead of any other
2281 	 * ras functions so hardware fatal error interrupt
2282 	 * can be enabled as early as possible */
2283 	switch (adev->asic_type) {
2284 	case CHIP_VEGA20:
2285 	case CHIP_ARCTURUS:
2286 	case CHIP_ALDEBARAN:
2287 		if (!adev->gmc.xgmi.connected_to_cpu) {
2288 			adev->nbio.ras = &nbio_v7_4_ras;
2289 			amdgpu_ras_register_ras_block(adev, &adev->nbio.ras->ras_block);
2290 		}
2291 		break;
2292 	default:
2293 		/* nbio ras is not available */
2294 		break;
2295 	}
2296 
2297 	if (adev->nbio.ras &&
2298 	    adev->nbio.ras->init_ras_controller_interrupt) {
2299 		r = adev->nbio.ras->init_ras_controller_interrupt(adev);
2300 		if (r)
2301 			goto release_con;
2302 	}
2303 
2304 	if (adev->nbio.ras &&
2305 	    adev->nbio.ras->init_ras_err_event_athub_interrupt) {
2306 		r = adev->nbio.ras->init_ras_err_event_athub_interrupt(adev);
2307 		if (r)
2308 			goto release_con;
2309 	}
2310 
2311 	/* Init poison supported flag, the default value is false */
2312 	if (adev->gmc.xgmi.connected_to_cpu) {
2313 		/* enabled by default when GPU is connected to CPU */
2314 		con->poison_supported = true;
2315 	}
2316 	else if (adev->df.funcs &&
2317 	    adev->df.funcs->query_ras_poison_mode &&
2318 	    adev->umc.ras &&
2319 	    adev->umc.ras->query_ras_poison_mode) {
2320 		df_poison =
2321 			adev->df.funcs->query_ras_poison_mode(adev);
2322 		umc_poison =
2323 			adev->umc.ras->query_ras_poison_mode(adev);
2324 		/* Only poison is set in both DF and UMC, we can support it */
2325 		if (df_poison && umc_poison)
2326 			con->poison_supported = true;
2327 		else if (df_poison != umc_poison)
2328 			dev_warn(adev->dev, "Poison setting is inconsistent in DF/UMC(%d:%d)!\n",
2329 					df_poison, umc_poison);
2330 	}
2331 
2332 	if (amdgpu_ras_fs_init(adev)) {
2333 		r = -EINVAL;
2334 		goto release_con;
2335 	}
2336 
2337 	dev_info(adev->dev, "RAS INFO: ras initialized successfully, "
2338 		 "hardware ability[%x] ras_mask[%x]\n",
2339 		 adev->ras_hw_enabled, adev->ras_enabled);
2340 
2341 	return 0;
2342 release_con:
2343 	amdgpu_ras_set_context(adev, NULL);
2344 	kfree(con);
2345 
2346 	return r;
2347 }
2348 
2349 int amdgpu_persistent_edc_harvesting_supported(struct amdgpu_device *adev)
2350 {
2351 	if (adev->gmc.xgmi.connected_to_cpu)
2352 		return 1;
2353 	return 0;
2354 }
2355 
2356 static int amdgpu_persistent_edc_harvesting(struct amdgpu_device *adev,
2357 					struct ras_common_if *ras_block)
2358 {
2359 	struct ras_query_if info = {
2360 		.head = *ras_block,
2361 	};
2362 
2363 	if (!amdgpu_persistent_edc_harvesting_supported(adev))
2364 		return 0;
2365 
2366 	if (amdgpu_ras_query_error_status(adev, &info) != 0)
2367 		DRM_WARN("RAS init harvest failure");
2368 
2369 	if (amdgpu_ras_reset_error_status(adev, ras_block->block) != 0)
2370 		DRM_WARN("RAS init harvest reset failure");
2371 
2372 	return 0;
2373 }
2374 
2375 bool amdgpu_ras_is_poison_mode_supported(struct amdgpu_device *adev)
2376 {
2377        struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2378 
2379        if (!con)
2380                return false;
2381 
2382        return con->poison_supported;
2383 }
2384 
2385 /* helper function to handle common stuff in ip late init phase */
2386 int amdgpu_ras_late_init(struct amdgpu_device *adev,
2387 			 struct ras_common_if *ras_block,
2388 			 struct ras_fs_if *fs_info,
2389 			 struct ras_ih_if *ih_info)
2390 {
2391 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2392 	unsigned long ue_count, ce_count;
2393 	int r;
2394 
2395 	/* disable RAS feature per IP block if it is not supported */
2396 	if (!amdgpu_ras_is_supported(adev, ras_block->block)) {
2397 		amdgpu_ras_feature_enable_on_boot(adev, ras_block, 0);
2398 		return 0;
2399 	}
2400 
2401 	r = amdgpu_ras_feature_enable_on_boot(adev, ras_block, 1);
2402 	if (r) {
2403 		if (adev->in_suspend || amdgpu_in_reset(adev)) {
2404 			/* in resume phase, if fail to enable ras,
2405 			 * clean up all ras fs nodes, and disable ras */
2406 			goto cleanup;
2407 		} else
2408 			return r;
2409 	}
2410 
2411 	/* check for errors on warm reset edc persisant supported ASIC */
2412 	amdgpu_persistent_edc_harvesting(adev, ras_block);
2413 
2414 	/* in resume phase, no need to create ras fs node */
2415 	if (adev->in_suspend || amdgpu_in_reset(adev))
2416 		return 0;
2417 
2418 	if (ih_info->cb) {
2419 		r = amdgpu_ras_interrupt_add_handler(adev, ih_info);
2420 		if (r)
2421 			goto interrupt;
2422 	}
2423 
2424 	r = amdgpu_ras_sysfs_create(adev, fs_info);
2425 	if (r)
2426 		goto sysfs;
2427 
2428 	/* Those are the cached values at init.
2429 	 */
2430 	if (amdgpu_ras_query_error_count(adev, &ce_count, &ue_count) == 0) {
2431 		atomic_set(&con->ras_ce_count, ce_count);
2432 		atomic_set(&con->ras_ue_count, ue_count);
2433 	}
2434 
2435 	return 0;
2436 cleanup:
2437 	amdgpu_ras_sysfs_remove(adev, ras_block);
2438 sysfs:
2439 	if (ih_info->cb)
2440 		amdgpu_ras_interrupt_remove_handler(adev, ih_info);
2441 interrupt:
2442 	amdgpu_ras_feature_enable(adev, ras_block, 0);
2443 	return r;
2444 }
2445 
2446 /* helper function to remove ras fs node and interrupt handler */
2447 void amdgpu_ras_late_fini(struct amdgpu_device *adev,
2448 			  struct ras_common_if *ras_block,
2449 			  struct ras_ih_if *ih_info)
2450 {
2451 	if (!ras_block || !ih_info)
2452 		return;
2453 
2454 	amdgpu_ras_sysfs_remove(adev, ras_block);
2455 	if (ih_info->cb)
2456 		amdgpu_ras_interrupt_remove_handler(adev, ih_info);
2457 }
2458 
2459 /* do some init work after IP late init as dependence.
2460  * and it runs in resume/gpu reset/booting up cases.
2461  */
2462 void amdgpu_ras_resume(struct amdgpu_device *adev)
2463 {
2464 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2465 	struct ras_manager *obj, *tmp;
2466 
2467 	if (!adev->ras_enabled || !con) {
2468 		/* clean ras context for VEGA20 Gaming after send ras disable cmd */
2469 		amdgpu_release_ras_context(adev);
2470 
2471 		return;
2472 	}
2473 
2474 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
2475 		/* Set up all other IPs which are not implemented. There is a
2476 		 * tricky thing that IP's actual ras error type should be
2477 		 * MULTI_UNCORRECTABLE, but as driver does not handle it, so
2478 		 * ERROR_NONE make sense anyway.
2479 		 */
2480 		amdgpu_ras_enable_all_features(adev, 1);
2481 
2482 		/* We enable ras on all hw_supported block, but as boot
2483 		 * parameter might disable some of them and one or more IP has
2484 		 * not implemented yet. So we disable them on behalf.
2485 		 */
2486 		list_for_each_entry_safe(obj, tmp, &con->head, node) {
2487 			if (!amdgpu_ras_is_supported(adev, obj->head.block)) {
2488 				amdgpu_ras_feature_enable(adev, &obj->head, 0);
2489 				/* there should be no any reference. */
2490 				WARN_ON(alive_obj(obj));
2491 			}
2492 		}
2493 	}
2494 }
2495 
2496 void amdgpu_ras_suspend(struct amdgpu_device *adev)
2497 {
2498 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2499 
2500 	if (!adev->ras_enabled || !con)
2501 		return;
2502 
2503 	amdgpu_ras_disable_all_features(adev, 0);
2504 	/* Make sure all ras objects are disabled. */
2505 	if (con->features)
2506 		amdgpu_ras_disable_all_features(adev, 1);
2507 }
2508 
2509 /* do some fini work before IP fini as dependence */
2510 int amdgpu_ras_pre_fini(struct amdgpu_device *adev)
2511 {
2512 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2513 
2514 	if (!adev->ras_enabled || !con)
2515 		return 0;
2516 
2517 
2518 	/* Need disable ras on all IPs here before ip [hw/sw]fini */
2519 	amdgpu_ras_disable_all_features(adev, 0);
2520 	amdgpu_ras_recovery_fini(adev);
2521 	return 0;
2522 }
2523 
2524 int amdgpu_ras_fini(struct amdgpu_device *adev)
2525 {
2526 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2527 
2528 	if (!adev->ras_enabled || !con)
2529 		return 0;
2530 
2531 	amdgpu_ras_fs_fini(adev);
2532 	amdgpu_ras_interrupt_remove_all(adev);
2533 
2534 	WARN(con->features, "Feature mask is not cleared");
2535 
2536 	if (con->features)
2537 		amdgpu_ras_disable_all_features(adev, 1);
2538 
2539 	cancel_delayed_work_sync(&con->ras_counte_delay_work);
2540 
2541 	amdgpu_ras_set_context(adev, NULL);
2542 	kfree(con);
2543 
2544 	return 0;
2545 }
2546 
2547 void amdgpu_ras_global_ras_isr(struct amdgpu_device *adev)
2548 {
2549 	amdgpu_ras_check_supported(adev);
2550 	if (!adev->ras_hw_enabled)
2551 		return;
2552 
2553 	if (atomic_cmpxchg(&amdgpu_ras_in_intr, 0, 1) == 0) {
2554 		dev_info(adev->dev, "uncorrectable hardware error"
2555 			"(ERREVENT_ATHUB_INTERRUPT) detected!\n");
2556 
2557 		amdgpu_ras_reset_gpu(adev);
2558 	}
2559 }
2560 
2561 bool amdgpu_ras_need_emergency_restart(struct amdgpu_device *adev)
2562 {
2563 	if (adev->asic_type == CHIP_VEGA20 &&
2564 	    adev->pm.fw_version <= 0x283400) {
2565 		return !(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) &&
2566 				amdgpu_ras_intr_triggered();
2567 	}
2568 
2569 	return false;
2570 }
2571 
2572 void amdgpu_release_ras_context(struct amdgpu_device *adev)
2573 {
2574 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2575 
2576 	if (!con)
2577 		return;
2578 
2579 	if (!adev->ras_enabled && con->features & BIT(AMDGPU_RAS_BLOCK__GFX)) {
2580 		con->features &= ~BIT(AMDGPU_RAS_BLOCK__GFX);
2581 		amdgpu_ras_set_context(adev, NULL);
2582 		kfree(con);
2583 	}
2584 }
2585 
2586 #ifdef CONFIG_X86_MCE_AMD
2587 static struct amdgpu_device *find_adev(uint32_t node_id)
2588 {
2589 	int i;
2590 	struct amdgpu_device *adev = NULL;
2591 
2592 	for (i = 0; i < mce_adev_list.num_gpu; i++) {
2593 		adev = mce_adev_list.devs[i];
2594 
2595 		if (adev && adev->gmc.xgmi.connected_to_cpu &&
2596 		    adev->gmc.xgmi.physical_node_id == node_id)
2597 			break;
2598 		adev = NULL;
2599 	}
2600 
2601 	return adev;
2602 }
2603 
2604 #define GET_MCA_IPID_GPUID(m)	(((m) >> 44) & 0xF)
2605 #define GET_UMC_INST(m)		(((m) >> 21) & 0x7)
2606 #define GET_CHAN_INDEX(m)	((((m) >> 12) & 0x3) | (((m) >> 18) & 0x4))
2607 #define GPU_ID_OFFSET		8
2608 
2609 static int amdgpu_bad_page_notifier(struct notifier_block *nb,
2610 				    unsigned long val, void *data)
2611 {
2612 	struct mce *m = (struct mce *)data;
2613 	struct amdgpu_device *adev = NULL;
2614 	uint32_t gpu_id = 0;
2615 	uint32_t umc_inst = 0;
2616 	uint32_t ch_inst, channel_index = 0;
2617 	struct ras_err_data err_data = {0, 0, 0, NULL};
2618 	struct eeprom_table_record err_rec;
2619 	uint64_t retired_page;
2620 
2621 	/*
2622 	 * If the error was generated in UMC_V2, which belongs to GPU UMCs,
2623 	 * and error occurred in DramECC (Extended error code = 0) then only
2624 	 * process the error, else bail out.
2625 	 */
2626 	if (!m || !((smca_get_bank_type(m->bank) == SMCA_UMC_V2) &&
2627 		    (XEC(m->status, 0x3f) == 0x0)))
2628 		return NOTIFY_DONE;
2629 
2630 	/*
2631 	 * If it is correctable error, return.
2632 	 */
2633 	if (mce_is_correctable(m))
2634 		return NOTIFY_OK;
2635 
2636 	/*
2637 	 * GPU Id is offset by GPU_ID_OFFSET in MCA_IPID_UMC register.
2638 	 */
2639 	gpu_id = GET_MCA_IPID_GPUID(m->ipid) - GPU_ID_OFFSET;
2640 
2641 	adev = find_adev(gpu_id);
2642 	if (!adev) {
2643 		DRM_WARN("%s: Unable to find adev for gpu_id: %d\n", __func__,
2644 								gpu_id);
2645 		return NOTIFY_DONE;
2646 	}
2647 
2648 	/*
2649 	 * If it is uncorrectable error, then find out UMC instance and
2650 	 * channel index.
2651 	 */
2652 	umc_inst = GET_UMC_INST(m->ipid);
2653 	ch_inst = GET_CHAN_INDEX(m->ipid);
2654 
2655 	dev_info(adev->dev, "Uncorrectable error detected in UMC inst: %d, chan_idx: %d",
2656 			     umc_inst, ch_inst);
2657 
2658 	/*
2659 	 * Translate UMC channel address to Physical address
2660 	 */
2661 	channel_index =
2662 		adev->umc.channel_idx_tbl[umc_inst * adev->umc.channel_inst_num
2663 					  + ch_inst];
2664 
2665 	retired_page = ADDR_OF_8KB_BLOCK(m->addr) |
2666 			ADDR_OF_256B_BLOCK(channel_index) |
2667 			OFFSET_IN_256B_BLOCK(m->addr);
2668 
2669 	memset(&err_rec, 0x0, sizeof(struct eeprom_table_record));
2670 	err_data.err_addr = &err_rec;
2671 	amdgpu_umc_fill_error_record(&err_data, m->addr,
2672 			retired_page, channel_index, umc_inst);
2673 
2674 	if (amdgpu_bad_page_threshold != 0) {
2675 		amdgpu_ras_add_bad_pages(adev, err_data.err_addr,
2676 						err_data.err_addr_cnt);
2677 		amdgpu_ras_save_bad_pages(adev);
2678 	}
2679 
2680 	return NOTIFY_OK;
2681 }
2682 
2683 static struct notifier_block amdgpu_bad_page_nb = {
2684 	.notifier_call  = amdgpu_bad_page_notifier,
2685 	.priority       = MCE_PRIO_UC,
2686 };
2687 
2688 static void amdgpu_register_bad_pages_mca_notifier(struct amdgpu_device *adev)
2689 {
2690 	/*
2691 	 * Add the adev to the mce_adev_list.
2692 	 * During mode2 reset, amdgpu device is temporarily
2693 	 * removed from the mgpu_info list which can cause
2694 	 * page retirement to fail.
2695 	 * Use this list instead of mgpu_info to find the amdgpu
2696 	 * device on which the UMC error was reported.
2697 	 */
2698 	mce_adev_list.devs[mce_adev_list.num_gpu++] = adev;
2699 
2700 	/*
2701 	 * Register the x86 notifier only once
2702 	 * with MCE subsystem.
2703 	 */
2704 	if (notifier_registered == false) {
2705 		mce_register_decode_chain(&amdgpu_bad_page_nb);
2706 		notifier_registered = true;
2707 	}
2708 }
2709 #endif
2710 
2711 struct amdgpu_ras *amdgpu_ras_get_context(struct amdgpu_device *adev)
2712 {
2713 	if (!adev)
2714 		return NULL;
2715 
2716 	return adev->psp.ras_context.ras;
2717 }
2718 
2719 int amdgpu_ras_set_context(struct amdgpu_device *adev, struct amdgpu_ras *ras_con)
2720 {
2721 	if (!adev)
2722 		return -EINVAL;
2723 
2724 	adev->psp.ras_context.ras = ras_con;
2725 	return 0;
2726 }
2727 
2728 /* check if ras is supported on block, say, sdma, gfx */
2729 int amdgpu_ras_is_supported(struct amdgpu_device *adev,
2730 		unsigned int block)
2731 {
2732 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
2733 
2734 	if (block >= AMDGPU_RAS_BLOCK_COUNT)
2735 		return 0;
2736 	return ras && (adev->ras_enabled & (1 << block));
2737 }
2738 
2739 int amdgpu_ras_reset_gpu(struct amdgpu_device *adev)
2740 {
2741 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
2742 
2743 	if (atomic_cmpxchg(&ras->in_recovery, 0, 1) == 0)
2744 		schedule_work(&ras->recovery_work);
2745 	return 0;
2746 }
2747 
2748 
2749 /* Register each ip ras block into amdgpu ras */
2750 int amdgpu_ras_register_ras_block(struct amdgpu_device *adev,
2751 		struct amdgpu_ras_block_object *ras_block_obj)
2752 {
2753 	if (!adev || !ras_block_obj)
2754 		return -EINVAL;
2755 
2756 	if (!amdgpu_ras_asic_supported(adev))
2757 		return 0;
2758 
2759 	INIT_LIST_HEAD(&ras_block_obj->node);
2760 	list_add_tail(&ras_block_obj->node, &adev->ras_list);
2761 
2762 	return 0;
2763 }
2764