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