GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / usb / gadget / function / f_uvc.c
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 void uvc_set_trace_param(unsigned int trace)
201 {
202         uvc_gadget_trace_param = trace;
203 }
204 EXPORT_SYMBOL(uvc_set_trace_param);
205
206 /* --------------------------------------------------------------------------
207  * Control requests
208  */
209
210 static void
211 uvc_function_ep0_complete(struct usb_ep *ep, struct usb_request *req)
212 {
213         struct uvc_device *uvc = req->context;
214         struct v4l2_event v4l2_event;
215         struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
216
217         if (uvc->event_setup_out) {
218                 uvc->event_setup_out = 0;
219
220                 memset(&v4l2_event, 0, sizeof(v4l2_event));
221                 v4l2_event.type = UVC_EVENT_DATA;
222                 uvc_event->data.length = min_t(unsigned int, req->actual,
223                         sizeof(uvc_event->data.data));
224                 memcpy(&uvc_event->data.data, req->buf, uvc_event->data.length);
225                 v4l2_event_queue(&uvc->vdev, &v4l2_event);
226         }
227 }
228
229 static int
230 uvc_function_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
231 {
232         struct uvc_device *uvc = to_uvc(f);
233         struct v4l2_event v4l2_event;
234         struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
235
236         /* printk(KERN_INFO "setup request %02x %02x value %04x index %04x %04x\n",
237          *      ctrl->bRequestType, ctrl->bRequest, le16_to_cpu(ctrl->wValue),
238          *      le16_to_cpu(ctrl->wIndex), le16_to_cpu(ctrl->wLength));
239          */
240
241         if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_CLASS) {
242                 INFO(f->config->cdev, "invalid request type\n");
243                 return -EINVAL;
244         }
245
246         /* Stall too big requests. */
247         if (le16_to_cpu(ctrl->wLength) > UVC_MAX_REQUEST_SIZE)
248                 return -EINVAL;
249
250         /* Tell the complete callback to generate an event for the next request
251          * that will be enqueued by UVCIOC_SEND_RESPONSE.
252          */
253         uvc->event_setup_out = !(ctrl->bRequestType & USB_DIR_IN);
254         uvc->event_length = le16_to_cpu(ctrl->wLength);
255
256         memset(&v4l2_event, 0, sizeof(v4l2_event));
257         v4l2_event.type = UVC_EVENT_SETUP;
258         memcpy(&uvc_event->req, ctrl, sizeof(uvc_event->req));
259         v4l2_event_queue(&uvc->vdev, &v4l2_event);
260
261         return 0;
262 }
263
264 void uvc_function_setup_continue(struct uvc_device *uvc)
265 {
266         struct usb_composite_dev *cdev = uvc->func.config->cdev;
267
268         usb_composite_setup_continue(cdev);
269 }
270
271 static int
272 uvc_function_get_alt(struct usb_function *f, unsigned interface)
273 {
274         struct uvc_device *uvc = to_uvc(f);
275
276         INFO(f->config->cdev, "uvc_function_get_alt(%u)\n", interface);
277
278         if (interface == uvc->control_intf)
279                 return 0;
280         else if (interface != uvc->streaming_intf)
281                 return -EINVAL;
282         else
283                 return uvc->video.ep->enabled ? 1 : 0;
284 }
285
286 static int
287 uvc_function_set_alt(struct usb_function *f, unsigned interface, unsigned alt)
288 {
289         struct uvc_device *uvc = to_uvc(f);
290         struct usb_composite_dev *cdev = f->config->cdev;
291         struct v4l2_event v4l2_event;
292         struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
293         int ret;
294
295         INFO(cdev, "uvc_function_set_alt(%u, %u)\n", interface, alt);
296
297         if (interface == uvc->control_intf) {
298                 if (alt)
299                         return -EINVAL;
300
301                 INFO(cdev, "reset UVC Control\n");
302                 usb_ep_disable(uvc->control_ep);
303
304                 if (!uvc->control_ep->desc)
305                         if (config_ep_by_speed(cdev->gadget, f, uvc->control_ep))
306                                 return -EINVAL;
307
308                 usb_ep_enable(uvc->control_ep);
309
310                 if (uvc->state == UVC_STATE_DISCONNECTED) {
311                         memset(&v4l2_event, 0, sizeof(v4l2_event));
312                         v4l2_event.type = UVC_EVENT_CONNECT;
313                         uvc_event->speed = cdev->gadget->speed;
314                         v4l2_event_queue(&uvc->vdev, &v4l2_event);
315
316                         uvc->state = UVC_STATE_CONNECTED;
317                 }
318
319                 return 0;
320         }
321
322         if (interface != uvc->streaming_intf)
323                 return -EINVAL;
324
325         /* TODO
326         if (usb_endpoint_xfer_bulk(&uvc->desc.vs_ep))
327                 return alt ? -EINVAL : 0;
328         */
329
330         switch (alt) {
331         case 0:
332                 if (uvc->state != UVC_STATE_STREAMING)
333                         return 0;
334
335                 if (uvc->video.ep)
336                         usb_ep_disable(uvc->video.ep);
337
338                 memset(&v4l2_event, 0, sizeof(v4l2_event));
339                 v4l2_event.type = UVC_EVENT_STREAMOFF;
340                 v4l2_event_queue(&uvc->vdev, &v4l2_event);
341
342                 uvc->state = UVC_STATE_CONNECTED;
343                 return 0;
344
345         case 1:
346                 if (uvc->state != UVC_STATE_CONNECTED)
347                         return 0;
348
349                 if (!uvc->video.ep)
350                         return -EINVAL;
351
352                 INFO(cdev, "reset UVC\n");
353                 usb_ep_disable(uvc->video.ep);
354
355                 ret = config_ep_by_speed(f->config->cdev->gadget,
356                                 &(uvc->func), uvc->video.ep);
357                 if (ret)
358                         return ret;
359                 usb_ep_enable(uvc->video.ep);
360
361                 memset(&v4l2_event, 0, sizeof(v4l2_event));
362                 v4l2_event.type = UVC_EVENT_STREAMON;
363                 v4l2_event_queue(&uvc->vdev, &v4l2_event);
364                 return USB_GADGET_DELAYED_STATUS;
365
366         default:
367                 return -EINVAL;
368         }
369 }
370
371 static void
372 uvc_function_disable(struct usb_function *f)
373 {
374         struct uvc_device *uvc = to_uvc(f);
375         struct v4l2_event v4l2_event;
376
377         INFO(f->config->cdev, "uvc_function_disable\n");
378
379         memset(&v4l2_event, 0, sizeof(v4l2_event));
380         v4l2_event.type = UVC_EVENT_DISCONNECT;
381         v4l2_event_queue(&uvc->vdev, &v4l2_event);
382
383         uvc->state = UVC_STATE_DISCONNECTED;
384
385         usb_ep_disable(uvc->video.ep);
386         usb_ep_disable(uvc->control_ep);
387 }
388
389 /* --------------------------------------------------------------------------
390  * Connection / disconnection
391  */
392
393 void
394 uvc_function_connect(struct uvc_device *uvc)
395 {
396         struct usb_composite_dev *cdev = uvc->func.config->cdev;
397         int ret;
398
399         if ((ret = usb_function_activate(&uvc->func)) < 0)
400                 INFO(cdev, "UVC connect failed with %d\n", ret);
401 }
402
403 void
404 uvc_function_disconnect(struct uvc_device *uvc)
405 {
406         struct usb_composite_dev *cdev = uvc->func.config->cdev;
407         int ret;
408
409         if ((ret = usb_function_deactivate(&uvc->func)) < 0)
410                 INFO(cdev, "UVC disconnect failed with %d\n", ret);
411 }
412
413 /* --------------------------------------------------------------------------
414  * USB probe and disconnect
415  */
416
417 static ssize_t function_name_show(struct device *dev,
418                                   struct device_attribute *attr, char *buf)
419 {
420         struct uvc_device *uvc = dev_get_drvdata(dev);
421
422         return sprintf(buf, "%s\n", uvc->func.fi->group.cg_item.ci_name);
423 }
424
425 static DEVICE_ATTR_RO(function_name);
426
427 static int
428 uvc_register_video(struct uvc_device *uvc)
429 {
430         struct usb_composite_dev *cdev = uvc->func.config->cdev;
431         int ret;
432
433         /* TODO reference counting. */
434         uvc->vdev.v4l2_dev = &uvc->v4l2_dev;
435         uvc->vdev.fops = &uvc_v4l2_fops;
436         uvc->vdev.ioctl_ops = &uvc_v4l2_ioctl_ops;
437         uvc->vdev.release = video_device_release_empty;
438         uvc->vdev.vfl_dir = VFL_DIR_TX;
439         uvc->vdev.lock = &uvc->video.mutex;
440         strlcpy(uvc->vdev.name, cdev->gadget->name, sizeof(uvc->vdev.name));
441
442         video_set_drvdata(&uvc->vdev, uvc);
443
444         ret = video_register_device(&uvc->vdev, VFL_TYPE_GRABBER, -1);
445         if (ret < 0)
446                 return ret;
447
448         ret = device_create_file(&uvc->vdev.dev, &dev_attr_function_name);
449         if (ret < 0) {
450                 video_unregister_device(&uvc->vdev);
451                 return ret;
452         }
453
454         return 0;
455 }
456
457 #define UVC_COPY_DESCRIPTOR(mem, dst, desc) \
458         do { \
459                 memcpy(mem, desc, (desc)->bLength); \
460                 *(dst)++ = mem; \
461                 mem += (desc)->bLength; \
462         } while (0);
463
464 #define UVC_COPY_DESCRIPTORS(mem, dst, src) \
465         do { \
466                 const struct usb_descriptor_header * const *__src; \
467                 for (__src = src; *__src; ++__src) { \
468                         memcpy(mem, *__src, (*__src)->bLength); \
469                         *dst++ = mem; \
470                         mem += (*__src)->bLength; \
471                 } \
472         } while (0)
473
474 static struct usb_descriptor_header **
475 uvc_copy_descriptors(struct uvc_device *uvc, enum usb_device_speed speed)
476 {
477         struct uvc_input_header_descriptor *uvc_streaming_header;
478         struct uvc_header_descriptor *uvc_control_header;
479         const struct uvc_descriptor_header * const *uvc_control_desc;
480         const struct uvc_descriptor_header * const *uvc_streaming_cls;
481         const struct usb_descriptor_header * const *uvc_streaming_std;
482         const struct usb_descriptor_header * const *src;
483         struct usb_descriptor_header **dst;
484         struct usb_descriptor_header **hdr;
485         unsigned int control_size;
486         unsigned int streaming_size;
487         unsigned int n_desc;
488         unsigned int bytes;
489         void *mem;
490
491         switch (speed) {
492         case USB_SPEED_SUPER:
493                 uvc_control_desc = uvc->desc.ss_control;
494                 uvc_streaming_cls = uvc->desc.ss_streaming;
495                 uvc_streaming_std = uvc_ss_streaming;
496                 break;
497
498         case USB_SPEED_HIGH:
499                 uvc_control_desc = uvc->desc.fs_control;
500                 uvc_streaming_cls = uvc->desc.hs_streaming;
501                 uvc_streaming_std = uvc_hs_streaming;
502                 break;
503
504         case USB_SPEED_FULL:
505         default:
506                 uvc_control_desc = uvc->desc.fs_control;
507                 uvc_streaming_cls = uvc->desc.fs_streaming;
508                 uvc_streaming_std = uvc_fs_streaming;
509                 break;
510         }
511
512         if (!uvc_control_desc || !uvc_streaming_cls)
513                 return ERR_PTR(-ENODEV);
514
515         /* Descriptors layout
516          *
517          * uvc_iad
518          * uvc_control_intf
519          * Class-specific UVC control descriptors
520          * uvc_control_ep
521          * uvc_control_cs_ep
522          * uvc_ss_control_comp (for SS only)
523          * uvc_streaming_intf_alt0
524          * Class-specific UVC streaming descriptors
525          * uvc_{fs|hs}_streaming
526          */
527
528         /* Count descriptors and compute their size. */
529         control_size = 0;
530         streaming_size = 0;
531         bytes = uvc_iad.bLength + uvc_control_intf.bLength
532               + uvc_control_ep.bLength + uvc_control_cs_ep.bLength
533               + uvc_streaming_intf_alt0.bLength;
534
535         if (speed == USB_SPEED_SUPER) {
536                 bytes += uvc_ss_control_comp.bLength;
537                 n_desc = 6;
538         } else {
539                 n_desc = 5;
540         }
541
542         for (src = (const struct usb_descriptor_header **)uvc_control_desc;
543              *src; ++src) {
544                 control_size += (*src)->bLength;
545                 bytes += (*src)->bLength;
546                 n_desc++;
547         }
548         for (src = (const struct usb_descriptor_header **)uvc_streaming_cls;
549              *src; ++src) {
550                 streaming_size += (*src)->bLength;
551                 bytes += (*src)->bLength;
552                 n_desc++;
553         }
554         for (src = uvc_streaming_std; *src; ++src) {
555                 bytes += (*src)->bLength;
556                 n_desc++;
557         }
558
559         mem = kmalloc((n_desc + 1) * sizeof(*src) + bytes, GFP_KERNEL);
560         if (mem == NULL)
561                 return NULL;
562
563         hdr = mem;
564         dst = mem;
565         mem += (n_desc + 1) * sizeof(*src);
566
567         /* Copy the descriptors. */
568         UVC_COPY_DESCRIPTOR(mem, dst, &uvc_iad);
569         UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_intf);
570
571         uvc_control_header = mem;
572         UVC_COPY_DESCRIPTORS(mem, dst,
573                 (const struct usb_descriptor_header **)uvc_control_desc);
574         uvc_control_header->wTotalLength = cpu_to_le16(control_size);
575         uvc_control_header->bInCollection = 1;
576         uvc_control_header->baInterfaceNr[0] = uvc->streaming_intf;
577
578         UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_ep);
579         if (speed == USB_SPEED_SUPER)
580                 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_ss_control_comp);
581
582         UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_cs_ep);
583         UVC_COPY_DESCRIPTOR(mem, dst, &uvc_streaming_intf_alt0);
584
585         uvc_streaming_header = mem;
586         UVC_COPY_DESCRIPTORS(mem, dst,
587                 (const struct usb_descriptor_header**)uvc_streaming_cls);
588         uvc_streaming_header->wTotalLength = cpu_to_le16(streaming_size);
589         uvc_streaming_header->bEndpointAddress = uvc->video.ep->address;
590
591         UVC_COPY_DESCRIPTORS(mem, dst, uvc_streaming_std);
592
593         *dst = NULL;
594         return hdr;
595 }
596
597 static int
598 uvc_function_bind(struct usb_configuration *c, struct usb_function *f)
599 {
600         struct usb_composite_dev *cdev = c->cdev;
601         struct uvc_device *uvc = to_uvc(f);
602         struct usb_string *us;
603         unsigned int max_packet_mult;
604         unsigned int max_packet_size;
605         struct usb_ep *ep;
606         struct f_uvc_opts *opts;
607         int ret = -EINVAL;
608
609         INFO(cdev, "uvc_function_bind\n");
610
611         opts = fi_to_f_uvc_opts(f->fi);
612         /* Sanity check the streaming endpoint module parameters.
613          */
614         opts->streaming_interval = clamp(opts->streaming_interval, 1U, 16U);
615         opts->streaming_maxpacket = clamp(opts->streaming_maxpacket, 1U, 3072U);
616         opts->streaming_maxburst = min(opts->streaming_maxburst, 15U);
617
618         /* For SS, wMaxPacketSize has to be 1024 if bMaxBurst is not 0 */
619         if (opts->streaming_maxburst &&
620             (opts->streaming_maxpacket % 1024) != 0) {
621                 opts->streaming_maxpacket = roundup(opts->streaming_maxpacket, 1024);
622                 INFO(cdev, "overriding streaming_maxpacket to %d\n",
623                      opts->streaming_maxpacket);
624         }
625
626         /* Fill in the FS/HS/SS Video Streaming specific descriptors from the
627          * module parameters.
628          *
629          * NOTE: We assume that the user knows what they are doing and won't
630          * give parameters that their UDC doesn't support.
631          */
632         if (opts->streaming_maxpacket <= 1024) {
633                 max_packet_mult = 1;
634                 max_packet_size = opts->streaming_maxpacket;
635         } else if (opts->streaming_maxpacket <= 2048) {
636                 max_packet_mult = 2;
637                 max_packet_size = opts->streaming_maxpacket / 2;
638         } else {
639                 max_packet_mult = 3;
640                 max_packet_size = opts->streaming_maxpacket / 3;
641         }
642
643         uvc_fs_streaming_ep.wMaxPacketSize =
644                 cpu_to_le16(min(opts->streaming_maxpacket, 1023U));
645         uvc_fs_streaming_ep.bInterval = opts->streaming_interval;
646
647         uvc_hs_streaming_ep.wMaxPacketSize =
648                 cpu_to_le16(max_packet_size | ((max_packet_mult - 1) << 11));
649
650         /* A high-bandwidth endpoint must specify a bInterval value of 1 */
651         if (max_packet_mult > 1)
652                 uvc_hs_streaming_ep.bInterval = 1;
653         else
654                 uvc_hs_streaming_ep.bInterval = opts->streaming_interval;
655
656         uvc_ss_streaming_ep.wMaxPacketSize = cpu_to_le16(max_packet_size);
657         uvc_ss_streaming_ep.bInterval = opts->streaming_interval;
658         uvc_ss_streaming_comp.bmAttributes = max_packet_mult - 1;
659         uvc_ss_streaming_comp.bMaxBurst = opts->streaming_maxburst;
660         uvc_ss_streaming_comp.wBytesPerInterval =
661                 cpu_to_le16(max_packet_size * max_packet_mult *
662                             (opts->streaming_maxburst + 1));
663
664         /* Allocate endpoints. */
665         ep = usb_ep_autoconfig(cdev->gadget, &uvc_control_ep);
666         if (!ep) {
667                 INFO(cdev, "Unable to allocate control EP\n");
668                 goto error;
669         }
670         uvc->control_ep = ep;
671
672         if (gadget_is_superspeed(c->cdev->gadget))
673                 ep = usb_ep_autoconfig_ss(cdev->gadget, &uvc_ss_streaming_ep,
674                                           &uvc_ss_streaming_comp);
675         else if (gadget_is_dualspeed(cdev->gadget))
676                 ep = usb_ep_autoconfig(cdev->gadget, &uvc_hs_streaming_ep);
677         else
678                 ep = usb_ep_autoconfig(cdev->gadget, &uvc_fs_streaming_ep);
679
680         if (!ep) {
681                 INFO(cdev, "Unable to allocate streaming EP\n");
682                 goto error;
683         }
684         uvc->video.ep = ep;
685
686         uvc_fs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
687         uvc_hs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
688         uvc_ss_streaming_ep.bEndpointAddress = uvc->video.ep->address;
689
690         us = usb_gstrings_attach(cdev, uvc_function_strings,
691                                  ARRAY_SIZE(uvc_en_us_strings));
692         if (IS_ERR(us)) {
693                 ret = PTR_ERR(us);
694                 goto error;
695         }
696         uvc_iad.iFunction = us[UVC_STRING_CONTROL_IDX].id;
697         uvc_control_intf.iInterface = us[UVC_STRING_CONTROL_IDX].id;
698         ret = us[UVC_STRING_STREAMING_IDX].id;
699         uvc_streaming_intf_alt0.iInterface = ret;
700         uvc_streaming_intf_alt1.iInterface = ret;
701
702         /* Allocate interface IDs. */
703         if ((ret = usb_interface_id(c, f)) < 0)
704                 goto error;
705         uvc_iad.bFirstInterface = ret;
706         uvc_control_intf.bInterfaceNumber = ret;
707         uvc->control_intf = 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
715         /* Copy descriptors */
716         f->fs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_FULL);
717         if (IS_ERR(f->fs_descriptors)) {
718                 ret = PTR_ERR(f->fs_descriptors);
719                 f->fs_descriptors = NULL;
720                 goto error;
721         }
722         if (gadget_is_dualspeed(cdev->gadget)) {
723                 f->hs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_HIGH);
724                 if (IS_ERR(f->hs_descriptors)) {
725                         ret = PTR_ERR(f->hs_descriptors);
726                         f->hs_descriptors = NULL;
727                         goto error;
728                 }
729         }
730         if (gadget_is_superspeed(c->cdev->gadget)) {
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
739         /* Preallocate control endpoint request. */
740         uvc->control_req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
741         uvc->control_buf = kmalloc(UVC_MAX_REQUEST_SIZE, GFP_KERNEL);
742         if (uvc->control_req == NULL || uvc->control_buf == NULL) {
743                 ret = -ENOMEM;
744                 goto error;
745         }
746
747         uvc->control_req->buf = uvc->control_buf;
748         uvc->control_req->complete = uvc_function_ep0_complete;
749         uvc->control_req->context = uvc;
750
751         if (v4l2_device_register(&cdev->gadget->dev, &uvc->v4l2_dev)) {
752                 printk(KERN_INFO "v4l2_device_register failed\n");
753                 goto error;
754         }
755
756         /* Initialise video. */
757         ret = uvcg_video_init(&uvc->video);
758         if (ret < 0)
759                 goto error;
760
761         /* Register a V4L2 device. */
762         ret = uvc_register_video(uvc);
763         if (ret < 0) {
764                 printk(KERN_INFO "Unable to register video device\n");
765                 goto error;
766         }
767
768         return 0;
769
770 error:
771         v4l2_device_unregister(&uvc->v4l2_dev);
772
773         if (uvc->control_req)
774                 usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
775         kfree(uvc->control_buf);
776
777         usb_free_all_descriptors(f);
778         return ret;
779 }
780
781 /* --------------------------------------------------------------------------
782  * USB gadget function
783  */
784
785 static void uvc_free_inst(struct usb_function_instance *f)
786 {
787         struct f_uvc_opts *opts = fi_to_f_uvc_opts(f);
788
789         mutex_destroy(&opts->lock);
790         kfree(opts);
791 }
792
793 static struct usb_function_instance *uvc_alloc_inst(void)
794 {
795         struct f_uvc_opts *opts;
796         struct uvc_camera_terminal_descriptor *cd;
797         struct uvc_processing_unit_descriptor *pd;
798         struct uvc_output_terminal_descriptor *od;
799         struct uvc_color_matching_descriptor *md;
800         struct uvc_descriptor_header **ctl_cls;
801
802         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
803         if (!opts)
804                 return ERR_PTR(-ENOMEM);
805         opts->func_inst.free_func_inst = uvc_free_inst;
806         mutex_init(&opts->lock);
807
808         cd = &opts->uvc_camera_terminal;
809         cd->bLength                     = UVC_DT_CAMERA_TERMINAL_SIZE(3);
810         cd->bDescriptorType             = USB_DT_CS_INTERFACE;
811         cd->bDescriptorSubType          = UVC_VC_INPUT_TERMINAL;
812         cd->bTerminalID                 = 1;
813         cd->wTerminalType               = cpu_to_le16(0x0201);
814         cd->bAssocTerminal              = 0;
815         cd->iTerminal                   = 0;
816         cd->wObjectiveFocalLengthMin    = cpu_to_le16(0);
817         cd->wObjectiveFocalLengthMax    = cpu_to_le16(0);
818         cd->wOcularFocalLength          = cpu_to_le16(0);
819         cd->bControlSize                = 3;
820         cd->bmControls[0]               = 2;
821         cd->bmControls[1]               = 0;
822         cd->bmControls[2]               = 0;
823
824         pd = &opts->uvc_processing;
825         pd->bLength                     = UVC_DT_PROCESSING_UNIT_SIZE(2);
826         pd->bDescriptorType             = USB_DT_CS_INTERFACE;
827         pd->bDescriptorSubType          = UVC_VC_PROCESSING_UNIT;
828         pd->bUnitID                     = 2;
829         pd->bSourceID                   = 1;
830         pd->wMaxMultiplier              = cpu_to_le16(16*1024);
831         pd->bControlSize                = 2;
832         pd->bmControls[0]               = 1;
833         pd->bmControls[1]               = 0;
834         pd->iProcessing                 = 0;
835
836         od = &opts->uvc_output_terminal;
837         od->bLength                     = UVC_DT_OUTPUT_TERMINAL_SIZE;
838         od->bDescriptorType             = USB_DT_CS_INTERFACE;
839         od->bDescriptorSubType          = UVC_VC_OUTPUT_TERMINAL;
840         od->bTerminalID                 = 3;
841         od->wTerminalType               = cpu_to_le16(0x0101);
842         od->bAssocTerminal              = 0;
843         od->bSourceID                   = 2;
844         od->iTerminal                   = 0;
845
846         md = &opts->uvc_color_matching;
847         md->bLength                     = UVC_DT_COLOR_MATCHING_SIZE;
848         md->bDescriptorType             = USB_DT_CS_INTERFACE;
849         md->bDescriptorSubType          = UVC_VS_COLORFORMAT;
850         md->bColorPrimaries             = 1;
851         md->bTransferCharacteristics    = 1;
852         md->bMatrixCoefficients         = 4;
853
854         /* Prepare fs control class descriptors for configfs-based gadgets */
855         ctl_cls = opts->uvc_fs_control_cls;
856         ctl_cls[0] = NULL;      /* assigned elsewhere by configfs */
857         ctl_cls[1] = (struct uvc_descriptor_header *)cd;
858         ctl_cls[2] = (struct uvc_descriptor_header *)pd;
859         ctl_cls[3] = (struct uvc_descriptor_header *)od;
860         ctl_cls[4] = NULL;      /* NULL-terminate */
861         opts->fs_control =
862                 (const struct uvc_descriptor_header * const *)ctl_cls;
863
864         /* Prepare hs control class descriptors for configfs-based gadgets */
865         ctl_cls = opts->uvc_ss_control_cls;
866         ctl_cls[0] = NULL;      /* assigned elsewhere by configfs */
867         ctl_cls[1] = (struct uvc_descriptor_header *)cd;
868         ctl_cls[2] = (struct uvc_descriptor_header *)pd;
869         ctl_cls[3] = (struct uvc_descriptor_header *)od;
870         ctl_cls[4] = NULL;      /* NULL-terminate */
871         opts->ss_control =
872                 (const struct uvc_descriptor_header * const *)ctl_cls;
873
874         opts->streaming_interval = 1;
875         opts->streaming_maxpacket = 1024;
876
877         uvcg_attach_configfs(opts);
878         return &opts->func_inst;
879 }
880
881 static void uvc_free(struct usb_function *f)
882 {
883         struct uvc_device *uvc = to_uvc(f);
884         struct f_uvc_opts *opts = container_of(f->fi, struct f_uvc_opts,
885                                                func_inst);
886         --opts->refcnt;
887         kfree(uvc);
888 }
889
890 static void uvc_unbind(struct usb_configuration *c, struct usb_function *f)
891 {
892         struct usb_composite_dev *cdev = c->cdev;
893         struct uvc_device *uvc = to_uvc(f);
894
895         INFO(cdev, "%s\n", __func__);
896
897         device_remove_file(&uvc->vdev.dev, &dev_attr_function_name);
898         video_unregister_device(&uvc->vdev);
899         v4l2_device_unregister(&uvc->v4l2_dev);
900
901         usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
902         kfree(uvc->control_buf);
903
904         usb_free_all_descriptors(f);
905 }
906
907 static struct usb_function *uvc_alloc(struct usb_function_instance *fi)
908 {
909         struct uvc_device *uvc;
910         struct f_uvc_opts *opts;
911         struct uvc_descriptor_header **strm_cls;
912
913         uvc = kzalloc(sizeof(*uvc), GFP_KERNEL);
914         if (uvc == NULL)
915                 return ERR_PTR(-ENOMEM);
916
917         mutex_init(&uvc->video.mutex);
918         uvc->state = UVC_STATE_DISCONNECTED;
919         opts = fi_to_f_uvc_opts(fi);
920
921         mutex_lock(&opts->lock);
922         if (opts->uvc_fs_streaming_cls) {
923                 strm_cls = opts->uvc_fs_streaming_cls;
924                 opts->fs_streaming =
925                         (const struct uvc_descriptor_header * const *)strm_cls;
926         }
927         if (opts->uvc_hs_streaming_cls) {
928                 strm_cls = opts->uvc_hs_streaming_cls;
929                 opts->hs_streaming =
930                         (const struct uvc_descriptor_header * const *)strm_cls;
931         }
932         if (opts->uvc_ss_streaming_cls) {
933                 strm_cls = opts->uvc_ss_streaming_cls;
934                 opts->ss_streaming =
935                         (const struct uvc_descriptor_header * const *)strm_cls;
936         }
937
938         uvc->desc.fs_control = opts->fs_control;
939         uvc->desc.ss_control = opts->ss_control;
940         uvc->desc.fs_streaming = opts->fs_streaming;
941         uvc->desc.hs_streaming = opts->hs_streaming;
942         uvc->desc.ss_streaming = opts->ss_streaming;
943         ++opts->refcnt;
944         mutex_unlock(&opts->lock);
945
946         /* Register the function. */
947         uvc->func.name = "uvc";
948         uvc->func.bind = uvc_function_bind;
949         uvc->func.unbind = uvc_unbind;
950         uvc->func.get_alt = uvc_function_get_alt;
951         uvc->func.set_alt = uvc_function_set_alt;
952         uvc->func.disable = uvc_function_disable;
953         uvc->func.setup = uvc_function_setup;
954         uvc->func.free_func = uvc_free;
955         uvc->func.bind_deactivated = true;
956
957         return &uvc->func;
958 }
959
960 DECLARE_USB_FUNCTION_INIT(uvc, uvc_alloc_inst, uvc_alloc);
961 MODULE_LICENSE("GPL");
962 MODULE_AUTHOR("Laurent Pinchart");