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