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 panfrost_mmu_unmap(bo); 23 24 spin_lock(&pfdev->mm_lock); 25 drm_mm_remove_node(&bo->node); 26 spin_unlock(&pfdev->mm_lock); 27 28 drm_gem_shmem_free_object(obj); 29 } 30 31 static const struct drm_gem_object_funcs panfrost_gem_funcs = { 32 .free = panfrost_gem_free_object, 33 .print_info = drm_gem_shmem_print_info, 34 .pin = drm_gem_shmem_pin, 35 .unpin = drm_gem_shmem_unpin, 36 .get_sg_table = drm_gem_shmem_get_sg_table, 37 .vmap = drm_gem_shmem_vmap, 38 .vunmap = drm_gem_shmem_vunmap, 39 .vm_ops = &drm_gem_shmem_vm_ops, 40 }; 41 42 /** 43 * panfrost_gem_create_object - Implementation of driver->gem_create_object. 44 * @dev: DRM device 45 * @size: Size in bytes of the memory the object will reference 46 * 47 * This lets the GEM helpers allocate object structs for us, and keep 48 * our BO stats correct. 49 */ 50 struct drm_gem_object *panfrost_gem_create_object(struct drm_device *dev, size_t size) 51 { 52 int ret; 53 struct panfrost_device *pfdev = dev->dev_private; 54 struct panfrost_gem_object *obj; 55 u64 align; 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 size = roundup(size, PAGE_SIZE); 64 align = size >= SZ_2M ? SZ_2M >> PAGE_SHIFT : 0; 65 66 spin_lock(&pfdev->mm_lock); 67 ret = drm_mm_insert_node_generic(&pfdev->mm, &obj->node, 68 size >> PAGE_SHIFT, align, 0, 0); 69 spin_unlock(&pfdev->mm_lock); 70 if (ret) 71 goto free_obj; 72 73 return &obj->base.base; 74 75 free_obj: 76 kfree(obj); 77 return ERR_PTR(ret); 78 } 79 80 struct drm_gem_object * 81 panfrost_gem_prime_import_sg_table(struct drm_device *dev, 82 struct dma_buf_attachment *attach, 83 struct sg_table *sgt) 84 { 85 struct drm_gem_object *obj; 86 struct panfrost_gem_object *pobj; 87 88 obj = drm_gem_shmem_prime_import_sg_table(dev, attach, sgt); 89 if (IS_ERR(obj)) 90 return ERR_CAST(obj); 91 92 pobj = to_panfrost_bo(obj); 93 94 obj->resv = attach->dmabuf->resv; 95 96 panfrost_mmu_map(pobj); 97 98 return obj; 99 } 100