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