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