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