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 #include <linux/power_supply.h>
29 #include <linux/kthread.h>
30 #include <linux/module.h>
31 #include <linux/console.h>
32 #include <linux/slab.h>
33 #include <linux/iommu.h>
34 #include <linux/pci.h>
35 
36 #include <drm/drm_atomic_helper.h>
37 #include <drm/drm_probe_helper.h>
38 #include <drm/amdgpu_drm.h>
39 #include <linux/vgaarb.h>
40 #include <linux/vga_switcheroo.h>
41 #include <linux/efi.h>
42 #include "amdgpu.h"
43 #include "amdgpu_trace.h"
44 #include "amdgpu_i2c.h"
45 #include "atom.h"
46 #include "amdgpu_atombios.h"
47 #include "amdgpu_atomfirmware.h"
48 #include "amd_pcie.h"
49 #ifdef CONFIG_DRM_AMDGPU_SI
50 #include "si.h"
51 #endif
52 #ifdef CONFIG_DRM_AMDGPU_CIK
53 #include "cik.h"
54 #endif
55 #include "vi.h"
56 #include "soc15.h"
57 #include "nv.h"
58 #include "bif/bif_4_1_d.h"
59 #include <linux/firmware.h>
60 #include "amdgpu_vf_error.h"
61 
62 #include "amdgpu_amdkfd.h"
63 #include "amdgpu_pm.h"
64 
65 #include "amdgpu_xgmi.h"
66 #include "amdgpu_ras.h"
67 #include "amdgpu_pmu.h"
68 #include "amdgpu_fru_eeprom.h"
69 #include "amdgpu_reset.h"
70 
71 #include <linux/suspend.h>
72 #include <drm/task_barrier.h>
73 #include <linux/pm_runtime.h>
74 
75 #include <drm/drm_drv.h>
76 
77 MODULE_FIRMWARE("amdgpu/vega10_gpu_info.bin");
78 MODULE_FIRMWARE("amdgpu/vega12_gpu_info.bin");
79 MODULE_FIRMWARE("amdgpu/raven_gpu_info.bin");
80 MODULE_FIRMWARE("amdgpu/picasso_gpu_info.bin");
81 MODULE_FIRMWARE("amdgpu/raven2_gpu_info.bin");
82 MODULE_FIRMWARE("amdgpu/arcturus_gpu_info.bin");
83 MODULE_FIRMWARE("amdgpu/renoir_gpu_info.bin");
84 MODULE_FIRMWARE("amdgpu/navi10_gpu_info.bin");
85 MODULE_FIRMWARE("amdgpu/navi14_gpu_info.bin");
86 MODULE_FIRMWARE("amdgpu/navi12_gpu_info.bin");
87 MODULE_FIRMWARE("amdgpu/vangogh_gpu_info.bin");
88 MODULE_FIRMWARE("amdgpu/yellow_carp_gpu_info.bin");
89 
90 #define AMDGPU_RESUME_MS		2000
91 
92 const char *amdgpu_asic_name[] = {
93 	"TAHITI",
94 	"PITCAIRN",
95 	"VERDE",
96 	"OLAND",
97 	"HAINAN",
98 	"BONAIRE",
99 	"KAVERI",
100 	"KABINI",
101 	"HAWAII",
102 	"MULLINS",
103 	"TOPAZ",
104 	"TONGA",
105 	"FIJI",
106 	"CARRIZO",
107 	"STONEY",
108 	"POLARIS10",
109 	"POLARIS11",
110 	"POLARIS12",
111 	"VEGAM",
112 	"VEGA10",
113 	"VEGA12",
114 	"VEGA20",
115 	"RAVEN",
116 	"ARCTURUS",
117 	"RENOIR",
118 	"ALDEBARAN",
119 	"NAVI10",
120 	"CYAN_SKILLFISH",
121 	"NAVI14",
122 	"NAVI12",
123 	"SIENNA_CICHLID",
124 	"NAVY_FLOUNDER",
125 	"VANGOGH",
126 	"DIMGREY_CAVEFISH",
127 	"BEIGE_GOBY",
128 	"YELLOW_CARP",
129 	"IP DISCOVERY",
130 	"LAST",
131 };
132 
133 /**
134  * DOC: pcie_replay_count
135  *
136  * The amdgpu driver provides a sysfs API for reporting the total number
137  * of PCIe replays (NAKs)
138  * The file pcie_replay_count is used for this and returns the total
139  * number of replays as a sum of the NAKs generated and NAKs received
140  */
141 
142 static ssize_t amdgpu_device_get_pcie_replay_count(struct device *dev,
143 		struct device_attribute *attr, char *buf)
144 {
145 	struct drm_device *ddev = dev_get_drvdata(dev);
146 	struct amdgpu_device *adev = drm_to_adev(ddev);
147 	uint64_t cnt = amdgpu_asic_get_pcie_replay_count(adev);
148 
149 	return sysfs_emit(buf, "%llu\n", cnt);
150 }
151 
152 static DEVICE_ATTR(pcie_replay_count, S_IRUGO,
153 		amdgpu_device_get_pcie_replay_count, NULL);
154 
155 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev);
156 
157 /**
158  * DOC: product_name
159  *
160  * The amdgpu driver provides a sysfs API for reporting the product name
161  * for the device
162  * The file serial_number is used for this and returns the product name
163  * as returned from the FRU.
164  * NOTE: This is only available for certain server cards
165  */
166 
167 static ssize_t amdgpu_device_get_product_name(struct device *dev,
168 		struct device_attribute *attr, char *buf)
169 {
170 	struct drm_device *ddev = dev_get_drvdata(dev);
171 	struct amdgpu_device *adev = drm_to_adev(ddev);
172 
173 	return sysfs_emit(buf, "%s\n", adev->product_name);
174 }
175 
176 static DEVICE_ATTR(product_name, S_IRUGO,
177 		amdgpu_device_get_product_name, NULL);
178 
179 /**
180  * DOC: product_number
181  *
182  * The amdgpu driver provides a sysfs API for reporting the part number
183  * for the device
184  * The file serial_number is used for this and returns the part number
185  * as returned from the FRU.
186  * NOTE: This is only available for certain server cards
187  */
188 
189 static ssize_t amdgpu_device_get_product_number(struct device *dev,
190 		struct device_attribute *attr, char *buf)
191 {
192 	struct drm_device *ddev = dev_get_drvdata(dev);
193 	struct amdgpu_device *adev = drm_to_adev(ddev);
194 
195 	return sysfs_emit(buf, "%s\n", adev->product_number);
196 }
197 
198 static DEVICE_ATTR(product_number, S_IRUGO,
199 		amdgpu_device_get_product_number, NULL);
200 
201 /**
202  * DOC: serial_number
203  *
204  * The amdgpu driver provides a sysfs API for reporting the serial number
205  * for the device
206  * The file serial_number is used for this and returns the serial number
207  * as returned from the FRU.
208  * NOTE: This is only available for certain server cards
209  */
210 
211 static ssize_t amdgpu_device_get_serial_number(struct device *dev,
212 		struct device_attribute *attr, char *buf)
213 {
214 	struct drm_device *ddev = dev_get_drvdata(dev);
215 	struct amdgpu_device *adev = drm_to_adev(ddev);
216 
217 	return sysfs_emit(buf, "%s\n", adev->serial);
218 }
219 
220 static DEVICE_ATTR(serial_number, S_IRUGO,
221 		amdgpu_device_get_serial_number, NULL);
222 
223 /**
224  * amdgpu_device_supports_px - Is the device a dGPU with ATPX power control
225  *
226  * @dev: drm_device pointer
227  *
228  * Returns true if the device is a dGPU with ATPX power control,
229  * otherwise return false.
230  */
231 bool amdgpu_device_supports_px(struct drm_device *dev)
232 {
233 	struct amdgpu_device *adev = drm_to_adev(dev);
234 
235 	if ((adev->flags & AMD_IS_PX) && !amdgpu_is_atpx_hybrid())
236 		return true;
237 	return false;
238 }
239 
240 /**
241  * amdgpu_device_supports_boco - Is the device a dGPU with ACPI power resources
242  *
243  * @dev: drm_device pointer
244  *
245  * Returns true if the device is a dGPU with ACPI power control,
246  * otherwise return false.
247  */
248 bool amdgpu_device_supports_boco(struct drm_device *dev)
249 {
250 	struct amdgpu_device *adev = drm_to_adev(dev);
251 
252 	if (adev->has_pr3 ||
253 	    ((adev->flags & AMD_IS_PX) && amdgpu_is_atpx_hybrid()))
254 		return true;
255 	return false;
256 }
257 
258 /**
259  * amdgpu_device_supports_baco - Does the device support BACO
260  *
261  * @dev: drm_device pointer
262  *
263  * Returns true if the device supporte BACO,
264  * otherwise return false.
265  */
266 bool amdgpu_device_supports_baco(struct drm_device *dev)
267 {
268 	struct amdgpu_device *adev = drm_to_adev(dev);
269 
270 	return amdgpu_asic_supports_baco(adev);
271 }
272 
273 /**
274  * amdgpu_device_supports_smart_shift - Is the device dGPU with
275  * smart shift support
276  *
277  * @dev: drm_device pointer
278  *
279  * Returns true if the device is a dGPU with Smart Shift support,
280  * otherwise returns false.
281  */
282 bool amdgpu_device_supports_smart_shift(struct drm_device *dev)
283 {
284 	return (amdgpu_device_supports_boco(dev) &&
285 		amdgpu_acpi_is_power_shift_control_supported());
286 }
287 
288 /*
289  * VRAM access helper functions
290  */
291 
292 /**
293  * amdgpu_device_mm_access - access vram by MM_INDEX/MM_DATA
294  *
295  * @adev: amdgpu_device pointer
296  * @pos: offset of the buffer in vram
297  * @buf: virtual address of the buffer in system memory
298  * @size: read/write size, sizeof(@buf) must > @size
299  * @write: true - write to vram, otherwise - read from vram
300  */
301 void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos,
302 			     void *buf, size_t size, bool write)
303 {
304 	unsigned long flags;
305 	uint32_t hi = ~0, tmp = 0;
306 	uint32_t *data = buf;
307 	uint64_t last;
308 	int idx;
309 
310 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
311 		return;
312 
313 	BUG_ON(!IS_ALIGNED(pos, 4) || !IS_ALIGNED(size, 4));
314 
315 	spin_lock_irqsave(&adev->mmio_idx_lock, flags);
316 	for (last = pos + size; pos < last; pos += 4) {
317 		tmp = pos >> 31;
318 
319 		WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000);
320 		if (tmp != hi) {
321 			WREG32_NO_KIQ(mmMM_INDEX_HI, tmp);
322 			hi = tmp;
323 		}
324 		if (write)
325 			WREG32_NO_KIQ(mmMM_DATA, *data++);
326 		else
327 			*data++ = RREG32_NO_KIQ(mmMM_DATA);
328 	}
329 
330 	spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
331 	drm_dev_exit(idx);
332 }
333 
334 /**
335  * amdgpu_device_aper_access - access vram by vram aperature
336  *
337  * @adev: amdgpu_device pointer
338  * @pos: offset of the buffer in vram
339  * @buf: virtual address of the buffer in system memory
340  * @size: read/write size, sizeof(@buf) must > @size
341  * @write: true - write to vram, otherwise - read from vram
342  *
343  * The return value means how many bytes have been transferred.
344  */
345 size_t amdgpu_device_aper_access(struct amdgpu_device *adev, loff_t pos,
346 				 void *buf, size_t size, bool write)
347 {
348 #ifdef CONFIG_64BIT
349 	void __iomem *addr;
350 	size_t count = 0;
351 	uint64_t last;
352 
353 	if (!adev->mman.aper_base_kaddr)
354 		return 0;
355 
356 	last = min(pos + size, adev->gmc.visible_vram_size);
357 	if (last > pos) {
358 		addr = adev->mman.aper_base_kaddr + pos;
359 		count = last - pos;
360 
361 		if (write) {
362 			memcpy_toio(addr, buf, count);
363 			mb();
364 			amdgpu_device_flush_hdp(adev, NULL);
365 		} else {
366 			amdgpu_device_invalidate_hdp(adev, NULL);
367 			mb();
368 			memcpy_fromio(buf, addr, count);
369 		}
370 
371 	}
372 
373 	return count;
374 #else
375 	return 0;
376 #endif
377 }
378 
379 /**
380  * amdgpu_device_vram_access - read/write a buffer in vram
381  *
382  * @adev: amdgpu_device pointer
383  * @pos: offset of the buffer in vram
384  * @buf: virtual address of the buffer in system memory
385  * @size: read/write size, sizeof(@buf) must > @size
386  * @write: true - write to vram, otherwise - read from vram
387  */
388 void amdgpu_device_vram_access(struct amdgpu_device *adev, loff_t pos,
389 			       void *buf, size_t size, bool write)
390 {
391 	size_t count;
392 
393 	/* try to using vram apreature to access vram first */
394 	count = amdgpu_device_aper_access(adev, pos, buf, size, write);
395 	size -= count;
396 	if (size) {
397 		/* using MM to access rest vram */
398 		pos += count;
399 		buf += count;
400 		amdgpu_device_mm_access(adev, pos, buf, size, write);
401 	}
402 }
403 
404 /*
405  * register access helper functions.
406  */
407 
408 /* Check if hw access should be skipped because of hotplug or device error */
409 bool amdgpu_device_skip_hw_access(struct amdgpu_device *adev)
410 {
411 	if (adev->no_hw_access)
412 		return true;
413 
414 #ifdef CONFIG_LOCKDEP
415 	/*
416 	 * This is a bit complicated to understand, so worth a comment. What we assert
417 	 * here is that the GPU reset is not running on another thread in parallel.
418 	 *
419 	 * For this we trylock the read side of the reset semaphore, if that succeeds
420 	 * we know that the reset is not running in paralell.
421 	 *
422 	 * If the trylock fails we assert that we are either already holding the read
423 	 * side of the lock or are the reset thread itself and hold the write side of
424 	 * the lock.
425 	 */
426 	if (in_task()) {
427 		if (down_read_trylock(&adev->reset_sem))
428 			up_read(&adev->reset_sem);
429 		else
430 			lockdep_assert_held(&adev->reset_sem);
431 	}
432 #endif
433 	return false;
434 }
435 
436 /**
437  * amdgpu_device_rreg - read a memory mapped IO or indirect register
438  *
439  * @adev: amdgpu_device pointer
440  * @reg: dword aligned register offset
441  * @acc_flags: access flags which require special behavior
442  *
443  * Returns the 32 bit value from the offset specified.
444  */
445 uint32_t amdgpu_device_rreg(struct amdgpu_device *adev,
446 			    uint32_t reg, uint32_t acc_flags)
447 {
448 	uint32_t ret;
449 
450 	if (amdgpu_device_skip_hw_access(adev))
451 		return 0;
452 
453 	if ((reg * 4) < adev->rmmio_size) {
454 		if (!(acc_flags & AMDGPU_REGS_NO_KIQ) &&
455 		    amdgpu_sriov_runtime(adev) &&
456 		    down_read_trylock(&adev->reset_sem)) {
457 			ret = amdgpu_kiq_rreg(adev, reg);
458 			up_read(&adev->reset_sem);
459 		} else {
460 			ret = readl(((void __iomem *)adev->rmmio) + (reg * 4));
461 		}
462 	} else {
463 		ret = adev->pcie_rreg(adev, reg * 4);
464 	}
465 
466 	trace_amdgpu_device_rreg(adev->pdev->device, reg, ret);
467 
468 	return ret;
469 }
470 
471 /*
472  * MMIO register read with bytes helper functions
473  * @offset:bytes offset from MMIO start
474  *
475 */
476 
477 /**
478  * amdgpu_mm_rreg8 - read a memory mapped IO register
479  *
480  * @adev: amdgpu_device pointer
481  * @offset: byte aligned register offset
482  *
483  * Returns the 8 bit value from the offset specified.
484  */
485 uint8_t amdgpu_mm_rreg8(struct amdgpu_device *adev, uint32_t offset)
486 {
487 	if (amdgpu_device_skip_hw_access(adev))
488 		return 0;
489 
490 	if (offset < adev->rmmio_size)
491 		return (readb(adev->rmmio + offset));
492 	BUG();
493 }
494 
495 /*
496  * MMIO register write with bytes helper functions
497  * @offset:bytes offset from MMIO start
498  * @value: the value want to be written to the register
499  *
500 */
501 /**
502  * amdgpu_mm_wreg8 - read a memory mapped IO register
503  *
504  * @adev: amdgpu_device pointer
505  * @offset: byte aligned register offset
506  * @value: 8 bit value to write
507  *
508  * Writes the value specified to the offset specified.
509  */
510 void amdgpu_mm_wreg8(struct amdgpu_device *adev, uint32_t offset, uint8_t value)
511 {
512 	if (amdgpu_device_skip_hw_access(adev))
513 		return;
514 
515 	if (offset < adev->rmmio_size)
516 		writeb(value, adev->rmmio + offset);
517 	else
518 		BUG();
519 }
520 
521 /**
522  * amdgpu_device_wreg - write to a memory mapped IO or indirect register
523  *
524  * @adev: amdgpu_device pointer
525  * @reg: dword aligned register offset
526  * @v: 32 bit value to write to the register
527  * @acc_flags: access flags which require special behavior
528  *
529  * Writes the value specified to the offset specified.
530  */
531 void amdgpu_device_wreg(struct amdgpu_device *adev,
532 			uint32_t reg, uint32_t v,
533 			uint32_t acc_flags)
534 {
535 	if (amdgpu_device_skip_hw_access(adev))
536 		return;
537 
538 	if ((reg * 4) < adev->rmmio_size) {
539 		if (!(acc_flags & AMDGPU_REGS_NO_KIQ) &&
540 		    amdgpu_sriov_runtime(adev) &&
541 		    down_read_trylock(&adev->reset_sem)) {
542 			amdgpu_kiq_wreg(adev, reg, v);
543 			up_read(&adev->reset_sem);
544 		} else {
545 			writel(v, ((void __iomem *)adev->rmmio) + (reg * 4));
546 		}
547 	} else {
548 		adev->pcie_wreg(adev, reg * 4, v);
549 	}
550 
551 	trace_amdgpu_device_wreg(adev->pdev->device, reg, v);
552 }
553 
554 /**
555  * amdgpu_mm_wreg_mmio_rlc -  write register either with direct/indirect mmio or with RLC path if in range
556  *
557  * this function is invoked only the debugfs register access
558  */
559 void amdgpu_mm_wreg_mmio_rlc(struct amdgpu_device *adev,
560 			     uint32_t reg, uint32_t v)
561 {
562 	if (amdgpu_device_skip_hw_access(adev))
563 		return;
564 
565 	if (amdgpu_sriov_fullaccess(adev) &&
566 	    adev->gfx.rlc.funcs &&
567 	    adev->gfx.rlc.funcs->is_rlcg_access_range) {
568 		if (adev->gfx.rlc.funcs->is_rlcg_access_range(adev, reg))
569 			return amdgpu_sriov_wreg(adev, reg, v, 0, 0);
570 	} else if ((reg * 4) >= adev->rmmio_size) {
571 		adev->pcie_wreg(adev, reg * 4, v);
572 	} else {
573 		writel(v, ((void __iomem *)adev->rmmio) + (reg * 4));
574 	}
575 }
576 
577 /**
578  * amdgpu_mm_rdoorbell - read a doorbell dword
579  *
580  * @adev: amdgpu_device pointer
581  * @index: doorbell index
582  *
583  * Returns the value in the doorbell aperture at the
584  * requested doorbell index (CIK).
585  */
586 u32 amdgpu_mm_rdoorbell(struct amdgpu_device *adev, u32 index)
587 {
588 	if (amdgpu_device_skip_hw_access(adev))
589 		return 0;
590 
591 	if (index < adev->doorbell.num_doorbells) {
592 		return readl(adev->doorbell.ptr + index);
593 	} else {
594 		DRM_ERROR("reading beyond doorbell aperture: 0x%08x!\n", index);
595 		return 0;
596 	}
597 }
598 
599 /**
600  * amdgpu_mm_wdoorbell - write a doorbell dword
601  *
602  * @adev: amdgpu_device pointer
603  * @index: doorbell index
604  * @v: value to write
605  *
606  * Writes @v to the doorbell aperture at the
607  * requested doorbell index (CIK).
608  */
609 void amdgpu_mm_wdoorbell(struct amdgpu_device *adev, u32 index, u32 v)
610 {
611 	if (amdgpu_device_skip_hw_access(adev))
612 		return;
613 
614 	if (index < adev->doorbell.num_doorbells) {
615 		writel(v, adev->doorbell.ptr + index);
616 	} else {
617 		DRM_ERROR("writing beyond doorbell aperture: 0x%08x!\n", index);
618 	}
619 }
620 
621 /**
622  * amdgpu_mm_rdoorbell64 - read a doorbell Qword
623  *
624  * @adev: amdgpu_device pointer
625  * @index: doorbell index
626  *
627  * Returns the value in the doorbell aperture at the
628  * requested doorbell index (VEGA10+).
629  */
630 u64 amdgpu_mm_rdoorbell64(struct amdgpu_device *adev, u32 index)
631 {
632 	if (amdgpu_device_skip_hw_access(adev))
633 		return 0;
634 
635 	if (index < adev->doorbell.num_doorbells) {
636 		return atomic64_read((atomic64_t *)(adev->doorbell.ptr + index));
637 	} else {
638 		DRM_ERROR("reading beyond doorbell aperture: 0x%08x!\n", index);
639 		return 0;
640 	}
641 }
642 
643 /**
644  * amdgpu_mm_wdoorbell64 - write a doorbell Qword
645  *
646  * @adev: amdgpu_device pointer
647  * @index: doorbell index
648  * @v: value to write
649  *
650  * Writes @v to the doorbell aperture at the
651  * requested doorbell index (VEGA10+).
652  */
653 void amdgpu_mm_wdoorbell64(struct amdgpu_device *adev, u32 index, u64 v)
654 {
655 	if (amdgpu_device_skip_hw_access(adev))
656 		return;
657 
658 	if (index < adev->doorbell.num_doorbells) {
659 		atomic64_set((atomic64_t *)(adev->doorbell.ptr + index), v);
660 	} else {
661 		DRM_ERROR("writing beyond doorbell aperture: 0x%08x!\n", index);
662 	}
663 }
664 
665 /**
666  * amdgpu_device_indirect_rreg - read an indirect register
667  *
668  * @adev: amdgpu_device pointer
669  * @pcie_index: mmio register offset
670  * @pcie_data: mmio register offset
671  * @reg_addr: indirect register address to read from
672  *
673  * Returns the value of indirect register @reg_addr
674  */
675 u32 amdgpu_device_indirect_rreg(struct amdgpu_device *adev,
676 				u32 pcie_index, u32 pcie_data,
677 				u32 reg_addr)
678 {
679 	unsigned long flags;
680 	u32 r;
681 	void __iomem *pcie_index_offset;
682 	void __iomem *pcie_data_offset;
683 
684 	spin_lock_irqsave(&adev->pcie_idx_lock, flags);
685 	pcie_index_offset = (void __iomem *)adev->rmmio + pcie_index * 4;
686 	pcie_data_offset = (void __iomem *)adev->rmmio + pcie_data * 4;
687 
688 	writel(reg_addr, pcie_index_offset);
689 	readl(pcie_index_offset);
690 	r = readl(pcie_data_offset);
691 	spin_unlock_irqrestore(&adev->pcie_idx_lock, flags);
692 
693 	return r;
694 }
695 
696 /**
697  * amdgpu_device_indirect_rreg64 - read a 64bits indirect register
698  *
699  * @adev: amdgpu_device pointer
700  * @pcie_index: mmio register offset
701  * @pcie_data: mmio register offset
702  * @reg_addr: indirect register address to read from
703  *
704  * Returns the value of indirect register @reg_addr
705  */
706 u64 amdgpu_device_indirect_rreg64(struct amdgpu_device *adev,
707 				  u32 pcie_index, u32 pcie_data,
708 				  u32 reg_addr)
709 {
710 	unsigned long flags;
711 	u64 r;
712 	void __iomem *pcie_index_offset;
713 	void __iomem *pcie_data_offset;
714 
715 	spin_lock_irqsave(&adev->pcie_idx_lock, flags);
716 	pcie_index_offset = (void __iomem *)adev->rmmio + pcie_index * 4;
717 	pcie_data_offset = (void __iomem *)adev->rmmio + pcie_data * 4;
718 
719 	/* read low 32 bits */
720 	writel(reg_addr, pcie_index_offset);
721 	readl(pcie_index_offset);
722 	r = readl(pcie_data_offset);
723 	/* read high 32 bits */
724 	writel(reg_addr + 4, pcie_index_offset);
725 	readl(pcie_index_offset);
726 	r |= ((u64)readl(pcie_data_offset) << 32);
727 	spin_unlock_irqrestore(&adev->pcie_idx_lock, flags);
728 
729 	return r;
730 }
731 
732 /**
733  * amdgpu_device_indirect_wreg - write an indirect register address
734  *
735  * @adev: amdgpu_device pointer
736  * @pcie_index: mmio register offset
737  * @pcie_data: mmio register offset
738  * @reg_addr: indirect register offset
739  * @reg_data: indirect register data
740  *
741  */
742 void amdgpu_device_indirect_wreg(struct amdgpu_device *adev,
743 				 u32 pcie_index, u32 pcie_data,
744 				 u32 reg_addr, u32 reg_data)
745 {
746 	unsigned long flags;
747 	void __iomem *pcie_index_offset;
748 	void __iomem *pcie_data_offset;
749 
750 	spin_lock_irqsave(&adev->pcie_idx_lock, flags);
751 	pcie_index_offset = (void __iomem *)adev->rmmio + pcie_index * 4;
752 	pcie_data_offset = (void __iomem *)adev->rmmio + pcie_data * 4;
753 
754 	writel(reg_addr, pcie_index_offset);
755 	readl(pcie_index_offset);
756 	writel(reg_data, pcie_data_offset);
757 	readl(pcie_data_offset);
758 	spin_unlock_irqrestore(&adev->pcie_idx_lock, flags);
759 }
760 
761 /**
762  * amdgpu_device_indirect_wreg64 - write a 64bits indirect register address
763  *
764  * @adev: amdgpu_device pointer
765  * @pcie_index: mmio register offset
766  * @pcie_data: mmio register offset
767  * @reg_addr: indirect register offset
768  * @reg_data: indirect register data
769  *
770  */
771 void amdgpu_device_indirect_wreg64(struct amdgpu_device *adev,
772 				   u32 pcie_index, u32 pcie_data,
773 				   u32 reg_addr, u64 reg_data)
774 {
775 	unsigned long flags;
776 	void __iomem *pcie_index_offset;
777 	void __iomem *pcie_data_offset;
778 
779 	spin_lock_irqsave(&adev->pcie_idx_lock, flags);
780 	pcie_index_offset = (void __iomem *)adev->rmmio + pcie_index * 4;
781 	pcie_data_offset = (void __iomem *)adev->rmmio + pcie_data * 4;
782 
783 	/* write low 32 bits */
784 	writel(reg_addr, pcie_index_offset);
785 	readl(pcie_index_offset);
786 	writel((u32)(reg_data & 0xffffffffULL), pcie_data_offset);
787 	readl(pcie_data_offset);
788 	/* write high 32 bits */
789 	writel(reg_addr + 4, pcie_index_offset);
790 	readl(pcie_index_offset);
791 	writel((u32)(reg_data >> 32), pcie_data_offset);
792 	readl(pcie_data_offset);
793 	spin_unlock_irqrestore(&adev->pcie_idx_lock, flags);
794 }
795 
796 /**
797  * amdgpu_invalid_rreg - dummy reg read function
798  *
799  * @adev: amdgpu_device pointer
800  * @reg: offset of register
801  *
802  * Dummy register read function.  Used for register blocks
803  * that certain asics don't have (all asics).
804  * Returns the value in the register.
805  */
806 static uint32_t amdgpu_invalid_rreg(struct amdgpu_device *adev, uint32_t reg)
807 {
808 	DRM_ERROR("Invalid callback to read register 0x%04X\n", reg);
809 	BUG();
810 	return 0;
811 }
812 
813 /**
814  * amdgpu_invalid_wreg - dummy reg write function
815  *
816  * @adev: amdgpu_device pointer
817  * @reg: offset of register
818  * @v: value to write to the register
819  *
820  * Dummy register read function.  Used for register blocks
821  * that certain asics don't have (all asics).
822  */
823 static void amdgpu_invalid_wreg(struct amdgpu_device *adev, uint32_t reg, uint32_t v)
824 {
825 	DRM_ERROR("Invalid callback to write register 0x%04X with 0x%08X\n",
826 		  reg, v);
827 	BUG();
828 }
829 
830 /**
831  * amdgpu_invalid_rreg64 - dummy 64 bit reg read function
832  *
833  * @adev: amdgpu_device pointer
834  * @reg: offset of register
835  *
836  * Dummy register read function.  Used for register blocks
837  * that certain asics don't have (all asics).
838  * Returns the value in the register.
839  */
840 static uint64_t amdgpu_invalid_rreg64(struct amdgpu_device *adev, uint32_t reg)
841 {
842 	DRM_ERROR("Invalid callback to read 64 bit register 0x%04X\n", reg);
843 	BUG();
844 	return 0;
845 }
846 
847 /**
848  * amdgpu_invalid_wreg64 - dummy reg write function
849  *
850  * @adev: amdgpu_device pointer
851  * @reg: offset of register
852  * @v: value to write to the register
853  *
854  * Dummy register read function.  Used for register blocks
855  * that certain asics don't have (all asics).
856  */
857 static void amdgpu_invalid_wreg64(struct amdgpu_device *adev, uint32_t reg, uint64_t v)
858 {
859 	DRM_ERROR("Invalid callback to write 64 bit register 0x%04X with 0x%08llX\n",
860 		  reg, v);
861 	BUG();
862 }
863 
864 /**
865  * amdgpu_block_invalid_rreg - dummy reg read function
866  *
867  * @adev: amdgpu_device pointer
868  * @block: offset of instance
869  * @reg: offset of register
870  *
871  * Dummy register read function.  Used for register blocks
872  * that certain asics don't have (all asics).
873  * Returns the value in the register.
874  */
875 static uint32_t amdgpu_block_invalid_rreg(struct amdgpu_device *adev,
876 					  uint32_t block, uint32_t reg)
877 {
878 	DRM_ERROR("Invalid callback to read register 0x%04X in block 0x%04X\n",
879 		  reg, block);
880 	BUG();
881 	return 0;
882 }
883 
884 /**
885  * amdgpu_block_invalid_wreg - dummy reg write function
886  *
887  * @adev: amdgpu_device pointer
888  * @block: offset of instance
889  * @reg: offset of register
890  * @v: value to write to the register
891  *
892  * Dummy register read function.  Used for register blocks
893  * that certain asics don't have (all asics).
894  */
895 static void amdgpu_block_invalid_wreg(struct amdgpu_device *adev,
896 				      uint32_t block,
897 				      uint32_t reg, uint32_t v)
898 {
899 	DRM_ERROR("Invalid block callback to write register 0x%04X in block 0x%04X with 0x%08X\n",
900 		  reg, block, v);
901 	BUG();
902 }
903 
904 /**
905  * amdgpu_device_asic_init - Wrapper for atom asic_init
906  *
907  * @adev: amdgpu_device pointer
908  *
909  * Does any asic specific work and then calls atom asic init.
910  */
911 static int amdgpu_device_asic_init(struct amdgpu_device *adev)
912 {
913 	amdgpu_asic_pre_asic_init(adev);
914 
915 	return amdgpu_atom_asic_init(adev->mode_info.atom_context);
916 }
917 
918 /**
919  * amdgpu_device_vram_scratch_init - allocate the VRAM scratch page
920  *
921  * @adev: amdgpu_device pointer
922  *
923  * Allocates a scratch page of VRAM for use by various things in the
924  * driver.
925  */
926 static int amdgpu_device_vram_scratch_init(struct amdgpu_device *adev)
927 {
928 	return amdgpu_bo_create_kernel(adev, AMDGPU_GPU_PAGE_SIZE,
929 				       PAGE_SIZE, AMDGPU_GEM_DOMAIN_VRAM,
930 				       &adev->vram_scratch.robj,
931 				       &adev->vram_scratch.gpu_addr,
932 				       (void **)&adev->vram_scratch.ptr);
933 }
934 
935 /**
936  * amdgpu_device_vram_scratch_fini - Free the VRAM scratch page
937  *
938  * @adev: amdgpu_device pointer
939  *
940  * Frees the VRAM scratch page.
941  */
942 static void amdgpu_device_vram_scratch_fini(struct amdgpu_device *adev)
943 {
944 	amdgpu_bo_free_kernel(&adev->vram_scratch.robj, NULL, NULL);
945 }
946 
947 /**
948  * amdgpu_device_program_register_sequence - program an array of registers.
949  *
950  * @adev: amdgpu_device pointer
951  * @registers: pointer to the register array
952  * @array_size: size of the register array
953  *
954  * Programs an array or registers with and and or masks.
955  * This is a helper for setting golden registers.
956  */
957 void amdgpu_device_program_register_sequence(struct amdgpu_device *adev,
958 					     const u32 *registers,
959 					     const u32 array_size)
960 {
961 	u32 tmp, reg, and_mask, or_mask;
962 	int i;
963 
964 	if (array_size % 3)
965 		return;
966 
967 	for (i = 0; i < array_size; i +=3) {
968 		reg = registers[i + 0];
969 		and_mask = registers[i + 1];
970 		or_mask = registers[i + 2];
971 
972 		if (and_mask == 0xffffffff) {
973 			tmp = or_mask;
974 		} else {
975 			tmp = RREG32(reg);
976 			tmp &= ~and_mask;
977 			if (adev->family >= AMDGPU_FAMILY_AI)
978 				tmp |= (or_mask & and_mask);
979 			else
980 				tmp |= or_mask;
981 		}
982 		WREG32(reg, tmp);
983 	}
984 }
985 
986 /**
987  * amdgpu_device_pci_config_reset - reset the GPU
988  *
989  * @adev: amdgpu_device pointer
990  *
991  * Resets the GPU using the pci config reset sequence.
992  * Only applicable to asics prior to vega10.
993  */
994 void amdgpu_device_pci_config_reset(struct amdgpu_device *adev)
995 {
996 	pci_write_config_dword(adev->pdev, 0x7c, AMDGPU_ASIC_RESET_DATA);
997 }
998 
999 /**
1000  * amdgpu_device_pci_reset - reset the GPU using generic PCI means
1001  *
1002  * @adev: amdgpu_device pointer
1003  *
1004  * Resets the GPU using generic pci reset interfaces (FLR, SBR, etc.).
1005  */
1006 int amdgpu_device_pci_reset(struct amdgpu_device *adev)
1007 {
1008 	return pci_reset_function(adev->pdev);
1009 }
1010 
1011 /*
1012  * GPU doorbell aperture helpers function.
1013  */
1014 /**
1015  * amdgpu_device_doorbell_init - Init doorbell driver information.
1016  *
1017  * @adev: amdgpu_device pointer
1018  *
1019  * Init doorbell driver information (CIK)
1020  * Returns 0 on success, error on failure.
1021  */
1022 static int amdgpu_device_doorbell_init(struct amdgpu_device *adev)
1023 {
1024 
1025 	/* No doorbell on SI hardware generation */
1026 	if (adev->asic_type < CHIP_BONAIRE) {
1027 		adev->doorbell.base = 0;
1028 		adev->doorbell.size = 0;
1029 		adev->doorbell.num_doorbells = 0;
1030 		adev->doorbell.ptr = NULL;
1031 		return 0;
1032 	}
1033 
1034 	if (pci_resource_flags(adev->pdev, 2) & IORESOURCE_UNSET)
1035 		return -EINVAL;
1036 
1037 	amdgpu_asic_init_doorbell_index(adev);
1038 
1039 	/* doorbell bar mapping */
1040 	adev->doorbell.base = pci_resource_start(adev->pdev, 2);
1041 	adev->doorbell.size = pci_resource_len(adev->pdev, 2);
1042 
1043 	adev->doorbell.num_doorbells = min_t(u32, adev->doorbell.size / sizeof(u32),
1044 					     adev->doorbell_index.max_assignment+1);
1045 	if (adev->doorbell.num_doorbells == 0)
1046 		return -EINVAL;
1047 
1048 	/* For Vega, reserve and map two pages on doorbell BAR since SDMA
1049 	 * paging queue doorbell use the second page. The
1050 	 * AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the
1051 	 * doorbells are in the first page. So with paging queue enabled,
1052 	 * the max num_doorbells should + 1 page (0x400 in dword)
1053 	 */
1054 	if (adev->asic_type >= CHIP_VEGA10)
1055 		adev->doorbell.num_doorbells += 0x400;
1056 
1057 	adev->doorbell.ptr = ioremap(adev->doorbell.base,
1058 				     adev->doorbell.num_doorbells *
1059 				     sizeof(u32));
1060 	if (adev->doorbell.ptr == NULL)
1061 		return -ENOMEM;
1062 
1063 	return 0;
1064 }
1065 
1066 /**
1067  * amdgpu_device_doorbell_fini - Tear down doorbell driver information.
1068  *
1069  * @adev: amdgpu_device pointer
1070  *
1071  * Tear down doorbell driver information (CIK)
1072  */
1073 static void amdgpu_device_doorbell_fini(struct amdgpu_device *adev)
1074 {
1075 	iounmap(adev->doorbell.ptr);
1076 	adev->doorbell.ptr = NULL;
1077 }
1078 
1079 
1080 
1081 /*
1082  * amdgpu_device_wb_*()
1083  * Writeback is the method by which the GPU updates special pages in memory
1084  * with the status of certain GPU events (fences, ring pointers,etc.).
1085  */
1086 
1087 /**
1088  * amdgpu_device_wb_fini - Disable Writeback and free memory
1089  *
1090  * @adev: amdgpu_device pointer
1091  *
1092  * Disables Writeback and frees the Writeback memory (all asics).
1093  * Used at driver shutdown.
1094  */
1095 static void amdgpu_device_wb_fini(struct amdgpu_device *adev)
1096 {
1097 	if (adev->wb.wb_obj) {
1098 		amdgpu_bo_free_kernel(&adev->wb.wb_obj,
1099 				      &adev->wb.gpu_addr,
1100 				      (void **)&adev->wb.wb);
1101 		adev->wb.wb_obj = NULL;
1102 	}
1103 }
1104 
1105 /**
1106  * amdgpu_device_wb_init - Init Writeback driver info and allocate memory
1107  *
1108  * @adev: amdgpu_device pointer
1109  *
1110  * Initializes writeback and allocates writeback memory (all asics).
1111  * Used at driver startup.
1112  * Returns 0 on success or an -error on failure.
1113  */
1114 static int amdgpu_device_wb_init(struct amdgpu_device *adev)
1115 {
1116 	int r;
1117 
1118 	if (adev->wb.wb_obj == NULL) {
1119 		/* AMDGPU_MAX_WB * sizeof(uint32_t) * 8 = AMDGPU_MAX_WB 256bit slots */
1120 		r = amdgpu_bo_create_kernel(adev, AMDGPU_MAX_WB * sizeof(uint32_t) * 8,
1121 					    PAGE_SIZE, AMDGPU_GEM_DOMAIN_GTT,
1122 					    &adev->wb.wb_obj, &adev->wb.gpu_addr,
1123 					    (void **)&adev->wb.wb);
1124 		if (r) {
1125 			dev_warn(adev->dev, "(%d) create WB bo failed\n", r);
1126 			return r;
1127 		}
1128 
1129 		adev->wb.num_wb = AMDGPU_MAX_WB;
1130 		memset(&adev->wb.used, 0, sizeof(adev->wb.used));
1131 
1132 		/* clear wb memory */
1133 		memset((char *)adev->wb.wb, 0, AMDGPU_MAX_WB * sizeof(uint32_t) * 8);
1134 	}
1135 
1136 	return 0;
1137 }
1138 
1139 /**
1140  * amdgpu_device_wb_get - Allocate a wb entry
1141  *
1142  * @adev: amdgpu_device pointer
1143  * @wb: wb index
1144  *
1145  * Allocate a wb slot for use by the driver (all asics).
1146  * Returns 0 on success or -EINVAL on failure.
1147  */
1148 int amdgpu_device_wb_get(struct amdgpu_device *adev, u32 *wb)
1149 {
1150 	unsigned long offset = find_first_zero_bit(adev->wb.used, adev->wb.num_wb);
1151 
1152 	if (offset < adev->wb.num_wb) {
1153 		__set_bit(offset, adev->wb.used);
1154 		*wb = offset << 3; /* convert to dw offset */
1155 		return 0;
1156 	} else {
1157 		return -EINVAL;
1158 	}
1159 }
1160 
1161 /**
1162  * amdgpu_device_wb_free - Free a wb entry
1163  *
1164  * @adev: amdgpu_device pointer
1165  * @wb: wb index
1166  *
1167  * Free a wb slot allocated for use by the driver (all asics)
1168  */
1169 void amdgpu_device_wb_free(struct amdgpu_device *adev, u32 wb)
1170 {
1171 	wb >>= 3;
1172 	if (wb < adev->wb.num_wb)
1173 		__clear_bit(wb, adev->wb.used);
1174 }
1175 
1176 /**
1177  * amdgpu_device_resize_fb_bar - try to resize FB BAR
1178  *
1179  * @adev: amdgpu_device pointer
1180  *
1181  * Try to resize FB BAR to make all VRAM CPU accessible. We try very hard not
1182  * to fail, but if any of the BARs is not accessible after the size we abort
1183  * driver loading by returning -ENODEV.
1184  */
1185 int amdgpu_device_resize_fb_bar(struct amdgpu_device *adev)
1186 {
1187 	int rbar_size = pci_rebar_bytes_to_size(adev->gmc.real_vram_size);
1188 	struct pci_bus *root;
1189 	struct resource *res;
1190 	unsigned i;
1191 	u16 cmd;
1192 	int r;
1193 
1194 	/* Bypass for VF */
1195 	if (amdgpu_sriov_vf(adev))
1196 		return 0;
1197 
1198 	/* skip if the bios has already enabled large BAR */
1199 	if (adev->gmc.real_vram_size &&
1200 	    (pci_resource_len(adev->pdev, 0) >= adev->gmc.real_vram_size))
1201 		return 0;
1202 
1203 	/* Check if the root BUS has 64bit memory resources */
1204 	root = adev->pdev->bus;
1205 	while (root->parent)
1206 		root = root->parent;
1207 
1208 	pci_bus_for_each_resource(root, res, i) {
1209 		if (res && res->flags & (IORESOURCE_MEM | IORESOURCE_MEM_64) &&
1210 		    res->start > 0x100000000ull)
1211 			break;
1212 	}
1213 
1214 	/* Trying to resize is pointless without a root hub window above 4GB */
1215 	if (!res)
1216 		return 0;
1217 
1218 	/* Limit the BAR size to what is available */
1219 	rbar_size = min(fls(pci_rebar_get_possible_sizes(adev->pdev, 0)) - 1,
1220 			rbar_size);
1221 
1222 	/* Disable memory decoding while we change the BAR addresses and size */
1223 	pci_read_config_word(adev->pdev, PCI_COMMAND, &cmd);
1224 	pci_write_config_word(adev->pdev, PCI_COMMAND,
1225 			      cmd & ~PCI_COMMAND_MEMORY);
1226 
1227 	/* Free the VRAM and doorbell BAR, we most likely need to move both. */
1228 	amdgpu_device_doorbell_fini(adev);
1229 	if (adev->asic_type >= CHIP_BONAIRE)
1230 		pci_release_resource(adev->pdev, 2);
1231 
1232 	pci_release_resource(adev->pdev, 0);
1233 
1234 	r = pci_resize_resource(adev->pdev, 0, rbar_size);
1235 	if (r == -ENOSPC)
1236 		DRM_INFO("Not enough PCI address space for a large BAR.");
1237 	else if (r && r != -ENOTSUPP)
1238 		DRM_ERROR("Problem resizing BAR0 (%d).", r);
1239 
1240 	pci_assign_unassigned_bus_resources(adev->pdev->bus);
1241 
1242 	/* When the doorbell or fb BAR isn't available we have no chance of
1243 	 * using the device.
1244 	 */
1245 	r = amdgpu_device_doorbell_init(adev);
1246 	if (r || (pci_resource_flags(adev->pdev, 0) & IORESOURCE_UNSET))
1247 		return -ENODEV;
1248 
1249 	pci_write_config_word(adev->pdev, PCI_COMMAND, cmd);
1250 
1251 	return 0;
1252 }
1253 
1254 /*
1255  * GPU helpers function.
1256  */
1257 /**
1258  * amdgpu_device_need_post - check if the hw need post or not
1259  *
1260  * @adev: amdgpu_device pointer
1261  *
1262  * Check if the asic has been initialized (all asics) at driver startup
1263  * or post is needed if  hw reset is performed.
1264  * Returns true if need or false if not.
1265  */
1266 bool amdgpu_device_need_post(struct amdgpu_device *adev)
1267 {
1268 	uint32_t reg;
1269 
1270 	if (amdgpu_sriov_vf(adev))
1271 		return false;
1272 
1273 	if (amdgpu_passthrough(adev)) {
1274 		/* for FIJI: In whole GPU pass-through virtualization case, after VM reboot
1275 		 * some old smc fw still need driver do vPost otherwise gpu hang, while
1276 		 * those smc fw version above 22.15 doesn't have this flaw, so we force
1277 		 * vpost executed for smc version below 22.15
1278 		 */
1279 		if (adev->asic_type == CHIP_FIJI) {
1280 			int err;
1281 			uint32_t fw_ver;
1282 			err = request_firmware(&adev->pm.fw, "amdgpu/fiji_smc.bin", adev->dev);
1283 			/* force vPost if error occured */
1284 			if (err)
1285 				return true;
1286 
1287 			fw_ver = *((uint32_t *)adev->pm.fw->data + 69);
1288 			if (fw_ver < 0x00160e00)
1289 				return true;
1290 		}
1291 	}
1292 
1293 	/* Don't post if we need to reset whole hive on init */
1294 	if (adev->gmc.xgmi.pending_reset)
1295 		return false;
1296 
1297 	if (adev->has_hw_reset) {
1298 		adev->has_hw_reset = false;
1299 		return true;
1300 	}
1301 
1302 	/* bios scratch used on CIK+ */
1303 	if (adev->asic_type >= CHIP_BONAIRE)
1304 		return amdgpu_atombios_scratch_need_asic_init(adev);
1305 
1306 	/* check MEM_SIZE for older asics */
1307 	reg = amdgpu_asic_get_config_memsize(adev);
1308 
1309 	if ((reg != 0) && (reg != 0xffffffff))
1310 		return false;
1311 
1312 	return true;
1313 }
1314 
1315 /* if we get transitioned to only one device, take VGA back */
1316 /**
1317  * amdgpu_device_vga_set_decode - enable/disable vga decode
1318  *
1319  * @pdev: PCI device pointer
1320  * @state: enable/disable vga decode
1321  *
1322  * Enable/disable vga decode (all asics).
1323  * Returns VGA resource flags.
1324  */
1325 static unsigned int amdgpu_device_vga_set_decode(struct pci_dev *pdev,
1326 		bool state)
1327 {
1328 	struct amdgpu_device *adev = drm_to_adev(pci_get_drvdata(pdev));
1329 	amdgpu_asic_set_vga_state(adev, state);
1330 	if (state)
1331 		return VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
1332 		       VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
1333 	else
1334 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
1335 }
1336 
1337 /**
1338  * amdgpu_device_check_block_size - validate the vm block size
1339  *
1340  * @adev: amdgpu_device pointer
1341  *
1342  * Validates the vm block size specified via module parameter.
1343  * The vm block size defines number of bits in page table versus page directory,
1344  * a page is 4KB so we have 12 bits offset, minimum 9 bits in the
1345  * page table and the remaining bits are in the page directory.
1346  */
1347 static void amdgpu_device_check_block_size(struct amdgpu_device *adev)
1348 {
1349 	/* defines number of bits in page table versus page directory,
1350 	 * a page is 4KB so we have 12 bits offset, minimum 9 bits in the
1351 	 * page table and the remaining bits are in the page directory */
1352 	if (amdgpu_vm_block_size == -1)
1353 		return;
1354 
1355 	if (amdgpu_vm_block_size < 9) {
1356 		dev_warn(adev->dev, "VM page table size (%d) too small\n",
1357 			 amdgpu_vm_block_size);
1358 		amdgpu_vm_block_size = -1;
1359 	}
1360 }
1361 
1362 /**
1363  * amdgpu_device_check_vm_size - validate the vm size
1364  *
1365  * @adev: amdgpu_device pointer
1366  *
1367  * Validates the vm size in GB specified via module parameter.
1368  * The VM size is the size of the GPU virtual memory space in GB.
1369  */
1370 static void amdgpu_device_check_vm_size(struct amdgpu_device *adev)
1371 {
1372 	/* no need to check the default value */
1373 	if (amdgpu_vm_size == -1)
1374 		return;
1375 
1376 	if (amdgpu_vm_size < 1) {
1377 		dev_warn(adev->dev, "VM size (%d) too small, min is 1GB\n",
1378 			 amdgpu_vm_size);
1379 		amdgpu_vm_size = -1;
1380 	}
1381 }
1382 
1383 static void amdgpu_device_check_smu_prv_buffer_size(struct amdgpu_device *adev)
1384 {
1385 	struct sysinfo si;
1386 	bool is_os_64 = (sizeof(void *) == 8);
1387 	uint64_t total_memory;
1388 	uint64_t dram_size_seven_GB = 0x1B8000000;
1389 	uint64_t dram_size_three_GB = 0xB8000000;
1390 
1391 	if (amdgpu_smu_memory_pool_size == 0)
1392 		return;
1393 
1394 	if (!is_os_64) {
1395 		DRM_WARN("Not 64-bit OS, feature not supported\n");
1396 		goto def_value;
1397 	}
1398 	si_meminfo(&si);
1399 	total_memory = (uint64_t)si.totalram * si.mem_unit;
1400 
1401 	if ((amdgpu_smu_memory_pool_size == 1) ||
1402 		(amdgpu_smu_memory_pool_size == 2)) {
1403 		if (total_memory < dram_size_three_GB)
1404 			goto def_value1;
1405 	} else if ((amdgpu_smu_memory_pool_size == 4) ||
1406 		(amdgpu_smu_memory_pool_size == 8)) {
1407 		if (total_memory < dram_size_seven_GB)
1408 			goto def_value1;
1409 	} else {
1410 		DRM_WARN("Smu memory pool size not supported\n");
1411 		goto def_value;
1412 	}
1413 	adev->pm.smu_prv_buffer_size = amdgpu_smu_memory_pool_size << 28;
1414 
1415 	return;
1416 
1417 def_value1:
1418 	DRM_WARN("No enough system memory\n");
1419 def_value:
1420 	adev->pm.smu_prv_buffer_size = 0;
1421 }
1422 
1423 static int amdgpu_device_init_apu_flags(struct amdgpu_device *adev)
1424 {
1425 	if (!(adev->flags & AMD_IS_APU) ||
1426 	    adev->asic_type < CHIP_RAVEN)
1427 		return 0;
1428 
1429 	switch (adev->asic_type) {
1430 	case CHIP_RAVEN:
1431 		if (adev->pdev->device == 0x15dd)
1432 			adev->apu_flags |= AMD_APU_IS_RAVEN;
1433 		if (adev->pdev->device == 0x15d8)
1434 			adev->apu_flags |= AMD_APU_IS_PICASSO;
1435 		break;
1436 	case CHIP_RENOIR:
1437 		if ((adev->pdev->device == 0x1636) ||
1438 		    (adev->pdev->device == 0x164c))
1439 			adev->apu_flags |= AMD_APU_IS_RENOIR;
1440 		else
1441 			adev->apu_flags |= AMD_APU_IS_GREEN_SARDINE;
1442 		break;
1443 	case CHIP_VANGOGH:
1444 		adev->apu_flags |= AMD_APU_IS_VANGOGH;
1445 		break;
1446 	case CHIP_YELLOW_CARP:
1447 		break;
1448 	case CHIP_CYAN_SKILLFISH:
1449 		if (adev->pdev->device == 0x13FE)
1450 			adev->apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2;
1451 		break;
1452 	default:
1453 		break;
1454 	}
1455 
1456 	return 0;
1457 }
1458 
1459 /**
1460  * amdgpu_device_check_arguments - validate module params
1461  *
1462  * @adev: amdgpu_device pointer
1463  *
1464  * Validates certain module parameters and updates
1465  * the associated values used by the driver (all asics).
1466  */
1467 static int amdgpu_device_check_arguments(struct amdgpu_device *adev)
1468 {
1469 	if (amdgpu_sched_jobs < 4) {
1470 		dev_warn(adev->dev, "sched jobs (%d) must be at least 4\n",
1471 			 amdgpu_sched_jobs);
1472 		amdgpu_sched_jobs = 4;
1473 	} else if (!is_power_of_2(amdgpu_sched_jobs)){
1474 		dev_warn(adev->dev, "sched jobs (%d) must be a power of 2\n",
1475 			 amdgpu_sched_jobs);
1476 		amdgpu_sched_jobs = roundup_pow_of_two(amdgpu_sched_jobs);
1477 	}
1478 
1479 	if (amdgpu_gart_size != -1 && amdgpu_gart_size < 32) {
1480 		/* gart size must be greater or equal to 32M */
1481 		dev_warn(adev->dev, "gart size (%d) too small\n",
1482 			 amdgpu_gart_size);
1483 		amdgpu_gart_size = -1;
1484 	}
1485 
1486 	if (amdgpu_gtt_size != -1 && amdgpu_gtt_size < 32) {
1487 		/* gtt size must be greater or equal to 32M */
1488 		dev_warn(adev->dev, "gtt size (%d) too small\n",
1489 				 amdgpu_gtt_size);
1490 		amdgpu_gtt_size = -1;
1491 	}
1492 
1493 	/* valid range is between 4 and 9 inclusive */
1494 	if (amdgpu_vm_fragment_size != -1 &&
1495 	    (amdgpu_vm_fragment_size > 9 || amdgpu_vm_fragment_size < 4)) {
1496 		dev_warn(adev->dev, "valid range is between 4 and 9\n");
1497 		amdgpu_vm_fragment_size = -1;
1498 	}
1499 
1500 	if (amdgpu_sched_hw_submission < 2) {
1501 		dev_warn(adev->dev, "sched hw submission jobs (%d) must be at least 2\n",
1502 			 amdgpu_sched_hw_submission);
1503 		amdgpu_sched_hw_submission = 2;
1504 	} else if (!is_power_of_2(amdgpu_sched_hw_submission)) {
1505 		dev_warn(adev->dev, "sched hw submission jobs (%d) must be a power of 2\n",
1506 			 amdgpu_sched_hw_submission);
1507 		amdgpu_sched_hw_submission = roundup_pow_of_two(amdgpu_sched_hw_submission);
1508 	}
1509 
1510 	amdgpu_device_check_smu_prv_buffer_size(adev);
1511 
1512 	amdgpu_device_check_vm_size(adev);
1513 
1514 	amdgpu_device_check_block_size(adev);
1515 
1516 	adev->firmware.load_type = amdgpu_ucode_get_load_type(adev, amdgpu_fw_load_type);
1517 
1518 	amdgpu_gmc_tmz_set(adev);
1519 
1520 	amdgpu_gmc_noretry_set(adev);
1521 
1522 	return 0;
1523 }
1524 
1525 /**
1526  * amdgpu_switcheroo_set_state - set switcheroo state
1527  *
1528  * @pdev: pci dev pointer
1529  * @state: vga_switcheroo state
1530  *
1531  * Callback for the switcheroo driver.  Suspends or resumes the
1532  * the asics before or after it is powered up using ACPI methods.
1533  */
1534 static void amdgpu_switcheroo_set_state(struct pci_dev *pdev,
1535 					enum vga_switcheroo_state state)
1536 {
1537 	struct drm_device *dev = pci_get_drvdata(pdev);
1538 	int r;
1539 
1540 	if (amdgpu_device_supports_px(dev) && state == VGA_SWITCHEROO_OFF)
1541 		return;
1542 
1543 	if (state == VGA_SWITCHEROO_ON) {
1544 		pr_info("switched on\n");
1545 		/* don't suspend or resume card normally */
1546 		dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
1547 
1548 		pci_set_power_state(pdev, PCI_D0);
1549 		amdgpu_device_load_pci_state(pdev);
1550 		r = pci_enable_device(pdev);
1551 		if (r)
1552 			DRM_WARN("pci_enable_device failed (%d)\n", r);
1553 		amdgpu_device_resume(dev, true);
1554 
1555 		dev->switch_power_state = DRM_SWITCH_POWER_ON;
1556 	} else {
1557 		pr_info("switched off\n");
1558 		dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
1559 		amdgpu_device_suspend(dev, true);
1560 		amdgpu_device_cache_pci_state(pdev);
1561 		/* Shut down the device */
1562 		pci_disable_device(pdev);
1563 		pci_set_power_state(pdev, PCI_D3cold);
1564 		dev->switch_power_state = DRM_SWITCH_POWER_OFF;
1565 	}
1566 }
1567 
1568 /**
1569  * amdgpu_switcheroo_can_switch - see if switcheroo state can change
1570  *
1571  * @pdev: pci dev pointer
1572  *
1573  * Callback for the switcheroo driver.  Check of the switcheroo
1574  * state can be changed.
1575  * Returns true if the state can be changed, false if not.
1576  */
1577 static bool amdgpu_switcheroo_can_switch(struct pci_dev *pdev)
1578 {
1579 	struct drm_device *dev = pci_get_drvdata(pdev);
1580 
1581 	/*
1582 	* FIXME: open_count is protected by drm_global_mutex but that would lead to
1583 	* locking inversion with the driver load path. And the access here is
1584 	* completely racy anyway. So don't bother with locking for now.
1585 	*/
1586 	return atomic_read(&dev->open_count) == 0;
1587 }
1588 
1589 static const struct vga_switcheroo_client_ops amdgpu_switcheroo_ops = {
1590 	.set_gpu_state = amdgpu_switcheroo_set_state,
1591 	.reprobe = NULL,
1592 	.can_switch = amdgpu_switcheroo_can_switch,
1593 };
1594 
1595 /**
1596  * amdgpu_device_ip_set_clockgating_state - set the CG state
1597  *
1598  * @dev: amdgpu_device pointer
1599  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1600  * @state: clockgating state (gate or ungate)
1601  *
1602  * Sets the requested clockgating state for all instances of
1603  * the hardware IP specified.
1604  * Returns the error code from the last instance.
1605  */
1606 int amdgpu_device_ip_set_clockgating_state(void *dev,
1607 					   enum amd_ip_block_type block_type,
1608 					   enum amd_clockgating_state state)
1609 {
1610 	struct amdgpu_device *adev = dev;
1611 	int i, r = 0;
1612 
1613 	for (i = 0; i < adev->num_ip_blocks; i++) {
1614 		if (!adev->ip_blocks[i].status.valid)
1615 			continue;
1616 		if (adev->ip_blocks[i].version->type != block_type)
1617 			continue;
1618 		if (!adev->ip_blocks[i].version->funcs->set_clockgating_state)
1619 			continue;
1620 		r = adev->ip_blocks[i].version->funcs->set_clockgating_state(
1621 			(void *)adev, state);
1622 		if (r)
1623 			DRM_ERROR("set_clockgating_state of IP block <%s> failed %d\n",
1624 				  adev->ip_blocks[i].version->funcs->name, r);
1625 	}
1626 	return r;
1627 }
1628 
1629 /**
1630  * amdgpu_device_ip_set_powergating_state - set the PG state
1631  *
1632  * @dev: amdgpu_device pointer
1633  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1634  * @state: powergating state (gate or ungate)
1635  *
1636  * Sets the requested powergating state for all instances of
1637  * the hardware IP specified.
1638  * Returns the error code from the last instance.
1639  */
1640 int amdgpu_device_ip_set_powergating_state(void *dev,
1641 					   enum amd_ip_block_type block_type,
1642 					   enum amd_powergating_state state)
1643 {
1644 	struct amdgpu_device *adev = dev;
1645 	int i, r = 0;
1646 
1647 	for (i = 0; i < adev->num_ip_blocks; i++) {
1648 		if (!adev->ip_blocks[i].status.valid)
1649 			continue;
1650 		if (adev->ip_blocks[i].version->type != block_type)
1651 			continue;
1652 		if (!adev->ip_blocks[i].version->funcs->set_powergating_state)
1653 			continue;
1654 		r = adev->ip_blocks[i].version->funcs->set_powergating_state(
1655 			(void *)adev, state);
1656 		if (r)
1657 			DRM_ERROR("set_powergating_state of IP block <%s> failed %d\n",
1658 				  adev->ip_blocks[i].version->funcs->name, r);
1659 	}
1660 	return r;
1661 }
1662 
1663 /**
1664  * amdgpu_device_ip_get_clockgating_state - get the CG state
1665  *
1666  * @adev: amdgpu_device pointer
1667  * @flags: clockgating feature flags
1668  *
1669  * Walks the list of IPs on the device and updates the clockgating
1670  * flags for each IP.
1671  * Updates @flags with the feature flags for each hardware IP where
1672  * clockgating is enabled.
1673  */
1674 void amdgpu_device_ip_get_clockgating_state(struct amdgpu_device *adev,
1675 					    u32 *flags)
1676 {
1677 	int i;
1678 
1679 	for (i = 0; i < adev->num_ip_blocks; i++) {
1680 		if (!adev->ip_blocks[i].status.valid)
1681 			continue;
1682 		if (adev->ip_blocks[i].version->funcs->get_clockgating_state)
1683 			adev->ip_blocks[i].version->funcs->get_clockgating_state((void *)adev, flags);
1684 	}
1685 }
1686 
1687 /**
1688  * amdgpu_device_ip_wait_for_idle - wait for idle
1689  *
1690  * @adev: amdgpu_device pointer
1691  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1692  *
1693  * Waits for the request hardware IP to be idle.
1694  * Returns 0 for success or a negative error code on failure.
1695  */
1696 int amdgpu_device_ip_wait_for_idle(struct amdgpu_device *adev,
1697 				   enum amd_ip_block_type block_type)
1698 {
1699 	int i, r;
1700 
1701 	for (i = 0; i < adev->num_ip_blocks; i++) {
1702 		if (!adev->ip_blocks[i].status.valid)
1703 			continue;
1704 		if (adev->ip_blocks[i].version->type == block_type) {
1705 			r = adev->ip_blocks[i].version->funcs->wait_for_idle((void *)adev);
1706 			if (r)
1707 				return r;
1708 			break;
1709 		}
1710 	}
1711 	return 0;
1712 
1713 }
1714 
1715 /**
1716  * amdgpu_device_ip_is_idle - is the hardware IP idle
1717  *
1718  * @adev: amdgpu_device pointer
1719  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1720  *
1721  * Check if the hardware IP is idle or not.
1722  * Returns true if it the IP is idle, false if not.
1723  */
1724 bool amdgpu_device_ip_is_idle(struct amdgpu_device *adev,
1725 			      enum amd_ip_block_type block_type)
1726 {
1727 	int i;
1728 
1729 	for (i = 0; i < adev->num_ip_blocks; i++) {
1730 		if (!adev->ip_blocks[i].status.valid)
1731 			continue;
1732 		if (adev->ip_blocks[i].version->type == block_type)
1733 			return adev->ip_blocks[i].version->funcs->is_idle((void *)adev);
1734 	}
1735 	return true;
1736 
1737 }
1738 
1739 /**
1740  * amdgpu_device_ip_get_ip_block - get a hw IP pointer
1741  *
1742  * @adev: amdgpu_device pointer
1743  * @type: Type of hardware IP (SMU, GFX, UVD, etc.)
1744  *
1745  * Returns a pointer to the hardware IP block structure
1746  * if it exists for the asic, otherwise NULL.
1747  */
1748 struct amdgpu_ip_block *
1749 amdgpu_device_ip_get_ip_block(struct amdgpu_device *adev,
1750 			      enum amd_ip_block_type type)
1751 {
1752 	int i;
1753 
1754 	for (i = 0; i < adev->num_ip_blocks; i++)
1755 		if (adev->ip_blocks[i].version->type == type)
1756 			return &adev->ip_blocks[i];
1757 
1758 	return NULL;
1759 }
1760 
1761 /**
1762  * amdgpu_device_ip_block_version_cmp
1763  *
1764  * @adev: amdgpu_device pointer
1765  * @type: enum amd_ip_block_type
1766  * @major: major version
1767  * @minor: minor version
1768  *
1769  * return 0 if equal or greater
1770  * return 1 if smaller or the ip_block doesn't exist
1771  */
1772 int amdgpu_device_ip_block_version_cmp(struct amdgpu_device *adev,
1773 				       enum amd_ip_block_type type,
1774 				       u32 major, u32 minor)
1775 {
1776 	struct amdgpu_ip_block *ip_block = amdgpu_device_ip_get_ip_block(adev, type);
1777 
1778 	if (ip_block && ((ip_block->version->major > major) ||
1779 			((ip_block->version->major == major) &&
1780 			(ip_block->version->minor >= minor))))
1781 		return 0;
1782 
1783 	return 1;
1784 }
1785 
1786 /**
1787  * amdgpu_device_ip_block_add
1788  *
1789  * @adev: amdgpu_device pointer
1790  * @ip_block_version: pointer to the IP to add
1791  *
1792  * Adds the IP block driver information to the collection of IPs
1793  * on the asic.
1794  */
1795 int amdgpu_device_ip_block_add(struct amdgpu_device *adev,
1796 			       const struct amdgpu_ip_block_version *ip_block_version)
1797 {
1798 	if (!ip_block_version)
1799 		return -EINVAL;
1800 
1801 	switch (ip_block_version->type) {
1802 	case AMD_IP_BLOCK_TYPE_VCN:
1803 		if (adev->harvest_ip_mask & AMD_HARVEST_IP_VCN_MASK)
1804 			return 0;
1805 		break;
1806 	case AMD_IP_BLOCK_TYPE_JPEG:
1807 		if (adev->harvest_ip_mask & AMD_HARVEST_IP_JPEG_MASK)
1808 			return 0;
1809 		break;
1810 	default:
1811 		break;
1812 	}
1813 
1814 	DRM_INFO("add ip block number %d <%s>\n", adev->num_ip_blocks,
1815 		  ip_block_version->funcs->name);
1816 
1817 	adev->ip_blocks[adev->num_ip_blocks++].version = ip_block_version;
1818 
1819 	return 0;
1820 }
1821 
1822 /**
1823  * amdgpu_device_enable_virtual_display - enable virtual display feature
1824  *
1825  * @adev: amdgpu_device pointer
1826  *
1827  * Enabled the virtual display feature if the user has enabled it via
1828  * the module parameter virtual_display.  This feature provides a virtual
1829  * display hardware on headless boards or in virtualized environments.
1830  * This function parses and validates the configuration string specified by
1831  * the user and configues the virtual display configuration (number of
1832  * virtual connectors, crtcs, etc.) specified.
1833  */
1834 static void amdgpu_device_enable_virtual_display(struct amdgpu_device *adev)
1835 {
1836 	adev->enable_virtual_display = false;
1837 
1838 	if (amdgpu_virtual_display) {
1839 		const char *pci_address_name = pci_name(adev->pdev);
1840 		char *pciaddstr, *pciaddstr_tmp, *pciaddname_tmp, *pciaddname;
1841 
1842 		pciaddstr = kstrdup(amdgpu_virtual_display, GFP_KERNEL);
1843 		pciaddstr_tmp = pciaddstr;
1844 		while ((pciaddname_tmp = strsep(&pciaddstr_tmp, ";"))) {
1845 			pciaddname = strsep(&pciaddname_tmp, ",");
1846 			if (!strcmp("all", pciaddname)
1847 			    || !strcmp(pci_address_name, pciaddname)) {
1848 				long num_crtc;
1849 				int res = -1;
1850 
1851 				adev->enable_virtual_display = true;
1852 
1853 				if (pciaddname_tmp)
1854 					res = kstrtol(pciaddname_tmp, 10,
1855 						      &num_crtc);
1856 
1857 				if (!res) {
1858 					if (num_crtc < 1)
1859 						num_crtc = 1;
1860 					if (num_crtc > 6)
1861 						num_crtc = 6;
1862 					adev->mode_info.num_crtc = num_crtc;
1863 				} else {
1864 					adev->mode_info.num_crtc = 1;
1865 				}
1866 				break;
1867 			}
1868 		}
1869 
1870 		DRM_INFO("virtual display string:%s, %s:virtual_display:%d, num_crtc:%d\n",
1871 			 amdgpu_virtual_display, pci_address_name,
1872 			 adev->enable_virtual_display, adev->mode_info.num_crtc);
1873 
1874 		kfree(pciaddstr);
1875 	}
1876 }
1877 
1878 /**
1879  * amdgpu_device_parse_gpu_info_fw - parse gpu info firmware
1880  *
1881  * @adev: amdgpu_device pointer
1882  *
1883  * Parses the asic configuration parameters specified in the gpu info
1884  * firmware and makes them availale to the driver for use in configuring
1885  * the asic.
1886  * Returns 0 on success, -EINVAL on failure.
1887  */
1888 static int amdgpu_device_parse_gpu_info_fw(struct amdgpu_device *adev)
1889 {
1890 	const char *chip_name;
1891 	char fw_name[40];
1892 	int err;
1893 	const struct gpu_info_firmware_header_v1_0 *hdr;
1894 
1895 	adev->firmware.gpu_info_fw = NULL;
1896 
1897 	if (adev->mman.discovery_bin) {
1898 		amdgpu_discovery_get_gfx_info(adev);
1899 
1900 		/*
1901 		 * FIXME: The bounding box is still needed by Navi12, so
1902 		 * temporarily read it from gpu_info firmware. Should be droped
1903 		 * when DAL no longer needs it.
1904 		 */
1905 		if (adev->asic_type != CHIP_NAVI12)
1906 			return 0;
1907 	}
1908 
1909 	switch (adev->asic_type) {
1910 #ifdef CONFIG_DRM_AMDGPU_SI
1911 	case CHIP_VERDE:
1912 	case CHIP_TAHITI:
1913 	case CHIP_PITCAIRN:
1914 	case CHIP_OLAND:
1915 	case CHIP_HAINAN:
1916 #endif
1917 #ifdef CONFIG_DRM_AMDGPU_CIK
1918 	case CHIP_BONAIRE:
1919 	case CHIP_HAWAII:
1920 	case CHIP_KAVERI:
1921 	case CHIP_KABINI:
1922 	case CHIP_MULLINS:
1923 #endif
1924 	case CHIP_TOPAZ:
1925 	case CHIP_TONGA:
1926 	case CHIP_FIJI:
1927 	case CHIP_POLARIS10:
1928 	case CHIP_POLARIS11:
1929 	case CHIP_POLARIS12:
1930 	case CHIP_VEGAM:
1931 	case CHIP_CARRIZO:
1932 	case CHIP_STONEY:
1933 	case CHIP_VEGA20:
1934 	case CHIP_ALDEBARAN:
1935 	case CHIP_SIENNA_CICHLID:
1936 	case CHIP_NAVY_FLOUNDER:
1937 	case CHIP_DIMGREY_CAVEFISH:
1938 	case CHIP_BEIGE_GOBY:
1939 	default:
1940 		return 0;
1941 	case CHIP_VEGA10:
1942 		chip_name = "vega10";
1943 		break;
1944 	case CHIP_VEGA12:
1945 		chip_name = "vega12";
1946 		break;
1947 	case CHIP_RAVEN:
1948 		if (adev->apu_flags & AMD_APU_IS_RAVEN2)
1949 			chip_name = "raven2";
1950 		else if (adev->apu_flags & AMD_APU_IS_PICASSO)
1951 			chip_name = "picasso";
1952 		else
1953 			chip_name = "raven";
1954 		break;
1955 	case CHIP_ARCTURUS:
1956 		chip_name = "arcturus";
1957 		break;
1958 	case CHIP_RENOIR:
1959 		if (adev->apu_flags & AMD_APU_IS_RENOIR)
1960 			chip_name = "renoir";
1961 		else
1962 			chip_name = "green_sardine";
1963 		break;
1964 	case CHIP_NAVI10:
1965 		chip_name = "navi10";
1966 		break;
1967 	case CHIP_NAVI14:
1968 		chip_name = "navi14";
1969 		break;
1970 	case CHIP_NAVI12:
1971 		chip_name = "navi12";
1972 		break;
1973 	case CHIP_VANGOGH:
1974 		chip_name = "vangogh";
1975 		break;
1976 	case CHIP_YELLOW_CARP:
1977 		chip_name = "yellow_carp";
1978 		break;
1979 	}
1980 
1981 	snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_gpu_info.bin", chip_name);
1982 	err = request_firmware(&adev->firmware.gpu_info_fw, fw_name, adev->dev);
1983 	if (err) {
1984 		dev_err(adev->dev,
1985 			"Failed to load gpu_info firmware \"%s\"\n",
1986 			fw_name);
1987 		goto out;
1988 	}
1989 	err = amdgpu_ucode_validate(adev->firmware.gpu_info_fw);
1990 	if (err) {
1991 		dev_err(adev->dev,
1992 			"Failed to validate gpu_info firmware \"%s\"\n",
1993 			fw_name);
1994 		goto out;
1995 	}
1996 
1997 	hdr = (const struct gpu_info_firmware_header_v1_0 *)adev->firmware.gpu_info_fw->data;
1998 	amdgpu_ucode_print_gpu_info_hdr(&hdr->header);
1999 
2000 	switch (hdr->version_major) {
2001 	case 1:
2002 	{
2003 		const struct gpu_info_firmware_v1_0 *gpu_info_fw =
2004 			(const struct gpu_info_firmware_v1_0 *)(adev->firmware.gpu_info_fw->data +
2005 								le32_to_cpu(hdr->header.ucode_array_offset_bytes));
2006 
2007 		/*
2008 		 * Should be droped when DAL no longer needs it.
2009 		 */
2010 		if (adev->asic_type == CHIP_NAVI12)
2011 			goto parse_soc_bounding_box;
2012 
2013 		adev->gfx.config.max_shader_engines = le32_to_cpu(gpu_info_fw->gc_num_se);
2014 		adev->gfx.config.max_cu_per_sh = le32_to_cpu(gpu_info_fw->gc_num_cu_per_sh);
2015 		adev->gfx.config.max_sh_per_se = le32_to_cpu(gpu_info_fw->gc_num_sh_per_se);
2016 		adev->gfx.config.max_backends_per_se = le32_to_cpu(gpu_info_fw->gc_num_rb_per_se);
2017 		adev->gfx.config.max_texture_channel_caches =
2018 			le32_to_cpu(gpu_info_fw->gc_num_tccs);
2019 		adev->gfx.config.max_gprs = le32_to_cpu(gpu_info_fw->gc_num_gprs);
2020 		adev->gfx.config.max_gs_threads = le32_to_cpu(gpu_info_fw->gc_num_max_gs_thds);
2021 		adev->gfx.config.gs_vgt_table_depth = le32_to_cpu(gpu_info_fw->gc_gs_table_depth);
2022 		adev->gfx.config.gs_prim_buffer_depth = le32_to_cpu(gpu_info_fw->gc_gsprim_buff_depth);
2023 		adev->gfx.config.double_offchip_lds_buf =
2024 			le32_to_cpu(gpu_info_fw->gc_double_offchip_lds_buffer);
2025 		adev->gfx.cu_info.wave_front_size = le32_to_cpu(gpu_info_fw->gc_wave_size);
2026 		adev->gfx.cu_info.max_waves_per_simd =
2027 			le32_to_cpu(gpu_info_fw->gc_max_waves_per_simd);
2028 		adev->gfx.cu_info.max_scratch_slots_per_cu =
2029 			le32_to_cpu(gpu_info_fw->gc_max_scratch_slots_per_cu);
2030 		adev->gfx.cu_info.lds_size = le32_to_cpu(gpu_info_fw->gc_lds_size);
2031 		if (hdr->version_minor >= 1) {
2032 			const struct gpu_info_firmware_v1_1 *gpu_info_fw =
2033 				(const struct gpu_info_firmware_v1_1 *)(adev->firmware.gpu_info_fw->data +
2034 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
2035 			adev->gfx.config.num_sc_per_sh =
2036 				le32_to_cpu(gpu_info_fw->num_sc_per_sh);
2037 			adev->gfx.config.num_packer_per_sc =
2038 				le32_to_cpu(gpu_info_fw->num_packer_per_sc);
2039 		}
2040 
2041 parse_soc_bounding_box:
2042 		/*
2043 		 * soc bounding box info is not integrated in disocovery table,
2044 		 * we always need to parse it from gpu info firmware if needed.
2045 		 */
2046 		if (hdr->version_minor == 2) {
2047 			const struct gpu_info_firmware_v1_2 *gpu_info_fw =
2048 				(const struct gpu_info_firmware_v1_2 *)(adev->firmware.gpu_info_fw->data +
2049 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
2050 			adev->dm.soc_bounding_box = &gpu_info_fw->soc_bounding_box;
2051 		}
2052 		break;
2053 	}
2054 	default:
2055 		dev_err(adev->dev,
2056 			"Unsupported gpu_info table %d\n", hdr->header.ucode_version);
2057 		err = -EINVAL;
2058 		goto out;
2059 	}
2060 out:
2061 	return err;
2062 }
2063 
2064 /**
2065  * amdgpu_device_ip_early_init - run early init for hardware IPs
2066  *
2067  * @adev: amdgpu_device pointer
2068  *
2069  * Early initialization pass for hardware IPs.  The hardware IPs that make
2070  * up each asic are discovered each IP's early_init callback is run.  This
2071  * is the first stage in initializing the asic.
2072  * Returns 0 on success, negative error code on failure.
2073  */
2074 static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
2075 {
2076 	struct drm_device *dev = adev_to_drm(adev);
2077 	struct pci_dev *parent;
2078 	int i, r;
2079 
2080 	amdgpu_device_enable_virtual_display(adev);
2081 
2082 	if (amdgpu_sriov_vf(adev)) {
2083 		r = amdgpu_virt_request_full_gpu(adev, true);
2084 		if (r)
2085 			return r;
2086 	}
2087 
2088 	switch (adev->asic_type) {
2089 #ifdef CONFIG_DRM_AMDGPU_SI
2090 	case CHIP_VERDE:
2091 	case CHIP_TAHITI:
2092 	case CHIP_PITCAIRN:
2093 	case CHIP_OLAND:
2094 	case CHIP_HAINAN:
2095 		adev->family = AMDGPU_FAMILY_SI;
2096 		r = si_set_ip_blocks(adev);
2097 		if (r)
2098 			return r;
2099 		break;
2100 #endif
2101 #ifdef CONFIG_DRM_AMDGPU_CIK
2102 	case CHIP_BONAIRE:
2103 	case CHIP_HAWAII:
2104 	case CHIP_KAVERI:
2105 	case CHIP_KABINI:
2106 	case CHIP_MULLINS:
2107 		if (adev->flags & AMD_IS_APU)
2108 			adev->family = AMDGPU_FAMILY_KV;
2109 		else
2110 			adev->family = AMDGPU_FAMILY_CI;
2111 
2112 		r = cik_set_ip_blocks(adev);
2113 		if (r)
2114 			return r;
2115 		break;
2116 #endif
2117 	case CHIP_TOPAZ:
2118 	case CHIP_TONGA:
2119 	case CHIP_FIJI:
2120 	case CHIP_POLARIS10:
2121 	case CHIP_POLARIS11:
2122 	case CHIP_POLARIS12:
2123 	case CHIP_VEGAM:
2124 	case CHIP_CARRIZO:
2125 	case CHIP_STONEY:
2126 		if (adev->flags & AMD_IS_APU)
2127 			adev->family = AMDGPU_FAMILY_CZ;
2128 		else
2129 			adev->family = AMDGPU_FAMILY_VI;
2130 
2131 		r = vi_set_ip_blocks(adev);
2132 		if (r)
2133 			return r;
2134 		break;
2135 	default:
2136 		r = amdgpu_discovery_set_ip_blocks(adev);
2137 		if (r)
2138 			return r;
2139 		break;
2140 	}
2141 
2142 	if (amdgpu_has_atpx() &&
2143 	    (amdgpu_is_atpx_hybrid() ||
2144 	     amdgpu_has_atpx_dgpu_power_cntl()) &&
2145 	    ((adev->flags & AMD_IS_APU) == 0) &&
2146 	    !pci_is_thunderbolt_attached(to_pci_dev(dev->dev)))
2147 		adev->flags |= AMD_IS_PX;
2148 
2149 	parent = pci_upstream_bridge(adev->pdev);
2150 	adev->has_pr3 = parent ? pci_pr3_present(parent) : false;
2151 
2152 	amdgpu_amdkfd_device_probe(adev);
2153 
2154 	adev->pm.pp_feature = amdgpu_pp_feature_mask;
2155 	if (amdgpu_sriov_vf(adev) || sched_policy == KFD_SCHED_POLICY_NO_HWS)
2156 		adev->pm.pp_feature &= ~PP_GFXOFF_MASK;
2157 	if (amdgpu_sriov_vf(adev) && adev->asic_type == CHIP_SIENNA_CICHLID)
2158 		adev->pm.pp_feature &= ~PP_OVERDRIVE_MASK;
2159 
2160 	for (i = 0; i < adev->num_ip_blocks; i++) {
2161 		if ((amdgpu_ip_block_mask & (1 << i)) == 0) {
2162 			DRM_ERROR("disabled ip block: %d <%s>\n",
2163 				  i, adev->ip_blocks[i].version->funcs->name);
2164 			adev->ip_blocks[i].status.valid = false;
2165 		} else {
2166 			if (adev->ip_blocks[i].version->funcs->early_init) {
2167 				r = adev->ip_blocks[i].version->funcs->early_init((void *)adev);
2168 				if (r == -ENOENT) {
2169 					adev->ip_blocks[i].status.valid = false;
2170 				} else if (r) {
2171 					DRM_ERROR("early_init of IP block <%s> failed %d\n",
2172 						  adev->ip_blocks[i].version->funcs->name, r);
2173 					return r;
2174 				} else {
2175 					adev->ip_blocks[i].status.valid = true;
2176 				}
2177 			} else {
2178 				adev->ip_blocks[i].status.valid = true;
2179 			}
2180 		}
2181 		/* get the vbios after the asic_funcs are set up */
2182 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON) {
2183 			r = amdgpu_device_parse_gpu_info_fw(adev);
2184 			if (r)
2185 				return r;
2186 
2187 			/* Read BIOS */
2188 			if (!amdgpu_get_bios(adev))
2189 				return -EINVAL;
2190 
2191 			r = amdgpu_atombios_init(adev);
2192 			if (r) {
2193 				dev_err(adev->dev, "amdgpu_atombios_init failed\n");
2194 				amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_INIT_FAIL, 0, 0);
2195 				return r;
2196 			}
2197 
2198 			/*get pf2vf msg info at it's earliest time*/
2199 			if (amdgpu_sriov_vf(adev))
2200 				amdgpu_virt_init_data_exchange(adev);
2201 
2202 		}
2203 	}
2204 
2205 	adev->cg_flags &= amdgpu_cg_mask;
2206 	adev->pg_flags &= amdgpu_pg_mask;
2207 
2208 	return 0;
2209 }
2210 
2211 static int amdgpu_device_ip_hw_init_phase1(struct amdgpu_device *adev)
2212 {
2213 	int i, r;
2214 
2215 	for (i = 0; i < adev->num_ip_blocks; i++) {
2216 		if (!adev->ip_blocks[i].status.sw)
2217 			continue;
2218 		if (adev->ip_blocks[i].status.hw)
2219 			continue;
2220 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2221 		    (amdgpu_sriov_vf(adev) && (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)) ||
2222 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
2223 			r = adev->ip_blocks[i].version->funcs->hw_init(adev);
2224 			if (r) {
2225 				DRM_ERROR("hw_init of IP block <%s> failed %d\n",
2226 					  adev->ip_blocks[i].version->funcs->name, r);
2227 				return r;
2228 			}
2229 			adev->ip_blocks[i].status.hw = true;
2230 		}
2231 	}
2232 
2233 	return 0;
2234 }
2235 
2236 static int amdgpu_device_ip_hw_init_phase2(struct amdgpu_device *adev)
2237 {
2238 	int i, r;
2239 
2240 	for (i = 0; i < adev->num_ip_blocks; i++) {
2241 		if (!adev->ip_blocks[i].status.sw)
2242 			continue;
2243 		if (adev->ip_blocks[i].status.hw)
2244 			continue;
2245 		r = adev->ip_blocks[i].version->funcs->hw_init(adev);
2246 		if (r) {
2247 			DRM_ERROR("hw_init of IP block <%s> failed %d\n",
2248 				  adev->ip_blocks[i].version->funcs->name, r);
2249 			return r;
2250 		}
2251 		adev->ip_blocks[i].status.hw = true;
2252 	}
2253 
2254 	return 0;
2255 }
2256 
2257 static int amdgpu_device_fw_loading(struct amdgpu_device *adev)
2258 {
2259 	int r = 0;
2260 	int i;
2261 	uint32_t smu_version;
2262 
2263 	if (adev->asic_type >= CHIP_VEGA10) {
2264 		for (i = 0; i < adev->num_ip_blocks; i++) {
2265 			if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_PSP)
2266 				continue;
2267 
2268 			if (!adev->ip_blocks[i].status.sw)
2269 				continue;
2270 
2271 			/* no need to do the fw loading again if already done*/
2272 			if (adev->ip_blocks[i].status.hw == true)
2273 				break;
2274 
2275 			if (amdgpu_in_reset(adev) || adev->in_suspend) {
2276 				r = adev->ip_blocks[i].version->funcs->resume(adev);
2277 				if (r) {
2278 					DRM_ERROR("resume of IP block <%s> failed %d\n",
2279 							  adev->ip_blocks[i].version->funcs->name, r);
2280 					return r;
2281 				}
2282 			} else {
2283 				r = adev->ip_blocks[i].version->funcs->hw_init(adev);
2284 				if (r) {
2285 					DRM_ERROR("hw_init of IP block <%s> failed %d\n",
2286 							  adev->ip_blocks[i].version->funcs->name, r);
2287 					return r;
2288 				}
2289 			}
2290 
2291 			adev->ip_blocks[i].status.hw = true;
2292 			break;
2293 		}
2294 	}
2295 
2296 	if (!amdgpu_sriov_vf(adev) || adev->asic_type == CHIP_TONGA)
2297 		r = amdgpu_pm_load_smu_firmware(adev, &smu_version);
2298 
2299 	return r;
2300 }
2301 
2302 /**
2303  * amdgpu_device_ip_init - run init for hardware IPs
2304  *
2305  * @adev: amdgpu_device pointer
2306  *
2307  * Main initialization pass for hardware IPs.  The list of all the hardware
2308  * IPs that make up the asic is walked and the sw_init and hw_init callbacks
2309  * are run.  sw_init initializes the software state associated with each IP
2310  * and hw_init initializes the hardware associated with each IP.
2311  * Returns 0 on success, negative error code on failure.
2312  */
2313 static int amdgpu_device_ip_init(struct amdgpu_device *adev)
2314 {
2315 	int i, r;
2316 
2317 	r = amdgpu_ras_init(adev);
2318 	if (r)
2319 		return r;
2320 
2321 	for (i = 0; i < adev->num_ip_blocks; i++) {
2322 		if (!adev->ip_blocks[i].status.valid)
2323 			continue;
2324 		r = adev->ip_blocks[i].version->funcs->sw_init((void *)adev);
2325 		if (r) {
2326 			DRM_ERROR("sw_init of IP block <%s> failed %d\n",
2327 				  adev->ip_blocks[i].version->funcs->name, r);
2328 			goto init_failed;
2329 		}
2330 		adev->ip_blocks[i].status.sw = true;
2331 
2332 		/* need to do gmc hw init early so we can allocate gpu mem */
2333 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
2334 			/* Try to reserve bad pages early */
2335 			if (amdgpu_sriov_vf(adev))
2336 				amdgpu_virt_exchange_data(adev);
2337 
2338 			r = amdgpu_device_vram_scratch_init(adev);
2339 			if (r) {
2340 				DRM_ERROR("amdgpu_vram_scratch_init failed %d\n", r);
2341 				goto init_failed;
2342 			}
2343 			r = adev->ip_blocks[i].version->funcs->hw_init((void *)adev);
2344 			if (r) {
2345 				DRM_ERROR("hw_init %d failed %d\n", i, r);
2346 				goto init_failed;
2347 			}
2348 			r = amdgpu_device_wb_init(adev);
2349 			if (r) {
2350 				DRM_ERROR("amdgpu_device_wb_init failed %d\n", r);
2351 				goto init_failed;
2352 			}
2353 			adev->ip_blocks[i].status.hw = true;
2354 
2355 			/* right after GMC hw init, we create CSA */
2356 			if (amdgpu_mcbp || amdgpu_sriov_vf(adev)) {
2357 				r = amdgpu_allocate_static_csa(adev, &adev->virt.csa_obj,
2358 								AMDGPU_GEM_DOMAIN_VRAM,
2359 								AMDGPU_CSA_SIZE);
2360 				if (r) {
2361 					DRM_ERROR("allocate CSA failed %d\n", r);
2362 					goto init_failed;
2363 				}
2364 			}
2365 		}
2366 	}
2367 
2368 	if (amdgpu_sriov_vf(adev))
2369 		amdgpu_virt_init_data_exchange(adev);
2370 
2371 	r = amdgpu_ib_pool_init(adev);
2372 	if (r) {
2373 		dev_err(adev->dev, "IB initialization failed (%d).\n", r);
2374 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_IB_INIT_FAIL, 0, r);
2375 		goto init_failed;
2376 	}
2377 
2378 	r = amdgpu_ucode_create_bo(adev); /* create ucode bo when sw_init complete*/
2379 	if (r)
2380 		goto init_failed;
2381 
2382 	r = amdgpu_device_ip_hw_init_phase1(adev);
2383 	if (r)
2384 		goto init_failed;
2385 
2386 	r = amdgpu_device_fw_loading(adev);
2387 	if (r)
2388 		goto init_failed;
2389 
2390 	r = amdgpu_device_ip_hw_init_phase2(adev);
2391 	if (r)
2392 		goto init_failed;
2393 
2394 	/*
2395 	 * retired pages will be loaded from eeprom and reserved here,
2396 	 * it should be called after amdgpu_device_ip_hw_init_phase2  since
2397 	 * for some ASICs the RAS EEPROM code relies on SMU fully functioning
2398 	 * for I2C communication which only true at this point.
2399 	 *
2400 	 * amdgpu_ras_recovery_init may fail, but the upper only cares the
2401 	 * failure from bad gpu situation and stop amdgpu init process
2402 	 * accordingly. For other failed cases, it will still release all
2403 	 * the resource and print error message, rather than returning one
2404 	 * negative value to upper level.
2405 	 *
2406 	 * Note: theoretically, this should be called before all vram allocations
2407 	 * to protect retired page from abusing
2408 	 */
2409 	r = amdgpu_ras_recovery_init(adev);
2410 	if (r)
2411 		goto init_failed;
2412 
2413 	if (adev->gmc.xgmi.num_physical_nodes > 1)
2414 		amdgpu_xgmi_add_device(adev);
2415 
2416 	/* Don't init kfd if whole hive need to be reset during init */
2417 	if (!adev->gmc.xgmi.pending_reset)
2418 		amdgpu_amdkfd_device_init(adev);
2419 
2420 	amdgpu_fru_get_product_info(adev);
2421 
2422 init_failed:
2423 	if (amdgpu_sriov_vf(adev))
2424 		amdgpu_virt_release_full_gpu(adev, true);
2425 
2426 	return r;
2427 }
2428 
2429 /**
2430  * amdgpu_device_fill_reset_magic - writes reset magic to gart pointer
2431  *
2432  * @adev: amdgpu_device pointer
2433  *
2434  * Writes a reset magic value to the gart pointer in VRAM.  The driver calls
2435  * this function before a GPU reset.  If the value is retained after a
2436  * GPU reset, VRAM has not been lost.  Some GPU resets may destry VRAM contents.
2437  */
2438 static void amdgpu_device_fill_reset_magic(struct amdgpu_device *adev)
2439 {
2440 	memcpy(adev->reset_magic, adev->gart.ptr, AMDGPU_RESET_MAGIC_NUM);
2441 }
2442 
2443 /**
2444  * amdgpu_device_check_vram_lost - check if vram is valid
2445  *
2446  * @adev: amdgpu_device pointer
2447  *
2448  * Checks the reset magic value written to the gart pointer in VRAM.
2449  * The driver calls this after a GPU reset to see if the contents of
2450  * VRAM is lost or now.
2451  * returns true if vram is lost, false if not.
2452  */
2453 static bool amdgpu_device_check_vram_lost(struct amdgpu_device *adev)
2454 {
2455 	if (memcmp(adev->gart.ptr, adev->reset_magic,
2456 			AMDGPU_RESET_MAGIC_NUM))
2457 		return true;
2458 
2459 	if (!amdgpu_in_reset(adev))
2460 		return false;
2461 
2462 	/*
2463 	 * For all ASICs with baco/mode1 reset, the VRAM is
2464 	 * always assumed to be lost.
2465 	 */
2466 	switch (amdgpu_asic_reset_method(adev)) {
2467 	case AMD_RESET_METHOD_BACO:
2468 	case AMD_RESET_METHOD_MODE1:
2469 		return true;
2470 	default:
2471 		return false;
2472 	}
2473 }
2474 
2475 /**
2476  * amdgpu_device_set_cg_state - set clockgating for amdgpu device
2477  *
2478  * @adev: amdgpu_device pointer
2479  * @state: clockgating state (gate or ungate)
2480  *
2481  * The list of all the hardware IPs that make up the asic is walked and the
2482  * set_clockgating_state callbacks are run.
2483  * Late initialization pass enabling clockgating for hardware IPs.
2484  * Fini or suspend, pass disabling clockgating for hardware IPs.
2485  * Returns 0 on success, negative error code on failure.
2486  */
2487 
2488 int amdgpu_device_set_cg_state(struct amdgpu_device *adev,
2489 			       enum amd_clockgating_state state)
2490 {
2491 	int i, j, r;
2492 
2493 	if (amdgpu_emu_mode == 1)
2494 		return 0;
2495 
2496 	for (j = 0; j < adev->num_ip_blocks; j++) {
2497 		i = state == AMD_CG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2498 		if (!adev->ip_blocks[i].status.late_initialized)
2499 			continue;
2500 		/* skip CG for GFX on S0ix */
2501 		if (adev->in_s0ix &&
2502 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX)
2503 			continue;
2504 		/* skip CG for VCE/UVD, it's handled specially */
2505 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2506 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2507 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2508 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2509 		    adev->ip_blocks[i].version->funcs->set_clockgating_state) {
2510 			/* enable clockgating to save power */
2511 			r = adev->ip_blocks[i].version->funcs->set_clockgating_state((void *)adev,
2512 										     state);
2513 			if (r) {
2514 				DRM_ERROR("set_clockgating_state(gate) of IP block <%s> failed %d\n",
2515 					  adev->ip_blocks[i].version->funcs->name, r);
2516 				return r;
2517 			}
2518 		}
2519 	}
2520 
2521 	return 0;
2522 }
2523 
2524 int amdgpu_device_set_pg_state(struct amdgpu_device *adev,
2525 			       enum amd_powergating_state state)
2526 {
2527 	int i, j, r;
2528 
2529 	if (amdgpu_emu_mode == 1)
2530 		return 0;
2531 
2532 	for (j = 0; j < adev->num_ip_blocks; j++) {
2533 		i = state == AMD_PG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2534 		if (!adev->ip_blocks[i].status.late_initialized)
2535 			continue;
2536 		/* skip PG for GFX on S0ix */
2537 		if (adev->in_s0ix &&
2538 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX)
2539 			continue;
2540 		/* skip CG for VCE/UVD, it's handled specially */
2541 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2542 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2543 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2544 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2545 		    adev->ip_blocks[i].version->funcs->set_powergating_state) {
2546 			/* enable powergating to save power */
2547 			r = adev->ip_blocks[i].version->funcs->set_powergating_state((void *)adev,
2548 											state);
2549 			if (r) {
2550 				DRM_ERROR("set_powergating_state(gate) of IP block <%s> failed %d\n",
2551 					  adev->ip_blocks[i].version->funcs->name, r);
2552 				return r;
2553 			}
2554 		}
2555 	}
2556 	return 0;
2557 }
2558 
2559 static int amdgpu_device_enable_mgpu_fan_boost(void)
2560 {
2561 	struct amdgpu_gpu_instance *gpu_ins;
2562 	struct amdgpu_device *adev;
2563 	int i, ret = 0;
2564 
2565 	mutex_lock(&mgpu_info.mutex);
2566 
2567 	/*
2568 	 * MGPU fan boost feature should be enabled
2569 	 * only when there are two or more dGPUs in
2570 	 * the system
2571 	 */
2572 	if (mgpu_info.num_dgpu < 2)
2573 		goto out;
2574 
2575 	for (i = 0; i < mgpu_info.num_dgpu; i++) {
2576 		gpu_ins = &(mgpu_info.gpu_ins[i]);
2577 		adev = gpu_ins->adev;
2578 		if (!(adev->flags & AMD_IS_APU) &&
2579 		    !gpu_ins->mgpu_fan_enabled) {
2580 			ret = amdgpu_dpm_enable_mgpu_fan_boost(adev);
2581 			if (ret)
2582 				break;
2583 
2584 			gpu_ins->mgpu_fan_enabled = 1;
2585 		}
2586 	}
2587 
2588 out:
2589 	mutex_unlock(&mgpu_info.mutex);
2590 
2591 	return ret;
2592 }
2593 
2594 /**
2595  * amdgpu_device_ip_late_init - run late init for hardware IPs
2596  *
2597  * @adev: amdgpu_device pointer
2598  *
2599  * Late initialization pass for hardware IPs.  The list of all the hardware
2600  * IPs that make up the asic is walked and the late_init callbacks are run.
2601  * late_init covers any special initialization that an IP requires
2602  * after all of the have been initialized or something that needs to happen
2603  * late in the init process.
2604  * Returns 0 on success, negative error code on failure.
2605  */
2606 static int amdgpu_device_ip_late_init(struct amdgpu_device *adev)
2607 {
2608 	struct amdgpu_gpu_instance *gpu_instance;
2609 	int i = 0, r;
2610 
2611 	for (i = 0; i < adev->num_ip_blocks; i++) {
2612 		if (!adev->ip_blocks[i].status.hw)
2613 			continue;
2614 		if (adev->ip_blocks[i].version->funcs->late_init) {
2615 			r = adev->ip_blocks[i].version->funcs->late_init((void *)adev);
2616 			if (r) {
2617 				DRM_ERROR("late_init of IP block <%s> failed %d\n",
2618 					  adev->ip_blocks[i].version->funcs->name, r);
2619 				return r;
2620 			}
2621 		}
2622 		adev->ip_blocks[i].status.late_initialized = true;
2623 	}
2624 
2625 	amdgpu_ras_set_error_query_ready(adev, true);
2626 
2627 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE);
2628 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE);
2629 
2630 	amdgpu_device_fill_reset_magic(adev);
2631 
2632 	r = amdgpu_device_enable_mgpu_fan_boost();
2633 	if (r)
2634 		DRM_ERROR("enable mgpu fan boost failed (%d).\n", r);
2635 
2636 	/* For passthrough configuration on arcturus and aldebaran, enable special handling SBR */
2637 	if (amdgpu_passthrough(adev) && ((adev->asic_type == CHIP_ARCTURUS && adev->gmc.xgmi.num_physical_nodes > 1)||
2638 			       adev->asic_type == CHIP_ALDEBARAN ))
2639 		amdgpu_dpm_handle_passthrough_sbr(adev, true);
2640 
2641 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
2642 		mutex_lock(&mgpu_info.mutex);
2643 
2644 		/*
2645 		 * Reset device p-state to low as this was booted with high.
2646 		 *
2647 		 * This should be performed only after all devices from the same
2648 		 * hive get initialized.
2649 		 *
2650 		 * However, it's unknown how many device in the hive in advance.
2651 		 * As this is counted one by one during devices initializations.
2652 		 *
2653 		 * So, we wait for all XGMI interlinked devices initialized.
2654 		 * This may bring some delays as those devices may come from
2655 		 * different hives. But that should be OK.
2656 		 */
2657 		if (mgpu_info.num_dgpu == adev->gmc.xgmi.num_physical_nodes) {
2658 			for (i = 0; i < mgpu_info.num_gpu; i++) {
2659 				gpu_instance = &(mgpu_info.gpu_ins[i]);
2660 				if (gpu_instance->adev->flags & AMD_IS_APU)
2661 					continue;
2662 
2663 				r = amdgpu_xgmi_set_pstate(gpu_instance->adev,
2664 						AMDGPU_XGMI_PSTATE_MIN);
2665 				if (r) {
2666 					DRM_ERROR("pstate setting failed (%d).\n", r);
2667 					break;
2668 				}
2669 			}
2670 		}
2671 
2672 		mutex_unlock(&mgpu_info.mutex);
2673 	}
2674 
2675 	return 0;
2676 }
2677 
2678 /**
2679  * amdgpu_device_smu_fini_early - smu hw_fini wrapper
2680  *
2681  * @adev: amdgpu_device pointer
2682  *
2683  * For ASICs need to disable SMC first
2684  */
2685 static void amdgpu_device_smu_fini_early(struct amdgpu_device *adev)
2686 {
2687 	int i, r;
2688 
2689 	if (adev->ip_versions[GC_HWIP][0] > IP_VERSION(9, 0, 0))
2690 		return;
2691 
2692 	for (i = 0; i < adev->num_ip_blocks; i++) {
2693 		if (!adev->ip_blocks[i].status.hw)
2694 			continue;
2695 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2696 			r = adev->ip_blocks[i].version->funcs->hw_fini((void *)adev);
2697 			/* XXX handle errors */
2698 			if (r) {
2699 				DRM_DEBUG("hw_fini of IP block <%s> failed %d\n",
2700 					  adev->ip_blocks[i].version->funcs->name, r);
2701 			}
2702 			adev->ip_blocks[i].status.hw = false;
2703 			break;
2704 		}
2705 	}
2706 }
2707 
2708 static int amdgpu_device_ip_fini_early(struct amdgpu_device *adev)
2709 {
2710 	int i, r;
2711 
2712 	for (i = 0; i < adev->num_ip_blocks; i++) {
2713 		if (!adev->ip_blocks[i].version->funcs->early_fini)
2714 			continue;
2715 
2716 		r = adev->ip_blocks[i].version->funcs->early_fini((void *)adev);
2717 		if (r) {
2718 			DRM_DEBUG("early_fini of IP block <%s> failed %d\n",
2719 				  adev->ip_blocks[i].version->funcs->name, r);
2720 		}
2721 	}
2722 
2723 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2724 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2725 
2726 	amdgpu_amdkfd_suspend(adev, false);
2727 
2728 	/* Workaroud for ASICs need to disable SMC first */
2729 	amdgpu_device_smu_fini_early(adev);
2730 
2731 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2732 		if (!adev->ip_blocks[i].status.hw)
2733 			continue;
2734 
2735 		r = adev->ip_blocks[i].version->funcs->hw_fini((void *)adev);
2736 		/* XXX handle errors */
2737 		if (r) {
2738 			DRM_DEBUG("hw_fini of IP block <%s> failed %d\n",
2739 				  adev->ip_blocks[i].version->funcs->name, r);
2740 		}
2741 
2742 		adev->ip_blocks[i].status.hw = false;
2743 	}
2744 
2745 	if (amdgpu_sriov_vf(adev)) {
2746 		if (amdgpu_virt_release_full_gpu(adev, false))
2747 			DRM_ERROR("failed to release exclusive mode on fini\n");
2748 	}
2749 
2750 	return 0;
2751 }
2752 
2753 /**
2754  * amdgpu_device_ip_fini - run fini for hardware IPs
2755  *
2756  * @adev: amdgpu_device pointer
2757  *
2758  * Main teardown pass for hardware IPs.  The list of all the hardware
2759  * IPs that make up the asic is walked and the hw_fini and sw_fini callbacks
2760  * are run.  hw_fini tears down the hardware associated with each IP
2761  * and sw_fini tears down any software state associated with each IP.
2762  * Returns 0 on success, negative error code on failure.
2763  */
2764 static int amdgpu_device_ip_fini(struct amdgpu_device *adev)
2765 {
2766 	int i, r;
2767 
2768 	if (amdgpu_sriov_vf(adev) && adev->virt.ras_init_done)
2769 		amdgpu_virt_release_ras_err_handler_data(adev);
2770 
2771 	if (adev->gmc.xgmi.num_physical_nodes > 1)
2772 		amdgpu_xgmi_remove_device(adev);
2773 
2774 	amdgpu_amdkfd_device_fini_sw(adev);
2775 
2776 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2777 		if (!adev->ip_blocks[i].status.sw)
2778 			continue;
2779 
2780 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
2781 			amdgpu_ucode_free_bo(adev);
2782 			amdgpu_free_static_csa(&adev->virt.csa_obj);
2783 			amdgpu_device_wb_fini(adev);
2784 			amdgpu_device_vram_scratch_fini(adev);
2785 			amdgpu_ib_pool_fini(adev);
2786 		}
2787 
2788 		r = adev->ip_blocks[i].version->funcs->sw_fini((void *)adev);
2789 		/* XXX handle errors */
2790 		if (r) {
2791 			DRM_DEBUG("sw_fini of IP block <%s> failed %d\n",
2792 				  adev->ip_blocks[i].version->funcs->name, r);
2793 		}
2794 		adev->ip_blocks[i].status.sw = false;
2795 		adev->ip_blocks[i].status.valid = false;
2796 	}
2797 
2798 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2799 		if (!adev->ip_blocks[i].status.late_initialized)
2800 			continue;
2801 		if (adev->ip_blocks[i].version->funcs->late_fini)
2802 			adev->ip_blocks[i].version->funcs->late_fini((void *)adev);
2803 		adev->ip_blocks[i].status.late_initialized = false;
2804 	}
2805 
2806 	amdgpu_ras_fini(adev);
2807 
2808 	return 0;
2809 }
2810 
2811 /**
2812  * amdgpu_device_delayed_init_work_handler - work handler for IB tests
2813  *
2814  * @work: work_struct.
2815  */
2816 static void amdgpu_device_delayed_init_work_handler(struct work_struct *work)
2817 {
2818 	struct amdgpu_device *adev =
2819 		container_of(work, struct amdgpu_device, delayed_init_work.work);
2820 	int r;
2821 
2822 	r = amdgpu_ib_ring_tests(adev);
2823 	if (r)
2824 		DRM_ERROR("ib ring test failed (%d).\n", r);
2825 }
2826 
2827 static void amdgpu_device_delay_enable_gfx_off(struct work_struct *work)
2828 {
2829 	struct amdgpu_device *adev =
2830 		container_of(work, struct amdgpu_device, gfx.gfx_off_delay_work.work);
2831 
2832 	WARN_ON_ONCE(adev->gfx.gfx_off_state);
2833 	WARN_ON_ONCE(adev->gfx.gfx_off_req_count);
2834 
2835 	if (!amdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_GFX, true))
2836 		adev->gfx.gfx_off_state = true;
2837 }
2838 
2839 /**
2840  * amdgpu_device_ip_suspend_phase1 - run suspend for hardware IPs (phase 1)
2841  *
2842  * @adev: amdgpu_device pointer
2843  *
2844  * Main suspend function for hardware IPs.  The list of all the hardware
2845  * IPs that make up the asic is walked, clockgating is disabled and the
2846  * suspend callbacks are run.  suspend puts the hardware and software state
2847  * in each IP into a state suitable for suspend.
2848  * Returns 0 on success, negative error code on failure.
2849  */
2850 static int amdgpu_device_ip_suspend_phase1(struct amdgpu_device *adev)
2851 {
2852 	int i, r;
2853 
2854 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2855 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2856 
2857 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2858 		if (!adev->ip_blocks[i].status.valid)
2859 			continue;
2860 
2861 		/* displays are handled separately */
2862 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_DCE)
2863 			continue;
2864 
2865 		/* XXX handle errors */
2866 		r = adev->ip_blocks[i].version->funcs->suspend(adev);
2867 		/* XXX handle errors */
2868 		if (r) {
2869 			DRM_ERROR("suspend of IP block <%s> failed %d\n",
2870 				  adev->ip_blocks[i].version->funcs->name, r);
2871 			return r;
2872 		}
2873 
2874 		adev->ip_blocks[i].status.hw = false;
2875 	}
2876 
2877 	return 0;
2878 }
2879 
2880 /**
2881  * amdgpu_device_ip_suspend_phase2 - run suspend for hardware IPs (phase 2)
2882  *
2883  * @adev: amdgpu_device pointer
2884  *
2885  * Main suspend function for hardware IPs.  The list of all the hardware
2886  * IPs that make up the asic is walked, clockgating is disabled and the
2887  * suspend callbacks are run.  suspend puts the hardware and software state
2888  * in each IP into a state suitable for suspend.
2889  * Returns 0 on success, negative error code on failure.
2890  */
2891 static int amdgpu_device_ip_suspend_phase2(struct amdgpu_device *adev)
2892 {
2893 	int i, r;
2894 
2895 	if (adev->in_s0ix)
2896 		amdgpu_dpm_gfx_state_change(adev, sGpuChangeState_D3Entry);
2897 
2898 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2899 		if (!adev->ip_blocks[i].status.valid)
2900 			continue;
2901 		/* displays are handled in phase1 */
2902 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE)
2903 			continue;
2904 		/* PSP lost connection when err_event_athub occurs */
2905 		if (amdgpu_ras_intr_triggered() &&
2906 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
2907 			adev->ip_blocks[i].status.hw = false;
2908 			continue;
2909 		}
2910 
2911 		/* skip unnecessary suspend if we do not initialize them yet */
2912 		if (adev->gmc.xgmi.pending_reset &&
2913 		    !(adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
2914 		      adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC ||
2915 		      adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2916 		      adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH)) {
2917 			adev->ip_blocks[i].status.hw = false;
2918 			continue;
2919 		}
2920 
2921 		/* skip suspend of gfx and psp for S0ix
2922 		 * gfx is in gfxoff state, so on resume it will exit gfxoff just
2923 		 * like at runtime. PSP is also part of the always on hardware
2924 		 * so no need to suspend it.
2925 		 */
2926 		if (adev->in_s0ix &&
2927 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP ||
2928 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GFX))
2929 			continue;
2930 
2931 		/* XXX handle errors */
2932 		r = adev->ip_blocks[i].version->funcs->suspend(adev);
2933 		/* XXX handle errors */
2934 		if (r) {
2935 			DRM_ERROR("suspend of IP block <%s> failed %d\n",
2936 				  adev->ip_blocks[i].version->funcs->name, r);
2937 		}
2938 		adev->ip_blocks[i].status.hw = false;
2939 		/* handle putting the SMC in the appropriate state */
2940 		if(!amdgpu_sriov_vf(adev)){
2941 			if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2942 				r = amdgpu_dpm_set_mp1_state(adev, adev->mp1_state);
2943 				if (r) {
2944 					DRM_ERROR("SMC failed to set mp1 state %d, %d\n",
2945 							adev->mp1_state, r);
2946 					return r;
2947 				}
2948 			}
2949 		}
2950 	}
2951 
2952 	return 0;
2953 }
2954 
2955 /**
2956  * amdgpu_device_ip_suspend - run suspend for hardware IPs
2957  *
2958  * @adev: amdgpu_device pointer
2959  *
2960  * Main suspend function for hardware IPs.  The list of all the hardware
2961  * IPs that make up the asic is walked, clockgating is disabled and the
2962  * suspend callbacks are run.  suspend puts the hardware and software state
2963  * in each IP into a state suitable for suspend.
2964  * Returns 0 on success, negative error code on failure.
2965  */
2966 int amdgpu_device_ip_suspend(struct amdgpu_device *adev)
2967 {
2968 	int r;
2969 
2970 	if (amdgpu_sriov_vf(adev)) {
2971 		amdgpu_virt_fini_data_exchange(adev);
2972 		amdgpu_virt_request_full_gpu(adev, false);
2973 	}
2974 
2975 	r = amdgpu_device_ip_suspend_phase1(adev);
2976 	if (r)
2977 		return r;
2978 	r = amdgpu_device_ip_suspend_phase2(adev);
2979 
2980 	if (amdgpu_sriov_vf(adev))
2981 		amdgpu_virt_release_full_gpu(adev, false);
2982 
2983 	return r;
2984 }
2985 
2986 static int amdgpu_device_ip_reinit_early_sriov(struct amdgpu_device *adev)
2987 {
2988 	int i, r;
2989 
2990 	static enum amd_ip_block_type ip_order[] = {
2991 		AMD_IP_BLOCK_TYPE_GMC,
2992 		AMD_IP_BLOCK_TYPE_COMMON,
2993 		AMD_IP_BLOCK_TYPE_PSP,
2994 		AMD_IP_BLOCK_TYPE_IH,
2995 	};
2996 
2997 	for (i = 0; i < adev->num_ip_blocks; i++) {
2998 		int j;
2999 		struct amdgpu_ip_block *block;
3000 
3001 		block = &adev->ip_blocks[i];
3002 		block->status.hw = false;
3003 
3004 		for (j = 0; j < ARRAY_SIZE(ip_order); j++) {
3005 
3006 			if (block->version->type != ip_order[j] ||
3007 				!block->status.valid)
3008 				continue;
3009 
3010 			r = block->version->funcs->hw_init(adev);
3011 			DRM_INFO("RE-INIT-early: %s %s\n", block->version->funcs->name, r?"failed":"succeeded");
3012 			if (r)
3013 				return r;
3014 			block->status.hw = true;
3015 		}
3016 	}
3017 
3018 	return 0;
3019 }
3020 
3021 static int amdgpu_device_ip_reinit_late_sriov(struct amdgpu_device *adev)
3022 {
3023 	int i, r;
3024 
3025 	static enum amd_ip_block_type ip_order[] = {
3026 		AMD_IP_BLOCK_TYPE_SMC,
3027 		AMD_IP_BLOCK_TYPE_DCE,
3028 		AMD_IP_BLOCK_TYPE_GFX,
3029 		AMD_IP_BLOCK_TYPE_SDMA,
3030 		AMD_IP_BLOCK_TYPE_UVD,
3031 		AMD_IP_BLOCK_TYPE_VCE,
3032 		AMD_IP_BLOCK_TYPE_VCN
3033 	};
3034 
3035 	for (i = 0; i < ARRAY_SIZE(ip_order); i++) {
3036 		int j;
3037 		struct amdgpu_ip_block *block;
3038 
3039 		for (j = 0; j < adev->num_ip_blocks; j++) {
3040 			block = &adev->ip_blocks[j];
3041 
3042 			if (block->version->type != ip_order[i] ||
3043 				!block->status.valid ||
3044 				block->status.hw)
3045 				continue;
3046 
3047 			if (block->version->type == AMD_IP_BLOCK_TYPE_SMC)
3048 				r = block->version->funcs->resume(adev);
3049 			else
3050 				r = block->version->funcs->hw_init(adev);
3051 
3052 			DRM_INFO("RE-INIT-late: %s %s\n", block->version->funcs->name, r?"failed":"succeeded");
3053 			if (r)
3054 				return r;
3055 			block->status.hw = true;
3056 		}
3057 	}
3058 
3059 	return 0;
3060 }
3061 
3062 /**
3063  * amdgpu_device_ip_resume_phase1 - run resume for hardware IPs
3064  *
3065  * @adev: amdgpu_device pointer
3066  *
3067  * First resume function for hardware IPs.  The list of all the hardware
3068  * IPs that make up the asic is walked and the resume callbacks are run for
3069  * COMMON, GMC, and IH.  resume puts the hardware into a functional state
3070  * after a suspend and updates the software state as necessary.  This
3071  * function is also used for restoring the GPU after a GPU reset.
3072  * Returns 0 on success, negative error code on failure.
3073  */
3074 static int amdgpu_device_ip_resume_phase1(struct amdgpu_device *adev)
3075 {
3076 	int i, r;
3077 
3078 	for (i = 0; i < adev->num_ip_blocks; i++) {
3079 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
3080 			continue;
3081 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
3082 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
3083 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
3084 
3085 			r = adev->ip_blocks[i].version->funcs->resume(adev);
3086 			if (r) {
3087 				DRM_ERROR("resume of IP block <%s> failed %d\n",
3088 					  adev->ip_blocks[i].version->funcs->name, r);
3089 				return r;
3090 			}
3091 			adev->ip_blocks[i].status.hw = true;
3092 		}
3093 	}
3094 
3095 	return 0;
3096 }
3097 
3098 /**
3099  * amdgpu_device_ip_resume_phase2 - run resume for hardware IPs
3100  *
3101  * @adev: amdgpu_device pointer
3102  *
3103  * First resume function for hardware IPs.  The list of all the hardware
3104  * IPs that make up the asic is walked and the resume callbacks are run for
3105  * all blocks except COMMON, GMC, and IH.  resume puts the hardware into a
3106  * functional state after a suspend and updates the software state as
3107  * necessary.  This function is also used for restoring the GPU after a GPU
3108  * reset.
3109  * Returns 0 on success, negative error code on failure.
3110  */
3111 static int amdgpu_device_ip_resume_phase2(struct amdgpu_device *adev)
3112 {
3113 	int i, r;
3114 
3115 	for (i = 0; i < adev->num_ip_blocks; i++) {
3116 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
3117 			continue;
3118 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
3119 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
3120 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH ||
3121 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)
3122 			continue;
3123 		r = adev->ip_blocks[i].version->funcs->resume(adev);
3124 		if (r) {
3125 			DRM_ERROR("resume of IP block <%s> failed %d\n",
3126 				  adev->ip_blocks[i].version->funcs->name, r);
3127 			return r;
3128 		}
3129 		adev->ip_blocks[i].status.hw = true;
3130 	}
3131 
3132 	return 0;
3133 }
3134 
3135 /**
3136  * amdgpu_device_ip_resume - run resume for hardware IPs
3137  *
3138  * @adev: amdgpu_device pointer
3139  *
3140  * Main resume function for hardware IPs.  The hardware IPs
3141  * are split into two resume functions because they are
3142  * are also used in in recovering from a GPU reset and some additional
3143  * steps need to be take between them.  In this case (S3/S4) they are
3144  * run sequentially.
3145  * Returns 0 on success, negative error code on failure.
3146  */
3147 static int amdgpu_device_ip_resume(struct amdgpu_device *adev)
3148 {
3149 	int r;
3150 
3151 	r = amdgpu_amdkfd_resume_iommu(adev);
3152 	if (r)
3153 		return r;
3154 
3155 	r = amdgpu_device_ip_resume_phase1(adev);
3156 	if (r)
3157 		return r;
3158 
3159 	r = amdgpu_device_fw_loading(adev);
3160 	if (r)
3161 		return r;
3162 
3163 	r = amdgpu_device_ip_resume_phase2(adev);
3164 
3165 	return r;
3166 }
3167 
3168 /**
3169  * amdgpu_device_detect_sriov_bios - determine if the board supports SR-IOV
3170  *
3171  * @adev: amdgpu_device pointer
3172  *
3173  * Query the VBIOS data tables to determine if the board supports SR-IOV.
3174  */
3175 static void amdgpu_device_detect_sriov_bios(struct amdgpu_device *adev)
3176 {
3177 	if (amdgpu_sriov_vf(adev)) {
3178 		if (adev->is_atom_fw) {
3179 			if (amdgpu_atomfirmware_gpu_virtualization_supported(adev))
3180 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
3181 		} else {
3182 			if (amdgpu_atombios_has_gpu_virtualization_table(adev))
3183 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
3184 		}
3185 
3186 		if (!(adev->virt.caps & AMDGPU_SRIOV_CAPS_SRIOV_VBIOS))
3187 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_NO_VBIOS, 0, 0);
3188 	}
3189 }
3190 
3191 /**
3192  * amdgpu_device_asic_has_dc_support - determine if DC supports the asic
3193  *
3194  * @asic_type: AMD asic type
3195  *
3196  * Check if there is DC (new modesetting infrastructre) support for an asic.
3197  * returns true if DC has support, false if not.
3198  */
3199 bool amdgpu_device_asic_has_dc_support(enum amd_asic_type asic_type)
3200 {
3201 	switch (asic_type) {
3202 #ifdef CONFIG_DRM_AMDGPU_SI
3203 	case CHIP_HAINAN:
3204 #endif
3205 	case CHIP_TOPAZ:
3206 		/* chips with no display hardware */
3207 		return false;
3208 #if defined(CONFIG_DRM_AMD_DC)
3209 	case CHIP_TAHITI:
3210 	case CHIP_PITCAIRN:
3211 	case CHIP_VERDE:
3212 	case CHIP_OLAND:
3213 		/*
3214 		 * We have systems in the wild with these ASICs that require
3215 		 * LVDS and VGA support which is not supported with DC.
3216 		 *
3217 		 * Fallback to the non-DC driver here by default so as not to
3218 		 * cause regressions.
3219 		 */
3220 #if defined(CONFIG_DRM_AMD_DC_SI)
3221 		return amdgpu_dc > 0;
3222 #else
3223 		return false;
3224 #endif
3225 	case CHIP_BONAIRE:
3226 	case CHIP_KAVERI:
3227 	case CHIP_KABINI:
3228 	case CHIP_MULLINS:
3229 		/*
3230 		 * We have systems in the wild with these ASICs that require
3231 		 * LVDS and VGA support which is not supported with DC.
3232 		 *
3233 		 * Fallback to the non-DC driver here by default so as not to
3234 		 * cause regressions.
3235 		 */
3236 		return amdgpu_dc > 0;
3237 	case CHIP_HAWAII:
3238 	case CHIP_CARRIZO:
3239 	case CHIP_STONEY:
3240 	case CHIP_POLARIS10:
3241 	case CHIP_POLARIS11:
3242 	case CHIP_POLARIS12:
3243 	case CHIP_VEGAM:
3244 	case CHIP_TONGA:
3245 	case CHIP_FIJI:
3246 	case CHIP_VEGA10:
3247 	case CHIP_VEGA12:
3248 	case CHIP_VEGA20:
3249 #if defined(CONFIG_DRM_AMD_DC_DCN)
3250 	case CHIP_RAVEN:
3251 	case CHIP_NAVI10:
3252 	case CHIP_NAVI14:
3253 	case CHIP_NAVI12:
3254 	case CHIP_RENOIR:
3255 	case CHIP_CYAN_SKILLFISH:
3256 	case CHIP_SIENNA_CICHLID:
3257 	case CHIP_NAVY_FLOUNDER:
3258 	case CHIP_DIMGREY_CAVEFISH:
3259 	case CHIP_BEIGE_GOBY:
3260 	case CHIP_VANGOGH:
3261 	case CHIP_YELLOW_CARP:
3262 #endif
3263 	default:
3264 		return amdgpu_dc != 0;
3265 #else
3266 	default:
3267 		if (amdgpu_dc > 0)
3268 			DRM_INFO_ONCE("Display Core has been requested via kernel parameter "
3269 					 "but isn't supported by ASIC, ignoring\n");
3270 		return false;
3271 #endif
3272 	}
3273 }
3274 
3275 /**
3276  * amdgpu_device_has_dc_support - check if dc is supported
3277  *
3278  * @adev: amdgpu_device pointer
3279  *
3280  * Returns true for supported, false for not supported
3281  */
3282 bool amdgpu_device_has_dc_support(struct amdgpu_device *adev)
3283 {
3284 	if (amdgpu_sriov_vf(adev) ||
3285 	    adev->enable_virtual_display ||
3286 	    (adev->harvest_ip_mask & AMD_HARVEST_IP_DMU_MASK))
3287 		return false;
3288 
3289 	return amdgpu_device_asic_has_dc_support(adev->asic_type);
3290 }
3291 
3292 static void amdgpu_device_xgmi_reset_func(struct work_struct *__work)
3293 {
3294 	struct amdgpu_device *adev =
3295 		container_of(__work, struct amdgpu_device, xgmi_reset_work);
3296 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev);
3297 
3298 	/* It's a bug to not have a hive within this function */
3299 	if (WARN_ON(!hive))
3300 		return;
3301 
3302 	/*
3303 	 * Use task barrier to synchronize all xgmi reset works across the
3304 	 * hive. task_barrier_enter and task_barrier_exit will block
3305 	 * until all the threads running the xgmi reset works reach
3306 	 * those points. task_barrier_full will do both blocks.
3307 	 */
3308 	if (amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) {
3309 
3310 		task_barrier_enter(&hive->tb);
3311 		adev->asic_reset_res = amdgpu_device_baco_enter(adev_to_drm(adev));
3312 
3313 		if (adev->asic_reset_res)
3314 			goto fail;
3315 
3316 		task_barrier_exit(&hive->tb);
3317 		adev->asic_reset_res = amdgpu_device_baco_exit(adev_to_drm(adev));
3318 
3319 		if (adev->asic_reset_res)
3320 			goto fail;
3321 
3322 		if (adev->mmhub.ras && adev->mmhub.ras->ras_block.hw_ops &&
3323 		    adev->mmhub.ras->ras_block.hw_ops->reset_ras_error_count)
3324 			adev->mmhub.ras->ras_block.hw_ops->reset_ras_error_count(adev);
3325 	} else {
3326 
3327 		task_barrier_full(&hive->tb);
3328 		adev->asic_reset_res =  amdgpu_asic_reset(adev);
3329 	}
3330 
3331 fail:
3332 	if (adev->asic_reset_res)
3333 		DRM_WARN("ASIC reset failed with error, %d for drm dev, %s",
3334 			 adev->asic_reset_res, adev_to_drm(adev)->unique);
3335 	amdgpu_put_xgmi_hive(hive);
3336 }
3337 
3338 static int amdgpu_device_get_job_timeout_settings(struct amdgpu_device *adev)
3339 {
3340 	char *input = amdgpu_lockup_timeout;
3341 	char *timeout_setting = NULL;
3342 	int index = 0;
3343 	long timeout;
3344 	int ret = 0;
3345 
3346 	/*
3347 	 * By default timeout for non compute jobs is 10000
3348 	 * and 60000 for compute jobs.
3349 	 * In SR-IOV or passthrough mode, timeout for compute
3350 	 * jobs are 60000 by default.
3351 	 */
3352 	adev->gfx_timeout = msecs_to_jiffies(10000);
3353 	adev->sdma_timeout = adev->video_timeout = adev->gfx_timeout;
3354 	if (amdgpu_sriov_vf(adev))
3355 		adev->compute_timeout = amdgpu_sriov_is_pp_one_vf(adev) ?
3356 					msecs_to_jiffies(60000) : msecs_to_jiffies(10000);
3357 	else
3358 		adev->compute_timeout =  msecs_to_jiffies(60000);
3359 
3360 	if (strnlen(input, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
3361 		while ((timeout_setting = strsep(&input, ",")) &&
3362 				strnlen(timeout_setting, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
3363 			ret = kstrtol(timeout_setting, 0, &timeout);
3364 			if (ret)
3365 				return ret;
3366 
3367 			if (timeout == 0) {
3368 				index++;
3369 				continue;
3370 			} else if (timeout < 0) {
3371 				timeout = MAX_SCHEDULE_TIMEOUT;
3372 				dev_warn(adev->dev, "lockup timeout disabled");
3373 				add_taint(TAINT_SOFTLOCKUP, LOCKDEP_STILL_OK);
3374 			} else {
3375 				timeout = msecs_to_jiffies(timeout);
3376 			}
3377 
3378 			switch (index++) {
3379 			case 0:
3380 				adev->gfx_timeout = timeout;
3381 				break;
3382 			case 1:
3383 				adev->compute_timeout = timeout;
3384 				break;
3385 			case 2:
3386 				adev->sdma_timeout = timeout;
3387 				break;
3388 			case 3:
3389 				adev->video_timeout = timeout;
3390 				break;
3391 			default:
3392 				break;
3393 			}
3394 		}
3395 		/*
3396 		 * There is only one value specified and
3397 		 * it should apply to all non-compute jobs.
3398 		 */
3399 		if (index == 1) {
3400 			adev->sdma_timeout = adev->video_timeout = adev->gfx_timeout;
3401 			if (amdgpu_sriov_vf(adev) || amdgpu_passthrough(adev))
3402 				adev->compute_timeout = adev->gfx_timeout;
3403 		}
3404 	}
3405 
3406 	return ret;
3407 }
3408 
3409 /**
3410  * amdgpu_device_check_iommu_direct_map - check if RAM direct mapped to GPU
3411  *
3412  * @adev: amdgpu_device pointer
3413  *
3414  * RAM direct mapped to GPU if IOMMU is not enabled or is pass through mode
3415  */
3416 static void amdgpu_device_check_iommu_direct_map(struct amdgpu_device *adev)
3417 {
3418 	struct iommu_domain *domain;
3419 
3420 	domain = iommu_get_domain_for_dev(adev->dev);
3421 	if (!domain || domain->type == IOMMU_DOMAIN_IDENTITY)
3422 		adev->ram_is_direct_mapped = true;
3423 }
3424 
3425 static const struct attribute *amdgpu_dev_attributes[] = {
3426 	&dev_attr_product_name.attr,
3427 	&dev_attr_product_number.attr,
3428 	&dev_attr_serial_number.attr,
3429 	&dev_attr_pcie_replay_count.attr,
3430 	NULL
3431 };
3432 
3433 /**
3434  * amdgpu_device_init - initialize the driver
3435  *
3436  * @adev: amdgpu_device pointer
3437  * @flags: driver flags
3438  *
3439  * Initializes the driver info and hw (all asics).
3440  * Returns 0 for success or an error on failure.
3441  * Called at driver startup.
3442  */
3443 int amdgpu_device_init(struct amdgpu_device *adev,
3444 		       uint32_t flags)
3445 {
3446 	struct drm_device *ddev = adev_to_drm(adev);
3447 	struct pci_dev *pdev = adev->pdev;
3448 	int r, i;
3449 	bool px = false;
3450 	u32 max_MBps;
3451 
3452 	adev->shutdown = false;
3453 	adev->flags = flags;
3454 
3455 	if (amdgpu_force_asic_type >= 0 && amdgpu_force_asic_type < CHIP_LAST)
3456 		adev->asic_type = amdgpu_force_asic_type;
3457 	else
3458 		adev->asic_type = flags & AMD_ASIC_MASK;
3459 
3460 	adev->usec_timeout = AMDGPU_MAX_USEC_TIMEOUT;
3461 	if (amdgpu_emu_mode == 1)
3462 		adev->usec_timeout *= 10;
3463 	adev->gmc.gart_size = 512 * 1024 * 1024;
3464 	adev->accel_working = false;
3465 	adev->num_rings = 0;
3466 	adev->mman.buffer_funcs = NULL;
3467 	adev->mman.buffer_funcs_ring = NULL;
3468 	adev->vm_manager.vm_pte_funcs = NULL;
3469 	adev->vm_manager.vm_pte_num_scheds = 0;
3470 	adev->gmc.gmc_funcs = NULL;
3471 	adev->harvest_ip_mask = 0x0;
3472 	adev->fence_context = dma_fence_context_alloc(AMDGPU_MAX_RINGS);
3473 	bitmap_zero(adev->gfx.pipe_reserve_bitmap, AMDGPU_MAX_COMPUTE_QUEUES);
3474 
3475 	adev->smc_rreg = &amdgpu_invalid_rreg;
3476 	adev->smc_wreg = &amdgpu_invalid_wreg;
3477 	adev->pcie_rreg = &amdgpu_invalid_rreg;
3478 	adev->pcie_wreg = &amdgpu_invalid_wreg;
3479 	adev->pciep_rreg = &amdgpu_invalid_rreg;
3480 	adev->pciep_wreg = &amdgpu_invalid_wreg;
3481 	adev->pcie_rreg64 = &amdgpu_invalid_rreg64;
3482 	adev->pcie_wreg64 = &amdgpu_invalid_wreg64;
3483 	adev->uvd_ctx_rreg = &amdgpu_invalid_rreg;
3484 	adev->uvd_ctx_wreg = &amdgpu_invalid_wreg;
3485 	adev->didt_rreg = &amdgpu_invalid_rreg;
3486 	adev->didt_wreg = &amdgpu_invalid_wreg;
3487 	adev->gc_cac_rreg = &amdgpu_invalid_rreg;
3488 	adev->gc_cac_wreg = &amdgpu_invalid_wreg;
3489 	adev->audio_endpt_rreg = &amdgpu_block_invalid_rreg;
3490 	adev->audio_endpt_wreg = &amdgpu_block_invalid_wreg;
3491 
3492 	DRM_INFO("initializing kernel modesetting (%s 0x%04X:0x%04X 0x%04X:0x%04X 0x%02X).\n",
3493 		 amdgpu_asic_name[adev->asic_type], pdev->vendor, pdev->device,
3494 		 pdev->subsystem_vendor, pdev->subsystem_device, pdev->revision);
3495 
3496 	/* mutex initialization are all done here so we
3497 	 * can recall function without having locking issues */
3498 	mutex_init(&adev->firmware.mutex);
3499 	mutex_init(&adev->pm.mutex);
3500 	mutex_init(&adev->gfx.gpu_clock_mutex);
3501 	mutex_init(&adev->srbm_mutex);
3502 	mutex_init(&adev->gfx.pipe_reserve_mutex);
3503 	mutex_init(&adev->gfx.gfx_off_mutex);
3504 	mutex_init(&adev->grbm_idx_mutex);
3505 	mutex_init(&adev->mn_lock);
3506 	mutex_init(&adev->virt.vf_errors.lock);
3507 	hash_init(adev->mn_hash);
3508 	atomic_set(&adev->in_gpu_reset, 0);
3509 	init_rwsem(&adev->reset_sem);
3510 	mutex_init(&adev->psp.mutex);
3511 	mutex_init(&adev->notifier_lock);
3512 	mutex_init(&adev->pm.stable_pstate_ctx_lock);
3513 
3514 	amdgpu_device_init_apu_flags(adev);
3515 
3516 	r = amdgpu_device_check_arguments(adev);
3517 	if (r)
3518 		return r;
3519 
3520 	spin_lock_init(&adev->mmio_idx_lock);
3521 	spin_lock_init(&adev->smc_idx_lock);
3522 	spin_lock_init(&adev->pcie_idx_lock);
3523 	spin_lock_init(&adev->uvd_ctx_idx_lock);
3524 	spin_lock_init(&adev->didt_idx_lock);
3525 	spin_lock_init(&adev->gc_cac_idx_lock);
3526 	spin_lock_init(&adev->se_cac_idx_lock);
3527 	spin_lock_init(&adev->audio_endpt_idx_lock);
3528 	spin_lock_init(&adev->mm_stats.lock);
3529 
3530 	INIT_LIST_HEAD(&adev->shadow_list);
3531 	mutex_init(&adev->shadow_list_lock);
3532 
3533 	INIT_LIST_HEAD(&adev->reset_list);
3534 
3535 	INIT_LIST_HEAD(&adev->ras_list);
3536 
3537 	INIT_DELAYED_WORK(&adev->delayed_init_work,
3538 			  amdgpu_device_delayed_init_work_handler);
3539 	INIT_DELAYED_WORK(&adev->gfx.gfx_off_delay_work,
3540 			  amdgpu_device_delay_enable_gfx_off);
3541 
3542 	INIT_WORK(&adev->xgmi_reset_work, amdgpu_device_xgmi_reset_func);
3543 
3544 	adev->gfx.gfx_off_req_count = 1;
3545 	adev->pm.ac_power = power_supply_is_system_supplied() > 0;
3546 
3547 	atomic_set(&adev->throttling_logging_enabled, 1);
3548 	/*
3549 	 * If throttling continues, logging will be performed every minute
3550 	 * to avoid log flooding. "-1" is subtracted since the thermal
3551 	 * throttling interrupt comes every second. Thus, the total logging
3552 	 * interval is 59 seconds(retelimited printk interval) + 1(waiting
3553 	 * for throttling interrupt) = 60 seconds.
3554 	 */
3555 	ratelimit_state_init(&adev->throttling_logging_rs, (60 - 1) * HZ, 1);
3556 	ratelimit_set_flags(&adev->throttling_logging_rs, RATELIMIT_MSG_ON_RELEASE);
3557 
3558 	/* Registers mapping */
3559 	/* TODO: block userspace mapping of io register */
3560 	if (adev->asic_type >= CHIP_BONAIRE) {
3561 		adev->rmmio_base = pci_resource_start(adev->pdev, 5);
3562 		adev->rmmio_size = pci_resource_len(adev->pdev, 5);
3563 	} else {
3564 		adev->rmmio_base = pci_resource_start(adev->pdev, 2);
3565 		adev->rmmio_size = pci_resource_len(adev->pdev, 2);
3566 	}
3567 
3568 	for (i = 0; i < AMD_IP_BLOCK_TYPE_NUM; i++)
3569 		atomic_set(&adev->pm.pwr_state[i], POWER_STATE_UNKNOWN);
3570 
3571 	adev->rmmio = ioremap(adev->rmmio_base, adev->rmmio_size);
3572 	if (adev->rmmio == NULL) {
3573 		return -ENOMEM;
3574 	}
3575 	DRM_INFO("register mmio base: 0x%08X\n", (uint32_t)adev->rmmio_base);
3576 	DRM_INFO("register mmio size: %u\n", (unsigned)adev->rmmio_size);
3577 
3578 	amdgpu_device_get_pcie_info(adev);
3579 
3580 	if (amdgpu_mcbp)
3581 		DRM_INFO("MCBP is enabled\n");
3582 
3583 	if (amdgpu_mes && adev->asic_type >= CHIP_NAVI10)
3584 		adev->enable_mes = true;
3585 
3586 	/* detect hw virtualization here */
3587 	amdgpu_detect_virtualization(adev);
3588 
3589 	r = amdgpu_device_get_job_timeout_settings(adev);
3590 	if (r) {
3591 		dev_err(adev->dev, "invalid lockup_timeout parameter syntax\n");
3592 		return r;
3593 	}
3594 
3595 	/* early init functions */
3596 	r = amdgpu_device_ip_early_init(adev);
3597 	if (r)
3598 		return r;
3599 
3600 	/* Need to get xgmi info early to decide the reset behavior*/
3601 	if (adev->gmc.xgmi.supported) {
3602 		r = adev->gfxhub.funcs->get_xgmi_info(adev);
3603 		if (r)
3604 			return r;
3605 	}
3606 
3607 	/* enable PCIE atomic ops */
3608 	if (amdgpu_sriov_vf(adev))
3609 		adev->have_atomics_support = ((struct amd_sriov_msg_pf2vf_info *)
3610 			adev->virt.fw_reserve.p_pf2vf)->pcie_atomic_ops_enabled_flags ==
3611 			(PCI_EXP_DEVCAP2_ATOMIC_COMP32 | PCI_EXP_DEVCAP2_ATOMIC_COMP64);
3612 	else
3613 		adev->have_atomics_support =
3614 			!pci_enable_atomic_ops_to_root(adev->pdev,
3615 					  PCI_EXP_DEVCAP2_ATOMIC_COMP32 |
3616 					  PCI_EXP_DEVCAP2_ATOMIC_COMP64);
3617 	if (!adev->have_atomics_support)
3618 		dev_info(adev->dev, "PCIE atomic ops is not supported\n");
3619 
3620 	/* doorbell bar mapping and doorbell index init*/
3621 	amdgpu_device_doorbell_init(adev);
3622 
3623 	if (amdgpu_emu_mode == 1) {
3624 		/* post the asic on emulation mode */
3625 		emu_soc_asic_init(adev);
3626 		goto fence_driver_init;
3627 	}
3628 
3629 	amdgpu_reset_init(adev);
3630 
3631 	/* detect if we are with an SRIOV vbios */
3632 	amdgpu_device_detect_sriov_bios(adev);
3633 
3634 	/* check if we need to reset the asic
3635 	 *  E.g., driver was not cleanly unloaded previously, etc.
3636 	 */
3637 	if (!amdgpu_sriov_vf(adev) && amdgpu_asic_need_reset_on_init(adev)) {
3638 		if (adev->gmc.xgmi.num_physical_nodes) {
3639 			dev_info(adev->dev, "Pending hive reset.\n");
3640 			adev->gmc.xgmi.pending_reset = true;
3641 			/* Only need to init necessary block for SMU to handle the reset */
3642 			for (i = 0; i < adev->num_ip_blocks; i++) {
3643 				if (!adev->ip_blocks[i].status.valid)
3644 					continue;
3645 				if (!(adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
3646 				      adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
3647 				      adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH ||
3648 				      adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC)) {
3649 					DRM_DEBUG("IP %s disabled for hw_init.\n",
3650 						adev->ip_blocks[i].version->funcs->name);
3651 					adev->ip_blocks[i].status.hw = true;
3652 				}
3653 			}
3654 		} else {
3655 			r = amdgpu_asic_reset(adev);
3656 			if (r) {
3657 				dev_err(adev->dev, "asic reset on init failed\n");
3658 				goto failed;
3659 			}
3660 		}
3661 	}
3662 
3663 	pci_enable_pcie_error_reporting(adev->pdev);
3664 
3665 	/* Post card if necessary */
3666 	if (amdgpu_device_need_post(adev)) {
3667 		if (!adev->bios) {
3668 			dev_err(adev->dev, "no vBIOS found\n");
3669 			r = -EINVAL;
3670 			goto failed;
3671 		}
3672 		DRM_INFO("GPU posting now...\n");
3673 		r = amdgpu_device_asic_init(adev);
3674 		if (r) {
3675 			dev_err(adev->dev, "gpu post error!\n");
3676 			goto failed;
3677 		}
3678 	}
3679 
3680 	if (adev->is_atom_fw) {
3681 		/* Initialize clocks */
3682 		r = amdgpu_atomfirmware_get_clock_info(adev);
3683 		if (r) {
3684 			dev_err(adev->dev, "amdgpu_atomfirmware_get_clock_info failed\n");
3685 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
3686 			goto failed;
3687 		}
3688 	} else {
3689 		/* Initialize clocks */
3690 		r = amdgpu_atombios_get_clock_info(adev);
3691 		if (r) {
3692 			dev_err(adev->dev, "amdgpu_atombios_get_clock_info failed\n");
3693 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
3694 			goto failed;
3695 		}
3696 		/* init i2c buses */
3697 		if (!amdgpu_device_has_dc_support(adev))
3698 			amdgpu_atombios_i2c_init(adev);
3699 	}
3700 
3701 fence_driver_init:
3702 	/* Fence driver */
3703 	r = amdgpu_fence_driver_sw_init(adev);
3704 	if (r) {
3705 		dev_err(adev->dev, "amdgpu_fence_driver_sw_init failed\n");
3706 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_FENCE_INIT_FAIL, 0, 0);
3707 		goto failed;
3708 	}
3709 
3710 	/* init the mode config */
3711 	drm_mode_config_init(adev_to_drm(adev));
3712 
3713 	r = amdgpu_device_ip_init(adev);
3714 	if (r) {
3715 		/* failed in exclusive mode due to timeout */
3716 		if (amdgpu_sriov_vf(adev) &&
3717 		    !amdgpu_sriov_runtime(adev) &&
3718 		    amdgpu_virt_mmio_blocked(adev) &&
3719 		    !amdgpu_virt_wait_reset(adev)) {
3720 			dev_err(adev->dev, "VF exclusive mode timeout\n");
3721 			/* Don't send request since VF is inactive. */
3722 			adev->virt.caps &= ~AMDGPU_SRIOV_CAPS_RUNTIME;
3723 			adev->virt.ops = NULL;
3724 			r = -EAGAIN;
3725 			goto release_ras_con;
3726 		}
3727 		dev_err(adev->dev, "amdgpu_device_ip_init failed\n");
3728 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_INIT_FAIL, 0, 0);
3729 		goto release_ras_con;
3730 	}
3731 
3732 	amdgpu_fence_driver_hw_init(adev);
3733 
3734 	dev_info(adev->dev,
3735 		"SE %d, SH per SE %d, CU per SH %d, active_cu_number %d\n",
3736 			adev->gfx.config.max_shader_engines,
3737 			adev->gfx.config.max_sh_per_se,
3738 			adev->gfx.config.max_cu_per_sh,
3739 			adev->gfx.cu_info.number);
3740 
3741 	adev->accel_working = true;
3742 
3743 	amdgpu_vm_check_compute_bug(adev);
3744 
3745 	/* Initialize the buffer migration limit. */
3746 	if (amdgpu_moverate >= 0)
3747 		max_MBps = amdgpu_moverate;
3748 	else
3749 		max_MBps = 8; /* Allow 8 MB/s. */
3750 	/* Get a log2 for easy divisions. */
3751 	adev->mm_stats.log2_max_MBps = ilog2(max(1u, max_MBps));
3752 
3753 	r = amdgpu_pm_sysfs_init(adev);
3754 	if (r) {
3755 		adev->pm_sysfs_en = false;
3756 		DRM_ERROR("registering pm debugfs failed (%d).\n", r);
3757 	} else
3758 		adev->pm_sysfs_en = true;
3759 
3760 	r = amdgpu_ucode_sysfs_init(adev);
3761 	if (r) {
3762 		adev->ucode_sysfs_en = false;
3763 		DRM_ERROR("Creating firmware sysfs failed (%d).\n", r);
3764 	} else
3765 		adev->ucode_sysfs_en = true;
3766 
3767 	if ((amdgpu_testing & 1)) {
3768 		if (adev->accel_working)
3769 			amdgpu_test_moves(adev);
3770 		else
3771 			DRM_INFO("amdgpu: acceleration disabled, skipping move tests\n");
3772 	}
3773 	if (amdgpu_benchmarking) {
3774 		if (adev->accel_working)
3775 			amdgpu_benchmark(adev, amdgpu_benchmarking);
3776 		else
3777 			DRM_INFO("amdgpu: acceleration disabled, skipping benchmarks\n");
3778 	}
3779 
3780 	/*
3781 	 * Register gpu instance before amdgpu_device_enable_mgpu_fan_boost.
3782 	 * Otherwise the mgpu fan boost feature will be skipped due to the
3783 	 * gpu instance is counted less.
3784 	 */
3785 	amdgpu_register_gpu_instance(adev);
3786 
3787 	/* enable clockgating, etc. after ib tests, etc. since some blocks require
3788 	 * explicit gating rather than handling it automatically.
3789 	 */
3790 	if (!adev->gmc.xgmi.pending_reset) {
3791 		r = amdgpu_device_ip_late_init(adev);
3792 		if (r) {
3793 			dev_err(adev->dev, "amdgpu_device_ip_late_init failed\n");
3794 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_LATE_INIT_FAIL, 0, r);
3795 			goto release_ras_con;
3796 		}
3797 		/* must succeed. */
3798 		amdgpu_ras_resume(adev);
3799 		queue_delayed_work(system_wq, &adev->delayed_init_work,
3800 				   msecs_to_jiffies(AMDGPU_RESUME_MS));
3801 	}
3802 
3803 	if (amdgpu_sriov_vf(adev))
3804 		flush_delayed_work(&adev->delayed_init_work);
3805 
3806 	r = sysfs_create_files(&adev->dev->kobj, amdgpu_dev_attributes);
3807 	if (r)
3808 		dev_err(adev->dev, "Could not create amdgpu device attr\n");
3809 
3810 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
3811 		r = amdgpu_pmu_init(adev);
3812 	if (r)
3813 		dev_err(adev->dev, "amdgpu_pmu_init failed\n");
3814 
3815 	/* Have stored pci confspace at hand for restore in sudden PCI error */
3816 	if (amdgpu_device_cache_pci_state(adev->pdev))
3817 		pci_restore_state(pdev);
3818 
3819 	/* if we have > 1 VGA cards, then disable the amdgpu VGA resources */
3820 	/* this will fail for cards that aren't VGA class devices, just
3821 	 * ignore it */
3822 	if ((adev->pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA)
3823 		vga_client_register(adev->pdev, amdgpu_device_vga_set_decode);
3824 
3825 	if (amdgpu_device_supports_px(ddev)) {
3826 		px = true;
3827 		vga_switcheroo_register_client(adev->pdev,
3828 					       &amdgpu_switcheroo_ops, px);
3829 		vga_switcheroo_init_domain_pm_ops(adev->dev, &adev->vga_pm_domain);
3830 	}
3831 
3832 	if (adev->gmc.xgmi.pending_reset)
3833 		queue_delayed_work(system_wq, &mgpu_info.delayed_reset_work,
3834 				   msecs_to_jiffies(AMDGPU_RESUME_MS));
3835 
3836 	amdgpu_device_check_iommu_direct_map(adev);
3837 
3838 	return 0;
3839 
3840 release_ras_con:
3841 	amdgpu_release_ras_context(adev);
3842 
3843 failed:
3844 	amdgpu_vf_error_trans_all(adev);
3845 
3846 	return r;
3847 }
3848 
3849 static void amdgpu_device_unmap_mmio(struct amdgpu_device *adev)
3850 {
3851 
3852 	/* Clear all CPU mappings pointing to this device */
3853 	unmap_mapping_range(adev->ddev.anon_inode->i_mapping, 0, 0, 1);
3854 
3855 	/* Unmap all mapped bars - Doorbell, registers and VRAM */
3856 	amdgpu_device_doorbell_fini(adev);
3857 
3858 	iounmap(adev->rmmio);
3859 	adev->rmmio = NULL;
3860 	if (adev->mman.aper_base_kaddr)
3861 		iounmap(adev->mman.aper_base_kaddr);
3862 	adev->mman.aper_base_kaddr = NULL;
3863 
3864 	/* Memory manager related */
3865 	if (!adev->gmc.xgmi.connected_to_cpu) {
3866 		arch_phys_wc_del(adev->gmc.vram_mtrr);
3867 		arch_io_free_memtype_wc(adev->gmc.aper_base, adev->gmc.aper_size);
3868 	}
3869 }
3870 
3871 /**
3872  * amdgpu_device_fini_hw - tear down the driver
3873  *
3874  * @adev: amdgpu_device pointer
3875  *
3876  * Tear down the driver info (all asics).
3877  * Called at driver shutdown.
3878  */
3879 void amdgpu_device_fini_hw(struct amdgpu_device *adev)
3880 {
3881 	dev_info(adev->dev, "amdgpu: finishing device.\n");
3882 	flush_delayed_work(&adev->delayed_init_work);
3883 	if (adev->mman.initialized) {
3884 		flush_delayed_work(&adev->mman.bdev.wq);
3885 		ttm_bo_lock_delayed_workqueue(&adev->mman.bdev);
3886 	}
3887 	adev->shutdown = true;
3888 
3889 	/* make sure IB test finished before entering exclusive mode
3890 	 * to avoid preemption on IB test
3891 	 * */
3892 	if (amdgpu_sriov_vf(adev)) {
3893 		amdgpu_virt_request_full_gpu(adev, false);
3894 		amdgpu_virt_fini_data_exchange(adev);
3895 	}
3896 
3897 	/* disable all interrupts */
3898 	amdgpu_irq_disable_all(adev);
3899 	if (adev->mode_info.mode_config_initialized){
3900 		if (!drm_drv_uses_atomic_modeset(adev_to_drm(adev)))
3901 			drm_helper_force_disable_all(adev_to_drm(adev));
3902 		else
3903 			drm_atomic_helper_shutdown(adev_to_drm(adev));
3904 	}
3905 	amdgpu_fence_driver_hw_fini(adev);
3906 
3907 	if (adev->pm_sysfs_en)
3908 		amdgpu_pm_sysfs_fini(adev);
3909 	if (adev->ucode_sysfs_en)
3910 		amdgpu_ucode_sysfs_fini(adev);
3911 	sysfs_remove_files(&adev->dev->kobj, amdgpu_dev_attributes);
3912 
3913 	/* disable ras feature must before hw fini */
3914 	amdgpu_ras_pre_fini(adev);
3915 
3916 	amdgpu_device_ip_fini_early(adev);
3917 
3918 	amdgpu_irq_fini_hw(adev);
3919 
3920 	if (adev->mman.initialized)
3921 		ttm_device_clear_dma_mappings(&adev->mman.bdev);
3922 
3923 	amdgpu_gart_dummy_page_fini(adev);
3924 
3925 	if (drm_dev_is_unplugged(adev_to_drm(adev)))
3926 		amdgpu_device_unmap_mmio(adev);
3927 
3928 }
3929 
3930 void amdgpu_device_fini_sw(struct amdgpu_device *adev)
3931 {
3932 	int idx;
3933 
3934 	amdgpu_fence_driver_sw_fini(adev);
3935 	amdgpu_device_ip_fini(adev);
3936 	release_firmware(adev->firmware.gpu_info_fw);
3937 	adev->firmware.gpu_info_fw = NULL;
3938 	adev->accel_working = false;
3939 
3940 	amdgpu_reset_fini(adev);
3941 
3942 	/* free i2c buses */
3943 	if (!amdgpu_device_has_dc_support(adev))
3944 		amdgpu_i2c_fini(adev);
3945 
3946 	if (amdgpu_emu_mode != 1)
3947 		amdgpu_atombios_fini(adev);
3948 
3949 	kfree(adev->bios);
3950 	adev->bios = NULL;
3951 	if (amdgpu_device_supports_px(adev_to_drm(adev))) {
3952 		vga_switcheroo_unregister_client(adev->pdev);
3953 		vga_switcheroo_fini_domain_pm_ops(adev->dev);
3954 	}
3955 	if ((adev->pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA)
3956 		vga_client_unregister(adev->pdev);
3957 
3958 	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
3959 
3960 		iounmap(adev->rmmio);
3961 		adev->rmmio = NULL;
3962 		amdgpu_device_doorbell_fini(adev);
3963 		drm_dev_exit(idx);
3964 	}
3965 
3966 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
3967 		amdgpu_pmu_fini(adev);
3968 	if (adev->mman.discovery_bin)
3969 		amdgpu_discovery_fini(adev);
3970 
3971 	kfree(adev->pci_state);
3972 
3973 }
3974 
3975 /**
3976  * amdgpu_device_evict_resources - evict device resources
3977  * @adev: amdgpu device object
3978  *
3979  * Evicts all ttm device resources(vram BOs, gart table) from the lru list
3980  * of the vram memory type. Mainly used for evicting device resources
3981  * at suspend time.
3982  *
3983  */
3984 static void amdgpu_device_evict_resources(struct amdgpu_device *adev)
3985 {
3986 	/* No need to evict vram on APUs for suspend to ram or s2idle */
3987 	if ((adev->in_s3 || adev->in_s0ix) && (adev->flags & AMD_IS_APU))
3988 		return;
3989 
3990 	if (amdgpu_ttm_evict_resources(adev, TTM_PL_VRAM))
3991 		DRM_WARN("evicting device resources failed\n");
3992 
3993 }
3994 
3995 /*
3996  * Suspend & resume.
3997  */
3998 /**
3999  * amdgpu_device_suspend - initiate device suspend
4000  *
4001  * @dev: drm dev pointer
4002  * @fbcon : notify the fbdev of suspend
4003  *
4004  * Puts the hw in the suspend state (all asics).
4005  * Returns 0 for success or an error on failure.
4006  * Called at driver suspend.
4007  */
4008 int amdgpu_device_suspend(struct drm_device *dev, bool fbcon)
4009 {
4010 	struct amdgpu_device *adev = drm_to_adev(dev);
4011 
4012 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
4013 		return 0;
4014 
4015 	adev->in_suspend = true;
4016 
4017 	if (amdgpu_acpi_smart_shift_update(dev, AMDGPU_SS_DEV_D3))
4018 		DRM_WARN("smart shift update failed\n");
4019 
4020 	drm_kms_helper_poll_disable(dev);
4021 
4022 	if (fbcon)
4023 		drm_fb_helper_set_suspend_unlocked(adev_to_drm(adev)->fb_helper, true);
4024 
4025 	cancel_delayed_work_sync(&adev->delayed_init_work);
4026 
4027 	amdgpu_ras_suspend(adev);
4028 
4029 	amdgpu_device_ip_suspend_phase1(adev);
4030 
4031 	if (!adev->in_s0ix)
4032 		amdgpu_amdkfd_suspend(adev, adev->in_runpm);
4033 
4034 	amdgpu_device_evict_resources(adev);
4035 
4036 	amdgpu_fence_driver_hw_fini(adev);
4037 
4038 	amdgpu_device_ip_suspend_phase2(adev);
4039 
4040 	return 0;
4041 }
4042 
4043 /**
4044  * amdgpu_device_resume - initiate device resume
4045  *
4046  * @dev: drm dev pointer
4047  * @fbcon : notify the fbdev of resume
4048  *
4049  * Bring the hw back to operating state (all asics).
4050  * Returns 0 for success or an error on failure.
4051  * Called at driver resume.
4052  */
4053 int amdgpu_device_resume(struct drm_device *dev, bool fbcon)
4054 {
4055 	struct amdgpu_device *adev = drm_to_adev(dev);
4056 	int r = 0;
4057 
4058 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
4059 		return 0;
4060 
4061 	if (adev->in_s0ix)
4062 		amdgpu_dpm_gfx_state_change(adev, sGpuChangeState_D0Entry);
4063 
4064 	/* post card */
4065 	if (amdgpu_device_need_post(adev)) {
4066 		r = amdgpu_device_asic_init(adev);
4067 		if (r)
4068 			dev_err(adev->dev, "amdgpu asic init failed\n");
4069 	}
4070 
4071 	r = amdgpu_device_ip_resume(adev);
4072 	if (r) {
4073 		dev_err(adev->dev, "amdgpu_device_ip_resume failed (%d).\n", r);
4074 		return r;
4075 	}
4076 	amdgpu_fence_driver_hw_init(adev);
4077 
4078 	r = amdgpu_device_ip_late_init(adev);
4079 	if (r)
4080 		return r;
4081 
4082 	queue_delayed_work(system_wq, &adev->delayed_init_work,
4083 			   msecs_to_jiffies(AMDGPU_RESUME_MS));
4084 
4085 	if (!adev->in_s0ix) {
4086 		r = amdgpu_amdkfd_resume(adev, adev->in_runpm);
4087 		if (r)
4088 			return r;
4089 	}
4090 
4091 	/* Make sure IB tests flushed */
4092 	flush_delayed_work(&adev->delayed_init_work);
4093 
4094 	if (fbcon)
4095 		drm_fb_helper_set_suspend_unlocked(adev_to_drm(adev)->fb_helper, false);
4096 
4097 	drm_kms_helper_poll_enable(dev);
4098 
4099 	amdgpu_ras_resume(adev);
4100 
4101 	/*
4102 	 * Most of the connector probing functions try to acquire runtime pm
4103 	 * refs to ensure that the GPU is powered on when connector polling is
4104 	 * performed. Since we're calling this from a runtime PM callback,
4105 	 * trying to acquire rpm refs will cause us to deadlock.
4106 	 *
4107 	 * Since we're guaranteed to be holding the rpm lock, it's safe to
4108 	 * temporarily disable the rpm helpers so this doesn't deadlock us.
4109 	 */
4110 #ifdef CONFIG_PM
4111 	dev->dev->power.disable_depth++;
4112 #endif
4113 	if (!amdgpu_device_has_dc_support(adev))
4114 		drm_helper_hpd_irq_event(dev);
4115 	else
4116 		drm_kms_helper_hotplug_event(dev);
4117 #ifdef CONFIG_PM
4118 	dev->dev->power.disable_depth--;
4119 #endif
4120 	adev->in_suspend = false;
4121 
4122 	if (amdgpu_acpi_smart_shift_update(dev, AMDGPU_SS_DEV_D0))
4123 		DRM_WARN("smart shift update failed\n");
4124 
4125 	return 0;
4126 }
4127 
4128 /**
4129  * amdgpu_device_ip_check_soft_reset - did soft reset succeed
4130  *
4131  * @adev: amdgpu_device pointer
4132  *
4133  * The list of all the hardware IPs that make up the asic is walked and
4134  * the check_soft_reset callbacks are run.  check_soft_reset determines
4135  * if the asic is still hung or not.
4136  * Returns true if any of the IPs are still in a hung state, false if not.
4137  */
4138 static bool amdgpu_device_ip_check_soft_reset(struct amdgpu_device *adev)
4139 {
4140 	int i;
4141 	bool asic_hang = false;
4142 
4143 	if (amdgpu_sriov_vf(adev))
4144 		return true;
4145 
4146 	if (amdgpu_asic_need_full_reset(adev))
4147 		return true;
4148 
4149 	for (i = 0; i < adev->num_ip_blocks; i++) {
4150 		if (!adev->ip_blocks[i].status.valid)
4151 			continue;
4152 		if (adev->ip_blocks[i].version->funcs->check_soft_reset)
4153 			adev->ip_blocks[i].status.hang =
4154 				adev->ip_blocks[i].version->funcs->check_soft_reset(adev);
4155 		if (adev->ip_blocks[i].status.hang) {
4156 			dev_info(adev->dev, "IP block:%s is hung!\n", adev->ip_blocks[i].version->funcs->name);
4157 			asic_hang = true;
4158 		}
4159 	}
4160 	return asic_hang;
4161 }
4162 
4163 /**
4164  * amdgpu_device_ip_pre_soft_reset - prepare for soft reset
4165  *
4166  * @adev: amdgpu_device pointer
4167  *
4168  * The list of all the hardware IPs that make up the asic is walked and the
4169  * pre_soft_reset callbacks are run if the block is hung.  pre_soft_reset
4170  * handles any IP specific hardware or software state changes that are
4171  * necessary for a soft reset to succeed.
4172  * Returns 0 on success, negative error code on failure.
4173  */
4174 static int amdgpu_device_ip_pre_soft_reset(struct amdgpu_device *adev)
4175 {
4176 	int i, r = 0;
4177 
4178 	for (i = 0; i < adev->num_ip_blocks; i++) {
4179 		if (!adev->ip_blocks[i].status.valid)
4180 			continue;
4181 		if (adev->ip_blocks[i].status.hang &&
4182 		    adev->ip_blocks[i].version->funcs->pre_soft_reset) {
4183 			r = adev->ip_blocks[i].version->funcs->pre_soft_reset(adev);
4184 			if (r)
4185 				return r;
4186 		}
4187 	}
4188 
4189 	return 0;
4190 }
4191 
4192 /**
4193  * amdgpu_device_ip_need_full_reset - check if a full asic reset is needed
4194  *
4195  * @adev: amdgpu_device pointer
4196  *
4197  * Some hardware IPs cannot be soft reset.  If they are hung, a full gpu
4198  * reset is necessary to recover.
4199  * Returns true if a full asic reset is required, false if not.
4200  */
4201 static bool amdgpu_device_ip_need_full_reset(struct amdgpu_device *adev)
4202 {
4203 	int i;
4204 
4205 	if (amdgpu_asic_need_full_reset(adev))
4206 		return true;
4207 
4208 	for (i = 0; i < adev->num_ip_blocks; i++) {
4209 		if (!adev->ip_blocks[i].status.valid)
4210 			continue;
4211 		if ((adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) ||
4212 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) ||
4213 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_ACP) ||
4214 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) ||
4215 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
4216 			if (adev->ip_blocks[i].status.hang) {
4217 				dev_info(adev->dev, "Some block need full reset!\n");
4218 				return true;
4219 			}
4220 		}
4221 	}
4222 	return false;
4223 }
4224 
4225 /**
4226  * amdgpu_device_ip_soft_reset - do a soft reset
4227  *
4228  * @adev: amdgpu_device pointer
4229  *
4230  * The list of all the hardware IPs that make up the asic is walked and the
4231  * soft_reset callbacks are run if the block is hung.  soft_reset handles any
4232  * IP specific hardware or software state changes that are necessary to soft
4233  * reset the IP.
4234  * Returns 0 on success, negative error code on failure.
4235  */
4236 static int amdgpu_device_ip_soft_reset(struct amdgpu_device *adev)
4237 {
4238 	int i, r = 0;
4239 
4240 	for (i = 0; i < adev->num_ip_blocks; i++) {
4241 		if (!adev->ip_blocks[i].status.valid)
4242 			continue;
4243 		if (adev->ip_blocks[i].status.hang &&
4244 		    adev->ip_blocks[i].version->funcs->soft_reset) {
4245 			r = adev->ip_blocks[i].version->funcs->soft_reset(adev);
4246 			if (r)
4247 				return r;
4248 		}
4249 	}
4250 
4251 	return 0;
4252 }
4253 
4254 /**
4255  * amdgpu_device_ip_post_soft_reset - clean up from soft reset
4256  *
4257  * @adev: amdgpu_device pointer
4258  *
4259  * The list of all the hardware IPs that make up the asic is walked and the
4260  * post_soft_reset callbacks are run if the asic was hung.  post_soft_reset
4261  * handles any IP specific hardware or software state changes that are
4262  * necessary after the IP has been soft reset.
4263  * Returns 0 on success, negative error code on failure.
4264  */
4265 static int amdgpu_device_ip_post_soft_reset(struct amdgpu_device *adev)
4266 {
4267 	int i, r = 0;
4268 
4269 	for (i = 0; i < adev->num_ip_blocks; i++) {
4270 		if (!adev->ip_blocks[i].status.valid)
4271 			continue;
4272 		if (adev->ip_blocks[i].status.hang &&
4273 		    adev->ip_blocks[i].version->funcs->post_soft_reset)
4274 			r = adev->ip_blocks[i].version->funcs->post_soft_reset(adev);
4275 		if (r)
4276 			return r;
4277 	}
4278 
4279 	return 0;
4280 }
4281 
4282 /**
4283  * amdgpu_device_recover_vram - Recover some VRAM contents
4284  *
4285  * @adev: amdgpu_device pointer
4286  *
4287  * Restores the contents of VRAM buffers from the shadows in GTT.  Used to
4288  * restore things like GPUVM page tables after a GPU reset where
4289  * the contents of VRAM might be lost.
4290  *
4291  * Returns:
4292  * 0 on success, negative error code on failure.
4293  */
4294 static int amdgpu_device_recover_vram(struct amdgpu_device *adev)
4295 {
4296 	struct dma_fence *fence = NULL, *next = NULL;
4297 	struct amdgpu_bo *shadow;
4298 	struct amdgpu_bo_vm *vmbo;
4299 	long r = 1, tmo;
4300 
4301 	if (amdgpu_sriov_runtime(adev))
4302 		tmo = msecs_to_jiffies(8000);
4303 	else
4304 		tmo = msecs_to_jiffies(100);
4305 
4306 	dev_info(adev->dev, "recover vram bo from shadow start\n");
4307 	mutex_lock(&adev->shadow_list_lock);
4308 	list_for_each_entry(vmbo, &adev->shadow_list, shadow_list) {
4309 		shadow = &vmbo->bo;
4310 		/* No need to recover an evicted BO */
4311 		if (shadow->tbo.resource->mem_type != TTM_PL_TT ||
4312 		    shadow->tbo.resource->start == AMDGPU_BO_INVALID_OFFSET ||
4313 		    shadow->parent->tbo.resource->mem_type != TTM_PL_VRAM)
4314 			continue;
4315 
4316 		r = amdgpu_bo_restore_shadow(shadow, &next);
4317 		if (r)
4318 			break;
4319 
4320 		if (fence) {
4321 			tmo = dma_fence_wait_timeout(fence, false, tmo);
4322 			dma_fence_put(fence);
4323 			fence = next;
4324 			if (tmo == 0) {
4325 				r = -ETIMEDOUT;
4326 				break;
4327 			} else if (tmo < 0) {
4328 				r = tmo;
4329 				break;
4330 			}
4331 		} else {
4332 			fence = next;
4333 		}
4334 	}
4335 	mutex_unlock(&adev->shadow_list_lock);
4336 
4337 	if (fence)
4338 		tmo = dma_fence_wait_timeout(fence, false, tmo);
4339 	dma_fence_put(fence);
4340 
4341 	if (r < 0 || tmo <= 0) {
4342 		dev_err(adev->dev, "recover vram bo from shadow failed, r is %ld, tmo is %ld\n", r, tmo);
4343 		return -EIO;
4344 	}
4345 
4346 	dev_info(adev->dev, "recover vram bo from shadow done\n");
4347 	return 0;
4348 }
4349 
4350 
4351 /**
4352  * amdgpu_device_reset_sriov - reset ASIC for SR-IOV vf
4353  *
4354  * @adev: amdgpu_device pointer
4355  * @from_hypervisor: request from hypervisor
4356  *
4357  * do VF FLR and reinitialize Asic
4358  * return 0 means succeeded otherwise failed
4359  */
4360 static int amdgpu_device_reset_sriov(struct amdgpu_device *adev,
4361 				     bool from_hypervisor)
4362 {
4363 	int r;
4364 	struct amdgpu_hive_info *hive = NULL;
4365 
4366 	amdgpu_amdkfd_pre_reset(adev);
4367 
4368 	amdgpu_amdkfd_pre_reset(adev);
4369 
4370 	if (from_hypervisor)
4371 		r = amdgpu_virt_request_full_gpu(adev, true);
4372 	else
4373 		r = amdgpu_virt_reset_gpu(adev);
4374 	if (r)
4375 		return r;
4376 
4377 	/* Resume IP prior to SMC */
4378 	r = amdgpu_device_ip_reinit_early_sriov(adev);
4379 	if (r)
4380 		goto error;
4381 
4382 	amdgpu_virt_init_data_exchange(adev);
4383 
4384 	r = amdgpu_device_fw_loading(adev);
4385 	if (r)
4386 		return r;
4387 
4388 	/* now we are okay to resume SMC/CP/SDMA */
4389 	r = amdgpu_device_ip_reinit_late_sriov(adev);
4390 	if (r)
4391 		goto error;
4392 
4393 	hive = amdgpu_get_xgmi_hive(adev);
4394 	/* Update PSP FW topology after reset */
4395 	if (hive && adev->gmc.xgmi.num_physical_nodes > 1)
4396 		r = amdgpu_xgmi_update_topology(hive, adev);
4397 
4398 	if (hive)
4399 		amdgpu_put_xgmi_hive(hive);
4400 
4401 	if (!r) {
4402 		amdgpu_irq_gpu_reset_resume_helper(adev);
4403 		r = amdgpu_ib_ring_tests(adev);
4404 		amdgpu_amdkfd_post_reset(adev);
4405 	}
4406 
4407 error:
4408 	if (!r && adev->virt.gim_feature & AMDGIM_FEATURE_GIM_FLR_VRAMLOST) {
4409 		amdgpu_inc_vram_lost(adev);
4410 		r = amdgpu_device_recover_vram(adev);
4411 	}
4412 	amdgpu_virt_release_full_gpu(adev, true);
4413 
4414 	return r;
4415 }
4416 
4417 /**
4418  * amdgpu_device_has_job_running - check if there is any job in mirror list
4419  *
4420  * @adev: amdgpu_device pointer
4421  *
4422  * check if there is any job in mirror list
4423  */
4424 bool amdgpu_device_has_job_running(struct amdgpu_device *adev)
4425 {
4426 	int i;
4427 	struct drm_sched_job *job;
4428 
4429 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4430 		struct amdgpu_ring *ring = adev->rings[i];
4431 
4432 		if (!ring || !ring->sched.thread)
4433 			continue;
4434 
4435 		spin_lock(&ring->sched.job_list_lock);
4436 		job = list_first_entry_or_null(&ring->sched.pending_list,
4437 					       struct drm_sched_job, list);
4438 		spin_unlock(&ring->sched.job_list_lock);
4439 		if (job)
4440 			return true;
4441 	}
4442 	return false;
4443 }
4444 
4445 /**
4446  * amdgpu_device_should_recover_gpu - check if we should try GPU recovery
4447  *
4448  * @adev: amdgpu_device pointer
4449  *
4450  * Check amdgpu_gpu_recovery and SRIOV status to see if we should try to recover
4451  * a hung GPU.
4452  */
4453 bool amdgpu_device_should_recover_gpu(struct amdgpu_device *adev)
4454 {
4455 	if (!amdgpu_device_ip_check_soft_reset(adev)) {
4456 		dev_info(adev->dev, "Timeout, but no hardware hang detected.\n");
4457 		return false;
4458 	}
4459 
4460 	if (amdgpu_gpu_recovery == 0)
4461 		goto disabled;
4462 
4463 	if (amdgpu_sriov_vf(adev))
4464 		return true;
4465 
4466 	if (amdgpu_gpu_recovery == -1) {
4467 		switch (adev->asic_type) {
4468 #ifdef CONFIG_DRM_AMDGPU_SI
4469 		case CHIP_VERDE:
4470 		case CHIP_TAHITI:
4471 		case CHIP_PITCAIRN:
4472 		case CHIP_OLAND:
4473 		case CHIP_HAINAN:
4474 #endif
4475 #ifdef CONFIG_DRM_AMDGPU_CIK
4476 		case CHIP_KAVERI:
4477 		case CHIP_KABINI:
4478 		case CHIP_MULLINS:
4479 #endif
4480 		case CHIP_CARRIZO:
4481 		case CHIP_STONEY:
4482 		case CHIP_CYAN_SKILLFISH:
4483 			goto disabled;
4484 		default:
4485 			break;
4486 		}
4487 	}
4488 
4489 	return true;
4490 
4491 disabled:
4492 		dev_info(adev->dev, "GPU recovery disabled.\n");
4493 		return false;
4494 }
4495 
4496 int amdgpu_device_mode1_reset(struct amdgpu_device *adev)
4497 {
4498         u32 i;
4499         int ret = 0;
4500 
4501         amdgpu_atombios_scratch_regs_engine_hung(adev, true);
4502 
4503         dev_info(adev->dev, "GPU mode1 reset\n");
4504 
4505         /* disable BM */
4506         pci_clear_master(adev->pdev);
4507 
4508         amdgpu_device_cache_pci_state(adev->pdev);
4509 
4510         if (amdgpu_dpm_is_mode1_reset_supported(adev)) {
4511                 dev_info(adev->dev, "GPU smu mode1 reset\n");
4512                 ret = amdgpu_dpm_mode1_reset(adev);
4513         } else {
4514                 dev_info(adev->dev, "GPU psp mode1 reset\n");
4515                 ret = psp_gpu_reset(adev);
4516         }
4517 
4518         if (ret)
4519                 dev_err(adev->dev, "GPU mode1 reset failed\n");
4520 
4521         amdgpu_device_load_pci_state(adev->pdev);
4522 
4523         /* wait for asic to come out of reset */
4524         for (i = 0; i < adev->usec_timeout; i++) {
4525                 u32 memsize = adev->nbio.funcs->get_memsize(adev);
4526 
4527                 if (memsize != 0xffffffff)
4528                         break;
4529                 udelay(1);
4530         }
4531 
4532         amdgpu_atombios_scratch_regs_engine_hung(adev, false);
4533         return ret;
4534 }
4535 
4536 int amdgpu_device_pre_asic_reset(struct amdgpu_device *adev,
4537 				 struct amdgpu_reset_context *reset_context)
4538 {
4539 	int i, r = 0;
4540 	struct amdgpu_job *job = NULL;
4541 	bool need_full_reset =
4542 		test_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
4543 
4544 	if (reset_context->reset_req_dev == adev)
4545 		job = reset_context->job;
4546 
4547 	if (amdgpu_sriov_vf(adev)) {
4548 		/* stop the data exchange thread */
4549 		amdgpu_virt_fini_data_exchange(adev);
4550 	}
4551 
4552 	/* block all schedulers and reset given job's ring */
4553 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4554 		struct amdgpu_ring *ring = adev->rings[i];
4555 
4556 		if (!ring || !ring->sched.thread)
4557 			continue;
4558 
4559 		/*clear job fence from fence drv to avoid force_completion
4560 		 *leave NULL and vm flush fence in fence drv */
4561 		amdgpu_fence_driver_clear_job_fences(ring);
4562 
4563 		/* after all hw jobs are reset, hw fence is meaningless, so force_completion */
4564 		amdgpu_fence_driver_force_completion(ring);
4565 	}
4566 
4567 	if (job && job->vm)
4568 		drm_sched_increase_karma(&job->base);
4569 
4570 	r = amdgpu_reset_prepare_hwcontext(adev, reset_context);
4571 	/* If reset handler not implemented, continue; otherwise return */
4572 	if (r == -ENOSYS)
4573 		r = 0;
4574 	else
4575 		return r;
4576 
4577 	/* Don't suspend on bare metal if we are not going to HW reset the ASIC */
4578 	if (!amdgpu_sriov_vf(adev)) {
4579 
4580 		if (!need_full_reset)
4581 			need_full_reset = amdgpu_device_ip_need_full_reset(adev);
4582 
4583 		if (!need_full_reset) {
4584 			amdgpu_device_ip_pre_soft_reset(adev);
4585 			r = amdgpu_device_ip_soft_reset(adev);
4586 			amdgpu_device_ip_post_soft_reset(adev);
4587 			if (r || amdgpu_device_ip_check_soft_reset(adev)) {
4588 				dev_info(adev->dev, "soft reset failed, will fallback to full reset!\n");
4589 				need_full_reset = true;
4590 			}
4591 		}
4592 
4593 		if (need_full_reset)
4594 			r = amdgpu_device_ip_suspend(adev);
4595 		if (need_full_reset)
4596 			set_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
4597 		else
4598 			clear_bit(AMDGPU_NEED_FULL_RESET,
4599 				  &reset_context->flags);
4600 	}
4601 
4602 	return r;
4603 }
4604 
4605 int amdgpu_do_asic_reset(struct list_head *device_list_handle,
4606 			 struct amdgpu_reset_context *reset_context)
4607 {
4608 	struct amdgpu_device *tmp_adev = NULL;
4609 	bool need_full_reset, skip_hw_reset, vram_lost = false;
4610 	int r = 0;
4611 
4612 	/* Try reset handler method first */
4613 	tmp_adev = list_first_entry(device_list_handle, struct amdgpu_device,
4614 				    reset_list);
4615 	r = amdgpu_reset_perform_reset(tmp_adev, reset_context);
4616 	/* If reset handler not implemented, continue; otherwise return */
4617 	if (r == -ENOSYS)
4618 		r = 0;
4619 	else
4620 		return r;
4621 
4622 	/* Reset handler not implemented, use the default method */
4623 	need_full_reset =
4624 		test_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
4625 	skip_hw_reset = test_bit(AMDGPU_SKIP_HW_RESET, &reset_context->flags);
4626 
4627 	/*
4628 	 * ASIC reset has to be done on all XGMI hive nodes ASAP
4629 	 * to allow proper links negotiation in FW (within 1 sec)
4630 	 */
4631 	if (!skip_hw_reset && need_full_reset) {
4632 		list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
4633 			/* For XGMI run all resets in parallel to speed up the process */
4634 			if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
4635 				tmp_adev->gmc.xgmi.pending_reset = false;
4636 				if (!queue_work(system_unbound_wq, &tmp_adev->xgmi_reset_work))
4637 					r = -EALREADY;
4638 			} else
4639 				r = amdgpu_asic_reset(tmp_adev);
4640 
4641 			if (r) {
4642 				dev_err(tmp_adev->dev, "ASIC reset failed with error, %d for drm dev, %s",
4643 					 r, adev_to_drm(tmp_adev)->unique);
4644 				break;
4645 			}
4646 		}
4647 
4648 		/* For XGMI wait for all resets to complete before proceed */
4649 		if (!r) {
4650 			list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
4651 				if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
4652 					flush_work(&tmp_adev->xgmi_reset_work);
4653 					r = tmp_adev->asic_reset_res;
4654 					if (r)
4655 						break;
4656 				}
4657 			}
4658 		}
4659 	}
4660 
4661 	if (!r && amdgpu_ras_intr_triggered()) {
4662 		list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
4663 			if (tmp_adev->mmhub.ras && tmp_adev->mmhub.ras->ras_block.hw_ops &&
4664 			    tmp_adev->mmhub.ras->ras_block.hw_ops->reset_ras_error_count)
4665 				tmp_adev->mmhub.ras->ras_block.hw_ops->reset_ras_error_count(tmp_adev);
4666 		}
4667 
4668 		amdgpu_ras_intr_cleared();
4669 	}
4670 
4671 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
4672 		if (need_full_reset) {
4673 			/* post card */
4674 			r = amdgpu_device_asic_init(tmp_adev);
4675 			if (r) {
4676 				dev_warn(tmp_adev->dev, "asic atom init failed!");
4677 			} else {
4678 				dev_info(tmp_adev->dev, "GPU reset succeeded, trying to resume\n");
4679 				r = amdgpu_amdkfd_resume_iommu(tmp_adev);
4680 				if (r)
4681 					goto out;
4682 
4683 				r = amdgpu_device_ip_resume_phase1(tmp_adev);
4684 				if (r)
4685 					goto out;
4686 
4687 				vram_lost = amdgpu_device_check_vram_lost(tmp_adev);
4688 				if (vram_lost) {
4689 					DRM_INFO("VRAM is lost due to GPU reset!\n");
4690 					amdgpu_inc_vram_lost(tmp_adev);
4691 				}
4692 
4693 				r = amdgpu_device_fw_loading(tmp_adev);
4694 				if (r)
4695 					return r;
4696 
4697 				r = amdgpu_device_ip_resume_phase2(tmp_adev);
4698 				if (r)
4699 					goto out;
4700 
4701 				if (vram_lost)
4702 					amdgpu_device_fill_reset_magic(tmp_adev);
4703 
4704 				/*
4705 				 * Add this ASIC as tracked as reset was already
4706 				 * complete successfully.
4707 				 */
4708 				amdgpu_register_gpu_instance(tmp_adev);
4709 
4710 				if (!reset_context->hive &&
4711 				    tmp_adev->gmc.xgmi.num_physical_nodes > 1)
4712 					amdgpu_xgmi_add_device(tmp_adev);
4713 
4714 				r = amdgpu_device_ip_late_init(tmp_adev);
4715 				if (r)
4716 					goto out;
4717 
4718 				drm_fb_helper_set_suspend_unlocked(adev_to_drm(tmp_adev)->fb_helper, false);
4719 
4720 				/*
4721 				 * The GPU enters bad state once faulty pages
4722 				 * by ECC has reached the threshold, and ras
4723 				 * recovery is scheduled next. So add one check
4724 				 * here to break recovery if it indeed exceeds
4725 				 * bad page threshold, and remind user to
4726 				 * retire this GPU or setting one bigger
4727 				 * bad_page_threshold value to fix this once
4728 				 * probing driver again.
4729 				 */
4730 				if (!amdgpu_ras_eeprom_check_err_threshold(tmp_adev)) {
4731 					/* must succeed. */
4732 					amdgpu_ras_resume(tmp_adev);
4733 				} else {
4734 					r = -EINVAL;
4735 					goto out;
4736 				}
4737 
4738 				/* Update PSP FW topology after reset */
4739 				if (reset_context->hive &&
4740 				    tmp_adev->gmc.xgmi.num_physical_nodes > 1)
4741 					r = amdgpu_xgmi_update_topology(
4742 						reset_context->hive, tmp_adev);
4743 			}
4744 		}
4745 
4746 out:
4747 		if (!r) {
4748 			amdgpu_irq_gpu_reset_resume_helper(tmp_adev);
4749 			r = amdgpu_ib_ring_tests(tmp_adev);
4750 			if (r) {
4751 				dev_err(tmp_adev->dev, "ib ring test failed (%d).\n", r);
4752 				need_full_reset = true;
4753 				r = -EAGAIN;
4754 				goto end;
4755 			}
4756 		}
4757 
4758 		if (!r)
4759 			r = amdgpu_device_recover_vram(tmp_adev);
4760 		else
4761 			tmp_adev->asic_reset_res = r;
4762 	}
4763 
4764 end:
4765 	if (need_full_reset)
4766 		set_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
4767 	else
4768 		clear_bit(AMDGPU_NEED_FULL_RESET, &reset_context->flags);
4769 	return r;
4770 }
4771 
4772 static bool amdgpu_device_lock_adev(struct amdgpu_device *adev,
4773 				struct amdgpu_hive_info *hive)
4774 {
4775 	if (atomic_cmpxchg(&adev->in_gpu_reset, 0, 1) != 0)
4776 		return false;
4777 
4778 	if (hive) {
4779 		down_write_nest_lock(&adev->reset_sem, &hive->hive_lock);
4780 	} else {
4781 		down_write(&adev->reset_sem);
4782 	}
4783 
4784 	switch (amdgpu_asic_reset_method(adev)) {
4785 	case AMD_RESET_METHOD_MODE1:
4786 		adev->mp1_state = PP_MP1_STATE_SHUTDOWN;
4787 		break;
4788 	case AMD_RESET_METHOD_MODE2:
4789 		adev->mp1_state = PP_MP1_STATE_RESET;
4790 		break;
4791 	default:
4792 		adev->mp1_state = PP_MP1_STATE_NONE;
4793 		break;
4794 	}
4795 
4796 	return true;
4797 }
4798 
4799 static void amdgpu_device_unlock_adev(struct amdgpu_device *adev)
4800 {
4801 	amdgpu_vf_error_trans_all(adev);
4802 	adev->mp1_state = PP_MP1_STATE_NONE;
4803 	atomic_set(&adev->in_gpu_reset, 0);
4804 	up_write(&adev->reset_sem);
4805 }
4806 
4807 /*
4808  * to lockup a list of amdgpu devices in a hive safely, if not a hive
4809  * with multiple nodes, it will be similar as amdgpu_device_lock_adev.
4810  *
4811  * unlock won't require roll back.
4812  */
4813 static int amdgpu_device_lock_hive_adev(struct amdgpu_device *adev, struct amdgpu_hive_info *hive)
4814 {
4815 	struct amdgpu_device *tmp_adev = NULL;
4816 
4817 	if (!amdgpu_sriov_vf(adev) && (adev->gmc.xgmi.num_physical_nodes > 1)) {
4818 		if (!hive) {
4819 			dev_err(adev->dev, "Hive is NULL while device has multiple xgmi nodes");
4820 			return -ENODEV;
4821 		}
4822 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head) {
4823 			if (!amdgpu_device_lock_adev(tmp_adev, hive))
4824 				goto roll_back;
4825 		}
4826 	} else if (!amdgpu_device_lock_adev(adev, hive))
4827 		return -EAGAIN;
4828 
4829 	return 0;
4830 roll_back:
4831 	if (!list_is_first(&tmp_adev->gmc.xgmi.head, &hive->device_list)) {
4832 		/*
4833 		 * if the lockup iteration break in the middle of a hive,
4834 		 * it may means there may has a race issue,
4835 		 * or a hive device locked up independently.
4836 		 * we may be in trouble and may not, so will try to roll back
4837 		 * the lock and give out a warnning.
4838 		 */
4839 		dev_warn(tmp_adev->dev, "Hive lock iteration broke in the middle. Rolling back to unlock");
4840 		list_for_each_entry_continue_reverse(tmp_adev, &hive->device_list, gmc.xgmi.head) {
4841 			amdgpu_device_unlock_adev(tmp_adev);
4842 		}
4843 	}
4844 	return -EAGAIN;
4845 }
4846 
4847 static void amdgpu_device_resume_display_audio(struct amdgpu_device *adev)
4848 {
4849 	struct pci_dev *p = NULL;
4850 
4851 	p = pci_get_domain_bus_and_slot(pci_domain_nr(adev->pdev->bus),
4852 			adev->pdev->bus->number, 1);
4853 	if (p) {
4854 		pm_runtime_enable(&(p->dev));
4855 		pm_runtime_resume(&(p->dev));
4856 	}
4857 }
4858 
4859 static int amdgpu_device_suspend_display_audio(struct amdgpu_device *adev)
4860 {
4861 	enum amd_reset_method reset_method;
4862 	struct pci_dev *p = NULL;
4863 	u64 expires;
4864 
4865 	/*
4866 	 * For now, only BACO and mode1 reset are confirmed
4867 	 * to suffer the audio issue without proper suspended.
4868 	 */
4869 	reset_method = amdgpu_asic_reset_method(adev);
4870 	if ((reset_method != AMD_RESET_METHOD_BACO) &&
4871 	     (reset_method != AMD_RESET_METHOD_MODE1))
4872 		return -EINVAL;
4873 
4874 	p = pci_get_domain_bus_and_slot(pci_domain_nr(adev->pdev->bus),
4875 			adev->pdev->bus->number, 1);
4876 	if (!p)
4877 		return -ENODEV;
4878 
4879 	expires = pm_runtime_autosuspend_expiration(&(p->dev));
4880 	if (!expires)
4881 		/*
4882 		 * If we cannot get the audio device autosuspend delay,
4883 		 * a fixed 4S interval will be used. Considering 3S is
4884 		 * the audio controller default autosuspend delay setting.
4885 		 * 4S used here is guaranteed to cover that.
4886 		 */
4887 		expires = ktime_get_mono_fast_ns() + NSEC_PER_SEC * 4ULL;
4888 
4889 	while (!pm_runtime_status_suspended(&(p->dev))) {
4890 		if (!pm_runtime_suspend(&(p->dev)))
4891 			break;
4892 
4893 		if (expires < ktime_get_mono_fast_ns()) {
4894 			dev_warn(adev->dev, "failed to suspend display audio\n");
4895 			/* TODO: abort the succeeding gpu reset? */
4896 			return -ETIMEDOUT;
4897 		}
4898 	}
4899 
4900 	pm_runtime_disable(&(p->dev));
4901 
4902 	return 0;
4903 }
4904 
4905 static void amdgpu_device_recheck_guilty_jobs(
4906 	struct amdgpu_device *adev, struct list_head *device_list_handle,
4907 	struct amdgpu_reset_context *reset_context)
4908 {
4909 	int i, r = 0;
4910 
4911 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4912 		struct amdgpu_ring *ring = adev->rings[i];
4913 		int ret = 0;
4914 		struct drm_sched_job *s_job;
4915 
4916 		if (!ring || !ring->sched.thread)
4917 			continue;
4918 
4919 		s_job = list_first_entry_or_null(&ring->sched.pending_list,
4920 				struct drm_sched_job, list);
4921 		if (s_job == NULL)
4922 			continue;
4923 
4924 		/* clear job's guilty and depend the folowing step to decide the real one */
4925 		drm_sched_reset_karma(s_job);
4926 		/* for the real bad job, it will be resubmitted twice, adding a dma_fence_get
4927 		 * to make sure fence is balanced */
4928 		dma_fence_get(s_job->s_fence->parent);
4929 		drm_sched_resubmit_jobs_ext(&ring->sched, 1);
4930 
4931 		ret = dma_fence_wait_timeout(s_job->s_fence->parent, false, ring->sched.timeout);
4932 		if (ret == 0) { /* timeout */
4933 			DRM_ERROR("Found the real bad job! ring:%s, job_id:%llx\n",
4934 						ring->sched.name, s_job->id);
4935 
4936 			/* set guilty */
4937 			drm_sched_increase_karma(s_job);
4938 retry:
4939 			/* do hw reset */
4940 			if (amdgpu_sriov_vf(adev)) {
4941 				amdgpu_virt_fini_data_exchange(adev);
4942 				r = amdgpu_device_reset_sriov(adev, false);
4943 				if (r)
4944 					adev->asic_reset_res = r;
4945 			} else {
4946 				clear_bit(AMDGPU_SKIP_HW_RESET,
4947 					  &reset_context->flags);
4948 				r = amdgpu_do_asic_reset(device_list_handle,
4949 							 reset_context);
4950 				if (r && r == -EAGAIN)
4951 					goto retry;
4952 			}
4953 
4954 			/*
4955 			 * add reset counter so that the following
4956 			 * resubmitted job could flush vmid
4957 			 */
4958 			atomic_inc(&adev->gpu_reset_counter);
4959 			continue;
4960 		}
4961 
4962 		/* got the hw fence, signal finished fence */
4963 		atomic_dec(ring->sched.score);
4964 		dma_fence_put(s_job->s_fence->parent);
4965 		dma_fence_get(&s_job->s_fence->finished);
4966 		dma_fence_signal(&s_job->s_fence->finished);
4967 		dma_fence_put(&s_job->s_fence->finished);
4968 
4969 		/* remove node from list and free the job */
4970 		spin_lock(&ring->sched.job_list_lock);
4971 		list_del_init(&s_job->list);
4972 		spin_unlock(&ring->sched.job_list_lock);
4973 		ring->sched.ops->free_job(s_job);
4974 	}
4975 }
4976 
4977 /**
4978  * amdgpu_device_gpu_recover - reset the asic and recover scheduler
4979  *
4980  * @adev: amdgpu_device pointer
4981  * @job: which job trigger hang
4982  *
4983  * Attempt to reset the GPU if it has hung (all asics).
4984  * Attempt to do soft-reset or full-reset and reinitialize Asic
4985  * Returns 0 for success or an error on failure.
4986  */
4987 
4988 int amdgpu_device_gpu_recover(struct amdgpu_device *adev,
4989 			      struct amdgpu_job *job)
4990 {
4991 	struct list_head device_list, *device_list_handle =  NULL;
4992 	bool job_signaled = false;
4993 	struct amdgpu_hive_info *hive = NULL;
4994 	struct amdgpu_device *tmp_adev = NULL;
4995 	int i, r = 0;
4996 	bool need_emergency_restart = false;
4997 	bool audio_suspended = false;
4998 	int tmp_vram_lost_counter;
4999 	struct amdgpu_reset_context reset_context;
5000 
5001 	memset(&reset_context, 0, sizeof(reset_context));
5002 
5003 	/*
5004 	 * Special case: RAS triggered and full reset isn't supported
5005 	 */
5006 	need_emergency_restart = amdgpu_ras_need_emergency_restart(adev);
5007 
5008 	/*
5009 	 * Flush RAM to disk so that after reboot
5010 	 * the user can read log and see why the system rebooted.
5011 	 */
5012 	if (need_emergency_restart && amdgpu_ras_get_context(adev)->reboot) {
5013 		DRM_WARN("Emergency reboot.");
5014 
5015 		ksys_sync_helper();
5016 		emergency_restart();
5017 	}
5018 
5019 	dev_info(adev->dev, "GPU %s begin!\n",
5020 		need_emergency_restart ? "jobs stop":"reset");
5021 
5022 	/*
5023 	 * Here we trylock to avoid chain of resets executing from
5024 	 * either trigger by jobs on different adevs in XGMI hive or jobs on
5025 	 * different schedulers for same device while this TO handler is running.
5026 	 * We always reset all schedulers for device and all devices for XGMI
5027 	 * hive so that should take care of them too.
5028 	 */
5029 	if (!amdgpu_sriov_vf(adev))
5030 		hive = amdgpu_get_xgmi_hive(adev);
5031 	if (hive) {
5032 		if (atomic_cmpxchg(&hive->in_reset, 0, 1) != 0) {
5033 			DRM_INFO("Bailing on TDR for s_job:%llx, hive: %llx as another already in progress",
5034 				job ? job->base.id : -1, hive->hive_id);
5035 			amdgpu_put_xgmi_hive(hive);
5036 			if (job && job->vm)
5037 				drm_sched_increase_karma(&job->base);
5038 			return 0;
5039 		}
5040 		mutex_lock(&hive->hive_lock);
5041 	}
5042 
5043 	reset_context.method = AMD_RESET_METHOD_NONE;
5044 	reset_context.reset_req_dev = adev;
5045 	reset_context.job = job;
5046 	reset_context.hive = hive;
5047 	clear_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
5048 
5049 	/*
5050 	 * lock the device before we try to operate the linked list
5051 	 * if didn't get the device lock, don't touch the linked list since
5052 	 * others may iterating it.
5053 	 */
5054 	r = amdgpu_device_lock_hive_adev(adev, hive);
5055 	if (r) {
5056 		dev_info(adev->dev, "Bailing on TDR for s_job:%llx, as another already in progress",
5057 					job ? job->base.id : -1);
5058 
5059 		/* even we skipped this reset, still need to set the job to guilty */
5060 		if (job && job->vm)
5061 			drm_sched_increase_karma(&job->base);
5062 		goto skip_recovery;
5063 	}
5064 
5065 	/*
5066 	 * Build list of devices to reset.
5067 	 * In case we are in XGMI hive mode, resort the device list
5068 	 * to put adev in the 1st position.
5069 	 */
5070 	INIT_LIST_HEAD(&device_list);
5071 	if (!amdgpu_sriov_vf(adev) && (adev->gmc.xgmi.num_physical_nodes > 1)) {
5072 		list_for_each_entry(tmp_adev, &hive->device_list, gmc.xgmi.head)
5073 			list_add_tail(&tmp_adev->reset_list, &device_list);
5074 		if (!list_is_first(&adev->reset_list, &device_list))
5075 			list_rotate_to_front(&adev->reset_list, &device_list);
5076 		device_list_handle = &device_list;
5077 	} else {
5078 		list_add_tail(&adev->reset_list, &device_list);
5079 		device_list_handle = &device_list;
5080 	}
5081 
5082 	/* block all schedulers and reset given job's ring */
5083 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5084 		/*
5085 		 * Try to put the audio codec into suspend state
5086 		 * before gpu reset started.
5087 		 *
5088 		 * Due to the power domain of the graphics device
5089 		 * is shared with AZ power domain. Without this,
5090 		 * we may change the audio hardware from behind
5091 		 * the audio driver's back. That will trigger
5092 		 * some audio codec errors.
5093 		 */
5094 		if (!amdgpu_device_suspend_display_audio(tmp_adev))
5095 			audio_suspended = true;
5096 
5097 		amdgpu_ras_set_error_query_ready(tmp_adev, false);
5098 
5099 		cancel_delayed_work_sync(&tmp_adev->delayed_init_work);
5100 
5101 		if (!amdgpu_sriov_vf(tmp_adev))
5102 			amdgpu_amdkfd_pre_reset(tmp_adev);
5103 
5104 		/*
5105 		 * Mark these ASICs to be reseted as untracked first
5106 		 * And add them back after reset completed
5107 		 */
5108 		amdgpu_unregister_gpu_instance(tmp_adev);
5109 
5110 		drm_fb_helper_set_suspend_unlocked(adev_to_drm(adev)->fb_helper, true);
5111 
5112 		/* disable ras on ALL IPs */
5113 		if (!need_emergency_restart &&
5114 		      amdgpu_device_ip_need_full_reset(tmp_adev))
5115 			amdgpu_ras_suspend(tmp_adev);
5116 
5117 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5118 			struct amdgpu_ring *ring = tmp_adev->rings[i];
5119 
5120 			if (!ring || !ring->sched.thread)
5121 				continue;
5122 
5123 			drm_sched_stop(&ring->sched, job ? &job->base : NULL);
5124 
5125 			if (need_emergency_restart)
5126 				amdgpu_job_stop_all_jobs_on_sched(&ring->sched);
5127 		}
5128 		atomic_inc(&tmp_adev->gpu_reset_counter);
5129 	}
5130 
5131 	if (need_emergency_restart)
5132 		goto skip_sched_resume;
5133 
5134 	/*
5135 	 * Must check guilty signal here since after this point all old
5136 	 * HW fences are force signaled.
5137 	 *
5138 	 * job->base holds a reference to parent fence
5139 	 */
5140 	if (job && job->base.s_fence->parent &&
5141 	    dma_fence_is_signaled(job->base.s_fence->parent)) {
5142 		job_signaled = true;
5143 		dev_info(adev->dev, "Guilty job already signaled, skipping HW reset");
5144 		goto skip_hw_reset;
5145 	}
5146 
5147 retry:	/* Rest of adevs pre asic reset from XGMI hive. */
5148 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5149 		r = amdgpu_device_pre_asic_reset(tmp_adev, &reset_context);
5150 		/*TODO Should we stop ?*/
5151 		if (r) {
5152 			dev_err(tmp_adev->dev, "GPU pre asic reset failed with err, %d for drm dev, %s ",
5153 				  r, adev_to_drm(tmp_adev)->unique);
5154 			tmp_adev->asic_reset_res = r;
5155 		}
5156 	}
5157 
5158 	tmp_vram_lost_counter = atomic_read(&((adev)->vram_lost_counter));
5159 	/* Actual ASIC resets if needed.*/
5160 	/* Host driver will handle XGMI hive reset for SRIOV */
5161 	if (amdgpu_sriov_vf(adev)) {
5162 		r = amdgpu_device_reset_sriov(adev, job ? false : true);
5163 		if (r)
5164 			adev->asic_reset_res = r;
5165 	} else {
5166 		r = amdgpu_do_asic_reset(device_list_handle, &reset_context);
5167 		if (r && r == -EAGAIN)
5168 			goto retry;
5169 	}
5170 
5171 skip_hw_reset:
5172 
5173 	/* Post ASIC reset for all devs .*/
5174 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5175 
5176 		/*
5177 		 * Sometimes a later bad compute job can block a good gfx job as gfx
5178 		 * and compute ring share internal GC HW mutually. We add an additional
5179 		 * guilty jobs recheck step to find the real guilty job, it synchronously
5180 		 * submits and pends for the first job being signaled. If it gets timeout,
5181 		 * we identify it as a real guilty job.
5182 		 */
5183 		if (amdgpu_gpu_recovery == 2 &&
5184 			!(tmp_vram_lost_counter < atomic_read(&adev->vram_lost_counter)))
5185 			amdgpu_device_recheck_guilty_jobs(
5186 				tmp_adev, device_list_handle, &reset_context);
5187 
5188 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5189 			struct amdgpu_ring *ring = tmp_adev->rings[i];
5190 
5191 			if (!ring || !ring->sched.thread)
5192 				continue;
5193 
5194 			/* No point to resubmit jobs if we didn't HW reset*/
5195 			if (!tmp_adev->asic_reset_res && !job_signaled)
5196 				drm_sched_resubmit_jobs(&ring->sched);
5197 
5198 			drm_sched_start(&ring->sched, !tmp_adev->asic_reset_res);
5199 		}
5200 
5201 		if (!drm_drv_uses_atomic_modeset(adev_to_drm(tmp_adev)) && !job_signaled) {
5202 			drm_helper_resume_force_mode(adev_to_drm(tmp_adev));
5203 		}
5204 
5205 		tmp_adev->asic_reset_res = 0;
5206 
5207 		if (r) {
5208 			/* bad news, how to tell it to userspace ? */
5209 			dev_info(tmp_adev->dev, "GPU reset(%d) failed\n", atomic_read(&tmp_adev->gpu_reset_counter));
5210 			amdgpu_vf_error_put(tmp_adev, AMDGIM_ERROR_VF_GPU_RESET_FAIL, 0, r);
5211 		} else {
5212 			dev_info(tmp_adev->dev, "GPU reset(%d) succeeded!\n", atomic_read(&tmp_adev->gpu_reset_counter));
5213 			if (amdgpu_acpi_smart_shift_update(adev_to_drm(tmp_adev), AMDGPU_SS_DEV_D0))
5214 				DRM_WARN("smart shift update failed\n");
5215 		}
5216 	}
5217 
5218 skip_sched_resume:
5219 	list_for_each_entry(tmp_adev, device_list_handle, reset_list) {
5220 		/* unlock kfd: SRIOV would do it separately */
5221 		if (!need_emergency_restart && !amdgpu_sriov_vf(tmp_adev))
5222 			amdgpu_amdkfd_post_reset(tmp_adev);
5223 
5224 		/* kfd_post_reset will do nothing if kfd device is not initialized,
5225 		 * need to bring up kfd here if it's not be initialized before
5226 		 */
5227 		if (!adev->kfd.init_complete)
5228 			amdgpu_amdkfd_device_init(adev);
5229 
5230 		if (audio_suspended)
5231 			amdgpu_device_resume_display_audio(tmp_adev);
5232 		amdgpu_device_unlock_adev(tmp_adev);
5233 	}
5234 
5235 skip_recovery:
5236 	if (hive) {
5237 		atomic_set(&hive->in_reset, 0);
5238 		mutex_unlock(&hive->hive_lock);
5239 		amdgpu_put_xgmi_hive(hive);
5240 	}
5241 
5242 	if (r && r != -EAGAIN)
5243 		dev_info(adev->dev, "GPU reset end with ret = %d\n", r);
5244 	return r;
5245 }
5246 
5247 /**
5248  * amdgpu_device_get_pcie_info - fence pcie info about the PCIE slot
5249  *
5250  * @adev: amdgpu_device pointer
5251  *
5252  * Fetchs and stores in the driver the PCIE capabilities (gen speed
5253  * and lanes) of the slot the device is in. Handles APUs and
5254  * virtualized environments where PCIE config space may not be available.
5255  */
5256 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev)
5257 {
5258 	struct pci_dev *pdev;
5259 	enum pci_bus_speed speed_cap, platform_speed_cap;
5260 	enum pcie_link_width platform_link_width;
5261 
5262 	if (amdgpu_pcie_gen_cap)
5263 		adev->pm.pcie_gen_mask = amdgpu_pcie_gen_cap;
5264 
5265 	if (amdgpu_pcie_lane_cap)
5266 		adev->pm.pcie_mlw_mask = amdgpu_pcie_lane_cap;
5267 
5268 	/* covers APUs as well */
5269 	if (pci_is_root_bus(adev->pdev->bus)) {
5270 		if (adev->pm.pcie_gen_mask == 0)
5271 			adev->pm.pcie_gen_mask = AMDGPU_DEFAULT_PCIE_GEN_MASK;
5272 		if (adev->pm.pcie_mlw_mask == 0)
5273 			adev->pm.pcie_mlw_mask = AMDGPU_DEFAULT_PCIE_MLW_MASK;
5274 		return;
5275 	}
5276 
5277 	if (adev->pm.pcie_gen_mask && adev->pm.pcie_mlw_mask)
5278 		return;
5279 
5280 	pcie_bandwidth_available(adev->pdev, NULL,
5281 				 &platform_speed_cap, &platform_link_width);
5282 
5283 	if (adev->pm.pcie_gen_mask == 0) {
5284 		/* asic caps */
5285 		pdev = adev->pdev;
5286 		speed_cap = pcie_get_speed_cap(pdev);
5287 		if (speed_cap == PCI_SPEED_UNKNOWN) {
5288 			adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5289 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5290 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
5291 		} else {
5292 			if (speed_cap == PCIE_SPEED_32_0GT)
5293 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5294 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5295 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3 |
5296 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN4 |
5297 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN5);
5298 			else if (speed_cap == PCIE_SPEED_16_0GT)
5299 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5300 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5301 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3 |
5302 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN4);
5303 			else if (speed_cap == PCIE_SPEED_8_0GT)
5304 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5305 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5306 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
5307 			else if (speed_cap == PCIE_SPEED_5_0GT)
5308 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5309 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2);
5310 			else
5311 				adev->pm.pcie_gen_mask |= CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1;
5312 		}
5313 		/* platform caps */
5314 		if (platform_speed_cap == PCI_SPEED_UNKNOWN) {
5315 			adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5316 						   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
5317 		} else {
5318 			if (platform_speed_cap == PCIE_SPEED_32_0GT)
5319 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5320 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5321 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3 |
5322 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN4 |
5323 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN5);
5324 			else if (platform_speed_cap == PCIE_SPEED_16_0GT)
5325 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5326 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5327 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3 |
5328 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN4);
5329 			else if (platform_speed_cap == PCIE_SPEED_8_0GT)
5330 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5331 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
5332 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3);
5333 			else if (platform_speed_cap == PCIE_SPEED_5_0GT)
5334 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
5335 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
5336 			else
5337 				adev->pm.pcie_gen_mask |= CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1;
5338 
5339 		}
5340 	}
5341 	if (adev->pm.pcie_mlw_mask == 0) {
5342 		if (platform_link_width == PCIE_LNK_WIDTH_UNKNOWN) {
5343 			adev->pm.pcie_mlw_mask |= AMDGPU_DEFAULT_PCIE_MLW_MASK;
5344 		} else {
5345 			switch (platform_link_width) {
5346 			case PCIE_LNK_X32:
5347 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X32 |
5348 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
5349 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
5350 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
5351 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
5352 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
5353 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
5354 				break;
5355 			case PCIE_LNK_X16:
5356 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
5357 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
5358 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
5359 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
5360 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
5361 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
5362 				break;
5363 			case PCIE_LNK_X12:
5364 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
5365 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
5366 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
5367 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
5368 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
5369 				break;
5370 			case PCIE_LNK_X8:
5371 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
5372 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
5373 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
5374 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
5375 				break;
5376 			case PCIE_LNK_X4:
5377 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
5378 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
5379 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
5380 				break;
5381 			case PCIE_LNK_X2:
5382 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
5383 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
5384 				break;
5385 			case PCIE_LNK_X1:
5386 				adev->pm.pcie_mlw_mask = CAIL_PCIE_LINK_WIDTH_SUPPORT_X1;
5387 				break;
5388 			default:
5389 				break;
5390 			}
5391 		}
5392 	}
5393 }
5394 
5395 int amdgpu_device_baco_enter(struct drm_device *dev)
5396 {
5397 	struct amdgpu_device *adev = drm_to_adev(dev);
5398 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
5399 
5400 	if (!amdgpu_device_supports_baco(adev_to_drm(adev)))
5401 		return -ENOTSUPP;
5402 
5403 	if (ras && adev->ras_enabled &&
5404 	    adev->nbio.funcs->enable_doorbell_interrupt)
5405 		adev->nbio.funcs->enable_doorbell_interrupt(adev, false);
5406 
5407 	return amdgpu_dpm_baco_enter(adev);
5408 }
5409 
5410 int amdgpu_device_baco_exit(struct drm_device *dev)
5411 {
5412 	struct amdgpu_device *adev = drm_to_adev(dev);
5413 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
5414 	int ret = 0;
5415 
5416 	if (!amdgpu_device_supports_baco(adev_to_drm(adev)))
5417 		return -ENOTSUPP;
5418 
5419 	ret = amdgpu_dpm_baco_exit(adev);
5420 	if (ret)
5421 		return ret;
5422 
5423 	if (ras && adev->ras_enabled &&
5424 	    adev->nbio.funcs->enable_doorbell_interrupt)
5425 		adev->nbio.funcs->enable_doorbell_interrupt(adev, true);
5426 
5427 	if (amdgpu_passthrough(adev) &&
5428 	    adev->nbio.funcs->clear_doorbell_interrupt)
5429 		adev->nbio.funcs->clear_doorbell_interrupt(adev);
5430 
5431 	return 0;
5432 }
5433 
5434 static void amdgpu_cancel_all_tdr(struct amdgpu_device *adev)
5435 {
5436 	int i;
5437 
5438 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5439 		struct amdgpu_ring *ring = adev->rings[i];
5440 
5441 		if (!ring || !ring->sched.thread)
5442 			continue;
5443 
5444 		cancel_delayed_work_sync(&ring->sched.work_tdr);
5445 	}
5446 }
5447 
5448 /**
5449  * amdgpu_pci_error_detected - Called when a PCI error is detected.
5450  * @pdev: PCI device struct
5451  * @state: PCI channel state
5452  *
5453  * Description: Called when a PCI error is detected.
5454  *
5455  * Return: PCI_ERS_RESULT_NEED_RESET or PCI_ERS_RESULT_DISCONNECT.
5456  */
5457 pci_ers_result_t amdgpu_pci_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
5458 {
5459 	struct drm_device *dev = pci_get_drvdata(pdev);
5460 	struct amdgpu_device *adev = drm_to_adev(dev);
5461 	int i;
5462 
5463 	DRM_INFO("PCI error: detected callback, state(%d)!!\n", state);
5464 
5465 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
5466 		DRM_WARN("No support for XGMI hive yet...");
5467 		return PCI_ERS_RESULT_DISCONNECT;
5468 	}
5469 
5470 	adev->pci_channel_state = state;
5471 
5472 	switch (state) {
5473 	case pci_channel_io_normal:
5474 		return PCI_ERS_RESULT_CAN_RECOVER;
5475 	/* Fatal error, prepare for slot reset */
5476 	case pci_channel_io_frozen:
5477 		/*
5478 		 * Cancel and wait for all TDRs in progress if failing to
5479 		 * set  adev->in_gpu_reset in amdgpu_device_lock_adev
5480 		 *
5481 		 * Locking adev->reset_sem will prevent any external access
5482 		 * to GPU during PCI error recovery
5483 		 */
5484 		while (!amdgpu_device_lock_adev(adev, NULL))
5485 			amdgpu_cancel_all_tdr(adev);
5486 
5487 		/*
5488 		 * Block any work scheduling as we do for regular GPU reset
5489 		 * for the duration of the recovery
5490 		 */
5491 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5492 			struct amdgpu_ring *ring = adev->rings[i];
5493 
5494 			if (!ring || !ring->sched.thread)
5495 				continue;
5496 
5497 			drm_sched_stop(&ring->sched, NULL);
5498 		}
5499 		atomic_inc(&adev->gpu_reset_counter);
5500 		return PCI_ERS_RESULT_NEED_RESET;
5501 	case pci_channel_io_perm_failure:
5502 		/* Permanent error, prepare for device removal */
5503 		return PCI_ERS_RESULT_DISCONNECT;
5504 	}
5505 
5506 	return PCI_ERS_RESULT_NEED_RESET;
5507 }
5508 
5509 /**
5510  * amdgpu_pci_mmio_enabled - Enable MMIO and dump debug registers
5511  * @pdev: pointer to PCI device
5512  */
5513 pci_ers_result_t amdgpu_pci_mmio_enabled(struct pci_dev *pdev)
5514 {
5515 
5516 	DRM_INFO("PCI error: mmio enabled callback!!\n");
5517 
5518 	/* TODO - dump whatever for debugging purposes */
5519 
5520 	/* This called only if amdgpu_pci_error_detected returns
5521 	 * PCI_ERS_RESULT_CAN_RECOVER. Read/write to the device still
5522 	 * works, no need to reset slot.
5523 	 */
5524 
5525 	return PCI_ERS_RESULT_RECOVERED;
5526 }
5527 
5528 /**
5529  * amdgpu_pci_slot_reset - Called when PCI slot has been reset.
5530  * @pdev: PCI device struct
5531  *
5532  * Description: This routine is called by the pci error recovery
5533  * code after the PCI slot has been reset, just before we
5534  * should resume normal operations.
5535  */
5536 pci_ers_result_t amdgpu_pci_slot_reset(struct pci_dev *pdev)
5537 {
5538 	struct drm_device *dev = pci_get_drvdata(pdev);
5539 	struct amdgpu_device *adev = drm_to_adev(dev);
5540 	int r, i;
5541 	struct amdgpu_reset_context reset_context;
5542 	u32 memsize;
5543 	struct list_head device_list;
5544 
5545 	DRM_INFO("PCI error: slot reset callback!!\n");
5546 
5547 	memset(&reset_context, 0, sizeof(reset_context));
5548 
5549 	INIT_LIST_HEAD(&device_list);
5550 	list_add_tail(&adev->reset_list, &device_list);
5551 
5552 	/* wait for asic to come out of reset */
5553 	msleep(500);
5554 
5555 	/* Restore PCI confspace */
5556 	amdgpu_device_load_pci_state(pdev);
5557 
5558 	/* confirm  ASIC came out of reset */
5559 	for (i = 0; i < adev->usec_timeout; i++) {
5560 		memsize = amdgpu_asic_get_config_memsize(adev);
5561 
5562 		if (memsize != 0xffffffff)
5563 			break;
5564 		udelay(1);
5565 	}
5566 	if (memsize == 0xffffffff) {
5567 		r = -ETIME;
5568 		goto out;
5569 	}
5570 
5571 	reset_context.method = AMD_RESET_METHOD_NONE;
5572 	reset_context.reset_req_dev = adev;
5573 	set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
5574 	set_bit(AMDGPU_SKIP_HW_RESET, &reset_context.flags);
5575 
5576 	adev->no_hw_access = true;
5577 	r = amdgpu_device_pre_asic_reset(adev, &reset_context);
5578 	adev->no_hw_access = false;
5579 	if (r)
5580 		goto out;
5581 
5582 	r = amdgpu_do_asic_reset(&device_list, &reset_context);
5583 
5584 out:
5585 	if (!r) {
5586 		if (amdgpu_device_cache_pci_state(adev->pdev))
5587 			pci_restore_state(adev->pdev);
5588 
5589 		DRM_INFO("PCIe error recovery succeeded\n");
5590 	} else {
5591 		DRM_ERROR("PCIe error recovery failed, err:%d", r);
5592 		amdgpu_device_unlock_adev(adev);
5593 	}
5594 
5595 	return r ? PCI_ERS_RESULT_DISCONNECT : PCI_ERS_RESULT_RECOVERED;
5596 }
5597 
5598 /**
5599  * amdgpu_pci_resume() - resume normal ops after PCI reset
5600  * @pdev: pointer to PCI device
5601  *
5602  * Called when the error recovery driver tells us that its
5603  * OK to resume normal operation.
5604  */
5605 void amdgpu_pci_resume(struct pci_dev *pdev)
5606 {
5607 	struct drm_device *dev = pci_get_drvdata(pdev);
5608 	struct amdgpu_device *adev = drm_to_adev(dev);
5609 	int i;
5610 
5611 
5612 	DRM_INFO("PCI error: resume callback!!\n");
5613 
5614 	/* Only continue execution for the case of pci_channel_io_frozen */
5615 	if (adev->pci_channel_state != pci_channel_io_frozen)
5616 		return;
5617 
5618 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
5619 		struct amdgpu_ring *ring = adev->rings[i];
5620 
5621 		if (!ring || !ring->sched.thread)
5622 			continue;
5623 
5624 
5625 		drm_sched_resubmit_jobs(&ring->sched);
5626 		drm_sched_start(&ring->sched, true);
5627 	}
5628 
5629 	amdgpu_device_unlock_adev(adev);
5630 }
5631 
5632 bool amdgpu_device_cache_pci_state(struct pci_dev *pdev)
5633 {
5634 	struct drm_device *dev = pci_get_drvdata(pdev);
5635 	struct amdgpu_device *adev = drm_to_adev(dev);
5636 	int r;
5637 
5638 	r = pci_save_state(pdev);
5639 	if (!r) {
5640 		kfree(adev->pci_state);
5641 
5642 		adev->pci_state = pci_store_saved_state(pdev);
5643 
5644 		if (!adev->pci_state) {
5645 			DRM_ERROR("Failed to store PCI saved state");
5646 			return false;
5647 		}
5648 	} else {
5649 		DRM_WARN("Failed to save PCI state, err:%d\n", r);
5650 		return false;
5651 	}
5652 
5653 	return true;
5654 }
5655 
5656 bool amdgpu_device_load_pci_state(struct pci_dev *pdev)
5657 {
5658 	struct drm_device *dev = pci_get_drvdata(pdev);
5659 	struct amdgpu_device *adev = drm_to_adev(dev);
5660 	int r;
5661 
5662 	if (!adev->pci_state)
5663 		return false;
5664 
5665 	r = pci_load_saved_state(pdev, adev->pci_state);
5666 
5667 	if (!r) {
5668 		pci_restore_state(pdev);
5669 	} else {
5670 		DRM_WARN("Failed to load PCI state, err:%d\n", r);
5671 		return false;
5672 	}
5673 
5674 	return true;
5675 }
5676 
5677 void amdgpu_device_flush_hdp(struct amdgpu_device *adev,
5678 		struct amdgpu_ring *ring)
5679 {
5680 #ifdef CONFIG_X86_64
5681 	if (adev->flags & AMD_IS_APU)
5682 		return;
5683 #endif
5684 	if (adev->gmc.xgmi.connected_to_cpu)
5685 		return;
5686 
5687 	if (ring && ring->funcs->emit_hdp_flush)
5688 		amdgpu_ring_emit_hdp_flush(ring);
5689 	else
5690 		amdgpu_asic_flush_hdp(adev, ring);
5691 }
5692 
5693 void amdgpu_device_invalidate_hdp(struct amdgpu_device *adev,
5694 		struct amdgpu_ring *ring)
5695 {
5696 #ifdef CONFIG_X86_64
5697 	if (adev->flags & AMD_IS_APU)
5698 		return;
5699 #endif
5700 	if (adev->gmc.xgmi.connected_to_cpu)
5701 		return;
5702 
5703 	amdgpu_asic_invalidate_hdp(adev, ring);
5704 }
5705 
5706 /**
5707  * amdgpu_device_halt() - bring hardware to some kind of halt state
5708  *
5709  * @adev: amdgpu_device pointer
5710  *
5711  * Bring hardware to some kind of halt state so that no one can touch it
5712  * any more. It will help to maintain error context when error occurred.
5713  * Compare to a simple hang, the system will keep stable at least for SSH
5714  * access. Then it should be trivial to inspect the hardware state and
5715  * see what's going on. Implemented as following:
5716  *
5717  * 1. drm_dev_unplug() makes device inaccessible to user space(IOCTLs, etc),
5718  *    clears all CPU mappings to device, disallows remappings through page faults
5719  * 2. amdgpu_irq_disable_all() disables all interrupts
5720  * 3. amdgpu_fence_driver_hw_fini() signals all HW fences
5721  * 4. set adev->no_hw_access to avoid potential crashes after setp 5
5722  * 5. amdgpu_device_unmap_mmio() clears all MMIO mappings
5723  * 6. pci_disable_device() and pci_wait_for_pending_transaction()
5724  *    flush any in flight DMA operations
5725  */
5726 void amdgpu_device_halt(struct amdgpu_device *adev)
5727 {
5728 	struct pci_dev *pdev = adev->pdev;
5729 	struct drm_device *ddev = adev_to_drm(adev);
5730 
5731 	drm_dev_unplug(ddev);
5732 
5733 	amdgpu_irq_disable_all(adev);
5734 
5735 	amdgpu_fence_driver_hw_fini(adev);
5736 
5737 	adev->no_hw_access = true;
5738 
5739 	amdgpu_device_unmap_mmio(adev);
5740 
5741 	pci_disable_device(pdev);
5742 	pci_wait_for_pending_transaction(pdev);
5743 }
5744 
5745 u32 amdgpu_device_pcie_port_rreg(struct amdgpu_device *adev,
5746 				u32 reg)
5747 {
5748 	unsigned long flags, address, data;
5749 	u32 r;
5750 
5751 	address = adev->nbio.funcs->get_pcie_port_index_offset(adev);
5752 	data = adev->nbio.funcs->get_pcie_port_data_offset(adev);
5753 
5754 	spin_lock_irqsave(&adev->pcie_idx_lock, flags);
5755 	WREG32(address, reg * 4);
5756 	(void)RREG32(address);
5757 	r = RREG32(data);
5758 	spin_unlock_irqrestore(&adev->pcie_idx_lock, flags);
5759 	return r;
5760 }
5761 
5762 void amdgpu_device_pcie_port_wreg(struct amdgpu_device *adev,
5763 				u32 reg, u32 v)
5764 {
5765 	unsigned long flags, address, data;
5766 
5767 	address = adev->nbio.funcs->get_pcie_port_index_offset(adev);
5768 	data = adev->nbio.funcs->get_pcie_port_data_offset(adev);
5769 
5770 	spin_lock_irqsave(&adev->pcie_idx_lock, flags);
5771 	WREG32(address, reg * 4);
5772 	(void)RREG32(address);
5773 	WREG32(data, v);
5774 	(void)RREG32(data);
5775 	spin_unlock_irqrestore(&adev->pcie_idx_lock, flags);
5776 }
5777