xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_device.c (revision cf85f810f911234a06a4ef2439e8694b93b717fc)
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 
29 #include <linux/aperture.h>
30 #include <linux/power_supply.h>
31 #include <linux/kthread.h>
32 #include <linux/module.h>
33 #include <linux/console.h>
34 #include <linux/slab.h>
35 #include <linux/iommu.h>
36 #include <linux/pci.h>
37 #include <linux/pci-p2pdma.h>
38 #include <linux/apple-gmux.h>
39 #include <linux/nospec.h>
40 
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_client_event.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_probe_helper.h>
45 #include <drm/amdgpu_drm.h>
46 #include <linux/device.h>
47 #include <linux/vgaarb.h>
48 #include <linux/vga_switcheroo.h>
49 #include <linux/efi.h>
50 #include "amdgpu.h"
51 #include "amdgpu_trace.h"
52 #include "amdgpu_i2c.h"
53 #include "atom.h"
54 #include "amdgpu_atombios.h"
55 #include "amdgpu_atomfirmware.h"
56 #include "amd_pcie.h"
57 #ifdef CONFIG_DRM_AMDGPU_SI
58 #include "si.h"
59 #endif
60 #ifdef CONFIG_DRM_AMDGPU_CIK
61 #include "cik.h"
62 #endif
63 #include "vi.h"
64 #include "soc15.h"
65 #include "nv.h"
66 #include "bif/bif_4_1_d.h"
67 #include <linux/firmware.h>
68 #include "amdgpu_vf_error.h"
69 
70 #include "amdgpu_amdkfd.h"
71 #include "amdgpu_pm.h"
72 
73 #include "amdgpu_xgmi.h"
74 #include "amdgpu_ras.h"
75 #include "amdgpu_ras_mgr.h"
76 #include "amdgpu_pmu.h"
77 #include "amdgpu_fru_eeprom.h"
78 #include "amdgpu_reset.h"
79 #include "amdgpu_virt.h"
80 #include "amdgpu_dev_coredump.h"
81 
82 #include <linux/suspend.h>
83 #include <drm/task_barrier.h>
84 #include <linux/pm_runtime.h>
85 
86 #include <drm/drm_drv.h>
87 
88 #if IS_ENABLED(CONFIG_X86)
89 #include <asm/intel-family.h>
90 #include <asm/cpu_device_id.h>
91 #endif
92 
93 MODULE_FIRMWARE("amdgpu/vega10_gpu_info.bin");
94 MODULE_FIRMWARE("amdgpu/vega12_gpu_info.bin");
95 MODULE_FIRMWARE("amdgpu/raven_gpu_info.bin");
96 MODULE_FIRMWARE("amdgpu/picasso_gpu_info.bin");
97 MODULE_FIRMWARE("amdgpu/raven2_gpu_info.bin");
98 MODULE_FIRMWARE("amdgpu/arcturus_gpu_info.bin");
99 MODULE_FIRMWARE("amdgpu/navi12_gpu_info.bin");
100 MODULE_FIRMWARE("amdgpu/cyan_skillfish_gpu_info.bin");
101 
102 #define AMDGPU_RESUME_MS		2000
103 #define AMDGPU_MAX_RETRY_LIMIT		2
104 #define AMDGPU_RETRY_SRIOV_RESET(r) ((r) == -EBUSY || (r) == -ETIMEDOUT || (r) == -EINVAL)
105 #define AMDGPU_PCIE_INDEX_FALLBACK (0x38 >> 2)
106 #define AMDGPU_PCIE_INDEX_HI_FALLBACK (0x44 >> 2)
107 #define AMDGPU_PCIE_DATA_FALLBACK (0x3C >> 2)
108 
109 #define AMDGPU_VBIOS_SKIP (1U << 0)
110 #define AMDGPU_VBIOS_OPTIONAL (1U << 1)
111 
112 static const struct drm_driver amdgpu_kms_driver;
113 
114 const char *amdgpu_asic_name[] = {
115 	"TAHITI",
116 	"PITCAIRN",
117 	"VERDE",
118 	"OLAND",
119 	"HAINAN",
120 	"BONAIRE",
121 	"KAVERI",
122 	"KABINI",
123 	"HAWAII",
124 	"MULLINS",
125 	"TOPAZ",
126 	"TONGA",
127 	"FIJI",
128 	"CARRIZO",
129 	"STONEY",
130 	"POLARIS10",
131 	"POLARIS11",
132 	"POLARIS12",
133 	"VEGAM",
134 	"VEGA10",
135 	"VEGA12",
136 	"VEGA20",
137 	"RAVEN",
138 	"ARCTURUS",
139 	"RENOIR",
140 	"ALDEBARAN",
141 	"NAVI10",
142 	"CYAN_SKILLFISH",
143 	"NAVI14",
144 	"NAVI12",
145 	"SIENNA_CICHLID",
146 	"NAVY_FLOUNDER",
147 	"VANGOGH",
148 	"DIMGREY_CAVEFISH",
149 	"BEIGE_GOBY",
150 	"YELLOW_CARP",
151 	"IP DISCOVERY",
152 	"LAST",
153 };
154 
155 #define AMDGPU_IP_BLK_MASK_ALL GENMASK(AMD_IP_BLOCK_TYPE_NUM  - 1, 0)
156 /*
157  * Default init level where all blocks are expected to be initialized. This is
158  * the level of initialization expected by default and also after a full reset
159  * of the device.
160  */
161 struct amdgpu_init_level amdgpu_init_default = {
162 	.level = AMDGPU_INIT_LEVEL_DEFAULT,
163 	.hwini_ip_block_mask = AMDGPU_IP_BLK_MASK_ALL,
164 };
165 
166 struct amdgpu_init_level amdgpu_init_recovery = {
167 	.level = AMDGPU_INIT_LEVEL_RESET_RECOVERY,
168 	.hwini_ip_block_mask = AMDGPU_IP_BLK_MASK_ALL,
169 };
170 
171 /*
172  * Minimal blocks needed to be initialized before a XGMI hive can be reset. This
173  * is used for cases like reset on initialization where the entire hive needs to
174  * be reset before first use.
175  */
176 struct amdgpu_init_level amdgpu_init_minimal_xgmi = {
177 	.level = AMDGPU_INIT_LEVEL_MINIMAL_XGMI,
178 	.hwini_ip_block_mask =
179 		BIT(AMD_IP_BLOCK_TYPE_GMC) | BIT(AMD_IP_BLOCK_TYPE_SMC) |
180 		BIT(AMD_IP_BLOCK_TYPE_COMMON) | BIT(AMD_IP_BLOCK_TYPE_IH) |
181 		BIT(AMD_IP_BLOCK_TYPE_PSP)
182 };
183 
184 static int amdgpu_device_ip_resume_phase1(struct amdgpu_device *adev);
185 static int amdgpu_device_ip_resume_phase2(struct amdgpu_device *adev);
186 static int amdgpu_device_ip_resume_phase3(struct amdgpu_device *adev);
187 
188 static void amdgpu_device_load_switch_state(struct amdgpu_device *adev);
189 
190 static inline bool amdgpu_ip_member_of_hwini(struct amdgpu_device *adev,
191 					     enum amd_ip_block_type block)
192 {
193 	return (adev->init_lvl->hwini_ip_block_mask & (1U << block)) != 0;
194 }
195 
196 void amdgpu_set_init_level(struct amdgpu_device *adev,
197 			   enum amdgpu_init_lvl_id lvl)
198 {
199 	switch (lvl) {
200 	case AMDGPU_INIT_LEVEL_MINIMAL_XGMI:
201 		adev->init_lvl = &amdgpu_init_minimal_xgmi;
202 		break;
203 	case AMDGPU_INIT_LEVEL_RESET_RECOVERY:
204 		adev->init_lvl = &amdgpu_init_recovery;
205 		break;
206 	case AMDGPU_INIT_LEVEL_DEFAULT:
207 		fallthrough;
208 	default:
209 		adev->init_lvl = &amdgpu_init_default;
210 		break;
211 	}
212 }
213 
214 static inline void amdgpu_device_stop_pending_resets(struct amdgpu_device *adev);
215 static int amdgpu_device_pm_notifier(struct notifier_block *nb, unsigned long mode,
216 				     void *data);
217 
218 /**
219  * DOC: pcie_replay_count
220  *
221  * The amdgpu driver provides a sysfs API for reporting the total number
222  * of PCIe replays (NAKs).
223  * The file pcie_replay_count is used for this and returns the total
224  * number of replays as a sum of the NAKs generated and NAKs received.
225  */
226 
227 static ssize_t amdgpu_device_get_pcie_replay_count(struct device *dev,
228 		struct device_attribute *attr, char *buf)
229 {
230 	struct drm_device *ddev = dev_get_drvdata(dev);
231 	struct amdgpu_device *adev = drm_to_adev(ddev);
232 	uint64_t cnt = amdgpu_asic_get_pcie_replay_count(adev);
233 
234 	return sysfs_emit(buf, "%llu\n", cnt);
235 }
236 
237 static DEVICE_ATTR(pcie_replay_count, 0444,
238 		amdgpu_device_get_pcie_replay_count, NULL);
239 
240 static int amdgpu_device_attr_sysfs_init(struct amdgpu_device *adev)
241 {
242 	int ret = 0;
243 
244 	if (amdgpu_nbio_is_replay_cnt_supported(adev))
245 		ret = sysfs_create_file(&adev->dev->kobj,
246 					&dev_attr_pcie_replay_count.attr);
247 
248 	return ret;
249 }
250 
251 static void amdgpu_device_attr_sysfs_fini(struct amdgpu_device *adev)
252 {
253 	if (amdgpu_nbio_is_replay_cnt_supported(adev))
254 		sysfs_remove_file(&adev->dev->kobj,
255 				  &dev_attr_pcie_replay_count.attr);
256 }
257 
258 static ssize_t amdgpu_sysfs_reg_state_get(struct file *f, struct kobject *kobj,
259 					  const struct bin_attribute *attr, char *buf,
260 					  loff_t ppos, size_t count)
261 {
262 	struct device *dev = kobj_to_dev(kobj);
263 	struct drm_device *ddev = dev_get_drvdata(dev);
264 	struct amdgpu_device *adev = drm_to_adev(ddev);
265 	ssize_t bytes_read;
266 
267 	switch (ppos) {
268 	case AMDGPU_SYS_REG_STATE_XGMI:
269 		bytes_read = amdgpu_asic_get_reg_state(
270 			adev, AMDGPU_REG_STATE_TYPE_XGMI, buf, count);
271 		break;
272 	case AMDGPU_SYS_REG_STATE_WAFL:
273 		bytes_read = amdgpu_asic_get_reg_state(
274 			adev, AMDGPU_REG_STATE_TYPE_WAFL, buf, count);
275 		break;
276 	case AMDGPU_SYS_REG_STATE_PCIE:
277 		bytes_read = amdgpu_asic_get_reg_state(
278 			adev, AMDGPU_REG_STATE_TYPE_PCIE, buf, count);
279 		break;
280 	case AMDGPU_SYS_REG_STATE_USR:
281 		bytes_read = amdgpu_asic_get_reg_state(
282 			adev, AMDGPU_REG_STATE_TYPE_USR, buf, count);
283 		break;
284 	case AMDGPU_SYS_REG_STATE_USR_1:
285 		bytes_read = amdgpu_asic_get_reg_state(
286 			adev, AMDGPU_REG_STATE_TYPE_USR_1, buf, count);
287 		break;
288 	default:
289 		return -EINVAL;
290 	}
291 
292 	return bytes_read;
293 }
294 
295 static const BIN_ATTR(reg_state, 0444, amdgpu_sysfs_reg_state_get, NULL,
296 		      AMDGPU_SYS_REG_STATE_END);
297 
298 int amdgpu_reg_state_sysfs_init(struct amdgpu_device *adev)
299 {
300 	int ret;
301 
302 	if (!amdgpu_asic_get_reg_state_supported(adev))
303 		return 0;
304 
305 	ret = sysfs_create_bin_file(&adev->dev->kobj, &bin_attr_reg_state);
306 
307 	return ret;
308 }
309 
310 void amdgpu_reg_state_sysfs_fini(struct amdgpu_device *adev)
311 {
312 	if (!amdgpu_asic_get_reg_state_supported(adev))
313 		return;
314 	sysfs_remove_bin_file(&adev->dev->kobj, &bin_attr_reg_state);
315 }
316 
317 /**
318  * DOC: board_info
319  *
320  * The amdgpu driver provides a sysfs API for giving board related information.
321  * It provides the form factor information in the format
322  *
323  *   type : form factor
324  *
325  * Possible form factor values
326  *
327  * - "cem"		- PCIE CEM card
328  * - "oam"		- Open Compute Accelerator Module
329  * - "unknown"	- Not known
330  *
331  */
332 
333 static ssize_t amdgpu_device_get_board_info(struct device *dev,
334 					    struct device_attribute *attr,
335 					    char *buf)
336 {
337 	struct drm_device *ddev = dev_get_drvdata(dev);
338 	struct amdgpu_device *adev = drm_to_adev(ddev);
339 	enum amdgpu_pkg_type pkg_type = AMDGPU_PKG_TYPE_CEM;
340 	const char *pkg;
341 
342 	if (adev->smuio.funcs && adev->smuio.funcs->get_pkg_type)
343 		pkg_type = adev->smuio.funcs->get_pkg_type(adev);
344 
345 	switch (pkg_type) {
346 	case AMDGPU_PKG_TYPE_CEM:
347 		pkg = "cem";
348 		break;
349 	case AMDGPU_PKG_TYPE_OAM:
350 		pkg = "oam";
351 		break;
352 	default:
353 		pkg = "unknown";
354 		break;
355 	}
356 
357 	return sysfs_emit(buf, "%s : %s\n", "type", pkg);
358 }
359 
360 static DEVICE_ATTR(board_info, 0444, amdgpu_device_get_board_info, NULL);
361 
362 static struct attribute *amdgpu_board_attrs[] = {
363 	&dev_attr_board_info.attr,
364 	NULL,
365 };
366 
367 static umode_t amdgpu_board_attrs_is_visible(struct kobject *kobj,
368 					     struct attribute *attr, int n)
369 {
370 	struct device *dev = kobj_to_dev(kobj);
371 	struct drm_device *ddev = dev_get_drvdata(dev);
372 	struct amdgpu_device *adev = drm_to_adev(ddev);
373 
374 	if (adev->flags & AMD_IS_APU)
375 		return 0;
376 
377 	return attr->mode;
378 }
379 
380 static const struct attribute_group amdgpu_board_attrs_group = {
381 	.attrs = amdgpu_board_attrs,
382 	.is_visible = amdgpu_board_attrs_is_visible
383 };
384 
385 /**
386  * DOC: uma/carveout_options
387  *
388  * This is a read-only file that lists all available UMA allocation
389  * options and their corresponding indices. Example output::
390  *
391  *     $ cat uma/carveout_options
392  *     0: Minimum (512 MB)
393  *     1:  (1 GB)
394  *     2:  (2 GB)
395  *     3:  (4 GB)
396  *     4:  (6 GB)
397  *     5:  (8 GB)
398  *     6:  (12 GB)
399  *     7: Medium (16 GB)
400  *     8:  (24 GB)
401  *     9: High (32 GB)
402  */
403 static ssize_t carveout_options_show(struct device *dev,
404 				     struct device_attribute *attr,
405 				     char *buf)
406 {
407 	struct drm_device *ddev = dev_get_drvdata(dev);
408 	struct amdgpu_device *adev = drm_to_adev(ddev);
409 	struct amdgpu_uma_carveout_info *uma_info = &adev->uma_info;
410 	uint32_t memory_carved;
411 	ssize_t size = 0;
412 
413 	if (!uma_info || !uma_info->num_entries)
414 		return -ENODEV;
415 
416 	for (int i = 0; i < uma_info->num_entries; i++) {
417 		memory_carved = uma_info->entries[i].memory_carved_mb;
418 		if (memory_carved >= SZ_1G/SZ_1M) {
419 			size += sysfs_emit_at(buf, size, "%d: %s (%u GB)\n",
420 					      i,
421 					      uma_info->entries[i].name,
422 					      memory_carved >> 10);
423 		} else {
424 			size += sysfs_emit_at(buf, size, "%d: %s (%u MB)\n",
425 					      i,
426 					      uma_info->entries[i].name,
427 					      memory_carved);
428 		}
429 	}
430 
431 	return size;
432 }
433 static DEVICE_ATTR_RO(carveout_options);
434 
435 /**
436  * DOC: uma/carveout
437  *
438  * This file is both readable and writable. When read, it shows the
439  * index of the current setting. Writing a valid index to this file
440  * allows users to change the UMA carveout size to the selected option
441  * on the next boot.
442  *
443  * The available options and their corresponding indices can be read
444  * from the uma/carveout_options file.
445  */
446 static ssize_t carveout_show(struct device *dev,
447 			     struct device_attribute *attr,
448 			     char *buf)
449 {
450 	struct drm_device *ddev = dev_get_drvdata(dev);
451 	struct amdgpu_device *adev = drm_to_adev(ddev);
452 
453 	return sysfs_emit(buf, "%u\n", adev->uma_info.uma_option_index);
454 }
455 
456 static ssize_t carveout_store(struct device *dev,
457 			      struct device_attribute *attr,
458 			      const char *buf, size_t count)
459 {
460 	struct drm_device *ddev = dev_get_drvdata(dev);
461 	struct amdgpu_device *adev = drm_to_adev(ddev);
462 	struct amdgpu_uma_carveout_info *uma_info = &adev->uma_info;
463 	struct amdgpu_uma_carveout_option *opt;
464 	unsigned long val;
465 	uint8_t flags;
466 	int r;
467 
468 	r = kstrtoul(buf, 10, &val);
469 	if (r)
470 		return r;
471 
472 	if (val >= uma_info->num_entries)
473 		return -EINVAL;
474 
475 	val = array_index_nospec(val, uma_info->num_entries);
476 	opt = &uma_info->entries[val];
477 
478 	if (!(opt->flags & AMDGPU_UMA_FLAG_AUTO) &&
479 	    !(opt->flags & AMDGPU_UMA_FLAG_CUSTOM)) {
480 		drm_err_once(ddev, "Option %lu not supported due to lack of Custom/Auto flag", val);
481 		return -EINVAL;
482 	}
483 
484 	flags = opt->flags;
485 	flags &= ~((flags & AMDGPU_UMA_FLAG_AUTO) >> 1);
486 
487 	guard(mutex)(&uma_info->update_lock);
488 
489 	r = amdgpu_acpi_set_uma_allocation_size(adev, val, flags);
490 	if (r)
491 		return r;
492 
493 	uma_info->uma_option_index = val;
494 
495 	return count;
496 }
497 static DEVICE_ATTR_RW(carveout);
498 
499 static struct attribute *amdgpu_uma_attrs[] = {
500 	&dev_attr_carveout.attr,
501 	&dev_attr_carveout_options.attr,
502 	NULL
503 };
504 
505 const struct attribute_group amdgpu_uma_attr_group = {
506 	.name = "uma",
507 	.attrs = amdgpu_uma_attrs
508 };
509 
510 static void amdgpu_uma_sysfs_init(struct amdgpu_device *adev)
511 {
512 	int rc;
513 
514 	if (!(adev->flags & AMD_IS_APU))
515 		return;
516 
517 	if (!amdgpu_acpi_is_set_uma_allocation_size_supported())
518 		return;
519 
520 	rc = amdgpu_atomfirmware_get_uma_carveout_info(adev, &adev->uma_info);
521 	if (rc) {
522 		drm_dbg(adev_to_drm(adev),
523 			"Failed to parse UMA carveout info from VBIOS: %d\n", rc);
524 		goto out_info;
525 	}
526 
527 	mutex_init(&adev->uma_info.update_lock);
528 
529 	rc = devm_device_add_group(adev->dev, &amdgpu_uma_attr_group);
530 	if (rc) {
531 		drm_dbg(adev_to_drm(adev), "Failed to add UMA carveout sysfs interfaces %d\n", rc);
532 		goto out_attr;
533 	}
534 
535 	return;
536 
537 out_attr:
538 	mutex_destroy(&adev->uma_info.update_lock);
539 out_info:
540 	return;
541 }
542 
543 static void amdgpu_uma_sysfs_fini(struct amdgpu_device *adev)
544 {
545 	struct amdgpu_uma_carveout_info *uma_info = &adev->uma_info;
546 
547 	if (!amdgpu_acpi_is_set_uma_allocation_size_supported())
548 		return;
549 
550 	mutex_destroy(&uma_info->update_lock);
551 	uma_info->num_entries = 0;
552 }
553 
554 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev);
555 
556 /**
557  * amdgpu_device_supports_px - Is the device a dGPU with ATPX power control
558  *
559  * @adev: amdgpu device pointer
560  *
561  * Returns true if the device is a dGPU with ATPX power control,
562  * otherwise return false.
563  */
564 bool amdgpu_device_supports_px(struct amdgpu_device *adev)
565 {
566 	if ((adev->flags & AMD_IS_PX) && !amdgpu_is_atpx_hybrid())
567 		return true;
568 	return false;
569 }
570 
571 /**
572  * amdgpu_device_supports_boco - Is the device a dGPU with ACPI power resources
573  *
574  * @adev: amdgpu device pointer
575  *
576  * Returns true if the device is a dGPU with ACPI power control,
577  * otherwise return false.
578  */
579 bool amdgpu_device_supports_boco(struct amdgpu_device *adev)
580 {
581 	if (!IS_ENABLED(CONFIG_HOTPLUG_PCI_PCIE))
582 		return false;
583 
584 	if (adev->has_pr3 ||
585 	    ((adev->flags & AMD_IS_PX) && amdgpu_is_atpx_hybrid()))
586 		return true;
587 	return false;
588 }
589 
590 /**
591  * amdgpu_device_supports_baco - Does the device support BACO
592  *
593  * @adev: amdgpu device pointer
594  *
595  * Return:
596  * 1 if the device supports BACO;
597  * 3 if the device supports MACO (only works if BACO is supported)
598  * otherwise return 0.
599  */
600 int amdgpu_device_supports_baco(struct amdgpu_device *adev)
601 {
602 	return amdgpu_asic_supports_baco(adev);
603 }
604 
605 void amdgpu_device_detect_runtime_pm_mode(struct amdgpu_device *adev)
606 {
607 	int bamaco_support;
608 
609 	adev->pm.rpm_mode = AMDGPU_RUNPM_NONE;
610 	bamaco_support = amdgpu_device_supports_baco(adev);
611 
612 	switch (amdgpu_runtime_pm) {
613 	case 2:
614 		if (bamaco_support & MACO_SUPPORT) {
615 			adev->pm.rpm_mode = AMDGPU_RUNPM_BAMACO;
616 			dev_info(adev->dev, "Forcing BAMACO for runtime pm\n");
617 		} else if (bamaco_support == BACO_SUPPORT) {
618 			adev->pm.rpm_mode = AMDGPU_RUNPM_BACO;
619 			dev_info(adev->dev, "Requested mode BAMACO not available,fallback to use BACO\n");
620 		}
621 		break;
622 	case 1:
623 		if (bamaco_support & BACO_SUPPORT) {
624 			adev->pm.rpm_mode = AMDGPU_RUNPM_BACO;
625 			dev_info(adev->dev, "Forcing BACO for runtime pm\n");
626 		}
627 		break;
628 	case -1:
629 	case -2:
630 		if (amdgpu_device_supports_px(adev)) {
631 			/* enable PX as runtime mode */
632 			adev->pm.rpm_mode = AMDGPU_RUNPM_PX;
633 			dev_info(adev->dev, "Using ATPX for runtime pm\n");
634 		} else if (amdgpu_device_supports_boco(adev)) {
635 			/* enable boco as runtime mode */
636 			adev->pm.rpm_mode = AMDGPU_RUNPM_BOCO;
637 			dev_info(adev->dev, "Using BOCO for runtime pm\n");
638 		} else {
639 			if (!bamaco_support)
640 				goto no_runtime_pm;
641 
642 			switch (adev->asic_type) {
643 			case CHIP_VEGA20:
644 			case CHIP_ARCTURUS:
645 				/* BACO are not supported on vega20 and arctrus */
646 				break;
647 			case CHIP_VEGA10:
648 				/* enable BACO as runpm mode if noretry=0 */
649 				if (!adev->gmc.noretry && !amdgpu_passthrough(adev))
650 					adev->pm.rpm_mode = AMDGPU_RUNPM_BACO;
651 				break;
652 			default:
653 				/* enable BACO as runpm mode on CI+ */
654 				if (!amdgpu_passthrough(adev))
655 					adev->pm.rpm_mode = AMDGPU_RUNPM_BACO;
656 				break;
657 			}
658 
659 			if (adev->pm.rpm_mode == AMDGPU_RUNPM_BACO) {
660 				if (bamaco_support & MACO_SUPPORT) {
661 					adev->pm.rpm_mode = AMDGPU_RUNPM_BAMACO;
662 					dev_info(adev->dev, "Using BAMACO for runtime pm\n");
663 				} else {
664 					dev_info(adev->dev, "Using BACO for runtime pm\n");
665 				}
666 			}
667 		}
668 		break;
669 	case 0:
670 		dev_info(adev->dev, "runtime pm is manually disabled\n");
671 		break;
672 	default:
673 		break;
674 	}
675 
676 no_runtime_pm:
677 	if (adev->pm.rpm_mode == AMDGPU_RUNPM_NONE)
678 		dev_info(adev->dev, "Runtime PM not available\n");
679 }
680 /**
681  * amdgpu_device_supports_smart_shift - Is the device dGPU with
682  * smart shift support
683  *
684  * @adev: amdgpu device pointer
685  *
686  * Returns true if the device is a dGPU with Smart Shift support,
687  * otherwise returns false.
688  */
689 bool amdgpu_device_supports_smart_shift(struct amdgpu_device *adev)
690 {
691 	return (amdgpu_device_supports_boco(adev) &&
692 		amdgpu_acpi_is_power_shift_control_supported());
693 }
694 
695 /*
696  * VRAM access helper functions
697  */
698 
699 /**
700  * amdgpu_device_mm_access - access vram by MM_INDEX/MM_DATA
701  *
702  * @adev: amdgpu_device pointer
703  * @pos: offset of the buffer in vram
704  * @buf: virtual address of the buffer in system memory
705  * @size: read/write size, sizeof(@buf) must > @size
706  * @write: true - write to vram, otherwise - read from vram
707  */
708 void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos,
709 			     void *buf, size_t size, bool write)
710 {
711 	unsigned long flags;
712 	uint32_t hi = ~0, tmp = 0;
713 	uint32_t *data = buf;
714 	uint64_t last;
715 	int idx;
716 
717 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
718 		return;
719 
720 	if (!IS_ALIGNED(pos, 4) || !IS_ALIGNED(size, 4)) {
721 		dev_err(adev->dev, "unaligned pos/size (pos=0x%llx, size=0x%zx)\n",
722 			pos, size);
723 		drm_dev_exit(idx);
724 		return;
725 	}
726 
727 	spin_lock_irqsave(&adev->mmio_idx_lock, flags);
728 	for (last = pos + size; pos < last; pos += 4) {
729 		tmp = pos >> 31;
730 
731 		WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000);
732 		if (tmp != hi) {
733 			WREG32_NO_KIQ(mmMM_INDEX_HI, tmp);
734 			hi = tmp;
735 		}
736 		if (write)
737 			WREG32_NO_KIQ(mmMM_DATA, *data++);
738 		else
739 			*data++ = RREG32_NO_KIQ(mmMM_DATA);
740 	}
741 
742 	spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
743 	drm_dev_exit(idx);
744 }
745 
746 /**
747  * amdgpu_device_aper_access - access vram by vram aperture
748  *
749  * @adev: amdgpu_device pointer
750  * @pos: offset of the buffer in vram
751  * @buf: virtual address of the buffer in system memory
752  * @size: read/write size, sizeof(@buf) must > @size
753  * @write: true - write to vram, otherwise - read from vram
754  *
755  * The return value means how many bytes have been transferred.
756  */
757 size_t amdgpu_device_aper_access(struct amdgpu_device *adev, loff_t pos,
758 				 void *buf, size_t size, bool write)
759 {
760 #ifdef CONFIG_64BIT
761 	void __iomem *addr;
762 	size_t count = 0;
763 	uint64_t last;
764 
765 	if (!adev->mman.aper_base_kaddr)
766 		return 0;
767 
768 	last = min(pos + size, adev->gmc.visible_vram_size);
769 	if (last > pos) {
770 		addr = adev->mman.aper_base_kaddr + pos;
771 		count = last - pos;
772 
773 		if (write) {
774 			memcpy_toio(addr, buf, count);
775 			/* Make sure HDP write cache flush happens without any reordering
776 			 * after the system memory contents are sent over PCIe device
777 			 */
778 			mb();
779 			amdgpu_device_flush_hdp(adev, NULL);
780 		} else {
781 			amdgpu_device_invalidate_hdp(adev, NULL);
782 			/* Make sure HDP read cache is invalidated before issuing a read
783 			 * to the PCIe device
784 			 */
785 			mb();
786 			memcpy_fromio(buf, addr, count);
787 		}
788 
789 	}
790 
791 	return count;
792 #else
793 	return 0;
794 #endif
795 }
796 
797 /**
798  * amdgpu_device_vram_access - read/write a buffer in vram
799  *
800  * @adev: amdgpu_device pointer
801  * @pos: offset of the buffer in vram
802  * @buf: virtual address of the buffer in system memory
803  * @size: read/write size, sizeof(@buf) must > @size
804  * @write: true - write to vram, otherwise - read from vram
805  */
806 void amdgpu_device_vram_access(struct amdgpu_device *adev, loff_t pos,
807 			       void *buf, size_t size, bool write)
808 {
809 	size_t count;
810 
811 	/* try to using vram apreature to access vram first */
812 	count = amdgpu_device_aper_access(adev, pos, buf, size, write);
813 	size -= count;
814 	if (size) {
815 		/* using MM to access rest vram */
816 		pos += count;
817 		buf += count;
818 		amdgpu_device_mm_access(adev, pos, buf, size, write);
819 	}
820 }
821 
822 /*
823  * register access helper functions.
824  */
825 
826 /* Check if hw access should be skipped because of hotplug or device error */
827 bool amdgpu_device_skip_hw_access(struct amdgpu_device *adev)
828 {
829 	if (adev->no_hw_access)
830 		return true;
831 
832 #ifdef CONFIG_LOCKDEP
833 	/*
834 	 * This is a bit complicated to understand, so worth a comment. What we assert
835 	 * here is that the GPU reset is not running on another thread in parallel.
836 	 *
837 	 * For this we trylock the read side of the reset semaphore, if that succeeds
838 	 * we know that the reset is not running in parallel.
839 	 *
840 	 * If the trylock fails we assert that we are either already holding the read
841 	 * side of the lock or are the reset thread itself and hold the write side of
842 	 * the lock.
843 	 */
844 	if (in_task()) {
845 		if (down_read_trylock(&adev->reset_domain->sem))
846 			up_read(&adev->reset_domain->sem);
847 		else
848 			lockdep_assert_held(&adev->reset_domain->sem);
849 	}
850 #endif
851 	return false;
852 }
853 
854 /**
855  * amdgpu_device_get_rev_id - query device rev_id
856  *
857  * @adev: amdgpu_device pointer
858  *
859  * Return device rev_id
860  */
861 u32 amdgpu_device_get_rev_id(struct amdgpu_device *adev)
862 {
863 	return adev->nbio.funcs->get_rev_id(adev);
864 }
865 
866 static uint32_t amdgpu_device_get_vbios_flags(struct amdgpu_device *adev)
867 {
868 	if (hweight32(adev->aid_mask) && (adev->flags & AMD_IS_APU))
869 		return AMDGPU_VBIOS_SKIP;
870 
871 	if (hweight32(adev->aid_mask) && amdgpu_passthrough(adev))
872 		return AMDGPU_VBIOS_OPTIONAL;
873 
874 	return 0;
875 }
876 
877 /**
878  * amdgpu_device_asic_init - Wrapper for atom asic_init
879  *
880  * @adev: amdgpu_device pointer
881  *
882  * Does any asic specific work and then calls atom asic init.
883  */
884 static int amdgpu_device_asic_init(struct amdgpu_device *adev)
885 {
886 	uint32_t flags;
887 	bool optional;
888 	int ret;
889 
890 	amdgpu_asic_pre_asic_init(adev);
891 	flags = amdgpu_device_get_vbios_flags(adev);
892 	optional = !!(flags & (AMDGPU_VBIOS_OPTIONAL | AMDGPU_VBIOS_SKIP));
893 
894 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) ||
895 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 4) ||
896 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 5, 0) ||
897 	    amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0)) {
898 		amdgpu_psp_wait_for_bootloader(adev);
899 		if (optional && !adev->bios)
900 			return 0;
901 
902 		ret = amdgpu_atomfirmware_asic_init(adev, true);
903 		return ret;
904 	} else {
905 		if (optional && !adev->bios)
906 			return 0;
907 
908 		return amdgpu_atom_asic_init(adev->mode_info.atom_context);
909 	}
910 
911 	return 0;
912 }
913 
914 /**
915  * amdgpu_device_mem_scratch_init - allocate the VRAM scratch page
916  *
917  * @adev: amdgpu_device pointer
918  *
919  * Allocates a scratch page of VRAM for use by various things in the
920  * driver.
921  */
922 static int amdgpu_device_mem_scratch_init(struct amdgpu_device *adev)
923 {
924 	return amdgpu_bo_create_kernel(adev, AMDGPU_GPU_PAGE_SIZE, PAGE_SIZE,
925 				       AMDGPU_GEM_DOMAIN_VRAM |
926 				       AMDGPU_GEM_DOMAIN_GTT,
927 				       &adev->mem_scratch.robj,
928 				       &adev->mem_scratch.gpu_addr,
929 				       (void **)&adev->mem_scratch.ptr);
930 }
931 
932 /**
933  * amdgpu_device_mem_scratch_fini - Free the VRAM scratch page
934  *
935  * @adev: amdgpu_device pointer
936  *
937  * Frees the VRAM scratch page.
938  */
939 static void amdgpu_device_mem_scratch_fini(struct amdgpu_device *adev)
940 {
941 	amdgpu_bo_free_kernel(&adev->mem_scratch.robj, NULL, NULL);
942 }
943 
944 /**
945  * amdgpu_device_program_register_sequence - program an array of registers.
946  *
947  * @adev: amdgpu_device pointer
948  * @registers: pointer to the register array
949  * @array_size: size of the register array
950  *
951  * Programs an array or registers with and or masks.
952  * This is a helper for setting golden registers.
953  */
954 void amdgpu_device_program_register_sequence(struct amdgpu_device *adev,
955 					     const u32 *registers,
956 					     const u32 array_size)
957 {
958 	u32 tmp, reg, and_mask, or_mask;
959 	int i;
960 
961 	if (array_size % 3)
962 		return;
963 
964 	for (i = 0; i < array_size; i += 3) {
965 		reg = registers[i + 0];
966 		and_mask = registers[i + 1];
967 		or_mask = registers[i + 2];
968 
969 		if (and_mask == 0xffffffff) {
970 			tmp = or_mask;
971 		} else {
972 			tmp = RREG32(reg);
973 			tmp &= ~and_mask;
974 			if (adev->family >= AMDGPU_FAMILY_AI)
975 				tmp |= (or_mask & and_mask);
976 			else
977 				tmp |= or_mask;
978 		}
979 		WREG32(reg, tmp);
980 	}
981 }
982 
983 /**
984  * amdgpu_device_pci_config_reset - reset the GPU
985  *
986  * @adev: amdgpu_device pointer
987  *
988  * Resets the GPU using the pci config reset sequence.
989  * Only applicable to asics prior to vega10.
990  */
991 void amdgpu_device_pci_config_reset(struct amdgpu_device *adev)
992 {
993 	pci_write_config_dword(adev->pdev, 0x7c, AMDGPU_ASIC_RESET_DATA);
994 }
995 
996 /**
997  * amdgpu_device_pci_reset - reset the GPU using generic PCI means
998  *
999  * @adev: amdgpu_device pointer
1000  *
1001  * Resets the GPU using generic pci reset interfaces (FLR, SBR, etc.).
1002  */
1003 int amdgpu_device_pci_reset(struct amdgpu_device *adev)
1004 {
1005 	return pci_reset_function(adev->pdev);
1006 }
1007 
1008 /*
1009  * amdgpu_device_wb_*()
1010  * Writeback is the method by which the GPU updates special pages in memory
1011  * with the status of certain GPU events (fences, ring pointers,etc.).
1012  */
1013 
1014 /**
1015  * amdgpu_device_wb_fini - Disable Writeback and free memory
1016  *
1017  * @adev: amdgpu_device pointer
1018  *
1019  * Disables Writeback and frees the Writeback memory (all asics).
1020  * Used at driver shutdown.
1021  */
1022 static void amdgpu_device_wb_fini(struct amdgpu_device *adev)
1023 {
1024 	if (adev->wb.wb_obj) {
1025 		amdgpu_bo_free_kernel(&adev->wb.wb_obj,
1026 				      &adev->wb.gpu_addr,
1027 				      (void **)&adev->wb.wb);
1028 		adev->wb.wb_obj = NULL;
1029 	}
1030 }
1031 
1032 /**
1033  * amdgpu_device_wb_init - Init Writeback driver info and allocate memory
1034  *
1035  * @adev: amdgpu_device pointer
1036  *
1037  * Initializes writeback and allocates writeback memory (all asics).
1038  * Used at driver startup.
1039  * Returns 0 on success or an -error on failure.
1040  */
1041 static int amdgpu_device_wb_init(struct amdgpu_device *adev)
1042 {
1043 	int r;
1044 
1045 	if (adev->wb.wb_obj == NULL) {
1046 		/* AMDGPU_MAX_WB * sizeof(uint32_t) * 8 = AMDGPU_MAX_WB 256bit slots */
1047 		r = amdgpu_bo_create_kernel(adev, AMDGPU_MAX_WB * sizeof(uint32_t) * 8,
1048 					    PAGE_SIZE, AMDGPU_GEM_DOMAIN_GTT,
1049 					    &adev->wb.wb_obj, &adev->wb.gpu_addr,
1050 					    (void **)&adev->wb.wb);
1051 		if (r) {
1052 			dev_warn(adev->dev, "(%d) create WB bo failed\n", r);
1053 			return r;
1054 		}
1055 
1056 		adev->wb.num_wb = AMDGPU_MAX_WB;
1057 		memset(&adev->wb.used, 0, sizeof(adev->wb.used));
1058 
1059 		/* clear wb memory */
1060 		memset((char *)adev->wb.wb, 0, AMDGPU_MAX_WB * sizeof(uint32_t) * 8);
1061 	}
1062 
1063 	return 0;
1064 }
1065 
1066 /**
1067  * amdgpu_device_wb_get - Allocate a wb entry
1068  *
1069  * @adev: amdgpu_device pointer
1070  * @wb: wb index
1071  *
1072  * Allocate a wb slot for use by the driver (all asics).
1073  * Returns 0 on success or -EINVAL on failure.
1074  */
1075 int amdgpu_device_wb_get(struct amdgpu_device *adev, u32 *wb)
1076 {
1077 	unsigned long flags, offset;
1078 
1079 	spin_lock_irqsave(&adev->wb.lock, flags);
1080 	offset = find_first_zero_bit(adev->wb.used, adev->wb.num_wb);
1081 	if (offset < adev->wb.num_wb) {
1082 		__set_bit(offset, adev->wb.used);
1083 		spin_unlock_irqrestore(&adev->wb.lock, flags);
1084 		*wb = offset << 3; /* convert to dw offset */
1085 		return 0;
1086 	} else {
1087 		spin_unlock_irqrestore(&adev->wb.lock, flags);
1088 		return -EINVAL;
1089 	}
1090 }
1091 
1092 /**
1093  * amdgpu_device_wb_free - Free a wb entry
1094  *
1095  * @adev: amdgpu_device pointer
1096  * @wb: wb index
1097  *
1098  * Free a wb slot allocated for use by the driver (all asics)
1099  */
1100 void amdgpu_device_wb_free(struct amdgpu_device *adev, u32 wb)
1101 {
1102 	unsigned long flags;
1103 
1104 	wb >>= 3;
1105 	spin_lock_irqsave(&adev->wb.lock, flags);
1106 	if (wb < adev->wb.num_wb)
1107 		__clear_bit(wb, adev->wb.used);
1108 	spin_unlock_irqrestore(&adev->wb.lock, flags);
1109 }
1110 
1111 /**
1112  * amdgpu_device_resize_fb_bar - try to resize FB BAR
1113  *
1114  * @adev: amdgpu_device pointer
1115  *
1116  * Try to resize FB BAR to make all VRAM CPU accessible. We try very hard not
1117  * to fail, but if any of the BARs is not accessible after the size we abort
1118  * driver loading by returning -ENODEV.
1119  */
1120 int amdgpu_device_resize_fb_bar(struct amdgpu_device *adev)
1121 {
1122 	int rbar_size = pci_rebar_bytes_to_size(adev->gmc.real_vram_size);
1123 	struct pci_bus *root;
1124 	struct resource *res;
1125 	int max_size, r;
1126 	unsigned int i;
1127 	u16 cmd;
1128 
1129 	if (!IS_ENABLED(CONFIG_PHYS_ADDR_T_64BIT))
1130 		return 0;
1131 
1132 	/* Bypass for VF */
1133 	if (amdgpu_sriov_vf(adev))
1134 		return 0;
1135 
1136 	if (!amdgpu_rebar)
1137 		return 0;
1138 
1139 	/* resizing on Dell G5 SE platforms causes problems with runtime pm */
1140 	if ((amdgpu_runtime_pm != 0) &&
1141 	    adev->pdev->vendor == PCI_VENDOR_ID_ATI &&
1142 	    adev->pdev->device == 0x731f &&
1143 	    adev->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL)
1144 		return 0;
1145 
1146 	/* PCI_EXT_CAP_ID_VNDR extended capability is located at 0x100 */
1147 	if (!pci_find_ext_capability(adev->pdev, PCI_EXT_CAP_ID_VNDR))
1148 		dev_warn(
1149 			adev->dev,
1150 			"System can't access extended configuration space, please check!!\n");
1151 
1152 	/* skip if the bios has already enabled large BAR */
1153 	if (adev->gmc.real_vram_size &&
1154 	    (pci_resource_len(adev->pdev, 0) >= adev->gmc.real_vram_size))
1155 		return 0;
1156 
1157 	/* Check if the root BUS has 64bit memory resources */
1158 	root = adev->pdev->bus;
1159 	while (root->parent)
1160 		root = root->parent;
1161 
1162 	pci_bus_for_each_resource(root, res, i) {
1163 		if (res && res->flags & (IORESOURCE_MEM | IORESOURCE_MEM_64) &&
1164 		    res->start > 0x100000000ull)
1165 			break;
1166 	}
1167 
1168 	/* Trying to resize is pointless without a root hub window above 4GB */
1169 	if (!res)
1170 		return 0;
1171 
1172 	/* Limit the BAR size to what is available */
1173 	max_size = pci_rebar_get_max_size(adev->pdev, 0);
1174 	if (max_size < 0)
1175 		return 0;
1176 	rbar_size = min(max_size, rbar_size);
1177 
1178 	/* Disable memory decoding while we change the BAR addresses and size */
1179 	pci_read_config_word(adev->pdev, PCI_COMMAND, &cmd);
1180 	pci_write_config_word(adev->pdev, PCI_COMMAND,
1181 			      cmd & ~PCI_COMMAND_MEMORY);
1182 
1183 	/* Tear down doorbell as resizing will release BARs */
1184 	amdgpu_doorbell_fini(adev);
1185 
1186 	r = pci_resize_resource(adev->pdev, 0, rbar_size,
1187 				(adev->asic_type >= CHIP_BONAIRE) ? 1 << 5
1188 								  : 1 << 2);
1189 	if (r == -ENOSPC)
1190 		dev_info(adev->dev,
1191 			 "Not enough PCI address space for a large BAR.");
1192 	else if (r && r != -ENOTSUPP)
1193 		dev_err(adev->dev, "Problem resizing BAR0 (%d).", r);
1194 
1195 	/* When the doorbell or fb BAR isn't available we have no chance of
1196 	 * using the device.
1197 	 */
1198 	r = amdgpu_doorbell_init(adev);
1199 	if (r || (pci_resource_flags(adev->pdev, 0) & IORESOURCE_UNSET))
1200 		return -ENODEV;
1201 
1202 	pci_write_config_word(adev->pdev, PCI_COMMAND, cmd);
1203 
1204 	return 0;
1205 }
1206 
1207 /*
1208  * GPU helpers function.
1209  */
1210 /**
1211  * amdgpu_device_need_post - check if the hw need post or not
1212  *
1213  * @adev: amdgpu_device pointer
1214  *
1215  * Check if the asic has been initialized (all asics) at driver startup
1216  * or post is needed if  hw reset is performed.
1217  * Returns true if need or false if not.
1218  */
1219 bool amdgpu_device_need_post(struct amdgpu_device *adev)
1220 {
1221 	uint32_t reg, flags;
1222 
1223 	if (amdgpu_sriov_vf(adev))
1224 		return false;
1225 
1226 	flags = amdgpu_device_get_vbios_flags(adev);
1227 	if (flags & AMDGPU_VBIOS_SKIP)
1228 		return false;
1229 	if ((flags & AMDGPU_VBIOS_OPTIONAL) && !adev->bios)
1230 		return false;
1231 
1232 	if (amdgpu_passthrough(adev)) {
1233 		/* for FIJI: In whole GPU pass-through virtualization case, after VM reboot
1234 		 * some old smc fw still need driver do vPost otherwise gpu hang, while
1235 		 * those smc fw version above 22.15 doesn't have this flaw, so we force
1236 		 * vpost executed for smc version below 22.15
1237 		 */
1238 		if (adev->asic_type == CHIP_FIJI) {
1239 			int err;
1240 			uint32_t fw_ver;
1241 
1242 			err = request_firmware(&adev->pm.fw, "amdgpu/fiji_smc.bin", adev->dev);
1243 			/* force vPost if error occurred */
1244 			if (err)
1245 				return true;
1246 
1247 			fw_ver = *((uint32_t *)adev->pm.fw->data + 69);
1248 			release_firmware(adev->pm.fw);
1249 			if (fw_ver < 0x00160e00)
1250 				return true;
1251 		}
1252 	}
1253 
1254 	/* Don't post if we need to reset whole hive on init */
1255 	if (adev->init_lvl->level == AMDGPU_INIT_LEVEL_MINIMAL_XGMI)
1256 		return false;
1257 
1258 	if (adev->has_hw_reset) {
1259 		adev->has_hw_reset = false;
1260 		return true;
1261 	}
1262 
1263 	/* bios scratch used on CIK+ */
1264 	if (adev->asic_type >= CHIP_BONAIRE)
1265 		return amdgpu_atombios_scratch_need_asic_init(adev);
1266 
1267 	/* check MEM_SIZE for older asics */
1268 	reg = amdgpu_asic_get_config_memsize(adev);
1269 
1270 	if ((reg != 0) && (reg != 0xffffffff))
1271 		return false;
1272 
1273 	return true;
1274 }
1275 
1276 /*
1277  * Check whether seamless boot is supported.
1278  *
1279  * So far we only support seamless boot on DCE 3.0 or later.
1280  * If users report that it works on older ASICS as well, we may
1281  * loosen this.
1282  */
1283 bool amdgpu_device_seamless_boot_supported(struct amdgpu_device *adev)
1284 {
1285 	switch (amdgpu_seamless) {
1286 	case -1:
1287 		break;
1288 	case 1:
1289 		return true;
1290 	case 0:
1291 		return false;
1292 	default:
1293 		dev_err(adev->dev, "Invalid value for amdgpu.seamless: %d\n",
1294 			amdgpu_seamless);
1295 		return false;
1296 	}
1297 
1298 	if (!(adev->flags & AMD_IS_APU))
1299 		return false;
1300 
1301 	if (adev->mman.keep_stolen_vga_memory)
1302 		return false;
1303 
1304 	return amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0);
1305 }
1306 
1307 /*
1308  * Intel hosts such as Rocket Lake, Alder Lake, Raptor Lake and Sapphire Rapids
1309  * don't support dynamic speed switching. Until we have confirmation from Intel
1310  * that a specific host supports it, it's safer that we keep it disabled for all.
1311  *
1312  * https://edc.intel.com/content/www/us/en/design/products/platforms/details/raptor-lake-s/13th-generation-core-processors-datasheet-volume-1-of-2/005/pci-express-support/
1313  * https://gitlab.freedesktop.org/drm/amd/-/issues/2663
1314  */
1315 static bool amdgpu_device_pcie_dynamic_switching_supported(struct amdgpu_device *adev)
1316 {
1317 #if IS_ENABLED(CONFIG_X86)
1318 	struct cpuinfo_x86 *c = &cpu_data(0);
1319 
1320 	/* eGPU change speeds based on USB4 fabric conditions */
1321 	if (dev_is_removable(adev->dev))
1322 		return true;
1323 
1324 	if (c->x86_vendor == X86_VENDOR_INTEL)
1325 		return false;
1326 
1327 	/*
1328 	 * AMD Ryzen Pinnacle Ridge (Zen+, family 0x17 model 0x08) CPUs don't
1329 	 * support PCIe dynamic speed switching.
1330 	 * https://gitlab.freedesktop.org/drm/amd/-/work_items/5436
1331 	 */
1332 	if (c->x86_vendor == X86_VENDOR_AMD && c->x86 == 0x17 &&
1333 	    c->x86_model == 0x08)
1334 		return false;
1335 #endif
1336 	return true;
1337 }
1338 
1339 static bool amdgpu_device_aspm_support_quirk(struct amdgpu_device *adev)
1340 {
1341 	/* Enabling ASPM causes randoms hangs on Tahiti and Oland on Zen4.
1342 	 * It's unclear if this is a platform-specific or GPU-specific issue.
1343 	 * Disable ASPM on SI for the time being.
1344 	 */
1345 	if (adev->family == AMDGPU_FAMILY_SI ||
1346 		(!(adev->pm.pp_feature & PP_PCIE_DPM_MASK) && adev->family == AMDGPU_FAMILY_VI))
1347 		return true;
1348 
1349 #if IS_ENABLED(CONFIG_X86)
1350 	struct cpuinfo_x86 *c = &cpu_data(0);
1351 
1352 	if (c->x86_vendor == X86_VENDOR_INTEL) {
1353 		switch (c->x86_model) {
1354 		case VFM_MODEL(INTEL_ALDERLAKE):
1355 		case VFM_MODEL(INTEL_ALDERLAKE_L):
1356 		case VFM_MODEL(INTEL_RAPTORLAKE):
1357 		case VFM_MODEL(INTEL_RAPTORLAKE_P):
1358 		case VFM_MODEL(INTEL_RAPTORLAKE_S):
1359 		case VFM_MODEL(INTEL_TIGERLAKE):
1360 		case VFM_MODEL(INTEL_TIGERLAKE_L):
1361 			return true;
1362 		default:
1363 			return false;
1364 		}
1365 	} else {
1366 		return false;
1367 	}
1368 #else
1369 	return false;
1370 #endif
1371 }
1372 
1373 /**
1374  * amdgpu_device_should_use_aspm - check if the device should program ASPM
1375  *
1376  * @adev: amdgpu_device pointer
1377  *
1378  * Confirm whether the module parameter and pcie bridge agree that ASPM should
1379  * be set for this device.
1380  *
1381  * Returns true if it should be used or false if not.
1382  */
1383 bool amdgpu_device_should_use_aspm(struct amdgpu_device *adev)
1384 {
1385 	switch (amdgpu_aspm) {
1386 	case -1:
1387 		break;
1388 	case 0:
1389 		return false;
1390 	case 1:
1391 		return true;
1392 	default:
1393 		return false;
1394 	}
1395 	if (adev->flags & AMD_IS_APU)
1396 		return false;
1397 	if (amdgpu_device_aspm_support_quirk(adev))
1398 		return false;
1399 	return pcie_aspm_enabled(adev->pdev);
1400 }
1401 
1402 /* if we get transitioned to only one device, take VGA back */
1403 /**
1404  * amdgpu_device_vga_set_decode - enable/disable vga decode
1405  *
1406  * @pdev: PCI device pointer
1407  * @state: enable/disable vga decode
1408  *
1409  * Enable/disable vga decode (all asics).
1410  * Returns VGA resource flags.
1411  */
1412 static unsigned int amdgpu_device_vga_set_decode(struct pci_dev *pdev,
1413 		bool state)
1414 {
1415 	struct amdgpu_device *adev = drm_to_adev(pci_get_drvdata(pdev));
1416 
1417 	amdgpu_asic_set_vga_state(adev, state);
1418 	if (state)
1419 		return VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
1420 		       VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
1421 	else
1422 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
1423 }
1424 
1425 /**
1426  * amdgpu_device_check_block_size - validate the vm block size
1427  *
1428  * @adev: amdgpu_device pointer
1429  *
1430  * Validates the vm block size specified via module parameter.
1431  * The vm block size defines number of bits in page table versus page directory,
1432  * a page is 4KB so we have 12 bits offset, minimum 9 bits in the
1433  * page table and the remaining bits are in the page directory.
1434  */
1435 static void amdgpu_device_check_block_size(struct amdgpu_device *adev)
1436 {
1437 	/* defines number of bits in page table versus page directory,
1438 	 * a page is 4KB so we have 12 bits offset, minimum 9 bits in the
1439 	 * page table and the remaining bits are in the page directory
1440 	 */
1441 	if (amdgpu_vm_block_size == -1)
1442 		return;
1443 
1444 	if (amdgpu_vm_block_size < 9) {
1445 		dev_warn(adev->dev, "VM page table size (%d) too small\n",
1446 			 amdgpu_vm_block_size);
1447 		amdgpu_vm_block_size = -1;
1448 	}
1449 }
1450 
1451 /**
1452  * amdgpu_device_check_vm_size - validate the vm size
1453  *
1454  * @adev: amdgpu_device pointer
1455  *
1456  * Validates the vm size in GB specified via module parameter.
1457  * The VM size is the size of the GPU virtual memory space in GB.
1458  */
1459 static void amdgpu_device_check_vm_size(struct amdgpu_device *adev)
1460 {
1461 	/* no need to check the default value */
1462 	if (amdgpu_vm_size == -1)
1463 		return;
1464 
1465 	if (amdgpu_vm_size < 1) {
1466 		dev_warn(adev->dev, "VM size (%d) too small, min is 1GB\n",
1467 			 amdgpu_vm_size);
1468 		amdgpu_vm_size = -1;
1469 	}
1470 }
1471 
1472 static void amdgpu_device_check_smu_prv_buffer_size(struct amdgpu_device *adev)
1473 {
1474 	struct sysinfo si;
1475 	bool is_os_64 = (sizeof(void *) == 8);
1476 	uint64_t total_memory;
1477 	uint64_t dram_size_seven_GB = 0x1B8000000;
1478 	uint64_t dram_size_three_GB = 0xB8000000;
1479 
1480 	if (amdgpu_smu_memory_pool_size == 0)
1481 		return;
1482 
1483 	if (!is_os_64) {
1484 		dev_warn(adev->dev, "Not 64-bit OS, feature not supported\n");
1485 		goto def_value;
1486 	}
1487 	si_meminfo(&si);
1488 	total_memory = (uint64_t)si.totalram * si.mem_unit;
1489 
1490 	if ((amdgpu_smu_memory_pool_size == 1) ||
1491 		(amdgpu_smu_memory_pool_size == 2)) {
1492 		if (total_memory < dram_size_three_GB)
1493 			goto def_value1;
1494 	} else if ((amdgpu_smu_memory_pool_size == 4) ||
1495 		(amdgpu_smu_memory_pool_size == 8)) {
1496 		if (total_memory < dram_size_seven_GB)
1497 			goto def_value1;
1498 	} else {
1499 		dev_warn(adev->dev, "Smu memory pool size not supported\n");
1500 		goto def_value;
1501 	}
1502 	adev->pm.smu_prv_buffer_size = amdgpu_smu_memory_pool_size << 28;
1503 
1504 	return;
1505 
1506 def_value1:
1507 	dev_warn(adev->dev, "No enough system memory\n");
1508 def_value:
1509 	adev->pm.smu_prv_buffer_size = 0;
1510 }
1511 
1512 static int amdgpu_device_init_apu_flags(struct amdgpu_device *adev)
1513 {
1514 	if (!(adev->flags & AMD_IS_APU) ||
1515 	    adev->asic_type < CHIP_RAVEN)
1516 		return 0;
1517 
1518 	switch (adev->asic_type) {
1519 	case CHIP_RAVEN:
1520 		if (adev->pdev->device == 0x15dd)
1521 			adev->apu_flags |= AMD_APU_IS_RAVEN;
1522 		if (adev->pdev->device == 0x15d8)
1523 			adev->apu_flags |= AMD_APU_IS_PICASSO;
1524 		break;
1525 	case CHIP_RENOIR:
1526 		if ((adev->pdev->device == 0x1636) ||
1527 		    (adev->pdev->device == 0x164c))
1528 			adev->apu_flags |= AMD_APU_IS_RENOIR;
1529 		else
1530 			adev->apu_flags |= AMD_APU_IS_GREEN_SARDINE;
1531 		break;
1532 	case CHIP_VANGOGH:
1533 		adev->apu_flags |= AMD_APU_IS_VANGOGH;
1534 		break;
1535 	case CHIP_YELLOW_CARP:
1536 		break;
1537 	case CHIP_CYAN_SKILLFISH:
1538 		if ((adev->pdev->device == 0x13FE) ||
1539 		    (adev->pdev->device == 0x143F))
1540 			adev->apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2;
1541 		break;
1542 	default:
1543 		break;
1544 	}
1545 
1546 	return 0;
1547 }
1548 
1549 /**
1550  * amdgpu_device_check_arguments - validate module params
1551  *
1552  * @adev: amdgpu_device pointer
1553  *
1554  * Validates certain module parameters and updates
1555  * the associated values used by the driver (all asics).
1556  */
1557 static int amdgpu_device_check_arguments(struct amdgpu_device *adev)
1558 {
1559 	int i;
1560 
1561 	if (amdgpu_sched_jobs < 4) {
1562 		dev_warn(adev->dev, "sched jobs (%d) must be at least 4\n",
1563 			 amdgpu_sched_jobs);
1564 		amdgpu_sched_jobs = 4;
1565 	} else if (!is_power_of_2(amdgpu_sched_jobs)) {
1566 		dev_warn(adev->dev, "sched jobs (%d) must be a power of 2\n",
1567 			 amdgpu_sched_jobs);
1568 		amdgpu_sched_jobs = roundup_pow_of_two(amdgpu_sched_jobs);
1569 	}
1570 
1571 	if (amdgpu_gart_size != -1 && amdgpu_gart_size < 32) {
1572 		/* gart size must be greater or equal to 32M */
1573 		dev_warn(adev->dev, "gart size (%d) too small\n",
1574 			 amdgpu_gart_size);
1575 		amdgpu_gart_size = -1;
1576 	}
1577 
1578 	if (amdgpu_gtt_size != -1 && amdgpu_gtt_size < 32) {
1579 		/* gtt size must be greater or equal to 32M */
1580 		dev_warn(adev->dev, "gtt size (%d) too small\n",
1581 				 amdgpu_gtt_size);
1582 		amdgpu_gtt_size = -1;
1583 	}
1584 
1585 	/* valid range is between 4 and 9 inclusive */
1586 	if (amdgpu_vm_fragment_size != -1 &&
1587 	    (amdgpu_vm_fragment_size > 9 || amdgpu_vm_fragment_size < 4)) {
1588 		dev_warn(adev->dev, "valid range is between 4 and 9\n");
1589 		amdgpu_vm_fragment_size = -1;
1590 	}
1591 
1592 	if (amdgpu_sched_hw_submission < 2) {
1593 		dev_warn(adev->dev, "sched hw submission jobs (%d) must be at least 2\n",
1594 			 amdgpu_sched_hw_submission);
1595 		amdgpu_sched_hw_submission = 2;
1596 	} else if (!is_power_of_2(amdgpu_sched_hw_submission)) {
1597 		dev_warn(adev->dev, "sched hw submission jobs (%d) must be a power of 2\n",
1598 			 amdgpu_sched_hw_submission);
1599 		amdgpu_sched_hw_submission = roundup_pow_of_two(amdgpu_sched_hw_submission);
1600 	}
1601 
1602 	if (amdgpu_reset_method < -1 || amdgpu_reset_method > 4) {
1603 		dev_warn(adev->dev, "invalid option for reset method, reverting to default\n");
1604 		amdgpu_reset_method = -1;
1605 	}
1606 
1607 	amdgpu_device_check_smu_prv_buffer_size(adev);
1608 
1609 	amdgpu_device_check_vm_size(adev);
1610 
1611 	amdgpu_device_check_block_size(adev);
1612 
1613 	adev->firmware.load_type = amdgpu_ucode_get_load_type(adev, amdgpu_fw_load_type);
1614 
1615 	for (i = 0; i < MAX_XCP; i++) {
1616 		switch (amdgpu_enforce_isolation) {
1617 		case -1:
1618 		case 0:
1619 		default:
1620 			/* disable */
1621 			adev->enforce_isolation[i] = AMDGPU_ENFORCE_ISOLATION_DISABLE;
1622 			break;
1623 		case 1:
1624 			/* enable */
1625 			adev->enforce_isolation[i] =
1626 				AMDGPU_ENFORCE_ISOLATION_ENABLE;
1627 			break;
1628 		case 2:
1629 			/* enable legacy mode */
1630 			adev->enforce_isolation[i] =
1631 				AMDGPU_ENFORCE_ISOLATION_ENABLE_LEGACY;
1632 			break;
1633 		case 3:
1634 			/* enable only process isolation without submitting cleaner shader */
1635 			adev->enforce_isolation[i] =
1636 				AMDGPU_ENFORCE_ISOLATION_NO_CLEANER_SHADER;
1637 			break;
1638 		}
1639 	}
1640 
1641 	return 0;
1642 }
1643 
1644 /**
1645  * amdgpu_switcheroo_set_state - set switcheroo state
1646  *
1647  * @pdev: pci dev pointer
1648  * @state: vga_switcheroo state
1649  *
1650  * Callback for the switcheroo driver.  Suspends or resumes
1651  * the asics before or after it is powered up using ACPI methods.
1652  */
1653 static void amdgpu_switcheroo_set_state(struct pci_dev *pdev,
1654 					enum vga_switcheroo_state state)
1655 {
1656 	struct drm_device *dev = pci_get_drvdata(pdev);
1657 	int r;
1658 
1659 	if (amdgpu_device_supports_px(drm_to_adev(dev)) &&
1660 	    state == VGA_SWITCHEROO_OFF)
1661 		return;
1662 
1663 	if (state == VGA_SWITCHEROO_ON) {
1664 		pr_info("switched on\n");
1665 		/* don't suspend or resume card normally */
1666 		dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
1667 
1668 		pci_set_power_state(pdev, PCI_D0);
1669 		amdgpu_device_load_pci_state(pdev);
1670 		r = pci_enable_device(pdev);
1671 		if (r)
1672 			dev_warn(&pdev->dev, "pci_enable_device failed (%d)\n",
1673 				 r);
1674 		amdgpu_device_resume(dev, true);
1675 
1676 		dev->switch_power_state = DRM_SWITCH_POWER_ON;
1677 	} else {
1678 		dev_info(&pdev->dev, "switched off\n");
1679 		dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
1680 		amdgpu_device_prepare(dev);
1681 		amdgpu_device_suspend(dev, true);
1682 		amdgpu_device_cache_pci_state(pdev);
1683 		/* Shut down the device */
1684 		pci_disable_device(pdev);
1685 		pci_set_power_state(pdev, PCI_D3cold);
1686 		dev->switch_power_state = DRM_SWITCH_POWER_OFF;
1687 	}
1688 }
1689 
1690 /**
1691  * amdgpu_switcheroo_can_switch - see if switcheroo state can change
1692  *
1693  * @pdev: pci dev pointer
1694  *
1695  * Callback for the switcheroo driver.  Check of the switcheroo
1696  * state can be changed.
1697  * Returns true if the state can be changed, false if not.
1698  */
1699 static bool amdgpu_switcheroo_can_switch(struct pci_dev *pdev)
1700 {
1701 	struct drm_device *dev = pci_get_drvdata(pdev);
1702 
1703        /*
1704 	* FIXME: open_count is protected by drm_global_mutex but that would lead to
1705 	* locking inversion with the driver load path. And the access here is
1706 	* completely racy anyway. So don't bother with locking for now.
1707 	*/
1708 	return atomic_read(&dev->open_count) == 0;
1709 }
1710 
1711 static const struct vga_switcheroo_client_ops amdgpu_switcheroo_ops = {
1712 	.set_gpu_state = amdgpu_switcheroo_set_state,
1713 	.reprobe = NULL,
1714 	.can_switch = amdgpu_switcheroo_can_switch,
1715 };
1716 
1717 /**
1718  * amdgpu_device_enable_virtual_display - enable virtual display feature
1719  *
1720  * @adev: amdgpu_device pointer
1721  *
1722  * Enabled the virtual display feature if the user has enabled it via
1723  * the module parameter virtual_display.  This feature provides a virtual
1724  * display hardware on headless boards or in virtualized environments.
1725  * This function parses and validates the configuration string specified by
1726  * the user and configures the virtual display configuration (number of
1727  * virtual connectors, crtcs, etc.) specified.
1728  */
1729 static void amdgpu_device_enable_virtual_display(struct amdgpu_device *adev)
1730 {
1731 	adev->enable_virtual_display = false;
1732 
1733 	if (amdgpu_virtual_display) {
1734 		const char *pci_address_name = pci_name(adev->pdev);
1735 		char *pciaddstr, *pciaddstr_tmp, *pciaddname_tmp, *pciaddname;
1736 
1737 		pciaddstr = kstrdup(amdgpu_virtual_display, GFP_KERNEL);
1738 		pciaddstr_tmp = pciaddstr;
1739 		while ((pciaddname_tmp = strsep(&pciaddstr_tmp, ";"))) {
1740 			pciaddname = strsep(&pciaddname_tmp, ",");
1741 			if (!strcmp("all", pciaddname)
1742 			    || !strcmp(pci_address_name, pciaddname)) {
1743 				long num_crtc;
1744 				int res = -1;
1745 
1746 				adev->enable_virtual_display = true;
1747 
1748 				if (pciaddname_tmp)
1749 					res = kstrtol(pciaddname_tmp, 10,
1750 						      &num_crtc);
1751 
1752 				if (!res) {
1753 					if (num_crtc < 1)
1754 						num_crtc = 1;
1755 					if (num_crtc > 6)
1756 						num_crtc = 6;
1757 					adev->mode_info.num_crtc = num_crtc;
1758 				} else {
1759 					adev->mode_info.num_crtc = 1;
1760 				}
1761 				break;
1762 			}
1763 		}
1764 
1765 		dev_info(
1766 			adev->dev,
1767 			"virtual display string:%s, %s:virtual_display:%d, num_crtc:%d\n",
1768 			amdgpu_virtual_display, pci_address_name,
1769 			adev->enable_virtual_display, adev->mode_info.num_crtc);
1770 
1771 		kfree(pciaddstr);
1772 	}
1773 }
1774 
1775 void amdgpu_device_set_sriov_virtual_display(struct amdgpu_device *adev)
1776 {
1777 	if (amdgpu_sriov_vf(adev) && !adev->enable_virtual_display) {
1778 		adev->mode_info.num_crtc = 1;
1779 		adev->enable_virtual_display = true;
1780 		dev_info(adev->dev, "virtual_display:%d, num_crtc:%d\n",
1781 			 adev->enable_virtual_display,
1782 			 adev->mode_info.num_crtc);
1783 	}
1784 }
1785 
1786 /**
1787  * amdgpu_device_parse_gpu_info_fw - parse gpu info firmware
1788  *
1789  * @adev: amdgpu_device pointer
1790  *
1791  * Parses the asic configuration parameters specified in the gpu info
1792  * firmware and makes them available to the driver for use in configuring
1793  * the asic.
1794  * Returns 0 on success, -EINVAL on failure.
1795  */
1796 static int amdgpu_device_parse_gpu_info_fw(struct amdgpu_device *adev)
1797 {
1798 	const char *chip_name;
1799 	int err;
1800 	const struct gpu_info_firmware_header_v1_0 *hdr;
1801 
1802 	adev->firmware.gpu_info_fw = NULL;
1803 
1804 	switch (adev->asic_type) {
1805 	default:
1806 		return 0;
1807 	case CHIP_VEGA10:
1808 		chip_name = "vega10";
1809 		break;
1810 	case CHIP_VEGA12:
1811 		chip_name = "vega12";
1812 		break;
1813 	case CHIP_RAVEN:
1814 		if (adev->apu_flags & AMD_APU_IS_RAVEN2)
1815 			chip_name = "raven2";
1816 		else if (adev->apu_flags & AMD_APU_IS_PICASSO)
1817 			chip_name = "picasso";
1818 		else
1819 			chip_name = "raven";
1820 		break;
1821 	case CHIP_ARCTURUS:
1822 		chip_name = "arcturus";
1823 		break;
1824 	case CHIP_NAVI12:
1825 		if (adev->discovery.bin)
1826 			return 0;
1827 		chip_name = "navi12";
1828 		break;
1829 	case CHIP_CYAN_SKILLFISH:
1830 		if (adev->discovery.bin)
1831 			return 0;
1832 		chip_name = "cyan_skillfish";
1833 		break;
1834 	}
1835 
1836 	err = amdgpu_ucode_request(adev, &adev->firmware.gpu_info_fw,
1837 				   AMDGPU_UCODE_OPTIONAL,
1838 				   "amdgpu/%s_gpu_info.bin", chip_name);
1839 	if (err) {
1840 		dev_err(adev->dev,
1841 			"Failed to get gpu_info firmware \"%s_gpu_info.bin\"\n",
1842 			chip_name);
1843 		goto out;
1844 	}
1845 
1846 	hdr = (const struct gpu_info_firmware_header_v1_0 *)adev->firmware.gpu_info_fw->data;
1847 	amdgpu_ucode_print_gpu_info_hdr(&hdr->header);
1848 
1849 	switch (hdr->version_major) {
1850 	case 1:
1851 	{
1852 		const struct gpu_info_firmware_v1_0 *gpu_info_fw =
1853 			(const struct gpu_info_firmware_v1_0 *)(adev->firmware.gpu_info_fw->data +
1854 								le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1855 
1856 		/*
1857 		 * Should be dropped when DAL no longer needs it.
1858 		 */
1859 		if (adev->asic_type == CHIP_NAVI12)
1860 			goto parse_soc_bounding_box;
1861 
1862 		adev->gfx.config.max_shader_engines = le32_to_cpu(gpu_info_fw->gc_num_se);
1863 		adev->gfx.config.max_cu_per_sh = le32_to_cpu(gpu_info_fw->gc_num_cu_per_sh);
1864 		adev->gfx.config.max_sh_per_se = le32_to_cpu(gpu_info_fw->gc_num_sh_per_se);
1865 		adev->gfx.config.max_backends_per_se = le32_to_cpu(gpu_info_fw->gc_num_rb_per_se);
1866 		adev->gfx.config.max_texture_channel_caches =
1867 			le32_to_cpu(gpu_info_fw->gc_num_tccs);
1868 		adev->gfx.config.max_gprs = le32_to_cpu(gpu_info_fw->gc_num_gprs);
1869 		adev->gfx.config.max_gs_threads = le32_to_cpu(gpu_info_fw->gc_num_max_gs_thds);
1870 		adev->gfx.config.gs_vgt_table_depth = le32_to_cpu(gpu_info_fw->gc_gs_table_depth);
1871 		adev->gfx.config.gs_prim_buffer_depth = le32_to_cpu(gpu_info_fw->gc_gsprim_buff_depth);
1872 		adev->gfx.config.double_offchip_lds_buf =
1873 			le32_to_cpu(gpu_info_fw->gc_double_offchip_lds_buffer);
1874 		adev->gfx.cu_info.wave_front_size = le32_to_cpu(gpu_info_fw->gc_wave_size);
1875 		adev->gfx.cu_info.max_waves_per_simd =
1876 			le32_to_cpu(gpu_info_fw->gc_max_waves_per_simd);
1877 		adev->gfx.cu_info.max_scratch_slots_per_cu =
1878 			le32_to_cpu(gpu_info_fw->gc_max_scratch_slots_per_cu);
1879 		adev->gfx.cu_info.lds_size = le32_to_cpu(gpu_info_fw->gc_lds_size);
1880 		if (hdr->version_minor >= 1) {
1881 			const struct gpu_info_firmware_v1_1 *gpu_info_fw =
1882 				(const struct gpu_info_firmware_v1_1 *)(adev->firmware.gpu_info_fw->data +
1883 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1884 			adev->gfx.config.num_sc_per_sh =
1885 				le32_to_cpu(gpu_info_fw->num_sc_per_sh);
1886 			adev->gfx.config.num_packer_per_sc =
1887 				le32_to_cpu(gpu_info_fw->num_packer_per_sc);
1888 		}
1889 
1890 parse_soc_bounding_box:
1891 		/*
1892 		 * soc bounding box info is not integrated in disocovery table,
1893 		 * we always need to parse it from gpu info firmware if needed.
1894 		 */
1895 		if (hdr->version_minor == 2) {
1896 			const struct gpu_info_firmware_v1_2 *gpu_info_fw =
1897 				(const struct gpu_info_firmware_v1_2 *)(adev->firmware.gpu_info_fw->data +
1898 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1899 			adev->dm.soc_bounding_box = &gpu_info_fw->soc_bounding_box;
1900 		}
1901 		break;
1902 	}
1903 	default:
1904 		dev_err(adev->dev,
1905 			"Unsupported gpu_info table %d\n", hdr->header.ucode_version);
1906 		err = -EINVAL;
1907 		goto out;
1908 	}
1909 out:
1910 	return err;
1911 }
1912 
1913 static void amdgpu_uid_init(struct amdgpu_device *adev)
1914 {
1915 	/* Initialize the UID for the device */
1916 	adev->uid_info = kzalloc_obj(struct amdgpu_uid);
1917 	if (!adev->uid_info) {
1918 		dev_warn(adev->dev, "Failed to allocate memory for UID\n");
1919 		return;
1920 	}
1921 	adev->uid_info->adev = adev;
1922 }
1923 
1924 static void amdgpu_uid_fini(struct amdgpu_device *adev)
1925 {
1926 	/* Free the UID memory */
1927 	kfree(adev->uid_info);
1928 	adev->uid_info = NULL;
1929 }
1930 
1931 static struct pci_dev *amdgpu_device_find_parent(struct amdgpu_device *adev)
1932 {
1933 	struct pci_dev *parent = adev->pdev;
1934 
1935 	/* skip upstream/downstream switches internal to dGPU */
1936 	while ((parent = pci_upstream_bridge(parent))) {
1937 		if (parent->vendor == PCI_VENDOR_ID_ATI)
1938 			continue;
1939 		break;
1940 	}
1941 
1942 	return parent;
1943 }
1944 
1945 /**
1946  * amdgpu_device_ip_early_init - run early init for hardware IPs
1947  *
1948  * @adev: amdgpu_device pointer
1949  *
1950  * Early initialization pass for hardware IPs.  The hardware IPs that make
1951  * up each asic are discovered each IP's early_init callback is run.  This
1952  * is the first stage in initializing the asic.
1953  * Returns 0 on success, negative error code on failure.
1954  */
1955 static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
1956 {
1957 	struct amdgpu_ip_block *ip_block;
1958 	struct pci_dev *parent;
1959 	bool total, skip_bios;
1960 	uint32_t bios_flags;
1961 	int i, r;
1962 
1963 	amdgpu_device_enable_virtual_display(adev);
1964 
1965 	if (amdgpu_sriov_vf(adev)) {
1966 		r = amdgpu_virt_request_full_gpu(adev, true);
1967 		if (r)
1968 			return r;
1969 
1970 		r = amdgpu_virt_init_critical_region(adev);
1971 		if (r)
1972 			return r;
1973 	}
1974 
1975 	switch (adev->asic_type) {
1976 #ifdef CONFIG_DRM_AMDGPU_SI
1977 	case CHIP_VERDE:
1978 	case CHIP_TAHITI:
1979 	case CHIP_PITCAIRN:
1980 	case CHIP_OLAND:
1981 	case CHIP_HAINAN:
1982 		adev->family = AMDGPU_FAMILY_SI;
1983 		r = si_set_ip_blocks(adev);
1984 		if (r)
1985 			return r;
1986 		break;
1987 #endif
1988 #ifdef CONFIG_DRM_AMDGPU_CIK
1989 	case CHIP_BONAIRE:
1990 	case CHIP_HAWAII:
1991 	case CHIP_KAVERI:
1992 	case CHIP_KABINI:
1993 	case CHIP_MULLINS:
1994 		if (adev->flags & AMD_IS_APU)
1995 			adev->family = AMDGPU_FAMILY_KV;
1996 		else
1997 			adev->family = AMDGPU_FAMILY_CI;
1998 
1999 		r = cik_set_ip_blocks(adev);
2000 		if (r)
2001 			return r;
2002 		break;
2003 #endif
2004 	case CHIP_TOPAZ:
2005 	case CHIP_TONGA:
2006 	case CHIP_FIJI:
2007 	case CHIP_POLARIS10:
2008 	case CHIP_POLARIS11:
2009 	case CHIP_POLARIS12:
2010 	case CHIP_VEGAM:
2011 	case CHIP_CARRIZO:
2012 	case CHIP_STONEY:
2013 		if (adev->flags & AMD_IS_APU)
2014 			adev->family = AMDGPU_FAMILY_CZ;
2015 		else
2016 			adev->family = AMDGPU_FAMILY_VI;
2017 
2018 		r = vi_set_ip_blocks(adev);
2019 		if (r)
2020 			return r;
2021 		break;
2022 	default:
2023 		r = amdgpu_discovery_set_ip_blocks(adev);
2024 		if (r) {
2025 			adev->num_ip_blocks = 0;
2026 			return r;
2027 		}
2028 		break;
2029 	}
2030 
2031 	/* Check for IP version 9.4.3 with A0 hardware */
2032 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) &&
2033 	    !amdgpu_device_get_rev_id(adev)) {
2034 		dev_err(adev->dev, "Unsupported A0 hardware\n");
2035 		return -ENODEV;	/* device unsupported - no device error */
2036 	}
2037 
2038 	if (amdgpu_has_atpx() &&
2039 	    (amdgpu_is_atpx_hybrid() ||
2040 	     amdgpu_has_atpx_dgpu_power_cntl()) &&
2041 	    ((adev->flags & AMD_IS_APU) == 0) &&
2042 	    !dev_is_removable(&adev->pdev->dev))
2043 		adev->flags |= AMD_IS_PX;
2044 
2045 	if (!(adev->flags & AMD_IS_APU)) {
2046 		parent = amdgpu_device_find_parent(adev);
2047 		adev->has_pr3 = parent ? pci_pr3_present(parent) : false;
2048 	}
2049 
2050 	adev->pm.pp_feature = amdgpu_pp_feature_mask;
2051 	if (amdgpu_sriov_vf(adev) || sched_policy == KFD_SCHED_POLICY_NO_HWS)
2052 		adev->pm.pp_feature &= ~PP_GFXOFF_MASK;
2053 	if (amdgpu_sriov_vf(adev) && adev->asic_type == CHIP_SIENNA_CICHLID)
2054 		adev->pm.pp_feature &= ~PP_OVERDRIVE_MASK;
2055 	if (!amdgpu_device_pcie_dynamic_switching_supported(adev))
2056 		adev->pm.pp_feature &= ~PP_PCIE_DPM_MASK;
2057 
2058 	adev->virt.is_xgmi_node_migrate_enabled = false;
2059 	if (amdgpu_sriov_vf(adev)) {
2060 		adev->virt.is_xgmi_node_migrate_enabled =
2061 			amdgpu_ip_version((adev), GC_HWIP, 0) == IP_VERSION(9, 4, 4);
2062 	}
2063 
2064 	total = true;
2065 	for (i = 0; i < adev->num_ip_blocks; i++) {
2066 		ip_block = &adev->ip_blocks[i];
2067 
2068 		if ((amdgpu_ip_block_mask & (1 << i)) == 0) {
2069 			dev_warn(adev->dev, "disabled ip block: %d <%s>\n", i,
2070 				 adev->ip_blocks[i].version->funcs->name);
2071 			adev->ip_blocks[i].status.valid = false;
2072 		} else if (ip_block->version->funcs->early_init) {
2073 			r = ip_block->version->funcs->early_init(ip_block);
2074 			if (r == -ENOENT) {
2075 				adev->ip_blocks[i].status.valid = false;
2076 			} else if (r) {
2077 				dev_err(adev->dev,
2078 					"early_init of IP block <%s> failed %d\n",
2079 					adev->ip_blocks[i].version->funcs->name,
2080 					r);
2081 				total = false;
2082 			} else {
2083 				adev->ip_blocks[i].status.valid = true;
2084 			}
2085 		} else {
2086 			adev->ip_blocks[i].status.valid = true;
2087 		}
2088 		/* get the vbios after the asic_funcs are set up */
2089 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON) {
2090 			r = amdgpu_device_parse_gpu_info_fw(adev);
2091 			if (r)
2092 				return r;
2093 
2094 			bios_flags = amdgpu_device_get_vbios_flags(adev);
2095 			skip_bios = !!(bios_flags & AMDGPU_VBIOS_SKIP);
2096 			/* Read BIOS */
2097 			if (!skip_bios) {
2098 				bool optional =
2099 					!!(bios_flags & AMDGPU_VBIOS_OPTIONAL);
2100 				if (!amdgpu_get_bios(adev) && !optional)
2101 					return -EINVAL;
2102 
2103 				if (optional && !adev->bios)
2104 					dev_info(
2105 						adev->dev,
2106 						"VBIOS image optional, proceeding without VBIOS image");
2107 
2108 				if (adev->bios) {
2109 					r = amdgpu_atombios_init(adev);
2110 					if (r) {
2111 						dev_err(adev->dev,
2112 							"amdgpu_atombios_init failed\n");
2113 						amdgpu_vf_error_put(
2114 							adev,
2115 							AMDGIM_ERROR_VF_ATOMBIOS_INIT_FAIL,
2116 							0, 0);
2117 						return r;
2118 					}
2119 				}
2120 			}
2121 
2122 			/*get pf2vf msg info at it's earliest time*/
2123 			if (amdgpu_sriov_vf(adev))
2124 				amdgpu_virt_init_data_exchange(adev);
2125 
2126 		}
2127 	}
2128 	if (!total)
2129 		return -ENODEV;
2130 
2131 	if (adev->gmc.xgmi.supported)
2132 		amdgpu_xgmi_early_init(adev);
2133 
2134 	if (amdgpu_is_multi_aid(adev))
2135 		amdgpu_uid_init(adev);
2136 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
2137 	if (ip_block->status.valid != false)
2138 		amdgpu_amdkfd_device_probe(adev);
2139 
2140 	adev->cg_flags &= amdgpu_cg_mask;
2141 	adev->pg_flags &= amdgpu_pg_mask;
2142 
2143 	return 0;
2144 }
2145 
2146 static int amdgpu_device_ip_hw_init_phase1(struct amdgpu_device *adev)
2147 {
2148 	int i, r;
2149 
2150 	for (i = 0; i < adev->num_ip_blocks; i++) {
2151 		if (!adev->ip_blocks[i].status.sw)
2152 			continue;
2153 		if (adev->ip_blocks[i].status.hw)
2154 			continue;
2155 		if (!amdgpu_ip_member_of_hwini(
2156 			    adev, adev->ip_blocks[i].version->type))
2157 			continue;
2158 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2159 		    (amdgpu_sriov_vf(adev) && (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)) ||
2160 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
2161 			r = adev->ip_blocks[i].version->funcs->hw_init(&adev->ip_blocks[i]);
2162 			if (r) {
2163 				dev_err(adev->dev,
2164 					"hw_init of IP block <%s> failed %d\n",
2165 					adev->ip_blocks[i].version->funcs->name,
2166 					r);
2167 				return r;
2168 			}
2169 			adev->ip_blocks[i].status.hw = true;
2170 		}
2171 	}
2172 
2173 	return 0;
2174 }
2175 
2176 static int amdgpu_device_ip_hw_init_phase2(struct amdgpu_device *adev)
2177 {
2178 	int i, r;
2179 
2180 	for (i = 0; i < adev->num_ip_blocks; i++) {
2181 		if (!adev->ip_blocks[i].status.sw)
2182 			continue;
2183 		if (adev->ip_blocks[i].status.hw)
2184 			continue;
2185 		if (!amdgpu_ip_member_of_hwini(
2186 			    adev, adev->ip_blocks[i].version->type))
2187 			continue;
2188 		r = adev->ip_blocks[i].version->funcs->hw_init(&adev->ip_blocks[i]);
2189 		if (r) {
2190 			dev_err(adev->dev,
2191 				"hw_init of IP block <%s> failed %d\n",
2192 				adev->ip_blocks[i].version->funcs->name, r);
2193 			return r;
2194 		}
2195 		adev->ip_blocks[i].status.hw = true;
2196 	}
2197 
2198 	return 0;
2199 }
2200 
2201 static int amdgpu_device_fw_loading(struct amdgpu_device *adev)
2202 {
2203 	int r = 0;
2204 	int i;
2205 	uint32_t smu_version;
2206 
2207 	if (adev->asic_type >= CHIP_VEGA10) {
2208 		for (i = 0; i < adev->num_ip_blocks; i++) {
2209 			if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_PSP)
2210 				continue;
2211 
2212 			if (!amdgpu_ip_member_of_hwini(adev,
2213 						       AMD_IP_BLOCK_TYPE_PSP))
2214 				break;
2215 
2216 			if (!adev->ip_blocks[i].status.sw)
2217 				continue;
2218 
2219 			/* no need to do the fw loading again if already done*/
2220 			if (adev->ip_blocks[i].status.hw == true)
2221 				break;
2222 
2223 			if (amdgpu_in_reset(adev) || adev->in_suspend) {
2224 				r = amdgpu_ip_block_resume(&adev->ip_blocks[i]);
2225 				if (r)
2226 					return r;
2227 			} else {
2228 				r = adev->ip_blocks[i].version->funcs->hw_init(&adev->ip_blocks[i]);
2229 				if (r) {
2230 					dev_err(adev->dev,
2231 						"hw_init of IP block <%s> failed %d\n",
2232 						adev->ip_blocks[i]
2233 							.version->funcs->name,
2234 						r);
2235 					return r;
2236 				}
2237 				adev->ip_blocks[i].status.hw = true;
2238 			}
2239 			break;
2240 		}
2241 	}
2242 
2243 	if (!amdgpu_sriov_vf(adev) || adev->asic_type == CHIP_TONGA)
2244 		r = amdgpu_pm_load_smu_firmware(adev, &smu_version);
2245 
2246 	return r;
2247 }
2248 
2249 static int amdgpu_device_init_schedulers(struct amdgpu_device *adev)
2250 {
2251 	struct drm_sched_init_args args = {
2252 		.ops = &amdgpu_sched_ops,
2253 		.timeout_wq = adev->reset_domain->wq,
2254 		.dev = adev->dev,
2255 	};
2256 	long timeout;
2257 	int r, i;
2258 
2259 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
2260 		struct amdgpu_ring *ring = adev->rings[i];
2261 
2262 		/* No need to setup the GPU scheduler for rings that don't need it */
2263 		if (!ring || ring->no_scheduler)
2264 			continue;
2265 
2266 		switch (ring->funcs->type) {
2267 		case AMDGPU_RING_TYPE_GFX:
2268 			timeout = adev->gfx_timeout;
2269 			break;
2270 		case AMDGPU_RING_TYPE_COMPUTE:
2271 			timeout = adev->compute_timeout;
2272 			break;
2273 		case AMDGPU_RING_TYPE_SDMA:
2274 			timeout = adev->sdma_timeout;
2275 			break;
2276 		default:
2277 			timeout = adev->video_timeout;
2278 			break;
2279 		}
2280 
2281 		args.timeout = timeout;
2282 		args.credit_limit = ring->num_hw_submission;
2283 		args.score = ring->sched_score;
2284 		args.name = ring->name;
2285 
2286 		r = drm_sched_init(&ring->sched, &args);
2287 		if (r) {
2288 			dev_err(adev->dev,
2289 				"Failed to create scheduler on ring %s.\n",
2290 				ring->name);
2291 			return r;
2292 		}
2293 		r = amdgpu_uvd_entity_init(adev, ring);
2294 		if (r) {
2295 			dev_err(adev->dev,
2296 				"Failed to create UVD scheduling entity on ring %s.\n",
2297 				ring->name);
2298 			return r;
2299 		}
2300 		r = amdgpu_vce_entity_init(adev, ring);
2301 		if (r) {
2302 			dev_err(adev->dev,
2303 				"Failed to create VCE scheduling entity on ring %s.\n",
2304 				ring->name);
2305 			return r;
2306 		}
2307 	}
2308 
2309 	if (adev->xcp_mgr)
2310 		amdgpu_xcp_update_partition_sched_list(adev);
2311 
2312 	return 0;
2313 }
2314 
2315 
2316 /**
2317  * amdgpu_device_ip_init - run init for hardware IPs
2318  *
2319  * @adev: amdgpu_device pointer
2320  *
2321  * Main initialization pass for hardware IPs.  The list of all the hardware
2322  * IPs that make up the asic is walked and the sw_init and hw_init callbacks
2323  * are run.  sw_init initializes the software state associated with each IP
2324  * and hw_init initializes the hardware associated with each IP.
2325  * Returns 0 on success, negative error code on failure.
2326  */
2327 static int amdgpu_device_ip_init(struct amdgpu_device *adev)
2328 {
2329 	bool init_badpage;
2330 	int i, r;
2331 
2332 	r = amdgpu_ras_init(adev);
2333 	if (r)
2334 		return r;
2335 
2336 	for (i = 0; i < adev->num_ip_blocks; i++) {
2337 		if (!adev->ip_blocks[i].status.valid)
2338 			continue;
2339 		if (adev->ip_blocks[i].version->funcs->sw_init) {
2340 			r = adev->ip_blocks[i].version->funcs->sw_init(&adev->ip_blocks[i]);
2341 			if (r) {
2342 				dev_err(adev->dev,
2343 					"sw_init of IP block <%s> failed %d\n",
2344 					adev->ip_blocks[i].version->funcs->name,
2345 					r);
2346 				goto init_failed;
2347 			}
2348 		}
2349 		adev->ip_blocks[i].status.sw = true;
2350 
2351 		if (!amdgpu_ip_member_of_hwini(
2352 			    adev, adev->ip_blocks[i].version->type))
2353 			continue;
2354 
2355 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON) {
2356 			/* need to do common hw init early so everything is set up for gmc */
2357 			r = adev->ip_blocks[i].version->funcs->hw_init(&adev->ip_blocks[i]);
2358 			if (r) {
2359 				dev_err(adev->dev, "hw_init %d failed %d\n", i,
2360 					r);
2361 				goto init_failed;
2362 			}
2363 			adev->ip_blocks[i].status.hw = true;
2364 		} else if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
2365 			/* need to do gmc hw init early so we can allocate gpu mem */
2366 			/* Try to reserve bad pages early */
2367 			if (amdgpu_sriov_vf(adev))
2368 				amdgpu_virt_exchange_data(adev);
2369 
2370 			r = amdgpu_device_mem_scratch_init(adev);
2371 			if (r) {
2372 				dev_err(adev->dev,
2373 					"amdgpu_mem_scratch_init failed %d\n",
2374 					r);
2375 				goto init_failed;
2376 			}
2377 			r = adev->ip_blocks[i].version->funcs->hw_init(&adev->ip_blocks[i]);
2378 			if (r) {
2379 				dev_err(adev->dev, "hw_init %d failed %d\n", i,
2380 					r);
2381 				goto init_failed;
2382 			}
2383 			r = amdgpu_device_wb_init(adev);
2384 			if (r) {
2385 				dev_err(adev->dev,
2386 					"amdgpu_device_wb_init failed %d\n", r);
2387 				goto init_failed;
2388 			}
2389 			adev->ip_blocks[i].status.hw = true;
2390 
2391 			/* right after GMC hw init, we create CSA */
2392 			if (adev->gfx.mcbp) {
2393 				r = amdgpu_allocate_static_csa(adev, &adev->virt.csa_obj,
2394 							       AMDGPU_GEM_DOMAIN_VRAM |
2395 							       AMDGPU_GEM_DOMAIN_GTT,
2396 							       AMDGPU_CSA_SIZE);
2397 				if (r) {
2398 					dev_err(adev->dev,
2399 						"allocate CSA failed %d\n", r);
2400 					goto init_failed;
2401 				}
2402 			}
2403 
2404 			r = amdgpu_seq64_init(adev);
2405 			if (r) {
2406 				dev_err(adev->dev, "allocate seq64 failed %d\n",
2407 					r);
2408 				goto init_failed;
2409 			}
2410 		}
2411 	}
2412 
2413 	if (amdgpu_sriov_vf(adev))
2414 		amdgpu_virt_init_data_exchange(adev);
2415 
2416 	r = amdgpu_ib_pool_init(adev);
2417 	if (r) {
2418 		dev_err(adev->dev, "IB initialization failed (%d).\n", r);
2419 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_IB_INIT_FAIL, 0, r);
2420 		goto init_failed;
2421 	}
2422 
2423 	r = amdgpu_ucode_create_bo(adev); /* create ucode bo when sw_init complete*/
2424 	if (r)
2425 		goto init_failed;
2426 
2427 	r = amdgpu_device_ip_hw_init_phase1(adev);
2428 	if (r)
2429 		goto init_failed;
2430 
2431 	r = amdgpu_device_fw_loading(adev);
2432 	if (r)
2433 		goto init_failed;
2434 
2435 	r = amdgpu_device_ip_hw_init_phase2(adev);
2436 	if (r)
2437 		goto init_failed;
2438 
2439 	/*
2440 	 * retired pages will be loaded from eeprom and reserved here,
2441 	 * it should be called after amdgpu_device_ip_hw_init_phase2  since
2442 	 * for some ASICs the RAS EEPROM code relies on SMU fully functioning
2443 	 * for I2C communication which only true at this point.
2444 	 *
2445 	 * amdgpu_ras_recovery_init may fail, but the upper only cares the
2446 	 * failure from bad gpu situation and stop amdgpu init process
2447 	 * accordingly. For other failed cases, it will still release all
2448 	 * the resource and print error message, rather than returning one
2449 	 * negative value to upper level.
2450 	 *
2451 	 * Note: theoretically, this should be called before all vram allocations
2452 	 * to protect retired page from abusing
2453 	 */
2454 	init_badpage = (adev->init_lvl->level != AMDGPU_INIT_LEVEL_MINIMAL_XGMI);
2455 	r = amdgpu_ras_recovery_init(adev, init_badpage);
2456 	if (r)
2457 		goto init_failed;
2458 
2459 	/**
2460 	 * In case of XGMI grab extra reference for reset domain for this device
2461 	 */
2462 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
2463 		if (amdgpu_xgmi_add_device(adev) == 0) {
2464 			if (!amdgpu_sriov_vf(adev)) {
2465 				struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
2466 
2467 				if (WARN_ON(!hive)) {
2468 					r = -ENOENT;
2469 					goto init_failed;
2470 				}
2471 
2472 				if (!hive->reset_domain ||
2473 				    !amdgpu_reset_get_reset_domain(hive->reset_domain)) {
2474 					r = -ENOENT;
2475 					amdgpu_put_xgmi_hive(hive);
2476 					goto init_failed;
2477 				}
2478 
2479 				/* Drop the early temporary reset domain we created for device */
2480 				amdgpu_reset_put_reset_domain(adev->reset_domain);
2481 				adev->reset_domain = hive->reset_domain;
2482 				amdgpu_put_xgmi_hive(hive);
2483 			}
2484 		}
2485 	}
2486 
2487 	r = amdgpu_device_init_schedulers(adev);
2488 	if (r)
2489 		goto init_failed;
2490 
2491 	amdgpu_ttm_enable_buffer_funcs(adev);
2492 
2493 	/* Don't init kfd if whole hive need to be reset during init */
2494 	if (adev->init_lvl->level != AMDGPU_INIT_LEVEL_MINIMAL_XGMI) {
2495 		amdgpu_amdkfd_device_init(adev);
2496 	}
2497 
2498 	amdgpu_fru_get_product_info(adev);
2499 
2500 	r = amdgpu_cper_init(adev);
2501 
2502 init_failed:
2503 
2504 	return r;
2505 }
2506 
2507 /**
2508  * amdgpu_device_fill_reset_magic - writes reset magic to gart pointer
2509  *
2510  * @adev: amdgpu_device pointer
2511  *
2512  * Writes a reset magic value to the gart pointer in VRAM.  The driver calls
2513  * this function before a GPU reset.  If the value is retained after a
2514  * GPU reset, VRAM has not been lost. Some GPU resets may destroy VRAM contents.
2515  */
2516 static void amdgpu_device_fill_reset_magic(struct amdgpu_device *adev)
2517 {
2518 	memcpy(adev->reset_magic, adev->gart.ptr, AMDGPU_RESET_MAGIC_NUM);
2519 }
2520 
2521 /**
2522  * amdgpu_device_check_vram_lost - check if vram is valid
2523  *
2524  * @adev: amdgpu_device pointer
2525  *
2526  * Checks the reset magic value written to the gart pointer in VRAM.
2527  * The driver calls this after a GPU reset to see if the contents of
2528  * VRAM is lost or now.
2529  * returns true if vram is lost, false if not.
2530  */
2531 static bool amdgpu_device_check_vram_lost(struct amdgpu_device *adev)
2532 {
2533 	if (memcmp(adev->gart.ptr, adev->reset_magic,
2534 			AMDGPU_RESET_MAGIC_NUM))
2535 		return true;
2536 
2537 	if (!amdgpu_in_reset(adev))
2538 		return false;
2539 
2540 	/*
2541 	 * For all ASICs with baco/mode1 reset, the VRAM is
2542 	 * always assumed to be lost.
2543 	 */
2544 	switch (amdgpu_asic_reset_method(adev)) {
2545 	case AMD_RESET_METHOD_LEGACY:
2546 	case AMD_RESET_METHOD_LINK:
2547 	case AMD_RESET_METHOD_BACO:
2548 	case AMD_RESET_METHOD_MODE1:
2549 		return true;
2550 	default:
2551 		return false;
2552 	}
2553 }
2554 
2555 /**
2556  * amdgpu_device_set_cg_state - set clockgating for amdgpu device
2557  *
2558  * @adev: amdgpu_device pointer
2559  * @state: clockgating state (gate or ungate)
2560  *
2561  * The list of all the hardware IPs that make up the asic is walked and the
2562  * set_clockgating_state callbacks are run.
2563  * Late initialization pass enabling clockgating for hardware IPs.
2564  * Fini or suspend, pass disabling clockgating for hardware IPs.
2565  * Returns 0 on success, negative error code on failure.
2566  */
2567 
2568 int amdgpu_device_set_cg_state(struct amdgpu_device *adev,
2569 			       enum amd_clockgating_state state)
2570 {
2571 	int i, j, r;
2572 
2573 	if (amdgpu_emu_mode == 1)
2574 		return 0;
2575 
2576 	for (j = 0; j < adev->num_ip_blocks; j++) {
2577 		i = state == AMD_CG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2578 		if (!adev->ip_blocks[i].status.late_initialized)
2579 			continue;
2580 		if (!adev->ip_blocks[i].version)
2581 			continue;
2582 		/* skip CG for GFX, SDMA on S0ix */
2583 		if (adev->in_s0ix &&
2584 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX ||
2585 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SDMA))
2586 			continue;
2587 		/* skip CG for VCE/UVD, it's handled specially */
2588 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2589 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2590 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2591 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2592 		    adev->ip_blocks[i].version->funcs->set_clockgating_state) {
2593 			/* enable clockgating to save power */
2594 			r = adev->ip_blocks[i].version->funcs->set_clockgating_state(&adev->ip_blocks[i],
2595 										     state);
2596 			if (r) {
2597 				dev_err(adev->dev,
2598 					"set_clockgating_state(gate) of IP block <%s> failed %d\n",
2599 					adev->ip_blocks[i].version->funcs->name,
2600 					r);
2601 				return r;
2602 			}
2603 		}
2604 	}
2605 
2606 	return 0;
2607 }
2608 
2609 int amdgpu_device_set_pg_state(struct amdgpu_device *adev,
2610 			       enum amd_powergating_state state)
2611 {
2612 	int i, j, r;
2613 
2614 	if (amdgpu_emu_mode == 1)
2615 		return 0;
2616 
2617 	for (j = 0; j < adev->num_ip_blocks; j++) {
2618 		i = state == AMD_PG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2619 		if (!adev->ip_blocks[i].status.late_initialized)
2620 			continue;
2621 		if (!adev->ip_blocks[i].version)
2622 			continue;
2623 		/* skip PG for GFX, SDMA on S0ix */
2624 		if (adev->in_s0ix &&
2625 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX ||
2626 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SDMA))
2627 			continue;
2628 		/* skip CG for VCE/UVD, it's handled specially */
2629 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2630 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2631 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2632 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2633 		    adev->ip_blocks[i].version->funcs->set_powergating_state) {
2634 			/* enable powergating to save power */
2635 			r = adev->ip_blocks[i].version->funcs->set_powergating_state(&adev->ip_blocks[i],
2636 											state);
2637 			if (r) {
2638 				dev_err(adev->dev,
2639 					"set_powergating_state(gate) of IP block <%s> failed %d\n",
2640 					adev->ip_blocks[i].version->funcs->name,
2641 					r);
2642 				return r;
2643 			}
2644 		}
2645 	}
2646 	return 0;
2647 }
2648 
2649 static int amdgpu_device_enable_mgpu_fan_boost(void)
2650 {
2651 	struct amdgpu_gpu_instance *gpu_ins;
2652 	struct amdgpu_device *adev;
2653 	int i, ret = 0;
2654 
2655 	mutex_lock(&mgpu_info.mutex);
2656 
2657 	/*
2658 	 * MGPU fan boost feature should be enabled
2659 	 * only when there are two or more dGPUs in
2660 	 * the system
2661 	 */
2662 	if (mgpu_info.num_dgpu < 2)
2663 		goto out;
2664 
2665 	for (i = 0; i < mgpu_info.num_dgpu; i++) {
2666 		gpu_ins = &(mgpu_info.gpu_ins[i]);
2667 		adev = gpu_ins->adev;
2668 		if (!(adev->flags & AMD_IS_APU || amdgpu_sriov_multi_vf_mode(adev)) &&
2669 		    !gpu_ins->mgpu_fan_enabled) {
2670 			ret = amdgpu_dpm_enable_mgpu_fan_boost(adev);
2671 			if (ret)
2672 				break;
2673 
2674 			gpu_ins->mgpu_fan_enabled = 1;
2675 		}
2676 	}
2677 
2678 out:
2679 	mutex_unlock(&mgpu_info.mutex);
2680 
2681 	return ret;
2682 }
2683 
2684 /**
2685  * amdgpu_device_ip_late_init - run late init for hardware IPs
2686  *
2687  * @adev: amdgpu_device pointer
2688  *
2689  * Late initialization pass for hardware IPs.  The list of all the hardware
2690  * IPs that make up the asic is walked and the late_init callbacks are run.
2691  * late_init covers any special initialization that an IP requires
2692  * after all of the have been initialized or something that needs to happen
2693  * late in the init process.
2694  * Returns 0 on success, negative error code on failure.
2695  */
2696 static int amdgpu_device_ip_late_init(struct amdgpu_device *adev)
2697 {
2698 	struct amdgpu_gpu_instance *gpu_instance;
2699 	int i = 0, r;
2700 
2701 	for (i = 0; i < adev->num_ip_blocks; i++) {
2702 		if (!adev->ip_blocks[i].status.hw)
2703 			continue;
2704 		if (adev->ip_blocks[i].version->funcs->late_init) {
2705 			r = adev->ip_blocks[i].version->funcs->late_init(&adev->ip_blocks[i]);
2706 			if (r) {
2707 				dev_err(adev->dev,
2708 					"late_init of IP block <%s> failed %d\n",
2709 					adev->ip_blocks[i].version->funcs->name,
2710 					r);
2711 				return r;
2712 			}
2713 		}
2714 		adev->ip_blocks[i].status.late_initialized = true;
2715 	}
2716 
2717 	r = amdgpu_ras_late_init(adev);
2718 	if (r) {
2719 		dev_err(adev->dev, "amdgpu_ras_late_init failed %d", r);
2720 		return r;
2721 	}
2722 
2723 	if (!amdgpu_reset_in_recovery(adev))
2724 		amdgpu_ras_set_error_query_ready(adev, true);
2725 
2726 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE);
2727 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE);
2728 
2729 	amdgpu_device_fill_reset_magic(adev);
2730 
2731 	r = amdgpu_device_enable_mgpu_fan_boost();
2732 	if (r)
2733 		dev_err(adev->dev, "enable mgpu fan boost failed (%d).\n", r);
2734 
2735 	/* For passthrough configuration on arcturus and aldebaran, enable special handling SBR */
2736 	if (amdgpu_passthrough(adev) &&
2737 	    ((adev->asic_type == CHIP_ARCTURUS && adev->gmc.xgmi.num_physical_nodes > 1) ||
2738 	     adev->asic_type == CHIP_ALDEBARAN))
2739 		amdgpu_dpm_handle_passthrough_sbr(adev, true);
2740 
2741 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
2742 		mutex_lock(&mgpu_info.mutex);
2743 
2744 		/*
2745 		 * Reset device p-state to low as this was booted with high.
2746 		 *
2747 		 * This should be performed only after all devices from the same
2748 		 * hive get initialized.
2749 		 *
2750 		 * However, it's unknown how many device in the hive in advance.
2751 		 * As this is counted one by one during devices initializations.
2752 		 *
2753 		 * So, we wait for all XGMI interlinked devices initialized.
2754 		 * This may bring some delays as those devices may come from
2755 		 * different hives. But that should be OK.
2756 		 */
2757 		if (mgpu_info.num_dgpu == adev->gmc.xgmi.num_physical_nodes) {
2758 			for (i = 0; i < mgpu_info.num_gpu; i++) {
2759 				gpu_instance = &(mgpu_info.gpu_ins[i]);
2760 				if (gpu_instance->adev->flags & AMD_IS_APU)
2761 					continue;
2762 
2763 				r = amdgpu_xgmi_set_pstate(gpu_instance->adev,
2764 						AMDGPU_XGMI_PSTATE_MIN);
2765 				if (r) {
2766 					dev_err(adev->dev,
2767 						"pstate setting failed (%d).\n",
2768 						r);
2769 					break;
2770 				}
2771 			}
2772 		}
2773 
2774 		mutex_unlock(&mgpu_info.mutex);
2775 	}
2776 
2777 	return 0;
2778 }
2779 
2780 static void amdgpu_ip_block_hw_fini(struct amdgpu_ip_block *ip_block)
2781 {
2782 	struct amdgpu_device *adev = ip_block->adev;
2783 	int r;
2784 
2785 	if (!ip_block->version->funcs->hw_fini) {
2786 		dev_err(adev->dev, "hw_fini of IP block <%s> not defined\n",
2787 			ip_block->version->funcs->name);
2788 	} else {
2789 		r = ip_block->version->funcs->hw_fini(ip_block);
2790 		/* XXX handle errors */
2791 		if (r) {
2792 			dev_dbg(adev->dev,
2793 				"hw_fini of IP block <%s> failed %d\n",
2794 				ip_block->version->funcs->name, r);
2795 		}
2796 	}
2797 
2798 	ip_block->status.hw = false;
2799 }
2800 
2801 /**
2802  * amdgpu_device_smu_fini_early - smu hw_fini wrapper
2803  *
2804  * @adev: amdgpu_device pointer
2805  *
2806  * For ASICs need to disable SMC first
2807  */
2808 static void amdgpu_device_smu_fini_early(struct amdgpu_device *adev)
2809 {
2810 	int i;
2811 
2812 	if (amdgpu_ip_version(adev, GC_HWIP, 0) > IP_VERSION(9, 0, 0))
2813 		return;
2814 
2815 	for (i = 0; i < adev->num_ip_blocks; i++) {
2816 		if (!adev->ip_blocks[i].status.hw)
2817 			continue;
2818 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2819 			amdgpu_ip_block_hw_fini(&adev->ip_blocks[i]);
2820 			break;
2821 		}
2822 	}
2823 }
2824 
2825 static int amdgpu_device_ip_fini_early(struct amdgpu_device *adev)
2826 {
2827 	int i, r;
2828 
2829 	for (i = 0; i < adev->num_ip_blocks; i++) {
2830 		if (!adev->ip_blocks[i].version)
2831 			continue;
2832 		if (!adev->ip_blocks[i].version->funcs->early_fini)
2833 			continue;
2834 
2835 		r = adev->ip_blocks[i].version->funcs->early_fini(&adev->ip_blocks[i]);
2836 		if (r) {
2837 			dev_dbg(adev->dev,
2838 				"early_fini of IP block <%s> failed %d\n",
2839 				adev->ip_blocks[i].version->funcs->name, r);
2840 		}
2841 	}
2842 
2843 	amdgpu_amdkfd_suspend(adev, true);
2844 	amdgpu_amdkfd_teardown_processes(adev);
2845 	amdgpu_userq_suspend(adev);
2846 
2847 	/* Workaround for ASICs need to disable SMC first */
2848 	amdgpu_device_smu_fini_early(adev);
2849 
2850 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2851 		if (!adev->ip_blocks[i].status.hw)
2852 			continue;
2853 
2854 		amdgpu_ip_block_hw_fini(&adev->ip_blocks[i]);
2855 	}
2856 
2857 	if (amdgpu_sriov_vf(adev)) {
2858 		if (amdgpu_virt_release_full_gpu(adev, false))
2859 			dev_err(adev->dev,
2860 				"failed to release exclusive mode on fini\n");
2861 	}
2862 
2863 	/*
2864 	 * Driver reload on the APU can fail due to firmware validation because
2865 	 * the PSP is always running, as it is shared across the whole SoC.
2866 	 * This same issue does not occur on dGPU because it has a mechanism
2867 	 * that checks whether the PSP is running. A solution for those issues
2868 	 * in the APU is to trigger a GPU reset, but this should be done during
2869 	 * the unload phase to avoid adding boot latency and screen flicker.
2870 	 * GFX V11 has GC block as default off IP. Every time AMDGPU driver sends
2871 	 * a request to PMFW to unload MP1, PMFW will put GC in reset and power down
2872 	 * the voltage. Hence, skipping reset for APUs with GFX V11 or later.
2873 	 */
2874 	if ((adev->flags & AMD_IS_APU) && !adev->gmc.is_app_apu &&
2875 		amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(11, 0, 0)) {
2876 		r = amdgpu_asic_reset(adev);
2877 		if (r)
2878 			dev_err(adev->dev, "asic reset on %s failed\n", __func__);
2879 	}
2880 
2881 	return 0;
2882 }
2883 
2884 /**
2885  * amdgpu_device_ip_fini - run fini for hardware IPs
2886  *
2887  * @adev: amdgpu_device pointer
2888  *
2889  * Main teardown pass for hardware IPs.  The list of all the hardware
2890  * IPs that make up the asic is walked and the hw_fini and sw_fini callbacks
2891  * are run.  hw_fini tears down the hardware associated with each IP
2892  * and sw_fini tears down any software state associated with each IP.
2893  * Returns 0 on success, negative error code on failure.
2894  */
2895 static int amdgpu_device_ip_fini(struct amdgpu_device *adev)
2896 {
2897 	int i, r;
2898 
2899 	amdgpu_cper_fini(adev);
2900 
2901 	if (amdgpu_sriov_vf(adev) && adev->virt.ras_init_done)
2902 		amdgpu_virt_release_ras_err_handler_data(adev);
2903 
2904 	if (adev->gmc.xgmi.num_physical_nodes > 1)
2905 		amdgpu_xgmi_remove_device(adev);
2906 
2907 	amdgpu_amdkfd_device_fini_sw(adev);
2908 
2909 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2910 		if (!adev->ip_blocks[i].status.sw)
2911 			continue;
2912 
2913 		if (!adev->ip_blocks[i].version)
2914 			continue;
2915 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
2916 			amdgpu_ucode_free_bo(adev);
2917 			amdgpu_free_static_csa(&adev->virt.csa_obj);
2918 			amdgpu_device_wb_fini(adev);
2919 			amdgpu_device_mem_scratch_fini(adev);
2920 			amdgpu_ib_pool_fini(adev);
2921 			amdgpu_seq64_fini(adev);
2922 			amdgpu_doorbell_fini(adev);
2923 		}
2924 		if (adev->ip_blocks[i].version->funcs->sw_fini) {
2925 			r = adev->ip_blocks[i].version->funcs->sw_fini(&adev->ip_blocks[i]);
2926 			/* XXX handle errors */
2927 			if (r) {
2928 				dev_dbg(adev->dev,
2929 					"sw_fini of IP block <%s> failed %d\n",
2930 					adev->ip_blocks[i].version->funcs->name,
2931 					r);
2932 			}
2933 		}
2934 		adev->ip_blocks[i].status.sw = false;
2935 		adev->ip_blocks[i].status.valid = false;
2936 	}
2937 
2938 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2939 		if (!adev->ip_blocks[i].status.late_initialized)
2940 			continue;
2941 		if (!adev->ip_blocks[i].version)
2942 			continue;
2943 		if (adev->ip_blocks[i].version->funcs->late_fini)
2944 			adev->ip_blocks[i].version->funcs->late_fini(&adev->ip_blocks[i]);
2945 		adev->ip_blocks[i].status.late_initialized = false;
2946 	}
2947 
2948 	amdgpu_ras_fini(adev);
2949 	amdgpu_uid_fini(adev);
2950 
2951 	return 0;
2952 }
2953 
2954 /**
2955  * amdgpu_device_delayed_init_work_handler - work handler for IB tests
2956  *
2957  * @work: work_struct.
2958  */
2959 static void amdgpu_device_delayed_init_work_handler(struct work_struct *work)
2960 {
2961 	struct amdgpu_device *adev =
2962 		container_of(work, struct amdgpu_device, delayed_init_work.work);
2963 	int r;
2964 
2965 	r = amdgpu_ib_ring_tests(adev);
2966 	if (r)
2967 		dev_err(adev->dev, "ib ring test failed (%d).\n", r);
2968 }
2969 
2970 static void amdgpu_device_delay_enable_gfx_off(struct work_struct *work)
2971 {
2972 	struct amdgpu_device *adev =
2973 		container_of(work, struct amdgpu_device, gfx.gfx_off_delay_work.work);
2974 
2975 	WARN_ON_ONCE(adev->gfx.gfx_off_state);
2976 	WARN_ON_ONCE(adev->gfx.gfx_off_req_count);
2977 
2978 	if (!amdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_GFX, true, 0))
2979 		adev->gfx.gfx_off_state = true;
2980 }
2981 
2982 /**
2983  * amdgpu_device_ip_suspend_phase1 - run suspend for hardware IPs (phase 1)
2984  *
2985  * @adev: amdgpu_device pointer
2986  *
2987  * Main suspend function for hardware IPs.  The list of all the hardware
2988  * IPs that make up the asic is walked, clockgating is disabled and the
2989  * suspend callbacks are run.  suspend puts the hardware and software state
2990  * in each IP into a state suitable for suspend.
2991  * Returns 0 on success, negative error code on failure.
2992  */
2993 static int amdgpu_device_ip_suspend_phase1(struct amdgpu_device *adev)
2994 {
2995 	int i, r, rec;
2996 
2997 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2998 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2999 
3000 	/*
3001 	 * Per PMFW team's suggestion, driver needs to handle gfxoff
3002 	 * and df cstate features disablement for gpu reset(e.g. Mode1Reset)
3003 	 * scenario. Add the missing df cstate disablement here.
3004 	 */
3005 	if (amdgpu_dpm_set_df_cstate(adev, DF_CSTATE_DISALLOW))
3006 		dev_warn(adev->dev, "Failed to disallow df cstate");
3007 
3008 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
3009 		if (!adev->ip_blocks[i].status.valid)
3010 			continue;
3011 
3012 		/* displays are handled separately */
3013 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_DCE)
3014 			continue;
3015 
3016 		r = amdgpu_ip_block_suspend(&adev->ip_blocks[i]);
3017 		if (r)
3018 			goto unwind;
3019 	}
3020 
3021 	return 0;
3022 unwind:
3023 	rec = amdgpu_device_ip_resume_phase3(adev);
3024 	if (rec)
3025 		dev_err(adev->dev,
3026 			"amdgpu_device_ip_resume_phase3 failed during unwind: %d\n",
3027 			rec);
3028 
3029 	amdgpu_dpm_set_df_cstate(adev, DF_CSTATE_ALLOW);
3030 
3031 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE);
3032 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE);
3033 
3034 	return r;
3035 }
3036 
3037 /**
3038  * amdgpu_device_ip_suspend_phase2 - run suspend for hardware IPs (phase 2)
3039  *
3040  * @adev: amdgpu_device pointer
3041  *
3042  * Main suspend function for hardware IPs.  The list of all the hardware
3043  * IPs that make up the asic is walked, clockgating is disabled and the
3044  * suspend callbacks are run.  suspend puts the hardware and software state
3045  * in each IP into a state suitable for suspend.
3046  * Returns 0 on success, negative error code on failure.
3047  */
3048 static int amdgpu_device_ip_suspend_phase2(struct amdgpu_device *adev)
3049 {
3050 	int i, r, rec;
3051 
3052 	if (adev->in_s0ix)
3053 		amdgpu_dpm_gfx_state_change(adev, sGpuChangeState_D3Entry);
3054 
3055 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
3056 		if (!adev->ip_blocks[i].status.valid || !adev->ip_blocks[i].status.hw)
3057 			continue;
3058 		/* displays are handled in phase1 */
3059 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE)
3060 			continue;
3061 		/* PSP lost connection when err_event_athub occurs */
3062 		if (amdgpu_ras_intr_triggered() &&
3063 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
3064 			adev->ip_blocks[i].status.hw = false;
3065 			continue;
3066 		}
3067 
3068 		/* skip unnecessary suspend if we do not initialize them yet */
3069 		if (!amdgpu_ip_member_of_hwini(
3070 			    adev, adev->ip_blocks[i].version->type))
3071 			continue;
3072 
3073 		/* Since we skip suspend for S0i3, we need to cancel the delayed
3074 		 * idle work here as the suspend callback never gets called.
3075 		 */
3076 		if (adev->in_s0ix &&
3077 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX &&
3078 		    amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(10, 0, 0))
3079 			cancel_delayed_work_sync(&adev->gfx.idle_work);
3080 		/* skip suspend of gfx/mes and psp for S0ix
3081 		 * gfx is in gfxoff state, so on resume it will exit gfxoff just
3082 		 * like at runtime. PSP is also part of the always on hardware
3083 		 * so no need to suspend it.
3084 		 */
3085 		if (adev->in_s0ix &&
3086 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP ||
3087 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX ||
3088 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_MES))
3089 			continue;
3090 
3091 		/* SDMA 5.x+ is part of GFX power domain so it's covered by GFXOFF */
3092 		if (adev->in_s0ix &&
3093 		    (amdgpu_ip_version(adev, SDMA0_HWIP, 0) >=
3094 		     IP_VERSION(5, 0, 0)) &&
3095 		    (adev->ip_blocks[i].version->type ==
3096 		     AMD_IP_BLOCK_TYPE_SDMA))
3097 			continue;
3098 
3099 		/* Once swPSP provides the IMU, RLC FW binaries to TOS during cold-boot.
3100 		 * These are in TMR, hence are expected to be reused by PSP-TOS to reload
3101 		 * from this location and RLC Autoload automatically also gets loaded
3102 		 * from here based on PMFW -> PSP message during re-init sequence.
3103 		 * Therefore, the psp suspend & resume should be skipped to avoid destroy
3104 		 * the TMR and reload FWs again for IMU enabled APU ASICs.
3105 		 */
3106 		if (amdgpu_in_reset(adev) &&
3107 		    (adev->flags & AMD_IS_APU) && adev->gfx.imu.funcs &&
3108 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)
3109 			continue;
3110 
3111 		r = amdgpu_ip_block_suspend(&adev->ip_blocks[i]);
3112 		if (r)
3113 			goto unwind;
3114 
3115 		/* handle putting the SMC in the appropriate state */
3116 		if (!amdgpu_sriov_vf(adev)) {
3117 			if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
3118 				r = amdgpu_dpm_set_mp1_state(adev, adev->mp1_state);
3119 				if (r) {
3120 					dev_err(adev->dev,
3121 						"SMC failed to set mp1 state %d, %d\n",
3122 						adev->mp1_state, r);
3123 					goto unwind;
3124 				}
3125 			}
3126 		}
3127 	}
3128 
3129 	return 0;
3130 unwind:
3131 	/* suspend phase 2 = resume phase 1 + resume phase 2 */
3132 	rec = amdgpu_device_ip_resume_phase1(adev);
3133 	if (rec) {
3134 		dev_err(adev->dev,
3135 			"amdgpu_device_ip_resume_phase1 failed during unwind: %d\n",
3136 			rec);
3137 		return r;
3138 	}
3139 
3140 	rec = amdgpu_device_fw_loading(adev);
3141 	if (rec) {
3142 		dev_err(adev->dev,
3143 			"amdgpu_device_fw_loading failed during unwind: %d\n",
3144 			rec);
3145 		return r;
3146 	}
3147 
3148 	rec = amdgpu_device_ip_resume_phase2(adev);
3149 	if (rec) {
3150 		dev_err(adev->dev,
3151 			"amdgpu_device_ip_resume_phase2 failed during unwind: %d\n",
3152 			rec);
3153 		return r;
3154 	}
3155 
3156 	return r;
3157 }
3158 
3159 /**
3160  * amdgpu_device_ip_suspend - run suspend for hardware IPs
3161  *
3162  * @adev: amdgpu_device pointer
3163  *
3164  * Main suspend function for hardware IPs.  The list of all the hardware
3165  * IPs that make up the asic is walked, clockgating is disabled and the
3166  * suspend callbacks are run.  suspend puts the hardware and software state
3167  * in each IP into a state suitable for suspend.
3168  * Returns 0 on success, negative error code on failure.
3169  */
3170 static int amdgpu_device_ip_suspend(struct amdgpu_device *adev)
3171 {
3172 	int r;
3173 
3174 	if (amdgpu_sriov_vf(adev)) {
3175 		amdgpu_virt_fini_data_exchange(adev);
3176 		amdgpu_virt_request_full_gpu(adev, false);
3177 	}
3178 
3179 	amdgpu_ttm_disable_buffer_funcs(adev);
3180 
3181 	r = amdgpu_device_ip_suspend_phase1(adev);
3182 	if (r)
3183 		return r;
3184 	r = amdgpu_device_ip_suspend_phase2(adev);
3185 
3186 	if (amdgpu_sriov_vf(adev))
3187 		amdgpu_virt_release_full_gpu(adev, false);
3188 
3189 	return r;
3190 }
3191 
3192 static int amdgpu_device_ip_reinit_early_sriov(struct amdgpu_device *adev)
3193 {
3194 	int i, r;
3195 
3196 	static enum amd_ip_block_type ip_order[] = {
3197 		AMD_IP_BLOCK_TYPE_COMMON,
3198 		AMD_IP_BLOCK_TYPE_GMC,
3199 		AMD_IP_BLOCK_TYPE_PSP,
3200 		AMD_IP_BLOCK_TYPE_IH,
3201 	};
3202 
3203 	for (i = 0; i < adev->num_ip_blocks; i++) {
3204 		int j;
3205 		struct amdgpu_ip_block *block;
3206 
3207 		block = &adev->ip_blocks[i];
3208 		block->status.hw = false;
3209 
3210 		for (j = 0; j < ARRAY_SIZE(ip_order); j++) {
3211 
3212 			if (block->version->type != ip_order[j] ||
3213 				!block->status.valid)
3214 				continue;
3215 
3216 			r = block->version->funcs->hw_init(&adev->ip_blocks[i]);
3217 			if (r) {
3218 				dev_err(adev->dev, "RE-INIT-early: %s failed\n",
3219 					 block->version->funcs->name);
3220 				return r;
3221 			}
3222 			block->status.hw = true;
3223 		}
3224 	}
3225 
3226 	return 0;
3227 }
3228 
3229 static int amdgpu_device_ip_reinit_late_sriov(struct amdgpu_device *adev)
3230 {
3231 	struct amdgpu_ip_block *block;
3232 	int i, r = 0;
3233 
3234 	static enum amd_ip_block_type ip_order[] = {
3235 		AMD_IP_BLOCK_TYPE_SMC,
3236 		AMD_IP_BLOCK_TYPE_DCE,
3237 		AMD_IP_BLOCK_TYPE_GFX,
3238 		AMD_IP_BLOCK_TYPE_SDMA,
3239 		AMD_IP_BLOCK_TYPE_MES,
3240 		AMD_IP_BLOCK_TYPE_UVD,
3241 		AMD_IP_BLOCK_TYPE_VCE,
3242 		AMD_IP_BLOCK_TYPE_VCN,
3243 		AMD_IP_BLOCK_TYPE_JPEG
3244 	};
3245 
3246 	for (i = 0; i < ARRAY_SIZE(ip_order); i++) {
3247 		block = amdgpu_device_ip_get_ip_block(adev, ip_order[i]);
3248 
3249 		if (!block)
3250 			continue;
3251 
3252 		if (block->status.valid && !block->status.hw) {
3253 			if (block->version->type == AMD_IP_BLOCK_TYPE_SMC) {
3254 				r = amdgpu_ip_block_resume(block);
3255 			} else {
3256 				r = block->version->funcs->hw_init(block);
3257 			}
3258 
3259 			if (r) {
3260 				dev_err(adev->dev, "RE-INIT-late: %s failed\n",
3261 					 block->version->funcs->name);
3262 				break;
3263 			}
3264 			block->status.hw = true;
3265 		}
3266 	}
3267 
3268 	return r;
3269 }
3270 
3271 /**
3272  * amdgpu_device_ip_resume_phase1 - run resume for hardware IPs
3273  *
3274  * @adev: amdgpu_device pointer
3275  *
3276  * First resume function for hardware IPs.  The list of all the hardware
3277  * IPs that make up the asic is walked and the resume callbacks are run for
3278  * COMMON, GMC, and IH.  resume puts the hardware into a functional state
3279  * after a suspend and updates the software state as necessary.  This
3280  * function is also used for restoring the GPU after a GPU reset.
3281  * Returns 0 on success, negative error code on failure.
3282  */
3283 static int amdgpu_device_ip_resume_phase1(struct amdgpu_device *adev)
3284 {
3285 	int i, r;
3286 
3287 	for (i = 0; i < adev->num_ip_blocks; i++) {
3288 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
3289 			continue;
3290 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
3291 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
3292 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH ||
3293 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP && amdgpu_sriov_vf(adev))) {
3294 
3295 			r = amdgpu_ip_block_resume(&adev->ip_blocks[i]);
3296 			if (r)
3297 				return r;
3298 		}
3299 	}
3300 
3301 	return 0;
3302 }
3303 
3304 /**
3305  * amdgpu_device_ip_resume_phase2 - run resume for hardware IPs
3306  *
3307  * @adev: amdgpu_device pointer
3308  *
3309  * Second resume function for hardware IPs.  The list of all the hardware
3310  * IPs that make up the asic is walked and the resume callbacks are run for
3311  * all blocks except COMMON, GMC, and IH.  resume puts the hardware into a
3312  * functional state after a suspend and updates the software state as
3313  * necessary.  This function is also used for restoring the GPU after a GPU
3314  * reset.
3315  * Returns 0 on success, negative error code on failure.
3316  */
3317 static int amdgpu_device_ip_resume_phase2(struct amdgpu_device *adev)
3318 {
3319 	int i, r;
3320 
3321 	for (i = 0; i < adev->num_ip_blocks; i++) {
3322 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
3323 			continue;
3324 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
3325 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
3326 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH ||
3327 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE ||
3328 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)
3329 			continue;
3330 		r = amdgpu_ip_block_resume(&adev->ip_blocks[i]);
3331 		if (r)
3332 			return r;
3333 	}
3334 
3335 	return 0;
3336 }
3337 
3338 /**
3339  * amdgpu_device_ip_resume_phase3 - run resume for hardware IPs
3340  *
3341  * @adev: amdgpu_device pointer
3342  *
3343  * Third resume function for hardware IPs.  The list of all the hardware
3344  * IPs that make up the asic is walked and the resume callbacks are run for
3345  * all DCE.  resume puts the hardware into a functional state after a suspend
3346  * and updates the software state as necessary.  This function is also used
3347  * for restoring the GPU after a GPU reset.
3348  *
3349  * Returns 0 on success, negative error code on failure.
3350  */
3351 static int amdgpu_device_ip_resume_phase3(struct amdgpu_device *adev)
3352 {
3353 	int i, r;
3354 
3355 	for (i = 0; i < adev->num_ip_blocks; i++) {
3356 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
3357 			continue;
3358 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) {
3359 			r = amdgpu_ip_block_resume(&adev->ip_blocks[i]);
3360 			if (r)
3361 				return r;
3362 		}
3363 	}
3364 
3365 	return 0;
3366 }
3367 
3368 /**
3369  * amdgpu_device_ip_resume - run resume for hardware IPs
3370  *
3371  * @adev: amdgpu_device pointer
3372  *
3373  * Main resume function for hardware IPs.  The hardware IPs
3374  * are split into two resume functions because they are
3375  * also used in recovering from a GPU reset and some additional
3376  * steps need to be take between them.  In this case (S3/S4) they are
3377  * run sequentially.
3378  * Returns 0 on success, negative error code on failure.
3379  */
3380 static int amdgpu_device_ip_resume(struct amdgpu_device *adev)
3381 {
3382 	int r;
3383 
3384 	r = amdgpu_device_ip_resume_phase1(adev);
3385 	if (r)
3386 		return r;
3387 
3388 	r = amdgpu_device_fw_loading(adev);
3389 	if (r)
3390 		return r;
3391 
3392 	r = amdgpu_device_ip_resume_phase2(adev);
3393 
3394 	amdgpu_ttm_enable_buffer_funcs(adev);
3395 
3396 	if (r)
3397 		return r;
3398 
3399 	amdgpu_fence_driver_hw_init(adev);
3400 
3401 	r = amdgpu_device_ip_resume_phase3(adev);
3402 
3403 	return r;
3404 }
3405 
3406 /**
3407  * amdgpu_device_detect_sriov_bios - determine if the board supports SR-IOV
3408  *
3409  * @adev: amdgpu_device pointer
3410  *
3411  * Query the VBIOS data tables to determine if the board supports SR-IOV.
3412  */
3413 static void amdgpu_device_detect_sriov_bios(struct amdgpu_device *adev)
3414 {
3415 	if (amdgpu_sriov_vf(adev)) {
3416 		if (adev->is_atom_fw) {
3417 			if (amdgpu_atomfirmware_gpu_virtualization_supported(adev))
3418 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
3419 		} else {
3420 			if (amdgpu_atombios_has_gpu_virtualization_table(adev))
3421 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
3422 		}
3423 
3424 		if (!(adev->virt.caps & AMDGPU_SRIOV_CAPS_SRIOV_VBIOS))
3425 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_NO_VBIOS, 0, 0);
3426 	}
3427 }
3428 
3429 /**
3430  * amdgpu_device_asic_has_dc_support - determine if DC supports the asic
3431  *
3432  * @pdev : pci device context
3433  * @asic_type: AMD asic type
3434  *
3435  * Check if there is DC (new modesetting infrastructre) support for an asic.
3436  * returns true if DC has support, false if not.
3437  */
3438 bool amdgpu_device_asic_has_dc_support(struct pci_dev *pdev,
3439 				       enum amd_asic_type asic_type)
3440 {
3441 	switch (asic_type) {
3442 #ifdef CONFIG_DRM_AMDGPU_SI
3443 	case CHIP_HAINAN:
3444 #endif
3445 	case CHIP_TOPAZ:
3446 		/* chips with no display hardware */
3447 		return false;
3448 #if defined(CONFIG_DRM_AMD_DC)
3449 	case CHIP_TAHITI:
3450 	case CHIP_PITCAIRN:
3451 	case CHIP_VERDE:
3452 	case CHIP_OLAND:
3453 		return amdgpu_dc != 0 && IS_ENABLED(CONFIG_DRM_AMD_DC_SI);
3454 	default:
3455 		return amdgpu_dc != 0;
3456 #else
3457 	default:
3458 		if (amdgpu_dc > 0)
3459 			dev_info_once(
3460 				&pdev->dev,
3461 				"Display Core has been requested via kernel parameter but isn't supported by ASIC, ignoring\n");
3462 		return false;
3463 #endif
3464 	}
3465 }
3466 
3467 /**
3468  * amdgpu_device_has_dc_support - check if dc is supported
3469  *
3470  * @adev: amdgpu_device pointer
3471  *
3472  * Returns true for supported, false for not supported
3473  */
3474 bool amdgpu_device_has_dc_support(struct amdgpu_device *adev)
3475 {
3476 	if (adev->enable_virtual_display ||
3477 	    (adev->harvest_ip_mask & AMD_HARVEST_IP_DMU_MASK))
3478 		return false;
3479 
3480 	return amdgpu_device_asic_has_dc_support(adev->pdev, adev->asic_type);
3481 }
3482 
3483 static void amdgpu_device_xgmi_reset_func(struct work_struct *__work)
3484 {
3485 	struct amdgpu_device *adev =
3486 		container_of(__work, struct amdgpu_device, xgmi_reset_work);
3487 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
3488 
3489 	/* It's a bug to not have a hive within this function */
3490 	if (WARN_ON(!hive))
3491 		return;
3492 
3493 	/*
3494 	 * Use task barrier to synchronize all xgmi reset works across the
3495 	 * hive. task_barrier_enter and task_barrier_exit will block
3496 	 * until all the threads running the xgmi reset works reach
3497 	 * those points. task_barrier_full will do both blocks.
3498 	 */
3499 	if (amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) {
3500 
3501 		task_barrier_enter(&hive->tb);
3502 		adev->asic_reset_res = amdgpu_device_baco_enter(adev);
3503 
3504 		if (adev->asic_reset_res)
3505 			goto fail;
3506 
3507 		task_barrier_exit(&hive->tb);
3508 		adev->asic_reset_res = amdgpu_device_baco_exit(adev);
3509 
3510 		if (adev->asic_reset_res)
3511 			goto fail;
3512 
3513 		amdgpu_ras_reset_error_count(adev, AMDGPU_RAS_BLOCK__MMHUB);
3514 	} else {
3515 
3516 		task_barrier_full(&hive->tb);
3517 		adev->asic_reset_res =  amdgpu_asic_reset(adev);
3518 	}
3519 
3520 fail:
3521 	if (adev->asic_reset_res)
3522 		dev_warn(adev->dev,
3523 			 "ASIC reset failed with error, %d for drm dev, %s",
3524 			 adev->asic_reset_res, adev_to_drm(adev)->unique);
3525 	amdgpu_put_xgmi_hive(hive);
3526 }
3527 
3528 static int amdgpu_device_get_job_timeout_settings(struct amdgpu_device *adev)
3529 {
3530 	char buf[AMDGPU_MAX_TIMEOUT_PARAM_LENGTH];
3531 	char *input = buf;
3532 	char *timeout_setting = NULL;
3533 	int index = 0;
3534 	long timeout;
3535 	int ret = 0;
3536 
3537 	/* By default timeout for all queues is 2 sec */
3538 	adev->gfx_timeout = adev->compute_timeout = adev->sdma_timeout =
3539 		adev->video_timeout = msecs_to_jiffies(2000);
3540 
3541 	if (!strnlen(amdgpu_lockup_timeout, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH))
3542 		return 0;
3543 
3544 	/*
3545 	 * strsep() destructively modifies its input by replacing delimiters
3546 	 * with '\0'. Use a stack copy so the global module parameter buffer
3547 	 * remains intact for multi-GPU systems where this function is called
3548 	 * once per device.
3549 	 */
3550 	strscpy(buf, amdgpu_lockup_timeout, sizeof(buf));
3551 
3552 	while ((timeout_setting = strsep(&input, ",")) &&
3553 	       strnlen(timeout_setting, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
3554 		ret = kstrtol(timeout_setting, 0, &timeout);
3555 		if (ret)
3556 			return ret;
3557 
3558 		if (timeout == 0) {
3559 			index++;
3560 			continue;
3561 		} else if (timeout < 0) {
3562 			timeout = MAX_SCHEDULE_TIMEOUT;
3563 			dev_warn(adev->dev, "lockup timeout disabled");
3564 			add_taint(TAINT_SOFTLOCKUP, LOCKDEP_STILL_OK);
3565 		} else {
3566 			timeout = msecs_to_jiffies(timeout);
3567 		}
3568 
3569 		switch (index++) {
3570 		case 0:
3571 			adev->gfx_timeout = timeout;
3572 			break;
3573 		case 1:
3574 			adev->compute_timeout = timeout;
3575 			break;
3576 		case 2:
3577 			adev->sdma_timeout = timeout;
3578 			break;
3579 		case 3:
3580 			adev->video_timeout = timeout;
3581 			break;
3582 		default:
3583 			break;
3584 		}
3585 	}
3586 
3587 	/* When only one value specified apply it to all queues. */
3588 	if (index == 1)
3589 		adev->gfx_timeout = adev->compute_timeout = adev->sdma_timeout =
3590 			adev->video_timeout = timeout;
3591 
3592 	return ret;
3593 }
3594 
3595 /**
3596  * amdgpu_device_check_iommu_direct_map - check if RAM direct mapped to GPU
3597  *
3598  * @adev: amdgpu_device pointer
3599  *
3600  * RAM direct mapped to GPU if IOMMU is not enabled or is pass through mode
3601  */
3602 static void amdgpu_device_check_iommu_direct_map(struct amdgpu_device *adev)
3603 {
3604 	struct iommu_domain *domain;
3605 
3606 	domain = iommu_get_domain_for_dev(adev->dev);
3607 	if (!domain || domain->type == IOMMU_DOMAIN_IDENTITY)
3608 		adev->ram_is_direct_mapped = true;
3609 }
3610 
3611 #if defined(CONFIG_HSA_AMD_P2P)
3612 /**
3613  * amdgpu_device_check_iommu_remap - Check if DMA remapping is enabled.
3614  *
3615  * @adev: amdgpu_device pointer
3616  *
3617  * return if IOMMU remapping bar address
3618  */
3619 static bool amdgpu_device_check_iommu_remap(struct amdgpu_device *adev)
3620 {
3621 	struct iommu_domain *domain;
3622 
3623 	domain = iommu_get_domain_for_dev(adev->dev);
3624 	if (domain && (domain->type == IOMMU_DOMAIN_DMA ||
3625 		domain->type ==	IOMMU_DOMAIN_DMA_FQ))
3626 		return true;
3627 
3628 	return false;
3629 }
3630 #endif
3631 
3632 static void amdgpu_device_set_mcbp(struct amdgpu_device *adev)
3633 {
3634 	if (amdgpu_mcbp == 1)
3635 		adev->gfx.mcbp = true;
3636 	else if (amdgpu_mcbp == 0)
3637 		adev->gfx.mcbp = false;
3638 
3639 	if (amdgpu_sriov_vf(adev))
3640 		adev->gfx.mcbp = true;
3641 
3642 	if (adev->gfx.mcbp)
3643 		dev_info(adev->dev, "MCBP is enabled\n");
3644 }
3645 
3646 static int amdgpu_device_sys_interface_init(struct amdgpu_device *adev)
3647 {
3648 	int r;
3649 
3650 	r = amdgpu_atombios_sysfs_init(adev);
3651 	if (r)
3652 		drm_err(&adev->ddev,
3653 			"registering atombios sysfs failed (%d).\n", r);
3654 
3655 	r = amdgpu_pm_sysfs_init(adev);
3656 	if (r)
3657 		dev_err(adev->dev, "registering pm sysfs failed (%d).\n", r);
3658 
3659 	r = amdgpu_ucode_sysfs_init(adev);
3660 	if (r) {
3661 		adev->ucode_sysfs_en = false;
3662 		dev_err(adev->dev, "Creating firmware sysfs failed (%d).\n", r);
3663 	} else
3664 		adev->ucode_sysfs_en = true;
3665 
3666 	r = amdgpu_device_attr_sysfs_init(adev);
3667 	if (r)
3668 		dev_err(adev->dev, "Could not create amdgpu device attr\n");
3669 
3670 	r = devm_device_add_group(adev->dev, &amdgpu_board_attrs_group);
3671 	if (r)
3672 		dev_err(adev->dev,
3673 			"Could not create amdgpu board attributes\n");
3674 
3675 	amdgpu_fru_sysfs_init(adev);
3676 	amdgpu_reg_state_sysfs_init(adev);
3677 	amdgpu_xcp_sysfs_init(adev);
3678 	amdgpu_uma_sysfs_init(adev);
3679 	amdgpu_ptl_sysfs_init(adev);
3680 
3681 	return r;
3682 }
3683 
3684 static void amdgpu_device_sys_interface_fini(struct amdgpu_device *adev)
3685 {
3686 	if (adev->pm.sysfs_initialized)
3687 		amdgpu_pm_sysfs_fini(adev);
3688 	if (adev->ucode_sysfs_en)
3689 		amdgpu_ucode_sysfs_fini(adev);
3690 	amdgpu_device_attr_sysfs_fini(adev);
3691 	amdgpu_fru_sysfs_fini(adev);
3692 
3693 	amdgpu_reg_state_sysfs_fini(adev);
3694 	amdgpu_xcp_sysfs_fini(adev);
3695 	amdgpu_uma_sysfs_fini(adev);
3696 	amdgpu_ptl_sysfs_fini(adev);
3697 }
3698 
3699 /**
3700  * amdgpu_device_init - initialize the driver
3701  *
3702  * @adev: amdgpu_device pointer
3703  * @flags: driver flags
3704  *
3705  * Initializes the driver info and hw (all asics).
3706  * Returns 0 for success or an error on failure.
3707  * Called at driver startup.
3708  */
3709 int amdgpu_device_init(struct amdgpu_device *adev,
3710 		       uint32_t flags)
3711 {
3712 	struct pci_dev *pdev = adev->pdev;
3713 	int r, i;
3714 	bool px = false;
3715 	u32 max_MBps;
3716 	int tmp;
3717 
3718 	adev->shutdown = false;
3719 	adev->flags = flags;
3720 
3721 	if (amdgpu_force_asic_type >= 0 && amdgpu_force_asic_type < CHIP_LAST)
3722 		adev->asic_type = amdgpu_force_asic_type;
3723 	else
3724 		adev->asic_type = flags & AMD_ASIC_MASK;
3725 
3726 	adev->usec_timeout = AMDGPU_MAX_USEC_TIMEOUT;
3727 	if (amdgpu_emu_mode == 1)
3728 		adev->usec_timeout *= 10;
3729 	adev->gmc.gart_size = 512 * 1024 * 1024;
3730 	adev->accel_working = false;
3731 	adev->num_rings = 0;
3732 	RCU_INIT_POINTER(adev->gang_submit, dma_fence_get_stub());
3733 	adev->mman.buffer_funcs = NULL;
3734 	adev->mman.num_buffer_funcs_scheds = 0;
3735 	adev->vm_manager.vm_pte_funcs = NULL;
3736 	adev->vm_manager.vm_pte_num_scheds = 0;
3737 	adev->gmc.gmc_funcs = NULL;
3738 	adev->harvest_ip_mask = 0x0;
3739 	adev->fence_context = dma_fence_context_alloc(AMDGPU_MAX_RINGS);
3740 	bitmap_zero(adev->gfx.pipe_reserve_bitmap, AMDGPU_MAX_COMPUTE_QUEUES);
3741 
3742 	amdgpu_reg_access_init(adev);
3743 
3744 	dev_info(
3745 		adev->dev,
3746 		"initializing kernel modesetting (%s 0x%04X:0x%04X 0x%04X:0x%04X 0x%02X).\n",
3747 		amdgpu_asic_name[adev->asic_type], pdev->vendor, pdev->device,
3748 		pdev->subsystem_vendor, pdev->subsystem_device, pdev->revision);
3749 
3750 	/* mutex initialization are all done here so we
3751 	 * can recall function without having locking issues
3752 	 */
3753 	mutex_init(&adev->firmware.mutex);
3754 	mutex_init(&adev->pm.mutex);
3755 	mutex_init(&adev->gfx.gpu_clock_mutex);
3756 	mutex_init(&adev->srbm_mutex);
3757 	mutex_init(&adev->gfx.pipe_reserve_mutex);
3758 	mutex_init(&adev->gfx.gfx_off_mutex);
3759 	mutex_init(&adev->gfx.partition_mutex);
3760 	mutex_init(&adev->grbm_idx_mutex);
3761 	mutex_init(&adev->mn_lock);
3762 	mutex_init(&adev->virt.vf_errors.lock);
3763 	hash_init(adev->mn_hash);
3764 	mutex_init(&adev->psp.mutex);
3765 	mutex_init(&adev->psp.ptl.mutex);
3766 	mutex_init(&adev->notifier_lock);
3767 	mutex_init(&adev->pm.stable_pstate_ctx_lock);
3768 	mutex_init(&adev->benchmark_mutex);
3769 	mutex_init(&adev->gfx.reset_sem_mutex);
3770 
3771 	/* Associate locks with lockdep classes for ordering validation */
3772 	amdgpu_lockdep_set_class(adev);
3773 	/* Initialize the mutex for cleaner shader isolation between GFX and compute processes */
3774 	mutex_init(&adev->enforce_isolation_mutex);
3775 	for (i = 0; i < MAX_XCP; ++i) {
3776 		adev->isolation[i].spearhead = dma_fence_get_stub();
3777 		amdgpu_sync_create(&adev->isolation[i].active);
3778 		amdgpu_sync_create(&adev->isolation[i].prev);
3779 	}
3780 	mutex_init(&adev->gfx.userq_sch_mutex);
3781 	mutex_init(&adev->gfx.workload_profile_mutex);
3782 	mutex_init(&adev->vcn.workload_profile_mutex);
3783 
3784 	spin_lock_init(&adev->irq.lock);
3785 
3786 	amdgpu_device_init_apu_flags(adev);
3787 
3788 	r = amdgpu_device_check_arguments(adev);
3789 	if (r)
3790 		return r;
3791 
3792 	spin_lock_init(&adev->mmio_idx_lock);
3793 	spin_lock_init(&adev->mm_stats.lock);
3794 	spin_lock_init(&adev->virt.rlcg_reg_lock);
3795 	spin_lock_init(&adev->wb.lock);
3796 
3797 	INIT_LIST_HEAD(&adev->reset_list);
3798 
3799 	INIT_LIST_HEAD(&adev->ras_list);
3800 
3801 	INIT_LIST_HEAD(&adev->pm.od_kobj_list);
3802 
3803 	xa_init_flags(&adev->userq_doorbell_xa, XA_FLAGS_LOCK_IRQ);
3804 
3805 	INIT_DELAYED_WORK(&adev->delayed_init_work,
3806 			  amdgpu_device_delayed_init_work_handler);
3807 	INIT_DELAYED_WORK(&adev->gfx.gfx_off_delay_work,
3808 			  amdgpu_device_delay_enable_gfx_off);
3809 	/*
3810 	 * Initialize the enforce_isolation work structures for each XCP
3811 	 * partition.  This work handler is responsible for enforcing shader
3812 	 * isolation on AMD GPUs.  It counts the number of emitted fences for
3813 	 * each GFX and compute ring.  If there are any fences, it schedules
3814 	 * the `enforce_isolation_work` to be run after a delay.  If there are
3815 	 * no fences, it signals the Kernel Fusion Driver (KFD) to resume the
3816 	 * runqueue.
3817 	 */
3818 	for (i = 0; i < MAX_XCP; i++) {
3819 		INIT_DELAYED_WORK(&adev->gfx.enforce_isolation[i].work,
3820 				  amdgpu_gfx_enforce_isolation_handler);
3821 		adev->gfx.enforce_isolation[i].adev = adev;
3822 		adev->gfx.enforce_isolation[i].xcp_id = i;
3823 	}
3824 
3825 	INIT_WORK(&adev->xgmi_reset_work, amdgpu_device_xgmi_reset_func);
3826 
3827 	amdgpu_coredump_init(adev);
3828 
3829 	adev->gfx.gfx_off_req_count = 1;
3830 	adev->gfx.gfx_off_residency = 0;
3831 	adev->gfx.gfx_off_entrycount = 0;
3832 	adev->pm.ac_power = power_supply_is_system_supplied() > 0;
3833 
3834 	atomic_set(&adev->throttling_logging_enabled, 1);
3835 	/*
3836 	 * If throttling continues, logging will be performed every minute
3837 	 * to avoid log flooding. "-1" is subtracted since the thermal
3838 	 * throttling interrupt comes every second. Thus, the total logging
3839 	 * interval is 59 seconds(retelimited printk interval) + 1(waiting
3840 	 * for throttling interrupt) = 60 seconds.
3841 	 */
3842 	ratelimit_state_init(&adev->throttling_logging_rs, (60 - 1) * HZ, 1);
3843 
3844 	ratelimit_set_flags(&adev->throttling_logging_rs, RATELIMIT_MSG_ON_RELEASE);
3845 
3846 	/* Registers mapping */
3847 	/* TODO: block userspace mapping of io register */
3848 	if (adev->asic_type >= CHIP_BONAIRE) {
3849 		adev->rmmio_base = pci_resource_start(adev->pdev, 5);
3850 		adev->rmmio_size = pci_resource_len(adev->pdev, 5);
3851 	} else {
3852 		adev->rmmio_base = pci_resource_start(adev->pdev, 2);
3853 		adev->rmmio_size = pci_resource_len(adev->pdev, 2);
3854 	}
3855 
3856 	for (i = 0; i < AMD_IP_BLOCK_TYPE_NUM; i++)
3857 		atomic_set(&adev->pm.pwr_state[i], POWER_STATE_UNKNOWN);
3858 
3859 	adev->rmmio = ioremap(adev->rmmio_base, adev->rmmio_size);
3860 	if (!adev->rmmio)
3861 		return -ENOMEM;
3862 
3863 	dev_info(adev->dev, "register mmio base: 0x%08X\n",
3864 		 (uint32_t)adev->rmmio_base);
3865 	dev_info(adev->dev, "register mmio size: %u\n",
3866 		 (unsigned int)adev->rmmio_size);
3867 
3868 	/*
3869 	 * Reset domain needs to be present early, before XGMI hive discovered
3870 	 * (if any) and initialized to use reset sem and in_gpu reset flag
3871 	 * early on during init and before calling to RREG32.
3872 	 */
3873 	adev->reset_domain = amdgpu_reset_create_reset_domain(SINGLE_DEVICE, "amdgpu-reset-dev");
3874 	if (!adev->reset_domain)
3875 		return -ENOMEM;
3876 
3877 	/* detect hw virtualization here */
3878 	amdgpu_virt_init(adev);
3879 
3880 	amdgpu_device_get_pcie_info(adev);
3881 
3882 	r = amdgpu_device_get_job_timeout_settings(adev);
3883 	if (r) {
3884 		dev_err(adev->dev, "invalid lockup_timeout parameter syntax\n");
3885 		return r;
3886 	}
3887 
3888 	amdgpu_device_set_mcbp(adev);
3889 
3890 	/*
3891 	 * By default, use default mode where all blocks are expected to be
3892 	 * initialized. At present a 'swinit' of blocks is required to be
3893 	 * completed before the need for a different level is detected.
3894 	 */
3895 	amdgpu_set_init_level(adev, AMDGPU_INIT_LEVEL_DEFAULT);
3896 
3897 	amdgpu_device_check_iommu_direct_map(adev);
3898 
3899 	/* early init functions */
3900 	r = amdgpu_device_ip_early_init(adev);
3901 	if (r)
3902 		return r;
3903 
3904 	/*
3905 	 * No need to remove conflicting FBs for non-display class devices.
3906 	 * This prevents the sysfb from being freed accidently.
3907 	 */
3908 	if ((pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA ||
3909 	    (pdev->class >> 8) == PCI_CLASS_DISPLAY_OTHER) {
3910 		/* Get rid of things like offb */
3911 		r = aperture_remove_conflicting_pci_devices(adev->pdev, amdgpu_kms_driver.name);
3912 		if (r)
3913 			return r;
3914 	}
3915 
3916 	/* Enable TMZ based on IP_VERSION */
3917 	amdgpu_gmc_tmz_set(adev);
3918 
3919 	if (amdgpu_sriov_vf(adev) &&
3920 	    amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(10, 3, 0))
3921 		/* VF MMIO access (except mailbox range) from CPU
3922 		 * will be blocked during sriov runtime
3923 		 */
3924 		adev->virt.caps |= AMDGPU_VF_MMIO_ACCESS_PROTECT;
3925 
3926 	amdgpu_gmc_noretry_set(adev);
3927 	/* Need to get xgmi info early to decide the reset behavior*/
3928 	if (adev->gmc.xgmi.supported) {
3929 		if (adev->gfxhub.funcs &&
3930 		    adev->gfxhub.funcs->get_xgmi_info) {
3931 			r = adev->gfxhub.funcs->get_xgmi_info(adev);
3932 			if (r)
3933 				return r;
3934 		}
3935 	}
3936 
3937 	if (adev->gmc.xgmi.connected_to_cpu) {
3938 		if (adev->mmhub.funcs &&
3939 		    adev->mmhub.funcs->get_xgmi_info) {
3940 			r = adev->mmhub.funcs->get_xgmi_info(adev);
3941 			if (r)
3942 				return r;
3943 		}
3944 	}
3945 
3946 	/* enable PCIE atomic ops */
3947 	if (amdgpu_sriov_vf(adev)) {
3948 		if (adev->virt.fw_reserve.p_pf2vf)
3949 			adev->have_atomics_support = ((struct amd_sriov_msg_pf2vf_info *)
3950 						      adev->virt.fw_reserve.p_pf2vf)->pcie_atomic_ops_support_flags ==
3951 				(PCI_EXP_DEVCAP2_ATOMIC_COMP32 | PCI_EXP_DEVCAP2_ATOMIC_COMP64);
3952 	/* APUs w/ gfx9 onwards doesn't reply on PCIe atomics, rather it is a
3953 	 * internal path natively support atomics, set have_atomics_support to true.
3954 	 */
3955 	} else if ((adev->flags & AMD_IS_APU &&
3956 		   amdgpu_ip_version(adev, GC_HWIP, 0) > IP_VERSION(9, 0, 0)) ||
3957 		   (adev->gmc.xgmi.connected_to_cpu &&
3958 		   amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(12, 1, 0))) {
3959 		adev->have_atomics_support = true;
3960 	} else {
3961 		adev->have_atomics_support =
3962 			!pci_enable_atomic_ops_to_root(adev->pdev,
3963 					  PCI_EXP_DEVCAP2_ATOMIC_COMP32 |
3964 					  PCI_EXP_DEVCAP2_ATOMIC_COMP64);
3965 	}
3966 
3967 	if (!adev->have_atomics_support)
3968 		dev_info(adev->dev, "PCIE atomic ops is not supported\n");
3969 
3970 	/* doorbell bar mapping and doorbell index init*/
3971 	amdgpu_doorbell_init(adev);
3972 
3973 	if (amdgpu_emu_mode == 1) {
3974 		/* post the asic on emulation mode */
3975 		emu_soc_asic_init(adev);
3976 		goto fence_driver_init;
3977 	}
3978 
3979 	amdgpu_reset_init(adev);
3980 
3981 	/* detect if we are with an SRIOV vbios */
3982 	if (adev->bios)
3983 		amdgpu_device_detect_sriov_bios(adev);
3984 
3985 	/* check if we need to reset the asic
3986 	 *  E.g., driver was not cleanly unloaded previously, etc.
3987 	 */
3988 	if (!amdgpu_sriov_vf(adev) && amdgpu_asic_need_reset_on_init(adev)) {
3989 		if (adev->gmc.xgmi.num_physical_nodes) {
3990 			dev_info(adev->dev, "Pending hive reset.\n");
3991 			amdgpu_set_init_level(adev,
3992 					      AMDGPU_INIT_LEVEL_MINIMAL_XGMI);
3993 		} else {
3994 				tmp = amdgpu_reset_method;
3995 				/* It should do a default reset when loading or reloading the driver,
3996 				 * regardless of the module parameter reset_method.
3997 				 */
3998 				amdgpu_reset_method = AMD_RESET_METHOD_NONE;
3999 				r = amdgpu_asic_reset(adev);
4000 				amdgpu_reset_method = tmp;
4001 		}
4002 
4003 		if (r) {
4004 		  dev_err(adev->dev, "asic reset on init failed\n");
4005 		  goto failed;
4006 		}
4007 	}
4008 
4009 	/* Post card if necessary */
4010 	if (amdgpu_device_need_post(adev)) {
4011 		if (!adev->bios) {
4012 			dev_err(adev->dev, "no vBIOS found\n");
4013 			r = -EINVAL;
4014 			goto failed;
4015 		}
4016 		dev_info(adev->dev, "GPU posting now...\n");
4017 		r = amdgpu_device_asic_init(adev);
4018 		if (r) {
4019 			dev_err(adev->dev, "gpu post error!\n");
4020 			goto failed;
4021 		}
4022 	}
4023 
4024 	if (adev->bios) {
4025 		if (adev->is_atom_fw) {
4026 			/* Initialize clocks */
4027 			r = amdgpu_atomfirmware_get_clock_info(adev);
4028 			if (r) {
4029 				dev_err(adev->dev, "amdgpu_atomfirmware_get_clock_info failed\n");
4030 				amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
4031 				goto failed;
4032 			}
4033 		} else {
4034 			/* Initialize clocks */
4035 			r = amdgpu_atombios_get_clock_info(adev);
4036 			if (r) {
4037 				dev_err(adev->dev, "amdgpu_atombios_get_clock_info failed\n");
4038 				amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
4039 				goto failed;
4040 			}
4041 			/* init i2c buses */
4042 			amdgpu_i2c_init(adev);
4043 		}
4044 	}
4045 
4046 fence_driver_init:
4047 	/* Fence driver */
4048 	r = amdgpu_fence_driver_sw_init(adev);
4049 	if (r) {
4050 		dev_err(adev->dev, "amdgpu_fence_driver_sw_init failed\n");
4051 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_FENCE_INIT_FAIL, 0, 0);
4052 		goto failed;
4053 	}
4054 
4055 	/* init the mode config */
4056 	drm_mode_config_init(adev_to_drm(adev));
4057 
4058 	r = amdgpu_device_ip_init(adev);
4059 	if (r) {
4060 		dev_err(adev->dev, "amdgpu_device_ip_init failed\n");
4061 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_INIT_FAIL, 0, 0);
4062 		goto release_ras_con;
4063 	}
4064 
4065 	amdgpu_fence_driver_hw_init(adev);
4066 
4067 	dev_info(adev->dev,
4068 		"SE %d, SH per SE %d, CU per SH %d, active_cu_number %d\n",
4069 			adev->gfx.config.max_shader_engines,
4070 			adev->gfx.config.max_sh_per_se,
4071 			adev->gfx.config.max_cu_per_sh,
4072 			adev->gfx.cu_info.number);
4073 
4074 	adev->accel_working = true;
4075 
4076 	amdgpu_vm_check_compute_bug(adev);
4077 
4078 	/* Initialize the buffer migration limit. */
4079 	if (amdgpu_moverate >= 0)
4080 		max_MBps = amdgpu_moverate;
4081 	else
4082 		max_MBps = 8; /* Allow 8 MB/s. */
4083 	/* Get a log2 for easy divisions. */
4084 	adev->mm_stats.log2_max_MBps = ilog2(max(1u, max_MBps));
4085 
4086 	/*
4087 	 * Register gpu instance before amdgpu_device_enable_mgpu_fan_boost.
4088 	 * Otherwise the mgpu fan boost feature will be skipped due to the
4089 	 * gpu instance is counted less.
4090 	 */
4091 	amdgpu_register_gpu_instance(adev);
4092 
4093 	/* enable clockgating, etc. after ib tests, etc. since some blocks require
4094 	 * explicit gating rather than handling it automatically.
4095 	 */
4096 	if (adev->init_lvl->level != AMDGPU_INIT_LEVEL_MINIMAL_XGMI) {
4097 		r = amdgpu_device_ip_late_init(adev);
4098 		if (r) {
4099 			dev_err(adev->dev, "amdgpu_device_ip_late_init failed\n");
4100 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_LATE_INIT_FAIL, 0, r);
4101 			goto release_ras_con;
4102 		}
4103 		/* must succeed. */
4104 		amdgpu_ras_resume(adev);
4105 		queue_delayed_work(system_dfl_wq, &adev->delayed_init_work,
4106 				   msecs_to_jiffies(AMDGPU_RESUME_MS));
4107 	}
4108 
4109 	if (amdgpu_sriov_vf(adev)) {
4110 		amdgpu_virt_release_full_gpu(adev, true);
4111 		flush_delayed_work(&adev->delayed_init_work);
4112 	}
4113 
4114 	/* Don't init kfd if whole hive need to be reset during init */
4115 	if (adev->init_lvl->level != AMDGPU_INIT_LEVEL_MINIMAL_XGMI) {
4116 		kgd2kfd_init_zone_device(adev);
4117 		kfd_update_svm_support_properties(adev);
4118 	}
4119 
4120 	if (adev->init_lvl->level == AMDGPU_INIT_LEVEL_MINIMAL_XGMI)
4121 		amdgpu_xgmi_reset_on_init(adev);
4122 
4123 	/*
4124 	 * Place those sysfs registering after `late_init`. As some of those
4125 	 * operations performed in `late_init` might affect the sysfs
4126 	 * interfaces creating.
4127 	 */
4128 	r = amdgpu_device_sys_interface_init(adev);
4129 
4130 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
4131 		r = amdgpu_pmu_init(adev);
4132 	if (r)
4133 		dev_err(adev->dev, "amdgpu_pmu_init failed\n");
4134 
4135 	/* Have stored pci confspace at hand for restore in sudden PCI error */
4136 	if (amdgpu_device_cache_pci_state(adev->pdev))
4137 		pci_restore_state(pdev);
4138 
4139 	/* if we have > 1 VGA cards, then disable the amdgpu VGA resources */
4140 	/* this will fail for cards that aren't VGA class devices, just
4141 	 * ignore it
4142 	 */
4143 	if ((adev->pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA)
4144 		vga_client_register(adev->pdev, amdgpu_device_vga_set_decode);
4145 
4146 	px = amdgpu_device_supports_px(adev);
4147 
4148 	if (px || (!dev_is_removable(&adev->pdev->dev) &&
4149 				apple_gmux_detect(NULL, NULL)))
4150 		vga_switcheroo_register_client(adev->pdev,
4151 					       &amdgpu_switcheroo_ops, px);
4152 
4153 	if (px)
4154 		vga_switcheroo_init_domain_pm_ops(adev->dev, &adev->vga_pm_domain);
4155 
4156 	adev->pm_nb.notifier_call = amdgpu_device_pm_notifier;
4157 	r = register_pm_notifier(&adev->pm_nb);
4158 	if (r)
4159 		goto failed;
4160 
4161 	return 0;
4162 
4163 release_ras_con:
4164 	if (amdgpu_sriov_vf(adev))
4165 		amdgpu_virt_release_full_gpu(adev, true);
4166 
4167 	/* failed in exclusive mode due to timeout */
4168 	if (amdgpu_sriov_vf(adev) &&
4169 		!amdgpu_sriov_runtime(adev) &&
4170 		amdgpu_virt_mmio_blocked(adev) &&
4171 		!amdgpu_virt_wait_reset(adev)) {
4172 		dev_err(adev->dev, "VF exclusive mode timeout\n");
4173 		/* Don't send request since VF is inactive. */
4174 		adev->virt.caps &= ~AMDGPU_SRIOV_CAPS_RUNTIME;
4175 		adev->virt.ops = NULL;
4176 		r = -EAGAIN;
4177 	}
4178 	amdgpu_release_ras_context(adev);
4179 
4180 failed:
4181 	amdgpu_vf_error_trans_all(adev);
4182 
4183 	return r;
4184 }
4185 
4186 static void amdgpu_device_unmap_mmio(struct amdgpu_device *adev)
4187 {
4188 
4189 	/* Clear all CPU mappings pointing to this device */
4190 	unmap_mapping_range(adev->ddev.anon_inode->i_mapping, 0, 0, 1);
4191 
4192 	/* Unmap all mapped bars - Doorbell, registers and VRAM */
4193 	amdgpu_doorbell_fini(adev);
4194 
4195 	iounmap(adev->rmmio);
4196 	adev->rmmio = NULL;
4197 	if (adev->mman.aper_base_kaddr)
4198 		iounmap(adev->mman.aper_base_kaddr);
4199 	adev->mman.aper_base_kaddr = NULL;
4200 
4201 	/* Memory manager related */
4202 	if (!adev->gmc.xgmi.connected_to_cpu && !adev->gmc.is_app_apu) {
4203 		arch_phys_wc_del(adev->gmc.vram_mtrr);
4204 		arch_io_free_memtype_wc(adev->gmc.aper_base, adev->gmc.aper_size);
4205 	}
4206 }
4207 
4208 /**
4209  * amdgpu_device_fini_hw - tear down the driver
4210  *
4211  * @adev: amdgpu_device pointer
4212  *
4213  * Tear down the driver info (all asics).
4214  * Called at driver shutdown.
4215  */
4216 void amdgpu_device_fini_hw(struct amdgpu_device *adev)
4217 {
4218 	dev_info(adev->dev, "finishing device.\n");
4219 	flush_delayed_work(&adev->delayed_init_work);
4220 
4221 	if (adev->mman.initialized)
4222 		drain_workqueue(adev->mman.bdev.wq);
4223 	adev->shutdown = true;
4224 
4225 	unregister_pm_notifier(&adev->pm_nb);
4226 
4227 	/* make sure IB test finished before entering exclusive mode
4228 	 * to avoid preemption on IB test
4229 	 */
4230 	if (amdgpu_sriov_vf(adev)) {
4231 		amdgpu_virt_request_full_gpu(adev, false);
4232 		amdgpu_virt_fini_data_exchange(adev);
4233 	}
4234 
4235 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
4236 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
4237 
4238 	/* disable all interrupts */
4239 	amdgpu_irq_disable_all(adev);
4240 	if (adev->mode_info.mode_config_initialized) {
4241 		if (!drm_drv_uses_atomic_modeset(adev_to_drm(adev)))
4242 			drm_helper_force_disable_all(adev_to_drm(adev));
4243 		else
4244 			drm_atomic_helper_shutdown(adev_to_drm(adev));
4245 	}
4246 	amdgpu_fence_driver_hw_fini(adev);
4247 
4248 	amdgpu_device_sys_interface_fini(adev);
4249 
4250 	/* disable ras feature must before hw fini */
4251 	amdgpu_ras_pre_fini(adev);
4252 
4253 	amdgpu_ttm_disable_buffer_funcs(adev);
4254 
4255 	/*
4256 	 * device went through surprise hotplug; we need to destroy topology
4257 	 * before ip_fini_early to prevent kfd locking refcount issues by calling
4258 	 * amdgpu_amdkfd_suspend()
4259 	 */
4260 	if (pci_dev_is_disconnected(adev->pdev))
4261 		amdgpu_amdkfd_device_fini_sw(adev);
4262 
4263 	amdgpu_coredump_fini(adev);
4264 	amdgpu_device_ip_fini_early(adev);
4265 
4266 	amdgpu_irq_fini_hw(adev);
4267 
4268 	if (adev->mman.initialized)
4269 		ttm_device_clear_dma_mappings(&adev->mman.bdev);
4270 
4271 	amdgpu_gart_dummy_page_fini(adev);
4272 
4273 	if (pci_dev_is_disconnected(adev->pdev))
4274 		amdgpu_device_unmap_mmio(adev);
4275 
4276 }
4277 
4278 void amdgpu_device_fini_sw(struct amdgpu_device *adev)
4279 {
4280 	int i, idx;
4281 	bool px;
4282 
4283 	amdgpu_device_ip_fini(adev);
4284 	amdgpu_fence_driver_sw_fini(adev);
4285 	amdgpu_ucode_release(&adev->firmware.gpu_info_fw);
4286 	adev->accel_working = false;
4287 	dma_fence_put(rcu_dereference_protected(adev->gang_submit, true));
4288 	for (i = 0; i < MAX_XCP; ++i) {
4289 		dma_fence_put(adev->isolation[i].spearhead);
4290 		amdgpu_sync_free(&adev->isolation[i].active);
4291 		amdgpu_sync_free(&adev->isolation[i].prev);
4292 	}
4293 
4294 	amdgpu_reset_fini(adev);
4295 
4296 	/* free i2c buses */
4297 	amdgpu_i2c_fini(adev);
4298 
4299 	if (adev->bios) {
4300 		if (amdgpu_emu_mode != 1)
4301 			amdgpu_atombios_fini(adev);
4302 		amdgpu_bios_release(adev);
4303 	}
4304 
4305 	kfree(adev->fru_info);
4306 	adev->fru_info = NULL;
4307 
4308 	kfree(adev->xcp_mgr);
4309 	adev->xcp_mgr = NULL;
4310 
4311 	px = amdgpu_device_supports_px(adev);
4312 
4313 	if (px || (!dev_is_removable(&adev->pdev->dev) &&
4314 				apple_gmux_detect(NULL, NULL)))
4315 		vga_switcheroo_unregister_client(adev->pdev);
4316 
4317 	if (px)
4318 		vga_switcheroo_fini_domain_pm_ops(adev->dev);
4319 
4320 	if ((adev->pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA)
4321 		vga_client_unregister(adev->pdev);
4322 
4323 	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
4324 
4325 		iounmap(adev->rmmio);
4326 		adev->rmmio = NULL;
4327 		drm_dev_exit(idx);
4328 	}
4329 
4330 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
4331 		amdgpu_pmu_fini(adev);
4332 	if (adev->discovery.bin)
4333 		amdgpu_discovery_fini(adev);
4334 
4335 	amdgpu_reset_put_reset_domain(adev->reset_domain);
4336 	adev->reset_domain = NULL;
4337 
4338 	kfree(adev->pci_state);
4339 	kfree(adev->pcie_reset_ctx.swds_pcistate);
4340 	kfree(adev->pcie_reset_ctx.swus_pcistate);
4341 }
4342 
4343 /**
4344  * amdgpu_device_evict_resources - evict device resources
4345  * @adev: amdgpu device object
4346  *
4347  * Evicts all ttm device resources(vram BOs, gart table) from the lru list
4348  * of the vram memory type. Mainly used for evicting device resources
4349  * at suspend time.
4350  *
4351  */
4352 static int amdgpu_device_evict_resources(struct amdgpu_device *adev)
4353 {
4354 	int ret;
4355 
4356 	/* No need to evict vram on APUs unless going to S4 */
4357 	if (!adev->in_s4 && (adev->flags & AMD_IS_APU))
4358 		return 0;
4359 
4360 	/* No need to evict when going to S5 through S4 callbacks */
4361 	if (system_state == SYSTEM_POWER_OFF)
4362 		return 0;
4363 
4364 	ret = amdgpu_ttm_evict_resources(adev, TTM_PL_VRAM);
4365 	if (ret) {
4366 		dev_warn(adev->dev, "evicting device resources failed\n");
4367 		return ret;
4368 	}
4369 
4370 	if (adev->in_s4) {
4371 		ret = ttm_device_prepare_hibernation(&adev->mman.bdev);
4372 		if (ret)
4373 			dev_err(adev->dev, "prepare hibernation failed, %d\n", ret);
4374 	}
4375 	return ret;
4376 }
4377 
4378 /*
4379  * Suspend & resume.
4380  */
4381 /**
4382  * amdgpu_device_pm_notifier - Notification block for Suspend/Hibernate events
4383  * @nb: notifier block
4384  * @mode: suspend mode
4385  * @data: data
4386  *
4387  * This function is called when the system is about to suspend or hibernate.
4388  * It is used to set the appropriate flags so that eviction can be optimized
4389  * in the pm prepare callback.
4390  */
4391 static int amdgpu_device_pm_notifier(struct notifier_block *nb, unsigned long mode,
4392 				     void *data)
4393 {
4394 	struct amdgpu_device *adev = container_of(nb, struct amdgpu_device, pm_nb);
4395 
4396 	switch (mode) {
4397 	case PM_HIBERNATION_PREPARE:
4398 		adev->in_s4 = true;
4399 		break;
4400 	case PM_POST_HIBERNATION:
4401 		adev->in_s4 = false;
4402 		break;
4403 	}
4404 
4405 	return NOTIFY_DONE;
4406 }
4407 
4408 /**
4409  * amdgpu_device_prepare - prepare for device suspend
4410  *
4411  * @dev: drm dev pointer
4412  *
4413  * Prepare to put the hw in the suspend state (all asics).
4414  * Returns 0 for success or an error on failure.
4415  * Called at driver suspend.
4416  */
4417 int amdgpu_device_prepare(struct drm_device *dev)
4418 {
4419 	struct amdgpu_device *adev = drm_to_adev(dev);
4420 	int i, r;
4421 
4422 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
4423 		return 0;
4424 
4425 	/* Evict the majority of BOs before starting suspend sequence */
4426 	r = amdgpu_device_evict_resources(adev);
4427 	if (r)
4428 		return r;
4429 
4430 	flush_delayed_work(&adev->gfx.gfx_off_delay_work);
4431 
4432 	for (i = 0; i < adev->num_ip_blocks; i++) {
4433 		if (!adev->ip_blocks[i].status.valid)
4434 			continue;
4435 		if (!adev->ip_blocks[i].version->funcs->prepare_suspend)
4436 			continue;
4437 		r = adev->ip_blocks[i].version->funcs->prepare_suspend(&adev->ip_blocks[i]);
4438 		if (r)
4439 			return r;
4440 	}
4441 
4442 	return 0;
4443 }
4444 
4445 /**
4446  * amdgpu_device_complete - complete power state transition
4447  *
4448  * @dev: drm dev pointer
4449  *
4450  * Undo the changes from amdgpu_device_prepare. This will be
4451  * called on all resume transitions, including those that failed.
4452  */
4453 void amdgpu_device_complete(struct drm_device *dev)
4454 {
4455 	struct amdgpu_device *adev = drm_to_adev(dev);
4456 	int i;
4457 
4458 	for (i = 0; i < adev->num_ip_blocks; i++) {
4459 		if (!adev->ip_blocks[i].status.valid)
4460 			continue;
4461 		if (!adev->ip_blocks[i].version->funcs->complete)
4462 			continue;
4463 		adev->ip_blocks[i].version->funcs->complete(&adev->ip_blocks[i]);
4464 	}
4465 }
4466 
4467 /**
4468  * amdgpu_device_suspend - initiate device suspend
4469  *
4470  * @dev: drm dev pointer
4471  * @notify_clients: notify in-kernel DRM clients
4472  *
4473  * Puts the hw in the suspend state (all asics).
4474  * Returns 0 for success or an error on failure.
4475  * Called at driver suspend.
4476  */
4477 int amdgpu_device_suspend(struct drm_device *dev, bool notify_clients)
4478 {
4479 	struct amdgpu_device *adev = drm_to_adev(dev);
4480 	int r, rec;
4481 
4482 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
4483 		return 0;
4484 
4485 	adev->in_suspend = true;
4486 
4487 	if (amdgpu_sriov_vf(adev)) {
4488 		if (!adev->in_runpm)
4489 			amdgpu_amdkfd_suspend_process(adev);
4490 		amdgpu_virt_fini_data_exchange(adev);
4491 		r = amdgpu_virt_request_full_gpu(adev, false);
4492 		if (r)
4493 			return r;
4494 	}
4495 
4496 	r = amdgpu_acpi_smart_shift_update(adev, AMDGPU_SS_DEV_D3);
4497 	if (r)
4498 		goto unwind_sriov;
4499 
4500 	if (notify_clients)
4501 		drm_client_dev_suspend(adev_to_drm(adev));
4502 
4503 	cancel_delayed_work_sync(&adev->delayed_init_work);
4504 
4505 	amdgpu_ras_suspend(adev);
4506 
4507 	r = amdgpu_device_ip_suspend_phase1(adev);
4508 	if (r)
4509 		goto unwind_smartshift;
4510 
4511 	amdgpu_amdkfd_suspend(adev, !amdgpu_sriov_vf(adev) && !adev->in_runpm);
4512 	r = amdgpu_userq_suspend(adev);
4513 	if (r)
4514 		goto unwind_ip_phase1;
4515 
4516 	r = amdgpu_device_evict_resources(adev);
4517 	if (r)
4518 		goto unwind_userq;
4519 
4520 	amdgpu_ttm_disable_buffer_funcs(adev);
4521 
4522 	amdgpu_fence_driver_hw_fini(adev);
4523 
4524 	r = amdgpu_device_ip_suspend_phase2(adev);
4525 	if (r)
4526 		goto unwind_evict;
4527 
4528 	if (amdgpu_sriov_vf(adev))
4529 		amdgpu_virt_release_full_gpu(adev, false);
4530 
4531 	return 0;
4532 
4533 unwind_evict:
4534 	amdgpu_ttm_enable_buffer_funcs(adev);
4535 	amdgpu_fence_driver_hw_init(adev);
4536 
4537 unwind_userq:
4538 	rec = amdgpu_userq_resume(adev);
4539 	if (rec) {
4540 		dev_warn(adev->dev, "failed to re-initialize user queues: %d\n", rec);
4541 		return r;
4542 	}
4543 	rec = amdgpu_amdkfd_resume(adev, !amdgpu_sriov_vf(adev) && !adev->in_runpm);
4544 	if (rec) {
4545 		dev_warn(adev->dev, "failed to re-initialize kfd: %d\n", rec);
4546 		return r;
4547 	}
4548 
4549 unwind_ip_phase1:
4550 	/* suspend phase 1 = resume phase 3 */
4551 	rec = amdgpu_device_ip_resume_phase3(adev);
4552 	if (rec) {
4553 		dev_warn(adev->dev, "failed to re-initialize IPs phase1: %d\n", rec);
4554 		return r;
4555 	}
4556 
4557 unwind_smartshift:
4558 	rec = amdgpu_acpi_smart_shift_update(adev, AMDGPU_SS_DEV_D0);
4559 	if (rec) {
4560 		dev_warn(adev->dev, "failed to re-update smart shift: %d\n", rec);
4561 		return r;
4562 	}
4563 
4564 	if (notify_clients)
4565 		drm_client_dev_resume(adev_to_drm(adev));
4566 
4567 	amdgpu_ras_resume(adev);
4568 
4569 unwind_sriov:
4570 	if (amdgpu_sriov_vf(adev)) {
4571 		rec = amdgpu_virt_request_full_gpu(adev, true);
4572 		if (rec) {
4573 			dev_warn(adev->dev, "failed to reinitialize sriov: %d\n", rec);
4574 			return r;
4575 		}
4576 	}
4577 
4578 	adev->in_suspend = adev->in_s0ix = adev->in_s3 = false;
4579 
4580 	return r;
4581 }
4582 
4583 static inline int amdgpu_virt_resume(struct amdgpu_device *adev)
4584 {
4585 	int r;
4586 	unsigned int prev_physical_node_id = adev->gmc.xgmi.physical_node_id;
4587 
4588 	/* During VM resume, QEMU programming of VF MSIX table (register GFXMSIX_VECT0_ADDR_LO)
4589 	 * may not work. The access could be blocked by nBIF protection as VF isn't in
4590 	 * exclusive access mode. Exclusive access is enabled now, disable/enable MSIX
4591 	 * so that QEMU reprograms MSIX table.
4592 	 */
4593 	amdgpu_restore_msix(adev);
4594 
4595 	r = adev->gfxhub.funcs->get_xgmi_info(adev);
4596 	if (r)
4597 		return r;
4598 
4599 	dev_info(adev->dev, "xgmi node, old id %d, new id %d\n",
4600 		prev_physical_node_id, adev->gmc.xgmi.physical_node_id);
4601 
4602 	adev->vm_manager.vram_base_offset = adev->gfxhub.funcs->get_mc_fb_offset(adev);
4603 	adev->vm_manager.vram_base_offset +=
4604 		adev->gmc.xgmi.physical_node_id * adev->gmc.xgmi.node_segment_size;
4605 
4606 	return 0;
4607 }
4608 
4609 /**
4610  * amdgpu_device_resume - initiate device resume
4611  *
4612  * @dev: drm dev pointer
4613  * @notify_clients: notify in-kernel DRM clients
4614  *
4615  * Bring the hw back to operating state (all asics).
4616  * Returns 0 for success or an error on failure.
4617  * Called at driver resume.
4618  */
4619 int amdgpu_device_resume(struct drm_device *dev, bool notify_clients)
4620 {
4621 	struct amdgpu_device *adev = drm_to_adev(dev);
4622 	int r = 0;
4623 
4624 	if (amdgpu_sriov_vf(adev)) {
4625 		r = amdgpu_virt_request_full_gpu(adev, true);
4626 		if (r)
4627 			return r;
4628 	}
4629 
4630 	if (amdgpu_virt_xgmi_migrate_enabled(adev)) {
4631 		r = amdgpu_virt_resume(adev);
4632 		if (r)
4633 			goto exit;
4634 	}
4635 
4636 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
4637 		return 0;
4638 
4639 	if (adev->in_s0ix)
4640 		amdgpu_dpm_gfx_state_change(adev, sGpuChangeState_D0Entry);
4641 
4642 	/* post card */
4643 	if (amdgpu_device_need_post(adev)) {
4644 		r = amdgpu_device_asic_init(adev);
4645 		if (r)
4646 			dev_err(adev->dev, "amdgpu asic init failed\n");
4647 	}
4648 
4649 	r = amdgpu_device_ip_resume(adev);
4650 
4651 	if (r) {
4652 		dev_err(adev->dev, "amdgpu_device_ip_resume failed (%d).\n", r);
4653 		goto exit;
4654 	}
4655 
4656 	r = amdgpu_amdkfd_resume(adev, !amdgpu_sriov_vf(adev) && !adev->in_runpm);
4657 	if (r)
4658 		goto exit;
4659 
4660 	r = amdgpu_userq_resume(adev);
4661 	if (r)
4662 		goto exit;
4663 
4664 	r = amdgpu_device_ip_late_init(adev);
4665 	if (r)
4666 		goto exit;
4667 
4668 	queue_delayed_work(system_dfl_wq, &adev->delayed_init_work,
4669 			   msecs_to_jiffies(AMDGPU_RESUME_MS));
4670 exit:
4671 	if (amdgpu_sriov_vf(adev)) {
4672 		amdgpu_virt_init_data_exchange(adev);
4673 		amdgpu_virt_release_full_gpu(adev, true);
4674 
4675 		if (!r && !adev->in_runpm)
4676 			r = amdgpu_amdkfd_resume_process(adev);
4677 	}
4678 
4679 	if (r)
4680 		return r;
4681 
4682 	/* Make sure IB tests flushed */
4683 	flush_delayed_work(&adev->delayed_init_work);
4684 
4685 	if (notify_clients)
4686 		drm_client_dev_resume(adev_to_drm(adev));
4687 
4688 	amdgpu_ras_resume(adev);
4689 
4690 	if (adev->mode_info.num_crtc) {
4691 		/*
4692 		 * Most of the connector probing functions try to acquire runtime pm
4693 		 * refs to ensure that the GPU is powered on when connector polling is
4694 		 * performed. Since we're calling this from a runtime PM callback,
4695 		 * trying to acquire rpm refs will cause us to deadlock.
4696 		 *
4697 		 * Since we're guaranteed to be holding the rpm lock, it's safe to
4698 		 * temporarily disable the rpm helpers so this doesn't deadlock us.
4699 		 */
4700 #ifdef CONFIG_PM
4701 		dev->dev->power.disable_depth++;
4702 #endif
4703 		if (!adev->dc_enabled)
4704 			drm_helper_hpd_irq_event(dev);
4705 		else
4706 			drm_kms_helper_hotplug_event(dev);
4707 #ifdef CONFIG_PM
4708 		dev->dev->power.disable_depth--;
4709 #endif
4710 	}
4711 
4712 	amdgpu_vram_mgr_clear_reset_blocks(adev);
4713 	adev->in_suspend = false;
4714 
4715 	if (amdgpu_acpi_smart_shift_update(adev, AMDGPU_SS_DEV_D0))
4716 		dev_warn(adev->dev, "smart shift update failed\n");
4717 
4718 	return 0;
4719 }
4720 
4721 /**
4722  * amdgpu_device_ip_check_soft_reset - did soft reset succeed
4723  *
4724  * @adev: amdgpu_device pointer
4725  *
4726  * The list of all the hardware IPs that make up the asic is walked and
4727  * the check_soft_reset callbacks are run.  check_soft_reset determines
4728  * if the asic is still hung or not.
4729  * Returns true if any of the IPs are still in a hung state, false if not.
4730  */
4731 static bool amdgpu_device_ip_check_soft_reset(struct amdgpu_device *adev)
4732 {
4733 	int i;
4734 	bool asic_hang = false;
4735 
4736 	if (amdgpu_sriov_vf(adev))
4737 		return true;
4738 
4739 	if (amdgpu_asic_need_full_reset(adev))
4740 		return true;
4741 
4742 	for (i = 0; i < adev->num_ip_blocks; i++) {
4743 		if (!adev->ip_blocks[i].status.valid)
4744 			continue;
4745 		if (adev->ip_blocks[i].version->funcs->check_soft_reset)
4746 			adev->ip_blocks[i].status.hang =
4747 				adev->ip_blocks[i].version->funcs->check_soft_reset(
4748 					&adev->ip_blocks[i]);
4749 		if (adev->ip_blocks[i].status.hang) {
4750 			dev_info(adev->dev, "IP block:%s is hung!\n", adev->ip_blocks[i].version->funcs->name);
4751 			asic_hang = true;
4752 		}
4753 	}
4754 	return asic_hang;
4755 }
4756 
4757 /**
4758  * amdgpu_device_ip_pre_soft_reset - prepare for soft reset
4759  *
4760  * @adev: amdgpu_device pointer
4761  *
4762  * The list of all the hardware IPs that make up the asic is walked and the
4763  * pre_soft_reset callbacks are run if the block is hung.  pre_soft_reset
4764  * handles any IP specific hardware or software state changes that are
4765  * necessary for a soft reset to succeed.
4766  * Returns 0 on success, negative error code on failure.
4767  */
4768 static int amdgpu_device_ip_pre_soft_reset(struct amdgpu_device *adev)
4769 {
4770 	int i, r = 0;
4771 
4772 	for (i = 0; i < adev->num_ip_blocks; i++) {
4773 		if (!adev->ip_blocks[i].status.valid)
4774 			continue;
4775 		if (adev->ip_blocks[i].status.hang &&
4776 		    adev->ip_blocks[i].version->funcs->pre_soft_reset) {
4777 			r = adev->ip_blocks[i].version->funcs->pre_soft_reset(&adev->ip_blocks[i]);
4778 			if (r)
4779 				return r;
4780 		}
4781 	}
4782 
4783 	return 0;
4784 }
4785 
4786 /**
4787  * amdgpu_device_ip_need_full_reset - check if a full asic reset is needed
4788  *
4789  * @adev: amdgpu_device pointer
4790  *
4791  * Some hardware IPs cannot be soft reset.  If they are hung, a full gpu
4792  * reset is necessary to recover.
4793  * Returns true if a full asic reset is required, false if not.
4794  */
4795 static bool amdgpu_device_ip_need_full_reset(struct amdgpu_device *adev)
4796 {
4797 	int i;
4798 
4799 	if (amdgpu_asic_need_full_reset(adev))
4800 		return true;
4801 
4802 	for (i = 0; i < adev->num_ip_blocks; i++) {
4803 		if (!adev->ip_blocks[i].status.valid)
4804 			continue;
4805 		if ((adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) ||
4806 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) ||
4807 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_ACP) ||
4808 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) ||
4809 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
4810 			if (adev->ip_blocks[i].status.hang) {
4811 				dev_info(adev->dev, "Some block need full reset!\n");
4812 				return true;
4813 			}
4814 		}
4815 	}
4816 	return false;
4817 }
4818 
4819 /**
4820  * amdgpu_device_ip_soft_reset - do a soft reset
4821  *
4822  * @adev: amdgpu_device pointer
4823  *
4824  * The list of all the hardware IPs that make up the asic is walked and the
4825  * soft_reset callbacks are run if the block is hung.  soft_reset handles any
4826  * IP specific hardware or software state changes that are necessary to soft
4827  * reset the IP.
4828  * Returns 0 on success, negative error code on failure.
4829  */
4830 static int amdgpu_device_ip_soft_reset(struct amdgpu_device *adev)
4831 {
4832 	int i, r = 0;
4833 
4834 	for (i = 0; i < adev->num_ip_blocks; i++) {
4835 		if (!adev->ip_blocks[i].status.valid)
4836 			continue;
4837 		if (adev->ip_blocks[i].status.hang &&
4838 		    adev->ip_blocks[i].version->funcs->soft_reset) {
4839 			r = adev->ip_blocks[i].version->funcs->soft_reset(&adev->ip_blocks[i]);
4840 			if (r)
4841 				return r;
4842 		}
4843 	}
4844 
4845 	return 0;
4846 }
4847 
4848 /**
4849  * amdgpu_device_ip_post_soft_reset - clean up from soft reset
4850  *
4851  * @adev: amdgpu_device pointer
4852  *
4853  * The list of all the hardware IPs that make up the asic is walked and the
4854  * post_soft_reset callbacks are run if the asic was hung.  post_soft_reset
4855  * handles any IP specific hardware or software state changes that are
4856  * necessary after the IP has been soft reset.
4857  * Returns 0 on success, negative error code on failure.
4858  */
4859 static int amdgpu_device_ip_post_soft_reset(struct amdgpu_device *adev)
4860 {
4861 	int i, r = 0;
4862 
4863 	for (i = 0; i < adev->num_ip_blocks; i++) {
4864 		if (!adev->ip_blocks[i].status.valid)
4865 			continue;
4866 		if (adev->ip_blocks[i].status.hang &&
4867 		    adev->ip_blocks[i].version->funcs->post_soft_reset)
4868 			r = adev->ip_blocks[i].version->funcs->post_soft_reset(&adev->ip_blocks[i]);
4869 		if (r)
4870 			return r;
4871 	}
4872 
4873 	return 0;
4874 }
4875 
4876 /**
4877  * amdgpu_device_reset_sriov - reset ASIC for SR-IOV vf
4878  *
4879  * @adev: amdgpu_device pointer
4880  * @reset_context: amdgpu reset context pointer
4881  *
4882  * do VF FLR and reinitialize Asic
4883  * return 0 means succeeded otherwise failed
4884  */
4885 static int amdgpu_device_reset_sriov(struct amdgpu_device *adev,
4886 				     struct amdgpu_reset_context *reset_context)
4887 {
4888 	int r;
4889 	struct amdgpu_hive_info *hive = NULL;
4890 
4891 	if (test_bit(AMDGPU_HOST_FLR, &reset_context->flags)) {
4892 		if (!amdgpu_ras_get_fed_status(adev))
4893 			amdgpu_virt_ready_to_reset(adev);
4894 		amdgpu_virt_wait_reset(adev);
4895 		clear_bit(AMDGPU_HOST_FLR, &reset_context->flags);
4896 		r = amdgpu_virt_request_full_gpu(adev, true);
4897 	} else {
4898 		r = amdgpu_virt_reset_gpu(adev);
4899 	}
4900 	if (r)
4901 		return r;
4902 
4903 	amdgpu_ras_clear_err_state(adev);
4904 	amdgpu_irq_gpu_reset_resume_helper(adev);
4905 
4906 	/* some sw clean up VF needs to do before recover */
4907 	amdgpu_virt_post_reset(adev);
4908 
4909 	/* Resume IP prior to SMC */
4910 	r = amdgpu_device_ip_reinit_early_sriov(adev);
4911 	if (r)
4912 		return r;
4913 
4914 	amdgpu_virt_init_data_exchange(adev);
4915 
4916 	r = amdgpu_device_fw_loading(adev);
4917 	if (r)
4918 		return r;
4919 
4920 	/* now we are okay to resume SMC/CP/SDMA */
4921 	r = amdgpu_device_ip_reinit_late_sriov(adev);
4922 	if (r)
4923 		return r;
4924 
4925 	hive = amdgpu_get_xgmi_hive(adev);
4926 	/* Update PSP FW topology after reset */
4927 	if (hive && adev->gmc.xgmi.num_physical_nodes > 1)
4928 		r = amdgpu_xgmi_update_topology(hive, adev);
4929 	if (hive)
4930 		amdgpu_put_xgmi_hive(hive);
4931 	if (r)
4932 		return r;
4933 
4934 	r = amdgpu_ib_ring_tests(adev);
4935 	if (r)
4936 		return r;
4937 
4938 	if (adev->virt.gim_feature & AMDGIM_FEATURE_GIM_FLR_VRAMLOST)
4939 		amdgpu_inc_vram_lost(adev);
4940 
4941 	/* need to be called during full access so we can't do it later like
4942 	 * bare-metal does.
4943 	 */
4944 	amdgpu_amdkfd_post_reset(adev);
4945 	amdgpu_virt_release_full_gpu(adev, true);
4946 
4947 	/* Aldebaran and gfx_11_0_3 support ras in SRIOV, so need resume ras during reset */
4948 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 2) ||
4949 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) ||
4950 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 4) ||
4951 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 5, 0) ||
4952 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 0, 3))
4953 		amdgpu_ras_resume(adev);
4954 
4955 	amdgpu_virt_ras_telemetry_post_reset(adev);
4956 
4957 	return 0;
4958 }
4959 
4960 /**
4961  * amdgpu_device_has_job_running - check if there is any unfinished job
4962  *
4963  * @adev: amdgpu_device pointer
4964  *
4965  * check if there is any job running on the device when guest driver receives
4966  * FLR notification from host driver. If there are still jobs running, then
4967  * the guest driver will not respond the FLR reset. Instead, let the job hit
4968  * the timeout and guest driver then issue the reset request.
4969  */
4970 bool amdgpu_device_has_job_running(struct amdgpu_device *adev)
4971 {
4972 	int i;
4973 
4974 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4975 		struct amdgpu_ring *ring = adev->rings[i];
4976 
4977 		if (!amdgpu_ring_sched_ready(ring))
4978 			continue;
4979 
4980 		if (amdgpu_fence_count_emitted(ring))
4981 			return true;
4982 	}
4983 	return false;
4984 }
4985 
4986 /**
4987  * amdgpu_device_should_recover_gpu - check if we should try GPU recovery
4988  *
4989  * @adev: amdgpu_device pointer
4990  *
4991  * Check amdgpu_gpu_recovery and SRIOV status to see if we should try to recover
4992  * a hung GPU.
4993  */
4994 bool amdgpu_device_should_recover_gpu(struct amdgpu_device *adev)
4995 {
4996 
4997 	if (amdgpu_gpu_recovery == 0)
4998 		goto disabled;
4999 
5000 	/* Skip soft reset check in fatal error mode */
5001 	if (!amdgpu_ras_is_poison_mode_supported(adev))
5002 		return true;
5003 
5004 	if (amdgpu_sriov_vf(adev))
5005 		return true;
5006 
5007 	if (amdgpu_gpu_recovery == -1) {
5008 		switch (adev->asic_type) {
5009 #ifdef CONFIG_DRM_AMDGPU_SI
5010 		case CHIP_VERDE:
5011 		case CHIP_TAHITI:
5012 		case CHIP_PITCAIRN:
5013 		case CHIP_OLAND:
5014 		case CHIP_HAINAN:
5015 #endif
5016 #ifdef CONFIG_DRM_AMDGPU_CIK
5017 		case CHIP_KAVERI:
5018 		case CHIP_KABINI:
5019 		case CHIP_MULLINS:
5020 #endif
5021 		case CHIP_CARRIZO:
5022 		case CHIP_STONEY:
5023 		case CHIP_CYAN_SKILLFISH:
5024 			goto disabled;
5025 		default:
5026 			break;
5027 		}
5028 	}
5029 
5030 	return true;
5031 
5032 disabled:
5033 		dev_info(adev->dev, "GPU recovery disabled.\n");
5034 		return false;
5035 }
5036 
5037 int amdgpu_device_mode1_reset(struct amdgpu_device *adev)
5038 {
5039 	u32 i;
5040 	int ret = 0;
5041 
5042 	if (adev->bios)
5043 		amdgpu_atombios_scratch_regs_engine_hung(adev, true);
5044 
5045 	dev_info(adev->dev, "GPU mode1 reset\n");
5046 
5047 	/* Cache the state before bus master disable. The saved config space
5048 	 * values are used in other cases like restore after mode-2 reset.
5049 	 */
5050 	amdgpu_device_cache_pci_state(adev->pdev);
5051 
5052 	/* disable BM */
5053 	pci_clear_master(adev->pdev);
5054 
5055 	if (amdgpu_dpm_is_mode1_reset_supported(adev)) {
5056 		dev_info(adev->dev, "GPU smu mode1 reset\n");
5057 		ret = amdgpu_dpm_mode1_reset(adev);
5058 	} else {
5059 		dev_info(adev->dev, "GPU psp mode1 reset\n");
5060 		ret = psp_gpu_reset(adev);
5061 	}
5062 
5063 	if (ret)
5064 		goto mode1_reset_failed;
5065 
5066 	/* enable mmio access after mode 1 reset completed */
5067 	adev->no_hw_access = false;
5068 
5069 	/* ensure no_hw_access is updated before we access hw */
5070 	smp_mb();
5071 
5072 	amdgpu_device_load_pci_state(adev->pdev);
5073 	ret = amdgpu_psp_wait_for_bootloader(adev);
5074 	if (ret)
5075 		goto mode1_reset_failed;
5076 
5077 	/* wait for asic to come out of reset */
5078 	for (i = 0; i < adev->usec_timeout; i++) {
5079 		u32 memsize = adev->nbio.funcs->get_memsize(adev);
5080 
5081 		if (memsize != 0xffffffff)
5082 			break;
5083 		udelay(1);
5084 	}
5085 
5086 	if (i >= adev->usec_timeout) {
5087 		ret = -ETIMEDOUT;
5088 		goto mode1_reset_failed;
5089 	}
5090 
5091 	if (adev->bios)
5092 		amdgpu_atombios_scratch_regs_engine_hung(adev, false);
5093 
5094 	return 0;
5095 
5096 mode1_reset_failed:
5097 	dev_err(adev->dev, "GPU mode1 reset failed\n");
5098 	return ret;
5099 }
5100 
5101 int amdgpu_device_link_reset(struct amdgpu_device *adev)
5102 {
5103 	int ret = 0;
5104 
5105 	dev_info(adev->dev, "GPU link reset\n");
5106 
5107 	if (!amdgpu_reset_in_dpc(adev))
5108 		ret = amdgpu_dpm_link_reset(adev);
5109 
5110 	if (ret)
5111 		goto link_reset_failed;
5112 
5113 	ret = amdgpu_psp_wait_for_bootloader(adev);
5114 	if (ret)
5115 		goto link_reset_failed;
5116 
5117 	return 0;
5118 
5119 link_reset_failed:
5120 	dev_err(adev->dev, "GPU link reset failed\n");
5121 	return ret;
5122 }
5123 
5124 int amdgpu_device_pre_asic_reset(struct amdgpu_device *adev,
5125 				 struct amdgpu_reset_context *reset_context)
5126 {
5127 	struct amdgpu_job *job = NULL;
5128 	struct dma_fence *fence = NULL;
5129 	struct amdgpu_device *tmp_adev = reset_context->reset_req_dev;
5130 	bool need_full_reset =
5131 		test_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
5132 	int i, r;
5133 
5134 	if (reset_context->reset_req_dev == adev)
5135 		job = reset_context->job;
5136 
5137 	if (amdgpu_sriov_vf(adev))
5138 		amdgpu_virt_pre_reset(adev);
5139 
5140 	amdgpu_fence_driver_isr_toggle(adev, true);
5141 
5142 	if (job)
5143 		fence = &job->hw_fence->base;
5144 
5145 	/* block all schedulers and reset given job's ring */
5146 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5147 		struct amdgpu_ring *ring = adev->rings[i];
5148 
5149 		if (!amdgpu_ring_sched_ready(ring))
5150 			continue;
5151 
5152 		/* after all hw jobs are reset, hw fence is meaningless, so force_completion */
5153 		amdgpu_fence_driver_force_completion(ring, fence);
5154 	}
5155 
5156 	amdgpu_fence_driver_isr_toggle(adev, false);
5157 
5158 	r = amdgpu_reset_prepare_hwcontext(adev, reset_context);
5159 	/* If reset handler not implemented, continue; otherwise return */
5160 	if (r == -EOPNOTSUPP)
5161 		r = 0;
5162 	else
5163 		return r;
5164 
5165 	/* Don't suspend on bare metal if we are not going to HW reset the ASIC */
5166 	if (!amdgpu_sriov_vf(adev)) {
5167 
5168 		if (!need_full_reset)
5169 			need_full_reset = amdgpu_device_ip_need_full_reset(adev);
5170 
5171 		if (!need_full_reset && amdgpu_gpu_recovery &&
5172 		    amdgpu_device_ip_check_soft_reset(adev)) {
5173 			amdgpu_device_ip_pre_soft_reset(adev);
5174 			r = amdgpu_device_ip_soft_reset(adev);
5175 			amdgpu_device_ip_post_soft_reset(adev);
5176 			if (r || amdgpu_device_ip_check_soft_reset(adev)) {
5177 				dev_info(adev->dev, "soft reset failed, will fallback to full reset!\n");
5178 				need_full_reset = true;
5179 			}
5180 		}
5181 
5182 		if (!test_bit(AMDGPU_SKIP_COREDUMP, &reset_context->flags)) {
5183 			dev_info(tmp_adev->dev, "Dumping IP State\n");
5184 			/* Trigger ip dump before we reset the asic */
5185 			for (i = 0; i < tmp_adev->num_ip_blocks; i++)
5186 				if (tmp_adev->ip_blocks[i].version->funcs->dump_ip_state)
5187 					tmp_adev->ip_blocks[i].version->funcs
5188 						->dump_ip_state((void *)&tmp_adev->ip_blocks[i]);
5189 			dev_info(tmp_adev->dev, "Dumping IP State Completed\n");
5190 		}
5191 
5192 		if (need_full_reset)
5193 			r = amdgpu_device_ip_suspend(adev);
5194 		if (need_full_reset)
5195 			set_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
5196 		else
5197 			clear_bit(AMDGPU_NEED_FULL_RESET,
5198 				  &reset_context->flags);
5199 	}
5200 
5201 	return r;
5202 }
5203 
5204 int amdgpu_device_reinit_after_reset(struct amdgpu_reset_context *reset_context)
5205 {
5206 	struct list_head *device_list_handle;
5207 	bool full_reset, vram_lost = false;
5208 	struct amdgpu_device *tmp_adev;
5209 	int r, init_level;
5210 
5211 	device_list_handle = reset_context->reset_device_list;
5212 
5213 	if (!device_list_handle)
5214 		return -EINVAL;
5215 
5216 	full_reset = test_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
5217 
5218 	/**
5219 	 * If it's reset on init, it's default init level, otherwise keep level
5220 	 * as recovery level.
5221 	 */
5222 	if (reset_context->method == AMD_RESET_METHOD_ON_INIT)
5223 			init_level = AMDGPU_INIT_LEVEL_DEFAULT;
5224 	else
5225 			init_level = AMDGPU_INIT_LEVEL_RESET_RECOVERY;
5226 
5227 	r = 0;
5228 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5229 		amdgpu_set_init_level(tmp_adev, init_level);
5230 		if (full_reset) {
5231 			/* post card */
5232 			amdgpu_reset_set_dpc_status(tmp_adev, false);
5233 			amdgpu_ras_clear_err_state(tmp_adev);
5234 			r = amdgpu_device_asic_init(tmp_adev);
5235 			if (r) {
5236 				dev_warn(tmp_adev->dev, "asic atom init failed!");
5237 			} else {
5238 				dev_info(tmp_adev->dev, "GPU reset succeeded, trying to resume\n");
5239 
5240 				r = amdgpu_device_ip_resume_phase1(tmp_adev);
5241 				if (r)
5242 					goto out;
5243 
5244 				vram_lost = amdgpu_device_check_vram_lost(tmp_adev);
5245 
5246 				if (!test_bit(AMDGPU_SKIP_COREDUMP, &reset_context->flags))
5247 					amdgpu_coredump(tmp_adev, false, vram_lost, reset_context->job);
5248 
5249 				if (vram_lost) {
5250 					dev_info(
5251 						tmp_adev->dev,
5252 						"VRAM is lost due to GPU reset!\n");
5253 					amdgpu_inc_vram_lost(tmp_adev);
5254 				}
5255 
5256 				r = amdgpu_device_fw_loading(tmp_adev);
5257 				if (r)
5258 					return r;
5259 
5260 				r = amdgpu_xcp_restore_partition_mode(
5261 					tmp_adev->xcp_mgr);
5262 				if (r)
5263 					goto out;
5264 
5265 				r = amdgpu_device_ip_resume_phase2(tmp_adev);
5266 				if (r)
5267 					goto out;
5268 
5269 				amdgpu_ttm_enable_buffer_funcs(tmp_adev);
5270 
5271 				r = amdgpu_device_ip_resume_phase3(tmp_adev);
5272 				if (r)
5273 					goto out;
5274 
5275 				if (vram_lost)
5276 					amdgpu_device_fill_reset_magic(tmp_adev);
5277 
5278 				/*
5279 				 * Add this ASIC as tracked as reset was already
5280 				 * complete successfully.
5281 				 */
5282 				amdgpu_register_gpu_instance(tmp_adev);
5283 
5284 				if (!reset_context->hive &&
5285 				    tmp_adev->gmc.xgmi.num_physical_nodes > 1)
5286 					amdgpu_xgmi_add_device(tmp_adev);
5287 
5288 				r = amdgpu_device_ip_late_init(tmp_adev);
5289 				if (r)
5290 					goto out;
5291 
5292 				r = amdgpu_userq_post_reset(tmp_adev, vram_lost);
5293 				if (r)
5294 					goto out;
5295 
5296 				drm_client_dev_resume(adev_to_drm(tmp_adev));
5297 
5298 				/*
5299 				 * The GPU enters bad state once faulty pages
5300 				 * by ECC has reached the threshold, and ras
5301 				 * recovery is scheduled next. So add one check
5302 				 * here to break recovery if it indeed exceeds
5303 				 * bad page threshold, and remind user to
5304 				 * retire this GPU or setting one bigger
5305 				 * bad_page_threshold value to fix this once
5306 				 * probing driver again.
5307 				 */
5308 				if (!amdgpu_ras_is_rma(tmp_adev)) {
5309 					/* must succeed. */
5310 					amdgpu_ras_resume(tmp_adev);
5311 				} else {
5312 					r = -EINVAL;
5313 					goto out;
5314 				}
5315 
5316 				/* Update PSP FW topology after reset */
5317 				if (reset_context->hive &&
5318 				    tmp_adev->gmc.xgmi.num_physical_nodes > 1)
5319 					r = amdgpu_xgmi_update_topology(
5320 						reset_context->hive, tmp_adev);
5321 			}
5322 		}
5323 
5324 out:
5325 		if (!r) {
5326 			/* IP init is complete now, set level as default */
5327 			amdgpu_set_init_level(tmp_adev,
5328 					      AMDGPU_INIT_LEVEL_DEFAULT);
5329 			amdgpu_irq_gpu_reset_resume_helper(tmp_adev);
5330 			r = amdgpu_ib_ring_tests(tmp_adev);
5331 			if (r) {
5332 				dev_err(tmp_adev->dev, "ib ring test failed (%d).\n", r);
5333 				r = -EAGAIN;
5334 				goto end;
5335 			}
5336 		}
5337 
5338 		if (r)
5339 			tmp_adev->asic_reset_res = r;
5340 	}
5341 
5342 end:
5343 	return r;
5344 }
5345 
5346 int amdgpu_do_asic_reset(struct list_head *device_list_handle,
5347 			 struct amdgpu_reset_context *reset_context)
5348 {
5349 	struct amdgpu_device *tmp_adev = NULL;
5350 	bool need_full_reset, skip_hw_reset;
5351 	int r = 0;
5352 
5353 	/* Try reset handler method first */
5354 	tmp_adev = list_first_entry(device_list_handle, struct amdgpu_device,
5355 				    reset_list);
5356 
5357 	reset_context->reset_device_list = device_list_handle;
5358 	r = amdgpu_reset_perform_reset(tmp_adev, reset_context);
5359 	/* If reset handler not implemented, continue; otherwise return */
5360 	if (r == -EOPNOTSUPP)
5361 		r = 0;
5362 	else
5363 		return r;
5364 
5365 	/* Reset handler not implemented, use the default method */
5366 	need_full_reset =
5367 		test_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
5368 	skip_hw_reset = test_bit(AMDGPU_SKIP_HW_RESET, &reset_context->flags);
5369 
5370 	/*
5371 	 * ASIC reset has to be done on all XGMI hive nodes ASAP
5372 	 * to allow proper links negotiation in FW (within 1 sec)
5373 	 */
5374 	if (!skip_hw_reset && need_full_reset) {
5375 		list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5376 			/* For XGMI run all resets in parallel to speed up the process */
5377 			if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
5378 				if (!queue_work(system_dfl_wq,
5379 						&tmp_adev->xgmi_reset_work))
5380 					r = -EALREADY;
5381 			} else
5382 				r = amdgpu_asic_reset(tmp_adev);
5383 
5384 			if (r) {
5385 				dev_err(tmp_adev->dev,
5386 					"ASIC reset failed with error, %d for drm dev, %s",
5387 					r, adev_to_drm(tmp_adev)->unique);
5388 				goto out;
5389 			}
5390 		}
5391 
5392 		/* For XGMI wait for all resets to complete before proceed */
5393 		if (!r) {
5394 			list_for_each_entry(tmp_adev, device_list_handle,
5395 					    reset_list) {
5396 				if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
5397 					flush_work(&tmp_adev->xgmi_reset_work);
5398 					r = tmp_adev->asic_reset_res;
5399 					if (r)
5400 						break;
5401 				}
5402 			}
5403 		}
5404 	}
5405 
5406 	if (!r && amdgpu_ras_intr_triggered()) {
5407 		list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5408 			amdgpu_ras_reset_error_count(tmp_adev,
5409 						     AMDGPU_RAS_BLOCK__MMHUB);
5410 		}
5411 
5412 		amdgpu_ras_intr_cleared();
5413 	}
5414 
5415 	r = amdgpu_device_reinit_after_reset(reset_context);
5416 	if (r == -EAGAIN)
5417 		set_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
5418 	else
5419 		clear_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
5420 
5421 out:
5422 	return r;
5423 }
5424 
5425 static void amdgpu_device_set_mp1_state(struct amdgpu_device *adev)
5426 {
5427 
5428 	switch (amdgpu_asic_reset_method(adev)) {
5429 	case AMD_RESET_METHOD_MODE1:
5430 	case AMD_RESET_METHOD_LINK:
5431 		adev->mp1_state = PP_MP1_STATE_SHUTDOWN;
5432 		break;
5433 	case AMD_RESET_METHOD_MODE2:
5434 		adev->mp1_state = PP_MP1_STATE_RESET;
5435 		break;
5436 	default:
5437 		adev->mp1_state = PP_MP1_STATE_NONE;
5438 		break;
5439 	}
5440 }
5441 
5442 static void amdgpu_device_unset_mp1_state(struct amdgpu_device *adev)
5443 {
5444 	amdgpu_vf_error_trans_all(adev);
5445 	adev->mp1_state = PP_MP1_STATE_NONE;
5446 }
5447 
5448 static void amdgpu_device_resume_display_audio(struct amdgpu_device *adev)
5449 {
5450 	struct pci_dev *p = NULL;
5451 
5452 	p = pci_get_domain_bus_and_slot(pci_domain_nr(adev->pdev->bus),
5453 			adev->pdev->bus->number, 1);
5454 	if (p) {
5455 		pm_runtime_enable(&(p->dev));
5456 		pm_runtime_resume(&(p->dev));
5457 	}
5458 
5459 	pci_dev_put(p);
5460 }
5461 
5462 static int amdgpu_device_suspend_display_audio(struct amdgpu_device *adev)
5463 {
5464 	enum amd_reset_method reset_method;
5465 	struct pci_dev *p = NULL;
5466 	u64 expires;
5467 
5468 	/*
5469 	 * For now, only BACO and mode1 reset are confirmed
5470 	 * to suffer the audio issue without proper suspended.
5471 	 */
5472 	reset_method = amdgpu_asic_reset_method(adev);
5473 	if ((reset_method != AMD_RESET_METHOD_BACO) &&
5474 	     (reset_method != AMD_RESET_METHOD_MODE1))
5475 		return -EINVAL;
5476 
5477 	p = pci_get_domain_bus_and_slot(pci_domain_nr(adev->pdev->bus),
5478 			adev->pdev->bus->number, 1);
5479 	if (!p)
5480 		return -ENODEV;
5481 
5482 	expires = pm_runtime_autosuspend_expiration(&(p->dev));
5483 	if (!expires)
5484 		/*
5485 		 * If we cannot get the audio device autosuspend delay,
5486 		 * a fixed 4S interval will be used. Considering 3S is
5487 		 * the audio controller default autosuspend delay setting.
5488 		 * 4S used here is guaranteed to cover that.
5489 		 */
5490 		expires = ktime_get_mono_fast_ns() + NSEC_PER_SEC * 4ULL;
5491 
5492 	while (!pm_runtime_status_suspended(&(p->dev))) {
5493 		if (!pm_runtime_suspend(&(p->dev)))
5494 			break;
5495 
5496 		if (expires < ktime_get_mono_fast_ns()) {
5497 			dev_warn(adev->dev, "failed to suspend display audio\n");
5498 			pci_dev_put(p);
5499 			/* TODO: abort the succeeding gpu reset? */
5500 			return -ETIMEDOUT;
5501 		}
5502 	}
5503 
5504 	pm_runtime_disable(&(p->dev));
5505 
5506 	pci_dev_put(p);
5507 	return 0;
5508 }
5509 
5510 static inline void amdgpu_device_stop_pending_resets(struct amdgpu_device *adev)
5511 {
5512 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
5513 
5514 #if defined(CONFIG_DEBUG_FS)
5515 	if (!amdgpu_sriov_vf(adev))
5516 		cancel_work(&adev->reset_work);
5517 #endif
5518 	amdgpu_userq_mgr_cancel_reset_work(adev);
5519 
5520 	if (adev->kfd.dev)
5521 		cancel_work(&adev->kfd.reset_work);
5522 
5523 	if (amdgpu_sriov_vf(adev))
5524 		cancel_work(&adev->virt.flr_work);
5525 
5526 	if (con && adev->ras_enabled)
5527 		cancel_work(&con->recovery_work);
5528 
5529 }
5530 
5531 static int amdgpu_device_health_check(struct list_head *device_list_handle)
5532 {
5533 	struct amdgpu_device *tmp_adev;
5534 	int ret = 0;
5535 
5536 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5537 		ret |= amdgpu_device_bus_status_check(tmp_adev);
5538 	}
5539 
5540 	return ret;
5541 }
5542 
5543 static void amdgpu_device_recovery_prepare(struct amdgpu_device *adev,
5544 					  struct list_head *device_list,
5545 					  struct amdgpu_hive_info *hive)
5546 {
5547 	struct amdgpu_device *tmp_adev = NULL;
5548 
5549 	/*
5550 	 * Build list of devices to reset.
5551 	 * In case we are in XGMI hive mode, resort the device list
5552 	 * to put adev in the 1st position.
5553 	 */
5554 	if (!amdgpu_sriov_vf(adev) && (adev->gmc.xgmi.num_physical_nodes > 1) && hive) {
5555 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head) {
5556 			list_add_tail(&tmp_adev->reset_list, device_list);
5557 			if (adev->shutdown)
5558 				tmp_adev->shutdown = true;
5559 		}
5560 		if (!list_is_first(&adev->reset_list, device_list))
5561 			list_rotate_to_front(&adev->reset_list, device_list);
5562 	} else {
5563 		list_add_tail(&adev->reset_list, device_list);
5564 	}
5565 }
5566 
5567 static void amdgpu_device_recovery_get_reset_lock(struct amdgpu_device *adev,
5568 						  struct list_head *device_list)
5569 {
5570 	struct amdgpu_device *tmp_adev = NULL;
5571 
5572 	if (list_empty(device_list))
5573 		return;
5574 	tmp_adev =
5575 		list_first_entry(device_list, struct amdgpu_device, reset_list);
5576 	amdgpu_device_lock_reset_domain(tmp_adev->reset_domain);
5577 }
5578 
5579 static void amdgpu_device_recovery_put_reset_lock(struct amdgpu_device *adev,
5580 						  struct list_head *device_list)
5581 {
5582 	struct amdgpu_device *tmp_adev = NULL;
5583 
5584 	if (list_empty(device_list))
5585 		return;
5586 	tmp_adev =
5587 		list_first_entry(device_list, struct amdgpu_device, reset_list);
5588 	amdgpu_device_unlock_reset_domain(tmp_adev->reset_domain);
5589 }
5590 
5591 static void amdgpu_device_halt_activities(struct amdgpu_device *adev,
5592 					  struct amdgpu_job *job,
5593 					  struct amdgpu_reset_context *reset_context,
5594 					  struct list_head *device_list,
5595 					  struct amdgpu_hive_info *hive,
5596 					  bool need_emergency_restart)
5597 {
5598 	struct amdgpu_device *tmp_adev = NULL;
5599 	int i;
5600 
5601 	/* block all schedulers and reset given job's ring */
5602 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5603 		amdgpu_device_set_mp1_state(tmp_adev);
5604 
5605 		/*
5606 		 * Try to put the audio codec into suspend state
5607 		 * before gpu reset started.
5608 		 *
5609 		 * Due to the power domain of the graphics device
5610 		 * is shared with AZ power domain. Without this,
5611 		 * we may change the audio hardware from behind
5612 		 * the audio driver's back. That will trigger
5613 		 * some audio codec errors.
5614 		 */
5615 		if (!amdgpu_device_suspend_display_audio(tmp_adev))
5616 			tmp_adev->pcie_reset_ctx.audio_suspended = true;
5617 
5618 		amdgpu_ras_set_error_query_ready(tmp_adev, false);
5619 
5620 		cancel_delayed_work_sync(&tmp_adev->delayed_init_work);
5621 
5622 		amdgpu_amdkfd_pre_reset(tmp_adev, reset_context);
5623 
5624 		/*
5625 		 * Mark these ASICs to be reset as untracked first
5626 		 * And add them back after reset completed
5627 		 */
5628 		amdgpu_unregister_gpu_instance(tmp_adev);
5629 
5630 		drm_client_dev_suspend(adev_to_drm(tmp_adev));
5631 
5632 		/* disable ras on ALL IPs */
5633 		if (!need_emergency_restart && !amdgpu_reset_in_dpc(adev) &&
5634 		    amdgpu_device_ip_need_full_reset(tmp_adev))
5635 			amdgpu_ras_suspend(tmp_adev);
5636 
5637 		amdgpu_userq_pre_reset(tmp_adev);
5638 
5639 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5640 			struct amdgpu_ring *ring = tmp_adev->rings[i];
5641 
5642 			if (!amdgpu_ring_sched_ready(ring))
5643 				continue;
5644 
5645 			drm_sched_wqueue_stop(&ring->sched);
5646 
5647 			if (need_emergency_restart)
5648 				amdgpu_job_stop_all_jobs_on_sched(&ring->sched);
5649 		}
5650 		atomic_inc(&tmp_adev->gpu_reset_counter);
5651 	}
5652 }
5653 
5654 static int amdgpu_device_asic_reset(struct amdgpu_device *adev,
5655 			      struct list_head *device_list,
5656 			      struct amdgpu_reset_context *reset_context)
5657 {
5658 	struct amdgpu_device *tmp_adev = NULL;
5659 	int retry_limit = AMDGPU_MAX_RETRY_LIMIT;
5660 	int r = 0;
5661 
5662 retry:	/* Rest of adevs pre asic reset from XGMI hive. */
5663 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5664 		r = amdgpu_device_pre_asic_reset(tmp_adev, reset_context);
5665 		/*TODO Should we stop ?*/
5666 		if (r) {
5667 			dev_err(tmp_adev->dev, "GPU pre asic reset failed with err, %d for drm dev, %s ",
5668 				  r, adev_to_drm(tmp_adev)->unique);
5669 			tmp_adev->asic_reset_res = r;
5670 		}
5671 	}
5672 
5673 	/* Actual ASIC resets if needed.*/
5674 	/* Host driver will handle XGMI hive reset for SRIOV */
5675 	if (amdgpu_sriov_vf(adev)) {
5676 
5677 		/* Bail out of reset early */
5678 		if (amdgpu_ras_is_rma(adev))
5679 			return -ENODEV;
5680 
5681 		if (amdgpu_ras_get_fed_status(adev) || amdgpu_virt_rcvd_ras_interrupt(adev)) {
5682 			dev_dbg(adev->dev, "Detected RAS error, wait for FLR completion\n");
5683 			amdgpu_ras_set_fed(adev, true);
5684 			set_bit(AMDGPU_HOST_FLR, &reset_context->flags);
5685 		}
5686 
5687 		r = amdgpu_device_reset_sriov(adev, reset_context);
5688 		if (AMDGPU_RETRY_SRIOV_RESET(r) && (retry_limit--) > 0) {
5689 			amdgpu_virt_release_full_gpu(adev, true);
5690 			goto retry;
5691 		}
5692 		if (r)
5693 			adev->asic_reset_res = r;
5694 	} else {
5695 		r = amdgpu_do_asic_reset(device_list, reset_context);
5696 		if (r && r == -EAGAIN)
5697 			goto retry;
5698 	}
5699 
5700 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5701 		/*
5702 		 * Drop any pending non scheduler resets queued before reset is done.
5703 		 * Any reset scheduled after this point would be valid. Scheduler resets
5704 		 * were already dropped during drm_sched_stop and no new ones can come
5705 		 * in before drm_sched_start.
5706 		 */
5707 		amdgpu_device_stop_pending_resets(tmp_adev);
5708 	}
5709 
5710 	return r;
5711 }
5712 
5713 static int amdgpu_device_sched_resume(struct list_head *device_list,
5714 			      struct amdgpu_reset_context *reset_context,
5715 			      bool   job_signaled)
5716 {
5717 	struct amdgpu_device *tmp_adev = NULL;
5718 	int i, r = 0;
5719 
5720 	/* Post ASIC reset for all devs .*/
5721 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5722 
5723 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5724 			struct amdgpu_ring *ring = tmp_adev->rings[i];
5725 
5726 			if (!amdgpu_ring_sched_ready(ring))
5727 				continue;
5728 
5729 			drm_sched_wqueue_start(&ring->sched);
5730 		}
5731 
5732 		if (!drm_drv_uses_atomic_modeset(adev_to_drm(tmp_adev)) && !job_signaled)
5733 			drm_helper_resume_force_mode(adev_to_drm(tmp_adev));
5734 
5735 		if (tmp_adev->asic_reset_res) {
5736 			/* bad news, how to tell it to userspace ?
5737 			 * for ras error, we should report GPU bad status instead of
5738 			 * reset failure
5739 			 */
5740 			if (reset_context->src != AMDGPU_RESET_SRC_RAS ||
5741 			    !amdgpu_ras_eeprom_check_err_threshold(tmp_adev))
5742 				dev_info(
5743 					tmp_adev->dev,
5744 					"GPU reset(%d) failed with error %d\n",
5745 					atomic_read(
5746 						&tmp_adev->gpu_reset_counter),
5747 					tmp_adev->asic_reset_res);
5748 			amdgpu_vf_error_put(tmp_adev,
5749 					    AMDGIM_ERROR_VF_GPU_RESET_FAIL, 0,
5750 					    tmp_adev->asic_reset_res);
5751 			if (!r)
5752 				r = tmp_adev->asic_reset_res;
5753 			tmp_adev->asic_reset_res = 0;
5754 		} else {
5755 			dev_info(tmp_adev->dev, "GPU reset(%d) succeeded!\n",
5756 				 atomic_read(&tmp_adev->gpu_reset_counter));
5757 			if (amdgpu_acpi_smart_shift_update(tmp_adev,
5758 							   AMDGPU_SS_DEV_D0))
5759 				dev_warn(tmp_adev->dev,
5760 					 "smart shift update failed\n");
5761 		}
5762 	}
5763 
5764 	return r;
5765 }
5766 
5767 static void amdgpu_device_gpu_resume(struct amdgpu_device *adev,
5768 			      struct list_head *device_list,
5769 			      bool   need_emergency_restart)
5770 {
5771 	struct amdgpu_device *tmp_adev = NULL;
5772 
5773 	list_for_each_entry(tmp_adev, device_list, reset_list) {
5774 		/* unlock kfd: SRIOV would do it separately */
5775 		if (!need_emergency_restart && !amdgpu_sriov_vf(tmp_adev))
5776 			amdgpu_amdkfd_post_reset(tmp_adev);
5777 
5778 		/* kfd_post_reset will do nothing if kfd device is not initialized,
5779 		 * need to bring up kfd here if it's not be initialized before
5780 		 */
5781 		if (!adev->kfd.init_complete)
5782 			amdgpu_amdkfd_device_init(adev);
5783 
5784 		if (tmp_adev->pcie_reset_ctx.audio_suspended)
5785 			amdgpu_device_resume_display_audio(tmp_adev);
5786 
5787 		amdgpu_device_unset_mp1_state(tmp_adev);
5788 
5789 		amdgpu_ras_set_error_query_ready(tmp_adev, true);
5790 
5791 	}
5792 }
5793 
5794 
5795 /**
5796  * amdgpu_device_gpu_recover - reset the asic and recover scheduler
5797  *
5798  * @adev: amdgpu_device pointer
5799  * @job: which job trigger hang
5800  * @reset_context: amdgpu reset context pointer
5801  *
5802  * Attempt to reset the GPU if it has hung (all asics).
5803  * Attempt to do soft-reset or full-reset and reinitialize Asic
5804  * Returns 0 for success or an error on failure.
5805  */
5806 
5807 int amdgpu_device_gpu_recover(struct amdgpu_device *adev,
5808 			      struct amdgpu_job *job,
5809 			      struct amdgpu_reset_context *reset_context)
5810 {
5811 	struct list_head device_list;
5812 	bool job_signaled = false;
5813 	struct amdgpu_hive_info *hive = NULL;
5814 	int r = 0;
5815 	bool need_emergency_restart = false;
5816 	/* save the pasid here as the job may be freed before the end of the reset */
5817 	int pasid = job ? job->pasid : -EINVAL;
5818 
5819 	/*
5820 	 * If it reaches here because of hang/timeout and a RAS error is
5821 	 * detected at the same time, let RAS recovery take care of it.
5822 	 */
5823 	if (amdgpu_ras_is_err_state(adev, AMDGPU_RAS_BLOCK__ANY) &&
5824 	    !amdgpu_sriov_vf(adev) &&
5825 	    reset_context->src != AMDGPU_RESET_SRC_RAS) {
5826 		dev_dbg(adev->dev,
5827 			"Gpu recovery from source: %d yielding to RAS error recovery handling",
5828 			reset_context->src);
5829 		return 0;
5830 	}
5831 
5832 	/*
5833 	 * Special case: RAS triggered and full reset isn't supported
5834 	 */
5835 	need_emergency_restart = amdgpu_ras_need_emergency_restart(adev);
5836 
5837 	/*
5838 	 * Flush RAM to disk so that after reboot
5839 	 * the user can read log and see why the system rebooted.
5840 	 */
5841 	if (need_emergency_restart && amdgpu_ras_get_context(adev) &&
5842 		amdgpu_ras_get_context(adev)->reboot) {
5843 		dev_warn(adev->dev, "Emergency reboot.");
5844 
5845 		ksys_sync_helper();
5846 		emergency_restart();
5847 	}
5848 
5849 	dev_info(adev->dev, "GPU %s begin!. Source:  %d\n",
5850 		 need_emergency_restart ? "jobs stop" : "reset",
5851 		 reset_context->src);
5852 
5853 	if (!amdgpu_sriov_vf(adev))
5854 		hive = amdgpu_get_xgmi_hive(adev);
5855 	if (hive)
5856 		mutex_lock(&hive->hive_lock);
5857 
5858 	reset_context->job = job;
5859 	reset_context->hive = hive;
5860 	INIT_LIST_HEAD(&device_list);
5861 
5862 	amdgpu_device_recovery_prepare(adev, &device_list, hive);
5863 
5864 	if (!amdgpu_sriov_vf(adev)) {
5865 		r = amdgpu_device_health_check(&device_list);
5866 		if (r)
5867 			goto end_reset;
5868 	}
5869 
5870 	/* Cannot be called after locking reset domain */
5871 	amdgpu_ras_pre_reset(adev, &device_list);
5872 
5873 	/* We need to lock reset domain only once both for XGMI and single device */
5874 	amdgpu_device_recovery_get_reset_lock(adev, &device_list);
5875 
5876 	/* unmap all the mappings of doorbell and framebuffer to prevent user space from
5877 	 * accessing them
5878 	 */
5879 	unmap_mapping_range(adev->ddev.anon_inode->i_mapping, 0, 0, 1);
5880 	amdgpu_amdkfd_clear_kfd_mapping(adev);
5881 
5882 	amdgpu_device_halt_activities(adev, job, reset_context, &device_list,
5883 				      hive, need_emergency_restart);
5884 	if (need_emergency_restart)
5885 		goto skip_sched_resume;
5886 	/*
5887 	 * Must check guilty signal here since after this point all old
5888 	 * HW fences are force signaled.
5889 	 *
5890 	 * job->base holds a reference to parent fence
5891 	 */
5892 	if (job && (dma_fence_get_status(&job->hw_fence->base) > 0)) {
5893 		job_signaled = true;
5894 		dev_info(adev->dev, "Guilty job already signaled, skipping HW reset");
5895 		goto skip_hw_reset;
5896 	}
5897 
5898 	r = amdgpu_device_asic_reset(adev, &device_list, reset_context);
5899 	if (r)
5900 		goto reset_unlock;
5901 skip_hw_reset:
5902 	r = amdgpu_device_sched_resume(&device_list, reset_context, job_signaled);
5903 	if (r)
5904 		goto reset_unlock;
5905 skip_sched_resume:
5906 	amdgpu_device_gpu_resume(adev, &device_list, need_emergency_restart);
5907 reset_unlock:
5908 	amdgpu_device_recovery_put_reset_lock(adev, &device_list);
5909 	amdgpu_ras_post_reset(adev, &device_list);
5910 end_reset:
5911 	if (hive) {
5912 		mutex_unlock(&hive->hive_lock);
5913 		amdgpu_put_xgmi_hive(hive);
5914 	}
5915 
5916 	if (r)
5917 		dev_info(adev->dev, "GPU reset end with ret = %d\n", r);
5918 
5919 	atomic_set(&adev->reset_domain->reset_res, r);
5920 
5921 	if (!r) {
5922 		struct amdgpu_task_info *ti = NULL;
5923 
5924 		/*
5925 		 * The job may already be freed at this point via the sched tdr workqueue so
5926 		 * use the cached pasid.
5927 		 */
5928 		if (pasid >= 0)
5929 			ti = amdgpu_vm_get_task_info_pasid(adev, pasid);
5930 
5931 		drm_dev_wedged_event(adev_to_drm(adev), DRM_WEDGE_RECOVERY_NONE,
5932 				     ti ? &ti->task : NULL);
5933 
5934 		amdgpu_vm_put_task_info(ti);
5935 	}
5936 
5937 	return r;
5938 }
5939 
5940 /**
5941  * amdgpu_device_partner_bandwidth - find the bandwidth of appropriate partner
5942  *
5943  * @adev: amdgpu_device pointer
5944  * @speed: pointer to the speed of the link
5945  * @width: pointer to the width of the link
5946  *
5947  * Evaluate the hierarchy to find the speed and bandwidth capabilities of the
5948  * first physical partner to an AMD dGPU.
5949  * This will exclude any virtual switches and links.
5950  */
5951 static void amdgpu_device_partner_bandwidth(struct amdgpu_device *adev,
5952 					    enum pci_bus_speed *speed,
5953 					    enum pcie_link_width *width)
5954 {
5955 	if (!speed || !width)
5956 		return;
5957 
5958 	*speed = PCI_SPEED_UNKNOWN;
5959 	*width = PCIE_LNK_WIDTH_UNKNOWN;
5960 
5961 	if (amdgpu_device_pcie_dynamic_switching_supported(adev)) {
5962 		struct pci_dev *parent = amdgpu_device_find_parent(adev);
5963 
5964 		if (parent) {
5965 			*speed = pcie_get_speed_cap(parent);
5966 			*width = pcie_get_width_cap(parent);
5967 		}
5968 	} else {
5969 		/* use the current speeds rather than max if switching is not supported */
5970 		pcie_bandwidth_available(adev->pdev, NULL, speed, width);
5971 	}
5972 }
5973 
5974 /**
5975  * amdgpu_device_gpu_bandwidth - find the bandwidth of the GPU
5976  *
5977  * @adev: amdgpu_device pointer
5978  * @speed: pointer to the speed of the link
5979  * @width: pointer to the width of the link
5980  *
5981  * Evaluate the hierarchy to find the speed and bandwidth capabilities of the
5982  * AMD dGPU which may be a virtual upstream bridge.
5983  */
5984 static void amdgpu_device_gpu_bandwidth(struct amdgpu_device *adev,
5985 					enum pci_bus_speed *speed,
5986 					enum pcie_link_width *width)
5987 {
5988 	struct pci_dev *parent = adev->pdev;
5989 
5990 	if (!speed || !width)
5991 		return;
5992 
5993 	/* use the device itself */
5994 	*speed = pcie_get_speed_cap(adev->pdev);
5995 	*width = pcie_get_width_cap(adev->pdev);
5996 
5997 	/* use the link outside the device */
5998 	parent = amdgpu_device_find_parent(adev);
5999 	if (parent) {
6000 		*speed = pcie_get_speed_cap(parent);
6001 		*width = pcie_get_width_cap(parent);
6002 	}
6003 }
6004 
6005 /**
6006  * amdgpu_device_get_pcie_info - fence pcie info about the PCIE slot
6007  *
6008  * @adev: amdgpu_device pointer
6009  *
6010  * Fetches and stores in the driver the PCIE capabilities (gen speed
6011  * and lanes) of the slot the device is in. Handles APUs and
6012  * virtualized environments where PCIE config space may not be available.
6013  */
6014 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev)
6015 {
6016 	enum pci_bus_speed speed_cap, platform_speed_cap;
6017 	enum pcie_link_width platform_link_width, link_width;
6018 
6019 	if (amdgpu_pcie_gen_cap)
6020 		adev->pm.pcie_gen_mask = amdgpu_pcie_gen_cap;
6021 
6022 	if (amdgpu_pcie_lane_cap)
6023 		adev->pm.pcie_mlw_mask = amdgpu_pcie_lane_cap;
6024 
6025 	/* covers APUs as well */
6026 	if (pci_is_root_bus(adev->pdev->bus) && !amdgpu_passthrough(adev)) {
6027 		if (adev->pm.pcie_gen_mask == 0)
6028 			adev->pm.pcie_gen_mask = AMDGPU_DEFAULT_PCIE_GEN_MASK;
6029 		if (adev->pm.pcie_mlw_mask == 0)
6030 			adev->pm.pcie_mlw_mask = AMDGPU_DEFAULT_PCIE_MLW_MASK;
6031 		return;
6032 	}
6033 
6034 	if (adev->pm.pcie_gen_mask && adev->pm.pcie_mlw_mask)
6035 		return;
6036 
6037 	amdgpu_device_partner_bandwidth(adev, &platform_speed_cap,
6038 					&platform_link_width);
6039 	amdgpu_device_gpu_bandwidth(adev, &speed_cap, &link_width);
6040 
6041 	if (adev->pm.pcie_gen_mask == 0) {
6042 		/* asic caps */
6043 		if (speed_cap == PCI_SPEED_UNKNOWN) {
6044 			adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6045 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6046 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
6047 		} else {
6048 			if (speed_cap == PCIE_SPEED_32_0GT)
6049 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6050 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6051 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3 |
6052 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN4 |
6053 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN5);
6054 			else if (speed_cap == PCIE_SPEED_16_0GT)
6055 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6056 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6057 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3 |
6058 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN4);
6059 			else if (speed_cap == PCIE_SPEED_8_0GT)
6060 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6061 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6062 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
6063 			else if (speed_cap == PCIE_SPEED_5_0GT)
6064 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6065 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2);
6066 			else
6067 				adev->pm.pcie_gen_mask |= CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1;
6068 		}
6069 		/* platform caps */
6070 		if (platform_speed_cap == PCI_SPEED_UNKNOWN) {
6071 			adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6072 						   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
6073 		} else {
6074 			if (platform_speed_cap == PCIE_SPEED_32_0GT)
6075 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6076 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6077 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3 |
6078 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN4 |
6079 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN5);
6080 			else if (platform_speed_cap == PCIE_SPEED_16_0GT)
6081 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6082 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6083 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3 |
6084 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN4);
6085 			else if (platform_speed_cap == PCIE_SPEED_8_0GT)
6086 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6087 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
6088 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3);
6089 			else if (platform_speed_cap == PCIE_SPEED_5_0GT)
6090 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
6091 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
6092 			else
6093 				adev->pm.pcie_gen_mask |= CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1;
6094 
6095 		}
6096 	}
6097 	if (adev->pm.pcie_mlw_mask == 0) {
6098 		/* asic caps */
6099 		if (link_width == PCIE_LNK_WIDTH_UNKNOWN) {
6100 			adev->pm.pcie_mlw_mask |= AMDGPU_DEFAULT_ASIC_PCIE_MLW_MASK;
6101 		} else {
6102 			switch (link_width) {
6103 			case PCIE_LNK_X32:
6104 				adev->pm.pcie_mlw_mask |= (CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X32 |
6105 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X16 |
6106 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X12 |
6107 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X8 |
6108 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X4 |
6109 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X2 |
6110 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1);
6111 				break;
6112 			case PCIE_LNK_X16:
6113 				adev->pm.pcie_mlw_mask |= (CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X16 |
6114 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X12 |
6115 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X8 |
6116 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X4 |
6117 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X2 |
6118 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1);
6119 				break;
6120 			case PCIE_LNK_X12:
6121 				adev->pm.pcie_mlw_mask |= (CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X12 |
6122 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X8 |
6123 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X4 |
6124 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X2 |
6125 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1);
6126 				break;
6127 			case PCIE_LNK_X8:
6128 				adev->pm.pcie_mlw_mask |= (CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X8 |
6129 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X4 |
6130 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X2 |
6131 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1);
6132 				break;
6133 			case PCIE_LNK_X4:
6134 				adev->pm.pcie_mlw_mask |= (CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X4 |
6135 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X2 |
6136 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1);
6137 				break;
6138 			case PCIE_LNK_X2:
6139 				adev->pm.pcie_mlw_mask |= (CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X2 |
6140 							   CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1);
6141 				break;
6142 			case PCIE_LNK_X1:
6143 				adev->pm.pcie_mlw_mask |= CAIL_ASIC_PCIE_LINK_WIDTH_SUPPORT_X1;
6144 				break;
6145 			default:
6146 				break;
6147 			}
6148 		}
6149 		/* platform caps */
6150 		if (platform_link_width == PCIE_LNK_WIDTH_UNKNOWN) {
6151 			adev->pm.pcie_mlw_mask |= AMDGPU_DEFAULT_PCIE_MLW_MASK;
6152 		} else {
6153 			switch (platform_link_width) {
6154 			case PCIE_LNK_X32:
6155 				adev->pm.pcie_mlw_mask |= (CAIL_PCIE_LINK_WIDTH_SUPPORT_X32 |
6156 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
6157 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
6158 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
6159 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
6160 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
6161 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
6162 				break;
6163 			case PCIE_LNK_X16:
6164 				adev->pm.pcie_mlw_mask |= (CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
6165 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
6166 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
6167 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
6168 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
6169 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
6170 				break;
6171 			case PCIE_LNK_X12:
6172 				adev->pm.pcie_mlw_mask |= (CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
6173 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
6174 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
6175 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
6176 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
6177 				break;
6178 			case PCIE_LNK_X8:
6179 				adev->pm.pcie_mlw_mask |= (CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
6180 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
6181 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
6182 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
6183 				break;
6184 			case PCIE_LNK_X4:
6185 				adev->pm.pcie_mlw_mask |= (CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
6186 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
6187 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
6188 				break;
6189 			case PCIE_LNK_X2:
6190 				adev->pm.pcie_mlw_mask |= (CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
6191 							   CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
6192 				break;
6193 			case PCIE_LNK_X1:
6194 				adev->pm.pcie_mlw_mask |= CAIL_PCIE_LINK_WIDTH_SUPPORT_X1;
6195 				break;
6196 			default:
6197 				break;
6198 			}
6199 		}
6200 	}
6201 }
6202 
6203 /**
6204  * amdgpu_device_is_peer_accessible - Check peer access through PCIe BAR
6205  *
6206  * @adev: amdgpu_device pointer
6207  * @peer_adev: amdgpu_device pointer for peer device trying to access @adev
6208  *
6209  * Return true if @peer_adev can access (DMA) @adev through the PCIe
6210  * BAR, i.e. @adev is "large BAR" and the BAR matches the DMA mask of
6211  * @peer_adev.
6212  */
6213 bool amdgpu_device_is_peer_accessible(struct amdgpu_device *adev,
6214 				      struct amdgpu_device *peer_adev)
6215 {
6216 #ifdef CONFIG_HSA_AMD_P2P
6217 	bool p2p_access =
6218 		!adev->gmc.xgmi.connected_to_cpu &&
6219 		!(pci_p2pdma_distance(adev->pdev, peer_adev->dev, false) < 0);
6220 	if (!p2p_access)
6221 		dev_info(adev->dev, "PCIe P2P access from peer device %s is not supported by the chipset\n",
6222 			pci_name(peer_adev->pdev));
6223 
6224 	bool is_large_bar = adev->gmc.visible_vram_size &&
6225 		adev->gmc.real_vram_size == adev->gmc.visible_vram_size;
6226 	bool p2p_addressable = amdgpu_device_check_iommu_remap(peer_adev);
6227 
6228 	if (!p2p_addressable) {
6229 		uint64_t address_mask = peer_adev->dev->dma_mask ?
6230 			~*peer_adev->dev->dma_mask : ~((1ULL << 32) - 1);
6231 		resource_size_t aper_limit =
6232 			adev->gmc.aper_base + adev->gmc.aper_size - 1;
6233 
6234 		p2p_addressable = !(adev->gmc.aper_base & address_mask ||
6235 				     aper_limit & address_mask);
6236 	}
6237 	return pcie_p2p && is_large_bar && p2p_access && p2p_addressable;
6238 #else
6239 	return false;
6240 #endif
6241 }
6242 
6243 int amdgpu_device_baco_enter(struct amdgpu_device *adev)
6244 {
6245 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
6246 
6247 	if (!amdgpu_device_supports_baco(adev))
6248 		return -ENOTSUPP;
6249 
6250 	if (ras && adev->ras_enabled &&
6251 	    adev->nbio.funcs->enable_doorbell_interrupt)
6252 		adev->nbio.funcs->enable_doorbell_interrupt(adev, false);
6253 
6254 	return amdgpu_dpm_baco_enter(adev);
6255 }
6256 
6257 int amdgpu_device_baco_exit(struct amdgpu_device *adev)
6258 {
6259 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
6260 	int ret = 0;
6261 
6262 	if (!amdgpu_device_supports_baco(adev))
6263 		return -ENOTSUPP;
6264 
6265 	ret = amdgpu_dpm_baco_exit(adev);
6266 	if (ret)
6267 		return ret;
6268 
6269 	if (ras && adev->ras_enabled &&
6270 	    adev->nbio.funcs->enable_doorbell_interrupt)
6271 		adev->nbio.funcs->enable_doorbell_interrupt(adev, true);
6272 
6273 	if (amdgpu_passthrough(adev) && adev->nbio.funcs &&
6274 	    adev->nbio.funcs->clear_doorbell_interrupt)
6275 		adev->nbio.funcs->clear_doorbell_interrupt(adev);
6276 
6277 	return 0;
6278 }
6279 
6280 /**
6281  * amdgpu_pci_error_detected - Called when a PCI error is detected.
6282  * @pdev: PCI device struct
6283  * @state: PCI channel state
6284  *
6285  * Description: Called when a PCI error is detected.
6286  *
6287  * Return: PCI_ERS_RESULT_NEED_RESET or PCI_ERS_RESULT_DISCONNECT.
6288  */
6289 pci_ers_result_t amdgpu_pci_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
6290 {
6291 	struct drm_device *dev = pci_get_drvdata(pdev);
6292 	struct amdgpu_device *adev = drm_to_adev(dev);
6293 	struct amdgpu_hive_info *hive __free(xgmi_put_hive) =
6294 		amdgpu_get_xgmi_hive(adev);
6295 	struct amdgpu_reset_context reset_context;
6296 	struct list_head device_list;
6297 
6298 	dev_info(adev->dev, "PCI error: detected callback!!\n");
6299 
6300 	adev->pci_channel_state = state;
6301 
6302 	switch (state) {
6303 	case pci_channel_io_normal:
6304 		dev_info(adev->dev, "pci_channel_io_normal: state(%d)!!\n", state);
6305 		return PCI_ERS_RESULT_CAN_RECOVER;
6306 	case pci_channel_io_frozen:
6307 		/* Fatal error, prepare for slot reset */
6308 		dev_info(adev->dev, "pci_channel_io_frozen: state(%d)!!\n", state);
6309 		if (hive) {
6310 			/* Hive devices should be able to support FW based
6311 			 * link reset on other devices, if not return.
6312 			 */
6313 			if (!amdgpu_dpm_is_link_reset_supported(adev)) {
6314 				dev_warn(adev->dev,
6315 					 "No support for XGMI hive yet...\n");
6316 				return PCI_ERS_RESULT_DISCONNECT;
6317 			}
6318 			/* Set dpc status only if device is part of hive
6319 			 * Non-hive devices should be able to recover after
6320 			 * link reset.
6321 			 */
6322 			amdgpu_reset_set_dpc_status(adev, true);
6323 
6324 			mutex_lock(&hive->hive_lock);
6325 		} else {
6326 			if (amdgpu_device_bus_status_check(adev))
6327 				amdgpu_reset_set_dpc_status(adev, true);
6328 		}
6329 		memset(&reset_context, 0, sizeof(reset_context));
6330 		INIT_LIST_HEAD(&device_list);
6331 
6332 		amdgpu_device_recovery_prepare(adev, &device_list, hive);
6333 		amdgpu_device_recovery_get_reset_lock(adev, &device_list);
6334 		amdgpu_device_halt_activities(adev, NULL, &reset_context, &device_list,
6335 					      hive, false);
6336 		if (hive)
6337 			mutex_unlock(&hive->hive_lock);
6338 		return PCI_ERS_RESULT_NEED_RESET;
6339 	case pci_channel_io_perm_failure:
6340 		/* Permanent error, prepare for device removal */
6341 		dev_info(adev->dev, "pci_channel_io_perm_failure: state(%d)!!\n", state);
6342 		return PCI_ERS_RESULT_DISCONNECT;
6343 	}
6344 
6345 	return PCI_ERS_RESULT_NEED_RESET;
6346 }
6347 
6348 /**
6349  * amdgpu_pci_mmio_enabled - Enable MMIO and dump debug registers
6350  * @pdev: pointer to PCI device
6351  */
6352 pci_ers_result_t amdgpu_pci_mmio_enabled(struct pci_dev *pdev)
6353 {
6354 	struct drm_device *dev = pci_get_drvdata(pdev);
6355 	struct amdgpu_device *adev = drm_to_adev(dev);
6356 
6357 	dev_info(adev->dev, "PCI error: mmio enabled callback!!\n");
6358 
6359 	/* TODO - dump whatever for debugging purposes */
6360 
6361 	/* This called only if amdgpu_pci_error_detected returns
6362 	 * PCI_ERS_RESULT_CAN_RECOVER. Read/write to the device still
6363 	 * works, no need to reset slot.
6364 	 */
6365 
6366 	return PCI_ERS_RESULT_RECOVERED;
6367 }
6368 
6369 /**
6370  * amdgpu_pci_slot_reset - Called when PCI slot has been reset.
6371  * @pdev: PCI device struct
6372  *
6373  * Description: This routine is called by the pci error recovery
6374  * code after the PCI slot has been reset, just before we
6375  * should resume normal operations.
6376  */
6377 pci_ers_result_t amdgpu_pci_slot_reset(struct pci_dev *pdev)
6378 {
6379 	struct drm_device *dev = pci_get_drvdata(pdev);
6380 	struct amdgpu_device *adev = drm_to_adev(dev);
6381 	struct amdgpu_reset_context reset_context;
6382 	struct amdgpu_device *tmp_adev;
6383 	struct amdgpu_hive_info *hive;
6384 	struct list_head device_list;
6385 	struct pci_dev *link_dev;
6386 	int r = 0, i, timeout;
6387 	u32 memsize;
6388 	u16 status;
6389 
6390 	dev_info(adev->dev, "PCI error: slot reset callback!!\n");
6391 
6392 	memset(&reset_context, 0, sizeof(reset_context));
6393 	INIT_LIST_HEAD(&device_list);
6394 	hive = amdgpu_get_xgmi_hive(adev);
6395 	if (hive) {
6396 		mutex_lock(&hive->hive_lock);
6397 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head)
6398 			list_add_tail(&tmp_adev->reset_list, &device_list);
6399 	} else {
6400 		list_add_tail(&adev->reset_list, &device_list);
6401 	}
6402 
6403 	if (adev->pcie_reset_ctx.swus)
6404 		link_dev = adev->pcie_reset_ctx.swus;
6405 	else
6406 		link_dev = adev->pdev;
6407 	/* wait for asic to come out of reset, timeout = 10s */
6408 	timeout = 10000;
6409 	do {
6410 		usleep_range(10000, 10500);
6411 		r = pci_read_config_word(link_dev, PCI_VENDOR_ID, &status);
6412 		timeout -= 10;
6413 	} while (timeout > 0 && (status != PCI_VENDOR_ID_ATI) &&
6414 		 (status != PCI_VENDOR_ID_AMD));
6415 
6416 	if ((status != PCI_VENDOR_ID_ATI) && (status != PCI_VENDOR_ID_AMD)) {
6417 		r = -ETIME;
6418 		goto out;
6419 	}
6420 
6421 	amdgpu_device_load_switch_state(adev);
6422 	/* Restore PCI confspace */
6423 	amdgpu_device_load_pci_state(pdev);
6424 
6425 	/* confirm  ASIC came out of reset */
6426 	for (i = 0; i < adev->usec_timeout; i++) {
6427 		memsize = amdgpu_asic_get_config_memsize(adev);
6428 
6429 		if (memsize != 0xffffffff)
6430 			break;
6431 		udelay(1);
6432 	}
6433 	if (memsize == 0xffffffff) {
6434 		r = -ETIME;
6435 		goto out;
6436 	}
6437 
6438 	reset_context.method = AMD_RESET_METHOD_NONE;
6439 	reset_context.reset_req_dev = adev;
6440 	set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
6441 	set_bit(AMDGPU_SKIP_COREDUMP, &reset_context.flags);
6442 
6443 	if (hive) {
6444 		reset_context.hive = hive;
6445 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head)
6446 			tmp_adev->pcie_reset_ctx.in_link_reset = true;
6447 	} else {
6448 		adev->pcie_reset_ctx.in_link_reset = true;
6449 		set_bit(AMDGPU_SKIP_HW_RESET, &reset_context.flags);
6450 	}
6451 
6452 	r = amdgpu_device_asic_reset(adev, &device_list, &reset_context);
6453 out:
6454 	if (!r) {
6455 		if (amdgpu_device_cache_pci_state(adev->pdev))
6456 			pci_restore_state(adev->pdev);
6457 		dev_info(adev->dev, "PCIe error recovery succeeded\n");
6458 	} else {
6459 		dev_err(adev->dev, "PCIe error recovery failed, err:%d\n", r);
6460 		if (hive) {
6461 			list_for_each_entry(tmp_adev, &device_list, reset_list)
6462 				amdgpu_device_unset_mp1_state(tmp_adev);
6463 		}
6464 		amdgpu_device_recovery_put_reset_lock(adev, &device_list);
6465 	}
6466 
6467 	if (hive) {
6468 		mutex_unlock(&hive->hive_lock);
6469 		amdgpu_put_xgmi_hive(hive);
6470 	}
6471 
6472 	return r ? PCI_ERS_RESULT_DISCONNECT : PCI_ERS_RESULT_RECOVERED;
6473 }
6474 
6475 /**
6476  * amdgpu_pci_resume() - resume normal ops after PCI reset
6477  * @pdev: pointer to PCI device
6478  *
6479  * Called when the error recovery driver tells us that its
6480  * OK to resume normal operation.
6481  */
6482 void amdgpu_pci_resume(struct pci_dev *pdev)
6483 {
6484 	struct drm_device *dev = pci_get_drvdata(pdev);
6485 	struct amdgpu_device *adev = drm_to_adev(dev);
6486 	struct list_head device_list;
6487 	struct amdgpu_hive_info *hive = NULL;
6488 	struct amdgpu_device *tmp_adev = NULL;
6489 
6490 	dev_info(adev->dev, "PCI error: resume callback!!\n");
6491 
6492 	/* Only continue execution for the case of pci_channel_io_frozen */
6493 	if (adev->pci_channel_state != pci_channel_io_frozen)
6494 		return;
6495 
6496 	INIT_LIST_HEAD(&device_list);
6497 
6498 	hive = amdgpu_get_xgmi_hive(adev);
6499 	if (hive) {
6500 		mutex_lock(&hive->hive_lock);
6501 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head) {
6502 			tmp_adev->pcie_reset_ctx.in_link_reset = false;
6503 			list_add_tail(&tmp_adev->reset_list, &device_list);
6504 		}
6505 	} else {
6506 		adev->pcie_reset_ctx.in_link_reset = false;
6507 		list_add_tail(&adev->reset_list, &device_list);
6508 	}
6509 	amdgpu_device_sched_resume(&device_list, NULL, NULL);
6510 	amdgpu_device_gpu_resume(adev, &device_list, false);
6511 	amdgpu_device_recovery_put_reset_lock(adev, &device_list);
6512 
6513 	if (hive) {
6514 		mutex_unlock(&hive->hive_lock);
6515 		amdgpu_put_xgmi_hive(hive);
6516 	}
6517 }
6518 
6519 static void amdgpu_device_cache_switch_state(struct amdgpu_device *adev)
6520 {
6521 	struct pci_dev *swus, *swds;
6522 	int r;
6523 
6524 	swds = pci_upstream_bridge(adev->pdev);
6525 	if (!swds || swds->vendor != PCI_VENDOR_ID_ATI ||
6526 	    pci_pcie_type(swds) != PCI_EXP_TYPE_DOWNSTREAM)
6527 		return;
6528 	swus = pci_upstream_bridge(swds);
6529 	if (!swus ||
6530 	    (swus->vendor != PCI_VENDOR_ID_ATI &&
6531 	     swus->vendor != PCI_VENDOR_ID_AMD) ||
6532 	    pci_pcie_type(swus) != PCI_EXP_TYPE_UPSTREAM)
6533 		return;
6534 
6535 	/* If already saved, return */
6536 	if (adev->pcie_reset_ctx.swus)
6537 		return;
6538 	/* Upstream bridge is ATI, assume it's SWUS/DS architecture */
6539 	r = pci_save_state(swds);
6540 	if (r)
6541 		return;
6542 	adev->pcie_reset_ctx.swds_pcistate = pci_store_saved_state(swds);
6543 
6544 	r = pci_save_state(swus);
6545 	if (r)
6546 		return;
6547 	adev->pcie_reset_ctx.swus_pcistate = pci_store_saved_state(swus);
6548 
6549 	adev->pcie_reset_ctx.swus = swus;
6550 }
6551 
6552 static void amdgpu_device_load_switch_state(struct amdgpu_device *adev)
6553 {
6554 	struct pci_dev *pdev;
6555 	int r;
6556 
6557 	if (!adev->pcie_reset_ctx.swds_pcistate ||
6558 	    !adev->pcie_reset_ctx.swus_pcistate)
6559 		return;
6560 
6561 	pdev = adev->pcie_reset_ctx.swus;
6562 	r = pci_load_saved_state(pdev, adev->pcie_reset_ctx.swus_pcistate);
6563 	if (!r) {
6564 		pci_restore_state(pdev);
6565 	} else {
6566 		dev_warn(adev->dev, "Failed to load SWUS state, err:%d\n", r);
6567 		return;
6568 	}
6569 
6570 	pdev = pci_upstream_bridge(adev->pdev);
6571 	r = pci_load_saved_state(pdev, adev->pcie_reset_ctx.swds_pcistate);
6572 	if (!r)
6573 		pci_restore_state(pdev);
6574 	else
6575 		dev_warn(adev->dev, "Failed to load SWDS state, err:%d\n", r);
6576 }
6577 
6578 bool amdgpu_device_cache_pci_state(struct pci_dev *pdev)
6579 {
6580 	struct drm_device *dev = pci_get_drvdata(pdev);
6581 	struct amdgpu_device *adev = drm_to_adev(dev);
6582 	int r;
6583 
6584 	if (amdgpu_sriov_vf(adev))
6585 		return false;
6586 
6587 	r = pci_save_state(pdev);
6588 	if (!r) {
6589 		kfree(adev->pci_state);
6590 
6591 		adev->pci_state = pci_store_saved_state(pdev);
6592 
6593 		if (!adev->pci_state) {
6594 			dev_err(adev->dev, "Failed to store PCI saved state");
6595 			return false;
6596 		}
6597 	} else {
6598 		dev_warn(adev->dev, "Failed to save PCI state, err:%d\n", r);
6599 		return false;
6600 	}
6601 
6602 	amdgpu_device_cache_switch_state(adev);
6603 
6604 	return true;
6605 }
6606 
6607 bool amdgpu_device_load_pci_state(struct pci_dev *pdev)
6608 {
6609 	struct drm_device *dev = pci_get_drvdata(pdev);
6610 	struct amdgpu_device *adev = drm_to_adev(dev);
6611 	int r;
6612 
6613 	if (!adev->pci_state)
6614 		return false;
6615 
6616 	r = pci_load_saved_state(pdev, adev->pci_state);
6617 
6618 	if (!r) {
6619 		pci_restore_state(pdev);
6620 	} else {
6621 		dev_warn(adev->dev, "Failed to load PCI state, err:%d\n", r);
6622 		return false;
6623 	}
6624 
6625 	return true;
6626 }
6627 
6628 void amdgpu_device_flush_hdp(struct amdgpu_device *adev,
6629 		struct amdgpu_ring *ring)
6630 {
6631 #ifdef CONFIG_X86_64
6632 	if ((adev->flags & AMD_IS_APU) && !amdgpu_passthrough(adev))
6633 		return;
6634 #endif
6635 	if (adev->gmc.xgmi.connected_to_cpu)
6636 		return;
6637 
6638 	if (ring && ring->funcs->emit_hdp_flush) {
6639 		amdgpu_ring_emit_hdp_flush(ring);
6640 		return;
6641 	}
6642 
6643 	if (!ring && amdgpu_sriov_runtime(adev)) {
6644 		if (!amdgpu_kiq_hdp_flush(adev))
6645 			return;
6646 	}
6647 
6648 	amdgpu_hdp_flush(adev, ring);
6649 }
6650 
6651 void amdgpu_device_invalidate_hdp(struct amdgpu_device *adev,
6652 		struct amdgpu_ring *ring)
6653 {
6654 #ifdef CONFIG_X86_64
6655 	if ((adev->flags & AMD_IS_APU) && !amdgpu_passthrough(adev))
6656 		return;
6657 #endif
6658 	if (adev->gmc.xgmi.connected_to_cpu)
6659 		return;
6660 
6661 	amdgpu_hdp_invalidate(adev, ring);
6662 }
6663 
6664 int amdgpu_in_reset(struct amdgpu_device *adev)
6665 {
6666 	return atomic_read(&adev->reset_domain->in_gpu_reset);
6667 }
6668 
6669 /**
6670  * amdgpu_device_halt() - bring hardware to some kind of halt state
6671  *
6672  * @adev: amdgpu_device pointer
6673  *
6674  * Bring hardware to some kind of halt state so that no one can touch it
6675  * any more. It will help to maintain error context when error occurred.
6676  * Compare to a simple hang, the system will keep stable at least for SSH
6677  * access. Then it should be trivial to inspect the hardware state and
6678  * see what's going on. Implemented as following:
6679  *
6680  * 1. drm_dev_unplug() makes device inaccessible to user space(IOCTLs, etc),
6681  *    clears all CPU mappings to device, disallows remappings through page faults
6682  * 2. amdgpu_irq_disable_all() disables all interrupts
6683  * 3. amdgpu_fence_driver_hw_fini() signals all HW fences
6684  * 4. set adev->no_hw_access to avoid potential crashes after setp 5
6685  * 5. amdgpu_device_unmap_mmio() clears all MMIO mappings
6686  * 6. pci_disable_device() and pci_wait_for_pending_transaction()
6687  *    flush any in flight DMA operations
6688  */
6689 void amdgpu_device_halt(struct amdgpu_device *adev)
6690 {
6691 	struct pci_dev *pdev = adev->pdev;
6692 	struct drm_device *ddev = adev_to_drm(adev);
6693 
6694 	amdgpu_xcp_dev_unplug(adev);
6695 	drm_dev_unplug(ddev);
6696 
6697 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
6698 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
6699 
6700 	amdgpu_irq_disable_all(adev);
6701 
6702 	amdgpu_fence_driver_hw_fini(adev);
6703 
6704 	adev->no_hw_access = true;
6705 
6706 	amdgpu_device_unmap_mmio(adev);
6707 
6708 	pci_disable_device(pdev);
6709 	pci_wait_for_pending_transaction(pdev);
6710 }
6711 
6712 /**
6713  * amdgpu_device_get_gang - return a reference to the current gang
6714  * @adev: amdgpu_device pointer
6715  *
6716  * Returns: A new reference to the current gang leader.
6717  */
6718 struct dma_fence *amdgpu_device_get_gang(struct amdgpu_device *adev)
6719 {
6720 	struct dma_fence *fence;
6721 
6722 	rcu_read_lock();
6723 	fence = dma_fence_get_rcu_safe(&adev->gang_submit);
6724 	rcu_read_unlock();
6725 	return fence;
6726 }
6727 
6728 /**
6729  * amdgpu_device_switch_gang - switch to a new gang
6730  * @adev: amdgpu_device pointer
6731  * @gang: the gang to switch to
6732  *
6733  * Try to switch to a new gang.
6734  * Returns: NULL if we switched to the new gang or a reference to the current
6735  * gang leader.
6736  */
6737 struct dma_fence *amdgpu_device_switch_gang(struct amdgpu_device *adev,
6738 					    struct dma_fence *gang)
6739 {
6740 	struct dma_fence *old = NULL;
6741 
6742 	dma_fence_get(gang);
6743 	do {
6744 		dma_fence_put(old);
6745 		old = amdgpu_device_get_gang(adev);
6746 		if (old == gang)
6747 			break;
6748 
6749 		if (!dma_fence_is_signaled(old)) {
6750 			dma_fence_put(gang);
6751 			return old;
6752 		}
6753 
6754 	} while (cmpxchg((struct dma_fence __force **)&adev->gang_submit,
6755 			 old, gang) != old);
6756 
6757 	/*
6758 	 * Drop it once for the exchanged reference in adev and once for the
6759 	 * thread local reference acquired in amdgpu_device_get_gang().
6760 	 */
6761 	dma_fence_put(old);
6762 	dma_fence_put(old);
6763 	return NULL;
6764 }
6765 
6766 /**
6767  * amdgpu_device_enforce_isolation - enforce HW isolation
6768  * @adev: the amdgpu device pointer
6769  * @ring: the HW ring the job is supposed to run on
6770  * @job: the job which is about to be pushed to the HW ring
6771  *
6772  * Makes sure that only one client at a time can use the GFX block.
6773  * Returns: The dependency to wait on before the job can be pushed to the HW.
6774  * The function is called multiple times until NULL is returned.
6775  */
6776 struct dma_fence *amdgpu_device_enforce_isolation(struct amdgpu_device *adev,
6777 						  struct amdgpu_ring *ring,
6778 						  struct amdgpu_job *job)
6779 {
6780 	struct amdgpu_isolation *isolation = &adev->isolation[ring->xcp_id];
6781 	struct drm_sched_fence *f = job->base.s_fence;
6782 	struct dma_fence *dep;
6783 	void *owner;
6784 	int r;
6785 
6786 	/*
6787 	 * For now enforce isolation only for the GFX block since we only need
6788 	 * the cleaner shader on those rings.
6789 	 */
6790 	if (ring->funcs->type != AMDGPU_RING_TYPE_GFX &&
6791 	    ring->funcs->type != AMDGPU_RING_TYPE_COMPUTE)
6792 		return NULL;
6793 
6794 	/*
6795 	 * All submissions where enforce isolation is false are handled as if
6796 	 * they come from a single client. Use ~0l as the owner to distinct it
6797 	 * from kernel submissions where the owner is NULL.
6798 	 */
6799 	owner = job->enforce_isolation ? f->owner : (void *)~0l;
6800 
6801 	mutex_lock(&adev->enforce_isolation_mutex);
6802 
6803 	/*
6804 	 * The "spearhead" submission is the first one which changes the
6805 	 * ownership to its client. We always need to wait for it to be
6806 	 * pushed to the HW before proceeding with anything.
6807 	 */
6808 	if (&f->scheduled != isolation->spearhead &&
6809 	    !dma_fence_is_signaled(isolation->spearhead)) {
6810 		dep = isolation->spearhead;
6811 		goto out_grab_ref;
6812 	}
6813 
6814 	if (isolation->owner != owner) {
6815 
6816 		/*
6817 		 * Wait for any gang to be assembled before switching to a
6818 		 * different owner or otherwise we could deadlock the
6819 		 * submissions.
6820 		 */
6821 		if (!job->gang_submit) {
6822 			dep = amdgpu_device_get_gang(adev);
6823 			if (!dma_fence_is_signaled(dep))
6824 				goto out_return_dep;
6825 			dma_fence_put(dep);
6826 		}
6827 
6828 		dma_fence_put(isolation->spearhead);
6829 		isolation->spearhead = dma_fence_get(&f->scheduled);
6830 		amdgpu_sync_move(&isolation->active, &isolation->prev);
6831 		trace_amdgpu_isolation(isolation->owner, owner);
6832 		isolation->owner = owner;
6833 	}
6834 
6835 	/*
6836 	 * Specifying the ring here helps to pipeline submissions even when
6837 	 * isolation is enabled. If that is not desired for testing NULL can be
6838 	 * used instead of the ring to enforce a CPU round trip while switching
6839 	 * between clients.
6840 	 */
6841 	dep = amdgpu_sync_peek_fence(&isolation->prev, ring);
6842 	r = amdgpu_sync_fence(&isolation->active, &f->finished, GFP_NOWAIT);
6843 	if (r)
6844 		dev_warn(adev->dev, "OOM tracking isolation\n");
6845 
6846 out_grab_ref:
6847 	dma_fence_get(dep);
6848 out_return_dep:
6849 	mutex_unlock(&adev->enforce_isolation_mutex);
6850 	return dep;
6851 }
6852 
6853 bool amdgpu_device_has_display_hardware(struct amdgpu_device *adev)
6854 {
6855 	switch (adev->asic_type) {
6856 #ifdef CONFIG_DRM_AMDGPU_SI
6857 	case CHIP_HAINAN:
6858 #endif
6859 	case CHIP_TOPAZ:
6860 		/* chips with no display hardware */
6861 		return false;
6862 #ifdef CONFIG_DRM_AMDGPU_SI
6863 	case CHIP_TAHITI:
6864 	case CHIP_PITCAIRN:
6865 	case CHIP_VERDE:
6866 	case CHIP_OLAND:
6867 #endif
6868 #ifdef CONFIG_DRM_AMDGPU_CIK
6869 	case CHIP_BONAIRE:
6870 	case CHIP_HAWAII:
6871 	case CHIP_KAVERI:
6872 	case CHIP_KABINI:
6873 	case CHIP_MULLINS:
6874 #endif
6875 	case CHIP_TONGA:
6876 	case CHIP_FIJI:
6877 	case CHIP_POLARIS10:
6878 	case CHIP_POLARIS11:
6879 	case CHIP_POLARIS12:
6880 	case CHIP_VEGAM:
6881 	case CHIP_CARRIZO:
6882 	case CHIP_STONEY:
6883 		/* chips with display hardware */
6884 		return true;
6885 	default:
6886 		/* IP discovery */
6887 		if (!amdgpu_ip_version(adev, DCE_HWIP, 0) ||
6888 		    (adev->harvest_ip_mask & AMD_HARVEST_IP_DMU_MASK))
6889 			return false;
6890 		return true;
6891 	}
6892 }
6893 
6894 ssize_t amdgpu_get_soft_full_reset_mask(struct amdgpu_ring *ring)
6895 {
6896 	ssize_t size = 0;
6897 
6898 	if (!ring || !ring->adev)
6899 		return size;
6900 
6901 	if (amdgpu_device_should_recover_gpu(ring->adev))
6902 		size |= AMDGPU_RESET_TYPE_FULL;
6903 
6904 	if (unlikely(!ring->adev->debug_disable_soft_recovery) &&
6905 	    !amdgpu_sriov_vf(ring->adev) && ring->funcs->soft_recovery)
6906 		size |= AMDGPU_RESET_TYPE_SOFT_RESET;
6907 
6908 	return size;
6909 }
6910 
6911 ssize_t amdgpu_show_reset_mask(char *buf, uint32_t supported_reset)
6912 {
6913 	ssize_t size = 0;
6914 
6915 	if (supported_reset == 0) {
6916 		size += sysfs_emit_at(buf, size, "unsupported");
6917 		size += sysfs_emit_at(buf, size, "\n");
6918 		return size;
6919 
6920 	}
6921 
6922 	if (supported_reset & AMDGPU_RESET_TYPE_SOFT_RESET)
6923 		size += sysfs_emit_at(buf, size, "soft ");
6924 
6925 	if (supported_reset & AMDGPU_RESET_TYPE_PER_QUEUE)
6926 		size += sysfs_emit_at(buf, size, "queue ");
6927 
6928 	if (supported_reset & AMDGPU_RESET_TYPE_PER_PIPE)
6929 		size += sysfs_emit_at(buf, size, "pipe ");
6930 
6931 	if (supported_reset & AMDGPU_RESET_TYPE_FULL)
6932 		size += sysfs_emit_at(buf, size, "full ");
6933 
6934 	size += sysfs_emit_at(buf, size, "\n");
6935 	return size;
6936 }
6937 
6938 void amdgpu_device_set_uid(struct amdgpu_uid *uid_info,
6939 			   enum amdgpu_uid_type type, uint8_t inst,
6940 			   uint64_t uid)
6941 {
6942 	if (!uid_info)
6943 		return;
6944 
6945 	if (type >= AMDGPU_UID_TYPE_MAX) {
6946 		dev_err_once(uid_info->adev->dev, "Invalid UID type %d\n",
6947 			     type);
6948 		return;
6949 	}
6950 
6951 	if (inst >= AMDGPU_UID_INST_MAX) {
6952 		dev_err_once(uid_info->adev->dev, "Invalid UID instance %d\n",
6953 			     inst);
6954 		return;
6955 	}
6956 
6957 	if (uid_info->uid[type][inst] != 0) {
6958 		dev_warn_once(
6959 			uid_info->adev->dev,
6960 			"Overwriting existing UID %llu for type %d instance %d\n",
6961 			uid_info->uid[type][inst], type, inst);
6962 	}
6963 
6964 	uid_info->uid[type][inst] = uid;
6965 }
6966 
6967 u64 amdgpu_device_get_uid(struct amdgpu_uid *uid_info,
6968 			  enum amdgpu_uid_type type, uint8_t inst)
6969 {
6970 	if (!uid_info)
6971 		return 0;
6972 
6973 	if (type >= AMDGPU_UID_TYPE_MAX) {
6974 		dev_err_once(uid_info->adev->dev, "Invalid UID type %d\n",
6975 			     type);
6976 		return 0;
6977 	}
6978 
6979 	if (inst >= AMDGPU_UID_INST_MAX) {
6980 		dev_err_once(uid_info->adev->dev, "Invalid UID instance %d\n",
6981 			     inst);
6982 		return 0;
6983 	}
6984 
6985 	return uid_info->uid[type][inst];
6986 }
6987