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