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