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