MtpFfsCompatHandle.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*
  2. * Copyright (C) 2017 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. #include <android-base/logging.h>
  17. #include <android-base/properties.h>
  18. #include <dirent.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <linux/usb/ch9.h>
  22. #include <linux/usb/functionfs.h>
  23. #include <mutex>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/endian.h>
  28. #include <sys/ioctl.h>
  29. #include <sys/mman.h>
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #include <unistd.h>
  33. #include "PosixAsyncIO.h"
  34. #include "MtpFfsCompatHandle.h"
  35. #include "mtp.h"
  36. #define FUNCTIONFS_ENDPOINT_ALLOC _IOR('g', 231, __u32)
  37. namespace {
  38. // Must be divisible by all max packet size values
  39. constexpr int MAX_FILE_CHUNK_SIZE = 3145728;
  40. // Safe values since some devices cannot handle large DMAs
  41. // To get good performance, override these with
  42. // higher values per device using the properties
  43. // sys.usb.ffs.max_read and sys.usb.ffs.max_write
  44. constexpr int USB_FFS_MAX_WRITE = MTP_BUFFER_SIZE;
  45. constexpr int USB_FFS_MAX_READ = MTP_BUFFER_SIZE;
  46. static_assert(USB_FFS_MAX_WRITE > 0, "Max r/w values must be > 0!");
  47. static_assert(USB_FFS_MAX_READ > 0, "Max r/w values must be > 0!");
  48. constexpr unsigned int MAX_MTP_FILE_SIZE = 0xFFFFFFFF;
  49. constexpr size_t ENDPOINT_ALLOC_RETRIES = 10;
  50. } // anonymous namespace
  51. namespace android {
  52. MtpFfsCompatHandle::MtpFfsCompatHandle(int controlFd) :
  53. MtpFfsHandle(controlFd),
  54. mMaxWrite(USB_FFS_MAX_WRITE),
  55. mMaxRead(USB_FFS_MAX_READ) {}
  56. MtpFfsCompatHandle::~MtpFfsCompatHandle() {}
  57. int MtpFfsCompatHandle::writeHandle(int fd, const void* data, size_t len) {
  58. int ret = 0;
  59. const char* buf = static_cast<const char*>(data);
  60. while (len > 0) {
  61. int write_len = std::min(mMaxWrite, len);
  62. int n = TEMP_FAILURE_RETRY(::write(fd, buf, write_len));
  63. if (n < 0) {
  64. PLOG(ERROR) << "write ERROR: fd = " << fd << ", n = " << n;
  65. return -1;
  66. } else if (n < write_len) {
  67. errno = EIO;
  68. PLOG(ERROR) << "less written than expected";
  69. return -1;
  70. }
  71. buf += n;
  72. len -= n;
  73. ret += n;
  74. }
  75. return ret;
  76. }
  77. int MtpFfsCompatHandle::readHandle(int fd, void* data, size_t len) {
  78. int ret = 0;
  79. char* buf = static_cast<char*>(data);
  80. while (len > 0) {
  81. int read_len = std::min(mMaxRead, len);
  82. int n = TEMP_FAILURE_RETRY(::read(fd, buf, read_len));
  83. if (n < 0) {
  84. PLOG(ERROR) << "read ERROR: fd = " << fd << ", n = " << n;
  85. return -1;
  86. }
  87. ret += n;
  88. if (n < read_len) // done reading early
  89. break;
  90. buf += n;
  91. len -= n;
  92. }
  93. return ret;
  94. }
  95. int MtpFfsCompatHandle::start(bool ptp) {
  96. if (!openEndpoints(ptp))
  97. return -1;
  98. for (unsigned i = 0; i < NUM_IO_BUFS; i++) {
  99. mIobuf[i].bufs.resize(MAX_FILE_CHUNK_SIZE);
  100. posix_madvise(mIobuf[i].bufs.data(), MAX_FILE_CHUNK_SIZE,
  101. POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED);
  102. }
  103. // Get device specific r/w size
  104. mMaxWrite = android::base::GetIntProperty("sys.usb.ffs.max_write", USB_FFS_MAX_WRITE);
  105. mMaxRead = android::base::GetIntProperty("sys.usb.ffs.max_read", USB_FFS_MAX_READ);
  106. size_t attempts = 0;
  107. while (mMaxWrite >= USB_FFS_MAX_WRITE && mMaxRead >= USB_FFS_MAX_READ &&
  108. attempts < ENDPOINT_ALLOC_RETRIES) {
  109. // If larger contiguous chunks of memory aren't available, attempt to try
  110. // smaller allocations.
  111. if (ioctl(mBulkIn, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(mMaxWrite)) ||
  112. ioctl(mBulkOut, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(mMaxRead))) {
  113. if (errno == ENODEV) {
  114. // Driver hasn't enabled endpoints yet.
  115. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  116. attempts += 1;
  117. continue;
  118. }
  119. mMaxWrite /= 2;
  120. mMaxRead /=2;
  121. } else {
  122. return 0;
  123. }
  124. }
  125. // Try to start MtpServer anyway, with the smallest max r/w values
  126. mMaxWrite = USB_FFS_MAX_WRITE;
  127. mMaxRead = USB_FFS_MAX_READ;
  128. PLOG(ERROR) << "Functionfs could not allocate any memory!";
  129. return 0;
  130. }
  131. int MtpFfsCompatHandle::read(void* data, size_t len) {
  132. return readHandle(mBulkOut, data, len);
  133. }
  134. int MtpFfsCompatHandle::write(const void* data, size_t len) {
  135. return writeHandle(mBulkIn, data, len);
  136. }
  137. int MtpFfsCompatHandle::receiveFile(mtp_file_range mfr, bool zero_packet) {
  138. // When receiving files, the incoming length is given in 32 bits.
  139. // A >4G file is given as 0xFFFFFFFF
  140. uint32_t file_length = mfr.length;
  141. uint64_t offset = mfr.offset;
  142. int packet_size = getPacketSize(mBulkOut);
  143. unsigned char *data = mIobuf[0].bufs.data();
  144. unsigned char *data2 = mIobuf[1].bufs.data();
  145. struct aiocb aio;
  146. aio.aio_fildes = mfr.fd;
  147. aio.aio_buf = nullptr;
  148. struct aiocb *aiol[] = {&aio};
  149. int ret = -1;
  150. size_t length;
  151. bool read = false;
  152. bool write = false;
  153. posix_fadvise(mfr.fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
  154. // Break down the file into pieces that fit in buffers
  155. while (file_length > 0 || write) {
  156. if (file_length > 0) {
  157. length = std::min(static_cast<uint32_t>(MAX_FILE_CHUNK_SIZE), file_length);
  158. // Read data from USB, handle errors after waiting for write thread.
  159. ret = readHandle(mBulkOut, data, length);
  160. if (file_length != MAX_MTP_FILE_SIZE && ret < static_cast<int>(length)) {
  161. ret = -1;
  162. errno = EIO;
  163. }
  164. read = true;
  165. }
  166. if (write) {
  167. // get the return status of the last write request
  168. aio_suspend(aiol, 1, nullptr);
  169. int written = aio_return(&aio);
  170. if (written == -1) {
  171. errno = aio_error(&aio);
  172. return -1;
  173. }
  174. if (static_cast<size_t>(written) < aio.aio_nbytes) {
  175. errno = EIO;
  176. return -1;
  177. }
  178. write = false;
  179. }
  180. // If there was an error reading above
  181. if (ret == -1) {
  182. return -1;
  183. }
  184. if (read) {
  185. if (file_length == MAX_MTP_FILE_SIZE) {
  186. // For larger files, receive until a short packet is received.
  187. if (static_cast<size_t>(ret) < length) {
  188. file_length = 0;
  189. }
  190. } else {
  191. file_length -= ret;
  192. }
  193. // Enqueue a new write request
  194. aio_prepare(&aio, data, length, offset);
  195. aio_write(&aio);
  196. offset += ret;
  197. std::swap(data, data2);
  198. write = true;
  199. read = false;
  200. }
  201. }
  202. // Receive an empty packet if size is a multiple of the endpoint size.
  203. if (ret % packet_size == 0 || zero_packet) {
  204. if (TEMP_FAILURE_RETRY(::read(mBulkOut, data, packet_size)) != 0) {
  205. return -1;
  206. }
  207. }
  208. return 0;
  209. }
  210. int MtpFfsCompatHandle::sendFile(mtp_file_range mfr) {
  211. uint64_t file_length = mfr.length;
  212. uint32_t given_length = std::min(static_cast<uint64_t>(MAX_MTP_FILE_SIZE),
  213. file_length + sizeof(mtp_data_header));
  214. uint64_t offset = mfr.offset;
  215. int packet_size = getPacketSize(mBulkIn);
  216. // If file_length is larger than a size_t, truncating would produce the wrong comparison.
  217. // Instead, promote the left side to 64 bits, then truncate the small result.
  218. int init_read_len = std::min(
  219. static_cast<uint64_t>(packet_size - sizeof(mtp_data_header)), file_length);
  220. unsigned char *data = mIobuf[0].bufs.data();
  221. unsigned char *data2 = mIobuf[1].bufs.data();
  222. posix_fadvise(mfr.fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
  223. struct aiocb aio;
  224. aio.aio_fildes = mfr.fd;
  225. struct aiocb *aiol[] = {&aio};
  226. int ret, length;
  227. int error = 0;
  228. bool read = false;
  229. bool write = false;
  230. // Send the header data
  231. mtp_data_header *header = reinterpret_cast<mtp_data_header*>(data);
  232. header->length = htole32(given_length);
  233. header->type = htole16(2); /* data packet */
  234. header->command = htole16(mfr.command);
  235. header->transaction_id = htole32(mfr.transaction_id);
  236. // Some hosts don't support header/data separation even though MTP allows it
  237. // Handle by filling first packet with initial file data
  238. if (TEMP_FAILURE_RETRY(pread(mfr.fd, reinterpret_cast<char*>(data) +
  239. sizeof(mtp_data_header), init_read_len, offset))
  240. != init_read_len) return -1;
  241. if (writeHandle(mBulkIn, data, sizeof(mtp_data_header) + init_read_len) == -1) return -1;
  242. file_length -= init_read_len;
  243. offset += init_read_len;
  244. ret = init_read_len + sizeof(mtp_data_header);
  245. // Break down the file into pieces that fit in buffers
  246. while (file_length > 0) {
  247. if (read) {
  248. // Wait for the previous read to finish
  249. aio_suspend(aiol, 1, nullptr);
  250. ret = aio_return(&aio);
  251. if (ret == -1) {
  252. errno = aio_error(&aio);
  253. return -1;
  254. }
  255. if (static_cast<size_t>(ret) < aio.aio_nbytes) {
  256. errno = EIO;
  257. return -1;
  258. }
  259. file_length -= ret;
  260. offset += ret;
  261. std::swap(data, data2);
  262. read = false;
  263. write = true;
  264. }
  265. if (error == -1) {
  266. return -1;
  267. }
  268. if (file_length > 0) {
  269. length = std::min(static_cast<uint64_t>(MAX_FILE_CHUNK_SIZE), file_length);
  270. // Queue up another read
  271. aio_prepare(&aio, data, length, offset);
  272. aio_read(&aio);
  273. read = true;
  274. }
  275. if (write) {
  276. if (writeHandle(mBulkIn, data2, ret) == -1) {
  277. error = -1;
  278. }
  279. write = false;
  280. }
  281. }
  282. if (ret % packet_size == 0) {
  283. // If the last packet wasn't short, send a final empty packet
  284. if (TEMP_FAILURE_RETRY(::write(mBulkIn, data, 0)) != 0) {
  285. return -1;
  286. }
  287. }
  288. return 0;
  289. }
  290. } // namespace android