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