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