1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (c) 2015, 2017, 2022 Linaro Limited
5 #include <linux/device.h>
6 #include <linux/dma-buf.h>
7 #include <linux/genalloc.h>
8 #include <linux/slab.h>
9 #include <linux/tee_drv.h>
10 #include "tee_private.h"
12 static int pool_op_gen_alloc(struct tee_shm_pool *pool, struct tee_shm *shm,
13 size_t size, size_t align)
16 struct gen_pool *genpool = pool->private_data;
17 size_t a = max_t(size_t, align, BIT(genpool->min_alloc_order));
18 struct genpool_data_align data = { .align = a };
19 size_t s = roundup(size, a);
21 va = gen_pool_alloc_algo(genpool, s, gen_pool_first_fit_align, &data);
25 memset((void *)va, 0, s);
26 shm->kaddr = (void *)va;
27 shm->paddr = gen_pool_virt_to_phys(genpool, va);
30 * This is from a static shared memory pool so no need to register
31 * each chunk, and no need to unregister later either.
33 shm->flags &= ~TEE_SHM_DYNAMIC;
37 static void pool_op_gen_free(struct tee_shm_pool *pool, struct tee_shm *shm)
39 gen_pool_free(pool->private_data, (unsigned long)shm->kaddr,
44 static void pool_op_gen_destroy_pool(struct tee_shm_pool *pool)
46 gen_pool_destroy(pool->private_data);
50 static const struct tee_shm_pool_ops pool_ops_generic = {
51 .alloc = pool_op_gen_alloc,
52 .free = pool_op_gen_free,
53 .destroy_pool = pool_op_gen_destroy_pool,
56 struct tee_shm_pool *tee_shm_pool_alloc_res_mem(unsigned long vaddr,
57 phys_addr_t paddr, size_t size,
60 const size_t page_mask = PAGE_SIZE - 1;
61 struct tee_shm_pool *pool;
64 /* Start and end must be page aligned */
65 if (vaddr & page_mask || paddr & page_mask || size & page_mask)
66 return ERR_PTR(-EINVAL);
68 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
70 return ERR_PTR(-ENOMEM);
72 pool->private_data = gen_pool_create(min_alloc_order, -1);
73 if (!pool->private_data) {
78 rc = gen_pool_add_virt(pool->private_data, vaddr, paddr, size, -1);
80 gen_pool_destroy(pool->private_data);
84 pool->ops = &pool_ops_generic;
92 EXPORT_SYMBOL_GPL(tee_shm_pool_alloc_res_mem);