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