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