blob: 5d747c2810637cff68d8e284dc2c34a1bf11dfc0 [file] [log] [blame]
Jerry Zhang487be612016-10-24 12:10:41 -07001/*
2 * Copyright (C) 2016 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>
Jerry Zhange9d94422017-01-18 12:03:56 -080030#include <sys/mman.h>
Jerry Zhang487be612016-10-24 12:10:41 -070031#include <sys/stat.h>
32#include <sys/types.h>
33#include <unistd.h>
34#include <vector>
35
36#include "AsyncIO.h"
37#include "MtpFfsHandle.h"
Jerry Zhangcc9d0fd2017-01-27 10:29:59 -080038#include "mtp.h"
Jerry Zhang487be612016-10-24 12:10:41 -070039
40#define cpu_to_le16(x) htole16(x)
41#define cpu_to_le32(x) htole32(x)
42
Jerry Zhang5a804b92016-12-15 17:07:38 -080043#define FUNCTIONFS_ENDPOINT_ALLOC _IOR('g', 131, __u32)
44
Jerry Zhang487be612016-10-24 12:10:41 -070045namespace {
46
47constexpr char FFS_MTP_EP_IN[] = "/dev/usb-ffs/mtp/ep1";
48constexpr char FFS_MTP_EP_OUT[] = "/dev/usb-ffs/mtp/ep2";
49constexpr char FFS_MTP_EP_INTR[] = "/dev/usb-ffs/mtp/ep3";
50
51constexpr int MAX_PACKET_SIZE_FS = 64;
52constexpr int MAX_PACKET_SIZE_HS = 512;
53constexpr int MAX_PACKET_SIZE_SS = 1024;
54
55// Must be divisible by all max packet size values
56constexpr int MAX_FILE_CHUNK_SIZE = 3145728;
57
58// Safe values since some devices cannot handle large DMAs
59// To get good performance, override these with
60// higher values per device using the properties
61// sys.usb.ffs.max_read and sys.usb.ffs.max_write
Jerry Zhangcc9d0fd2017-01-27 10:29:59 -080062constexpr int USB_FFS_MAX_WRITE = MTP_BUFFER_SIZE;
63constexpr int USB_FFS_MAX_READ = MTP_BUFFER_SIZE;
Jerry Zhang487be612016-10-24 12:10:41 -070064
65constexpr unsigned int MAX_MTP_FILE_SIZE = 0xFFFFFFFF;
66
67struct func_desc {
68 struct usb_interface_descriptor intf;
69 struct usb_endpoint_descriptor_no_audio sink;
70 struct usb_endpoint_descriptor_no_audio source;
71 struct usb_endpoint_descriptor_no_audio intr;
72} __attribute__((packed));
73
74struct ss_func_desc {
75 struct usb_interface_descriptor intf;
76 struct usb_endpoint_descriptor_no_audio sink;
77 struct usb_ss_ep_comp_descriptor sink_comp;
78 struct usb_endpoint_descriptor_no_audio source;
79 struct usb_ss_ep_comp_descriptor source_comp;
80 struct usb_endpoint_descriptor_no_audio intr;
81 struct usb_ss_ep_comp_descriptor intr_comp;
82} __attribute__((packed));
83
84struct desc_v1 {
85 struct usb_functionfs_descs_head_v1 {
86 __le32 magic;
87 __le32 length;
88 __le32 fs_count;
89 __le32 hs_count;
90 } __attribute__((packed)) header;
91 struct func_desc fs_descs, hs_descs;
92} __attribute__((packed));
93
94struct desc_v2 {
95 struct usb_functionfs_descs_head_v2 header;
96 // The rest of the structure depends on the flags in the header.
97 __le32 fs_count;
98 __le32 hs_count;
99 __le32 ss_count;
100 struct func_desc fs_descs, hs_descs;
101 struct ss_func_desc ss_descs;
102} __attribute__((packed));
103
104const struct usb_interface_descriptor mtp_interface_desc = {
105 .bLength = USB_DT_INTERFACE_SIZE,
106 .bDescriptorType = USB_DT_INTERFACE,
107 .bInterfaceNumber = 0,
108 .bNumEndpoints = 3,
109 .bInterfaceClass = USB_CLASS_STILL_IMAGE,
110 .bInterfaceSubClass = 1,
111 .bInterfaceProtocol = 1,
Jerry Zhang6a790522017-01-11 15:17:53 -0800112 .iInterface = 1,
Jerry Zhang487be612016-10-24 12:10:41 -0700113};
114
115const struct usb_interface_descriptor ptp_interface_desc = {
116 .bLength = USB_DT_INTERFACE_SIZE,
117 .bDescriptorType = USB_DT_INTERFACE,
118 .bInterfaceNumber = 0,
119 .bNumEndpoints = 3,
120 .bInterfaceClass = USB_CLASS_STILL_IMAGE,
121 .bInterfaceSubClass = 1,
122 .bInterfaceProtocol = 1,
123};
124
125const struct usb_endpoint_descriptor_no_audio fs_sink = {
126 .bLength = USB_DT_ENDPOINT_SIZE,
127 .bDescriptorType = USB_DT_ENDPOINT,
128 .bEndpointAddress = 1 | USB_DIR_IN,
129 .bmAttributes = USB_ENDPOINT_XFER_BULK,
130 .wMaxPacketSize = MAX_PACKET_SIZE_FS,
131};
132
133const struct usb_endpoint_descriptor_no_audio fs_source = {
134 .bLength = USB_DT_ENDPOINT_SIZE,
135 .bDescriptorType = USB_DT_ENDPOINT,
136 .bEndpointAddress = 2 | USB_DIR_OUT,
137 .bmAttributes = USB_ENDPOINT_XFER_BULK,
138 .wMaxPacketSize = MAX_PACKET_SIZE_FS,
139};
140
141const struct usb_endpoint_descriptor_no_audio fs_intr = {
142 .bLength = USB_DT_ENDPOINT_SIZE,
143 .bDescriptorType = USB_DT_ENDPOINT,
144 .bEndpointAddress = 3 | USB_DIR_IN,
145 .bmAttributes = USB_ENDPOINT_XFER_INT,
146 .wMaxPacketSize = MAX_PACKET_SIZE_FS,
147 .bInterval = 6,
148};
149
150const struct usb_endpoint_descriptor_no_audio hs_sink = {
151 .bLength = USB_DT_ENDPOINT_SIZE,
152 .bDescriptorType = USB_DT_ENDPOINT,
153 .bEndpointAddress = 1 | USB_DIR_IN,
154 .bmAttributes = USB_ENDPOINT_XFER_BULK,
155 .wMaxPacketSize = MAX_PACKET_SIZE_HS,
156};
157
158const struct usb_endpoint_descriptor_no_audio hs_source = {
159 .bLength = USB_DT_ENDPOINT_SIZE,
160 .bDescriptorType = USB_DT_ENDPOINT,
161 .bEndpointAddress = 2 | USB_DIR_OUT,
162 .bmAttributes = USB_ENDPOINT_XFER_BULK,
163 .wMaxPacketSize = MAX_PACKET_SIZE_HS,
164};
165
166const struct usb_endpoint_descriptor_no_audio hs_intr = {
167 .bLength = USB_DT_ENDPOINT_SIZE,
168 .bDescriptorType = USB_DT_ENDPOINT,
169 .bEndpointAddress = 3 | USB_DIR_IN,
170 .bmAttributes = USB_ENDPOINT_XFER_INT,
171 .wMaxPacketSize = MAX_PACKET_SIZE_HS,
172 .bInterval = 6,
173};
174
175const struct usb_endpoint_descriptor_no_audio ss_sink = {
176 .bLength = USB_DT_ENDPOINT_SIZE,
177 .bDescriptorType = USB_DT_ENDPOINT,
178 .bEndpointAddress = 1 | USB_DIR_IN,
179 .bmAttributes = USB_ENDPOINT_XFER_BULK,
180 .wMaxPacketSize = MAX_PACKET_SIZE_SS,
181};
182
183const struct usb_endpoint_descriptor_no_audio ss_source = {
184 .bLength = USB_DT_ENDPOINT_SIZE,
185 .bDescriptorType = USB_DT_ENDPOINT,
186 .bEndpointAddress = 2 | USB_DIR_OUT,
187 .bmAttributes = USB_ENDPOINT_XFER_BULK,
188 .wMaxPacketSize = MAX_PACKET_SIZE_SS,
189};
190
191const struct usb_endpoint_descriptor_no_audio ss_intr = {
192 .bLength = USB_DT_ENDPOINT_SIZE,
193 .bDescriptorType = USB_DT_ENDPOINT,
194 .bEndpointAddress = 3 | USB_DIR_IN,
195 .bmAttributes = USB_ENDPOINT_XFER_INT,
196 .wMaxPacketSize = MAX_PACKET_SIZE_SS,
197 .bInterval = 6,
198};
199
200const struct usb_ss_ep_comp_descriptor ss_sink_comp = {
201 .bLength = sizeof(ss_sink_comp),
202 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
203 .bMaxBurst = 2,
204};
205
206const struct usb_ss_ep_comp_descriptor ss_source_comp = {
207 .bLength = sizeof(ss_source_comp),
208 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
209 .bMaxBurst = 2,
210};
211
212const struct usb_ss_ep_comp_descriptor ss_intr_comp = {
213 .bLength = sizeof(ss_intr_comp),
214 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
215};
216
217const struct func_desc mtp_fs_descriptors = {
218 .intf = mtp_interface_desc,
219 .sink = fs_sink,
220 .source = fs_source,
221 .intr = fs_intr,
222};
223
224const struct func_desc mtp_hs_descriptors = {
225 .intf = mtp_interface_desc,
226 .sink = hs_sink,
227 .source = hs_source,
228 .intr = hs_intr,
229};
230
231const struct ss_func_desc mtp_ss_descriptors = {
232 .intf = mtp_interface_desc,
233 .sink = ss_sink,
234 .sink_comp = ss_sink_comp,
235 .source = ss_source,
236 .source_comp = ss_source_comp,
237 .intr = ss_intr,
238 .intr_comp = ss_intr_comp,
239};
240
241const struct func_desc ptp_fs_descriptors = {
242 .intf = ptp_interface_desc,
243 .sink = fs_sink,
244 .source = fs_source,
245 .intr = fs_intr,
246};
247
248const struct func_desc ptp_hs_descriptors = {
249 .intf = ptp_interface_desc,
250 .sink = hs_sink,
251 .source = hs_source,
252 .intr = hs_intr,
253};
254
255const struct ss_func_desc ptp_ss_descriptors = {
256 .intf = ptp_interface_desc,
257 .sink = ss_sink,
258 .sink_comp = ss_sink_comp,
259 .source = ss_source,
260 .source_comp = ss_source_comp,
261 .intr = ss_intr,
262 .intr_comp = ss_intr_comp,
263};
264
Jerry Zhang6a790522017-01-11 15:17:53 -0800265#define STR_INTERFACE "MTP"
Jerry Zhang487be612016-10-24 12:10:41 -0700266const struct {
267 struct usb_functionfs_strings_head header;
Jerry Zhang6a790522017-01-11 15:17:53 -0800268 struct {
269 __le16 code;
270 const char str1[sizeof(STR_INTERFACE)];
271 } __attribute__((packed)) lang0;
Jerry Zhang487be612016-10-24 12:10:41 -0700272} __attribute__((packed)) strings = {
273 .header = {
274 .magic = cpu_to_le32(FUNCTIONFS_STRINGS_MAGIC),
275 .length = cpu_to_le32(sizeof(strings)),
Jerry Zhang6a790522017-01-11 15:17:53 -0800276 .str_count = cpu_to_le32(1),
277 .lang_count = cpu_to_le32(1),
278 },
279 .lang0 = {
280 .code = cpu_to_le16(0x0409),
281 .str1 = STR_INTERFACE,
Jerry Zhang487be612016-10-24 12:10:41 -0700282 },
283};
284
285} // anonymous namespace
286
287namespace android {
288
289MtpFfsHandle::MtpFfsHandle() :
290 mMaxWrite(USB_FFS_MAX_WRITE),
291 mMaxRead(USB_FFS_MAX_READ) {}
292
293MtpFfsHandle::~MtpFfsHandle() {}
294
295void MtpFfsHandle::closeEndpoints() {
296 mIntr.reset();
297 mBulkIn.reset();
298 mBulkOut.reset();
299}
300
301bool MtpFfsHandle::initFunctionfs() {
302 ssize_t ret;
303 struct desc_v1 v1_descriptor;
304 struct desc_v2 v2_descriptor;
305
306 v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
307 v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor));
308 v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
309 FUNCTIONFS_HAS_SS_DESC;
310 v2_descriptor.fs_count = 4;
311 v2_descriptor.hs_count = 4;
312 v2_descriptor.ss_count = 7;
313 v2_descriptor.fs_descs = mPtp ? ptp_fs_descriptors : mtp_fs_descriptors;
314 v2_descriptor.hs_descs = mPtp ? ptp_hs_descriptors : mtp_hs_descriptors;
315 v2_descriptor.ss_descs = mPtp ? ptp_ss_descriptors : mtp_ss_descriptors;
316
317 if (mControl < 0) { // might have already done this before
318 mControl.reset(TEMP_FAILURE_RETRY(open(FFS_MTP_EP0, O_RDWR)));
319 if (mControl < 0) {
320 PLOG(ERROR) << FFS_MTP_EP0 << ": cannot open control endpoint";
321 goto err;
322 }
323
324 ret = TEMP_FAILURE_RETRY(::write(mControl, &v2_descriptor, sizeof(v2_descriptor)));
325 if (ret < 0) {
326 v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
327 v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor));
328 v1_descriptor.header.fs_count = 4;
329 v1_descriptor.header.hs_count = 4;
330 v1_descriptor.fs_descs = mPtp ? ptp_fs_descriptors : mtp_fs_descriptors;
331 v1_descriptor.hs_descs = mPtp ? ptp_hs_descriptors : mtp_hs_descriptors;
332 PLOG(ERROR) << FFS_MTP_EP0 << "Switching to V1 descriptor format";
333 ret = TEMP_FAILURE_RETRY(::write(mControl, &v1_descriptor, sizeof(v1_descriptor)));
334 if (ret < 0) {
335 PLOG(ERROR) << FFS_MTP_EP0 << "Writing descriptors failed";
336 goto err;
337 }
338 }
339 ret = TEMP_FAILURE_RETRY(::write(mControl, &strings, sizeof(strings)));
340 if (ret < 0) {
341 PLOG(ERROR) << FFS_MTP_EP0 << "Writing strings failed";
342 goto err;
343 }
344 }
345 if (mBulkIn > -1 || mBulkOut > -1 || mIntr > -1)
346 LOG(WARNING) << "Endpoints were not closed before configure!";
347
Jerry Zhang487be612016-10-24 12:10:41 -0700348 return true;
349
350err:
Jerry Zhang487be612016-10-24 12:10:41 -0700351 closeConfig();
352 return false;
353}
354
355void MtpFfsHandle::closeConfig() {
356 mControl.reset();
357}
358
359int MtpFfsHandle::writeHandle(int fd, const void* data, int len) {
360 LOG(VERBOSE) << "MTP about to write fd = " << fd << ", len=" << len;
361 int ret = 0;
362 const char* buf = static_cast<const char*>(data);
363 while (len > 0) {
364 int write_len = std::min(mMaxWrite, len);
365 int n = TEMP_FAILURE_RETRY(::write(fd, buf, write_len));
366
367 if (n < 0) {
368 PLOG(ERROR) << "write ERROR: fd = " << fd << ", n = " << n;
369 return -1;
370 } else if (n < write_len) {
371 errno = EIO;
372 PLOG(ERROR) << "less written than expected";
373 return -1;
374 }
375 buf += n;
376 len -= n;
377 ret += n;
378 }
379 return ret;
380}
381
382int MtpFfsHandle::readHandle(int fd, void* data, int len) {
383 LOG(VERBOSE) << "MTP about to read fd = " << fd << ", len=" << len;
384 int ret = 0;
385 char* buf = static_cast<char*>(data);
386 while (len > 0) {
387 int read_len = std::min(mMaxRead, len);
388 int n = TEMP_FAILURE_RETRY(::read(fd, buf, read_len));
389 if (n < 0) {
390 PLOG(ERROR) << "read ERROR: fd = " << fd << ", n = " << n;
391 return -1;
392 }
393 ret += n;
394 if (n < read_len) // done reading early
395 break;
396 buf += n;
397 len -= n;
398 }
399 return ret;
400}
401
402int MtpFfsHandle::spliceReadHandle(int fd, int pipe_out, int len) {
403 LOG(VERBOSE) << "MTP about to splice read fd = " << fd << ", len=" << len;
404 int ret = 0;
405 loff_t dummyoff;
406 while (len > 0) {
407 int read_len = std::min(mMaxRead, len);
408 dummyoff = 0;
409 int n = TEMP_FAILURE_RETRY(splice(fd, &dummyoff, pipe_out, nullptr, read_len, 0));
410 if (n < 0) {
411 PLOG(ERROR) << "splice read ERROR: fd = " << fd << ", n = " << n;
412 return -1;
413 }
414 ret += n;
415 if (n < read_len) // done reading early
416 break;
417 len -= n;
418 }
419 return ret;
420}
421
422int MtpFfsHandle::read(void* data, int len) {
423 return readHandle(mBulkOut, data, len);
424}
425
426int MtpFfsHandle::write(const void* data, int len) {
427 return writeHandle(mBulkIn, data, len);
428}
429
430int MtpFfsHandle::start() {
431 mLock.lock();
Jerry Zhangcc9d0fd2017-01-27 10:29:59 -0800432
433 mBulkIn.reset(TEMP_FAILURE_RETRY(open(FFS_MTP_EP_IN, O_RDWR)));
434 if (mBulkIn < 0) {
435 PLOG(ERROR) << FFS_MTP_EP_IN << ": cannot open bulk in ep";
436 return -1;
437 }
438
439 mBulkOut.reset(TEMP_FAILURE_RETRY(open(FFS_MTP_EP_OUT, O_RDWR)));
440 if (mBulkOut < 0) {
441 PLOG(ERROR) << FFS_MTP_EP_OUT << ": cannot open bulk out ep";
442 return -1;
443 }
444
445 mIntr.reset(TEMP_FAILURE_RETRY(open(FFS_MTP_EP_INTR, O_RDWR)));
446 if (mIntr < 0) {
447 PLOG(ERROR) << FFS_MTP_EP0 << ": cannot open intr ep";
448 return -1;
449 }
450
451 mBuffer1.resize(MAX_FILE_CHUNK_SIZE);
452 mBuffer2.resize(MAX_FILE_CHUNK_SIZE);
453 posix_madvise(mBuffer1.data(), MAX_FILE_CHUNK_SIZE,
454 POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED);
455 posix_madvise(mBuffer2.data(), MAX_FILE_CHUNK_SIZE,
456 POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED);
457
458 // Get device specific r/w size
459 mMaxWrite = android::base::GetIntProperty("sys.usb.ffs.max_write", USB_FFS_MAX_WRITE);
460 mMaxRead = android::base::GetIntProperty("sys.usb.ffs.max_read", USB_FFS_MAX_READ);
461
462 while (mMaxWrite > USB_FFS_MAX_WRITE && mMaxRead > USB_FFS_MAX_READ) {
463 // If larger contiguous chunks of memory aren't available, attempt to try
464 // smaller allocations.
465 if (ioctl(mBulkIn, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(mMaxWrite)) ||
466 ioctl(mBulkOut, FUNCTIONFS_ENDPOINT_ALLOC, static_cast<__u32>(mMaxRead))) {
467 mMaxWrite /= 2;
468 mMaxRead /=2;
469 } else {
470 return 0;
471 }
472 }
473 PLOG(ERROR) << "Functionfs could not allocate any memory!";
474 return -1;
Jerry Zhang487be612016-10-24 12:10:41 -0700475}
476
477int MtpFfsHandle::configure(bool usePtp) {
478 // Wait till previous server invocation has closed
479 std::lock_guard<std::mutex> lk(mLock);
480
481 // If ptp is changed, the configuration must be rewritten
482 if (mPtp != usePtp) {
483 closeEndpoints();
484 closeConfig();
485 }
486 mPtp = usePtp;
487
488 if (!initFunctionfs()) {
489 return -1;
490 }
491
Jerry Zhang487be612016-10-24 12:10:41 -0700492 return 0;
493}
494
495void MtpFfsHandle::close() {
496 closeEndpoints();
497 mLock.unlock();
498}
499
500/* Read from USB and write to a local file. */
501int MtpFfsHandle::receiveFile(mtp_file_range mfr) {
502 // When receiving files, the incoming length is given in 32 bits.
503 // A >4G file is given as 0xFFFFFFFF
504 uint32_t file_length = mfr.length;
505 uint64_t offset = lseek(mfr.fd, 0, SEEK_CUR);
506
Jerry Zhangcc9d0fd2017-01-27 10:29:59 -0800507 char *data = mBuffer1.data();
508 char *data2 = mBuffer2.data();
Jerry Zhang487be612016-10-24 12:10:41 -0700509
510 struct aiocb aio;
511 aio.aio_fildes = mfr.fd;
512 aio.aio_buf = nullptr;
513 struct aiocb *aiol[] = {&aio};
514 int ret;
515 size_t length;
516 bool read = false;
517 bool write = false;
518
519 posix_fadvise(mfr.fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
520
521 // Break down the file into pieces that fit in buffers
522 while (file_length > 0 || write) {
523 if (file_length > 0) {
524 length = std::min(static_cast<uint32_t>(MAX_FILE_CHUNK_SIZE), file_length);
525
526 // Read data from USB
527 if ((ret = readHandle(mBulkOut, data, length)) == -1) {
528 return -1;
529 }
530
531 if (file_length != MAX_MTP_FILE_SIZE && ret < static_cast<int>(length)) {
532 errno = EIO;
533 return -1;
534 }
535 read = true;
536 }
537
538 if (write) {
539 // get the return status of the last write request
540 aio_suspend(aiol, 1, nullptr);
541
542 int written = aio_return(&aio);
543 if (written == -1) {
544 errno = aio_error(&aio);
545 return -1;
546 }
547 if (static_cast<size_t>(written) < aio.aio_nbytes) {
548 errno = EIO;
549 return -1;
550 }
551 write = false;
552 }
553
554 if (read) {
555 // Enqueue a new write request
556 aio.aio_buf = data;
557 aio.aio_sink = mfr.fd;
558 aio.aio_offset = offset;
559 aio.aio_nbytes = ret;
560 aio_write(&aio);
561
562 if (file_length == MAX_MTP_FILE_SIZE) {
563 // For larger files, receive until a short packet is received.
564 if (static_cast<size_t>(ret) < length) {
565 file_length = 0;
566 }
567 } else {
568 file_length -= ret;
569 }
570
571 offset += ret;
572 std::swap(data, data2);
573
574 write = true;
575 read = false;
576 }
577 }
578 return 0;
579}
580
581/* Read from a local file and send over USB. */
582int MtpFfsHandle::sendFile(mtp_file_range mfr) {
583 uint64_t file_length = mfr.length;
584 uint32_t given_length = std::min(static_cast<uint64_t>(MAX_MTP_FILE_SIZE),
585 file_length + sizeof(mtp_data_header));
Jerry Zhang44180302017-02-03 16:31:31 -0800586 uint64_t offset = mfr.offset;
Jerry Zhang487be612016-10-24 12:10:41 -0700587 struct usb_endpoint_descriptor mBulkIn_desc;
588 int packet_size;
589
590 if (ioctl(mBulkIn, FUNCTIONFS_ENDPOINT_DESC, reinterpret_cast<unsigned long>(&mBulkIn_desc))) {
591 PLOG(ERROR) << "Could not get FFS bulk-in descriptor";
592 packet_size = MAX_PACKET_SIZE_HS;
593 } else {
594 packet_size = mBulkIn_desc.wMaxPacketSize;
595 }
596
Jerry Zhang44180302017-02-03 16:31:31 -0800597 // If file_length is larger than a size_t, truncating would produce the wrong comparison.
598 // Instead, promote the left side to 64 bits, then truncate the small result.
599 int init_read_len = std::min(
600 static_cast<uint64_t>(packet_size - sizeof(mtp_data_header)), file_length);
Jerry Zhang487be612016-10-24 12:10:41 -0700601
Jerry Zhangcc9d0fd2017-01-27 10:29:59 -0800602 char *data = mBuffer1.data();
603 char *data2 = mBuffer2.data();
Jerry Zhang487be612016-10-24 12:10:41 -0700604
Jerry Zhange9d94422017-01-18 12:03:56 -0800605 posix_fadvise(mfr.fd, 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
Jerry Zhange9d94422017-01-18 12:03:56 -0800606
Jerry Zhang487be612016-10-24 12:10:41 -0700607 struct aiocb aio;
608 aio.aio_fildes = mfr.fd;
609 struct aiocb *aiol[] = {&aio};
610 int ret, length;
611 bool read = false;
612 bool write = false;
613
614 // Send the header data
615 mtp_data_header *header = reinterpret_cast<mtp_data_header*>(data);
616 header->length = __cpu_to_le32(given_length);
617 header->type = __cpu_to_le16(2); /* data packet */
618 header->command = __cpu_to_le16(mfr.command);
619 header->transaction_id = __cpu_to_le32(mfr.transaction_id);
620
621 // Some hosts don't support header/data separation even though MTP allows it
622 // Handle by filling first packet with initial file data
623 if (TEMP_FAILURE_RETRY(pread(mfr.fd, reinterpret_cast<char*>(data) +
624 sizeof(mtp_data_header), init_read_len, offset))
625 != init_read_len) return -1;
Jerry Zhang44180302017-02-03 16:31:31 -0800626 if (writeHandle(mBulkIn, data, sizeof(mtp_data_header) + init_read_len) == -1) return -1;
627 if (file_length == static_cast<unsigned>(init_read_len)) return 0;
Jerry Zhang487be612016-10-24 12:10:41 -0700628 file_length -= init_read_len;
629 offset += init_read_len;
Jerry Zhang487be612016-10-24 12:10:41 -0700630
Jerry Zhang487be612016-10-24 12:10:41 -0700631 // Break down the file into pieces that fit in buffers
632 while(file_length > 0) {
633 if (read) {
634 // Wait for the previous read to finish
635 aio_suspend(aiol, 1, nullptr);
636 ret = aio_return(&aio);
637 if (ret == -1) {
638 errno = aio_error(&aio);
639 return -1;
640 }
641 if (static_cast<size_t>(ret) < aio.aio_nbytes) {
642 errno = EIO;
643 return -1;
644 }
645
646 file_length -= ret;
647 offset += ret;
648 std::swap(data, data2);
649 read = false;
650 write = true;
651 }
652
653 if (file_length > 0) {
Jerry Zhangcc9d0fd2017-01-27 10:29:59 -0800654 length = std::min(static_cast<uint64_t>(MAX_FILE_CHUNK_SIZE), file_length);
Jerry Zhang487be612016-10-24 12:10:41 -0700655 // Queue up another read
656 aio.aio_buf = data;
657 aio.aio_offset = offset;
658 aio.aio_nbytes = length;
659 aio_read(&aio);
660 read = true;
661 }
662
663 if (write) {
664 if (writeHandle(mBulkIn, data2, ret) == -1)
665 return -1;
666 write = false;
667 }
668 }
669
670 if (given_length == MAX_MTP_FILE_SIZE && ret % packet_size == 0) {
671 // If the last packet wasn't short, send a final empty packet
672 if (writeHandle(mBulkIn, data, 0) == -1) return -1;
673 }
674
675 return 0;
676}
677
678int MtpFfsHandle::sendEvent(mtp_event me) {
679 unsigned length = me.length;
680 int ret = writeHandle(mIntr, me.data, length);
681 return static_cast<unsigned>(ret) == length ? 0 : -1;
682}
683
684} // namespace android
685
686IMtpHandle *get_ffs_handle() {
687 return new android::MtpFfsHandle();
688}
689