1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright 2019 Linaro, Ltd, Rob Herring <robh@kernel.org> */
3 
4 #include <linux/err.h>
5 #include <linux/slab.h>
6 #include <linux/dma-buf.h>
7 #include <linux/dma-mapping.h>
8 
9 #include <drm/panfrost_drm.h>
10 #include "panfrost_device.h"
11 #include "panfrost_gem.h"
12 #include "panfrost_mmu.h"
13 
14 /* Called DRM core on the last userspace/kernel unreference of the
15  * BO.
16  */
17 static void panfrost_gem_free_object(struct drm_gem_object *obj)
18 {
19 	struct panfrost_gem_object *bo = to_panfrost_bo(obj);
20 	struct panfrost_device *pfdev = obj->dev->dev_private;
21 
22 	if (bo->is_mapped)
23 		panfrost_mmu_unmap(bo);
24 
25 	spin_lock(&pfdev->mm_lock);
26 	drm_mm_remove_node(&bo->node);
27 	spin_unlock(&pfdev->mm_lock);
28 
29 	drm_gem_shmem_free_object(obj);
30 }
31 
32 static const struct drm_gem_object_funcs panfrost_gem_funcs = {
33 	.free = panfrost_gem_free_object,
34 	.print_info = drm_gem_shmem_print_info,
35 	.pin = drm_gem_shmem_pin,
36 	.unpin = drm_gem_shmem_unpin,
37 	.get_sg_table = drm_gem_shmem_get_sg_table,
38 	.vmap = drm_gem_shmem_vmap,
39 	.vunmap = drm_gem_shmem_vunmap,
40 	.vm_ops = &drm_gem_shmem_vm_ops,
41 };
42 
43 /**
44  * panfrost_gem_create_object - Implementation of driver->gem_create_object.
45  * @dev: DRM device
46  * @size: Size in bytes of the memory the object will reference
47  *
48  * This lets the GEM helpers allocate object structs for us, and keep
49  * our BO stats correct.
50  */
51 struct drm_gem_object *panfrost_gem_create_object(struct drm_device *dev, size_t size)
52 {
53 	int ret;
54 	struct panfrost_device *pfdev = dev->dev_private;
55 	struct panfrost_gem_object *obj;
56 
57 	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
58 	if (!obj)
59 		return NULL;
60 
61 	obj->base.base.funcs = &panfrost_gem_funcs;
62 
63 	spin_lock(&pfdev->mm_lock);
64 	ret = drm_mm_insert_node(&pfdev->mm, &obj->node,
65 				 roundup(size, PAGE_SIZE) >> PAGE_SHIFT);
66 	spin_unlock(&pfdev->mm_lock);
67 	if (ret)
68 		goto free_obj;
69 
70 	return &obj->base.base;
71 
72 free_obj:
73 	kfree(obj);
74 	return ERR_PTR(ret);
75 }
76 
77 struct drm_gem_object *
78 panfrost_gem_prime_import_sg_table(struct drm_device *dev,
79 				   struct dma_buf_attachment *attach,
80 				   struct sg_table *sgt)
81 {
82 	struct drm_gem_object *obj;
83 	struct panfrost_gem_object *pobj;
84 
85 	obj = drm_gem_shmem_prime_import_sg_table(dev, attach, sgt);
86 	if (IS_ERR(obj))
87 		return ERR_CAST(obj);
88 
89 	pobj = to_panfrost_bo(obj);
90 
91 	obj->resv = attach->dmabuf->resv;
92 
93 	panfrost_mmu_map(pobj);
94 
95 	return obj;
96 }
97