• 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 "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		= 1,
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_control_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_control_comp = {
96 	.bLength		= sizeof(uvc_ss_control_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_control_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
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 	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 
uvc_function_setup_continue(struct uvc_device * uvc,int disable_ep)266 void uvc_function_setup_continue(struct uvc_device *uvc, int disable_ep)
267 {
268 	struct usb_composite_dev *cdev = uvc->func.config->cdev;
269 
270 	if (disable_ep && uvc->video.ep)
271 		usb_ep_disable(uvc->video.ep);
272 
273 	usb_composite_setup_continue(cdev);
274 }
275 
276 static int
uvc_function_get_alt(struct usb_function * f,unsigned interface)277 uvc_function_get_alt(struct usb_function *f, unsigned interface)
278 {
279 	struct uvc_device *uvc = to_uvc(f);
280 
281 	uvcg_info(f, "%s(%u)\n", __func__, interface);
282 
283 	if (interface == uvc->control_intf)
284 		return 0;
285 	else if (interface != uvc->streaming_intf)
286 		return -EINVAL;
287 	else
288 		return uvc->video.ep->enabled ? 1 : 0;
289 }
290 
291 static int
uvc_function_set_alt(struct usb_function * f,unsigned interface,unsigned alt)292 uvc_function_set_alt(struct usb_function *f, unsigned interface, unsigned alt)
293 {
294 	struct uvc_device *uvc = to_uvc(f);
295 	struct usb_composite_dev *cdev = f->config->cdev;
296 	struct v4l2_event v4l2_event;
297 	struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
298 	int ret;
299 
300 	uvcg_info(f, "%s(%u, %u)\n", __func__, interface, alt);
301 
302 	if (interface == uvc->control_intf) {
303 		if (alt)
304 			return -EINVAL;
305 
306 		uvcg_info(f, "reset UVC Control\n");
307 		usb_ep_disable(uvc->control_ep);
308 
309 		if (!uvc->control_ep->desc)
310 			if (config_ep_by_speed(cdev->gadget, f, uvc->control_ep))
311 				return -EINVAL;
312 
313 		usb_ep_enable(uvc->control_ep);
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 		memset(&v4l2_event, 0, sizeof(v4l2_event));
341 		v4l2_event.type = UVC_EVENT_STREAMOFF;
342 		v4l2_event_queue(&uvc->vdev, &v4l2_event);
343 
344 		return USB_GADGET_DELAYED_STATUS;
345 
346 	case 1:
347 		if (uvc->state != UVC_STATE_CONNECTED)
348 			return 0;
349 
350 		if (!uvc->video.ep)
351 			return -EINVAL;
352 
353 		uvcg_info(f, "reset UVC\n");
354 		usb_ep_disable(uvc->video.ep);
355 
356 		ret = config_ep_by_speed(f->config->cdev->gadget,
357 				&(uvc->func), uvc->video.ep);
358 		if (ret)
359 			return ret;
360 		usb_ep_enable(uvc->video.ep);
361 
362 		memset(&v4l2_event, 0, sizeof(v4l2_event));
363 		v4l2_event.type = UVC_EVENT_STREAMON;
364 		v4l2_event_queue(&uvc->vdev, &v4l2_event);
365 		return USB_GADGET_DELAYED_STATUS;
366 
367 	default:
368 		return -EINVAL;
369 	}
370 }
371 
372 static void
uvc_function_disable(struct usb_function * f)373 uvc_function_disable(struct usb_function *f)
374 {
375 	struct uvc_device *uvc = to_uvc(f);
376 	struct v4l2_event v4l2_event;
377 
378 	uvcg_info(f, "%s()\n", __func__);
379 
380 	memset(&v4l2_event, 0, sizeof(v4l2_event));
381 	v4l2_event.type = UVC_EVENT_DISCONNECT;
382 	v4l2_event_queue(&uvc->vdev, &v4l2_event);
383 
384 	uvc->state = UVC_STATE_DISCONNECTED;
385 
386 	usb_ep_disable(uvc->video.ep);
387 	usb_ep_disable(uvc->control_ep);
388 }
389 
390 /* --------------------------------------------------------------------------
391  * Connection / disconnection
392  */
393 
394 void
uvc_function_connect(struct uvc_device * uvc)395 uvc_function_connect(struct uvc_device *uvc)
396 {
397 	int ret;
398 
399 	if ((ret = usb_function_activate(&uvc->func)) < 0)
400 		uvcg_info(&uvc->func, "UVC connect failed with %d\n", ret);
401 }
402 
403 void
uvc_function_disconnect(struct uvc_device * uvc)404 uvc_function_disconnect(struct uvc_device *uvc)
405 {
406 	int ret;
407 
408 	if ((ret = usb_function_deactivate(&uvc->func)) < 0)
409 		uvcg_info(&uvc->func, "UVC disconnect failed with %d\n", ret);
410 }
411 
412 /* --------------------------------------------------------------------------
413  * USB probe and disconnect
414  */
415 
function_name_show(struct device * dev,struct device_attribute * attr,char * buf)416 static ssize_t function_name_show(struct device *dev,
417 				  struct device_attribute *attr, char *buf)
418 {
419 	struct uvc_device *uvc = dev_get_drvdata(dev);
420 
421 	return sprintf(buf, "%s\n", uvc->func.fi->group.cg_item.ci_name);
422 }
423 
424 static DEVICE_ATTR_RO(function_name);
425 
426 static int
uvc_register_video(struct uvc_device * uvc)427 uvc_register_video(struct uvc_device *uvc)
428 {
429 	struct usb_composite_dev *cdev = uvc->func.config->cdev;
430 	int ret;
431 
432 	/* TODO reference counting. */
433 	memset(&uvc->vdev, 0, sizeof(uvc->vdev));
434 	uvc->vdev.v4l2_dev = &uvc->v4l2_dev;
435 	uvc->vdev.v4l2_dev->dev = &cdev->gadget->dev;
436 	uvc->vdev.fops = &uvc_v4l2_fops;
437 	uvc->vdev.ioctl_ops = &uvc_v4l2_ioctl_ops;
438 	uvc->vdev.release = video_device_release_empty;
439 	uvc->vdev.vfl_dir = VFL_DIR_TX;
440 	uvc->vdev.lock = &uvc->video.mutex;
441 	uvc->vdev.device_caps = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
442 	strscpy(uvc->vdev.name, cdev->gadget->name, sizeof(uvc->vdev.name));
443 
444 	video_set_drvdata(&uvc->vdev, uvc);
445 
446 	ret = video_register_device(&uvc->vdev, VFL_TYPE_VIDEO, -1);
447 	if (ret < 0)
448 		return ret;
449 
450 	ret = device_create_file(&uvc->vdev.dev, &dev_attr_function_name);
451 	if (ret < 0) {
452 		video_unregister_device(&uvc->vdev);
453 		return ret;
454 	}
455 
456 	return 0;
457 }
458 
459 #define UVC_COPY_DESCRIPTOR(mem, dst, desc) \
460 	do { \
461 		memcpy(mem, desc, (desc)->bLength); \
462 		*(dst)++ = mem; \
463 		mem += (desc)->bLength; \
464 	} while (0);
465 
466 #define UVC_COPY_DESCRIPTORS(mem, dst, src) \
467 	do { \
468 		const struct usb_descriptor_header * const *__src; \
469 		for (__src = src; *__src; ++__src) { \
470 			memcpy(mem, *__src, (*__src)->bLength); \
471 			*dst++ = mem; \
472 			mem += (*__src)->bLength; \
473 		} \
474 	} while (0)
475 
476 static struct usb_descriptor_header **
uvc_copy_descriptors(struct uvc_device * uvc,enum usb_device_speed speed)477 uvc_copy_descriptors(struct uvc_device *uvc, enum usb_device_speed speed)
478 {
479 	struct uvc_input_header_descriptor *uvc_streaming_header;
480 	struct uvc_header_descriptor *uvc_control_header;
481 	const struct uvc_descriptor_header * const *uvc_control_desc;
482 	const struct uvc_descriptor_header * const *uvc_streaming_cls;
483 	const struct usb_descriptor_header * const *uvc_streaming_std;
484 	const struct usb_descriptor_header * const *src;
485 	struct usb_descriptor_header **dst;
486 	struct usb_descriptor_header **hdr;
487 	unsigned int control_size;
488 	unsigned int streaming_size;
489 	unsigned int n_desc;
490 	unsigned int bytes;
491 	void *mem;
492 
493 	switch (speed) {
494 	case USB_SPEED_SUPER_PLUS:
495 	case USB_SPEED_SUPER:
496 		uvc_control_desc = uvc->desc.ss_control;
497 		uvc_streaming_cls = uvc->desc.ss_streaming;
498 		uvc_streaming_std = uvc_ss_streaming;
499 		break;
500 
501 	case USB_SPEED_HIGH:
502 		uvc_control_desc = uvc->desc.fs_control;
503 		uvc_streaming_cls = uvc->desc.hs_streaming;
504 		uvc_streaming_std = uvc_hs_streaming;
505 		break;
506 
507 	case USB_SPEED_FULL:
508 	default:
509 		uvc_control_desc = uvc->desc.fs_control;
510 		uvc_streaming_cls = uvc->desc.fs_streaming;
511 		uvc_streaming_std = uvc_fs_streaming;
512 		break;
513 	}
514 
515 	if (!uvc_control_desc || !uvc_streaming_cls)
516 		return ERR_PTR(-ENODEV);
517 
518 	/*
519 	 * Descriptors layout
520 	 *
521 	 * uvc_iad
522 	 * uvc_control_intf
523 	 * Class-specific UVC control descriptors
524 	 * uvc_control_ep
525 	 * uvc_control_cs_ep
526 	 * uvc_ss_control_comp (for SS only)
527 	 * uvc_streaming_intf_alt0
528 	 * Class-specific UVC streaming descriptors
529 	 * uvc_{fs|hs}_streaming
530 	 */
531 
532 	/* Count descriptors and compute their size. */
533 	control_size = 0;
534 	streaming_size = 0;
535 	bytes = uvc_iad.bLength + uvc_control_intf.bLength
536 	      + uvc_control_ep.bLength + uvc_control_cs_ep.bLength
537 	      + uvc_streaming_intf_alt0.bLength;
538 
539 	if (speed == USB_SPEED_SUPER ||
540 	    speed == USB_SPEED_SUPER_PLUS) {
541 		bytes += uvc_ss_control_comp.bLength;
542 		n_desc = 6;
543 	} else {
544 		n_desc = 5;
545 	}
546 
547 	for (src = (const struct usb_descriptor_header **)uvc_control_desc;
548 	     *src; ++src) {
549 		control_size += (*src)->bLength;
550 		bytes += (*src)->bLength;
551 		n_desc++;
552 	}
553 	for (src = (const struct usb_descriptor_header **)uvc_streaming_cls;
554 	     *src; ++src) {
555 		streaming_size += (*src)->bLength;
556 		bytes += (*src)->bLength;
557 		n_desc++;
558 	}
559 	for (src = uvc_streaming_std; *src; ++src) {
560 		bytes += (*src)->bLength;
561 		n_desc++;
562 	}
563 
564 	mem = kmalloc((n_desc + 1) * sizeof(*src) + bytes, GFP_KERNEL);
565 	if (mem == NULL)
566 		return NULL;
567 
568 	hdr = mem;
569 	dst = mem;
570 	mem += (n_desc + 1) * sizeof(*src);
571 
572 	/* Copy the descriptors. */
573 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_iad);
574 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_intf);
575 
576 	uvc_control_header = mem;
577 	UVC_COPY_DESCRIPTORS(mem, dst,
578 		(const struct usb_descriptor_header **)uvc_control_desc);
579 	uvc_control_header->wTotalLength = cpu_to_le16(control_size);
580 	uvc_control_header->bInCollection = 1;
581 	uvc_control_header->baInterfaceNr[0] = uvc->streaming_intf;
582 
583 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_ep);
584 	if (speed == USB_SPEED_SUPER
585 	    || speed == USB_SPEED_SUPER_PLUS)
586 		UVC_COPY_DESCRIPTOR(mem, dst, &uvc_ss_control_comp);
587 
588 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_cs_ep);
589 	UVC_COPY_DESCRIPTOR(mem, dst, &uvc_streaming_intf_alt0);
590 
591 	uvc_streaming_header = mem;
592 	UVC_COPY_DESCRIPTORS(mem, dst,
593 		(const struct usb_descriptor_header**)uvc_streaming_cls);
594 	uvc_streaming_header->wTotalLength = cpu_to_le16(streaming_size);
595 	uvc_streaming_header->bEndpointAddress = uvc->video.ep->address;
596 
597 	UVC_COPY_DESCRIPTORS(mem, dst, uvc_streaming_std);
598 
599 	*dst = NULL;
600 	return hdr;
601 }
602 
603 static int
uvc_function_bind(struct usb_configuration * c,struct usb_function * f)604 uvc_function_bind(struct usb_configuration *c, struct usb_function *f)
605 {
606 	struct usb_composite_dev *cdev = c->cdev;
607 	struct uvc_device *uvc = to_uvc(f);
608 	struct usb_string *us;
609 	unsigned int max_packet_mult;
610 	unsigned int max_packet_size;
611 	struct usb_ep *ep;
612 	struct f_uvc_opts *opts;
613 	int ret = -EINVAL;
614 
615 	uvcg_info(f, "%s()\n", __func__);
616 
617 	opts = fi_to_f_uvc_opts(f->fi);
618 	/* Sanity check the streaming endpoint module parameters. */
619 	opts->streaming_interval = clamp(opts->streaming_interval, 1U, 16U);
620 	opts->streaming_maxpacket = clamp(opts->streaming_maxpacket, 1U, 3072U);
621 	opts->streaming_maxburst = min(opts->streaming_maxburst, 15U);
622 
623 	/* For SS, wMaxPacketSize has to be 1024 if bMaxBurst is not 0 */
624 	if (opts->streaming_maxburst &&
625 	    (opts->streaming_maxpacket % 1024) != 0) {
626 		opts->streaming_maxpacket = roundup(opts->streaming_maxpacket, 1024);
627 		uvcg_info(f, "overriding streaming_maxpacket to %d\n",
628 			  opts->streaming_maxpacket);
629 	}
630 
631 	/*
632 	 * Fill in the FS/HS/SS Video Streaming specific descriptors from the
633 	 * module parameters.
634 	 *
635 	 * NOTE: We assume that the user knows what they are doing and won't
636 	 * give parameters that their UDC doesn't support.
637 	 */
638 	if (opts->streaming_maxpacket <= 1024) {
639 		max_packet_mult = 1;
640 		max_packet_size = opts->streaming_maxpacket;
641 	} else if (opts->streaming_maxpacket <= 2048) {
642 		max_packet_mult = 2;
643 		max_packet_size = opts->streaming_maxpacket / 2;
644 	} else {
645 		max_packet_mult = 3;
646 		max_packet_size = opts->streaming_maxpacket / 3;
647 	}
648 
649 	uvc_fs_streaming_ep.wMaxPacketSize =
650 		cpu_to_le16(min(opts->streaming_maxpacket, 1023U));
651 	uvc_fs_streaming_ep.bInterval = opts->streaming_interval;
652 
653 	uvc_hs_streaming_ep.wMaxPacketSize =
654 		cpu_to_le16(max_packet_size | ((max_packet_mult - 1) << 11));
655 
656 	/* A high-bandwidth endpoint must specify a bInterval value of 1 */
657 	if (max_packet_mult > 1)
658 		uvc_hs_streaming_ep.bInterval = 1;
659 	else
660 		uvc_hs_streaming_ep.bInterval = opts->streaming_interval;
661 
662 	uvc_ss_streaming_ep.wMaxPacketSize = cpu_to_le16(max_packet_size);
663 	uvc_ss_streaming_ep.bInterval = opts->streaming_interval;
664 	uvc_ss_streaming_comp.bmAttributes = max_packet_mult - 1;
665 	uvc_ss_streaming_comp.bMaxBurst = opts->streaming_maxburst;
666 	uvc_ss_streaming_comp.wBytesPerInterval =
667 		cpu_to_le16(max_packet_size * max_packet_mult *
668 			    (opts->streaming_maxburst + 1));
669 
670 	/* Allocate endpoints. */
671 	ep = usb_ep_autoconfig(cdev->gadget, &uvc_control_ep);
672 	if (!ep) {
673 		uvcg_info(f, "Unable to allocate control EP\n");
674 		goto error;
675 	}
676 	uvc->control_ep = ep;
677 
678 	ep = usb_ep_autoconfig(cdev->gadget, &uvc_fs_streaming_ep);
679 	if (!ep) {
680 		uvcg_info(f, "Unable to allocate streaming EP\n");
681 		goto error;
682 	}
683 	uvc->video.ep = ep;
684 
685 	uvc_hs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
686 	uvc_ss_streaming_ep.bEndpointAddress = uvc->video.ep->address;
687 
688 	uvc_en_us_strings[UVC_STRING_CONTROL_IDX].s = opts->function_name;
689 	us = usb_gstrings_attach(cdev, uvc_function_strings,
690 				 ARRAY_SIZE(uvc_en_us_strings));
691 	if (IS_ERR(us)) {
692 		ret = PTR_ERR(us);
693 		goto error;
694 	}
695 	uvc_iad.iFunction = us[UVC_STRING_CONTROL_IDX].id;
696 	uvc_control_intf.iInterface = us[UVC_STRING_CONTROL_IDX].id;
697 	ret = us[UVC_STRING_STREAMING_IDX].id;
698 	uvc_streaming_intf_alt0.iInterface = ret;
699 	uvc_streaming_intf_alt1.iInterface = ret;
700 
701 	/* Allocate interface IDs. */
702 	if ((ret = usb_interface_id(c, f)) < 0)
703 		goto error;
704 	uvc_iad.bFirstInterface = ret;
705 	uvc_control_intf.bInterfaceNumber = ret;
706 	uvc->control_intf = ret;
707 	opts->control_interface = ret;
708 
709 	if ((ret = usb_interface_id(c, f)) < 0)
710 		goto error;
711 	uvc_streaming_intf_alt0.bInterfaceNumber = ret;
712 	uvc_streaming_intf_alt1.bInterfaceNumber = ret;
713 	uvc->streaming_intf = ret;
714 	opts->streaming_interface = ret;
715 
716 	/* Copy descriptors */
717 	f->fs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_FULL);
718 	if (IS_ERR(f->fs_descriptors)) {
719 		ret = PTR_ERR(f->fs_descriptors);
720 		f->fs_descriptors = NULL;
721 		goto error;
722 	}
723 
724 	f->hs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_HIGH);
725 	if (IS_ERR(f->hs_descriptors)) {
726 		ret = PTR_ERR(f->hs_descriptors);
727 		f->hs_descriptors = NULL;
728 		goto error;
729 	}
730 
731 	f->ss_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_SUPER);
732 	if (IS_ERR(f->ss_descriptors)) {
733 		ret = PTR_ERR(f->ss_descriptors);
734 		f->ss_descriptors = NULL;
735 		goto error;
736 	}
737 
738 	f->ssp_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_SUPER_PLUS);
739 	if (IS_ERR(f->ssp_descriptors)) {
740 		ret = PTR_ERR(f->ssp_descriptors);
741 		f->ssp_descriptors = NULL;
742 		goto error;
743 	}
744 
745 	/* Preallocate control endpoint request. */
746 	uvc->control_req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
747 	uvc->control_buf = kmalloc(UVC_MAX_REQUEST_SIZE, GFP_KERNEL);
748 	if (uvc->control_req == NULL || uvc->control_buf == NULL) {
749 		ret = -ENOMEM;
750 		goto error;
751 	}
752 
753 	uvc->control_req->buf = uvc->control_buf;
754 	uvc->control_req->complete = uvc_function_ep0_complete;
755 	uvc->control_req->context = uvc;
756 
757 	if (v4l2_device_register(&cdev->gadget->dev, &uvc->v4l2_dev)) {
758 		uvcg_err(f, "failed to register V4L2 device\n");
759 		goto error;
760 	}
761 
762 	/* Initialise video. */
763 	ret = uvcg_video_init(&uvc->video, uvc);
764 	if (ret < 0)
765 		goto v4l2_error;
766 
767 	/* Register a V4L2 device. */
768 	ret = uvc_register_video(uvc);
769 	if (ret < 0) {
770 		uvcg_err(f, "failed to register video device\n");
771 		goto v4l2_error;
772 	}
773 
774 	return 0;
775 
776 v4l2_error:
777 	v4l2_device_unregister(&uvc->v4l2_dev);
778 error:
779 	if (uvc->control_req)
780 		usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
781 	kfree(uvc->control_buf);
782 
783 	usb_free_all_descriptors(f);
784 	return ret;
785 }
786 
787 /* --------------------------------------------------------------------------
788  * USB gadget function
789  */
790 
uvc_free_inst(struct usb_function_instance * f)791 static void uvc_free_inst(struct usb_function_instance *f)
792 {
793 	struct f_uvc_opts *opts = fi_to_f_uvc_opts(f);
794 
795 	mutex_destroy(&opts->lock);
796 	kfree(opts);
797 }
798 
uvc_alloc_inst(void)799 static struct usb_function_instance *uvc_alloc_inst(void)
800 {
801 	struct f_uvc_opts *opts;
802 	struct uvc_camera_terminal_descriptor *cd;
803 	struct uvc_processing_unit_descriptor *pd;
804 	struct uvc_output_terminal_descriptor *od;
805 	struct uvc_color_matching_descriptor *md;
806 	struct uvc_descriptor_header **ctl_cls;
807 	int ret;
808 
809 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
810 	if (!opts)
811 		return ERR_PTR(-ENOMEM);
812 	opts->func_inst.free_func_inst = uvc_free_inst;
813 	mutex_init(&opts->lock);
814 
815 	cd = &opts->uvc_camera_terminal;
816 	cd->bLength			= UVC_DT_CAMERA_TERMINAL_SIZE(3);
817 	cd->bDescriptorType		= USB_DT_CS_INTERFACE;
818 	cd->bDescriptorSubType		= UVC_VC_INPUT_TERMINAL;
819 	cd->bTerminalID			= 1;
820 	cd->wTerminalType		= cpu_to_le16(0x0201);
821 	cd->bAssocTerminal		= 0;
822 	cd->iTerminal			= 0;
823 	cd->wObjectiveFocalLengthMin	= cpu_to_le16(0);
824 	cd->wObjectiveFocalLengthMax	= cpu_to_le16(0);
825 	cd->wOcularFocalLength		= cpu_to_le16(0);
826 	cd->bControlSize		= 3;
827 	cd->bmControls[0]		= 2;
828 	cd->bmControls[1]		= 0;
829 	cd->bmControls[2]		= 0;
830 
831 	pd = &opts->uvc_processing;
832 	pd->bLength			= UVC_DT_PROCESSING_UNIT_SIZE(2);
833 	pd->bDescriptorType		= USB_DT_CS_INTERFACE;
834 	pd->bDescriptorSubType		= UVC_VC_PROCESSING_UNIT;
835 	pd->bUnitID			= 2;
836 	pd->bSourceID			= 1;
837 	pd->wMaxMultiplier		= cpu_to_le16(16*1024);
838 	pd->bControlSize		= 2;
839 	pd->bmControls[0]		= 1;
840 	pd->bmControls[1]		= 0;
841 	pd->iProcessing			= 0;
842 	pd->bmVideoStandards		= 0;
843 
844 	od = &opts->uvc_output_terminal;
845 	od->bLength			= UVC_DT_OUTPUT_TERMINAL_SIZE;
846 	od->bDescriptorType		= USB_DT_CS_INTERFACE;
847 	od->bDescriptorSubType		= UVC_VC_OUTPUT_TERMINAL;
848 	od->bTerminalID			= 3;
849 	od->wTerminalType		= cpu_to_le16(0x0101);
850 	od->bAssocTerminal		= 0;
851 	od->bSourceID			= 2;
852 	od->iTerminal			= 0;
853 
854 	md = &opts->uvc_color_matching;
855 	md->bLength			= UVC_DT_COLOR_MATCHING_SIZE;
856 	md->bDescriptorType		= USB_DT_CS_INTERFACE;
857 	md->bDescriptorSubType		= UVC_VS_COLORFORMAT;
858 	md->bColorPrimaries		= 1;
859 	md->bTransferCharacteristics	= 1;
860 	md->bMatrixCoefficients		= 4;
861 
862 	/* Prepare fs control class descriptors for configfs-based gadgets */
863 	ctl_cls = opts->uvc_fs_control_cls;
864 	ctl_cls[0] = NULL;	/* assigned elsewhere by configfs */
865 	ctl_cls[1] = (struct uvc_descriptor_header *)cd;
866 	ctl_cls[2] = (struct uvc_descriptor_header *)pd;
867 	ctl_cls[3] = (struct uvc_descriptor_header *)od;
868 	ctl_cls[4] = NULL;	/* NULL-terminate */
869 	opts->fs_control =
870 		(const struct uvc_descriptor_header * const *)ctl_cls;
871 
872 	/* Prepare hs control class descriptors for configfs-based gadgets */
873 	ctl_cls = opts->uvc_ss_control_cls;
874 	ctl_cls[0] = NULL;	/* assigned elsewhere by configfs */
875 	ctl_cls[1] = (struct uvc_descriptor_header *)cd;
876 	ctl_cls[2] = (struct uvc_descriptor_header *)pd;
877 	ctl_cls[3] = (struct uvc_descriptor_header *)od;
878 	ctl_cls[4] = NULL;	/* NULL-terminate */
879 	opts->ss_control =
880 		(const struct uvc_descriptor_header * const *)ctl_cls;
881 
882 	opts->streaming_interval = 1;
883 	opts->streaming_maxpacket = 1024;
884 	snprintf(opts->function_name, sizeof(opts->function_name), "UVC Camera");
885 
886 	ret = uvcg_attach_configfs(opts);
887 	if (ret < 0) {
888 		kfree(opts);
889 		return ERR_PTR(ret);
890 	}
891 
892 	return &opts->func_inst;
893 }
894 
uvc_free(struct usb_function * f)895 static void uvc_free(struct usb_function *f)
896 {
897 	struct uvc_device *uvc = to_uvc(f);
898 	struct f_uvc_opts *opts = container_of(f->fi, struct f_uvc_opts,
899 					       func_inst);
900 	config_item_put(&uvc->header->item);
901 	--opts->refcnt;
902 	kfree(uvc);
903 }
904 
uvc_function_unbind(struct usb_configuration * c,struct usb_function * f)905 static void uvc_function_unbind(struct usb_configuration *c,
906 				struct usb_function *f)
907 {
908 	struct usb_composite_dev *cdev = c->cdev;
909 	struct uvc_device *uvc = to_uvc(f);
910 	struct uvc_video *video = &uvc->video;
911 	long wait_ret = 1;
912 
913 	uvcg_info(f, "%s()\n", __func__);
914 
915 	if (video->async_wq)
916 		destroy_workqueue(video->async_wq);
917 
918 	/*
919 	 * If we know we're connected via v4l2, then there should be a cleanup
920 	 * of the device from userspace either via UVC_EVENT_DISCONNECT or
921 	 * though the video device removal uevent. Allow some time for the
922 	 * application to close out before things get deleted.
923 	 */
924 	if (uvc->func_connected) {
925 		uvcg_dbg(f, "waiting for clean disconnect\n");
926 		wait_ret = wait_event_interruptible_timeout(uvc->func_connected_queue,
927 				uvc->func_connected == false, msecs_to_jiffies(500));
928 		uvcg_dbg(f, "done waiting with ret: %ld\n", wait_ret);
929 	}
930 
931 	device_remove_file(&uvc->vdev.dev, &dev_attr_function_name);
932 	video_unregister_device(&uvc->vdev);
933 	v4l2_device_unregister(&uvc->v4l2_dev);
934 
935 	if (uvc->func_connected) {
936 		/*
937 		 * Wait for the release to occur to ensure there are no longer any
938 		 * pending operations that may cause panics when resources are cleaned
939 		 * up.
940 		 */
941 		uvcg_warn(f, "%s no clean disconnect, wait for release\n", __func__);
942 		wait_ret = wait_event_interruptible_timeout(uvc->func_connected_queue,
943 				uvc->func_connected == false, msecs_to_jiffies(1000));
944 		uvcg_dbg(f, "done waiting for release with ret: %ld\n", wait_ret);
945 	}
946 
947 	usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
948 	kfree(uvc->control_buf);
949 
950 	usb_free_all_descriptors(f);
951 }
952 
uvc_alloc(struct usb_function_instance * fi)953 static struct usb_function *uvc_alloc(struct usb_function_instance *fi)
954 {
955 	struct uvc_device *uvc;
956 	struct f_uvc_opts *opts;
957 	struct uvc_descriptor_header **strm_cls;
958 	struct config_item *streaming, *header, *h;
959 
960 	uvc = kzalloc(sizeof(*uvc), GFP_KERNEL);
961 	if (uvc == NULL)
962 		return ERR_PTR(-ENOMEM);
963 
964 	mutex_init(&uvc->video.mutex);
965 	uvc->state = UVC_STATE_DISCONNECTED;
966 	init_waitqueue_head(&uvc->func_connected_queue);
967 	opts = fi_to_f_uvc_opts(fi);
968 
969 	mutex_lock(&opts->lock);
970 	if (opts->uvc_fs_streaming_cls) {
971 		strm_cls = opts->uvc_fs_streaming_cls;
972 		opts->fs_streaming =
973 			(const struct uvc_descriptor_header * const *)strm_cls;
974 	}
975 	if (opts->uvc_hs_streaming_cls) {
976 		strm_cls = opts->uvc_hs_streaming_cls;
977 		opts->hs_streaming =
978 			(const struct uvc_descriptor_header * const *)strm_cls;
979 	}
980 	if (opts->uvc_ss_streaming_cls) {
981 		strm_cls = opts->uvc_ss_streaming_cls;
982 		opts->ss_streaming =
983 			(const struct uvc_descriptor_header * const *)strm_cls;
984 	}
985 
986 	uvc->desc.fs_control = opts->fs_control;
987 	uvc->desc.ss_control = opts->ss_control;
988 	uvc->desc.fs_streaming = opts->fs_streaming;
989 	uvc->desc.hs_streaming = opts->hs_streaming;
990 	uvc->desc.ss_streaming = opts->ss_streaming;
991 
992 	streaming = config_group_find_item(&opts->func_inst.group, "streaming");
993 	if (!streaming)
994 		goto err_config;
995 
996 	header = config_group_find_item(to_config_group(streaming), "header");
997 	config_item_put(streaming);
998 	if (!header)
999 		goto err_config;
1000 
1001 	h = config_group_find_item(to_config_group(header), "h");
1002 	config_item_put(header);
1003 	if (!h)
1004 		goto err_config;
1005 
1006 	uvc->header = to_uvcg_streaming_header(h);
1007 	if (!uvc->header->linked) {
1008 		mutex_unlock(&opts->lock);
1009 		kfree(uvc);
1010 		return ERR_PTR(-EBUSY);
1011 	}
1012 
1013 	++opts->refcnt;
1014 	mutex_unlock(&opts->lock);
1015 
1016 	/* Register the function. */
1017 	uvc->func.name = "uvc";
1018 	uvc->func.bind = uvc_function_bind;
1019 	uvc->func.unbind = uvc_function_unbind;
1020 	uvc->func.get_alt = uvc_function_get_alt;
1021 	uvc->func.set_alt = uvc_function_set_alt;
1022 	uvc->func.disable = uvc_function_disable;
1023 	uvc->func.setup = uvc_function_setup;
1024 	uvc->func.free_func = uvc_free;
1025 	uvc->func.bind_deactivated = true;
1026 
1027 	return &uvc->func;
1028 
1029 err_config:
1030 	mutex_unlock(&opts->lock);
1031 	kfree(uvc);
1032 	return ERR_PTR(-ENOENT);
1033 }
1034 
1035 DECLARE_USB_FUNCTION_INIT(uvc, uvc_alloc_inst, uvc_alloc);
1036 MODULE_LICENSE("GPL");
1037 MODULE_AUTHOR("Laurent Pinchart");
1038