1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * An example software sink buffer for Intel TH MSU.
4  *
5  * Copyright (C) 2019 Intel Corporation.
6  */
7 
8 #include <linux/intel_th.h>
9 #include <linux/module.h>
10 #include <linux/slab.h>
11 #include <linux/device.h>
12 #include <linux/dma-mapping.h>
13 
14 #define MAX_SGTS 16
15 
16 struct msu_sink_private {
17 	struct device	*dev;
18 	struct sg_table **sgts;
19 	unsigned int	nr_sgts;
20 };
21 
22 static void *msu_sink_assign(struct device *dev, int *mode)
23 {
24 	struct msu_sink_private *priv;
25 
26 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
27 	if (!priv)
28 		return NULL;
29 
30 	priv->sgts = kcalloc(MAX_SGTS, sizeof(void *), GFP_KERNEL);
31 	if (!priv->sgts) {
32 		kfree(priv);
33 		return NULL;
34 	}
35 
36 	priv->dev = dev;
37 	*mode = MSC_MODE_MULTI;
38 
39 	return priv;
40 }
41 
42 static void msu_sink_unassign(void *data)
43 {
44 	struct msu_sink_private *priv = data;
45 
46 	kfree(priv->sgts);
47 	kfree(priv);
48 }
49 
50 /* See also: msc.c: __msc_buffer_win_alloc() */
51 static int msu_sink_alloc_window(void *data, struct sg_table **sgt, size_t size)
52 {
53 	struct msu_sink_private *priv = data;
54 	unsigned int nents;
55 	struct scatterlist *sg_ptr;
56 	void *block;
57 	int ret, i;
58 
59 	if (priv->nr_sgts == MAX_SGTS)
60 		return -ENOMEM;
61 
62 	nents = DIV_ROUND_UP(size, PAGE_SIZE);
63 
64 	ret = sg_alloc_table(*sgt, nents, GFP_KERNEL);
65 	if (ret)
66 		return -ENOMEM;
67 
68 	priv->sgts[priv->nr_sgts++] = *sgt;
69 
70 	for_each_sg((*sgt)->sgl, sg_ptr, nents, i) {
71 		block = dma_alloc_coherent(priv->dev->parent->parent,
72 					   PAGE_SIZE, &sg_dma_address(sg_ptr),
73 					   GFP_KERNEL);
74 		sg_set_buf(sg_ptr, block, PAGE_SIZE);
75 	}
76 
77 	return nents;
78 }
79 
80 /* See also: msc.c: __msc_buffer_win_free() */
81 static void msu_sink_free_window(void *data, struct sg_table *sgt)
82 {
83 	struct msu_sink_private *priv = data;
84 	struct scatterlist *sg_ptr;
85 	int i;
86 
87 	for_each_sg(sgt->sgl, sg_ptr, sgt->nents, i) {
88 		dma_free_coherent(priv->dev->parent->parent, PAGE_SIZE,
89 				  sg_virt(sg_ptr), sg_dma_address(sg_ptr));
90 	}
91 
92 	sg_free_table(sgt);
93 	priv->nr_sgts--;
94 }
95 
96 static int msu_sink_ready(void *data, struct sg_table *sgt, size_t bytes)
97 {
98 	struct msu_sink_private *priv = data;
99 
100 	intel_th_msc_window_unlock(priv->dev, sgt);
101 
102 	return 0;
103 }
104 
105 static const struct msu_buffer sink_mbuf = {
106 	.name		= "sink",
107 	.assign		= msu_sink_assign,
108 	.unassign	= msu_sink_unassign,
109 	.alloc_window	= msu_sink_alloc_window,
110 	.free_window	= msu_sink_free_window,
111 	.ready		= msu_sink_ready,
112 };
113 
114 module_intel_th_msu_buffer(sink_mbuf);
115 
116 MODULE_LICENSE("GPL v2");
117