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/amd-iommu.h>
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 
31 #define MQD_SIZE_ALIGNED 768
32 
33 static const struct kfd_device_info kaveri_device_info = {
34 	.asic_family = CHIP_KAVERI,
35 	.max_pasid_bits = 16,
36 	/* max num of queues for KV.TODO should be a dynamic value */
37 	.max_no_of_hqd	= 24,
38 	.ih_ring_entry_size = 4 * sizeof(uint32_t),
39 	.event_interrupt_class = &event_interrupt_class_cik,
40 	.num_of_watch_points = 4,
41 	.mqd_size_aligned = MQD_SIZE_ALIGNED
42 };
43 
44 static const struct kfd_device_info carrizo_device_info = {
45 	.asic_family = CHIP_CARRIZO,
46 	.max_pasid_bits = 16,
47 	/* max num of queues for CZ.TODO should be a dynamic value */
48 	.max_no_of_hqd	= 24,
49 	.ih_ring_entry_size = 4 * sizeof(uint32_t),
50 	.event_interrupt_class = &event_interrupt_class_cik,
51 	.num_of_watch_points = 4,
52 	.mqd_size_aligned = MQD_SIZE_ALIGNED
53 };
54 
55 struct kfd_deviceid {
56 	unsigned short did;
57 	const struct kfd_device_info *device_info;
58 };
59 
60 /* Please keep this sorted by increasing device id. */
61 static const struct kfd_deviceid supported_devices[] = {
62 	{ 0x1304, &kaveri_device_info },	/* Kaveri */
63 	{ 0x1305, &kaveri_device_info },	/* Kaveri */
64 	{ 0x1306, &kaveri_device_info },	/* Kaveri */
65 	{ 0x1307, &kaveri_device_info },	/* Kaveri */
66 	{ 0x1309, &kaveri_device_info },	/* Kaveri */
67 	{ 0x130A, &kaveri_device_info },	/* Kaveri */
68 	{ 0x130B, &kaveri_device_info },	/* Kaveri */
69 	{ 0x130C, &kaveri_device_info },	/* Kaveri */
70 	{ 0x130D, &kaveri_device_info },	/* Kaveri */
71 	{ 0x130E, &kaveri_device_info },	/* Kaveri */
72 	{ 0x130F, &kaveri_device_info },	/* Kaveri */
73 	{ 0x1310, &kaveri_device_info },	/* Kaveri */
74 	{ 0x1311, &kaveri_device_info },	/* Kaveri */
75 	{ 0x1312, &kaveri_device_info },	/* Kaveri */
76 	{ 0x1313, &kaveri_device_info },	/* Kaveri */
77 	{ 0x1315, &kaveri_device_info },	/* Kaveri */
78 	{ 0x1316, &kaveri_device_info },	/* Kaveri */
79 	{ 0x1317, &kaveri_device_info },	/* Kaveri */
80 	{ 0x1318, &kaveri_device_info },	/* Kaveri */
81 	{ 0x131B, &kaveri_device_info },	/* Kaveri */
82 	{ 0x131C, &kaveri_device_info },	/* Kaveri */
83 	{ 0x131D, &kaveri_device_info },	/* Kaveri */
84 	{ 0x9870, &carrizo_device_info },	/* Carrizo */
85 	{ 0x9874, &carrizo_device_info },	/* Carrizo */
86 	{ 0x9875, &carrizo_device_info },	/* Carrizo */
87 	{ 0x9876, &carrizo_device_info },	/* Carrizo */
88 	{ 0x9877, &carrizo_device_info }	/* Carrizo */
89 };
90 
91 static int kfd_gtt_sa_init(struct kfd_dev *kfd, unsigned int buf_size,
92 				unsigned int chunk_size);
93 static void kfd_gtt_sa_fini(struct kfd_dev *kfd);
94 
95 static const struct kfd_device_info *lookup_device_info(unsigned short did)
96 {
97 	size_t i;
98 
99 	for (i = 0; i < ARRAY_SIZE(supported_devices); i++) {
100 		if (supported_devices[i].did == did) {
101 			WARN_ON(!supported_devices[i].device_info);
102 			return supported_devices[i].device_info;
103 		}
104 	}
105 
106 	dev_warn(kfd_device, "DID %04x is missing in supported_devices\n",
107 		 did);
108 
109 	return NULL;
110 }
111 
112 struct kfd_dev *kgd2kfd_probe(struct kgd_dev *kgd,
113 	struct pci_dev *pdev, const struct kfd2kgd_calls *f2g)
114 {
115 	struct kfd_dev *kfd;
116 
117 	const struct kfd_device_info *device_info =
118 					lookup_device_info(pdev->device);
119 
120 	if (!device_info) {
121 		dev_err(kfd_device, "kgd2kfd_probe failed\n");
122 		return NULL;
123 	}
124 
125 	kfd = kzalloc(sizeof(*kfd), GFP_KERNEL);
126 	if (!kfd)
127 		return NULL;
128 
129 	kfd->kgd = kgd;
130 	kfd->device_info = device_info;
131 	kfd->pdev = pdev;
132 	kfd->init_complete = false;
133 	kfd->kfd2kgd = f2g;
134 
135 	mutex_init(&kfd->doorbell_mutex);
136 	memset(&kfd->doorbell_available_index, 0,
137 		sizeof(kfd->doorbell_available_index));
138 
139 	return kfd;
140 }
141 
142 static bool device_iommu_pasid_init(struct kfd_dev *kfd)
143 {
144 	const u32 required_iommu_flags = AMD_IOMMU_DEVICE_FLAG_ATS_SUP |
145 					AMD_IOMMU_DEVICE_FLAG_PRI_SUP |
146 					AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
147 
148 	struct amd_iommu_device_info iommu_info;
149 	unsigned int pasid_limit;
150 	int err;
151 
152 	err = amd_iommu_device_info(kfd->pdev, &iommu_info);
153 	if (err < 0) {
154 		dev_err(kfd_device,
155 			"error getting iommu info. is the iommu enabled?\n");
156 		return false;
157 	}
158 
159 	if ((iommu_info.flags & required_iommu_flags) != required_iommu_flags) {
160 		dev_err(kfd_device, "error required iommu flags ats %i, pri %i, pasid %i\n",
161 		       (iommu_info.flags & AMD_IOMMU_DEVICE_FLAG_ATS_SUP) != 0,
162 		       (iommu_info.flags & AMD_IOMMU_DEVICE_FLAG_PRI_SUP) != 0,
163 		       (iommu_info.flags & AMD_IOMMU_DEVICE_FLAG_PASID_SUP)
164 									!= 0);
165 		return false;
166 	}
167 
168 	pasid_limit = min_t(unsigned int,
169 			(unsigned int)(1 << kfd->device_info->max_pasid_bits),
170 			iommu_info.max_pasids);
171 	/*
172 	 * last pasid is used for kernel queues doorbells
173 	 * in the future the last pasid might be used for a kernel thread.
174 	 */
175 	pasid_limit = min_t(unsigned int,
176 				pasid_limit,
177 				kfd->doorbell_process_limit - 1);
178 
179 	err = amd_iommu_init_device(kfd->pdev, pasid_limit);
180 	if (err < 0) {
181 		dev_err(kfd_device, "error initializing iommu device\n");
182 		return false;
183 	}
184 
185 	if (!kfd_set_pasid_limit(pasid_limit)) {
186 		dev_err(kfd_device, "error setting pasid limit\n");
187 		amd_iommu_free_device(kfd->pdev);
188 		return false;
189 	}
190 
191 	return true;
192 }
193 
194 static void iommu_pasid_shutdown_callback(struct pci_dev *pdev, int pasid)
195 {
196 	struct kfd_dev *dev = kfd_device_by_pci_dev(pdev);
197 
198 	if (dev)
199 		kfd_unbind_process_from_device(dev, pasid);
200 }
201 
202 /*
203  * This function called by IOMMU driver on PPR failure
204  */
205 static int iommu_invalid_ppr_cb(struct pci_dev *pdev, int pasid,
206 		unsigned long address, u16 flags)
207 {
208 	struct kfd_dev *dev;
209 
210 	dev_warn(kfd_device,
211 			"Invalid PPR device %x:%x.%x pasid %d address 0x%lX flags 0x%X",
212 			PCI_BUS_NUM(pdev->devfn),
213 			PCI_SLOT(pdev->devfn),
214 			PCI_FUNC(pdev->devfn),
215 			pasid,
216 			address,
217 			flags);
218 
219 	dev = kfd_device_by_pci_dev(pdev);
220 	if (!WARN_ON(!dev))
221 		kfd_signal_iommu_event(dev, pasid, address,
222 			flags & PPR_FAULT_WRITE, flags & PPR_FAULT_EXEC);
223 
224 	return AMD_IOMMU_INV_PRI_RSP_INVALID;
225 }
226 
227 bool kgd2kfd_device_init(struct kfd_dev *kfd,
228 			 const struct kgd2kfd_shared_resources *gpu_resources)
229 {
230 	unsigned int size;
231 
232 	kfd->shared_resources = *gpu_resources;
233 
234 	/* calculate max size of mqds needed for queues */
235 	size = max_num_of_queues_per_device *
236 			kfd->device_info->mqd_size_aligned;
237 
238 	/*
239 	 * calculate max size of runlist packet.
240 	 * There can be only 2 packets at once
241 	 */
242 	size += (KFD_MAX_NUM_OF_PROCESSES * sizeof(struct pm4_mes_map_process) +
243 		max_num_of_queues_per_device * sizeof(struct pm4_mes_map_queues)
244 		+ sizeof(struct pm4_mes_runlist)) * 2;
245 
246 	/* Add size of HIQ & DIQ */
247 	size += KFD_KERNEL_QUEUE_SIZE * 2;
248 
249 	/* add another 512KB for all other allocations on gart (HPD, fences) */
250 	size += 512 * 1024;
251 
252 	if (kfd->kfd2kgd->init_gtt_mem_allocation(
253 			kfd->kgd, size, &kfd->gtt_mem,
254 			&kfd->gtt_start_gpu_addr, &kfd->gtt_start_cpu_ptr)){
255 		dev_err(kfd_device, "Could not allocate %d bytes\n", size);
256 		goto out;
257 	}
258 
259 	dev_info(kfd_device, "Allocated %d bytes on gart\n", size);
260 
261 	/* Initialize GTT sa with 512 byte chunk size */
262 	if (kfd_gtt_sa_init(kfd, size, 512) != 0) {
263 		dev_err(kfd_device, "Error initializing gtt sub-allocator\n");
264 		goto kfd_gtt_sa_init_error;
265 	}
266 
267 	if (kfd_doorbell_init(kfd)) {
268 		dev_err(kfd_device,
269 			"Error initializing doorbell aperture\n");
270 		goto kfd_doorbell_error;
271 	}
272 
273 	if (kfd_topology_add_device(kfd)) {
274 		dev_err(kfd_device, "Error adding device to topology\n");
275 		goto kfd_topology_add_device_error;
276 	}
277 
278 	if (kfd_interrupt_init(kfd)) {
279 		dev_err(kfd_device, "Error initializing interrupts\n");
280 		goto kfd_interrupt_error;
281 	}
282 
283 	if (!device_iommu_pasid_init(kfd)) {
284 		dev_err(kfd_device,
285 			"Error initializing iommuv2 for device %x:%x\n",
286 			kfd->pdev->vendor, kfd->pdev->device);
287 		goto device_iommu_pasid_error;
288 	}
289 	amd_iommu_set_invalidate_ctx_cb(kfd->pdev,
290 						iommu_pasid_shutdown_callback);
291 	amd_iommu_set_invalid_ppr_cb(kfd->pdev, iommu_invalid_ppr_cb);
292 
293 	kfd->dqm = device_queue_manager_init(kfd);
294 	if (!kfd->dqm) {
295 		dev_err(kfd_device, "Error initializing queue manager\n");
296 		goto device_queue_manager_error;
297 	}
298 
299 	if (kfd->dqm->ops.start(kfd->dqm)) {
300 		dev_err(kfd_device,
301 			"Error starting queue manager for device %x:%x\n",
302 			kfd->pdev->vendor, kfd->pdev->device);
303 		goto dqm_start_error;
304 	}
305 
306 	kfd->dbgmgr = NULL;
307 
308 	kfd->init_complete = true;
309 	dev_info(kfd_device, "added device %x:%x\n", kfd->pdev->vendor,
310 		 kfd->pdev->device);
311 
312 	pr_debug("Starting kfd with the following scheduling policy %d\n",
313 		sched_policy);
314 
315 	goto out;
316 
317 dqm_start_error:
318 	device_queue_manager_uninit(kfd->dqm);
319 device_queue_manager_error:
320 	amd_iommu_free_device(kfd->pdev);
321 device_iommu_pasid_error:
322 	kfd_interrupt_exit(kfd);
323 kfd_interrupt_error:
324 	kfd_topology_remove_device(kfd);
325 kfd_topology_add_device_error:
326 	kfd_doorbell_fini(kfd);
327 kfd_doorbell_error:
328 	kfd_gtt_sa_fini(kfd);
329 kfd_gtt_sa_init_error:
330 	kfd->kfd2kgd->free_gtt_mem(kfd->kgd, kfd->gtt_mem);
331 	dev_err(kfd_device,
332 		"device %x:%x NOT added due to errors\n",
333 		kfd->pdev->vendor, kfd->pdev->device);
334 out:
335 	return kfd->init_complete;
336 }
337 
338 void kgd2kfd_device_exit(struct kfd_dev *kfd)
339 {
340 	if (kfd->init_complete) {
341 		device_queue_manager_uninit(kfd->dqm);
342 		amd_iommu_free_device(kfd->pdev);
343 		kfd_interrupt_exit(kfd);
344 		kfd_topology_remove_device(kfd);
345 		kfd_doorbell_fini(kfd);
346 		kfd_gtt_sa_fini(kfd);
347 		kfd->kfd2kgd->free_gtt_mem(kfd->kgd, kfd->gtt_mem);
348 	}
349 
350 	kfree(kfd);
351 }
352 
353 void kgd2kfd_suspend(struct kfd_dev *kfd)
354 {
355 	if (kfd->init_complete) {
356 		kfd->dqm->ops.stop(kfd->dqm);
357 		amd_iommu_set_invalidate_ctx_cb(kfd->pdev, NULL);
358 		amd_iommu_set_invalid_ppr_cb(kfd->pdev, NULL);
359 		amd_iommu_free_device(kfd->pdev);
360 	}
361 }
362 
363 int kgd2kfd_resume(struct kfd_dev *kfd)
364 {
365 	unsigned int pasid_limit;
366 	int err;
367 
368 	pasid_limit = kfd_get_pasid_limit();
369 
370 	if (kfd->init_complete) {
371 		err = amd_iommu_init_device(kfd->pdev, pasid_limit);
372 		if (err < 0) {
373 			dev_err(kfd_device, "failed to initialize iommu\n");
374 			return -ENXIO;
375 		}
376 
377 		amd_iommu_set_invalidate_ctx_cb(kfd->pdev,
378 						iommu_pasid_shutdown_callback);
379 		amd_iommu_set_invalid_ppr_cb(kfd->pdev, iommu_invalid_ppr_cb);
380 		kfd->dqm->ops.start(kfd->dqm);
381 	}
382 
383 	return 0;
384 }
385 
386 /* This is called directly from KGD at ISR. */
387 void kgd2kfd_interrupt(struct kfd_dev *kfd, const void *ih_ring_entry)
388 {
389 	if (!kfd->init_complete)
390 		return;
391 
392 	spin_lock(&kfd->interrupt_lock);
393 
394 	if (kfd->interrupts_active
395 	    && interrupt_is_wanted(kfd, ih_ring_entry)
396 	    && enqueue_ih_ring_entry(kfd, ih_ring_entry))
397 		schedule_work(&kfd->interrupt_work);
398 
399 	spin_unlock(&kfd->interrupt_lock);
400 }
401 
402 static int kfd_gtt_sa_init(struct kfd_dev *kfd, unsigned int buf_size,
403 				unsigned int chunk_size)
404 {
405 	unsigned int num_of_longs;
406 
407 	if (WARN_ON(buf_size < chunk_size))
408 		return -EINVAL;
409 	if (WARN_ON(buf_size == 0))
410 		return -EINVAL;
411 	if (WARN_ON(chunk_size == 0))
412 		return -EINVAL;
413 
414 	kfd->gtt_sa_chunk_size = chunk_size;
415 	kfd->gtt_sa_num_of_chunks = buf_size / chunk_size;
416 
417 	num_of_longs = (kfd->gtt_sa_num_of_chunks + BITS_PER_LONG - 1) /
418 		BITS_PER_LONG;
419 
420 	kfd->gtt_sa_bitmap = kcalloc(num_of_longs, sizeof(long), GFP_KERNEL);
421 
422 	if (!kfd->gtt_sa_bitmap)
423 		return -ENOMEM;
424 
425 	pr_debug("gtt_sa_num_of_chunks = %d, gtt_sa_bitmap = %p\n",
426 			kfd->gtt_sa_num_of_chunks, kfd->gtt_sa_bitmap);
427 
428 	mutex_init(&kfd->gtt_sa_lock);
429 
430 	return 0;
431 
432 }
433 
434 static void kfd_gtt_sa_fini(struct kfd_dev *kfd)
435 {
436 	mutex_destroy(&kfd->gtt_sa_lock);
437 	kfree(kfd->gtt_sa_bitmap);
438 }
439 
440 static inline uint64_t kfd_gtt_sa_calc_gpu_addr(uint64_t start_addr,
441 						unsigned int bit_num,
442 						unsigned int chunk_size)
443 {
444 	return start_addr + bit_num * chunk_size;
445 }
446 
447 static inline uint32_t *kfd_gtt_sa_calc_cpu_addr(void *start_addr,
448 						unsigned int bit_num,
449 						unsigned int chunk_size)
450 {
451 	return (uint32_t *) ((uint64_t) start_addr + bit_num * chunk_size);
452 }
453 
454 int kfd_gtt_sa_allocate(struct kfd_dev *kfd, unsigned int size,
455 			struct kfd_mem_obj **mem_obj)
456 {
457 	unsigned int found, start_search, cur_size;
458 
459 	if (size == 0)
460 		return -EINVAL;
461 
462 	if (size > kfd->gtt_sa_num_of_chunks * kfd->gtt_sa_chunk_size)
463 		return -ENOMEM;
464 
465 	*mem_obj = kmalloc(sizeof(struct kfd_mem_obj), GFP_KERNEL);
466 	if ((*mem_obj) == NULL)
467 		return -ENOMEM;
468 
469 	pr_debug("Allocated mem_obj = %p for size = %d\n", *mem_obj, size);
470 
471 	start_search = 0;
472 
473 	mutex_lock(&kfd->gtt_sa_lock);
474 
475 kfd_gtt_restart_search:
476 	/* Find the first chunk that is free */
477 	found = find_next_zero_bit(kfd->gtt_sa_bitmap,
478 					kfd->gtt_sa_num_of_chunks,
479 					start_search);
480 
481 	pr_debug("Found = %d\n", found);
482 
483 	/* If there wasn't any free chunk, bail out */
484 	if (found == kfd->gtt_sa_num_of_chunks)
485 		goto kfd_gtt_no_free_chunk;
486 
487 	/* Update fields of mem_obj */
488 	(*mem_obj)->range_start = found;
489 	(*mem_obj)->range_end = found;
490 	(*mem_obj)->gpu_addr = kfd_gtt_sa_calc_gpu_addr(
491 					kfd->gtt_start_gpu_addr,
492 					found,
493 					kfd->gtt_sa_chunk_size);
494 	(*mem_obj)->cpu_ptr = kfd_gtt_sa_calc_cpu_addr(
495 					kfd->gtt_start_cpu_ptr,
496 					found,
497 					kfd->gtt_sa_chunk_size);
498 
499 	pr_debug("gpu_addr = %p, cpu_addr = %p\n",
500 			(uint64_t *) (*mem_obj)->gpu_addr, (*mem_obj)->cpu_ptr);
501 
502 	/* If we need only one chunk, mark it as allocated and get out */
503 	if (size <= kfd->gtt_sa_chunk_size) {
504 		pr_debug("Single bit\n");
505 		set_bit(found, kfd->gtt_sa_bitmap);
506 		goto kfd_gtt_out;
507 	}
508 
509 	/* Otherwise, try to see if we have enough contiguous chunks */
510 	cur_size = size - kfd->gtt_sa_chunk_size;
511 	do {
512 		(*mem_obj)->range_end =
513 			find_next_zero_bit(kfd->gtt_sa_bitmap,
514 					kfd->gtt_sa_num_of_chunks, ++found);
515 		/*
516 		 * If next free chunk is not contiguous than we need to
517 		 * restart our search from the last free chunk we found (which
518 		 * wasn't contiguous to the previous ones
519 		 */
520 		if ((*mem_obj)->range_end != found) {
521 			start_search = found;
522 			goto kfd_gtt_restart_search;
523 		}
524 
525 		/*
526 		 * If we reached end of buffer, bail out with error
527 		 */
528 		if (found == kfd->gtt_sa_num_of_chunks)
529 			goto kfd_gtt_no_free_chunk;
530 
531 		/* Check if we don't need another chunk */
532 		if (cur_size <= kfd->gtt_sa_chunk_size)
533 			cur_size = 0;
534 		else
535 			cur_size -= kfd->gtt_sa_chunk_size;
536 
537 	} while (cur_size > 0);
538 
539 	pr_debug("range_start = %d, range_end = %d\n",
540 		(*mem_obj)->range_start, (*mem_obj)->range_end);
541 
542 	/* Mark the chunks as allocated */
543 	for (found = (*mem_obj)->range_start;
544 		found <= (*mem_obj)->range_end;
545 		found++)
546 		set_bit(found, kfd->gtt_sa_bitmap);
547 
548 kfd_gtt_out:
549 	mutex_unlock(&kfd->gtt_sa_lock);
550 	return 0;
551 
552 kfd_gtt_no_free_chunk:
553 	pr_debug("Allocation failed with mem_obj = %p\n", mem_obj);
554 	mutex_unlock(&kfd->gtt_sa_lock);
555 	kfree(mem_obj);
556 	return -ENOMEM;
557 }
558 
559 int kfd_gtt_sa_free(struct kfd_dev *kfd, struct kfd_mem_obj *mem_obj)
560 {
561 	unsigned int bit;
562 
563 	/* Act like kfree when trying to free a NULL object */
564 	if (!mem_obj)
565 		return 0;
566 
567 	pr_debug("Free mem_obj = %p, range_start = %d, range_end = %d\n",
568 			mem_obj, mem_obj->range_start, mem_obj->range_end);
569 
570 	mutex_lock(&kfd->gtt_sa_lock);
571 
572 	/* Mark the chunks as free */
573 	for (bit = mem_obj->range_start;
574 		bit <= mem_obj->range_end;
575 		bit++)
576 		clear_bit(bit, kfd->gtt_sa_bitmap);
577 
578 	mutex_unlock(&kfd->gtt_sa_lock);
579 
580 	kfree(mem_obj);
581 	return 0;
582 }
583