tee_shm_pool.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (c) 2015, 2017, 2022 Linaro Limited
  4. */
  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"
  11. static int pool_op_gen_alloc(struct tee_shm_pool *pool, struct tee_shm *shm,
  12. size_t size, size_t align)
  13. {
  14. unsigned long va;
  15. struct gen_pool *genpool = pool->private_data;
  16. size_t a = max_t(size_t, align, BIT(genpool->min_alloc_order));
  17. struct genpool_data_align data = { .align = a };
  18. size_t s = roundup(size, a);
  19. va = gen_pool_alloc_algo(genpool, s, gen_pool_first_fit_align, &data);
  20. if (!va)
  21. return -ENOMEM;
  22. memset((void *)va, 0, s);
  23. shm->kaddr = (void *)va;
  24. shm->paddr = gen_pool_virt_to_phys(genpool, va);
  25. shm->size = s;
  26. /*
  27. * This is from a static shared memory pool so no need to register
  28. * each chunk, and no need to unregister later either.
  29. */
  30. shm->flags &= ~TEE_SHM_DYNAMIC;
  31. return 0;
  32. }
  33. static void pool_op_gen_free(struct tee_shm_pool *pool, struct tee_shm *shm)
  34. {
  35. gen_pool_free(pool->private_data, (unsigned long)shm->kaddr,
  36. shm->size);
  37. shm->kaddr = NULL;
  38. }
  39. static void pool_op_gen_destroy_pool(struct tee_shm_pool *pool)
  40. {
  41. gen_pool_destroy(pool->private_data);
  42. kfree(pool);
  43. }
  44. static const struct tee_shm_pool_ops pool_ops_generic = {
  45. .alloc = pool_op_gen_alloc,
  46. .free = pool_op_gen_free,
  47. .destroy_pool = pool_op_gen_destroy_pool,
  48. };
  49. struct tee_shm_pool *tee_shm_pool_alloc_res_mem(unsigned long vaddr,
  50. phys_addr_t paddr, size_t size,
  51. int min_alloc_order)
  52. {
  53. const size_t page_mask = PAGE_SIZE - 1;
  54. struct tee_shm_pool *pool;
  55. int rc;
  56. /* Start and end must be page aligned */
  57. if (vaddr & page_mask || paddr & page_mask || size & page_mask)
  58. return ERR_PTR(-EINVAL);
  59. pool = kzalloc(sizeof(*pool), GFP_KERNEL);
  60. if (!pool)
  61. return ERR_PTR(-ENOMEM);
  62. pool->private_data = gen_pool_create(min_alloc_order, -1);
  63. if (!pool->private_data) {
  64. rc = -ENOMEM;
  65. goto err;
  66. }
  67. rc = gen_pool_add_virt(pool->private_data, vaddr, paddr, size, -1);
  68. if (rc) {
  69. gen_pool_destroy(pool->private_data);
  70. goto err;
  71. }
  72. pool->ops = &pool_ops_generic;
  73. return pool;
  74. err:
  75. kfree(pool);
  76. return ERR_PTR(rc);
  77. }
  78. EXPORT_SYMBOL_GPL(tee_shm_pool_alloc_res_mem);