1 /*
2  * Copyright 2014 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  */
22 
23 #include <linux/bsearch.h>
24 #include <linux/pci.h>
25 #include <linux/slab.h>
26 #include "kfd_priv.h"
27 #include "kfd_device_queue_manager.h"
28 #include "kfd_pm4_headers_vi.h"
29 #include "kfd_pm4_headers_aldebaran.h"
30 #include "cwsr_trap_handler.h"
31 #include "kfd_iommu.h"
32 #include "amdgpu_amdkfd.h"
33 #include "kfd_smi_events.h"
34 #include "kfd_migrate.h"
35 #include "amdgpu.h"
36 
37 #define MQD_SIZE_ALIGNED 768
38 
39 /*
40  * kfd_locked is used to lock the kfd driver during suspend or reset
41  * once locked, kfd driver will stop any further GPU execution.
42  * create process (open) will return -EAGAIN.
43  */
44 static atomic_t kfd_locked = ATOMIC_INIT(0);
45 
46 #ifdef CONFIG_DRM_AMDGPU_CIK
47 extern const struct kfd2kgd_calls gfx_v7_kfd2kgd;
48 #endif
49 extern const struct kfd2kgd_calls gfx_v8_kfd2kgd;
50 extern const struct kfd2kgd_calls gfx_v9_kfd2kgd;
51 extern const struct kfd2kgd_calls arcturus_kfd2kgd;
52 extern const struct kfd2kgd_calls aldebaran_kfd2kgd;
53 extern const struct kfd2kgd_calls gfx_v10_kfd2kgd;
54 extern const struct kfd2kgd_calls gfx_v10_3_kfd2kgd;
55 
56 static int kfd_gtt_sa_init(struct kfd_dev *kfd, unsigned int buf_size,
57 				unsigned int chunk_size);
58 static void kfd_gtt_sa_fini(struct kfd_dev *kfd);
59 
60 static int kfd_resume(struct kfd_dev *kfd);
61 
62 static void kfd_device_info_set_sdma_queue_num(struct kfd_dev *kfd)
63 {
64 	uint32_t sdma_version = kfd->adev->ip_versions[SDMA0_HWIP][0];
65 
66 	switch (sdma_version) {
67 	case IP_VERSION(4, 0, 0):/* VEGA10 */
68 	case IP_VERSION(4, 0, 1):/* VEGA12 */
69 	case IP_VERSION(4, 1, 0):/* RAVEN */
70 	case IP_VERSION(4, 1, 1):/* RAVEN */
71 	case IP_VERSION(4, 1, 2):/* RENOIR */
72 	case IP_VERSION(5, 2, 1):/* VANGOGH */
73 	case IP_VERSION(5, 2, 3):/* YELLOW_CARP */
74 		kfd->device_info.num_sdma_queues_per_engine = 2;
75 		break;
76 	case IP_VERSION(4, 2, 0):/* VEGA20 */
77 	case IP_VERSION(4, 2, 2):/* ARCTURUS */
78 	case IP_VERSION(4, 4, 0):/* ALDEBARAN */
79 	case IP_VERSION(5, 0, 0):/* NAVI10 */
80 	case IP_VERSION(5, 0, 1):/* CYAN_SKILLFISH */
81 	case IP_VERSION(5, 0, 2):/* NAVI14 */
82 	case IP_VERSION(5, 0, 5):/* NAVI12 */
83 	case IP_VERSION(5, 2, 0):/* SIENNA_CICHLID */
84 	case IP_VERSION(5, 2, 2):/* NAVY_FLOUNDER */
85 	case IP_VERSION(5, 2, 4):/* DIMGREY_CAVEFISH */
86 	case IP_VERSION(5, 2, 5):/* BEIGE_GOBY */
87 		kfd->device_info.num_sdma_queues_per_engine = 8;
88 		break;
89 	default:
90 		dev_warn(kfd_device,
91 			"Default sdma queue per engine(8) is set due to mismatch of sdma ip block(SDMA_HWIP:0x%x).\n",
92 			sdma_version);
93 		kfd->device_info.num_sdma_queues_per_engine = 8;
94 	}
95 }
96 
97 static void kfd_device_info_set_event_interrupt_class(struct kfd_dev *kfd)
98 {
99 	uint32_t gc_version = KFD_GC_VERSION(kfd);
100 
101 	switch (gc_version) {
102 	case IP_VERSION(9, 0, 1): /* VEGA10 */
103 	case IP_VERSION(9, 1, 0): /* RAVEN */
104 	case IP_VERSION(9, 2, 1): /* VEGA12 */
105 	case IP_VERSION(9, 2, 2): /* RAVEN */
106 	case IP_VERSION(9, 3, 0): /* RENOIR */
107 	case IP_VERSION(9, 4, 0): /* VEGA20 */
108 	case IP_VERSION(9, 4, 1): /* ARCTURUS */
109 	case IP_VERSION(9, 4, 2): /* ALDEBARAN */
110 	case IP_VERSION(10, 3, 1): /* VANGOGH */
111 	case IP_VERSION(10, 3, 3): /* YELLOW_CARP */
112 	case IP_VERSION(10, 1, 3): /* CYAN_SKILLFISH */
113 	case IP_VERSION(10, 1, 10): /* NAVI10 */
114 	case IP_VERSION(10, 1, 2): /* NAVI12 */
115 	case IP_VERSION(10, 1, 1): /* NAVI14 */
116 	case IP_VERSION(10, 3, 0): /* SIENNA_CICHLID */
117 	case IP_VERSION(10, 3, 2): /* NAVY_FLOUNDER */
118 	case IP_VERSION(10, 3, 4): /* DIMGREY_CAVEFISH */
119 	case IP_VERSION(10, 3, 5): /* BEIGE_GOBY */
120 		kfd->device_info.event_interrupt_class = &event_interrupt_class_v9;
121 		break;
122 	default:
123 		dev_warn(kfd_device, "v9 event interrupt handler is set due to "
124 			"mismatch of gc ip block(GC_HWIP:0x%x).\n", gc_version);
125 		kfd->device_info.event_interrupt_class = &event_interrupt_class_v9;
126 	}
127 }
128 
129 static void kfd_device_info_init(struct kfd_dev *kfd,
130 				 bool vf, uint32_t gfx_target_version)
131 {
132 	uint32_t gc_version = KFD_GC_VERSION(kfd);
133 	uint32_t asic_type = kfd->adev->asic_type;
134 
135 	kfd->device_info.max_pasid_bits = 16;
136 	kfd->device_info.max_no_of_hqd = 24;
137 	kfd->device_info.num_of_watch_points = 4;
138 	kfd->device_info.mqd_size_aligned = MQD_SIZE_ALIGNED;
139 	kfd->device_info.gfx_target_version = gfx_target_version;
140 
141 	if (KFD_IS_SOC15(kfd)) {
142 		kfd->device_info.doorbell_size = 8;
143 		kfd->device_info.ih_ring_entry_size = 8 * sizeof(uint32_t);
144 		kfd->device_info.supports_cwsr = true;
145 
146 		kfd_device_info_set_sdma_queue_num(kfd);
147 
148 		kfd_device_info_set_event_interrupt_class(kfd);
149 
150 		/* Raven */
151 		if (gc_version == IP_VERSION(9, 1, 0) ||
152 		    gc_version == IP_VERSION(9, 2, 2))
153 			kfd->device_info.needs_iommu_device = true;
154 
155 		if (gc_version < IP_VERSION(11, 0, 0)) {
156 			/* Navi2x+, Navi1x+ */
157 			if (gc_version >= IP_VERSION(10, 3, 0))
158 				kfd->device_info.no_atomic_fw_version = 92;
159 			else if (gc_version >= IP_VERSION(10, 1, 1))
160 				kfd->device_info.no_atomic_fw_version = 145;
161 
162 			/* Navi1x+ */
163 			if (gc_version >= IP_VERSION(10, 1, 1))
164 				kfd->device_info.needs_pci_atomics = true;
165 		}
166 	} else {
167 		kfd->device_info.doorbell_size = 4;
168 		kfd->device_info.ih_ring_entry_size = 4 * sizeof(uint32_t);
169 		kfd->device_info.event_interrupt_class = &event_interrupt_class_cik;
170 		kfd->device_info.num_sdma_queues_per_engine = 2;
171 
172 		if (asic_type != CHIP_KAVERI &&
173 		    asic_type != CHIP_HAWAII &&
174 		    asic_type != CHIP_TONGA)
175 			kfd->device_info.supports_cwsr = true;
176 
177 		if (asic_type == CHIP_KAVERI ||
178 		    asic_type == CHIP_CARRIZO)
179 			kfd->device_info.needs_iommu_device = true;
180 
181 		if (asic_type != CHIP_HAWAII && !vf)
182 			kfd->device_info.needs_pci_atomics = true;
183 	}
184 }
185 
186 struct kfd_dev *kgd2kfd_probe(struct amdgpu_device *adev, bool vf)
187 {
188 	struct kfd_dev *kfd = NULL;
189 	const struct kfd2kgd_calls *f2g = NULL;
190 	struct pci_dev *pdev = adev->pdev;
191 	uint32_t gfx_target_version = 0;
192 
193 	switch (adev->asic_type) {
194 #ifdef KFD_SUPPORT_IOMMU_V2
195 #ifdef CONFIG_DRM_AMDGPU_CIK
196 	case CHIP_KAVERI:
197 		gfx_target_version = 70000;
198 		if (!vf)
199 			f2g = &gfx_v7_kfd2kgd;
200 		break;
201 #endif
202 	case CHIP_CARRIZO:
203 		gfx_target_version = 80001;
204 		if (!vf)
205 			f2g = &gfx_v8_kfd2kgd;
206 		break;
207 #endif
208 #ifdef CONFIG_DRM_AMDGPU_CIK
209 	case CHIP_HAWAII:
210 		gfx_target_version = 70001;
211 		if (!amdgpu_exp_hw_support)
212 			pr_info(
213 	"KFD support on Hawaii is experimental. See modparam exp_hw_support\n"
214 				);
215 		else if (!vf)
216 			f2g = &gfx_v7_kfd2kgd;
217 		break;
218 #endif
219 	case CHIP_TONGA:
220 		gfx_target_version = 80002;
221 		if (!vf)
222 			f2g = &gfx_v8_kfd2kgd;
223 		break;
224 	case CHIP_FIJI:
225 		gfx_target_version = 80003;
226 		f2g = &gfx_v8_kfd2kgd;
227 		break;
228 	case CHIP_POLARIS10:
229 		gfx_target_version = 80003;
230 		f2g = &gfx_v8_kfd2kgd;
231 		break;
232 	case CHIP_POLARIS11:
233 		gfx_target_version = 80003;
234 		if (!vf)
235 			f2g = &gfx_v8_kfd2kgd;
236 		break;
237 	case CHIP_POLARIS12:
238 		gfx_target_version = 80003;
239 		if (!vf)
240 			f2g = &gfx_v8_kfd2kgd;
241 		break;
242 	case CHIP_VEGAM:
243 		gfx_target_version = 80003;
244 		if (!vf)
245 			f2g = &gfx_v8_kfd2kgd;
246 		break;
247 	default:
248 		switch (adev->ip_versions[GC_HWIP][0]) {
249 		/* Vega 10 */
250 		case IP_VERSION(9, 0, 1):
251 			gfx_target_version = 90000;
252 			f2g = &gfx_v9_kfd2kgd;
253 			break;
254 #ifdef KFD_SUPPORT_IOMMU_V2
255 		/* Raven */
256 		case IP_VERSION(9, 1, 0):
257 		case IP_VERSION(9, 2, 2):
258 			gfx_target_version = 90002;
259 			if (!vf)
260 				f2g = &gfx_v9_kfd2kgd;
261 			break;
262 #endif
263 		/* Vega12 */
264 		case IP_VERSION(9, 2, 1):
265 			gfx_target_version = 90004;
266 			if (!vf)
267 				f2g = &gfx_v9_kfd2kgd;
268 			break;
269 		/* Renoir */
270 		case IP_VERSION(9, 3, 0):
271 			gfx_target_version = 90012;
272 			if (!vf)
273 				f2g = &gfx_v9_kfd2kgd;
274 			break;
275 		/* Vega20 */
276 		case IP_VERSION(9, 4, 0):
277 			gfx_target_version = 90006;
278 			if (!vf)
279 				f2g = &gfx_v9_kfd2kgd;
280 			break;
281 		/* Arcturus */
282 		case IP_VERSION(9, 4, 1):
283 			gfx_target_version = 90008;
284 			f2g = &arcturus_kfd2kgd;
285 			break;
286 		/* Aldebaran */
287 		case IP_VERSION(9, 4, 2):
288 			gfx_target_version = 90010;
289 			f2g = &aldebaran_kfd2kgd;
290 			break;
291 		/* Navi10 */
292 		case IP_VERSION(10, 1, 10):
293 			gfx_target_version = 100100;
294 			if (!vf)
295 				f2g = &gfx_v10_kfd2kgd;
296 			break;
297 		/* Navi12 */
298 		case IP_VERSION(10, 1, 2):
299 			gfx_target_version = 100101;
300 			f2g = &gfx_v10_kfd2kgd;
301 			break;
302 		/* Navi14 */
303 		case IP_VERSION(10, 1, 1):
304 			gfx_target_version = 100102;
305 			if (!vf)
306 				f2g = &gfx_v10_kfd2kgd;
307 			break;
308 		/* Cyan Skillfish */
309 		case IP_VERSION(10, 1, 3):
310 			gfx_target_version = 100103;
311 			if (!vf)
312 				f2g = &gfx_v10_kfd2kgd;
313 			break;
314 		/* Sienna Cichlid */
315 		case IP_VERSION(10, 3, 0):
316 			gfx_target_version = 100300;
317 			f2g = &gfx_v10_3_kfd2kgd;
318 			break;
319 		/* Navy Flounder */
320 		case IP_VERSION(10, 3, 2):
321 			gfx_target_version = 100301;
322 			f2g = &gfx_v10_3_kfd2kgd;
323 			break;
324 		/* Van Gogh */
325 		case IP_VERSION(10, 3, 1):
326 			gfx_target_version = 100303;
327 			if (!vf)
328 				f2g = &gfx_v10_3_kfd2kgd;
329 			break;
330 		/* Dimgrey Cavefish */
331 		case IP_VERSION(10, 3, 4):
332 			gfx_target_version = 100302;
333 			f2g = &gfx_v10_3_kfd2kgd;
334 			break;
335 		/* Beige Goby */
336 		case IP_VERSION(10, 3, 5):
337 			gfx_target_version = 100304;
338 			f2g = &gfx_v10_3_kfd2kgd;
339 			break;
340 		/* Yellow Carp */
341 		case IP_VERSION(10, 3, 3):
342 			gfx_target_version = 100305;
343 			if (!vf)
344 				f2g = &gfx_v10_3_kfd2kgd;
345 			break;
346 		default:
347 			break;
348 		}
349 		break;
350 	}
351 
352 	if (!f2g) {
353 		if (adev->ip_versions[GC_HWIP][0])
354 			dev_err(kfd_device, "GC IP %06x %s not supported in kfd\n",
355 				adev->ip_versions[GC_HWIP][0], vf ? "VF" : "");
356 		else
357 			dev_err(kfd_device, "%s %s not supported in kfd\n",
358 				amdgpu_asic_name[adev->asic_type], vf ? "VF" : "");
359 		return NULL;
360 	}
361 
362 	kfd = kzalloc(sizeof(*kfd), GFP_KERNEL);
363 	if (!kfd)
364 		return NULL;
365 
366 	kfd->adev = adev;
367 	kfd_device_info_init(kfd, vf, gfx_target_version);
368 	kfd->pdev = pdev;
369 	kfd->init_complete = false;
370 	kfd->kfd2kgd = f2g;
371 	atomic_set(&kfd->compute_profile, 0);
372 
373 	mutex_init(&kfd->doorbell_mutex);
374 	memset(&kfd->doorbell_available_index, 0,
375 		sizeof(kfd->doorbell_available_index));
376 
377 	atomic_set(&kfd->sram_ecc_flag, 0);
378 
379 	ida_init(&kfd->doorbell_ida);
380 
381 	return kfd;
382 }
383 
384 static void kfd_cwsr_init(struct kfd_dev *kfd)
385 {
386 	if (cwsr_enable && kfd->device_info.supports_cwsr) {
387 		if (KFD_GC_VERSION(kfd) < IP_VERSION(9, 0, 1)) {
388 			BUILD_BUG_ON(sizeof(cwsr_trap_gfx8_hex) > PAGE_SIZE);
389 			kfd->cwsr_isa = cwsr_trap_gfx8_hex;
390 			kfd->cwsr_isa_size = sizeof(cwsr_trap_gfx8_hex);
391 		} else if (KFD_GC_VERSION(kfd) == IP_VERSION(9, 4, 1)) {
392 			BUILD_BUG_ON(sizeof(cwsr_trap_arcturus_hex) > PAGE_SIZE);
393 			kfd->cwsr_isa = cwsr_trap_arcturus_hex;
394 			kfd->cwsr_isa_size = sizeof(cwsr_trap_arcturus_hex);
395 		} else if (KFD_GC_VERSION(kfd) == IP_VERSION(9, 4, 2)) {
396 			BUILD_BUG_ON(sizeof(cwsr_trap_aldebaran_hex) > PAGE_SIZE);
397 			kfd->cwsr_isa = cwsr_trap_aldebaran_hex;
398 			kfd->cwsr_isa_size = sizeof(cwsr_trap_aldebaran_hex);
399 		} else if (KFD_GC_VERSION(kfd) < IP_VERSION(10, 1, 1)) {
400 			BUILD_BUG_ON(sizeof(cwsr_trap_gfx9_hex) > PAGE_SIZE);
401 			kfd->cwsr_isa = cwsr_trap_gfx9_hex;
402 			kfd->cwsr_isa_size = sizeof(cwsr_trap_gfx9_hex);
403 		} else if (KFD_GC_VERSION(kfd) < IP_VERSION(10, 3, 0)) {
404 			BUILD_BUG_ON(sizeof(cwsr_trap_nv1x_hex) > PAGE_SIZE);
405 			kfd->cwsr_isa = cwsr_trap_nv1x_hex;
406 			kfd->cwsr_isa_size = sizeof(cwsr_trap_nv1x_hex);
407 		} else {
408 			BUILD_BUG_ON(sizeof(cwsr_trap_gfx10_hex) > PAGE_SIZE);
409 			kfd->cwsr_isa = cwsr_trap_gfx10_hex;
410 			kfd->cwsr_isa_size = sizeof(cwsr_trap_gfx10_hex);
411 		}
412 
413 		kfd->cwsr_enabled = true;
414 	}
415 }
416 
417 static int kfd_gws_init(struct kfd_dev *kfd)
418 {
419 	int ret = 0;
420 
421 	if (kfd->dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS)
422 		return 0;
423 
424 	if (hws_gws_support || (KFD_IS_SOC15(kfd) &&
425 		((KFD_GC_VERSION(kfd) == IP_VERSION(9, 0, 1)
426 			&& kfd->mec2_fw_version >= 0x81b3) ||
427 		(KFD_GC_VERSION(kfd) <= IP_VERSION(9, 4, 0)
428 			&& kfd->mec2_fw_version >= 0x1b3)  ||
429 		(KFD_GC_VERSION(kfd) == IP_VERSION(9, 4, 1)
430 			&& kfd->mec2_fw_version >= 0x30)   ||
431 		(KFD_GC_VERSION(kfd) == IP_VERSION(9, 4, 2)
432 			&& kfd->mec2_fw_version >= 0x28))))
433 		ret = amdgpu_amdkfd_alloc_gws(kfd->adev,
434 				kfd->adev->gds.gws_size, &kfd->gws);
435 
436 	return ret;
437 }
438 
439 static void kfd_smi_init(struct kfd_dev *dev) {
440 	INIT_LIST_HEAD(&dev->smi_clients);
441 	spin_lock_init(&dev->smi_lock);
442 }
443 
444 bool kgd2kfd_device_init(struct kfd_dev *kfd,
445 			 struct drm_device *ddev,
446 			 const struct kgd2kfd_shared_resources *gpu_resources)
447 {
448 	unsigned int size, map_process_packet_size;
449 
450 	kfd->ddev = ddev;
451 	kfd->mec_fw_version = amdgpu_amdkfd_get_fw_version(kfd->adev,
452 			KGD_ENGINE_MEC1);
453 	kfd->mec2_fw_version = amdgpu_amdkfd_get_fw_version(kfd->adev,
454 			KGD_ENGINE_MEC2);
455 	kfd->sdma_fw_version = amdgpu_amdkfd_get_fw_version(kfd->adev,
456 			KGD_ENGINE_SDMA1);
457 	kfd->shared_resources = *gpu_resources;
458 
459 	kfd->vm_info.first_vmid_kfd = ffs(gpu_resources->compute_vmid_bitmap)-1;
460 	kfd->vm_info.last_vmid_kfd = fls(gpu_resources->compute_vmid_bitmap)-1;
461 	kfd->vm_info.vmid_num_kfd = kfd->vm_info.last_vmid_kfd
462 			- kfd->vm_info.first_vmid_kfd + 1;
463 
464 	/* Allow BIF to recode atomics to PCIe 3.0 AtomicOps.
465 	 * 32 and 64-bit requests are possible and must be
466 	 * supported.
467 	 */
468 	kfd->pci_atomic_requested = amdgpu_amdkfd_have_atomics_support(kfd->adev);
469 	if (!kfd->pci_atomic_requested &&
470 	    kfd->device_info.needs_pci_atomics &&
471 	    (!kfd->device_info.no_atomic_fw_version ||
472 	     kfd->mec_fw_version < kfd->device_info.no_atomic_fw_version)) {
473 		dev_info(kfd_device,
474 			 "skipped device %x:%x, PCI rejects atomics %d<%d\n",
475 			 kfd->pdev->vendor, kfd->pdev->device,
476 			 kfd->mec_fw_version,
477 			 kfd->device_info.no_atomic_fw_version);
478 		return false;
479 	}
480 
481 	/* Verify module parameters regarding mapped process number*/
482 	if ((hws_max_conc_proc < 0)
483 			|| (hws_max_conc_proc > kfd->vm_info.vmid_num_kfd)) {
484 		dev_err(kfd_device,
485 			"hws_max_conc_proc %d must be between 0 and %d, use %d instead\n",
486 			hws_max_conc_proc, kfd->vm_info.vmid_num_kfd,
487 			kfd->vm_info.vmid_num_kfd);
488 		kfd->max_proc_per_quantum = kfd->vm_info.vmid_num_kfd;
489 	} else
490 		kfd->max_proc_per_quantum = hws_max_conc_proc;
491 
492 	/* calculate max size of mqds needed for queues */
493 	size = max_num_of_queues_per_device *
494 			kfd->device_info.mqd_size_aligned;
495 
496 	/*
497 	 * calculate max size of runlist packet.
498 	 * There can be only 2 packets at once
499 	 */
500 	map_process_packet_size = KFD_GC_VERSION(kfd) == IP_VERSION(9, 4, 2) ?
501 				sizeof(struct pm4_mes_map_process_aldebaran) :
502 				sizeof(struct pm4_mes_map_process);
503 	size += (KFD_MAX_NUM_OF_PROCESSES * map_process_packet_size +
504 		max_num_of_queues_per_device * sizeof(struct pm4_mes_map_queues)
505 		+ sizeof(struct pm4_mes_runlist)) * 2;
506 
507 	/* Add size of HIQ & DIQ */
508 	size += KFD_KERNEL_QUEUE_SIZE * 2;
509 
510 	/* add another 512KB for all other allocations on gart (HPD, fences) */
511 	size += 512 * 1024;
512 
513 	if (amdgpu_amdkfd_alloc_gtt_mem(
514 			kfd->adev, size, &kfd->gtt_mem,
515 			&kfd->gtt_start_gpu_addr, &kfd->gtt_start_cpu_ptr,
516 			false)) {
517 		dev_err(kfd_device, "Could not allocate %d bytes\n", size);
518 		goto alloc_gtt_mem_failure;
519 	}
520 
521 	dev_info(kfd_device, "Allocated %d bytes on gart\n", size);
522 
523 	/* Initialize GTT sa with 512 byte chunk size */
524 	if (kfd_gtt_sa_init(kfd, size, 512) != 0) {
525 		dev_err(kfd_device, "Error initializing gtt sub-allocator\n");
526 		goto kfd_gtt_sa_init_error;
527 	}
528 
529 	if (kfd_doorbell_init(kfd)) {
530 		dev_err(kfd_device,
531 			"Error initializing doorbell aperture\n");
532 		goto kfd_doorbell_error;
533 	}
534 
535 	kfd->hive_id = kfd->adev->gmc.xgmi.hive_id;
536 
537 	kfd->noretry = kfd->adev->gmc.noretry;
538 
539 	if (kfd_interrupt_init(kfd)) {
540 		dev_err(kfd_device, "Error initializing interrupts\n");
541 		goto kfd_interrupt_error;
542 	}
543 
544 	kfd->dqm = device_queue_manager_init(kfd);
545 	if (!kfd->dqm) {
546 		dev_err(kfd_device, "Error initializing queue manager\n");
547 		goto device_queue_manager_error;
548 	}
549 
550 	/* If supported on this device, allocate global GWS that is shared
551 	 * by all KFD processes
552 	 */
553 	if (kfd_gws_init(kfd)) {
554 		dev_err(kfd_device, "Could not allocate %d gws\n",
555 			kfd->adev->gds.gws_size);
556 		goto gws_error;
557 	}
558 
559 	/* If CRAT is broken, won't set iommu enabled */
560 	kfd_double_confirm_iommu_support(kfd);
561 
562 	if (kfd_iommu_device_init(kfd)) {
563 		kfd->use_iommu_v2 = false;
564 		dev_err(kfd_device, "Error initializing iommuv2\n");
565 		goto device_iommu_error;
566 	}
567 
568 	kfd_cwsr_init(kfd);
569 
570 	svm_migrate_init(kfd->adev);
571 
572 	if(kgd2kfd_resume_iommu(kfd))
573 		goto device_iommu_error;
574 
575 	if (kfd_resume(kfd))
576 		goto kfd_resume_error;
577 
578 	kfd->dbgmgr = NULL;
579 
580 	if (kfd_topology_add_device(kfd)) {
581 		dev_err(kfd_device, "Error adding device to topology\n");
582 		goto kfd_topology_add_device_error;
583 	}
584 
585 	kfd_smi_init(kfd);
586 
587 	kfd->init_complete = true;
588 	dev_info(kfd_device, "added device %x:%x\n", kfd->pdev->vendor,
589 		 kfd->pdev->device);
590 
591 	pr_debug("Starting kfd with the following scheduling policy %d\n",
592 		kfd->dqm->sched_policy);
593 
594 	goto out;
595 
596 kfd_topology_add_device_error:
597 kfd_resume_error:
598 device_iommu_error:
599 gws_error:
600 	device_queue_manager_uninit(kfd->dqm);
601 device_queue_manager_error:
602 	kfd_interrupt_exit(kfd);
603 kfd_interrupt_error:
604 	kfd_doorbell_fini(kfd);
605 kfd_doorbell_error:
606 	kfd_gtt_sa_fini(kfd);
607 kfd_gtt_sa_init_error:
608 	amdgpu_amdkfd_free_gtt_mem(kfd->adev, kfd->gtt_mem);
609 alloc_gtt_mem_failure:
610 	if (kfd->gws)
611 		amdgpu_amdkfd_free_gws(kfd->adev, kfd->gws);
612 	dev_err(kfd_device,
613 		"device %x:%x NOT added due to errors\n",
614 		kfd->pdev->vendor, kfd->pdev->device);
615 out:
616 	return kfd->init_complete;
617 }
618 
619 void kgd2kfd_device_exit(struct kfd_dev *kfd)
620 {
621 	if (kfd->init_complete) {
622 		device_queue_manager_uninit(kfd->dqm);
623 		kfd_interrupt_exit(kfd);
624 		kfd_topology_remove_device(kfd);
625 		kfd_doorbell_fini(kfd);
626 		ida_destroy(&kfd->doorbell_ida);
627 		kfd_gtt_sa_fini(kfd);
628 		amdgpu_amdkfd_free_gtt_mem(kfd->adev, kfd->gtt_mem);
629 		if (kfd->gws)
630 			amdgpu_amdkfd_free_gws(kfd->adev, kfd->gws);
631 	}
632 
633 	kfree(kfd);
634 }
635 
636 int kgd2kfd_pre_reset(struct kfd_dev *kfd)
637 {
638 	if (!kfd->init_complete)
639 		return 0;
640 
641 	kfd_smi_event_update_gpu_reset(kfd, false);
642 
643 	kfd->dqm->ops.pre_reset(kfd->dqm);
644 
645 	kgd2kfd_suspend(kfd, false);
646 
647 	kfd_signal_reset_event(kfd);
648 	return 0;
649 }
650 
651 /*
652  * Fix me. KFD won't be able to resume existing process for now.
653  * We will keep all existing process in a evicted state and
654  * wait the process to be terminated.
655  */
656 
657 int kgd2kfd_post_reset(struct kfd_dev *kfd)
658 {
659 	int ret;
660 
661 	if (!kfd->init_complete)
662 		return 0;
663 
664 	ret = kfd_resume(kfd);
665 	if (ret)
666 		return ret;
667 	atomic_dec(&kfd_locked);
668 
669 	atomic_set(&kfd->sram_ecc_flag, 0);
670 
671 	kfd_smi_event_update_gpu_reset(kfd, true);
672 
673 	return 0;
674 }
675 
676 bool kfd_is_locked(void)
677 {
678 	return  (atomic_read(&kfd_locked) > 0);
679 }
680 
681 void kgd2kfd_suspend(struct kfd_dev *kfd, bool run_pm)
682 {
683 	if (!kfd->init_complete)
684 		return;
685 
686 	/* for runtime suspend, skip locking kfd */
687 	if (!run_pm) {
688 		/* For first KFD device suspend all the KFD processes */
689 		if (atomic_inc_return(&kfd_locked) == 1)
690 			kfd_suspend_all_processes();
691 	}
692 
693 	kfd->dqm->ops.stop(kfd->dqm);
694 	kfd_iommu_suspend(kfd);
695 }
696 
697 int kgd2kfd_resume(struct kfd_dev *kfd, bool run_pm)
698 {
699 	int ret, count;
700 
701 	if (!kfd->init_complete)
702 		return 0;
703 
704 	ret = kfd_resume(kfd);
705 	if (ret)
706 		return ret;
707 
708 	/* for runtime resume, skip unlocking kfd */
709 	if (!run_pm) {
710 		count = atomic_dec_return(&kfd_locked);
711 		WARN_ONCE(count < 0, "KFD suspend / resume ref. error");
712 		if (count == 0)
713 			ret = kfd_resume_all_processes();
714 	}
715 
716 	return ret;
717 }
718 
719 int kgd2kfd_resume_iommu(struct kfd_dev *kfd)
720 {
721 	int err = 0;
722 
723 	err = kfd_iommu_resume(kfd);
724 	if (err)
725 		dev_err(kfd_device,
726 			"Failed to resume IOMMU for device %x:%x\n",
727 			kfd->pdev->vendor, kfd->pdev->device);
728 	return err;
729 }
730 
731 static int kfd_resume(struct kfd_dev *kfd)
732 {
733 	int err = 0;
734 
735 	err = kfd->dqm->ops.start(kfd->dqm);
736 	if (err)
737 		dev_err(kfd_device,
738 			"Error starting queue manager for device %x:%x\n",
739 			kfd->pdev->vendor, kfd->pdev->device);
740 
741 	return err;
742 }
743 
744 static inline void kfd_queue_work(struct workqueue_struct *wq,
745 				  struct work_struct *work)
746 {
747 	int cpu, new_cpu;
748 
749 	cpu = new_cpu = smp_processor_id();
750 	do {
751 		new_cpu = cpumask_next(new_cpu, cpu_online_mask) % nr_cpu_ids;
752 		if (cpu_to_node(new_cpu) == numa_node_id())
753 			break;
754 	} while (cpu != new_cpu);
755 
756 	queue_work_on(new_cpu, wq, work);
757 }
758 
759 /* This is called directly from KGD at ISR. */
760 void kgd2kfd_interrupt(struct kfd_dev *kfd, const void *ih_ring_entry)
761 {
762 	uint32_t patched_ihre[KFD_MAX_RING_ENTRY_SIZE];
763 	bool is_patched = false;
764 	unsigned long flags;
765 
766 	if (!kfd->init_complete)
767 		return;
768 
769 	if (kfd->device_info.ih_ring_entry_size > sizeof(patched_ihre)) {
770 		dev_err_once(kfd_device, "Ring entry too small\n");
771 		return;
772 	}
773 
774 	spin_lock_irqsave(&kfd->interrupt_lock, flags);
775 
776 	if (kfd->interrupts_active
777 	    && interrupt_is_wanted(kfd, ih_ring_entry,
778 				   patched_ihre, &is_patched)
779 	    && enqueue_ih_ring_entry(kfd,
780 				     is_patched ? patched_ihre : ih_ring_entry))
781 		kfd_queue_work(kfd->ih_wq, &kfd->interrupt_work);
782 
783 	spin_unlock_irqrestore(&kfd->interrupt_lock, flags);
784 }
785 
786 int kgd2kfd_quiesce_mm(struct mm_struct *mm)
787 {
788 	struct kfd_process *p;
789 	int r;
790 
791 	/* Because we are called from arbitrary context (workqueue) as opposed
792 	 * to process context, kfd_process could attempt to exit while we are
793 	 * running so the lookup function increments the process ref count.
794 	 */
795 	p = kfd_lookup_process_by_mm(mm);
796 	if (!p)
797 		return -ESRCH;
798 
799 	WARN(debug_evictions, "Evicting pid %d", p->lead_thread->pid);
800 	r = kfd_process_evict_queues(p);
801 
802 	kfd_unref_process(p);
803 	return r;
804 }
805 
806 int kgd2kfd_resume_mm(struct mm_struct *mm)
807 {
808 	struct kfd_process *p;
809 	int r;
810 
811 	/* Because we are called from arbitrary context (workqueue) as opposed
812 	 * to process context, kfd_process could attempt to exit while we are
813 	 * running so the lookup function increments the process ref count.
814 	 */
815 	p = kfd_lookup_process_by_mm(mm);
816 	if (!p)
817 		return -ESRCH;
818 
819 	r = kfd_process_restore_queues(p);
820 
821 	kfd_unref_process(p);
822 	return r;
823 }
824 
825 /** kgd2kfd_schedule_evict_and_restore_process - Schedules work queue that will
826  *   prepare for safe eviction of KFD BOs that belong to the specified
827  *   process.
828  *
829  * @mm: mm_struct that identifies the specified KFD process
830  * @fence: eviction fence attached to KFD process BOs
831  *
832  */
833 int kgd2kfd_schedule_evict_and_restore_process(struct mm_struct *mm,
834 					       struct dma_fence *fence)
835 {
836 	struct kfd_process *p;
837 	unsigned long active_time;
838 	unsigned long delay_jiffies = msecs_to_jiffies(PROCESS_ACTIVE_TIME_MS);
839 
840 	if (!fence)
841 		return -EINVAL;
842 
843 	if (dma_fence_is_signaled(fence))
844 		return 0;
845 
846 	p = kfd_lookup_process_by_mm(mm);
847 	if (!p)
848 		return -ENODEV;
849 
850 	if (fence->seqno == p->last_eviction_seqno)
851 		goto out;
852 
853 	p->last_eviction_seqno = fence->seqno;
854 
855 	/* Avoid KFD process starvation. Wait for at least
856 	 * PROCESS_ACTIVE_TIME_MS before evicting the process again
857 	 */
858 	active_time = get_jiffies_64() - p->last_restore_timestamp;
859 	if (delay_jiffies > active_time)
860 		delay_jiffies -= active_time;
861 	else
862 		delay_jiffies = 0;
863 
864 	/* During process initialization eviction_work.dwork is initialized
865 	 * to kfd_evict_bo_worker
866 	 */
867 	WARN(debug_evictions, "Scheduling eviction of pid %d in %ld jiffies",
868 	     p->lead_thread->pid, delay_jiffies);
869 	schedule_delayed_work(&p->eviction_work, delay_jiffies);
870 out:
871 	kfd_unref_process(p);
872 	return 0;
873 }
874 
875 static int kfd_gtt_sa_init(struct kfd_dev *kfd, unsigned int buf_size,
876 				unsigned int chunk_size)
877 {
878 	unsigned int num_of_longs;
879 
880 	if (WARN_ON(buf_size < chunk_size))
881 		return -EINVAL;
882 	if (WARN_ON(buf_size == 0))
883 		return -EINVAL;
884 	if (WARN_ON(chunk_size == 0))
885 		return -EINVAL;
886 
887 	kfd->gtt_sa_chunk_size = chunk_size;
888 	kfd->gtt_sa_num_of_chunks = buf_size / chunk_size;
889 
890 	num_of_longs = (kfd->gtt_sa_num_of_chunks + BITS_PER_LONG - 1) /
891 		BITS_PER_LONG;
892 
893 	kfd->gtt_sa_bitmap = kcalloc(num_of_longs, sizeof(long), GFP_KERNEL);
894 
895 	if (!kfd->gtt_sa_bitmap)
896 		return -ENOMEM;
897 
898 	pr_debug("gtt_sa_num_of_chunks = %d, gtt_sa_bitmap = %p\n",
899 			kfd->gtt_sa_num_of_chunks, kfd->gtt_sa_bitmap);
900 
901 	mutex_init(&kfd->gtt_sa_lock);
902 
903 	return 0;
904 
905 }
906 
907 static void kfd_gtt_sa_fini(struct kfd_dev *kfd)
908 {
909 	mutex_destroy(&kfd->gtt_sa_lock);
910 	kfree(kfd->gtt_sa_bitmap);
911 }
912 
913 static inline uint64_t kfd_gtt_sa_calc_gpu_addr(uint64_t start_addr,
914 						unsigned int bit_num,
915 						unsigned int chunk_size)
916 {
917 	return start_addr + bit_num * chunk_size;
918 }
919 
920 static inline uint32_t *kfd_gtt_sa_calc_cpu_addr(void *start_addr,
921 						unsigned int bit_num,
922 						unsigned int chunk_size)
923 {
924 	return (uint32_t *) ((uint64_t) start_addr + bit_num * chunk_size);
925 }
926 
927 int kfd_gtt_sa_allocate(struct kfd_dev *kfd, unsigned int size,
928 			struct kfd_mem_obj **mem_obj)
929 {
930 	unsigned int found, start_search, cur_size;
931 
932 	if (size == 0)
933 		return -EINVAL;
934 
935 	if (size > kfd->gtt_sa_num_of_chunks * kfd->gtt_sa_chunk_size)
936 		return -ENOMEM;
937 
938 	*mem_obj = kzalloc(sizeof(struct kfd_mem_obj), GFP_KERNEL);
939 	if (!(*mem_obj))
940 		return -ENOMEM;
941 
942 	pr_debug("Allocated mem_obj = %p for size = %d\n", *mem_obj, size);
943 
944 	start_search = 0;
945 
946 	mutex_lock(&kfd->gtt_sa_lock);
947 
948 kfd_gtt_restart_search:
949 	/* Find the first chunk that is free */
950 	found = find_next_zero_bit(kfd->gtt_sa_bitmap,
951 					kfd->gtt_sa_num_of_chunks,
952 					start_search);
953 
954 	pr_debug("Found = %d\n", found);
955 
956 	/* If there wasn't any free chunk, bail out */
957 	if (found == kfd->gtt_sa_num_of_chunks)
958 		goto kfd_gtt_no_free_chunk;
959 
960 	/* Update fields of mem_obj */
961 	(*mem_obj)->range_start = found;
962 	(*mem_obj)->range_end = found;
963 	(*mem_obj)->gpu_addr = kfd_gtt_sa_calc_gpu_addr(
964 					kfd->gtt_start_gpu_addr,
965 					found,
966 					kfd->gtt_sa_chunk_size);
967 	(*mem_obj)->cpu_ptr = kfd_gtt_sa_calc_cpu_addr(
968 					kfd->gtt_start_cpu_ptr,
969 					found,
970 					kfd->gtt_sa_chunk_size);
971 
972 	pr_debug("gpu_addr = %p, cpu_addr = %p\n",
973 			(uint64_t *) (*mem_obj)->gpu_addr, (*mem_obj)->cpu_ptr);
974 
975 	/* If we need only one chunk, mark it as allocated and get out */
976 	if (size <= kfd->gtt_sa_chunk_size) {
977 		pr_debug("Single bit\n");
978 		set_bit(found, kfd->gtt_sa_bitmap);
979 		goto kfd_gtt_out;
980 	}
981 
982 	/* Otherwise, try to see if we have enough contiguous chunks */
983 	cur_size = size - kfd->gtt_sa_chunk_size;
984 	do {
985 		(*mem_obj)->range_end =
986 			find_next_zero_bit(kfd->gtt_sa_bitmap,
987 					kfd->gtt_sa_num_of_chunks, ++found);
988 		/*
989 		 * If next free chunk is not contiguous than we need to
990 		 * restart our search from the last free chunk we found (which
991 		 * wasn't contiguous to the previous ones
992 		 */
993 		if ((*mem_obj)->range_end != found) {
994 			start_search = found;
995 			goto kfd_gtt_restart_search;
996 		}
997 
998 		/*
999 		 * If we reached end of buffer, bail out with error
1000 		 */
1001 		if (found == kfd->gtt_sa_num_of_chunks)
1002 			goto kfd_gtt_no_free_chunk;
1003 
1004 		/* Check if we don't need another chunk */
1005 		if (cur_size <= kfd->gtt_sa_chunk_size)
1006 			cur_size = 0;
1007 		else
1008 			cur_size -= kfd->gtt_sa_chunk_size;
1009 
1010 	} while (cur_size > 0);
1011 
1012 	pr_debug("range_start = %d, range_end = %d\n",
1013 		(*mem_obj)->range_start, (*mem_obj)->range_end);
1014 
1015 	/* Mark the chunks as allocated */
1016 	for (found = (*mem_obj)->range_start;
1017 		found <= (*mem_obj)->range_end;
1018 		found++)
1019 		set_bit(found, kfd->gtt_sa_bitmap);
1020 
1021 kfd_gtt_out:
1022 	mutex_unlock(&kfd->gtt_sa_lock);
1023 	return 0;
1024 
1025 kfd_gtt_no_free_chunk:
1026 	pr_debug("Allocation failed with mem_obj = %p\n", *mem_obj);
1027 	mutex_unlock(&kfd->gtt_sa_lock);
1028 	kfree(*mem_obj);
1029 	return -ENOMEM;
1030 }
1031 
1032 int kfd_gtt_sa_free(struct kfd_dev *kfd, struct kfd_mem_obj *mem_obj)
1033 {
1034 	unsigned int bit;
1035 
1036 	/* Act like kfree when trying to free a NULL object */
1037 	if (!mem_obj)
1038 		return 0;
1039 
1040 	pr_debug("Free mem_obj = %p, range_start = %d, range_end = %d\n",
1041 			mem_obj, mem_obj->range_start, mem_obj->range_end);
1042 
1043 	mutex_lock(&kfd->gtt_sa_lock);
1044 
1045 	/* Mark the chunks as free */
1046 	for (bit = mem_obj->range_start;
1047 		bit <= mem_obj->range_end;
1048 		bit++)
1049 		clear_bit(bit, kfd->gtt_sa_bitmap);
1050 
1051 	mutex_unlock(&kfd->gtt_sa_lock);
1052 
1053 	kfree(mem_obj);
1054 	return 0;
1055 }
1056 
1057 void kgd2kfd_set_sram_ecc_flag(struct kfd_dev *kfd)
1058 {
1059 	if (kfd)
1060 		atomic_inc(&kfd->sram_ecc_flag);
1061 }
1062 
1063 void kfd_inc_compute_active(struct kfd_dev *kfd)
1064 {
1065 	if (atomic_inc_return(&kfd->compute_profile) == 1)
1066 		amdgpu_amdkfd_set_compute_idle(kfd->adev, false);
1067 }
1068 
1069 void kfd_dec_compute_active(struct kfd_dev *kfd)
1070 {
1071 	int count = atomic_dec_return(&kfd->compute_profile);
1072 
1073 	if (count == 0)
1074 		amdgpu_amdkfd_set_compute_idle(kfd->adev, true);
1075 	WARN_ONCE(count < 0, "Compute profile ref. count error");
1076 }
1077 
1078 void kgd2kfd_smi_event_throttle(struct kfd_dev *kfd, uint64_t throttle_bitmask)
1079 {
1080 	if (kfd && kfd->init_complete)
1081 		kfd_smi_event_update_thermal_throttling(kfd, throttle_bitmask);
1082 }
1083 
1084 /* kfd_get_num_sdma_engines returns the number of PCIe optimized SDMA and
1085  * kfd_get_num_xgmi_sdma_engines returns the number of XGMI SDMA.
1086  * When the device has more than two engines, we reserve two for PCIe to enable
1087  * full-duplex and the rest are used as XGMI.
1088  */
1089 unsigned int kfd_get_num_sdma_engines(struct kfd_dev *kdev)
1090 {
1091 	/* If XGMI is not supported, all SDMA engines are PCIe */
1092 	if (!kdev->adev->gmc.xgmi.supported)
1093 		return kdev->adev->sdma.num_instances;
1094 
1095 	return min(kdev->adev->sdma.num_instances, 2);
1096 }
1097 
1098 unsigned int kfd_get_num_xgmi_sdma_engines(struct kfd_dev *kdev)
1099 {
1100 	/* After reserved for PCIe, the rest of engines are XGMI */
1101 	return kdev->adev->sdma.num_instances - kfd_get_num_sdma_engines(kdev);
1102 }
1103 
1104 #if defined(CONFIG_DEBUG_FS)
1105 
1106 /* This function will send a package to HIQ to hang the HWS
1107  * which will trigger a GPU reset and bring the HWS back to normal state
1108  */
1109 int kfd_debugfs_hang_hws(struct kfd_dev *dev)
1110 {
1111 	if (dev->dqm->sched_policy != KFD_SCHED_POLICY_HWS) {
1112 		pr_err("HWS is not enabled");
1113 		return -EINVAL;
1114 	}
1115 
1116 	return dqm_debugfs_hang_hws(dev->dqm);
1117 }
1118 
1119 #endif
1120