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