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