xref: /linux-6.15/drivers/usb/gadget/function/f_uvc.c (revision 4e8a720e)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *	uvc_gadget.c  --  USB Video Class Gadget driver
4  *
5  *	Copyright (C) 2009-2010
6  *	    Laurent Pinchart ([email protected])
7  */
8 
9 #include <linux/device.h>
10 #include <linux/errno.h>
11 #include <linux/fs.h>
12 #include <linux/kernel.h>
13 #include <linux/list.h>
14 #include <linux/module.h>
15 #include <linux/mutex.h>
16 #include <linux/string.h>
17 #include <linux/usb/ch9.h>
18 #include <linux/usb/gadget.h>
19 #include <linux/usb/g_uvc.h>
20 #include <linux/usb/video.h>
21 #include <linux/vmalloc.h>
22 #include <linux/wait.h>
23 
24 #include <media/v4l2-dev.h>
25 #include <media/v4l2-event.h>
26 
27 #include "uvc.h"
28 #include "uvc_configfs.h"
29 #include "uvc_v4l2.h"
30 #include "uvc_video.h"
31 
32 unsigned int uvc_gadget_trace_param;
33 module_param_named(trace, uvc_gadget_trace_param, uint, 0644);
34 MODULE_PARM_DESC(trace, "Trace level bitmask");
35 
36 /* --------------------------------------------------------------------------
37  * Function descriptors
38  */
39 
40 /* string IDs are assigned dynamically */
41 
42 static struct usb_string uvc_en_us_strings[] = {
43 	/* [UVC_STRING_CONTROL_IDX].s = DYNAMIC, */
44 	[UVC_STRING_STREAMING_IDX].s = "Video Streaming",
45 	{  }
46 };
47 
48 static struct usb_gadget_strings uvc_stringtab = {
49 	.language = 0x0409,	/* en-us */
50 	.strings = uvc_en_us_strings,
51 };
52 
53 static struct usb_gadget_strings *uvc_function_strings[] = {
54 	&uvc_stringtab,
55 	NULL,
56 };
57 
58 #define UVC_INTF_VIDEO_CONTROL			0
59 #define UVC_INTF_VIDEO_STREAMING		1
60 
61 #define UVC_STATUS_MAX_PACKET_SIZE		16	/* 16 bytes status */
62 
63 static struct usb_interface_assoc_descriptor uvc_iad = {
64 	.bLength		= sizeof(uvc_iad),
65 	.bDescriptorType	= USB_DT_INTERFACE_ASSOCIATION,
66 	.bFirstInterface	= 0,
67 	.bInterfaceCount	= 2,
68 	.bFunctionClass		= USB_CLASS_VIDEO,
69 	.bFunctionSubClass	= UVC_SC_VIDEO_INTERFACE_COLLECTION,
70 	.bFunctionProtocol	= 0x00,
71 	.iFunction		= 0,
72 };
73 
74 static struct usb_interface_descriptor uvc_control_intf = {
75 	.bLength		= USB_DT_INTERFACE_SIZE,
76 	.bDescriptorType	= USB_DT_INTERFACE,
77 	.bInterfaceNumber	= UVC_INTF_VIDEO_CONTROL,
78 	.bAlternateSetting	= 0,
79 	.bNumEndpoints		= 0,
80 	.bInterfaceClass	= USB_CLASS_VIDEO,
81 	.bInterfaceSubClass	= UVC_SC_VIDEOCONTROL,
82 	.bInterfaceProtocol	= 0x00,
83 	.iInterface		= 0,
84 };
85 
86 static struct usb_endpoint_descriptor uvc_interrupt_ep = {
87 	.bLength		= USB_DT_ENDPOINT_SIZE,
88 	.bDescriptorType	= USB_DT_ENDPOINT,
89 	.bEndpointAddress	= USB_DIR_IN,
90 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
91 	.wMaxPacketSize		= cpu_to_le16(UVC_STATUS_MAX_PACKET_SIZE),
92 	.bInterval		= 8,
93 };
94 
95 static struct usb_ss_ep_comp_descriptor uvc_ss_interrupt_comp = {
96 	.bLength		= sizeof(uvc_ss_interrupt_comp),
97 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
98 	/* The following 3 values can be tweaked if necessary. */
99 	.bMaxBurst		= 0,
100 	.bmAttributes		= 0,
101 	.wBytesPerInterval	= cpu_to_le16(UVC_STATUS_MAX_PACKET_SIZE),
102 };
103 
104 static struct uvc_control_endpoint_descriptor uvc_interrupt_cs_ep = {
105 	.bLength		= UVC_DT_CONTROL_ENDPOINT_SIZE,
106 	.bDescriptorType	= USB_DT_CS_ENDPOINT,
107 	.bDescriptorSubType	= UVC_EP_INTERRUPT,
108 	.wMaxTransferSize	= cpu_to_le16(UVC_STATUS_MAX_PACKET_SIZE),
109 };
110 
111 static struct usb_interface_descriptor uvc_streaming_intf_alt0 = {
112 	.bLength		= USB_DT_INTERFACE_SIZE,
113 	.bDescriptorType	= USB_DT_INTERFACE,
114 	.bInterfaceNumber	= UVC_INTF_VIDEO_STREAMING,
115 	.bAlternateSetting	= 0,
116 	.bNumEndpoints		= 0,
117 	.bInterfaceClass	= USB_CLASS_VIDEO,
118 	.bInterfaceSubClass	= UVC_SC_VIDEOSTREAMING,
119 	.bInterfaceProtocol	= 0x00,
120 	.iInterface		= 0,
121 };
122 
123 static struct usb_interface_descriptor uvc_streaming_intf_alt1 = {
124 	.bLength		= USB_DT_INTERFACE_SIZE,
125 	.bDescriptorType	= USB_DT_INTERFACE,
126 	.bInterfaceNumber	= UVC_INTF_VIDEO_STREAMING,
127 	.bAlternateSetting	= 1,
128 	.bNumEndpoints		= 1,
129 	.bInterfaceClass	= USB_CLASS_VIDEO,
130 	.bInterfaceSubClass	= UVC_SC_VIDEOSTREAMING,
131 	.bInterfaceProtocol	= 0x00,
132 	.iInterface		= 0,
133 };
134 
135 static struct usb_endpoint_descriptor uvc_fs_streaming_ep = {
136 	.bLength		= USB_DT_ENDPOINT_SIZE,
137 	.bDescriptorType	= USB_DT_ENDPOINT,
138 	.bEndpointAddress	= USB_DIR_IN,
139 	.bmAttributes		= USB_ENDPOINT_SYNC_ASYNC
140 				| USB_ENDPOINT_XFER_ISOC,
141 	/*
142 	 * The wMaxPacketSize and bInterval values will be initialized from
143 	 * module parameters.
144 	 */
145 };
146 
147 static struct usb_endpoint_descriptor uvc_hs_streaming_ep = {
148 	.bLength		= USB_DT_ENDPOINT_SIZE,
149 	.bDescriptorType	= USB_DT_ENDPOINT,
150 	.bEndpointAddress	= USB_DIR_IN,
151 	.bmAttributes		= USB_ENDPOINT_SYNC_ASYNC
152 				| USB_ENDPOINT_XFER_ISOC,
153 	/*
154 	 * The wMaxPacketSize and bInterval values will be initialized from
155 	 * module parameters.
156 	 */
157 };
158 
159 static struct usb_endpoint_descriptor uvc_ss_streaming_ep = {
160 	.bLength		= USB_DT_ENDPOINT_SIZE,
161 	.bDescriptorType	= USB_DT_ENDPOINT,
162 
163 	.bEndpointAddress	= USB_DIR_IN,
164 	.bmAttributes		= USB_ENDPOINT_SYNC_ASYNC
165 				| USB_ENDPOINT_XFER_ISOC,
166 	/*
167 	 * The wMaxPacketSize and bInterval values will be initialized from
168 	 * module parameters.
169 	 */
170 };
171 
172 static struct usb_ss_ep_comp_descriptor uvc_ss_streaming_comp = {
173 	.bLength		= sizeof(uvc_ss_streaming_comp),
174 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
175 	/*
176 	 * The bMaxBurst, bmAttributes and wBytesPerInterval values will be
177 	 * initialized from module parameters.
178 	 */
179 };
180 
181 static const struct usb_descriptor_header * const uvc_fs_streaming[] = {
182 	(struct usb_descriptor_header *) &uvc_streaming_intf_alt1,
183 	(struct usb_descriptor_header *) &uvc_fs_streaming_ep,
184 	NULL,
185 };
186 
187 static const struct usb_descriptor_header * const uvc_hs_streaming[] = {
188 	(struct usb_descriptor_header *) &uvc_streaming_intf_alt1,
189 	(struct usb_descriptor_header *) &uvc_hs_streaming_ep,
190 	NULL,
191 };
192 
193 static const struct usb_descriptor_header * const uvc_ss_streaming[] = {
194 	(struct usb_descriptor_header *) &uvc_streaming_intf_alt1,
195 	(struct usb_descriptor_header *) &uvc_ss_streaming_ep,
196 	(struct usb_descriptor_header *) &uvc_ss_streaming_comp,
197 	NULL,
198 };
199 
200 /* --------------------------------------------------------------------------
201  * Control requests
202  */
203 
204 static void
205 uvc_function_ep0_complete(struct usb_ep *ep, struct usb_request *req)
206 {
207 	struct uvc_device *uvc = req->context;
208 	struct v4l2_event v4l2_event;
209 	struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
210 
211 	if (uvc->event_setup_out) {
212 		uvc->event_setup_out = 0;
213 
214 		memset(&v4l2_event, 0, sizeof(v4l2_event));
215 		v4l2_event.type = UVC_EVENT_DATA;
216 		uvc_event->data.length = min_t(unsigned int, req->actual,
217 			sizeof(uvc_event->data.data));
218 		memcpy(&uvc_event->data.data, req->buf, uvc_event->data.length);
219 		v4l2_event_queue(&uvc->vdev, &v4l2_event);
220 	}
221 }
222 
223 static int
224 uvc_function_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
225 {
226 	struct uvc_device *uvc = to_uvc(f);
227 	struct v4l2_event v4l2_event;
228 	struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
229 	unsigned int interface = le16_to_cpu(ctrl->wIndex) & 0xff;
230 	struct usb_ctrlrequest *mctrl;
231 
232 	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_CLASS) {
233 		uvcg_info(f, "invalid request type\n");
234 		return -EINVAL;
235 	}
236 
237 	/* Stall too big requests. */
238 	if (le16_to_cpu(ctrl->wLength) > UVC_MAX_REQUEST_SIZE)
239 		return -EINVAL;
240 
241 	/*
242 	 * Tell the complete callback to generate an event for the next request
243 	 * that will be enqueued by UVCIOC_SEND_RESPONSE.
244 	 */
245 	uvc->event_setup_out = !(ctrl->bRequestType & USB_DIR_IN);
246 	uvc->event_length = le16_to_cpu(ctrl->wLength);
247 
248 	memset(&v4l2_event, 0, sizeof(v4l2_event));
249 	v4l2_event.type = UVC_EVENT_SETUP;
250 	memcpy(&uvc_event->req, ctrl, sizeof(uvc_event->req));
251 
252 	/* check for the interface number, fixup the interface number in
253 	 * the ctrl request so the userspace doesn't have to bother with
254 	 * offset and configfs parsing
255 	 */
256 	mctrl = &uvc_event->req;
257 	mctrl->wIndex &= ~cpu_to_le16(0xff);
258 	if (interface == uvc->streaming_intf)
259 		mctrl->wIndex = cpu_to_le16(UVC_STRING_STREAMING_IDX);
260 
261 	v4l2_event_queue(&uvc->vdev, &v4l2_event);
262 
263 	return 0;
264 }
265 
266 void uvc_function_setup_continue(struct uvc_device *uvc)
267 {
268 	struct usb_composite_dev *cdev = uvc->func.config->cdev;
269 
270 	usb_composite_setup_continue(cdev);
271 }
272 
273 static int
274 uvc_function_get_alt(struct usb_function *f, unsigned interface)
275 {
276 	struct uvc_device *uvc = to_uvc(f);
277 
278 	uvcg_info(f, "%s(%u)\n", __func__, interface);
279 
280 	if (interface == uvc->control_intf)
281 		return 0;
282 	else if (interface != uvc->streaming_intf)
283 		return -EINVAL;
284 	else
285 		return uvc->video.ep->enabled ? 1 : 0;
286 }
287 
288 static int
289 uvc_function_set_alt(struct usb_function *f, unsigned interface, unsigned alt)
290 {
291 	struct uvc_device *uvc = to_uvc(f);
292 	struct usb_composite_dev *cdev = f->config->cdev;
293 	struct v4l2_event v4l2_event;
294 	struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
295 	int ret;
296 
297 	uvcg_info(f, "%s(%u, %u)\n", __func__, interface, alt);
298 
299 	if (interface == uvc->control_intf) {
300 		if (alt)
301 			return -EINVAL;
302 
303 		if (uvc->enable_interrupt_ep) {
304 			uvcg_info(f, "reset UVC interrupt endpoint\n");
305 			usb_ep_disable(uvc->interrupt_ep);
306 
307 			if (!uvc->interrupt_ep->desc)
308 				if (config_ep_by_speed(cdev->gadget, f,
309 						       uvc->interrupt_ep))
310 					return -EINVAL;
311 
312 			usb_ep_enable(uvc->interrupt_ep);
313 		}
314 
315 		if (uvc->state == UVC_STATE_DISCONNECTED) {
316 			memset(&v4l2_event, 0, sizeof(v4l2_event));
317 			v4l2_event.type = UVC_EVENT_CONNECT;
318 			uvc_event->speed = cdev->gadget->speed;
319 			v4l2_event_queue(&uvc->vdev, &v4l2_event);
320 
321 			uvc->state = UVC_STATE_CONNECTED;
322 		}
323 
324 		return 0;
325 	}
326 
327 	if (interface != uvc->streaming_intf)
328 		return -EINVAL;
329 
330 	/* TODO
331 	if (usb_endpoint_xfer_bulk(&uvc->desc.vs_ep))
332 		return alt ? -EINVAL : 0;
333 	*/
334 
335 	switch (alt) {
336 	case 0:
337 		if (uvc->state != UVC_STATE_STREAMING)
338 			return 0;
339 
340 		if (uvc->video.ep)
341 			usb_ep_disable(uvc->video.ep);
342 
343 		memset(&v4l2_event, 0, sizeof(v4l2_event));
344 		v4l2_event.type = UVC_EVENT_STREAMOFF;
345 		v4l2_event_queue(&uvc->vdev, &v4l2_event);
346 
347 		uvc->state = UVC_STATE_CONNECTED;
348 		return 0;
349 
350 	case 1:
351 		if (uvc->state != UVC_STATE_CONNECTED)
352 			return 0;
353 
354 		if (!uvc->video.ep)
355 			return -EINVAL;
356 
357 		uvcg_info(f, "reset UVC\n");
358 		usb_ep_disable(uvc->video.ep);
359 
360 		ret = config_ep_by_speed(f->config->cdev->gadget,
361 				&(uvc->func), uvc->video.ep);
362 		if (ret)
363 			return ret;
364 		usb_ep_enable(uvc->video.ep);
365 
366 		memset(&v4l2_event, 0, sizeof(v4l2_event));
367 		v4l2_event.type = UVC_EVENT_STREAMON;
368 		v4l2_event_queue(&uvc->vdev, &v4l2_event);
369 		return USB_GADGET_DELAYED_STATUS;
370 
371 	default:
372 		return -EINVAL;
373 	}
374 }
375 
376 static void
377 uvc_function_disable(struct usb_function *f)
378 {
379 	struct uvc_device *uvc = to_uvc(f);
380 	struct v4l2_event v4l2_event;
381 
382 	uvcg_info(f, "%s()\n", __func__);
383 
384 	memset(&v4l2_event, 0, sizeof(v4l2_event));
385 	v4l2_event.type = UVC_EVENT_DISCONNECT;
386 	v4l2_event_queue(&uvc->vdev, &v4l2_event);
387 
388 	uvc->state = UVC_STATE_DISCONNECTED;
389 
390 	usb_ep_disable(uvc->video.ep);
391 	if (uvc->enable_interrupt_ep)
392 		usb_ep_disable(uvc->interrupt_ep);
393 }
394 
395 /* --------------------------------------------------------------------------
396  * Connection / disconnection
397  */
398 
399 void
400 uvc_function_connect(struct uvc_device *uvc)
401 {
402 	int ret;
403 
404 	if ((ret = usb_function_activate(&uvc->func)) < 0)
405 		uvcg_info(&uvc->func, "UVC connect failed with %d\n", ret);
406 }
407 
408 void
409 uvc_function_disconnect(struct uvc_device *uvc)
410 {
411 	int ret;
412 
413 	if ((ret = usb_function_deactivate(&uvc->func)) < 0)
414 		uvcg_info(&uvc->func, "UVC disconnect failed with %d\n", ret);
415 }
416 
417 /* --------------------------------------------------------------------------
418  * USB probe and disconnect
419  */
420 
421 static ssize_t function_name_show(struct device *dev,
422 				  struct device_attribute *attr, char *buf)
423 {
424 	struct uvc_device *uvc = dev_get_drvdata(dev);
425 
426 	return sprintf(buf, "%s\n", uvc->func.fi->group.cg_item.ci_name);
427 }
428 
429 static DEVICE_ATTR_RO(function_name);
430 
431 static int
432 uvc_register_video(struct uvc_device *uvc)
433 {
434 	struct usb_composite_dev *cdev = uvc->func.config->cdev;
435 	int ret;
436 
437 	/* TODO reference counting. */
438 	memset(&uvc->vdev, 0, sizeof(uvc->vdev));
439 	uvc->vdev.v4l2_dev = &uvc->v4l2_dev;
440 	uvc->vdev.v4l2_dev->dev = &cdev->gadget->dev;
441 	uvc->vdev.fops = &uvc_v4l2_fops;
442 	uvc->vdev.ioctl_ops = &uvc_v4l2_ioctl_ops;
443 	uvc->vdev.release = video_device_release_empty;
444 	uvc->vdev.vfl_dir = VFL_DIR_TX;
445 	uvc->vdev.lock = &uvc->video.mutex;
446 	uvc->vdev.device_caps = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
447 	strscpy(uvc->vdev.name, cdev->gadget->name, sizeof(uvc->vdev.name));
448 
449 	video_set_drvdata(&uvc->vdev, uvc);
450 
451 	ret = video_register_device(&uvc->vdev, VFL_TYPE_VIDEO, -1);
452 	if (ret < 0)
453 		return ret;
454 
455 	ret = device_create_file(&uvc->vdev.dev, &dev_attr_function_name);
456 	if (ret < 0) {
457 		video_unregister_device(&uvc->vdev);
458 		return ret;
459 	}
460 
461 	return 0;
462 }
463 
464 #define UVC_COPY_DESCRIPTOR(mem, dst, desc) \
465 	do { \
466 		memcpy(mem, desc, (desc)->bLength); \
467 		*(dst)++ = mem; \
468 		mem += (desc)->bLength; \
469 	} while (0);
470 
471 #define UVC_COPY_DESCRIPTORS(mem, dst, src) \
472 	do { \
473 		const struct usb_descriptor_header * const *__src; \
474 		for (__src = src; *__src; ++__src) { \
475 			memcpy(mem, *__src, (*__src)->bLength); \
476 			*dst++ = mem; \
477 			mem += (*__src)->bLength; \
478 		} \
479 	} while (0)
480 
481 static struct usb_descriptor_header **
482 uvc_copy_descriptors(struct uvc_device *uvc, enum usb_device_speed speed)
483 {
484 	struct uvc_input_header_descriptor *uvc_streaming_header;
485 	struct uvc_header_descriptor *uvc_control_header;
486 	const struct uvc_descriptor_header * const *uvc_control_desc;
487 	const struct uvc_descriptor_header * const *uvc_streaming_cls;
488 	const struct usb_descriptor_header * const *uvc_streaming_std;
489 	const struct usb_descriptor_header * const *src;
490 	struct usb_descriptor_header **dst;
491 	struct usb_descriptor_header **hdr;
492 	unsigned int control_size;
493 	unsigned int streaming_size;
494 	unsigned int n_desc;
495 	unsigned int bytes;
496 	void *mem;
497 
498 	switch (speed) {
499 	case USB_SPEED_SUPER:
500 		uvc_control_desc = uvc->desc.ss_control;
501 		uvc_streaming_cls = uvc->desc.ss_streaming;
502 		uvc_streaming_std = uvc_ss_streaming;
503 		break;
504 
505 	case USB_SPEED_HIGH:
506 		uvc_control_desc = uvc->desc.fs_control;
507 		uvc_streaming_cls = uvc->desc.hs_streaming;
508 		uvc_streaming_std = uvc_hs_streaming;
509 		break;
510 
511 	case USB_SPEED_FULL:
512 	default:
513 		uvc_control_desc = uvc->desc.fs_control;
514 		uvc_streaming_cls = uvc->desc.fs_streaming;
515 		uvc_streaming_std = uvc_fs_streaming;
516 		break;
517 	}
518 
519 	if (!uvc_control_desc || !uvc_streaming_cls)
520 		return ERR_PTR(-ENODEV);
521 
522 	/*
523 	 * Descriptors layout
524 	 *
525 	 * uvc_iad
526 	 * uvc_control_intf
527 	 * Class-specific UVC control descriptors
528 	 * uvc_interrupt_ep
529 	 * uvc_interrupt_cs_ep
530 	 * uvc_ss_interrupt_comp (for SS only)
531 	 * uvc_streaming_intf_alt0
532 	 * Class-specific UVC streaming descriptors
533 	 * uvc_{fs|hs}_streaming
534 	 */
535 
536 	/* Count descriptors and compute their size. */
537 	control_size = 0;
538 	streaming_size = 0;
539 	bytes = uvc_iad.bLength + uvc_control_intf.bLength
540 	      + uvc_streaming_intf_alt0.bLength;
541 
542 	n_desc = 3;
543 	if (uvc->enable_interrupt_ep) {
544 		bytes += uvc_interrupt_ep.bLength + uvc_interrupt_cs_ep.bLength;
545 		n_desc += 2;
546 
547 		if (speed == USB_SPEED_SUPER) {
548 			bytes += uvc_ss_interrupt_comp.bLength;
549 			n_desc += 1;
550 		}
551 	}
552 
553 	for (src = (const struct usb_descriptor_header **)uvc_control_desc;
554 	     *src; ++src) {
555 		control_size += (*src)->bLength;
556 		bytes += (*src)->bLength;
557 		n_desc++;
558 	}
559 	for (src = (const struct usb_descriptor_header **)uvc_streaming_cls;
560 	     *src; ++src) {
561 		streaming_size += (*src)->bLength;
562 		bytes += (*src)->bLength;
563 		n_desc++;
564 	}
565 	for (src = uvc_streaming_std; *src; ++src) {
566 		bytes += (*src)->bLength;
567 		n_desc++;
568 	}
569 
570 	mem = kmalloc((n_desc + 1) * sizeof(*src) + bytes, GFP_KERNEL);
571 	if (mem == NULL)
572 		return NULL;
573 
574 	hdr = mem;
575 	dst = mem;
576 	mem += (n_desc + 1) * sizeof(*src);
577 
578 	/* Copy the descriptors. */
579 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_iad);
580 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_intf);
581 
582 	uvc_control_header = mem;
583 	UVC_COPY_DESCRIPTORS(mem, dst,
584 		(const struct usb_descriptor_header **)uvc_control_desc);
585 	uvc_control_header->wTotalLength = cpu_to_le16(control_size);
586 	uvc_control_header->bInCollection = 1;
587 	uvc_control_header->baInterfaceNr[0] = uvc->streaming_intf;
588 
589 	if (uvc->enable_interrupt_ep) {
590 		UVC_COPY_DESCRIPTOR(mem, dst, &uvc_interrupt_ep);
591 		if (speed == USB_SPEED_SUPER)
592 			UVC_COPY_DESCRIPTOR(mem, dst, &uvc_ss_interrupt_comp);
593 
594 		UVC_COPY_DESCRIPTOR(mem, dst, &uvc_interrupt_cs_ep);
595 	}
596 
597 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_streaming_intf_alt0);
598 
599 	uvc_streaming_header = mem;
600 	UVC_COPY_DESCRIPTORS(mem, dst,
601 		(const struct usb_descriptor_header**)uvc_streaming_cls);
602 	uvc_streaming_header->wTotalLength = cpu_to_le16(streaming_size);
603 	uvc_streaming_header->bEndpointAddress = uvc->video.ep->address;
604 
605 	UVC_COPY_DESCRIPTORS(mem, dst, uvc_streaming_std);
606 
607 	*dst = NULL;
608 	return hdr;
609 }
610 
611 static int
612 uvc_function_bind(struct usb_configuration *c, struct usb_function *f)
613 {
614 	struct usb_composite_dev *cdev = c->cdev;
615 	struct uvc_device *uvc = to_uvc(f);
616 	struct usb_string *us;
617 	unsigned int max_packet_mult;
618 	unsigned int max_packet_size;
619 	struct usb_ep *ep;
620 	struct f_uvc_opts *opts;
621 	int ret = -EINVAL;
622 
623 	uvcg_info(f, "%s()\n", __func__);
624 
625 	opts = fi_to_f_uvc_opts(f->fi);
626 	/* Sanity check the streaming endpoint module parameters. */
627 	opts->streaming_interval = clamp(opts->streaming_interval, 1U, 16U);
628 	opts->streaming_maxpacket = clamp(opts->streaming_maxpacket, 1U, 3072U);
629 	opts->streaming_maxburst = min(opts->streaming_maxburst, 15U);
630 
631 	/* For SS, wMaxPacketSize has to be 1024 if bMaxBurst is not 0 */
632 	if (opts->streaming_maxburst &&
633 	    (opts->streaming_maxpacket % 1024) != 0) {
634 		opts->streaming_maxpacket = roundup(opts->streaming_maxpacket, 1024);
635 		uvcg_info(f, "overriding streaming_maxpacket to %d\n",
636 			  opts->streaming_maxpacket);
637 	}
638 
639 	/*
640 	 * Fill in the FS/HS/SS Video Streaming specific descriptors from the
641 	 * module parameters.
642 	 *
643 	 * NOTE: We assume that the user knows what they are doing and won't
644 	 * give parameters that their UDC doesn't support.
645 	 */
646 	if (opts->streaming_maxpacket <= 1024) {
647 		max_packet_mult = 1;
648 		max_packet_size = opts->streaming_maxpacket;
649 	} else if (opts->streaming_maxpacket <= 2048) {
650 		max_packet_mult = 2;
651 		max_packet_size = opts->streaming_maxpacket / 2;
652 	} else {
653 		max_packet_mult = 3;
654 		max_packet_size = opts->streaming_maxpacket / 3;
655 	}
656 
657 	uvc_fs_streaming_ep.wMaxPacketSize =
658 		cpu_to_le16(min(opts->streaming_maxpacket, 1023U));
659 	uvc_fs_streaming_ep.bInterval = opts->streaming_interval;
660 
661 	uvc_hs_streaming_ep.wMaxPacketSize =
662 		cpu_to_le16(max_packet_size | ((max_packet_mult - 1) << 11));
663 
664 	/* A high-bandwidth endpoint must specify a bInterval value of 1 */
665 	if (max_packet_mult > 1)
666 		uvc_hs_streaming_ep.bInterval = 1;
667 	else
668 		uvc_hs_streaming_ep.bInterval = opts->streaming_interval;
669 
670 	uvc_ss_streaming_ep.wMaxPacketSize = cpu_to_le16(max_packet_size);
671 	uvc_ss_streaming_ep.bInterval = opts->streaming_interval;
672 	uvc_ss_streaming_comp.bmAttributes = max_packet_mult - 1;
673 	uvc_ss_streaming_comp.bMaxBurst = opts->streaming_maxburst;
674 	uvc_ss_streaming_comp.wBytesPerInterval =
675 		cpu_to_le16(max_packet_size * max_packet_mult *
676 			    (opts->streaming_maxburst + 1));
677 
678 	/* Allocate endpoints. */
679 	if (opts->enable_interrupt_ep) {
680 		ep = usb_ep_autoconfig(cdev->gadget, &uvc_interrupt_ep);
681 		if (!ep) {
682 			uvcg_info(f, "Unable to allocate interrupt EP\n");
683 			goto error;
684 		}
685 		uvc->interrupt_ep = ep;
686 		uvc_control_intf.bNumEndpoints = 1;
687 	}
688 	uvc->enable_interrupt_ep = opts->enable_interrupt_ep;
689 
690 	if (gadget_is_superspeed(c->cdev->gadget))
691 		ep = usb_ep_autoconfig_ss(cdev->gadget, &uvc_ss_streaming_ep,
692 					  &uvc_ss_streaming_comp);
693 	else if (gadget_is_dualspeed(cdev->gadget))
694 		ep = usb_ep_autoconfig(cdev->gadget, &uvc_hs_streaming_ep);
695 	else
696 		ep = usb_ep_autoconfig(cdev->gadget, &uvc_fs_streaming_ep);
697 
698 	if (!ep) {
699 		uvcg_info(f, "Unable to allocate streaming EP\n");
700 		goto error;
701 	}
702 	uvc->video.ep = ep;
703 
704 	uvc_fs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
705 	uvc_hs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
706 	uvc_ss_streaming_ep.bEndpointAddress = uvc->video.ep->address;
707 
708 	uvc_en_us_strings[UVC_STRING_CONTROL_IDX].s = opts->function_name;
709 	us = usb_gstrings_attach(cdev, uvc_function_strings,
710 				 ARRAY_SIZE(uvc_en_us_strings));
711 	if (IS_ERR(us)) {
712 		ret = PTR_ERR(us);
713 		goto error;
714 	}
715 	uvc_iad.iFunction = us[UVC_STRING_CONTROL_IDX].id;
716 	uvc_control_intf.iInterface = us[UVC_STRING_CONTROL_IDX].id;
717 	ret = us[UVC_STRING_STREAMING_IDX].id;
718 	uvc_streaming_intf_alt0.iInterface = ret;
719 	uvc_streaming_intf_alt1.iInterface = ret;
720 
721 	/* Allocate interface IDs. */
722 	if ((ret = usb_interface_id(c, f)) < 0)
723 		goto error;
724 	uvc_iad.bFirstInterface = ret;
725 	uvc_control_intf.bInterfaceNumber = ret;
726 	uvc->control_intf = ret;
727 	opts->control_interface = ret;
728 
729 	if ((ret = usb_interface_id(c, f)) < 0)
730 		goto error;
731 	uvc_streaming_intf_alt0.bInterfaceNumber = ret;
732 	uvc_streaming_intf_alt1.bInterfaceNumber = ret;
733 	uvc->streaming_intf = ret;
734 	opts->streaming_interface = ret;
735 
736 	/* Copy descriptors */
737 	f->fs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_FULL);
738 	if (IS_ERR(f->fs_descriptors)) {
739 		ret = PTR_ERR(f->fs_descriptors);
740 		f->fs_descriptors = NULL;
741 		goto error;
742 	}
743 	if (gadget_is_dualspeed(cdev->gadget)) {
744 		f->hs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_HIGH);
745 		if (IS_ERR(f->hs_descriptors)) {
746 			ret = PTR_ERR(f->hs_descriptors);
747 			f->hs_descriptors = NULL;
748 			goto error;
749 		}
750 	}
751 	if (gadget_is_superspeed(c->cdev->gadget)) {
752 		f->ss_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_SUPER);
753 		if (IS_ERR(f->ss_descriptors)) {
754 			ret = PTR_ERR(f->ss_descriptors);
755 			f->ss_descriptors = NULL;
756 			goto error;
757 		}
758 	}
759 
760 	/* Preallocate control endpoint request. */
761 	uvc->control_req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
762 	uvc->control_buf = kmalloc(UVC_MAX_REQUEST_SIZE, GFP_KERNEL);
763 	if (uvc->control_req == NULL || uvc->control_buf == NULL) {
764 		ret = -ENOMEM;
765 		goto error;
766 	}
767 
768 	uvc->control_req->buf = uvc->control_buf;
769 	uvc->control_req->complete = uvc_function_ep0_complete;
770 	uvc->control_req->context = uvc;
771 
772 	if (v4l2_device_register(&cdev->gadget->dev, &uvc->v4l2_dev)) {
773 		uvcg_err(f, "failed to register V4L2 device\n");
774 		goto error;
775 	}
776 
777 	/* Initialise video. */
778 	ret = uvcg_video_init(&uvc->video, uvc);
779 	if (ret < 0)
780 		goto v4l2_error;
781 
782 	/* Register a V4L2 device. */
783 	ret = uvc_register_video(uvc);
784 	if (ret < 0) {
785 		uvcg_err(f, "failed to register video device\n");
786 		goto v4l2_error;
787 	}
788 
789 	return 0;
790 
791 v4l2_error:
792 	v4l2_device_unregister(&uvc->v4l2_dev);
793 error:
794 	if (uvc->control_req)
795 		usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
796 	kfree(uvc->control_buf);
797 
798 	usb_free_all_descriptors(f);
799 	return ret;
800 }
801 
802 /* --------------------------------------------------------------------------
803  * USB gadget function
804  */
805 
806 static void uvc_free_inst(struct usb_function_instance *f)
807 {
808 	struct f_uvc_opts *opts = fi_to_f_uvc_opts(f);
809 
810 	mutex_destroy(&opts->lock);
811 	kfree(opts);
812 }
813 
814 static struct usb_function_instance *uvc_alloc_inst(void)
815 {
816 	struct f_uvc_opts *opts;
817 	struct uvc_camera_terminal_descriptor *cd;
818 	struct uvc_processing_unit_descriptor *pd;
819 	struct uvc_output_terminal_descriptor *od;
820 	struct uvc_descriptor_header **ctl_cls;
821 	int ret;
822 
823 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
824 	if (!opts)
825 		return ERR_PTR(-ENOMEM);
826 	opts->func_inst.free_func_inst = uvc_free_inst;
827 	mutex_init(&opts->lock);
828 
829 	cd = &opts->uvc_camera_terminal;
830 	cd->bLength			= UVC_DT_CAMERA_TERMINAL_SIZE(3);
831 	cd->bDescriptorType		= USB_DT_CS_INTERFACE;
832 	cd->bDescriptorSubType		= UVC_VC_INPUT_TERMINAL;
833 	cd->bTerminalID			= 1;
834 	cd->wTerminalType		= cpu_to_le16(0x0201);
835 	cd->bAssocTerminal		= 0;
836 	cd->iTerminal			= 0;
837 	cd->wObjectiveFocalLengthMin	= cpu_to_le16(0);
838 	cd->wObjectiveFocalLengthMax	= cpu_to_le16(0);
839 	cd->wOcularFocalLength		= cpu_to_le16(0);
840 	cd->bControlSize		= 3;
841 	cd->bmControls[0]		= 2;
842 	cd->bmControls[1]		= 0;
843 	cd->bmControls[2]		= 0;
844 
845 	pd = &opts->uvc_processing;
846 	pd->bLength			= UVC_DT_PROCESSING_UNIT_SIZE(2);
847 	pd->bDescriptorType		= USB_DT_CS_INTERFACE;
848 	pd->bDescriptorSubType		= UVC_VC_PROCESSING_UNIT;
849 	pd->bUnitID			= 2;
850 	pd->bSourceID			= 1;
851 	pd->wMaxMultiplier		= cpu_to_le16(16*1024);
852 	pd->bControlSize		= 2;
853 	pd->bmControls[0]		= 1;
854 	pd->bmControls[1]		= 0;
855 	pd->iProcessing			= 0;
856 	pd->bmVideoStandards		= 0;
857 
858 	od = &opts->uvc_output_terminal;
859 	od->bLength			= UVC_DT_OUTPUT_TERMINAL_SIZE;
860 	od->bDescriptorType		= USB_DT_CS_INTERFACE;
861 	od->bDescriptorSubType		= UVC_VC_OUTPUT_TERMINAL;
862 	od->bTerminalID			= 3;
863 	od->wTerminalType		= cpu_to_le16(0x0101);
864 	od->bAssocTerminal		= 0;
865 	od->bSourceID			= 2;
866 	od->iTerminal			= 0;
867 
868 	/* Prepare fs control class descriptors for configfs-based gadgets */
869 	ctl_cls = opts->uvc_fs_control_cls;
870 	ctl_cls[0] = NULL;	/* assigned elsewhere by configfs */
871 	ctl_cls[1] = (struct uvc_descriptor_header *)cd;
872 	ctl_cls[2] = (struct uvc_descriptor_header *)pd;
873 	ctl_cls[3] = (struct uvc_descriptor_header *)od;
874 	ctl_cls[4] = NULL;	/* NULL-terminate */
875 	opts->fs_control =
876 		(const struct uvc_descriptor_header * const *)ctl_cls;
877 
878 	/* Prepare hs control class descriptors for configfs-based gadgets */
879 	ctl_cls = opts->uvc_ss_control_cls;
880 	ctl_cls[0] = NULL;	/* assigned elsewhere by configfs */
881 	ctl_cls[1] = (struct uvc_descriptor_header *)cd;
882 	ctl_cls[2] = (struct uvc_descriptor_header *)pd;
883 	ctl_cls[3] = (struct uvc_descriptor_header *)od;
884 	ctl_cls[4] = NULL;	/* NULL-terminate */
885 	opts->ss_control =
886 		(const struct uvc_descriptor_header * const *)ctl_cls;
887 
888 	opts->streaming_interval = 1;
889 	opts->streaming_maxpacket = 1024;
890 	snprintf(opts->function_name, sizeof(opts->function_name), "UVC Camera");
891 
892 	ret = uvcg_attach_configfs(opts);
893 	if (ret < 0) {
894 		kfree(opts);
895 		return ERR_PTR(ret);
896 	}
897 
898 	return &opts->func_inst;
899 }
900 
901 static void uvc_free(struct usb_function *f)
902 {
903 	struct uvc_device *uvc = to_uvc(f);
904 	struct f_uvc_opts *opts = container_of(f->fi, struct f_uvc_opts,
905 					       func_inst);
906 	config_item_put(&uvc->header->item);
907 	--opts->refcnt;
908 	kfree(uvc);
909 }
910 
911 static void uvc_function_unbind(struct usb_configuration *c,
912 				struct usb_function *f)
913 {
914 	struct usb_composite_dev *cdev = c->cdev;
915 	struct uvc_device *uvc = to_uvc(f);
916 	struct uvc_video *video = &uvc->video;
917 	long wait_ret = 1;
918 
919 	uvcg_info(f, "%s()\n", __func__);
920 
921 	if (video->async_wq)
922 		destroy_workqueue(video->async_wq);
923 
924 	/*
925 	 * If we know we're connected via v4l2, then there should be a cleanup
926 	 * of the device from userspace either via UVC_EVENT_DISCONNECT or
927 	 * though the video device removal uevent. Allow some time for the
928 	 * application to close out before things get deleted.
929 	 */
930 	if (uvc->func_connected) {
931 		uvcg_dbg(f, "waiting for clean disconnect\n");
932 		wait_ret = wait_event_interruptible_timeout(uvc->func_connected_queue,
933 				uvc->func_connected == false, msecs_to_jiffies(500));
934 		uvcg_dbg(f, "done waiting with ret: %ld\n", wait_ret);
935 	}
936 
937 	device_remove_file(&uvc->vdev.dev, &dev_attr_function_name);
938 	video_unregister_device(&uvc->vdev);
939 	v4l2_device_unregister(&uvc->v4l2_dev);
940 
941 	if (uvc->func_connected) {
942 		/*
943 		 * Wait for the release to occur to ensure there are no longer any
944 		 * pending operations that may cause panics when resources are cleaned
945 		 * up.
946 		 */
947 		uvcg_warn(f, "%s no clean disconnect, wait for release\n", __func__);
948 		wait_ret = wait_event_interruptible_timeout(uvc->func_connected_queue,
949 				uvc->func_connected == false, msecs_to_jiffies(1000));
950 		uvcg_dbg(f, "done waiting for release with ret: %ld\n", wait_ret);
951 	}
952 
953 	usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
954 	kfree(uvc->control_buf);
955 
956 	usb_free_all_descriptors(f);
957 }
958 
959 static struct usb_function *uvc_alloc(struct usb_function_instance *fi)
960 {
961 	struct uvc_device *uvc;
962 	struct f_uvc_opts *opts;
963 	struct uvc_descriptor_header **strm_cls;
964 	struct config_item *streaming, *header, *h;
965 
966 	uvc = kzalloc(sizeof(*uvc), GFP_KERNEL);
967 	if (uvc == NULL)
968 		return ERR_PTR(-ENOMEM);
969 
970 	mutex_init(&uvc->video.mutex);
971 	uvc->state = UVC_STATE_DISCONNECTED;
972 	init_waitqueue_head(&uvc->func_connected_queue);
973 	opts = fi_to_f_uvc_opts(fi);
974 
975 	mutex_lock(&opts->lock);
976 	if (opts->uvc_fs_streaming_cls) {
977 		strm_cls = opts->uvc_fs_streaming_cls;
978 		opts->fs_streaming =
979 			(const struct uvc_descriptor_header * const *)strm_cls;
980 	}
981 	if (opts->uvc_hs_streaming_cls) {
982 		strm_cls = opts->uvc_hs_streaming_cls;
983 		opts->hs_streaming =
984 			(const struct uvc_descriptor_header * const *)strm_cls;
985 	}
986 	if (opts->uvc_ss_streaming_cls) {
987 		strm_cls = opts->uvc_ss_streaming_cls;
988 		opts->ss_streaming =
989 			(const struct uvc_descriptor_header * const *)strm_cls;
990 	}
991 
992 	uvc->desc.fs_control = opts->fs_control;
993 	uvc->desc.ss_control = opts->ss_control;
994 	uvc->desc.fs_streaming = opts->fs_streaming;
995 	uvc->desc.hs_streaming = opts->hs_streaming;
996 	uvc->desc.ss_streaming = opts->ss_streaming;
997 
998 	streaming = config_group_find_item(&opts->func_inst.group, "streaming");
999 	if (!streaming)
1000 		goto err_config;
1001 
1002 	header = config_group_find_item(to_config_group(streaming), "header");
1003 	config_item_put(streaming);
1004 	if (!header)
1005 		goto err_config;
1006 
1007 	h = config_group_find_item(to_config_group(header), "h");
1008 	config_item_put(header);
1009 	if (!h)
1010 		goto err_config;
1011 
1012 	uvc->header = to_uvcg_streaming_header(h);
1013 	if (!uvc->header->linked) {
1014 		mutex_unlock(&opts->lock);
1015 		kfree(uvc);
1016 		return ERR_PTR(-EBUSY);
1017 	}
1018 
1019 	++opts->refcnt;
1020 	mutex_unlock(&opts->lock);
1021 
1022 	/* Register the function. */
1023 	uvc->func.name = "uvc";
1024 	uvc->func.bind = uvc_function_bind;
1025 	uvc->func.unbind = uvc_function_unbind;
1026 	uvc->func.get_alt = uvc_function_get_alt;
1027 	uvc->func.set_alt = uvc_function_set_alt;
1028 	uvc->func.disable = uvc_function_disable;
1029 	uvc->func.setup = uvc_function_setup;
1030 	uvc->func.free_func = uvc_free;
1031 	uvc->func.bind_deactivated = true;
1032 
1033 	return &uvc->func;
1034 
1035 err_config:
1036 	mutex_unlock(&opts->lock);
1037 	kfree(uvc);
1038 	return ERR_PTR(-ENOENT);
1039 }
1040 
1041 DECLARE_USB_FUNCTION_INIT(uvc, uvc_alloc_inst, uvc_alloc);
1042 MODULE_LICENSE("GPL");
1043 MODULE_AUTHOR("Laurent Pinchart");
1044