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