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