1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2017-2018 Etnaviv Project
6 #include <drm/drm_mm.h>
8 #include "etnaviv_cmdbuf.h"
9 #include "etnaviv_gpu.h"
10 #include "etnaviv_mmu.h"
11 #include "etnaviv_perfmon.h"
13 #define SUBALLOC_SIZE SZ_256K
14 #define SUBALLOC_GRANULE SZ_4K
15 #define SUBALLOC_GRANULES (SUBALLOC_SIZE / SUBALLOC_GRANULE)
17 struct etnaviv_cmdbuf_suballoc {
18 /* suballocated dma buffer properties */
19 struct etnaviv_gpu *gpu;
25 struct drm_mm_node vram_node; /* only used on MMUv2 */
27 /* allocation management */
29 DECLARE_BITMAP(granule_map, SUBALLOC_GRANULES);
31 wait_queue_head_t free_event;
34 struct etnaviv_cmdbuf_suballoc *
35 etnaviv_cmdbuf_suballoc_new(struct etnaviv_gpu * gpu)
37 struct etnaviv_cmdbuf_suballoc *suballoc;
40 suballoc = kzalloc(sizeof(*suballoc), GFP_KERNEL);
42 return ERR_PTR(-ENOMEM);
45 mutex_init(&suballoc->lock);
46 init_waitqueue_head(&suballoc->free_event);
48 suballoc->vaddr = dma_alloc_wc(gpu->dev, SUBALLOC_SIZE,
49 &suballoc->paddr, GFP_KERNEL);
53 ret = etnaviv_iommu_get_suballoc_va(gpu, suballoc->paddr,
54 &suballoc->vram_node, SUBALLOC_SIZE,
62 dma_free_wc(gpu->dev, SUBALLOC_SIZE, suballoc->vaddr, suballoc->paddr);
69 void etnaviv_cmdbuf_suballoc_destroy(struct etnaviv_cmdbuf_suballoc *suballoc)
71 etnaviv_iommu_put_suballoc_va(suballoc->gpu, &suballoc->vram_node,
72 SUBALLOC_SIZE, suballoc->iova);
73 dma_free_wc(suballoc->gpu->dev, SUBALLOC_SIZE, suballoc->vaddr,
78 int etnaviv_cmdbuf_init(struct etnaviv_cmdbuf_suballoc *suballoc,
79 struct etnaviv_cmdbuf *cmdbuf, u32 size)
81 int granule_offs, order, ret;
83 cmdbuf->suballoc = suballoc;
86 order = order_base_2(ALIGN(size, SUBALLOC_GRANULE) / SUBALLOC_GRANULE);
88 mutex_lock(&suballoc->lock);
89 granule_offs = bitmap_find_free_region(suballoc->granule_map,
90 SUBALLOC_GRANULES, order);
91 if (granule_offs < 0) {
92 suballoc->free_space = 0;
93 mutex_unlock(&suballoc->lock);
94 ret = wait_event_interruptible_timeout(suballoc->free_event,
96 msecs_to_jiffies(10 * 1000));
98 dev_err(suballoc->gpu->dev,
99 "Timeout waiting for cmdbuf space\n");
104 mutex_unlock(&suballoc->lock);
105 cmdbuf->suballoc_offset = granule_offs * SUBALLOC_GRANULE;
106 cmdbuf->vaddr = suballoc->vaddr + cmdbuf->suballoc_offset;
111 void etnaviv_cmdbuf_free(struct etnaviv_cmdbuf *cmdbuf)
113 struct etnaviv_cmdbuf_suballoc *suballoc = cmdbuf->suballoc;
114 int order = order_base_2(ALIGN(cmdbuf->size, SUBALLOC_GRANULE) /
117 mutex_lock(&suballoc->lock);
118 bitmap_release_region(suballoc->granule_map,
119 cmdbuf->suballoc_offset / SUBALLOC_GRANULE,
121 suballoc->free_space = 1;
122 mutex_unlock(&suballoc->lock);
123 wake_up_all(&suballoc->free_event);
126 u32 etnaviv_cmdbuf_get_va(struct etnaviv_cmdbuf *buf)
128 return buf->suballoc->iova + buf->suballoc_offset;
131 dma_addr_t etnaviv_cmdbuf_get_pa(struct etnaviv_cmdbuf *buf)
133 return buf->suballoc->paddr + buf->suballoc_offset;