1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35#include <linux/export.h>
36#include <drm/drm_buffer.h>
37
38
39
40
41
42
43
44int drm_buffer_alloc(struct drm_buffer **buf, int size)
45{
46 int nr_pages = size / PAGE_SIZE + 1;
47 int idx;
48
49
50
51 *buf = kzalloc(sizeof(struct drm_buffer) + nr_pages*sizeof(char *),
52 GFP_KERNEL);
53
54 if (*buf == NULL) {
55 DRM_ERROR("Failed to allocate drm buffer object to hold"
56 " %d bytes in %d pages.\n",
57 size, nr_pages);
58 return -ENOMEM;
59 }
60
61 (*buf)->size = size;
62
63 for (idx = 0; idx < nr_pages; ++idx) {
64
65 (*buf)->data[idx] =
66 kmalloc(min(PAGE_SIZE, size - idx * PAGE_SIZE),
67 GFP_KERNEL);
68
69
70 if ((*buf)->data[idx] == NULL) {
71 DRM_ERROR("Failed to allocate %dth page for drm"
72 " buffer with %d bytes and %d pages.\n",
73 idx + 1, size, nr_pages);
74 goto error_out;
75 }
76
77 }
78
79 return 0;
80
81error_out:
82
83
84 if ((*buf)->data[idx])
85 kfree((*buf)->data[idx]);
86
87 for (--idx; idx >= 0; --idx)
88 kfree((*buf)->data[idx]);
89
90 kfree(*buf);
91 return -ENOMEM;
92}
93EXPORT_SYMBOL(drm_buffer_alloc);
94
95
96
97
98
99
100
101
102int drm_buffer_copy_from_user(struct drm_buffer *buf,
103 void __user *user_data, int size)
104{
105 int nr_pages = size / PAGE_SIZE + 1;
106 int idx;
107
108 if (size > buf->size) {
109 DRM_ERROR("Requesting to copy %d bytes to a drm buffer with"
110 " %d bytes space\n",
111 size, buf->size);
112 return -EFAULT;
113 }
114
115 for (idx = 0; idx < nr_pages; ++idx) {
116
117 if (DRM_COPY_FROM_USER(buf->data[idx],
118 user_data + idx * PAGE_SIZE,
119 min(PAGE_SIZE, size - idx * PAGE_SIZE))) {
120 DRM_ERROR("Failed to copy user data (%p) to drm buffer"
121 " (%p) %dth page.\n",
122 user_data, buf, idx);
123 return -EFAULT;
124
125 }
126 }
127 buf->iterator = 0;
128 return 0;
129}
130EXPORT_SYMBOL(drm_buffer_copy_from_user);
131
132
133
134
135void drm_buffer_free(struct drm_buffer *buf)
136{
137
138 if (buf != NULL) {
139
140 int nr_pages = buf->size / PAGE_SIZE + 1;
141 int idx;
142 for (idx = 0; idx < nr_pages; ++idx)
143 kfree(buf->data[idx]);
144
145 kfree(buf);
146 }
147}
148EXPORT_SYMBOL(drm_buffer_free);
149
150
151
152
153
154
155
156
157
158
159
160
161
162void *drm_buffer_read_object(struct drm_buffer *buf,
163 int objsize, void *stack_obj)
164{
165 int idx = drm_buffer_index(buf);
166 int page = drm_buffer_page(buf);
167 void *obj = NULL;
168
169 if (idx + objsize <= PAGE_SIZE) {
170 obj = &buf->data[page][idx];
171 } else {
172
173 int beginsz = PAGE_SIZE - idx;
174 memcpy(stack_obj, &buf->data[page][idx], beginsz);
175
176 memcpy(stack_obj + beginsz, &buf->data[page + 1][0],
177 objsize - beginsz);
178
179 obj = stack_obj;
180 }
181
182 drm_buffer_advance(buf, objsize);
183 return obj;
184}
185EXPORT_SYMBOL(drm_buffer_read_object);
186