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 #pragma once
18 
19 #include "HostConnection.h"
20 #include "IOStream.h"
21 
22 #include <stdlib.h>
23 
24 /* This file implements an IOStream that uses VIRTGPU TRANSFER* ioctls on a
25  * virtio-gpu DRM rendernode device to communicate with a goldfish-pipe
26  * service on the host side.
27  */
28 
29 class VirtioGpuPipeStream : public IOStream {
30 public:
31     typedef enum { ERR_INVALID_SOCKET = -1000 } QemuPipeStreamError;
32 
33     explicit VirtioGpuPipeStream(size_t bufsize = 10000);
34     ~VirtioGpuPipeStream();
35     int connect(const char* serviceName = 0);
36     static int openRendernode();
37     uint64_t initProcessPipe();
38 
39     virtual void *allocBuffer(size_t minSize);
40     virtual int commitBuffer(size_t size);
41     virtual const unsigned char *readFully( void *buf, size_t len);
42     virtual const unsigned char *commitBufferAndReadFully(
43         size_t size, void *buf, size_t len);
44     virtual const unsigned char *read( void *buf, size_t *inout_len);
45 
valid()46     bool valid() { return m_fd >= 0; }
getRendernodeFd()47     int getRendernodeFd() { return m_fd; }
48     int recv(void *buf, size_t len);
49 
50     virtual int writeFully(const void *buf, size_t len);
51 
52     int getSocket() const;
53 private:
54     // sync. Also resets the write position.
55     void wait();
56 
57     // transfer to/from host ops
58     ssize_t transferToHost(const void* buffer, size_t len);
59     ssize_t transferFromHost(void* buffer, size_t len);
60 
61     int m_fd; // rendernode fd
62 
63     uint32_t m_virtio_rh; // transfer buffer res handle
64     uint32_t m_virtio_bo; // transfer bo handle
65     unsigned char* m_virtio_mapped; // user mapping of bo
66 
67     // intermediate buffer
68     size_t m_bufsize;
69     unsigned char *m_buf;
70     size_t m_read;
71     size_t m_readLeft;
72 
73     size_t m_writtenPos;
74 
75     VirtioGpuPipeStream(int sock, size_t bufSize);
76 };
77