1 // SPDX-License-Identifier: GPL-2.0+
3 * uvc_video.c -- USB Video Class Gadget driver
5 * Copyright (C) 2009-2010
6 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
9 #include <linux/kernel.h>
10 #include <linux/device.h>
11 #include <linux/errno.h>
12 #include <linux/usb/ch9.h>
13 #include <linux/usb/gadget.h>
14 #include <linux/usb/video.h>
15 #include <asm/unaligned.h>
17 #include <media/v4l2-dev.h>
20 #include "uvc_queue.h"
21 #include "uvc_video.h"
23 /* --------------------------------------------------------------------------
28 uvc_video_encode_header(struct uvc_video *video, struct uvc_buffer *buf,
31 struct uvc_device *uvc = container_of(video, struct uvc_device, video);
32 struct usb_composite_dev *cdev = uvc->func.config->cdev;
33 struct timespec64 ts = ns_to_timespec64(buf->buf.vb2_buf.timestamp);
36 data[1] = UVC_STREAM_EOH | video->fid;
38 if (video->queue.flags & UVC_QUEUE_DROP_INCOMPLETE)
39 data[1] |= UVC_STREAM_ERR;
41 if (video->queue.buf_used == 0 && ts.tv_sec) {
42 /* dwClockFrequency is 48 MHz */
43 u32 pts = ((u64)ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / NSEC_PER_USEC) * 48;
45 data[1] |= UVC_STREAM_PTS;
46 put_unaligned_le32(pts, &data[pos]);
50 if (cdev->gadget->ops->get_frame) {
53 sof = usb_gadget_frame_number(cdev->gadget);
55 stc = ((u64)ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / NSEC_PER_USEC) * 48;
57 data[1] |= UVC_STREAM_SCR;
58 put_unaligned_le32(stc, &data[pos]);
59 put_unaligned_le16(sof, &data[pos+4]);
65 if (buf->bytesused - video->queue.buf_used <= len - pos)
66 data[1] |= UVC_STREAM_EOF;
72 uvc_video_encode_data(struct uvc_video *video, struct uvc_buffer *buf,
75 struct uvc_video_queue *queue = &video->queue;
79 /* Copy video data to the USB buffer. */
80 mem = buf->mem + queue->buf_used;
81 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
83 memcpy(data, mem, nbytes);
84 queue->buf_used += nbytes;
90 uvc_video_encode_bulk(struct usb_request *req, struct uvc_video *video,
91 struct uvc_buffer *buf)
94 struct uvc_request *ureq = req->context;
95 int len = video->req_size;
98 /* Add a header at the beginning of the payload. */
99 if (video->payload_size == 0) {
100 ret = uvc_video_encode_header(video, buf, mem, len);
101 video->payload_size += ret;
106 /* Process video data. */
107 len = min((int)(video->max_payload_size - video->payload_size), len);
108 ret = uvc_video_encode_data(video, buf, mem, len);
110 video->payload_size += ret;
113 req->length = video->req_size - len;
114 req->zero = video->payload_size == video->max_payload_size;
116 if (buf->bytesused == video->queue.buf_used) {
117 video->queue.buf_used = 0;
118 buf->state = UVC_BUF_STATE_DONE;
119 list_del(&buf->queue);
120 video->fid ^= UVC_STREAM_FID;
121 ureq->last_buf = buf;
123 video->payload_size = 0;
126 if (video->payload_size == video->max_payload_size ||
127 video->queue.flags & UVC_QUEUE_DROP_INCOMPLETE ||
128 buf->bytesused == video->queue.buf_used)
129 video->payload_size = 0;
133 uvc_video_encode_isoc_sg(struct usb_request *req, struct uvc_video *video,
134 struct uvc_buffer *buf)
136 unsigned int pending = buf->bytesused - video->queue.buf_used;
137 struct uvc_request *ureq = req->context;
138 struct scatterlist *sg, *iter;
139 unsigned int len = video->req_size;
140 unsigned int sg_left, part = 0;
145 sg_init_table(sg, ureq->sgt.nents);
147 /* Init the header. */
148 header_len = uvc_video_encode_header(video, buf, ureq->header,
150 sg_set_buf(sg, ureq->header, header_len);
156 req->length = (len == pending) ?
157 len + header_len : video->req_size;
159 /* Init the pending sgs with payload */
162 for_each_sg(sg, iter, ureq->sgt.nents - 1, i) {
163 if (!len || !buf->sg || !buf->sg->length)
166 sg_left = buf->sg->length - buf->offset;
167 part = min_t(unsigned int, len, sg_left);
169 sg_set_page(iter, sg_page(buf->sg), part, buf->offset);
171 if (part == sg_left) {
173 buf->sg = sg_next(buf->sg);
180 /* Assign the video data with header. */
182 req->sg = ureq->sgt.sgl;
183 req->num_sgs = i + 1;
186 video->queue.buf_used += req->length - header_len;
188 if (buf->bytesused == video->queue.buf_used || !buf->sg ||
189 video->queue.flags & UVC_QUEUE_DROP_INCOMPLETE) {
190 video->queue.buf_used = 0;
191 buf->state = UVC_BUF_STATE_DONE;
193 list_del(&buf->queue);
194 video->fid ^= UVC_STREAM_FID;
195 ureq->last_buf = buf;
200 uvc_video_encode_isoc(struct usb_request *req, struct uvc_video *video,
201 struct uvc_buffer *buf)
203 void *mem = req->buf;
204 struct uvc_request *ureq = req->context;
205 int len = video->req_size;
208 /* Add the header. */
209 ret = uvc_video_encode_header(video, buf, mem, len);
213 /* Process video data. */
214 ret = uvc_video_encode_data(video, buf, mem, len);
217 req->length = video->req_size - len;
219 if (buf->bytesused == video->queue.buf_used ||
220 video->queue.flags & UVC_QUEUE_DROP_INCOMPLETE) {
221 video->queue.buf_used = 0;
222 buf->state = UVC_BUF_STATE_DONE;
223 list_del(&buf->queue);
224 video->fid ^= UVC_STREAM_FID;
225 ureq->last_buf = buf;
229 /* --------------------------------------------------------------------------
234 * Callers must take care to hold req_lock when this function may be called
235 * from multiple threads. For example, when frames are streaming to the host.
238 uvc_video_free_request(struct uvc_request *ureq, struct usb_ep *ep)
240 sg_free_table(&ureq->sgt);
241 if (ureq->req && ep) {
242 usb_ep_free_request(ep, ureq->req);
246 kfree(ureq->req_buffer);
247 ureq->req_buffer = NULL;
249 if (!list_empty(&ureq->list))
250 list_del_init(&ureq->list);
255 static int uvcg_video_ep_queue(struct uvc_video *video, struct usb_request *req)
259 ret = usb_ep_queue(video->ep, req, GFP_ATOMIC);
261 uvcg_err(&video->uvc->func, "Failed to queue request (%d).\n",
264 /* If the endpoint is disabled the descriptor may be NULL. */
265 if (video->ep->desc) {
266 /* Isochronous endpoints can't be halted. */
267 if (usb_endpoint_xfer_bulk(video->ep->desc))
268 usb_ep_set_halt(video->ep);
275 /* This function must be called with video->req_lock held. */
276 static int uvcg_video_usb_req_queue(struct uvc_video *video,
277 struct usb_request *req, bool queue_to_ep)
279 bool is_bulk = video->max_payload_size;
280 struct list_head *list = NULL;
282 if (!video->is_enabled)
286 struct uvc_request *ureq = req->context;
288 * With USB3 handling more requests at a higher speed, we can't
289 * afford to generate an interrupt for every request. Decide to
292 * - When no more requests are available in the free queue, as
293 * this may be our last chance to refill the endpoint's
296 * - When this is request is the last request for the video
297 * buffer, as we want to start sending the next video buffer
298 * ASAP in case it doesn't get started already in the next
299 * iteration of this loop.
301 * - Four times over the length of the requests queue (as
302 * indicated by video->uvc_num_requests), as a trade-off
303 * between latency and interrupt load.
305 if (list_empty(&video->req_free) || ureq->last_buf ||
306 !(video->req_int_count %
307 DIV_ROUND_UP(video->uvc_num_requests, 4))) {
308 video->req_int_count = 0;
309 req->no_interrupt = 0;
311 req->no_interrupt = 1;
313 video->req_int_count++;
314 return uvcg_video_ep_queue(video, req);
317 * If we're not queuing to the ep, for isoc we're queuing
318 * to the req_ready list, otherwise req_free.
320 list = is_bulk ? &video->req_free : &video->req_ready;
321 list_add_tail(&req->list, list);
326 * Must only be called from uvcg_video_enable - since after that we only want to
327 * queue requests to the endpoint from the uvc_video_complete complete handler.
328 * This function is needed in order to 'kick start' the flow of requests from
329 * gadget driver to the usb controller.
331 static void uvc_video_ep_queue_initial_requests(struct uvc_video *video)
333 struct usb_request *req = NULL;
334 unsigned long flags = 0;
335 unsigned int count = 0;
339 * We only queue half of the free list since we still want to have
340 * some free usb_requests in the free list for the video_pump async_wq
341 * thread to encode uvc buffers into. Otherwise we could get into a
342 * situation where the free list does not have any usb requests to
343 * encode into - we always end up queueing 0 length requests to the
346 unsigned int half_list_size = video->uvc_num_requests / 2;
348 spin_lock_irqsave(&video->req_lock, flags);
350 * Take these requests off the free list and queue them all to the
351 * endpoint. Since we queue 0 length requests with the req_lock held,
352 * there isn't any 'data' race involved here with the complete handler.
354 while (count < half_list_size) {
355 req = list_first_entry(&video->req_free, struct usb_request,
357 list_del(&req->list);
359 ret = uvcg_video_ep_queue(video, req);
361 uvcg_queue_cancel(&video->queue, 0);
366 spin_unlock_irqrestore(&video->req_lock, flags);
370 uvc_video_complete(struct usb_ep *ep, struct usb_request *req)
372 struct uvc_request *ureq = req->context;
373 struct uvc_video *video = ureq->video;
374 struct uvc_video_queue *queue = &video->queue;
375 struct uvc_buffer *last_buf;
377 bool is_bulk = video->max_payload_size;
380 spin_lock_irqsave(&video->req_lock, flags);
381 if (!video->is_enabled) {
383 * When is_enabled is false, uvcg_video_disable() ensures
384 * that in-flight uvc_buffers are returned, so we can
385 * safely call free_request without worrying about
388 uvc_video_free_request(ureq, ep);
389 spin_unlock_irqrestore(&video->req_lock, flags);
393 last_buf = ureq->last_buf;
394 ureq->last_buf = NULL;
395 spin_unlock_irqrestore(&video->req_lock, flags);
397 switch (req->status) {
402 uvcg_dbg(&video->uvc->func, "VS request missed xfer.\n");
403 queue->flags |= UVC_QUEUE_DROP_INCOMPLETE;
406 case -ESHUTDOWN: /* disconnect from host. */
407 uvcg_dbg(&video->uvc->func, "VS request cancelled.\n");
408 uvcg_queue_cancel(queue, 1);
412 uvcg_warn(&video->uvc->func,
413 "VS request completed with status %d.\n",
415 uvcg_queue_cancel(queue, 0);
419 spin_lock_irqsave(&queue->irqlock, flags);
420 uvcg_complete_buffer(queue, last_buf);
421 spin_unlock_irqrestore(&queue->irqlock, flags);
424 spin_lock_irqsave(&video->req_lock, flags);
426 * Video stream might have been disabled while we were
427 * processing the current usb_request. So make sure
428 * we're still streaming before queueing the usb_request
431 if (video->is_enabled) {
433 * Here we check whether any request is available in the ready
434 * list. If it is, queue it to the ep and add the current
435 * usb_request to the req_free list - for video_pump to fill in.
436 * Otherwise, just use the current usb_request to queue a 0
437 * length request to the ep. Since we always add to the req_free
438 * list if we dequeue from the ready list, there will never
439 * be a situation where the req_free list is completely out of
440 * requests and cannot recover.
442 struct usb_request *to_queue = req;
444 to_queue->length = 0;
445 if (!list_empty(&video->req_ready)) {
446 to_queue = list_first_entry(&video->req_ready,
447 struct usb_request, list);
448 list_del(&to_queue->list);
449 list_add_tail(&req->list, &video->req_free);
451 * Queue work to the wq as well since it is possible that a
452 * buffer may not have been completely encoded with the set of
453 * in-flight usb requests for whih the complete callbacks are
455 * In that case, if we do not queue work to the worker thread,
456 * the buffer will never be marked as complete - and therefore
457 * not be returned to userpsace. As a result,
458 * dequeue -> queue -> dequeue flow of uvc buffers will not
461 queue_work(video->async_wq, &video->pump);
464 * Queue to the endpoint. The actual queueing to ep will
465 * only happen on one thread - the async_wq for bulk endpoints
466 * and this thread for isoc endpoints.
468 ret = uvcg_video_usb_req_queue(video, to_queue, !is_bulk);
471 * Endpoint error, but the stream is still enabled.
472 * Put request back in req_free for it to be cleaned
475 list_add_tail(&to_queue->list, &video->req_free);
478 uvc_video_free_request(ureq, ep);
481 spin_unlock_irqrestore(&video->req_lock, flags);
483 uvcg_queue_cancel(queue, 0);
487 uvc_video_free_requests(struct uvc_video *video)
489 struct uvc_request *ureq, *temp;
491 list_for_each_entry_safe(ureq, temp, &video->ureqs, list)
492 uvc_video_free_request(ureq, video->ep);
494 INIT_LIST_HEAD(&video->ureqs);
495 INIT_LIST_HEAD(&video->req_free);
496 INIT_LIST_HEAD(&video->req_ready);
502 uvc_video_alloc_requests(struct uvc_video *video)
504 struct uvc_request *ureq;
505 unsigned int req_size;
509 BUG_ON(video->req_size);
511 req_size = video->ep->maxpacket
512 * max_t(unsigned int, video->ep->maxburst, 1)
515 for (i = 0; i < video->uvc_num_requests; i++) {
516 ureq = kzalloc(sizeof(struct uvc_request), GFP_KERNEL);
520 INIT_LIST_HEAD(&ureq->list);
522 list_add_tail(&ureq->list, &video->ureqs);
524 ureq->req_buffer = kmalloc(req_size, GFP_KERNEL);
525 if (ureq->req_buffer == NULL)
528 ureq->req = usb_ep_alloc_request(video->ep, GFP_KERNEL);
529 if (ureq->req == NULL)
532 ureq->req->buf = ureq->req_buffer;
533 ureq->req->length = 0;
534 ureq->req->complete = uvc_video_complete;
535 ureq->req->context = ureq;
537 ureq->last_buf = NULL;
539 list_add_tail(&ureq->req->list, &video->req_free);
540 /* req_size/PAGE_SIZE + 1 for overruns and + 1 for header */
541 sg_alloc_table(&ureq->sgt,
542 DIV_ROUND_UP(req_size - UVCG_REQUEST_HEADER_LEN,
543 PAGE_SIZE) + 2, GFP_KERNEL);
546 video->req_size = req_size;
551 uvc_video_free_requests(video);
555 /* --------------------------------------------------------------------------
560 * uvcg_video_pump - Pump video data into the USB requests
562 * This function fills the available USB requests (listed in req_free) with
563 * video data from the queued buffers.
565 static void uvcg_video_pump(struct work_struct *work)
567 struct uvc_video *video = container_of(work, struct uvc_video, pump);
568 struct uvc_video_queue *queue = &video->queue;
569 /* video->max_payload_size is only set when using bulk transfer */
570 bool is_bulk = video->max_payload_size;
571 struct usb_request *req = NULL;
572 struct uvc_buffer *buf;
577 if (!video->ep->enabled)
581 * Check is_enabled and retrieve the first available USB
582 * request, protected by the request lock.
584 spin_lock_irqsave(&video->req_lock, flags);
585 if (!video->is_enabled || list_empty(&video->req_free)) {
586 spin_unlock_irqrestore(&video->req_lock, flags);
589 req = list_first_entry(&video->req_free, struct usb_request,
591 list_del(&req->list);
592 spin_unlock_irqrestore(&video->req_lock, flags);
595 * Retrieve the first available video buffer and fill the
596 * request, protected by the video queue irqlock.
598 spin_lock_irqsave(&queue->irqlock, flags);
599 buf = uvcg_queue_head(queue);
602 * Either the queue has been disconnected or no video buffer
603 * available for bulk transfer. Either way, stop processing
606 spin_unlock_irqrestore(&queue->irqlock, flags);
610 video->encode(req, video, buf);
612 spin_unlock_irqrestore(&queue->irqlock, flags);
614 spin_lock_irqsave(&video->req_lock, flags);
615 /* For bulk end points we queue from the worker thread
616 * since we would preferably not want to wait on requests
617 * to be ready, in the uvcg_video_complete() handler.
618 * For isoc endpoints we add the request to the ready list
619 * and only queue it to the endpoint from the complete handler.
621 ret = uvcg_video_usb_req_queue(video, req, is_bulk);
622 spin_unlock_irqrestore(&video->req_lock, flags);
625 uvcg_queue_cancel(queue, 0);
629 /* The request is owned by the endpoint / ready list. */
636 spin_lock_irqsave(&video->req_lock, flags);
637 if (video->is_enabled)
638 list_add_tail(&req->list, &video->req_free);
640 uvc_video_free_request(req->context, video->ep);
641 spin_unlock_irqrestore(&video->req_lock, flags);
645 * Disable the video stream
648 uvcg_video_disable(struct uvc_video *video)
651 struct list_head inflight_bufs;
652 struct usb_request *req, *temp;
653 struct uvc_buffer *buf, *btemp;
654 struct uvc_request *ureq, *utemp;
656 if (video->ep == NULL) {
657 uvcg_info(&video->uvc->func,
658 "Video disable failed, device is uninitialized.\n");
662 INIT_LIST_HEAD(&inflight_bufs);
663 spin_lock_irqsave(&video->req_lock, flags);
664 video->is_enabled = false;
667 * Remove any in-flight buffers from the uvc_requests
668 * because we want to return them before cancelling the
669 * queue. This ensures that we aren't stuck waiting for
670 * all complete callbacks to come through before disabling
673 list_for_each_entry(ureq, &video->ureqs, list) {
674 if (ureq->last_buf) {
675 list_add_tail(&ureq->last_buf->queue, &inflight_bufs);
676 ureq->last_buf = NULL;
679 spin_unlock_irqrestore(&video->req_lock, flags);
681 cancel_work_sync(&video->pump);
682 uvcg_queue_cancel(&video->queue, 0);
684 spin_lock_irqsave(&video->req_lock, flags);
686 * Remove all uvc_requests from ureqs with list_del_init
687 * This lets uvc_video_free_request correctly identify
688 * if the uvc_request is attached to a list or not when freeing
691 list_for_each_entry_safe(ureq, utemp, &video->ureqs, list)
692 list_del_init(&ureq->list);
694 list_for_each_entry_safe(req, temp, &video->req_free, list) {
695 list_del(&req->list);
696 uvc_video_free_request(req->context, video->ep);
699 list_for_each_entry_safe(req, temp, &video->req_ready, list) {
700 list_del(&req->list);
701 uvc_video_free_request(req->context, video->ep);
704 INIT_LIST_HEAD(&video->ureqs);
705 INIT_LIST_HEAD(&video->req_free);
706 INIT_LIST_HEAD(&video->req_ready);
708 spin_unlock_irqrestore(&video->req_lock, flags);
711 * Return all the video buffers before disabling the queue.
713 spin_lock_irqsave(&video->queue.irqlock, flags);
714 list_for_each_entry_safe(buf, btemp, &inflight_bufs, queue) {
715 list_del(&buf->queue);
716 uvcg_complete_buffer(&video->queue, buf);
718 spin_unlock_irqrestore(&video->queue.irqlock, flags);
720 uvcg_queue_enable(&video->queue, 0);
725 * Enable the video stream.
727 int uvcg_video_enable(struct uvc_video *video)
731 if (video->ep == NULL) {
732 uvcg_info(&video->uvc->func,
733 "Video enable failed, device is uninitialized.\n");
738 * Safe to access request related fields without req_lock because
739 * this is the only thread currently active, and no other
740 * request handling thread will become active until this function
743 video->is_enabled = true;
745 if ((ret = uvcg_queue_enable(&video->queue, 1)) < 0)
748 if ((ret = uvc_video_alloc_requests(video)) < 0)
751 if (video->max_payload_size) {
752 video->encode = uvc_video_encode_bulk;
753 video->payload_size = 0;
755 video->encode = video->queue.use_sg ?
756 uvc_video_encode_isoc_sg : uvc_video_encode_isoc;
758 video->req_int_count = 0;
760 uvc_video_ep_queue_initial_requests(video);
766 * Initialize the UVC video stream.
768 int uvcg_video_init(struct uvc_video *video, struct uvc_device *uvc)
770 video->is_enabled = false;
771 INIT_LIST_HEAD(&video->ureqs);
772 INIT_LIST_HEAD(&video->req_free);
773 INIT_LIST_HEAD(&video->req_ready);
774 spin_lock_init(&video->req_lock);
775 INIT_WORK(&video->pump, uvcg_video_pump);
777 /* Allocate a work queue for asynchronous video pump handler. */
778 video->async_wq = alloc_workqueue("uvcgadget", WQ_UNBOUND | WQ_HIGHPRI, 0);
779 if (!video->async_wq)
783 video->fcc = V4L2_PIX_FMT_YUYV;
787 video->imagesize = 320 * 240 * 2;
789 /* Initialize the video buffers queue. */
790 uvcg_queue_init(&video->queue, uvc->v4l2_dev.dev->parent,
791 V4L2_BUF_TYPE_VIDEO_OUTPUT, &video->mutex);