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