xref: /openbsd-src/sys/dev/pci/drm/amd/amdgpu/amdgpu_device.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
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 			amdgpu_discovery_get_gfx_info(adev);
1625 			goto parse_soc_bounding_box;
1626 		}
1627 
1628 		adev->gfx.config.max_shader_engines = le32_to_cpu(gpu_info_fw->gc_num_se);
1629 		adev->gfx.config.max_cu_per_sh = le32_to_cpu(gpu_info_fw->gc_num_cu_per_sh);
1630 		adev->gfx.config.max_sh_per_se = le32_to_cpu(gpu_info_fw->gc_num_sh_per_se);
1631 		adev->gfx.config.max_backends_per_se = le32_to_cpu(gpu_info_fw->gc_num_rb_per_se);
1632 		adev->gfx.config.max_texture_channel_caches =
1633 			le32_to_cpu(gpu_info_fw->gc_num_tccs);
1634 		adev->gfx.config.max_gprs = le32_to_cpu(gpu_info_fw->gc_num_gprs);
1635 		adev->gfx.config.max_gs_threads = le32_to_cpu(gpu_info_fw->gc_num_max_gs_thds);
1636 		adev->gfx.config.gs_vgt_table_depth = le32_to_cpu(gpu_info_fw->gc_gs_table_depth);
1637 		adev->gfx.config.gs_prim_buffer_depth = le32_to_cpu(gpu_info_fw->gc_gsprim_buff_depth);
1638 		adev->gfx.config.double_offchip_lds_buf =
1639 			le32_to_cpu(gpu_info_fw->gc_double_offchip_lds_buffer);
1640 		adev->gfx.cu_info.wave_front_size = le32_to_cpu(gpu_info_fw->gc_wave_size);
1641 		adev->gfx.cu_info.max_waves_per_simd =
1642 			le32_to_cpu(gpu_info_fw->gc_max_waves_per_simd);
1643 		adev->gfx.cu_info.max_scratch_slots_per_cu =
1644 			le32_to_cpu(gpu_info_fw->gc_max_scratch_slots_per_cu);
1645 		adev->gfx.cu_info.lds_size = le32_to_cpu(gpu_info_fw->gc_lds_size);
1646 		if (hdr->version_minor >= 1) {
1647 			const struct gpu_info_firmware_v1_1 *gpu_info_fw =
1648 				(const struct gpu_info_firmware_v1_1 *)(adev->firmware.gpu_info_fw->data +
1649 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1650 			adev->gfx.config.num_sc_per_sh =
1651 				le32_to_cpu(gpu_info_fw->num_sc_per_sh);
1652 			adev->gfx.config.num_packer_per_sc =
1653 				le32_to_cpu(gpu_info_fw->num_packer_per_sc);
1654 		}
1655 
1656 parse_soc_bounding_box:
1657 		/*
1658 		 * soc bounding box info is not integrated in disocovery table,
1659 		 * we always need to parse it from gpu info firmware.
1660 		 */
1661 		if (hdr->version_minor == 2) {
1662 			const struct gpu_info_firmware_v1_2 *gpu_info_fw =
1663 				(const struct gpu_info_firmware_v1_2 *)(adev->firmware.gpu_info_fw->data +
1664 									le32_to_cpu(hdr->header.ucode_array_offset_bytes));
1665 			adev->dm.soc_bounding_box = &gpu_info_fw->soc_bounding_box;
1666 		}
1667 		break;
1668 	}
1669 	default:
1670 		dev_err(adev->dev,
1671 			"Unsupported gpu_info table %d\n", hdr->header.ucode_version);
1672 		err = -EINVAL;
1673 		goto out;
1674 	}
1675 out:
1676 	return err;
1677 }
1678 
1679 /**
1680  * amdgpu_device_ip_early_init - run early init for hardware IPs
1681  *
1682  * @adev: amdgpu_device pointer
1683  *
1684  * Early initialization pass for hardware IPs.  The hardware IPs that make
1685  * up each asic are discovered each IP's early_init callback is run.  This
1686  * is the first stage in initializing the asic.
1687  * Returns 0 on success, negative error code on failure.
1688  */
1689 static int amdgpu_device_ip_early_init(struct amdgpu_device *adev)
1690 {
1691 	int i, r;
1692 
1693 	amdgpu_device_enable_virtual_display(adev);
1694 
1695 	switch (adev->asic_type) {
1696 	case CHIP_TOPAZ:
1697 	case CHIP_TONGA:
1698 	case CHIP_FIJI:
1699 	case CHIP_POLARIS10:
1700 	case CHIP_POLARIS11:
1701 	case CHIP_POLARIS12:
1702 	case CHIP_VEGAM:
1703 	case CHIP_CARRIZO:
1704 	case CHIP_STONEY:
1705 		if (adev->asic_type == CHIP_CARRIZO || adev->asic_type == CHIP_STONEY)
1706 			adev->family = AMDGPU_FAMILY_CZ;
1707 		else
1708 			adev->family = AMDGPU_FAMILY_VI;
1709 
1710 		r = vi_set_ip_blocks(adev);
1711 		if (r)
1712 			return r;
1713 		break;
1714 #ifdef CONFIG_DRM_AMDGPU_SI
1715 	case CHIP_VERDE:
1716 	case CHIP_TAHITI:
1717 	case CHIP_PITCAIRN:
1718 	case CHIP_OLAND:
1719 	case CHIP_HAINAN:
1720 		adev->family = AMDGPU_FAMILY_SI;
1721 		r = si_set_ip_blocks(adev);
1722 		if (r)
1723 			return r;
1724 		break;
1725 #endif
1726 #ifdef CONFIG_DRM_AMDGPU_CIK
1727 	case CHIP_BONAIRE:
1728 	case CHIP_HAWAII:
1729 	case CHIP_KAVERI:
1730 	case CHIP_KABINI:
1731 	case CHIP_MULLINS:
1732 		if ((adev->asic_type == CHIP_BONAIRE) || (adev->asic_type == CHIP_HAWAII))
1733 			adev->family = AMDGPU_FAMILY_CI;
1734 		else
1735 			adev->family = AMDGPU_FAMILY_KV;
1736 
1737 		r = cik_set_ip_blocks(adev);
1738 		if (r)
1739 			return r;
1740 		break;
1741 #endif
1742 	case CHIP_VEGA10:
1743 	case CHIP_VEGA12:
1744 	case CHIP_VEGA20:
1745 	case CHIP_RAVEN:
1746 	case CHIP_ARCTURUS:
1747 	case CHIP_RENOIR:
1748 		if (adev->asic_type == CHIP_RAVEN ||
1749 		    adev->asic_type == CHIP_RENOIR)
1750 			adev->family = AMDGPU_FAMILY_RV;
1751 		else
1752 			adev->family = AMDGPU_FAMILY_AI;
1753 
1754 		r = soc15_set_ip_blocks(adev);
1755 		if (r)
1756 			return r;
1757 		break;
1758 	case  CHIP_NAVI10:
1759 	case  CHIP_NAVI14:
1760 	case  CHIP_NAVI12:
1761 		adev->family = AMDGPU_FAMILY_NV;
1762 
1763 		r = nv_set_ip_blocks(adev);
1764 		if (r)
1765 			return r;
1766 		break;
1767 	default:
1768 		/* FIXME: not supported yet */
1769 		return -EINVAL;
1770 	}
1771 
1772 	amdgpu_amdkfd_device_probe(adev);
1773 
1774 	if (amdgpu_sriov_vf(adev)) {
1775 		r = amdgpu_virt_request_full_gpu(adev, true);
1776 		if (r)
1777 			return -EAGAIN;
1778 	}
1779 
1780 	adev->pm.pp_feature = amdgpu_pp_feature_mask;
1781 	if (amdgpu_sriov_vf(adev) || sched_policy == KFD_SCHED_POLICY_NO_HWS)
1782 		adev->pm.pp_feature &= ~PP_GFXOFF_MASK;
1783 
1784 	for (i = 0; i < adev->num_ip_blocks; i++) {
1785 		if ((amdgpu_ip_block_mask & (1 << i)) == 0) {
1786 			DRM_ERROR("disabled ip block: %d <%s>\n",
1787 				  i, adev->ip_blocks[i].version->funcs->name);
1788 			adev->ip_blocks[i].status.valid = false;
1789 		} else {
1790 			if (adev->ip_blocks[i].version->funcs->early_init) {
1791 				r = adev->ip_blocks[i].version->funcs->early_init((void *)adev);
1792 				if (r == -ENOENT) {
1793 					adev->ip_blocks[i].status.valid = false;
1794 				} else if (r) {
1795 					DRM_ERROR("early_init of IP block <%s> failed %d\n",
1796 						  adev->ip_blocks[i].version->funcs->name, r);
1797 					return r;
1798 				} else {
1799 					adev->ip_blocks[i].status.valid = true;
1800 				}
1801 			} else {
1802 				adev->ip_blocks[i].status.valid = true;
1803 			}
1804 		}
1805 		/* get the vbios after the asic_funcs are set up */
1806 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON) {
1807 			r = amdgpu_device_parse_gpu_info_fw(adev);
1808 			if (r)
1809 				return r;
1810 
1811 			/* Read BIOS */
1812 			if (!amdgpu_get_bios(adev))
1813 				return -EINVAL;
1814 
1815 			r = amdgpu_atombios_init(adev);
1816 			if (r) {
1817 				dev_err(adev->dev, "amdgpu_atombios_init failed\n");
1818 				amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_INIT_FAIL, 0, 0);
1819 				return r;
1820 			}
1821 		}
1822 	}
1823 
1824 	adev->cg_flags &= amdgpu_cg_mask;
1825 	adev->pg_flags &= amdgpu_pg_mask;
1826 
1827 	return 0;
1828 }
1829 
1830 static int amdgpu_device_ip_hw_init_phase1(struct amdgpu_device *adev)
1831 {
1832 	int i, r;
1833 
1834 	for (i = 0; i < adev->num_ip_blocks; i++) {
1835 		if (!adev->ip_blocks[i].status.sw)
1836 			continue;
1837 		if (adev->ip_blocks[i].status.hw)
1838 			continue;
1839 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
1840 		    (amdgpu_sriov_vf(adev) && (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)) ||
1841 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
1842 			r = adev->ip_blocks[i].version->funcs->hw_init(adev);
1843 			if (r) {
1844 				DRM_ERROR("hw_init of IP block <%s> failed %d\n",
1845 					  adev->ip_blocks[i].version->funcs->name, r);
1846 				return r;
1847 			}
1848 			adev->ip_blocks[i].status.hw = true;
1849 		}
1850 	}
1851 
1852 	return 0;
1853 }
1854 
1855 static int amdgpu_device_ip_hw_init_phase2(struct amdgpu_device *adev)
1856 {
1857 	int i, r;
1858 
1859 	for (i = 0; i < adev->num_ip_blocks; i++) {
1860 		if (!adev->ip_blocks[i].status.sw)
1861 			continue;
1862 		if (adev->ip_blocks[i].status.hw)
1863 			continue;
1864 		r = adev->ip_blocks[i].version->funcs->hw_init(adev);
1865 		if (r) {
1866 			DRM_ERROR("hw_init of IP block <%s> failed %d\n",
1867 				  adev->ip_blocks[i].version->funcs->name, r);
1868 			return r;
1869 		}
1870 		adev->ip_blocks[i].status.hw = true;
1871 	}
1872 
1873 	return 0;
1874 }
1875 
1876 static int amdgpu_device_fw_loading(struct amdgpu_device *adev)
1877 {
1878 	int r = 0;
1879 	int i;
1880 	uint32_t smu_version;
1881 
1882 	if (adev->asic_type >= CHIP_VEGA10) {
1883 		for (i = 0; i < adev->num_ip_blocks; i++) {
1884 			if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_PSP)
1885 				continue;
1886 
1887 			/* no need to do the fw loading again if already done*/
1888 			if (adev->ip_blocks[i].status.hw == true)
1889 				break;
1890 
1891 			if (adev->in_gpu_reset || adev->in_suspend) {
1892 				r = adev->ip_blocks[i].version->funcs->resume(adev);
1893 				if (r) {
1894 					DRM_ERROR("resume of IP block <%s> failed %d\n",
1895 							  adev->ip_blocks[i].version->funcs->name, r);
1896 					return r;
1897 				}
1898 			} else {
1899 				r = adev->ip_blocks[i].version->funcs->hw_init(adev);
1900 				if (r) {
1901 					DRM_ERROR("hw_init of IP block <%s> failed %d\n",
1902 							  adev->ip_blocks[i].version->funcs->name, r);
1903 					return r;
1904 				}
1905 			}
1906 
1907 			adev->ip_blocks[i].status.hw = true;
1908 			break;
1909 		}
1910 	}
1911 
1912 	if (!amdgpu_sriov_vf(adev) || adev->asic_type == CHIP_TONGA)
1913 		r = amdgpu_pm_load_smu_firmware(adev, &smu_version);
1914 
1915 	return r;
1916 }
1917 
1918 /**
1919  * amdgpu_device_ip_init - run init for hardware IPs
1920  *
1921  * @adev: amdgpu_device pointer
1922  *
1923  * Main initialization pass for hardware IPs.  The list of all the hardware
1924  * IPs that make up the asic is walked and the sw_init and hw_init callbacks
1925  * are run.  sw_init initializes the software state associated with each IP
1926  * and hw_init initializes the hardware associated with each IP.
1927  * Returns 0 on success, negative error code on failure.
1928  */
1929 static int amdgpu_device_ip_init(struct amdgpu_device *adev)
1930 {
1931 	int i, r;
1932 
1933 	r = amdgpu_ras_init(adev);
1934 	if (r)
1935 		return r;
1936 
1937 	for (i = 0; i < adev->num_ip_blocks; i++) {
1938 		if (!adev->ip_blocks[i].status.valid)
1939 			continue;
1940 		r = adev->ip_blocks[i].version->funcs->sw_init((void *)adev);
1941 		if (r) {
1942 			DRM_ERROR("sw_init of IP block <%s> failed %d\n",
1943 				  adev->ip_blocks[i].version->funcs->name, r);
1944 			goto init_failed;
1945 		}
1946 		adev->ip_blocks[i].status.sw = true;
1947 
1948 		/* need to do gmc hw init early so we can allocate gpu mem */
1949 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
1950 			r = amdgpu_device_vram_scratch_init(adev);
1951 			if (r) {
1952 				DRM_ERROR("amdgpu_vram_scratch_init failed %d\n", r);
1953 				goto init_failed;
1954 			}
1955 			r = adev->ip_blocks[i].version->funcs->hw_init((void *)adev);
1956 			if (r) {
1957 				DRM_ERROR("hw_init %d failed %d\n", i, r);
1958 				goto init_failed;
1959 			}
1960 			r = amdgpu_device_wb_init(adev);
1961 			if (r) {
1962 				DRM_ERROR("amdgpu_device_wb_init failed %d\n", r);
1963 				goto init_failed;
1964 			}
1965 			adev->ip_blocks[i].status.hw = true;
1966 
1967 			/* right after GMC hw init, we create CSA */
1968 			if (amdgpu_mcbp || amdgpu_sriov_vf(adev)) {
1969 				r = amdgpu_allocate_static_csa(adev, &adev->virt.csa_obj,
1970 								AMDGPU_GEM_DOMAIN_VRAM,
1971 								AMDGPU_CSA_SIZE);
1972 				if (r) {
1973 					DRM_ERROR("allocate CSA failed %d\n", r);
1974 					goto init_failed;
1975 				}
1976 			}
1977 		}
1978 	}
1979 
1980 	if (amdgpu_sriov_vf(adev))
1981 		amdgpu_virt_init_data_exchange(adev);
1982 
1983 	r = amdgpu_ib_pool_init(adev);
1984 	if (r) {
1985 		dev_err(adev->dev, "IB initialization failed (%d).\n", r);
1986 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_IB_INIT_FAIL, 0, r);
1987 		goto init_failed;
1988 	}
1989 
1990 	r = amdgpu_ucode_create_bo(adev); /* create ucode bo when sw_init complete*/
1991 	if (r)
1992 		goto init_failed;
1993 
1994 	r = amdgpu_device_ip_hw_init_phase1(adev);
1995 	if (r)
1996 		goto init_failed;
1997 
1998 	r = amdgpu_device_fw_loading(adev);
1999 	if (r)
2000 		goto init_failed;
2001 
2002 	r = amdgpu_device_ip_hw_init_phase2(adev);
2003 	if (r)
2004 		goto init_failed;
2005 
2006 	/*
2007 	 * retired pages will be loaded from eeprom and reserved here,
2008 	 * it should be called after amdgpu_device_ip_hw_init_phase2  since
2009 	 * for some ASICs the RAS EEPROM code relies on SMU fully functioning
2010 	 * for I2C communication which only true at this point.
2011 	 * recovery_init may fail, but it can free all resources allocated by
2012 	 * itself and its failure should not stop amdgpu init process.
2013 	 *
2014 	 * Note: theoretically, this should be called before all vram allocations
2015 	 * to protect retired page from abusing
2016 	 */
2017 	amdgpu_ras_recovery_init(adev);
2018 
2019 	if (adev->gmc.xgmi.num_physical_nodes > 1)
2020 		amdgpu_xgmi_add_device(adev);
2021 	amdgpu_amdkfd_device_init(adev);
2022 
2023 init_failed:
2024 	if (amdgpu_sriov_vf(adev))
2025 		amdgpu_virt_release_full_gpu(adev, true);
2026 
2027 	return r;
2028 }
2029 
2030 /**
2031  * amdgpu_device_fill_reset_magic - writes reset magic to gart pointer
2032  *
2033  * @adev: amdgpu_device pointer
2034  *
2035  * Writes a reset magic value to the gart pointer in VRAM.  The driver calls
2036  * this function before a GPU reset.  If the value is retained after a
2037  * GPU reset, VRAM has not been lost.  Some GPU resets may destry VRAM contents.
2038  */
2039 static void amdgpu_device_fill_reset_magic(struct amdgpu_device *adev)
2040 {
2041 	memcpy(adev->reset_magic, adev->gart.ptr, AMDGPU_RESET_MAGIC_NUM);
2042 }
2043 
2044 /**
2045  * amdgpu_device_check_vram_lost - check if vram is valid
2046  *
2047  * @adev: amdgpu_device pointer
2048  *
2049  * Checks the reset magic value written to the gart pointer in VRAM.
2050  * The driver calls this after a GPU reset to see if the contents of
2051  * VRAM is lost or now.
2052  * returns true if vram is lost, false if not.
2053  */
2054 static bool amdgpu_device_check_vram_lost(struct amdgpu_device *adev)
2055 {
2056 	if (memcmp(adev->gart.ptr, adev->reset_magic,
2057 			AMDGPU_RESET_MAGIC_NUM))
2058 		return true;
2059 
2060 	if (!adev->in_gpu_reset)
2061 		return false;
2062 
2063 	/*
2064 	 * For all ASICs with baco/mode1 reset, the VRAM is
2065 	 * always assumed to be lost.
2066 	 */
2067 	switch (amdgpu_asic_reset_method(adev)) {
2068 	case AMD_RESET_METHOD_BACO:
2069 	case AMD_RESET_METHOD_MODE1:
2070 		return true;
2071 	default:
2072 		return false;
2073 	}
2074 }
2075 
2076 /**
2077  * amdgpu_device_set_cg_state - set clockgating for amdgpu device
2078  *
2079  * @adev: amdgpu_device pointer
2080  * @state: clockgating state (gate or ungate)
2081  *
2082  * The list of all the hardware IPs that make up the asic is walked and the
2083  * set_clockgating_state callbacks are run.
2084  * Late initialization pass enabling clockgating for hardware IPs.
2085  * Fini or suspend, pass disabling clockgating for hardware IPs.
2086  * Returns 0 on success, negative error code on failure.
2087  */
2088 
2089 static int amdgpu_device_set_cg_state(struct amdgpu_device *adev,
2090 						enum amd_clockgating_state state)
2091 {
2092 	int i, j, r;
2093 
2094 	if (amdgpu_emu_mode == 1)
2095 		return 0;
2096 
2097 	for (j = 0; j < adev->num_ip_blocks; j++) {
2098 		i = state == AMD_CG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2099 		if (!adev->ip_blocks[i].status.late_initialized)
2100 			continue;
2101 		/* skip CG for VCE/UVD, it's handled specially */
2102 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2103 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2104 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2105 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2106 		    adev->ip_blocks[i].version->funcs->set_clockgating_state) {
2107 			/* enable clockgating to save power */
2108 			r = adev->ip_blocks[i].version->funcs->set_clockgating_state((void *)adev,
2109 										     state);
2110 			if (r) {
2111 				DRM_ERROR("set_clockgating_state(gate) of IP block <%s> failed %d\n",
2112 					  adev->ip_blocks[i].version->funcs->name, r);
2113 				return r;
2114 			}
2115 		}
2116 	}
2117 
2118 	return 0;
2119 }
2120 
2121 static int amdgpu_device_set_pg_state(struct amdgpu_device *adev, enum amd_powergating_state state)
2122 {
2123 	int i, j, r;
2124 
2125 	if (amdgpu_emu_mode == 1)
2126 		return 0;
2127 
2128 	for (j = 0; j < adev->num_ip_blocks; j++) {
2129 		i = state == AMD_PG_STATE_GATE ? j : adev->num_ip_blocks - j - 1;
2130 		if (!adev->ip_blocks[i].status.late_initialized)
2131 			continue;
2132 		/* skip CG for VCE/UVD, it's handled specially */
2133 		if (adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_UVD &&
2134 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCE &&
2135 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_VCN &&
2136 		    adev->ip_blocks[i].version->type != AMD_IP_BLOCK_TYPE_JPEG &&
2137 		    adev->ip_blocks[i].version->funcs->set_powergating_state) {
2138 			/* enable powergating to save power */
2139 			r = adev->ip_blocks[i].version->funcs->set_powergating_state((void *)adev,
2140 											state);
2141 			if (r) {
2142 				DRM_ERROR("set_powergating_state(gate) of IP block <%s> failed %d\n",
2143 					  adev->ip_blocks[i].version->funcs->name, r);
2144 				return r;
2145 			}
2146 		}
2147 	}
2148 	return 0;
2149 }
2150 
2151 static int amdgpu_device_enable_mgpu_fan_boost(void)
2152 {
2153 	struct amdgpu_gpu_instance *gpu_ins;
2154 	struct amdgpu_device *adev;
2155 	int i, ret = 0;
2156 
2157 	mutex_lock(&mgpu_info.mutex);
2158 
2159 	/*
2160 	 * MGPU fan boost feature should be enabled
2161 	 * only when there are two or more dGPUs in
2162 	 * the system
2163 	 */
2164 	if (mgpu_info.num_dgpu < 2)
2165 		goto out;
2166 
2167 	for (i = 0; i < mgpu_info.num_dgpu; i++) {
2168 		gpu_ins = &(mgpu_info.gpu_ins[i]);
2169 		adev = gpu_ins->adev;
2170 		if (!(adev->flags & AMD_IS_APU) &&
2171 		    !gpu_ins->mgpu_fan_enabled &&
2172 		    adev->powerplay.pp_funcs &&
2173 		    adev->powerplay.pp_funcs->enable_mgpu_fan_boost) {
2174 			ret = amdgpu_dpm_enable_mgpu_fan_boost(adev);
2175 			if (ret)
2176 				break;
2177 
2178 			gpu_ins->mgpu_fan_enabled = 1;
2179 		}
2180 	}
2181 
2182 out:
2183 	mutex_unlock(&mgpu_info.mutex);
2184 
2185 	return ret;
2186 }
2187 
2188 /**
2189  * amdgpu_device_ip_late_init - run late init for hardware IPs
2190  *
2191  * @adev: amdgpu_device pointer
2192  *
2193  * Late initialization pass for hardware IPs.  The list of all the hardware
2194  * IPs that make up the asic is walked and the late_init callbacks are run.
2195  * late_init covers any special initialization that an IP requires
2196  * after all of the have been initialized or something that needs to happen
2197  * late in the init process.
2198  * Returns 0 on success, negative error code on failure.
2199  */
2200 static int amdgpu_device_ip_late_init(struct amdgpu_device *adev)
2201 {
2202 	struct amdgpu_gpu_instance *gpu_instance;
2203 	int i = 0, r;
2204 
2205 	for (i = 0; i < adev->num_ip_blocks; i++) {
2206 		if (!adev->ip_blocks[i].status.hw)
2207 			continue;
2208 		if (adev->ip_blocks[i].version->funcs->late_init) {
2209 			r = adev->ip_blocks[i].version->funcs->late_init((void *)adev);
2210 			if (r) {
2211 				DRM_ERROR("late_init of IP block <%s> failed %d\n",
2212 					  adev->ip_blocks[i].version->funcs->name, r);
2213 				return r;
2214 			}
2215 		}
2216 		adev->ip_blocks[i].status.late_initialized = true;
2217 	}
2218 
2219 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_GATE);
2220 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_GATE);
2221 
2222 	amdgpu_device_fill_reset_magic(adev);
2223 
2224 	r = amdgpu_device_enable_mgpu_fan_boost();
2225 	if (r)
2226 		DRM_ERROR("enable mgpu fan boost failed (%d).\n", r);
2227 
2228 
2229 	if (adev->gmc.xgmi.num_physical_nodes > 1) {
2230 		mutex_lock(&mgpu_info.mutex);
2231 
2232 		/*
2233 		 * Reset device p-state to low as this was booted with high.
2234 		 *
2235 		 * This should be performed only after all devices from the same
2236 		 * hive get initialized.
2237 		 *
2238 		 * However, it's unknown how many device in the hive in advance.
2239 		 * As this is counted one by one during devices initializations.
2240 		 *
2241 		 * So, we wait for all XGMI interlinked devices initialized.
2242 		 * This may bring some delays as those devices may come from
2243 		 * different hives. But that should be OK.
2244 		 */
2245 		if (mgpu_info.num_dgpu == adev->gmc.xgmi.num_physical_nodes) {
2246 			for (i = 0; i < mgpu_info.num_gpu; i++) {
2247 				gpu_instance = &(mgpu_info.gpu_ins[i]);
2248 				if (gpu_instance->adev->flags & AMD_IS_APU)
2249 					continue;
2250 
2251 				r = amdgpu_xgmi_set_pstate(gpu_instance->adev, 0);
2252 				if (r) {
2253 					DRM_ERROR("pstate setting failed (%d).\n", r);
2254 					break;
2255 				}
2256 			}
2257 		}
2258 
2259 		mutex_unlock(&mgpu_info.mutex);
2260 	}
2261 
2262 	return 0;
2263 }
2264 
2265 /**
2266  * amdgpu_device_ip_fini - run fini for hardware IPs
2267  *
2268  * @adev: amdgpu_device pointer
2269  *
2270  * Main teardown pass for hardware IPs.  The list of all the hardware
2271  * IPs that make up the asic is walked and the hw_fini and sw_fini callbacks
2272  * are run.  hw_fini tears down the hardware associated with each IP
2273  * and sw_fini tears down any software state associated with each IP.
2274  * Returns 0 on success, negative error code on failure.
2275  */
2276 static int amdgpu_device_ip_fini(struct amdgpu_device *adev)
2277 {
2278 	int i, r;
2279 
2280 	amdgpu_ras_pre_fini(adev);
2281 
2282 	if (adev->gmc.xgmi.num_physical_nodes > 1)
2283 		amdgpu_xgmi_remove_device(adev);
2284 
2285 	amdgpu_amdkfd_device_fini(adev);
2286 
2287 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2288 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2289 
2290 	/* need to disable SMC first */
2291 	for (i = 0; i < adev->num_ip_blocks; i++) {
2292 		if (!adev->ip_blocks[i].status.hw)
2293 			continue;
2294 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2295 			r = adev->ip_blocks[i].version->funcs->hw_fini((void *)adev);
2296 			/* XXX handle errors */
2297 			if (r) {
2298 				DRM_DEBUG("hw_fini of IP block <%s> failed %d\n",
2299 					  adev->ip_blocks[i].version->funcs->name, r);
2300 			}
2301 			adev->ip_blocks[i].status.hw = false;
2302 			break;
2303 		}
2304 	}
2305 
2306 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2307 		if (!adev->ip_blocks[i].status.hw)
2308 			continue;
2309 
2310 		r = adev->ip_blocks[i].version->funcs->hw_fini((void *)adev);
2311 		/* XXX handle errors */
2312 		if (r) {
2313 			DRM_DEBUG("hw_fini of IP block <%s> failed %d\n",
2314 				  adev->ip_blocks[i].version->funcs->name, r);
2315 		}
2316 
2317 		adev->ip_blocks[i].status.hw = false;
2318 	}
2319 
2320 
2321 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2322 		if (!adev->ip_blocks[i].status.sw)
2323 			continue;
2324 
2325 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) {
2326 			amdgpu_ucode_free_bo(adev);
2327 			amdgpu_free_static_csa(&adev->virt.csa_obj);
2328 			amdgpu_device_wb_fini(adev);
2329 			amdgpu_device_vram_scratch_fini(adev);
2330 			amdgpu_ib_pool_fini(adev);
2331 		}
2332 
2333 		r = adev->ip_blocks[i].version->funcs->sw_fini((void *)adev);
2334 		/* XXX handle errors */
2335 		if (r) {
2336 			DRM_DEBUG("sw_fini of IP block <%s> failed %d\n",
2337 				  adev->ip_blocks[i].version->funcs->name, r);
2338 		}
2339 		adev->ip_blocks[i].status.sw = false;
2340 		adev->ip_blocks[i].status.valid = false;
2341 	}
2342 
2343 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2344 		if (!adev->ip_blocks[i].status.late_initialized)
2345 			continue;
2346 		if (adev->ip_blocks[i].version->funcs->late_fini)
2347 			adev->ip_blocks[i].version->funcs->late_fini((void *)adev);
2348 		adev->ip_blocks[i].status.late_initialized = false;
2349 	}
2350 
2351 	amdgpu_ras_fini(adev);
2352 
2353 	if (amdgpu_sriov_vf(adev))
2354 		if (amdgpu_virt_release_full_gpu(adev, false))
2355 			DRM_ERROR("failed to release exclusive mode on fini\n");
2356 
2357 	return 0;
2358 }
2359 
2360 /**
2361  * amdgpu_device_delayed_init_work_handler - work handler for IB tests
2362  *
2363  * @work: work_struct.
2364  */
2365 static void amdgpu_device_delayed_init_work_handler(struct work_struct *work)
2366 {
2367 	struct amdgpu_device *adev =
2368 		container_of(work, struct amdgpu_device, delayed_init_work.work);
2369 	int r;
2370 
2371 	r = amdgpu_ib_ring_tests(adev);
2372 	if (r)
2373 		DRM_ERROR("ib ring test failed (%d).\n", r);
2374 }
2375 
2376 static void amdgpu_device_delay_enable_gfx_off(struct work_struct *work)
2377 {
2378 	struct amdgpu_device *adev =
2379 		container_of(work, struct amdgpu_device, gfx.gfx_off_delay_work.work);
2380 
2381 	mutex_lock(&adev->gfx.gfx_off_mutex);
2382 	if (!adev->gfx.gfx_off_state && !adev->gfx.gfx_off_req_count) {
2383 		if (!amdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_GFX, true))
2384 			adev->gfx.gfx_off_state = true;
2385 	}
2386 	mutex_unlock(&adev->gfx.gfx_off_mutex);
2387 }
2388 
2389 /**
2390  * amdgpu_device_ip_suspend_phase1 - run suspend for hardware IPs (phase 1)
2391  *
2392  * @adev: amdgpu_device pointer
2393  *
2394  * Main suspend function for hardware IPs.  The list of all the hardware
2395  * IPs that make up the asic is walked, clockgating is disabled and the
2396  * suspend callbacks are run.  suspend puts the hardware and software state
2397  * in each IP into a state suitable for suspend.
2398  * Returns 0 on success, negative error code on failure.
2399  */
2400 static int amdgpu_device_ip_suspend_phase1(struct amdgpu_device *adev)
2401 {
2402 	int i, r;
2403 
2404 	amdgpu_device_set_pg_state(adev, AMD_PG_STATE_UNGATE);
2405 	amdgpu_device_set_cg_state(adev, AMD_CG_STATE_UNGATE);
2406 
2407 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2408 		if (!adev->ip_blocks[i].status.valid)
2409 			continue;
2410 		/* displays are handled separately */
2411 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) {
2412 			/* XXX handle errors */
2413 			r = adev->ip_blocks[i].version->funcs->suspend(adev);
2414 			/* XXX handle errors */
2415 			if (r) {
2416 				DRM_ERROR("suspend of IP block <%s> failed %d\n",
2417 					  adev->ip_blocks[i].version->funcs->name, r);
2418 				return r;
2419 			}
2420 			adev->ip_blocks[i].status.hw = false;
2421 		}
2422 	}
2423 
2424 	return 0;
2425 }
2426 
2427 /**
2428  * amdgpu_device_ip_suspend_phase2 - run suspend for hardware IPs (phase 2)
2429  *
2430  * @adev: amdgpu_device pointer
2431  *
2432  * Main suspend function for hardware IPs.  The list of all the hardware
2433  * IPs that make up the asic is walked, clockgating is disabled and the
2434  * suspend callbacks are run.  suspend puts the hardware and software state
2435  * in each IP into a state suitable for suspend.
2436  * Returns 0 on success, negative error code on failure.
2437  */
2438 static int amdgpu_device_ip_suspend_phase2(struct amdgpu_device *adev)
2439 {
2440 	int i, r;
2441 
2442 	for (i = adev->num_ip_blocks - 1; i >= 0; i--) {
2443 		if (!adev->ip_blocks[i].status.valid)
2444 			continue;
2445 		/* displays are handled in phase1 */
2446 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE)
2447 			continue;
2448 		/* PSP lost connection when err_event_athub occurs */
2449 		if (amdgpu_ras_intr_triggered() &&
2450 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
2451 			adev->ip_blocks[i].status.hw = false;
2452 			continue;
2453 		}
2454 		/* XXX handle errors */
2455 		r = adev->ip_blocks[i].version->funcs->suspend(adev);
2456 		/* XXX handle errors */
2457 		if (r) {
2458 			DRM_ERROR("suspend of IP block <%s> failed %d\n",
2459 				  adev->ip_blocks[i].version->funcs->name, r);
2460 		}
2461 		adev->ip_blocks[i].status.hw = false;
2462 		/* handle putting the SMC in the appropriate state */
2463 		if(!amdgpu_sriov_vf(adev)){
2464 			if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) {
2465 				r = amdgpu_dpm_set_mp1_state(adev, adev->mp1_state);
2466 				if (r) {
2467 					DRM_ERROR("SMC failed to set mp1 state %d, %d\n",
2468 							adev->mp1_state, r);
2469 					return r;
2470 				}
2471 			}
2472 		}
2473 		adev->ip_blocks[i].status.hw = false;
2474 	}
2475 
2476 	return 0;
2477 }
2478 
2479 /**
2480  * amdgpu_device_ip_suspend - run suspend for hardware IPs
2481  *
2482  * @adev: amdgpu_device pointer
2483  *
2484  * Main suspend function for hardware IPs.  The list of all the hardware
2485  * IPs that make up the asic is walked, clockgating is disabled and the
2486  * suspend callbacks are run.  suspend puts the hardware and software state
2487  * in each IP into a state suitable for suspend.
2488  * Returns 0 on success, negative error code on failure.
2489  */
2490 int amdgpu_device_ip_suspend(struct amdgpu_device *adev)
2491 {
2492 	int r;
2493 
2494 	if (amdgpu_sriov_vf(adev))
2495 		amdgpu_virt_request_full_gpu(adev, false);
2496 
2497 	r = amdgpu_device_ip_suspend_phase1(adev);
2498 	if (r)
2499 		return r;
2500 	r = amdgpu_device_ip_suspend_phase2(adev);
2501 
2502 	if (amdgpu_sriov_vf(adev))
2503 		amdgpu_virt_release_full_gpu(adev, false);
2504 
2505 	return r;
2506 }
2507 
2508 static int amdgpu_device_ip_reinit_early_sriov(struct amdgpu_device *adev)
2509 {
2510 	int i, r;
2511 
2512 	static enum amd_ip_block_type ip_order[] = {
2513 		AMD_IP_BLOCK_TYPE_GMC,
2514 		AMD_IP_BLOCK_TYPE_COMMON,
2515 		AMD_IP_BLOCK_TYPE_PSP,
2516 		AMD_IP_BLOCK_TYPE_IH,
2517 	};
2518 
2519 	for (i = 0; i < ARRAY_SIZE(ip_order); i++) {
2520 		int j;
2521 		struct amdgpu_ip_block *block;
2522 
2523 		for (j = 0; j < adev->num_ip_blocks; j++) {
2524 			block = &adev->ip_blocks[j];
2525 
2526 			block->status.hw = false;
2527 			if (block->version->type != ip_order[i] ||
2528 				!block->status.valid)
2529 				continue;
2530 
2531 			r = block->version->funcs->hw_init(adev);
2532 			DRM_INFO("RE-INIT-early: %s %s\n", block->version->funcs->name, r?"failed":"succeeded");
2533 			if (r)
2534 				return r;
2535 			block->status.hw = true;
2536 		}
2537 	}
2538 
2539 	return 0;
2540 }
2541 
2542 static int amdgpu_device_ip_reinit_late_sriov(struct amdgpu_device *adev)
2543 {
2544 	int i, r;
2545 
2546 	static enum amd_ip_block_type ip_order[] = {
2547 		AMD_IP_BLOCK_TYPE_SMC,
2548 		AMD_IP_BLOCK_TYPE_DCE,
2549 		AMD_IP_BLOCK_TYPE_GFX,
2550 		AMD_IP_BLOCK_TYPE_SDMA,
2551 		AMD_IP_BLOCK_TYPE_UVD,
2552 		AMD_IP_BLOCK_TYPE_VCE,
2553 		AMD_IP_BLOCK_TYPE_VCN
2554 	};
2555 
2556 	for (i = 0; i < ARRAY_SIZE(ip_order); i++) {
2557 		int j;
2558 		struct amdgpu_ip_block *block;
2559 
2560 		for (j = 0; j < adev->num_ip_blocks; j++) {
2561 			block = &adev->ip_blocks[j];
2562 
2563 			if (block->version->type != ip_order[i] ||
2564 				!block->status.valid ||
2565 				block->status.hw)
2566 				continue;
2567 
2568 			if (block->version->type == AMD_IP_BLOCK_TYPE_SMC)
2569 				r = block->version->funcs->resume(adev);
2570 			else
2571 				r = block->version->funcs->hw_init(adev);
2572 
2573 			DRM_INFO("RE-INIT-late: %s %s\n", block->version->funcs->name, r?"failed":"succeeded");
2574 			if (r)
2575 				return r;
2576 			block->status.hw = true;
2577 		}
2578 	}
2579 
2580 	return 0;
2581 }
2582 
2583 /**
2584  * amdgpu_device_ip_resume_phase1 - run resume for hardware IPs
2585  *
2586  * @adev: amdgpu_device pointer
2587  *
2588  * First resume function for hardware IPs.  The list of all the hardware
2589  * IPs that make up the asic is walked and the resume callbacks are run for
2590  * COMMON, GMC, and IH.  resume puts the hardware into a functional state
2591  * after a suspend and updates the software state as necessary.  This
2592  * function is also used for restoring the GPU after a GPU reset.
2593  * Returns 0 on success, negative error code on failure.
2594  */
2595 static int amdgpu_device_ip_resume_phase1(struct amdgpu_device *adev)
2596 {
2597 	int i, r;
2598 
2599 	for (i = 0; i < adev->num_ip_blocks; i++) {
2600 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
2601 			continue;
2602 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2603 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
2604 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH) {
2605 
2606 			r = adev->ip_blocks[i].version->funcs->resume(adev);
2607 			if (r) {
2608 				DRM_ERROR("resume of IP block <%s> failed %d\n",
2609 					  adev->ip_blocks[i].version->funcs->name, r);
2610 				return r;
2611 			}
2612 			adev->ip_blocks[i].status.hw = true;
2613 		}
2614 	}
2615 
2616 	return 0;
2617 }
2618 
2619 /**
2620  * amdgpu_device_ip_resume_phase2 - run resume for hardware IPs
2621  *
2622  * @adev: amdgpu_device pointer
2623  *
2624  * First resume function for hardware IPs.  The list of all the hardware
2625  * IPs that make up the asic is walked and the resume callbacks are run for
2626  * all blocks except COMMON, GMC, and IH.  resume puts the hardware into a
2627  * functional state after a suspend and updates the software state as
2628  * necessary.  This function is also used for restoring the GPU after a GPU
2629  * reset.
2630  * Returns 0 on success, negative error code on failure.
2631  */
2632 static int amdgpu_device_ip_resume_phase2(struct amdgpu_device *adev)
2633 {
2634 	int i, r;
2635 
2636 	for (i = 0; i < adev->num_ip_blocks; i++) {
2637 		if (!adev->ip_blocks[i].status.valid || adev->ip_blocks[i].status.hw)
2638 			continue;
2639 		if (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_COMMON ||
2640 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC ||
2641 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_IH ||
2642 		    adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP)
2643 			continue;
2644 		r = adev->ip_blocks[i].version->funcs->resume(adev);
2645 		if (r) {
2646 			DRM_ERROR("resume of IP block <%s> failed %d\n",
2647 				  adev->ip_blocks[i].version->funcs->name, r);
2648 			return r;
2649 		}
2650 		adev->ip_blocks[i].status.hw = true;
2651 	}
2652 
2653 	return 0;
2654 }
2655 
2656 /**
2657  * amdgpu_device_ip_resume - run resume for hardware IPs
2658  *
2659  * @adev: amdgpu_device pointer
2660  *
2661  * Main resume function for hardware IPs.  The hardware IPs
2662  * are split into two resume functions because they are
2663  * are also used in in recovering from a GPU reset and some additional
2664  * steps need to be take between them.  In this case (S3/S4) they are
2665  * run sequentially.
2666  * Returns 0 on success, negative error code on failure.
2667  */
2668 static int amdgpu_device_ip_resume(struct amdgpu_device *adev)
2669 {
2670 	int r;
2671 
2672 	r = amdgpu_device_ip_resume_phase1(adev);
2673 	if (r)
2674 		return r;
2675 
2676 	r = amdgpu_device_fw_loading(adev);
2677 	if (r)
2678 		return r;
2679 
2680 	r = amdgpu_device_ip_resume_phase2(adev);
2681 
2682 	return r;
2683 }
2684 
2685 /**
2686  * amdgpu_device_detect_sriov_bios - determine if the board supports SR-IOV
2687  *
2688  * @adev: amdgpu_device pointer
2689  *
2690  * Query the VBIOS data tables to determine if the board supports SR-IOV.
2691  */
2692 static void amdgpu_device_detect_sriov_bios(struct amdgpu_device *adev)
2693 {
2694 	if (amdgpu_sriov_vf(adev)) {
2695 		if (adev->is_atom_fw) {
2696 			if (amdgpu_atomfirmware_gpu_supports_virtualization(adev))
2697 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
2698 		} else {
2699 			if (amdgpu_atombios_has_gpu_virtualization_table(adev))
2700 				adev->virt.caps |= AMDGPU_SRIOV_CAPS_SRIOV_VBIOS;
2701 		}
2702 
2703 		if (!(adev->virt.caps & AMDGPU_SRIOV_CAPS_SRIOV_VBIOS))
2704 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_NO_VBIOS, 0, 0);
2705 	}
2706 }
2707 
2708 /**
2709  * amdgpu_device_asic_has_dc_support - determine if DC supports the asic
2710  *
2711  * @asic_type: AMD asic type
2712  *
2713  * Check if there is DC (new modesetting infrastructre) support for an asic.
2714  * returns true if DC has support, false if not.
2715  */
2716 bool amdgpu_device_asic_has_dc_support(enum amd_asic_type asic_type)
2717 {
2718 	switch (asic_type) {
2719 #if defined(CONFIG_DRM_AMD_DC)
2720 	case CHIP_BONAIRE:
2721 	case CHIP_KAVERI:
2722 	case CHIP_KABINI:
2723 	case CHIP_MULLINS:
2724 		/*
2725 		 * We have systems in the wild with these ASICs that require
2726 		 * LVDS and VGA support which is not supported with DC.
2727 		 *
2728 		 * Fallback to the non-DC driver here by default so as not to
2729 		 * cause regressions.
2730 		 */
2731 		return amdgpu_dc > 0;
2732 	case CHIP_HAWAII:
2733 	case CHIP_CARRIZO:
2734 	case CHIP_STONEY:
2735 	case CHIP_POLARIS10:
2736 	case CHIP_POLARIS11:
2737 	case CHIP_POLARIS12:
2738 	case CHIP_VEGAM:
2739 	case CHIP_TONGA:
2740 	case CHIP_FIJI:
2741 	case CHIP_VEGA10:
2742 	case CHIP_VEGA12:
2743 	case CHIP_VEGA20:
2744 #if defined(CONFIG_DRM_AMD_DC_DCN)
2745 	case CHIP_RAVEN:
2746 	case CHIP_NAVI10:
2747 	case CHIP_NAVI14:
2748 	case CHIP_NAVI12:
2749 	case CHIP_RENOIR:
2750 #endif
2751 		return amdgpu_dc != 0;
2752 #endif
2753 	default:
2754 		if (amdgpu_dc > 0)
2755 			DRM_INFO("Display Core has been requested via kernel parameter "
2756 					 "but isn't supported by ASIC, ignoring\n");
2757 		return false;
2758 	}
2759 }
2760 
2761 /**
2762  * amdgpu_device_has_dc_support - check if dc is supported
2763  *
2764  * @adev: amdgpu_device_pointer
2765  *
2766  * Returns true for supported, false for not supported
2767  */
2768 bool amdgpu_device_has_dc_support(struct amdgpu_device *adev)
2769 {
2770 	if (amdgpu_sriov_vf(adev))
2771 		return false;
2772 
2773 	return amdgpu_device_asic_has_dc_support(adev->asic_type);
2774 }
2775 
2776 
2777 static void amdgpu_device_xgmi_reset_func(struct work_struct *__work)
2778 {
2779 	struct amdgpu_device *adev =
2780 		container_of(__work, struct amdgpu_device, xgmi_reset_work);
2781 	struct amdgpu_hive_info *hive = amdgpu_get_xgmi_hive(adev, 0);
2782 
2783 	/* It's a bug to not have a hive within this function */
2784 	if (WARN_ON(!hive))
2785 		return;
2786 
2787 	/*
2788 	 * Use task barrier to synchronize all xgmi reset works across the
2789 	 * hive. task_barrier_enter and task_barrier_exit will block
2790 	 * until all the threads running the xgmi reset works reach
2791 	 * those points. task_barrier_full will do both blocks.
2792 	 */
2793 	if (amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) {
2794 
2795 		task_barrier_enter(&hive->tb);
2796 		adev->asic_reset_res = amdgpu_device_baco_enter(adev->ddev);
2797 
2798 		if (adev->asic_reset_res)
2799 			goto fail;
2800 
2801 		task_barrier_exit(&hive->tb);
2802 		adev->asic_reset_res = amdgpu_device_baco_exit(adev->ddev);
2803 
2804 		if (adev->asic_reset_res)
2805 			goto fail;
2806 
2807 		if (adev->mmhub.funcs && adev->mmhub.funcs->reset_ras_error_count)
2808 			adev->mmhub.funcs->reset_ras_error_count(adev);
2809 	} else {
2810 
2811 		task_barrier_full(&hive->tb);
2812 		adev->asic_reset_res =  amdgpu_asic_reset(adev);
2813 	}
2814 
2815 fail:
2816 	if (adev->asic_reset_res)
2817 		DRM_WARN("ASIC reset failed with error, %d for drm dev, %s",
2818 			 adev->asic_reset_res, adev->ddev->unique);
2819 }
2820 
2821 static int amdgpu_device_get_job_timeout_settings(struct amdgpu_device *adev)
2822 {
2823 	char *input = amdgpu_lockup_timeout;
2824 	char *timeout_setting = NULL;
2825 	int index = 0;
2826 	long timeout;
2827 	int ret = 0;
2828 
2829 	/*
2830 	 * By default timeout for non compute jobs is 10000.
2831 	 * And there is no timeout enforced on compute jobs.
2832 	 * In SR-IOV or passthrough mode, timeout for compute
2833 	 * jobs are 10000 by default.
2834 	 */
2835 	adev->gfx_timeout = msecs_to_jiffies(10000);
2836 	adev->sdma_timeout = adev->video_timeout = adev->gfx_timeout;
2837 	if (amdgpu_sriov_vf(adev) || amdgpu_passthrough(adev))
2838 		adev->compute_timeout = adev->gfx_timeout;
2839 	else
2840 		adev->compute_timeout = MAX_SCHEDULE_TIMEOUT;
2841 
2842 #ifdef notyet
2843 	if (strnlen(input, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
2844 		while ((timeout_setting = strsep(&input, ",")) &&
2845 				strnlen(timeout_setting, AMDGPU_MAX_TIMEOUT_PARAM_LENGTH)) {
2846 			ret = kstrtol(timeout_setting, 0, &timeout);
2847 			if (ret)
2848 				return ret;
2849 
2850 			if (timeout == 0) {
2851 				index++;
2852 				continue;
2853 			} else if (timeout < 0) {
2854 				timeout = MAX_SCHEDULE_TIMEOUT;
2855 			} else {
2856 				timeout = msecs_to_jiffies(timeout);
2857 			}
2858 
2859 			switch (index++) {
2860 			case 0:
2861 				adev->gfx_timeout = timeout;
2862 				break;
2863 			case 1:
2864 				adev->compute_timeout = timeout;
2865 				break;
2866 			case 2:
2867 				adev->sdma_timeout = timeout;
2868 				break;
2869 			case 3:
2870 				adev->video_timeout = timeout;
2871 				break;
2872 			default:
2873 				break;
2874 			}
2875 		}
2876 		/*
2877 		 * There is only one value specified and
2878 		 * it should apply to all non-compute jobs.
2879 		 */
2880 		if (index == 1) {
2881 			adev->sdma_timeout = adev->video_timeout = adev->gfx_timeout;
2882 			if (amdgpu_sriov_vf(adev) || amdgpu_passthrough(adev))
2883 				adev->compute_timeout = adev->gfx_timeout;
2884 		}
2885 	}
2886 #endif
2887 
2888 	return ret;
2889 }
2890 
2891 /**
2892  * amdgpu_device_init - initialize the driver
2893  *
2894  * @adev: amdgpu_device pointer
2895  * @ddev: drm dev pointer
2896  * @pdev: pci dev pointer
2897  * @flags: driver flags
2898  *
2899  * Initializes the driver info and hw (all asics).
2900  * Returns 0 for success or an error on failure.
2901  * Called at driver startup.
2902  */
2903 int amdgpu_device_init(struct amdgpu_device *adev,
2904 		       struct drm_device *ddev,
2905 		       struct pci_dev *pdev,
2906 		       uint32_t flags)
2907 {
2908 	int r, i;
2909 	bool boco = false;
2910 	u32 max_MBps;
2911 
2912 	adev->shutdown = false;
2913 #ifdef __linux__
2914 	adev->dev = &pdev->dev;
2915 #endif
2916 	adev->ddev = ddev;
2917 	adev->pdev = pdev;
2918 	adev->flags = flags;
2919 
2920 	if (amdgpu_force_asic_type >= 0 && amdgpu_force_asic_type < CHIP_LAST)
2921 		adev->asic_type = amdgpu_force_asic_type;
2922 	else
2923 		adev->asic_type = flags & AMD_ASIC_MASK;
2924 
2925 	adev->usec_timeout = AMDGPU_MAX_USEC_TIMEOUT;
2926 	if (amdgpu_emu_mode == 1)
2927 		adev->usec_timeout *= 10;
2928 	adev->gmc.gart_size = 512 * 1024 * 1024;
2929 	adev->accel_working = false;
2930 	adev->num_rings = 0;
2931 	adev->mman.buffer_funcs = NULL;
2932 	adev->mman.buffer_funcs_ring = NULL;
2933 	adev->vm_manager.vm_pte_funcs = NULL;
2934 	adev->vm_manager.vm_pte_num_scheds = 0;
2935 	adev->gmc.gmc_funcs = NULL;
2936 	adev->fence_context = dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2937 	bitmap_zero(adev->gfx.pipe_reserve_bitmap, AMDGPU_MAX_COMPUTE_QUEUES);
2938 
2939 	adev->smc_rreg = &amdgpu_invalid_rreg;
2940 	adev->smc_wreg = &amdgpu_invalid_wreg;
2941 	adev->pcie_rreg = &amdgpu_invalid_rreg;
2942 	adev->pcie_wreg = &amdgpu_invalid_wreg;
2943 	adev->pciep_rreg = &amdgpu_invalid_rreg;
2944 	adev->pciep_wreg = &amdgpu_invalid_wreg;
2945 	adev->pcie_rreg64 = &amdgpu_invalid_rreg64;
2946 	adev->pcie_wreg64 = &amdgpu_invalid_wreg64;
2947 	adev->uvd_ctx_rreg = &amdgpu_invalid_rreg;
2948 	adev->uvd_ctx_wreg = &amdgpu_invalid_wreg;
2949 	adev->didt_rreg = &amdgpu_invalid_rreg;
2950 	adev->didt_wreg = &amdgpu_invalid_wreg;
2951 	adev->gc_cac_rreg = &amdgpu_invalid_rreg;
2952 	adev->gc_cac_wreg = &amdgpu_invalid_wreg;
2953 	adev->audio_endpt_rreg = &amdgpu_block_invalid_rreg;
2954 	adev->audio_endpt_wreg = &amdgpu_block_invalid_wreg;
2955 
2956 	DRM_INFO("initializing kernel modesetting (%s 0x%04X:0x%04X 0x%04X:0x%04X 0x%02X).\n",
2957 		 amdgpu_asic_name[adev->asic_type], pdev->vendor, pdev->device,
2958 		 pdev->subsystem_vendor, pdev->subsystem_device, pdev->revision);
2959 
2960 	/* mutex initialization are all done here so we
2961 	 * can recall function without having locking issues */
2962 	atomic_set(&adev->irq.ih.lock, 0);
2963 	rw_init(&adev->firmware.mutex, "agfw");
2964 	rw_init(&adev->pm.mutex, "agpm");
2965 	rw_init(&adev->gfx.gpu_clock_mutex, "gfxclk");
2966 	rw_init(&adev->srbm_mutex, "srbm");
2967 	rw_init(&adev->gfx.pipe_reserve_mutex, "pipers");
2968 	rw_init(&adev->gfx.gfx_off_mutex, "gfxoff");
2969 	rw_init(&adev->grbm_idx_mutex, "grbmidx");
2970 	rw_init(&adev->mn_lock, "agpumn");
2971 	rw_init(&adev->virt.vf_errors.lock, "vferr");
2972 	hash_init(adev->mn_hash);
2973 	rw_init(&adev->lock_reset, "aglkrst");
2974 	rw_init(&adev->psp.mutex, "agpsp");
2975 	rw_init(&adev->notifier_lock, "agnf");
2976 
2977 	r = amdgpu_device_check_arguments(adev);
2978 	if (r)
2979 		return r;
2980 
2981 	mtx_init(&adev->mmio_idx_lock, IPL_TTY);
2982 	mtx_init(&adev->smc_idx_lock, IPL_TTY);
2983 	mtx_init(&adev->pcie_idx_lock, IPL_TTY);
2984 	mtx_init(&adev->uvd_ctx_idx_lock, IPL_TTY);
2985 	mtx_init(&adev->didt_idx_lock, IPL_TTY);
2986 	mtx_init(&adev->gc_cac_idx_lock, IPL_TTY);
2987 	mtx_init(&adev->se_cac_idx_lock, IPL_TTY);
2988 	mtx_init(&adev->audio_endpt_idx_lock, IPL_TTY);
2989 	mtx_init(&adev->mm_stats.lock, IPL_NONE);
2990 
2991 	INIT_LIST_HEAD(&adev->shadow_list);
2992 	rw_init(&adev->shadow_list_lock, "sdwlst");
2993 
2994 	INIT_LIST_HEAD(&adev->ring_lru_list);
2995 	mtx_init(&adev->ring_lru_list_lock, IPL_NONE);
2996 
2997 	INIT_DELAYED_WORK(&adev->delayed_init_work,
2998 			  amdgpu_device_delayed_init_work_handler);
2999 	INIT_DELAYED_WORK(&adev->gfx.gfx_off_delay_work,
3000 			  amdgpu_device_delay_enable_gfx_off);
3001 
3002 	INIT_WORK(&adev->xgmi_reset_work, amdgpu_device_xgmi_reset_func);
3003 
3004 	adev->gfx.gfx_off_req_count = 1;
3005 	adev->pm.ac_power = power_supply_is_system_supplied() > 0 ? true : false;
3006 
3007 #ifdef __linux__
3008 	/* Registers mapping */
3009 	/* TODO: block userspace mapping of io register */
3010 	if (adev->asic_type >= CHIP_BONAIRE) {
3011 		adev->rmmio_base = pci_resource_start(adev->pdev, 5);
3012 		adev->rmmio_size = pci_resource_len(adev->pdev, 5);
3013 	} else {
3014 		adev->rmmio_base = pci_resource_start(adev->pdev, 2);
3015 		adev->rmmio_size = pci_resource_len(adev->pdev, 2);
3016 	}
3017 
3018 	adev->rmmio = ioremap(adev->rmmio_base, adev->rmmio_size);
3019 	if (adev->rmmio == NULL) {
3020 		return -ENOMEM;
3021 	}
3022 #endif
3023 	DRM_INFO("register mmio base: 0x%08X\n", (uint32_t)adev->rmmio_base);
3024 	DRM_INFO("register mmio size: %u\n", (unsigned)adev->rmmio_size);
3025 
3026 	/* io port mapping */
3027 #ifdef __linux__
3028 	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3029 		if (pci_resource_flags(adev->pdev, i) & IORESOURCE_IO) {
3030 			adev->rio_mem_size = pci_resource_len(adev->pdev, i);
3031 			adev->rio_mem = pci_iomap(adev->pdev, i, adev->rio_mem_size);
3032 			break;
3033 		}
3034 	}
3035 	if (adev->rio_mem == NULL)
3036 		DRM_INFO("PCI I/O BAR is not found.\n");
3037 #endif
3038 
3039 	/* enable PCIE atomic ops */
3040 #ifdef notyet
3041 	r = pci_enable_atomic_ops_to_root(adev->pdev,
3042 					  PCI_EXP_DEVCAP2_ATOMIC_COMP32 |
3043 					  PCI_EXP_DEVCAP2_ATOMIC_COMP64);
3044 	if (r) {
3045 		adev->have_atomics_support = false;
3046 		DRM_INFO("PCIE atomic ops is not supported\n");
3047 	} else {
3048 		adev->have_atomics_support = true;
3049 	}
3050 #else
3051 	adev->have_atomics_support = false;
3052 #endif
3053 
3054 	amdgpu_device_get_pcie_info(adev);
3055 
3056 	if (amdgpu_mcbp)
3057 		DRM_INFO("MCBP is enabled\n");
3058 
3059 	if (amdgpu_mes && adev->asic_type >= CHIP_NAVI10)
3060 		adev->enable_mes = true;
3061 
3062 	if (amdgpu_discovery && adev->asic_type >= CHIP_NAVI10) {
3063 		r = amdgpu_discovery_init(adev);
3064 		if (r) {
3065 			dev_err(adev->dev, "amdgpu_discovery_init failed\n");
3066 			return r;
3067 		}
3068 	}
3069 
3070 	/* early init functions */
3071 	r = amdgpu_device_ip_early_init(adev);
3072 	if (r)
3073 		return r;
3074 
3075 	r = amdgpu_device_get_job_timeout_settings(adev);
3076 	if (r) {
3077 		dev_err(adev->dev, "invalid lockup_timeout parameter syntax\n");
3078 		return r;
3079 	}
3080 
3081 	/* doorbell bar mapping and doorbell index init*/
3082 	amdgpu_device_doorbell_init(adev);
3083 
3084 	/* if we have > 1 VGA cards, then disable the amdgpu VGA resources */
3085 	/* this will fail for cards that aren't VGA class devices, just
3086 	 * ignore it */
3087 #ifdef notyet
3088 	vga_client_register(adev->pdev, adev, NULL, amdgpu_device_vga_set_decode);
3089 #endif
3090 
3091 	if (amdgpu_device_supports_boco(ddev))
3092 		boco = true;
3093 	if (amdgpu_has_atpx() &&
3094 	    (amdgpu_is_atpx_hybrid() ||
3095 	     amdgpu_has_atpx_dgpu_power_cntl()) &&
3096 	    !pci_is_thunderbolt_attached(adev->pdev))
3097 		vga_switcheroo_register_client(adev->pdev,
3098 					       &amdgpu_switcheroo_ops, boco);
3099 	if (boco)
3100 		vga_switcheroo_init_domain_pm_ops(adev->dev, &adev->vga_pm_domain);
3101 
3102 	if (amdgpu_emu_mode == 1) {
3103 		/* post the asic on emulation mode */
3104 		emu_soc_asic_init(adev);
3105 		goto fence_driver_init;
3106 	}
3107 
3108 	/* detect if we are with an SRIOV vbios */
3109 	amdgpu_device_detect_sriov_bios(adev);
3110 
3111 	/* check if we need to reset the asic
3112 	 *  E.g., driver was not cleanly unloaded previously, etc.
3113 	 */
3114 	if (!amdgpu_sriov_vf(adev) && amdgpu_asic_need_reset_on_init(adev)) {
3115 		r = amdgpu_asic_reset(adev);
3116 		if (r) {
3117 			dev_err(adev->dev, "asic reset on init failed\n");
3118 			goto failed;
3119 		}
3120 	}
3121 
3122 	/* Post card if necessary */
3123 	if (amdgpu_device_need_post(adev)) {
3124 		if (!adev->bios) {
3125 			dev_err(adev->dev, "no vBIOS found\n");
3126 			r = -EINVAL;
3127 			goto failed;
3128 		}
3129 		DRM_INFO("GPU posting now...\n");
3130 		r = amdgpu_atom_asic_init(adev->mode_info.atom_context);
3131 		if (r) {
3132 			dev_err(adev->dev, "gpu post error!\n");
3133 			goto failed;
3134 		}
3135 	}
3136 
3137 	if (adev->is_atom_fw) {
3138 		/* Initialize clocks */
3139 		r = amdgpu_atomfirmware_get_clock_info(adev);
3140 		if (r) {
3141 			dev_err(adev->dev, "amdgpu_atomfirmware_get_clock_info failed\n");
3142 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
3143 			goto failed;
3144 		}
3145 	} else {
3146 		/* Initialize clocks */
3147 		r = amdgpu_atombios_get_clock_info(adev);
3148 		if (r) {
3149 			dev_err(adev->dev, "amdgpu_atombios_get_clock_info failed\n");
3150 			amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_ATOMBIOS_GET_CLOCK_FAIL, 0, 0);
3151 			goto failed;
3152 		}
3153 		/* init i2c buses */
3154 		if (!amdgpu_device_has_dc_support(adev))
3155 			amdgpu_atombios_i2c_init(adev);
3156 	}
3157 
3158 fence_driver_init:
3159 	/* Fence driver */
3160 	r = amdgpu_fence_driver_init(adev);
3161 	if (r) {
3162 		dev_err(adev->dev, "amdgpu_fence_driver_init failed\n");
3163 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_FENCE_INIT_FAIL, 0, 0);
3164 		goto failed;
3165 	}
3166 
3167 	/* init the mode config */
3168 	drm_mode_config_init(adev->ddev);
3169 
3170 	r = amdgpu_device_ip_init(adev);
3171 	if (r) {
3172 		/* failed in exclusive mode due to timeout */
3173 		if (amdgpu_sriov_vf(adev) &&
3174 		    !amdgpu_sriov_runtime(adev) &&
3175 		    amdgpu_virt_mmio_blocked(adev) &&
3176 		    !amdgpu_virt_wait_reset(adev)) {
3177 			dev_err(adev->dev, "VF exclusive mode timeout\n");
3178 			/* Don't send request since VF is inactive. */
3179 			adev->virt.caps &= ~AMDGPU_SRIOV_CAPS_RUNTIME;
3180 			adev->virt.ops = NULL;
3181 			r = -EAGAIN;
3182 			goto failed;
3183 		}
3184 		dev_err(adev->dev, "amdgpu_device_ip_init failed\n");
3185 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_INIT_FAIL, 0, 0);
3186 		goto failed;
3187 	}
3188 
3189 	DRM_DEBUG("SE %d, SH per SE %d, CU per SH %d, active_cu_number %d\n",
3190 			adev->gfx.config.max_shader_engines,
3191 			adev->gfx.config.max_sh_per_se,
3192 			adev->gfx.config.max_cu_per_sh,
3193 			adev->gfx.cu_info.number);
3194 
3195 #ifdef __OpenBSD__
3196 {
3197 	const char *chip_name;
3198 
3199 	switch (adev->asic_type) {
3200 	case CHIP_RAVEN:
3201 		if (adev->rev_id >= 8)
3202 			chip_name = "RAVEN2";
3203 		else if (adev->pdev->device == 0x15d8)
3204 			chip_name = "PICASSO";
3205 		else
3206 			chip_name = "RAVEN";
3207 		break;
3208 	default:
3209 		chip_name = amdgpu_asic_name[adev->asic_type];
3210 	}
3211 	printf("%s: %s %d CU rev 0x%02x\n", adev->self.dv_xname,
3212 	    chip_name, adev->gfx.cu_info.number, adev->rev_id);
3213 }
3214 #endif
3215 
3216 	amdgpu_ctx_init_sched(adev);
3217 
3218 	adev->accel_working = true;
3219 
3220 	amdgpu_vm_check_compute_bug(adev);
3221 
3222 	/* Initialize the buffer migration limit. */
3223 	if (amdgpu_moverate >= 0)
3224 		max_MBps = amdgpu_moverate;
3225 	else
3226 		max_MBps = 8; /* Allow 8 MB/s. */
3227 	/* Get a log2 for easy divisions. */
3228 	adev->mm_stats.log2_max_MBps = ilog2(max(1u, max_MBps));
3229 
3230 	amdgpu_fbdev_init(adev);
3231 
3232 	r = amdgpu_pm_sysfs_init(adev);
3233 	if (r) {
3234 		adev->pm_sysfs_en = false;
3235 		DRM_ERROR("registering pm debugfs failed (%d).\n", r);
3236 	} else
3237 		adev->pm_sysfs_en = true;
3238 
3239 	r = amdgpu_ucode_sysfs_init(adev);
3240 	if (r) {
3241 		adev->ucode_sysfs_en = false;
3242 		DRM_ERROR("Creating firmware sysfs failed (%d).\n", r);
3243 	} else
3244 		adev->ucode_sysfs_en = true;
3245 
3246 	if ((amdgpu_testing & 1)) {
3247 		if (adev->accel_working)
3248 			amdgpu_test_moves(adev);
3249 		else
3250 			DRM_INFO("amdgpu: acceleration disabled, skipping move tests\n");
3251 	}
3252 	if (amdgpu_benchmarking) {
3253 		if (adev->accel_working)
3254 			amdgpu_benchmark(adev, amdgpu_benchmarking);
3255 		else
3256 			DRM_INFO("amdgpu: acceleration disabled, skipping benchmarks\n");
3257 	}
3258 
3259 	/*
3260 	 * Register gpu instance before amdgpu_device_enable_mgpu_fan_boost.
3261 	 * Otherwise the mgpu fan boost feature will be skipped due to the
3262 	 * gpu instance is counted less.
3263 	 */
3264 	amdgpu_register_gpu_instance(adev);
3265 
3266 	/* enable clockgating, etc. after ib tests, etc. since some blocks require
3267 	 * explicit gating rather than handling it automatically.
3268 	 */
3269 	r = amdgpu_device_ip_late_init(adev);
3270 	if (r) {
3271 		dev_err(adev->dev, "amdgpu_device_ip_late_init failed\n");
3272 		amdgpu_vf_error_put(adev, AMDGIM_ERROR_VF_AMDGPU_LATE_INIT_FAIL, 0, r);
3273 		goto failed;
3274 	}
3275 
3276 	/* must succeed. */
3277 	amdgpu_ras_resume(adev);
3278 
3279 	queue_delayed_work(system_wq, &adev->delayed_init_work,
3280 			   msecs_to_jiffies(AMDGPU_RESUME_MS));
3281 
3282 	r = device_create_file(adev->dev, &dev_attr_pcie_replay_count);
3283 	if (r) {
3284 		dev_err(adev->dev, "Could not create pcie_replay_count");
3285 		return r;
3286 	}
3287 
3288 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
3289 		r = amdgpu_pmu_init(adev);
3290 	if (r)
3291 		dev_err(adev->dev, "amdgpu_pmu_init failed\n");
3292 
3293 	return 0;
3294 
3295 failed:
3296 	amdgpu_vf_error_trans_all(adev);
3297 	if (boco)
3298 		vga_switcheroo_fini_domain_pm_ops(adev->dev);
3299 
3300 	return r;
3301 }
3302 
3303 /**
3304  * amdgpu_device_fini - tear down the driver
3305  *
3306  * @adev: amdgpu_device pointer
3307  *
3308  * Tear down the driver info (all asics).
3309  * Called at driver shutdown.
3310  */
3311 void amdgpu_device_fini(struct amdgpu_device *adev)
3312 {
3313 	int r;
3314 
3315 	DRM_INFO("amdgpu: finishing device.\n");
3316 	flush_delayed_work(&adev->delayed_init_work);
3317 	adev->shutdown = true;
3318 
3319 	/* make sure IB test finished before entering exclusive mode
3320 	 * to avoid preemption on IB test
3321 	 * */
3322 	if (amdgpu_sriov_vf(adev))
3323 		amdgpu_virt_request_full_gpu(adev, false);
3324 
3325 	/* disable all interrupts */
3326 	amdgpu_irq_disable_all(adev);
3327 	if (adev->mode_info.mode_config_initialized){
3328 		if (!amdgpu_device_has_dc_support(adev))
3329 			drm_helper_force_disable_all(adev->ddev);
3330 		else
3331 			drm_atomic_helper_shutdown(adev->ddev);
3332 	}
3333 	amdgpu_fence_driver_fini(adev);
3334 	if (adev->pm_sysfs_en)
3335 		amdgpu_pm_sysfs_fini(adev);
3336 	amdgpu_fbdev_fini(adev);
3337 	r = amdgpu_device_ip_fini(adev);
3338 	if (adev->firmware.gpu_info_fw) {
3339 		release_firmware(adev->firmware.gpu_info_fw);
3340 		adev->firmware.gpu_info_fw = NULL;
3341 	}
3342 	adev->accel_working = false;
3343 	/* free i2c buses */
3344 	if (!amdgpu_device_has_dc_support(adev))
3345 		amdgpu_i2c_fini(adev);
3346 
3347 	if (amdgpu_emu_mode != 1)
3348 		amdgpu_atombios_fini(adev);
3349 
3350 	kfree(adev->bios);
3351 	adev->bios = NULL;
3352 	if (amdgpu_has_atpx() &&
3353 	    (amdgpu_is_atpx_hybrid() ||
3354 	     amdgpu_has_atpx_dgpu_power_cntl()) &&
3355 	    !pci_is_thunderbolt_attached(adev->pdev))
3356 		vga_switcheroo_unregister_client(adev->pdev);
3357 	if (amdgpu_device_supports_boco(adev->ddev))
3358 		vga_switcheroo_fini_domain_pm_ops(adev->dev);
3359 	vga_client_register(adev->pdev, NULL, NULL, NULL);
3360 #ifdef __linux__
3361 	if (adev->rio_mem)
3362 		pci_iounmap(adev->pdev, adev->rio_mem);
3363 	adev->rio_mem = NULL;
3364 	iounmap(adev->rmmio);
3365 	adev->rmmio = NULL;
3366 #else
3367 	if (adev->rio_mem_size > 0)
3368 		bus_space_unmap(adev->rio_mem_bst, adev->rio_mem_bsh,
3369 		    adev->rio_mem_size);
3370 	adev->rio_mem_size = 0;
3371 
3372 	if (adev->rmmio_size > 0)
3373 		bus_space_unmap(adev->rmmio_bst, adev->rmmio_bsh,
3374 		    adev->rmmio_size);
3375 	adev->rmmio_size = 0;
3376 #endif
3377 	amdgpu_device_doorbell_fini(adev);
3378 
3379 	device_remove_file(adev->dev, &dev_attr_pcie_replay_count);
3380 	if (adev->ucode_sysfs_en)
3381 		amdgpu_ucode_sysfs_fini(adev);
3382 	if (IS_ENABLED(CONFIG_PERF_EVENTS))
3383 		amdgpu_pmu_fini(adev);
3384 	if (amdgpu_discovery && adev->asic_type >= CHIP_NAVI10)
3385 		amdgpu_discovery_fini(adev);
3386 }
3387 
3388 
3389 /*
3390  * Suspend & resume.
3391  */
3392 /**
3393  * amdgpu_device_suspend - initiate device suspend
3394  *
3395  * @dev: drm dev pointer
3396  * @suspend: suspend state
3397  * @fbcon : notify the fbdev of suspend
3398  *
3399  * Puts the hw in the suspend state (all asics).
3400  * Returns 0 for success or an error on failure.
3401  * Called at driver suspend.
3402  */
3403 int amdgpu_device_suspend(struct drm_device *dev, bool fbcon)
3404 {
3405 	struct amdgpu_device *adev;
3406 	struct drm_crtc *crtc;
3407 	struct drm_connector *connector;
3408 	struct drm_connector_list_iter iter;
3409 	int r;
3410 
3411 	if (dev == NULL || dev->dev_private == NULL) {
3412 		return -ENODEV;
3413 	}
3414 
3415 	adev = dev->dev_private;
3416 	if (adev->shutdown)
3417 		return 0;
3418 
3419 #ifdef notyet
3420 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
3421 		return 0;
3422 #endif
3423 
3424 	adev->in_suspend = true;
3425 	drm_kms_helper_poll_disable(dev);
3426 
3427 	if (fbcon)
3428 		amdgpu_fbdev_set_suspend(adev, 1);
3429 
3430 	cancel_delayed_work_sync(&adev->delayed_init_work);
3431 
3432 	if (!amdgpu_device_has_dc_support(adev)) {
3433 		/* turn off display hw */
3434 		drm_modeset_lock_all(dev);
3435 		drm_connector_list_iter_begin(dev, &iter);
3436 		drm_for_each_connector_iter(connector, &iter)
3437 			drm_helper_connector_dpms(connector,
3438 						  DRM_MODE_DPMS_OFF);
3439 		drm_connector_list_iter_end(&iter);
3440 		drm_modeset_unlock_all(dev);
3441 			/* unpin the front buffers and cursors */
3442 		list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
3443 			struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3444 			struct drm_framebuffer *fb = crtc->primary->fb;
3445 			struct amdgpu_bo *robj;
3446 
3447 			if (amdgpu_crtc->cursor_bo && !adev->enable_virtual_display) {
3448 				struct amdgpu_bo *aobj = gem_to_amdgpu_bo(amdgpu_crtc->cursor_bo);
3449 				r = amdgpu_bo_reserve(aobj, true);
3450 				if (r == 0) {
3451 					amdgpu_bo_unpin(aobj);
3452 					amdgpu_bo_unreserve(aobj);
3453 				}
3454 			}
3455 
3456 			if (fb == NULL || fb->obj[0] == NULL) {
3457 				continue;
3458 			}
3459 			robj = gem_to_amdgpu_bo(fb->obj[0]);
3460 			/* don't unpin kernel fb objects */
3461 			if (!amdgpu_fbdev_robj_is_fb(adev, robj)) {
3462 				r = amdgpu_bo_reserve(robj, true);
3463 				if (r == 0) {
3464 					amdgpu_bo_unpin(robj);
3465 					amdgpu_bo_unreserve(robj);
3466 				}
3467 			}
3468 		}
3469 	}
3470 
3471 	amdgpu_ras_suspend(adev);
3472 
3473 	r = amdgpu_device_ip_suspend_phase1(adev);
3474 
3475 	amdgpu_amdkfd_suspend(adev, !fbcon);
3476 
3477 	/* evict vram memory */
3478 	amdgpu_bo_evict_vram(adev);
3479 
3480 	amdgpu_fence_driver_suspend(adev);
3481 
3482 	r = amdgpu_device_ip_suspend_phase2(adev);
3483 
3484 	/* evict remaining vram memory
3485 	 * This second call to evict vram is to evict the gart page table
3486 	 * using the CPU.
3487 	 */
3488 	amdgpu_bo_evict_vram(adev);
3489 
3490 	return 0;
3491 }
3492 
3493 /**
3494  * amdgpu_device_resume - initiate device resume
3495  *
3496  * @dev: drm dev pointer
3497  * @resume: resume state
3498  * @fbcon : notify the fbdev of resume
3499  *
3500  * Bring the hw back to operating state (all asics).
3501  * Returns 0 for success or an error on failure.
3502  * Called at driver resume.
3503  */
3504 int amdgpu_device_resume(struct drm_device *dev, bool fbcon)
3505 {
3506 	struct drm_connector *connector;
3507 	struct drm_connector_list_iter iter;
3508 	struct amdgpu_device *adev = dev->dev_private;
3509 	struct drm_crtc *crtc;
3510 	int r = 0;
3511 
3512 #ifdef notyet
3513 	if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
3514 		return 0;
3515 #endif
3516 
3517 	/* post card */
3518 	if (amdgpu_device_need_post(adev)) {
3519 		r = amdgpu_atom_asic_init(adev->mode_info.atom_context);
3520 		if (r)
3521 			DRM_ERROR("amdgpu asic init failed\n");
3522 	}
3523 
3524 	r = amdgpu_device_ip_resume(adev);
3525 	if (r) {
3526 		DRM_ERROR("amdgpu_device_ip_resume failed (%d).\n", r);
3527 		return r;
3528 	}
3529 	amdgpu_fence_driver_resume(adev);
3530 
3531 
3532 	r = amdgpu_device_ip_late_init(adev);
3533 	if (r)
3534 		return r;
3535 
3536 	queue_delayed_work(system_wq, &adev->delayed_init_work,
3537 			   msecs_to_jiffies(AMDGPU_RESUME_MS));
3538 
3539 	if (!amdgpu_device_has_dc_support(adev)) {
3540 		/* pin cursors */
3541 		list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
3542 			struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3543 
3544 			if (amdgpu_crtc->cursor_bo && !adev->enable_virtual_display) {
3545 				struct amdgpu_bo *aobj = gem_to_amdgpu_bo(amdgpu_crtc->cursor_bo);
3546 				r = amdgpu_bo_reserve(aobj, true);
3547 				if (r == 0) {
3548 					r = amdgpu_bo_pin(aobj, AMDGPU_GEM_DOMAIN_VRAM);
3549 					if (r != 0)
3550 						DRM_ERROR("Failed to pin cursor BO (%d)\n", r);
3551 					amdgpu_crtc->cursor_addr = amdgpu_bo_gpu_offset(aobj);
3552 					amdgpu_bo_unreserve(aobj);
3553 				}
3554 			}
3555 		}
3556 	}
3557 	r = amdgpu_amdkfd_resume(adev, !fbcon);
3558 	if (r)
3559 		return r;
3560 
3561 	/* Make sure IB tests flushed */
3562 	flush_delayed_work(&adev->delayed_init_work);
3563 
3564 	/* blat the mode back in */
3565 	if (fbcon) {
3566 		if (!amdgpu_device_has_dc_support(adev)) {
3567 			/* pre DCE11 */
3568 			drm_helper_resume_force_mode(dev);
3569 
3570 			/* turn on display hw */
3571 			drm_modeset_lock_all(dev);
3572 
3573 			drm_connector_list_iter_begin(dev, &iter);
3574 			drm_for_each_connector_iter(connector, &iter)
3575 				drm_helper_connector_dpms(connector,
3576 							  DRM_MODE_DPMS_ON);
3577 			drm_connector_list_iter_end(&iter);
3578 
3579 			drm_modeset_unlock_all(dev);
3580 		}
3581 		amdgpu_fbdev_set_suspend(adev, 0);
3582 	}
3583 
3584 	drm_kms_helper_poll_enable(dev);
3585 
3586 	amdgpu_ras_resume(adev);
3587 
3588 	/*
3589 	 * Most of the connector probing functions try to acquire runtime pm
3590 	 * refs to ensure that the GPU is powered on when connector polling is
3591 	 * performed. Since we're calling this from a runtime PM callback,
3592 	 * trying to acquire rpm refs will cause us to deadlock.
3593 	 *
3594 	 * Since we're guaranteed to be holding the rpm lock, it's safe to
3595 	 * temporarily disable the rpm helpers so this doesn't deadlock us.
3596 	 */
3597 #if defined(CONFIG_PM) && defined(__linux__)
3598 	dev->dev->power.disable_depth++;
3599 #endif
3600 	if (!amdgpu_device_has_dc_support(adev))
3601 		drm_helper_hpd_irq_event(dev);
3602 	else
3603 		drm_kms_helper_hotplug_event(dev);
3604 #if defined(CONFIG_PM) && defined(__linux__)
3605 	dev->dev->power.disable_depth--;
3606 #endif
3607 	adev->in_suspend = false;
3608 
3609 	return 0;
3610 }
3611 
3612 /**
3613  * amdgpu_device_ip_check_soft_reset - did soft reset succeed
3614  *
3615  * @adev: amdgpu_device pointer
3616  *
3617  * The list of all the hardware IPs that make up the asic is walked and
3618  * the check_soft_reset callbacks are run.  check_soft_reset determines
3619  * if the asic is still hung or not.
3620  * Returns true if any of the IPs are still in a hung state, false if not.
3621  */
3622 static bool amdgpu_device_ip_check_soft_reset(struct amdgpu_device *adev)
3623 {
3624 	int i;
3625 	bool asic_hang = false;
3626 
3627 	if (amdgpu_sriov_vf(adev))
3628 		return true;
3629 
3630 	if (amdgpu_asic_need_full_reset(adev))
3631 		return true;
3632 
3633 	for (i = 0; i < adev->num_ip_blocks; i++) {
3634 		if (!adev->ip_blocks[i].status.valid)
3635 			continue;
3636 		if (adev->ip_blocks[i].version->funcs->check_soft_reset)
3637 			adev->ip_blocks[i].status.hang =
3638 				adev->ip_blocks[i].version->funcs->check_soft_reset(adev);
3639 		if (adev->ip_blocks[i].status.hang) {
3640 			DRM_INFO("IP block:%s is hung!\n", adev->ip_blocks[i].version->funcs->name);
3641 			asic_hang = true;
3642 		}
3643 	}
3644 	return asic_hang;
3645 }
3646 
3647 /**
3648  * amdgpu_device_ip_pre_soft_reset - prepare for soft reset
3649  *
3650  * @adev: amdgpu_device pointer
3651  *
3652  * The list of all the hardware IPs that make up the asic is walked and the
3653  * pre_soft_reset callbacks are run if the block is hung.  pre_soft_reset
3654  * handles any IP specific hardware or software state changes that are
3655  * necessary for a soft reset to succeed.
3656  * Returns 0 on success, negative error code on failure.
3657  */
3658 static int amdgpu_device_ip_pre_soft_reset(struct amdgpu_device *adev)
3659 {
3660 	int i, r = 0;
3661 
3662 	for (i = 0; i < adev->num_ip_blocks; i++) {
3663 		if (!adev->ip_blocks[i].status.valid)
3664 			continue;
3665 		if (adev->ip_blocks[i].status.hang &&
3666 		    adev->ip_blocks[i].version->funcs->pre_soft_reset) {
3667 			r = adev->ip_blocks[i].version->funcs->pre_soft_reset(adev);
3668 			if (r)
3669 				return r;
3670 		}
3671 	}
3672 
3673 	return 0;
3674 }
3675 
3676 /**
3677  * amdgpu_device_ip_need_full_reset - check if a full asic reset is needed
3678  *
3679  * @adev: amdgpu_device pointer
3680  *
3681  * Some hardware IPs cannot be soft reset.  If they are hung, a full gpu
3682  * reset is necessary to recover.
3683  * Returns true if a full asic reset is required, false if not.
3684  */
3685 static bool amdgpu_device_ip_need_full_reset(struct amdgpu_device *adev)
3686 {
3687 	int i;
3688 
3689 	if (amdgpu_asic_need_full_reset(adev))
3690 		return true;
3691 
3692 	for (i = 0; i < adev->num_ip_blocks; i++) {
3693 		if (!adev->ip_blocks[i].status.valid)
3694 			continue;
3695 		if ((adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_GMC) ||
3696 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_SMC) ||
3697 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_ACP) ||
3698 		    (adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_DCE) ||
3699 		     adev->ip_blocks[i].version->type == AMD_IP_BLOCK_TYPE_PSP) {
3700 			if (adev->ip_blocks[i].status.hang) {
3701 				DRM_INFO("Some block need full reset!\n");
3702 				return true;
3703 			}
3704 		}
3705 	}
3706 	return false;
3707 }
3708 
3709 /**
3710  * amdgpu_device_ip_soft_reset - do a soft reset
3711  *
3712  * @adev: amdgpu_device pointer
3713  *
3714  * The list of all the hardware IPs that make up the asic is walked and the
3715  * soft_reset callbacks are run if the block is hung.  soft_reset handles any
3716  * IP specific hardware or software state changes that are necessary to soft
3717  * reset the IP.
3718  * Returns 0 on success, negative error code on failure.
3719  */
3720 static int amdgpu_device_ip_soft_reset(struct amdgpu_device *adev)
3721 {
3722 	int i, r = 0;
3723 
3724 	for (i = 0; i < adev->num_ip_blocks; i++) {
3725 		if (!adev->ip_blocks[i].status.valid)
3726 			continue;
3727 		if (adev->ip_blocks[i].status.hang &&
3728 		    adev->ip_blocks[i].version->funcs->soft_reset) {
3729 			r = adev->ip_blocks[i].version->funcs->soft_reset(adev);
3730 			if (r)
3731 				return r;
3732 		}
3733 	}
3734 
3735 	return 0;
3736 }
3737 
3738 /**
3739  * amdgpu_device_ip_post_soft_reset - clean up from soft reset
3740  *
3741  * @adev: amdgpu_device pointer
3742  *
3743  * The list of all the hardware IPs that make up the asic is walked and the
3744  * post_soft_reset callbacks are run if the asic was hung.  post_soft_reset
3745  * handles any IP specific hardware or software state changes that are
3746  * necessary after the IP has been soft reset.
3747  * Returns 0 on success, negative error code on failure.
3748  */
3749 static int amdgpu_device_ip_post_soft_reset(struct amdgpu_device *adev)
3750 {
3751 	int i, r = 0;
3752 
3753 	for (i = 0; i < adev->num_ip_blocks; i++) {
3754 		if (!adev->ip_blocks[i].status.valid)
3755 			continue;
3756 		if (adev->ip_blocks[i].status.hang &&
3757 		    adev->ip_blocks[i].version->funcs->post_soft_reset)
3758 			r = adev->ip_blocks[i].version->funcs->post_soft_reset(adev);
3759 		if (r)
3760 			return r;
3761 	}
3762 
3763 	return 0;
3764 }
3765 
3766 /**
3767  * amdgpu_device_recover_vram - Recover some VRAM contents
3768  *
3769  * @adev: amdgpu_device pointer
3770  *
3771  * Restores the contents of VRAM buffers from the shadows in GTT.  Used to
3772  * restore things like GPUVM page tables after a GPU reset where
3773  * the contents of VRAM might be lost.
3774  *
3775  * Returns:
3776  * 0 on success, negative error code on failure.
3777  */
3778 static int amdgpu_device_recover_vram(struct amdgpu_device *adev)
3779 {
3780 	struct dma_fence *fence = NULL, *next = NULL;
3781 	struct amdgpu_bo *shadow;
3782 	long r = 1, tmo;
3783 
3784 	if (amdgpu_sriov_runtime(adev))
3785 		tmo = msecs_to_jiffies(8000);
3786 	else
3787 		tmo = msecs_to_jiffies(100);
3788 
3789 	DRM_INFO("recover vram bo from shadow start\n");
3790 	mutex_lock(&adev->shadow_list_lock);
3791 	list_for_each_entry(shadow, &adev->shadow_list, shadow_list) {
3792 
3793 		/* No need to recover an evicted BO */
3794 		if (shadow->tbo.mem.mem_type != TTM_PL_TT ||
3795 		    shadow->tbo.mem.start == AMDGPU_BO_INVALID_OFFSET ||
3796 		    shadow->parent->tbo.mem.mem_type != TTM_PL_VRAM)
3797 			continue;
3798 
3799 		r = amdgpu_bo_restore_shadow(shadow, &next);
3800 		if (r)
3801 			break;
3802 
3803 		if (fence) {
3804 			tmo = dma_fence_wait_timeout(fence, false, tmo);
3805 			dma_fence_put(fence);
3806 			fence = next;
3807 			if (tmo == 0) {
3808 				r = -ETIMEDOUT;
3809 				break;
3810 			} else if (tmo < 0) {
3811 				r = tmo;
3812 				break;
3813 			}
3814 		} else {
3815 			fence = next;
3816 		}
3817 	}
3818 	mutex_unlock(&adev->shadow_list_lock);
3819 
3820 	if (fence)
3821 		tmo = dma_fence_wait_timeout(fence, false, tmo);
3822 	dma_fence_put(fence);
3823 
3824 	if (r < 0 || tmo <= 0) {
3825 		DRM_ERROR("recover vram bo from shadow failed, r is %ld, tmo is %ld\n", r, tmo);
3826 		return -EIO;
3827 	}
3828 
3829 	DRM_INFO("recover vram bo from shadow done\n");
3830 	return 0;
3831 }
3832 
3833 
3834 /**
3835  * amdgpu_device_reset_sriov - reset ASIC for SR-IOV vf
3836  *
3837  * @adev: amdgpu device pointer
3838  * @from_hypervisor: request from hypervisor
3839  *
3840  * do VF FLR and reinitialize Asic
3841  * return 0 means succeeded otherwise failed
3842  */
3843 static int amdgpu_device_reset_sriov(struct amdgpu_device *adev,
3844 				     bool from_hypervisor)
3845 {
3846 	int r;
3847 
3848 	if (from_hypervisor)
3849 		r = amdgpu_virt_request_full_gpu(adev, true);
3850 	else
3851 		r = amdgpu_virt_reset_gpu(adev);
3852 	if (r)
3853 		return r;
3854 
3855 	/* Resume IP prior to SMC */
3856 	r = amdgpu_device_ip_reinit_early_sriov(adev);
3857 	if (r)
3858 		goto error;
3859 
3860 	amdgpu_virt_init_data_exchange(adev);
3861 	/* we need recover gart prior to run SMC/CP/SDMA resume */
3862 	amdgpu_gtt_mgr_recover(&adev->mman.bdev.man[TTM_PL_TT]);
3863 
3864 	r = amdgpu_device_fw_loading(adev);
3865 	if (r)
3866 		return r;
3867 
3868 	/* now we are okay to resume SMC/CP/SDMA */
3869 	r = amdgpu_device_ip_reinit_late_sriov(adev);
3870 	if (r)
3871 		goto error;
3872 
3873 	amdgpu_irq_gpu_reset_resume_helper(adev);
3874 	r = amdgpu_ib_ring_tests(adev);
3875 	amdgpu_amdkfd_post_reset(adev);
3876 
3877 error:
3878 	amdgpu_virt_release_full_gpu(adev, true);
3879 	if (!r && adev->virt.gim_feature & AMDGIM_FEATURE_GIM_FLR_VRAMLOST) {
3880 		amdgpu_inc_vram_lost(adev);
3881 		r = amdgpu_device_recover_vram(adev);
3882 	}
3883 
3884 	return r;
3885 }
3886 
3887 /**
3888  * amdgpu_device_should_recover_gpu - check if we should try GPU recovery
3889  *
3890  * @adev: amdgpu device pointer
3891  *
3892  * Check amdgpu_gpu_recovery and SRIOV status to see if we should try to recover
3893  * a hung GPU.
3894  */
3895 bool amdgpu_device_should_recover_gpu(struct amdgpu_device *adev)
3896 {
3897 	if (!amdgpu_device_ip_check_soft_reset(adev)) {
3898 		DRM_INFO("Timeout, but no hardware hang detected.\n");
3899 		return false;
3900 	}
3901 
3902 	if (amdgpu_gpu_recovery == 0)
3903 		goto disabled;
3904 
3905 	if (amdgpu_sriov_vf(adev))
3906 		return true;
3907 
3908 	if (amdgpu_gpu_recovery == -1) {
3909 		switch (adev->asic_type) {
3910 		case CHIP_BONAIRE:
3911 		case CHIP_HAWAII:
3912 		case CHIP_TOPAZ:
3913 		case CHIP_TONGA:
3914 		case CHIP_FIJI:
3915 		case CHIP_POLARIS10:
3916 		case CHIP_POLARIS11:
3917 		case CHIP_POLARIS12:
3918 		case CHIP_VEGAM:
3919 		case CHIP_VEGA20:
3920 		case CHIP_VEGA10:
3921 		case CHIP_VEGA12:
3922 		case CHIP_RAVEN:
3923 		case CHIP_ARCTURUS:
3924 		case CHIP_RENOIR:
3925 		case CHIP_NAVI10:
3926 		case CHIP_NAVI14:
3927 		case CHIP_NAVI12:
3928 			break;
3929 		default:
3930 			goto disabled;
3931 		}
3932 	}
3933 
3934 	return true;
3935 
3936 disabled:
3937 		DRM_INFO("GPU recovery disabled.\n");
3938 		return false;
3939 }
3940 
3941 
3942 static int amdgpu_device_pre_asic_reset(struct amdgpu_device *adev,
3943 					struct amdgpu_job *job,
3944 					bool *need_full_reset_arg)
3945 {
3946 	int i, r = 0;
3947 	bool need_full_reset  = *need_full_reset_arg;
3948 
3949 	/* block all schedulers and reset given job's ring */
3950 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
3951 		struct amdgpu_ring *ring = adev->rings[i];
3952 
3953 		if (!ring || !ring->sched.thread)
3954 			continue;
3955 
3956 		/* after all hw jobs are reset, hw fence is meaningless, so force_completion */
3957 		amdgpu_fence_driver_force_completion(ring);
3958 	}
3959 
3960 	if(job)
3961 		drm_sched_increase_karma(&job->base);
3962 
3963 	/* Don't suspend on bare metal if we are not going to HW reset the ASIC */
3964 	if (!amdgpu_sriov_vf(adev)) {
3965 
3966 		if (!need_full_reset)
3967 			need_full_reset = amdgpu_device_ip_need_full_reset(adev);
3968 
3969 		if (!need_full_reset) {
3970 			amdgpu_device_ip_pre_soft_reset(adev);
3971 			r = amdgpu_device_ip_soft_reset(adev);
3972 			amdgpu_device_ip_post_soft_reset(adev);
3973 			if (r || amdgpu_device_ip_check_soft_reset(adev)) {
3974 				DRM_INFO("soft reset failed, will fallback to full reset!\n");
3975 				need_full_reset = true;
3976 			}
3977 		}
3978 
3979 		if (need_full_reset)
3980 			r = amdgpu_device_ip_suspend(adev);
3981 
3982 		*need_full_reset_arg = need_full_reset;
3983 	}
3984 
3985 	return r;
3986 }
3987 
3988 static int amdgpu_do_asic_reset(struct amdgpu_hive_info *hive,
3989 			       struct list_head *device_list_handle,
3990 			       bool *need_full_reset_arg)
3991 {
3992 	struct amdgpu_device *tmp_adev = NULL;
3993 	bool need_full_reset = *need_full_reset_arg, vram_lost = false;
3994 	int r = 0;
3995 
3996 	/*
3997 	 * ASIC reset has to be done on all HGMI hive nodes ASAP
3998 	 * to allow proper links negotiation in FW (within 1 sec)
3999 	 */
4000 	if (need_full_reset) {
4001 		list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4002 			/* For XGMI run all resets in parallel to speed up the process */
4003 			if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
4004 				if (!queue_work(system_unbound_wq, &tmp_adev->xgmi_reset_work))
4005 					r = -EALREADY;
4006 			} else
4007 				r = amdgpu_asic_reset(tmp_adev);
4008 
4009 			if (r) {
4010 				DRM_ERROR("ASIC reset failed with error, %d for drm dev, %s",
4011 					 r, tmp_adev->ddev->unique);
4012 				break;
4013 			}
4014 		}
4015 
4016 		/* For XGMI wait for all resets to complete before proceed */
4017 		if (!r) {
4018 			list_for_each_entry(tmp_adev, device_list_handle,
4019 					    gmc.xgmi.head) {
4020 				if (tmp_adev->gmc.xgmi.num_physical_nodes > 1) {
4021 					flush_work(&tmp_adev->xgmi_reset_work);
4022 					r = tmp_adev->asic_reset_res;
4023 					if (r)
4024 						break;
4025 				}
4026 			}
4027 		}
4028 	}
4029 
4030 	if (!r && amdgpu_ras_intr_triggered()) {
4031 		list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4032 			if (tmp_adev->mmhub.funcs &&
4033 			    tmp_adev->mmhub.funcs->reset_ras_error_count)
4034 				tmp_adev->mmhub.funcs->reset_ras_error_count(tmp_adev);
4035 		}
4036 
4037 		amdgpu_ras_intr_cleared();
4038 	}
4039 
4040 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4041 		if (need_full_reset) {
4042 			/* post card */
4043 			if (amdgpu_atom_asic_init(tmp_adev->mode_info.atom_context))
4044 				DRM_WARN("asic atom init failed!");
4045 
4046 			if (!r) {
4047 				dev_info(tmp_adev->dev, "GPU reset succeeded, trying to resume\n");
4048 				r = amdgpu_device_ip_resume_phase1(tmp_adev);
4049 				if (r)
4050 					goto out;
4051 
4052 				vram_lost = amdgpu_device_check_vram_lost(tmp_adev);
4053 				if (vram_lost) {
4054 					DRM_INFO("VRAM is lost due to GPU reset!\n");
4055 					amdgpu_inc_vram_lost(tmp_adev);
4056 				}
4057 
4058 				r = amdgpu_gtt_mgr_recover(
4059 					&tmp_adev->mman.bdev.man[TTM_PL_TT]);
4060 				if (r)
4061 					goto out;
4062 
4063 				r = amdgpu_device_fw_loading(tmp_adev);
4064 				if (r)
4065 					return r;
4066 
4067 				r = amdgpu_device_ip_resume_phase2(tmp_adev);
4068 				if (r)
4069 					goto out;
4070 
4071 				if (vram_lost)
4072 					amdgpu_device_fill_reset_magic(tmp_adev);
4073 
4074 				/*
4075 				 * Add this ASIC as tracked as reset was already
4076 				 * complete successfully.
4077 				 */
4078 				amdgpu_register_gpu_instance(tmp_adev);
4079 
4080 				r = amdgpu_device_ip_late_init(tmp_adev);
4081 				if (r)
4082 					goto out;
4083 
4084 				amdgpu_fbdev_set_suspend(tmp_adev, 0);
4085 
4086 				/* must succeed. */
4087 				amdgpu_ras_resume(tmp_adev);
4088 
4089 				/* Update PSP FW topology after reset */
4090 				if (hive && tmp_adev->gmc.xgmi.num_physical_nodes > 1)
4091 					r = amdgpu_xgmi_update_topology(hive, tmp_adev);
4092 			}
4093 		}
4094 
4095 
4096 out:
4097 		if (!r) {
4098 			amdgpu_irq_gpu_reset_resume_helper(tmp_adev);
4099 			r = amdgpu_ib_ring_tests(tmp_adev);
4100 			if (r) {
4101 				dev_err(tmp_adev->dev, "ib ring test failed (%d).\n", r);
4102 				r = amdgpu_device_ip_suspend(tmp_adev);
4103 				need_full_reset = true;
4104 				r = -EAGAIN;
4105 				goto end;
4106 			}
4107 		}
4108 
4109 		if (!r)
4110 			r = amdgpu_device_recover_vram(tmp_adev);
4111 		else
4112 			tmp_adev->asic_reset_res = r;
4113 	}
4114 
4115 end:
4116 	*need_full_reset_arg = need_full_reset;
4117 	return r;
4118 }
4119 
4120 static bool amdgpu_device_lock_adev(struct amdgpu_device *adev, bool trylock)
4121 {
4122 	if (trylock) {
4123 		if (!mutex_trylock(&adev->lock_reset))
4124 			return false;
4125 	} else
4126 		mutex_lock(&adev->lock_reset);
4127 
4128 	atomic_inc(&adev->gpu_reset_counter);
4129 	adev->in_gpu_reset = true;
4130 	switch (amdgpu_asic_reset_method(adev)) {
4131 	case AMD_RESET_METHOD_MODE1:
4132 		adev->mp1_state = PP_MP1_STATE_SHUTDOWN;
4133 		break;
4134 	case AMD_RESET_METHOD_MODE2:
4135 		adev->mp1_state = PP_MP1_STATE_RESET;
4136 		break;
4137 	default:
4138 		adev->mp1_state = PP_MP1_STATE_NONE;
4139 		break;
4140 	}
4141 
4142 	return true;
4143 }
4144 
4145 static void amdgpu_device_unlock_adev(struct amdgpu_device *adev)
4146 {
4147 	amdgpu_vf_error_trans_all(adev);
4148 	adev->mp1_state = PP_MP1_STATE_NONE;
4149 	adev->in_gpu_reset = false;
4150 	mutex_unlock(&adev->lock_reset);
4151 }
4152 
4153 /**
4154  * amdgpu_device_gpu_recover - reset the asic and recover scheduler
4155  *
4156  * @adev: amdgpu device pointer
4157  * @job: which job trigger hang
4158  *
4159  * Attempt to reset the GPU if it has hung (all asics).
4160  * Attempt to do soft-reset or full-reset and reinitialize Asic
4161  * Returns 0 for success or an error on failure.
4162  */
4163 
4164 int amdgpu_device_gpu_recover(struct amdgpu_device *adev,
4165 			      struct amdgpu_job *job)
4166 {
4167 	struct list_head device_list, *device_list_handle =  NULL;
4168 	bool need_full_reset, job_signaled;
4169 	struct amdgpu_hive_info *hive = NULL;
4170 	struct amdgpu_device *tmp_adev = NULL;
4171 	int i, r = 0;
4172 	bool in_ras_intr = amdgpu_ras_intr_triggered();
4173 	bool use_baco =
4174 		(amdgpu_asic_reset_method(adev) == AMD_RESET_METHOD_BACO) ?
4175 		true : false;
4176 
4177 	/*
4178 	 * Flush RAM to disk so that after reboot
4179 	 * the user can read log and see why the system rebooted.
4180 	 */
4181 	if (in_ras_intr && !use_baco && amdgpu_ras_get_context(adev)->reboot) {
4182 
4183 		DRM_WARN("Emergency reboot.");
4184 
4185 #ifdef notyet
4186 		ksys_sync_helper();
4187 		emergency_restart();
4188 #else
4189 		panic("emergency_restart");
4190 #endif
4191 	}
4192 
4193 	need_full_reset = job_signaled = false;
4194 	INIT_LIST_HEAD(&device_list);
4195 
4196 	amdgpu_ras_set_error_query_ready(adev, false);
4197 
4198 	dev_info(adev->dev, "GPU %s begin!\n",
4199 		(in_ras_intr && !use_baco) ? "jobs stop":"reset");
4200 
4201 	cancel_delayed_work_sync(&adev->delayed_init_work);
4202 
4203 	hive = amdgpu_get_xgmi_hive(adev, false);
4204 
4205 	/*
4206 	 * Here we trylock to avoid chain of resets executing from
4207 	 * either trigger by jobs on different adevs in XGMI hive or jobs on
4208 	 * different schedulers for same device while this TO handler is running.
4209 	 * We always reset all schedulers for device and all devices for XGMI
4210 	 * hive so that should take care of them too.
4211 	 */
4212 
4213 	if (hive && !mutex_trylock(&hive->reset_lock)) {
4214 		DRM_INFO("Bailing on TDR for s_job:%llx, hive: %llx as another already in progress",
4215 			  job ? job->base.id : -1, hive->hive_id);
4216 		return 0;
4217 	}
4218 
4219 	/* Start with adev pre asic reset first for soft reset check.*/
4220 	if (!amdgpu_device_lock_adev(adev, !hive)) {
4221 		DRM_INFO("Bailing on TDR for s_job:%llx, as another already in progress",
4222 			  job ? job->base.id : -1);
4223 		return 0;
4224 	}
4225 
4226 	/* Block kfd: SRIOV would do it separately */
4227 	if (!amdgpu_sriov_vf(adev))
4228                 amdgpu_amdkfd_pre_reset(adev);
4229 
4230 	/* Build list of devices to reset */
4231 	if  (adev->gmc.xgmi.num_physical_nodes > 1) {
4232 		if (!hive) {
4233 			/*unlock kfd: SRIOV would do it separately */
4234 			if (!amdgpu_sriov_vf(adev))
4235 		                amdgpu_amdkfd_post_reset(adev);
4236 			amdgpu_device_unlock_adev(adev);
4237 			return -ENODEV;
4238 		}
4239 
4240 		/*
4241 		 * In case we are in XGMI hive mode device reset is done for all the
4242 		 * nodes in the hive to retrain all XGMI links and hence the reset
4243 		 * sequence is executed in loop on all nodes.
4244 		 */
4245 		device_list_handle = &hive->device_list;
4246 	} else {
4247 		list_add_tail(&adev->gmc.xgmi.head, &device_list);
4248 		device_list_handle = &device_list;
4249 	}
4250 
4251 	/* block all schedulers and reset given job's ring */
4252 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4253 		if (tmp_adev != adev) {
4254 			amdgpu_ras_set_error_query_ready(tmp_adev, false);
4255 			amdgpu_device_lock_adev(tmp_adev, false);
4256 			if (!amdgpu_sriov_vf(tmp_adev))
4257 			                amdgpu_amdkfd_pre_reset(tmp_adev);
4258 		}
4259 
4260 		/*
4261 		 * Mark these ASICs to be reseted as untracked first
4262 		 * And add them back after reset completed
4263 		 */
4264 		amdgpu_unregister_gpu_instance(tmp_adev);
4265 
4266 		amdgpu_fbdev_set_suspend(adev, 1);
4267 
4268 		/* disable ras on ALL IPs */
4269 		if (!(in_ras_intr && !use_baco) &&
4270 		      amdgpu_device_ip_need_full_reset(tmp_adev))
4271 			amdgpu_ras_suspend(tmp_adev);
4272 
4273 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4274 			struct amdgpu_ring *ring = tmp_adev->rings[i];
4275 
4276 			if (!ring || !ring->sched.thread)
4277 				continue;
4278 
4279 			drm_sched_stop(&ring->sched, job ? &job->base : NULL);
4280 
4281 			if (in_ras_intr && !use_baco)
4282 				amdgpu_job_stop_all_jobs_on_sched(&ring->sched);
4283 		}
4284 	}
4285 
4286 
4287 	if (in_ras_intr && !use_baco)
4288 		goto skip_sched_resume;
4289 
4290 	/*
4291 	 * Must check guilty signal here since after this point all old
4292 	 * HW fences are force signaled.
4293 	 *
4294 	 * job->base holds a reference to parent fence
4295 	 */
4296 	if (job && job->base.s_fence->parent &&
4297 	    dma_fence_is_signaled(job->base.s_fence->parent))
4298 		job_signaled = true;
4299 
4300 	if (job_signaled) {
4301 		dev_info(adev->dev, "Guilty job already signaled, skipping HW reset");
4302 		goto skip_hw_reset;
4303 	}
4304 
4305 
4306 	/* Guilty job will be freed after this*/
4307 	r = amdgpu_device_pre_asic_reset(adev, job, &need_full_reset);
4308 	if (r) {
4309 		/*TODO Should we stop ?*/
4310 		DRM_ERROR("GPU pre asic reset failed with err, %d for drm dev, %s ",
4311 			  r, adev->ddev->unique);
4312 		adev->asic_reset_res = r;
4313 	}
4314 
4315 retry:	/* Rest of adevs pre asic reset from XGMI hive. */
4316 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4317 
4318 		if (tmp_adev == adev)
4319 			continue;
4320 
4321 		r = amdgpu_device_pre_asic_reset(tmp_adev,
4322 						 NULL,
4323 						 &need_full_reset);
4324 		/*TODO Should we stop ?*/
4325 		if (r) {
4326 			DRM_ERROR("GPU pre asic reset failed with err, %d for drm dev, %s ",
4327 				  r, tmp_adev->ddev->unique);
4328 			tmp_adev->asic_reset_res = r;
4329 		}
4330 	}
4331 
4332 	/* Actual ASIC resets if needed.*/
4333 	/* TODO Implement XGMI hive reset logic for SRIOV */
4334 	if (amdgpu_sriov_vf(adev)) {
4335 		r = amdgpu_device_reset_sriov(adev, job ? false : true);
4336 		if (r)
4337 			adev->asic_reset_res = r;
4338 	} else {
4339 		r  = amdgpu_do_asic_reset(hive, device_list_handle, &need_full_reset);
4340 		if (r && r == -EAGAIN)
4341 			goto retry;
4342 	}
4343 
4344 skip_hw_reset:
4345 
4346 	/* Post ASIC reset for all devs .*/
4347 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4348 
4349 		for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
4350 			struct amdgpu_ring *ring = tmp_adev->rings[i];
4351 
4352 			if (!ring || !ring->sched.thread)
4353 				continue;
4354 
4355 			/* No point to resubmit jobs if we didn't HW reset*/
4356 			if (!tmp_adev->asic_reset_res && !job_signaled)
4357 				drm_sched_resubmit_jobs(&ring->sched);
4358 
4359 			drm_sched_start(&ring->sched, !tmp_adev->asic_reset_res);
4360 		}
4361 
4362 		if (!amdgpu_device_has_dc_support(tmp_adev) && !job_signaled) {
4363 			drm_helper_resume_force_mode(tmp_adev->ddev);
4364 		}
4365 
4366 		tmp_adev->asic_reset_res = 0;
4367 
4368 		if (r) {
4369 			/* bad news, how to tell it to userspace ? */
4370 			dev_info(tmp_adev->dev, "GPU reset(%d) failed\n", atomic_read(&tmp_adev->gpu_reset_counter));
4371 			amdgpu_vf_error_put(tmp_adev, AMDGIM_ERROR_VF_GPU_RESET_FAIL, 0, r);
4372 		} else {
4373 			dev_info(tmp_adev->dev, "GPU reset(%d) succeeded!\n", atomic_read(&tmp_adev->gpu_reset_counter));
4374 		}
4375 	}
4376 
4377 skip_sched_resume:
4378 	list_for_each_entry(tmp_adev, device_list_handle, gmc.xgmi.head) {
4379 		/*unlock kfd: SRIOV would do it separately */
4380 		if (!(in_ras_intr && !use_baco) && !amdgpu_sriov_vf(tmp_adev))
4381 	                amdgpu_amdkfd_post_reset(tmp_adev);
4382 		amdgpu_device_unlock_adev(tmp_adev);
4383 	}
4384 
4385 	if (hive)
4386 		mutex_unlock(&hive->reset_lock);
4387 
4388 	if (r)
4389 		dev_info(adev->dev, "GPU reset end with ret = %d\n", r);
4390 	return r;
4391 }
4392 
4393 /**
4394  * amdgpu_device_get_pcie_info - fence pcie info about the PCIE slot
4395  *
4396  * @adev: amdgpu_device pointer
4397  *
4398  * Fetchs and stores in the driver the PCIE capabilities (gen speed
4399  * and lanes) of the slot the device is in. Handles APUs and
4400  * virtualized environments where PCIE config space may not be available.
4401  */
4402 static void amdgpu_device_get_pcie_info(struct amdgpu_device *adev)
4403 {
4404 	struct pci_dev *pdev;
4405 	enum pci_bus_speed speed_cap, platform_speed_cap;
4406 	enum pcie_link_width platform_link_width;
4407 
4408 	if (amdgpu_pcie_gen_cap)
4409 		adev->pm.pcie_gen_mask = amdgpu_pcie_gen_cap;
4410 
4411 	if (amdgpu_pcie_lane_cap)
4412 		adev->pm.pcie_mlw_mask = amdgpu_pcie_lane_cap;
4413 
4414 	/* covers APUs as well */
4415 	if (pci_is_root_bus(adev->pdev->bus)) {
4416 		if (adev->pm.pcie_gen_mask == 0)
4417 			adev->pm.pcie_gen_mask = AMDGPU_DEFAULT_PCIE_GEN_MASK;
4418 		if (adev->pm.pcie_mlw_mask == 0)
4419 			adev->pm.pcie_mlw_mask = AMDGPU_DEFAULT_PCIE_MLW_MASK;
4420 		return;
4421 	}
4422 
4423 	if (adev->pm.pcie_gen_mask && adev->pm.pcie_mlw_mask)
4424 		return;
4425 
4426 	pcie_bandwidth_available(adev->pdev, NULL,
4427 				 &platform_speed_cap, &platform_link_width);
4428 
4429 	if (adev->pm.pcie_gen_mask == 0) {
4430 		/* asic caps */
4431 		pdev = adev->pdev;
4432 		speed_cap = pcie_get_speed_cap(pdev);
4433 		if (speed_cap == PCI_SPEED_UNKNOWN) {
4434 			adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4435 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4436 						  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
4437 		} else {
4438 			if (speed_cap == PCIE_SPEED_16_0GT)
4439 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4440 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4441 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3 |
4442 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN4);
4443 			else if (speed_cap == PCIE_SPEED_8_0GT)
4444 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4445 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4446 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN3);
4447 			else if (speed_cap == PCIE_SPEED_5_0GT)
4448 				adev->pm.pcie_gen_mask |= (CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4449 							  CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN2);
4450 			else
4451 				adev->pm.pcie_gen_mask |= CAIL_ASIC_PCIE_LINK_SPEED_SUPPORT_GEN1;
4452 		}
4453 		/* platform caps */
4454 		if (platform_speed_cap == PCI_SPEED_UNKNOWN) {
4455 			adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4456 						   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
4457 		} else {
4458 			if (platform_speed_cap == PCIE_SPEED_16_0GT)
4459 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4460 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4461 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3 |
4462 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN4);
4463 			else if (platform_speed_cap == PCIE_SPEED_8_0GT)
4464 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4465 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2 |
4466 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN3);
4467 			else if (platform_speed_cap == PCIE_SPEED_5_0GT)
4468 				adev->pm.pcie_gen_mask |= (CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1 |
4469 							   CAIL_PCIE_LINK_SPEED_SUPPORT_GEN2);
4470 			else
4471 				adev->pm.pcie_gen_mask |= CAIL_PCIE_LINK_SPEED_SUPPORT_GEN1;
4472 
4473 		}
4474 	}
4475 	if (adev->pm.pcie_mlw_mask == 0) {
4476 		if (platform_link_width == PCIE_LNK_WIDTH_UNKNOWN) {
4477 			adev->pm.pcie_mlw_mask |= AMDGPU_DEFAULT_PCIE_MLW_MASK;
4478 		} else {
4479 			switch (platform_link_width) {
4480 			case PCIE_LNK_X32:
4481 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X32 |
4482 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
4483 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
4484 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4485 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4486 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4487 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4488 				break;
4489 			case PCIE_LNK_X16:
4490 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X16 |
4491 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
4492 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4493 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4494 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4495 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4496 				break;
4497 			case PCIE_LNK_X12:
4498 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X12 |
4499 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4500 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4501 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4502 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4503 				break;
4504 			case PCIE_LNK_X8:
4505 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X8 |
4506 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4507 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4508 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4509 				break;
4510 			case PCIE_LNK_X4:
4511 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X4 |
4512 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4513 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4514 				break;
4515 			case PCIE_LNK_X2:
4516 				adev->pm.pcie_mlw_mask = (CAIL_PCIE_LINK_WIDTH_SUPPORT_X2 |
4517 							  CAIL_PCIE_LINK_WIDTH_SUPPORT_X1);
4518 				break;
4519 			case PCIE_LNK_X1:
4520 				adev->pm.pcie_mlw_mask = CAIL_PCIE_LINK_WIDTH_SUPPORT_X1;
4521 				break;
4522 			default:
4523 				break;
4524 			}
4525 		}
4526 	}
4527 }
4528 
4529 int amdgpu_device_baco_enter(struct drm_device *dev)
4530 {
4531 	struct amdgpu_device *adev = dev->dev_private;
4532 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4533 
4534 	if (!amdgpu_device_supports_baco(adev->ddev))
4535 		return -ENOTSUPP;
4536 
4537 	if (ras && ras->supported)
4538 		adev->nbio.funcs->enable_doorbell_interrupt(adev, false);
4539 
4540 	return amdgpu_dpm_baco_enter(adev);
4541 }
4542 
4543 int amdgpu_device_baco_exit(struct drm_device *dev)
4544 {
4545 	struct amdgpu_device *adev = dev->dev_private;
4546 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
4547 	int ret = 0;
4548 
4549 	if (!amdgpu_device_supports_baco(adev->ddev))
4550 		return -ENOTSUPP;
4551 
4552 	ret = amdgpu_dpm_baco_exit(adev);
4553 	if (ret)
4554 		return ret;
4555 
4556 	if (ras && ras->supported)
4557 		adev->nbio.funcs->enable_doorbell_interrupt(adev, true);
4558 
4559 	return 0;
4560 }
4561