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