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