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