xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_dma_buf.c (revision 815e260a18a3af4dab59025ee99a7156c0e8b5e0)
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 "amdgpu_xgmi.h"
39 #include "amdgpu_vm.h"
40 #include <drm/amdgpu_drm.h>
41 #include <drm/ttm/ttm_tt.h>
42 #include <linux/dma-buf.h>
43 #include <linux/dma-fence-array.h>
44 #include <linux/pci-p2pdma.h>
45 
46 static const struct dma_buf_attach_ops amdgpu_dma_buf_attach_ops;
47 
48 /**
49  * dma_buf_attach_adev - Helper to get adev of an attachment
50  *
51  * @attach: attachment
52  *
53  * Returns:
54  * A struct amdgpu_device * if the attaching device is an amdgpu device or
55  * partition, NULL otherwise.
56  */
57 static struct amdgpu_device *dma_buf_attach_adev(struct dma_buf_attachment *attach)
58 {
59 	if (attach->importer_ops == &amdgpu_dma_buf_attach_ops) {
60 		struct drm_gem_object *obj = attach->importer_priv;
61 		struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
62 
63 		return amdgpu_ttm_adev(bo->tbo.bdev);
64 	}
65 
66 	return NULL;
67 }
68 
69 /**
70  * amdgpu_dma_buf_attach - &dma_buf_ops.attach implementation
71  *
72  * @dmabuf: DMA-buf where we attach to
73  * @attach: attachment to add
74  *
75  * Add the attachment as user to the exported DMA-buf.
76  */
77 static int amdgpu_dma_buf_attach(struct dma_buf *dmabuf,
78 				 struct dma_buf_attachment *attach)
79 {
80 	struct amdgpu_device *attach_adev = dma_buf_attach_adev(attach);
81 	struct drm_gem_object *obj = dmabuf->priv;
82 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
83 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
84 	int r;
85 
86 	if (!amdgpu_dmabuf_is_xgmi_accessible(attach_adev, bo) &&
87 	    pci_p2pdma_distance(adev->pdev, attach->dev, false) < 0)
88 		attach->peer2peer = false;
89 
90 	r = dma_resv_lock(bo->tbo.base.resv, NULL);
91 	if (r)
92 		return r;
93 
94 	amdgpu_vm_bo_update_shared(bo);
95 
96 	dma_resv_unlock(bo->tbo.base.resv);
97 
98 	return 0;
99 }
100 
101 /**
102  * amdgpu_dma_buf_pin - &dma_buf_ops.pin implementation
103  *
104  * @attach: attachment to pin down
105  *
106  * Pin the BO which is backing the DMA-buf so that it can't move any more.
107  */
108 static int amdgpu_dma_buf_pin(struct dma_buf_attachment *attach)
109 {
110 	struct dma_buf *dmabuf = attach->dmabuf;
111 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(dmabuf->priv);
112 	u32 domains = bo->allowed_domains;
113 
114 	dma_resv_assert_held(dmabuf->resv);
115 
116 	/* Try pinning into VRAM to allow P2P with RDMA NICs without ODP
117 	 * support if all attachments can do P2P. If any attachment can't do
118 	 * P2P just pin into GTT instead.
119 	 *
120 	 * To avoid with conflicting pinnings between GPUs and RDMA when move
121 	 * notifiers are disabled, only allow pinning in VRAM when move
122 	 * notiers are enabled.
123 	 */
124 	if (!IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY)) {
125 		domains &= ~AMDGPU_GEM_DOMAIN_VRAM;
126 	} else {
127 		list_for_each_entry(attach, &dmabuf->attachments, node)
128 			if (!attach->peer2peer)
129 				domains &= ~AMDGPU_GEM_DOMAIN_VRAM;
130 	}
131 
132 	if (domains & AMDGPU_GEM_DOMAIN_VRAM)
133 		bo->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
134 
135 	if (WARN_ON(!domains))
136 		return -EINVAL;
137 
138 	return amdgpu_bo_pin(bo, domains);
139 }
140 
141 /**
142  * amdgpu_dma_buf_unpin - &dma_buf_ops.unpin implementation
143  *
144  * @attach: attachment to unpin
145  *
146  * Unpin a previously pinned BO to make it movable again.
147  */
148 static void amdgpu_dma_buf_unpin(struct dma_buf_attachment *attach)
149 {
150 	struct drm_gem_object *obj = attach->dmabuf->priv;
151 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
152 
153 	amdgpu_bo_unpin(bo);
154 }
155 
156 /**
157  * amdgpu_dma_buf_map - &dma_buf_ops.map_dma_buf implementation
158  * @attach: DMA-buf attachment
159  * @dir: DMA direction
160  *
161  * Makes sure that the shared DMA buffer can be accessed by the target device.
162  * For now, simply pins it to the GTT domain, where it should be accessible by
163  * all DMA devices.
164  *
165  * Returns:
166  * sg_table filled with the DMA addresses to use or ERR_PRT with negative error
167  * code.
168  */
169 static struct sg_table *amdgpu_dma_buf_map(struct dma_buf_attachment *attach,
170 					   enum dma_data_direction dir)
171 {
172 	struct dma_buf *dma_buf = attach->dmabuf;
173 	struct drm_gem_object *obj = dma_buf->priv;
174 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
175 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
176 	struct sg_table *sgt;
177 	long r;
178 
179 	if (!bo->tbo.pin_count) {
180 		/* move buffer into GTT or VRAM */
181 		struct ttm_operation_ctx ctx = { false, false };
182 		unsigned int domains = AMDGPU_GEM_DOMAIN_GTT;
183 
184 		if (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM &&
185 		    attach->peer2peer) {
186 			bo->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
187 			domains |= AMDGPU_GEM_DOMAIN_VRAM;
188 		}
189 		amdgpu_bo_placement_from_domain(bo, domains);
190 		r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
191 		if (r)
192 			return ERR_PTR(r);
193 	}
194 
195 	switch (bo->tbo.resource->mem_type) {
196 	case TTM_PL_TT:
197 		sgt = drm_prime_pages_to_sg(obj->dev,
198 					    bo->tbo.ttm->pages,
199 					    bo->tbo.ttm->num_pages);
200 		if (IS_ERR(sgt))
201 			return sgt;
202 
203 		if (dma_map_sgtable(attach->dev, sgt, dir,
204 				    DMA_ATTR_SKIP_CPU_SYNC))
205 			goto error_free;
206 		break;
207 
208 	case TTM_PL_VRAM:
209 		/* XGMI-accessible memory should never be DMA-mapped */
210 		if (WARN_ON(amdgpu_dmabuf_is_xgmi_accessible(
211 				dma_buf_attach_adev(attach), bo)))
212 			return ERR_PTR(-EINVAL);
213 
214 		r = amdgpu_vram_mgr_alloc_sgt(adev, bo->tbo.resource, 0,
215 					      bo->tbo.base.size, attach->dev,
216 					      dir, &sgt);
217 		if (r)
218 			return ERR_PTR(r);
219 		break;
220 	default:
221 		return ERR_PTR(-EINVAL);
222 	}
223 
224 	return sgt;
225 
226 error_free:
227 	sg_free_table(sgt);
228 	kfree(sgt);
229 	return ERR_PTR(-EBUSY);
230 }
231 
232 /**
233  * amdgpu_dma_buf_unmap - &dma_buf_ops.unmap_dma_buf implementation
234  * @attach: DMA-buf attachment
235  * @sgt: sg_table to unmap
236  * @dir: DMA direction
237  *
238  * This is called when a shared DMA buffer no longer needs to be accessible by
239  * another device. For now, simply unpins the buffer from GTT.
240  */
241 static void amdgpu_dma_buf_unmap(struct dma_buf_attachment *attach,
242 				 struct sg_table *sgt,
243 				 enum dma_data_direction dir)
244 {
245 	if (sg_page(sgt->sgl)) {
246 		dma_unmap_sgtable(attach->dev, sgt, dir, 0);
247 		sg_free_table(sgt);
248 		kfree(sgt);
249 	} else {
250 		amdgpu_vram_mgr_free_sgt(attach->dev, dir, sgt);
251 	}
252 }
253 
254 /**
255  * amdgpu_dma_buf_begin_cpu_access - &dma_buf_ops.begin_cpu_access implementation
256  * @dma_buf: Shared DMA buffer
257  * @direction: Direction of DMA transfer
258  *
259  * This is called before CPU access to the shared DMA buffer's memory. If it's
260  * a read access, the buffer is moved to the GTT domain if possible, for optimal
261  * CPU read performance.
262  *
263  * Returns:
264  * 0 on success or a negative error code on failure.
265  */
266 static int amdgpu_dma_buf_begin_cpu_access(struct dma_buf *dma_buf,
267 					   enum dma_data_direction direction)
268 {
269 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(dma_buf->priv);
270 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
271 	struct ttm_operation_ctx ctx = { true, false };
272 	u32 domain = amdgpu_display_supported_domains(adev, bo->flags);
273 	int ret;
274 	bool reads = (direction == DMA_BIDIRECTIONAL ||
275 		      direction == DMA_FROM_DEVICE);
276 
277 	if (!reads || !(domain & AMDGPU_GEM_DOMAIN_GTT))
278 		return 0;
279 
280 	/* move to gtt */
281 	ret = amdgpu_bo_reserve(bo, false);
282 	if (unlikely(ret != 0))
283 		return ret;
284 
285 	if (!bo->tbo.pin_count &&
286 	    (bo->allowed_domains & AMDGPU_GEM_DOMAIN_GTT)) {
287 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
288 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
289 	}
290 
291 	amdgpu_bo_unreserve(bo);
292 	return ret;
293 }
294 
295 static int amdgpu_dma_buf_vmap(struct dma_buf *dma_buf, struct iosys_map *map)
296 {
297 	struct drm_gem_object *obj = dma_buf->priv;
298 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
299 	int ret;
300 
301 	/*
302 	 * Pin to keep buffer in place while it's vmap'ed. The actual
303 	 * domain is not that important as long as it's mapable. Using
304 	 * GTT and VRAM should be compatible with most use cases.
305 	 */
306 	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT | AMDGPU_GEM_DOMAIN_VRAM);
307 	if (ret)
308 		return ret;
309 	ret = drm_gem_dmabuf_vmap(dma_buf, map);
310 	if (ret)
311 		amdgpu_bo_unpin(bo);
312 
313 	return ret;
314 }
315 
316 static void amdgpu_dma_buf_vunmap(struct dma_buf *dma_buf, struct iosys_map *map)
317 {
318 	struct drm_gem_object *obj = dma_buf->priv;
319 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
320 
321 	drm_gem_dmabuf_vunmap(dma_buf, map);
322 	amdgpu_bo_unpin(bo);
323 }
324 
325 const struct dma_buf_ops amdgpu_dmabuf_ops = {
326 	.attach = amdgpu_dma_buf_attach,
327 	.pin = amdgpu_dma_buf_pin,
328 	.unpin = amdgpu_dma_buf_unpin,
329 	.map_dma_buf = amdgpu_dma_buf_map,
330 	.unmap_dma_buf = amdgpu_dma_buf_unmap,
331 	.release = drm_gem_dmabuf_release,
332 	.begin_cpu_access = amdgpu_dma_buf_begin_cpu_access,
333 	.mmap = drm_gem_dmabuf_mmap,
334 	.vmap = amdgpu_dma_buf_vmap,
335 	.vunmap = amdgpu_dma_buf_vunmap,
336 };
337 
338 /**
339  * amdgpu_gem_prime_export - &drm_driver.gem_prime_export implementation
340  * @gobj: GEM BO
341  * @flags: Flags such as DRM_CLOEXEC and DRM_RDWR.
342  *
343  * The main work is done by the &drm_gem_prime_export helper.
344  *
345  * Returns:
346  * Shared DMA buffer representing the GEM BO from the given device.
347  */
348 struct dma_buf *amdgpu_gem_prime_export(struct drm_gem_object *gobj,
349 					int flags)
350 {
351 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
352 	struct dma_buf *buf;
353 	struct ttm_operation_ctx ctx = {
354 		.interruptible = true,
355 		.no_wait_gpu = true,
356 		/* We opt to avoid OOM on system pages allocations */
357 		.gfp_retry_mayfail = true,
358 		.allow_res_evict = false,
359 	};
360 	int ret;
361 
362 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) ||
363 	    bo->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
364 		return ERR_PTR(-EPERM);
365 
366 	ret = ttm_bo_setup_export(&bo->tbo, &ctx);
367 	if (ret)
368 		return ERR_PTR(ret);
369 
370 	buf = drm_gem_prime_export(gobj, flags);
371 	if (!IS_ERR(buf))
372 		buf->ops = &amdgpu_dmabuf_ops;
373 
374 	return buf;
375 }
376 
377 /**
378  * amdgpu_dma_buf_create_obj - create BO for DMA-buf import
379  *
380  * @dev: DRM device
381  * @dma_buf: DMA-buf
382  *
383  * Creates an empty SG BO for DMA-buf import.
384  *
385  * Returns:
386  * A new GEM BO of the given DRM device, representing the memory
387  * described by the given DMA-buf attachment and scatter/gather table.
388  */
389 static struct drm_gem_object *
390 amdgpu_dma_buf_create_obj(struct drm_device *dev, struct dma_buf *dma_buf)
391 {
392 	struct dma_resv *resv = dma_buf->resv;
393 	struct amdgpu_device *adev = drm_to_adev(dev);
394 	struct drm_gem_object *gobj;
395 	struct amdgpu_bo *bo;
396 	uint64_t flags = 0;
397 	int ret;
398 
399 	dma_resv_lock(resv, NULL);
400 
401 	if (dma_buf->ops == &amdgpu_dmabuf_ops) {
402 		struct amdgpu_bo *other = gem_to_amdgpu_bo(dma_buf->priv);
403 
404 		flags |= other->flags & (AMDGPU_GEM_CREATE_CPU_GTT_USWC |
405 					 AMDGPU_GEM_CREATE_COHERENT |
406 					 AMDGPU_GEM_CREATE_EXT_COHERENT |
407 					 AMDGPU_GEM_CREATE_UNCACHED);
408 	}
409 
410 	ret = amdgpu_gem_object_create(adev, dma_buf->size, PAGE_SIZE,
411 				       AMDGPU_GEM_DOMAIN_CPU, flags,
412 				       ttm_bo_type_sg, resv, &gobj, 0);
413 	if (ret)
414 		goto error;
415 
416 	bo = gem_to_amdgpu_bo(gobj);
417 	bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
418 	bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
419 
420 	dma_resv_unlock(resv);
421 	return gobj;
422 
423 error:
424 	dma_resv_unlock(resv);
425 	return ERR_PTR(ret);
426 }
427 
428 /**
429  * amdgpu_dma_buf_move_notify - &attach.move_notify implementation
430  *
431  * @attach: the DMA-buf attachment
432  *
433  * Invalidate the DMA-buf attachment, making sure that the we re-create the
434  * mapping before the next use.
435  */
436 static void
437 amdgpu_dma_buf_move_notify(struct dma_buf_attachment *attach)
438 {
439 	struct drm_gem_object *obj = attach->importer_priv;
440 	struct ww_acquire_ctx *ticket = dma_resv_locking_ctx(obj->resv);
441 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
442 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
443 	struct ttm_operation_ctx ctx = { false, false };
444 	struct ttm_placement placement = {};
445 	struct amdgpu_vm_bo_base *bo_base;
446 	int r;
447 
448 	/* FIXME: This should be after the "if", but needs a fix to make sure
449 	 * DMABuf imports are initialized in the right VM list.
450 	 */
451 	amdgpu_vm_bo_invalidate(bo, false);
452 	if (!bo->tbo.resource || bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
453 		return;
454 
455 	r = ttm_bo_validate(&bo->tbo, &placement, &ctx);
456 	if (r) {
457 		DRM_ERROR("Failed to invalidate DMA-buf import (%d))\n", r);
458 		return;
459 	}
460 
461 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
462 		struct amdgpu_vm *vm = bo_base->vm;
463 		struct dma_resv *resv = vm->root.bo->tbo.base.resv;
464 
465 		if (ticket) {
466 			/* When we get an error here it means that somebody
467 			 * else is holding the VM lock and updating page tables
468 			 * So we can just continue here.
469 			 */
470 			r = dma_resv_lock(resv, ticket);
471 			if (r)
472 				continue;
473 
474 		} else {
475 			/* TODO: This is more problematic and we actually need
476 			 * to allow page tables updates without holding the
477 			 * lock.
478 			 */
479 			if (!dma_resv_trylock(resv))
480 				continue;
481 		}
482 
483 		/* Reserve fences for two SDMA page table updates */
484 		r = dma_resv_reserve_fences(resv, 2);
485 		if (!r)
486 			r = amdgpu_vm_clear_freed(adev, vm, NULL);
487 		if (!r)
488 			r = amdgpu_vm_handle_moved(adev, vm, ticket);
489 
490 		if (r && r != -EBUSY)
491 			DRM_ERROR("Failed to invalidate VM page tables (%d))\n",
492 				  r);
493 
494 		dma_resv_unlock(resv);
495 	}
496 }
497 
498 static const struct dma_buf_attach_ops amdgpu_dma_buf_attach_ops = {
499 	.allow_peer2peer = true,
500 	.move_notify = amdgpu_dma_buf_move_notify
501 };
502 
503 /**
504  * amdgpu_gem_prime_import - &drm_driver.gem_prime_import implementation
505  * @dev: DRM device
506  * @dma_buf: Shared DMA buffer
507  *
508  * Import a dma_buf into a the driver and potentially create a new GEM object.
509  *
510  * Returns:
511  * GEM BO representing the shared DMA buffer for the given device.
512  */
513 struct drm_gem_object *amdgpu_gem_prime_import(struct drm_device *dev,
514 					       struct dma_buf *dma_buf)
515 {
516 	struct dma_buf_attachment *attach;
517 	struct drm_gem_object *obj;
518 
519 	if (dma_buf->ops == &amdgpu_dmabuf_ops) {
520 		obj = dma_buf->priv;
521 		if (obj->dev == dev) {
522 			/*
523 			 * Importing dmabuf exported from out own gem increases
524 			 * refcount on gem itself instead of f_count of dmabuf.
525 			 */
526 			drm_gem_object_get(obj);
527 			return obj;
528 		}
529 	}
530 
531 	obj = amdgpu_dma_buf_create_obj(dev, dma_buf);
532 	if (IS_ERR(obj))
533 		return obj;
534 
535 	attach = dma_buf_dynamic_attach(dma_buf, dev->dev,
536 					&amdgpu_dma_buf_attach_ops, obj);
537 	if (IS_ERR(attach)) {
538 		drm_gem_object_put(obj);
539 		return ERR_CAST(attach);
540 	}
541 
542 	get_dma_buf(dma_buf);
543 	obj->import_attach = attach;
544 	return obj;
545 }
546 
547 /**
548  * amdgpu_dmabuf_is_xgmi_accessible - Check if xgmi available for P2P transfer
549  *
550  * @adev: amdgpu_device pointer of the importer
551  * @bo: amdgpu buffer object
552  *
553  * Returns:
554  * True if dmabuf accessible over xgmi, false otherwise.
555  */
556 bool amdgpu_dmabuf_is_xgmi_accessible(struct amdgpu_device *adev,
557 				      struct amdgpu_bo *bo)
558 {
559 	struct drm_gem_object *obj = &bo->tbo.base;
560 	struct drm_gem_object *gobj;
561 
562 	if (!adev)
563 		return false;
564 
565 	if (drm_gem_is_imported(obj)) {
566 		struct dma_buf *dma_buf = obj->import_attach->dmabuf;
567 
568 		if (dma_buf->ops != &amdgpu_dmabuf_ops)
569 			/* No XGMI with non AMD GPUs */
570 			return false;
571 
572 		gobj = dma_buf->priv;
573 		bo = gem_to_amdgpu_bo(gobj);
574 	}
575 
576 	if (amdgpu_xgmi_same_hive(adev, amdgpu_ttm_adev(bo->tbo.bdev)) &&
577 			(bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM))
578 		return true;
579 
580 	return false;
581 }
582