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 
31 #include "amdgpu.h"
32 #include "amdgpu_ras.h"
33 #include "amdgpu_atomfirmware.h"
34 #include "amdgpu_xgmi.h"
35 #include "ivsrcid/nbio/irqsrcs_nbif_7_4.h"
36 
37 static const char *RAS_FS_NAME = "ras";
38 
39 const char *ras_error_string[] = {
40 	"none",
41 	"parity",
42 	"single_correctable",
43 	"multi_uncorrectable",
44 	"poison",
45 };
46 
47 const char *ras_block_string[] = {
48 	"umc",
49 	"sdma",
50 	"gfx",
51 	"mmhub",
52 	"athub",
53 	"pcie_bif",
54 	"hdp",
55 	"xgmi_wafl",
56 	"df",
57 	"smn",
58 	"sem",
59 	"mp0",
60 	"mp1",
61 	"fuse",
62 };
63 
64 #define ras_err_str(i) (ras_error_string[ffs(i)])
65 #define ras_block_str(i) (ras_block_string[i])
66 
67 #define RAS_DEFAULT_FLAGS (AMDGPU_RAS_FLAG_INIT_BY_VBIOS)
68 
69 /* inject address is 52 bits */
70 #define	RAS_UMC_INJECT_ADDR_LIMIT	(0x1ULL << 52)
71 
72 /* typical ECC bad page rate(1 bad page per 100MB VRAM) */
73 #define RAS_BAD_PAGE_RATE		(100 * 1024 * 1024ULL)
74 
75 enum amdgpu_ras_retire_page_reservation {
76 	AMDGPU_RAS_RETIRE_PAGE_RESERVED,
77 	AMDGPU_RAS_RETIRE_PAGE_PENDING,
78 	AMDGPU_RAS_RETIRE_PAGE_FAULT,
79 };
80 
81 atomic_t amdgpu_ras_in_intr = ATOMIC_INIT(0);
82 
83 static bool amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
84 				uint64_t addr);
85 static bool amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
86 				uint64_t addr);
87 
88 void amdgpu_ras_set_error_query_ready(struct amdgpu_device *adev, bool ready)
89 {
90 	if (adev && amdgpu_ras_get_context(adev))
91 		amdgpu_ras_get_context(adev)->error_query_ready = ready;
92 }
93 
94 static bool amdgpu_ras_get_error_query_ready(struct amdgpu_device *adev)
95 {
96 	if (adev && amdgpu_ras_get_context(adev))
97 		return amdgpu_ras_get_context(adev)->error_query_ready;
98 
99 	return false;
100 }
101 
102 static ssize_t amdgpu_ras_debugfs_read(struct file *f, char __user *buf,
103 					size_t size, loff_t *pos)
104 {
105 	struct ras_manager *obj = (struct ras_manager *)file_inode(f)->i_private;
106 	struct ras_query_if info = {
107 		.head = obj->head,
108 	};
109 	ssize_t s;
110 	char val[128];
111 
112 	if (amdgpu_ras_query_error_status(obj->adev, &info))
113 		return -EINVAL;
114 
115 	s = snprintf(val, sizeof(val), "%s: %lu\n%s: %lu\n",
116 			"ue", info.ue_count,
117 			"ce", info.ce_count);
118 	if (*pos >= s)
119 		return 0;
120 
121 	s -= *pos;
122 	s = min_t(u64, s, size);
123 
124 
125 	if (copy_to_user(buf, &val[*pos], s))
126 		return -EINVAL;
127 
128 	*pos += s;
129 
130 	return s;
131 }
132 
133 static const struct file_operations amdgpu_ras_debugfs_ops = {
134 	.owner = THIS_MODULE,
135 	.read = amdgpu_ras_debugfs_read,
136 	.write = NULL,
137 	.llseek = default_llseek
138 };
139 
140 static int amdgpu_ras_find_block_id_by_name(const char *name, int *block_id)
141 {
142 	int i;
143 
144 	for (i = 0; i < ARRAY_SIZE(ras_block_string); i++) {
145 		*block_id = i;
146 		if (strcmp(name, ras_block_str(i)) == 0)
147 			return 0;
148 	}
149 	return -EINVAL;
150 }
151 
152 static int amdgpu_ras_debugfs_ctrl_parse_data(struct file *f,
153 		const char __user *buf, size_t size,
154 		loff_t *pos, struct ras_debug_if *data)
155 {
156 	ssize_t s = min_t(u64, 64, size);
157 	char str[65];
158 	char block_name[33];
159 	char err[9] = "ue";
160 	int op = -1;
161 	int block_id;
162 	uint32_t sub_block;
163 	u64 address, value;
164 
165 	if (*pos)
166 		return -EINVAL;
167 	*pos = size;
168 
169 	memset(str, 0, sizeof(str));
170 	memset(data, 0, sizeof(*data));
171 
172 	if (copy_from_user(str, buf, s))
173 		return -EINVAL;
174 
175 	if (sscanf(str, "disable %32s", block_name) == 1)
176 		op = 0;
177 	else if (sscanf(str, "enable %32s %8s", block_name, err) == 2)
178 		op = 1;
179 	else if (sscanf(str, "inject %32s %8s", block_name, err) == 2)
180 		op = 2;
181 	else if (str[0] && str[1] && str[2] && str[3])
182 		/* ascii string, but commands are not matched. */
183 		return -EINVAL;
184 
185 	if (op != -1) {
186 		if (amdgpu_ras_find_block_id_by_name(block_name, &block_id))
187 			return -EINVAL;
188 
189 		data->head.block = block_id;
190 		/* only ue and ce errors are supported */
191 		if (!memcmp("ue", err, 2))
192 			data->head.type = AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE;
193 		else if (!memcmp("ce", err, 2))
194 			data->head.type = AMDGPU_RAS_ERROR__SINGLE_CORRECTABLE;
195 		else
196 			return -EINVAL;
197 
198 		data->op = op;
199 
200 		if (op == 2) {
201 			if (sscanf(str, "%*s %*s %*s %u %llu %llu",
202 						&sub_block, &address, &value) != 3)
203 				if (sscanf(str, "%*s %*s %*s 0x%x 0x%llx 0x%llx",
204 							&sub_block, &address, &value) != 3)
205 					return -EINVAL;
206 			data->head.sub_block_index = sub_block;
207 			data->inject.address = address;
208 			data->inject.value = value;
209 		}
210 	} else {
211 		if (size < sizeof(*data))
212 			return -EINVAL;
213 
214 		if (copy_from_user(data, buf, sizeof(*data)))
215 			return -EINVAL;
216 	}
217 
218 	return 0;
219 }
220 
221 /**
222  * DOC: AMDGPU RAS debugfs control interface
223  *
224  * It accepts struct ras_debug_if who has two members.
225  *
226  * First member: ras_debug_if::head or ras_debug_if::inject.
227  *
228  * head is used to indicate which IP block will be under control.
229  *
230  * head has four members, they are block, type, sub_block_index, name.
231  * block: which IP will be under control.
232  * type: what kind of error will be enabled/disabled/injected.
233  * sub_block_index: some IPs have subcomponets. say, GFX, sDMA.
234  * name: the name of IP.
235  *
236  * inject has two more members than head, they are address, value.
237  * As their names indicate, inject operation will write the
238  * value to the address.
239  *
240  * The second member: struct ras_debug_if::op.
241  * It has three kinds of operations.
242  *
243  * - 0: disable RAS on the block. Take ::head as its data.
244  * - 1: enable RAS on the block. Take ::head as its data.
245  * - 2: inject errors on the block. Take ::inject as its data.
246  *
247  * How to use the interface?
248  *
249  * Programs
250  *
251  * Copy the struct ras_debug_if in your codes and initialize it.
252  * Write the struct to the control node.
253  *
254  * Shells
255  *
256  * .. code-block:: bash
257  *
258  *	echo op block [error [sub_block address value]] > .../ras/ras_ctrl
259  *
260  * Parameters:
261  *
262  * op: disable, enable, inject
263  *	disable: only block is needed
264  *	enable: block and error are needed
265  *	inject: error, address, value are needed
266  * block: umc, sdma, gfx, .........
267  *	see ras_block_string[] for details
268  * error: ue, ce
269  *	ue: multi_uncorrectable
270  *	ce: single_correctable
271  * sub_block:
272  *	sub block index, pass 0 if there is no sub block
273  *
274  * here are some examples for bash commands:
275  *
276  * .. code-block:: bash
277  *
278  *	echo inject umc ue 0x0 0x0 0x0 > /sys/kernel/debug/dri/0/ras/ras_ctrl
279  *	echo inject umc ce 0 0 0 > /sys/kernel/debug/dri/0/ras/ras_ctrl
280  *	echo disable umc > /sys/kernel/debug/dri/0/ras/ras_ctrl
281  *
282  * How to check the result?
283  *
284  * For disable/enable, please check ras features at
285  * /sys/class/drm/card[0/1/2...]/device/ras/features
286  *
287  * For inject, please check corresponding err count at
288  * /sys/class/drm/card[0/1/2...]/device/ras/[gfx/sdma/...]_err_count
289  *
290  * .. note::
291  *	Operations are only allowed on blocks which are supported.
292  *	Please check ras mask at /sys/module/amdgpu/parameters/ras_mask
293  *	to see which blocks support RAS on a particular asic.
294  *
295  */
296 static ssize_t amdgpu_ras_debugfs_ctrl_write(struct file *f, const char __user *buf,
297 		size_t size, loff_t *pos)
298 {
299 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
300 	struct ras_debug_if data;
301 	int ret = 0;
302 
303 	if (!amdgpu_ras_get_error_query_ready(adev)) {
304 		dev_warn(adev->dev, "RAS WARN: error injection "
305 				"currently inaccessible\n");
306 		return size;
307 	}
308 
309 	ret = amdgpu_ras_debugfs_ctrl_parse_data(f, buf, size, pos, &data);
310 	if (ret)
311 		return -EINVAL;
312 
313 	if (!amdgpu_ras_is_supported(adev, data.head.block))
314 		return -EINVAL;
315 
316 	switch (data.op) {
317 	case 0:
318 		ret = amdgpu_ras_feature_enable(adev, &data.head, 0);
319 		break;
320 	case 1:
321 		ret = amdgpu_ras_feature_enable(adev, &data.head, 1);
322 		break;
323 	case 2:
324 		if ((data.inject.address >= adev->gmc.mc_vram_size) ||
325 		    (data.inject.address >= RAS_UMC_INJECT_ADDR_LIMIT)) {
326 			dev_warn(adev->dev, "RAS WARN: input address "
327 					"0x%llx is invalid.",
328 					data.inject.address);
329 			ret = -EINVAL;
330 			break;
331 		}
332 
333 		/* umc ce/ue error injection for a bad page is not allowed */
334 		if ((data.head.block == AMDGPU_RAS_BLOCK__UMC) &&
335 		    amdgpu_ras_check_bad_page(adev, data.inject.address)) {
336 			dev_warn(adev->dev, "RAS WARN: 0x%llx has been marked "
337 					"as bad before error injection!\n",
338 					data.inject.address);
339 			break;
340 		}
341 
342 		/* data.inject.address is offset instead of absolute gpu address */
343 		ret = amdgpu_ras_error_inject(adev, &data.inject);
344 		break;
345 	default:
346 		ret = -EINVAL;
347 		break;
348 	}
349 
350 	if (ret)
351 		return -EINVAL;
352 
353 	return size;
354 }
355 
356 /**
357  * DOC: AMDGPU RAS debugfs EEPROM table reset interface
358  *
359  * Some boards contain an EEPROM which is used to persistently store a list of
360  * bad pages which experiences ECC errors in vram.  This interface provides
361  * a way to reset the EEPROM, e.g., after testing error injection.
362  *
363  * Usage:
364  *
365  * .. code-block:: bash
366  *
367  *	echo 1 > ../ras/ras_eeprom_reset
368  *
369  * will reset EEPROM table to 0 entries.
370  *
371  */
372 static ssize_t amdgpu_ras_debugfs_eeprom_write(struct file *f, const char __user *buf,
373 		size_t size, loff_t *pos)
374 {
375 	struct amdgpu_device *adev =
376 		(struct amdgpu_device *)file_inode(f)->i_private;
377 	int ret;
378 
379 	ret = amdgpu_ras_eeprom_reset_table(
380 			&(amdgpu_ras_get_context(adev)->eeprom_control));
381 
382 	if (ret == 1) {
383 		amdgpu_ras_get_context(adev)->flags = RAS_DEFAULT_FLAGS;
384 		return size;
385 	} else {
386 		return -EIO;
387 	}
388 }
389 
390 static const struct file_operations amdgpu_ras_debugfs_ctrl_ops = {
391 	.owner = THIS_MODULE,
392 	.read = NULL,
393 	.write = amdgpu_ras_debugfs_ctrl_write,
394 	.llseek = default_llseek
395 };
396 
397 static const struct file_operations amdgpu_ras_debugfs_eeprom_ops = {
398 	.owner = THIS_MODULE,
399 	.read = NULL,
400 	.write = amdgpu_ras_debugfs_eeprom_write,
401 	.llseek = default_llseek
402 };
403 
404 /**
405  * DOC: AMDGPU RAS sysfs Error Count Interface
406  *
407  * It allows the user to read the error count for each IP block on the gpu through
408  * /sys/class/drm/card[0/1/2...]/device/ras/[gfx/sdma/...]_err_count
409  *
410  * It outputs the multiple lines which report the uncorrected (ue) and corrected
411  * (ce) error counts.
412  *
413  * The format of one line is below,
414  *
415  * [ce|ue]: count
416  *
417  * Example:
418  *
419  * .. code-block:: bash
420  *
421  *	ue: 0
422  *	ce: 1
423  *
424  */
425 static ssize_t amdgpu_ras_sysfs_read(struct device *dev,
426 		struct device_attribute *attr, char *buf)
427 {
428 	struct ras_manager *obj = container_of(attr, struct ras_manager, sysfs_attr);
429 	struct ras_query_if info = {
430 		.head = obj->head,
431 	};
432 
433 	if (!amdgpu_ras_get_error_query_ready(obj->adev))
434 		return snprintf(buf, PAGE_SIZE,
435 				"Query currently inaccessible\n");
436 
437 	if (amdgpu_ras_query_error_status(obj->adev, &info))
438 		return -EINVAL;
439 
440 	return snprintf(buf, PAGE_SIZE, "%s: %lu\n%s: %lu\n",
441 			"ue", info.ue_count,
442 			"ce", info.ce_count);
443 }
444 
445 /* obj begin */
446 
447 #define get_obj(obj) do { (obj)->use++; } while (0)
448 #define alive_obj(obj) ((obj)->use)
449 
450 static inline void put_obj(struct ras_manager *obj)
451 {
452 	if (obj && --obj->use == 0)
453 		list_del(&obj->node);
454 	if (obj && obj->use < 0) {
455 		 DRM_ERROR("RAS ERROR: Unbalance obj(%s) use\n", obj->head.name);
456 	}
457 }
458 
459 /* make one obj and return it. */
460 static struct ras_manager *amdgpu_ras_create_obj(struct amdgpu_device *adev,
461 		struct ras_common_if *head)
462 {
463 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
464 	struct ras_manager *obj;
465 
466 	if (!adev->ras_features || !con)
467 		return NULL;
468 
469 	if (head->block >= AMDGPU_RAS_BLOCK_COUNT)
470 		return NULL;
471 
472 	obj = &con->objs[head->block];
473 	/* already exist. return obj? */
474 	if (alive_obj(obj))
475 		return NULL;
476 
477 	obj->head = *head;
478 	obj->adev = adev;
479 	list_add(&obj->node, &con->head);
480 	get_obj(obj);
481 
482 	return obj;
483 }
484 
485 /* return an obj equal to head, or the first when head is NULL */
486 struct ras_manager *amdgpu_ras_find_obj(struct amdgpu_device *adev,
487 		struct ras_common_if *head)
488 {
489 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
490 	struct ras_manager *obj;
491 	int i;
492 
493 	if (!adev->ras_features || !con)
494 		return NULL;
495 
496 	if (head) {
497 		if (head->block >= AMDGPU_RAS_BLOCK_COUNT)
498 			return NULL;
499 
500 		obj = &con->objs[head->block];
501 
502 		if (alive_obj(obj)) {
503 			WARN_ON(head->block != obj->head.block);
504 			return obj;
505 		}
506 	} else {
507 		for (i = 0; i < AMDGPU_RAS_BLOCK_COUNT; i++) {
508 			obj = &con->objs[i];
509 			if (alive_obj(obj)) {
510 				WARN_ON(i != obj->head.block);
511 				return obj;
512 			}
513 		}
514 	}
515 
516 	return NULL;
517 }
518 /* obj end */
519 
520 static void amdgpu_ras_parse_status_code(struct amdgpu_device *adev,
521 					 const char* invoke_type,
522 					 const char* block_name,
523 					 enum ta_ras_status ret)
524 {
525 	switch (ret) {
526 	case TA_RAS_STATUS__SUCCESS:
527 		return;
528 	case TA_RAS_STATUS__ERROR_RAS_NOT_AVAILABLE:
529 		dev_warn(adev->dev,
530 			"RAS WARN: %s %s currently unavailable\n",
531 			invoke_type,
532 			block_name);
533 		break;
534 	default:
535 		dev_err(adev->dev,
536 			"RAS ERROR: %s %s error failed ret 0x%X\n",
537 			invoke_type,
538 			block_name,
539 			ret);
540 	}
541 }
542 
543 /* feature ctl begin */
544 static int amdgpu_ras_is_feature_allowed(struct amdgpu_device *adev,
545 		struct ras_common_if *head)
546 {
547 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
548 
549 	return con->hw_supported & BIT(head->block);
550 }
551 
552 static int amdgpu_ras_is_feature_enabled(struct amdgpu_device *adev,
553 		struct ras_common_if *head)
554 {
555 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
556 
557 	return con->features & BIT(head->block);
558 }
559 
560 /*
561  * if obj is not created, then create one.
562  * set feature enable flag.
563  */
564 static int __amdgpu_ras_feature_enable(struct amdgpu_device *adev,
565 		struct ras_common_if *head, int enable)
566 {
567 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
568 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
569 
570 	/* If hardware does not support ras, then do not create obj.
571 	 * But if hardware support ras, we can create the obj.
572 	 * Ras framework checks con->hw_supported to see if it need do
573 	 * corresponding initialization.
574 	 * IP checks con->support to see if it need disable ras.
575 	 */
576 	if (!amdgpu_ras_is_feature_allowed(adev, head))
577 		return 0;
578 	if (!(!!enable ^ !!amdgpu_ras_is_feature_enabled(adev, head)))
579 		return 0;
580 
581 	if (enable) {
582 		if (!obj) {
583 			obj = amdgpu_ras_create_obj(adev, head);
584 			if (!obj)
585 				return -EINVAL;
586 		} else {
587 			/* In case we create obj somewhere else */
588 			get_obj(obj);
589 		}
590 		con->features |= BIT(head->block);
591 	} else {
592 		if (obj && amdgpu_ras_is_feature_enabled(adev, head)) {
593 			/* skip clean gfx ras context feature for VEGA20 Gaming.
594 			 * will clean later
595 			 */
596 			if (!(!adev->ras_features && con->features & BIT(AMDGPU_RAS_BLOCK__GFX)))
597 				con->features &= ~BIT(head->block);
598 			put_obj(obj);
599 		}
600 	}
601 
602 	return 0;
603 }
604 
605 /* wrapper of psp_ras_enable_features */
606 int amdgpu_ras_feature_enable(struct amdgpu_device *adev,
607 		struct ras_common_if *head, bool enable)
608 {
609 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
610 	union ta_ras_cmd_input *info;
611 	int ret;
612 
613 	if (!con)
614 		return -EINVAL;
615 
616 	info = kzalloc(sizeof(union ta_ras_cmd_input), GFP_KERNEL);
617 	if (!info)
618 		return -ENOMEM;
619 
620 	if (!enable) {
621 		info->disable_features = (struct ta_ras_disable_features_input) {
622 			.block_id =  amdgpu_ras_block_to_ta(head->block),
623 			.error_type = amdgpu_ras_error_to_ta(head->type),
624 		};
625 	} else {
626 		info->enable_features = (struct ta_ras_enable_features_input) {
627 			.block_id =  amdgpu_ras_block_to_ta(head->block),
628 			.error_type = amdgpu_ras_error_to_ta(head->type),
629 		};
630 	}
631 
632 	/* Do not enable if it is not allowed. */
633 	WARN_ON(enable && !amdgpu_ras_is_feature_allowed(adev, head));
634 	/* Are we alerady in that state we are going to set? */
635 	if (!(!!enable ^ !!amdgpu_ras_is_feature_enabled(adev, head))) {
636 		ret = 0;
637 		goto out;
638 	}
639 
640 	if (!amdgpu_ras_intr_triggered()) {
641 		ret = psp_ras_enable_features(&adev->psp, info, enable);
642 		if (ret) {
643 			amdgpu_ras_parse_status_code(adev,
644 						     enable ? "enable":"disable",
645 						     ras_block_str(head->block),
646 						    (enum ta_ras_status)ret);
647 			if (ret == TA_RAS_STATUS__RESET_NEEDED)
648 				ret = -EAGAIN;
649 			else
650 				ret = -EINVAL;
651 
652 			goto out;
653 		}
654 	}
655 
656 	/* setup the obj */
657 	__amdgpu_ras_feature_enable(adev, head, enable);
658 	ret = 0;
659 out:
660 	kfree(info);
661 	return ret;
662 }
663 
664 /* Only used in device probe stage and called only once. */
665 int amdgpu_ras_feature_enable_on_boot(struct amdgpu_device *adev,
666 		struct ras_common_if *head, bool enable)
667 {
668 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
669 	int ret;
670 
671 	if (!con)
672 		return -EINVAL;
673 
674 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
675 		if (enable) {
676 			/* There is no harm to issue a ras TA cmd regardless of
677 			 * the currecnt ras state.
678 			 * If current state == target state, it will do nothing
679 			 * But sometimes it requests driver to reset and repost
680 			 * with error code -EAGAIN.
681 			 */
682 			ret = amdgpu_ras_feature_enable(adev, head, 1);
683 			/* With old ras TA, we might fail to enable ras.
684 			 * Log it and just setup the object.
685 			 * TODO need remove this WA in the future.
686 			 */
687 			if (ret == -EINVAL) {
688 				ret = __amdgpu_ras_feature_enable(adev, head, 1);
689 				if (!ret)
690 					dev_info(adev->dev,
691 						"RAS INFO: %s setup object\n",
692 						ras_block_str(head->block));
693 			}
694 		} else {
695 			/* setup the object then issue a ras TA disable cmd.*/
696 			ret = __amdgpu_ras_feature_enable(adev, head, 1);
697 			if (ret)
698 				return ret;
699 
700 			/* gfx block ras dsiable cmd must send to ras-ta */
701 			if (head->block == AMDGPU_RAS_BLOCK__GFX)
702 				con->features |= BIT(head->block);
703 
704 			ret = amdgpu_ras_feature_enable(adev, head, 0);
705 		}
706 	} else
707 		ret = amdgpu_ras_feature_enable(adev, head, enable);
708 
709 	return ret;
710 }
711 
712 static int amdgpu_ras_disable_all_features(struct amdgpu_device *adev,
713 		bool bypass)
714 {
715 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
716 	struct ras_manager *obj, *tmp;
717 
718 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
719 		/* bypass psp.
720 		 * aka just release the obj and corresponding flags
721 		 */
722 		if (bypass) {
723 			if (__amdgpu_ras_feature_enable(adev, &obj->head, 0))
724 				break;
725 		} else {
726 			if (amdgpu_ras_feature_enable(adev, &obj->head, 0))
727 				break;
728 		}
729 	}
730 
731 	return con->features;
732 }
733 
734 static int amdgpu_ras_enable_all_features(struct amdgpu_device *adev,
735 		bool bypass)
736 {
737 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
738 	int ras_block_count = AMDGPU_RAS_BLOCK_COUNT;
739 	int i;
740 	const enum amdgpu_ras_error_type default_ras_type =
741 		AMDGPU_RAS_ERROR__NONE;
742 
743 	for (i = 0; i < ras_block_count; i++) {
744 		struct ras_common_if head = {
745 			.block = i,
746 			.type = default_ras_type,
747 			.sub_block_index = 0,
748 		};
749 		strcpy(head.name, ras_block_str(i));
750 		if (bypass) {
751 			/*
752 			 * bypass psp. vbios enable ras for us.
753 			 * so just create the obj
754 			 */
755 			if (__amdgpu_ras_feature_enable(adev, &head, 1))
756 				break;
757 		} else {
758 			if (amdgpu_ras_feature_enable(adev, &head, 1))
759 				break;
760 		}
761 	}
762 
763 	return con->features;
764 }
765 /* feature ctl end */
766 
767 /* query/inject/cure begin */
768 int amdgpu_ras_query_error_status(struct amdgpu_device *adev,
769 	struct ras_query_if *info)
770 {
771 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
772 	struct ras_err_data err_data = {0, 0, 0, NULL};
773 	int i;
774 
775 	if (!obj)
776 		return -EINVAL;
777 
778 	switch (info->head.block) {
779 	case AMDGPU_RAS_BLOCK__UMC:
780 		if (adev->umc.funcs->query_ras_error_count)
781 			adev->umc.funcs->query_ras_error_count(adev, &err_data);
782 		/* umc query_ras_error_address is also responsible for clearing
783 		 * error status
784 		 */
785 		if (adev->umc.funcs->query_ras_error_address)
786 			adev->umc.funcs->query_ras_error_address(adev, &err_data);
787 		break;
788 	case AMDGPU_RAS_BLOCK__SDMA:
789 		if (adev->sdma.funcs->query_ras_error_count) {
790 			for (i = 0; i < adev->sdma.num_instances; i++)
791 				adev->sdma.funcs->query_ras_error_count(adev, i,
792 									&err_data);
793 		}
794 		break;
795 	case AMDGPU_RAS_BLOCK__GFX:
796 		if (adev->gfx.funcs->query_ras_error_count)
797 			adev->gfx.funcs->query_ras_error_count(adev, &err_data);
798 
799 		if (adev->gfx.funcs->query_ras_error_status)
800 			adev->gfx.funcs->query_ras_error_status(adev);
801 		break;
802 	case AMDGPU_RAS_BLOCK__MMHUB:
803 		if (adev->mmhub.funcs->query_ras_error_count)
804 			adev->mmhub.funcs->query_ras_error_count(adev, &err_data);
805 
806 		if (adev->mmhub.funcs->query_ras_error_status)
807 			adev->mmhub.funcs->query_ras_error_status(adev);
808 		break;
809 	case AMDGPU_RAS_BLOCK__PCIE_BIF:
810 		if (adev->nbio.funcs->query_ras_error_count)
811 			adev->nbio.funcs->query_ras_error_count(adev, &err_data);
812 		break;
813 	case AMDGPU_RAS_BLOCK__XGMI_WAFL:
814 		amdgpu_xgmi_query_ras_error_count(adev, &err_data);
815 		break;
816 	default:
817 		break;
818 	}
819 
820 	obj->err_data.ue_count += err_data.ue_count;
821 	obj->err_data.ce_count += err_data.ce_count;
822 
823 	info->ue_count = obj->err_data.ue_count;
824 	info->ce_count = obj->err_data.ce_count;
825 
826 	if (err_data.ce_count) {
827 		dev_info(adev->dev, "%ld correctable hardware errors "
828 					"detected in %s block, no user "
829 					"action is needed.\n",
830 					obj->err_data.ce_count,
831 					ras_block_str(info->head.block));
832 	}
833 	if (err_data.ue_count) {
834 		dev_info(adev->dev, "%ld uncorrectable hardware errors "
835 					"detected in %s block\n",
836 					obj->err_data.ue_count,
837 					ras_block_str(info->head.block));
838 	}
839 
840 	return 0;
841 }
842 
843 int amdgpu_ras_reset_error_status(struct amdgpu_device *adev,
844 		enum amdgpu_ras_block block)
845 {
846 	if (!amdgpu_ras_is_supported(adev, block))
847 		return -EINVAL;
848 
849 	switch (block) {
850 	case AMDGPU_RAS_BLOCK__GFX:
851 		if (adev->gfx.funcs->reset_ras_error_count)
852 			adev->gfx.funcs->reset_ras_error_count(adev);
853 
854 		if (adev->gfx.funcs->reset_ras_error_status)
855 			adev->gfx.funcs->reset_ras_error_status(adev);
856 		break;
857 	case AMDGPU_RAS_BLOCK__MMHUB:
858 		if (adev->mmhub.funcs->reset_ras_error_count)
859 			adev->mmhub.funcs->reset_ras_error_count(adev);
860 		break;
861 	case AMDGPU_RAS_BLOCK__SDMA:
862 		if (adev->sdma.funcs->reset_ras_error_count)
863 			adev->sdma.funcs->reset_ras_error_count(adev);
864 		break;
865 	default:
866 		break;
867 	}
868 
869 	return 0;
870 }
871 
872 /* Trigger XGMI/WAFL error */
873 static int amdgpu_ras_error_inject_xgmi(struct amdgpu_device *adev,
874 				 struct ta_ras_trigger_error_input *block_info)
875 {
876 	int ret;
877 
878 	if (amdgpu_dpm_set_df_cstate(adev, DF_CSTATE_DISALLOW))
879 		dev_warn(adev->dev, "Failed to disallow df cstate");
880 
881 	if (amdgpu_dpm_allow_xgmi_power_down(adev, false))
882 		dev_warn(adev->dev, "Failed to disallow XGMI power down");
883 
884 	ret = psp_ras_trigger_error(&adev->psp, block_info);
885 
886 	if (amdgpu_ras_intr_triggered())
887 		return ret;
888 
889 	if (amdgpu_dpm_allow_xgmi_power_down(adev, true))
890 		dev_warn(adev->dev, "Failed to allow XGMI power down");
891 
892 	if (amdgpu_dpm_set_df_cstate(adev, DF_CSTATE_ALLOW))
893 		dev_warn(adev->dev, "Failed to allow df cstate");
894 
895 	return ret;
896 }
897 
898 /* wrapper of psp_ras_trigger_error */
899 int amdgpu_ras_error_inject(struct amdgpu_device *adev,
900 		struct ras_inject_if *info)
901 {
902 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
903 	struct ta_ras_trigger_error_input block_info = {
904 		.block_id =  amdgpu_ras_block_to_ta(info->head.block),
905 		.inject_error_type = amdgpu_ras_error_to_ta(info->head.type),
906 		.sub_block_index = info->head.sub_block_index,
907 		.address = info->address,
908 		.value = info->value,
909 	};
910 	int ret = 0;
911 
912 	if (!obj)
913 		return -EINVAL;
914 
915 	/* Calculate XGMI relative offset */
916 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
917 		block_info.address =
918 			amdgpu_xgmi_get_relative_phy_addr(adev,
919 							  block_info.address);
920 	}
921 
922 	switch (info->head.block) {
923 	case AMDGPU_RAS_BLOCK__GFX:
924 		if (adev->gfx.funcs->ras_error_inject)
925 			ret = adev->gfx.funcs->ras_error_inject(adev, info);
926 		else
927 			ret = -EINVAL;
928 		break;
929 	case AMDGPU_RAS_BLOCK__UMC:
930 	case AMDGPU_RAS_BLOCK__MMHUB:
931 	case AMDGPU_RAS_BLOCK__PCIE_BIF:
932 		ret = psp_ras_trigger_error(&adev->psp, &block_info);
933 		break;
934 	case AMDGPU_RAS_BLOCK__XGMI_WAFL:
935 		ret = amdgpu_ras_error_inject_xgmi(adev, &block_info);
936 		break;
937 	default:
938 		dev_info(adev->dev, "%s error injection is not supported yet\n",
939 			 ras_block_str(info->head.block));
940 		ret = -EINVAL;
941 	}
942 
943 	amdgpu_ras_parse_status_code(adev,
944 				     "inject",
945 				     ras_block_str(info->head.block),
946 				     (enum ta_ras_status)ret);
947 
948 	return ret;
949 }
950 
951 /* get the total error counts on all IPs */
952 unsigned long amdgpu_ras_query_error_count(struct amdgpu_device *adev,
953 		bool is_ce)
954 {
955 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
956 	struct ras_manager *obj;
957 	struct ras_err_data data = {0, 0};
958 
959 	if (!adev->ras_features || !con)
960 		return 0;
961 
962 	list_for_each_entry(obj, &con->head, node) {
963 		struct ras_query_if info = {
964 			.head = obj->head,
965 		};
966 
967 		if (amdgpu_ras_query_error_status(adev, &info))
968 			return 0;
969 
970 		data.ce_count += info.ce_count;
971 		data.ue_count += info.ue_count;
972 	}
973 
974 	return is_ce ? data.ce_count : data.ue_count;
975 }
976 /* query/inject/cure end */
977 
978 
979 /* sysfs begin */
980 
981 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
982 		struct ras_badpage **bps, unsigned int *count);
983 
984 static char *amdgpu_ras_badpage_flags_str(unsigned int flags)
985 {
986 	switch (flags) {
987 	case AMDGPU_RAS_RETIRE_PAGE_RESERVED:
988 		return "R";
989 	case AMDGPU_RAS_RETIRE_PAGE_PENDING:
990 		return "P";
991 	case AMDGPU_RAS_RETIRE_PAGE_FAULT:
992 	default:
993 		return "F";
994 	}
995 }
996 
997 /**
998  * DOC: AMDGPU RAS sysfs gpu_vram_bad_pages Interface
999  *
1000  * It allows user to read the bad pages of vram on the gpu through
1001  * /sys/class/drm/card[0/1/2...]/device/ras/gpu_vram_bad_pages
1002  *
1003  * It outputs multiple lines, and each line stands for one gpu page.
1004  *
1005  * The format of one line is below,
1006  * gpu pfn : gpu page size : flags
1007  *
1008  * gpu pfn and gpu page size are printed in hex format.
1009  * flags can be one of below character,
1010  *
1011  * R: reserved, this gpu page is reserved and not able to use.
1012  *
1013  * P: pending for reserve, this gpu page is marked as bad, will be reserved
1014  * in next window of page_reserve.
1015  *
1016  * F: unable to reserve. this gpu page can't be reserved due to some reasons.
1017  *
1018  * Examples:
1019  *
1020  * .. code-block:: bash
1021  *
1022  *	0x00000001 : 0x00001000 : R
1023  *	0x00000002 : 0x00001000 : P
1024  *
1025  */
1026 
1027 static ssize_t amdgpu_ras_sysfs_badpages_read(struct file *f,
1028 		struct kobject *kobj, struct bin_attribute *attr,
1029 		char *buf, loff_t ppos, size_t count)
1030 {
1031 	struct amdgpu_ras *con =
1032 		container_of(attr, struct amdgpu_ras, badpages_attr);
1033 	struct amdgpu_device *adev = con->adev;
1034 	const unsigned int element_size =
1035 		sizeof("0xabcdabcd : 0x12345678 : R\n") - 1;
1036 	unsigned int start = div64_ul(ppos + element_size - 1, element_size);
1037 	unsigned int end = div64_ul(ppos + count - 1, element_size);
1038 	ssize_t s = 0;
1039 	struct ras_badpage *bps = NULL;
1040 	unsigned int bps_count = 0;
1041 
1042 	memset(buf, 0, count);
1043 
1044 	if (amdgpu_ras_badpages_read(adev, &bps, &bps_count))
1045 		return 0;
1046 
1047 	for (; start < end && start < bps_count; start++)
1048 		s += scnprintf(&buf[s], element_size + 1,
1049 				"0x%08x : 0x%08x : %1s\n",
1050 				bps[start].bp,
1051 				bps[start].size,
1052 				amdgpu_ras_badpage_flags_str(bps[start].flags));
1053 
1054 	kfree(bps);
1055 
1056 	return s;
1057 }
1058 
1059 static ssize_t amdgpu_ras_sysfs_features_read(struct device *dev,
1060 		struct device_attribute *attr, char *buf)
1061 {
1062 	struct amdgpu_ras *con =
1063 		container_of(attr, struct amdgpu_ras, features_attr);
1064 
1065 	return scnprintf(buf, PAGE_SIZE, "feature mask: 0x%x\n", con->features);
1066 }
1067 
1068 static void amdgpu_ras_sysfs_remove_bad_page_node(struct amdgpu_device *adev)
1069 {
1070 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1071 
1072 	sysfs_remove_file_from_group(&adev->dev->kobj,
1073 				&con->badpages_attr.attr,
1074 				RAS_FS_NAME);
1075 }
1076 
1077 static int amdgpu_ras_sysfs_remove_feature_node(struct amdgpu_device *adev)
1078 {
1079 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1080 	struct attribute *attrs[] = {
1081 		&con->features_attr.attr,
1082 		NULL
1083 	};
1084 	struct attribute_group group = {
1085 		.name = RAS_FS_NAME,
1086 		.attrs = attrs,
1087 	};
1088 
1089 	sysfs_remove_group(&adev->dev->kobj, &group);
1090 
1091 	return 0;
1092 }
1093 
1094 int amdgpu_ras_sysfs_create(struct amdgpu_device *adev,
1095 		struct ras_fs_if *head)
1096 {
1097 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &head->head);
1098 
1099 	if (!obj || obj->attr_inuse)
1100 		return -EINVAL;
1101 
1102 	get_obj(obj);
1103 
1104 	memcpy(obj->fs_data.sysfs_name,
1105 			head->sysfs_name,
1106 			sizeof(obj->fs_data.sysfs_name));
1107 
1108 	obj->sysfs_attr = (struct device_attribute){
1109 		.attr = {
1110 			.name = obj->fs_data.sysfs_name,
1111 			.mode = S_IRUGO,
1112 		},
1113 			.show = amdgpu_ras_sysfs_read,
1114 	};
1115 	sysfs_attr_init(&obj->sysfs_attr.attr);
1116 
1117 	if (sysfs_add_file_to_group(&adev->dev->kobj,
1118 				&obj->sysfs_attr.attr,
1119 				RAS_FS_NAME)) {
1120 		put_obj(obj);
1121 		return -EINVAL;
1122 	}
1123 
1124 	obj->attr_inuse = 1;
1125 
1126 	return 0;
1127 }
1128 
1129 int amdgpu_ras_sysfs_remove(struct amdgpu_device *adev,
1130 		struct ras_common_if *head)
1131 {
1132 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, head);
1133 
1134 	if (!obj || !obj->attr_inuse)
1135 		return -EINVAL;
1136 
1137 	sysfs_remove_file_from_group(&adev->dev->kobj,
1138 				&obj->sysfs_attr.attr,
1139 				RAS_FS_NAME);
1140 	obj->attr_inuse = 0;
1141 	put_obj(obj);
1142 
1143 	return 0;
1144 }
1145 
1146 static int amdgpu_ras_sysfs_remove_all(struct amdgpu_device *adev)
1147 {
1148 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1149 	struct ras_manager *obj, *tmp;
1150 
1151 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
1152 		amdgpu_ras_sysfs_remove(adev, &obj->head);
1153 	}
1154 
1155 	if (amdgpu_bad_page_threshold != 0)
1156 		amdgpu_ras_sysfs_remove_bad_page_node(adev);
1157 
1158 	amdgpu_ras_sysfs_remove_feature_node(adev);
1159 
1160 	return 0;
1161 }
1162 /* sysfs end */
1163 
1164 /**
1165  * DOC: AMDGPU RAS Reboot Behavior for Unrecoverable Errors
1166  *
1167  * Normally when there is an uncorrectable error, the driver will reset
1168  * the GPU to recover.  However, in the event of an unrecoverable error,
1169  * the driver provides an interface to reboot the system automatically
1170  * in that event.
1171  *
1172  * The following file in debugfs provides that interface:
1173  * /sys/kernel/debug/dri/[0/1/2...]/ras/auto_reboot
1174  *
1175  * Usage:
1176  *
1177  * .. code-block:: bash
1178  *
1179  *	echo true > .../ras/auto_reboot
1180  *
1181  */
1182 /* debugfs begin */
1183 static struct dentry *amdgpu_ras_debugfs_create_ctrl_node(struct amdgpu_device *adev)
1184 {
1185 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1186 	struct dentry *dir;
1187 	struct drm_minor *minor = adev_to_drm(adev)->primary;
1188 
1189 	dir = debugfs_create_dir(RAS_FS_NAME, minor->debugfs_root);
1190 	debugfs_create_file("ras_ctrl", S_IWUGO | S_IRUGO, dir, adev,
1191 			    &amdgpu_ras_debugfs_ctrl_ops);
1192 	debugfs_create_file("ras_eeprom_reset", S_IWUGO | S_IRUGO, dir, adev,
1193 			    &amdgpu_ras_debugfs_eeprom_ops);
1194 
1195 	/*
1196 	 * After one uncorrectable error happens, usually GPU recovery will
1197 	 * be scheduled. But due to the known problem in GPU recovery failing
1198 	 * to bring GPU back, below interface provides one direct way to
1199 	 * user to reboot system automatically in such case within
1200 	 * ERREVENT_ATHUB_INTERRUPT generated. Normal GPU recovery routine
1201 	 * will never be called.
1202 	 */
1203 	debugfs_create_bool("auto_reboot", S_IWUGO | S_IRUGO, dir, &con->reboot);
1204 
1205 	/*
1206 	 * User could set this not to clean up hardware's error count register
1207 	 * of RAS IPs during ras recovery.
1208 	 */
1209 	debugfs_create_bool("disable_ras_err_cnt_harvest", 0644, dir,
1210 			    &con->disable_ras_err_cnt_harvest);
1211 	return dir;
1212 }
1213 
1214 static void amdgpu_ras_debugfs_create(struct amdgpu_device *adev,
1215 				      struct ras_fs_if *head,
1216 				      struct dentry *dir)
1217 {
1218 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &head->head);
1219 
1220 	if (!obj || !dir)
1221 		return;
1222 
1223 	get_obj(obj);
1224 
1225 	memcpy(obj->fs_data.debugfs_name,
1226 			head->debugfs_name,
1227 			sizeof(obj->fs_data.debugfs_name));
1228 
1229 	debugfs_create_file(obj->fs_data.debugfs_name, S_IWUGO | S_IRUGO, dir,
1230 			    obj, &amdgpu_ras_debugfs_ops);
1231 }
1232 
1233 void amdgpu_ras_debugfs_create_all(struct amdgpu_device *adev)
1234 {
1235 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1236 	struct dentry *dir;
1237 	struct ras_manager *obj;
1238 	struct ras_fs_if fs_info;
1239 
1240 	/*
1241 	 * it won't be called in resume path, no need to check
1242 	 * suspend and gpu reset status
1243 	 */
1244 	if (!IS_ENABLED(CONFIG_DEBUG_FS) || !con)
1245 		return;
1246 
1247 	dir = amdgpu_ras_debugfs_create_ctrl_node(adev);
1248 
1249 	list_for_each_entry(obj, &con->head, node) {
1250 		if (amdgpu_ras_is_supported(adev, obj->head.block) &&
1251 			(obj->attr_inuse == 1)) {
1252 			sprintf(fs_info.debugfs_name, "%s_err_inject",
1253 					ras_block_str(obj->head.block));
1254 			fs_info.head = obj->head;
1255 			amdgpu_ras_debugfs_create(adev, &fs_info, dir);
1256 		}
1257 	}
1258 }
1259 
1260 /* debugfs end */
1261 
1262 /* ras fs */
1263 static BIN_ATTR(gpu_vram_bad_pages, S_IRUGO,
1264 		amdgpu_ras_sysfs_badpages_read, NULL, 0);
1265 static DEVICE_ATTR(features, S_IRUGO,
1266 		amdgpu_ras_sysfs_features_read, NULL);
1267 static int amdgpu_ras_fs_init(struct amdgpu_device *adev)
1268 {
1269 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1270 	struct attribute_group group = {
1271 		.name = RAS_FS_NAME,
1272 	};
1273 	struct attribute *attrs[] = {
1274 		&con->features_attr.attr,
1275 		NULL
1276 	};
1277 	struct bin_attribute *bin_attrs[] = {
1278 		NULL,
1279 		NULL,
1280 	};
1281 	int r;
1282 
1283 	/* add features entry */
1284 	con->features_attr = dev_attr_features;
1285 	group.attrs = attrs;
1286 	sysfs_attr_init(attrs[0]);
1287 
1288 	if (amdgpu_bad_page_threshold != 0) {
1289 		/* add bad_page_features entry */
1290 		bin_attr_gpu_vram_bad_pages.private = NULL;
1291 		con->badpages_attr = bin_attr_gpu_vram_bad_pages;
1292 		bin_attrs[0] = &con->badpages_attr;
1293 		group.bin_attrs = bin_attrs;
1294 		sysfs_bin_attr_init(bin_attrs[0]);
1295 	}
1296 
1297 	r = sysfs_create_group(&adev->dev->kobj, &group);
1298 	if (r)
1299 		dev_err(adev->dev, "Failed to create RAS sysfs group!");
1300 
1301 	return 0;
1302 }
1303 
1304 static int amdgpu_ras_fs_fini(struct amdgpu_device *adev)
1305 {
1306 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1307 	struct ras_manager *con_obj, *ip_obj, *tmp;
1308 
1309 	if (IS_ENABLED(CONFIG_DEBUG_FS)) {
1310 		list_for_each_entry_safe(con_obj, tmp, &con->head, node) {
1311 			ip_obj = amdgpu_ras_find_obj(adev, &con_obj->head);
1312 			if (ip_obj)
1313 				put_obj(ip_obj);
1314 		}
1315 	}
1316 
1317 	amdgpu_ras_sysfs_remove_all(adev);
1318 	return 0;
1319 }
1320 /* ras fs end */
1321 
1322 /* ih begin */
1323 static void amdgpu_ras_interrupt_handler(struct ras_manager *obj)
1324 {
1325 	struct ras_ih_data *data = &obj->ih_data;
1326 	struct amdgpu_iv_entry entry;
1327 	int ret;
1328 	struct ras_err_data err_data = {0, 0, 0, NULL};
1329 
1330 	while (data->rptr != data->wptr) {
1331 		rmb();
1332 		memcpy(&entry, &data->ring[data->rptr],
1333 				data->element_size);
1334 
1335 		wmb();
1336 		data->rptr = (data->aligned_element_size +
1337 				data->rptr) % data->ring_size;
1338 
1339 		/* Let IP handle its data, maybe we need get the output
1340 		 * from the callback to udpate the error type/count, etc
1341 		 */
1342 		if (data->cb) {
1343 			ret = data->cb(obj->adev, &err_data, &entry);
1344 			/* ue will trigger an interrupt, and in that case
1345 			 * we need do a reset to recovery the whole system.
1346 			 * But leave IP do that recovery, here we just dispatch
1347 			 * the error.
1348 			 */
1349 			if (ret == AMDGPU_RAS_SUCCESS) {
1350 				/* these counts could be left as 0 if
1351 				 * some blocks do not count error number
1352 				 */
1353 				obj->err_data.ue_count += err_data.ue_count;
1354 				obj->err_data.ce_count += err_data.ce_count;
1355 			}
1356 		}
1357 	}
1358 }
1359 
1360 static void amdgpu_ras_interrupt_process_handler(struct work_struct *work)
1361 {
1362 	struct ras_ih_data *data =
1363 		container_of(work, struct ras_ih_data, ih_work);
1364 	struct ras_manager *obj =
1365 		container_of(data, struct ras_manager, ih_data);
1366 
1367 	amdgpu_ras_interrupt_handler(obj);
1368 }
1369 
1370 int amdgpu_ras_interrupt_dispatch(struct amdgpu_device *adev,
1371 		struct ras_dispatch_if *info)
1372 {
1373 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1374 	struct ras_ih_data *data = &obj->ih_data;
1375 
1376 	if (!obj)
1377 		return -EINVAL;
1378 
1379 	if (data->inuse == 0)
1380 		return 0;
1381 
1382 	/* Might be overflow... */
1383 	memcpy(&data->ring[data->wptr], info->entry,
1384 			data->element_size);
1385 
1386 	wmb();
1387 	data->wptr = (data->aligned_element_size +
1388 			data->wptr) % data->ring_size;
1389 
1390 	schedule_work(&data->ih_work);
1391 
1392 	return 0;
1393 }
1394 
1395 int amdgpu_ras_interrupt_remove_handler(struct amdgpu_device *adev,
1396 		struct ras_ih_if *info)
1397 {
1398 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1399 	struct ras_ih_data *data;
1400 
1401 	if (!obj)
1402 		return -EINVAL;
1403 
1404 	data = &obj->ih_data;
1405 	if (data->inuse == 0)
1406 		return 0;
1407 
1408 	cancel_work_sync(&data->ih_work);
1409 
1410 	kfree(data->ring);
1411 	memset(data, 0, sizeof(*data));
1412 	put_obj(obj);
1413 
1414 	return 0;
1415 }
1416 
1417 int amdgpu_ras_interrupt_add_handler(struct amdgpu_device *adev,
1418 		struct ras_ih_if *info)
1419 {
1420 	struct ras_manager *obj = amdgpu_ras_find_obj(adev, &info->head);
1421 	struct ras_ih_data *data;
1422 
1423 	if (!obj) {
1424 		/* in case we registe the IH before enable ras feature */
1425 		obj = amdgpu_ras_create_obj(adev, &info->head);
1426 		if (!obj)
1427 			return -EINVAL;
1428 	} else
1429 		get_obj(obj);
1430 
1431 	data = &obj->ih_data;
1432 	/* add the callback.etc */
1433 	*data = (struct ras_ih_data) {
1434 		.inuse = 0,
1435 		.cb = info->cb,
1436 		.element_size = sizeof(struct amdgpu_iv_entry),
1437 		.rptr = 0,
1438 		.wptr = 0,
1439 	};
1440 
1441 	INIT_WORK(&data->ih_work, amdgpu_ras_interrupt_process_handler);
1442 
1443 	data->aligned_element_size = ALIGN(data->element_size, 8);
1444 	/* the ring can store 64 iv entries. */
1445 	data->ring_size = 64 * data->aligned_element_size;
1446 	data->ring = kmalloc(data->ring_size, GFP_KERNEL);
1447 	if (!data->ring) {
1448 		put_obj(obj);
1449 		return -ENOMEM;
1450 	}
1451 
1452 	/* IH is ready */
1453 	data->inuse = 1;
1454 
1455 	return 0;
1456 }
1457 
1458 static int amdgpu_ras_interrupt_remove_all(struct amdgpu_device *adev)
1459 {
1460 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1461 	struct ras_manager *obj, *tmp;
1462 
1463 	list_for_each_entry_safe(obj, tmp, &con->head, node) {
1464 		struct ras_ih_if info = {
1465 			.head = obj->head,
1466 		};
1467 		amdgpu_ras_interrupt_remove_handler(adev, &info);
1468 	}
1469 
1470 	return 0;
1471 }
1472 /* ih end */
1473 
1474 /* traversal all IPs except NBIO to query error counter */
1475 static void amdgpu_ras_log_on_err_counter(struct amdgpu_device *adev)
1476 {
1477 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1478 	struct ras_manager *obj;
1479 
1480 	if (!adev->ras_features || !con)
1481 		return;
1482 
1483 	list_for_each_entry(obj, &con->head, node) {
1484 		struct ras_query_if info = {
1485 			.head = obj->head,
1486 		};
1487 
1488 		/*
1489 		 * PCIE_BIF IP has one different isr by ras controller
1490 		 * interrupt, the specific ras counter query will be
1491 		 * done in that isr. So skip such block from common
1492 		 * sync flood interrupt isr calling.
1493 		 */
1494 		if (info.head.block == AMDGPU_RAS_BLOCK__PCIE_BIF)
1495 			continue;
1496 
1497 		amdgpu_ras_query_error_status(adev, &info);
1498 	}
1499 }
1500 
1501 /* Parse RdRspStatus and WrRspStatus */
1502 static void amdgpu_ras_error_status_query(struct amdgpu_device *adev,
1503 					  struct ras_query_if *info)
1504 {
1505 	/*
1506 	 * Only two block need to query read/write
1507 	 * RspStatus at current state
1508 	 */
1509 	switch (info->head.block) {
1510 	case AMDGPU_RAS_BLOCK__GFX:
1511 		if (adev->gfx.funcs->query_ras_error_status)
1512 			adev->gfx.funcs->query_ras_error_status(adev);
1513 		break;
1514 	case AMDGPU_RAS_BLOCK__MMHUB:
1515 		if (adev->mmhub.funcs->query_ras_error_status)
1516 			adev->mmhub.funcs->query_ras_error_status(adev);
1517 		break;
1518 	default:
1519 		break;
1520 	}
1521 }
1522 
1523 static void amdgpu_ras_query_err_status(struct amdgpu_device *adev)
1524 {
1525 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1526 	struct ras_manager *obj;
1527 
1528 	if (!adev->ras_features || !con)
1529 		return;
1530 
1531 	list_for_each_entry(obj, &con->head, node) {
1532 		struct ras_query_if info = {
1533 			.head = obj->head,
1534 		};
1535 
1536 		amdgpu_ras_error_status_query(adev, &info);
1537 	}
1538 }
1539 
1540 /* recovery begin */
1541 
1542 /* return 0 on success.
1543  * caller need free bps.
1544  */
1545 static int amdgpu_ras_badpages_read(struct amdgpu_device *adev,
1546 		struct ras_badpage **bps, unsigned int *count)
1547 {
1548 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1549 	struct ras_err_handler_data *data;
1550 	int i = 0;
1551 	int ret = 0, status;
1552 
1553 	if (!con || !con->eh_data || !bps || !count)
1554 		return -EINVAL;
1555 
1556 	mutex_lock(&con->recovery_lock);
1557 	data = con->eh_data;
1558 	if (!data || data->count == 0) {
1559 		*bps = NULL;
1560 		ret = -EINVAL;
1561 		goto out;
1562 	}
1563 
1564 	*bps = kmalloc(sizeof(struct ras_badpage) * data->count, GFP_KERNEL);
1565 	if (!*bps) {
1566 		ret = -ENOMEM;
1567 		goto out;
1568 	}
1569 
1570 	for (; i < data->count; i++) {
1571 		(*bps)[i] = (struct ras_badpage){
1572 			.bp = data->bps[i].retired_page,
1573 			.size = AMDGPU_GPU_PAGE_SIZE,
1574 			.flags = AMDGPU_RAS_RETIRE_PAGE_RESERVED,
1575 		};
1576 		status = amdgpu_vram_mgr_query_page_status(
1577 				ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM),
1578 				data->bps[i].retired_page);
1579 		if (status == -EBUSY)
1580 			(*bps)[i].flags = AMDGPU_RAS_RETIRE_PAGE_PENDING;
1581 		else if (status == -ENOENT)
1582 			(*bps)[i].flags = AMDGPU_RAS_RETIRE_PAGE_FAULT;
1583 	}
1584 
1585 	*count = data->count;
1586 out:
1587 	mutex_unlock(&con->recovery_lock);
1588 	return ret;
1589 }
1590 
1591 static void amdgpu_ras_do_recovery(struct work_struct *work)
1592 {
1593 	struct amdgpu_ras *ras =
1594 		container_of(work, struct amdgpu_ras, recovery_work);
1595 	struct amdgpu_device *remote_adev = NULL;
1596 	struct amdgpu_device *adev = ras->adev;
1597 	struct list_head device_list, *device_list_handle =  NULL;
1598 
1599 	if (!ras->disable_ras_err_cnt_harvest) {
1600 		struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
1601 
1602 		/* Build list of devices to query RAS related errors */
1603 		if  (hive && adev->gmc.xgmi.num_physical_nodes > 1) {
1604 			device_list_handle = &hive->device_list;
1605 		} else {
1606 			INIT_LIST_HEAD(&device_list);
1607 			list_add_tail(&adev->gmc.xgmi.head, &device_list);
1608 			device_list_handle = &device_list;
1609 		}
1610 
1611 		list_for_each_entry(remote_adev,
1612 				device_list_handle, gmc.xgmi.head) {
1613 			amdgpu_ras_query_err_status(remote_adev);
1614 			amdgpu_ras_log_on_err_counter(remote_adev);
1615 		}
1616 
1617 		amdgpu_put_xgmi_hive(hive);
1618 	}
1619 
1620 	if (amdgpu_device_should_recover_gpu(ras->adev))
1621 		amdgpu_device_gpu_recover(ras->adev, NULL);
1622 	atomic_set(&ras->in_recovery, 0);
1623 }
1624 
1625 /* alloc/realloc bps array */
1626 static int amdgpu_ras_realloc_eh_data_space(struct amdgpu_device *adev,
1627 		struct ras_err_handler_data *data, int pages)
1628 {
1629 	unsigned int old_space = data->count + data->space_left;
1630 	unsigned int new_space = old_space + pages;
1631 	unsigned int align_space = ALIGN(new_space, 512);
1632 	void *bps = kmalloc(align_space * sizeof(*data->bps), GFP_KERNEL);
1633 
1634 	if (!bps) {
1635 		kfree(bps);
1636 		return -ENOMEM;
1637 	}
1638 
1639 	if (data->bps) {
1640 		memcpy(bps, data->bps,
1641 				data->count * sizeof(*data->bps));
1642 		kfree(data->bps);
1643 	}
1644 
1645 	data->bps = bps;
1646 	data->space_left += align_space - old_space;
1647 	return 0;
1648 }
1649 
1650 /* it deal with vram only. */
1651 int amdgpu_ras_add_bad_pages(struct amdgpu_device *adev,
1652 		struct eeprom_table_record *bps, int pages)
1653 {
1654 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1655 	struct ras_err_handler_data *data;
1656 	int ret = 0;
1657 	uint32_t i;
1658 
1659 	if (!con || !con->eh_data || !bps || pages <= 0)
1660 		return 0;
1661 
1662 	mutex_lock(&con->recovery_lock);
1663 	data = con->eh_data;
1664 	if (!data)
1665 		goto out;
1666 
1667 	for (i = 0; i < pages; i++) {
1668 		if (amdgpu_ras_check_bad_page_unlock(con,
1669 			bps[i].retired_page << AMDGPU_GPU_PAGE_SHIFT))
1670 			continue;
1671 
1672 		if (!data->space_left &&
1673 			amdgpu_ras_realloc_eh_data_space(adev, data, 256)) {
1674 			ret = -ENOMEM;
1675 			goto out;
1676 		}
1677 
1678 		amdgpu_vram_mgr_reserve_range(
1679 			ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM),
1680 			bps[i].retired_page << AMDGPU_GPU_PAGE_SHIFT,
1681 			AMDGPU_GPU_PAGE_SIZE);
1682 
1683 		memcpy(&data->bps[data->count], &bps[i], sizeof(*data->bps));
1684 		data->count++;
1685 		data->space_left--;
1686 	}
1687 out:
1688 	mutex_unlock(&con->recovery_lock);
1689 
1690 	return ret;
1691 }
1692 
1693 /*
1694  * write error record array to eeprom, the function should be
1695  * protected by recovery_lock
1696  */
1697 int amdgpu_ras_save_bad_pages(struct amdgpu_device *adev)
1698 {
1699 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1700 	struct ras_err_handler_data *data;
1701 	struct amdgpu_ras_eeprom_control *control;
1702 	int save_count;
1703 
1704 	if (!con || !con->eh_data)
1705 		return 0;
1706 
1707 	control = &con->eeprom_control;
1708 	data = con->eh_data;
1709 	save_count = data->count - control->num_recs;
1710 	/* only new entries are saved */
1711 	if (save_count > 0) {
1712 		if (amdgpu_ras_eeprom_process_recods(control,
1713 							&data->bps[control->num_recs],
1714 							true,
1715 							save_count)) {
1716 			dev_err(adev->dev, "Failed to save EEPROM table data!");
1717 			return -EIO;
1718 		}
1719 
1720 		dev_info(adev->dev, "Saved %d pages to EEPROM table.\n", save_count);
1721 	}
1722 
1723 	return 0;
1724 }
1725 
1726 /*
1727  * read error record array in eeprom and reserve enough space for
1728  * storing new bad pages
1729  */
1730 static int amdgpu_ras_load_bad_pages(struct amdgpu_device *adev)
1731 {
1732 	struct amdgpu_ras_eeprom_control *control =
1733 					&adev->psp.ras.ras->eeprom_control;
1734 	struct eeprom_table_record *bps = NULL;
1735 	int ret = 0;
1736 
1737 	/* no bad page record, skip eeprom access */
1738 	if (!control->num_recs || (amdgpu_bad_page_threshold == 0))
1739 		return ret;
1740 
1741 	bps = kcalloc(control->num_recs, sizeof(*bps), GFP_KERNEL);
1742 	if (!bps)
1743 		return -ENOMEM;
1744 
1745 	if (amdgpu_ras_eeprom_process_recods(control, bps, false,
1746 		control->num_recs)) {
1747 		dev_err(adev->dev, "Failed to load EEPROM table records!");
1748 		ret = -EIO;
1749 		goto out;
1750 	}
1751 
1752 	ret = amdgpu_ras_add_bad_pages(adev, bps, control->num_recs);
1753 
1754 out:
1755 	kfree(bps);
1756 	return ret;
1757 }
1758 
1759 static bool amdgpu_ras_check_bad_page_unlock(struct amdgpu_ras *con,
1760 				uint64_t addr)
1761 {
1762 	struct ras_err_handler_data *data = con->eh_data;
1763 	int i;
1764 
1765 	addr >>= AMDGPU_GPU_PAGE_SHIFT;
1766 	for (i = 0; i < data->count; i++)
1767 		if (addr == data->bps[i].retired_page)
1768 			return true;
1769 
1770 	return false;
1771 }
1772 
1773 /*
1774  * check if an address belongs to bad page
1775  *
1776  * Note: this check is only for umc block
1777  */
1778 static bool amdgpu_ras_check_bad_page(struct amdgpu_device *adev,
1779 				uint64_t addr)
1780 {
1781 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1782 	bool ret = false;
1783 
1784 	if (!con || !con->eh_data)
1785 		return ret;
1786 
1787 	mutex_lock(&con->recovery_lock);
1788 	ret = amdgpu_ras_check_bad_page_unlock(con, addr);
1789 	mutex_unlock(&con->recovery_lock);
1790 	return ret;
1791 }
1792 
1793 static void amdgpu_ras_validate_threshold(struct amdgpu_device *adev,
1794 					uint32_t max_length)
1795 {
1796 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1797 	int tmp_threshold = amdgpu_bad_page_threshold;
1798 	u64 val;
1799 
1800 	/*
1801 	 * Justification of value bad_page_cnt_threshold in ras structure
1802 	 *
1803 	 * Generally, -1 <= amdgpu_bad_page_threshold <= max record length
1804 	 * in eeprom, and introduce two scenarios accordingly.
1805 	 *
1806 	 * Bad page retirement enablement:
1807 	 *    - If amdgpu_bad_page_threshold = -1,
1808 	 *      bad_page_cnt_threshold = typical value by formula.
1809 	 *
1810 	 *    - When the value from user is 0 < amdgpu_bad_page_threshold <
1811 	 *      max record length in eeprom, use it directly.
1812 	 *
1813 	 * Bad page retirement disablement:
1814 	 *    - If amdgpu_bad_page_threshold = 0, bad page retirement
1815 	 *      functionality is disabled, and bad_page_cnt_threshold will
1816 	 *      take no effect.
1817 	 */
1818 
1819 	if (tmp_threshold < -1)
1820 		tmp_threshold = -1;
1821 	else if (tmp_threshold > max_length)
1822 		tmp_threshold = max_length;
1823 
1824 	if (tmp_threshold == -1) {
1825 		val = adev->gmc.mc_vram_size;
1826 		do_div(val, RAS_BAD_PAGE_RATE);
1827 		con->bad_page_cnt_threshold = min(lower_32_bits(val),
1828 						max_length);
1829 	} else {
1830 		con->bad_page_cnt_threshold = tmp_threshold;
1831 	}
1832 }
1833 
1834 int amdgpu_ras_recovery_init(struct amdgpu_device *adev)
1835 {
1836 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1837 	struct ras_err_handler_data **data;
1838 	uint32_t max_eeprom_records_len = 0;
1839 	bool exc_err_limit = false;
1840 	int ret;
1841 
1842 	if (adev->ras_features && con)
1843 		data = &con->eh_data;
1844 	else
1845 		return 0;
1846 
1847 	*data = kmalloc(sizeof(**data), GFP_KERNEL | __GFP_ZERO);
1848 	if (!*data) {
1849 		ret = -ENOMEM;
1850 		goto out;
1851 	}
1852 
1853 	mutex_init(&con->recovery_lock);
1854 	INIT_WORK(&con->recovery_work, amdgpu_ras_do_recovery);
1855 	atomic_set(&con->in_recovery, 0);
1856 	con->adev = adev;
1857 
1858 	max_eeprom_records_len = amdgpu_ras_eeprom_get_record_max_length();
1859 	amdgpu_ras_validate_threshold(adev, max_eeprom_records_len);
1860 
1861 	/* Todo: During test the SMU might fail to read the eeprom through I2C
1862 	 * when the GPU is pending on XGMI reset during probe time
1863 	 * (Mostly after second bus reset), skip it now
1864 	 */
1865 	if (adev->gmc.xgmi.pending_reset)
1866 		return 0;
1867 	ret = amdgpu_ras_eeprom_init(&con->eeprom_control, &exc_err_limit);
1868 	/*
1869 	 * This calling fails when exc_err_limit is true or
1870 	 * ret != 0.
1871 	 */
1872 	if (exc_err_limit || ret)
1873 		goto free;
1874 
1875 	if (con->eeprom_control.num_recs) {
1876 		ret = amdgpu_ras_load_bad_pages(adev);
1877 		if (ret)
1878 			goto free;
1879 	}
1880 
1881 	return 0;
1882 
1883 free:
1884 	kfree((*data)->bps);
1885 	kfree(*data);
1886 	con->eh_data = NULL;
1887 out:
1888 	dev_warn(adev->dev, "Failed to initialize ras recovery!\n");
1889 
1890 	/*
1891 	 * Except error threshold exceeding case, other failure cases in this
1892 	 * function would not fail amdgpu driver init.
1893 	 */
1894 	if (!exc_err_limit)
1895 		ret = 0;
1896 	else
1897 		ret = -EINVAL;
1898 
1899 	return ret;
1900 }
1901 
1902 static int amdgpu_ras_recovery_fini(struct amdgpu_device *adev)
1903 {
1904 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1905 	struct ras_err_handler_data *data = con->eh_data;
1906 
1907 	/* recovery_init failed to init it, fini is useless */
1908 	if (!data)
1909 		return 0;
1910 
1911 	cancel_work_sync(&con->recovery_work);
1912 
1913 	mutex_lock(&con->recovery_lock);
1914 	con->eh_data = NULL;
1915 	kfree(data->bps);
1916 	kfree(data);
1917 	mutex_unlock(&con->recovery_lock);
1918 
1919 	return 0;
1920 }
1921 /* recovery end */
1922 
1923 /* return 0 if ras will reset gpu and repost.*/
1924 int amdgpu_ras_request_reset_on_boot(struct amdgpu_device *adev,
1925 		unsigned int block)
1926 {
1927 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1928 
1929 	if (!ras)
1930 		return -EINVAL;
1931 
1932 	ras->flags |= AMDGPU_RAS_FLAG_INIT_NEED_RESET;
1933 	return 0;
1934 }
1935 
1936 static int amdgpu_ras_check_asic_type(struct amdgpu_device *adev)
1937 {
1938 	if (adev->asic_type != CHIP_VEGA10 &&
1939 		adev->asic_type != CHIP_VEGA20 &&
1940 		adev->asic_type != CHIP_ARCTURUS &&
1941 		adev->asic_type != CHIP_SIENNA_CICHLID)
1942 		return 1;
1943 	else
1944 		return 0;
1945 }
1946 
1947 /*
1948  * check hardware's ras ability which will be saved in hw_supported.
1949  * if hardware does not support ras, we can skip some ras initializtion and
1950  * forbid some ras operations from IP.
1951  * if software itself, say boot parameter, limit the ras ability. We still
1952  * need allow IP do some limited operations, like disable. In such case,
1953  * we have to initialize ras as normal. but need check if operation is
1954  * allowed or not in each function.
1955  */
1956 static void amdgpu_ras_check_supported(struct amdgpu_device *adev,
1957 		uint32_t *hw_supported, uint32_t *supported)
1958 {
1959 	*hw_supported = 0;
1960 	*supported = 0;
1961 
1962 	if (amdgpu_sriov_vf(adev) || !adev->is_atom_fw ||
1963 		amdgpu_ras_check_asic_type(adev))
1964 		return;
1965 
1966 	if (amdgpu_atomfirmware_mem_ecc_supported(adev)) {
1967 		dev_info(adev->dev, "MEM ECC is active.\n");
1968 		*hw_supported |= (1 << AMDGPU_RAS_BLOCK__UMC |
1969 				1 << AMDGPU_RAS_BLOCK__DF);
1970 	} else
1971 		dev_info(adev->dev, "MEM ECC is not presented.\n");
1972 
1973 	if (amdgpu_atomfirmware_sram_ecc_supported(adev)) {
1974 		dev_info(adev->dev, "SRAM ECC is active.\n");
1975 		*hw_supported |= ~(1 << AMDGPU_RAS_BLOCK__UMC |
1976 				1 << AMDGPU_RAS_BLOCK__DF);
1977 	} else
1978 		dev_info(adev->dev, "SRAM ECC is not presented.\n");
1979 
1980 	/* hw_supported needs to be aligned with RAS block mask. */
1981 	*hw_supported &= AMDGPU_RAS_BLOCK_MASK;
1982 
1983 	*supported = amdgpu_ras_enable == 0 ?
1984 			0 : *hw_supported & amdgpu_ras_mask;
1985 	adev->ras_features = *supported;
1986 }
1987 
1988 int amdgpu_ras_init(struct amdgpu_device *adev)
1989 {
1990 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
1991 	int r;
1992 
1993 	if (con)
1994 		return 0;
1995 
1996 	con = kmalloc(sizeof(struct amdgpu_ras) +
1997 			sizeof(struct ras_manager) * AMDGPU_RAS_BLOCK_COUNT,
1998 			GFP_KERNEL|__GFP_ZERO);
1999 	if (!con)
2000 		return -ENOMEM;
2001 
2002 	con->objs = (struct ras_manager *)(con + 1);
2003 
2004 	amdgpu_ras_set_context(adev, con);
2005 
2006 	amdgpu_ras_check_supported(adev, &con->hw_supported,
2007 			&con->supported);
2008 	if (!con->hw_supported || (adev->asic_type == CHIP_VEGA10)) {
2009 		/* set gfx block ras context feature for VEGA20 Gaming
2010 		 * send ras disable cmd to ras ta during ras late init.
2011 		 */
2012 		if (!adev->ras_features && adev->asic_type == CHIP_VEGA20) {
2013 			con->features |= BIT(AMDGPU_RAS_BLOCK__GFX);
2014 
2015 			return 0;
2016 		}
2017 
2018 		r = 0;
2019 		goto release_con;
2020 	}
2021 
2022 	con->features = 0;
2023 	INIT_LIST_HEAD(&con->head);
2024 	/* Might need get this flag from vbios. */
2025 	con->flags = RAS_DEFAULT_FLAGS;
2026 
2027 	if (adev->nbio.funcs->init_ras_controller_interrupt) {
2028 		r = adev->nbio.funcs->init_ras_controller_interrupt(adev);
2029 		if (r)
2030 			goto release_con;
2031 	}
2032 
2033 	if (adev->nbio.funcs->init_ras_err_event_athub_interrupt) {
2034 		r = adev->nbio.funcs->init_ras_err_event_athub_interrupt(adev);
2035 		if (r)
2036 			goto release_con;
2037 	}
2038 
2039 	if (amdgpu_ras_fs_init(adev)) {
2040 		r = -EINVAL;
2041 		goto release_con;
2042 	}
2043 
2044 	dev_info(adev->dev, "RAS INFO: ras initialized successfully, "
2045 			"hardware ability[%x] ras_mask[%x]\n",
2046 			con->hw_supported, con->supported);
2047 	return 0;
2048 release_con:
2049 	amdgpu_ras_set_context(adev, NULL);
2050 	kfree(con);
2051 
2052 	return r;
2053 }
2054 
2055 /* helper function to handle common stuff in ip late init phase */
2056 int amdgpu_ras_late_init(struct amdgpu_device *adev,
2057 			 struct ras_common_if *ras_block,
2058 			 struct ras_fs_if *fs_info,
2059 			 struct ras_ih_if *ih_info)
2060 {
2061 	int r;
2062 
2063 	/* disable RAS feature per IP block if it is not supported */
2064 	if (!amdgpu_ras_is_supported(adev, ras_block->block)) {
2065 		amdgpu_ras_feature_enable_on_boot(adev, ras_block, 0);
2066 		return 0;
2067 	}
2068 
2069 	r = amdgpu_ras_feature_enable_on_boot(adev, ras_block, 1);
2070 	if (r) {
2071 		if (r == -EAGAIN) {
2072 			/* request gpu reset. will run again */
2073 			amdgpu_ras_request_reset_on_boot(adev,
2074 					ras_block->block);
2075 			return 0;
2076 		} else if (adev->in_suspend || amdgpu_in_reset(adev)) {
2077 			/* in resume phase, if fail to enable ras,
2078 			 * clean up all ras fs nodes, and disable ras */
2079 			goto cleanup;
2080 		} else
2081 			return r;
2082 	}
2083 
2084 	/* in resume phase, no need to create ras fs node */
2085 	if (adev->in_suspend || amdgpu_in_reset(adev))
2086 		return 0;
2087 
2088 	if (ih_info->cb) {
2089 		r = amdgpu_ras_interrupt_add_handler(adev, ih_info);
2090 		if (r)
2091 			goto interrupt;
2092 	}
2093 
2094 	r = amdgpu_ras_sysfs_create(adev, fs_info);
2095 	if (r)
2096 		goto sysfs;
2097 
2098 	return 0;
2099 cleanup:
2100 	amdgpu_ras_sysfs_remove(adev, ras_block);
2101 sysfs:
2102 	if (ih_info->cb)
2103 		amdgpu_ras_interrupt_remove_handler(adev, ih_info);
2104 interrupt:
2105 	amdgpu_ras_feature_enable(adev, ras_block, 0);
2106 	return r;
2107 }
2108 
2109 /* helper function to remove ras fs node and interrupt handler */
2110 void amdgpu_ras_late_fini(struct amdgpu_device *adev,
2111 			  struct ras_common_if *ras_block,
2112 			  struct ras_ih_if *ih_info)
2113 {
2114 	if (!ras_block || !ih_info)
2115 		return;
2116 
2117 	amdgpu_ras_sysfs_remove(adev, ras_block);
2118 	if (ih_info->cb)
2119 		amdgpu_ras_interrupt_remove_handler(adev, ih_info);
2120 	amdgpu_ras_feature_enable(adev, ras_block, 0);
2121 }
2122 
2123 /* do some init work after IP late init as dependence.
2124  * and it runs in resume/gpu reset/booting up cases.
2125  */
2126 void amdgpu_ras_resume(struct amdgpu_device *adev)
2127 {
2128 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2129 	struct ras_manager *obj, *tmp;
2130 
2131 	if (!adev->ras_features || !con) {
2132 		/* clean ras context for VEGA20 Gaming after send ras disable cmd */
2133 		amdgpu_release_ras_context(adev);
2134 
2135 		return;
2136 	}
2137 
2138 	if (con->flags & AMDGPU_RAS_FLAG_INIT_BY_VBIOS) {
2139 		/* Set up all other IPs which are not implemented. There is a
2140 		 * tricky thing that IP's actual ras error type should be
2141 		 * MULTI_UNCORRECTABLE, but as driver does not handle it, so
2142 		 * ERROR_NONE make sense anyway.
2143 		 */
2144 		amdgpu_ras_enable_all_features(adev, 1);
2145 
2146 		/* We enable ras on all hw_supported block, but as boot
2147 		 * parameter might disable some of them and one or more IP has
2148 		 * not implemented yet. So we disable them on behalf.
2149 		 */
2150 		list_for_each_entry_safe(obj, tmp, &con->head, node) {
2151 			if (!amdgpu_ras_is_supported(adev, obj->head.block)) {
2152 				amdgpu_ras_feature_enable(adev, &obj->head, 0);
2153 				/* there should be no any reference. */
2154 				WARN_ON(alive_obj(obj));
2155 			}
2156 		}
2157 	}
2158 
2159 	if (con->flags & AMDGPU_RAS_FLAG_INIT_NEED_RESET) {
2160 		con->flags &= ~AMDGPU_RAS_FLAG_INIT_NEED_RESET;
2161 		/* setup ras obj state as disabled.
2162 		 * for init_by_vbios case.
2163 		 * if we want to enable ras, just enable it in a normal way.
2164 		 * If we want do disable it, need setup ras obj as enabled,
2165 		 * then issue another TA disable cmd.
2166 		 * See feature_enable_on_boot
2167 		 */
2168 		amdgpu_ras_disable_all_features(adev, 1);
2169 		amdgpu_ras_reset_gpu(adev);
2170 	}
2171 }
2172 
2173 void amdgpu_ras_suspend(struct amdgpu_device *adev)
2174 {
2175 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2176 
2177 	if (!adev->ras_features || !con)
2178 		return;
2179 
2180 	amdgpu_ras_disable_all_features(adev, 0);
2181 	/* Make sure all ras objects are disabled. */
2182 	if (con->features)
2183 		amdgpu_ras_disable_all_features(adev, 1);
2184 }
2185 
2186 /* do some fini work before IP fini as dependence */
2187 int amdgpu_ras_pre_fini(struct amdgpu_device *adev)
2188 {
2189 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2190 
2191 	if (!adev->ras_features || !con)
2192 		return 0;
2193 
2194 	/* Need disable ras on all IPs here before ip [hw/sw]fini */
2195 	amdgpu_ras_disable_all_features(adev, 0);
2196 	amdgpu_ras_recovery_fini(adev);
2197 	return 0;
2198 }
2199 
2200 int amdgpu_ras_fini(struct amdgpu_device *adev)
2201 {
2202 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2203 
2204 	if (!adev->ras_features || !con)
2205 		return 0;
2206 
2207 	amdgpu_ras_fs_fini(adev);
2208 	amdgpu_ras_interrupt_remove_all(adev);
2209 
2210 	WARN(con->features, "Feature mask is not cleared");
2211 
2212 	if (con->features)
2213 		amdgpu_ras_disable_all_features(adev, 1);
2214 
2215 	amdgpu_ras_set_context(adev, NULL);
2216 	kfree(con);
2217 
2218 	return 0;
2219 }
2220 
2221 void amdgpu_ras_global_ras_isr(struct amdgpu_device *adev)
2222 {
2223 	uint32_t hw_supported, supported;
2224 
2225 	amdgpu_ras_check_supported(adev, &hw_supported, &supported);
2226 	if (!hw_supported)
2227 		return;
2228 
2229 	if (atomic_cmpxchg(&amdgpu_ras_in_intr, 0, 1) == 0) {
2230 		dev_info(adev->dev, "uncorrectable hardware error"
2231 			"(ERREVENT_ATHUB_INTERRUPT) detected!\n");
2232 
2233 		amdgpu_ras_reset_gpu(adev);
2234 	}
2235 }
2236 
2237 bool amdgpu_ras_need_emergency_restart(struct amdgpu_device *adev)
2238 {
2239 	if (adev->asic_type == CHIP_VEGA20 &&
2240 	    adev->pm.fw_version <= 0x283400) {
2241 		return !(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) &&
2242 				amdgpu_ras_intr_triggered();
2243 	}
2244 
2245 	return false;
2246 }
2247 
2248 void amdgpu_release_ras_context(struct amdgpu_device *adev)
2249 {
2250 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
2251 
2252 	if (!con)
2253 		return;
2254 
2255 	if (!adev->ras_features && con->features & BIT(AMDGPU_RAS_BLOCK__GFX)) {
2256 		con->features &= ~BIT(AMDGPU_RAS_BLOCK__GFX);
2257 		amdgpu_ras_set_context(adev, NULL);
2258 		kfree(con);
2259 	}
2260 }
2261