1 // SPDX-License-Identifier: GPL-2.0
3 * drivers/staging/android/ion/ion_cma_heap.c
5 * Copyright (C) Linaro 2012
6 * Author: <benjamin.gaignard@linaro.org> for ST-Ericsson.
9 #include <linux/device.h>
10 #include <linux/slab.h>
11 #include <linux/errno.h>
12 #include <linux/err.h>
13 #include <linux/cma.h>
14 #include <linux/scatterlist.h>
15 #include <linux/highmem.h>
24 #define to_cma_heap(x) container_of(x, struct ion_cma_heap, heap)
26 /* ION CMA heap operations functions */
27 static int ion_cma_allocate(struct ion_heap *heap, struct ion_buffer *buffer,
31 struct ion_cma_heap *cma_heap = to_cma_heap(heap);
32 struct sg_table *table;
34 unsigned long size = PAGE_ALIGN(len);
35 unsigned long nr_pages = size >> PAGE_SHIFT;
36 unsigned long align = get_order(size);
39 if (align > CONFIG_CMA_ALIGNMENT)
40 align = CONFIG_CMA_ALIGNMENT;
42 pages = cma_alloc(cma_heap->cma, nr_pages, align, false);
46 if (PageHighMem(pages)) {
47 unsigned long nr_clear_pages = nr_pages;
48 struct page *page = pages;
50 while (nr_clear_pages > 0) {
51 void *vaddr = kmap_atomic(page);
53 memset(vaddr, 0, PAGE_SIZE);
59 memset(page_address(pages), 0, size);
62 table = kmalloc(sizeof(*table), GFP_KERNEL);
66 ret = sg_alloc_table(table, 1, GFP_KERNEL);
70 sg_set_page(table->sgl, pages, size, 0);
72 buffer->priv_virt = pages;
73 buffer->sg_table = table;
79 cma_release(cma_heap->cma, pages, nr_pages);
83 static void ion_cma_free(struct ion_buffer *buffer)
85 struct ion_cma_heap *cma_heap = to_cma_heap(buffer->heap);
86 struct page *pages = buffer->priv_virt;
87 unsigned long nr_pages = PAGE_ALIGN(buffer->size) >> PAGE_SHIFT;
90 cma_release(cma_heap->cma, pages, nr_pages);
91 /* release sg table */
92 sg_free_table(buffer->sg_table);
93 kfree(buffer->sg_table);
96 static struct ion_heap_ops ion_cma_ops = {
97 .allocate = ion_cma_allocate,
99 .map_user = ion_heap_map_user,
100 .map_kernel = ion_heap_map_kernel,
101 .unmap_kernel = ion_heap_unmap_kernel,
104 static struct ion_heap *__ion_cma_heap_create(struct cma *cma)
106 struct ion_cma_heap *cma_heap;
108 cma_heap = kzalloc(sizeof(*cma_heap), GFP_KERNEL);
111 return ERR_PTR(-ENOMEM);
113 cma_heap->heap.ops = &ion_cma_ops;
115 * get device from private heaps data, later it will be
116 * used to make the link with reserved CMA memory
119 cma_heap->heap.type = ION_HEAP_TYPE_DMA;
120 return &cma_heap->heap;
123 static int __ion_add_cma_heaps(struct cma *cma, void *data)
125 struct ion_heap *heap;
127 heap = __ion_cma_heap_create(cma);
129 return PTR_ERR(heap);
131 heap->name = cma_get_name(cma);
133 ion_device_add_heap(heap);
137 static int ion_add_cma_heaps(void)
139 cma_for_each_area(__ion_add_cma_heaps, NULL);
142 device_initcall(ion_add_cma_heaps);