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