rk: temp revert rk change
[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 /* temporary variable used between mtp_open() and mtp_gadget_bind() */
273 static struct mtp_dev *_mtp_dev;
274
275 static inline struct mtp_dev *func_to_mtp(struct usb_function *f)
276 {
277         return container_of(f, struct mtp_dev, function);
278 }
279
280 static struct usb_request *mtp_request_new(struct usb_ep *ep, int buffer_size)
281 {
282         struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
283         if (!req)
284                 return NULL;
285
286         /* now allocate buffers for the requests */
287         req->buf = kmalloc(buffer_size, GFP_KERNEL);
288         if (!req->buf) {
289                 usb_ep_free_request(ep, req);
290                 return NULL;
291         }
292
293         return req;
294 }
295
296 static void mtp_request_free(struct usb_request *req, struct usb_ep *ep)
297 {
298         if (req) {
299                 kfree(req->buf);
300                 usb_ep_free_request(ep, req);
301         }
302 }
303
304 static inline int mtp_lock(atomic_t *excl)
305 {
306         if (atomic_inc_return(excl) == 1) {
307                 return 0;
308         } else {
309                 atomic_dec(excl);
310                 return -1;
311         }
312 }
313
314 static inline void mtp_unlock(atomic_t *excl)
315 {
316         atomic_dec(excl);
317 }
318
319 /* add a request to the tail of a list */
320 static void mtp_req_put(struct mtp_dev *dev, struct list_head *head,
321                 struct usb_request *req)
322 {
323         unsigned long flags;
324
325         spin_lock_irqsave(&dev->lock, flags);
326         list_add_tail(&req->list, head);
327         spin_unlock_irqrestore(&dev->lock, flags);
328 }
329
330 /* remove a request from the head of a list */
331 static struct usb_request
332 *mtp_req_get(struct mtp_dev *dev, struct list_head *head)
333 {
334         unsigned long flags;
335         struct usb_request *req;
336
337         spin_lock_irqsave(&dev->lock, flags);
338         if (list_empty(head)) {
339                 req = 0;
340         } else {
341                 req = list_first_entry(head, struct usb_request, list);
342                 list_del(&req->list);
343         }
344         spin_unlock_irqrestore(&dev->lock, flags);
345         return req;
346 }
347
348 static void mtp_complete_in(struct usb_ep *ep, struct usb_request *req)
349 {
350         struct mtp_dev *dev = _mtp_dev;
351
352         if (req->status != 0)
353                 dev->state = STATE_ERROR;
354
355         mtp_req_put(dev, &dev->tx_idle, req);
356
357         wake_up(&dev->write_wq);
358 }
359
360 static void mtp_complete_out(struct usb_ep *ep, struct usb_request *req)
361 {
362         struct mtp_dev *dev = _mtp_dev;
363
364         dev->rx_done = 1;
365         if (req->status != 0)
366                 dev->state = STATE_ERROR;
367
368         wake_up(&dev->read_wq);
369 }
370
371 static void mtp_complete_intr(struct usb_ep *ep, struct usb_request *req)
372 {
373         struct mtp_dev *dev = _mtp_dev;
374
375         if (req->status != 0)
376                 dev->state = STATE_ERROR;
377
378         mtp_req_put(dev, &dev->intr_idle, req);
379
380         wake_up(&dev->intr_wq);
381 }
382
383 static int mtp_create_bulk_endpoints(struct mtp_dev *dev,
384                                 struct usb_endpoint_descriptor *in_desc,
385                                 struct usb_endpoint_descriptor *out_desc,
386                                 struct usb_endpoint_descriptor *intr_desc)
387 {
388         struct usb_composite_dev *cdev = dev->cdev;
389         struct usb_request *req;
390         struct usb_ep *ep;
391         int i;
392
393         DBG(cdev, "create_bulk_endpoints dev: %p\n", dev);
394
395         ep = usb_ep_autoconfig(cdev->gadget, in_desc);
396         if (!ep) {
397                 DBG(cdev, "usb_ep_autoconfig for ep_in failed\n");
398                 return -ENODEV;
399         }
400         DBG(cdev, "usb_ep_autoconfig for ep_in got %s\n", ep->name);
401         ep->driver_data = dev;          /* claim the endpoint */
402         dev->ep_in = ep;
403
404         ep = usb_ep_autoconfig(cdev->gadget, out_desc);
405         if (!ep) {
406                 DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
407                 return -ENODEV;
408         }
409         DBG(cdev, "usb_ep_autoconfig for mtp ep_out got %s\n", ep->name);
410         ep->driver_data = dev;          /* claim the endpoint */
411         dev->ep_out = ep;
412
413         ep = usb_ep_autoconfig(cdev->gadget, out_desc);
414         if (!ep) {
415                 DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
416                 return -ENODEV;
417         }
418         DBG(cdev, "usb_ep_autoconfig for mtp ep_out got %s\n", ep->name);
419         ep->driver_data = dev;          /* claim the endpoint */
420         dev->ep_out = ep;
421
422         ep = usb_ep_autoconfig(cdev->gadget, intr_desc);
423         if (!ep) {
424                 DBG(cdev, "usb_ep_autoconfig for ep_intr failed\n");
425                 return -ENODEV;
426         }
427         DBG(cdev, "usb_ep_autoconfig for mtp ep_intr got %s\n", ep->name);
428         ep->driver_data = dev;          /* claim the endpoint */
429         dev->ep_intr = ep;
430
431         /* now allocate requests for our endpoints */
432         for (i = 0; i < TX_REQ_MAX; i++) {
433                 req = mtp_request_new(dev->ep_in, MTP_BULK_BUFFER_SIZE);
434                 if (!req)
435                         goto fail;
436                 req->complete = mtp_complete_in;
437                 mtp_req_put(dev, &dev->tx_idle, req);
438         }
439         for (i = 0; i < RX_REQ_MAX; i++) {
440                 req = mtp_request_new(dev->ep_out, MTP_BULK_BUFFER_SIZE);
441                 if (!req)
442                         goto fail;
443                 req->complete = mtp_complete_out;
444                 dev->rx_req[i] = req;
445         }
446         for (i = 0; i < INTR_REQ_MAX; i++) {
447                 req = mtp_request_new(dev->ep_intr, INTR_BUFFER_SIZE);
448                 if (!req)
449                         goto fail;
450                 req->complete = mtp_complete_intr;
451                 mtp_req_put(dev, &dev->intr_idle, req);
452         }
453
454         return 0;
455
456 fail:
457         printk(KERN_ERR "mtp_bind() could not allocate requests\n");
458         return -1;
459 }
460
461 static ssize_t mtp_read(struct file *fp, char __user *buf,
462         size_t count, loff_t *pos)
463 {
464         struct mtp_dev *dev = fp->private_data;
465         struct usb_composite_dev *cdev = dev->cdev;
466         struct usb_request *req;
467         int r = count, xfer;
468         int ret = 0;
469
470         DBG(cdev, "mtp_read(%d)\n", count);
471
472         if (count > MTP_BULK_BUFFER_SIZE)
473                 return -EINVAL;
474
475         /* we will block until we're online */
476         DBG(cdev, "mtp_read: waiting for online state\n");
477         ret = wait_event_interruptible(dev->read_wq,
478                 dev->state != STATE_OFFLINE);
479         if (ret < 0) {
480                 r = ret;
481                 goto done;
482         }
483         spin_lock_irq(&dev->lock);
484         if (dev->state == STATE_CANCELED) {
485                 /* report cancelation to userspace */
486                 dev->state = STATE_READY;
487                 spin_unlock_irq(&dev->lock);
488                 return -ECANCELED;
489         }
490         dev->state = STATE_BUSY;
491         spin_unlock_irq(&dev->lock);
492
493 requeue_req:
494         /* queue a request */
495         req = dev->rx_req[0];
496         req->length = count;
497         dev->rx_done = 0;
498         ret = usb_ep_queue(dev->ep_out, req, GFP_KERNEL);
499         if (ret < 0) {
500                 r = -EIO;
501                 goto done;
502         } else {
503                 DBG(cdev, "rx %p queue\n", req);
504         }
505
506         /* wait for a request to complete */
507         ret = wait_event_interruptible(dev->read_wq, dev->rx_done);
508         if (ret < 0) {
509                 r = ret;
510                 usb_ep_dequeue(dev->ep_out, req);
511                 goto done;
512         }
513         if (dev->state == STATE_BUSY) {
514                 /* If we got a 0-len packet, throw it back and try again. */
515                 if (req->actual == 0)
516                         goto requeue_req;
517
518                 DBG(cdev, "rx %p %d\n", req, req->actual);
519                 xfer = (req->actual < count) ? req->actual : count;
520                 r = xfer;
521                 if (copy_to_user(buf, req->buf, xfer))
522                         r = -EFAULT;
523         } else
524                 r = -EIO;
525
526 done:
527         spin_lock_irq(&dev->lock);
528         if (dev->state == STATE_CANCELED)
529                 r = -ECANCELED;
530         else if (dev->state != STATE_OFFLINE)
531                 dev->state = STATE_READY;
532         spin_unlock_irq(&dev->lock);
533
534         DBG(cdev, "mtp_read returning %d\n", r);
535         return r;
536 }
537
538 static ssize_t mtp_write(struct file *fp, const char __user *buf,
539         size_t count, loff_t *pos)
540 {
541         struct mtp_dev *dev = fp->private_data;
542         struct usb_composite_dev *cdev = dev->cdev;
543         struct usb_request *req = 0;
544         int r = count, xfer;
545         int sendZLP = 0;
546         int ret;
547
548         DBG(cdev, "mtp_write(%d)\n", count);
549
550         spin_lock_irq(&dev->lock);
551         if (dev->state == STATE_CANCELED) {
552                 /* report cancelation to userspace */
553                 dev->state = STATE_READY;
554                 spin_unlock_irq(&dev->lock);
555                 return -ECANCELED;
556         }
557         if (dev->state == STATE_OFFLINE) {
558                 spin_unlock_irq(&dev->lock);
559                 return -ENODEV;
560         }
561         dev->state = STATE_BUSY;
562         spin_unlock_irq(&dev->lock);
563
564         /* we need to send a zero length packet to signal the end of transfer
565          * if the transfer size is aligned to a packet boundary.
566          */
567         if ((count & (dev->ep_in->maxpacket - 1)) == 0) {
568                 sendZLP = 1;
569         }
570
571         while (count > 0 || sendZLP) {
572                 /* so we exit after sending ZLP */
573                 if (count == 0)
574                         sendZLP = 0;
575
576                 if (dev->state != STATE_BUSY) {
577                         DBG(cdev, "mtp_write dev->error\n");
578                         r = -EIO;
579                         break;
580                 }
581
582                 /* get an idle tx request to use */
583                 req = 0;
584                 ret = wait_event_interruptible(dev->write_wq,
585                         ((req = mtp_req_get(dev, &dev->tx_idle))
586                                 || dev->state != STATE_BUSY));
587                 if (!req) {
588                         r = ret;
589                         break;
590                 }
591
592                 if (count > MTP_BULK_BUFFER_SIZE)
593                         xfer = MTP_BULK_BUFFER_SIZE;
594                 else
595                         xfer = count;
596                 if (xfer && copy_from_user(req->buf, buf, xfer)) {
597                         r = -EFAULT;
598                         break;
599                 }
600
601                 req->length = xfer;
602                 ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
603                 if (ret < 0) {
604                         DBG(cdev, "mtp_write: xfer error %d\n", ret);
605                         r = -EIO;
606                         break;
607                 }
608
609                 buf += xfer;
610                 count -= xfer;
611
612                 /* zero this so we don't try to free it on error exit */
613                 req = 0;
614         }
615
616         if (req)
617                 mtp_req_put(dev, &dev->tx_idle, req);
618
619         spin_lock_irq(&dev->lock);
620         if (dev->state == STATE_CANCELED)
621                 r = -ECANCELED;
622         else if (dev->state != STATE_OFFLINE)
623                 dev->state = STATE_READY;
624         spin_unlock_irq(&dev->lock);
625
626         DBG(cdev, "mtp_write returning %d\n", r);
627         return r;
628 }
629
630 /* read from a local file and write to USB */
631 static void send_file_work(struct work_struct *data) {
632         struct mtp_dev  *dev = container_of(data, struct mtp_dev, send_file_work);
633         struct usb_composite_dev *cdev = dev->cdev;
634         struct usb_request *req = 0;
635         struct mtp_data_header *header;
636         struct file *filp;
637         loff_t offset;
638         int64_t count;
639         int xfer, ret, hdr_size;
640         int r = 0;
641         int sendZLP = 0;
642
643         /* read our parameters */
644         smp_rmb();
645         filp = dev->xfer_file;
646         offset = dev->xfer_file_offset;
647         count = dev->xfer_file_length;
648
649         DBG(cdev, "send_file_work(%lld %lld)\n", offset, count);
650
651         if (dev->xfer_send_header) {
652                 hdr_size = sizeof(struct mtp_data_header);
653                 count += hdr_size;
654         } else {
655                 hdr_size = 0;
656         }
657
658         /* we need to send a zero length packet to signal the end of transfer
659          * if the transfer size is aligned to a packet boundary.
660          */
661         if ((count & (dev->ep_in->maxpacket - 1)) == 0) {
662                 sendZLP = 1;
663         }
664
665         while (count > 0 || sendZLP) {
666                 /* so we exit after sending ZLP */
667                 if (count == 0)
668                         sendZLP = 0;
669
670                 /* get an idle tx request to use */
671                 req = 0;
672                 ret = wait_event_interruptible(dev->write_wq,
673                         (req = mtp_req_get(dev, &dev->tx_idle))
674                         || dev->state != STATE_BUSY);
675                 if (dev->state == STATE_CANCELED) {
676                         r = -ECANCELED;
677                         break;
678                 }
679                 if (!req) {
680                         r = ret;
681                         break;
682                 }
683
684                 if (count > MTP_BULK_BUFFER_SIZE)
685                         xfer = MTP_BULK_BUFFER_SIZE;
686                 else
687                         xfer = count;
688
689                 if (hdr_size) {
690                         /* prepend MTP data header */
691                         header = (struct mtp_data_header *)req->buf;
692                         header->length = __cpu_to_le32(count);
693                         header->type = __cpu_to_le16(2); /* data packet */
694                         header->command = __cpu_to_le16(dev->xfer_command);
695                         header->transaction_id = __cpu_to_le32(dev->xfer_transaction_id);
696                 }
697
698                 ret = vfs_read(filp, req->buf + hdr_size, xfer - hdr_size, &offset);
699                 if (ret < 0) {
700                         r = ret;
701                         break;
702                 }
703                 xfer = ret + hdr_size;
704                 hdr_size = 0;
705
706                 req->length = xfer;
707                 ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
708                 if (ret < 0) {
709                         DBG(cdev, "send_file_work: xfer error %d\n", ret);
710                         dev->state = STATE_ERROR;
711                         r = -EIO;
712                         break;
713                 }
714
715                 count -= xfer;
716
717                 /* zero this so we don't try to free it on error exit */
718                 req = 0;
719         }
720
721         if (req)
722                 mtp_req_put(dev, &dev->tx_idle, req);
723
724         DBG(cdev, "send_file_work returning %d\n", r);
725         /* write the result */
726         dev->xfer_result = r;
727         smp_wmb();
728 }
729
730 /* read from USB and write to a local file */
731 static void receive_file_work(struct work_struct *data)
732 {
733         struct mtp_dev  *dev = container_of(data, struct mtp_dev, receive_file_work);
734         struct usb_composite_dev *cdev = dev->cdev;
735         struct usb_request *read_req = NULL, *write_req = NULL;
736         struct file *filp;
737         loff_t offset;
738         int64_t count;
739         int ret, cur_buf = 0;
740         int r = 0;
741
742         /* read our parameters */
743         smp_rmb();
744         filp = dev->xfer_file;
745         offset = dev->xfer_file_offset;
746         count = dev->xfer_file_length;
747
748         DBG(cdev, "receive_file_work(%lld)\n", count);
749
750         while (count > 0 || write_req) {
751                 if (count > 0) {
752                         /* queue a request */
753                         read_req = dev->rx_req[cur_buf];
754                         cur_buf = (cur_buf + 1) % RX_REQ_MAX;
755
756                         read_req->length = (count > MTP_BULK_BUFFER_SIZE
757                                         ? MTP_BULK_BUFFER_SIZE : count);
758                         dev->rx_done = 0;
759                         ret = usb_ep_queue(dev->ep_out, read_req, GFP_KERNEL);
760                         if (ret < 0) {
761                                 r = -EIO;
762                                 dev->state = STATE_ERROR;
763                                 break;
764                         }
765                 }
766
767                 if (write_req) {
768                         DBG(cdev, "rx %p %d\n", write_req, write_req->actual);
769                         ret = vfs_write(filp, write_req->buf, write_req->actual,
770                                 &offset);
771                         DBG(cdev, "vfs_write %d\n", ret);
772                         if (ret != write_req->actual) {
773                                 r = -EIO;
774                                 dev->state = STATE_ERROR;
775                                 break;
776                         }
777                         write_req = NULL;
778                 }
779
780                 if (read_req) {
781                         /* wait for our last read to complete */
782                         ret = wait_event_interruptible(dev->read_wq,
783                                 dev->rx_done || dev->state != STATE_BUSY);
784                         if (dev->state == STATE_CANCELED) {
785                                 r = -ECANCELED;
786                                 if (!dev->rx_done)
787                                         usb_ep_dequeue(dev->ep_out, read_req);
788                                 break;
789                         }
790                         /* if xfer_file_length is 0xFFFFFFFF, then we read until
791                          * we get a zero length packet
792                          */
793                         if (count != 0xFFFFFFFF)
794                                 count -= read_req->actual;
795                         if (read_req->actual < read_req->length) {
796                                 /* short packet is used to signal EOF for sizes > 4 gig */
797                                 DBG(cdev, "got short packet\n");
798                                 count = 0;
799                         }
800
801                         write_req = read_req;
802                         read_req = NULL;
803                 }
804         }
805
806         DBG(cdev, "receive_file_work returning %d\n", r);
807         /* write the result */
808         dev->xfer_result = r;
809         smp_wmb();
810 }
811
812 static int mtp_send_event(struct mtp_dev *dev, struct mtp_event *event)
813 {
814         struct usb_request *req= NULL;
815         int ret;
816         int length = event->length;
817
818         DBG(dev->cdev, "mtp_send_event(%d)\n", event->length);
819
820         if (length < 0 || length > INTR_BUFFER_SIZE)
821                 return -EINVAL;
822         if (dev->state == STATE_OFFLINE)
823                 return -ENODEV;
824
825         ret = wait_event_interruptible_timeout(dev->intr_wq,
826                 (req = mtp_req_get(dev, &dev->intr_idle)), msecs_to_jiffies(1000));
827         if (!req)
828             return -ETIME;
829
830         if (copy_from_user(req->buf, (void __user *)event->data, length)) {
831                 mtp_req_put(dev, &dev->intr_idle, req);
832                 return -EFAULT;
833         }
834         req->length = length;
835         ret = usb_ep_queue(dev->ep_intr, req, GFP_KERNEL);
836         if (ret)
837                 mtp_req_put(dev, &dev->intr_idle, req);
838
839         return ret;
840 }
841
842 static long mtp_ioctl(struct file *fp, unsigned code, unsigned long value)
843 {
844         struct mtp_dev *dev = fp->private_data;
845         struct file *filp = NULL;
846         int ret = -EINVAL;
847
848         if (mtp_lock(&dev->ioctl_excl))
849                 return -EBUSY;
850
851         switch (code) {
852         case MTP_SEND_FILE:
853         case MTP_RECEIVE_FILE:
854         case MTP_SEND_FILE_WITH_HEADER:
855         {
856                 struct mtp_file_range   mfr;
857                 struct work_struct *work;
858
859                 spin_lock_irq(&dev->lock);
860                 if (dev->state == STATE_CANCELED) {
861                         /* report cancelation to userspace */
862                         dev->state = STATE_READY;
863                         spin_unlock_irq(&dev->lock);
864                         ret = -ECANCELED;
865                         goto out;
866                 }
867                 if (dev->state == STATE_OFFLINE) {
868                         spin_unlock_irq(&dev->lock);
869                         ret = -ENODEV;
870                         goto out;
871                 }
872                 dev->state = STATE_BUSY;
873                 spin_unlock_irq(&dev->lock);
874
875                 if (copy_from_user(&mfr, (void __user *)value, sizeof(mfr))) {
876                         ret = -EFAULT;
877                         goto fail;
878                 }
879                 /* hold a reference to the file while we are working with it */
880                 filp = fget(mfr.fd);
881                 if (!filp) {
882                         ret = -EBADF;
883                         goto fail;
884                 }
885
886                 /* write the parameters */
887                 dev->xfer_file = filp;
888                 dev->xfer_file_offset = mfr.offset;
889                 dev->xfer_file_length = mfr.length;
890                 smp_wmb();
891
892                 if (code == MTP_SEND_FILE_WITH_HEADER) {
893                         work = &dev->send_file_work;
894                         dev->xfer_send_header = 1;
895                         dev->xfer_command = mfr.command;
896                         dev->xfer_transaction_id = mfr.transaction_id;
897                 } else if (code == MTP_SEND_FILE) {
898                         work = &dev->send_file_work;
899                         dev->xfer_send_header = 0;
900                 } else {
901                         work = &dev->receive_file_work;
902                 }
903
904                 /* We do the file transfer on a work queue so it will run
905                  * in kernel context, which is necessary for vfs_read and
906                  * vfs_write to use our buffers in the kernel address space.
907                  */
908                 queue_work(dev->wq, work);
909                 /* wait for operation to complete */
910                 flush_workqueue(dev->wq);
911                 fput(filp);
912
913                 /* read the result */
914                 smp_rmb();
915                 ret = dev->xfer_result;
916                 break;
917         }
918         case MTP_SEND_EVENT:
919         {
920                 struct mtp_event        event;
921                 /* return here so we don't change dev->state below,
922                  * which would interfere with bulk transfer state.
923                  */
924                 if (copy_from_user(&event, (void __user *)value, sizeof(event)))
925                         ret = -EFAULT;
926                 else
927                         ret = mtp_send_event(dev, &event);
928                 goto out;
929         }
930         }
931
932 fail:
933         spin_lock_irq(&dev->lock);
934         if (dev->state == STATE_CANCELED)
935                 ret = -ECANCELED;
936         else if (dev->state != STATE_OFFLINE)
937                 dev->state = STATE_READY;
938         spin_unlock_irq(&dev->lock);
939 out:
940         mtp_unlock(&dev->ioctl_excl);
941         DBG(dev->cdev, "ioctl returning %d\n", ret);
942         return ret;
943 }
944
945 static int mtp_open(struct inode *ip, struct file *fp)
946 {
947         printk(KERN_INFO "mtp_open\n");
948         if (mtp_lock(&_mtp_dev->open_excl))
949                 return -EBUSY;
950
951         /* clear any error condition */
952         if (_mtp_dev->state != STATE_OFFLINE)
953                 _mtp_dev->state = STATE_READY;
954
955         fp->private_data = _mtp_dev;
956         return 0;
957 }
958
959 static int mtp_release(struct inode *ip, struct file *fp)
960 {
961         printk(KERN_INFO "mtp_release\n");
962
963         mtp_unlock(&_mtp_dev->open_excl);
964         return 0;
965 }
966
967 /* file operations for /dev/mtp_usb */
968 static const struct file_operations mtp_fops = {
969         .owner = THIS_MODULE,
970         .read = mtp_read,
971         .write = mtp_write,
972         .unlocked_ioctl = mtp_ioctl,
973         .open = mtp_open,
974         .release = mtp_release,
975 };
976
977 static struct miscdevice mtp_device = {
978         .minor = MISC_DYNAMIC_MINOR,
979         .name = mtp_shortname,
980         .fops = &mtp_fops,
981 };
982
983 static int mtp_ctrlrequest(struct usb_composite_dev *cdev,
984                                 const struct usb_ctrlrequest *ctrl)
985 {
986         struct mtp_dev *dev = _mtp_dev;
987         int     value = -EOPNOTSUPP;
988         u16     w_index = le16_to_cpu(ctrl->wIndex);
989         u16     w_value = le16_to_cpu(ctrl->wValue);
990         u16     w_length = le16_to_cpu(ctrl->wLength);
991         unsigned long   flags;
992
993         VDBG(cdev, "mtp_ctrlrequest "
994                         "%02x.%02x v%04x i%04x l%u\n",
995                         ctrl->bRequestType, ctrl->bRequest,
996                         w_value, w_index, w_length);
997
998         /* Handle MTP OS string */
999         if (ctrl->bRequestType ==
1000                         (USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE)
1001                         && ctrl->bRequest == USB_REQ_GET_DESCRIPTOR
1002                         && (w_value >> 8) == USB_DT_STRING
1003                         && (w_value & 0xFF) == MTP_OS_STRING_ID) {
1004                 value = (w_length < sizeof(mtp_os_string)
1005                                 ? w_length : sizeof(mtp_os_string));
1006                 memcpy(cdev->req->buf, mtp_os_string, value);
1007         } else if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_VENDOR) {
1008                 /* Handle MTP OS descriptor */
1009                 DBG(cdev, "vendor request: %d index: %d value: %d length: %d\n",
1010                         ctrl->bRequest, w_index, w_value, w_length);
1011
1012                 if (ctrl->bRequest == 1
1013                                 && (ctrl->bRequestType & USB_DIR_IN)
1014                                 && (w_index == 4 || w_index == 5)) {
1015                         value = (w_length < sizeof(mtp_ext_config_desc) ?
1016                                         w_length : sizeof(mtp_ext_config_desc));
1017                         memcpy(cdev->req->buf, &mtp_ext_config_desc, value);
1018                 }
1019         } else if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
1020                 DBG(cdev, "class request: %d index: %d value: %d length: %d\n",
1021                         ctrl->bRequest, w_index, w_value, w_length);
1022
1023                 if (ctrl->bRequest == MTP_REQ_CANCEL && w_index == 0
1024                                 && w_value == 0) {
1025                         DBG(cdev, "MTP_REQ_CANCEL\n");
1026
1027                         spin_lock_irqsave(&dev->lock, flags);
1028                         if (dev->state == STATE_BUSY) {
1029                                 dev->state = STATE_CANCELED;
1030                                 wake_up(&dev->read_wq);
1031                                 wake_up(&dev->write_wq);
1032                         }
1033                         spin_unlock_irqrestore(&dev->lock, flags);
1034
1035                         /* We need to queue a request to read the remaining
1036                          *  bytes, but we don't actually need to look at
1037                          * the contents.
1038                          */
1039                         value = w_length;
1040                 } else if (ctrl->bRequest == MTP_REQ_GET_DEVICE_STATUS
1041                                 && w_index == 0 && w_value == 0) {
1042                         struct mtp_device_status *status = cdev->req->buf;
1043                         status->wLength =
1044                                 __constant_cpu_to_le16(sizeof(*status));
1045
1046                         DBG(cdev, "MTP_REQ_GET_DEVICE_STATUS\n");
1047                         spin_lock_irqsave(&dev->lock, flags);
1048                         /* device status is "busy" until we report
1049                          * the cancelation to userspace
1050                          */
1051                         if (dev->state == STATE_CANCELED)
1052                                 status->wCode =
1053                                         __cpu_to_le16(MTP_RESPONSE_DEVICE_BUSY);
1054                         else
1055                                 status->wCode =
1056                                         __cpu_to_le16(MTP_RESPONSE_OK);
1057                         spin_unlock_irqrestore(&dev->lock, flags);
1058                         value = sizeof(*status);
1059                 }
1060         }
1061
1062         /* respond with data transfer or status phase? */
1063         if (value >= 0) {
1064                 int rc;
1065                 cdev->req->zero = value < w_length;
1066                 cdev->req->length = value;
1067                 rc = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
1068                 if (rc < 0)
1069                         ERROR(cdev, "%s setup response queue error\n", __func__);
1070         }
1071         return value;
1072 }
1073
1074 static int
1075 mtp_function_bind(struct usb_configuration *c, struct usb_function *f)
1076 {
1077         struct usb_composite_dev *cdev = c->cdev;
1078         struct mtp_dev  *dev = func_to_mtp(f);
1079         int                     id;
1080         int                     ret;
1081
1082         dev->cdev = cdev;
1083         DBG(cdev, "mtp_function_bind dev: %p\n", dev);
1084
1085         /* allocate interface ID(s) */
1086         id = usb_interface_id(c, f);
1087         if (id < 0)
1088                 return id;
1089         mtp_interface_desc.bInterfaceNumber = id;
1090
1091         /* allocate endpoints */
1092         ret = mtp_create_bulk_endpoints(dev, &mtp_fullspeed_in_desc,
1093                         &mtp_fullspeed_out_desc, &mtp_intr_desc);
1094         if (ret)
1095                 return ret;
1096
1097         /* support high speed hardware */
1098         if (gadget_is_dualspeed(c->cdev->gadget)) {
1099                 mtp_highspeed_in_desc.bEndpointAddress =
1100                         mtp_fullspeed_in_desc.bEndpointAddress;
1101                 mtp_highspeed_out_desc.bEndpointAddress =
1102                         mtp_fullspeed_out_desc.bEndpointAddress;
1103         }
1104
1105         DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
1106                         gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1107                         f->name, dev->ep_in->name, dev->ep_out->name);
1108         return 0;
1109 }
1110
1111 static void
1112 mtp_function_unbind(struct usb_configuration *c, struct usb_function *f)
1113 {
1114         struct mtp_dev  *dev = func_to_mtp(f);
1115         struct usb_request *req;
1116         int i;
1117
1118         while ((req = mtp_req_get(dev, &dev->tx_idle)))
1119                 mtp_request_free(req, dev->ep_in);
1120         for (i = 0; i < RX_REQ_MAX; i++)
1121                 mtp_request_free(dev->rx_req[i], dev->ep_out);
1122         while ((req = mtp_req_get(dev, &dev->intr_idle)))
1123                 mtp_request_free(req, dev->ep_intr);
1124         dev->state = STATE_OFFLINE;
1125 }
1126
1127 static int mtp_function_set_alt(struct usb_function *f,
1128                 unsigned intf, unsigned alt)
1129 {
1130         struct mtp_dev  *dev = func_to_mtp(f);
1131         struct usb_composite_dev *cdev = f->config->cdev;
1132         int ret;
1133
1134         DBG(cdev, "mtp_function_set_alt intf: %d alt: %d\n", intf, alt);
1135         ret = usb_ep_enable(dev->ep_in,
1136                         ep_choose(cdev->gadget,
1137                                 &mtp_highspeed_in_desc,
1138                                 &mtp_fullspeed_in_desc));
1139         if (ret)
1140                 return ret;
1141         ret = usb_ep_enable(dev->ep_out,
1142                         ep_choose(cdev->gadget,
1143                                 &mtp_highspeed_out_desc,
1144                                 &mtp_fullspeed_out_desc));
1145         if (ret) {
1146                 usb_ep_disable(dev->ep_in);
1147                 return ret;
1148         }
1149         ret = usb_ep_enable(dev->ep_intr, &mtp_intr_desc);
1150         if (ret) {
1151                 usb_ep_disable(dev->ep_out);
1152                 usb_ep_disable(dev->ep_in);
1153                 return ret;
1154         }
1155         dev->state = STATE_READY;
1156
1157         /* readers may be blocked waiting for us to go online */
1158         wake_up(&dev->read_wq);
1159         return 0;
1160 }
1161
1162 static void mtp_function_disable(struct usb_function *f)
1163 {
1164         struct mtp_dev  *dev = func_to_mtp(f);
1165         struct usb_composite_dev        *cdev = dev->cdev;
1166
1167         DBG(cdev, "mtp_function_disable\n");
1168         dev->state = STATE_OFFLINE;
1169         usb_ep_disable(dev->ep_in);
1170         usb_ep_disable(dev->ep_out);
1171         usb_ep_disable(dev->ep_intr);
1172
1173         /* readers may be blocked waiting for us to go online */
1174         wake_up(&dev->read_wq);
1175
1176         VDBG(cdev, "%s disabled\n", dev->function.name);
1177 }
1178
1179 static int mtp_bind_config(struct usb_configuration *c, bool ptp_config)
1180 {
1181         struct mtp_dev *dev = _mtp_dev;
1182         int ret = 0;
1183
1184         printk(KERN_INFO "mtp_bind_config\n");
1185
1186         /* allocate a string ID for our interface */
1187         if (mtp_string_defs[INTERFACE_STRING_INDEX].id == 0) {
1188                 ret = usb_string_id(c->cdev);
1189                 if (ret < 0)
1190                         return ret;
1191                 mtp_string_defs[INTERFACE_STRING_INDEX].id = ret;
1192                 mtp_interface_desc.iInterface = ret;
1193         }
1194
1195         dev->cdev = c->cdev;
1196         dev->function.name = "mtp";
1197         dev->function.strings = mtp_strings;
1198         if (ptp_config) {
1199                 dev->function.descriptors = fs_ptp_descs;
1200                 dev->function.hs_descriptors = hs_ptp_descs;
1201         } else {
1202                 dev->function.descriptors = fs_mtp_descs;
1203                 dev->function.hs_descriptors = hs_mtp_descs;
1204         }
1205         dev->function.bind = mtp_function_bind;
1206         dev->function.unbind = mtp_function_unbind;
1207         dev->function.set_alt = mtp_function_set_alt;
1208         dev->function.disable = mtp_function_disable;
1209
1210         return usb_add_function(c, &dev->function);
1211 }
1212
1213 static int mtp_setup(void)
1214 {
1215         struct mtp_dev *dev;
1216         int ret;
1217
1218         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1219         if (!dev)
1220                 return -ENOMEM;
1221
1222         spin_lock_init(&dev->lock);
1223         init_waitqueue_head(&dev->read_wq);
1224         init_waitqueue_head(&dev->write_wq);
1225         init_waitqueue_head(&dev->intr_wq);
1226         atomic_set(&dev->open_excl, 0);
1227         atomic_set(&dev->ioctl_excl, 0);
1228         INIT_LIST_HEAD(&dev->tx_idle);
1229         INIT_LIST_HEAD(&dev->intr_idle);
1230
1231         dev->wq = create_singlethread_workqueue("f_mtp");
1232         if (!dev->wq) {
1233                 ret = -ENOMEM;
1234                 goto err1;
1235         }
1236         INIT_WORK(&dev->send_file_work, send_file_work);
1237         INIT_WORK(&dev->receive_file_work, receive_file_work);
1238
1239         _mtp_dev = dev;
1240
1241         ret = misc_register(&mtp_device);
1242         if (ret)
1243                 goto err2;
1244
1245         return 0;
1246
1247 err2:
1248         destroy_workqueue(dev->wq);
1249 err1:
1250         _mtp_dev = NULL;
1251         kfree(dev);
1252         printk(KERN_ERR "mtp gadget driver failed to initialize\n");
1253         return ret;
1254 }
1255
1256 static void mtp_cleanup(void)
1257 {
1258         struct mtp_dev *dev = _mtp_dev;
1259
1260         if (!dev)
1261                 return;
1262
1263         misc_deregister(&mtp_device);
1264         destroy_workqueue(dev->wq);
1265         _mtp_dev = NULL;
1266         kfree(dev);
1267 }