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