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