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