1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "VirtioGpuStream.h"
18 
19 #include <cros_gralloc_handle.h>
20 #include <drm/virtgpu_drm.h>
21 #include <xf86drm.h>
22 
23 #include <sys/types.h>
24 #include <sys/mman.h>
25 
26 #include <errno.h>
27 #include <unistd.h>
28 
29 #ifndef PAGE_SIZE
30 #define PAGE_SIZE 0x1000
31 #endif
32 
33 // In a virtual machine, there should only be one GPU
34 #define RENDERNODE_MINOR 128
35 
36 // Maximum size of readback / response buffer in bytes
37 #define MAX_CMDRESPBUF_SIZE (10*PAGE_SIZE)
38 
39 // Attributes use to allocate our response buffer
40 // Similar to virgl's fence objects
41 #define PIPE_BUFFER             0
42 #define VIRGL_FORMAT_R8_UNORM   64
43 #define VIRGL_BIND_CUSTOM       (1 << 17)
44 
45 // Conservative; see virgl_winsys.h
46 #define VIRGL_MAX_CMDBUF_DWORDS (16*1024)
47 #define VIRGL_MAX_CMDBUF_SIZE   (4*VIRGL_MAX_CMDBUF_DWORDS)
48 
49 struct VirtioGpuCmd {
50     uint32_t op;
51     uint32_t cmdSize;
52     unsigned char buf[0];
53 } __attribute__((packed));
54 
processPipeInit(HostConnectionType,renderControl_encoder_context_t * rcEnc)55 bool VirtioGpuProcessPipe::processPipeInit(HostConnectionType, renderControl_encoder_context_t *rcEnc)
56 {
57   union {
58       uint64_t proto;
59       struct {
60           int pid;
61           int tid;
62       } id;
63   } puid = {
64       .id.pid = getpid(),
65       .id.tid = gettid(),
66   };
67   rcEnc->rcSetPuid(rcEnc, puid.proto);
68   return true;
69 }
70 
VirtioGpuStream(size_t bufSize)71 VirtioGpuStream::VirtioGpuStream(size_t bufSize) :
72     IOStream(0U),
73     m_fd(-1),
74     m_bufSize(bufSize),
75     m_buf(nullptr),
76     m_cmdResp_rh(0U),
77     m_cmdResp_bo(0U),
78     m_cmdResp(nullptr),
79     m_cmdRespPos(0U),
80     m_cmdPos(0U),
81     m_flushPos(0U),
82     m_allocSize(0U),
83     m_allocFlushSize(0U)
84 {
85 }
86 
~VirtioGpuStream()87 VirtioGpuStream::~VirtioGpuStream()
88 {
89     if (m_cmdResp) {
90         munmap(m_cmdResp, MAX_CMDRESPBUF_SIZE);
91     }
92 
93     if (m_cmdResp_bo > 0U) {
94         drm_gem_close gem_close = {
95             .handle = m_cmdResp_bo,
96         };
97         drmIoctl(m_fd, DRM_IOCTL_GEM_CLOSE, &gem_close);
98     }
99 
100     if (m_fd >= 0) {
101         close(m_fd);
102     }
103 
104     free(m_buf);
105 }
106 
connect()107 int VirtioGpuStream::connect()
108 {
109     if (m_fd < 0) {
110         m_fd = drmOpenRender(RENDERNODE_MINOR);
111         if (m_fd < 0) {
112             ERR("%s: failed with fd %d (%s)", __func__, m_fd, strerror(errno));
113             return -1;
114         }
115     }
116 
117     if (!m_cmdResp_bo) {
118         drm_virtgpu_resource_create create = {
119             .target     = PIPE_BUFFER,
120             .format     = VIRGL_FORMAT_R8_UNORM,
121             .bind       = VIRGL_BIND_CUSTOM,
122             .width      = MAX_CMDRESPBUF_SIZE,
123             .height     = 1U,
124             .depth      = 1U,
125             .array_size = 0U,
126             .size       = MAX_CMDRESPBUF_SIZE,
127             .stride     = MAX_CMDRESPBUF_SIZE,
128         };
129         int ret = drmIoctl(m_fd, DRM_IOCTL_VIRTGPU_RESOURCE_CREATE, &create);
130         if (ret) {
131             ERR("%s: failed with %d allocating command response buffer (%s)",
132                 __func__, ret, strerror(errno));
133             return -1;
134         }
135         m_cmdResp_bo = create.bo_handle;
136         if (!m_cmdResp_bo) {
137             ERR("%s: no handle when allocating command response buffer",
138                 __func__);
139             return -1;
140         }
141         m_cmdResp_rh = create.res_handle;
142         if (create.size != MAX_CMDRESPBUF_SIZE) {
143 	    ERR("%s: command response buffer wrongly sized, create.size=%zu "
144 		"!= %zu", __func__,
145 		static_cast<size_t>(create.size),
146 		static_cast<size_t>(MAX_CMDRESPBUF_SIZE));
147 	    abort();
148 	}
149     }
150 
151     if (!m_cmdResp) {
152         drm_virtgpu_map map = {
153             .handle = m_cmdResp_bo,
154         };
155         int ret = drmIoctl(m_fd, DRM_IOCTL_VIRTGPU_MAP, &map);
156         if (ret) {
157             ERR("%s: failed with %d mapping command response buffer (%s)",
158                 __func__, ret, strerror(errno));
159             return -1;
160         }
161         m_cmdResp = static_cast<VirtioGpuCmd *>(mmap64(nullptr,
162                                                        MAX_CMDRESPBUF_SIZE,
163                                                        PROT_READ, MAP_SHARED,
164                                                        m_fd, map.offset));
165         if (m_cmdResp == MAP_FAILED) {
166             ERR("%s: failed with %d mmap'ing command response buffer (%s)",
167                 __func__, ret, strerror(errno));
168             return -1;
169         }
170     }
171 
172     return 0;
173 }
174 
flush()175 int VirtioGpuStream::flush()
176 {
177     int ret = commitBuffer(m_allocSize - m_allocFlushSize);
178     if (ret)
179         return ret;
180     m_allocFlushSize = m_allocSize;
181     return 0;
182 }
183 
allocBuffer(size_t minSize)184 void *VirtioGpuStream::allocBuffer(size_t minSize)
185 {
186     if (m_buf) {
187         // Try to model the alloc() calls being made by the user. They should be
188         // obeying the protocol and using alloc() for anything they don't write
189         // with writeFully(), so we can know if this alloc() is for part of a
190         // command, or not. If it is not for part of a command, we are starting
191         // a new command, and should increment m_cmdPos.
192         VirtioGpuCmd *cmd = reinterpret_cast<VirtioGpuCmd *>(&m_buf[m_cmdPos]);
193         if (m_allocSize + minSize > cmd->cmdSize) {
194             m_allocFlushSize = 0U;
195             m_allocSize = 0U;
196             // This might also be a convenient point to flush commands
197             if (m_cmdPos + cmd->cmdSize + minSize > m_bufSize) {
198                 if (commitAll() < 0) {
199                     ERR("%s: command flush failed", __func__);
200                     m_flushPos = 0U;
201                     m_bufSize = 0U;
202                     m_cmdPos = 0U;
203                     free(m_buf);
204                     m_buf = nullptr;
205                     return nullptr;
206                 }
207             } else {
208                 m_cmdPos += cmd->cmdSize;
209                 m_flushPos = m_cmdPos;
210             }
211         }
212     }
213 
214     // Update m_allocSize here, before minSize is tampered with below
215     m_allocSize += minSize;
216 
217     // Make sure anything we already have written to the buffer is retained
218     minSize += m_flushPos;
219 
220     size_t allocSize = (m_bufSize < minSize ? minSize : m_bufSize);
221     if (!m_buf) {
222         m_buf = static_cast<unsigned char *>(malloc(allocSize));
223     } else if (m_bufSize < allocSize) {
224         unsigned char *p = static_cast<unsigned char *>(realloc(m_buf, allocSize));
225         if (!p) {
226             free(m_buf);
227         }
228         m_buf = p;
229     }
230     if (!m_buf) {
231         ERR("%s: alloc (%zu) failed\n", __func__, allocSize);
232         m_allocFlushSize = 0U;
233         m_allocSize = 0U;
234         m_flushPos = 0U;
235         m_bufSize = 0U;
236         m_cmdPos = 0U;
237     } else {
238         m_bufSize = allocSize;
239     }
240     if (m_flushPos == 0 && m_cmdPos == 0) {
241       // During initialization, HostConnection will send an empty command
242       // packet to check the connection is good, but it doesn't obey the usual
243       // line protocol. This is a 4 byte write to [0], which is our 'op' field,
244       // and we don't have an op=0 so it's OK. We fake up a valid length, and
245       // overload this workaround by putting the res_handle for the readback
246       // buffer in the command payload, patched in just before we submit.
247       VirtioGpuCmd *cmd = reinterpret_cast<VirtioGpuCmd *>(&m_buf[m_cmdPos]);
248       cmd->op = 0U;
249       cmd->cmdSize = sizeof(*cmd) + sizeof(__u32);
250     }
251     return m_buf + m_cmdPos;
252 }
253 
254 // For us, writeFully() means to write a command without any header, directly
255 // into the buffer stream. We can use the packet frame written directly to the
256 // stream to verify this write is within bounds, then update the counter.
257 
writeFully(const void * buf,size_t len)258 int VirtioGpuStream::writeFully(const void *buf, size_t len)
259 {
260     if (!valid())
261         return -1;
262 
263     if (!buf) {
264         if (len > 0) {
265             // If len is non-zero, buf must not be NULL. Otherwise the pipe would
266             // be in a corrupted state, which is lethal for the emulator.
267             ERR("%s: failed, buf=NULL, len %zu, lethal error, exiting",
268                 __func__, len);
269             abort();
270         }
271         return 0;
272     }
273 
274     VirtioGpuCmd *cmd = reinterpret_cast<VirtioGpuCmd *>(&m_buf[m_cmdPos]);
275 
276     if (m_flushPos < sizeof(*cmd)) {
277         ERR("%s: writeFully len %zu would overwrite command header, "
278             "cmd_pos=%zu, flush_pos=%zu, lethal error, exiting", __func__,
279             len, m_cmdPos, m_flushPos);
280         abort();
281     }
282 
283     if (m_flushPos + len > cmd->cmdSize) {
284         ERR("%s: writeFully len %zu would overflow the command bounds, "
285             "cmd_pos=%zu, flush_pos=%zu, cmdsize=%" PRIu32 ", lethal error, exiting",
286             __func__, len, m_cmdPos, m_flushPos, cmd->cmdSize);
287         abort();
288     }
289 
290     if (len > VIRGL_MAX_CMDBUF_SIZE) {
291         ERR("%s: Large command (%zu bytes) exceeds virgl limits",
292             __func__, len);
293         /* Fall through */
294     }
295 
296     memcpy(&m_buf[m_flushPos], buf, len);
297     commitBuffer(len);
298     m_allocSize += len;
299     return 0;
300 }
301 
readFully(void * buf,size_t len)302 const unsigned char *VirtioGpuStream::readFully(void *buf, size_t len)
303 {
304     if (!valid())
305         return nullptr;
306 
307     if (!buf) {
308         if (len > 0) {
309             // If len is non-zero, buf must not be NULL. Otherwise the pipe would
310             // be in a corrupted state, which is lethal for the emulator.
311             ERR("%s: failed, buf=NULL, len %zu, lethal error, exiting.",
312                 __func__, len);
313             abort();
314         }
315         return nullptr;
316     }
317 
318     // Read is too big for current architecture
319     if (len > MAX_CMDRESPBUF_SIZE - sizeof(*m_cmdResp)) {
320         ERR("%s: failed, read too large, len %zu, lethal error, exiting.",
321             __func__, len);
322         abort();
323     }
324 
325     // Commit all outstanding write commands (if any)
326     if (commitAll() < 0) {
327         ERR("%s: command flush failed", __func__);
328         return nullptr;
329     }
330 
331     if (len > 0U && m_cmdRespPos == 0U) {
332         // When we are about to read for the first time, wait for the virtqueue
333         // to drain to this command, otherwise the data could be stale
334         drm_virtgpu_3d_wait wait = {
335             .handle = m_cmdResp_bo,
336         };
337         int ret = drmIoctl(m_fd, DRM_IOCTL_VIRTGPU_WAIT, &wait);
338         if (ret) {
339             ERR("%s: failed with %d waiting for response buffer (%s)",
340                 __func__, ret, strerror(errno));
341             // Fall through, hope for the best
342         }
343     }
344 
345     // Most likely a protocol implementation error
346     if (m_cmdResp->cmdSize - sizeof(*m_cmdResp) < m_cmdRespPos + len) {
347         ERR("%s: failed, op %" PRIu32 ", len %zu, cmdSize %" PRIu32 ", pos %zu, lethal "
348             "error, exiting.", __func__, m_cmdResp->op, len,
349             m_cmdResp->cmdSize, m_cmdRespPos);
350         abort();
351     }
352 
353     memcpy(buf, &m_cmdResp->buf[m_cmdRespPos], len);
354 
355     if (m_cmdRespPos + len == m_cmdResp->cmdSize - sizeof(*m_cmdResp)) {
356         m_cmdRespPos = 0U;
357     } else {
358         m_cmdRespPos += len;
359     }
360 
361     return reinterpret_cast<const unsigned char *>(buf);
362 }
363 
commitBuffer(size_t size)364 int VirtioGpuStream::commitBuffer(size_t size)
365 {
366     if (m_flushPos + size > m_bufSize) {
367         ERR("%s: illegal commit size %zu, flushPos %zu, bufSize %zu",
368             __func__, size, m_flushPos, m_bufSize);
369         return -1;
370     }
371     m_flushPos += size;
372     return 0;
373 }
374 
commitAll()375 int VirtioGpuStream::commitAll()
376 {
377     size_t pos = 0U, numFlushed = 0U;
378     while (pos < m_flushPos) {
379         VirtioGpuCmd *cmd = reinterpret_cast<VirtioGpuCmd *>(&m_buf[pos]);
380 
381         // Should never happen
382         if (pos + cmd->cmdSize > m_bufSize) {
383             ERR("%s: failed, pos %zu, cmdSize %" PRIu32 ", bufSize %zu, lethal "
384                 "error, exiting.", __func__, pos, cmd->cmdSize, m_bufSize);
385             abort();
386         }
387 
388         // Saw dummy command; patch it with res handle
389         if (cmd->op == 0) {
390             *(uint32_t *)cmd->buf = m_cmdResp_rh;
391         }
392 
393         // Flush a single command
394         drm_virtgpu_execbuffer execbuffer = {
395             .size           = cmd->cmdSize,
396             .command        = reinterpret_cast<__u64>(cmd),
397             .bo_handles     = reinterpret_cast<__u64>(&m_cmdResp_bo),
398             .num_bo_handles = 1U,
399         };
400         int ret = drmIoctl(m_fd, DRM_IOCTL_VIRTGPU_EXECBUFFER, &execbuffer);
401         if (ret) {
402             ERR("%s: failed with %d executing command buffer (%s)",  __func__,
403                 ret, strerror(errno));
404             return -1;
405         }
406 
407         pos += cmd->cmdSize;
408         numFlushed++;
409     }
410 
411     if (pos > m_flushPos) {
412         ERR("%s: aliasing, flushPos %zu, pos %zu, probably ok", __func__,
413             m_flushPos, pos);
414         /* Fall through */
415     }
416 
417     m_flushPos = 0U;
418     m_cmdPos = 0U;
419     return 0;
420 }
421