1 // Copyright 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #include "OpenglEsPipe.h"
15
16 #include "base/Optional.h"
17 #include "base/PathUtils.h"
18 #include "base/StreamSerializing.h"
19 #include "base/FunctorThread.h"
20 #include "base/System.h"
21 #include "../globals.h"
22 // #include "loadpng.h"
23 #include "GLProcessPipe.h"
24 #include "../opengles-pipe.h"
25 #include "../opengles.h"
26 // #include "snapshot/Loader.h"
27 // #include "snapshot/Saver.h"
28 // #include "snapshot/Snapshotter.h"
29
30 #include <atomic>
31
32 #include <assert.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 // Set to 1 or 2 for debug traces
37 #define DEBUG 0
38
39 #if DEBUG >= 1
40 #define D(...) printf(__VA_ARGS__), printf("\n"), fflush(stdout)
41 #else
42 #define D(...) ((void)0)
43 #endif
44
45 #if DEBUG >= 2
46 #define DD(...) printf(__VA_ARGS__), printf("\n"), fflush(stdout)
47 #else
48 #define DD(...) ((void)0)
49 #endif
50
51 using ChannelBuffer = emugl::RenderChannel::Buffer;
52 using emugl::RenderChannel;
53 using emugl::RenderChannelPtr;
54 using ChannelState = emugl::RenderChannel::State;
55 using IoResult = emugl::RenderChannel::IoResult;
56 // using android::base::Stopwatch;
57 // using android::snapshot::Snapshotter;
58
59 #define OPENGL_SAVE_VERSION 1
60
61 namespace android {
62 namespace opengl {
63
64 // TODO (b/138549350): See if Android/Fuchsia pipe protocols can be unified
65 // to give the best performance in each guest OS.
66 enum class RecvMode {
67 Android = 0,
68 Fuchsia = 1,
69 VirtioGpu = 2,
70 };
71
72 static RecvMode recvMode = RecvMode::Android;
73
74 namespace {
75
76 class EmuglPipe : public AndroidPipe {
77 public:
78
79 //////////////////////////////////////////////////////////////////////////
80 // The pipe service class for this implementation.
81 class Service : public AndroidPipe::Service {
82 public:
Service()83 Service() : AndroidPipe::Service("opengles") {}
84
85 // Create a new EmuglPipe instance.
create(void * hwPipe,const char * args,AndroidPipeFlags flags)86 AndroidPipe* create(void* hwPipe, const char* args, AndroidPipeFlags flags) override {
87 return createPipe(hwPipe, this, args);
88 }
89
canLoad() const90 bool canLoad() const override { return true; }
91
preLoad(android::base::Stream * stream)92 virtual void preLoad(android::base::Stream* stream) override {
93 // #ifdef SNAPSHOT_PROFILE
94 // mLoadMeter.restartUs();
95 // #endif
96 // const bool hasRenderer = stream->getByte();
97 // const auto& renderer = android_getOpenglesRenderer();
98 // if (hasRenderer != (bool)renderer) {
99 // // die?
100 // return;
101 // }
102 // if (!hasRenderer) {
103 // return;
104 // }
105 // int version = stream->getBe32();
106 // (void)version;
107 // renderer->load(stream, Snapshotter::get().loader().textureLoader());
108 // #ifdef SNAPSHOT_PROFILE
109 // printf("OpenglEs preload time: %lld ms\n",
110 // (long long)(mLoadMeter.elapsedUs() / 1000));
111 // #endif
112 }
113
postLoad(android::base::Stream * stream)114 void postLoad(android::base::Stream* stream) override {
115 if (const auto& renderer = android_getOpenglesRenderer()) {
116 renderer->resumeAll();
117 }
118 #ifdef SNAPSHOT_PROFILE
119 printf("OpenglEs total load time: %lld ms\n",
120 (long long)(mLoadMeter.elapsedUs() / 1000));
121 #endif
122 }
123
preSave(android::base::Stream * stream)124 void preSave(android::base::Stream* stream) override {
125 // #ifdef SNAPSHOT_PROFILE
126 // mSaveMeter.restartUs();
127 // #endif
128 // if (const auto& renderer = android_getOpenglesRenderer()) {
129 // renderer->pauseAllPreSave();
130 // stream->putByte(1);
131 // stream->putBe32(OPENGL_SAVE_VERSION);
132 // renderer->save(stream,
133 // Snapshotter::get().saver().textureSaver());
134 //
135 // writeScreenshot(*renderer);
136 // } else {
137 // stream->putByte(0);
138 // }
139 }
140
postSave(android::base::Stream * stream)141 void postSave(android::base::Stream* stream) override {
142 if (const auto& renderer = android_getOpenglesRenderer()) {
143 renderer->resumeAll();
144 }
145 #ifdef SNAPSHOT_PROFILE
146 printf("OpenglEs total save time: %lld ms\n",
147 (long long)(mSaveMeter.elapsedUs() / 1000));
148 #endif
149 }
150
load(void * hwPipe,const char * args,android::base::Stream * stream)151 virtual AndroidPipe* load(void* hwPipe,
152 const char* args,
153 android::base::Stream* stream) override {
154 return createPipe(hwPipe, this, args, stream);
155 }
156
157 private:
createPipe(void * hwPipe,Service * service,const char * args,android::base::Stream * loadStream=nullptr)158 static AndroidPipe* createPipe(
159 void* hwPipe,
160 Service* service,
161 const char* args,
162 android::base::Stream* loadStream = nullptr) {
163 const auto& renderer = android_getOpenglesRenderer();
164 if (!renderer) {
165 // This should never happen, unless there is a bug in the
166 // emulator's initialization, or the system image, or we're
167 // loading from an incompatible snapshot.
168 D("Trying to open the OpenGLES pipe without GPU emulation!");
169 return nullptr;
170 }
171
172 auto pipe = new EmuglPipe(hwPipe, service, renderer, loadStream);
173 if (!pipe->mIsWorking) {
174 delete pipe;
175 pipe = nullptr;
176 }
177 return pipe;
178 }
179
writeScreenshot(emugl::Renderer & renderer)180 void writeScreenshot(emugl::Renderer& renderer) {
181 // #if SNAPSHOT_PROFILE > 1
182 // Stopwatch sw;
183 // #endif
184 // if (!mSnapshotCallbackRegistered) {
185 // // We have to wait for the screenshot saving thread, but
186 // // there's no need to join it too soon: it is ok to only
187 // // block when the rest of snapshot saving is complete.
188 // // Snapshotter::get().addOperationCallback(
189 // // [this](Snapshotter::Operation op,
190 // // Snapshotter::Stage stage) {
191 // // if (op == Snapshotter::Operation::Save &&
192 // // stage == Snapshotter::Stage::End) {
193 // // if (mScreenshotSaver) {
194 // // mScreenshotSaver->wait();
195 // // mScreenshotSaver.clear();
196 // // }
197 // // }
198 // // });
199 // mSnapshotCallbackRegistered = true;
200 // }
201 // // always do 4 channel screenshot because swiftshader_indirect
202 // // has issues with 3 channels
203 // const unsigned int nChannels = 4;
204 // unsigned int width;
205 // unsigned int height;
206 // std::vector<unsigned char> pixels;
207 // renderer.getScreenshot(nChannels, &width, &height, pixels);
208 // #if SNAPSHOT_PROFILE > 1
209 // printf("Screenshot load texture time %lld ms\n",
210 // (long long)(sw.elapsedUs() / 1000));
211 // #endif
212 // if (width > 0 && height > 0) {
213 // std::string dataDir =
214 // Snapshotter::get().saver().snapshot().dataDir();
215 // mScreenshotSaver.emplace([nChannels, width, height,
216 // dataDir = std::move(dataDir),
217 // pixels = std::move(pixels)] {
218 // #if SNAPSHOT_PROFILE > 1
219 // Stopwatch sw;
220 // #endif
221 // std::string fileName = android::base::PathUtils::join(
222 // dataDir, "screenshot.png");
223 // // TODO: fix the screenshot rotation?
224 // savepng(fileName.c_str(), nChannels, width, height,
225 // SKIN_ROTATION_0,
226 // const_cast<unsigned char*>(pixels.data()));
227 // #if SNAPSHOT_PROFILE > 1
228 // printf("Screenshot image write time %lld ms\n",
229 // (long long)(sw.elapsedUs() / 1000));
230 // #endif
231 // });
232 // mScreenshotSaver->start();
233 // }
234 }
235
236 base::Optional<base::FunctorThread> mScreenshotSaver;
237 #ifdef SNAPSHOT_PROFILE
238 Stopwatch mSaveMeter;
239 Stopwatch mLoadMeter;
240 #endif
241 };
242
243 /////////////////////////////////////////////////////////////////////////
244 // Constructor, check that |mIsWorking| is true after this call to verify
245 // that everything went well.
EmuglPipe(void * hwPipe,Service * service,const emugl::RendererPtr & renderer,android::base::Stream * loadStream=nullptr)246 EmuglPipe(void* hwPipe,
247 Service* service,
248 const emugl::RendererPtr& renderer,
249 android::base::Stream* loadStream = nullptr)
250 : AndroidPipe(hwPipe, service) {
251 bool isWorking = true;
252 if (loadStream) {
253 DD("%s: loading GLES pipe state for hwpipe=%p", __func__, mHwPipe);
254 isWorking = (bool)loadStream->getBe32();
255 android::base::loadBuffer(loadStream, &mDataForReading);
256 mDataForReadingLeft = loadStream->getBe32();
257 }
258
259 mChannel = renderer->createRenderChannel(loadStream);
260 if (!mChannel) {
261 D("Failed to create an OpenGLES pipe channel!");
262 return;
263 }
264
265 mIsWorking = isWorking;
266 mChannel->setEventCallback([this](RenderChannel::State events) {
267 onChannelHostEvent(events);
268 });
269 }
270
271 //////////////////////////////////////////////////////////////////////////
272 // Overriden AndroidPipe methods
273
onSave(android::base::Stream * stream)274 virtual void onSave(android::base::Stream* stream) override {
275 DD("%s: saving GLES pipe state for hwpipe=%p", __FUNCTION__, mHwPipe);
276 stream->putBe32(mIsWorking);
277 android::base::saveBuffer(stream, mDataForReading);
278 stream->putBe32(mDataForReadingLeft);
279
280 mChannel->onSave(stream);
281 }
282
onGuestClose(PipeCloseReason reason)283 virtual void onGuestClose(PipeCloseReason reason) override {
284 D("%s", __func__);
285 mIsWorking = false;
286 mChannel->stop();
287 // Make sure there's no operation scheduled for this pipe instance to
288 // run on the main thread.
289 abortPendingOperation();
290 delete this;
291 }
292
onGuestPoll() const293 virtual unsigned onGuestPoll() const override {
294 DD("%s", __func__);
295
296 unsigned ret = 0;
297 if (mDataForReadingLeft > 0) {
298 ret |= PIPE_POLL_IN;
299 }
300 ChannelState state = mChannel->state();
301 if ((state & ChannelState::CanRead) != 0) {
302 ret |= PIPE_POLL_IN;
303 }
304 if ((state & ChannelState::CanWrite) != 0) {
305 ret |= PIPE_POLL_OUT;
306 }
307 if ((state & ChannelState::Stopped) != 0) {
308 ret |= PIPE_POLL_HUP;
309 }
310 DD("%s: returning %d", __func__, ret);
311 return ret;
312 }
313
onGuestRecv(AndroidPipeBuffer * buffers,int numBuffers)314 virtual int onGuestRecv(AndroidPipeBuffer* buffers,
315 int numBuffers) override {
316 DD("%s", __func__);
317
318 // Consume the pipe's dataForReading, then put the next received data
319 // piece there. Repeat until the buffers are full or we're out of data
320 // in the channel.
321 int len = 0;
322 size_t buffOffset = 0;
323
324 auto buff = buffers;
325 const auto buffEnd = buff + numBuffers;
326 while (buff != buffEnd) {
327 if (mDataForReadingLeft == 0) {
328 if (android::opengl::recvMode == android::opengl::RecvMode::Android) {
329 // No data left, read a new chunk from the channel.
330 int spinCount = 20;
331 for (;;) {
332
333 auto result = mChannel->tryRead(&mDataForReading);
334 if (result == IoResult::Ok) {
335 mDataForReadingLeft = mDataForReading.size();
336 break;
337 }
338 DD("%s: tryRead() failed with %d", __func__, (int)result);
339 if (len > 0) {
340 DD("%s: returning %d bytes", __func__, (int)len);
341 return len;
342 }
343 // This failed either because the channel was stopped
344 // from the host, or if there was no data yet in the
345 if (result == IoResult::Error) {
346 return PIPE_ERROR_IO;
347 }
348 // Spin a little before declaring there is nothing
349 // to read. Many GL calls are much faster than the
350 // whole host-to-guest-to-host transition.
351 if (--spinCount > 0) {
352 continue;
353 }
354 DD("%s: returning PIPE_ERROR_AGAIN", __func__);
355 return PIPE_ERROR_AGAIN;
356 }
357 } else if (android::opengl::recvMode == android::opengl::RecvMode::Fuchsia) {
358 // No data left, return if we already received some data,
359 // otherwise read a new chunk from the channel.
360 if (len > 0) {
361 DD("%s: returning %d bytes", __func__, (int)len);
362 return len;
363 }
364 // Block a little before declaring there is nothing
365 // to read. This gives the render thread a chance to
366 // process pending data before we return control to
367 // the guest. The amount of time we block here should
368 // be kept at a minimum. It's preferred to instead have
369 // the guest block on work that takes a significant
370 // amount of time.
371
372 const RenderChannel::Duration kBlockAtMostUs = 100;
373 auto currTime = android::base::getUnixTimeUs();
374 auto result = mChannel->readBefore(&mDataForReading, currTime + kBlockAtMostUs);
375
376 if (result != IoResult::Ok) {
377 DD("%s: tryRead() failed with %d", __func__, (int)result);
378 // This failed either because the channel was stopped
379 // from the host, or if there was no data yet in the
380 // channel.
381 if (len > 0) {
382 DD("%s: returning %d bytes", __func__, (int)len);
383 return len;
384 }
385 if (result == IoResult::Error) {
386 return PIPE_ERROR_IO;
387 }
388
389 DD("%s: returning PIPE_ERROR_AGAIN", __func__);
390 return PIPE_ERROR_AGAIN;
391 }
392 mDataForReadingLeft = mDataForReading.size();
393 } else { // Virtio-gpu
394 // No data left, return if we already received some data,
395 // otherwise read a new chunk from the channel.
396 if (len > 0) {
397 DD("%s: returning %d bytes", __func__, (int)len);
398 return len;
399 }
400 // Block a little before declaring there is nothing
401 // to read. This gives the render thread a chance to
402 // process pending data before we return control to
403 // the guest. The amount of time we block here should
404 // be kept at a minimum. It's preferred to instead have
405 // the guest block on work that takes a significant
406 // amount of time.
407
408 const RenderChannel::Duration kBlockAtMostUs = 10000;
409 auto currTime = android::base::getUnixTimeUs();
410 auto result = mChannel->readBefore(&mDataForReading, currTime + kBlockAtMostUs);
411
412 if (result != IoResult::Ok) {
413 DD("%s: tryRead() failed with %d", __func__, (int)result);
414 // This failed either because the channel was stopped
415 // from the host, or if there was no data yet in the
416 // channel.
417 if (len > 0) {
418 DD("%s: returning %d bytes", __func__, (int)len);
419 return len;
420 }
421 if (result == IoResult::Error) {
422 return PIPE_ERROR_IO;
423 }
424
425 DD("%s: returning PIPE_ERROR_AGAIN", __func__);
426 return PIPE_ERROR_AGAIN;
427 }
428 mDataForReadingLeft = mDataForReading.size();
429 }
430 }
431
432 const size_t curSize = std::min<size_t>(buff->size - buffOffset,
433 mDataForReadingLeft);
434 memcpy(buff->data + buffOffset,
435 mDataForReading.data() +
436 (mDataForReading.size() - mDataForReadingLeft),
437 curSize);
438
439 len += curSize;
440 mDataForReadingLeft -= curSize;
441 buffOffset += curSize;
442 if (buffOffset == buff->size) {
443 ++buff;
444 buffOffset = 0;
445 }
446 }
447
448 DD("%s: received %d bytes", __func__, (int)len);
449 return len;
450 }
451
onGuestSend(const AndroidPipeBuffer * buffers,int numBuffers,void ** newPipePtr)452 virtual int onGuestSend(const AndroidPipeBuffer* buffers,
453 int numBuffers,
454 void** newPipePtr) override {
455 DD("%s", __func__);
456
457 if (!mIsWorking) {
458 DD("%s: pipe already closed!", __func__);
459 return PIPE_ERROR_IO;
460 }
461
462 // Count the total bytes to send.
463 int count = 0;
464 for (int n = 0; n < numBuffers; ++n) {
465 count += buffers[n].size;
466 }
467
468 // Copy everything into a single ChannelBuffer.
469 ChannelBuffer outBuffer;
470 outBuffer.resize_noinit(count);
471 auto ptr = outBuffer.data();
472 for (int n = 0; n < numBuffers; ++n) {
473 memcpy(ptr, buffers[n].data, buffers[n].size);
474 ptr += buffers[n].size;
475 }
476
477 D("%s: %p sending %d bytes to host", __func__, this, count);
478 // Send it through the channel.
479 auto result = mChannel->tryWrite(std::move(outBuffer));
480 if (result != IoResult::Ok) {
481 D("%s: tryWrite() failed with %d", __func__, (int)result);
482 return result == IoResult::Error ? PIPE_ERROR_IO : PIPE_ERROR_AGAIN;
483 }
484
485 return count;
486 }
487
onGuestWantWakeOn(int flags)488 virtual void onGuestWantWakeOn(int flags) override {
489 DD("%s: flags=%d", __func__, flags);
490
491 // Translate |flags| into ChannelState flags.
492 ChannelState wanted = ChannelState::Empty;
493 if (flags & PIPE_WAKE_READ) {
494 wanted |= ChannelState::CanRead;
495 }
496 if (flags & PIPE_WAKE_WRITE) {
497 wanted |= ChannelState::CanWrite;
498 }
499
500 // Signal events that are already available now.
501 ChannelState state = mChannel->state();
502 ChannelState available = state & wanted;
503 DD("%s: state=%d wanted=%d available=%d", __func__, (int)state,
504 (int)wanted, (int)available);
505 if (available != ChannelState::Empty) {
506 DD("%s: signaling events %d", __func__, (int)available);
507 signalState(available);
508 wanted &= ~available;
509 }
510
511 // Ask the channel to be notified of remaining events.
512 if (wanted != ChannelState::Empty) {
513 DD("%s: waiting for events %d", __func__, (int)wanted);
514 mChannel->setWantedEvents(wanted);
515 }
516 }
517
518 private:
519 // Called to signal the guest that read/write wake events occured.
520 // Note: this can be called from either the guest or host render
521 // thread.
signalState(ChannelState state)522 void signalState(ChannelState state) {
523 int wakeFlags = 0;
524 if ((state & ChannelState::CanRead) != 0) {
525 wakeFlags |= PIPE_WAKE_READ;
526 }
527 if ((state & ChannelState::CanWrite) != 0) {
528 wakeFlags |= PIPE_WAKE_WRITE;
529 }
530 if (wakeFlags != 0) {
531 this->signalWake(wakeFlags);
532 }
533 }
534
535 // Called when an i/o event occurs on the render channel
onChannelHostEvent(ChannelState state)536 void onChannelHostEvent(ChannelState state) {
537 D("%s: events %d (working %d)", __func__, (int)state, (int)mIsWorking);
538 // NOTE: This is called from the host-side render thread.
539 // but closeFromHost() and signalWake() can be called from
540 // any thread.
541 if (!mIsWorking) {
542 return;
543 }
544 if ((state & ChannelState::Stopped) != 0) {
545 this->closeFromHost();
546 return;
547 }
548 signalState(state);
549 }
550
551 // A RenderChannel pointer used for communication.
552 RenderChannelPtr mChannel;
553
554 // Set to |true| if the pipe is in working state, |false| means we're not
555 // initialized or the pipe is closed.
556 bool mIsWorking = false;
557
558 // These two variables serve as a reading buffer for the guest.
559 // Each time we get a read request, first we extract a single chunk from
560 // the |mChannel| into here, and then copy its content into the
561 // guest-supplied memory.
562 // If guest didn't have enough room for the whole buffer, we track the
563 // number of remaining bytes in |mDataForReadingLeft| for the next read().
564 uint32_t mDataForReadingLeft = 0;
565 ChannelBuffer mDataForReading;
566
567 DISALLOW_COPY_ASSIGN_AND_MOVE(EmuglPipe);
568 };
569
570 } // namespace
571
registerPipeService()572 void registerPipeService() {
573 android::AndroidPipe::Service::add(std::make_unique<EmuglPipe::Service>());
574 registerGLProcessPipeService();
575 }
576
pipeSetRecvMode(int mode)577 void pipeSetRecvMode(int mode) {
578 recvMode = (RecvMode)mode;
579 }
580
581 } // namespace opengl
582 } // namespace android
583
584 // Declared in android/opengles-pipe.h
android_init_opengles_pipe()585 void android_init_opengles_pipe() {
586 android::opengl::registerPipeService();
587 }
588
android_opengles_pipe_set_recv_mode(int mode)589 void android_opengles_pipe_set_recv_mode(int mode) {
590 android::opengl::pipeSetRecvMode(mode);
591 }
592
593