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 "aemu/base/files/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, 102 enum AndroidPipeFlags flags) = 0; 103 104 // Called once per whole vm save/load operation. preLoad(android::base::Stream * stream)105 virtual void preLoad(android::base::Stream* stream) {} postLoad(android::base::Stream * stream)106 virtual void postLoad(android::base::Stream* stream) {} preSave(android::base::Stream * stream)107 virtual void preSave(android::base::Stream* stream) {} postSave(android::base::Stream * stream)108 virtual void postSave(android::base::Stream* stream) {} 109 110 // Called for each pipe, override to save additional information. savePipe(AndroidPipe * pipe,android::base::Stream * stream)111 virtual void savePipe(AndroidPipe* pipe, 112 android::base::Stream* stream) { 113 pipe->onSave(stream); 114 } 115 116 // Returns true if loading pipe instances from a stream is 117 // supported. If true, the load() method will be called to load 118 // every pipe instance state from the stream, if false, the 119 // method will never be loaded, and the guest pipe channels will 120 // be force-closed instead. The default implementation returns 121 // false. canLoad()122 virtual bool canLoad() const { return false; } 123 124 // Load a pipe instance from input |stream|. Only called if 125 // canLoad() returns true. Default implementation returns nullptr 126 // to indicate an error loading the instance. load(void * hwPipe,const char * args,android::base::Stream * stream)127 virtual AndroidPipe* load(void* hwPipe, 128 const char* args, 129 android::base::Stream* stream) { 130 return nullptr; 131 } 132 133 // Register a new |service| instance. After the call, the object 134 // is owned by the global service manager, and will be destroyed 135 // when resetAll() is called. 136 static void add(std::unique_ptr<Service> service); 137 138 // Reset the list of registered services. Useful at the start and 139 // end of a unit-test. 140 static void resetAll(); 141 142 protected: 143 // No default constructor. 144 Service() = delete; 145 146 std::string mName; 147 }; 148 149 // Default destructor. 150 virtual ~AndroidPipe(); 151 152 // Called from the device thread to close the pipe entirely. 153 // The pipe management code will never access the instance after this call, 154 // which means the method is free to delete it before returning. 155 virtual void onGuestClose(PipeCloseReason reason) = 0; 156 157 // Called from the device thread to poll the pipe state. Must return a 158 // combination of PIPE_POLL_IN, PIPE_POLL_OUT and PIPE_POLL_HUP. 159 virtual unsigned onGuestPoll() const = 0; 160 161 // Called from the device thread when the guest wants to receive data 162 // from the pipe. |buffers| points to an array of |numBuffers| descriptors 163 // that specify where to copy the data to. Return the number of bytes that 164 // were actually transferred, 0 for EOF status, or a negative error 165 // value otherwise, including PIPE_ERROR_AGAIN which indicates there 166 // is no data yet to read. 167 virtual int onGuestRecv(AndroidPipeBuffer* buffers, int numBuffers) = 0; 168 169 // A blocking call that waits until guest is able to receive data from the pipe. 170 // This can be used if a previous call to |onGuestRecv| returns PIPE_ERROR_AGAIN. waitGuestRecv()171 virtual void waitGuestRecv() const {}; 172 173 // Called from the device thread when the guest wants to send data to 174 // the pipe. |buffers| points to an array of |numBuffers| descriptors that 175 // specify where to copy the data from. Return the number of bytes that 176 // were actually transferred, 0 for EOF status, or a negative error 177 // value otherwise, including PIPE_ERROR_AGAIN which indicates the pipe 178 // is not ready to receive any data yet. 179 virtual int onGuestSend(const AndroidPipeBuffer* buffers, 180 int numBuffers, 181 void** newPipePtr) = 0; 182 183 // A blocking call that waits until guest is able to send data to the pipe. 184 // This can be used if a previous call to |onGuestSend| returns PIPE_ERROR_AGAIN. waitGuestSend()185 virtual void waitGuestSend() const {} 186 187 // Called from the device thread when the guest wants to indicate it 188 // wants to be woken up when the set of PIPE_WAKE_XXX event bits in |flags| 189 // will occur. The pipe implementation should call the wake() method to 190 // signal the guest. 191 virtual void onGuestWantWakeOn(int flags) = 0; 192 193 // Called to save the pipe state to a |stream|, i.e. when saving snapshots. 194 // Note that this is never called if the service's canLoad() method returns 195 // false. TODO(digit): Is this always called from the device thread? onSave(android::base::Stream * stream)196 virtual void onSave(android::base::Stream* stream){}; 197 198 // Method used to signal the guest that the events corresponding to the 199 // PIPE_WAKE_XXX bits in |flags| occurred. NOTE: This can be called from 200 // any thread. 201 void signalWake(int flags); 202 203 // Method used to signal the guest that the pipe instance wants to close 204 // the pipe. NOTE: This can be called from any thread. 205 void closeFromHost(); 206 207 // Method for canceling any pending wake() or close() that's scheduled for 208 // this pipe. 209 void abortPendingOperation(); 210 211 // Return the name of the AndroidPipe service. name()212 const char* name() const { 213 return mService ? mService->name().c_str() : "<null>"; 214 } 215 216 // The following functions are implementation details. They are in the 217 // public scope to make the implementation of android_pipe_guest_save() 218 // and android_pipe_guest_load() easier. DO NOT CALL THEM DIRECTLY. 219 220 // Save an AndroidPipe instance state to a file |stream|. 221 void saveToStream(android::base::Stream* stream); 222 223 // Load an AndroidPipe instance from its saved state from |stream|. 224 // |hwPipe| is the hardware-side view of the pipe. On success, return 225 // a new instance pointer and sets |*pForceClose| to 0 or 1. A value 226 // of 1 means that the guest pipe connection should be forcibly closed 227 // because the implementation doesn't allow the state to be saved/loaded 228 // (e.g. network pipes). 229 static AndroidPipe* loadFromStream(android::base::Stream* stream, 230 void* hwPipe, 231 char* pForceClose); 232 233 // A variant of loadFromStream() that is only used to support legacy 234 // snapshot format for pipes. On success, sets |*pChannel|, |*pWakes| and 235 // |*pClosed|, as well as |*pForceClose|. Only used by the QEMU1 virtual 236 // pipe device, and will probably be removed in the future. 237 static AndroidPipe* loadFromStreamLegacy(android::base::Stream* stream, 238 void* hwPipe, 239 uint64_t* pChannel, 240 unsigned char* pWakes, 241 unsigned char* pClosed, 242 char* pForceClose); 243 244 // Flags accessor setFlags(AndroidPipeFlags flags)245 void setFlags(AndroidPipeFlags flags) { mFlags = flags; } getFlags()246 AndroidPipeFlags getFlags() const { return mFlags; } 247 248 protected: 249 // No default constructor. 250 AndroidPipe() = delete; 251 252 // Constructor used by derived classes only. AndroidPipe(void * hwPipe,Service * service)253 AndroidPipe(void* hwPipe, Service* service) 254 : mHwPipe(hwPipe), mService(service) {} 255 256 void* const mHwPipe = nullptr; 257 Service* mService = nullptr; 258 std::string mArgs; 259 AndroidPipeFlags mFlags = ANDROID_PIPE_DEFAULT; 260 }; 261 262 } // namespace android 263