1 // SPDX-License-Identifier: GPL-2.0
2 /* TI K3 CPPI5 descriptors pool API
4 * Copyright (C) 2020 Texas Instruments Incorporated - http://www.ti.com
7 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 #include <linux/device.h>
10 #include <linux/dma-mapping.h>
11 #include <linux/err.h>
12 #include <linux/genalloc.h>
13 #include <linux/kernel.h>
15 #include "k3-cppi-desc-pool.h"
17 struct k3_cppi_desc_pool
{
20 void *cpumem
; /* dma_alloc map */
24 struct gen_pool
*gen_pool
;
27 void k3_cppi_desc_pool_destroy(struct k3_cppi_desc_pool
*pool
)
32 WARN(gen_pool_size(pool
->gen_pool
) != gen_pool_avail(pool
->gen_pool
),
33 "k3_knav_desc_pool size %zu != avail %zu",
34 gen_pool_size(pool
->gen_pool
),
35 gen_pool_avail(pool
->gen_pool
));
37 dma_free_coherent(pool
->dev
, pool
->mem_size
, pool
->cpumem
,
40 gen_pool_destroy(pool
->gen_pool
); /* frees pool->name */
43 struct k3_cppi_desc_pool
*
44 k3_cppi_desc_pool_create_name(struct device
*dev
, size_t size
,
48 struct k3_cppi_desc_pool
*pool
;
49 const char *pool_name
= NULL
;
52 pool
= devm_kzalloc(dev
, sizeof(*pool
), GFP_KERNEL
);
57 pool
->desc_size
= roundup_pow_of_two(desc_size
);
58 pool
->num_desc
= size
;
59 pool
->mem_size
= pool
->num_desc
* pool
->desc_size
;
61 pool_name
= kstrdup_const(name
? name
: dev_name(pool
->dev
),
64 return ERR_PTR(-ENOMEM
);
66 pool
->gen_pool
= gen_pool_create(ilog2(pool
->desc_size
), -1);
67 if (IS_ERR(pool
->gen_pool
)) {
68 ret
= PTR_ERR(pool
->gen_pool
);
69 dev_err(pool
->dev
, "pool create failed %d\n", ret
);
70 kfree_const(pool_name
);
71 goto gen_pool_create_fail
;
74 pool
->gen_pool
->name
= pool_name
;
76 pool
->cpumem
= dma_alloc_coherent(pool
->dev
, pool
->mem_size
,
77 &pool
->dma_addr
, GFP_KERNEL
);
82 ret
= gen_pool_add_virt(pool
->gen_pool
, (unsigned long)pool
->cpumem
,
83 (phys_addr_t
)pool
->dma_addr
, pool
->mem_size
,
86 dev_err(pool
->dev
, "pool add failed %d\n", ret
);
87 goto gen_pool_add_virt_fail
;
92 gen_pool_add_virt_fail
:
93 dma_free_coherent(pool
->dev
, pool
->mem_size
, pool
->cpumem
,
96 gen_pool_destroy(pool
->gen_pool
); /* frees pool->name */
98 devm_kfree(pool
->dev
, pool
);
102 dma_addr_t
k3_cppi_desc_pool_virt2dma(struct k3_cppi_desc_pool
*pool
,
105 return addr
? pool
->dma_addr
+ (addr
- pool
->cpumem
) : 0;
108 void *k3_cppi_desc_pool_dma2virt(struct k3_cppi_desc_pool
*pool
, dma_addr_t dma
)
110 return dma
? pool
->cpumem
+ (dma
- pool
->dma_addr
) : NULL
;
113 void *k3_cppi_desc_pool_alloc(struct k3_cppi_desc_pool
*pool
)
115 return (void *)gen_pool_alloc(pool
->gen_pool
, pool
->desc_size
);
118 void k3_cppi_desc_pool_free(struct k3_cppi_desc_pool
*pool
, void *addr
)
120 gen_pool_free(pool
->gen_pool
, (unsigned long)addr
, pool
->desc_size
);
123 size_t k3_cppi_desc_pool_avail(struct k3_cppi_desc_pool
*pool
)
125 return gen_pool_avail(pool
->gen_pool
) / pool
->desc_size
;