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 15 #pragma once 16 17 #include <memory> 18 #include "base/Stream.h" 19 #include "android_pipe_common.h" 20 #include "VmLock.h" 21 22 namespace android { 23 24 namespace base { 25 // Forward-declare looper here because it is only used by 26 // initThreadingForTest. 27 class Looper; 28 } // namespace base 29 30 // AndroidPipe is a mostly-abstract base class for Android pipe connections. 31 // It's important to understand that most pipe operations (onGuestXXX methods) 32 // are performed with the global VM lock held. 33 // 34 // - QEMU1 runs all CPU-related operations and all timers/io events on its 35 // main loop. This will be referred as the 'device thread' here. 36 // 37 // - QEMU2 has dedicated CPU threads to run guest read/write operations and 38 // a different main-loop thread to run timers, check for pending host I/O. 39 // It uses a global lock that is held every time virtual device operations 40 // are performed. The 'device thread' is whichever CPU thread is holding 41 // the lock. 42 // 43 // IMPORTANT: Most AndroidPipe methods must be called from a thread that holds 44 // the global VM state lock (i.e. where VmLock::isLockedBySelf() is true). 45 // Failure to do so will result in incorrect results, and panics in debug 46 // builds. 47 // 48 // A few methods can be called from any thread though, see signalWake() and 49 // closeFromHost(). 50 // 51 // Usage is the following: 52 // 53 // 1) At emulation setup time (i.e. before the VM runs), call 54 // AndroidPipe::initThreading() from the main loop thread and pass an 55 // appropriate VmLock instance. 56 // 57 // 2) For each supported pipe service, create a new AndroidPipe::Service 58 // instance, and register it globally by calling AndroidPipe::Service::add(). 59 // This can happen before 1) and in different threads. 60 // 61 // 3) Once the VM starts, whenever a guest wants to connect to a specific 62 // named service, its instance's 'create' method will be called from the 63 // device thread. Alternatively, when resuming from a snapshot, the 'load' 64 // method will be called iff 'canLoad()' is overloaded to return true. 65 // 66 // 4) During pipe operations, onGuestXXX() methods will be called from the 67 // device thread to operate on the pipe. 68 // 69 // 5) The signalWake() and closeFromHost() pipe methods can be called from 70 // any thread to signal i/o events, or ask for the pipe closure. 71 // 72 class AndroidPipe { 73 public: 74 // Call this function in the main loop thread to ensure proper threading 75 // support. |vmLock| must be a valid android::VmLock instance that will be 76 // used to determine whether the current thread holds the global VM 77 // state lock or not (if not, operations are queued). 78 static void initThreading(VmLock* vmLock); 79 80 static void initThreadingForTest(VmLock* lock, base::Looper* looper); 81 82 // A base class for all AndroidPipe services, which is in charge 83 // of creating new instances when a guest client connects to the 84 // service. 85 class Service { 86 public: 87 // Explicit constructor. Service(const char * name)88 explicit Service(const char* name) : mName(name) {} 89 90 // Default destructor. 91 virtual ~Service() = default; 92 93 // Return service name. name()94 const std::string& name() const { return mName; } 95 96 // Create a new pipe instance. This will be called when a guest 97 // client connects to the service identified by its registration 98 // name (see add() below). |hwPipe| is the hardware-side 99 // view of the pipe, and |args| potential arguments. Must 100 // return nullptr on error. 101 virtual AndroidPipe* create(void* hwPipe, const char* args) = 0; 102 103 // Called once per whole vm save/load operation. preLoad(android::base::Stream * stream)104 virtual void preLoad(android::base::Stream* stream) {} postLoad(android::base::Stream * stream)105 virtual void postLoad(android::base::Stream* stream) {} preSave(android::base::Stream * stream)106 virtual void preSave(android::base::Stream* stream) {} postSave(android::base::Stream * stream)107 virtual void postSave(android::base::Stream* stream) {} 108 109 // Called for each pipe, override to save additional information. savePipe(AndroidPipe * pipe,android::base::Stream * stream)110 virtual void savePipe(AndroidPipe* pipe, 111 android::base::Stream* stream) { 112 pipe->onSave(stream); 113 } 114 115 // Returns true if loading pipe instances from a stream is 116 // supported. If true, the load() method will be called to load 117 // every pipe instance state from the stream, if false, the 118 // method will never be loaded, and the guest pipe channels will 119 // be force-closed instead. The default implementation returns 120 // false. canLoad()121 virtual bool canLoad() const { return false; } 122 123 // Load a pipe instance from input |stream|. Only called if 124 // canLoad() returns true. Default implementation returns nullptr 125 // to indicate an error loading the instance. load(void * hwPipe,const char * args,android::base::Stream * stream)126 virtual AndroidPipe* load(void* hwPipe, 127 const char* args, 128 android::base::Stream* stream) { 129 return nullptr; 130 } 131 132 // Register a new |service| instance. After the call, the object 133 // is owned by the global service manager, and will be destroyed 134 // when resetAll() is called. 135 static void add(std::unique_ptr<Service> service); 136 137 // Reset the list of registered services. Useful at the start and 138 // end of a unit-test. 139 static void resetAll(); 140 141 protected: 142 // No default constructor. 143 Service() = delete; 144 145 std::string mName; 146 }; 147 148 // Default destructor. 149 virtual ~AndroidPipe(); 150 151 // Called from the device thread to close the pipe entirely. 152 // The pipe management code will never access the instance after this call, 153 // which means the method is free to delete it before returning. 154 virtual void onGuestClose(PipeCloseReason reason) = 0; 155 156 // Called from the device thread to poll the pipe state. Must return a 157 // combination of PIPE_POLL_IN, PIPE_POLL_OUT and PIPE_POLL_HUP. 158 virtual unsigned onGuestPoll() const = 0; 159 160 // Called from the device thread when the guest wants to receive data 161 // from the pipe. |buffers| points to an array of |numBuffers| descriptors 162 // that specify where to copy the data to. Return the number of bytes that 163 // were actually transferred, 0 for EOF status, or a negative error 164 // value otherwise, including PIPE_ERROR_AGAIN which indicates there 165 // is no data yet to read. 166 virtual int onGuestRecv(AndroidPipeBuffer* buffers, int numBuffers) = 0; 167 168 // Called from the device thread when the guest wants to send data to 169 // the pipe. |buffers| points to an array of |numBuffers| descriptors that 170 // specify where to copy the data from. Return the number of bytes that 171 // were actually transferred, 0 for EOF status, or a negative error 172 // value otherwise, including PIPE_ERROR_AGAIN which indicates the pipe 173 // is not ready to receive any data yet. 174 virtual int onGuestSend(const AndroidPipeBuffer* buffers, 175 int numBuffers, 176 void** newPipePtr) = 0; 177 178 // Called from the device thread when the guest wants to indicate it 179 // wants to be woken up when the set of PIPE_WAKE_XXX event bits in |flags| 180 // will occur. The pipe implementation should call the wake() method to 181 // signal the guest. 182 virtual void onGuestWantWakeOn(int flags) = 0; 183 184 // Called to save the pipe state to a |stream|, i.e. when saving snapshots. 185 // Note that this is never called if the service's canLoad() method returns 186 // false. TODO(digit): Is this always called from the device thread? onSave(android::base::Stream * stream)187 virtual void onSave(android::base::Stream* stream){}; 188 189 // Method used to signal the guest that the events corresponding to the 190 // PIPE_WAKE_XXX bits in |flags| occurred. NOTE: This can be called from 191 // any thread. 192 void signalWake(int flags); 193 194 // Method used to signal the guest that the pipe instance wants to close 195 // the pipe. NOTE: This can be called from any thread. 196 void closeFromHost(); 197 198 // Method for canceling any pending wake() or close() that's scheduled for 199 // this pipe. 200 void abortPendingOperation(); 201 202 // Return the name of the AndroidPipe service. name()203 const char* name() const { 204 return mService ? mService->name().c_str() : "<null>"; 205 } 206 207 // The following functions are implementation details. They are in the 208 // public scope to make the implementation of android_pipe_guest_save() 209 // and android_pipe_guest_load() easier. DO NOT CALL THEM DIRECTLY. 210 211 // Save an AndroidPipe instance state to a file |stream|. 212 void saveToStream(android::base::Stream* stream); 213 214 // Load an AndroidPipe instance from its saved state from |stream|. 215 // |hwPipe| is the hardware-side view of the pipe. On success, return 216 // a new instance pointer and sets |*pForceClose| to 0 or 1. A value 217 // of 1 means that the guest pipe connection should be forcibly closed 218 // because the implementation doesn't allow the state to be saved/loaded 219 // (e.g. network pipes). 220 static AndroidPipe* loadFromStream(android::base::Stream* stream, 221 void* hwPipe, 222 char* pForceClose); 223 224 // A variant of loadFromStream() that is only used to support legacy 225 // snapshot format for pipes. On success, sets |*pChannel|, |*pWakes| and 226 // |*pClosed|, as well as |*pForceClose|. Only used by the QEMU1 virtual 227 // pipe device, and will probably be removed in the future. 228 static AndroidPipe* loadFromStreamLegacy(android::base::Stream* stream, 229 void* hwPipe, 230 uint64_t* pChannel, 231 unsigned char* pWakes, 232 unsigned char* pClosed, 233 char* pForceClose); 234 235 // Flags accessor setFlags(AndroidPipeFlags flags)236 void setFlags(AndroidPipeFlags flags) { mFlags = flags; } getFlags()237 AndroidPipeFlags getFlags() const { return mFlags; } 238 239 protected: 240 // No default constructor. 241 AndroidPipe() = delete; 242 243 // Constructor used by derived classes only. AndroidPipe(void * hwPipe,Service * service)244 AndroidPipe(void* hwPipe, Service* service) 245 : mHwPipe(hwPipe), mService(service) {} 246 247 void* const mHwPipe = nullptr; 248 Service* mService = nullptr; 249 std::string mArgs; 250 AndroidPipeFlags mFlags = ANDROID_PIPE_DEFAULT; 251 }; 252 253 } // namespace android 254