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 
34 #include <drm/drm_atomic_helper.h>
35 #include <drm/drm_probe_helper.h>
36 #include <drm/amdgpu_drm.h>
37 #include <linux/vgaarb.h>
38 #include <linux/vga_switcheroo.h>
39 #include <linux/efi.h>
40 #include "amdgpu.h"
41 #include "amdgpu_trace.h"
42 #include "amdgpu_i2c.h"
43 #include "atom.h"
44 #include "amdgpu_atombios.h"
45 #include "amdgpu_atomfirmware.h"
46 #include "amd_pcie.h"
47 #ifdef CONFIG_DRM_AMDGPU_SI
48 #include "si.h"
49 #endif
50 #ifdef CONFIG_DRM_AMDGPU_CIK
51 #include "cik.h"
52 #endif
53 #include "vi.h"
54 #include "soc15.h"
55 #include "nv.h"
56 #include "bif/bif_4_1_d.h"
57 #include <linux/pci.h>
58 #include <linux/firmware.h>
59 #include "amdgpu_vf_error.h"
60 
61 #include "amdgpu_amdkfd.h"
62 #include "amdgpu_pm.h"
63 
64 #include "amdgpu_xgmi.h"
65 #include "amdgpu_ras.h"
66 #include "amdgpu_pmu.h"
67 
68 #include <linux/suspend.h>
69 
70 MODULE_FIRMWARE("amdgpu/vega10_gpu_info.bin");
71 MODULE_FIRMWARE("amdgpu/vega12_gpu_info.bin");
72 MODULE_FIRMWARE("amdgpu/raven_gpu_info.bin");
73 MODULE_FIRMWARE("amdgpu/picasso_gpu_info.bin");
74 MODULE_FIRMWARE("amdgpu/raven2_gpu_info.bin");
75 MODULE_FIRMWARE("amdgpu/arcturus_gpu_info.bin");
76 MODULE_FIRMWARE("amdgpu/renoir_gpu_info.bin");
77 MODULE_FIRMWARE("amdgpu/navi10_gpu_info.bin");
78 MODULE_FIRMWARE("amdgpu/navi14_gpu_info.bin");
79 MODULE_FIRMWARE("amdgpu/navi12_gpu_info.bin");
80 
81 #define AMDGPU_RESUME_MS		2000
82 
83 const char *amdgpu_asic_name[] = {
84 	"TAHITI",
85 	"PITCAIRN",
86 	"VERDE",
87 	"OLAND",
88 	"HAINAN",
89 	"BONAIRE",
90 	"KAVERI",
91 	"KABINI",
92 	"HAWAII",
93 	"MULLINS",
94 	"TOPAZ",
95 	"TONGA",
96 	"FIJI",
97 	"CARRIZO",
98 	"STONEY",
99 	"POLARIS10",
100 	"POLARIS11",
101 	"POLARIS12",
102 	"VEGAM",
103 	"VEGA10",
104 	"VEGA12",
105 	"VEGA20",
106 	"RAVEN",
107 	"ARCTURUS",
108 	"RENOIR",
109 	"NAVI10",
110 	"NAVI14",
111 	"NAVI12",
112 	"LAST",
113 };
114 
115 /**
116  * DOC: pcie_replay_count
117  *
118  * The amdgpu driver provides a sysfs API for reporting the total number
119  * of PCIe replays (NAKs)
120  * The file pcie_replay_count is used for this and returns the total
121  * number of replays as a sum of the NAKs generated and NAKs received
122  */
123 
124 static ssize_t amdgpu_device_get_pcie_replay_count(struct device *dev,
125 		struct device_attribute *attr, char *buf)
126 {
127 	struct drm_device *ddev = dev_get_drvdata(dev);
128 	struct amdgpu_device *adev = ddev->dev_private;
129 	uint64_t cnt = amdgpu_asic_get_pcie_replay_count(adev);
130 
131 	return snprintf(buf, PAGE_SIZE, "%llu\n", cnt);
132 }
133 
134 static DEVICE_ATTR(pcie_replay_count, S_IRUGO,
135 		amdgpu_device_get_pcie_replay_count, NULL);
136 
137 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev);
138 
139 /**
140  * amdgpu_device_supports_boco - Is the device a dGPU with HG/PX power control
141  *
142  * @dev: drm_device pointer
143  *
144  * Returns true if the device is a dGPU with HG/PX power control,
145  * otherwise return false.
146  */
147 bool amdgpu_device_supports_boco(struct drm_device *dev)
148 {
149 	struct amdgpu_device *adev = dev->dev_private;
150 
151 	if (adev->flags & AMD_IS_PX)
152 		return true;
153 	return false;
154 }
155 
156 /**
157  * amdgpu_device_supports_baco - Does the device support BACO
158  *
159  * @dev: drm_device pointer
160  *
161  * Returns true if the device supporte BACO,
162  * otherwise return false.
163  */
164 bool amdgpu_device_supports_baco(struct drm_device *dev)
165 {
166 	struct amdgpu_device *adev = dev->dev_private;
167 
168 	return amdgpu_asic_supports_baco(adev);
169 }
170 
171 /**
172  * VRAM access helper functions.
173  *
174  * amdgpu_device_vram_access - read/write a buffer in vram
175  *
176  * @adev: amdgpu_device pointer
177  * @pos: offset of the buffer in vram
178  * @buf: virtual address of the buffer in system memory
179  * @size: read/write size, sizeof(@buf) must > @size
180  * @write: true - write to vram, otherwise - read from vram
181  */
182 void amdgpu_device_vram_access(struct amdgpu_device *adev, loff_t pos,
183 			       uint32_t *buf, size_t size, bool write)
184 {
185 	uint64_t last;
186 	unsigned long flags;
187 
188 	last = size - 4;
189 	for (last += pos; pos <= last; pos += 4) {
190 		spin_lock_irqsave(&adev->mmio_idx_lock, flags);
191 		WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000);
192 		WREG32_NO_KIQ(mmMM_INDEX_HI, pos >> 31);
193 		if (write)
194 			WREG32_NO_KIQ(mmMM_DATA, *buf++);
195 		else
196 			*buf++ = RREG32_NO_KIQ(mmMM_DATA);
197 		spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
198 	}
199 }
200 
201 /*
202  * MMIO register access helper functions.
203  */
204 /**
205  * amdgpu_mm_rreg - read a memory mapped IO register
206  *
207  * @adev: amdgpu_device pointer
208  * @reg: dword aligned register offset
209  * @acc_flags: access flags which require special behavior
210  *
211  * Returns the 32 bit value from the offset specified.
212  */
213 uint32_t amdgpu_mm_rreg(struct amdgpu_device *adev, uint32_t reg,
214 			uint32_t acc_flags)
215 {
216 	uint32_t ret;
217 
218 	if (!(acc_flags & AMDGPU_REGS_NO_KIQ) && amdgpu_sriov_runtime(adev))
219 		return amdgpu_virt_kiq_rreg(adev, reg);
220 
221 	if ((reg * 4) < adev->rmmio_size && !(acc_flags & AMDGPU_REGS_IDX))
222 		ret = readl(((void __iomem *)adev->rmmio) + (reg * 4));
223 	else {
224 		unsigned long flags;
225 
226 		spin_lock_irqsave(&adev->mmio_idx_lock, flags);
227 		writel((reg * 4), ((void __iomem *)adev->rmmio) + (mmMM_INDEX * 4));
228 		ret = readl(((void __iomem *)adev->rmmio) + (mmMM_DATA * 4));
229 		spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
230 	}
231 	trace_amdgpu_mm_rreg(adev->pdev->device, reg, ret);
232 	return ret;
233 }
234 
235 /*
236  * MMIO register read with bytes helper functions
237  * @offset:bytes offset from MMIO start
238  *
239 */
240 
241 /**
242  * amdgpu_mm_rreg8 - read a memory mapped IO register
243  *
244  * @adev: amdgpu_device pointer
245  * @offset: byte aligned register offset
246  *
247  * Returns the 8 bit value from the offset specified.
248  */
249 uint8_t amdgpu_mm_rreg8(struct amdgpu_device *adev, uint32_t offset) {
250 	if (offset < adev->rmmio_size)
251 		return (readb(adev->rmmio + offset));
252 	BUG();
253 }
254 
255 /*
256  * MMIO register write with bytes helper functions
257  * @offset:bytes offset from MMIO start
258  * @value: the value want to be written to the register
259  *
260 */
261 /**
262  * amdgpu_mm_wreg8 - read a memory mapped IO register
263  *
264  * @adev: amdgpu_device pointer
265  * @offset: byte aligned register offset
266  * @value: 8 bit value to write
267  *
268  * Writes the value specified to the offset specified.
269  */
270 void amdgpu_mm_wreg8(struct amdgpu_device *adev, uint32_t offset, uint8_t value) {
271 	if (offset < adev->rmmio_size)
272 		writeb(value, adev->rmmio + offset);
273 	else
274 		BUG();
275 }
276 
277 /**
278  * amdgpu_mm_wreg - write to a memory mapped IO register
279  *
280  * @adev: amdgpu_device pointer
281  * @reg: dword aligned register offset
282  * @v: 32 bit value to write to the register
283  * @acc_flags: access flags which require special behavior
284  *
285  * Writes the value specified to the offset specified.
286  */
287 void amdgpu_mm_wreg(struct amdgpu_device *adev, uint32_t reg, uint32_t v,
288 		    uint32_t acc_flags)
289 {
290 	trace_amdgpu_mm_wreg(adev->pdev->device, reg, v);
291 
292 	if (adev->asic_type >= CHIP_VEGA10 && reg == 0) {
293 		adev->last_mm_index = v;
294 	}
295 
296 	if (!(acc_flags & AMDGPU_REGS_NO_KIQ) && amdgpu_sriov_runtime(adev))
297 		return amdgpu_virt_kiq_wreg(adev, reg, v);
298 
299 	if ((reg * 4) < adev->rmmio_size && !(acc_flags & AMDGPU_REGS_IDX))
300 		writel(v, ((void __iomem *)adev->rmmio) + (reg * 4));
301 	else {
302 		unsigned long flags;
303 
304 		spin_lock_irqsave(&adev->mmio_idx_lock, flags);
305 		writel((reg * 4), ((void __iomem *)adev->rmmio) + (mmMM_INDEX * 4));
306 		writel(v, ((void __iomem *)adev->rmmio) + (mmMM_DATA * 4));
307 		spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
308 	}
309 
310 	if (adev->asic_type >= CHIP_VEGA10 && reg == 1 && adev->last_mm_index == 0x5702C) {
311 		udelay(500);
312 	}
313 }
314 
315 /**
316  * amdgpu_io_rreg - read an IO register
317  *
318  * @adev: amdgpu_device pointer
319  * @reg: dword aligned register offset
320  *
321  * Returns the 32 bit value from the offset specified.
322  */
323 u32 amdgpu_io_rreg(struct amdgpu_device *adev, u32 reg)
324 {
325 	if ((reg * 4) < adev->rio_mem_size)
326 		return ioread32(adev->rio_mem + (reg * 4));
327 	else {
328 		iowrite32((reg * 4), adev->rio_mem + (mmMM_INDEX * 4));
329 		return ioread32(adev->rio_mem + (mmMM_DATA * 4));
330 	}
331 }
332 
333 /**
334  * amdgpu_io_wreg - write to an IO register
335  *
336  * @adev: amdgpu_device pointer
337  * @reg: dword aligned register offset
338  * @v: 32 bit value to write to the register
339  *
340  * Writes the value specified to the offset specified.
341  */
342 void amdgpu_io_wreg(struct amdgpu_device *adev, u32 reg, u32 v)
343 {
344 	if (adev->asic_type >= CHIP_VEGA10 && reg == 0) {
345 		adev->last_mm_index = v;
346 	}
347 
348 	if ((reg * 4) < adev->rio_mem_size)
349 		iowrite32(v, adev->rio_mem + (reg * 4));
350 	else {
351 		iowrite32((reg * 4), adev->rio_mem + (mmMM_INDEX * 4));
352 		iowrite32(v, adev->rio_mem + (mmMM_DATA * 4));
353 	}
354 
355 	if (adev->asic_type >= CHIP_VEGA10 && reg == 1 && adev->last_mm_index == 0x5702C) {
356 		udelay(500);
357 	}
358 }
359 
360 /**
361  * amdgpu_mm_rdoorbell - read a doorbell dword
362  *
363  * @adev: amdgpu_device pointer
364  * @index: doorbell index
365  *
366  * Returns the value in the doorbell aperture at the
367  * requested doorbell index (CIK).
368  */
369 u32 amdgpu_mm_rdoorbell(struct amdgpu_device *adev, u32 index)
370 {
371 	if (index < adev->doorbell.num_doorbells) {
372 		return readl(adev->doorbell.ptr + index);
373 	} else {
374 		DRM_ERROR("reading beyond doorbell aperture: 0x%08x!\n", index);
375 		return 0;
376 	}
377 }
378 
379 /**
380  * amdgpu_mm_wdoorbell - write a doorbell dword
381  *
382  * @adev: amdgpu_device pointer
383  * @index: doorbell index
384  * @v: value to write
385  *
386  * Writes @v to the doorbell aperture at the
387  * requested doorbell index (CIK).
388  */
389 void amdgpu_mm_wdoorbell(struct amdgpu_device *adev, u32 index, u32 v)
390 {
391 	if (index < adev->doorbell.num_doorbells) {
392 		writel(v, adev->doorbell.ptr + index);
393 	} else {
394 		DRM_ERROR("writing beyond doorbell aperture: 0x%08x!\n", index);
395 	}
396 }
397 
398 /**
399  * amdgpu_mm_rdoorbell64 - read a doorbell Qword
400  *
401  * @adev: amdgpu_device pointer
402  * @index: doorbell index
403  *
404  * Returns the value in the doorbell aperture at the
405  * requested doorbell index (VEGA10+).
406  */
407 u64 amdgpu_mm_rdoorbell64(struct amdgpu_device *adev, u32 index)
408 {
409 	if (index < adev->doorbell.num_doorbells) {
410 		return atomic64_read((atomic64_t *)(adev->doorbell.ptr + index));
411 	} else {
412 		DRM_ERROR("reading beyond doorbell aperture: 0x%08x!\n", index);
413 		return 0;
414 	}
415 }
416 
417 /**
418  * amdgpu_mm_wdoorbell64 - write a doorbell Qword
419  *
420  * @adev: amdgpu_device pointer
421  * @index: doorbell index
422  * @v: value to write
423  *
424  * Writes @v to the doorbell aperture at the
425  * requested doorbell index (VEGA10+).
426  */
427 void amdgpu_mm_wdoorbell64(struct amdgpu_device *adev, u32 index, u64 v)
428 {
429 	if (index < adev->doorbell.num_doorbells) {
430 		atomic64_set((atomic64_t *)(adev->doorbell.ptr + index), v);
431 	} else {
432 		DRM_ERROR("writing beyond doorbell aperture: 0x%08x!\n", index);
433 	}
434 }
435 
436 /**
437  * amdgpu_invalid_rreg - dummy reg read function
438  *
439  * @adev: amdgpu device pointer
440  * @reg: offset of register
441  *
442  * Dummy register read function.  Used for register blocks
443  * that certain asics don't have (all asics).
444  * Returns the value in the register.
445  */
446 static uint32_t amdgpu_invalid_rreg(struct amdgpu_device *adev, uint32_t reg)
447 {
448 	DRM_ERROR("Invalid callback to read register 0x%04X\n", reg);
449 	BUG();
450 	return 0;
451 }
452 
453 /**
454  * amdgpu_invalid_wreg - dummy reg write function
455  *
456  * @adev: amdgpu device pointer
457  * @reg: offset of register
458  * @v: value to write to the register
459  *
460  * Dummy register read function.  Used for register blocks
461  * that certain asics don't have (all asics).
462  */
463 static void amdgpu_invalid_wreg(struct amdgpu_device *adev, uint32_t reg, uint32_t v)
464 {
465 	DRM_ERROR("Invalid callback to write register 0x%04X with 0x%08X\n",
466 		  reg, v);
467 	BUG();
468 }
469 
470 /**
471  * amdgpu_invalid_rreg64 - dummy 64 bit reg read function
472  *
473  * @adev: amdgpu device pointer
474  * @reg: offset of register
475  *
476  * Dummy register read function.  Used for register blocks
477  * that certain asics don't have (all asics).
478  * Returns the value in the register.
479  */
480 static uint64_t amdgpu_invalid_rreg64(struct amdgpu_device *adev, uint32_t reg)
481 {
482 	DRM_ERROR("Invalid callback to read 64 bit register 0x%04X\n", reg);
483 	BUG();
484 	return 0;
485 }
486 
487 /**
488  * amdgpu_invalid_wreg64 - dummy reg write function
489  *
490  * @adev: amdgpu device pointer
491  * @reg: offset of register
492  * @v: value to write to the register
493  *
494  * Dummy register read function.  Used for register blocks
495  * that certain asics don't have (all asics).
496  */
497 static void amdgpu_invalid_wreg64(struct amdgpu_device *adev, uint32_t reg, uint64_t v)
498 {
499 	DRM_ERROR("Invalid callback to write 64 bit register 0x%04X with 0x%08llX\n",
500 		  reg, v);
501 	BUG();
502 }
503 
504 /**
505  * amdgpu_block_invalid_rreg - dummy reg read function
506  *
507  * @adev: amdgpu device pointer
508  * @block: offset of instance
509  * @reg: offset of register
510  *
511  * Dummy register read function.  Used for register blocks
512  * that certain asics don't have (all asics).
513  * Returns the value in the register.
514  */
515 static uint32_t amdgpu_block_invalid_rreg(struct amdgpu_device *adev,
516 					  uint32_t block, uint32_t reg)
517 {
518 	DRM_ERROR("Invalid callback to read register 0x%04X in block 0x%04X\n",
519 		  reg, block);
520 	BUG();
521 	return 0;
522 }
523 
524 /**
525  * amdgpu_block_invalid_wreg - dummy reg write function
526  *
527  * @adev: amdgpu device pointer
528  * @block: offset of instance
529  * @reg: offset of register
530  * @v: value to write to the register
531  *
532  * Dummy register read function.  Used for register blocks
533  * that certain asics don't have (all asics).
534  */
535 static void amdgpu_block_invalid_wreg(struct amdgpu_device *adev,
536 				      uint32_t block,
537 				      uint32_t reg, uint32_t v)
538 {
539 	DRM_ERROR("Invalid block callback to write register 0x%04X in block 0x%04X with 0x%08X\n",
540 		  reg, block, v);
541 	BUG();
542 }
543 
544 /**
545  * amdgpu_device_vram_scratch_init - allocate the VRAM scratch page
546  *
547  * @adev: amdgpu device pointer
548  *
549  * Allocates a scratch page of VRAM for use by various things in the
550  * driver.
551  */
552 static int amdgpu_device_vram_scratch_init(struct amdgpu_device *adev)
553 {
554 	return amdgpu_bo_create_kernel(adev, AMDGPU_GPU_PAGE_SIZE,
555 				       PAGE_SIZE, AMDGPU_GEM_DOMAIN_VRAM,
556 				       &adev->vram_scratch.robj,
557 				       &adev->vram_scratch.gpu_addr,
558 				       (void **)&adev->vram_scratch.ptr);
559 }
560 
561 /**
562  * amdgpu_device_vram_scratch_fini - Free the VRAM scratch page
563  *
564  * @adev: amdgpu device pointer
565  *
566  * Frees the VRAM scratch page.
567  */
568 static void amdgpu_device_vram_scratch_fini(struct amdgpu_device *adev)
569 {
570 	amdgpu_bo_free_kernel(&adev->vram_scratch.robj, NULL, NULL);
571 }
572 
573 /**
574  * amdgpu_device_program_register_sequence - program an array of registers.
575  *
576  * @adev: amdgpu_device pointer
577  * @registers: pointer to the register array
578  * @array_size: size of the register array
579  *
580  * Programs an array or registers with and and or masks.
581  * This is a helper for setting golden registers.
582  */
583 void amdgpu_device_program_register_sequence(struct amdgpu_device *adev,
584 					     const u32 *registers,
585 					     const u32 array_size)
586 {
587 	u32 tmp, reg, and_mask, or_mask;
588 	int i;
589 
590 	if (array_size % 3)
591 		return;
592 
593 	for (i = 0; i < array_size; i +=3) {
594 		reg = registers[i + 0];
595 		and_mask = registers[i + 1];
596 		or_mask = registers[i + 2];
597 
598 		if (and_mask == 0xffffffff) {
599 			tmp = or_mask;
600 		} else {
601 			tmp = RREG32(reg);
602 			tmp &= ~and_mask;
603 			if (adev->family >= AMDGPU_FAMILY_AI)
604 				tmp |= (or_mask & and_mask);
605 			else
606 				tmp |= or_mask;
607 		}
608 		WREG32(reg, tmp);
609 	}
610 }
611 
612 /**
613  * amdgpu_device_pci_config_reset - reset the GPU
614  *
615  * @adev: amdgpu_device pointer
616  *
617  * Resets the GPU using the pci config reset sequence.
618  * Only applicable to asics prior to vega10.
619  */
620 void amdgpu_device_pci_config_reset(struct amdgpu_device *adev)
621 {
622 	pci_write_config_dword(adev->pdev, 0x7c, AMDGPU_ASIC_RESET_DATA);
623 }
624 
625 /*
626  * GPU doorbell aperture helpers function.
627  */
628 /**
629  * amdgpu_device_doorbell_init - Init doorbell driver information.
630  *
631  * @adev: amdgpu_device pointer
632  *
633  * Init doorbell driver information (CIK)
634  * Returns 0 on success, error on failure.
635  */
636 static int amdgpu_device_doorbell_init(struct amdgpu_device *adev)
637 {
638 
639 	/* No doorbell on SI hardware generation */
640 	if (adev->asic_type < CHIP_BONAIRE) {
641 		adev->doorbell.base = 0;
642 		adev->doorbell.size = 0;
643 		adev->doorbell.num_doorbells = 0;
644 		adev->doorbell.ptr = NULL;
645 		return 0;
646 	}
647 
648 	if (pci_resource_flags(adev->pdev, 2) & IORESOURCE_UNSET)
649 		return -EINVAL;
650 
651 	amdgpu_asic_init_doorbell_index(adev);
652 
653 	/* doorbell bar mapping */
654 	adev->doorbell.base = pci_resource_start(adev->pdev, 2);
655 	adev->doorbell.size = pci_resource_len(adev->pdev, 2);
656 
657 	adev->doorbell.num_doorbells = min_t(u32, adev->doorbell.size / sizeof(u32),
658 					     adev->doorbell_index.max_assignment+1);
659 	if (adev->doorbell.num_doorbells == 0)
660 		return -EINVAL;
661 
662 	/* For Vega, reserve and map two pages on doorbell BAR since SDMA
663 	 * paging queue doorbell use the second page. The
664 	 * AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the
665 	 * doorbells are in the first page. So with paging queue enabled,
666 	 * the max num_doorbells should + 1 page (0x400 in dword)
667 	 */
668 	if (adev->asic_type >= CHIP_VEGA10)
669 		adev->doorbell.num_doorbells += 0x400;
670 
671 	adev->doorbell.ptr = ioremap(adev->doorbell.base,
672 				     adev->doorbell.num_doorbells *
673 				     sizeof(u32));
674 	if (adev->doorbell.ptr == NULL)
675 		return -ENOMEM;
676 
677 	return 0;
678 }
679 
680 /**
681  * amdgpu_device_doorbell_fini - Tear down doorbell driver information.
682  *
683  * @adev: amdgpu_device pointer
684  *
685  * Tear down doorbell driver information (CIK)
686  */
687 static void amdgpu_device_doorbell_fini(struct amdgpu_device *adev)
688 {
689 	iounmap(adev->doorbell.ptr);
690 	adev->doorbell.ptr = NULL;
691 }
692 
693 
694 
695 /*
696  * amdgpu_device_wb_*()
697  * Writeback is the method by which the GPU updates special pages in memory
698  * with the status of certain GPU events (fences, ring pointers,etc.).
699  */
700 
701 /**
702  * amdgpu_device_wb_fini - Disable Writeback and free memory
703  *
704  * @adev: amdgpu_device pointer
705  *
706  * Disables Writeback and frees the Writeback memory (all asics).
707  * Used at driver shutdown.
708  */
709 static void amdgpu_device_wb_fini(struct amdgpu_device *adev)
710 {
711 	if (adev->wb.wb_obj) {
712 		amdgpu_bo_free_kernel(&adev->wb.wb_obj,
713 				      &adev->wb.gpu_addr,
714 				      (void **)&adev->wb.wb);
715 		adev->wb.wb_obj = NULL;
716 	}
717 }
718 
719 /**
720  * amdgpu_device_wb_init- Init Writeback driver info and allocate memory
721  *
722  * @adev: amdgpu_device pointer
723  *
724  * Initializes writeback and allocates writeback memory (all asics).
725  * Used at driver startup.
726  * Returns 0 on success or an -error on failure.
727  */
728 static int amdgpu_device_wb_init(struct amdgpu_device *adev)
729 {
730 	int r;
731 
732 	if (adev->wb.wb_obj == NULL) {
733 		/* AMDGPU_MAX_WB * sizeof(uint32_t) * 8 = AMDGPU_MAX_WB 256bit slots */
734 		r = amdgpu_bo_create_kernel(adev, AMDGPU_MAX_WB * sizeof(uint32_t) * 8,
735 					    PAGE_SIZE, AMDGPU_GEM_DOMAIN_GTT,
736 					    &adev->wb.wb_obj, &adev->wb.gpu_addr,
737 					    (void **)&adev->wb.wb);
738 		if (r) {
739 			dev_warn(adev->dev, "(%d) create WB bo failed\n", r);
740 			return r;
741 		}
742 
743 		adev->wb.num_wb = AMDGPU_MAX_WB;
744 		memset(&adev->wb.used, 0, sizeof(adev->wb.used));
745 
746 		/* clear wb memory */
747 		memset((char *)adev->wb.wb, 0, AMDGPU_MAX_WB * sizeof(uint32_t) * 8);
748 	}
749 
750 	return 0;
751 }
752 
753 /**
754  * amdgpu_device_wb_get - Allocate a wb entry
755  *
756  * @adev: amdgpu_device pointer
757  * @wb: wb index
758  *
759  * Allocate a wb slot for use by the driver (all asics).
760  * Returns 0 on success or -EINVAL on failure.
761  */
762 int amdgpu_device_wb_get(struct amdgpu_device *adev, u32 *wb)
763 {
764 	unsigned long offset = find_first_zero_bit(adev->wb.used, adev->wb.num_wb);
765 
766 	if (offset < adev->wb.num_wb) {
767 		__set_bit(offset, adev->wb.used);
768 		*wb = offset << 3; /* convert to dw offset */
769 		return 0;
770 	} else {
771 		return -EINVAL;
772 	}
773 }
774 
775 /**
776  * amdgpu_device_wb_free - Free a wb entry
777  *
778  * @adev: amdgpu_device pointer
779  * @wb: wb index
780  *
781  * Free a wb slot allocated for use by the driver (all asics)
782  */
783 void amdgpu_device_wb_free(struct amdgpu_device *adev, u32 wb)
784 {
785 	wb >>= 3;
786 	if (wb < adev->wb.num_wb)
787 		__clear_bit(wb, adev->wb.used);
788 }
789 
790 /**
791  * amdgpu_device_resize_fb_bar - try to resize FB BAR
792  *
793  * @adev: amdgpu_device pointer
794  *
795  * Try to resize FB BAR to make all VRAM CPU accessible. We try very hard not
796  * to fail, but if any of the BARs is not accessible after the size we abort
797  * driver loading by returning -ENODEV.
798  */
799 int amdgpu_device_resize_fb_bar(struct amdgpu_device *adev)
800 {
801 	u64 space_needed = roundup_pow_of_two(adev->gmc.real_vram_size);
802 	u32 rbar_size = order_base_2(((space_needed >> 20) | 1)) - 1;
803 	struct pci_bus *root;
804 	struct resource *res;
805 	unsigned i;
806 	u16 cmd;
807 	int r;
808 
809 	/* Bypass for VF */
810 	if (amdgpu_sriov_vf(adev))
811 		return 0;
812 
813 	/* Check if the root BUS has 64bit memory resources */
814 	root = adev->pdev->bus;
815 	while (root->parent)
816 		root = root->parent;
817 
818 	pci_bus_for_each_resource(root, res, i) {
819 		if (res && res->flags & (IORESOURCE_MEM | IORESOURCE_MEM_64) &&
820 		    res->start > 0x100000000ull)
821 			break;
822 	}
823 
824 	/* Trying to resize is pointless without a root hub window above 4GB */
825 	if (!res)
826 		return 0;
827 
828 	/* Disable memory decoding while we change the BAR addresses and size */
829 	pci_read_config_word(adev->pdev, PCI_COMMAND, &cmd);
830 	pci_write_config_word(adev->pdev, PCI_COMMAND,
831 			      cmd & ~PCI_COMMAND_MEMORY);
832 
833 	/* Free the VRAM and doorbell BAR, we most likely need to move both. */
834 	amdgpu_device_doorbell_fini(adev);
835 	if (adev->asic_type >= CHIP_BONAIRE)
836 		pci_release_resource(adev->pdev, 2);
837 
838 	pci_release_resource(adev->pdev, 0);
839 
840 	r = pci_resize_resource(adev->pdev, 0, rbar_size);
841 	if (r == -ENOSPC)
842 		DRM_INFO("Not enough PCI address space for a large BAR.");
843 	else if (r && r != -ENOTSUPP)
844 		DRM_ERROR("Problem resizing BAR0 (%d).", r);
845 
846 	pci_assign_unassigned_bus_resources(adev->pdev->bus);
847 
848 	/* When the doorbell or fb BAR isn't available we have no chance of
849 	 * using the device.
850 	 */
851 	r = amdgpu_device_doorbell_init(adev);
852 	if (r || (pci_resource_flags(adev->pdev, 0) & IORESOURCE_UNSET))
853 		return -ENODEV;
854 
855 	pci_write_config_word(adev->pdev, PCI_COMMAND, cmd);
856 
857 	return 0;
858 }
859 
860 /*
861  * GPU helpers function.
862  */
863 /**
864  * amdgpu_device_need_post - check if the hw need post or not
865  *
866  * @adev: amdgpu_device pointer
867  *
868  * Check if the asic has been initialized (all asics) at driver startup
869  * or post is needed if  hw reset is performed.
870  * Returns true if need or false if not.
871  */
872 bool amdgpu_device_need_post(struct amdgpu_device *adev)
873 {
874 	uint32_t reg;
875 
876 	if (amdgpu_sriov_vf(adev))
877 		return false;
878 
879 	if (amdgpu_passthrough(adev)) {
880 		/* for FIJI: In whole GPU pass-through virtualization case, after VM reboot
881 		 * some old smc fw still need driver do vPost otherwise gpu hang, while
882 		 * those smc fw version above 22.15 doesn't have this flaw, so we force
883 		 * vpost executed for smc version below 22.15
884 		 */
885 		if (adev->asic_type == CHIP_FIJI) {
886 			int err;
887 			uint32_t fw_ver;
888 			err = request_firmware(&adev->pm.fw, "amdgpu/fiji_smc.bin", adev->dev);
889 			/* force vPost if error occured */
890 			if (err)
891 				return true;
892 
893 			fw_ver = *((uint32_t *)adev->pm.fw->data + 69);
894 			if (fw_ver < 0x00160e00)
895 				return true;
896 		}
897 	}
898 
899 	if (adev->has_hw_reset) {
900 		adev->has_hw_reset = false;
901 		return true;
902 	}
903 
904 	/* bios scratch used on CIK+ */
905 	if (adev->asic_type >= CHIP_BONAIRE)
906 		return amdgpu_atombios_scratch_need_asic_init(adev);
907 
908 	/* check MEM_SIZE for older asics */
909 	reg = amdgpu_asic_get_config_memsize(adev);
910 
911 	if ((reg != 0) && (reg != 0xffffffff))
912 		return false;
913 
914 	return true;
915 }
916 
917 /* if we get transitioned to only one device, take VGA back */
918 /**
919  * amdgpu_device_vga_set_decode - enable/disable vga decode
920  *
921  * @cookie: amdgpu_device pointer
922  * @state: enable/disable vga decode
923  *
924  * Enable/disable vga decode (all asics).
925  * Returns VGA resource flags.
926  */
927 static unsigned int amdgpu_device_vga_set_decode(void *cookie, bool state)
928 {
929 	struct amdgpu_device *adev = cookie;
930 	amdgpu_asic_set_vga_state(adev, state);
931 	if (state)
932 		return VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
933 		       VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
934 	else
935 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
936 }
937 
938 /**
939  * amdgpu_device_check_block_size - validate the vm block size
940  *
941  * @adev: amdgpu_device pointer
942  *
943  * Validates the vm block size specified via module parameter.
944  * The vm block size defines number of bits in page table versus page directory,
945  * a page is 4KB so we have 12 bits offset, minimum 9 bits in the
946  * page table and the remaining bits are in the page directory.
947  */
948 static void amdgpu_device_check_block_size(struct amdgpu_device *adev)
949 {
950 	/* defines number of bits in page table versus page directory,
951 	 * a page is 4KB so we have 12 bits offset, minimum 9 bits in the
952 	 * page table and the remaining bits are in the page directory */
953 	if (amdgpu_vm_block_size == -1)
954 		return;
955 
956 	if (amdgpu_vm_block_size < 9) {
957 		dev_warn(adev->dev, "VM page table size (%d) too small\n",
958 			 amdgpu_vm_block_size);
959 		amdgpu_vm_block_size = -1;
960 	}
961 }
962 
963 /**
964  * amdgpu_device_check_vm_size - validate the vm size
965  *
966  * @adev: amdgpu_device pointer
967  *
968  * Validates the vm size in GB specified via module parameter.
969  * The VM size is the size of the GPU virtual memory space in GB.
970  */
971 static void amdgpu_device_check_vm_size(struct amdgpu_device *adev)
972 {
973 	/* no need to check the default value */
974 	if (amdgpu_vm_size == -1)
975 		return;
976 
977 	if (amdgpu_vm_size < 1) {
978 		dev_warn(adev->dev, "VM size (%d) too small, min is 1GB\n",
979 			 amdgpu_vm_size);
980 		amdgpu_vm_size = -1;
981 	}
982 }
983 
984 static void amdgpu_device_check_smu_prv_buffer_size(struct amdgpu_device *adev)
985 {
986 	struct sysinfo si;
987 	bool is_os_64 = (sizeof(void *) == 8) ? true : false;
988 	uint64_t total_memory;
989 	uint64_t dram_size_seven_GB = 0x1B8000000;
990 	uint64_t dram_size_three_GB = 0xB8000000;
991 
992 	if (amdgpu_smu_memory_pool_size == 0)
993 		return;
994 
995 	if (!is_os_64) {
996 		DRM_WARN("Not 64-bit OS, feature not supported\n");
997 		goto def_value;
998 	}
999 	si_meminfo(&si);
1000 	total_memory = (uint64_t)si.totalram * si.mem_unit;
1001 
1002 	if ((amdgpu_smu_memory_pool_size == 1) ||
1003 		(amdgpu_smu_memory_pool_size == 2)) {
1004 		if (total_memory < dram_size_three_GB)
1005 			goto def_value1;
1006 	} else if ((amdgpu_smu_memory_pool_size == 4) ||
1007 		(amdgpu_smu_memory_pool_size == 8)) {
1008 		if (total_memory < dram_size_seven_GB)
1009 			goto def_value1;
1010 	} else {
1011 		DRM_WARN("Smu memory pool size not supported\n");
1012 		goto def_value;
1013 	}
1014 	adev->pm.smu_prv_buffer_size = amdgpu_smu_memory_pool_size << 28;
1015 
1016 	return;
1017 
1018 def_value1:
1019 	DRM_WARN("No enough system memory\n");
1020 def_value:
1021 	adev->pm.smu_prv_buffer_size = 0;
1022 }
1023 
1024 /**
1025  * amdgpu_device_check_arguments - validate module params
1026  *
1027  * @adev: amdgpu_device pointer
1028  *
1029  * Validates certain module parameters and updates
1030  * the associated values used by the driver (all asics).
1031  */
1032 static int amdgpu_device_check_arguments(struct amdgpu_device *adev)
1033 {
1034 	int ret = 0;
1035 
1036 	if (amdgpu_sched_jobs < 4) {
1037 		dev_warn(adev->dev, "sched jobs (%d) must be at least 4\n",
1038 			 amdgpu_sched_jobs);
1039 		amdgpu_sched_jobs = 4;
1040 	} else if (!is_power_of_2(amdgpu_sched_jobs)){
1041 		dev_warn(adev->dev, "sched jobs (%d) must be a power of 2\n",
1042 			 amdgpu_sched_jobs);
1043 		amdgpu_sched_jobs = roundup_pow_of_two(amdgpu_sched_jobs);
1044 	}
1045 
1046 	if (amdgpu_gart_size != -1 && amdgpu_gart_size < 32) {
1047 		/* gart size must be greater or equal to 32M */
1048 		dev_warn(adev->dev, "gart size (%d) too small\n",
1049 			 amdgpu_gart_size);
1050 		amdgpu_gart_size = -1;
1051 	}
1052 
1053 	if (amdgpu_gtt_size != -1 && amdgpu_gtt_size < 32) {
1054 		/* gtt size must be greater or equal to 32M */
1055 		dev_warn(adev->dev, "gtt size (%d) too small\n",
1056 				 amdgpu_gtt_size);
1057 		amdgpu_gtt_size = -1;
1058 	}
1059 
1060 	/* valid range is between 4 and 9 inclusive */
1061 	if (amdgpu_vm_fragment_size != -1 &&
1062 	    (amdgpu_vm_fragment_size > 9 || amdgpu_vm_fragment_size < 4)) {
1063 		dev_warn(adev->dev, "valid range is between 4 and 9\n");
1064 		amdgpu_vm_fragment_size = -1;
1065 	}
1066 
1067 	amdgpu_device_check_smu_prv_buffer_size(adev);
1068 
1069 	amdgpu_device_check_vm_size(adev);
1070 
1071 	amdgpu_device_check_block_size(adev);
1072 
1073 	adev->firmware.load_type = amdgpu_ucode_get_load_type(adev, amdgpu_fw_load_type);
1074 
1075 	return ret;
1076 }
1077 
1078 /**
1079  * amdgpu_switcheroo_set_state - set switcheroo state
1080  *
1081  * @pdev: pci dev pointer
1082  * @state: vga_switcheroo state
1083  *
1084  * Callback for the switcheroo driver.  Suspends or resumes the
1085  * the asics before or after it is powered up using ACPI methods.
1086  */
1087 static void amdgpu_switcheroo_set_state(struct pci_dev *pdev, enum vga_switcheroo_state state)
1088 {
1089 	struct drm_device *dev = pci_get_drvdata(pdev);
1090 	int r;
1091 
1092 	if (amdgpu_device_supports_boco(dev) && state == VGA_SWITCHEROO_OFF)
1093 		return;
1094 
1095 	if (state == VGA_SWITCHEROO_ON) {
1096 		pr_info("amdgpu: switched on\n");
1097 		/* don't suspend or resume card normally */
1098 		dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
1099 
1100 		pci_set_power_state(dev->pdev, PCI_D0);
1101 		pci_restore_state(dev->pdev);
1102 		r = pci_enable_device(dev->pdev);
1103 		if (r)
1104 			DRM_WARN("pci_enable_device failed (%d)\n", r);
1105 		amdgpu_device_resume(dev, true);
1106 
1107 		dev->switch_power_state = DRM_SWITCH_POWER_ON;
1108 		drm_kms_helper_poll_enable(dev);
1109 	} else {
1110 		pr_info("amdgpu: switched off\n");
1111 		drm_kms_helper_poll_disable(dev);
1112 		dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
1113 		amdgpu_device_suspend(dev, true);
1114 		pci_save_state(dev->pdev);
1115 		/* Shut down the device */
1116 		pci_disable_device(dev->pdev);
1117 		pci_set_power_state(dev->pdev, PCI_D3cold);
1118 		dev->switch_power_state = DRM_SWITCH_POWER_OFF;
1119 	}
1120 }
1121 
1122 /**
1123  * amdgpu_switcheroo_can_switch - see if switcheroo state can change
1124  *
1125  * @pdev: pci dev pointer
1126  *
1127  * Callback for the switcheroo driver.  Check of the switcheroo
1128  * state can be changed.
1129  * Returns true if the state can be changed, false if not.
1130  */
1131 static bool amdgpu_switcheroo_can_switch(struct pci_dev *pdev)
1132 {
1133 	struct drm_device *dev = pci_get_drvdata(pdev);
1134 
1135 	/*
1136 	* FIXME: open_count is protected by drm_global_mutex but that would lead to
1137 	* locking inversion with the driver load path. And the access here is
1138 	* completely racy anyway. So don't bother with locking for now.
1139 	*/
1140 	return dev->open_count == 0;
1141 }
1142 
1143 static const struct vga_switcheroo_client_ops amdgpu_switcheroo_ops = {
1144 	.set_gpu_state = amdgpu_switcheroo_set_state,
1145 	.reprobe = NULL,
1146 	.can_switch = amdgpu_switcheroo_can_switch,
1147 };
1148 
1149 /**
1150  * amdgpu_device_ip_set_clockgating_state - set the CG state
1151  *
1152  * @dev: amdgpu_device pointer
1153  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1154  * @state: clockgating state (gate or ungate)
1155  *
1156  * Sets the requested clockgating state for all instances of
1157  * the hardware IP specified.
1158  * Returns the error code from the last instance.
1159  */
1160 int amdgpu_device_ip_set_clockgating_state(void *dev,
1161 					   enum amd_ip_block_type block_type,
1162 					   enum amd_clockgating_state state)
1163 {
1164 	struct amdgpu_device *adev = dev;
1165 	int i, r = 0;
1166 
1167 	for (i = 0; i < adev->num_ip_blocks; i++) {
1168 		if (!adev->ip_blocks[i].status.valid)
1169 			continue;
1170 		if (adev->ip_blocks[i].version->type != block_type)
1171 			continue;
1172 		if (!adev->ip_blocks[i].version->funcs->set_clockgating_state)
1173 			continue;
1174 		r = adev->ip_blocks[i].version->funcs->set_clockgating_state(
1175 			(void *)adev, state);
1176 		if (r)
1177 			DRM_ERROR("set_clockgating_state of IP block <%s> failed %d\n",
1178 				  adev->ip_blocks[i].version->funcs->name, r);
1179 	}
1180 	return r;
1181 }
1182 
1183 /**
1184  * amdgpu_device_ip_set_powergating_state - set the PG state
1185  *
1186  * @dev: amdgpu_device pointer
1187  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1188  * @state: powergating state (gate or ungate)
1189  *
1190  * Sets the requested powergating state for all instances of
1191  * the hardware IP specified.
1192  * Returns the error code from the last instance.
1193  */
1194 int amdgpu_device_ip_set_powergating_state(void *dev,
1195 					   enum amd_ip_block_type block_type,
1196 					   enum amd_powergating_state state)
1197 {
1198 	struct amdgpu_device *adev = dev;
1199 	int i, r = 0;
1200 
1201 	for (i = 0; i < adev->num_ip_blocks; i++) {
1202 		if (!adev->ip_blocks[i].status.valid)
1203 			continue;
1204 		if (adev->ip_blocks[i].version->type != block_type)
1205 			continue;
1206 		if (!adev->ip_blocks[i].version->funcs->set_powergating_state)
1207 			continue;
1208 		r = adev->ip_blocks[i].version->funcs->set_powergating_state(
1209 			(void *)adev, state);
1210 		if (r)
1211 			DRM_ERROR("set_powergating_state of IP block <%s> failed %d\n",
1212 				  adev->ip_blocks[i].version->funcs->name, r);
1213 	}
1214 	return r;
1215 }
1216 
1217 /**
1218  * amdgpu_device_ip_get_clockgating_state - get the CG state
1219  *
1220  * @adev: amdgpu_device pointer
1221  * @flags: clockgating feature flags
1222  *
1223  * Walks the list of IPs on the device and updates the clockgating
1224  * flags for each IP.
1225  * Updates @flags with the feature flags for each hardware IP where
1226  * clockgating is enabled.
1227  */
1228 void amdgpu_device_ip_get_clockgating_state(struct amdgpu_device *adev,
1229 					    u32 *flags)
1230 {
1231 	int i;
1232 
1233 	for (i = 0; i < adev->num_ip_blocks; i++) {
1234 		if (!adev->ip_blocks[i].status.valid)
1235 			continue;
1236 		if (adev->ip_blocks[i].version->funcs->get_clockgating_state)
1237 			adev->ip_blocks[i].version->funcs->get_clockgating_state((void *)adev, flags);
1238 	}
1239 }
1240 
1241 /**
1242  * amdgpu_device_ip_wait_for_idle - wait for idle
1243  *
1244  * @adev: amdgpu_device pointer
1245  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1246  *
1247  * Waits for the request hardware IP to be idle.
1248  * Returns 0 for success or a negative error code on failure.
1249  */
1250 int amdgpu_device_ip_wait_for_idle(struct amdgpu_device *adev,
1251 				   enum amd_ip_block_type block_type)
1252 {
1253 	int i, r;
1254 
1255 	for (i = 0; i < adev->num_ip_blocks; i++) {
1256 		if (!adev->ip_blocks[i].status.valid)
1257 			continue;
1258 		if (adev->ip_blocks[i].version->type == block_type) {
1259 			r = adev->ip_blocks[i].version->funcs->wait_for_idle((void *)adev);
1260 			if (r)
1261 				return r;
1262 			break;
1263 		}
1264 	}
1265 	return 0;
1266 
1267 }
1268 
1269 /**
1270  * amdgpu_device_ip_is_idle - is the hardware IP idle
1271  *
1272  * @adev: amdgpu_device pointer
1273  * @block_type: Type of hardware IP (SMU, GFX, UVD, etc.)
1274  *
1275  * Check if the hardware IP is idle or not.
1276  * Returns true if it the IP is idle, false if not.
1277  */
1278 bool amdgpu_device_ip_is_idle(struct amdgpu_device *adev,
1279 			      enum amd_ip_block_type block_type)
1280 {
1281 	int i;
1282 
1283 	for (i = 0; i < adev->num_ip_blocks; i++) {
1284 		if (!adev->ip_blocks[i].status.valid)
1285 			continue;
1286 		if (adev->ip_blocks[i].version->type == block_type)
1287 			return adev->ip_blocks[i].version->funcs->is_idle((void *)adev);
1288 	}
1289 	return true;
1290 
1291 }
1292 
1293 /**
1294  * amdgpu_device_ip_get_ip_block - get a hw IP pointer
1295  *
1296  * @adev: amdgpu_device pointer
1297  * @type: Type of hardware IP (SMU, GFX, UVD, etc.)
1298  *
1299  * Returns a pointer to the hardware IP block structure
1300  * if it exists for the asic, otherwise NULL.
1301  */
1302 struct amdgpu_ip_block *
1303 amdgpu_device_ip_get_ip_block(struct amdgpu_device *adev,
1304 			      enum amd_ip_block_type type)
1305 {
1306 	int i;
1307 
1308 	for (i = 0; i < adev->num_ip_blocks; i++)
1309 		if (adev->ip_blocks[i].version->type == type)
1310 			return &adev->ip_blocks[i];
1311 
1312 	return NULL;
1313 }
1314 
1315 /**
1316  * amdgpu_device_ip_block_version_cmp
1317  *
1318  * @adev: amdgpu_device pointer
1319  * @type: enum amd_ip_block_type
1320  * @major: major version
1321  * @minor: minor version
1322  *
1323  * return 0 if equal or greater
1324  * return 1 if smaller or the ip_block doesn't exist
1325  */
1326 int amdgpu_device_ip_block_version_cmp(struct amdgpu_device *adev,
1327 				       enum amd_ip_block_type type,
1328 				       u32 major, u32 minor)
1329 {
1330 	struct amdgpu_ip_block *ip_block = amdgpu_device_ip_get_ip_block(adev, type);
1331 
1332 	if (ip_block && ((ip_block->version->major > major) ||
1333 			((ip_block->version->major == major) &&
1334 			(ip_block->version->minor >= minor))))
1335 		return 0;
1336 
1337 	return 1;
1338 }
1339 
1340 /**
1341  * amdgpu_device_ip_block_add
1342  *
1343  * @adev: amdgpu_device pointer
1344  * @ip_block_version: pointer to the IP to add
1345  *
1346  * Adds the IP block driver information to the collection of IPs
1347  * on the asic.
1348  */
1349 int amdgpu_device_ip_block_add(struct amdgpu_device *adev,
1350 			       const struct amdgpu_ip_block_version *ip_block_version)
1351 {
1352 	if (!ip_block_version)
1353 		return -EINVAL;
1354 
1355 	DRM_INFO("add ip block number %d <%s>\n", adev->num_ip_blocks,
1356 		  ip_block_version->funcs->name);
1357 
1358 	adev->ip_blocks[adev->num_ip_blocks++].version = ip_block_version;
1359 
1360 	return 0;
1361 }
1362 
1363 /**
1364  * amdgpu_device_enable_virtual_display - enable virtual display feature
1365  *
1366  * @adev: amdgpu_device pointer
1367  *
1368  * Enabled the virtual display feature if the user has enabled it via
1369  * the module parameter virtual_display.  This feature provides a virtual
1370  * display hardware on headless boards or in virtualized environments.
1371  * This function parses and validates the configuration string specified by
1372  * the user and configues the virtual display configuration (number of
1373  * virtual connectors, crtcs, etc.) specified.
1374  */
1375 static void amdgpu_device_enable_virtual_display(struct amdgpu_device *adev)
1376 {
1377 	adev->enable_virtual_display = false;
1378 
1379 	if (amdgpu_virtual_display) {
1380 		struct drm_device *ddev = adev->ddev;
1381 		const char *pci_address_name = pci_name(ddev->pdev);
1382 		char *pciaddstr, *pciaddstr_tmp, *pciaddname_tmp, *pciaddname;
1383 
1384 		pciaddstr = kstrdup(amdgpu_virtual_display, GFP_KERNEL);
1385 		pciaddstr_tmp = pciaddstr;
1386 		while ((pciaddname_tmp = strsep(&pciaddstr_tmp, ";"))) {
1387 			pciaddname = strsep(&pciaddname_tmp, ",");
1388 			if (!strcmp("all", pciaddname)
1389 			    || !strcmp(pci_address_name, pciaddname)) {
1390 				long num_crtc;
1391 				int res = -1;
1392 
1393 				adev->enable_virtual_display = true;
1394 
1395 				if (pciaddname_tmp)
1396 					res = kstrtol(pciaddname_tmp, 10,
1397 						      &num_crtc);
1398 
1399 				if (!res) {
1400 					if (num_crtc < 1)
1401 						num_crtc = 1;
1402 					if (num_crtc > 6)
1403 						num_crtc = 6;
1404 					adev->mode_info.num_crtc = num_crtc;
1405 				} else {
1406 					adev->mode_info.num_crtc = 1;
1407 				}
1408 				break;
1409 			}
1410 		}
1411 
1412 		DRM_INFO("virtual display string:%s, %s:virtual_display:%d, num_crtc:%d\n",
1413 			 amdgpu_virtual_display, pci_address_name,
1414 			 adev->enable_virtual_display, adev->mode_info.num_crtc);
1415 
1416 		kfree(pciaddstr);
1417 	}
1418 }
1419 
1420 /**
1421  * amdgpu_device_parse_gpu_info_fw - parse gpu info firmware
1422  *
1423  * @adev: amdgpu_device pointer
1424  *
1425  * Parses the asic configuration parameters specified in the gpu info
1426  * firmware and makes them availale to the driver for use in configuring
1427  * the asic.
1428  * Returns 0 on success, -EINVAL on failure.
1429  */
1430 static int amdgpu_device_parse_gpu_info_fw(struct amdgpu_device *adev)
1431 {
1432 	const char *chip_name;
1433 	char fw_name[30];
1434 	int err;
1435 	const struct gpu_info_firmware_header_v1_0 *hdr;
1436 
1437 	adev->firmware.gpu_info_fw = NULL;
1438 
1439 	switch (adev->asic_type) {
1440 	case CHIP_TOPAZ:
1441 	case CHIP_TONGA:
1442 	case CHIP_FIJI:
1443 	case CHIP_POLARIS10:
1444 	case CHIP_POLARIS11:
1445 	case CHIP_POLARIS12:
1446 	case CHIP_VEGAM:
1447 	case CHIP_CARRIZO:
1448 	case CHIP_STONEY:
1449 #ifdef CONFIG_DRM_AMDGPU_SI
1450 	case CHIP_VERDE:
1451 	case CHIP_TAHITI:
1452 	case CHIP_PITCAIRN:
1453 	case CHIP_OLAND:
1454 	case CHIP_HAINAN:
1455 #endif
1456 #ifdef CONFIG_DRM_AMDGPU_CIK
1457 	case CHIP_BONAIRE:
1458 	case CHIP_HAWAII:
1459 	case CHIP_KAVERI:
1460 	case CHIP_KABINI:
1461 	case CHIP_MULLINS:
1462 #endif
1463 	case CHIP_VEGA20:
1464 	default:
1465 		return 0;
1466 	case CHIP_VEGA10:
1467 		chip_name = "vega10";
1468 		break;
1469 	case CHIP_VEGA12:
1470 		chip_name = "vega12";
1471 		break;
1472 	case CHIP_RAVEN:
1473 		if (adev->rev_id >= 8)
1474 			chip_name = "raven2";
1475 		else if (adev->pdev->device == 0x15d8)
1476 			chip_name = "picasso";
1477 		else
1478 			chip_name = "raven";
1479 		break;
1480 	case CHIP_ARCTURUS:
1481 		chip_name = "arcturus";
1482 		break;
1483 	case CHIP_RENOIR:
1484 		chip_name = "renoir";
1485 		break;
1486 	case CHIP_NAVI10:
1487 		chip_name = "navi10";
1488 		break;
1489 	case CHIP_NAVI14:
1490 		chip_name = "navi14";
1491 		break;
1492 	case CHIP_NAVI12:
1493 		chip_name = "navi12";
1494 		break;
1495 	}
1496 
1497 	snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_gpu_info.bin", chip_name);
1498 	err = request_firmware(&adev->firmware.gpu_info_fw, fw_name, adev->dev);
1499 	if (err) {
1500 		dev_err(adev->dev,
1501 			"Failed to load gpu_info firmware \"%s\"\n",
1502 			fw_name);
1503 		goto out;
1504 	}
1505 	err = amdgpu_ucode_validate(adev->firmware.gpu_info_fw);
1506 	if (err) {
1507 		dev_err(adev->dev,
1508 			"Failed to validate gpu_info firmware \"%s\"\n",
1509 			fw_name);
1510 		goto out;
1511 	}
1512 
1513 	hdr = (const struct gpu_info_firmware_header_v1_0 *)adev->firmware.gpu_info_fw->data;
1514 	amdgpu_ucode_print_gpu_info_hdr(&hdr->header);
1515 
1516 	switch (hdr->version_major) {
1517 	case 1:
1518 	{
1519 		const struct gpu_info_firmware_v1_0 *gpu_info_fw =
1520 			(const struct gpu_info_firmware_v1_0 *)(adev->firmware.gpu_info_fw->data +
1521 								le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1522 
1523 		if (amdgpu_discovery && adev->asic_type >= CHIP_NAVI10)
1524 			goto parse_soc_bounding_box;
1525 
1526 		adev->gfx.config.max_shader_engines = le32_to_cpu(gpu_info_fw->gc_num_se);
1527 		adev->gfx.config.max_cu_per_sh = le32_to_cpu(gpu_info_fw->gc_num_cu_per_sh);
1528 		adev->gfx.config.max_sh_per_se = le32_to_cpu(gpu_info_fw->gc_num_sh_per_se);
1529 		adev->gfx.config.max_backends_per_se = le32_to_cpu(gpu_info_fw->gc_num_rb_per_se);
1530 		adev->gfx.config.max_texture_channel_caches =
1531 			le32_to_cpu(gpu_info_fw->gc_num_tccs);
1532 		adev->gfx.config.max_gprs = le32_to_cpu(gpu_info_fw->gc_num_gprs);
1533 		adev->gfx.config.max_gs_threads = le32_to_cpu(gpu_info_fw->gc_num_max_gs_thds);
1534 		adev->gfx.config.gs_vgt_table_depth = le32_to_cpu(gpu_info_fw->gc_gs_table_depth);
1535 		adev->gfx.config.gs_prim_buffer_depth = le32_to_cpu(gpu_info_fw->gc_gsprim_buff_depth);
1536 		adev->gfx.config.double_offchip_lds_buf =
1537 			le32_to_cpu(gpu_info_fw->gc_double_offchip_lds_buffer);
1538 		adev->gfx.cu_info.wave_front_size = le32_to_cpu(gpu_info_fw->gc_wave_size);
1539 		adev->gfx.cu_info.max_waves_per_simd =
1540 			le32_to_cpu(gpu_info_fw->gc_max_waves_per_simd);
1541 		adev->gfx.cu_info.max_scratch_slots_per_cu =
1542 			le32_to_cpu(gpu_info_fw->gc_max_scratch_slots_per_cu);
1543 		adev->gfx.cu_info.lds_size = le32_to_cpu(gpu_info_fw->gc_lds_size);
1544 		if (hdr->version_minor >= 1) {
1545 			const struct gpu_info_firmware_v1_1 *gpu_info_fw =
1546 				(const struct gpu_info_firmware_v1_1 *)(adev->firmware.gpu_info_fw->data +
1547 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1548 			adev->gfx.config.num_sc_per_sh =
1549 				le32_to_cpu(gpu_info_fw->num_sc_per_sh);
1550 			adev->gfx.config.num_packer_per_sc =
1551 				le32_to_cpu(gpu_info_fw->num_packer_per_sc);
1552 		}
1553 
1554 parse_soc_bounding_box:
1555 		/*
1556 		 * soc bounding box info is not integrated in disocovery table,
1557 		 * we always need to parse it from gpu info firmware.
1558 		 */
1559 		if (hdr->version_minor == 2) {
1560 			const struct gpu_info_firmware_v1_2 *gpu_info_fw =
1561 				(const struct gpu_info_firmware_v1_2 *)(adev->firmware.gpu_info_fw->data +
1562 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1563 			adev->dm.soc_bounding_box = &gpu_info_fw->soc_bounding_box;
1564 		}
1565 		break;
1566 	}
1567 	default:
1568 		dev_err(adev->dev,
1569 			"Unsupported gpu_info table %d\n", hdr->header.ucode_version);
1570 		err = -EINVAL;
1571 		goto out;
1572 	}
1573 out:
1574 	return err;
1575 }
1576 
1577 /**
1578  * amdgpu_device_ip_early_init - run early init for hardware IPs
1579  *
1580  * @adev: amdgpu_device pointer
1581  *
1582  * Early initialization pass for hardware IPs.  The hardware IPs that make
1583  * up each asic are discovered each IP's early_init callback is run.  This
1584  * is the first stage in initializing the asic.
1585  * Returns 0 on success, negative error code on failure.
1586  */
1587 static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
1588 {
1589 	int i, r;
1590 
1591 	amdgpu_device_enable_virtual_display(adev);
1592 
1593 	switch (adev->asic_type) {
1594 	case CHIP_TOPAZ:
1595 	case CHIP_TONGA:
1596 	case CHIP_FIJI:
1597 	case CHIP_POLARIS10:
1598 	case CHIP_POLARIS11:
1599 	case CHIP_POLARIS12:
1600 	case CHIP_VEGAM:
1601 	case CHIP_CARRIZO:
1602 	case CHIP_STONEY:
1603 		if (adev->asic_type == CHIP_CARRIZO || adev->asic_type == CHIP_STONEY)
1604 			adev->family = AMDGPU_FAMILY_CZ;
1605 		else
1606 			adev->family = AMDGPU_FAMILY_VI;
1607 
1608 		r = vi_set_ip_blocks(adev);
1609 		if (r)
1610 			return r;
1611 		break;
1612 #ifdef CONFIG_DRM_AMDGPU_SI
1613 	case CHIP_VERDE:
1614 	case CHIP_TAHITI:
1615 	case CHIP_PITCAIRN:
1616 	case CHIP_OLAND:
1617 	case CHIP_HAINAN:
1618 		adev->family = AMDGPU_FAMILY_SI;
1619 		r = si_set_ip_blocks(adev);
1620 		if (r)
1621 			return r;
1622 		break;
1623 #endif
1624 #ifdef CONFIG_DRM_AMDGPU_CIK
1625 	case CHIP_BONAIRE:
1626 	case CHIP_HAWAII:
1627 	case CHIP_KAVERI:
1628 	case CHIP_KABINI:
1629 	case CHIP_MULLINS:
1630 		if ((adev->asic_type == CHIP_BONAIRE) || (adev->asic_type == CHIP_HAWAII))
1631 			adev->family = AMDGPU_FAMILY_CI;
1632 		else
1633 			adev->family = AMDGPU_FAMILY_KV;
1634 
1635 		r = cik_set_ip_blocks(adev);
1636 		if (r)
1637 			return r;
1638 		break;
1639 #endif
1640 	case CHIP_VEGA10:
1641 	case CHIP_VEGA12:
1642 	case CHIP_VEGA20:
1643 	case CHIP_RAVEN:
1644 	case CHIP_ARCTURUS:
1645 	case CHIP_RENOIR:
1646 		if (adev->asic_type == CHIP_RAVEN ||
1647 		    adev->asic_type == CHIP_RENOIR)
1648 			adev->family = AMDGPU_FAMILY_RV;
1649 		else
1650 			adev->family = AMDGPU_FAMILY_AI;
1651 
1652 		r = soc15_set_ip_blocks(adev);
1653 		if (r)
1654 			return r;
1655 		break;
1656 	case  CHIP_NAVI10:
1657 	case  CHIP_NAVI14:
1658 	case  CHIP_NAVI12:
1659 		adev->family = AMDGPU_FAMILY_NV;
1660 
1661 		r = nv_set_ip_blocks(adev);
1662 		if (r)
1663 			return r;
1664 		break;
1665 	default:
1666 		/* FIXME: not supported yet */
1667 		return -EINVAL;
1668 	}
1669 
1670 	r = amdgpu_device_parse_gpu_info_fw(adev);
1671 	if (r)
1672 		return r;
1673 
1674 	if (amdgpu_discovery && adev->asic_type >= CHIP_NAVI10)
1675 		amdgpu_discovery_get_gfx_info(adev);
1676 
1677 	amdgpu_amdkfd_device_probe(adev);
1678 
1679 	if (amdgpu_sriov_vf(adev)) {
1680 		r = amdgpu_virt_request_full_gpu(adev, true);
1681 		if (r)
1682 			return -EAGAIN;
1683 	}
1684 
1685 	adev->pm.pp_feature = amdgpu_pp_feature_mask;
1686 	if (amdgpu_sriov_vf(adev) || sched_policy == KFD_SCHED_POLICY_NO_HWS)
1687 		adev->pm.pp_feature &= ~PP_GFXOFF_MASK;
1688 
1689 	for (i = 0; i < adev->num_ip_blocks; i++) {
1690 		if ((amdgpu_ip_block_mask & (1 << i)) == 0) {
1691 			DRM_ERROR("disabled ip block: %d <%s>\n",
1692 				  i, adev->ip_blocks[i].version->funcs->name);
1693 			adev->ip_blocks[i].status.valid = false;
1694 		} else {
1695 			if (adev->ip_blocks[i].version->funcs->early_init) {
1696 				r = adev->ip_blocks[i].version->funcs->early_init((void *)adev);
1697 				if (r == -ENOENT) {
1698 					adev->ip_blocks[i].status.valid = false;
1699 				} else if (r) {
1700 					DRM_ERROR("early_init of IP block <%s> failed %d\n",
1701 						  adev->ip_blocks[i].version->funcs->name, r);
1702 					return r;
1703 				} else {
1704 					adev->ip_blocks[i].status.valid = true;
1705 				}
1706 			} else {
1707 				adev->ip_blocks[i].status.valid = true;
1708 			}
1709 		}
1710 		/* get the vbios after the asic_funcs are set up */
1711 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON) {
1712 			/* Read BIOS */
1713 			if (!amdgpu_get_bios(adev))
1714 				return -EINVAL;
1715 
1716 			r = amdgpu_atombios_init(adev);
1717 			if (r) {
1718 				dev_err(adev->dev, "amdgpu_atombios_init failed\n");
1719 				amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_INIT_FAIL, 0, 0);
1720 				return r;
1721 			}
1722 		}
1723 	}
1724 
1725 	adev->cg_flags &= amdgpu_cg_mask;
1726 	adev->pg_flags &= amdgpu_pg_mask;
1727 
1728 	return 0;
1729 }
1730 
1731 static int amdgpu_device_ip_hw_init_phase1(struct amdgpu_device *adev)
1732 {
1733 	int i, r;
1734 
1735 	for (i = 0; i < adev->num_ip_blocks; i++) {
1736 		if (!adev->ip_blocks[i].status.sw)
1737 			continue;
1738 		if (adev->ip_blocks[i].status.hw)
1739 			continue;
1740 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
1741 		    (amdgpu_sriov_vf(adev) && (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)) ||
1742 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
1743 			r = adev->ip_blocks[i].version->funcs->hw_init(adev);
1744 			if (r) {
1745 				DRM_ERROR("hw_init of IP block <%s> failed %d\n",
1746 					  adev->ip_blocks[i].version->funcs->name, r);
1747 				return r;
1748 			}
1749 			adev->ip_blocks[i].status.hw = true;
1750 		}
1751 	}
1752 
1753 	return 0;
1754 }
1755 
1756 static int amdgpu_device_ip_hw_init_phase2(struct amdgpu_device *adev)
1757 {
1758 	int i, r;
1759 
1760 	for (i = 0; i < adev->num_ip_blocks; i++) {
1761 		if (!adev->ip_blocks[i].status.sw)
1762 			continue;
1763 		if (adev->ip_blocks[i].status.hw)
1764 			continue;
1765 		r = adev->ip_blocks[i].version->funcs->hw_init(adev);
1766 		if (r) {
1767 			DRM_ERROR("hw_init of IP block <%s> failed %d\n",
1768 				  adev->ip_blocks[i].version->funcs->name, r);
1769 			return r;
1770 		}
1771 		adev->ip_blocks[i].status.hw = true;
1772 	}
1773 
1774 	return 0;
1775 }
1776 
1777 static int amdgpu_device_fw_loading(struct amdgpu_device *adev)
1778 {
1779 	int r = 0;
1780 	int i;
1781 	uint32_t smu_version;
1782 
1783 	if (adev->asic_type >= CHIP_VEGA10) {
1784 		for (i = 0; i < adev->num_ip_blocks; i++) {
1785 			if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_PSP)
1786 				continue;
1787 
1788 			/* no need to do the fw loading again if already done*/
1789 			if (adev->ip_blocks[i].status.hw == true)
1790 				break;
1791 
1792 			if (adev->in_gpu_reset || adev->in_suspend) {
1793 				r = adev->ip_blocks[i].version->funcs->resume(adev);
1794 				if (r) {
1795 					DRM_ERROR("resume of IP block <%s> failed %d\n",
1796 							  adev->ip_blocks[i].version->funcs->name, r);
1797 					return r;
1798 				}
1799 			} else {
1800 				r = adev->ip_blocks[i].version->funcs->hw_init(adev);
1801 				if (r) {
1802 					DRM_ERROR("hw_init of IP block <%s> failed %d\n",
1803 							  adev->ip_blocks[i].version->funcs->name, r);
1804 					return r;
1805 				}
1806 			}
1807 
1808 			adev->ip_blocks[i].status.hw = true;
1809 			break;
1810 		}
1811 	}
1812 
1813 	r = amdgpu_pm_load_smu_firmware(adev, &smu_version);
1814 
1815 	return r;
1816 }
1817 
1818 /**
1819  * amdgpu_device_ip_init - run init for hardware IPs
1820  *
1821  * @adev: amdgpu_device pointer
1822  *
1823  * Main initialization pass for hardware IPs.  The list of all the hardware
1824  * IPs that make up the asic is walked and the sw_init and hw_init callbacks
1825  * are run.  sw_init initializes the software state associated with each IP
1826  * and hw_init initializes the hardware associated with each IP.
1827  * Returns 0 on success, negative error code on failure.
1828  */
1829 static int amdgpu_device_ip_init(struct amdgpu_device *adev)
1830 {
1831 	int i, r;
1832 
1833 	r = amdgpu_ras_init(adev);
1834 	if (r)
1835 		return r;
1836 
1837 	for (i = 0; i < adev->num_ip_blocks; i++) {
1838 		if (!adev->ip_blocks[i].status.valid)
1839 			continue;
1840 		r = adev->ip_blocks[i].version->funcs->sw_init((void *)adev);
1841 		if (r) {
1842 			DRM_ERROR("sw_init of IP block <%s> failed %d\n",
1843 				  adev->ip_blocks[i].version->funcs->name, r);
1844 			goto init_failed;
1845 		}
1846 		adev->ip_blocks[i].status.sw = true;
1847 
1848 		/* need to do gmc hw init early so we can allocate gpu mem */
1849 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
1850 			r = amdgpu_device_vram_scratch_init(adev);
1851 			if (r) {
1852 				DRM_ERROR("amdgpu_vram_scratch_init failed %d\n", r);
1853 				goto init_failed;
1854 			}
1855 			r = adev->ip_blocks[i].version->funcs->hw_init((void *)adev);
1856 			if (r) {
1857 				DRM_ERROR("hw_init %d failed %d\n", i, r);
1858 				goto init_failed;
1859 			}
1860 			r = amdgpu_device_wb_init(adev);
1861 			if (r) {
1862 				DRM_ERROR("amdgpu_device_wb_init failed %d\n", r);
1863 				goto init_failed;
1864 			}
1865 			adev->ip_blocks[i].status.hw = true;
1866 
1867 			/* right after GMC hw init, we create CSA */
1868 			if (amdgpu_mcbp || amdgpu_sriov_vf(adev)) {
1869 				r = amdgpu_allocate_static_csa(adev, &adev->virt.csa_obj,
1870 								AMDGPU_GEM_DOMAIN_VRAM,
1871 								AMDGPU_CSA_SIZE);
1872 				if (r) {
1873 					DRM_ERROR("allocate CSA failed %d\n", r);
1874 					goto init_failed;
1875 				}
1876 			}
1877 		}
1878 	}
1879 
1880 	r = amdgpu_ib_pool_init(adev);
1881 	if (r) {
1882 		dev_err(adev->dev, "IB initialization failed (%d).\n", r);
1883 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_IB_INIT_FAIL, 0, r);
1884 		goto init_failed;
1885 	}
1886 
1887 	r = amdgpu_ucode_create_bo(adev); /* create ucode bo when sw_init complete*/
1888 	if (r)
1889 		goto init_failed;
1890 
1891 	r = amdgpu_device_ip_hw_init_phase1(adev);
1892 	if (r)
1893 		goto init_failed;
1894 
1895 	r = amdgpu_device_fw_loading(adev);
1896 	if (r)
1897 		goto init_failed;
1898 
1899 	r = amdgpu_device_ip_hw_init_phase2(adev);
1900 	if (r)
1901 		goto init_failed;
1902 
1903 	/*
1904 	 * retired pages will be loaded from eeprom and reserved here,
1905 	 * it should be called after amdgpu_device_ip_hw_init_phase2  since
1906 	 * for some ASICs the RAS EEPROM code relies on SMU fully functioning
1907 	 * for I2C communication which only true at this point.
1908 	 * recovery_init may fail, but it can free all resources allocated by
1909 	 * itself and its failure should not stop amdgpu init process.
1910 	 *
1911 	 * Note: theoretically, this should be called before all vram allocations
1912 	 * to protect retired page from abusing
1913 	 */
1914 	amdgpu_ras_recovery_init(adev);
1915 
1916 	if (adev->gmc.xgmi.num_physical_nodes > 1)
1917 		amdgpu_xgmi_add_device(adev);
1918 	amdgpu_amdkfd_device_init(adev);
1919 
1920 init_failed:
1921 	if (amdgpu_sriov_vf(adev)) {
1922 		if (!r)
1923 			amdgpu_virt_init_data_exchange(adev);
1924 		amdgpu_virt_release_full_gpu(adev, true);
1925 	}
1926 
1927 	return r;
1928 }
1929 
1930 /**
1931  * amdgpu_device_fill_reset_magic - writes reset magic to gart pointer
1932  *
1933  * @adev: amdgpu_device pointer
1934  *
1935  * Writes a reset magic value to the gart pointer in VRAM.  The driver calls
1936  * this function before a GPU reset.  If the value is retained after a
1937  * GPU reset, VRAM has not been lost.  Some GPU resets may destry VRAM contents.
1938  */
1939 static void amdgpu_device_fill_reset_magic(struct amdgpu_device *adev)
1940 {
1941 	memcpy(adev->reset_magic, adev->gart.ptr, AMDGPU_RESET_MAGIC_NUM);
1942 }
1943 
1944 /**
1945  * amdgpu_device_check_vram_lost - check if vram is valid
1946  *
1947  * @adev: amdgpu_device pointer
1948  *
1949  * Checks the reset magic value written to the gart pointer in VRAM.
1950  * The driver calls this after a GPU reset to see if the contents of
1951  * VRAM is lost or now.
1952  * returns true if vram is lost, false if not.
1953  */
1954 static bool amdgpu_device_check_vram_lost(struct amdgpu_device *adev)
1955 {
1956 	return !!memcmp(adev->gart.ptr, adev->reset_magic,
1957 			AMDGPU_RESET_MAGIC_NUM);
1958 }
1959 
1960 /**
1961  * amdgpu_device_set_cg_state - set clockgating for amdgpu device
1962  *
1963  * @adev: amdgpu_device pointer
1964  * @state: clockgating state (gate or ungate)
1965  *
1966  * The list of all the hardware IPs that make up the asic is walked and the
1967  * set_clockgating_state callbacks are run.
1968  * Late initialization pass enabling clockgating for hardware IPs.
1969  * Fini or suspend, pass disabling clockgating for hardware IPs.
1970  * Returns 0 on success, negative error code on failure.
1971  */
1972 
1973 static int amdgpu_device_set_cg_state(struct amdgpu_device *adev,
1974 						enum amd_clockgating_state state)
1975 {
1976 	int i, j, r;
1977 
1978 	if (amdgpu_emu_mode == 1)
1979 		return 0;
1980 
1981 	for (j = 0; j < adev->num_ip_blocks; j++) {
1982 		i = state == AMD_CG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
1983 		if (!adev->ip_blocks[i].status.late_initialized)
1984 			continue;
1985 		/* skip CG for VCE/UVD, it's handled specially */
1986 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
1987 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
1988 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
1989 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
1990 		    adev->ip_blocks[i].version->funcs->set_clockgating_state) {
1991 			/* enable clockgating to save power */
1992 			r = adev->ip_blocks[i].version->funcs->set_clockgating_state((void *)adev,
1993 										     state);
1994 			if (r) {
1995 				DRM_ERROR("set_clockgating_state(gate) of IP block <%s> failed %d\n",
1996 					  adev->ip_blocks[i].version->funcs->name, r);
1997 				return r;
1998 			}
1999 		}
2000 	}
2001 
2002 	return 0;
2003 }
2004 
2005 static int amdgpu_device_set_pg_state(struct amdgpu_device *adev, enum amd_powergating_state state)
2006 {
2007 	int i, j, r;
2008 
2009 	if (amdgpu_emu_mode == 1)
2010 		return 0;
2011 
2012 	for (j = 0; j < adev->num_ip_blocks; j++) {
2013 		i = state == AMD_PG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2014 		if (!adev->ip_blocks[i].status.late_initialized)
2015 			continue;
2016 		/* skip CG for VCE/UVD, it's handled specially */
2017 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2018 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2019 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2020 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2021 		    adev->ip_blocks[i].version->funcs->set_powergating_state) {
2022 			/* enable powergating to save power */
2023 			r = adev->ip_blocks[i].version->funcs->set_powergating_state((void *)adev,
2024 											state);
2025 			if (r) {
2026 				DRM_ERROR("set_powergating_state(gate) of IP block <%s> failed %d\n",
2027 					  adev->ip_blocks[i].version->funcs->name, r);
2028 				return r;
2029 			}
2030 		}
2031 	}
2032 	return 0;
2033 }
2034 
2035 static int amdgpu_device_enable_mgpu_fan_boost(void)
2036 {
2037 	struct amdgpu_gpu_instance *gpu_ins;
2038 	struct amdgpu_device *adev;
2039 	int i, ret = 0;
2040 
2041 	mutex_lock(&mgpu_info.mutex);
2042 
2043 	/*
2044 	 * MGPU fan boost feature should be enabled
2045 	 * only when there are two or more dGPUs in
2046 	 * the system
2047 	 */
2048 	if (mgpu_info.num_dgpu < 2)
2049 		goto out;
2050 
2051 	for (i = 0; i < mgpu_info.num_dgpu; i++) {
2052 		gpu_ins = &(mgpu_info.gpu_ins[i]);
2053 		adev = gpu_ins->adev;
2054 		if (!(adev->flags & AMD_IS_APU) &&
2055 		    !gpu_ins->mgpu_fan_enabled &&
2056 		    adev->powerplay.pp_funcs &&
2057 		    adev->powerplay.pp_funcs->enable_mgpu_fan_boost) {
2058 			ret = amdgpu_dpm_enable_mgpu_fan_boost(adev);
2059 			if (ret)
2060 				break;
2061 
2062 			gpu_ins->mgpu_fan_enabled = 1;
2063 		}
2064 	}
2065 
2066 out:
2067 	mutex_unlock(&mgpu_info.mutex);
2068 
2069 	return ret;
2070 }
2071 
2072 /**
2073  * amdgpu_device_ip_late_init - run late init for hardware IPs
2074  *
2075  * @adev: amdgpu_device pointer
2076  *
2077  * Late initialization pass for hardware IPs.  The list of all the hardware
2078  * IPs that make up the asic is walked and the late_init callbacks are run.
2079  * late_init covers any special initialization that an IP requires
2080  * after all of the have been initialized or something that needs to happen
2081  * late in the init process.
2082  * Returns 0 on success, negative error code on failure.
2083  */
2084 static int amdgpu_device_ip_late_init(struct amdgpu_device *adev)
2085 {
2086 	struct amdgpu_gpu_instance *gpu_instance;
2087 	int i = 0, r;
2088 
2089 	for (i = 0; i < adev->num_ip_blocks; i++) {
2090 		if (!adev->ip_blocks[i].status.hw)
2091 			continue;
2092 		if (adev->ip_blocks[i].version->funcs->late_init) {
2093 			r = adev->ip_blocks[i].version->funcs->late_init((void *)adev);
2094 			if (r) {
2095 				DRM_ERROR("late_init of IP block <%s> failed %d\n",
2096 					  adev->ip_blocks[i].version->funcs->name, r);
2097 				return r;
2098 			}
2099 		}
2100 		adev->ip_blocks[i].status.late_initialized = true;
2101 	}
2102 
2103 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE);
2104 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE);
2105 
2106 	amdgpu_device_fill_reset_magic(adev);
2107 
2108 	r = amdgpu_device_enable_mgpu_fan_boost();
2109 	if (r)
2110 		DRM_ERROR("enable mgpu fan boost failed (%d).\n", r);
2111 
2112 
2113 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
2114 		mutex_lock(&mgpu_info.mutex);
2115 
2116 		/*
2117 		 * Reset device p-state to low as this was booted with high.
2118 		 *
2119 		 * This should be performed only after all devices from the same
2120 		 * hive get initialized.
2121 		 *
2122 		 * However, it's unknown how many device in the hive in advance.
2123 		 * As this is counted one by one during devices initializations.
2124 		 *
2125 		 * So, we wait for all XGMI interlinked devices initialized.
2126 		 * This may bring some delays as those devices may come from
2127 		 * different hives. But that should be OK.
2128 		 */
2129 		if (mgpu_info.num_dgpu == adev->gmc.xgmi.num_physical_nodes) {
2130 			for (i = 0; i < mgpu_info.num_gpu; i++) {
2131 				gpu_instance = &(mgpu_info.gpu_ins[i]);
2132 				if (gpu_instance->adev->flags & AMD_IS_APU)
2133 					continue;
2134 
2135 				r = amdgpu_xgmi_set_pstate(gpu_instance->adev, 0);
2136 				if (r) {
2137 					DRM_ERROR("pstate setting failed (%d).\n", r);
2138 					break;
2139 				}
2140 			}
2141 		}
2142 
2143 		mutex_unlock(&mgpu_info.mutex);
2144 	}
2145 
2146 	return 0;
2147 }
2148 
2149 /**
2150  * amdgpu_device_ip_fini - run fini for hardware IPs
2151  *
2152  * @adev: amdgpu_device pointer
2153  *
2154  * Main teardown pass for hardware IPs.  The list of all the hardware
2155  * IPs that make up the asic is walked and the hw_fini and sw_fini callbacks
2156  * are run.  hw_fini tears down the hardware associated with each IP
2157  * and sw_fini tears down any software state associated with each IP.
2158  * Returns 0 on success, negative error code on failure.
2159  */
2160 static int amdgpu_device_ip_fini(struct amdgpu_device *adev)
2161 {
2162 	int i, r;
2163 
2164 	amdgpu_ras_pre_fini(adev);
2165 
2166 	if (adev->gmc.xgmi.num_physical_nodes > 1)
2167 		amdgpu_xgmi_remove_device(adev);
2168 
2169 	amdgpu_amdkfd_device_fini(adev);
2170 
2171 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2172 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2173 
2174 	/* need to disable SMC first */
2175 	for (i = 0; i < adev->num_ip_blocks; i++) {
2176 		if (!adev->ip_blocks[i].status.hw)
2177 			continue;
2178 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2179 			r = adev->ip_blocks[i].version->funcs->hw_fini((void *)adev);
2180 			/* XXX handle errors */
2181 			if (r) {
2182 				DRM_DEBUG("hw_fini of IP block <%s> failed %d\n",
2183 					  adev->ip_blocks[i].version->funcs->name, r);
2184 			}
2185 			adev->ip_blocks[i].status.hw = false;
2186 			break;
2187 		}
2188 	}
2189 
2190 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2191 		if (!adev->ip_blocks[i].status.hw)
2192 			continue;
2193 
2194 		r = adev->ip_blocks[i].version->funcs->hw_fini((void *)adev);
2195 		/* XXX handle errors */
2196 		if (r) {
2197 			DRM_DEBUG("hw_fini of IP block <%s> failed %d\n",
2198 				  adev->ip_blocks[i].version->funcs->name, r);
2199 		}
2200 
2201 		adev->ip_blocks[i].status.hw = false;
2202 	}
2203 
2204 
2205 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2206 		if (!adev->ip_blocks[i].status.sw)
2207 			continue;
2208 
2209 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
2210 			amdgpu_ucode_free_bo(adev);
2211 			amdgpu_free_static_csa(&adev->virt.csa_obj);
2212 			amdgpu_device_wb_fini(adev);
2213 			amdgpu_device_vram_scratch_fini(adev);
2214 			amdgpu_ib_pool_fini(adev);
2215 		}
2216 
2217 		r = adev->ip_blocks[i].version->funcs->sw_fini((void *)adev);
2218 		/* XXX handle errors */
2219 		if (r) {
2220 			DRM_DEBUG("sw_fini of IP block <%s> failed %d\n",
2221 				  adev->ip_blocks[i].version->funcs->name, r);
2222 		}
2223 		adev->ip_blocks[i].status.sw = false;
2224 		adev->ip_blocks[i].status.valid = false;
2225 	}
2226 
2227 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2228 		if (!adev->ip_blocks[i].status.late_initialized)
2229 			continue;
2230 		if (adev->ip_blocks[i].version->funcs->late_fini)
2231 			adev->ip_blocks[i].version->funcs->late_fini((void *)adev);
2232 		adev->ip_blocks[i].status.late_initialized = false;
2233 	}
2234 
2235 	amdgpu_ras_fini(adev);
2236 
2237 	if (amdgpu_sriov_vf(adev))
2238 		if (amdgpu_virt_release_full_gpu(adev, false))
2239 			DRM_ERROR("failed to release exclusive mode on fini\n");
2240 
2241 	return 0;
2242 }
2243 
2244 /**
2245  * amdgpu_device_delayed_init_work_handler - work handler for IB tests
2246  *
2247  * @work: work_struct.
2248  */
2249 static void amdgpu_device_delayed_init_work_handler(struct work_struct *work)
2250 {
2251 	struct amdgpu_device *adev =
2252 		container_of(work, struct amdgpu_device, delayed_init_work.work);
2253 	int r;
2254 
2255 	r = amdgpu_ib_ring_tests(adev);
2256 	if (r)
2257 		DRM_ERROR("ib ring test failed (%d).\n", r);
2258 }
2259 
2260 static void amdgpu_device_delay_enable_gfx_off(struct work_struct *work)
2261 {
2262 	struct amdgpu_device *adev =
2263 		container_of(work, struct amdgpu_device, gfx.gfx_off_delay_work.work);
2264 
2265 	mutex_lock(&adev->gfx.gfx_off_mutex);
2266 	if (!adev->gfx.gfx_off_state && !adev->gfx.gfx_off_req_count) {
2267 		if (!amdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_GFX, true))
2268 			adev->gfx.gfx_off_state = true;
2269 	}
2270 	mutex_unlock(&adev->gfx.gfx_off_mutex);
2271 }
2272 
2273 /**
2274  * amdgpu_device_ip_suspend_phase1 - run suspend for hardware IPs (phase 1)
2275  *
2276  * @adev: amdgpu_device pointer
2277  *
2278  * Main suspend function for hardware IPs.  The list of all the hardware
2279  * IPs that make up the asic is walked, clockgating is disabled and the
2280  * suspend callbacks are run.  suspend puts the hardware and software state
2281  * in each IP into a state suitable for suspend.
2282  * Returns 0 on success, negative error code on failure.
2283  */
2284 static int amdgpu_device_ip_suspend_phase1(struct amdgpu_device *adev)
2285 {
2286 	int i, r;
2287 
2288 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2289 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2290 
2291 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2292 		if (!adev->ip_blocks[i].status.valid)
2293 			continue;
2294 		/* displays are handled separately */
2295 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) {
2296 			/* XXX handle errors */
2297 			r = adev->ip_blocks[i].version->funcs->suspend(adev);
2298 			/* XXX handle errors */
2299 			if (r) {
2300 				DRM_ERROR("suspend of IP block <%s> failed %d\n",
2301 					  adev->ip_blocks[i].version->funcs->name, r);
2302 				return r;
2303 			}
2304 			adev->ip_blocks[i].status.hw = false;
2305 		}
2306 	}
2307 
2308 	return 0;
2309 }
2310 
2311 /**
2312  * amdgpu_device_ip_suspend_phase2 - run suspend for hardware IPs (phase 2)
2313  *
2314  * @adev: amdgpu_device pointer
2315  *
2316  * Main suspend function for hardware IPs.  The list of all the hardware
2317  * IPs that make up the asic is walked, clockgating is disabled and the
2318  * suspend callbacks are run.  suspend puts the hardware and software state
2319  * in each IP into a state suitable for suspend.
2320  * Returns 0 on success, negative error code on failure.
2321  */
2322 static int amdgpu_device_ip_suspend_phase2(struct amdgpu_device *adev)
2323 {
2324 	int i, r;
2325 
2326 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2327 		if (!adev->ip_blocks[i].status.valid)
2328 			continue;
2329 		/* displays are handled in phase1 */
2330 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE)
2331 			continue;
2332 		/* PSP lost connection when err_event_athub occurs */
2333 		if (amdgpu_ras_intr_triggered() &&
2334 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
2335 			adev->ip_blocks[i].status.hw = false;
2336 			continue;
2337 		}
2338 		/* XXX handle errors */
2339 		r = adev->ip_blocks[i].version->funcs->suspend(adev);
2340 		/* XXX handle errors */
2341 		if (r) {
2342 			DRM_ERROR("suspend of IP block <%s> failed %d\n",
2343 				  adev->ip_blocks[i].version->funcs->name, r);
2344 		}
2345 		adev->ip_blocks[i].status.hw = false;
2346 		/* handle putting the SMC in the appropriate state */
2347 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2348 			if (is_support_sw_smu(adev)) {
2349 				r = smu_set_mp1_state(&adev->smu, adev->mp1_state);
2350 			} else if (adev->powerplay.pp_funcs &&
2351 					   adev->powerplay.pp_funcs->set_mp1_state) {
2352 				r = adev->powerplay.pp_funcs->set_mp1_state(
2353 					adev->powerplay.pp_handle,
2354 					adev->mp1_state);
2355 			}
2356 			if (r) {
2357 				DRM_ERROR("SMC failed to set mp1 state %d, %d\n",
2358 					  adev->mp1_state, r);
2359 				return r;
2360 			}
2361 		}
2362 
2363 		adev->ip_blocks[i].status.hw = false;
2364 	}
2365 
2366 	return 0;
2367 }
2368 
2369 /**
2370  * amdgpu_device_ip_suspend - run suspend for hardware IPs
2371  *
2372  * @adev: amdgpu_device pointer
2373  *
2374  * Main suspend function for hardware IPs.  The list of all the hardware
2375  * IPs that make up the asic is walked, clockgating is disabled and the
2376  * suspend callbacks are run.  suspend puts the hardware and software state
2377  * in each IP into a state suitable for suspend.
2378  * Returns 0 on success, negative error code on failure.
2379  */
2380 int amdgpu_device_ip_suspend(struct amdgpu_device *adev)
2381 {
2382 	int r;
2383 
2384 	if (amdgpu_sriov_vf(adev))
2385 		amdgpu_virt_request_full_gpu(adev, false);
2386 
2387 	r = amdgpu_device_ip_suspend_phase1(adev);
2388 	if (r)
2389 		return r;
2390 	r = amdgpu_device_ip_suspend_phase2(adev);
2391 
2392 	if (amdgpu_sriov_vf(adev))
2393 		amdgpu_virt_release_full_gpu(adev, false);
2394 
2395 	return r;
2396 }
2397 
2398 static int amdgpu_device_ip_reinit_early_sriov(struct amdgpu_device *adev)
2399 {
2400 	int i, r;
2401 
2402 	static enum amd_ip_block_type ip_order[] = {
2403 		AMD_IP_BLOCK_TYPE_GMC,
2404 		AMD_IP_BLOCK_TYPE_COMMON,
2405 		AMD_IP_BLOCK_TYPE_PSP,
2406 		AMD_IP_BLOCK_TYPE_IH,
2407 	};
2408 
2409 	for (i = 0; i < ARRAY_SIZE(ip_order); i++) {
2410 		int j;
2411 		struct amdgpu_ip_block *block;
2412 
2413 		for (j = 0; j < adev->num_ip_blocks; j++) {
2414 			block = &adev->ip_blocks[j];
2415 
2416 			block->status.hw = false;
2417 			if (block->version->type != ip_order[i] ||
2418 				!block->status.valid)
2419 				continue;
2420 
2421 			r = block->version->funcs->hw_init(adev);
2422 			DRM_INFO("RE-INIT-early: %s %s\n", block->version->funcs->name, r?"failed":"succeeded");
2423 			if (r)
2424 				return r;
2425 			block->status.hw = true;
2426 		}
2427 	}
2428 
2429 	return 0;
2430 }
2431 
2432 static int amdgpu_device_ip_reinit_late_sriov(struct amdgpu_device *adev)
2433 {
2434 	int i, r;
2435 
2436 	static enum amd_ip_block_type ip_order[] = {
2437 		AMD_IP_BLOCK_TYPE_SMC,
2438 		AMD_IP_BLOCK_TYPE_DCE,
2439 		AMD_IP_BLOCK_TYPE_GFX,
2440 		AMD_IP_BLOCK_TYPE_SDMA,
2441 		AMD_IP_BLOCK_TYPE_UVD,
2442 		AMD_IP_BLOCK_TYPE_VCE
2443 	};
2444 
2445 	for (i = 0; i < ARRAY_SIZE(ip_order); i++) {
2446 		int j;
2447 		struct amdgpu_ip_block *block;
2448 
2449 		for (j = 0; j < adev->num_ip_blocks; j++) {
2450 			block = &adev->ip_blocks[j];
2451 
2452 			if (block->version->type != ip_order[i] ||
2453 				!block->status.valid ||
2454 				block->status.hw)
2455 				continue;
2456 
2457 			r = block->version->funcs->hw_init(adev);
2458 			DRM_INFO("RE-INIT-late: %s %s\n", block->version->funcs->name, r?"failed":"succeeded");
2459 			if (r)
2460 				return r;
2461 			block->status.hw = true;
2462 		}
2463 	}
2464 
2465 	return 0;
2466 }
2467 
2468 /**
2469  * amdgpu_device_ip_resume_phase1 - run resume for hardware IPs
2470  *
2471  * @adev: amdgpu_device pointer
2472  *
2473  * First resume function for hardware IPs.  The list of all the hardware
2474  * IPs that make up the asic is walked and the resume callbacks are run for
2475  * COMMON, GMC, and IH.  resume puts the hardware into a functional state
2476  * after a suspend and updates the software state as necessary.  This
2477  * function is also used for restoring the GPU after a GPU reset.
2478  * Returns 0 on success, negative error code on failure.
2479  */
2480 static int amdgpu_device_ip_resume_phase1(struct amdgpu_device *adev)
2481 {
2482 	int i, r;
2483 
2484 	for (i = 0; i < adev->num_ip_blocks; i++) {
2485 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
2486 			continue;
2487 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2488 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
2489 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
2490 
2491 			r = adev->ip_blocks[i].version->funcs->resume(adev);
2492 			if (r) {
2493 				DRM_ERROR("resume of IP block <%s> failed %d\n",
2494 					  adev->ip_blocks[i].version->funcs->name, r);
2495 				return r;
2496 			}
2497 			adev->ip_blocks[i].status.hw = true;
2498 		}
2499 	}
2500 
2501 	return 0;
2502 }
2503 
2504 /**
2505  * amdgpu_device_ip_resume_phase2 - run resume for hardware IPs
2506  *
2507  * @adev: amdgpu_device pointer
2508  *
2509  * First resume function for hardware IPs.  The list of all the hardware
2510  * IPs that make up the asic is walked and the resume callbacks are run for
2511  * all blocks except COMMON, GMC, and IH.  resume puts the hardware into a
2512  * functional state after a suspend and updates the software state as
2513  * necessary.  This function is also used for restoring the GPU after a GPU
2514  * reset.
2515  * Returns 0 on success, negative error code on failure.
2516  */
2517 static int amdgpu_device_ip_resume_phase2(struct amdgpu_device *adev)
2518 {
2519 	int i, r;
2520 
2521 	for (i = 0; i < adev->num_ip_blocks; i++) {
2522 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
2523 			continue;
2524 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2525 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
2526 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH ||
2527 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)
2528 			continue;
2529 		r = adev->ip_blocks[i].version->funcs->resume(adev);
2530 		if (r) {
2531 			DRM_ERROR("resume of IP block <%s> failed %d\n",
2532 				  adev->ip_blocks[i].version->funcs->name, r);
2533 			return r;
2534 		}
2535 		adev->ip_blocks[i].status.hw = true;
2536 	}
2537 
2538 	return 0;
2539 }
2540 
2541 /**
2542  * amdgpu_device_ip_resume - run resume for hardware IPs
2543  *
2544  * @adev: amdgpu_device pointer
2545  *
2546  * Main resume function for hardware IPs.  The hardware IPs
2547  * are split into two resume functions because they are
2548  * are also used in in recovering from a GPU reset and some additional
2549  * steps need to be take between them.  In this case (S3/S4) they are
2550  * run sequentially.
2551  * Returns 0 on success, negative error code on failure.
2552  */
2553 static int amdgpu_device_ip_resume(struct amdgpu_device *adev)
2554 {
2555 	int r;
2556 
2557 	r = amdgpu_device_ip_resume_phase1(adev);
2558 	if (r)
2559 		return r;
2560 
2561 	r = amdgpu_device_fw_loading(adev);
2562 	if (r)
2563 		return r;
2564 
2565 	r = amdgpu_device_ip_resume_phase2(adev);
2566 
2567 	return r;
2568 }
2569 
2570 /**
2571  * amdgpu_device_detect_sriov_bios - determine if the board supports SR-IOV
2572  *
2573  * @adev: amdgpu_device pointer
2574  *
2575  * Query the VBIOS data tables to determine if the board supports SR-IOV.
2576  */
2577 static void amdgpu_device_detect_sriov_bios(struct amdgpu_device *adev)
2578 {
2579 	if (amdgpu_sriov_vf(adev)) {
2580 		if (adev->is_atom_fw) {
2581 			if (amdgpu_atomfirmware_gpu_supports_virtualization(adev))
2582 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
2583 		} else {
2584 			if (amdgpu_atombios_has_gpu_virtualization_table(adev))
2585 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
2586 		}
2587 
2588 		if (!(adev->virt.caps & AMDGPU_SRIOV_CAPS_SRIOV_VBIOS))
2589 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_NO_VBIOS, 0, 0);
2590 	}
2591 }
2592 
2593 /**
2594  * amdgpu_device_asic_has_dc_support - determine if DC supports the asic
2595  *
2596  * @asic_type: AMD asic type
2597  *
2598  * Check if there is DC (new modesetting infrastructre) support for an asic.
2599  * returns true if DC has support, false if not.
2600  */
2601 bool amdgpu_device_asic_has_dc_support(enum amd_asic_type asic_type)
2602 {
2603 	switch (asic_type) {
2604 #if defined(CONFIG_DRM_AMD_DC)
2605 	case CHIP_BONAIRE:
2606 	case CHIP_KAVERI:
2607 	case CHIP_KABINI:
2608 	case CHIP_MULLINS:
2609 		/*
2610 		 * We have systems in the wild with these ASICs that require
2611 		 * LVDS and VGA support which is not supported with DC.
2612 		 *
2613 		 * Fallback to the non-DC driver here by default so as not to
2614 		 * cause regressions.
2615 		 */
2616 		return amdgpu_dc > 0;
2617 	case CHIP_HAWAII:
2618 	case CHIP_CARRIZO:
2619 	case CHIP_STONEY:
2620 	case CHIP_POLARIS10:
2621 	case CHIP_POLARIS11:
2622 	case CHIP_POLARIS12:
2623 	case CHIP_VEGAM:
2624 	case CHIP_TONGA:
2625 	case CHIP_FIJI:
2626 	case CHIP_VEGA10:
2627 	case CHIP_VEGA12:
2628 	case CHIP_VEGA20:
2629 #if defined(CONFIG_DRM_AMD_DC_DCN)
2630 	case CHIP_RAVEN:
2631 	case CHIP_NAVI10:
2632 	case CHIP_NAVI14:
2633 	case CHIP_NAVI12:
2634 	case CHIP_RENOIR:
2635 #endif
2636 		return amdgpu_dc != 0;
2637 #endif
2638 	default:
2639 		return false;
2640 	}
2641 }
2642 
2643 /**
2644  * amdgpu_device_has_dc_support - check if dc is supported
2645  *
2646  * @adev: amdgpu_device_pointer
2647  *
2648  * Returns true for supported, false for not supported
2649  */
2650 bool amdgpu_device_has_dc_support(struct amdgpu_device *adev)
2651 {
2652 	if (amdgpu_sriov_vf(adev))
2653 		return false;
2654 
2655 	return amdgpu_device_asic_has_dc_support(adev->asic_type);
2656 }
2657 
2658 
2659 static void amdgpu_device_xgmi_reset_func(struct work_struct *__work)
2660 {
2661 	struct amdgpu_device *adev =
2662 		container_of(__work, struct amdgpu_device, xgmi_reset_work);
2663 
2664 	if (amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO)
2665 		adev->asic_reset_res = (adev->in_baco == false) ?
2666 				amdgpu_device_baco_enter(adev->ddev) :
2667 				amdgpu_device_baco_exit(adev->ddev);
2668 	else
2669 		adev->asic_reset_res = amdgpu_asic_reset(adev);
2670 
2671 	if (adev->asic_reset_res)
2672 		DRM_WARN("ASIC reset failed with error, %d for drm dev, %s",
2673 			 adev->asic_reset_res, adev->ddev->unique);
2674 }
2675 
2676 static int amdgpu_device_get_job_timeout_settings(struct amdgpu_device *adev)
2677 {
2678 	char *input = amdgpu_lockup_timeout;
2679 	char *timeout_setting = NULL;
2680 	int index = 0;
2681 	long timeout;
2682 	int ret = 0;
2683 
2684 	/*
2685 	 * By default timeout for non compute jobs is 10000.
2686 	 * And there is no timeout enforced on compute jobs.
2687 	 * In SR-IOV or passthrough mode, timeout for compute
2688 	 * jobs are 10000 by default.
2689 	 */
2690 	adev->gfx_timeout = msecs_to_jiffies(10000);
2691 	adev->sdma_timeout = adev->video_timeout = adev->gfx_timeout;
2692 	if (amdgpu_sriov_vf(adev) || amdgpu_passthrough(adev))
2693 		adev->compute_timeout = adev->gfx_timeout;
2694 	else
2695 		adev->compute_timeout = MAX_SCHEDULE_TIMEOUT;
2696 
2697 	if (strnlen(input, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
2698 		while ((timeout_setting = strsep(&input, ",")) &&
2699 				strnlen(timeout_setting, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
2700 			ret = kstrtol(timeout_setting, 0, &timeout);
2701 			if (ret)
2702 				return ret;
2703 
2704 			if (timeout == 0) {
2705 				index++;
2706 				continue;
2707 			} else if (timeout < 0) {
2708 				timeout = MAX_SCHEDULE_TIMEOUT;
2709 			} else {
2710 				timeout = msecs_to_jiffies(timeout);
2711 			}
2712 
2713 			switch (index++) {
2714 			case 0:
2715 				adev->gfx_timeout = timeout;
2716 				break;
2717 			case 1:
2718 				adev->compute_timeout = timeout;
2719 				break;
2720 			case 2:
2721 				adev->sdma_timeout = timeout;
2722 				break;
2723 			case 3:
2724 				adev->video_timeout = timeout;
2725 				break;
2726 			default:
2727 				break;
2728 			}
2729 		}
2730 		/*
2731 		 * There is only one value specified and
2732 		 * it should apply to all non-compute jobs.
2733 		 */
2734 		if (index == 1) {
2735 			adev->sdma_timeout = adev->video_timeout = adev->gfx_timeout;
2736 			if (amdgpu_sriov_vf(adev) || amdgpu_passthrough(adev))
2737 				adev->compute_timeout = adev->gfx_timeout;
2738 		}
2739 	}
2740 
2741 	return ret;
2742 }
2743 
2744 /**
2745  * amdgpu_device_init - initialize the driver
2746  *
2747  * @adev: amdgpu_device pointer
2748  * @ddev: drm dev pointer
2749  * @pdev: pci dev pointer
2750  * @flags: driver flags
2751  *
2752  * Initializes the driver info and hw (all asics).
2753  * Returns 0 for success or an error on failure.
2754  * Called at driver startup.
2755  */
2756 int amdgpu_device_init(struct amdgpu_device *adev,
2757 		       struct drm_device *ddev,
2758 		       struct pci_dev *pdev,
2759 		       uint32_t flags)
2760 {
2761 	int r, i;
2762 	bool boco = false;
2763 	u32 max_MBps;
2764 
2765 	adev->shutdown = false;
2766 	adev->dev = &pdev->dev;
2767 	adev->ddev = ddev;
2768 	adev->pdev = pdev;
2769 	adev->flags = flags;
2770 
2771 	if (amdgpu_force_asic_type >= 0 && amdgpu_force_asic_type < CHIP_LAST)
2772 		adev->asic_type = amdgpu_force_asic_type;
2773 	else
2774 		adev->asic_type = flags & AMD_ASIC_MASK;
2775 
2776 	adev->usec_timeout = AMDGPU_MAX_USEC_TIMEOUT;
2777 	if (amdgpu_emu_mode == 1)
2778 		adev->usec_timeout *= 2;
2779 	adev->gmc.gart_size = 512 * 1024 * 1024;
2780 	adev->accel_working = false;
2781 	adev->num_rings = 0;
2782 	adev->mman.buffer_funcs = NULL;
2783 	adev->mman.buffer_funcs_ring = NULL;
2784 	adev->vm_manager.vm_pte_funcs = NULL;
2785 	adev->vm_manager.vm_pte_num_rqs = 0;
2786 	adev->gmc.gmc_funcs = NULL;
2787 	adev->fence_context = dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2788 	bitmap_zero(adev->gfx.pipe_reserve_bitmap, AMDGPU_MAX_COMPUTE_QUEUES);
2789 
2790 	adev->smc_rreg = &amdgpu_invalid_rreg;
2791 	adev->smc_wreg = &amdgpu_invalid_wreg;
2792 	adev->pcie_rreg = &amdgpu_invalid_rreg;
2793 	adev->pcie_wreg = &amdgpu_invalid_wreg;
2794 	adev->pciep_rreg = &amdgpu_invalid_rreg;
2795 	adev->pciep_wreg = &amdgpu_invalid_wreg;
2796 	adev->pcie_rreg64 = &amdgpu_invalid_rreg64;
2797 	adev->pcie_wreg64 = &amdgpu_invalid_wreg64;
2798 	adev->uvd_ctx_rreg = &amdgpu_invalid_rreg;
2799 	adev->uvd_ctx_wreg = &amdgpu_invalid_wreg;
2800 	adev->didt_rreg = &amdgpu_invalid_rreg;
2801 	adev->didt_wreg = &amdgpu_invalid_wreg;
2802 	adev->gc_cac_rreg = &amdgpu_invalid_rreg;
2803 	adev->gc_cac_wreg = &amdgpu_invalid_wreg;
2804 	adev->audio_endpt_rreg = &amdgpu_block_invalid_rreg;
2805 	adev->audio_endpt_wreg = &amdgpu_block_invalid_wreg;
2806 
2807 	DRM_INFO("initializing kernel modesetting (%s 0x%04X:0x%04X 0x%04X:0x%04X 0x%02X).\n",
2808 		 amdgpu_asic_name[adev->asic_type], pdev->vendor, pdev->device,
2809 		 pdev->subsystem_vendor, pdev->subsystem_device, pdev->revision);
2810 
2811 	/* mutex initialization are all done here so we
2812 	 * can recall function without having locking issues */
2813 	atomic_set(&adev->irq.ih.lock, 0);
2814 	mutex_init(&adev->firmware.mutex);
2815 	mutex_init(&adev->pm.mutex);
2816 	mutex_init(&adev->gfx.gpu_clock_mutex);
2817 	mutex_init(&adev->srbm_mutex);
2818 	mutex_init(&adev->gfx.pipe_reserve_mutex);
2819 	mutex_init(&adev->gfx.gfx_off_mutex);
2820 	mutex_init(&adev->grbm_idx_mutex);
2821 	mutex_init(&adev->mn_lock);
2822 	mutex_init(&adev->virt.vf_errors.lock);
2823 	hash_init(adev->mn_hash);
2824 	mutex_init(&adev->lock_reset);
2825 	mutex_init(&adev->virt.dpm_mutex);
2826 	mutex_init(&adev->psp.mutex);
2827 
2828 	r = amdgpu_device_check_arguments(adev);
2829 	if (r)
2830 		return r;
2831 
2832 	spin_lock_init(&adev->mmio_idx_lock);
2833 	spin_lock_init(&adev->smc_idx_lock);
2834 	spin_lock_init(&adev->pcie_idx_lock);
2835 	spin_lock_init(&adev->uvd_ctx_idx_lock);
2836 	spin_lock_init(&adev->didt_idx_lock);
2837 	spin_lock_init(&adev->gc_cac_idx_lock);
2838 	spin_lock_init(&adev->se_cac_idx_lock);
2839 	spin_lock_init(&adev->audio_endpt_idx_lock);
2840 	spin_lock_init(&adev->mm_stats.lock);
2841 
2842 	INIT_LIST_HEAD(&adev->shadow_list);
2843 	mutex_init(&adev->shadow_list_lock);
2844 
2845 	INIT_LIST_HEAD(&adev->ring_lru_list);
2846 	spin_lock_init(&adev->ring_lru_list_lock);
2847 
2848 	INIT_DELAYED_WORK(&adev->delayed_init_work,
2849 			  amdgpu_device_delayed_init_work_handler);
2850 	INIT_DELAYED_WORK(&adev->gfx.gfx_off_delay_work,
2851 			  amdgpu_device_delay_enable_gfx_off);
2852 
2853 	INIT_WORK(&adev->xgmi_reset_work, amdgpu_device_xgmi_reset_func);
2854 
2855 	adev->gfx.gfx_off_req_count = 1;
2856 	adev->pm.ac_power = power_supply_is_system_supplied() > 0 ? true : false;
2857 
2858 	/* Registers mapping */
2859 	/* TODO: block userspace mapping of io register */
2860 	if (adev->asic_type >= CHIP_BONAIRE) {
2861 		adev->rmmio_base = pci_resource_start(adev->pdev, 5);
2862 		adev->rmmio_size = pci_resource_len(adev->pdev, 5);
2863 	} else {
2864 		adev->rmmio_base = pci_resource_start(adev->pdev, 2);
2865 		adev->rmmio_size = pci_resource_len(adev->pdev, 2);
2866 	}
2867 
2868 	adev->rmmio = ioremap(adev->rmmio_base, adev->rmmio_size);
2869 	if (adev->rmmio == NULL) {
2870 		return -ENOMEM;
2871 	}
2872 	DRM_INFO("register mmio base: 0x%08X\n", (uint32_t)adev->rmmio_base);
2873 	DRM_INFO("register mmio size: %u\n", (unsigned)adev->rmmio_size);
2874 
2875 	/* io port mapping */
2876 	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
2877 		if (pci_resource_flags(adev->pdev, i) & IORESOURCE_IO) {
2878 			adev->rio_mem_size = pci_resource_len(adev->pdev, i);
2879 			adev->rio_mem = pci_iomap(adev->pdev, i, adev->rio_mem_size);
2880 			break;
2881 		}
2882 	}
2883 	if (adev->rio_mem == NULL)
2884 		DRM_INFO("PCI I/O BAR is not found.\n");
2885 
2886 	/* enable PCIE atomic ops */
2887 	r = pci_enable_atomic_ops_to_root(adev->pdev,
2888 					  PCI_EXP_DEVCAP2_ATOMIC_COMP32 |
2889 					  PCI_EXP_DEVCAP2_ATOMIC_COMP64);
2890 	if (r) {
2891 		adev->have_atomics_support = false;
2892 		DRM_INFO("PCIE atomic ops is not supported\n");
2893 	} else {
2894 		adev->have_atomics_support = true;
2895 	}
2896 
2897 	amdgpu_device_get_pcie_info(adev);
2898 
2899 	if (amdgpu_mcbp)
2900 		DRM_INFO("MCBP is enabled\n");
2901 
2902 	if (amdgpu_mes && adev->asic_type >= CHIP_NAVI10)
2903 		adev->enable_mes = true;
2904 
2905 	if (amdgpu_discovery && adev->asic_type >= CHIP_NAVI10) {
2906 		r = amdgpu_discovery_init(adev);
2907 		if (r) {
2908 			dev_err(adev->dev, "amdgpu_discovery_init failed\n");
2909 			return r;
2910 		}
2911 	}
2912 
2913 	/* early init functions */
2914 	r = amdgpu_device_ip_early_init(adev);
2915 	if (r)
2916 		return r;
2917 
2918 	r = amdgpu_device_get_job_timeout_settings(adev);
2919 	if (r) {
2920 		dev_err(adev->dev, "invalid lockup_timeout parameter syntax\n");
2921 		return r;
2922 	}
2923 
2924 	/* doorbell bar mapping and doorbell index init*/
2925 	amdgpu_device_doorbell_init(adev);
2926 
2927 	/* if we have > 1 VGA cards, then disable the amdgpu VGA resources */
2928 	/* this will fail for cards that aren't VGA class devices, just
2929 	 * ignore it */
2930 	vga_client_register(adev->pdev, adev, NULL, amdgpu_device_vga_set_decode);
2931 
2932 	if (amdgpu_device_supports_boco(ddev))
2933 		boco = true;
2934 	if (amdgpu_has_atpx() &&
2935 	    (amdgpu_is_atpx_hybrid() ||
2936 	     amdgpu_has_atpx_dgpu_power_cntl()) &&
2937 	    !pci_is_thunderbolt_attached(adev->pdev))
2938 		vga_switcheroo_register_client(adev->pdev,
2939 					       &amdgpu_switcheroo_ops, boco);
2940 	if (boco)
2941 		vga_switcheroo_init_domain_pm_ops(adev->dev, &adev->vga_pm_domain);
2942 
2943 	if (amdgpu_emu_mode == 1) {
2944 		/* post the asic on emulation mode */
2945 		emu_soc_asic_init(adev);
2946 		goto fence_driver_init;
2947 	}
2948 
2949 	/* detect if we are with an SRIOV vbios */
2950 	amdgpu_device_detect_sriov_bios(adev);
2951 
2952 	/* check if we need to reset the asic
2953 	 *  E.g., driver was not cleanly unloaded previously, etc.
2954 	 */
2955 	if (!amdgpu_sriov_vf(adev) && amdgpu_asic_need_reset_on_init(adev)) {
2956 		r = amdgpu_asic_reset(adev);
2957 		if (r) {
2958 			dev_err(adev->dev, "asic reset on init failed\n");
2959 			goto failed;
2960 		}
2961 	}
2962 
2963 	/* Post card if necessary */
2964 	if (amdgpu_device_need_post(adev)) {
2965 		if (!adev->bios) {
2966 			dev_err(adev->dev, "no vBIOS found\n");
2967 			r = -EINVAL;
2968 			goto failed;
2969 		}
2970 		DRM_INFO("GPU posting now...\n");
2971 		r = amdgpu_atom_asic_init(adev->mode_info.atom_context);
2972 		if (r) {
2973 			dev_err(adev->dev, "gpu post error!\n");
2974 			goto failed;
2975 		}
2976 	}
2977 
2978 	if (adev->is_atom_fw) {
2979 		/* Initialize clocks */
2980 		r = amdgpu_atomfirmware_get_clock_info(adev);
2981 		if (r) {
2982 			dev_err(adev->dev, "amdgpu_atomfirmware_get_clock_info failed\n");
2983 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
2984 			goto failed;
2985 		}
2986 	} else {
2987 		/* Initialize clocks */
2988 		r = amdgpu_atombios_get_clock_info(adev);
2989 		if (r) {
2990 			dev_err(adev->dev, "amdgpu_atombios_get_clock_info failed\n");
2991 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
2992 			goto failed;
2993 		}
2994 		/* init i2c buses */
2995 		if (!amdgpu_device_has_dc_support(adev))
2996 			amdgpu_atombios_i2c_init(adev);
2997 	}
2998 
2999 fence_driver_init:
3000 	/* Fence driver */
3001 	r = amdgpu_fence_driver_init(adev);
3002 	if (r) {
3003 		dev_err(adev->dev, "amdgpu_fence_driver_init failed\n");
3004 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_FENCE_INIT_FAIL, 0, 0);
3005 		goto failed;
3006 	}
3007 
3008 	/* init the mode config */
3009 	drm_mode_config_init(adev->ddev);
3010 
3011 	r = amdgpu_device_ip_init(adev);
3012 	if (r) {
3013 		/* failed in exclusive mode due to timeout */
3014 		if (amdgpu_sriov_vf(adev) &&
3015 		    !amdgpu_sriov_runtime(adev) &&
3016 		    amdgpu_virt_mmio_blocked(adev) &&
3017 		    !amdgpu_virt_wait_reset(adev)) {
3018 			dev_err(adev->dev, "VF exclusive mode timeout\n");
3019 			/* Don't send request since VF is inactive. */
3020 			adev->virt.caps &= ~AMDGPU_SRIOV_CAPS_RUNTIME;
3021 			adev->virt.ops = NULL;
3022 			r = -EAGAIN;
3023 			goto failed;
3024 		}
3025 		dev_err(adev->dev, "amdgpu_device_ip_init failed\n");
3026 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_INIT_FAIL, 0, 0);
3027 		goto failed;
3028 	}
3029 
3030 	adev->accel_working = true;
3031 
3032 	amdgpu_vm_check_compute_bug(adev);
3033 
3034 	/* Initialize the buffer migration limit. */
3035 	if (amdgpu_moverate >= 0)
3036 		max_MBps = amdgpu_moverate;
3037 	else
3038 		max_MBps = 8; /* Allow 8 MB/s. */
3039 	/* Get a log2 for easy divisions. */
3040 	adev->mm_stats.log2_max_MBps = ilog2(max(1u, max_MBps));
3041 
3042 	amdgpu_fbdev_init(adev);
3043 
3044 	if (amdgpu_sriov_vf(adev) && amdgim_is_hwperf(adev))
3045 		amdgpu_pm_virt_sysfs_init(adev);
3046 
3047 	r = amdgpu_pm_sysfs_init(adev);
3048 	if (r) {
3049 		adev->pm_sysfs_en = false;
3050 		DRM_ERROR("registering pm debugfs failed (%d).\n", r);
3051 	} else
3052 		adev->pm_sysfs_en = true;
3053 
3054 	r = amdgpu_ucode_sysfs_init(adev);
3055 	if (r) {
3056 		adev->ucode_sysfs_en = false;
3057 		DRM_ERROR("Creating firmware sysfs failed (%d).\n", r);
3058 	} else
3059 		adev->ucode_sysfs_en = true;
3060 
3061 	r = amdgpu_debugfs_gem_init(adev);
3062 	if (r)
3063 		DRM_ERROR("registering gem debugfs failed (%d).\n", r);
3064 
3065 	r = amdgpu_debugfs_regs_init(adev);
3066 	if (r)
3067 		DRM_ERROR("registering register debugfs failed (%d).\n", r);
3068 
3069 	r = amdgpu_debugfs_firmware_init(adev);
3070 	if (r)
3071 		DRM_ERROR("registering firmware debugfs failed (%d).\n", r);
3072 
3073 	r = amdgpu_debugfs_init(adev);
3074 	if (r)
3075 		DRM_ERROR("Creating debugfs files failed (%d).\n", r);
3076 
3077 	if ((amdgpu_testing & 1)) {
3078 		if (adev->accel_working)
3079 			amdgpu_test_moves(adev);
3080 		else
3081 			DRM_INFO("amdgpu: acceleration disabled, skipping move tests\n");
3082 	}
3083 	if (amdgpu_benchmarking) {
3084 		if (adev->accel_working)
3085 			amdgpu_benchmark(adev, amdgpu_benchmarking);
3086 		else
3087 			DRM_INFO("amdgpu: acceleration disabled, skipping benchmarks\n");
3088 	}
3089 
3090 	/*
3091 	 * Register gpu instance before amdgpu_device_enable_mgpu_fan_boost.
3092 	 * Otherwise the mgpu fan boost feature will be skipped due to the
3093 	 * gpu instance is counted less.
3094 	 */
3095 	amdgpu_register_gpu_instance(adev);
3096 
3097 	/* enable clockgating, etc. after ib tests, etc. since some blocks require
3098 	 * explicit gating rather than handling it automatically.
3099 	 */
3100 	r = amdgpu_device_ip_late_init(adev);
3101 	if (r) {
3102 		dev_err(adev->dev, "amdgpu_device_ip_late_init failed\n");
3103 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_LATE_INIT_FAIL, 0, r);
3104 		goto failed;
3105 	}
3106 
3107 	/* must succeed. */
3108 	amdgpu_ras_resume(adev);
3109 
3110 	queue_delayed_work(system_wq, &adev->delayed_init_work,
3111 			   msecs_to_jiffies(AMDGPU_RESUME_MS));
3112 
3113 	r = device_create_file(adev->dev, &dev_attr_pcie_replay_count);
3114 	if (r) {
3115 		dev_err(adev->dev, "Could not create pcie_replay_count");
3116 		return r;
3117 	}
3118 
3119 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
3120 		r = amdgpu_pmu_init(adev);
3121 	if (r)
3122 		dev_err(adev->dev, "amdgpu_pmu_init failed\n");
3123 
3124 	return 0;
3125 
3126 failed:
3127 	amdgpu_vf_error_trans_all(adev);
3128 	if (boco)
3129 		vga_switcheroo_fini_domain_pm_ops(adev->dev);
3130 
3131 	return r;
3132 }
3133 
3134 /**
3135  * amdgpu_device_fini - tear down the driver
3136  *
3137  * @adev: amdgpu_device pointer
3138  *
3139  * Tear down the driver info (all asics).
3140  * Called at driver shutdown.
3141  */
3142 void amdgpu_device_fini(struct amdgpu_device *adev)
3143 {
3144 	int r;
3145 
3146 	DRM_INFO("amdgpu: finishing device.\n");
3147 	flush_delayed_work(&adev->delayed_init_work);
3148 	adev->shutdown = true;
3149 
3150 	/* disable all interrupts */
3151 	amdgpu_irq_disable_all(adev);
3152 	if (adev->mode_info.mode_config_initialized){
3153 		if (!amdgpu_device_has_dc_support(adev))
3154 			drm_helper_force_disable_all(adev->ddev);
3155 		else
3156 			drm_atomic_helper_shutdown(adev->ddev);
3157 	}
3158 	amdgpu_fence_driver_fini(adev);
3159 	if (adev->pm_sysfs_en)
3160 		amdgpu_pm_sysfs_fini(adev);
3161 	amdgpu_fbdev_fini(adev);
3162 	r = amdgpu_device_ip_fini(adev);
3163 	if (adev->firmware.gpu_info_fw) {
3164 		release_firmware(adev->firmware.gpu_info_fw);
3165 		adev->firmware.gpu_info_fw = NULL;
3166 	}
3167 	adev->accel_working = false;
3168 	/* free i2c buses */
3169 	if (!amdgpu_device_has_dc_support(adev))
3170 		amdgpu_i2c_fini(adev);
3171 
3172 	if (amdgpu_emu_mode != 1)
3173 		amdgpu_atombios_fini(adev);
3174 
3175 	kfree(adev->bios);
3176 	adev->bios = NULL;
3177 	if (amdgpu_has_atpx() &&
3178 	    (amdgpu_is_atpx_hybrid() ||
3179 	     amdgpu_has_atpx_dgpu_power_cntl()) &&
3180 	    !pci_is_thunderbolt_attached(adev->pdev))
3181 		vga_switcheroo_unregister_client(adev->pdev);
3182 	if (amdgpu_device_supports_boco(adev->ddev))
3183 		vga_switcheroo_fini_domain_pm_ops(adev->dev);
3184 	vga_client_register(adev->pdev, NULL, NULL, NULL);
3185 	if (adev->rio_mem)
3186 		pci_iounmap(adev->pdev, adev->rio_mem);
3187 	adev->rio_mem = NULL;
3188 	iounmap(adev->rmmio);
3189 	adev->rmmio = NULL;
3190 	amdgpu_device_doorbell_fini(adev);
3191 	if (amdgpu_sriov_vf(adev) && amdgim_is_hwperf(adev))
3192 		amdgpu_pm_virt_sysfs_fini(adev);
3193 
3194 	amdgpu_debugfs_regs_cleanup(adev);
3195 	device_remove_file(adev->dev, &dev_attr_pcie_replay_count);
3196 	if (adev->ucode_sysfs_en)
3197 		amdgpu_ucode_sysfs_fini(adev);
3198 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
3199 		amdgpu_pmu_fini(adev);
3200 	amdgpu_debugfs_preempt_cleanup(adev);
3201 	if (amdgpu_discovery && adev->asic_type >= CHIP_NAVI10)
3202 		amdgpu_discovery_fini(adev);
3203 }
3204 
3205 
3206 /*
3207  * Suspend & resume.
3208  */
3209 /**
3210  * amdgpu_device_suspend - initiate device suspend
3211  *
3212  * @dev: drm dev pointer
3213  * @suspend: suspend state
3214  * @fbcon : notify the fbdev of suspend
3215  *
3216  * Puts the hw in the suspend state (all asics).
3217  * Returns 0 for success or an error on failure.
3218  * Called at driver suspend.
3219  */
3220 int amdgpu_device_suspend(struct drm_device *dev, bool fbcon)
3221 {
3222 	struct amdgpu_device *adev;
3223 	struct drm_crtc *crtc;
3224 	struct drm_connector *connector;
3225 	struct drm_connector_list_iter iter;
3226 	int r;
3227 
3228 	if (dev == NULL || dev->dev_private == NULL) {
3229 		return -ENODEV;
3230 	}
3231 
3232 	adev = dev->dev_private;
3233 
3234 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
3235 		return 0;
3236 
3237 	adev->in_suspend = true;
3238 	drm_kms_helper_poll_disable(dev);
3239 
3240 	if (fbcon)
3241 		amdgpu_fbdev_set_suspend(adev, 1);
3242 
3243 	cancel_delayed_work_sync(&adev->delayed_init_work);
3244 
3245 	if (!amdgpu_device_has_dc_support(adev)) {
3246 		/* turn off display hw */
3247 		drm_modeset_lock_all(dev);
3248 		drm_connector_list_iter_begin(dev, &iter);
3249 		drm_for_each_connector_iter(connector, &iter)
3250 			drm_helper_connector_dpms(connector,
3251 						  DRM_MODE_DPMS_OFF);
3252 		drm_connector_list_iter_end(&iter);
3253 		drm_modeset_unlock_all(dev);
3254 			/* unpin the front buffers and cursors */
3255 		list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
3256 			struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3257 			struct drm_framebuffer *fb = crtc->primary->fb;
3258 			struct amdgpu_bo *robj;
3259 
3260 			if (amdgpu_crtc->cursor_bo && !adev->enable_virtual_display) {
3261 				struct amdgpu_bo *aobj = gem_to_amdgpu_bo(amdgpu_crtc->cursor_bo);
3262 				r = amdgpu_bo_reserve(aobj, true);
3263 				if (r == 0) {
3264 					amdgpu_bo_unpin(aobj);
3265 					amdgpu_bo_unreserve(aobj);
3266 				}
3267 			}
3268 
3269 			if (fb == NULL || fb->obj[0] == NULL) {
3270 				continue;
3271 			}
3272 			robj = gem_to_amdgpu_bo(fb->obj[0]);
3273 			/* don't unpin kernel fb objects */
3274 			if (!amdgpu_fbdev_robj_is_fb(adev, robj)) {
3275 				r = amdgpu_bo_reserve(robj, true);
3276 				if (r == 0) {
3277 					amdgpu_bo_unpin(robj);
3278 					amdgpu_bo_unreserve(robj);
3279 				}
3280 			}
3281 		}
3282 	}
3283 
3284 	amdgpu_amdkfd_suspend(adev);
3285 
3286 	amdgpu_ras_suspend(adev);
3287 
3288 	r = amdgpu_device_ip_suspend_phase1(adev);
3289 
3290 	/* evict vram memory */
3291 	amdgpu_bo_evict_vram(adev);
3292 
3293 	amdgpu_fence_driver_suspend(adev);
3294 
3295 	r = amdgpu_device_ip_suspend_phase2(adev);
3296 
3297 	/* evict remaining vram memory
3298 	 * This second call to evict vram is to evict the gart page table
3299 	 * using the CPU.
3300 	 */
3301 	amdgpu_bo_evict_vram(adev);
3302 
3303 	return 0;
3304 }
3305 
3306 /**
3307  * amdgpu_device_resume - initiate device resume
3308  *
3309  * @dev: drm dev pointer
3310  * @resume: resume state
3311  * @fbcon : notify the fbdev of resume
3312  *
3313  * Bring the hw back to operating state (all asics).
3314  * Returns 0 for success or an error on failure.
3315  * Called at driver resume.
3316  */
3317 int amdgpu_device_resume(struct drm_device *dev, bool fbcon)
3318 {
3319 	struct drm_connector *connector;
3320 	struct drm_connector_list_iter iter;
3321 	struct amdgpu_device *adev = dev->dev_private;
3322 	struct drm_crtc *crtc;
3323 	int r = 0;
3324 
3325 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
3326 		return 0;
3327 
3328 	/* post card */
3329 	if (amdgpu_device_need_post(adev)) {
3330 		r = amdgpu_atom_asic_init(adev->mode_info.atom_context);
3331 		if (r)
3332 			DRM_ERROR("amdgpu asic init failed\n");
3333 	}
3334 
3335 	r = amdgpu_device_ip_resume(adev);
3336 	if (r) {
3337 		DRM_ERROR("amdgpu_device_ip_resume failed (%d).\n", r);
3338 		return r;
3339 	}
3340 	amdgpu_fence_driver_resume(adev);
3341 
3342 
3343 	r = amdgpu_device_ip_late_init(adev);
3344 	if (r)
3345 		return r;
3346 
3347 	queue_delayed_work(system_wq, &adev->delayed_init_work,
3348 			   msecs_to_jiffies(AMDGPU_RESUME_MS));
3349 
3350 	if (!amdgpu_device_has_dc_support(adev)) {
3351 		/* pin cursors */
3352 		list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
3353 			struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3354 
3355 			if (amdgpu_crtc->cursor_bo && !adev->enable_virtual_display) {
3356 				struct amdgpu_bo *aobj = gem_to_amdgpu_bo(amdgpu_crtc->cursor_bo);
3357 				r = amdgpu_bo_reserve(aobj, true);
3358 				if (r == 0) {
3359 					r = amdgpu_bo_pin(aobj, AMDGPU_GEM_DOMAIN_VRAM);
3360 					if (r != 0)
3361 						DRM_ERROR("Failed to pin cursor BO (%d)\n", r);
3362 					amdgpu_crtc->cursor_addr = amdgpu_bo_gpu_offset(aobj);
3363 					amdgpu_bo_unreserve(aobj);
3364 				}
3365 			}
3366 		}
3367 	}
3368 	r = amdgpu_amdkfd_resume(adev);
3369 	if (r)
3370 		return r;
3371 
3372 	/* Make sure IB tests flushed */
3373 	flush_delayed_work(&adev->delayed_init_work);
3374 
3375 	/* blat the mode back in */
3376 	if (fbcon) {
3377 		if (!amdgpu_device_has_dc_support(adev)) {
3378 			/* pre DCE11 */
3379 			drm_helper_resume_force_mode(dev);
3380 
3381 			/* turn on display hw */
3382 			drm_modeset_lock_all(dev);
3383 
3384 			drm_connector_list_iter_begin(dev, &iter);
3385 			drm_for_each_connector_iter(connector, &iter)
3386 				drm_helper_connector_dpms(connector,
3387 							  DRM_MODE_DPMS_ON);
3388 			drm_connector_list_iter_end(&iter);
3389 
3390 			drm_modeset_unlock_all(dev);
3391 		}
3392 		amdgpu_fbdev_set_suspend(adev, 0);
3393 	}
3394 
3395 	drm_kms_helper_poll_enable(dev);
3396 
3397 	amdgpu_ras_resume(adev);
3398 
3399 	/*
3400 	 * Most of the connector probing functions try to acquire runtime pm
3401 	 * refs to ensure that the GPU is powered on when connector polling is
3402 	 * performed. Since we're calling this from a runtime PM callback,
3403 	 * trying to acquire rpm refs will cause us to deadlock.
3404 	 *
3405 	 * Since we're guaranteed to be holding the rpm lock, it's safe to
3406 	 * temporarily disable the rpm helpers so this doesn't deadlock us.
3407 	 */
3408 #ifdef CONFIG_PM
3409 	dev->dev->power.disable_depth++;
3410 #endif
3411 	if (!amdgpu_device_has_dc_support(adev))
3412 		drm_helper_hpd_irq_event(dev);
3413 	else
3414 		drm_kms_helper_hotplug_event(dev);
3415 #ifdef CONFIG_PM
3416 	dev->dev->power.disable_depth--;
3417 #endif
3418 	adev->in_suspend = false;
3419 
3420 	return 0;
3421 }
3422 
3423 /**
3424  * amdgpu_device_ip_check_soft_reset - did soft reset succeed
3425  *
3426  * @adev: amdgpu_device pointer
3427  *
3428  * The list of all the hardware IPs that make up the asic is walked and
3429  * the check_soft_reset callbacks are run.  check_soft_reset determines
3430  * if the asic is still hung or not.
3431  * Returns true if any of the IPs are still in a hung state, false if not.
3432  */
3433 static bool amdgpu_device_ip_check_soft_reset(struct amdgpu_device *adev)
3434 {
3435 	int i;
3436 	bool asic_hang = false;
3437 
3438 	if (amdgpu_sriov_vf(adev))
3439 		return true;
3440 
3441 	if (amdgpu_asic_need_full_reset(adev))
3442 		return true;
3443 
3444 	for (i = 0; i < adev->num_ip_blocks; i++) {
3445 		if (!adev->ip_blocks[i].status.valid)
3446 			continue;
3447 		if (adev->ip_blocks[i].version->funcs->check_soft_reset)
3448 			adev->ip_blocks[i].status.hang =
3449 				adev->ip_blocks[i].version->funcs->check_soft_reset(adev);
3450 		if (adev->ip_blocks[i].status.hang) {
3451 			DRM_INFO("IP block:%s is hung!\n", adev->ip_blocks[i].version->funcs->name);
3452 			asic_hang = true;
3453 		}
3454 	}
3455 	return asic_hang;
3456 }
3457 
3458 /**
3459  * amdgpu_device_ip_pre_soft_reset - prepare for soft reset
3460  *
3461  * @adev: amdgpu_device pointer
3462  *
3463  * The list of all the hardware IPs that make up the asic is walked and the
3464  * pre_soft_reset callbacks are run if the block is hung.  pre_soft_reset
3465  * handles any IP specific hardware or software state changes that are
3466  * necessary for a soft reset to succeed.
3467  * Returns 0 on success, negative error code on failure.
3468  */
3469 static int amdgpu_device_ip_pre_soft_reset(struct amdgpu_device *adev)
3470 {
3471 	int i, r = 0;
3472 
3473 	for (i = 0; i < adev->num_ip_blocks; i++) {
3474 		if (!adev->ip_blocks[i].status.valid)
3475 			continue;
3476 		if (adev->ip_blocks[i].status.hang &&
3477 		    adev->ip_blocks[i].version->funcs->pre_soft_reset) {
3478 			r = adev->ip_blocks[i].version->funcs->pre_soft_reset(adev);
3479 			if (r)
3480 				return r;
3481 		}
3482 	}
3483 
3484 	return 0;
3485 }
3486 
3487 /**
3488  * amdgpu_device_ip_need_full_reset - check if a full asic reset is needed
3489  *
3490  * @adev: amdgpu_device pointer
3491  *
3492  * Some hardware IPs cannot be soft reset.  If they are hung, a full gpu
3493  * reset is necessary to recover.
3494  * Returns true if a full asic reset is required, false if not.
3495  */
3496 static bool amdgpu_device_ip_need_full_reset(struct amdgpu_device *adev)
3497 {
3498 	int i;
3499 
3500 	if (amdgpu_asic_need_full_reset(adev))
3501 		return true;
3502 
3503 	for (i = 0; i < adev->num_ip_blocks; i++) {
3504 		if (!adev->ip_blocks[i].status.valid)
3505 			continue;
3506 		if ((adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) ||
3507 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) ||
3508 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_ACP) ||
3509 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) ||
3510 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
3511 			if (adev->ip_blocks[i].status.hang) {
3512 				DRM_INFO("Some block need full reset!\n");
3513 				return true;
3514 			}
3515 		}
3516 	}
3517 	return false;
3518 }
3519 
3520 /**
3521  * amdgpu_device_ip_soft_reset - do a soft reset
3522  *
3523  * @adev: amdgpu_device pointer
3524  *
3525  * The list of all the hardware IPs that make up the asic is walked and the
3526  * soft_reset callbacks are run if the block is hung.  soft_reset handles any
3527  * IP specific hardware or software state changes that are necessary to soft
3528  * reset the IP.
3529  * Returns 0 on success, negative error code on failure.
3530  */
3531 static int amdgpu_device_ip_soft_reset(struct amdgpu_device *adev)
3532 {
3533 	int i, r = 0;
3534 
3535 	for (i = 0; i < adev->num_ip_blocks; i++) {
3536 		if (!adev->ip_blocks[i].status.valid)
3537 			continue;
3538 		if (adev->ip_blocks[i].status.hang &&
3539 		    adev->ip_blocks[i].version->funcs->soft_reset) {
3540 			r = adev->ip_blocks[i].version->funcs->soft_reset(adev);
3541 			if (r)
3542 				return r;
3543 		}
3544 	}
3545 
3546 	return 0;
3547 }
3548 
3549 /**
3550  * amdgpu_device_ip_post_soft_reset - clean up from soft reset
3551  *
3552  * @adev: amdgpu_device pointer
3553  *
3554  * The list of all the hardware IPs that make up the asic is walked and the
3555  * post_soft_reset callbacks are run if the asic was hung.  post_soft_reset
3556  * handles any IP specific hardware or software state changes that are
3557  * necessary after the IP has been soft reset.
3558  * Returns 0 on success, negative error code on failure.
3559  */
3560 static int amdgpu_device_ip_post_soft_reset(struct amdgpu_device *adev)
3561 {
3562 	int i, r = 0;
3563 
3564 	for (i = 0; i < adev->num_ip_blocks; i++) {
3565 		if (!adev->ip_blocks[i].status.valid)
3566 			continue;
3567 		if (adev->ip_blocks[i].status.hang &&
3568 		    adev->ip_blocks[i].version->funcs->post_soft_reset)
3569 			r = adev->ip_blocks[i].version->funcs->post_soft_reset(adev);
3570 		if (r)
3571 			return r;
3572 	}
3573 
3574 	return 0;
3575 }
3576 
3577 /**
3578  * amdgpu_device_recover_vram - Recover some VRAM contents
3579  *
3580  * @adev: amdgpu_device pointer
3581  *
3582  * Restores the contents of VRAM buffers from the shadows in GTT.  Used to
3583  * restore things like GPUVM page tables after a GPU reset where
3584  * the contents of VRAM might be lost.
3585  *
3586  * Returns:
3587  * 0 on success, negative error code on failure.
3588  */
3589 static int amdgpu_device_recover_vram(struct amdgpu_device *adev)
3590 {
3591 	struct dma_fence *fence = NULL, *next = NULL;
3592 	struct amdgpu_bo *shadow;
3593 	long r = 1, tmo;
3594 
3595 	if (amdgpu_sriov_runtime(adev))
3596 		tmo = msecs_to_jiffies(8000);
3597 	else
3598 		tmo = msecs_to_jiffies(100);
3599 
3600 	DRM_INFO("recover vram bo from shadow start\n");
3601 	mutex_lock(&adev->shadow_list_lock);
3602 	list_for_each_entry(shadow, &adev->shadow_list, shadow_list) {
3603 
3604 		/* No need to recover an evicted BO */
3605 		if (shadow->tbo.mem.mem_type != TTM_PL_TT ||
3606 		    shadow->tbo.mem.start == AMDGPU_BO_INVALID_OFFSET ||
3607 		    shadow->parent->tbo.mem.mem_type != TTM_PL_VRAM)
3608 			continue;
3609 
3610 		r = amdgpu_bo_restore_shadow(shadow, &next);
3611 		if (r)
3612 			break;
3613 
3614 		if (fence) {
3615 			tmo = dma_fence_wait_timeout(fence, false, tmo);
3616 			dma_fence_put(fence);
3617 			fence = next;
3618 			if (tmo == 0) {
3619 				r = -ETIMEDOUT;
3620 				break;
3621 			} else if (tmo < 0) {
3622 				r = tmo;
3623 				break;
3624 			}
3625 		} else {
3626 			fence = next;
3627 		}
3628 	}
3629 	mutex_unlock(&adev->shadow_list_lock);
3630 
3631 	if (fence)
3632 		tmo = dma_fence_wait_timeout(fence, false, tmo);
3633 	dma_fence_put(fence);
3634 
3635 	if (r < 0 || tmo <= 0) {
3636 		DRM_ERROR("recover vram bo from shadow failed, r is %ld, tmo is %ld\n", r, tmo);
3637 		return -EIO;
3638 	}
3639 
3640 	DRM_INFO("recover vram bo from shadow done\n");
3641 	return 0;
3642 }
3643 
3644 
3645 /**
3646  * amdgpu_device_reset_sriov - reset ASIC for SR-IOV vf
3647  *
3648  * @adev: amdgpu device pointer
3649  * @from_hypervisor: request from hypervisor
3650  *
3651  * do VF FLR and reinitialize Asic
3652  * return 0 means succeeded otherwise failed
3653  */
3654 static int amdgpu_device_reset_sriov(struct amdgpu_device *adev,
3655 				     bool from_hypervisor)
3656 {
3657 	int r;
3658 
3659 	if (from_hypervisor)
3660 		r = amdgpu_virt_request_full_gpu(adev, true);
3661 	else
3662 		r = amdgpu_virt_reset_gpu(adev);
3663 	if (r)
3664 		return r;
3665 
3666 	amdgpu_amdkfd_pre_reset(adev);
3667 
3668 	/* Resume IP prior to SMC */
3669 	r = amdgpu_device_ip_reinit_early_sriov(adev);
3670 	if (r)
3671 		goto error;
3672 
3673 	/* we need recover gart prior to run SMC/CP/SDMA resume */
3674 	amdgpu_gtt_mgr_recover(&adev->mman.bdev.man[TTM_PL_TT]);
3675 
3676 	r = amdgpu_device_fw_loading(adev);
3677 	if (r)
3678 		return r;
3679 
3680 	/* now we are okay to resume SMC/CP/SDMA */
3681 	r = amdgpu_device_ip_reinit_late_sriov(adev);
3682 	if (r)
3683 		goto error;
3684 
3685 	amdgpu_irq_gpu_reset_resume_helper(adev);
3686 	r = amdgpu_ib_ring_tests(adev);
3687 	amdgpu_amdkfd_post_reset(adev);
3688 
3689 error:
3690 	amdgpu_virt_init_data_exchange(adev);
3691 	amdgpu_virt_release_full_gpu(adev, true);
3692 	if (!r && adev->virt.gim_feature & AMDGIM_FEATURE_GIM_FLR_VRAMLOST) {
3693 		amdgpu_inc_vram_lost(adev);
3694 		r = amdgpu_device_recover_vram(adev);
3695 	}
3696 
3697 	return r;
3698 }
3699 
3700 /**
3701  * amdgpu_device_should_recover_gpu - check if we should try GPU recovery
3702  *
3703  * @adev: amdgpu device pointer
3704  *
3705  * Check amdgpu_gpu_recovery and SRIOV status to see if we should try to recover
3706  * a hung GPU.
3707  */
3708 bool amdgpu_device_should_recover_gpu(struct amdgpu_device *adev)
3709 {
3710 	if (!amdgpu_device_ip_check_soft_reset(adev)) {
3711 		DRM_INFO("Timeout, but no hardware hang detected.\n");
3712 		return false;
3713 	}
3714 
3715 	if (amdgpu_gpu_recovery == 0)
3716 		goto disabled;
3717 
3718 	if (amdgpu_sriov_vf(adev))
3719 		return true;
3720 
3721 	if (amdgpu_gpu_recovery == -1) {
3722 		switch (adev->asic_type) {
3723 		case CHIP_BONAIRE:
3724 		case CHIP_HAWAII:
3725 		case CHIP_TOPAZ:
3726 		case CHIP_TONGA:
3727 		case CHIP_FIJI:
3728 		case CHIP_POLARIS10:
3729 		case CHIP_POLARIS11:
3730 		case CHIP_POLARIS12:
3731 		case CHIP_VEGAM:
3732 		case CHIP_VEGA20:
3733 		case CHIP_VEGA10:
3734 		case CHIP_VEGA12:
3735 		case CHIP_RAVEN:
3736 			break;
3737 		default:
3738 			goto disabled;
3739 		}
3740 	}
3741 
3742 	return true;
3743 
3744 disabled:
3745 		DRM_INFO("GPU recovery disabled.\n");
3746 		return false;
3747 }
3748 
3749 
3750 static int amdgpu_device_pre_asic_reset(struct amdgpu_device *adev,
3751 					struct amdgpu_job *job,
3752 					bool *need_full_reset_arg)
3753 {
3754 	int i, r = 0;
3755 	bool need_full_reset  = *need_full_reset_arg;
3756 
3757 	/* block all schedulers and reset given job's ring */
3758 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
3759 		struct amdgpu_ring *ring = adev->rings[i];
3760 
3761 		if (!ring || !ring->sched.thread)
3762 			continue;
3763 
3764 		/* after all hw jobs are reset, hw fence is meaningless, so force_completion */
3765 		amdgpu_fence_driver_force_completion(ring);
3766 	}
3767 
3768 	if(job)
3769 		drm_sched_increase_karma(&job->base);
3770 
3771 	/* Don't suspend on bare metal if we are not going to HW reset the ASIC */
3772 	if (!amdgpu_sriov_vf(adev)) {
3773 
3774 		if (!need_full_reset)
3775 			need_full_reset = amdgpu_device_ip_need_full_reset(adev);
3776 
3777 		if (!need_full_reset) {
3778 			amdgpu_device_ip_pre_soft_reset(adev);
3779 			r = amdgpu_device_ip_soft_reset(adev);
3780 			amdgpu_device_ip_post_soft_reset(adev);
3781 			if (r || amdgpu_device_ip_check_soft_reset(adev)) {
3782 				DRM_INFO("soft reset failed, will fallback to full reset!\n");
3783 				need_full_reset = true;
3784 			}
3785 		}
3786 
3787 		if (need_full_reset)
3788 			r = amdgpu_device_ip_suspend(adev);
3789 
3790 		*need_full_reset_arg = need_full_reset;
3791 	}
3792 
3793 	return r;
3794 }
3795 
3796 static int amdgpu_do_asic_reset(struct amdgpu_device *adev,
3797 			       struct amdgpu_hive_info *hive,
3798 			       struct list_head *device_list_handle,
3799 			       bool *need_full_reset_arg)
3800 {
3801 	struct amdgpu_device *tmp_adev = NULL;
3802 	bool need_full_reset = *need_full_reset_arg, vram_lost = false;
3803 	int r = 0;
3804 	int cpu = smp_processor_id();
3805 	bool use_baco =
3806 		(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) ?
3807 		true : false;
3808 
3809 	/*
3810 	 * ASIC reset has to be done on all HGMI hive nodes ASAP
3811 	 * to allow proper links negotiation in FW (within 1 sec)
3812 	 */
3813 	if (need_full_reset) {
3814 		list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
3815 			/*
3816 			 * For XGMI run all resets in parallel to speed up the
3817 			 * process by scheduling the highpri wq on different
3818 			 * cpus. For XGMI with baco reset, all nodes must enter
3819 			 * baco within close proximity before anyone exit.
3820 			 */
3821 			if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
3822 				if (!queue_work_on(cpu, system_highpri_wq,
3823 						   &tmp_adev->xgmi_reset_work))
3824 					r = -EALREADY;
3825 				cpu = cpumask_next(cpu, cpu_online_mask);
3826 			} else
3827 				r = amdgpu_asic_reset(tmp_adev);
3828 			if (r)
3829 				break;
3830 		}
3831 
3832 		/* For XGMI wait for all work to complete before proceed */
3833 		if (!r) {
3834 			list_for_each_entry(tmp_adev, device_list_handle,
3835 					    gmc.xgmi.head) {
3836 				if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
3837 					flush_work(&tmp_adev->xgmi_reset_work);
3838 					r = tmp_adev->asic_reset_res;
3839 					if (r)
3840 						break;
3841 					if (use_baco)
3842 						tmp_adev->in_baco = true;
3843 				}
3844 			}
3845 		}
3846 
3847 		/*
3848 		 * For XGMI with baco reset, need exit baco phase by scheduling
3849 		 * xgmi_reset_work one more time. PSP reset and sGPU skips this
3850 		 * phase. Not assume the situation that PSP reset and baco reset
3851 		 * coexist within an XGMI hive.
3852 		 */
3853 
3854 		if (!r && use_baco) {
3855 			cpu = smp_processor_id();
3856 			list_for_each_entry(tmp_adev, device_list_handle,
3857 					    gmc.xgmi.head) {
3858 				if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
3859 					if (!queue_work_on(cpu,
3860 						system_highpri_wq,
3861 						&tmp_adev->xgmi_reset_work))
3862 						r = -EALREADY;
3863 					if (r)
3864 						break;
3865 					cpu = cpumask_next(cpu, cpu_online_mask);
3866 				}
3867 			}
3868 		}
3869 
3870 		if (!r && use_baco) {
3871 			list_for_each_entry(tmp_adev, device_list_handle,
3872 					    gmc.xgmi.head) {
3873 				if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
3874 					flush_work(&tmp_adev->xgmi_reset_work);
3875 					r = tmp_adev->asic_reset_res;
3876 					if (r)
3877 						break;
3878 					tmp_adev->in_baco = false;
3879 				}
3880 			}
3881 		}
3882 
3883 		if (r) {
3884 			DRM_ERROR("ASIC reset failed with error, %d for drm dev, %s",
3885 				 r, tmp_adev->ddev->unique);
3886 			goto end;
3887 		}
3888 	}
3889 
3890 	if (!r && amdgpu_ras_intr_triggered())
3891 		amdgpu_ras_intr_cleared();
3892 
3893 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
3894 		if (need_full_reset) {
3895 			/* post card */
3896 			if (amdgpu_atom_asic_init(tmp_adev->mode_info.atom_context))
3897 				DRM_WARN("asic atom init failed!");
3898 
3899 			if (!r) {
3900 				dev_info(tmp_adev->dev, "GPU reset succeeded, trying to resume\n");
3901 				r = amdgpu_device_ip_resume_phase1(tmp_adev);
3902 				if (r)
3903 					goto out;
3904 
3905 				vram_lost = amdgpu_device_check_vram_lost(tmp_adev);
3906 				if (vram_lost) {
3907 					DRM_INFO("VRAM is lost due to GPU reset!\n");
3908 					amdgpu_inc_vram_lost(tmp_adev);
3909 				}
3910 
3911 				r = amdgpu_gtt_mgr_recover(
3912 					&tmp_adev->mman.bdev.man[TTM_PL_TT]);
3913 				if (r)
3914 					goto out;
3915 
3916 				r = amdgpu_device_fw_loading(tmp_adev);
3917 				if (r)
3918 					return r;
3919 
3920 				r = amdgpu_device_ip_resume_phase2(tmp_adev);
3921 				if (r)
3922 					goto out;
3923 
3924 				if (vram_lost)
3925 					amdgpu_device_fill_reset_magic(tmp_adev);
3926 
3927 				/*
3928 				 * Add this ASIC as tracked as reset was already
3929 				 * complete successfully.
3930 				 */
3931 				amdgpu_register_gpu_instance(tmp_adev);
3932 
3933 				r = amdgpu_device_ip_late_init(tmp_adev);
3934 				if (r)
3935 					goto out;
3936 
3937 				/* must succeed. */
3938 				amdgpu_ras_resume(tmp_adev);
3939 
3940 				/* Update PSP FW topology after reset */
3941 				if (hive && tmp_adev->gmc.xgmi.num_physical_nodes > 1)
3942 					r = amdgpu_xgmi_update_topology(hive, tmp_adev);
3943 			}
3944 		}
3945 
3946 
3947 out:
3948 		if (!r) {
3949 			amdgpu_irq_gpu_reset_resume_helper(tmp_adev);
3950 			r = amdgpu_ib_ring_tests(tmp_adev);
3951 			if (r) {
3952 				dev_err(tmp_adev->dev, "ib ring test failed (%d).\n", r);
3953 				r = amdgpu_device_ip_suspend(tmp_adev);
3954 				need_full_reset = true;
3955 				r = -EAGAIN;
3956 				goto end;
3957 			}
3958 		}
3959 
3960 		if (!r)
3961 			r = amdgpu_device_recover_vram(tmp_adev);
3962 		else
3963 			tmp_adev->asic_reset_res = r;
3964 	}
3965 
3966 end:
3967 	*need_full_reset_arg = need_full_reset;
3968 	return r;
3969 }
3970 
3971 static bool amdgpu_device_lock_adev(struct amdgpu_device *adev, bool trylock)
3972 {
3973 	if (trylock) {
3974 		if (!mutex_trylock(&adev->lock_reset))
3975 			return false;
3976 	} else
3977 		mutex_lock(&adev->lock_reset);
3978 
3979 	atomic_inc(&adev->gpu_reset_counter);
3980 	adev->in_gpu_reset = 1;
3981 	switch (amdgpu_asic_reset_method(adev)) {
3982 	case AMD_RESET_METHOD_MODE1:
3983 		adev->mp1_state = PP_MP1_STATE_SHUTDOWN;
3984 		break;
3985 	case AMD_RESET_METHOD_MODE2:
3986 		adev->mp1_state = PP_MP1_STATE_RESET;
3987 		break;
3988 	default:
3989 		adev->mp1_state = PP_MP1_STATE_NONE;
3990 		break;
3991 	}
3992 
3993 	return true;
3994 }
3995 
3996 static void amdgpu_device_unlock_adev(struct amdgpu_device *adev)
3997 {
3998 	amdgpu_vf_error_trans_all(adev);
3999 	adev->mp1_state = PP_MP1_STATE_NONE;
4000 	adev->in_gpu_reset = 0;
4001 	mutex_unlock(&adev->lock_reset);
4002 }
4003 
4004 /**
4005  * amdgpu_device_gpu_recover - reset the asic and recover scheduler
4006  *
4007  * @adev: amdgpu device pointer
4008  * @job: which job trigger hang
4009  *
4010  * Attempt to reset the GPU if it has hung (all asics).
4011  * Attempt to do soft-reset or full-reset and reinitialize Asic
4012  * Returns 0 for success or an error on failure.
4013  */
4014 
4015 int amdgpu_device_gpu_recover(struct amdgpu_device *adev,
4016 			      struct amdgpu_job *job)
4017 {
4018 	struct list_head device_list, *device_list_handle =  NULL;
4019 	bool need_full_reset, job_signaled;
4020 	struct amdgpu_hive_info *hive = NULL;
4021 	struct amdgpu_device *tmp_adev = NULL;
4022 	int i, r = 0;
4023 	bool in_ras_intr = amdgpu_ras_intr_triggered();
4024 	bool use_baco =
4025 		(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) ?
4026 		true : false;
4027 
4028 	/*
4029 	 * Flush RAM to disk so that after reboot
4030 	 * the user can read log and see why the system rebooted.
4031 	 */
4032 	if (in_ras_intr && !use_baco && amdgpu_ras_get_context(adev)->reboot) {
4033 
4034 		DRM_WARN("Emergency reboot.");
4035 
4036 		ksys_sync_helper();
4037 		emergency_restart();
4038 	}
4039 
4040 	need_full_reset = job_signaled = false;
4041 	INIT_LIST_HEAD(&device_list);
4042 
4043 	dev_info(adev->dev, "GPU %s begin!\n",
4044 		(in_ras_intr && !use_baco) ? "jobs stop":"reset");
4045 
4046 	cancel_delayed_work_sync(&adev->delayed_init_work);
4047 
4048 	hive = amdgpu_get_xgmi_hive(adev, false);
4049 
4050 	/*
4051 	 * Here we trylock to avoid chain of resets executing from
4052 	 * either trigger by jobs on different adevs in XGMI hive or jobs on
4053 	 * different schedulers for same device while this TO handler is running.
4054 	 * We always reset all schedulers for device and all devices for XGMI
4055 	 * hive so that should take care of them too.
4056 	 */
4057 
4058 	if (hive && !mutex_trylock(&hive->reset_lock)) {
4059 		DRM_INFO("Bailing on TDR for s_job:%llx, hive: %llx as another already in progress",
4060 			  job ? job->base.id : -1, hive->hive_id);
4061 		return 0;
4062 	}
4063 
4064 	/* Start with adev pre asic reset first for soft reset check.*/
4065 	if (!amdgpu_device_lock_adev(adev, !hive)) {
4066 		DRM_INFO("Bailing on TDR for s_job:%llx, as another already in progress",
4067 			  job ? job->base.id : -1);
4068 		return 0;
4069 	}
4070 
4071 	/* Block kfd: SRIOV would do it separately */
4072 	if (!amdgpu_sriov_vf(adev))
4073                 amdgpu_amdkfd_pre_reset(adev);
4074 
4075 	/* Build list of devices to reset */
4076 	if  (adev->gmc.xgmi.num_physical_nodes > 1) {
4077 		if (!hive) {
4078 			/*unlock kfd: SRIOV would do it separately */
4079 			if (!amdgpu_sriov_vf(adev))
4080 		                amdgpu_amdkfd_post_reset(adev);
4081 			amdgpu_device_unlock_adev(adev);
4082 			return -ENODEV;
4083 		}
4084 
4085 		/*
4086 		 * In case we are in XGMI hive mode device reset is done for all the
4087 		 * nodes in the hive to retrain all XGMI links and hence the reset
4088 		 * sequence is executed in loop on all nodes.
4089 		 */
4090 		device_list_handle = &hive->device_list;
4091 	} else {
4092 		list_add_tail(&adev->gmc.xgmi.head, &device_list);
4093 		device_list_handle = &device_list;
4094 	}
4095 
4096 	/* block all schedulers and reset given job's ring */
4097 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4098 		if (tmp_adev != adev) {
4099 			amdgpu_device_lock_adev(tmp_adev, false);
4100 			if (!amdgpu_sriov_vf(tmp_adev))
4101 			                amdgpu_amdkfd_pre_reset(tmp_adev);
4102 		}
4103 
4104 		/*
4105 		 * Mark these ASICs to be reseted as untracked first
4106 		 * And add them back after reset completed
4107 		 */
4108 		amdgpu_unregister_gpu_instance(tmp_adev);
4109 
4110 		/* disable ras on ALL IPs */
4111 		if (!(in_ras_intr && !use_baco) &&
4112 		      amdgpu_device_ip_need_full_reset(tmp_adev))
4113 			amdgpu_ras_suspend(tmp_adev);
4114 
4115 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4116 			struct amdgpu_ring *ring = tmp_adev->rings[i];
4117 
4118 			if (!ring || !ring->sched.thread)
4119 				continue;
4120 
4121 			drm_sched_stop(&ring->sched, job ? &job->base : NULL);
4122 
4123 			if (in_ras_intr && !use_baco)
4124 				amdgpu_job_stop_all_jobs_on_sched(&ring->sched);
4125 		}
4126 	}
4127 
4128 
4129 	if (in_ras_intr && !use_baco)
4130 		goto skip_sched_resume;
4131 
4132 	/*
4133 	 * Must check guilty signal here since after this point all old
4134 	 * HW fences are force signaled.
4135 	 *
4136 	 * job->base holds a reference to parent fence
4137 	 */
4138 	if (job && job->base.s_fence->parent &&
4139 	    dma_fence_is_signaled(job->base.s_fence->parent))
4140 		job_signaled = true;
4141 
4142 	if (job_signaled) {
4143 		dev_info(adev->dev, "Guilty job already signaled, skipping HW reset");
4144 		goto skip_hw_reset;
4145 	}
4146 
4147 
4148 	/* Guilty job will be freed after this*/
4149 	r = amdgpu_device_pre_asic_reset(adev, job, &need_full_reset);
4150 	if (r) {
4151 		/*TODO Should we stop ?*/
4152 		DRM_ERROR("GPU pre asic reset failed with err, %d for drm dev, %s ",
4153 			  r, adev->ddev->unique);
4154 		adev->asic_reset_res = r;
4155 	}
4156 
4157 retry:	/* Rest of adevs pre asic reset from XGMI hive. */
4158 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4159 
4160 		if (tmp_adev == adev)
4161 			continue;
4162 
4163 		r = amdgpu_device_pre_asic_reset(tmp_adev,
4164 						 NULL,
4165 						 &need_full_reset);
4166 		/*TODO Should we stop ?*/
4167 		if (r) {
4168 			DRM_ERROR("GPU pre asic reset failed with err, %d for drm dev, %s ",
4169 				  r, tmp_adev->ddev->unique);
4170 			tmp_adev->asic_reset_res = r;
4171 		}
4172 	}
4173 
4174 	/* Actual ASIC resets if needed.*/
4175 	/* TODO Implement XGMI hive reset logic for SRIOV */
4176 	if (amdgpu_sriov_vf(adev)) {
4177 		r = amdgpu_device_reset_sriov(adev, job ? false : true);
4178 		if (r)
4179 			adev->asic_reset_res = r;
4180 	} else {
4181 		r  = amdgpu_do_asic_reset(adev, hive, device_list_handle,
4182 					  &need_full_reset);
4183 		if (r && r == -EAGAIN)
4184 			goto retry;
4185 	}
4186 
4187 skip_hw_reset:
4188 
4189 	/* Post ASIC reset for all devs .*/
4190 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4191 
4192 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4193 			struct amdgpu_ring *ring = tmp_adev->rings[i];
4194 
4195 			if (!ring || !ring->sched.thread)
4196 				continue;
4197 
4198 			/* No point to resubmit jobs if we didn't HW reset*/
4199 			if (!tmp_adev->asic_reset_res && !job_signaled)
4200 				drm_sched_resubmit_jobs(&ring->sched);
4201 
4202 			drm_sched_start(&ring->sched, !tmp_adev->asic_reset_res);
4203 		}
4204 
4205 		if (!amdgpu_device_has_dc_support(tmp_adev) && !job_signaled) {
4206 			drm_helper_resume_force_mode(tmp_adev->ddev);
4207 		}
4208 
4209 		tmp_adev->asic_reset_res = 0;
4210 
4211 		if (r) {
4212 			/* bad news, how to tell it to userspace ? */
4213 			dev_info(tmp_adev->dev, "GPU reset(%d) failed\n", atomic_read(&tmp_adev->gpu_reset_counter));
4214 			amdgpu_vf_error_put(tmp_adev, AMDGIM_ERROR_VF_GPU_RESET_FAIL, 0, r);
4215 		} else {
4216 			dev_info(tmp_adev->dev, "GPU reset(%d) succeeded!\n", atomic_read(&tmp_adev->gpu_reset_counter));
4217 		}
4218 	}
4219 
4220 skip_sched_resume:
4221 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4222 		/*unlock kfd: SRIOV would do it separately */
4223 		if (!(in_ras_intr && !use_baco) && !amdgpu_sriov_vf(tmp_adev))
4224 	                amdgpu_amdkfd_post_reset(tmp_adev);
4225 		amdgpu_device_unlock_adev(tmp_adev);
4226 	}
4227 
4228 	if (hive)
4229 		mutex_unlock(&hive->reset_lock);
4230 
4231 	if (r)
4232 		dev_info(adev->dev, "GPU reset end with ret = %d\n", r);
4233 	return r;
4234 }
4235 
4236 /**
4237  * amdgpu_device_get_pcie_info - fence pcie info about the PCIE slot
4238  *
4239  * @adev: amdgpu_device pointer
4240  *
4241  * Fetchs and stores in the driver the PCIE capabilities (gen speed
4242  * and lanes) of the slot the device is in. Handles APUs and
4243  * virtualized environments where PCIE config space may not be available.
4244  */
4245 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev)
4246 {
4247 	struct pci_dev *pdev;
4248 	enum pci_bus_speed speed_cap, platform_speed_cap;
4249 	enum pcie_link_width platform_link_width;
4250 
4251 	if (amdgpu_pcie_gen_cap)
4252 		adev->pm.pcie_gen_mask = amdgpu_pcie_gen_cap;
4253 
4254 	if (amdgpu_pcie_lane_cap)
4255 		adev->pm.pcie_mlw_mask = amdgpu_pcie_lane_cap;
4256 
4257 	/* covers APUs as well */
4258 	if (pci_is_root_bus(adev->pdev->bus)) {
4259 		if (adev->pm.pcie_gen_mask == 0)
4260 			adev->pm.pcie_gen_mask = AMDGPU_DEFAULT_PCIE_GEN_MASK;
4261 		if (adev->pm.pcie_mlw_mask == 0)
4262 			adev->pm.pcie_mlw_mask = AMDGPU_DEFAULT_PCIE_MLW_MASK;
4263 		return;
4264 	}
4265 
4266 	if (adev->pm.pcie_gen_mask && adev->pm.pcie_mlw_mask)
4267 		return;
4268 
4269 	pcie_bandwidth_available(adev->pdev, NULL,
4270 				 &platform_speed_cap, &platform_link_width);
4271 
4272 	if (adev->pm.pcie_gen_mask == 0) {
4273 		/* asic caps */
4274 		pdev = adev->pdev;
4275 		speed_cap = pcie_get_speed_cap(pdev);
4276 		if (speed_cap == PCI_SPEED_UNKNOWN) {
4277 			adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4278 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4279 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
4280 		} else {
4281 			if (speed_cap == PCIE_SPEED_16_0GT)
4282 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4283 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4284 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3 |
4285 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN4);
4286 			else if (speed_cap == PCIE_SPEED_8_0GT)
4287 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4288 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4289 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
4290 			else if (speed_cap == PCIE_SPEED_5_0GT)
4291 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4292 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2);
4293 			else
4294 				adev->pm.pcie_gen_mask |= CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1;
4295 		}
4296 		/* platform caps */
4297 		if (platform_speed_cap == PCI_SPEED_UNKNOWN) {
4298 			adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4299 						   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
4300 		} else {
4301 			if (platform_speed_cap == PCIE_SPEED_16_0GT)
4302 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4303 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4304 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3 |
4305 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN4);
4306 			else if (platform_speed_cap == PCIE_SPEED_8_0GT)
4307 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4308 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4309 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3);
4310 			else if (platform_speed_cap == PCIE_SPEED_5_0GT)
4311 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4312 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
4313 			else
4314 				adev->pm.pcie_gen_mask |= CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1;
4315 
4316 		}
4317 	}
4318 	if (adev->pm.pcie_mlw_mask == 0) {
4319 		if (platform_link_width == PCIE_LNK_WIDTH_UNKNOWN) {
4320 			adev->pm.pcie_mlw_mask |= AMDGPU_DEFAULT_PCIE_MLW_MASK;
4321 		} else {
4322 			switch (platform_link_width) {
4323 			case PCIE_LNK_X32:
4324 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X32 |
4325 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
4326 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
4327 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4328 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4329 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4330 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4331 				break;
4332 			case PCIE_LNK_X16:
4333 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
4334 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
4335 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4336 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4337 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4338 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4339 				break;
4340 			case PCIE_LNK_X12:
4341 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
4342 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4343 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4344 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4345 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4346 				break;
4347 			case PCIE_LNK_X8:
4348 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4349 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4350 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4351 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4352 				break;
4353 			case PCIE_LNK_X4:
4354 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4355 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4356 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4357 				break;
4358 			case PCIE_LNK_X2:
4359 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4360 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4361 				break;
4362 			case PCIE_LNK_X1:
4363 				adev->pm.pcie_mlw_mask = CAIL_PCIE_LINK_WIDTH_SUPPORT_X1;
4364 				break;
4365 			default:
4366 				break;
4367 			}
4368 		}
4369 	}
4370 }
4371 
4372 int amdgpu_device_baco_enter(struct drm_device *dev)
4373 {
4374 	struct amdgpu_device *adev = dev->dev_private;
4375 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4376 
4377 	if (!amdgpu_device_supports_baco(adev->ddev))
4378 		return -ENOTSUPP;
4379 
4380 	if (ras && ras->supported)
4381 		adev->nbio.funcs->enable_doorbell_interrupt(adev, false);
4382 
4383 	if (is_support_sw_smu(adev)) {
4384 		struct smu_context *smu = &adev->smu;
4385 		int ret;
4386 
4387 		ret = smu_baco_enter(smu);
4388 		if (ret)
4389 			return ret;
4390 	} else {
4391 		void *pp_handle = adev->powerplay.pp_handle;
4392 		const struct amd_pm_funcs *pp_funcs = adev->powerplay.pp_funcs;
4393 
4394 		if (!pp_funcs ||!pp_funcs->get_asic_baco_state ||!pp_funcs->set_asic_baco_state)
4395 			return -ENOENT;
4396 
4397 		/* enter BACO state */
4398 		if (pp_funcs->set_asic_baco_state(pp_handle, 1))
4399 			return -EIO;
4400 	}
4401 
4402 	return 0;
4403 }
4404 
4405 int amdgpu_device_baco_exit(struct drm_device *dev)
4406 {
4407 	struct amdgpu_device *adev = dev->dev_private;
4408 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4409 
4410 	if (!amdgpu_device_supports_baco(adev->ddev))
4411 		return -ENOTSUPP;
4412 
4413 	if (is_support_sw_smu(adev)) {
4414 		struct smu_context *smu = &adev->smu;
4415 		int ret;
4416 
4417 		ret = smu_baco_exit(smu);
4418 		if (ret)
4419 			return ret;
4420 
4421 	} else {
4422 		void *pp_handle = adev->powerplay.pp_handle;
4423 		const struct amd_pm_funcs *pp_funcs = adev->powerplay.pp_funcs;
4424 
4425 		if (!pp_funcs ||!pp_funcs->get_asic_baco_state ||!pp_funcs->set_asic_baco_state)
4426 			return -ENOENT;
4427 
4428 		/* exit BACO state */
4429 		if (pp_funcs->set_asic_baco_state(pp_handle, 0))
4430 			return -EIO;
4431 	}
4432 
4433 	if (ras && ras->supported)
4434 		adev->nbio.funcs->enable_doorbell_interrupt(adev, true);
4435 
4436 	return 0;
4437 }
4438