blob: cb63081d640f992a215cd2fee041e44c5d71377b [file] [log] [blame]
Mikael Olsson9c999fd2023-10-30 11:05:39 +01001/*
2 * SPDX-FileCopyrightText: Copyright 2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
3 * SPDX-License-Identifier: GPL-2.0-only
4 *
5 * This program is free software and is provided to you under the terms of the
6 * GNU General Public License version 2 as published by the Free Software
7 * Foundation, and any use by you of this program is subject to the terms
8 * of such GNU licence.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, you can access it online at
17 * http://www.gnu.org/licenses/gpl-2.0.html.
18 */
19
20/****************************************************************************
21 * Includes
22 ****************************************************************************/
23
24#include "ethosu_dma_mem.h"
25
26#include <linux/err.h>
27#include <linux/dma-mapping.h>
28
29/****************************************************************************
30 * Functions
31 ****************************************************************************/
32
33struct ethosu_dma_mem *ethosu_dma_mem_alloc(struct device *dev,
34 size_t size)
35{
36 struct ethosu_dma_mem *dma_mem;
37
38 if (!size)
39 return ERR_PTR(-EINVAL);
40
41 dma_mem = devm_kzalloc(dev, sizeof(*dma_mem), GFP_KERNEL);
42 if (!dma_mem)
43 return ERR_PTR(-ENOMEM);
44
45 dma_mem->dev = dev;
46 dma_mem->size = size;
47 dma_mem->cpu_addr = dma_alloc_coherent(dev, size, &dma_mem->dma_addr,
48 GFP_KERNEL);
49 if (!dma_mem->cpu_addr) {
50 memset(dma_mem, 0, sizeof(*dma_mem));
51 devm_kfree(dev, dma_mem);
52
53 return ERR_PTR(-ENOMEM);
54 }
55
56 return dma_mem;
57}
58
59void ethosu_dma_mem_free(struct ethosu_dma_mem **dma_mem)
60{
61 struct device *dev;
62 struct ethosu_dma_mem *mem;
63
64 if (!dma_mem || !*dma_mem)
65 return;
66
67 mem = *dma_mem;
68 dev = mem->dev;
69
70 memset(mem->cpu_addr, 0, mem->size);
71 dma_free_coherent(dev, mem->size, mem->cpu_addr, mem->dma_addr);
72
73 memset(mem, 0, sizeof(*mem));
74 devm_kfree(dev, mem);
75
76 *dma_mem = NULL;
77}