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