1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2015, Linaro Limited
4  * Copyright (c) 2017, EPAM Systems
5  */
6 #include <linux/device.h>
7 #include <linux/dma-buf.h>
8 #include <linux/genalloc.h>
9 #include <linux/slab.h>
10 #include <linux/tee_drv.h>
11 #include "optee_private.h"
12 #include "optee_smc.h"
13 #include "shm_pool.h"
14 
pool_op_alloc(struct tee_shm_pool_mgr * poolm,struct tee_shm * shm,size_t size)15 static int pool_op_alloc(struct tee_shm_pool_mgr *poolm,
16 			 struct tee_shm *shm, size_t size)
17 {
18 	unsigned int order = get_order(size);
19 	struct page *page;
20 
21 	page = alloc_pages(GFP_KERNEL | __GFP_ZERO, order);
22 	if (!page)
23 		return -ENOMEM;
24 
25 	shm->kaddr = page_address(page);
26 	shm->paddr = page_to_phys(page);
27 	shm->size = PAGE_SIZE << order;
28 
29 	return 0;
30 }
31 
pool_op_free(struct tee_shm_pool_mgr * poolm,struct tee_shm * shm)32 static void pool_op_free(struct tee_shm_pool_mgr *poolm,
33 			 struct tee_shm *shm)
34 {
35 	free_pages((unsigned long)shm->kaddr, get_order(shm->size));
36 	shm->kaddr = NULL;
37 }
38 
pool_op_destroy_poolmgr(struct tee_shm_pool_mgr * poolm)39 static void pool_op_destroy_poolmgr(struct tee_shm_pool_mgr *poolm)
40 {
41 	kfree(poolm);
42 }
43 
44 static const struct tee_shm_pool_mgr_ops pool_ops = {
45 	.alloc = pool_op_alloc,
46 	.free = pool_op_free,
47 	.destroy_poolmgr = pool_op_destroy_poolmgr,
48 };
49 
50 /**
51  * optee_shm_pool_alloc_pages() - create page-based allocator pool
52  *
53  * This pool is used when OP-TEE supports dymanic SHM. In this case
54  * command buffers and such are allocated from kernel's own memory.
55  */
optee_shm_pool_alloc_pages(void)56 struct tee_shm_pool_mgr *optee_shm_pool_alloc_pages(void)
57 {
58 	struct tee_shm_pool_mgr *mgr = kzalloc(sizeof(*mgr), GFP_KERNEL);
59 
60 	if (!mgr)
61 		return ERR_PTR(-ENOMEM);
62 
63 	mgr->ops = &pool_ops;
64 
65 	return mgr;
66 }
67