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 <drm/drmP.h>
35 
36 #include "amdgpu.h"
37 #include "amdgpu_display.h"
38 #include "amdgpu_gem.h"
39 #include <drm/amdgpu_drm.h>
40 #include <linux/dma-buf.h>
41 #include <linux/dma-fence-array.h>
42 
43 /**
44  * amdgpu_gem_prime_get_sg_table - &drm_driver.gem_prime_get_sg_table
45  * implementation
46  * @obj: GEM buffer object (BO)
47  *
48  * Returns:
49  * A scatter/gather table for the pinned pages of the BO's memory.
50  */
51 struct sg_table *amdgpu_gem_prime_get_sg_table(struct drm_gem_object *obj)
52 {
53 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
54 	int npages = bo->tbo.num_pages;
55 
56 	return drm_prime_pages_to_sg(bo->tbo.ttm->pages, npages);
57 }
58 
59 /**
60  * amdgpu_gem_prime_vmap - &dma_buf_ops.vmap implementation
61  * @obj: GEM BO
62  *
63  * Sets up an in-kernel virtual mapping of the BO's memory.
64  *
65  * Returns:
66  * The virtual address of the mapping or an error pointer.
67  */
68 void *amdgpu_gem_prime_vmap(struct drm_gem_object *obj)
69 {
70 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
71 	int ret;
72 
73 	ret = ttm_bo_kmap(&bo->tbo, 0, bo->tbo.num_pages,
74 			  &bo->dma_buf_vmap);
75 	if (ret)
76 		return ERR_PTR(ret);
77 
78 	return bo->dma_buf_vmap.virtual;
79 }
80 
81 /**
82  * amdgpu_gem_prime_vunmap - &dma_buf_ops.vunmap implementation
83  * @obj: GEM BO
84  * @vaddr: Virtual address (unused)
85  *
86  * Tears down the in-kernel virtual mapping of the BO's memory.
87  */
88 void amdgpu_gem_prime_vunmap(struct drm_gem_object *obj, void *vaddr)
89 {
90 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
91 
92 	ttm_bo_kunmap(&bo->dma_buf_vmap);
93 }
94 
95 /**
96  * amdgpu_gem_prime_mmap - &drm_driver.gem_prime_mmap implementation
97  * @obj: GEM BO
98  * @vma: Virtual memory area
99  *
100  * Sets up a userspace mapping of the BO's memory in the given
101  * virtual memory area.
102  *
103  * Returns:
104  * 0 on success or a negative error code on failure.
105  */
106 int amdgpu_gem_prime_mmap(struct drm_gem_object *obj,
107 			  struct vm_area_struct *vma)
108 {
109 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
110 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
111 	unsigned asize = amdgpu_bo_size(bo);
112 	int ret;
113 
114 	if (!vma->vm_file)
115 		return -ENODEV;
116 
117 	if (adev == NULL)
118 		return -ENODEV;
119 
120 	/* Check for valid size. */
121 	if (asize < vma->vm_end - vma->vm_start)
122 		return -EINVAL;
123 
124 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) ||
125 	    (bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)) {
126 		return -EPERM;
127 	}
128 	vma->vm_pgoff += amdgpu_bo_mmap_offset(bo) >> PAGE_SHIFT;
129 
130 	/* prime mmap does not need to check access, so allow here */
131 	ret = drm_vma_node_allow(&obj->vma_node, vma->vm_file->private_data);
132 	if (ret)
133 		return ret;
134 
135 	ret = ttm_bo_mmap(vma->vm_file, vma, &adev->mman.bdev);
136 	drm_vma_node_revoke(&obj->vma_node, vma->vm_file->private_data);
137 
138 	return ret;
139 }
140 
141 static int
142 __reservation_object_make_exclusive(struct reservation_object *obj)
143 {
144 	struct dma_fence **fences;
145 	unsigned int count;
146 	int r;
147 
148 	if (!reservation_object_get_list(obj)) /* no shared fences to convert */
149 		return 0;
150 
151 	r = reservation_object_get_fences_rcu(obj, NULL, &count, &fences);
152 	if (r)
153 		return r;
154 
155 	if (count == 0) {
156 		/* Now that was unexpected. */
157 	} else if (count == 1) {
158 		reservation_object_add_excl_fence(obj, fences[0]);
159 		dma_fence_put(fences[0]);
160 		kfree(fences);
161 	} else {
162 		struct dma_fence_array *array;
163 
164 		array = dma_fence_array_create(count, fences,
165 					       dma_fence_context_alloc(1), 0,
166 					       false);
167 		if (!array)
168 			goto err_fences_put;
169 
170 		reservation_object_add_excl_fence(obj, &array->base);
171 		dma_fence_put(&array->base);
172 	}
173 
174 	return 0;
175 
176 err_fences_put:
177 	while (count--)
178 		dma_fence_put(fences[count]);
179 	kfree(fences);
180 	return -ENOMEM;
181 }
182 
183 /**
184  * amdgpu_dma_buf_map_attach - &dma_buf_ops.attach implementation
185  * @dma_buf: Shared DMA buffer
186  * @attach: DMA-buf attachment
187  *
188  * Makes sure that the shared DMA buffer can be accessed by the target device.
189  * For now, simply pins it to the GTT domain, where it should be accessible by
190  * all DMA devices.
191  *
192  * Returns:
193  * 0 on success or a negative error code on failure.
194  */
195 static int amdgpu_dma_buf_map_attach(struct dma_buf *dma_buf,
196 				     struct dma_buf_attachment *attach)
197 {
198 	struct drm_gem_object *obj = dma_buf->priv;
199 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
200 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
201 	long r;
202 
203 	r = drm_gem_map_attach(dma_buf, attach);
204 	if (r)
205 		return r;
206 
207 	r = amdgpu_bo_reserve(bo, false);
208 	if (unlikely(r != 0))
209 		goto error_detach;
210 
211 
212 	if (attach->dev->driver != adev->dev->driver) {
213 		/*
214 		 * We only create shared fences for internal use, but importers
215 		 * of the dmabuf rely on exclusive fences for implicitly
216 		 * tracking write hazards. As any of the current fences may
217 		 * correspond to a write, we need to convert all existing
218 		 * fences on the reservation object into a single exclusive
219 		 * fence.
220 		 */
221 		r = __reservation_object_make_exclusive(bo->tbo.resv);
222 		if (r)
223 			goto error_unreserve;
224 	}
225 
226 	/* pin buffer into GTT */
227 	r = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
228 	if (r)
229 		goto error_unreserve;
230 
231 	if (attach->dev->driver != adev->dev->driver)
232 		bo->prime_shared_count++;
233 
234 error_unreserve:
235 	amdgpu_bo_unreserve(bo);
236 
237 error_detach:
238 	if (r)
239 		drm_gem_map_detach(dma_buf, attach);
240 	return r;
241 }
242 
243 /**
244  * amdgpu_dma_buf_map_detach - &dma_buf_ops.detach implementation
245  * @dma_buf: Shared DMA buffer
246  * @attach: DMA-buf attachment
247  *
248  * This is called when a shared DMA buffer no longer needs to be accessible by
249  * another device. For now, simply unpins the buffer from GTT.
250  */
251 static void amdgpu_dma_buf_map_detach(struct dma_buf *dma_buf,
252 				      struct dma_buf_attachment *attach)
253 {
254 	struct drm_gem_object *obj = dma_buf->priv;
255 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
256 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
257 	int ret = 0;
258 
259 	ret = amdgpu_bo_reserve(bo, true);
260 	if (unlikely(ret != 0))
261 		goto error;
262 
263 	amdgpu_bo_unpin(bo);
264 	if (attach->dev->driver != adev->dev->driver && bo->prime_shared_count)
265 		bo->prime_shared_count--;
266 	amdgpu_bo_unreserve(bo);
267 
268 error:
269 	drm_gem_map_detach(dma_buf, attach);
270 }
271 
272 /**
273  * amdgpu_gem_prime_res_obj - &drm_driver.gem_prime_res_obj implementation
274  * @obj: GEM BO
275  *
276  * Returns:
277  * The BO's reservation object.
278  */
279 struct reservation_object *amdgpu_gem_prime_res_obj(struct drm_gem_object *obj)
280 {
281 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
282 
283 	return bo->tbo.resv;
284 }
285 
286 /**
287  * amdgpu_dma_buf_begin_cpu_access - &dma_buf_ops.begin_cpu_access implementation
288  * @dma_buf: Shared DMA buffer
289  * @direction: Direction of DMA transfer
290  *
291  * This is called before CPU access to the shared DMA buffer's memory. If it's
292  * a read access, the buffer is moved to the GTT domain if possible, for optimal
293  * CPU read performance.
294  *
295  * Returns:
296  * 0 on success or a negative error code on failure.
297  */
298 static int amdgpu_dma_buf_begin_cpu_access(struct dma_buf *dma_buf,
299 					   enum dma_data_direction direction)
300 {
301 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(dma_buf->priv);
302 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
303 	struct ttm_operation_ctx ctx = { true, false };
304 	u32 domain = amdgpu_display_supported_domains(adev);
305 	int ret;
306 	bool reads = (direction == DMA_BIDIRECTIONAL ||
307 		      direction == DMA_FROM_DEVICE);
308 
309 	if (!reads || !(domain & AMDGPU_GEM_DOMAIN_GTT))
310 		return 0;
311 
312 	/* move to gtt */
313 	ret = amdgpu_bo_reserve(bo, false);
314 	if (unlikely(ret != 0))
315 		return ret;
316 
317 	if (!bo->pin_count && (bo->allowed_domains & AMDGPU_GEM_DOMAIN_GTT)) {
318 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
319 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
320 	}
321 
322 	amdgpu_bo_unreserve(bo);
323 	return ret;
324 }
325 
326 const struct dma_buf_ops amdgpu_dmabuf_ops = {
327 	.attach = amdgpu_dma_buf_map_attach,
328 	.detach = amdgpu_dma_buf_map_detach,
329 	.map_dma_buf = drm_gem_map_dma_buf,
330 	.unmap_dma_buf = drm_gem_unmap_dma_buf,
331 	.release = drm_gem_dmabuf_release,
332 	.begin_cpu_access = amdgpu_dma_buf_begin_cpu_access,
333 	.mmap = drm_gem_dmabuf_mmap,
334 	.vmap = drm_gem_dmabuf_vmap,
335 	.vunmap = drm_gem_dmabuf_vunmap,
336 };
337 
338 /**
339  * amdgpu_gem_prime_export - &drm_driver.gem_prime_export implementation
340  * @dev: DRM device
341  * @gobj: GEM BO
342  * @flags: Flags such as DRM_CLOEXEC and DRM_RDWR.
343  *
344  * The main work is done by the &drm_gem_prime_export helper, which in turn
345  * uses &amdgpu_gem_prime_res_obj.
346  *
347  * Returns:
348  * Shared DMA buffer representing the GEM BO from the given device.
349  */
350 struct dma_buf *amdgpu_gem_prime_export(struct drm_device *dev,
351 					struct drm_gem_object *gobj,
352 					int flags)
353 {
354 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
355 	struct dma_buf *buf;
356 
357 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) ||
358 	    bo->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
359 		return ERR_PTR(-EPERM);
360 
361 	buf = drm_gem_prime_export(dev, gobj, flags);
362 	if (!IS_ERR(buf)) {
363 		buf->file->f_mapping = dev->anon_inode->i_mapping;
364 		buf->ops = &amdgpu_dmabuf_ops;
365 	}
366 
367 	return buf;
368 }
369 
370 /**
371  * amdgpu_gem_prime_import_sg_table - &drm_driver.gem_prime_import_sg_table
372  * implementation
373  * @dev: DRM device
374  * @attach: DMA-buf attachment
375  * @sg: Scatter/gather table
376  *
377  * Imports shared DMA buffer memory exported by another device.
378  *
379  * Returns:
380  * A new GEM BO of the given DRM device, representing the memory
381  * described by the given DMA-buf attachment and scatter/gather table.
382  */
383 struct drm_gem_object *
384 amdgpu_gem_prime_import_sg_table(struct drm_device *dev,
385 				 struct dma_buf_attachment *attach,
386 				 struct sg_table *sg)
387 {
388 	struct reservation_object *resv = attach->dmabuf->resv;
389 	struct amdgpu_device *adev = dev->dev_private;
390 	struct amdgpu_bo *bo;
391 	struct amdgpu_bo_param bp;
392 	int ret;
393 
394 	memset(&bp, 0, sizeof(bp));
395 	bp.size = attach->dmabuf->size;
396 	bp.byte_align = PAGE_SIZE;
397 	bp.domain = AMDGPU_GEM_DOMAIN_CPU;
398 	bp.flags = 0;
399 	bp.type = ttm_bo_type_sg;
400 	bp.resv = resv;
401 	ww_mutex_lock(&resv->lock, NULL);
402 	ret = amdgpu_bo_create(adev, &bp, &bo);
403 	if (ret)
404 		goto error;
405 
406 	bo->tbo.sg = sg;
407 	bo->tbo.ttm->sg = sg;
408 	bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
409 	bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
410 	if (attach->dmabuf->ops != &amdgpu_dmabuf_ops)
411 		bo->prime_shared_count = 1;
412 
413 	ww_mutex_unlock(&resv->lock);
414 	return &bo->gem_base;
415 
416 error:
417 	ww_mutex_unlock(&resv->lock);
418 	return ERR_PTR(ret);
419 }
420 
421 /**
422  * amdgpu_gem_prime_import - &drm_driver.gem_prime_import implementation
423  * @dev: DRM device
424  * @dma_buf: Shared DMA buffer
425  *
426  * The main work is done by the &drm_gem_prime_import helper, which in turn
427  * uses &amdgpu_gem_prime_import_sg_table.
428  *
429  * Returns:
430  * GEM BO representing the shared DMA buffer for the given device.
431  */
432 struct drm_gem_object *amdgpu_gem_prime_import(struct drm_device *dev,
433 					    struct dma_buf *dma_buf)
434 {
435 	struct drm_gem_object *obj;
436 
437 	if (dma_buf->ops == &amdgpu_dmabuf_ops) {
438 		obj = dma_buf->priv;
439 		if (obj->dev == dev) {
440 			/*
441 			 * Importing dmabuf exported from out own gem increases
442 			 * refcount on gem itself instead of f_count of dmabuf.
443 			 */
444 			drm_gem_object_get(obj);
445 			return obj;
446 		}
447 	}
448 
449 	return drm_gem_prime_import(dev, dma_buf);
450 }
451