blob: 3dd73f3dd211adff7a0289ffe05abdfcdb662f60 [file] [log] [blame]
Jerry Zhangdf69dd32017-05-03 17:17:49 -07001/*
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
62namespace android {
63
64MtpFfsCompatHandle::MtpFfsCompatHandle() :
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() {
112 mLock.lock();
113
114 if (!openEndpoints())
115 return -1;
116
117 for (unsigned i = 0; i < NUM_IO_BUFS; i++) {
118 mIobuf[i].bufs.resize(MAX_FILE_CHUNK_SIZE);
119 posix_madvise(mIobuf[i].bufs.data(), MAX_FILE_CHUNK_SIZE,
120 POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED);
121 }
122
123 // Get device specific r/w size
124 mMaxWrite = android::base::GetIntProperty("sys.usb.ffs.max_write", USB_FFS_MAX_WRITE);
125 mMaxRead = android::base::GetIntProperty("sys.usb.ffs.max_read", USB_FFS_MAX_READ);
126
127 size_t attempts = 0;
128 while (mMaxWrite >= USB_FFS_MAX_WRITE && mMaxRead >= USB_FFS_MAX_READ &&
129 attempts < ENDPOINT_ALLOC_RETRIES) {
130 // If larger contiguous chunks of memory aren't available, attempt to try
131 // smaller allocations.
132 if (ioctl(mBulkIn, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(mMaxWrite)) ||
133 ioctl(mBulkOut, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(mMaxRead))) {
134 if (errno == ENODEV) {
135 // Driver hasn't enabled endpoints yet.
136 std::this_thread::sleep_for(std::chrono::milliseconds(100));
137 attempts += 1;
138 continue;
139 }
140 mMaxWrite /= 2;
141 mMaxRead /=2;
142 } else {
143 return 0;
144 }
145 }
146 // Try to start MtpServer anyway, with the smallest max r/w values
147 mMaxWrite = USB_FFS_MAX_WRITE;
148 mMaxRead = USB_FFS_MAX_READ;
149 PLOG(ERROR) << "Functionfs could not allocate any memory!";
150 return 0;
151}
152
153int MtpFfsCompatHandle::read(void* data, size_t len) {
154 return readHandle(mBulkOut, data, len);
155}
156
157int MtpFfsCompatHandle::write(const void* data, size_t len) {
158 return writeHandle(mBulkIn, data, len);
159}
160
161int MtpFfsCompatHandle::receiveFile(mtp_file_range mfr, bool zero_packet) {
162 // When receiving files, the incoming length is given in 32 bits.
163 // A >4G file is given as 0xFFFFFFFF
164 uint32_t file_length = mfr.length;
165 uint64_t offset = mfr.offset;
166 int packet_size = getPacketSize(mBulkOut);
167
168 unsigned char *data = mIobuf[0].bufs.data();
169 unsigned char *data2 = mIobuf[1].bufs.data();
170
171 struct aiocb aio;
172 aio.aio_fildes = mfr.fd;
173 aio.aio_buf = nullptr;
174 struct aiocb *aiol[] = {&aio};
175 int ret = -1;
176 size_t length;
177 bool read = false;
178 bool write = false;
179
180 posix_fadvise(mfr.fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
181
182 // Break down the file into pieces that fit in buffers
183 while (file_length > 0 || write) {
184 if (file_length > 0) {
185 length = std::min(static_cast<uint32_t>(MAX_FILE_CHUNK_SIZE), file_length);
186
187 // Read data from USB, handle errors after waiting for write thread.
188 ret = readHandle(mBulkOut, data, length);
189
190 if (file_length != MAX_MTP_FILE_SIZE && ret < static_cast<int>(length)) {
191 ret = -1;
192 errno = EIO;
193 }
194 read = true;
195 }
196
197 if (write) {
198 // get the return status of the last write request
199 aio_suspend(aiol, 1, nullptr);
200
201 int written = aio_return(&aio);
202 if (written == -1) {
203 errno = aio_error(&aio);
204 return -1;
205 }
206 if (static_cast<size_t>(written) < aio.aio_nbytes) {
207 errno = EIO;
208 return -1;
209 }
210 write = false;
211 }
212
213 // If there was an error reading above
214 if (ret == -1) {
215 return -1;
216 }
217
218 if (read) {
219 if (file_length == MAX_MTP_FILE_SIZE) {
220 // For larger files, receive until a short packet is received.
221 if (static_cast<size_t>(ret) < length) {
222 file_length = 0;
223 }
224 } else {
225 file_length -= ret;
226 }
227 // Enqueue a new write request
228 aio_prepare(&aio, data, length, offset);
229 aio_write(&aio);
230
231 offset += ret;
232 std::swap(data, data2);
233
234 write = true;
235 read = false;
236 }
237 }
238 // Receive an empty packet if size is a multiple of the endpoint size.
239 if (ret % packet_size == 0 || zero_packet) {
240 if (TEMP_FAILURE_RETRY(::read(mBulkOut, data, packet_size)) != 0) {
241 return -1;
242 }
243 }
244 return 0;
245}
246
247int MtpFfsCompatHandle::sendFile(mtp_file_range mfr) {
248 uint64_t file_length = mfr.length;
249 uint32_t given_length = std::min(static_cast<uint64_t>(MAX_MTP_FILE_SIZE),
250 file_length + sizeof(mtp_data_header));
251 uint64_t offset = mfr.offset;
252 int packet_size = getPacketSize(mBulkIn);
253
254 // If file_length is larger than a size_t, truncating would produce the wrong comparison.
255 // Instead, promote the left side to 64 bits, then truncate the small result.
256 int init_read_len = std::min(
257 static_cast<uint64_t>(packet_size - sizeof(mtp_data_header)), file_length);
258
259 unsigned char *data = mIobuf[0].bufs.data();
260 unsigned char *data2 = mIobuf[1].bufs.data();
261
262 posix_fadvise(mfr.fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
263
264 struct aiocb aio;
265 aio.aio_fildes = mfr.fd;
266 struct aiocb *aiol[] = {&aio};
267 int ret, length;
268 int error = 0;
269 bool read = false;
270 bool write = false;
271
272 // Send the header data
273 mtp_data_header *header = reinterpret_cast<mtp_data_header*>(data);
274 header->length = htole32(given_length);
275 header->type = htole16(2); /* data packet */
276 header->command = htole16(mfr.command);
277 header->transaction_id = htole32(mfr.transaction_id);
278
279 // Some hosts don't support header/data separation even though MTP allows it
280 // Handle by filling first packet with initial file data
281 if (TEMP_FAILURE_RETRY(pread(mfr.fd, reinterpret_cast<char*>(data) +
282 sizeof(mtp_data_header), init_read_len, offset))
283 != init_read_len) return -1;
284 if (writeHandle(mBulkIn, data, sizeof(mtp_data_header) + init_read_len) == -1) return -1;
285 file_length -= init_read_len;
286 offset += init_read_len;
287 ret = init_read_len + sizeof(mtp_data_header);
288
289 // Break down the file into pieces that fit in buffers
290 while (file_length > 0) {
291 if (read) {
292 // Wait for the previous read to finish
293 aio_suspend(aiol, 1, nullptr);
294 ret = aio_return(&aio);
295 if (ret == -1) {
296 errno = aio_error(&aio);
297 return -1;
298 }
299 if (static_cast<size_t>(ret) < aio.aio_nbytes) {
300 errno = EIO;
301 return -1;
302 }
303
304 file_length -= ret;
305 offset += ret;
306 std::swap(data, data2);
307 read = false;
308 write = true;
309 }
310
311 if (error == -1) {
312 return -1;
313 }
314
315 if (file_length > 0) {
316 length = std::min(static_cast<uint64_t>(MAX_FILE_CHUNK_SIZE), file_length);
317 // Queue up another read
318 aio_prepare(&aio, data, length, offset);
319 aio_read(&aio);
320 read = true;
321 }
322
323 if (write) {
324 if (writeHandle(mBulkIn, data2, ret) == -1) {
325 error = -1;
326 }
327 write = false;
328 }
329 }
330
331 if (ret % packet_size == 0) {
332 // If the last packet wasn't short, send a final empty packet
333 if (TEMP_FAILURE_RETRY(::write(mBulkIn, data, 0)) != 0) {
334 return -1;
335 }
336 }
337
338 return 0;
339}
340
341} // namespace android
342