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, 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 // Called from the device thread when the guest wants to send data to 170 // the pipe. |buffers| points to an array of |numBuffers| descriptors that 171 // specify where to copy the data from. Return the number of bytes that 172 // were actually transferred, 0 for EOF status, or a negative error 173 // value otherwise, including PIPE_ERROR_AGAIN which indicates the pipe 174 // is not ready to receive any data yet. 175 virtual int onGuestSend(const AndroidPipeBuffer* buffers, 176 int numBuffers, 177 void** newPipePtr) = 0; 178 179 // Called from the device thread when the guest wants to indicate it 180 // wants to be woken up when the set of PIPE_WAKE_XXX event bits in |flags| 181 // will occur. The pipe implementation should call the wake() method to 182 // signal the guest. 183 virtual void onGuestWantWakeOn(int flags) = 0; 184 185 // Called to save the pipe state to a |stream|, i.e. when saving snapshots. 186 // Note that this is never called if the service's canLoad() method returns 187 // false. TODO(digit): Is this always called from the device thread? onSave(android::base::Stream * stream)188 virtual void onSave(android::base::Stream* stream){}; 189 190 // Method used to signal the guest that the events corresponding to the 191 // PIPE_WAKE_XXX bits in |flags| occurred. NOTE: This can be called from 192 // any thread. 193 void signalWake(int flags); 194 195 // Method used to signal the guest that the pipe instance wants to close 196 // the pipe. NOTE: This can be called from any thread. 197 void closeFromHost(); 198 199 // Method for canceling any pending wake() or close() that's scheduled for 200 // this pipe. 201 void abortPendingOperation(); 202 203 // Return the name of the AndroidPipe service. name()204 const char* name() const { 205 return mService ? mService->name().c_str() : "<null>"; 206 } 207 208 // The following functions are implementation details. They are in the 209 // public scope to make the implementation of android_pipe_guest_save() 210 // and android_pipe_guest_load() easier. DO NOT CALL THEM DIRECTLY. 211 212 // Save an AndroidPipe instance state to a file |stream|. 213 void saveToStream(android::base::Stream* stream); 214 215 // Load an AndroidPipe instance from its saved state from |stream|. 216 // |hwPipe| is the hardware-side view of the pipe. On success, return 217 // a new instance pointer and sets |*pForceClose| to 0 or 1. A value 218 // of 1 means that the guest pipe connection should be forcibly closed 219 // because the implementation doesn't allow the state to be saved/loaded 220 // (e.g. network pipes). 221 static AndroidPipe* loadFromStream(android::base::Stream* stream, 222 void* hwPipe, 223 char* pForceClose); 224 225 // A variant of loadFromStream() that is only used to support legacy 226 // snapshot format for pipes. On success, sets |*pChannel|, |*pWakes| and 227 // |*pClosed|, as well as |*pForceClose|. Only used by the QEMU1 virtual 228 // pipe device, and will probably be removed in the future. 229 static AndroidPipe* loadFromStreamLegacy(android::base::Stream* stream, 230 void* hwPipe, 231 uint64_t* pChannel, 232 unsigned char* pWakes, 233 unsigned char* pClosed, 234 char* pForceClose); 235 236 // Flags accessor setFlags(AndroidPipeFlags flags)237 void setFlags(AndroidPipeFlags flags) { mFlags = flags; } getFlags()238 AndroidPipeFlags getFlags() const { return mFlags; } 239 240 protected: 241 // No default constructor. 242 AndroidPipe() = delete; 243 244 // Constructor used by derived classes only. AndroidPipe(void * hwPipe,Service * service)245 AndroidPipe(void* hwPipe, Service* service) 246 : mHwPipe(hwPipe), mService(service) {} 247 248 void* const mHwPipe = nullptr; 249 Service* mService = nullptr; 250 std::string mArgs; 251 AndroidPipeFlags mFlags = ANDROID_PIPE_DEFAULT; 252 }; 253 254 } // namespace android 255