1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STMicroelectronics SA 2015
4  * Authors: Yannick Fertre <yannick.fertre@st.com>
5  *          Hugues Fruchet <hugues.fruchet@st.com>
6  */
7 
8 #include "hva.h"
9 #include "hva-mem.h"
10 
11 int hva_mem_alloc(struct hva_ctx *ctx, u32 size, const char *name,
12 		  struct hva_buffer **buf)
13 {
14 	struct device *dev = ctx_to_dev(ctx);
15 	struct hva_buffer *b;
16 	dma_addr_t paddr;
17 	void *base;
18 
19 	b = devm_kzalloc(dev, sizeof(*b), GFP_KERNEL);
20 	if (!b) {
21 		ctx->sys_errors++;
22 		return -ENOMEM;
23 	}
24 
25 	base = dma_alloc_attrs(dev, size, &paddr, GFP_KERNEL,
26 			       DMA_ATTR_WRITE_COMBINE);
27 	if (!base) {
28 		dev_err(dev, "%s %s : dma_alloc_attrs failed for %s (size=%d)\n",
29 			ctx->name, __func__, name, size);
30 		ctx->sys_errors++;
31 		devm_kfree(dev, b);
32 		return -ENOMEM;
33 	}
34 
35 	b->size = size;
36 	b->paddr = paddr;
37 	b->vaddr = base;
38 	b->name = name;
39 
40 	dev_dbg(dev,
41 		"%s allocate %d bytes of HW memory @(virt=%p, phy=%pad): %s\n",
42 		ctx->name, size, b->vaddr, &b->paddr, b->name);
43 
44 	/* return  hva buffer to user */
45 	*buf = b;
46 
47 	return 0;
48 }
49 
50 void hva_mem_free(struct hva_ctx *ctx, struct hva_buffer *buf)
51 {
52 	struct device *dev = ctx_to_dev(ctx);
53 
54 	dev_dbg(dev,
55 		"%s free %d bytes of HW memory @(virt=%p, phy=%pad): %s\n",
56 		ctx->name, buf->size, buf->vaddr, &buf->paddr, buf->name);
57 
58 	dma_free_attrs(dev, buf->size, buf->vaddr, buf->paddr,
59 		       DMA_ATTR_WRITE_COMBINE);
60 
61 	devm_kfree(dev, buf);
62 }
63