1 /* 2 * Copyright (C) 2025 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 "sysdeps.h" 20 #include "types.h" 21 22 #include "usb_libusb_device.h" 23 24 struct LibUsbConnection : Connection { 25 explicit LibUsbConnection(std::unique_ptr<LibUsbDevice> device); 26 ~LibUsbConnection() override; 27 28 void Init(); 29 30 bool Write(std::unique_ptr<apacket> packet) override; 31 32 // Start transmitting. Start the write thread to consume from the 33 // write queue, Start the read thread to retrieve packets and send 34 // them to the transport layer. 35 bool Start() override; 36 37 // Stop both read and write threads. 38 void Stop() override; 39 40 // Not supported 41 bool DoTlsHandshake(RSA* key, std::string* auth_key) override; 42 43 // Reset the device. This will cause transmission to stop. 44 void Reset() override; 45 46 uint64_t NegotiatedSpeedMbps() override; 47 uint64_t MaxSpeedMbps() override; 48 49 bool SupportsDetach() const override; 50 51 // Stop transmitting and release transmission resources but don't report 52 // an error to the transport layer. Detaching allows another ADB server 53 // running on the same host to take over a device. 54 bool Attach(std::string* error) override; 55 56 // Opposite of Attach, re-acquire transmission resources and start 57 // transmitting. 58 bool Detach(std::string* error) override; 59 60 bool IsDetached(); 61 62 // Report an error condition to the upper layer. This will result 63 // in transport calling Stop() and this connection be destroyed 64 // on the fdevent thread. 65 void OnError(const std::string& error); 66 67 uint64_t GetSessionId() const; 68 69 private: 70 std::atomic<bool> detached_ = false; 71 72 void HandleStop(const std::string& reason); 73 74 void StartReadThread() REQUIRES(mutex_); 75 void StartWriteThread() REQUIRES(mutex_); 76 bool running_ GUARDED_BY(mutex_) = false; 77 78 std::unique_ptr<LibUsbDevice> device_; 79 std::thread read_thread_ GUARDED_BY(mutex_); 80 std::thread write_thread_ GUARDED_BY(mutex_); 81 82 // To improve throughput, we store apacket in a queue upon Write. This 83 // queue is consumed by the write thread. 84 std::deque<std::unique_ptr<apacket>> write_queue_ GUARDED_BY(mutex_); 85 std::mutex mutex_; 86 87 // Unlock the Write thread when we need to stop or when there are packets 88 // to Write. 89 std::condition_variable cv_write_; 90 91 std::once_flag error_flag_; 92 };