1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * uvc_video.c -- USB Video Class driver - Video handling 4 * 5 * Copyright (C) 2005-2010 6 * Laurent Pinchart (laurent.pinchart@ideasonboard.com) 7 */ 8 9 #include <linux/dma-mapping.h> 10 #include <linux/highmem.h> 11 #include <linux/kernel.h> 12 #include <linux/list.h> 13 #include <linux/module.h> 14 #include <linux/slab.h> 15 #include <linux/usb.h> 16 #include <linux/usb/hcd.h> 17 #include <linux/videodev2.h> 18 #include <linux/vmalloc.h> 19 #include <linux/wait.h> 20 #include <linux/atomic.h> 21 #include <linux/unaligned.h> 22 23 #include <media/jpeg.h> 24 #include <media/v4l2-common.h> 25 26 #include "uvcvideo.h" 27 28 /* ------------------------------------------------------------------------ 29 * UVC Controls 30 */ 31 32 static int __uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit, 33 u8 intfnum, u8 cs, void *data, u16 size, 34 int timeout) 35 { 36 u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE; 37 unsigned int pipe; 38 39 pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0) 40 : usb_sndctrlpipe(dev->udev, 0); 41 type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT; 42 43 return usb_control_msg(dev->udev, pipe, query, type, cs << 8, 44 unit << 8 | intfnum, data, size, timeout); 45 } 46 47 static const char *uvc_query_name(u8 query) 48 { 49 switch (query) { 50 case UVC_SET_CUR: 51 return "SET_CUR"; 52 case UVC_GET_CUR: 53 return "GET_CUR"; 54 case UVC_GET_MIN: 55 return "GET_MIN"; 56 case UVC_GET_MAX: 57 return "GET_MAX"; 58 case UVC_GET_RES: 59 return "GET_RES"; 60 case UVC_GET_LEN: 61 return "GET_LEN"; 62 case UVC_GET_INFO: 63 return "GET_INFO"; 64 case UVC_GET_DEF: 65 return "GET_DEF"; 66 default: 67 return "<invalid>"; 68 } 69 } 70 71 int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit, 72 u8 intfnum, u8 cs, void *data, u16 size) 73 { 74 int ret; 75 u8 error; 76 u8 tmp; 77 78 ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size, 79 UVC_CTRL_CONTROL_TIMEOUT); 80 if (likely(ret == size)) 81 return 0; 82 83 /* 84 * Some devices return shorter USB control packets than expected if the 85 * returned value can fit in less bytes. Zero all the bytes that the 86 * device has not written. 87 * 88 * This quirk is applied to all controls, regardless of their data type. 89 * Most controls are little-endian integers, in which case the missing 90 * bytes become 0 MSBs. For other data types, a different heuristic 91 * could be implemented if a device is found needing it. 92 * 93 * We exclude UVC_GET_INFO from the quirk. UVC_GET_LEN does not need 94 * to be excluded because its size is always 1. 95 */ 96 if (ret > 0 && query != UVC_GET_INFO) { 97 memset(data + ret, 0, size - ret); 98 dev_warn_once(&dev->udev->dev, 99 "UVC non compliance: %s control %u on unit %u returned %d bytes when we expected %u.\n", 100 uvc_query_name(query), cs, unit, ret, size); 101 return 0; 102 } 103 104 if (ret != -EPIPE) { 105 dev_err(&dev->udev->dev, 106 "Failed to query (%s) UVC control %u on unit %u: %d (exp. %u).\n", 107 uvc_query_name(query), cs, unit, ret, size); 108 return ret < 0 ? ret : -EPIPE; 109 } 110 111 /* Reuse data[0] to request the error code. */ 112 tmp = *(u8 *)data; 113 114 ret = __uvc_query_ctrl(dev, UVC_GET_CUR, 0, intfnum, 115 UVC_VC_REQUEST_ERROR_CODE_CONTROL, data, 1, 116 UVC_CTRL_CONTROL_TIMEOUT); 117 118 error = *(u8 *)data; 119 *(u8 *)data = tmp; 120 121 if (ret != 1) { 122 dev_err_ratelimited(&dev->udev->dev, 123 "Failed to query (%s) UVC error code control %u on unit %u: %d (exp. 1).\n", 124 uvc_query_name(query), cs, unit, ret); 125 return ret < 0 ? ret : -EPIPE; 126 } 127 128 uvc_dbg(dev, CONTROL, "Control error %u\n", error); 129 130 switch (error) { 131 case 0: 132 /* Cannot happen - we received a STALL */ 133 return -EPIPE; 134 case 1: /* Not ready */ 135 return -EBUSY; 136 case 2: /* Wrong state */ 137 return -EACCES; 138 case 3: /* Power */ 139 return -EREMOTE; 140 case 4: /* Out of range */ 141 return -ERANGE; 142 case 5: /* Invalid unit */ 143 case 6: /* Invalid control */ 144 case 7: /* Invalid Request */ 145 /* 146 * The firmware has not properly implemented 147 * the control or there has been a HW error. 148 */ 149 return -EIO; 150 case 8: /* Invalid value within range */ 151 return -EINVAL; 152 default: /* reserved or unknown */ 153 break; 154 } 155 156 return -EPIPE; 157 } 158 159 static const struct usb_device_id elgato_cam_link_4k = { 160 USB_DEVICE(0x0fd9, 0x0066) 161 }; 162 163 static void uvc_fixup_video_ctrl(struct uvc_streaming *stream, 164 struct uvc_streaming_control *ctrl) 165 { 166 const struct uvc_format *format = NULL; 167 const struct uvc_frame *frame = NULL; 168 unsigned int i; 169 170 /* 171 * The response of the Elgato Cam Link 4K is incorrect: The second byte 172 * contains bFormatIndex (instead of being the second byte of bmHint). 173 * The first byte is always zero. The third byte is always 1. 174 * 175 * The UVC 1.5 class specification defines the first five bits in the 176 * bmHint bitfield. The remaining bits are reserved and should be zero. 177 * Therefore a valid bmHint will be less than 32. 178 * 179 * Latest Elgato Cam Link 4K firmware as of 2021-03-23 needs this fix. 180 * MCU: 20.02.19, FPGA: 67 181 */ 182 if (usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k) && 183 ctrl->bmHint > 255) { 184 u8 corrected_format_index = ctrl->bmHint >> 8; 185 186 uvc_dbg(stream->dev, VIDEO, 187 "Correct USB video probe response from {bmHint: 0x%04x, bFormatIndex: %u} to {bmHint: 0x%04x, bFormatIndex: %u}\n", 188 ctrl->bmHint, ctrl->bFormatIndex, 189 1, corrected_format_index); 190 ctrl->bmHint = 1; 191 ctrl->bFormatIndex = corrected_format_index; 192 } 193 194 for (i = 0; i < stream->nformats; ++i) { 195 if (stream->formats[i].index == ctrl->bFormatIndex) { 196 format = &stream->formats[i]; 197 break; 198 } 199 } 200 201 if (format == NULL) 202 return; 203 204 for (i = 0; i < format->nframes; ++i) { 205 if (format->frames[i].bFrameIndex == ctrl->bFrameIndex) { 206 frame = &format->frames[i]; 207 break; 208 } 209 } 210 211 if (frame == NULL) 212 return; 213 214 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) || 215 (ctrl->dwMaxVideoFrameSize == 0 && 216 stream->dev->uvc_version < 0x0110)) 217 ctrl->dwMaxVideoFrameSize = 218 frame->dwMaxVideoFrameBufferSize; 219 220 /* 221 * The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to 222 * compute the bandwidth on 16 bits and erroneously sign-extend it to 223 * 32 bits, resulting in a huge bandwidth value. Detect and fix that 224 * condition by setting the 16 MSBs to 0 when they're all equal to 1. 225 */ 226 if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000) 227 ctrl->dwMaxPayloadTransferSize &= ~0xffff0000; 228 229 if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) && 230 stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH && 231 stream->intf->num_altsetting > 1) { 232 u32 interval; 233 u32 bandwidth; 234 235 interval = (ctrl->dwFrameInterval > 100000) 236 ? ctrl->dwFrameInterval 237 : frame->dwFrameInterval[0]; 238 239 /* 240 * Compute a bandwidth estimation by multiplying the frame 241 * size by the number of video frames per second, divide the 242 * result by the number of USB frames (or micro-frames for 243 * high- and super-speed devices) per second and add the UVC 244 * header size (assumed to be 12 bytes long). 245 */ 246 bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp; 247 bandwidth *= 10000000 / interval + 1; 248 bandwidth /= 1000; 249 if (stream->dev->udev->speed >= USB_SPEED_HIGH) 250 bandwidth /= 8; 251 bandwidth += 12; 252 253 /* 254 * The bandwidth estimate is too low for many cameras. Don't use 255 * maximum packet sizes lower than 1024 bytes to try and work 256 * around the problem. According to measurements done on two 257 * different camera models, the value is high enough to get most 258 * resolutions working while not preventing two simultaneous 259 * VGA streams at 15 fps. 260 */ 261 bandwidth = max_t(u32, bandwidth, 1024); 262 263 ctrl->dwMaxPayloadTransferSize = bandwidth; 264 } 265 266 if (stream->intf->num_altsetting > 1 && 267 ctrl->dwMaxPayloadTransferSize > stream->maxpsize) { 268 dev_warn_ratelimited(&stream->intf->dev, 269 "UVC non compliance: the max payload transmission size (%u) exceeds the size of the ep max packet (%u). Using the max size.\n", 270 ctrl->dwMaxPayloadTransferSize, 271 stream->maxpsize); 272 ctrl->dwMaxPayloadTransferSize = stream->maxpsize; 273 } 274 } 275 276 static size_t uvc_video_ctrl_size(struct uvc_streaming *stream) 277 { 278 /* 279 * Return the size of the video probe and commit controls, which depends 280 * on the protocol version. 281 */ 282 if (stream->dev->uvc_version < 0x0110) 283 return 26; 284 else if (stream->dev->uvc_version < 0x0150) 285 return 34; 286 else 287 return 48; 288 } 289 290 static int uvc_get_video_ctrl(struct uvc_streaming *stream, 291 struct uvc_streaming_control *ctrl, int probe, u8 query) 292 { 293 u16 size = uvc_video_ctrl_size(stream); 294 u8 *data; 295 int ret; 296 297 if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) && 298 query == UVC_GET_DEF) 299 return -EIO; 300 301 data = kmalloc(size, GFP_KERNEL); 302 if (data == NULL) 303 return -ENOMEM; 304 305 ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum, 306 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data, 307 size, uvc_timeout_param); 308 309 if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) { 310 /* 311 * Some cameras, mostly based on Bison Electronics chipsets, 312 * answer a GET_MIN or GET_MAX request with the wCompQuality 313 * field only. 314 */ 315 uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non " 316 "compliance - GET_MIN/MAX(PROBE) incorrectly " 317 "supported. Enabling workaround.\n"); 318 memset(ctrl, 0, sizeof(*ctrl)); 319 ctrl->wCompQuality = le16_to_cpup((__le16 *)data); 320 ret = 0; 321 goto out; 322 } else if (query == UVC_GET_DEF && probe == 1 && ret != size) { 323 /* 324 * Many cameras don't support the GET_DEF request on their 325 * video probe control. Warn once and return, the caller will 326 * fall back to GET_CUR. 327 */ 328 uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non " 329 "compliance - GET_DEF(PROBE) not supported. " 330 "Enabling workaround.\n"); 331 ret = -EIO; 332 goto out; 333 } else if (ret != size) { 334 dev_err(&stream->intf->dev, 335 "Failed to query (%s) UVC %s control : %d (exp. %u).\n", 336 uvc_query_name(query), probe ? "probe" : "commit", 337 ret, size); 338 ret = (ret == -EPROTO) ? -EPROTO : -EIO; 339 goto out; 340 } 341 342 ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]); 343 ctrl->bFormatIndex = data[2]; 344 ctrl->bFrameIndex = data[3]; 345 ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]); 346 ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]); 347 ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]); 348 ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]); 349 ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]); 350 ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]); 351 ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]); 352 ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]); 353 354 if (size >= 34) { 355 ctrl->dwClockFrequency = get_unaligned_le32(&data[26]); 356 ctrl->bmFramingInfo = data[30]; 357 ctrl->bPreferedVersion = data[31]; 358 ctrl->bMinVersion = data[32]; 359 ctrl->bMaxVersion = data[33]; 360 } else { 361 ctrl->dwClockFrequency = stream->dev->clock_frequency; 362 ctrl->bmFramingInfo = 0; 363 ctrl->bPreferedVersion = 0; 364 ctrl->bMinVersion = 0; 365 ctrl->bMaxVersion = 0; 366 } 367 368 /* 369 * Some broken devices return null or wrong dwMaxVideoFrameSize and 370 * dwMaxPayloadTransferSize fields. Try to get the value from the 371 * format and frame descriptors. 372 */ 373 uvc_fixup_video_ctrl(stream, ctrl); 374 ret = 0; 375 376 out: 377 kfree(data); 378 return ret; 379 } 380 381 static int uvc_set_video_ctrl(struct uvc_streaming *stream, 382 struct uvc_streaming_control *ctrl, int probe) 383 { 384 u16 size = uvc_video_ctrl_size(stream); 385 u8 *data; 386 int ret; 387 388 data = kzalloc(size, GFP_KERNEL); 389 if (data == NULL) 390 return -ENOMEM; 391 392 *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint); 393 data[2] = ctrl->bFormatIndex; 394 data[3] = ctrl->bFrameIndex; 395 *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval); 396 *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate); 397 *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate); 398 *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality); 399 *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize); 400 *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay); 401 put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]); 402 put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]); 403 404 if (size >= 34) { 405 put_unaligned_le32(ctrl->dwClockFrequency, &data[26]); 406 data[30] = ctrl->bmFramingInfo; 407 data[31] = ctrl->bPreferedVersion; 408 data[32] = ctrl->bMinVersion; 409 data[33] = ctrl->bMaxVersion; 410 } 411 412 ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum, 413 probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data, 414 size, uvc_timeout_param); 415 if (ret != size) { 416 dev_err(&stream->intf->dev, 417 "Failed to set UVC %s control : %d (exp. %u).\n", 418 probe ? "probe" : "commit", ret, size); 419 ret = -EIO; 420 } 421 422 kfree(data); 423 return ret; 424 } 425 426 int uvc_probe_video(struct uvc_streaming *stream, 427 struct uvc_streaming_control *probe) 428 { 429 struct uvc_streaming_control probe_min, probe_max; 430 unsigned int i; 431 int ret; 432 433 /* 434 * Perform probing. The device should adjust the requested values 435 * according to its capabilities. However, some devices, namely the 436 * first generation UVC Logitech webcams, don't implement the Video 437 * Probe control properly, and just return the needed bandwidth. For 438 * that reason, if the needed bandwidth exceeds the maximum available 439 * bandwidth, try to lower the quality. 440 */ 441 ret = uvc_set_video_ctrl(stream, probe, 1); 442 if (ret < 0) 443 goto done; 444 445 /* Get the minimum and maximum values for compression settings. */ 446 if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) { 447 ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN); 448 if (ret < 0) 449 goto done; 450 ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX); 451 if (ret < 0) 452 goto done; 453 454 probe->wCompQuality = probe_max.wCompQuality; 455 } 456 457 for (i = 0; i < 2; ++i) { 458 ret = uvc_set_video_ctrl(stream, probe, 1); 459 if (ret < 0) 460 goto done; 461 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR); 462 if (ret < 0) 463 goto done; 464 465 if (stream->intf->num_altsetting == 1) 466 break; 467 468 if (probe->dwMaxPayloadTransferSize <= stream->maxpsize) 469 break; 470 471 if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) { 472 ret = -ENOSPC; 473 goto done; 474 } 475 476 /* TODO: negotiate compression parameters */ 477 probe->wKeyFrameRate = probe_min.wKeyFrameRate; 478 probe->wPFrameRate = probe_min.wPFrameRate; 479 probe->wCompQuality = probe_max.wCompQuality; 480 probe->wCompWindowSize = probe_min.wCompWindowSize; 481 } 482 483 done: 484 return ret; 485 } 486 487 static int uvc_commit_video(struct uvc_streaming *stream, 488 struct uvc_streaming_control *probe) 489 { 490 return uvc_set_video_ctrl(stream, probe, 0); 491 } 492 493 /* ----------------------------------------------------------------------------- 494 * Clocks and timestamps 495 */ 496 497 static inline ktime_t uvc_video_get_time(void) 498 { 499 if (uvc_clock_param == CLOCK_MONOTONIC) 500 return ktime_get(); 501 else 502 return ktime_get_real(); 503 } 504 505 static void uvc_video_clock_add_sample(struct uvc_clock *clock, 506 const struct uvc_clock_sample *sample) 507 { 508 unsigned long flags; 509 510 /* 511 * If we write new data on the position where we had the last 512 * overflow, remove the overflow pointer. There is no SOF overflow 513 * in the whole circular buffer. 514 */ 515 if (clock->head == clock->last_sof_overflow) 516 clock->last_sof_overflow = -1; 517 518 spin_lock_irqsave(&clock->lock, flags); 519 520 if (clock->count > 0 && clock->last_sof > sample->dev_sof) { 521 /* 522 * Remove data from the circular buffer that is older than the 523 * last SOF overflow. We only support one SOF overflow per 524 * circular buffer. 525 */ 526 if (clock->last_sof_overflow != -1) 527 clock->count = (clock->head - clock->last_sof_overflow 528 + clock->size) % clock->size; 529 clock->last_sof_overflow = clock->head; 530 } 531 532 /* Add sample. */ 533 clock->samples[clock->head] = *sample; 534 clock->head = (clock->head + 1) % clock->size; 535 clock->count = min(clock->count + 1, clock->size); 536 537 spin_unlock_irqrestore(&clock->lock, flags); 538 } 539 540 static void 541 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf, 542 const u8 *data, int len) 543 { 544 struct uvc_clock_sample sample; 545 unsigned int header_size; 546 bool has_pts = false; 547 bool has_scr = false; 548 549 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) { 550 case UVC_STREAM_PTS | UVC_STREAM_SCR: 551 header_size = 12; 552 has_pts = true; 553 has_scr = true; 554 break; 555 case UVC_STREAM_PTS: 556 header_size = 6; 557 has_pts = true; 558 break; 559 case UVC_STREAM_SCR: 560 header_size = 8; 561 has_scr = true; 562 break; 563 default: 564 header_size = 2; 565 break; 566 } 567 568 /* Check for invalid headers. */ 569 if (len < header_size) 570 return; 571 572 /* 573 * Extract the timestamps: 574 * 575 * - store the frame PTS in the buffer structure 576 * - if the SCR field is present, retrieve the host SOF counter and 577 * kernel timestamps and store them with the SCR STC and SOF fields 578 * in the ring buffer 579 */ 580 if (has_pts && buf != NULL) 581 buf->pts = get_unaligned_le32(&data[2]); 582 583 if (!has_scr) 584 return; 585 586 /* 587 * To limit the amount of data, drop SCRs with an SOF identical to the 588 * previous one. This filtering is also needed to support UVC 1.5, where 589 * all the data packets of the same frame contains the same SOF. In that 590 * case only the first one will match the host_sof. 591 */ 592 sample.dev_sof = get_unaligned_le16(&data[header_size - 2]); 593 if (sample.dev_sof == stream->clock.last_sof) 594 return; 595 596 sample.dev_stc = get_unaligned_le32(&data[header_size - 6]); 597 598 /* 599 * STC (Source Time Clock) is the clock used by the camera. The UVC 1.5 600 * standard states that it "must be captured when the first video data 601 * of a video frame is put on the USB bus". This is generally understood 602 * as requiring devices to clear the payload header's SCR bit before 603 * the first packet containing video data. 604 * 605 * Most vendors follow that interpretation, but some (namely SunplusIT 606 * on some devices) always set the `UVC_STREAM_SCR` bit, fill the SCR 607 * field with 0's,and expect that the driver only processes the SCR if 608 * there is data in the packet. 609 * 610 * Ignore all the hardware timestamp information if we haven't received 611 * any data for this frame yet, the packet contains no data, and both 612 * STC and SOF are zero. This heuristics should be safe on compliant 613 * devices. This should be safe with compliant devices, as in the very 614 * unlikely case where a UVC 1.1 device would send timing information 615 * only before the first packet containing data, and both STC and SOF 616 * happen to be zero for a particular frame, we would only miss one 617 * clock sample from many and the clock recovery algorithm wouldn't 618 * suffer from this condition. 619 */ 620 if (buf && buf->bytesused == 0 && len == header_size && 621 sample.dev_stc == 0 && sample.dev_sof == 0) 622 return; 623 624 sample.host_sof = usb_get_current_frame_number(stream->dev->udev); 625 626 /* 627 * On some devices, like the Logitech C922, the device SOF does not run 628 * at a stable rate of 1kHz. For those devices use the host SOF instead. 629 * In the tests performed so far, this improves the timestamp precision. 630 * This is probably explained by a small packet handling jitter from the 631 * host, but the exact reason hasn't been fully determined. 632 */ 633 if (stream->dev->quirks & UVC_QUIRK_INVALID_DEVICE_SOF) 634 sample.dev_sof = sample.host_sof; 635 636 sample.host_time = uvc_video_get_time(); 637 638 /* 639 * The UVC specification allows device implementations that can't obtain 640 * the USB frame number to keep their own frame counters as long as they 641 * match the size and frequency of the frame number associated with USB 642 * SOF tokens. The SOF values sent by such devices differ from the USB 643 * SOF tokens by a fixed offset that needs to be estimated and accounted 644 * for to make timestamp recovery as accurate as possible. 645 * 646 * The offset is estimated the first time a device SOF value is received 647 * as the difference between the host and device SOF values. As the two 648 * SOF values can differ slightly due to transmission delays, consider 649 * that the offset is null if the difference is not higher than 10 ms 650 * (negative differences can not happen and are thus considered as an 651 * offset). The video commit control wDelay field should be used to 652 * compute a dynamic threshold instead of using a fixed 10 ms value, but 653 * devices don't report reliable wDelay values. 654 * 655 * See uvc_video_clock_host_sof() for an explanation regarding why only 656 * the 8 LSBs of the delta are kept. 657 */ 658 if (stream->clock.sof_offset == (u16)-1) { 659 u16 delta_sof = (sample.host_sof - sample.dev_sof) & 255; 660 if (delta_sof >= 10) 661 stream->clock.sof_offset = delta_sof; 662 else 663 stream->clock.sof_offset = 0; 664 } 665 666 sample.dev_sof = (sample.dev_sof + stream->clock.sof_offset) & 2047; 667 uvc_video_clock_add_sample(&stream->clock, &sample); 668 stream->clock.last_sof = sample.dev_sof; 669 } 670 671 static void uvc_video_clock_reset(struct uvc_clock *clock) 672 { 673 clock->head = 0; 674 clock->count = 0; 675 clock->last_sof = -1; 676 clock->last_sof_overflow = -1; 677 clock->sof_offset = -1; 678 } 679 680 static int uvc_video_clock_init(struct uvc_clock *clock) 681 { 682 spin_lock_init(&clock->lock); 683 clock->size = 32; 684 685 clock->samples = kmalloc_array(clock->size, sizeof(*clock->samples), 686 GFP_KERNEL); 687 if (clock->samples == NULL) 688 return -ENOMEM; 689 690 uvc_video_clock_reset(clock); 691 692 return 0; 693 } 694 695 static void uvc_video_clock_cleanup(struct uvc_clock *clock) 696 { 697 kfree(clock->samples); 698 clock->samples = NULL; 699 } 700 701 /* 702 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample 703 * 704 * Host SOF counters reported by usb_get_current_frame_number() usually don't 705 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame 706 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host 707 * controller and its configuration. 708 * 709 * We thus need to recover the SOF value corresponding to the host frame number. 710 * As the device and host frame numbers are sampled in a short interval, the 711 * difference between their values should be equal to a small delta plus an 712 * integer multiple of 256 caused by the host frame number limited precision. 713 * 714 * To obtain the recovered host SOF value, compute the small delta by masking 715 * the high bits of the host frame counter and device SOF difference and add it 716 * to the device SOF value. 717 */ 718 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample) 719 { 720 /* The delta value can be negative. */ 721 s8 delta_sof; 722 723 delta_sof = (sample->host_sof - sample->dev_sof) & 255; 724 725 return (sample->dev_sof + delta_sof) & 2047; 726 } 727 728 /* 729 * uvc_video_clock_update - Update the buffer timestamp 730 * 731 * This function converts the buffer PTS timestamp to the host clock domain by 732 * going through the USB SOF clock domain and stores the result in the V4L2 733 * buffer timestamp field. 734 * 735 * The relationship between the device clock and the host clock isn't known. 736 * However, the device and the host share the common USB SOF clock which can be 737 * used to recover that relationship. 738 * 739 * The relationship between the device clock and the USB SOF clock is considered 740 * to be linear over the clock samples sliding window and is given by 741 * 742 * SOF = m * PTS + p 743 * 744 * Several methods to compute the slope (m) and intercept (p) can be used. As 745 * the clock drift should be small compared to the sliding window size, we 746 * assume that the line that goes through the points at both ends of the window 747 * is a good approximation. Naming those points P1 and P2, we get 748 * 749 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS 750 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) 751 * 752 * or 753 * 754 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1) 755 * 756 * to avoid losing precision in the division. Similarly, the host timestamp is 757 * computed with 758 * 759 * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2) 760 * 761 * SOF values are coded on 11 bits by USB. We extend their precision with 16 762 * decimal bits, leading to a 11.16 coding. 763 * 764 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should 765 * be normalized using the nominal device clock frequency reported through the 766 * UVC descriptors. 767 * 768 * Both the PTS/STC and SOF counters roll over, after a fixed but device 769 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the 770 * sliding window size is smaller than the rollover period, differences computed 771 * on unsigned integers will produce the correct result. However, the p term in 772 * the linear relations will be miscomputed. 773 * 774 * To fix the issue, we subtract a constant from the PTS and STC values to bring 775 * PTS to half the 32 bit STC range. The sliding window STC values then fit into 776 * the 32 bit range without any rollover. 777 * 778 * Similarly, we add 2048 to the device SOF values to make sure that the SOF 779 * computed by (1) will never be smaller than 0. This offset is then compensated 780 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent 781 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly 782 * lower than 4096, and the host SOF counters can have rolled over to 2048. This 783 * case is handled by subtracting 2048 from the SOF value if it exceeds the host 784 * SOF value at the end of the sliding window. 785 * 786 * Finally we subtract a constant from the host timestamps to bring the first 787 * timestamp of the sliding window to 1s. 788 */ 789 void uvc_video_clock_update(struct uvc_streaming *stream, 790 struct vb2_v4l2_buffer *vbuf, 791 struct uvc_buffer *buf) 792 { 793 struct uvc_clock *clock = &stream->clock; 794 struct uvc_clock_sample *first; 795 struct uvc_clock_sample *last; 796 unsigned long flags; 797 u64 timestamp; 798 u32 delta_stc; 799 u32 y1; 800 u32 x1, x2; 801 u32 mean; 802 u32 sof; 803 u64 y, y2; 804 805 if (!uvc_hw_timestamps_param) 806 return; 807 808 /* 809 * We will get called from __vb2_queue_cancel() if there are buffers 810 * done but not dequeued by the user, but the sample array has already 811 * been released at that time. Just bail out in that case. 812 */ 813 if (!clock->samples) 814 return; 815 816 spin_lock_irqsave(&clock->lock, flags); 817 818 if (clock->count < 2) 819 goto done; 820 821 first = &clock->samples[(clock->head - clock->count + clock->size) % clock->size]; 822 last = &clock->samples[(clock->head - 1 + clock->size) % clock->size]; 823 824 /* First step, PTS to SOF conversion. */ 825 delta_stc = buf->pts - (1UL << 31); 826 x1 = first->dev_stc - delta_stc; 827 x2 = last->dev_stc - delta_stc; 828 if (x1 == x2) 829 goto done; 830 831 y1 = (first->dev_sof + 2048) << 16; 832 y2 = (last->dev_sof + 2048) << 16; 833 if (y2 < y1) 834 y2 += 2048 << 16; 835 836 /* 837 * Have at least 1/4 of a second of timestamps before we 838 * try to do any calculation. Otherwise we do not have enough 839 * precision. This value was determined by running Android CTS 840 * on different devices. 841 * 842 * dev_sof runs at 1KHz, and we have a fixed point precision of 843 * 16 bits. 844 */ 845 if ((y2 - y1) < ((1000 / 4) << 16)) 846 goto done; 847 848 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2 849 - (u64)y2 * (u64)x1; 850 y = div_u64(y, x2 - x1); 851 852 sof = y; 853 854 uvc_dbg(stream->dev, CLOCK, 855 "%s: PTS %u y %llu.%06llu SOF %u.%06llu (x1 %u x2 %u y1 %u y2 %llu SOF offset %u)\n", 856 stream->dev->name, buf->pts, 857 y >> 16, div_u64((y & 0xffff) * 1000000, 65536), 858 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536), 859 x1, x2, y1, y2, clock->sof_offset); 860 861 /* Second step, SOF to host clock conversion. */ 862 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16; 863 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16; 864 if (x2 < x1) 865 x2 += 2048 << 16; 866 if (x1 == x2) 867 goto done; 868 869 y1 = NSEC_PER_SEC; 870 y2 = ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1; 871 872 /* 873 * Interpolated and host SOF timestamps can wrap around at slightly 874 * different times. Handle this by adding or removing 2048 to or from 875 * the computed SOF value to keep it close to the SOF samples mean 876 * value. 877 */ 878 mean = (x1 + x2) / 2; 879 if (mean - (1024 << 16) > sof) 880 sof += 2048 << 16; 881 else if (sof > mean + (1024 << 16)) 882 sof -= 2048 << 16; 883 884 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2 885 - (u64)y2 * (u64)x1; 886 y = div_u64(y, x2 - x1); 887 888 timestamp = ktime_to_ns(first->host_time) + y - y1; 889 890 uvc_dbg(stream->dev, CLOCK, 891 "%s: SOF %u.%06llu y %llu ts %llu buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %llu)\n", 892 stream->dev->name, 893 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536), 894 y, timestamp, vbuf->vb2_buf.timestamp, 895 x1, first->host_sof, first->dev_sof, 896 x2, last->host_sof, last->dev_sof, y1, y2); 897 898 /* Update the V4L2 buffer. */ 899 vbuf->vb2_buf.timestamp = timestamp; 900 901 done: 902 spin_unlock_irqrestore(&clock->lock, flags); 903 } 904 905 /* ------------------------------------------------------------------------ 906 * Stream statistics 907 */ 908 909 static void uvc_video_stats_decode(struct uvc_streaming *stream, 910 const u8 *data, int len) 911 { 912 unsigned int header_size; 913 bool has_pts = false; 914 bool has_scr = false; 915 u16 scr_sof; 916 u32 scr_stc; 917 u32 pts; 918 919 if (stream->stats.stream.nb_frames == 0 && 920 stream->stats.frame.nb_packets == 0) 921 stream->stats.stream.start_ts = ktime_get(); 922 923 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) { 924 case UVC_STREAM_PTS | UVC_STREAM_SCR: 925 header_size = 12; 926 has_pts = true; 927 has_scr = true; 928 break; 929 case UVC_STREAM_PTS: 930 header_size = 6; 931 has_pts = true; 932 break; 933 case UVC_STREAM_SCR: 934 header_size = 8; 935 has_scr = true; 936 break; 937 default: 938 header_size = 2; 939 break; 940 } 941 942 /* Check for invalid headers. */ 943 if (len < header_size || data[0] < header_size) { 944 stream->stats.frame.nb_invalid++; 945 return; 946 } 947 948 /* Extract the timestamps. */ 949 if (has_pts) 950 pts = get_unaligned_le32(&data[2]); 951 952 if (has_scr) { 953 scr_stc = get_unaligned_le32(&data[header_size - 6]); 954 scr_sof = get_unaligned_le16(&data[header_size - 2]); 955 } 956 957 /* Is PTS constant through the whole frame ? */ 958 if (has_pts && stream->stats.frame.nb_pts) { 959 if (stream->stats.frame.pts != pts) { 960 stream->stats.frame.nb_pts_diffs++; 961 stream->stats.frame.last_pts_diff = 962 stream->stats.frame.nb_packets; 963 } 964 } 965 966 if (has_pts) { 967 stream->stats.frame.nb_pts++; 968 stream->stats.frame.pts = pts; 969 } 970 971 /* 972 * Do all frames have a PTS in their first non-empty packet, or before 973 * their first empty packet ? 974 */ 975 if (stream->stats.frame.size == 0) { 976 if (len > header_size) 977 stream->stats.frame.has_initial_pts = has_pts; 978 if (len == header_size && has_pts) 979 stream->stats.frame.has_early_pts = true; 980 } 981 982 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */ 983 if (has_scr && stream->stats.frame.nb_scr) { 984 if (stream->stats.frame.scr_stc != scr_stc) 985 stream->stats.frame.nb_scr_diffs++; 986 } 987 988 if (has_scr) { 989 /* Expand the SOF counter to 32 bits and store its value. */ 990 if (stream->stats.stream.nb_frames > 0 || 991 stream->stats.frame.nb_scr > 0) 992 stream->stats.stream.scr_sof_count += 993 (scr_sof - stream->stats.stream.scr_sof) % 2048; 994 stream->stats.stream.scr_sof = scr_sof; 995 996 stream->stats.frame.nb_scr++; 997 stream->stats.frame.scr_stc = scr_stc; 998 stream->stats.frame.scr_sof = scr_sof; 999 1000 if (scr_sof < stream->stats.stream.min_sof) 1001 stream->stats.stream.min_sof = scr_sof; 1002 if (scr_sof > stream->stats.stream.max_sof) 1003 stream->stats.stream.max_sof = scr_sof; 1004 } 1005 1006 /* Record the first non-empty packet number. */ 1007 if (stream->stats.frame.size == 0 && len > header_size) 1008 stream->stats.frame.first_data = stream->stats.frame.nb_packets; 1009 1010 /* Update the frame size. */ 1011 stream->stats.frame.size += len - header_size; 1012 1013 /* Update the packets counters. */ 1014 stream->stats.frame.nb_packets++; 1015 if (len <= header_size) 1016 stream->stats.frame.nb_empty++; 1017 1018 if (data[1] & UVC_STREAM_ERR) 1019 stream->stats.frame.nb_errors++; 1020 } 1021 1022 static void uvc_video_stats_update(struct uvc_streaming *stream) 1023 { 1024 struct uvc_stats_frame *frame = &stream->stats.frame; 1025 1026 uvc_dbg(stream->dev, STATS, 1027 "frame %u stats: %u/%u/%u packets, %u/%u/%u pts (%searly %sinitial), %u/%u scr, last pts/stc/sof %u/%u/%u\n", 1028 stream->sequence, frame->first_data, 1029 frame->nb_packets - frame->nb_empty, frame->nb_packets, 1030 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts, 1031 frame->has_early_pts ? "" : "!", 1032 frame->has_initial_pts ? "" : "!", 1033 frame->nb_scr_diffs, frame->nb_scr, 1034 frame->pts, frame->scr_stc, frame->scr_sof); 1035 1036 stream->stats.stream.nb_frames++; 1037 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets; 1038 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty; 1039 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors; 1040 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid; 1041 1042 if (frame->has_early_pts) 1043 stream->stats.stream.nb_pts_early++; 1044 if (frame->has_initial_pts) 1045 stream->stats.stream.nb_pts_initial++; 1046 if (frame->last_pts_diff <= frame->first_data) 1047 stream->stats.stream.nb_pts_constant++; 1048 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty) 1049 stream->stats.stream.nb_scr_count_ok++; 1050 if (frame->nb_scr_diffs + 1 == frame->nb_scr) 1051 stream->stats.stream.nb_scr_diffs_ok++; 1052 1053 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame)); 1054 } 1055 1056 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf, 1057 size_t size) 1058 { 1059 unsigned int scr_sof_freq; 1060 unsigned int duration; 1061 size_t count = 0; 1062 1063 /* 1064 * Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF 1065 * frequency this will not overflow before more than 1h. 1066 */ 1067 duration = ktime_ms_delta(stream->stats.stream.stop_ts, 1068 stream->stats.stream.start_ts); 1069 if (duration != 0) 1070 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000 1071 / duration; 1072 else 1073 scr_sof_freq = 0; 1074 1075 count += scnprintf(buf + count, size - count, 1076 "frames: %u\npackets: %u\nempty: %u\n" 1077 "errors: %u\ninvalid: %u\n", 1078 stream->stats.stream.nb_frames, 1079 stream->stats.stream.nb_packets, 1080 stream->stats.stream.nb_empty, 1081 stream->stats.stream.nb_errors, 1082 stream->stats.stream.nb_invalid); 1083 count += scnprintf(buf + count, size - count, 1084 "pts: %u early, %u initial, %u ok\n", 1085 stream->stats.stream.nb_pts_early, 1086 stream->stats.stream.nb_pts_initial, 1087 stream->stats.stream.nb_pts_constant); 1088 count += scnprintf(buf + count, size - count, 1089 "scr: %u count ok, %u diff ok\n", 1090 stream->stats.stream.nb_scr_count_ok, 1091 stream->stats.stream.nb_scr_diffs_ok); 1092 count += scnprintf(buf + count, size - count, 1093 "sof: %u <= sof <= %u, freq %u.%03u kHz\n", 1094 stream->stats.stream.min_sof, 1095 stream->stats.stream.max_sof, 1096 scr_sof_freq / 1000, scr_sof_freq % 1000); 1097 1098 return count; 1099 } 1100 1101 static void uvc_video_stats_start(struct uvc_streaming *stream) 1102 { 1103 memset(&stream->stats, 0, sizeof(stream->stats)); 1104 stream->stats.stream.min_sof = 2048; 1105 } 1106 1107 static void uvc_video_stats_stop(struct uvc_streaming *stream) 1108 { 1109 stream->stats.stream.stop_ts = ktime_get(); 1110 } 1111 1112 /* ------------------------------------------------------------------------ 1113 * Video codecs 1114 */ 1115 1116 /* 1117 * Video payload decoding is handled by uvc_video_decode_start(), 1118 * uvc_video_decode_data() and uvc_video_decode_end(). 1119 * 1120 * uvc_video_decode_start is called with URB data at the start of a bulk or 1121 * isochronous payload. It processes header data and returns the header size 1122 * in bytes if successful. If an error occurs, it returns a negative error 1123 * code. The following error codes have special meanings. 1124 * 1125 * - EAGAIN informs the caller that the current video buffer should be marked 1126 * as done, and that the function should be called again with the same data 1127 * and a new video buffer. This is used when end of frame conditions can be 1128 * reliably detected at the beginning of the next frame only. 1129 * 1130 * If an error other than -EAGAIN is returned, the caller will drop the current 1131 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be 1132 * made until the next payload. -ENODATA can be used to drop the current 1133 * payload if no other error code is appropriate. 1134 * 1135 * uvc_video_decode_data is called for every URB with URB data. It copies the 1136 * data to the video buffer. 1137 * 1138 * uvc_video_decode_end is called with header data at the end of a bulk or 1139 * isochronous payload. It performs any additional header data processing and 1140 * returns 0 or a negative error code if an error occurred. As header data have 1141 * already been processed by uvc_video_decode_start, this functions isn't 1142 * required to perform sanity checks a second time. 1143 * 1144 * For isochronous transfers where a payload is always transferred in a single 1145 * URB, the three functions will be called in a row. 1146 * 1147 * To let the decoder process header data and update its internal state even 1148 * when no video buffer is available, uvc_video_decode_start must be prepared 1149 * to be called with a NULL buf parameter. uvc_video_decode_data and 1150 * uvc_video_decode_end will never be called with a NULL buffer. 1151 */ 1152 static int uvc_video_decode_start(struct uvc_streaming *stream, 1153 struct uvc_buffer *buf, const u8 *data, int len) 1154 { 1155 u8 header_len; 1156 u8 fid; 1157 1158 /* 1159 * Sanity checks: 1160 * - packet must be at least 2 bytes long 1161 * - bHeaderLength value must be at least 2 bytes (see above) 1162 * - bHeaderLength value can't be larger than the packet size. 1163 */ 1164 if (len < 2 || data[0] < 2 || data[0] > len) { 1165 stream->stats.frame.nb_invalid++; 1166 return -EINVAL; 1167 } 1168 1169 header_len = data[0]; 1170 fid = data[1] & UVC_STREAM_FID; 1171 1172 /* 1173 * Increase the sequence number regardless of any buffer states, so 1174 * that discontinuous sequence numbers always indicate lost frames. 1175 */ 1176 if (stream->last_fid != fid) { 1177 stream->sequence++; 1178 if (stream->sequence) 1179 uvc_video_stats_update(stream); 1180 } 1181 1182 uvc_video_clock_decode(stream, buf, data, len); 1183 uvc_video_stats_decode(stream, data, len); 1184 1185 /* 1186 * Store the payload FID bit and return immediately when the buffer is 1187 * NULL. 1188 */ 1189 if (buf == NULL) { 1190 stream->last_fid = fid; 1191 return -ENODATA; 1192 } 1193 1194 /* Mark the buffer as bad if the error bit is set. */ 1195 if (data[1] & UVC_STREAM_ERR) { 1196 uvc_dbg(stream->dev, FRAME, 1197 "Marking buffer as bad (error bit set)\n"); 1198 buf->error = 1; 1199 } 1200 1201 /* 1202 * Synchronize to the input stream by waiting for the FID bit to be 1203 * toggled when the buffer state is not UVC_BUF_STATE_ACTIVE. 1204 * stream->last_fid is initialized to -1, so the first isochronous 1205 * frame will always be in sync. 1206 * 1207 * If the device doesn't toggle the FID bit, invert stream->last_fid 1208 * when the EOF bit is set to force synchronisation on the next packet. 1209 */ 1210 if (buf->state != UVC_BUF_STATE_ACTIVE) { 1211 if (fid == stream->last_fid) { 1212 uvc_dbg(stream->dev, FRAME, 1213 "Dropping payload (out of sync)\n"); 1214 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) && 1215 (data[1] & UVC_STREAM_EOF)) 1216 stream->last_fid ^= UVC_STREAM_FID; 1217 return -ENODATA; 1218 } 1219 1220 buf->buf.field = V4L2_FIELD_NONE; 1221 buf->buf.sequence = stream->sequence; 1222 buf->buf.vb2_buf.timestamp = ktime_to_ns(uvc_video_get_time()); 1223 1224 /* TODO: Handle PTS and SCR. */ 1225 buf->state = UVC_BUF_STATE_ACTIVE; 1226 } 1227 1228 /* 1229 * Mark the buffer as done if we're at the beginning of a new frame. 1230 * End of frame detection is better implemented by checking the EOF 1231 * bit (FID bit toggling is delayed by one frame compared to the EOF 1232 * bit), but some devices don't set the bit at end of frame (and the 1233 * last payload can be lost anyway). We thus must check if the FID has 1234 * been toggled. 1235 * 1236 * stream->last_fid is initialized to -1, so the first isochronous 1237 * frame will never trigger an end of frame detection. 1238 * 1239 * Empty buffers (bytesused == 0) don't trigger end of frame detection 1240 * as it doesn't make sense to return an empty buffer. This also 1241 * avoids detecting end of frame conditions at FID toggling if the 1242 * previous payload had the EOF bit set. 1243 */ 1244 if (fid != stream->last_fid && buf->bytesused != 0) { 1245 uvc_dbg(stream->dev, FRAME, 1246 "Frame complete (FID bit toggled)\n"); 1247 buf->state = UVC_BUF_STATE_READY; 1248 return -EAGAIN; 1249 } 1250 1251 /* 1252 * Some cameras, when running two parallel streams (one MJPEG alongside 1253 * another non-MJPEG stream), are known to lose the EOF packet for a frame. 1254 * We can detect the end of a frame by checking for a new SOI marker, as 1255 * the SOI always lies on the packet boundary between two frames for 1256 * these devices. 1257 */ 1258 if (stream->dev->quirks & UVC_QUIRK_MJPEG_NO_EOF && 1259 (stream->cur_format->fcc == V4L2_PIX_FMT_MJPEG || 1260 stream->cur_format->fcc == V4L2_PIX_FMT_JPEG)) { 1261 const u8 *packet = data + header_len; 1262 1263 if (len >= header_len + 2 && 1264 packet[0] == 0xff && packet[1] == JPEG_MARKER_SOI && 1265 buf->bytesused != 0) { 1266 buf->state = UVC_BUF_STATE_READY; 1267 buf->error = 1; 1268 stream->last_fid ^= UVC_STREAM_FID; 1269 return -EAGAIN; 1270 } 1271 } 1272 1273 stream->last_fid = fid; 1274 1275 return header_len; 1276 } 1277 1278 static inline enum dma_data_direction uvc_stream_dir( 1279 struct uvc_streaming *stream) 1280 { 1281 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) 1282 return DMA_FROM_DEVICE; 1283 else 1284 return DMA_TO_DEVICE; 1285 } 1286 1287 static inline struct device *uvc_stream_to_dmadev(struct uvc_streaming *stream) 1288 { 1289 return bus_to_hcd(stream->dev->udev->bus)->self.sysdev; 1290 } 1291 1292 static int uvc_submit_urb(struct uvc_urb *uvc_urb, gfp_t mem_flags) 1293 { 1294 /* Sync DMA. */ 1295 dma_sync_sgtable_for_device(uvc_stream_to_dmadev(uvc_urb->stream), 1296 uvc_urb->sgt, 1297 uvc_stream_dir(uvc_urb->stream)); 1298 return usb_submit_urb(uvc_urb->urb, mem_flags); 1299 } 1300 1301 /* 1302 * uvc_video_decode_data_work: Asynchronous memcpy processing 1303 * 1304 * Copy URB data to video buffers in process context, releasing buffer 1305 * references and requeuing the URB when done. 1306 */ 1307 static void uvc_video_copy_data_work(struct work_struct *work) 1308 { 1309 struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work); 1310 unsigned int i; 1311 int ret; 1312 1313 for (i = 0; i < uvc_urb->async_operations; i++) { 1314 struct uvc_copy_op *op = &uvc_urb->copy_operations[i]; 1315 1316 memcpy(op->dst, op->src, op->len); 1317 1318 /* Release reference taken on this buffer. */ 1319 uvc_queue_buffer_release(op->buf); 1320 } 1321 1322 ret = uvc_submit_urb(uvc_urb, GFP_KERNEL); 1323 if (ret < 0) 1324 dev_err(&uvc_urb->stream->intf->dev, 1325 "Failed to resubmit video URB (%d).\n", ret); 1326 } 1327 1328 static void uvc_video_decode_data(struct uvc_urb *uvc_urb, 1329 struct uvc_buffer *buf, const u8 *data, int len) 1330 { 1331 unsigned int active_op = uvc_urb->async_operations; 1332 struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op]; 1333 unsigned int maxlen; 1334 1335 if (len <= 0) 1336 return; 1337 1338 maxlen = buf->length - buf->bytesused; 1339 1340 /* Take a buffer reference for async work. */ 1341 kref_get(&buf->ref); 1342 1343 op->buf = buf; 1344 op->src = data; 1345 op->dst = buf->mem + buf->bytesused; 1346 op->len = min_t(unsigned int, len, maxlen); 1347 1348 buf->bytesused += op->len; 1349 1350 /* Complete the current frame if the buffer size was exceeded. */ 1351 if (len > maxlen) { 1352 uvc_dbg(uvc_urb->stream->dev, FRAME, 1353 "Frame complete (overflow)\n"); 1354 buf->error = 1; 1355 buf->state = UVC_BUF_STATE_READY; 1356 } 1357 1358 uvc_urb->async_operations++; 1359 } 1360 1361 static void uvc_video_decode_end(struct uvc_streaming *stream, 1362 struct uvc_buffer *buf, const u8 *data, int len) 1363 { 1364 /* Mark the buffer as done if the EOF marker is set. */ 1365 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) { 1366 uvc_dbg(stream->dev, FRAME, "Frame complete (EOF found)\n"); 1367 if (data[0] == len) 1368 uvc_dbg(stream->dev, FRAME, "EOF in empty payload\n"); 1369 buf->state = UVC_BUF_STATE_READY; 1370 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) 1371 stream->last_fid ^= UVC_STREAM_FID; 1372 } 1373 } 1374 1375 /* 1376 * Video payload encoding is handled by uvc_video_encode_header() and 1377 * uvc_video_encode_data(). Only bulk transfers are currently supported. 1378 * 1379 * uvc_video_encode_header is called at the start of a payload. It adds header 1380 * data to the transfer buffer and returns the header size. As the only known 1381 * UVC output device transfers a whole frame in a single payload, the EOF bit 1382 * is always set in the header. 1383 * 1384 * uvc_video_encode_data is called for every URB and copies the data from the 1385 * video buffer to the transfer buffer. 1386 */ 1387 static int uvc_video_encode_header(struct uvc_streaming *stream, 1388 struct uvc_buffer *buf, u8 *data, int len) 1389 { 1390 data[0] = 2; /* Header length */ 1391 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF 1392 | (stream->last_fid & UVC_STREAM_FID); 1393 return 2; 1394 } 1395 1396 static int uvc_video_encode_data(struct uvc_streaming *stream, 1397 struct uvc_buffer *buf, u8 *data, int len) 1398 { 1399 struct uvc_video_queue *queue = &stream->queue; 1400 unsigned int nbytes; 1401 void *mem; 1402 1403 /* Copy video data to the URB buffer. */ 1404 mem = buf->mem + queue->buf_used; 1405 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used); 1406 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size, 1407 nbytes); 1408 memcpy(data, mem, nbytes); 1409 1410 queue->buf_used += nbytes; 1411 1412 return nbytes; 1413 } 1414 1415 /* ------------------------------------------------------------------------ 1416 * Metadata 1417 */ 1418 1419 /* 1420 * Additionally to the payload headers we also want to provide the user with USB 1421 * Frame Numbers and system time values. The resulting buffer is thus composed 1422 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame 1423 * Number, and a copy of the payload header. 1424 * 1425 * Ideally we want to capture all payload headers for each frame. However, their 1426 * number is unknown and unbound. We thus drop headers that contain no vendor 1427 * data and that either contain no SCR value or an SCR value identical to the 1428 * previous header. 1429 */ 1430 static void uvc_video_decode_meta(struct uvc_streaming *stream, 1431 struct uvc_buffer *meta_buf, 1432 const u8 *mem, unsigned int length) 1433 { 1434 struct uvc_meta_buf *meta; 1435 size_t len_std = 2; 1436 bool has_pts, has_scr; 1437 unsigned long flags; 1438 unsigned int sof; 1439 ktime_t time; 1440 const u8 *scr; 1441 1442 if (!meta_buf || length == 2) 1443 return; 1444 1445 if (meta_buf->length - meta_buf->bytesused < 1446 length + sizeof(meta->ns) + sizeof(meta->sof)) { 1447 meta_buf->error = 1; 1448 return; 1449 } 1450 1451 has_pts = mem[1] & UVC_STREAM_PTS; 1452 has_scr = mem[1] & UVC_STREAM_SCR; 1453 1454 if (has_pts) { 1455 len_std += 4; 1456 scr = mem + 6; 1457 } else { 1458 scr = mem + 2; 1459 } 1460 1461 if (has_scr) 1462 len_std += 6; 1463 1464 if (stream->meta.format == V4L2_META_FMT_UVC) 1465 length = len_std; 1466 1467 if (length == len_std && (!has_scr || 1468 !memcmp(scr, stream->clock.last_scr, 6))) 1469 return; 1470 1471 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused); 1472 local_irq_save(flags); 1473 time = uvc_video_get_time(); 1474 sof = usb_get_current_frame_number(stream->dev->udev); 1475 local_irq_restore(flags); 1476 put_unaligned(ktime_to_ns(time), &meta->ns); 1477 put_unaligned(sof, &meta->sof); 1478 1479 if (has_scr) 1480 memcpy(stream->clock.last_scr, scr, 6); 1481 1482 meta->length = mem[0]; 1483 meta->flags = mem[1]; 1484 memcpy(meta->buf, &mem[2], length - 2); 1485 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof); 1486 1487 uvc_dbg(stream->dev, FRAME, 1488 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n", 1489 __func__, ktime_to_ns(time), meta->sof, meta->length, 1490 meta->flags, 1491 has_pts ? *(u32 *)meta->buf : 0, 1492 has_scr ? *(u32 *)scr : 0, 1493 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0); 1494 } 1495 1496 /* ------------------------------------------------------------------------ 1497 * URB handling 1498 */ 1499 1500 /* 1501 * Set error flag for incomplete buffer. 1502 */ 1503 static void uvc_video_validate_buffer(const struct uvc_streaming *stream, 1504 struct uvc_buffer *buf) 1505 { 1506 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused && 1507 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED)) 1508 buf->error = 1; 1509 } 1510 1511 /* 1512 * Completion handler for video URBs. 1513 */ 1514 1515 static void uvc_video_next_buffers(struct uvc_streaming *stream, 1516 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf) 1517 { 1518 uvc_video_validate_buffer(stream, *video_buf); 1519 1520 if (*meta_buf) { 1521 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf; 1522 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf; 1523 1524 vb2_meta->sequence = vb2_video->sequence; 1525 vb2_meta->field = vb2_video->field; 1526 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp; 1527 1528 (*meta_buf)->state = UVC_BUF_STATE_READY; 1529 if (!(*meta_buf)->error) 1530 (*meta_buf)->error = (*video_buf)->error; 1531 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue, 1532 *meta_buf); 1533 } 1534 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf); 1535 } 1536 1537 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb, 1538 struct uvc_buffer *buf, struct uvc_buffer *meta_buf) 1539 { 1540 struct urb *urb = uvc_urb->urb; 1541 struct uvc_streaming *stream = uvc_urb->stream; 1542 u8 *mem; 1543 int ret, i; 1544 1545 for (i = 0; i < urb->number_of_packets; ++i) { 1546 if (urb->iso_frame_desc[i].status < 0) { 1547 uvc_dbg(stream->dev, FRAME, 1548 "USB isochronous frame lost (%d)\n", 1549 urb->iso_frame_desc[i].status); 1550 /* Mark the buffer as faulty. */ 1551 if (buf != NULL) 1552 buf->error = 1; 1553 continue; 1554 } 1555 1556 /* Decode the payload header. */ 1557 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset; 1558 do { 1559 ret = uvc_video_decode_start(stream, buf, mem, 1560 urb->iso_frame_desc[i].actual_length); 1561 if (ret == -EAGAIN) 1562 uvc_video_next_buffers(stream, &buf, &meta_buf); 1563 } while (ret == -EAGAIN); 1564 1565 if (ret < 0) 1566 continue; 1567 1568 uvc_video_decode_meta(stream, meta_buf, mem, ret); 1569 1570 /* Decode the payload data. */ 1571 uvc_video_decode_data(uvc_urb, buf, mem + ret, 1572 urb->iso_frame_desc[i].actual_length - ret); 1573 1574 /* Process the header again. */ 1575 uvc_video_decode_end(stream, buf, mem, 1576 urb->iso_frame_desc[i].actual_length); 1577 1578 if (buf->state == UVC_BUF_STATE_READY) 1579 uvc_video_next_buffers(stream, &buf, &meta_buf); 1580 } 1581 } 1582 1583 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb, 1584 struct uvc_buffer *buf, struct uvc_buffer *meta_buf) 1585 { 1586 struct urb *urb = uvc_urb->urb; 1587 struct uvc_streaming *stream = uvc_urb->stream; 1588 u8 *mem; 1589 int len, ret; 1590 1591 /* 1592 * Ignore ZLPs if they're not part of a frame, otherwise process them 1593 * to trigger the end of payload detection. 1594 */ 1595 if (urb->actual_length == 0 && stream->bulk.header_size == 0) 1596 return; 1597 1598 mem = urb->transfer_buffer; 1599 len = urb->actual_length; 1600 stream->bulk.payload_size += len; 1601 1602 /* 1603 * If the URB is the first of its payload, decode and save the 1604 * header. 1605 */ 1606 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) { 1607 do { 1608 ret = uvc_video_decode_start(stream, buf, mem, len); 1609 if (ret == -EAGAIN) 1610 uvc_video_next_buffers(stream, &buf, &meta_buf); 1611 } while (ret == -EAGAIN); 1612 1613 /* If an error occurred skip the rest of the payload. */ 1614 if (ret < 0 || buf == NULL) { 1615 stream->bulk.skip_payload = 1; 1616 } else { 1617 memcpy(stream->bulk.header, mem, ret); 1618 stream->bulk.header_size = ret; 1619 1620 uvc_video_decode_meta(stream, meta_buf, mem, ret); 1621 1622 mem += ret; 1623 len -= ret; 1624 } 1625 } 1626 1627 /* 1628 * The buffer queue might have been cancelled while a bulk transfer 1629 * was in progress, so we can reach here with buf equal to NULL. Make 1630 * sure buf is never dereferenced if NULL. 1631 */ 1632 1633 /* Prepare video data for processing. */ 1634 if (!stream->bulk.skip_payload && buf != NULL) 1635 uvc_video_decode_data(uvc_urb, buf, mem, len); 1636 1637 /* 1638 * Detect the payload end by a URB smaller than the maximum size (or 1639 * a payload size equal to the maximum) and process the header again. 1640 */ 1641 if (urb->actual_length < urb->transfer_buffer_length || 1642 stream->bulk.payload_size >= stream->bulk.max_payload_size) { 1643 if (!stream->bulk.skip_payload && buf != NULL) { 1644 uvc_video_decode_end(stream, buf, stream->bulk.header, 1645 stream->bulk.payload_size); 1646 if (buf->state == UVC_BUF_STATE_READY) 1647 uvc_video_next_buffers(stream, &buf, &meta_buf); 1648 } 1649 1650 stream->bulk.header_size = 0; 1651 stream->bulk.skip_payload = 0; 1652 stream->bulk.payload_size = 0; 1653 } 1654 } 1655 1656 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb, 1657 struct uvc_buffer *buf, struct uvc_buffer *meta_buf) 1658 { 1659 struct urb *urb = uvc_urb->urb; 1660 struct uvc_streaming *stream = uvc_urb->stream; 1661 1662 u8 *mem = urb->transfer_buffer; 1663 int len = stream->urb_size, ret; 1664 1665 if (buf == NULL) { 1666 urb->transfer_buffer_length = 0; 1667 return; 1668 } 1669 1670 /* If the URB is the first of its payload, add the header. */ 1671 if (stream->bulk.header_size == 0) { 1672 ret = uvc_video_encode_header(stream, buf, mem, len); 1673 stream->bulk.header_size = ret; 1674 stream->bulk.payload_size += ret; 1675 mem += ret; 1676 len -= ret; 1677 } 1678 1679 /* Process video data. */ 1680 ret = uvc_video_encode_data(stream, buf, mem, len); 1681 1682 stream->bulk.payload_size += ret; 1683 len -= ret; 1684 1685 if (buf->bytesused == stream->queue.buf_used || 1686 stream->bulk.payload_size == stream->bulk.max_payload_size) { 1687 if (buf->bytesused == stream->queue.buf_used) { 1688 stream->queue.buf_used = 0; 1689 buf->state = UVC_BUF_STATE_READY; 1690 buf->buf.sequence = ++stream->sequence; 1691 uvc_queue_next_buffer(&stream->queue, buf); 1692 stream->last_fid ^= UVC_STREAM_FID; 1693 } 1694 1695 stream->bulk.header_size = 0; 1696 stream->bulk.payload_size = 0; 1697 } 1698 1699 urb->transfer_buffer_length = stream->urb_size - len; 1700 } 1701 1702 static void uvc_video_complete(struct urb *urb) 1703 { 1704 struct uvc_urb *uvc_urb = urb->context; 1705 struct uvc_streaming *stream = uvc_urb->stream; 1706 struct uvc_video_queue *queue = &stream->queue; 1707 struct uvc_video_queue *qmeta = &stream->meta.queue; 1708 struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue; 1709 struct uvc_buffer *buf = NULL; 1710 struct uvc_buffer *buf_meta = NULL; 1711 unsigned long flags; 1712 int ret; 1713 1714 switch (urb->status) { 1715 case 0: 1716 break; 1717 1718 default: 1719 dev_warn(&stream->intf->dev, 1720 "Non-zero status (%d) in video completion handler.\n", 1721 urb->status); 1722 fallthrough; 1723 case -ENOENT: /* usb_poison_urb() called. */ 1724 if (stream->frozen) 1725 return; 1726 fallthrough; 1727 case -ECONNRESET: /* usb_unlink_urb() called. */ 1728 case -ESHUTDOWN: /* The endpoint is being disabled. */ 1729 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN); 1730 if (vb2_qmeta) 1731 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN); 1732 return; 1733 } 1734 1735 buf = uvc_queue_get_current_buffer(queue); 1736 1737 if (vb2_qmeta) { 1738 spin_lock_irqsave(&qmeta->irqlock, flags); 1739 if (!list_empty(&qmeta->irqqueue)) 1740 buf_meta = list_first_entry(&qmeta->irqqueue, 1741 struct uvc_buffer, queue); 1742 spin_unlock_irqrestore(&qmeta->irqlock, flags); 1743 } 1744 1745 /* Re-initialise the URB async work. */ 1746 uvc_urb->async_operations = 0; 1747 1748 /* Sync DMA and invalidate vmap range. */ 1749 dma_sync_sgtable_for_cpu(uvc_stream_to_dmadev(uvc_urb->stream), 1750 uvc_urb->sgt, uvc_stream_dir(stream)); 1751 invalidate_kernel_vmap_range(uvc_urb->buffer, 1752 uvc_urb->stream->urb_size); 1753 1754 /* 1755 * Process the URB headers, and optionally queue expensive memcpy tasks 1756 * to be deferred to a work queue. 1757 */ 1758 stream->decode(uvc_urb, buf, buf_meta); 1759 1760 /* If no async work is needed, resubmit the URB immediately. */ 1761 if (!uvc_urb->async_operations) { 1762 ret = uvc_submit_urb(uvc_urb, GFP_ATOMIC); 1763 if (ret < 0) 1764 dev_err(&stream->intf->dev, 1765 "Failed to resubmit video URB (%d).\n", ret); 1766 return; 1767 } 1768 1769 queue_work(stream->async_wq, &uvc_urb->work); 1770 } 1771 1772 /* 1773 * Free transfer buffers. 1774 */ 1775 static void uvc_free_urb_buffers(struct uvc_streaming *stream) 1776 { 1777 struct device *dma_dev = uvc_stream_to_dmadev(stream); 1778 struct uvc_urb *uvc_urb; 1779 1780 for_each_uvc_urb(uvc_urb, stream) { 1781 if (!uvc_urb->buffer) 1782 continue; 1783 1784 dma_vunmap_noncontiguous(dma_dev, uvc_urb->buffer); 1785 dma_free_noncontiguous(dma_dev, stream->urb_size, uvc_urb->sgt, 1786 uvc_stream_dir(stream)); 1787 1788 uvc_urb->buffer = NULL; 1789 uvc_urb->sgt = NULL; 1790 } 1791 1792 stream->urb_size = 0; 1793 } 1794 1795 static bool uvc_alloc_urb_buffer(struct uvc_streaming *stream, 1796 struct uvc_urb *uvc_urb, gfp_t gfp_flags) 1797 { 1798 struct device *dma_dev = uvc_stream_to_dmadev(stream); 1799 1800 uvc_urb->sgt = dma_alloc_noncontiguous(dma_dev, stream->urb_size, 1801 uvc_stream_dir(stream), 1802 gfp_flags, 0); 1803 if (!uvc_urb->sgt) 1804 return false; 1805 uvc_urb->dma = uvc_urb->sgt->sgl->dma_address; 1806 1807 uvc_urb->buffer = dma_vmap_noncontiguous(dma_dev, stream->urb_size, 1808 uvc_urb->sgt); 1809 if (!uvc_urb->buffer) { 1810 dma_free_noncontiguous(dma_dev, stream->urb_size, 1811 uvc_urb->sgt, 1812 uvc_stream_dir(stream)); 1813 uvc_urb->sgt = NULL; 1814 return false; 1815 } 1816 1817 return true; 1818 } 1819 1820 /* 1821 * Allocate transfer buffers. This function can be called with buffers 1822 * already allocated when resuming from suspend, in which case it will 1823 * return without touching the buffers. 1824 * 1825 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the 1826 * system is too low on memory try successively smaller numbers of packets 1827 * until allocation succeeds. 1828 * 1829 * Return the number of allocated packets on success or 0 when out of memory. 1830 */ 1831 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream, 1832 unsigned int size, unsigned int psize, gfp_t gfp_flags) 1833 { 1834 unsigned int npackets; 1835 unsigned int i; 1836 1837 /* Buffers are already allocated, bail out. */ 1838 if (stream->urb_size) 1839 return stream->urb_size / psize; 1840 1841 /* 1842 * Compute the number of packets. Bulk endpoints might transfer UVC 1843 * payloads across multiple URBs. 1844 */ 1845 npackets = DIV_ROUND_UP(size, psize); 1846 if (npackets > UVC_MAX_PACKETS) 1847 npackets = UVC_MAX_PACKETS; 1848 1849 /* Retry allocations until one succeed. */ 1850 for (; npackets > 1; npackets /= 2) { 1851 stream->urb_size = psize * npackets; 1852 1853 for (i = 0; i < UVC_URBS; ++i) { 1854 struct uvc_urb *uvc_urb = &stream->uvc_urb[i]; 1855 1856 if (!uvc_alloc_urb_buffer(stream, uvc_urb, gfp_flags)) { 1857 uvc_free_urb_buffers(stream); 1858 break; 1859 } 1860 1861 uvc_urb->stream = stream; 1862 } 1863 1864 if (i == UVC_URBS) { 1865 uvc_dbg(stream->dev, VIDEO, 1866 "Allocated %u URB buffers of %ux%u bytes each\n", 1867 UVC_URBS, npackets, psize); 1868 return npackets; 1869 } 1870 } 1871 1872 uvc_dbg(stream->dev, VIDEO, 1873 "Failed to allocate URB buffers (%u bytes per packet)\n", 1874 psize); 1875 return 0; 1876 } 1877 1878 /* 1879 * Uninitialize isochronous/bulk URBs and free transfer buffers. 1880 */ 1881 static void uvc_video_stop_transfer(struct uvc_streaming *stream, 1882 int free_buffers) 1883 { 1884 struct uvc_urb *uvc_urb; 1885 1886 uvc_video_stats_stop(stream); 1887 1888 /* 1889 * We must poison the URBs rather than kill them to ensure that even 1890 * after the completion handler returns, any asynchronous workqueues 1891 * will be prevented from resubmitting the URBs. 1892 */ 1893 for_each_uvc_urb(uvc_urb, stream) 1894 usb_poison_urb(uvc_urb->urb); 1895 1896 flush_workqueue(stream->async_wq); 1897 1898 for_each_uvc_urb(uvc_urb, stream) { 1899 usb_free_urb(uvc_urb->urb); 1900 uvc_urb->urb = NULL; 1901 } 1902 1903 if (free_buffers) 1904 uvc_free_urb_buffers(stream); 1905 } 1906 1907 /* 1908 * Compute the maximum number of bytes per interval for an endpoint. 1909 */ 1910 u16 uvc_endpoint_max_bpi(struct usb_device *dev, struct usb_host_endpoint *ep) 1911 { 1912 u16 psize; 1913 1914 switch (dev->speed) { 1915 case USB_SPEED_SUPER: 1916 case USB_SPEED_SUPER_PLUS: 1917 return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval); 1918 default: 1919 psize = usb_endpoint_maxp(&ep->desc); 1920 psize *= usb_endpoint_maxp_mult(&ep->desc); 1921 return psize; 1922 } 1923 } 1924 1925 /* 1926 * Initialize isochronous URBs and allocate transfer buffers. The packet size 1927 * is given by the endpoint. 1928 */ 1929 static int uvc_init_video_isoc(struct uvc_streaming *stream, 1930 struct usb_host_endpoint *ep, gfp_t gfp_flags) 1931 { 1932 struct urb *urb; 1933 struct uvc_urb *uvc_urb; 1934 unsigned int npackets, i; 1935 u16 psize; 1936 u32 size; 1937 1938 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep); 1939 size = stream->ctrl.dwMaxVideoFrameSize; 1940 1941 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags); 1942 if (npackets == 0) 1943 return -ENOMEM; 1944 1945 size = npackets * psize; 1946 1947 for_each_uvc_urb(uvc_urb, stream) { 1948 urb = usb_alloc_urb(npackets, gfp_flags); 1949 if (urb == NULL) { 1950 uvc_video_stop_transfer(stream, 1); 1951 return -ENOMEM; 1952 } 1953 1954 urb->dev = stream->dev->udev; 1955 urb->context = uvc_urb; 1956 urb->pipe = usb_rcvisocpipe(stream->dev->udev, 1957 ep->desc.bEndpointAddress); 1958 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP; 1959 urb->transfer_dma = uvc_urb->dma; 1960 urb->interval = ep->desc.bInterval; 1961 urb->transfer_buffer = uvc_urb->buffer; 1962 urb->complete = uvc_video_complete; 1963 urb->number_of_packets = npackets; 1964 urb->transfer_buffer_length = size; 1965 1966 for (i = 0; i < npackets; ++i) { 1967 urb->iso_frame_desc[i].offset = i * psize; 1968 urb->iso_frame_desc[i].length = psize; 1969 } 1970 1971 uvc_urb->urb = urb; 1972 } 1973 1974 return 0; 1975 } 1976 1977 /* 1978 * Initialize bulk URBs and allocate transfer buffers. The packet size is 1979 * given by the endpoint. 1980 */ 1981 static int uvc_init_video_bulk(struct uvc_streaming *stream, 1982 struct usb_host_endpoint *ep, gfp_t gfp_flags) 1983 { 1984 struct urb *urb; 1985 struct uvc_urb *uvc_urb; 1986 unsigned int npackets, pipe; 1987 u16 psize; 1988 u32 size; 1989 1990 psize = usb_endpoint_maxp(&ep->desc); 1991 size = stream->ctrl.dwMaxPayloadTransferSize; 1992 stream->bulk.max_payload_size = size; 1993 1994 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags); 1995 if (npackets == 0) 1996 return -ENOMEM; 1997 1998 size = npackets * psize; 1999 2000 if (usb_endpoint_dir_in(&ep->desc)) 2001 pipe = usb_rcvbulkpipe(stream->dev->udev, 2002 ep->desc.bEndpointAddress); 2003 else 2004 pipe = usb_sndbulkpipe(stream->dev->udev, 2005 ep->desc.bEndpointAddress); 2006 2007 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) 2008 size = 0; 2009 2010 for_each_uvc_urb(uvc_urb, stream) { 2011 urb = usb_alloc_urb(0, gfp_flags); 2012 if (urb == NULL) { 2013 uvc_video_stop_transfer(stream, 1); 2014 return -ENOMEM; 2015 } 2016 2017 usb_fill_bulk_urb(urb, stream->dev->udev, pipe, uvc_urb->buffer, 2018 size, uvc_video_complete, uvc_urb); 2019 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP; 2020 urb->transfer_dma = uvc_urb->dma; 2021 2022 uvc_urb->urb = urb; 2023 } 2024 2025 return 0; 2026 } 2027 2028 /* 2029 * Initialize isochronous/bulk URBs and allocate transfer buffers. 2030 */ 2031 static int uvc_video_start_transfer(struct uvc_streaming *stream, 2032 gfp_t gfp_flags) 2033 { 2034 struct usb_interface *intf = stream->intf; 2035 struct usb_host_endpoint *ep; 2036 struct uvc_urb *uvc_urb; 2037 unsigned int i; 2038 int ret; 2039 2040 stream->sequence = -1; 2041 stream->last_fid = -1; 2042 stream->bulk.header_size = 0; 2043 stream->bulk.skip_payload = 0; 2044 stream->bulk.payload_size = 0; 2045 2046 uvc_video_stats_start(stream); 2047 2048 if (intf->num_altsetting > 1) { 2049 struct usb_host_endpoint *best_ep = NULL; 2050 unsigned int best_psize = UINT_MAX; 2051 unsigned int bandwidth; 2052 unsigned int altsetting; 2053 int intfnum = stream->intfnum; 2054 2055 /* Isochronous endpoint, select the alternate setting. */ 2056 bandwidth = stream->ctrl.dwMaxPayloadTransferSize; 2057 2058 if (bandwidth == 0) { 2059 uvc_dbg(stream->dev, VIDEO, 2060 "Device requested null bandwidth, defaulting to lowest\n"); 2061 bandwidth = 1; 2062 } else { 2063 uvc_dbg(stream->dev, VIDEO, 2064 "Device requested %u B/frame bandwidth\n", 2065 bandwidth); 2066 } 2067 2068 for (i = 0; i < intf->num_altsetting; ++i) { 2069 struct usb_host_interface *alts; 2070 unsigned int psize; 2071 2072 alts = &intf->altsetting[i]; 2073 ep = uvc_find_endpoint(alts, 2074 stream->header.bEndpointAddress); 2075 if (ep == NULL) 2076 continue; 2077 2078 /* Check if the bandwidth is high enough. */ 2079 psize = uvc_endpoint_max_bpi(stream->dev->udev, ep); 2080 if (psize >= bandwidth && psize < best_psize) { 2081 altsetting = alts->desc.bAlternateSetting; 2082 best_psize = psize; 2083 best_ep = ep; 2084 } 2085 } 2086 2087 if (best_ep == NULL) { 2088 uvc_dbg(stream->dev, VIDEO, 2089 "No fast enough alt setting for requested bandwidth\n"); 2090 return -EIO; 2091 } 2092 2093 uvc_dbg(stream->dev, VIDEO, 2094 "Selecting alternate setting %u (%u B/frame bandwidth)\n", 2095 altsetting, best_psize); 2096 2097 /* 2098 * Some devices, namely the Logitech C910 and B910, are unable 2099 * to recover from a USB autosuspend, unless the alternate 2100 * setting of the streaming interface is toggled. 2101 */ 2102 if (stream->dev->quirks & UVC_QUIRK_WAKE_AUTOSUSPEND) { 2103 usb_set_interface(stream->dev->udev, intfnum, 2104 altsetting); 2105 usb_set_interface(stream->dev->udev, intfnum, 0); 2106 } 2107 2108 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting); 2109 if (ret < 0) 2110 return ret; 2111 2112 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags); 2113 } else { 2114 /* Bulk endpoint, proceed to URB initialization. */ 2115 ep = uvc_find_endpoint(&intf->altsetting[0], 2116 stream->header.bEndpointAddress); 2117 if (ep == NULL) 2118 return -EIO; 2119 2120 /* Reject broken descriptors. */ 2121 if (usb_endpoint_maxp(&ep->desc) == 0) 2122 return -EIO; 2123 2124 ret = uvc_init_video_bulk(stream, ep, gfp_flags); 2125 } 2126 2127 if (ret < 0) 2128 return ret; 2129 2130 /* Submit the URBs. */ 2131 for_each_uvc_urb(uvc_urb, stream) { 2132 ret = uvc_submit_urb(uvc_urb, gfp_flags); 2133 if (ret < 0) { 2134 dev_err(&stream->intf->dev, 2135 "Failed to submit URB %u (%d).\n", 2136 uvc_urb_index(uvc_urb), ret); 2137 uvc_video_stop_transfer(stream, 1); 2138 return ret; 2139 } 2140 } 2141 2142 /* 2143 * The Logitech C920 temporarily forgets that it should not be adjusting 2144 * Exposure Absolute during init so restore controls to stored values. 2145 */ 2146 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT) 2147 uvc_ctrl_restore_values(stream->dev); 2148 2149 return 0; 2150 } 2151 2152 /* -------------------------------------------------------------------------- 2153 * Suspend/resume 2154 */ 2155 2156 /* 2157 * Stop streaming without disabling the video queue. 2158 * 2159 * To let userspace applications resume without trouble, we must not touch the 2160 * video buffers in any way. We mark the device as frozen to make sure the URB 2161 * completion handler won't try to cancel the queue when we kill the URBs. 2162 */ 2163 int uvc_video_suspend(struct uvc_streaming *stream) 2164 { 2165 if (!uvc_queue_streaming(&stream->queue)) 2166 return 0; 2167 2168 stream->frozen = 1; 2169 uvc_video_stop_transfer(stream, 0); 2170 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2171 return 0; 2172 } 2173 2174 /* 2175 * Reconfigure the video interface and restart streaming if it was enabled 2176 * before suspend. 2177 * 2178 * If an error occurs, disable the video queue. This will wake all pending 2179 * buffers, making sure userspace applications are notified of the problem 2180 * instead of waiting forever. 2181 */ 2182 int uvc_video_resume(struct uvc_streaming *stream, int reset) 2183 { 2184 int ret; 2185 2186 /* 2187 * If the bus has been reset on resume, set the alternate setting to 0. 2188 * This should be the default value, but some devices crash or otherwise 2189 * misbehave if they don't receive a SET_INTERFACE request before any 2190 * other video control request. 2191 */ 2192 if (reset) 2193 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2194 2195 stream->frozen = 0; 2196 2197 uvc_video_clock_reset(&stream->clock); 2198 2199 if (!uvc_queue_streaming(&stream->queue)) 2200 return 0; 2201 2202 ret = uvc_commit_video(stream, &stream->ctrl); 2203 if (ret < 0) 2204 return ret; 2205 2206 return uvc_video_start_transfer(stream, GFP_NOIO); 2207 } 2208 2209 /* ------------------------------------------------------------------------ 2210 * Video device 2211 */ 2212 2213 /* 2214 * Initialize the UVC video device by switching to alternate setting 0 and 2215 * retrieve the default format. 2216 * 2217 * Some cameras (namely the Fuji Finepix) set the format and frame 2218 * indexes to zero. The UVC standard doesn't clearly make this a spec 2219 * violation, so try to silently fix the values if possible. 2220 * 2221 * This function is called before registering the device with V4L. 2222 */ 2223 int uvc_video_init(struct uvc_streaming *stream) 2224 { 2225 struct uvc_streaming_control *probe = &stream->ctrl; 2226 const struct uvc_format *format = NULL; 2227 const struct uvc_frame *frame = NULL; 2228 struct uvc_urb *uvc_urb; 2229 unsigned int i; 2230 int ret; 2231 2232 if (stream->nformats == 0) { 2233 dev_info(&stream->intf->dev, 2234 "No supported video formats found.\n"); 2235 return -EINVAL; 2236 } 2237 2238 atomic_set(&stream->active, 0); 2239 2240 /* 2241 * Alternate setting 0 should be the default, yet the XBox Live Vision 2242 * Cam (and possibly other devices) crash or otherwise misbehave if 2243 * they don't receive a SET_INTERFACE request before any other video 2244 * control request. 2245 */ 2246 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2247 2248 /* 2249 * Set the streaming probe control with default streaming parameters 2250 * retrieved from the device. Webcams that don't support GET_DEF 2251 * requests on the probe control will just keep their current streaming 2252 * parameters. 2253 */ 2254 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0) 2255 uvc_set_video_ctrl(stream, probe, 1); 2256 2257 /* 2258 * Initialize the streaming parameters with the probe control current 2259 * value. This makes sure SET_CUR requests on the streaming commit 2260 * control will always use values retrieved from a successful GET_CUR 2261 * request on the probe control, as required by the UVC specification. 2262 */ 2263 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR); 2264 2265 /* 2266 * Elgato Cam Link 4k can be in a stalled state if the resolution of 2267 * the external source has changed while the firmware initializes. 2268 * Once in this state, the device is useless until it receives a 2269 * USB reset. It has even been observed that the stalled state will 2270 * continue even after unplugging the device. 2271 */ 2272 if (ret == -EPROTO && 2273 usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k)) { 2274 dev_err(&stream->intf->dev, "Elgato Cam Link 4K firmware crash detected\n"); 2275 dev_err(&stream->intf->dev, "Resetting the device, unplug and replug to recover\n"); 2276 usb_reset_device(stream->dev->udev); 2277 } 2278 2279 if (ret < 0) 2280 return ret; 2281 2282 /* 2283 * Check if the default format descriptor exists. Use the first 2284 * available format otherwise. 2285 */ 2286 for (i = stream->nformats; i > 0; --i) { 2287 format = &stream->formats[i-1]; 2288 if (format->index == probe->bFormatIndex) 2289 break; 2290 } 2291 2292 if (format->nframes == 0) { 2293 dev_info(&stream->intf->dev, 2294 "No frame descriptor found for the default format.\n"); 2295 return -EINVAL; 2296 } 2297 2298 /* 2299 * Zero bFrameIndex might be correct. Stream-based formats (including 2300 * MPEG-2 TS and DV) do not support frames but have a dummy frame 2301 * descriptor with bFrameIndex set to zero. If the default frame 2302 * descriptor is not found, use the first available frame. 2303 */ 2304 for (i = format->nframes; i > 0; --i) { 2305 frame = &format->frames[i-1]; 2306 if (frame->bFrameIndex == probe->bFrameIndex) 2307 break; 2308 } 2309 2310 probe->bFormatIndex = format->index; 2311 probe->bFrameIndex = frame->bFrameIndex; 2312 2313 stream->def_format = format; 2314 stream->cur_format = format; 2315 stream->cur_frame = frame; 2316 2317 /* Select the video decoding function */ 2318 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { 2319 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT) 2320 stream->decode = uvc_video_decode_isight; 2321 else if (stream->intf->num_altsetting > 1) 2322 stream->decode = uvc_video_decode_isoc; 2323 else 2324 stream->decode = uvc_video_decode_bulk; 2325 } else { 2326 if (stream->intf->num_altsetting == 1) 2327 stream->decode = uvc_video_encode_bulk; 2328 else { 2329 dev_info(&stream->intf->dev, 2330 "Isochronous endpoints are not supported for video output devices.\n"); 2331 return -EINVAL; 2332 } 2333 } 2334 2335 /* Prepare asynchronous work items. */ 2336 for_each_uvc_urb(uvc_urb, stream) 2337 INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work); 2338 2339 return 0; 2340 } 2341 2342 int uvc_video_start_streaming(struct uvc_streaming *stream) 2343 { 2344 int ret; 2345 2346 ret = uvc_video_clock_init(&stream->clock); 2347 if (ret < 0) 2348 return ret; 2349 2350 /* Commit the streaming parameters. */ 2351 ret = uvc_commit_video(stream, &stream->ctrl); 2352 if (ret < 0) 2353 goto error_commit; 2354 2355 ret = uvc_video_start_transfer(stream, GFP_KERNEL); 2356 if (ret < 0) 2357 goto error_video; 2358 2359 return 0; 2360 2361 error_video: 2362 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2363 error_commit: 2364 uvc_video_clock_cleanup(&stream->clock); 2365 2366 return ret; 2367 } 2368 2369 void uvc_video_stop_streaming(struct uvc_streaming *stream) 2370 { 2371 uvc_video_stop_transfer(stream, 1); 2372 2373 if (stream->intf->num_altsetting > 1) { 2374 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2375 } else { 2376 /* 2377 * UVC doesn't specify how to inform a bulk-based device 2378 * when the video stream is stopped. Windows sends a 2379 * CLEAR_FEATURE(HALT) request to the video streaming 2380 * bulk endpoint, mimic the same behaviour. 2381 */ 2382 unsigned int epnum = stream->header.bEndpointAddress 2383 & USB_ENDPOINT_NUMBER_MASK; 2384 unsigned int dir = stream->header.bEndpointAddress 2385 & USB_ENDPOINT_DIR_MASK; 2386 unsigned int pipe; 2387 2388 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir; 2389 usb_clear_halt(stream->dev->udev, pipe); 2390 } 2391 2392 uvc_video_clock_cleanup(&stream->clock); 2393 } 2394