xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c (revision b0a3a811634aa7422f8a92196db47a06a70bda16)
1 /*
2  * Copyright 2018 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sub license, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
16  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
17  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19  * USE OR OTHER DEALINGS IN THE SOFTWARE.
20  *
21  * The above copyright notice and this permission notice (including the
22  * next paragraph) shall be included in all copies or substantial portions
23  * of the Software.
24  *
25  */
26 
27 #include <linux/io-64-nonatomic-lo-hi.h>
28 #ifdef CONFIG_X86
29 #include <asm/hypervisor.h>
30 #endif
31 
32 #include "amdgpu.h"
33 #include "amdgpu_gmc.h"
34 #include "amdgpu_ras.h"
35 #include "amdgpu_reset.h"
36 #include "amdgpu_ring.h"
37 #include "amdgpu_sdma.h"
38 #include "amdgpu_xgmi.h"
39 #include "amdgpu_atomfirmware.h"
40 
41 #include <drm/drm_drv.h>
42 #include <drm/ttm/ttm_tt.h>
43 
44 static const u64 four_gb = 0x100000000ULL;
45 
46 bool amdgpu_gmc_is_pdb0_enabled(struct amdgpu_device *adev)
47 {
48 	return adev->gmc.xgmi.connected_to_cpu || amdgpu_virt_xgmi_migrate_enabled(adev);
49 }
50 
51 /**
52  * amdgpu_gmc_pdb0_alloc - allocate vram for pdb0
53  *
54  * @adev: amdgpu_device pointer
55  *
56  * Allocate video memory for pdb0 and map it for CPU access
57  * Returns 0 for success, error for failure.
58  */
59 int amdgpu_gmc_pdb0_alloc(struct amdgpu_device *adev)
60 {
61 	int r;
62 	struct amdgpu_bo_param bp;
63 	u64 vram_size = adev->gmc.xgmi.node_segment_size * adev->gmc.xgmi.num_physical_nodes;
64 	uint32_t pde0_page_shift = adev->gmc.vmid0_page_table_block_size + 21;
65 	uint32_t npdes = (vram_size + (1ULL << pde0_page_shift) - 1) >> pde0_page_shift;
66 
67 	memset(&bp, 0, sizeof(bp));
68 	bp.size = PAGE_ALIGN((npdes + 1) * 8);
69 	bp.byte_align = PAGE_SIZE;
70 	bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
71 	bp.flags = AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED |
72 		AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
73 	bp.type = ttm_bo_type_kernel;
74 	bp.resv = NULL;
75 	bp.bo_ptr_size = sizeof(struct amdgpu_bo);
76 
77 	r = amdgpu_bo_create(adev, &bp, &adev->gmc.pdb0_bo);
78 	if (r)
79 		return r;
80 
81 	r = amdgpu_bo_reserve(adev->gmc.pdb0_bo, false);
82 	if (unlikely(r != 0))
83 		goto bo_reserve_failure;
84 
85 	r = amdgpu_bo_pin(adev->gmc.pdb0_bo, AMDGPU_GEM_DOMAIN_VRAM);
86 	if (r)
87 		goto bo_pin_failure;
88 	r = amdgpu_bo_kmap(adev->gmc.pdb0_bo, &adev->gmc.ptr_pdb0);
89 	if (r)
90 		goto bo_kmap_failure;
91 
92 	amdgpu_bo_unreserve(adev->gmc.pdb0_bo);
93 	return 0;
94 
95 bo_kmap_failure:
96 	amdgpu_bo_unpin(adev->gmc.pdb0_bo);
97 bo_pin_failure:
98 	amdgpu_bo_unreserve(adev->gmc.pdb0_bo);
99 bo_reserve_failure:
100 	amdgpu_bo_unref(&adev->gmc.pdb0_bo);
101 	return r;
102 }
103 
104 /**
105  * amdgpu_gmc_get_pde_for_bo - get the PDE for a BO
106  *
107  * @bo: the BO to get the PDE for
108  * @level: the level in the PD hirarchy
109  * @addr: resulting addr
110  * @flags: resulting flags
111  *
112  * Get the address and flags to be used for a PDE (Page Directory Entry).
113  */
114 void amdgpu_gmc_get_pde_for_bo(struct amdgpu_bo *bo, int level,
115 			       uint64_t *addr, uint64_t *flags)
116 {
117 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
118 
119 	switch (bo->tbo.resource->mem_type) {
120 	case TTM_PL_TT:
121 		*addr = bo->tbo.ttm->dma_address[0];
122 		break;
123 	case TTM_PL_VRAM:
124 		*addr = amdgpu_bo_gpu_offset(bo);
125 		break;
126 	default:
127 		*addr = 0;
128 		break;
129 	}
130 	*flags = amdgpu_ttm_tt_pde_flags(bo->tbo.ttm, bo->tbo.resource);
131 	amdgpu_gmc_get_vm_pde(adev, level, addr, flags);
132 }
133 
134 /*
135  * amdgpu_gmc_pd_addr - return the address of the root directory
136  */
137 uint64_t amdgpu_gmc_pd_addr(struct amdgpu_bo *bo)
138 {
139 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
140 	uint64_t pd_addr;
141 
142 	/* TODO: move that into ASIC specific code */
143 	if (adev->asic_type >= CHIP_VEGA10) {
144 		uint64_t flags = AMDGPU_PTE_VALID;
145 
146 		amdgpu_gmc_get_pde_for_bo(bo, -1, &pd_addr, &flags);
147 		pd_addr |= flags;
148 	} else {
149 		pd_addr = amdgpu_bo_gpu_offset(bo);
150 	}
151 	return pd_addr;
152 }
153 
154 /**
155  * amdgpu_gmc_set_pte_pde - update the page tables using CPU
156  *
157  * @adev: amdgpu_device pointer
158  * @cpu_pt_addr: cpu address of the page table
159  * @gpu_page_idx: entry in the page table to update
160  * @addr: dst addr to write into pte/pde
161  * @flags: access flags
162  *
163  * Update the page tables using CPU.
164  */
165 int amdgpu_gmc_set_pte_pde(struct amdgpu_device *adev, void *cpu_pt_addr,
166 				uint32_t gpu_page_idx, uint64_t addr,
167 				uint64_t flags)
168 {
169 	void __iomem *ptr = (void *)cpu_pt_addr;
170 	uint64_t value;
171 
172 	/*
173 	 * The following is for PTE only. GART does not have PDEs.
174 	*/
175 	value = addr & adev->gmc.pte_addr_mask;
176 	value |= flags;
177 	writeq(value, ptr + (gpu_page_idx * 8));
178 
179 	return 0;
180 }
181 
182 /**
183  * amdgpu_gmc_agp_addr - return the address in the AGP address space
184  *
185  * @bo: TTM BO which needs the address, must be in GTT domain
186  *
187  * Tries to figure out how to access the BO through the AGP aperture. Returns
188  * AMDGPU_BO_INVALID_OFFSET if that is not possible.
189  */
190 uint64_t amdgpu_gmc_agp_addr(struct ttm_buffer_object *bo)
191 {
192 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
193 
194 	if (!bo->ttm)
195 		return AMDGPU_BO_INVALID_OFFSET;
196 
197 	if (bo->ttm->num_pages != 1 || bo->ttm->caching == ttm_cached)
198 		return AMDGPU_BO_INVALID_OFFSET;
199 
200 	if (bo->ttm->dma_address[0] + PAGE_SIZE >= adev->gmc.agp_size)
201 		return AMDGPU_BO_INVALID_OFFSET;
202 
203 	return adev->gmc.agp_start + bo->ttm->dma_address[0];
204 }
205 
206 /**
207  * amdgpu_gmc_vram_location - try to find VRAM location
208  *
209  * @adev: amdgpu device structure holding all necessary information
210  * @mc: memory controller structure holding memory information
211  * @base: base address at which to put VRAM
212  *
213  * Function will try to place VRAM at base address provided
214  * as parameter.
215  */
216 void amdgpu_gmc_vram_location(struct amdgpu_device *adev, struct amdgpu_gmc *mc,
217 			      u64 base)
218 {
219 	uint64_t vis_limit = (uint64_t)amdgpu_vis_vram_limit << 20;
220 	uint64_t limit = (uint64_t)amdgpu_vram_limit << 20;
221 
222 	mc->vram_start = base;
223 	mc->vram_end = mc->vram_start + mc->mc_vram_size - 1;
224 	if (limit < mc->real_vram_size)
225 		mc->real_vram_size = limit;
226 
227 	if (vis_limit && vis_limit < mc->visible_vram_size)
228 		mc->visible_vram_size = vis_limit;
229 
230 	if (mc->real_vram_size < mc->visible_vram_size)
231 		mc->visible_vram_size = mc->real_vram_size;
232 
233 	if (mc->xgmi.num_physical_nodes == 0) {
234 		mc->fb_start = mc->vram_start;
235 		mc->fb_end = mc->vram_end;
236 	}
237 	dev_info(adev->dev, "VRAM: %lluM 0x%016llX - 0x%016llX (%lluM used)\n",
238 			mc->mc_vram_size >> 20, mc->vram_start,
239 			mc->vram_end, mc->real_vram_size >> 20);
240 }
241 
242 /** amdgpu_gmc_sysvm_location - place vram and gart in sysvm aperture
243  *
244  * @adev: amdgpu device structure holding all necessary information
245  * @mc: memory controller structure holding memory information
246  *
247  * This function is only used if use GART for FB translation. In such
248  * case, we use sysvm aperture (vmid0 page tables) for both vram
249  * and gart (aka system memory) access.
250  *
251  * GPUVM (and our organization of vmid0 page tables) require sysvm
252  * aperture to be placed at a location aligned with 8 times of native
253  * page size. For example, if vm_context0_cntl.page_table_block_size
254  * is 12, then native page size is 8G (2M*2^12), sysvm should start
255  * with a 64G aligned address. For simplicity, we just put sysvm at
256  * address 0. So vram start at address 0 and gart is right after vram.
257  */
258 void amdgpu_gmc_sysvm_location(struct amdgpu_device *adev, struct amdgpu_gmc *mc)
259 {
260 	u64 hive_vram_start = 0;
261 	u64 hive_vram_end = mc->xgmi.node_segment_size * mc->xgmi.num_physical_nodes - 1;
262 	mc->vram_start = mc->xgmi.node_segment_size * mc->xgmi.physical_node_id;
263 	mc->vram_end = mc->vram_start + mc->xgmi.node_segment_size - 1;
264 	/* node_segment_size may not 4GB aligned on SRIOV, align up is needed. */
265 	mc->gart_start = ALIGN(hive_vram_end + 1, four_gb);
266 	mc->gart_end = mc->gart_start + mc->gart_size - 1;
267 	if (amdgpu_virt_xgmi_migrate_enabled(adev)) {
268 		/* set mc->vram_start to 0 to switch the returned GPU address of
269 		 * amdgpu_bo_create_reserved() from FB aperture to GART aperture.
270 		 */
271 		mc->vram_start = 0;
272 		mc->vram_end = mc->vram_start + mc->mc_vram_size - 1;
273 		mc->visible_vram_size = min(mc->visible_vram_size, mc->real_vram_size);
274 	} else {
275 		mc->fb_start = hive_vram_start;
276 		mc->fb_end = hive_vram_end;
277 	}
278 	dev_info(adev->dev, "VRAM: %lluM 0x%016llX - 0x%016llX (%lluM used)\n",
279 			mc->mc_vram_size >> 20, mc->vram_start,
280 			mc->vram_end, mc->real_vram_size >> 20);
281 	dev_info(adev->dev, "GART: %lluM 0x%016llX - 0x%016llX\n",
282 			mc->gart_size >> 20, mc->gart_start, mc->gart_end);
283 }
284 
285 void amdgpu_gmc_set_gart_size(struct amdgpu_device *adev, u64 default_size)
286 {
287 	if (amdgpu_gart_size == -1)
288 		adev->gmc.gart_size =
289 			default_size + adev->pm.smu_prv_buffer_size;
290 	else
291 		adev->gmc.gart_size = (u64)amdgpu_gart_size << 20;
292 }
293 
294 /**
295  * amdgpu_gmc_gart_location - try to find GART location
296  *
297  * @adev: amdgpu device structure holding all necessary information
298  * @mc: memory controller structure holding memory information
299  * @gart_placement: GART placement policy with respect to VRAM
300  *
301  * Function will try to place GART before or after VRAM.
302  * If GART size is bigger than space left then we ajust GART size.
303  * Thus function will never fails.
304  */
305 void amdgpu_gmc_gart_location(struct amdgpu_device *adev, struct amdgpu_gmc *mc,
306 			      enum amdgpu_gart_placement gart_placement)
307 {
308 	u64 size_af, size_bf;
309 	/*To avoid the hole, limit the max mc address to AMDGPU_GMC_HOLE_START*/
310 	u64 max_mc_address = min(adev->gmc.mc_mask, AMDGPU_GMC_HOLE_START - 1);
311 
312 	/* VCE doesn't like it when BOs cross a 4GB segment, so align
313 	 * the GART base on a 4GB boundary as well.
314 	 */
315 	size_bf = mc->fb_start;
316 	size_af = max_mc_address + 1 - ALIGN(mc->fb_end + 1, four_gb);
317 
318 	if (mc->gart_size > max(size_bf, size_af)) {
319 		dev_warn(adev->dev, "limiting GART\n");
320 		mc->gart_size = max(size_bf, size_af);
321 	}
322 
323 	switch (gart_placement) {
324 	case AMDGPU_GART_PLACEMENT_HIGH:
325 		mc->gart_start = max_mc_address - mc->gart_size + 1;
326 		break;
327 	case AMDGPU_GART_PLACEMENT_LOW:
328 		if (size_bf >= mc->gart_size)
329 			mc->gart_start = 0;
330 		else
331 			mc->gart_start = ALIGN(mc->fb_end, four_gb);
332 		break;
333 	case AMDGPU_GART_PLACEMENT_BEST_FIT:
334 	default:
335 		if ((size_bf >= mc->gart_size && size_bf < size_af) ||
336 		    (size_af < mc->gart_size))
337 			mc->gart_start = 0;
338 		else
339 			mc->gart_start = max_mc_address - mc->gart_size + 1;
340 		break;
341 	}
342 
343 	mc->gart_start &= ~(four_gb - 1);
344 	mc->gart_end = mc->gart_start + mc->gart_size - 1;
345 	dev_info(adev->dev, "GART: %lluM 0x%016llX - 0x%016llX\n",
346 			mc->gart_size >> 20, mc->gart_start, mc->gart_end);
347 }
348 
349 /**
350  * amdgpu_gmc_agp_location - try to find AGP location
351  * @adev: amdgpu device structure holding all necessary information
352  * @mc: memory controller structure holding memory information
353  *
354  * Function will place try to find a place for the AGP BAR in the MC address
355  * space.
356  *
357  * AGP BAR will be assigned the largest available hole in the address space.
358  * Should be called after VRAM and GART locations are setup.
359  */
360 void amdgpu_gmc_agp_location(struct amdgpu_device *adev, struct amdgpu_gmc *mc)
361 {
362 	const uint64_t sixteen_gb = 1ULL << 34;
363 	const uint64_t sixteen_gb_mask = ~(sixteen_gb - 1);
364 	u64 size_af, size_bf;
365 
366 	if (mc->fb_start > mc->gart_start) {
367 		size_bf = (mc->fb_start & sixteen_gb_mask) -
368 			ALIGN(mc->gart_end + 1, sixteen_gb);
369 		size_af = mc->mc_mask + 1 - ALIGN(mc->fb_end + 1, sixteen_gb);
370 	} else {
371 		size_bf = mc->fb_start & sixteen_gb_mask;
372 		size_af = (mc->gart_start & sixteen_gb_mask) -
373 			ALIGN(mc->fb_end + 1, sixteen_gb);
374 	}
375 
376 	if (size_bf > size_af) {
377 		mc->agp_start = (mc->fb_start - size_bf) & sixteen_gb_mask;
378 		mc->agp_size = size_bf;
379 	} else {
380 		mc->agp_start = ALIGN(mc->fb_end + 1, sixteen_gb);
381 		mc->agp_size = size_af;
382 	}
383 
384 	mc->agp_end = mc->agp_start + mc->agp_size - 1;
385 	dev_info(adev->dev, "AGP: %lluM 0x%016llX - 0x%016llX\n",
386 			mc->agp_size >> 20, mc->agp_start, mc->agp_end);
387 }
388 
389 /**
390  * amdgpu_gmc_set_agp_default - Set the default AGP aperture value.
391  * @adev: amdgpu device structure holding all necessary information
392  * @mc: memory controller structure holding memory information
393  *
394  * To disable the AGP aperture, you need to set the start to a larger
395  * value than the end.  This function sets the default value which
396  * can then be overridden using amdgpu_gmc_agp_location() if you want
397  * to enable the AGP aperture on a specific chip.
398  *
399  */
400 void amdgpu_gmc_set_agp_default(struct amdgpu_device *adev,
401 				struct amdgpu_gmc *mc)
402 {
403 	mc->agp_start = 0xffffffffffff;
404 	mc->agp_end = 0;
405 	mc->agp_size = 0;
406 }
407 
408 /**
409  * amdgpu_gmc_fault_key - get hask key from vm fault address and pasid
410  *
411  * @addr: 48 bit physical address, page aligned (36 significant bits)
412  * @pasid: 16 bit process address space identifier
413  */
414 static inline uint64_t amdgpu_gmc_fault_key(uint64_t addr, uint16_t pasid)
415 {
416 	return addr << 4 | pasid;
417 }
418 
419 /**
420  * amdgpu_gmc_filter_faults - filter VM faults
421  *
422  * @adev: amdgpu device structure
423  * @ih: interrupt ring that the fault received from
424  * @addr: address of the VM fault
425  * @pasid: PASID of the process causing the fault
426  * @timestamp: timestamp of the fault
427  *
428  * Returns:
429  * True if the fault was filtered and should not be processed further.
430  * False if the fault is a new one and needs to be handled.
431  */
432 bool amdgpu_gmc_filter_faults(struct amdgpu_device *adev,
433 			      struct amdgpu_ih_ring *ih, uint64_t addr,
434 			      uint16_t pasid, uint64_t timestamp)
435 {
436 	struct amdgpu_gmc *gmc = &adev->gmc;
437 	uint64_t stamp, key = amdgpu_gmc_fault_key(addr, pasid);
438 	struct amdgpu_gmc_fault *fault;
439 	uint32_t hash;
440 
441 	/* Stale retry fault if timestamp goes backward */
442 	if (amdgpu_ih_ts_after(timestamp, ih->processed_timestamp))
443 		return true;
444 
445 	/* If we don't have space left in the ring buffer return immediately */
446 	stamp = max(timestamp, AMDGPU_GMC_FAULT_TIMEOUT + 1) -
447 		AMDGPU_GMC_FAULT_TIMEOUT;
448 	if (gmc->fault_ring[gmc->last_fault].timestamp >= stamp)
449 		return true;
450 
451 	/* Try to find the fault in the hash */
452 	hash = hash_64(key, AMDGPU_GMC_FAULT_HASH_ORDER);
453 	fault = &gmc->fault_ring[gmc->fault_hash[hash].idx];
454 	while (fault->timestamp >= stamp) {
455 		uint64_t tmp;
456 
457 		if (atomic64_read(&fault->key) == key) {
458 			/*
459 			 * if we get a fault which is already present in
460 			 * the fault_ring and the timestamp of
461 			 * the fault is after the expired timestamp,
462 			 * then this is a new fault that needs to be added
463 			 * into the fault ring.
464 			 */
465 			if (fault->timestamp_expiry != 0 &&
466 			    amdgpu_ih_ts_after(fault->timestamp_expiry,
467 					       timestamp))
468 				break;
469 			else
470 				return true;
471 		}
472 
473 		tmp = fault->timestamp;
474 		fault = &gmc->fault_ring[fault->next];
475 
476 		/* Check if the entry was reused */
477 		if (fault->timestamp >= tmp)
478 			break;
479 	}
480 
481 	/* Add the fault to the ring */
482 	fault = &gmc->fault_ring[gmc->last_fault];
483 	atomic64_set(&fault->key, key);
484 	fault->timestamp = timestamp;
485 
486 	/* And update the hash */
487 	fault->next = gmc->fault_hash[hash].idx;
488 	gmc->fault_hash[hash].idx = gmc->last_fault++;
489 	return false;
490 }
491 
492 /**
493  * amdgpu_gmc_filter_faults_remove - remove address from VM faults filter
494  *
495  * @adev: amdgpu device structure
496  * @addr: address of the VM fault
497  * @pasid: PASID of the process causing the fault
498  *
499  * Remove the address from fault filter, then future vm fault on this address
500  * will pass to retry fault handler to recover.
501  */
502 void amdgpu_gmc_filter_faults_remove(struct amdgpu_device *adev, uint64_t addr,
503 				     uint16_t pasid)
504 {
505 	struct amdgpu_gmc *gmc = &adev->gmc;
506 	uint64_t key = amdgpu_gmc_fault_key(addr, pasid);
507 	struct amdgpu_ih_ring *ih;
508 	struct amdgpu_gmc_fault *fault;
509 	uint32_t last_wptr;
510 	uint64_t last_ts;
511 	uint32_t hash;
512 	uint64_t tmp;
513 
514 	if (adev->irq.retry_cam_enabled)
515 		return;
516 	else if (adev->irq.ih1.ring_size)
517 		ih = &adev->irq.ih1;
518 	else if (adev->irq.ih_soft.enabled)
519 		ih = &adev->irq.ih_soft;
520 	else
521 		return;
522 
523 	/* Get the WPTR of the last entry in IH ring */
524 	last_wptr = amdgpu_ih_get_wptr(adev, ih);
525 	/* Order wptr with ring data. */
526 	rmb();
527 	/* Get the timetamp of the last entry in IH ring */
528 	last_ts = amdgpu_ih_decode_iv_ts(adev, ih, last_wptr, -1);
529 
530 	hash = hash_64(key, AMDGPU_GMC_FAULT_HASH_ORDER);
531 	fault = &gmc->fault_ring[gmc->fault_hash[hash].idx];
532 	do {
533 		if (atomic64_read(&fault->key) == key) {
534 			/*
535 			 * Update the timestamp when this fault
536 			 * expired.
537 			 */
538 			fault->timestamp_expiry = last_ts;
539 			break;
540 		}
541 
542 		tmp = fault->timestamp;
543 		fault = &gmc->fault_ring[fault->next];
544 	} while (fault->timestamp < tmp);
545 }
546 
547 int amdgpu_gmc_handle_retry_fault(struct amdgpu_device *adev,
548 				  struct amdgpu_iv_entry *entry,
549 				  u64 addr,
550 				  u32 cam_index,
551 				  u32 node_id,
552 				  bool write_fault)
553 {
554 	int ret;
555 
556 	if (adev->irq.retry_cam_enabled) {
557 		/* Delegate it to a different ring if the hardware hasn't
558 		 * already done it.
559 		 */
560 		if (entry->ih == &adev->irq.ih) {
561 			amdgpu_irq_delegate(adev, entry, 8);
562 			return 1;
563 		}
564 
565 		ret = amdgpu_vm_handle_fault(adev, entry->pasid, entry->vmid, node_id,
566 					     addr, entry->timestamp, write_fault);
567 		WDOORBELL32(adev->irq.retry_cam_doorbell_index, cam_index);
568 		if (ret)
569 			return 1;
570 	} else {
571 		/* Process it only if it's the first fault for this address */
572 		if (entry->ih != &adev->irq.ih_soft &&
573 		    amdgpu_gmc_filter_faults(adev, entry->ih, addr, entry->pasid,
574 					     entry->timestamp))
575 			return 1;
576 
577 		/* Delegate it to a different ring if the hardware hasn't
578 		 * already done it.
579 		 */
580 		if (entry->ih == &adev->irq.ih) {
581 			amdgpu_irq_delegate(adev, entry, 8);
582 			return 1;
583 		}
584 
585 		/* Try to handle the recoverable page faults by filling page
586 		 * tables
587 		 */
588 		if (amdgpu_vm_handle_fault(adev, entry->pasid, entry->vmid, node_id,
589 					   addr, entry->timestamp, write_fault))
590 			return 1;
591 	}
592 	return 0;
593 }
594 
595 int amdgpu_gmc_ras_sw_init(struct amdgpu_device *adev)
596 {
597 	int r;
598 
599 	/* umc ras block */
600 	r = amdgpu_umc_ras_sw_init(adev);
601 	if (r)
602 		return r;
603 
604 	/* mmhub ras block */
605 	r = amdgpu_mmhub_ras_sw_init(adev);
606 	if (r)
607 		return r;
608 
609 	/* hdp ras block */
610 	r = amdgpu_hdp_ras_sw_init(adev);
611 	if (r)
612 		return r;
613 
614 	/* mca.x ras block */
615 	r = amdgpu_mca_mp0_ras_sw_init(adev);
616 	if (r)
617 		return r;
618 
619 	r = amdgpu_mca_mp1_ras_sw_init(adev);
620 	if (r)
621 		return r;
622 
623 	r = amdgpu_mca_mpio_ras_sw_init(adev);
624 	if (r)
625 		return r;
626 
627 	/* xgmi ras block */
628 	r = amdgpu_xgmi_ras_sw_init(adev);
629 	if (r)
630 		return r;
631 
632 	return 0;
633 }
634 
635 	/*
636 	 * The latest engine allocation on gfx9/10 is:
637 	 * Engine 2, 3: firmware
638 	 * Engine 0, 1, 4~16: amdgpu ring,
639 	 *                    subject to change when ring number changes
640 	 * Engine 17: Gart flushes
641 	 */
642 #define AMDGPU_VMHUB_INV_ENG_BITMAP		0x1FFF3
643 
644 int amdgpu_gmc_allocate_vm_inv_eng(struct amdgpu_device *adev)
645 {
646 	struct amdgpu_ring *ring;
647 	unsigned vm_inv_engs[AMDGPU_MAX_VMHUBS] = {0};
648 	unsigned i;
649 	unsigned vmhub, inv_eng;
650 	struct amdgpu_ring *shared_ring;
651 
652 	/* init the vm inv eng for all vmhubs */
653 	for_each_set_bit(i, adev->vmhubs_mask, AMDGPU_MAX_VMHUBS) {
654 		vm_inv_engs[i] = AMDGPU_VMHUB_INV_ENG_BITMAP;
655 		/* reserve engine 5 for firmware */
656 		if (adev->enable_mes)
657 			vm_inv_engs[i] &= ~(1 << 5);
658 		/* reserve engine 6 for uni mes */
659 		if (adev->enable_uni_mes)
660 			vm_inv_engs[i] &= ~(1 << 6);
661 		/* reserve mmhub engine 3 for firmware */
662 		if (adev->enable_umsch_mm)
663 			vm_inv_engs[i] &= ~(1 << 3);
664 	}
665 
666 	for (i = 0; i < adev->num_rings; ++i) {
667 		ring = adev->rings[i];
668 		vmhub = ring->vm_hub;
669 
670 		if (ring == &adev->mes.ring[0] ||
671 		    ring == &adev->mes.ring[1] ||
672 		    ring == &adev->umsch_mm.ring ||
673 		    ring == &adev->cper.ring_buf)
674 			continue;
675 
676 		/* Skip if the ring is a shared ring */
677 		if (amdgpu_sdma_is_shared_inv_eng(adev, ring) ||
678 		    amdgpu_jpeg_is_shared_inv_eng(adev, ring))
679 			continue;
680 
681 		inv_eng = ffs(vm_inv_engs[vmhub]);
682 		if (!inv_eng) {
683 			dev_err(adev->dev, "no VM inv eng for ring %s\n",
684 				ring->name);
685 			return -EINVAL;
686 		}
687 
688 		ring->vm_inv_eng = inv_eng - 1;
689 		vm_inv_engs[vmhub] &= ~(1 << ring->vm_inv_eng);
690 
691 		dev_info(adev->dev, "ring %s uses VM inv eng %u on hub %u\n",
692 			 ring->name, ring->vm_inv_eng, ring->vm_hub);
693 		/* SDMA has a special packet which allows it to use the same
694 		 * invalidation engine for all the rings in one instance.
695 		 * Therefore, we do not allocate a separate VM invalidation engine
696 		 * for SDMA page rings. Instead, they share the VM invalidation
697 		 * engine with the SDMA gfx ring. This change ensures efficient
698 		 * resource management and avoids the issue of insufficient VM
699 		 * invalidation engines.
700 		 */
701 		shared_ring = amdgpu_sdma_get_shared_ring(adev, ring);
702 		if (shared_ring) {
703 			shared_ring->vm_inv_eng = ring->vm_inv_eng;
704 			dev_info(adev->dev, "ring %s shares VM invalidation engine %u with ring %s on hub %u\n",
705 					ring->name, ring->vm_inv_eng, shared_ring->name, ring->vm_hub);
706 			continue;
707 		}
708 
709 		/* All decode rings within one JPEG instance share one VM
710 		 * invalidation engine (no-op unless ring is a JPEG instance's
711 		 * first ring).
712 		 */
713 		amdgpu_jpeg_set_shared_inv_eng(adev, ring);
714 	}
715 
716 	return 0;
717 }
718 
719 void amdgpu_gmc_flush_gpu_tlb(struct amdgpu_device *adev, uint32_t vmid,
720 			      uint32_t vmhub, uint32_t flush_type)
721 {
722 	struct amdgpu_ring *ring;
723 	struct amdgpu_vmhub *hub = &adev->vmhub[vmhub];
724 	struct dma_fence *fence;
725 	struct amdgpu_job *job;
726 	int r;
727 
728 	ring = to_amdgpu_ring(adev->mman.buffer_funcs_scheds[0]);
729 
730 	if (!hub->sdma_invalidation_workaround || vmid ||
731 	    !adev->mman.buffer_funcs_enabled || !adev->ib_pool_ready ||
732 	    !ring->sched.ready) {
733 		/*
734 		 * A GPU reset should flush all TLBs anyway, so no need to do
735 		 * this while one is ongoing.
736 		 */
737 		if (!down_read_trylock(&adev->reset_domain->sem))
738 			return;
739 
740 		if (adev->gmc.flush_tlb_needs_extra_type_2)
741 			adev->gmc.gmc_funcs->flush_gpu_tlb(adev, vmid,
742 							   vmhub, 2);
743 
744 		if (adev->gmc.flush_tlb_needs_extra_type_0 && flush_type == 2)
745 			adev->gmc.gmc_funcs->flush_gpu_tlb(adev, vmid,
746 							   vmhub, 0);
747 
748 		adev->gmc.gmc_funcs->flush_gpu_tlb(adev, vmid, vmhub,
749 						   flush_type);
750 		up_read(&adev->reset_domain->sem);
751 		return;
752 	}
753 
754 	/* The SDMA on Navi 1x has a bug which can theoretically result in memory
755 	 * corruption if an invalidation happens at the same time as an VA
756 	 * translation. Avoid this by doing the invalidation from the SDMA
757 	 * itself at least for GART.
758 	 */
759 	mutex_lock(&adev->mman.default_entity.lock);
760 	r = amdgpu_job_alloc_with_ib(ring->adev, &adev->mman.default_entity.base,
761 				     AMDGPU_FENCE_OWNER_UNDEFINED,
762 				     16 * 4, AMDGPU_IB_POOL_IMMEDIATE,
763 				     AMDGPU_KERNEL_JOB_ID_FLUSH_GPU_TLB,
764 				     &job);
765 	if (r)
766 		goto error_alloc;
767 
768 	job->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gart.bo);
769 	job->vm_needs_flush = true;
770 	job->ibs->ptr[job->ibs->length_dw++] = ring->funcs->nop;
771 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
772 	fence = amdgpu_job_submit(job);
773 	mutex_unlock(&adev->mman.default_entity.lock);
774 
775 	dma_fence_wait(fence, false);
776 	dma_fence_put(fence);
777 
778 	return;
779 
780 error_alloc:
781 	mutex_unlock(&adev->mman.default_entity.lock);
782 	dev_err(adev->dev, "Error flushing GPU TLB using the SDMA (%d)!\n", r);
783 }
784 
785 int amdgpu_gmc_flush_gpu_tlb_pasid(struct amdgpu_device *adev, uint16_t pasid,
786 				   uint32_t flush_type, bool all_hub,
787 				   uint32_t inst)
788 {
789 	struct amdgpu_ring *ring = &adev->gfx.kiq[inst].ring;
790 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[inst];
791 	unsigned int ndw;
792 	int r, cnt = 0;
793 	uint32_t seq;
794 
795 	/*
796 	 * A GPU reset should flush all TLBs anyway, so no need to do
797 	 * this while one is ongoing.
798 	 */
799 	if (!down_read_trylock(&adev->reset_domain->sem))
800 		return 0;
801 
802 	if (!adev->gmc.flush_pasid_uses_kiq || !ring->sched.ready) {
803 
804 		if (!adev->gmc.gmc_funcs->flush_gpu_tlb_pasid) {
805 			r = 0;
806 			goto error_unlock_reset;
807 		}
808 
809 		if (adev->gmc.flush_tlb_needs_extra_type_2)
810 			adev->gmc.gmc_funcs->flush_gpu_tlb_pasid(adev, pasid,
811 								 2, all_hub,
812 								 inst);
813 
814 		if (adev->gmc.flush_tlb_needs_extra_type_0 && flush_type == 2)
815 			adev->gmc.gmc_funcs->flush_gpu_tlb_pasid(adev, pasid,
816 								 0, all_hub,
817 								 inst);
818 
819 		adev->gmc.gmc_funcs->flush_gpu_tlb_pasid(adev, pasid,
820 							 flush_type, all_hub,
821 							 inst);
822 		r = 0;
823 	} else {
824 		/* 2 dwords flush + 8 dwords fence */
825 		ndw = kiq->pmf->invalidate_tlbs_size + 8;
826 
827 		if (adev->gmc.flush_tlb_needs_extra_type_2)
828 			ndw += kiq->pmf->invalidate_tlbs_size;
829 
830 		if (adev->gmc.flush_tlb_needs_extra_type_0)
831 			ndw += kiq->pmf->invalidate_tlbs_size;
832 
833 		spin_lock(&adev->gfx.kiq[inst].ring_lock);
834 		r = amdgpu_ring_alloc(ring, ndw);
835 		if (r) {
836 			spin_unlock(&adev->gfx.kiq[inst].ring_lock);
837 			goto error_unlock_reset;
838 		}
839 		if (adev->gmc.flush_tlb_needs_extra_type_2)
840 			kiq->pmf->kiq_invalidate_tlbs(ring, pasid, 2, all_hub);
841 
842 		if (flush_type == 2 && adev->gmc.flush_tlb_needs_extra_type_0)
843 			kiq->pmf->kiq_invalidate_tlbs(ring, pasid, 0, all_hub);
844 
845 		kiq->pmf->kiq_invalidate_tlbs(ring, pasid, flush_type, all_hub);
846 		r = amdgpu_fence_emit_polling(ring, &seq, MAX_KIQ_REG_WAIT);
847 		if (r) {
848 			amdgpu_ring_undo(ring);
849 			spin_unlock(&adev->gfx.kiq[inst].ring_lock);
850 			goto error_unlock_reset;
851 		}
852 
853 		amdgpu_ring_commit(ring);
854 		spin_unlock(&adev->gfx.kiq[inst].ring_lock);
855 
856 		r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
857 
858 		might_sleep();
859 		while (r < 1 && cnt++ < MAX_KIQ_REG_TRY &&
860 		       !amdgpu_reset_pending(adev->reset_domain)) {
861 			msleep(MAX_KIQ_REG_BAILOUT_INTERVAL);
862 			r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
863 		}
864 
865 		if (cnt > MAX_KIQ_REG_TRY) {
866 			dev_err(adev->dev, "timeout waiting for kiq fence\n");
867 			r = -ETIME;
868 		} else
869 			r = 0;
870 	}
871 
872 error_unlock_reset:
873 	up_read(&adev->reset_domain->sem);
874 	return r;
875 }
876 
877 void amdgpu_gmc_fw_reg_write_reg_wait(struct amdgpu_device *adev,
878 				      uint32_t reg0, uint32_t reg1,
879 				      uint32_t ref, uint32_t mask,
880 				      uint32_t xcc_inst)
881 {
882 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_inst];
883 	struct amdgpu_ring *ring = &kiq->ring;
884 	signed long r, cnt = 0;
885 	unsigned long flags;
886 	uint32_t seq;
887 
888 	if (adev->mes.ring[MES_PIPE_INST(xcc_inst, 0)].sched.ready) {
889 		amdgpu_mes_reg_write_reg_wait(adev, reg0, reg1,
890 					      ref, mask, xcc_inst);
891 		return;
892 	}
893 
894 	spin_lock_irqsave(&kiq->ring_lock, flags);
895 	amdgpu_ring_alloc(ring, 32);
896 	amdgpu_ring_emit_reg_write_reg_wait(ring, reg0, reg1,
897 					    ref, mask);
898 	r = amdgpu_fence_emit_polling(ring, &seq, MAX_KIQ_REG_WAIT);
899 	if (r)
900 		goto failed_undo;
901 
902 	amdgpu_ring_commit(ring);
903 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
904 
905 	r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
906 
907 	/* don't wait anymore for IRQ context */
908 	if (r < 1 && in_interrupt())
909 		goto failed_kiq;
910 
911 	might_sleep();
912 	while (r < 1 && cnt++ < MAX_KIQ_REG_TRY &&
913 	       !amdgpu_reset_pending(adev->reset_domain)) {
914 
915 		msleep(MAX_KIQ_REG_BAILOUT_INTERVAL);
916 		r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
917 	}
918 
919 	if (cnt > MAX_KIQ_REG_TRY)
920 		goto failed_kiq;
921 
922 	return;
923 
924 failed_undo:
925 	amdgpu_ring_undo(ring);
926 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
927 failed_kiq:
928 	dev_err(adev->dev, "failed to write reg %x wait reg %x\n", reg0, reg1);
929 }
930 
931 /**
932  * amdgpu_gmc_tmz_set -- check and set if a device supports TMZ
933  * @adev: amdgpu_device pointer
934  *
935  * Check and set if an the device @adev supports Trusted Memory
936  * Zones (TMZ).
937  */
938 void amdgpu_gmc_tmz_set(struct amdgpu_device *adev)
939 {
940 	switch (amdgpu_ip_version(adev, GC_HWIP, 0)) {
941 	/* RAVEN */
942 	case IP_VERSION(9, 2, 2):
943 	case IP_VERSION(9, 1, 0):
944 	/* RENOIR looks like RAVEN */
945 	case IP_VERSION(9, 3, 0):
946 	/* GC 10.3.7 */
947 	case IP_VERSION(10, 3, 7):
948 	/* GC 11.0.1 */
949 	case IP_VERSION(11, 0, 1):
950 		if (amdgpu_tmz == 0) {
951 			adev->gmc.tmz_enabled = false;
952 			dev_info(adev->dev,
953 				 "Trusted Memory Zone (TMZ) feature disabled (cmd line)\n");
954 		} else {
955 			adev->gmc.tmz_enabled = true;
956 			dev_info(adev->dev,
957 				 "Trusted Memory Zone (TMZ) feature enabled\n");
958 		}
959 		break;
960 	case IP_VERSION(10, 1, 10):
961 	case IP_VERSION(10, 1, 1):
962 	case IP_VERSION(10, 1, 2):
963 	case IP_VERSION(10, 1, 3):
964 	case IP_VERSION(10, 3, 0):
965 	case IP_VERSION(10, 3, 2):
966 	case IP_VERSION(10, 3, 4):
967 	case IP_VERSION(10, 3, 5):
968 	case IP_VERSION(10, 3, 6):
969 	/* VANGOGH */
970 	case IP_VERSION(10, 3, 1):
971 	/* YELLOW_CARP*/
972 	case IP_VERSION(10, 3, 3):
973 	case IP_VERSION(11, 0, 4):
974 	case IP_VERSION(11, 5, 0):
975 	case IP_VERSION(11, 5, 1):
976 	case IP_VERSION(11, 5, 2):
977 	case IP_VERSION(11, 5, 3):
978 	case IP_VERSION(11, 5, 4):
979 	case IP_VERSION(11, 5, 6):
980 	case IP_VERSION(11, 7, 0):
981 	case IP_VERSION(11, 7, 1):
982 		/* Don't enable it by default yet.
983 		 */
984 		if (amdgpu_tmz < 1) {
985 			adev->gmc.tmz_enabled = false;
986 			dev_info(adev->dev,
987 				 "Trusted Memory Zone (TMZ) feature disabled as experimental (default)\n");
988 		} else {
989 			adev->gmc.tmz_enabled = true;
990 			dev_info(adev->dev,
991 				 "Trusted Memory Zone (TMZ) feature enabled as experimental (cmd line)\n");
992 		}
993 		break;
994 	default:
995 		adev->gmc.tmz_enabled = false;
996 		dev_info(adev->dev,
997 			 "Trusted Memory Zone (TMZ) feature not supported\n");
998 		break;
999 	}
1000 }
1001 
1002 /**
1003  * amdgpu_gmc_noretry_set -- set per asic noretry defaults
1004  * @adev: amdgpu_device pointer
1005  *
1006  * Set a per asic default for the no-retry parameter.
1007  *
1008  */
1009 void amdgpu_gmc_noretry_set(struct amdgpu_device *adev)
1010 {
1011 	struct amdgpu_gmc *gmc = &adev->gmc;
1012 	uint32_t gc_ver = amdgpu_ip_version(adev, GC_HWIP, 0);
1013 	bool noretry_default = (gc_ver == IP_VERSION(9, 0, 1) ||
1014 				gc_ver == IP_VERSION(9, 4, 0) ||
1015 				gc_ver == IP_VERSION(9, 4, 1) ||
1016 				gc_ver == IP_VERSION(9, 4, 2) ||
1017 				gc_ver == IP_VERSION(9, 4, 3) ||
1018 				gc_ver == IP_VERSION(9, 4, 4) ||
1019 				gc_ver == IP_VERSION(9, 5, 0) ||
1020 				gc_ver >= IP_VERSION(10, 1, 0));
1021 
1022 	if (!amdgpu_sriov_xnack_support(adev))
1023 		gmc->noretry = 1;
1024 	else
1025 		gmc->noretry = (amdgpu_noretry == -1) ? noretry_default : amdgpu_noretry;
1026 }
1027 
1028 void amdgpu_gmc_set_vm_fault_masks(struct amdgpu_device *adev, int hub_type,
1029 				   bool enable)
1030 {
1031 	struct amdgpu_vmhub *hub;
1032 	u32 tmp, reg, i;
1033 
1034 	hub = &adev->vmhub[hub_type];
1035 	for (i = 0; i < 16; i++) {
1036 		reg = hub->vm_context0_cntl + hub->ctx_distance * i;
1037 
1038 		tmp = (hub_type == AMDGPU_GFXHUB(0)) ?
1039 			RREG32_SOC15_IP(GC, reg) :
1040 			RREG32_SOC15_IP(MMHUB, reg);
1041 
1042 		if (enable)
1043 			tmp |= hub->vm_cntx_cntl_vm_fault;
1044 		else
1045 			tmp &= ~hub->vm_cntx_cntl_vm_fault;
1046 
1047 		(hub_type == AMDGPU_GFXHUB(0)) ?
1048 			WREG32_SOC15_IP(GC, reg, tmp) :
1049 			WREG32_SOC15_IP(MMHUB, reg, tmp);
1050 	}
1051 }
1052 
1053 void amdgpu_gmc_init_vga_resv_regions(struct amdgpu_device *adev)
1054 {
1055 	unsigned size;
1056 
1057 	if (adev->gmc.is_app_apu)
1058 		return;
1059 
1060 	/*
1061 	 * Some ASICs need to reserve a region of video memory to avoid access
1062 	 * from driver
1063 	 */
1064 	/*
1065 	 * TODO:
1066 	 * Currently there is a bug where some memory client outside
1067 	 * of the driver writes to first 8M of VRAM on S3 resume,
1068 	 * this overrides GART which by default gets placed in first 8M and
1069 	 * causes VM_FAULTS once GTT is accessed.
1070 	 * Keep the stolen memory reservation until the while this is not solved.
1071 	 */
1072 	switch (adev->asic_type) {
1073 	case CHIP_VEGA10:
1074 		adev->mman.keep_stolen_vga_memory = true;
1075 		/*
1076 		 * VEGA10 SRIOV VF with MS_HYPERV host needs some firmware reserved area.
1077 		 */
1078 #ifdef CONFIG_X86
1079 		if (amdgpu_sriov_vf(adev) && hypervisor_is_type(X86_HYPER_MS_HYPERV)) {
1080 			amdgpu_ttm_init_vram_resv(adev, AMDGPU_RESV_STOLEN_RESERVED,
1081 						  0x500000, 0x200000, false);
1082 		}
1083 #endif
1084 		break;
1085 	case CHIP_RAVEN:
1086 	case CHIP_RENOIR:
1087 		adev->mman.keep_stolen_vga_memory = true;
1088 		break;
1089 	case CHIP_POLARIS10:
1090 	case CHIP_POLARIS11:
1091 	case CHIP_POLARIS12:
1092 		/* MacBookPros with switchable graphics put VRAM at 0 when
1093 		 * the iGPU is enabled which results in cursor issues if
1094 		 * the cursor ends up at 0.  Reserve vram at 0 in that case.
1095 		 */
1096 		if (adev->gmc.vram_start == 0)
1097 			adev->mman.keep_stolen_vga_memory = true;
1098 		break;
1099 	default:
1100 		adev->mman.keep_stolen_vga_memory = false;
1101 		break;
1102 	}
1103 
1104 	if (amdgpu_sriov_vf(adev) ||
1105 	    !amdgpu_device_has_display_hardware(adev)) {
1106 		size = 0;
1107 	} else {
1108 		size = amdgpu_gmc_get_vbios_fb_size(adev);
1109 
1110 		if (adev->mman.keep_stolen_vga_memory)
1111 			size = max(size, (unsigned)AMDGPU_VBIOS_VGA_ALLOCATION);
1112 	}
1113 
1114 	/* set to 0 if the pre-OS buffer uses up most of vram */
1115 	if ((adev->gmc.real_vram_size - size) < (8 * 1024 * 1024))
1116 		size = 0;
1117 
1118 	if (size > AMDGPU_VBIOS_VGA_ALLOCATION) {
1119 		amdgpu_ttm_init_vram_resv(adev, AMDGPU_RESV_STOLEN_VGA,
1120 					  0, AMDGPU_VBIOS_VGA_ALLOCATION, false);
1121 		amdgpu_ttm_init_vram_resv(adev, AMDGPU_RESV_STOLEN_EXTENDED,
1122 					  AMDGPU_VBIOS_VGA_ALLOCATION,
1123 					  size - AMDGPU_VBIOS_VGA_ALLOCATION, false);
1124 	} else {
1125 		amdgpu_ttm_init_vram_resv(adev, AMDGPU_RESV_STOLEN_VGA,
1126 					  0, size, false);
1127 	}
1128 }
1129 
1130 /**
1131  * amdgpu_gmc_init_pdb0 - initialize PDB0
1132  *
1133  * @adev: amdgpu_device pointer
1134  *
1135  * This function is only used when GART page table is used
1136  * for FB address translatioin. In such a case, we construct
1137  * a 2-level system VM page table: PDB0->PTB, to cover both
1138  * VRAM of the hive and system memory.
1139  *
1140  * PDB0 is static, initialized once on driver initialization.
1141  * The first n entries of PDB0 are used as PTE by setting
1142  * P bit to 1, pointing to VRAM. The n+1'th entry points
1143  * to a big PTB covering system memory.
1144  *
1145  */
1146 void amdgpu_gmc_init_pdb0(struct amdgpu_device *adev)
1147 {
1148 	int i;
1149 	uint64_t flags = adev->gart.gart_pte_flags; //TODO it is UC. explore NC/RW?
1150 	/* Each PDE0 (used as PTE) covers (2^vmid0_page_table_block_size)*2M
1151 	 */
1152 	u64 vram_size = adev->gmc.xgmi.node_segment_size * adev->gmc.xgmi.num_physical_nodes;
1153 	u64 pde0_page_size = (1ULL<<adev->gmc.vmid0_page_table_block_size)<<21;
1154 	u64 vram_addr, vram_end;
1155 	u64 gart_ptb_gpu_pa = amdgpu_gmc_vram_pa(adev, adev->gart.bo);
1156 	int idx;
1157 
1158 	if (!drm_dev_enter(adev_to_drm(adev), &idx))
1159 		return;
1160 
1161 	flags |= AMDGPU_PTE_VALID | AMDGPU_PTE_READABLE;
1162 	flags |= AMDGPU_PTE_WRITEABLE;
1163 	flags |= AMDGPU_PTE_SNOOPED;
1164 	flags |= AMDGPU_PTE_FRAG((adev->gmc.vmid0_page_table_block_size + 9*1));
1165 	flags |= AMDGPU_PDE_PTE_FLAG(adev);
1166 
1167 	vram_addr = adev->vm_manager.vram_base_offset;
1168 	if (!amdgpu_virt_xgmi_migrate_enabled(adev))
1169 		vram_addr -= adev->gmc.xgmi.physical_node_id * adev->gmc.xgmi.node_segment_size;
1170 	vram_end = vram_addr + vram_size;
1171 
1172 	/* The first n PDE0 entries are used as PTE,
1173 	 * pointing to vram
1174 	 */
1175 	for (i = 0; vram_addr < vram_end; i++, vram_addr += pde0_page_size)
1176 		amdgpu_gmc_set_pte_pde(adev, adev->gmc.ptr_pdb0, i, vram_addr, flags);
1177 
1178 	/* The n+1'th PDE0 entry points to a huge
1179 	 * PTB who has more than 512 entries each
1180 	 * pointing to a 4K system page
1181 	 */
1182 	flags = AMDGPU_PTE_VALID;
1183 	flags |= AMDGPU_PTE_SNOOPED | AMDGPU_PDE_BFS_FLAG(adev, 0);
1184 	/* Requires gart_ptb_gpu_pa to be 4K aligned */
1185 	amdgpu_gmc_set_pte_pde(adev, adev->gmc.ptr_pdb0, i, gart_ptb_gpu_pa, flags);
1186 	drm_dev_exit(idx);
1187 }
1188 
1189 /**
1190  * amdgpu_gmc_vram_mc2pa - calculate vram buffer's physical address from MC
1191  * address
1192  *
1193  * @adev: amdgpu_device pointer
1194  * @mc_addr: MC address of buffer
1195  */
1196 uint64_t amdgpu_gmc_vram_mc2pa(struct amdgpu_device *adev, uint64_t mc_addr)
1197 {
1198 	return mc_addr - adev->gmc.vram_start + adev->vm_manager.vram_base_offset;
1199 }
1200 
1201 /**
1202  * amdgpu_gmc_vram_pa - calculate vram buffer object's physical address from
1203  * GPU's view
1204  *
1205  * @adev: amdgpu_device pointer
1206  * @bo: amdgpu buffer object
1207  */
1208 uint64_t amdgpu_gmc_vram_pa(struct amdgpu_device *adev, struct amdgpu_bo *bo)
1209 {
1210 	return amdgpu_gmc_vram_mc2pa(adev, amdgpu_bo_gpu_offset(bo));
1211 }
1212 
1213 int amdgpu_gmc_vram_checking(struct amdgpu_device *adev)
1214 {
1215 	struct amdgpu_bo *vram_bo = NULL;
1216 	uint64_t vram_gpu = 0;
1217 	void *vram_ptr = NULL;
1218 
1219 	int ret, size = 0x100000;
1220 	uint8_t cptr[10];
1221 
1222 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1223 				AMDGPU_GEM_DOMAIN_VRAM,
1224 				&vram_bo,
1225 				&vram_gpu,
1226 				&vram_ptr);
1227 	if (ret)
1228 		return ret;
1229 
1230 	memset(vram_ptr, 0x86, size);
1231 	memset(cptr, 0x86, 10);
1232 
1233 	/**
1234 	 * Check the start, the mid, and the end of the memory if the content of
1235 	 * each byte is the pattern "0x86". If yes, we suppose the vram bo is
1236 	 * workable.
1237 	 *
1238 	 * Note: If check the each byte of whole 1M bo, it will cost too many
1239 	 * seconds, so here, we just pick up three parts for emulation.
1240 	 */
1241 	ret = memcmp(vram_ptr, cptr, 10);
1242 	if (ret) {
1243 		ret = -EIO;
1244 		goto release_buffer;
1245 	}
1246 
1247 	ret = memcmp(vram_ptr + (size / 2), cptr, 10);
1248 	if (ret) {
1249 		ret = -EIO;
1250 		goto release_buffer;
1251 	}
1252 
1253 	ret = memcmp(vram_ptr + size - 10, cptr, 10);
1254 	if (ret) {
1255 		ret = -EIO;
1256 		goto release_buffer;
1257 	}
1258 
1259 release_buffer:
1260 	amdgpu_bo_free_kernel(&vram_bo, &vram_gpu,
1261 			&vram_ptr);
1262 
1263 	return ret;
1264 }
1265 
1266 static const char *nps_desc[] = {
1267 	[AMDGPU_NPS1_PARTITION_MODE] = "NPS1",
1268 	[AMDGPU_NPS2_PARTITION_MODE] = "NPS2",
1269 	[AMDGPU_NPS3_PARTITION_MODE] = "NPS3",
1270 	[AMDGPU_NPS4_PARTITION_MODE] = "NPS4",
1271 	[AMDGPU_NPS6_PARTITION_MODE] = "NPS6",
1272 	[AMDGPU_NPS8_PARTITION_MODE] = "NPS8",
1273 };
1274 
1275 static ssize_t available_memory_partition_show(struct device *dev,
1276 					       struct device_attribute *addr,
1277 					       char *buf)
1278 {
1279 	struct drm_device *ddev = dev_get_drvdata(dev);
1280 	struct amdgpu_device *adev = drm_to_adev(ddev);
1281 	int size = 0, mode;
1282 	char *sep = "";
1283 
1284 	for_each_inst(mode, adev->gmc.supported_nps_modes) {
1285 		size += sysfs_emit_at(buf, size, "%s%s", sep, nps_desc[mode]);
1286 		sep = ", ";
1287 	}
1288 	size += sysfs_emit_at(buf, size, "\n");
1289 
1290 	return size;
1291 }
1292 
1293 static ssize_t current_memory_partition_store(struct device *dev,
1294 					      struct device_attribute *attr,
1295 					      const char *buf, size_t count)
1296 {
1297 	struct drm_device *ddev = dev_get_drvdata(dev);
1298 	struct amdgpu_device *adev = drm_to_adev(ddev);
1299 	enum amdgpu_memory_partition mode;
1300 	struct amdgpu_hive_info *hive;
1301 	int i;
1302 
1303 	mode = UNKNOWN_MEMORY_PARTITION_MODE;
1304 	for_each_inst(i, adev->gmc.supported_nps_modes) {
1305 		if (!strncasecmp(nps_desc[i], buf, strlen(nps_desc[i]))) {
1306 			mode = i;
1307 			break;
1308 		}
1309 	}
1310 
1311 	if (mode == UNKNOWN_MEMORY_PARTITION_MODE)
1312 		return -EINVAL;
1313 
1314 	if (mode == adev->gmc.gmc_funcs->query_mem_partition_mode(adev)) {
1315 		dev_info(
1316 			adev->dev,
1317 			"requested NPS mode is same as current NPS mode, skipping\n");
1318 		return count;
1319 	}
1320 
1321 	/* If device is part of hive, all devices in the hive should request the
1322 	 * same mode. Hence store the requested mode in hive.
1323 	 */
1324 	hive = amdgpu_get_xgmi_hive(adev);
1325 	if (hive) {
1326 		atomic_set(&hive->requested_nps_mode, mode);
1327 		amdgpu_put_xgmi_hive(hive);
1328 	} else {
1329 		adev->gmc.requested_nps_mode = mode;
1330 	}
1331 
1332 	dev_info(
1333 		adev->dev,
1334 		"NPS mode change requested, please remove and reload the driver\n");
1335 
1336 	return count;
1337 }
1338 
1339 static ssize_t current_memory_partition_show(
1340 	struct device *dev, struct device_attribute *addr, char *buf)
1341 {
1342 	struct drm_device *ddev = dev_get_drvdata(dev);
1343 	struct amdgpu_device *adev = drm_to_adev(ddev);
1344 	enum amdgpu_memory_partition mode;
1345 
1346 	/* Only minimal precaution taken to reject requests while in reset */
1347 	if (amdgpu_in_reset(adev))
1348 		return -EPERM;
1349 
1350 	mode = adev->gmc.gmc_funcs->query_mem_partition_mode(adev);
1351 	if ((mode >= ARRAY_SIZE(nps_desc)) ||
1352 	    (BIT(mode) & AMDGPU_ALL_NPS_MASK) != BIT(mode))
1353 		return sysfs_emit(buf, "UNKNOWN\n");
1354 
1355 	return sysfs_emit(buf, "%s\n", nps_desc[mode]);
1356 }
1357 
1358 static DEVICE_ATTR_RW(current_memory_partition);
1359 static DEVICE_ATTR_RO(available_memory_partition);
1360 
1361 int amdgpu_gmc_sysfs_init(struct amdgpu_device *adev)
1362 {
1363 	bool nps_switch_support;
1364 	int r = 0;
1365 
1366 	if (!adev->gmc.gmc_funcs->query_mem_partition_mode)
1367 		return 0;
1368 
1369 	nps_switch_support = !adev->gmc.xgmi.connected_to_cpu &&
1370 			     (hweight32(adev->gmc.supported_nps_modes &
1371 					AMDGPU_ALL_NPS_MASK) > 1);
1372 	if (!nps_switch_support)
1373 		dev_attr_current_memory_partition.attr.mode &=
1374 			~(S_IWUSR | S_IWGRP | S_IWOTH);
1375 	else
1376 		r = device_create_file(adev->dev,
1377 				       &dev_attr_available_memory_partition);
1378 
1379 	if (r)
1380 		return r;
1381 
1382 	return device_create_file(adev->dev,
1383 				  &dev_attr_current_memory_partition);
1384 }
1385 
1386 void amdgpu_gmc_sysfs_fini(struct amdgpu_device *adev)
1387 {
1388 	if (!adev->gmc.gmc_funcs->query_mem_partition_mode)
1389 		return;
1390 
1391 	device_remove_file(adev->dev, &dev_attr_current_memory_partition);
1392 	device_remove_file(adev->dev, &dev_attr_available_memory_partition);
1393 }
1394 
1395 int amdgpu_gmc_get_nps_memranges(struct amdgpu_device *adev,
1396 				 struct amdgpu_mem_partition_info *mem_ranges,
1397 				 uint8_t *exp_ranges)
1398 {
1399 	struct amdgpu_gmc_memrange ranges[AMDGPU_MAX_MEM_RANGES];
1400 	int range_cnt, ret, i, j;
1401 	uint32_t nps_type;
1402 	bool refresh;
1403 
1404 	if (!mem_ranges || !exp_ranges)
1405 		return -EINVAL;
1406 	range_cnt = AMDGPU_MAX_MEM_RANGES;
1407 	refresh = (adev->init_lvl->level != AMDGPU_INIT_LEVEL_MINIMAL_XGMI) &&
1408 		  (adev->gmc.reset_flags & AMDGPU_GMC_INIT_RESET_NPS);
1409 	ret = amdgpu_discovery_get_nps_info(adev, &nps_type, ranges, &range_cnt,
1410 					    refresh);
1411 
1412 	if (ret)
1413 		return ret;
1414 
1415 	/* TODO: For now, expect ranges and partition count to be the same.
1416 	 * Adjust if there are holes expected in any NPS domain.
1417 	 */
1418 	if (*exp_ranges && (range_cnt != *exp_ranges)) {
1419 		dev_warn(
1420 			adev->dev,
1421 			"NPS config mismatch - expected ranges: %d discovery - nps mode: %d, nps ranges: %d",
1422 			*exp_ranges, nps_type, range_cnt);
1423 		ret = -EINVAL;
1424 		goto err;
1425 	}
1426 
1427 	for (i = 0; i < range_cnt; ++i) {
1428 		if (ranges[i].base_address >= ranges[i].limit_address) {
1429 			dev_warn(
1430 				adev->dev,
1431 				"Invalid NPS range - nps mode: %d, range[%d]: base: %llx limit: %llx",
1432 				nps_type, i, ranges[i].base_address,
1433 				ranges[i].limit_address);
1434 			ret = -EINVAL;
1435 			goto err;
1436 		}
1437 
1438 		/* Check for overlaps, not expecting any now */
1439 		for (j = i - 1; j >= 0; j--) {
1440 			if (max(ranges[j].base_address,
1441 				ranges[i].base_address) <=
1442 			    min(ranges[j].limit_address,
1443 				ranges[i].limit_address)) {
1444 				dev_warn(
1445 					adev->dev,
1446 					"overlapping ranges detected [ %llx - %llx ] | [%llx - %llx]",
1447 					ranges[j].base_address,
1448 					ranges[j].limit_address,
1449 					ranges[i].base_address,
1450 					ranges[i].limit_address);
1451 				ret = -EINVAL;
1452 				goto err;
1453 			}
1454 		}
1455 
1456 		mem_ranges[i].range.fpfn =
1457 			(ranges[i].base_address -
1458 			 adev->vm_manager.vram_base_offset) >>
1459 			AMDGPU_GPU_PAGE_SHIFT;
1460 		mem_ranges[i].range.lpfn =
1461 			(ranges[i].limit_address -
1462 			 adev->vm_manager.vram_base_offset) >>
1463 			AMDGPU_GPU_PAGE_SHIFT;
1464 		mem_ranges[i].size =
1465 			ranges[i].limit_address - ranges[i].base_address + 1;
1466 	}
1467 
1468 	if (!*exp_ranges)
1469 		*exp_ranges = range_cnt;
1470 err:
1471 	return ret;
1472 }
1473 
1474 int amdgpu_gmc_request_memory_partition(struct amdgpu_device *adev,
1475 					int nps_mode)
1476 {
1477 	/* Not supported on VF devices and APUs */
1478 	if (amdgpu_sriov_vf(adev) || (adev->flags & AMD_IS_APU))
1479 		return -EOPNOTSUPP;
1480 
1481 	if (!adev->psp.funcs) {
1482 		dev_err(adev->dev,
1483 			"PSP interface not available for nps mode change request");
1484 		return -EINVAL;
1485 	}
1486 
1487 	return psp_memory_partition(&adev->psp, nps_mode);
1488 }
1489 
1490 static inline bool amdgpu_gmc_need_nps_switch_req(struct amdgpu_device *adev,
1491 						  int req_nps_mode,
1492 						  int cur_nps_mode)
1493 {
1494 	return (((BIT(req_nps_mode) & adev->gmc.supported_nps_modes) ==
1495 			BIT(req_nps_mode)) &&
1496 		req_nps_mode != cur_nps_mode);
1497 }
1498 
1499 void amdgpu_gmc_prepare_nps_mode_change(struct amdgpu_device *adev)
1500 {
1501 	int req_nps_mode, cur_nps_mode, r;
1502 	struct amdgpu_hive_info *hive;
1503 
1504 	if (amdgpu_sriov_vf(adev) || !adev->gmc.supported_nps_modes ||
1505 	    !adev->gmc.gmc_funcs->request_mem_partition_mode)
1506 		return;
1507 
1508 	cur_nps_mode = adev->gmc.gmc_funcs->query_mem_partition_mode(adev);
1509 	hive = amdgpu_get_xgmi_hive(adev);
1510 	if (hive) {
1511 		req_nps_mode = atomic_read(&hive->requested_nps_mode);
1512 		if (!amdgpu_gmc_need_nps_switch_req(adev, req_nps_mode,
1513 						    cur_nps_mode)) {
1514 			amdgpu_put_xgmi_hive(hive);
1515 			return;
1516 		}
1517 		r = amdgpu_xgmi_request_nps_change(adev, hive, req_nps_mode);
1518 		amdgpu_put_xgmi_hive(hive);
1519 		goto out;
1520 	}
1521 
1522 	req_nps_mode = adev->gmc.requested_nps_mode;
1523 	if (!amdgpu_gmc_need_nps_switch_req(adev, req_nps_mode, cur_nps_mode))
1524 		return;
1525 
1526 	/* even if this fails, we should let driver unload w/o blocking */
1527 	r = adev->gmc.gmc_funcs->request_mem_partition_mode(adev, req_nps_mode);
1528 out:
1529 	if (r)
1530 		dev_err(adev->dev, "NPS mode change request failed\n");
1531 	else
1532 		dev_info(
1533 			adev->dev,
1534 			"NPS mode change request done, reload driver to complete the change\n");
1535 }
1536 
1537 bool amdgpu_gmc_need_reset_on_init(struct amdgpu_device *adev)
1538 {
1539 	if (adev->gmc.gmc_funcs->need_reset_on_init)
1540 		return adev->gmc.gmc_funcs->need_reset_on_init(adev);
1541 
1542 	return false;
1543 }
1544 
1545 enum amdgpu_memory_partition
1546 amdgpu_gmc_get_vf_memory_partition(struct amdgpu_device *adev)
1547 {
1548 	switch (adev->gmc.num_mem_partitions) {
1549 	case 0:
1550 		return UNKNOWN_MEMORY_PARTITION_MODE;
1551 	case 1:
1552 		return AMDGPU_NPS1_PARTITION_MODE;
1553 	case 2:
1554 		return AMDGPU_NPS2_PARTITION_MODE;
1555 	case 4:
1556 		return AMDGPU_NPS4_PARTITION_MODE;
1557 	case 8:
1558 		return AMDGPU_NPS8_PARTITION_MODE;
1559 	default:
1560 		return AMDGPU_NPS1_PARTITION_MODE;
1561 	}
1562 }
1563 
1564 enum amdgpu_memory_partition
1565 amdgpu_gmc_get_memory_partition(struct amdgpu_device *adev, u32 *supp_modes)
1566 {
1567 	enum amdgpu_memory_partition mode = UNKNOWN_MEMORY_PARTITION_MODE;
1568 
1569 	if (adev->nbio.funcs &&
1570 	    adev->nbio.funcs->get_memory_partition_mode)
1571 		mode = adev->nbio.funcs->get_memory_partition_mode(adev,
1572 								   supp_modes);
1573 	else
1574 		dev_warn(adev->dev, "memory partition mode query is not supported\n");
1575 
1576 	return mode;
1577 }
1578 
1579 enum amdgpu_memory_partition
1580 amdgpu_gmc_query_memory_partition(struct amdgpu_device *adev)
1581 {
1582 	if (amdgpu_sriov_vf(adev))
1583 		return amdgpu_gmc_get_vf_memory_partition(adev);
1584 	else
1585 		return amdgpu_gmc_get_memory_partition(adev, NULL);
1586 }
1587 
1588 static bool amdgpu_gmc_validate_partition_info(struct amdgpu_device *adev)
1589 {
1590 	enum amdgpu_memory_partition mode;
1591 	u32 supp_modes;
1592 	bool valid;
1593 
1594 	mode = amdgpu_gmc_get_memory_partition(adev, &supp_modes);
1595 
1596 	/* Mode detected by hardware not present in supported modes */
1597 	if ((mode != UNKNOWN_MEMORY_PARTITION_MODE) &&
1598 	    !(BIT(mode - 1) & supp_modes))
1599 		return false;
1600 
1601 	switch (mode) {
1602 	case UNKNOWN_MEMORY_PARTITION_MODE:
1603 	case AMDGPU_NPS1_PARTITION_MODE:
1604 		valid = (adev->gmc.num_mem_partitions == 1);
1605 		break;
1606 	case AMDGPU_NPS2_PARTITION_MODE:
1607 		valid = (adev->gmc.num_mem_partitions == 2);
1608 		break;
1609 	case AMDGPU_NPS4_PARTITION_MODE:
1610 		valid = (adev->gmc.num_mem_partitions == 3 ||
1611 			 adev->gmc.num_mem_partitions == 4);
1612 		break;
1613 	case AMDGPU_NPS8_PARTITION_MODE:
1614 		valid = (adev->gmc.num_mem_partitions == 8);
1615 		break;
1616 	default:
1617 		valid = false;
1618 	}
1619 
1620 	return valid;
1621 }
1622 
1623 static bool amdgpu_gmc_is_node_present(int *node_ids, int num_ids, int nid)
1624 {
1625 	int i;
1626 
1627 	/* Check if node with id 'nid' is present in 'node_ids' array */
1628 	for (i = 0; i < num_ids; ++i)
1629 		if (node_ids[i] == nid)
1630 			return true;
1631 
1632 	return false;
1633 }
1634 
1635 static void
1636 amdgpu_gmc_init_acpi_mem_ranges(struct amdgpu_device *adev,
1637 				struct amdgpu_mem_partition_info *mem_ranges)
1638 {
1639 	struct amdgpu_numa_info numa_info;
1640 	int node_ids[AMDGPU_MAX_MEM_RANGES];
1641 	int num_ranges = 0, ret;
1642 	int num_xcc, xcc_id;
1643 	uint32_t xcc_mask;
1644 
1645 	num_xcc = NUM_XCC(adev->gfx.xcc_mask);
1646 	xcc_mask = (1U << num_xcc) - 1;
1647 
1648 	for_each_inst(xcc_id, xcc_mask)	{
1649 		ret = amdgpu_acpi_get_mem_info(adev, xcc_id, &numa_info);
1650 		if (ret)
1651 			continue;
1652 
1653 		if (numa_info.nid == NUMA_NO_NODE) {
1654 			mem_ranges[0].size = numa_info.size;
1655 			mem_ranges[0].numa.node = numa_info.nid;
1656 			num_ranges = 1;
1657 			break;
1658 		}
1659 
1660 		if (amdgpu_gmc_is_node_present(node_ids, num_ranges,
1661 					     numa_info.nid))
1662 			continue;
1663 
1664 		node_ids[num_ranges] = numa_info.nid;
1665 		mem_ranges[num_ranges].numa.node = numa_info.nid;
1666 		mem_ranges[num_ranges].size = numa_info.size;
1667 		++num_ranges;
1668 	}
1669 
1670 	adev->gmc.num_mem_partitions = num_ranges;
1671 }
1672 
1673 void amdgpu_gmc_init_sw_mem_ranges(struct amdgpu_device *adev,
1674 				   struct amdgpu_mem_partition_info *mem_ranges)
1675 {
1676 	enum amdgpu_memory_partition mode;
1677 	u32 start_addr = 0, size;
1678 	int i, r, l;
1679 
1680 	mode = amdgpu_gmc_query_memory_partition(adev);
1681 
1682 	switch (mode) {
1683 	case UNKNOWN_MEMORY_PARTITION_MODE:
1684 		adev->gmc.num_mem_partitions = 0;
1685 		break;
1686 	case AMDGPU_NPS1_PARTITION_MODE:
1687 		adev->gmc.num_mem_partitions = 1;
1688 		break;
1689 	case AMDGPU_NPS2_PARTITION_MODE:
1690 		adev->gmc.num_mem_partitions = 2;
1691 		break;
1692 	case AMDGPU_NPS4_PARTITION_MODE:
1693 		if (adev->flags & AMD_IS_APU)
1694 			adev->gmc.num_mem_partitions = 3;
1695 		else
1696 			adev->gmc.num_mem_partitions = 4;
1697 		break;
1698 	case AMDGPU_NPS8_PARTITION_MODE:
1699 		adev->gmc.num_mem_partitions = 8;
1700 		break;
1701 	default:
1702 		adev->gmc.num_mem_partitions = 1;
1703 		break;
1704 	}
1705 
1706 	/* Use NPS range info, if populated */
1707 	r = amdgpu_gmc_get_nps_memranges(adev, mem_ranges,
1708 					 &adev->gmc.num_mem_partitions);
1709 	if (!r) {
1710 		l = 0;
1711 		for (i = 1; i < adev->gmc.num_mem_partitions; ++i) {
1712 			if (mem_ranges[i].range.lpfn >
1713 			    mem_ranges[i - 1].range.lpfn)
1714 				l = i;
1715 		}
1716 
1717 	} else {
1718 		if (!adev->gmc.num_mem_partitions) {
1719 			dev_warn(adev->dev,
1720 				 "Not able to detect NPS mode, fall back to NPS1\n");
1721 			adev->gmc.num_mem_partitions = 1;
1722 		}
1723 		/* Fallback to sw based calculation */
1724 		size = (adev->gmc.real_vram_size + SZ_16M) >> AMDGPU_GPU_PAGE_SHIFT;
1725 		size /= adev->gmc.num_mem_partitions;
1726 
1727 		for (i = 0; i < adev->gmc.num_mem_partitions; ++i) {
1728 			mem_ranges[i].range.fpfn = start_addr;
1729 			mem_ranges[i].size =
1730 				((u64)size << AMDGPU_GPU_PAGE_SHIFT);
1731 			mem_ranges[i].range.lpfn = start_addr + size - 1;
1732 			start_addr += size;
1733 		}
1734 
1735 		l = adev->gmc.num_mem_partitions - 1;
1736 	}
1737 
1738 	/* Adjust the last one */
1739 	mem_ranges[l].range.lpfn =
1740 		(adev->gmc.real_vram_size >> AMDGPU_GPU_PAGE_SHIFT) - 1;
1741 	mem_ranges[l].size =
1742 		adev->gmc.real_vram_size -
1743 		((u64)mem_ranges[l].range.fpfn << AMDGPU_GPU_PAGE_SHIFT);
1744 }
1745 
1746 int amdgpu_gmc_init_mem_ranges(struct amdgpu_device *adev)
1747 {
1748 	bool valid;
1749 
1750 	adev->gmc.mem_partitions = kzalloc_objs(struct amdgpu_mem_partition_info,
1751 						AMDGPU_MAX_MEM_RANGES);
1752 	if (!adev->gmc.mem_partitions)
1753 		return -ENOMEM;
1754 
1755 	if (adev->gmc.is_app_apu)
1756 		amdgpu_gmc_init_acpi_mem_ranges(adev, adev->gmc.mem_partitions);
1757 	else
1758 		amdgpu_gmc_init_sw_mem_ranges(adev, adev->gmc.mem_partitions);
1759 
1760 	if (amdgpu_sriov_vf(adev))
1761 		valid = true;
1762 	else
1763 		valid = amdgpu_gmc_validate_partition_info(adev);
1764 	if (!valid)
1765 		dev_warn(adev->dev,
1766 			 "Mem ranges not matching with hardware config\n");
1767 
1768 	if (!adev->gmc.num_mem_partitions) {
1769 		dev_err(adev->dev, "num_mem_partitions is zero\n");
1770 		kfree(adev->gmc.mem_partitions);
1771 		adev->gmc.mem_partitions = NULL;
1772 		return -EINVAL;
1773 	}
1774 
1775 	return 0;
1776 }
1777 
1778 int amdgpu_gmc_get_vram_info(struct amdgpu_device *adev,
1779 		int *vram_width, int *vram_type, int *vram_vendor)
1780 {
1781 	int ret = 0;
1782 
1783 	if (adev->flags & AMD_IS_APU)
1784 		return amdgpu_atomfirmware_get_integrated_system_info(adev,
1785 							vram_width, vram_type, vram_vendor);
1786 	switch (amdgpu_ip_version(adev, GC_HWIP, 0)) {
1787 	case IP_VERSION(12, 0, 0):
1788 	case IP_VERSION(12, 0, 1):
1789 		return amdgpu_atomfirmware_get_umc_info(adev,
1790 								vram_width, vram_type, vram_vendor);
1791 	case IP_VERSION(9, 5, 0):
1792 	case IP_VERSION(9, 4, 4):
1793 	case IP_VERSION(9, 4, 3):
1794 		ret = amdgpu_atomfirmware_get_umc_info(adev,
1795 								vram_width, vram_type, vram_vendor);
1796 		if (vram_width && !ret)
1797 			*vram_width *= hweight32(adev->aid_mask);
1798 		return ret;
1799 	default:
1800 		return amdgpu_atomfirmware_get_vram_info(adev,
1801 								vram_width, vram_type, vram_vendor);
1802 	}
1803 	return 0;
1804 }
1805