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