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