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