usb: gadget: f_mtp: move userspace interface to uapi
[firefly-linux-kernel-4.4.55.git] / drivers / usb / gadget / f_mtp.c
1 /*
2  * Gadget Function Driver for MTP
3  *
4  * Copyright (C) 2010 Google, Inc.
5  * Author: Mike Lockwood <lockwood@android.com>
6  *
7  * This software is licensed under the terms of the GNU General Public
8  * License version 2, as published by the Free Software Foundation, and
9  * may be copied, distributed, and modified under those terms.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
20
21 #include <linux/module.h>
22 #include <linux/init.h>
23 #include <linux/poll.h>
24 #include <linux/delay.h>
25 #include <linux/wait.h>
26 #include <linux/err.h>
27 #include <linux/interrupt.h>
28
29 #include <linux/types.h>
30 #include <linux/file.h>
31 #include <linux/device.h>
32 #include <linux/miscdevice.h>
33
34 #include <linux/usb.h>
35 #include <linux/usb_usual.h>
36 #include <linux/usb/ch9.h>
37 #include <linux/usb/f_mtp.h>
38
39 #define MTP_BULK_BUFFER_SIZE       16384
40 #define INTR_BUFFER_SIZE           28
41
42 /* String IDs */
43 #define INTERFACE_STRING_INDEX  0
44
45 /* values for mtp_dev.state */
46 #define STATE_OFFLINE               0   /* initial state, disconnected */
47 #define STATE_READY                 1   /* ready for userspace calls */
48 #define STATE_BUSY                  2   /* processing userspace calls */
49 #define STATE_CANCELED              3   /* transaction canceled by host */
50 #define STATE_ERROR                 4   /* error from completion routine */
51
52 /* number of tx and rx requests to allocate */
53 #define TX_REQ_MAX 4
54 #define RX_REQ_MAX 2
55 #define INTR_REQ_MAX 5
56
57 /* ID for Microsoft MTP OS String */
58 #define MTP_OS_STRING_ID   0xEE
59
60 /* MTP class reqeusts */
61 #define MTP_REQ_CANCEL              0x64
62 #define MTP_REQ_GET_EXT_EVENT_DATA  0x65
63 #define MTP_REQ_RESET               0x66
64 #define MTP_REQ_GET_DEVICE_STATUS   0x67
65
66 /* constants for device status */
67 #define MTP_RESPONSE_OK             0x2001
68 #define MTP_RESPONSE_DEVICE_BUSY    0x2019
69
70 static const char mtp_shortname[] = "mtp_usb";
71
72 struct mtp_dev {
73         struct usb_function function;
74         struct usb_composite_dev *cdev;
75         spinlock_t lock;
76
77         struct usb_ep *ep_in;
78         struct usb_ep *ep_out;
79         struct usb_ep *ep_intr;
80
81         int state;
82
83         /* synchronize access to our device file */
84         atomic_t open_excl;
85         /* to enforce only one ioctl at a time */
86         atomic_t ioctl_excl;
87
88         struct list_head tx_idle;
89         struct list_head intr_idle;
90
91         wait_queue_head_t read_wq;
92         wait_queue_head_t write_wq;
93         wait_queue_head_t intr_wq;
94         struct usb_request *rx_req[RX_REQ_MAX];
95         int rx_done;
96
97         /* for processing MTP_SEND_FILE, MTP_RECEIVE_FILE and
98          * MTP_SEND_FILE_WITH_HEADER ioctls on a work queue
99          */
100         struct workqueue_struct *wq;
101         struct work_struct send_file_work;
102         struct work_struct receive_file_work;
103         struct file *xfer_file;
104         loff_t xfer_file_offset;
105         int64_t xfer_file_length;
106         unsigned xfer_send_header;
107         uint16_t xfer_command;
108         uint32_t xfer_transaction_id;
109         int xfer_result;
110 };
111
112 static struct usb_interface_descriptor mtp_interface_desc = {
113         .bLength                = USB_DT_INTERFACE_SIZE,
114         .bDescriptorType        = USB_DT_INTERFACE,
115         .bInterfaceNumber       = 0,
116         .bNumEndpoints          = 3,
117         .bInterfaceClass        = USB_CLASS_VENDOR_SPEC,
118         .bInterfaceSubClass     = USB_SUBCLASS_VENDOR_SPEC,
119         .bInterfaceProtocol     = 0,
120 };
121
122 static struct usb_interface_descriptor ptp_interface_desc = {
123         .bLength                = USB_DT_INTERFACE_SIZE,
124         .bDescriptorType        = USB_DT_INTERFACE,
125         .bInterfaceNumber       = 0,
126         .bNumEndpoints          = 3,
127         .bInterfaceClass        = USB_CLASS_STILL_IMAGE,
128         .bInterfaceSubClass     = 1,
129         .bInterfaceProtocol     = 1,
130 };
131
132 static struct usb_endpoint_descriptor mtp_highspeed_in_desc = {
133         .bLength                = USB_DT_ENDPOINT_SIZE,
134         .bDescriptorType        = USB_DT_ENDPOINT,
135         .bEndpointAddress       = USB_DIR_IN,
136         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
137         .wMaxPacketSize         = __constant_cpu_to_le16(512),
138 };
139
140 static struct usb_endpoint_descriptor mtp_highspeed_out_desc = {
141         .bLength                = USB_DT_ENDPOINT_SIZE,
142         .bDescriptorType        = USB_DT_ENDPOINT,
143         .bEndpointAddress       = USB_DIR_OUT,
144         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
145         .wMaxPacketSize         = __constant_cpu_to_le16(512),
146 };
147
148 static struct usb_endpoint_descriptor mtp_fullspeed_in_desc = {
149         .bLength                = USB_DT_ENDPOINT_SIZE,
150         .bDescriptorType        = USB_DT_ENDPOINT,
151         .bEndpointAddress       = USB_DIR_IN,
152         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
153 };
154
155 static struct usb_endpoint_descriptor mtp_fullspeed_out_desc = {
156         .bLength                = USB_DT_ENDPOINT_SIZE,
157         .bDescriptorType        = USB_DT_ENDPOINT,
158         .bEndpointAddress       = USB_DIR_OUT,
159         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
160 };
161
162 static struct usb_endpoint_descriptor mtp_intr_desc = {
163         .bLength                = USB_DT_ENDPOINT_SIZE,
164         .bDescriptorType        = USB_DT_ENDPOINT,
165         .bEndpointAddress       = USB_DIR_IN,
166         .bmAttributes           = USB_ENDPOINT_XFER_INT,
167         .wMaxPacketSize         = __constant_cpu_to_le16(INTR_BUFFER_SIZE),
168         .bInterval              = 6,
169 };
170
171 static struct usb_descriptor_header *fs_mtp_descs[] = {
172         (struct usb_descriptor_header *) &mtp_interface_desc,
173         (struct usb_descriptor_header *) &mtp_fullspeed_in_desc,
174         (struct usb_descriptor_header *) &mtp_fullspeed_out_desc,
175         (struct usb_descriptor_header *) &mtp_intr_desc,
176         NULL,
177 };
178
179 static struct usb_descriptor_header *hs_mtp_descs[] = {
180         (struct usb_descriptor_header *) &mtp_interface_desc,
181         (struct usb_descriptor_header *) &mtp_highspeed_in_desc,
182         (struct usb_descriptor_header *) &mtp_highspeed_out_desc,
183         (struct usb_descriptor_header *) &mtp_intr_desc,
184         NULL,
185 };
186
187 static struct usb_descriptor_header *fs_ptp_descs[] = {
188         (struct usb_descriptor_header *) &ptp_interface_desc,
189         (struct usb_descriptor_header *) &mtp_fullspeed_in_desc,
190         (struct usb_descriptor_header *) &mtp_fullspeed_out_desc,
191         (struct usb_descriptor_header *) &mtp_intr_desc,
192         NULL,
193 };
194
195 static struct usb_descriptor_header *hs_ptp_descs[] = {
196         (struct usb_descriptor_header *) &ptp_interface_desc,
197         (struct usb_descriptor_header *) &mtp_highspeed_in_desc,
198         (struct usb_descriptor_header *) &mtp_highspeed_out_desc,
199         (struct usb_descriptor_header *) &mtp_intr_desc,
200         NULL,
201 };
202
203 static struct usb_string mtp_string_defs[] = {
204         /* Naming interface "MTP" so libmtp will recognize us */
205         [INTERFACE_STRING_INDEX].s      = "MTP",
206         {  },   /* end of list */
207 };
208
209 static struct usb_gadget_strings mtp_string_table = {
210         .language               = 0x0409,       /* en-US */
211         .strings                = mtp_string_defs,
212 };
213
214 static struct usb_gadget_strings *mtp_strings[] = {
215         &mtp_string_table,
216         NULL,
217 };
218
219 /* Microsoft MTP OS String */
220 static u8 mtp_os_string[] = {
221         18, /* sizeof(mtp_os_string) */
222         USB_DT_STRING,
223         /* Signature field: "MSFT100" */
224         'M', 0, 'S', 0, 'F', 0, 'T', 0, '1', 0, '0', 0, '0', 0,
225         /* vendor code */
226         1,
227         /* padding */
228         0
229 };
230
231 /* Microsoft Extended Configuration Descriptor Header Section */
232 struct mtp_ext_config_desc_header {
233         __le32  dwLength;
234         __u16   bcdVersion;
235         __le16  wIndex;
236         __u8    bCount;
237         __u8    reserved[7];
238 };
239
240 /* Microsoft Extended Configuration Descriptor Function Section */
241 struct mtp_ext_config_desc_function {
242         __u8    bFirstInterfaceNumber;
243         __u8    bInterfaceCount;
244         __u8    compatibleID[8];
245         __u8    subCompatibleID[8];
246         __u8    reserved[6];
247 };
248
249 /* MTP Extended Configuration Descriptor */
250 struct {
251         struct mtp_ext_config_desc_header       header;
252         struct mtp_ext_config_desc_function    function;
253 } mtp_ext_config_desc = {
254         .header = {
255                 .dwLength = __constant_cpu_to_le32(sizeof(mtp_ext_config_desc)),
256                 .bcdVersion = __constant_cpu_to_le16(0x0100),
257                 .wIndex = __constant_cpu_to_le16(4),
258                 .bCount = __constant_cpu_to_le16(1),
259         },
260         .function = {
261                 .bFirstInterfaceNumber = 0,
262                 .bInterfaceCount = 1,
263                 .compatibleID = { 'M', 'T', 'P' },
264         },
265 };
266
267 struct mtp_device_status {
268         __le16  wLength;
269         __le16  wCode;
270 };
271
272 struct mtp_data_header {
273         /* length of packet, including this header */
274         __le32  length;
275         /* container type (2 for data packet) */
276         __le16  type;
277         /* MTP command code */
278         __le16  command;
279         /* MTP transaction ID */
280         __le32  transaction_id;
281 };
282
283 /* temporary variable used between mtp_open() and mtp_gadget_bind() */
284 static struct mtp_dev *_mtp_dev;
285
286 static inline struct mtp_dev *func_to_mtp(struct usb_function *f)
287 {
288         return container_of(f, struct mtp_dev, function);
289 }
290
291 static struct usb_request *mtp_request_new(struct usb_ep *ep, int buffer_size)
292 {
293         struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
294         if (!req)
295                 return NULL;
296
297         /* now allocate buffers for the requests */
298         req->buf = kmalloc(buffer_size, GFP_KERNEL);
299         if (!req->buf) {
300                 usb_ep_free_request(ep, req);
301                 return NULL;
302         }
303
304         return req;
305 }
306
307 static void mtp_request_free(struct usb_request *req, struct usb_ep *ep)
308 {
309         if (req) {
310                 kfree(req->buf);
311                 usb_ep_free_request(ep, req);
312         }
313 }
314
315 static inline int mtp_lock(atomic_t *excl)
316 {
317         if (atomic_inc_return(excl) == 1) {
318                 return 0;
319         } else {
320                 atomic_dec(excl);
321                 return -1;
322         }
323 }
324
325 static inline void mtp_unlock(atomic_t *excl)
326 {
327         atomic_dec(excl);
328 }
329
330 /* add a request to the tail of a list */
331 static void mtp_req_put(struct mtp_dev *dev, struct list_head *head,
332                 struct usb_request *req)
333 {
334         unsigned long flags;
335
336         spin_lock_irqsave(&dev->lock, flags);
337         list_add_tail(&req->list, head);
338         spin_unlock_irqrestore(&dev->lock, flags);
339 }
340
341 /* remove a request from the head of a list */
342 static struct usb_request
343 *mtp_req_get(struct mtp_dev *dev, struct list_head *head)
344 {
345         unsigned long flags;
346         struct usb_request *req;
347
348         spin_lock_irqsave(&dev->lock, flags);
349         if (list_empty(head)) {
350                 req = 0;
351         } else {
352                 req = list_first_entry(head, struct usb_request, list);
353                 list_del(&req->list);
354         }
355         spin_unlock_irqrestore(&dev->lock, flags);
356         return req;
357 }
358
359 static void mtp_complete_in(struct usb_ep *ep, struct usb_request *req)
360 {
361         struct mtp_dev *dev = _mtp_dev;
362
363         if (req->status != 0)
364                 dev->state = STATE_ERROR;
365
366         mtp_req_put(dev, &dev->tx_idle, req);
367
368         wake_up(&dev->write_wq);
369 }
370
371 static void mtp_complete_out(struct usb_ep *ep, struct usb_request *req)
372 {
373         struct mtp_dev *dev = _mtp_dev;
374
375         dev->rx_done = 1;
376         if (req->status != 0)
377                 dev->state = STATE_ERROR;
378
379         wake_up(&dev->read_wq);
380 }
381
382 static void mtp_complete_intr(struct usb_ep *ep, struct usb_request *req)
383 {
384         struct mtp_dev *dev = _mtp_dev;
385
386         if (req->status != 0)
387                 dev->state = STATE_ERROR;
388
389         mtp_req_put(dev, &dev->intr_idle, req);
390
391         wake_up(&dev->intr_wq);
392 }
393
394 static int mtp_create_bulk_endpoints(struct mtp_dev *dev,
395                                 struct usb_endpoint_descriptor *in_desc,
396                                 struct usb_endpoint_descriptor *out_desc,
397                                 struct usb_endpoint_descriptor *intr_desc)
398 {
399         struct usb_composite_dev *cdev = dev->cdev;
400         struct usb_request *req;
401         struct usb_ep *ep;
402         int i;
403
404         DBG(cdev, "create_bulk_endpoints dev: %p\n", dev);
405
406         ep = usb_ep_autoconfig(cdev->gadget, in_desc);
407         if (!ep) {
408                 DBG(cdev, "usb_ep_autoconfig for ep_in failed\n");
409                 return -ENODEV;
410         }
411         DBG(cdev, "usb_ep_autoconfig for ep_in got %s\n", ep->name);
412         ep->driver_data = dev;          /* claim the endpoint */
413         dev->ep_in = ep;
414
415         ep = usb_ep_autoconfig(cdev->gadget, out_desc);
416         if (!ep) {
417                 DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
418                 return -ENODEV;
419         }
420         DBG(cdev, "usb_ep_autoconfig for mtp ep_out got %s\n", ep->name);
421         ep->driver_data = dev;          /* claim the endpoint */
422         dev->ep_out = ep;
423
424         ep = usb_ep_autoconfig(cdev->gadget, intr_desc);
425         if (!ep) {
426                 DBG(cdev, "usb_ep_autoconfig for ep_intr failed\n");
427                 return -ENODEV;
428         }
429         DBG(cdev, "usb_ep_autoconfig for mtp ep_intr got %s\n", ep->name);
430         ep->driver_data = dev;          /* claim the endpoint */
431         dev->ep_intr = ep;
432
433         /* now allocate requests for our endpoints */
434         for (i = 0; i < TX_REQ_MAX; i++) {
435                 req = mtp_request_new(dev->ep_in, MTP_BULK_BUFFER_SIZE);
436                 if (!req)
437                         goto fail;
438                 req->complete = mtp_complete_in;
439                 mtp_req_put(dev, &dev->tx_idle, req);
440         }
441         for (i = 0; i < RX_REQ_MAX; i++) {
442                 req = mtp_request_new(dev->ep_out, MTP_BULK_BUFFER_SIZE);
443                 if (!req)
444                         goto fail;
445                 req->complete = mtp_complete_out;
446                 dev->rx_req[i] = req;
447         }
448         for (i = 0; i < INTR_REQ_MAX; i++) {
449                 req = mtp_request_new(dev->ep_intr, INTR_BUFFER_SIZE);
450                 if (!req)
451                         goto fail;
452                 req->complete = mtp_complete_intr;
453                 mtp_req_put(dev, &dev->intr_idle, req);
454         }
455
456         return 0;
457
458 fail:
459         printk(KERN_ERR "mtp_bind() could not allocate requests\n");
460         return -1;
461 }
462
463 static ssize_t mtp_read(struct file *fp, char __user *buf,
464         size_t count, loff_t *pos)
465 {
466         struct mtp_dev *dev = fp->private_data;
467         struct usb_composite_dev *cdev = dev->cdev;
468         struct usb_request *req;
469         int r = count, xfer;
470         int ret = 0;
471
472         DBG(cdev, "mtp_read(%d)\n", count);
473
474         if (count > MTP_BULK_BUFFER_SIZE)
475                 return -EINVAL;
476
477         /* we will block until we're online */
478         DBG(cdev, "mtp_read: waiting for online state\n");
479         ret = wait_event_interruptible(dev->read_wq,
480                 dev->state != STATE_OFFLINE);
481         if (ret < 0) {
482                 r = ret;
483                 goto done;
484         }
485         spin_lock_irq(&dev->lock);
486         if (dev->state == STATE_CANCELED) {
487                 /* report cancelation to userspace */
488                 dev->state = STATE_READY;
489                 spin_unlock_irq(&dev->lock);
490                 return -ECANCELED;
491         }
492         dev->state = STATE_BUSY;
493         spin_unlock_irq(&dev->lock);
494
495 requeue_req:
496         /* queue a request */
497         req = dev->rx_req[0];
498         req->length = count;
499         dev->rx_done = 0;
500         ret = usb_ep_queue(dev->ep_out, req, GFP_KERNEL);
501         if (ret < 0) {
502                 r = -EIO;
503                 goto done;
504         } else {
505                 DBG(cdev, "rx %p queue\n", req);
506         }
507
508         /* wait for a request to complete */
509         ret = wait_event_interruptible(dev->read_wq, dev->rx_done);
510         if (ret < 0) {
511                 r = ret;
512                 usb_ep_dequeue(dev->ep_out, req);
513                 goto done;
514         }
515         if (dev->state == STATE_BUSY) {
516                 /* If we got a 0-len packet, throw it back and try again. */
517                 if (req->actual == 0)
518                         goto requeue_req;
519
520                 DBG(cdev, "rx %p %d\n", req, req->actual);
521                 xfer = (req->actual < count) ? req->actual : count;
522                 r = xfer;
523                 if (copy_to_user(buf, req->buf, xfer))
524                         r = -EFAULT;
525         } else
526                 r = -EIO;
527
528 done:
529         spin_lock_irq(&dev->lock);
530         if (dev->state == STATE_CANCELED)
531                 r = -ECANCELED;
532         else if (dev->state != STATE_OFFLINE)
533                 dev->state = STATE_READY;
534         spin_unlock_irq(&dev->lock);
535
536         DBG(cdev, "mtp_read returning %d\n", r);
537         return r;
538 }
539
540 static ssize_t mtp_write(struct file *fp, const char __user *buf,
541         size_t count, loff_t *pos)
542 {
543         struct mtp_dev *dev = fp->private_data;
544         struct usb_composite_dev *cdev = dev->cdev;
545         struct usb_request *req = 0;
546         int r = count, xfer;
547         int sendZLP = 0;
548         int ret;
549
550         DBG(cdev, "mtp_write(%d)\n", count);
551
552         spin_lock_irq(&dev->lock);
553         if (dev->state == STATE_CANCELED) {
554                 /* report cancelation to userspace */
555                 dev->state = STATE_READY;
556                 spin_unlock_irq(&dev->lock);
557                 return -ECANCELED;
558         }
559         if (dev->state == STATE_OFFLINE) {
560                 spin_unlock_irq(&dev->lock);
561                 return -ENODEV;
562         }
563         dev->state = STATE_BUSY;
564         spin_unlock_irq(&dev->lock);
565
566         /* we need to send a zero length packet to signal the end of transfer
567          * if the transfer size is aligned to a packet boundary.
568          */
569         if ((count & (dev->ep_in->maxpacket - 1)) == 0)
570                 sendZLP = 1;
571
572         while (count > 0 || sendZLP) {
573                 /* so we exit after sending ZLP */
574                 if (count == 0)
575                         sendZLP = 0;
576
577                 if (dev->state != STATE_BUSY) {
578                         DBG(cdev, "mtp_write dev->error\n");
579                         r = -EIO;
580                         break;
581                 }
582
583                 /* get an idle tx request to use */
584                 req = 0;
585                 ret = wait_event_interruptible(dev->write_wq,
586                         ((req = mtp_req_get(dev, &dev->tx_idle))
587                                 || dev->state != STATE_BUSY));
588                 if (!req) {
589                         r = ret;
590                         break;
591                 }
592
593                 if (count > MTP_BULK_BUFFER_SIZE)
594                         xfer = MTP_BULK_BUFFER_SIZE;
595                 else
596                         xfer = count;
597                 if (xfer && copy_from_user(req->buf, buf, xfer)) {
598                         r = -EFAULT;
599                         break;
600                 }
601
602                 req->length = xfer;
603                 ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
604                 if (ret < 0) {
605                         DBG(cdev, "mtp_write: xfer error %d\n", ret);
606                         r = -EIO;
607                         break;
608                 }
609
610                 buf += xfer;
611                 count -= xfer;
612
613                 /* zero this so we don't try to free it on error exit */
614                 req = 0;
615         }
616
617         if (req)
618                 mtp_req_put(dev, &dev->tx_idle, req);
619
620         spin_lock_irq(&dev->lock);
621         if (dev->state == STATE_CANCELED)
622                 r = -ECANCELED;
623         else if (dev->state != STATE_OFFLINE)
624                 dev->state = STATE_READY;
625         spin_unlock_irq(&dev->lock);
626
627         DBG(cdev, "mtp_write returning %d\n", r);
628         return r;
629 }
630
631 /* read from a local file and write to USB */
632 static void send_file_work(struct work_struct *data)
633 {
634         struct mtp_dev *dev = container_of(data, struct mtp_dev,
635                                                 send_file_work);
636         struct usb_composite_dev *cdev = dev->cdev;
637         struct usb_request *req = 0;
638         struct mtp_data_header *header;
639         struct file *filp;
640         loff_t offset;
641         int64_t count;
642         int xfer, ret, hdr_size;
643         int r = 0;
644         int sendZLP = 0;
645
646         /* read our parameters */
647         smp_rmb();
648         filp = dev->xfer_file;
649         offset = dev->xfer_file_offset;
650         count = dev->xfer_file_length;
651
652         DBG(cdev, "send_file_work(%lld %lld)\n", offset, count);
653
654         if (dev->xfer_send_header) {
655                 hdr_size = sizeof(struct mtp_data_header);
656                 count += hdr_size;
657         } else {
658                 hdr_size = 0;
659         }
660
661         /* we need to send a zero length packet to signal the end of transfer
662          * if the transfer size is aligned to a packet boundary.
663          */
664         if ((count & (dev->ep_in->maxpacket - 1)) == 0)
665                 sendZLP = 1;
666
667         while (count > 0 || sendZLP) {
668                 /* so we exit after sending ZLP */
669                 if (count == 0)
670                         sendZLP = 0;
671
672                 /* get an idle tx request to use */
673                 req = 0;
674                 ret = wait_event_interruptible(dev->write_wq,
675                         (req = mtp_req_get(dev, &dev->tx_idle))
676                         || dev->state != STATE_BUSY);
677                 if (dev->state == STATE_CANCELED) {
678                         r = -ECANCELED;
679                         break;
680                 }
681                 if (!req) {
682                         r = ret;
683                         break;
684                 }
685
686                 if (count > MTP_BULK_BUFFER_SIZE)
687                         xfer = MTP_BULK_BUFFER_SIZE;
688                 else
689                         xfer = count;
690
691                 if (hdr_size) {
692                         /* prepend MTP data header */
693                         header = (struct mtp_data_header *)req->buf;
694                         header->length = __cpu_to_le32(count);
695                         header->type = __cpu_to_le16(2); /* data packet */
696                         header->command = __cpu_to_le16(dev->xfer_command);
697                         header->transaction_id =
698                                         __cpu_to_le32(dev->xfer_transaction_id);
699                 }
700
701                 ret = vfs_read(filp, req->buf + hdr_size, xfer - hdr_size,
702                                                                 &offset);
703                 if (ret < 0) {
704                         r = ret;
705                         break;
706                 }
707                 xfer = ret + hdr_size;
708                 hdr_size = 0;
709
710                 req->length = xfer;
711                 ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
712                 if (ret < 0) {
713                         DBG(cdev, "send_file_work: xfer error %d\n", ret);
714                         dev->state = STATE_ERROR;
715                         r = -EIO;
716                         break;
717                 }
718
719                 count -= xfer;
720
721                 /* zero this so we don't try to free it on error exit */
722                 req = 0;
723         }
724
725         if (req)
726                 mtp_req_put(dev, &dev->tx_idle, req);
727
728         DBG(cdev, "send_file_work returning %d\n", r);
729         /* write the result */
730         dev->xfer_result = r;
731         smp_wmb();
732 }
733
734 /* read from USB and write to a local file */
735 static void receive_file_work(struct work_struct *data)
736 {
737         struct mtp_dev *dev = container_of(data, struct mtp_dev,
738                                                 receive_file_work);
739         struct usb_composite_dev *cdev = dev->cdev;
740         struct usb_request *read_req = NULL, *write_req = NULL;
741         struct file *filp;
742         loff_t offset;
743         int64_t count;
744         int ret, cur_buf = 0;
745         int r = 0;
746
747         /* read our parameters */
748         smp_rmb();
749         filp = dev->xfer_file;
750         offset = dev->xfer_file_offset;
751         count = dev->xfer_file_length;
752
753         DBG(cdev, "receive_file_work(%lld)\n", count);
754
755         while (count > 0 || write_req) {
756                 if (count > 0) {
757                         /* queue a request */
758                         read_req = dev->rx_req[cur_buf];
759                         cur_buf = (cur_buf + 1) % RX_REQ_MAX;
760
761                         read_req->length = (count > MTP_BULK_BUFFER_SIZE
762                                         ? MTP_BULK_BUFFER_SIZE : count);
763                         dev->rx_done = 0;
764                         ret = usb_ep_queue(dev->ep_out, read_req, GFP_KERNEL);
765                         if (ret < 0) {
766                                 r = -EIO;
767                                 dev->state = STATE_ERROR;
768                                 break;
769                         }
770                 }
771
772                 if (write_req) {
773                         DBG(cdev, "rx %p %d\n", write_req, write_req->actual);
774                         ret = vfs_write(filp, write_req->buf, write_req->actual,
775                                 &offset);
776                         DBG(cdev, "vfs_write %d\n", ret);
777                         if (ret != write_req->actual) {
778                                 r = -EIO;
779                                 dev->state = STATE_ERROR;
780                                 break;
781                         }
782                         write_req = NULL;
783                 }
784
785                 if (read_req) {
786                         /* wait for our last read to complete */
787                         ret = wait_event_interruptible(dev->read_wq,
788                                 dev->rx_done || dev->state != STATE_BUSY);
789                         if (dev->state == STATE_CANCELED) {
790                                 r = -ECANCELED;
791                                 if (!dev->rx_done)
792                                         usb_ep_dequeue(dev->ep_out, read_req);
793                                 break;
794                         }
795                         /* if xfer_file_length is 0xFFFFFFFF, then we read until
796                          * we get a zero length packet
797                          */
798                         if (count != 0xFFFFFFFF)
799                                 count -= read_req->actual;
800                         if (read_req->actual < read_req->length) {
801                                 /*
802                                  * short packet is used to signal EOF for
803                                  * sizes > 4 gig
804                                  */
805                                 DBG(cdev, "got short packet\n");
806                                 count = 0;
807                         }
808
809                         write_req = read_req;
810                         read_req = NULL;
811                 }
812         }
813
814         DBG(cdev, "receive_file_work returning %d\n", r);
815         /* write the result */
816         dev->xfer_result = r;
817         smp_wmb();
818 }
819
820 static int mtp_send_event(struct mtp_dev *dev, struct mtp_event *event)
821 {
822         struct usb_request *req = NULL;
823         int ret;
824         int length = event->length;
825
826         DBG(dev->cdev, "mtp_send_event(%d)\n", event->length);
827
828         if (length < 0 || length > INTR_BUFFER_SIZE)
829                 return -EINVAL;
830         if (dev->state == STATE_OFFLINE)
831                 return -ENODEV;
832
833         ret = wait_event_interruptible_timeout(dev->intr_wq,
834                         (req = mtp_req_get(dev, &dev->intr_idle)),
835                         msecs_to_jiffies(1000));
836         if (!req)
837                 return -ETIME;
838
839         if (copy_from_user(req->buf, (void __user *)event->data, length)) {
840                 mtp_req_put(dev, &dev->intr_idle, req);
841                 return -EFAULT;
842         }
843         req->length = length;
844         ret = usb_ep_queue(dev->ep_intr, req, GFP_KERNEL);
845         if (ret)
846                 mtp_req_put(dev, &dev->intr_idle, req);
847
848         return ret;
849 }
850
851 static long mtp_ioctl(struct file *fp, unsigned code, unsigned long value)
852 {
853         struct mtp_dev *dev = fp->private_data;
854         struct file *filp = NULL;
855         int ret = -EINVAL;
856
857         if (mtp_lock(&dev->ioctl_excl))
858                 return -EBUSY;
859
860         switch (code) {
861         case MTP_SEND_FILE:
862         case MTP_RECEIVE_FILE:
863         case MTP_SEND_FILE_WITH_HEADER:
864         {
865                 struct mtp_file_range   mfr;
866                 struct work_struct *work;
867
868                 spin_lock_irq(&dev->lock);
869                 if (dev->state == STATE_CANCELED) {
870                         /* report cancelation to userspace */
871                         dev->state = STATE_READY;
872                         spin_unlock_irq(&dev->lock);
873                         ret = -ECANCELED;
874                         goto out;
875                 }
876                 if (dev->state == STATE_OFFLINE) {
877                         spin_unlock_irq(&dev->lock);
878                         ret = -ENODEV;
879                         goto out;
880                 }
881                 dev->state = STATE_BUSY;
882                 spin_unlock_irq(&dev->lock);
883
884                 if (copy_from_user(&mfr, (void __user *)value, sizeof(mfr))) {
885                         ret = -EFAULT;
886                         goto fail;
887                 }
888                 /* hold a reference to the file while we are working with it */
889                 filp = fget(mfr.fd);
890                 if (!filp) {
891                         ret = -EBADF;
892                         goto fail;
893                 }
894
895                 /* write the parameters */
896                 dev->xfer_file = filp;
897                 dev->xfer_file_offset = mfr.offset;
898                 dev->xfer_file_length = mfr.length;
899                 smp_wmb();
900
901                 if (code == MTP_SEND_FILE_WITH_HEADER) {
902                         work = &dev->send_file_work;
903                         dev->xfer_send_header = 1;
904                         dev->xfer_command = mfr.command;
905                         dev->xfer_transaction_id = mfr.transaction_id;
906                 } else if (code == MTP_SEND_FILE) {
907                         work = &dev->send_file_work;
908                         dev->xfer_send_header = 0;
909                 } else {
910                         work = &dev->receive_file_work;
911                 }
912
913                 /* We do the file transfer on a work queue so it will run
914                  * in kernel context, which is necessary for vfs_read and
915                  * vfs_write to use our buffers in the kernel address space.
916                  */
917                 queue_work(dev->wq, work);
918                 /* wait for operation to complete */
919                 flush_workqueue(dev->wq);
920                 fput(filp);
921
922                 /* read the result */
923                 smp_rmb();
924                 ret = dev->xfer_result;
925                 break;
926         }
927         case MTP_SEND_EVENT:
928         {
929                 struct mtp_event        event;
930                 /* return here so we don't change dev->state below,
931                  * which would interfere with bulk transfer state.
932                  */
933                 if (copy_from_user(&event, (void __user *)value, sizeof(event)))
934                         ret = -EFAULT;
935                 else
936                         ret = mtp_send_event(dev, &event);
937                 goto out;
938         }
939         }
940
941 fail:
942         spin_lock_irq(&dev->lock);
943         if (dev->state == STATE_CANCELED)
944                 ret = -ECANCELED;
945         else if (dev->state != STATE_OFFLINE)
946                 dev->state = STATE_READY;
947         spin_unlock_irq(&dev->lock);
948 out:
949         mtp_unlock(&dev->ioctl_excl);
950         DBG(dev->cdev, "ioctl returning %d\n", ret);
951         return ret;
952 }
953
954 static int mtp_open(struct inode *ip, struct file *fp)
955 {
956         printk(KERN_INFO "mtp_open\n");
957         if (mtp_lock(&_mtp_dev->open_excl))
958                 return -EBUSY;
959
960         /* clear any error condition */
961         if (_mtp_dev->state != STATE_OFFLINE)
962                 _mtp_dev->state = STATE_READY;
963
964         fp->private_data = _mtp_dev;
965         return 0;
966 }
967
968 static int mtp_release(struct inode *ip, struct file *fp)
969 {
970         printk(KERN_INFO "mtp_release\n");
971
972         mtp_unlock(&_mtp_dev->open_excl);
973         return 0;
974 }
975
976 /* file operations for /dev/mtp_usb */
977 static const struct file_operations mtp_fops = {
978         .owner = THIS_MODULE,
979         .read = mtp_read,
980         .write = mtp_write,
981         .unlocked_ioctl = mtp_ioctl,
982         .open = mtp_open,
983         .release = mtp_release,
984 };
985
986 static struct miscdevice mtp_device = {
987         .minor = MISC_DYNAMIC_MINOR,
988         .name = mtp_shortname,
989         .fops = &mtp_fops,
990 };
991
992 static int mtp_ctrlrequest(struct usb_composite_dev *cdev,
993                                 const struct usb_ctrlrequest *ctrl)
994 {
995         struct mtp_dev *dev = _mtp_dev;
996         int     value = -EOPNOTSUPP;
997         u16     w_index = le16_to_cpu(ctrl->wIndex);
998         u16     w_value = le16_to_cpu(ctrl->wValue);
999         u16     w_length = le16_to_cpu(ctrl->wLength);
1000         unsigned long   flags;
1001
1002         VDBG(cdev, "mtp_ctrlrequest "
1003                         "%02x.%02x v%04x i%04x l%u\n",
1004                         ctrl->bRequestType, ctrl->bRequest,
1005                         w_value, w_index, w_length);
1006
1007         /* Handle MTP OS string */
1008         if (ctrl->bRequestType ==
1009                         (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE)
1010                         && ctrl->bRequest == USB_REQ_GET_DESCRIPTOR
1011                         && (w_value >> 8) == USB_DT_STRING
1012                         && (w_value & 0xFF) == MTP_OS_STRING_ID) {
1013                 value = (w_length < sizeof(mtp_os_string)
1014                                 ? w_length : sizeof(mtp_os_string));
1015                 memcpy(cdev->req->buf, mtp_os_string, value);
1016         } else if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_VENDOR) {
1017                 /* Handle MTP OS descriptor */
1018                 DBG(cdev, "vendor request: %d index: %d value: %d length: %d\n",
1019                         ctrl->bRequest, w_index, w_value, w_length);
1020
1021                 if (ctrl->bRequest == 1
1022                                 && (ctrl->bRequestType & USB_DIR_IN)
1023                                 && (w_index == 4 || w_index == 5)) {
1024                         value = (w_length < sizeof(mtp_ext_config_desc) ?
1025                                         w_length : sizeof(mtp_ext_config_desc));
1026                         memcpy(cdev->req->buf, &mtp_ext_config_desc, value);
1027                 }
1028         } else if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
1029                 DBG(cdev, "class request: %d index: %d value: %d length: %d\n",
1030                         ctrl->bRequest, w_index, w_value, w_length);
1031
1032                 if (ctrl->bRequest == MTP_REQ_CANCEL && w_index == 0
1033                                 && w_value == 0) {
1034                         DBG(cdev, "MTP_REQ_CANCEL\n");
1035
1036                         spin_lock_irqsave(&dev->lock, flags);
1037                         if (dev->state == STATE_BUSY) {
1038                                 dev->state = STATE_CANCELED;
1039                                 wake_up(&dev->read_wq);
1040                                 wake_up(&dev->write_wq);
1041                         }
1042                         spin_unlock_irqrestore(&dev->lock, flags);
1043
1044                         /* We need to queue a request to read the remaining
1045                          *  bytes, but we don't actually need to look at
1046                          * the contents.
1047                          */
1048                         value = w_length;
1049                 } else if (ctrl->bRequest == MTP_REQ_GET_DEVICE_STATUS
1050                                 && w_index == 0 && w_value == 0) {
1051                         struct mtp_device_status *status = cdev->req->buf;
1052                         status->wLength =
1053                                 __constant_cpu_to_le16(sizeof(*status));
1054
1055                         DBG(cdev, "MTP_REQ_GET_DEVICE_STATUS\n");
1056                         spin_lock_irqsave(&dev->lock, flags);
1057                         /* device status is "busy" until we report
1058                          * the cancelation to userspace
1059                          */
1060                         if (dev->state == STATE_CANCELED)
1061                                 status->wCode =
1062                                         __cpu_to_le16(MTP_RESPONSE_DEVICE_BUSY);
1063                         else
1064                                 status->wCode =
1065                                         __cpu_to_le16(MTP_RESPONSE_OK);
1066                         spin_unlock_irqrestore(&dev->lock, flags);
1067                         value = sizeof(*status);
1068                 }
1069         }
1070
1071         /* respond with data transfer or status phase? */
1072         if (value >= 0) {
1073                 int rc;
1074                 cdev->req->zero = value < w_length;
1075                 cdev->req->length = value;
1076                 rc = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
1077                 if (rc < 0)
1078                         ERROR(cdev, "%s: response queue error\n", __func__);
1079         }
1080         return value;
1081 }
1082
1083 static int
1084 mtp_function_bind(struct usb_configuration *c, struct usb_function *f)
1085 {
1086         struct usb_composite_dev *cdev = c->cdev;
1087         struct mtp_dev  *dev = func_to_mtp(f);
1088         int                     id;
1089         int                     ret;
1090
1091         dev->cdev = cdev;
1092         DBG(cdev, "mtp_function_bind dev: %p\n", dev);
1093
1094         /* allocate interface ID(s) */
1095         id = usb_interface_id(c, f);
1096         if (id < 0)
1097                 return id;
1098         mtp_interface_desc.bInterfaceNumber = id;
1099
1100         /* allocate endpoints */
1101         ret = mtp_create_bulk_endpoints(dev, &mtp_fullspeed_in_desc,
1102                         &mtp_fullspeed_out_desc, &mtp_intr_desc);
1103         if (ret)
1104                 return ret;
1105
1106         /* support high speed hardware */
1107         if (gadget_is_dualspeed(c->cdev->gadget)) {
1108                 mtp_highspeed_in_desc.bEndpointAddress =
1109                         mtp_fullspeed_in_desc.bEndpointAddress;
1110                 mtp_highspeed_out_desc.bEndpointAddress =
1111                         mtp_fullspeed_out_desc.bEndpointAddress;
1112         }
1113
1114         DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
1115                         gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1116                         f->name, dev->ep_in->name, dev->ep_out->name);
1117         return 0;
1118 }
1119
1120 static void
1121 mtp_function_unbind(struct usb_configuration *c, struct usb_function *f)
1122 {
1123         struct mtp_dev  *dev = func_to_mtp(f);
1124         struct usb_request *req;
1125         int i;
1126
1127         while ((req = mtp_req_get(dev, &dev->tx_idle)))
1128                 mtp_request_free(req, dev->ep_in);
1129         for (i = 0; i < RX_REQ_MAX; i++)
1130                 mtp_request_free(dev->rx_req[i], dev->ep_out);
1131         while ((req = mtp_req_get(dev, &dev->intr_idle)))
1132                 mtp_request_free(req, dev->ep_intr);
1133         dev->state = STATE_OFFLINE;
1134 }
1135
1136 static int mtp_function_set_alt(struct usb_function *f,
1137                 unsigned intf, unsigned alt)
1138 {
1139         struct mtp_dev  *dev = func_to_mtp(f);
1140         struct usb_composite_dev *cdev = f->config->cdev;
1141         int ret;
1142
1143         DBG(cdev, "mtp_function_set_alt intf: %d alt: %d\n", intf, alt);
1144
1145         ret = config_ep_by_speed(cdev->gadget, f, dev->ep_in);
1146         if (ret)
1147                 return ret;
1148
1149         ret = usb_ep_enable(dev->ep_in);
1150         if (ret)
1151                 return ret;
1152
1153         ret = config_ep_by_speed(cdev->gadget, f, dev->ep_out);
1154         if (ret)
1155                 return ret;
1156
1157         ret = usb_ep_enable(dev->ep_out);
1158         if (ret) {
1159                 usb_ep_disable(dev->ep_in);
1160                 return ret;
1161         }
1162
1163         ret = config_ep_by_speed(cdev->gadget, f, dev->ep_intr);
1164         if (ret)
1165                 return ret;
1166
1167         ret = usb_ep_enable(dev->ep_intr);
1168         if (ret) {
1169                 usb_ep_disable(dev->ep_out);
1170                 usb_ep_disable(dev->ep_in);
1171                 return ret;
1172         }
1173         dev->state = STATE_READY;
1174
1175         /* readers may be blocked waiting for us to go online */
1176         wake_up(&dev->read_wq);
1177         return 0;
1178 }
1179
1180 static void mtp_function_disable(struct usb_function *f)
1181 {
1182         struct mtp_dev  *dev = func_to_mtp(f);
1183         struct usb_composite_dev        *cdev = dev->cdev;
1184
1185         DBG(cdev, "mtp_function_disable\n");
1186         dev->state = STATE_OFFLINE;
1187         usb_ep_disable(dev->ep_in);
1188         usb_ep_disable(dev->ep_out);
1189         usb_ep_disable(dev->ep_intr);
1190
1191         /* readers may be blocked waiting for us to go online */
1192         wake_up(&dev->read_wq);
1193
1194         VDBG(cdev, "%s disabled\n", dev->function.name);
1195 }
1196
1197 static int mtp_bind_config(struct usb_configuration *c, bool ptp_config)
1198 {
1199         struct mtp_dev *dev = _mtp_dev;
1200         int ret = 0;
1201
1202         printk(KERN_INFO "mtp_bind_config\n");
1203
1204         /* allocate a string ID for our interface */
1205         if (mtp_string_defs[INTERFACE_STRING_INDEX].id == 0) {
1206                 ret = usb_string_id(c->cdev);
1207                 if (ret < 0)
1208                         return ret;
1209                 mtp_string_defs[INTERFACE_STRING_INDEX].id = ret;
1210                 mtp_interface_desc.iInterface = ret;
1211         }
1212
1213         dev->cdev = c->cdev;
1214         dev->function.name = "mtp";
1215         dev->function.strings = mtp_strings;
1216         if (ptp_config) {
1217                 dev->function.fs_descriptors = fs_ptp_descs;
1218                 dev->function.hs_descriptors = hs_ptp_descs;
1219         } else {
1220                 dev->function.fs_descriptors = fs_mtp_descs;
1221                 dev->function.hs_descriptors = hs_mtp_descs;
1222         }
1223         dev->function.bind = mtp_function_bind;
1224         dev->function.unbind = mtp_function_unbind;
1225         dev->function.set_alt = mtp_function_set_alt;
1226         dev->function.disable = mtp_function_disable;
1227
1228         return usb_add_function(c, &dev->function);
1229 }
1230
1231 static int mtp_setup(void)
1232 {
1233         struct mtp_dev *dev;
1234         int ret;
1235
1236         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1237         if (!dev)
1238                 return -ENOMEM;
1239
1240         spin_lock_init(&dev->lock);
1241         init_waitqueue_head(&dev->read_wq);
1242         init_waitqueue_head(&dev->write_wq);
1243         init_waitqueue_head(&dev->intr_wq);
1244         atomic_set(&dev->open_excl, 0);
1245         atomic_set(&dev->ioctl_excl, 0);
1246         INIT_LIST_HEAD(&dev->tx_idle);
1247         INIT_LIST_HEAD(&dev->intr_idle);
1248
1249         dev->wq = create_singlethread_workqueue("f_mtp");
1250         if (!dev->wq) {
1251                 ret = -ENOMEM;
1252                 goto err1;
1253         }
1254         INIT_WORK(&dev->send_file_work, send_file_work);
1255         INIT_WORK(&dev->receive_file_work, receive_file_work);
1256
1257         _mtp_dev = dev;
1258
1259         ret = misc_register(&mtp_device);
1260         if (ret)
1261                 goto err2;
1262
1263         return 0;
1264
1265 err2:
1266         destroy_workqueue(dev->wq);
1267 err1:
1268         _mtp_dev = NULL;
1269         kfree(dev);
1270         printk(KERN_ERR "mtp gadget driver failed to initialize\n");
1271         return ret;
1272 }
1273
1274 static void mtp_cleanup(void)
1275 {
1276         struct mtp_dev *dev = _mtp_dev;
1277
1278         if (!dev)
1279                 return;
1280
1281         misc_deregister(&mtp_device);
1282         destroy_workqueue(dev->wq);
1283         _mtp_dev = NULL;
1284         kfree(dev);
1285 }