xref: /openbsd/sys/dev/pci/drm/amd/amdgpu/amdgpu_dma_buf.c (revision 905646f0)
1 /*
2  * Copyright 2019 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  * based on nouveau_prime.c
23  *
24  * Authors: Alex Deucher
25  */
26 
27 /**
28  * DOC: PRIME Buffer Sharing
29  *
30  * The following callback implementations are used for :ref:`sharing GEM buffer
31  * objects between different devices via PRIME <prime_buffer_sharing>`.
32  */
33 
34 #include "amdgpu.h"
35 #include "amdgpu_display.h"
36 #include "amdgpu_gem.h"
37 #include "amdgpu_dma_buf.h"
38 #include <drm/amdgpu_drm.h>
39 #include <linux/dma-buf.h>
40 #include <linux/dma-fence-array.h>
41 
42 /**
43  * amdgpu_gem_prime_vmap - &dma_buf_ops.vmap implementation
44  * @obj: GEM BO
45  *
46  * Sets up an in-kernel virtual mapping of the BO's memory.
47  *
48  * Returns:
49  * The virtual address of the mapping or an error pointer.
50  */
51 void *amdgpu_gem_prime_vmap(struct drm_gem_object *obj)
52 {
53 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
54 	int ret;
55 
56 	ret = ttm_bo_kmap(&bo->tbo, 0, bo->tbo.num_pages,
57 			  &bo->dma_buf_vmap);
58 	if (ret)
59 		return ERR_PTR(ret);
60 
61 	return bo->dma_buf_vmap.virtual;
62 }
63 
64 /**
65  * amdgpu_gem_prime_vunmap - &dma_buf_ops.vunmap implementation
66  * @obj: GEM BO
67  * @vaddr: Virtual address (unused)
68  *
69  * Tears down the in-kernel virtual mapping of the BO's memory.
70  */
71 void amdgpu_gem_prime_vunmap(struct drm_gem_object *obj, void *vaddr)
72 {
73 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
74 
75 	ttm_bo_kunmap(&bo->dma_buf_vmap);
76 }
77 
78 #ifdef notyet
79 
80 /**
81  * amdgpu_gem_prime_mmap - &drm_driver.gem_prime_mmap implementation
82  * @obj: GEM BO
83  * @vma: Virtual memory area
84  *
85  * Sets up a userspace mapping of the BO's memory in the given
86  * virtual memory area.
87  *
88  * Returns:
89  * 0 on success or a negative error code on failure.
90  */
91 int amdgpu_gem_prime_mmap(struct drm_gem_object *obj,
92 			  struct vm_area_struct *vma)
93 {
94 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
95 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
96 	unsigned asize = amdgpu_bo_size(bo);
97 	int ret;
98 
99 	if (!vma->vm_file)
100 		return -ENODEV;
101 
102 	if (adev == NULL)
103 		return -ENODEV;
104 
105 	/* Check for valid size. */
106 	if (asize < vma->vm_end - vma->vm_start)
107 		return -EINVAL;
108 
109 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) ||
110 	    (bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)) {
111 		return -EPERM;
112 	}
113 	vma->vm_pgoff += amdgpu_bo_mmap_offset(bo) >> PAGE_SHIFT;
114 
115 	/* prime mmap does not need to check access, so allow here */
116 	ret = drm_vma_node_allow(&obj->vma_node, vma->vm_file->private_data);
117 	if (ret)
118 		return ret;
119 
120 	ret = ttm_bo_mmap(vma->vm_file, vma, &adev->mman.bdev);
121 	drm_vma_node_revoke(&obj->vma_node, vma->vm_file->private_data);
122 
123 	return ret;
124 }
125 
126 static int
127 __dma_resv_make_exclusive(struct dma_resv *obj)
128 {
129 	struct dma_fence **fences;
130 	unsigned int count;
131 	int r;
132 
133 	if (!dma_resv_get_list(obj)) /* no shared fences to convert */
134 		return 0;
135 
136 	r = dma_resv_get_fences_rcu(obj, NULL, &count, &fences);
137 	if (r)
138 		return r;
139 
140 	if (count == 0) {
141 		/* Now that was unexpected. */
142 	} else if (count == 1) {
143 		dma_resv_add_excl_fence(obj, fences[0]);
144 		dma_fence_put(fences[0]);
145 		kfree(fences);
146 	} else {
147 		struct dma_fence_array *array;
148 
149 		array = dma_fence_array_create(count, fences,
150 					       dma_fence_context_alloc(1), 0,
151 					       false);
152 		if (!array)
153 			goto err_fences_put;
154 
155 		dma_resv_add_excl_fence(obj, &array->base);
156 		dma_fence_put(&array->base);
157 	}
158 
159 	return 0;
160 
161 err_fences_put:
162 	while (count--)
163 		dma_fence_put(fences[count]);
164 	kfree(fences);
165 	return -ENOMEM;
166 }
167 
168 /**
169  * amdgpu_dma_buf_attach - &dma_buf_ops.attach implementation
170  *
171  * @dmabuf: DMA-buf where we attach to
172  * @attach: attachment to add
173  *
174  * Add the attachment as user to the exported DMA-buf.
175  */
176 static int amdgpu_dma_buf_attach(struct dma_buf *dmabuf,
177 				 struct dma_buf_attachment *attach)
178 {
179 	struct drm_gem_object *obj = dmabuf->priv;
180 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
181 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
182 	int r;
183 
184 	if (attach->dev->driver == adev->dev->driver)
185 		return 0;
186 
187 	r = amdgpu_bo_reserve(bo, false);
188 	if (unlikely(r != 0))
189 		return r;
190 
191 	/*
192 	 * We only create shared fences for internal use, but importers
193 	 * of the dmabuf rely on exclusive fences for implicitly
194 	 * tracking write hazards. As any of the current fences may
195 	 * correspond to a write, we need to convert all existing
196 	 * fences on the reservation object into a single exclusive
197 	 * fence.
198 	 */
199 	r = __dma_resv_make_exclusive(bo->tbo.base.resv);
200 	if (r)
201 		return r;
202 
203 	bo->prime_shared_count++;
204 	amdgpu_bo_unreserve(bo);
205 	return 0;
206 }
207 
208 /**
209  * amdgpu_dma_buf_detach - &dma_buf_ops.detach implementation
210  *
211  * @dmabuf: DMA-buf where we remove the attachment from
212  * @attach: the attachment to remove
213  *
214  * Called when an attachment is removed from the DMA-buf.
215  */
216 static void amdgpu_dma_buf_detach(struct dma_buf *dmabuf,
217 				  struct dma_buf_attachment *attach)
218 {
219 	struct drm_gem_object *obj = dmabuf->priv;
220 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
221 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
222 
223 	if (attach->dev->driver != adev->dev->driver && bo->prime_shared_count)
224 		bo->prime_shared_count--;
225 }
226 
227 /**
228  * amdgpu_dma_buf_pin - &dma_buf_ops.pin implementation
229  *
230  * @attach: attachment to pin down
231  *
232  * Pin the BO which is backing the DMA-buf so that it can't move any more.
233  */
234 static int amdgpu_dma_buf_pin(struct dma_buf_attachment *attach)
235 {
236 	struct drm_gem_object *obj = attach->dmabuf->priv;
237 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
238 
239 	/* pin buffer into GTT */
240 	return amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
241 }
242 
243 /**
244  * amdgpu_dma_buf_unpin - &dma_buf_ops.unpin implementation
245  *
246  * @attach: attachment to unpin
247  *
248  * Unpin a previously pinned BO to make it movable again.
249  */
250 static void amdgpu_dma_buf_unpin(struct dma_buf_attachment *attach)
251 {
252 	struct drm_gem_object *obj = attach->dmabuf->priv;
253 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
254 
255 	amdgpu_bo_unpin(bo);
256 }
257 
258 /**
259  * amdgpu_dma_buf_map - &dma_buf_ops.map_dma_buf implementation
260  * @attach: DMA-buf attachment
261  * @dir: DMA direction
262  *
263  * Makes sure that the shared DMA buffer can be accessed by the target device.
264  * For now, simply pins it to the GTT domain, where it should be accessible by
265  * all DMA devices.
266  *
267  * Returns:
268  * sg_table filled with the DMA addresses to use or ERR_PRT with negative error
269  * code.
270  */
271 static struct sg_table *amdgpu_dma_buf_map(struct dma_buf_attachment *attach,
272 					   enum dma_data_direction dir)
273 {
274 	struct dma_buf *dma_buf = attach->dmabuf;
275 	struct drm_gem_object *obj = dma_buf->priv;
276 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
277 	struct sg_table *sgt;
278 	long r;
279 
280 	if (!bo->pin_count) {
281 		/* move buffer into GTT */
282 		struct ttm_operation_ctx ctx = { false, false };
283 
284 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
285 		r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
286 		if (r)
287 			return ERR_PTR(r);
288 
289 	} else if (!(amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type) &
290 		     AMDGPU_GEM_DOMAIN_GTT)) {
291 		return ERR_PTR(-EBUSY);
292 	}
293 
294 	sgt = drm_prime_pages_to_sg(bo->tbo.ttm->pages, bo->tbo.num_pages);
295 	if (IS_ERR(sgt))
296 		return sgt;
297 
298 	if (!dma_map_sg_attrs(attach->dev, sgt->sgl, sgt->nents, dir,
299 			      DMA_ATTR_SKIP_CPU_SYNC))
300 		goto error_free;
301 
302 	return sgt;
303 
304 error_free:
305 	sg_free_table(sgt);
306 	kfree(sgt);
307 	return ERR_PTR(-ENOMEM);
308 }
309 
310 /**
311  * amdgpu_dma_buf_unmap - &dma_buf_ops.unmap_dma_buf implementation
312  * @attach: DMA-buf attachment
313  * @sgt: sg_table to unmap
314  * @dir: DMA direction
315  *
316  * This is called when a shared DMA buffer no longer needs to be accessible by
317  * another device. For now, simply unpins the buffer from GTT.
318  */
319 static void amdgpu_dma_buf_unmap(struct dma_buf_attachment *attach,
320 				 struct sg_table *sgt,
321 				 enum dma_data_direction dir)
322 {
323 	dma_unmap_sg(attach->dev, sgt->sgl, sgt->nents, dir);
324 	sg_free_table(sgt);
325 	kfree(sgt);
326 }
327 
328 /**
329  * amdgpu_dma_buf_begin_cpu_access - &dma_buf_ops.begin_cpu_access implementation
330  * @dma_buf: Shared DMA buffer
331  * @direction: Direction of DMA transfer
332  *
333  * This is called before CPU access to the shared DMA buffer's memory. If it's
334  * a read access, the buffer is moved to the GTT domain if possible, for optimal
335  * CPU read performance.
336  *
337  * Returns:
338  * 0 on success or a negative error code on failure.
339  */
340 static int amdgpu_dma_buf_begin_cpu_access(struct dma_buf *dma_buf,
341 					   enum dma_data_direction direction)
342 {
343 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(dma_buf->priv);
344 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
345 	struct ttm_operation_ctx ctx = { true, false };
346 	u32 domain = amdgpu_display_supported_domains(adev, bo->flags);
347 	int ret;
348 	bool reads = (direction == DMA_BIDIRECTIONAL ||
349 		      direction == DMA_FROM_DEVICE);
350 
351 	if (!reads || !(domain & AMDGPU_GEM_DOMAIN_GTT))
352 		return 0;
353 
354 	/* move to gtt */
355 	ret = amdgpu_bo_reserve(bo, false);
356 	if (unlikely(ret != 0))
357 		return ret;
358 
359 	if (!bo->pin_count && (bo->allowed_domains & AMDGPU_GEM_DOMAIN_GTT)) {
360 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
361 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
362 	}
363 
364 	amdgpu_bo_unreserve(bo);
365 	return ret;
366 }
367 
368 #endif /* notyet */
369 
370 const struct dma_buf_ops amdgpu_dmabuf_ops = {
371 #ifdef notyet
372 	.attach = amdgpu_dma_buf_attach,
373 	.detach = amdgpu_dma_buf_detach,
374 	.pin = amdgpu_dma_buf_pin,
375 	.unpin = amdgpu_dma_buf_unpin,
376 	.map_dma_buf = amdgpu_dma_buf_map,
377 	.unmap_dma_buf = amdgpu_dma_buf_unmap,
378 #endif
379 	.release = drm_gem_dmabuf_release,
380 #ifdef notyet
381 	.begin_cpu_access = amdgpu_dma_buf_begin_cpu_access,
382 	.mmap = drm_gem_dmabuf_mmap,
383 	.vmap = drm_gem_dmabuf_vmap,
384 	.vunmap = drm_gem_dmabuf_vunmap,
385 #endif
386 };
387 
388 /**
389  * amdgpu_gem_prime_export - &drm_driver.gem_prime_export implementation
390  * @gobj: GEM BO
391  * @flags: Flags such as DRM_CLOEXEC and DRM_RDWR.
392  *
393  * The main work is done by the &drm_gem_prime_export helper.
394  *
395  * Returns:
396  * Shared DMA buffer representing the GEM BO from the given device.
397  */
398 struct dma_buf *amdgpu_gem_prime_export(struct drm_gem_object *gobj,
399 					int flags)
400 {
401 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
402 	struct dma_buf *buf;
403 
404 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) ||
405 	    bo->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
406 		return ERR_PTR(-EPERM);
407 
408 	buf = drm_gem_prime_export(gobj, flags);
409 	if (!IS_ERR(buf))
410 		buf->ops = &amdgpu_dmabuf_ops;
411 
412 	return buf;
413 }
414 
415 /**
416  * amdgpu_dma_buf_create_obj - create BO for DMA-buf import
417  *
418  * @dev: DRM device
419  * @dma_buf: DMA-buf
420  *
421  * Creates an empty SG BO for DMA-buf import.
422  *
423  * Returns:
424  * A new GEM BO of the given DRM device, representing the memory
425  * described by the given DMA-buf attachment and scatter/gather table.
426  */
427 static struct drm_gem_object *
428 amdgpu_dma_buf_create_obj(struct drm_device *dev, struct dma_buf *dma_buf)
429 {
430 	struct dma_resv *resv = dma_buf->resv;
431 	struct amdgpu_device *adev = dev->dev_private;
432 	struct amdgpu_bo *bo;
433 	struct amdgpu_bo_param bp;
434 	int ret;
435 
436 	memset(&bp, 0, sizeof(bp));
437 	bp.size = dma_buf->size;
438 	bp.byte_align = PAGE_SIZE;
439 	bp.domain = AMDGPU_GEM_DOMAIN_CPU;
440 	bp.flags = 0;
441 	bp.type = ttm_bo_type_sg;
442 	bp.resv = resv;
443 	dma_resv_lock(resv, NULL);
444 	ret = amdgpu_bo_create(adev, &bp, &bo);
445 	if (ret)
446 		goto error;
447 
448 	bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
449 	bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
450 	if (dma_buf->ops != &amdgpu_dmabuf_ops)
451 		bo->prime_shared_count = 1;
452 
453 	dma_resv_unlock(resv);
454 	return &bo->tbo.base;
455 
456 error:
457 	dma_resv_unlock(resv);
458 	return ERR_PTR(ret);
459 }
460 
461 /**
462  * amdgpu_dma_buf_move_notify - &attach.move_notify implementation
463  *
464  * @attach: the DMA-buf attachment
465  *
466  * Invalidate the DMA-buf attachment, making sure that the we re-create the
467  * mapping before the next use.
468  */
469 static void
470 amdgpu_dma_buf_move_notify(struct dma_buf_attachment *attach)
471 {
472 	struct drm_gem_object *obj = attach->importer_priv;
473 	struct ww_acquire_ctx *ticket = dma_resv_locking_ctx(obj->resv);
474 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
475 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
476 	struct ttm_operation_ctx ctx = { false, false };
477 	struct ttm_placement placement = {};
478 	struct amdgpu_vm_bo_base *bo_base;
479 	int r;
480 
481 	if (bo->tbo.mem.mem_type == TTM_PL_SYSTEM)
482 		return;
483 
484 	r = ttm_bo_validate(&bo->tbo, &placement, &ctx);
485 	if (r) {
486 		DRM_ERROR("Failed to invalidate DMA-buf import (%d))\n", r);
487 		return;
488 	}
489 
490 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
491 		struct amdgpu_vm *vm = bo_base->vm;
492 		struct dma_resv *resv = vm->root.base.bo->tbo.base.resv;
493 
494 		if (ticket) {
495 			/* When we get an error here it means that somebody
496 			 * else is holding the VM lock and updating page tables
497 			 * So we can just continue here.
498 			 */
499 			r = dma_resv_lock(resv, ticket);
500 			if (r)
501 				continue;
502 
503 		} else {
504 			/* TODO: This is more problematic and we actually need
505 			 * to allow page tables updates without holding the
506 			 * lock.
507 			 */
508 			if (!dma_resv_trylock(resv))
509 				continue;
510 		}
511 
512 		r = amdgpu_vm_clear_freed(adev, vm, NULL);
513 		if (!r)
514 			r = amdgpu_vm_handle_moved(adev, vm);
515 
516 		if (r && r != -EBUSY)
517 			DRM_ERROR("Failed to invalidate VM page tables (%d))\n",
518 				  r);
519 
520 		dma_resv_unlock(resv);
521 	}
522 }
523 
524 static const struct dma_buf_attach_ops amdgpu_dma_buf_attach_ops = {
525 	.move_notify = amdgpu_dma_buf_move_notify
526 };
527 
528 /**
529  * amdgpu_gem_prime_import - &drm_driver.gem_prime_import implementation
530  * @dev: DRM device
531  * @dma_buf: Shared DMA buffer
532  *
533  * Import a dma_buf into a the driver and potentially create a new GEM object.
534  *
535  * Returns:
536  * GEM BO representing the shared DMA buffer for the given device.
537  */
538 struct drm_gem_object *amdgpu_gem_prime_import(struct drm_device *dev,
539 					       struct dma_buf *dma_buf)
540 {
541 	struct dma_buf_attachment *attach;
542 	struct drm_gem_object *obj;
543 
544 	if (dma_buf->ops == &amdgpu_dmabuf_ops) {
545 		obj = dma_buf->priv;
546 		if (obj->dev == dev) {
547 			/*
548 			 * Importing dmabuf exported from out own gem increases
549 			 * refcount on gem itself instead of f_count of dmabuf.
550 			 */
551 			drm_gem_object_get(obj);
552 			return obj;
553 		}
554 	}
555 
556 	obj = amdgpu_dma_buf_create_obj(dev, dma_buf);
557 	if (IS_ERR(obj))
558 		return obj;
559 
560 	STUB();
561 #ifdef notyet
562 	attach = dma_buf_dynamic_attach(dma_buf, dev->dev,
563 					&amdgpu_dma_buf_attach_ops, obj);
564 	if (IS_ERR(attach)) {
565 		drm_gem_object_put_unlocked(obj);
566 		return ERR_CAST(attach);
567 	}
568 #else
569 	attach = NULL;
570 #endif
571 
572 	get_dma_buf(dma_buf);
573 	obj->import_attach = attach;
574 	return obj;
575 }
576