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