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->intf->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->intf->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->intf->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: Reducing max payload transfer size (%u) to fit endpoint limit (%u).\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 /* 498 * The accuracy of the hardware timestamping depends on having enough data to 499 * interpolate between the different clock domains. This value is sof cycles, 500 * this is, milliseconds. 501 */ 502 #define UVC_MIN_HW_TIMESTAMP_DIFF 100 503 504 static inline ktime_t uvc_video_get_time(void) 505 { 506 if (uvc_clock_param == CLOCK_MONOTONIC) 507 return ktime_get(); 508 else 509 return ktime_get_real(); 510 } 511 512 static void uvc_video_clock_add_sample(struct uvc_clock *clock, 513 const struct uvc_clock_sample *sample) 514 { 515 unsigned long flags; 516 517 /* 518 * If we write new data on the position where we had the last 519 * overflow, remove the overflow pointer. There is no SOF overflow 520 * in the whole circular buffer. 521 */ 522 if (clock->head == clock->last_sof_overflow) 523 clock->last_sof_overflow = -1; 524 525 spin_lock_irqsave(&clock->lock, flags); 526 527 if (clock->count > 0 && clock->last_sof_processed > sample->dev_sof) { 528 /* 529 * Remove data from the circular buffer that is older than the 530 * last SOF overflow. We only support one SOF overflow per 531 * circular buffer. 532 */ 533 if (clock->last_sof_overflow != -1) 534 clock->count = (clock->head - clock->last_sof_overflow 535 + clock->size) % clock->size; 536 clock->last_sof_overflow = clock->head; 537 } 538 539 /* Add sample. */ 540 clock->samples[clock->head] = *sample; 541 clock->head = (clock->head + 1) % clock->size; 542 clock->count = min(clock->count + 1, clock->size); 543 544 spin_unlock_irqrestore(&clock->lock, flags); 545 } 546 547 static inline u16 sof_diff(u16 a, u16 b) 548 { 549 /* 550 * Because the result is modulo 2048 (via & 2047), we do not need a 551 * special case for a < b. 552 */ 553 return (a - b) & 2047; 554 } 555 556 static void 557 uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf, 558 const u8 *data, int len) 559 { 560 struct uvc_clock_sample sample; 561 unsigned int header_size; 562 bool has_pts = false; 563 bool has_scr = false; 564 565 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) { 566 case UVC_STREAM_PTS | UVC_STREAM_SCR: 567 header_size = 12; 568 has_pts = true; 569 has_scr = true; 570 break; 571 case UVC_STREAM_PTS: 572 header_size = 6; 573 has_pts = true; 574 break; 575 case UVC_STREAM_SCR: 576 header_size = 8; 577 has_scr = true; 578 break; 579 default: 580 header_size = 2; 581 break; 582 } 583 584 /* Check for invalid headers. */ 585 if (len < header_size) 586 return; 587 588 /* 589 * Extract the timestamps: 590 * 591 * - store the frame PTS in the buffer structure 592 * - if the SCR field is present, retrieve the host SOF counter and 593 * kernel timestamps and store them with the SCR STC and SOF fields 594 * in the ring buffer 595 */ 596 if (has_pts && buf != NULL) 597 buf->pts = get_unaligned_le32(&data[2]); 598 599 if (!has_scr) 600 return; 601 602 sample.dev_sof = get_unaligned_le16(&data[header_size - 2]) & 2047; 603 /* If the sample SOF is identical to the previous one, quit early. */ 604 if (stream->clock.last_sof_raw == sample.dev_sof) 605 return; 606 stream->clock.last_sof_raw = sample.dev_sof; 607 608 sample.dev_stc = get_unaligned_le32(&data[header_size - 6]); 609 610 /* 611 * STC (Source Time Clock) is the clock used by the camera. The UVC 1.5 612 * standard states that it "must be captured when the first video data 613 * of a video frame is put on the USB bus". This is generally understood 614 * as requiring devices to clear the payload header's SCR bit before 615 * the first packet containing video data. 616 * 617 * Most vendors follow that interpretation, but some (namely SunplusIT 618 * on some devices) always set the `UVC_STREAM_SCR` bit, fill the SCR 619 * field with 0's,and expect that the driver only processes the SCR if 620 * there is data in the packet. 621 * 622 * Ignore all the hardware timestamp information if we haven't received 623 * any data for this frame yet, the packet contains no data, and both 624 * STC and SOF are zero. This heuristics should be safe on compliant 625 * devices. This should be safe with compliant devices, as in the very 626 * unlikely case where a UVC 1.1 device would send timing information 627 * only before the first packet containing data, and both STC and SOF 628 * happen to be zero for a particular frame, we would only miss one 629 * clock sample from many and the clock recovery algorithm wouldn't 630 * suffer from this condition. 631 */ 632 if (buf && buf->bytesused == 0 && len == header_size && 633 sample.dev_stc == 0 && sample.dev_sof == 0) 634 return; 635 636 sample.host_sof = usb_get_current_frame_number(stream->dev->udev); 637 638 /* 639 * On some devices, like the Logitech C922, the device SOF does not run 640 * at a stable rate of 1kHz. For those devices use the host SOF instead. 641 * In the tests performed so far, this improves the timestamp precision. 642 * This is probably explained by a small packet handling jitter from the 643 * host, but the exact reason hasn't been fully determined. 644 */ 645 if (stream->dev->quirks & UVC_QUIRK_INVALID_DEVICE_SOF) 646 sample.dev_sof = sample.host_sof; 647 648 /* 649 * The UVC specification allows device implementations that can't obtain 650 * the USB frame number to keep their own frame counters as long as they 651 * match the size and frequency of the frame number associated with USB 652 * SOF tokens. The SOF values sent by such devices differ from the USB 653 * SOF tokens by a fixed offset that needs to be estimated and accounted 654 * for to make timestamp recovery as accurate as possible. 655 * 656 * The offset is estimated the first time a device SOF value is received 657 * as the difference between the host and device SOF values. As the two 658 * SOF values can differ slightly due to transmission delays, consider 659 * that the offset is null if the difference is not higher than 10 ms 660 * (negative differences can not happen and are thus considered as an 661 * offset). The video commit control wDelay field should be used to 662 * compute a dynamic threshold instead of using a fixed 10 ms value, but 663 * devices don't report reliable wDelay values. 664 * 665 * See uvc_video_clock_host_sof() for an explanation regarding why only 666 * the 8 LSBs of the delta are kept. 667 */ 668 if (stream->clock.sof_offset == (u16)-1) { 669 u16 delta_sof = (sample.host_sof - sample.dev_sof) & 255; 670 if (delta_sof >= 10) 671 stream->clock.sof_offset = delta_sof; 672 else 673 stream->clock.sof_offset = 0; 674 } 675 676 sample.dev_sof = (sample.dev_sof + stream->clock.sof_offset) & 2047; 677 678 /* 679 * To limit the amount of data, drop SCRs with an SOF similar to the 680 * previous one. This filtering is also needed to support UVC 1.5, where 681 * all the data packets of the same frame contains the same SOF. In that 682 * case only the first one will match the host_sof. 683 */ 684 if (sof_diff(sample.dev_sof, stream->clock.last_sof_processed) <= 685 (UVC_MIN_HW_TIMESTAMP_DIFF / stream->clock.size)) 686 return; 687 688 /* This is expensive, only do it if the sample will be added. */ 689 sample.host_time = uvc_video_get_time(); 690 691 uvc_video_clock_add_sample(&stream->clock, &sample); 692 stream->clock.last_sof_processed = sample.dev_sof; 693 } 694 695 static void uvc_video_clock_reset(struct uvc_clock *clock) 696 { 697 clock->head = 0; 698 clock->count = 0; 699 clock->last_sof_processed = -1; 700 clock->last_sof_raw = -1; 701 clock->last_sof_overflow = -1; 702 clock->sof_offset = -1; 703 } 704 705 static int uvc_video_clock_init(struct uvc_clock *clock) 706 { 707 spin_lock_init(&clock->lock); 708 clock->size = 32; 709 710 clock->samples = kmalloc_objs(*clock->samples, clock->size); 711 if (clock->samples == NULL) 712 return -ENOMEM; 713 714 uvc_video_clock_reset(clock); 715 716 return 0; 717 } 718 719 static void uvc_video_clock_cleanup(struct uvc_clock *clock) 720 { 721 kfree(clock->samples); 722 clock->samples = NULL; 723 } 724 725 /* 726 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample 727 * 728 * Host SOF counters reported by usb_get_current_frame_number() usually don't 729 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame 730 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host 731 * controller and its configuration. 732 * 733 * We thus need to recover the SOF value corresponding to the host frame number. 734 * As the device and host frame numbers are sampled in a short interval, the 735 * difference between their values should be equal to a small delta plus an 736 * integer multiple of 256 caused by the host frame number limited precision. 737 * 738 * To obtain the recovered host SOF value, compute the small delta by masking 739 * the high bits of the host frame counter and device SOF difference and add it 740 * to the device SOF value. 741 */ 742 static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample) 743 { 744 /* The delta value can be negative. */ 745 s8 delta_sof; 746 747 delta_sof = (sample->host_sof - sample->dev_sof) & 255; 748 749 return (sample->dev_sof + delta_sof) & 2047; 750 } 751 752 /* 753 * uvc_video_clock_update - Update the buffer timestamp 754 * 755 * This function converts the buffer PTS timestamp to the host clock domain by 756 * going through the USB SOF clock domain and stores the result in the V4L2 757 * buffer timestamp field. 758 * 759 * The relationship between the device clock and the host clock isn't known. 760 * However, the device and the host share the common USB SOF clock which can be 761 * used to recover that relationship. 762 * 763 * The relationship between the device clock and the USB SOF clock is considered 764 * to be linear over the clock samples sliding window and is given by 765 * 766 * SOF = m * PTS + p 767 * 768 * Several methods to compute the slope (m) and intercept (p) can be used. As 769 * the clock drift should be small compared to the sliding window size, we 770 * assume that the line that goes through the points at both ends of the window 771 * is a good approximation. Naming those points P1 and P2, we get 772 * 773 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS 774 * + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) 775 * 776 * or 777 * 778 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1) (1) 779 * 780 * to avoid losing precision in the division. Similarly, the host timestamp is 781 * computed with 782 * 783 * TS = ((TS2 - TS1) * SOF + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1) (2) 784 * 785 * SOF values are coded on 11 bits by USB. We extend their precision with 16 786 * decimal bits, leading to a 11.16 coding. 787 * 788 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should 789 * be normalized using the nominal device clock frequency reported through the 790 * UVC descriptors. 791 * 792 * Both the PTS/STC and SOF counters roll over, after a fixed but device 793 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the 794 * sliding window size is smaller than the rollover period, differences computed 795 * on unsigned integers will produce the correct result. However, the p term in 796 * the linear relations will be miscomputed. 797 * 798 * To fix the issue, we subtract a constant from the PTS and STC values to bring 799 * PTS to half the 32 bit STC range. The sliding window STC values then fit into 800 * the 32 bit range without any rollover. 801 * 802 * Similarly, we add 2048 to the device SOF values to make sure that the SOF 803 * computed by (1) will never be smaller than 0. This offset is then compensated 804 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent 805 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly 806 * lower than 4096, and the host SOF counters can have rolled over to 2048. This 807 * case is handled by subtracting 2048 from the SOF value if it exceeds the host 808 * SOF value at the end of the sliding window. 809 * 810 * Finally we subtract a constant from the host timestamps to bring the first 811 * timestamp of the sliding window to 1s. 812 */ 813 void uvc_video_clock_update(struct uvc_streaming *stream, 814 struct vb2_v4l2_buffer *vbuf, 815 struct uvc_buffer *buf) 816 { 817 struct uvc_clock *clock = &stream->clock; 818 struct uvc_clock_sample *first; 819 struct uvc_clock_sample *last; 820 unsigned long flags; 821 u64 timestamp; 822 u32 delta_stc; 823 u32 y1; 824 u32 x1, x2; 825 u32 mean; 826 u32 sof; 827 u64 y, y2; 828 829 if (!uvc_hw_timestamps_param) 830 return; 831 832 /* 833 * We will get called from __vb2_queue_cancel() if there are buffers 834 * done but not dequeued by the user, but the sample array has already 835 * been released at that time. Just bail out in that case. 836 */ 837 if (!clock->samples) 838 return; 839 840 spin_lock_irqsave(&clock->lock, flags); 841 842 if (clock->count < 2) 843 goto done; 844 845 first = &clock->samples[(clock->head - clock->count + clock->size) % clock->size]; 846 last = &clock->samples[(clock->head - 1 + clock->size) % clock->size]; 847 848 /* First step, PTS to SOF conversion. */ 849 delta_stc = buf->pts - (1UL << 31); 850 x1 = first->dev_stc - delta_stc; 851 x2 = last->dev_stc - delta_stc; 852 if (x1 == x2) 853 goto done; 854 855 y1 = (first->dev_sof + 2048) << 16; 856 y2 = (last->dev_sof + 2048) << 16; 857 if (y2 < y1) 858 y2 += 2048 << 16; 859 860 /* 861 * If the buffer is not full, we want to gather at least 1/4th of 862 * timestamps before using HW timestamping. We do this to avoid jitter 863 * on the initial frames. 864 * 865 * If the buffer is full we would use it regardless of how much data 866 * it represents. This could be solved with an infinite big circular 867 * buffer, but RAM is expensive these days, specially the infinitely 868 * big. 869 * 870 * The value of UVC_MIN_HW_TIMESTAMP_DIFF was determined by running 871 * Android's CTS on different devices. 872 * 873 * y1 and y2 are dev_sof with a fixed point precision of 16 bits. 874 */ 875 if (clock->size != clock->count && 876 (y2 - y1) < (UVC_MIN_HW_TIMESTAMP_DIFF << 16)) 877 goto done; 878 879 y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2 880 - (u64)y2 * (u64)x1; 881 y = div_u64(y, x2 - x1); 882 883 sof = y; 884 885 uvc_dbg(stream->dev, CLOCK, 886 "%s: PTS %u y %llu.%06llu SOF %u.%06llu (x1 %u x2 %u y1 %u y2 %llu SOF offset %u)\n", 887 stream->dev->name, buf->pts, 888 y >> 16, div_u64((y & 0xffff) * 1000000, 65536), 889 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536), 890 x1, x2, y1, y2, clock->sof_offset); 891 892 /* Second step, SOF to host clock conversion. */ 893 x1 = (uvc_video_clock_host_sof(first) + 2048) << 16; 894 x2 = (uvc_video_clock_host_sof(last) + 2048) << 16; 895 if (x2 < x1) 896 x2 += 2048 << 16; 897 if (x1 == x2) 898 goto done; 899 900 y1 = NSEC_PER_SEC; 901 y2 = ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1; 902 903 /* 904 * Interpolated and host SOF timestamps can wrap around at slightly 905 * different times. Handle this by adding or removing 2048 to or from 906 * the computed SOF value to keep it close to the SOF samples mean 907 * value. 908 */ 909 mean = (x1 + x2) / 2; 910 if (mean - (1024 << 16) > sof) 911 sof += 2048 << 16; 912 else if (sof > mean + (1024 << 16)) 913 sof -= 2048 << 16; 914 915 y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2 916 - (u64)y2 * (u64)x1; 917 y = div_u64(y, x2 - x1); 918 919 timestamp = ktime_to_ns(first->host_time) + y - y1; 920 921 uvc_dbg(stream->dev, CLOCK, 922 "%s: SOF %u.%06llu y %llu ts %llu buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %llu)\n", 923 stream->dev->name, 924 sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536), 925 y, timestamp, vbuf->vb2_buf.timestamp, 926 x1, first->host_sof, first->dev_sof, 927 x2, last->host_sof, last->dev_sof, y1, y2); 928 929 /* Update the V4L2 buffer. */ 930 vbuf->vb2_buf.timestamp = timestamp; 931 932 done: 933 spin_unlock_irqrestore(&clock->lock, flags); 934 } 935 936 /* ------------------------------------------------------------------------ 937 * Stream statistics 938 */ 939 940 static void uvc_video_stats_decode(struct uvc_streaming *stream, 941 const u8 *data, int len) 942 { 943 unsigned int header_size; 944 bool has_pts = false; 945 bool has_scr = false; 946 u16 scr_sof; 947 u32 scr_stc; 948 u32 pts; 949 950 if (stream->stats.stream.nb_frames == 0 && 951 stream->stats.frame.nb_packets == 0) 952 stream->stats.stream.start_ts = ktime_get(); 953 954 switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) { 955 case UVC_STREAM_PTS | UVC_STREAM_SCR: 956 header_size = 12; 957 has_pts = true; 958 has_scr = true; 959 break; 960 case UVC_STREAM_PTS: 961 header_size = 6; 962 has_pts = true; 963 break; 964 case UVC_STREAM_SCR: 965 header_size = 8; 966 has_scr = true; 967 break; 968 default: 969 header_size = 2; 970 break; 971 } 972 973 /* Check for invalid headers. */ 974 if (len < header_size || data[0] < header_size) { 975 stream->stats.frame.nb_invalid++; 976 return; 977 } 978 979 /* Extract the timestamps. */ 980 if (has_pts) 981 pts = get_unaligned_le32(&data[2]); 982 983 if (has_scr) { 984 scr_stc = get_unaligned_le32(&data[header_size - 6]); 985 scr_sof = get_unaligned_le16(&data[header_size - 2]); 986 } 987 988 /* Is PTS constant through the whole frame ? */ 989 if (has_pts && stream->stats.frame.nb_pts) { 990 if (stream->stats.frame.pts != pts) { 991 stream->stats.frame.nb_pts_diffs++; 992 stream->stats.frame.last_pts_diff = 993 stream->stats.frame.nb_packets; 994 } 995 } 996 997 if (has_pts) { 998 stream->stats.frame.nb_pts++; 999 stream->stats.frame.pts = pts; 1000 } 1001 1002 /* 1003 * Do all frames have a PTS in their first non-empty packet, or before 1004 * their first empty packet ? 1005 */ 1006 if (stream->stats.frame.size == 0) { 1007 if (len > header_size) 1008 stream->stats.frame.has_initial_pts = has_pts; 1009 if (len == header_size && has_pts) 1010 stream->stats.frame.has_early_pts = true; 1011 } 1012 1013 /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */ 1014 if (has_scr && stream->stats.frame.nb_scr) { 1015 if (stream->stats.frame.scr_stc != scr_stc) 1016 stream->stats.frame.nb_scr_diffs++; 1017 } 1018 1019 if (has_scr) { 1020 /* Expand the SOF counter to 32 bits and store its value. */ 1021 if (stream->stats.stream.nb_frames > 0 || 1022 stream->stats.frame.nb_scr > 0) 1023 stream->stats.stream.scr_sof_count += 1024 (scr_sof - stream->stats.stream.scr_sof) % 2048; 1025 stream->stats.stream.scr_sof = scr_sof; 1026 1027 stream->stats.frame.nb_scr++; 1028 stream->stats.frame.scr_stc = scr_stc; 1029 stream->stats.frame.scr_sof = scr_sof; 1030 1031 if (scr_sof < stream->stats.stream.min_sof) 1032 stream->stats.stream.min_sof = scr_sof; 1033 if (scr_sof > stream->stats.stream.max_sof) 1034 stream->stats.stream.max_sof = scr_sof; 1035 } 1036 1037 /* Record the first non-empty packet number. */ 1038 if (stream->stats.frame.size == 0 && len > header_size) 1039 stream->stats.frame.first_data = stream->stats.frame.nb_packets; 1040 1041 /* Update the frame size. */ 1042 stream->stats.frame.size += len - header_size; 1043 1044 /* Update the packets counters. */ 1045 stream->stats.frame.nb_packets++; 1046 if (len <= header_size) 1047 stream->stats.frame.nb_empty++; 1048 1049 if (data[1] & UVC_STREAM_ERR) 1050 stream->stats.frame.nb_errors++; 1051 } 1052 1053 static void uvc_video_stats_update(struct uvc_streaming *stream) 1054 { 1055 struct uvc_stats_frame *frame = &stream->stats.frame; 1056 1057 uvc_dbg(stream->dev, STATS, 1058 "frame %u stats: %u/%u/%u packets, %u/%u/%u pts (%searly %sinitial), %u/%u scr, last pts/stc/sof %u/%u/%u\n", 1059 stream->sequence, frame->first_data, 1060 frame->nb_packets - frame->nb_empty, frame->nb_packets, 1061 frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts, 1062 frame->has_early_pts ? "" : "!", 1063 frame->has_initial_pts ? "" : "!", 1064 frame->nb_scr_diffs, frame->nb_scr, 1065 frame->pts, frame->scr_stc, frame->scr_sof); 1066 1067 stream->stats.stream.nb_frames++; 1068 stream->stats.stream.nb_packets += stream->stats.frame.nb_packets; 1069 stream->stats.stream.nb_empty += stream->stats.frame.nb_empty; 1070 stream->stats.stream.nb_errors += stream->stats.frame.nb_errors; 1071 stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid; 1072 1073 if (frame->has_early_pts) 1074 stream->stats.stream.nb_pts_early++; 1075 if (frame->has_initial_pts) 1076 stream->stats.stream.nb_pts_initial++; 1077 if (frame->last_pts_diff <= frame->first_data) 1078 stream->stats.stream.nb_pts_constant++; 1079 if (frame->nb_scr >= frame->nb_packets - frame->nb_empty) 1080 stream->stats.stream.nb_scr_count_ok++; 1081 if (frame->nb_scr_diffs + 1 == frame->nb_scr) 1082 stream->stats.stream.nb_scr_diffs_ok++; 1083 1084 memset(&stream->stats.frame, 0, sizeof(stream->stats.frame)); 1085 } 1086 1087 size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf, 1088 size_t size) 1089 { 1090 unsigned int scr_sof_freq; 1091 unsigned int duration; 1092 size_t count = 0; 1093 1094 /* 1095 * Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF 1096 * frequency this will not overflow before more than 1h. 1097 */ 1098 duration = ktime_ms_delta(stream->stats.stream.stop_ts, 1099 stream->stats.stream.start_ts); 1100 if (duration != 0) 1101 scr_sof_freq = stream->stats.stream.scr_sof_count * 1000 1102 / duration; 1103 else 1104 scr_sof_freq = 0; 1105 1106 count += scnprintf(buf + count, size - count, 1107 "frames: %u\npackets: %u\nempty: %u\n" 1108 "errors: %u\ninvalid: %u\n", 1109 stream->stats.stream.nb_frames, 1110 stream->stats.stream.nb_packets, 1111 stream->stats.stream.nb_empty, 1112 stream->stats.stream.nb_errors, 1113 stream->stats.stream.nb_invalid); 1114 count += scnprintf(buf + count, size - count, 1115 "pts: %u early, %u initial, %u ok\n", 1116 stream->stats.stream.nb_pts_early, 1117 stream->stats.stream.nb_pts_initial, 1118 stream->stats.stream.nb_pts_constant); 1119 count += scnprintf(buf + count, size - count, 1120 "scr: %u count ok, %u diff ok\n", 1121 stream->stats.stream.nb_scr_count_ok, 1122 stream->stats.stream.nb_scr_diffs_ok); 1123 count += scnprintf(buf + count, size - count, 1124 "sof: %u <= sof <= %u, freq %u.%03u kHz\n", 1125 stream->stats.stream.min_sof, 1126 stream->stats.stream.max_sof, 1127 scr_sof_freq / 1000, scr_sof_freq % 1000); 1128 1129 return count; 1130 } 1131 1132 static void uvc_video_stats_start(struct uvc_streaming *stream) 1133 { 1134 memset(&stream->stats, 0, sizeof(stream->stats)); 1135 stream->stats.stream.min_sof = 2048; 1136 } 1137 1138 static void uvc_video_stats_stop(struct uvc_streaming *stream) 1139 { 1140 stream->stats.stream.stop_ts = ktime_get(); 1141 } 1142 1143 /* ------------------------------------------------------------------------ 1144 * Video codecs 1145 */ 1146 1147 /* 1148 * Video payload decoding is handled by uvc_video_decode_start(), 1149 * uvc_video_decode_data() and uvc_video_decode_end(). 1150 * 1151 * uvc_video_decode_start is called with URB data at the start of a bulk or 1152 * isochronous payload. It processes header data and returns the header size 1153 * in bytes if successful. If an error occurs, it returns a negative error 1154 * code. The following error codes have special meanings. 1155 * 1156 * - EAGAIN informs the caller that the current video buffer should be marked 1157 * as done, and that the function should be called again with the same data 1158 * and a new video buffer. This is used when end of frame conditions can be 1159 * reliably detected at the beginning of the next frame only. 1160 * 1161 * If an error other than -EAGAIN is returned, the caller will drop the current 1162 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be 1163 * made until the next payload. -ENODATA can be used to drop the current 1164 * payload if no other error code is appropriate. 1165 * 1166 * uvc_video_decode_data is called for every URB with URB data. It copies the 1167 * data to the video buffer. 1168 * 1169 * uvc_video_decode_end is called with header data at the end of a bulk or 1170 * isochronous payload. It performs any additional header data processing and 1171 * returns 0 or a negative error code if an error occurred. As header data have 1172 * already been processed by uvc_video_decode_start, this functions isn't 1173 * required to perform sanity checks a second time. 1174 * 1175 * For isochronous transfers where a payload is always transferred in a single 1176 * URB, the three functions will be called in a row. 1177 * 1178 * To let the decoder process header data and update its internal state even 1179 * when no video buffer is available, uvc_video_decode_start must be prepared 1180 * to be called with a NULL buf parameter. uvc_video_decode_data and 1181 * uvc_video_decode_end will never be called with a NULL buffer. 1182 */ 1183 static int uvc_video_decode_start(struct uvc_streaming *stream, 1184 struct uvc_buffer *buf, 1185 struct uvc_buffer *meta_buf, 1186 const u8 *data, int len) 1187 { 1188 u8 header_len; 1189 u8 fid; 1190 1191 /* 1192 * Sanity checks: 1193 * - packet must be at least 2 bytes long 1194 * - bHeaderLength value must be at least 2 bytes (see above) 1195 * - bHeaderLength value can't be larger than the packet size. 1196 */ 1197 if (len < 2 || data[0] < 2 || data[0] > len) { 1198 stream->stats.frame.nb_invalid++; 1199 return -EINVAL; 1200 } 1201 1202 header_len = data[0]; 1203 fid = data[1] & UVC_STREAM_FID; 1204 1205 /* 1206 * Mark the buffer as done if we're at the beginning of a new frame. 1207 * End of frame detection is better implemented by checking the EOF 1208 * bit (FID bit toggling is delayed by one frame compared to the EOF 1209 * bit), but some devices don't set the bit at end of frame (and the 1210 * last payload can be lost anyway). We thus must check if the FID has 1211 * been toggled. 1212 * 1213 * stream->last_fid is initialized to -1, and buf->bytesused to 0, 1214 * so the first isochronous frame will never trigger an end of frame 1215 * detection. 1216 * 1217 * Empty buffers (bytesused == 0) don't trigger end of frame detection 1218 * as it doesn't make sense to return an empty buffer. This also 1219 * avoids detecting end of frame conditions at FID toggling if the 1220 * previous payload had the EOF bit set. 1221 */ 1222 if (fid != stream->last_fid && buf && buf->bytesused != 0) { 1223 uvc_dbg(stream->dev, FRAME, 1224 "Frame complete (FID bit toggled)\n"); 1225 buf->state = UVC_BUF_STATE_READY; 1226 1227 return -EAGAIN; 1228 } 1229 1230 /* 1231 * Some cameras, when running two parallel streams (one MJPEG alongside 1232 * another non-MJPEG stream), are known to lose the EOF packet for a frame. 1233 * We can detect the end of a frame by checking for a new SOI marker, as 1234 * the SOI always lies on the packet boundary between two frames for 1235 * these devices. 1236 */ 1237 if (stream->dev->quirks & UVC_QUIRK_MJPEG_NO_EOF && 1238 (stream->cur_format->fcc == V4L2_PIX_FMT_MJPEG || 1239 stream->cur_format->fcc == V4L2_PIX_FMT_JPEG) && 1240 buf && buf->bytesused != 0) { 1241 const u8 *packet = data + header_len; 1242 1243 if (len >= header_len + 2 && 1244 packet[0] == 0xff && packet[1] == JPEG_MARKER_SOI) { 1245 buf->state = UVC_BUF_STATE_READY; 1246 buf->error = 1; 1247 stream->last_fid ^= UVC_STREAM_FID; 1248 return -EAGAIN; 1249 } 1250 } 1251 1252 /* 1253 * Increase the sequence number regardless of any buffer states, so 1254 * that discontinuous sequence numbers always indicate lost frames. 1255 */ 1256 if (stream->last_fid != fid) { 1257 stream->sequence++; 1258 if (stream->sequence) 1259 uvc_video_stats_update(stream); 1260 1261 /* 1262 * On a FID flip initialize sequence number and timestamp. 1263 * 1264 * The driver already takes care of injecting FID flips for 1265 * UVC_QUIRK_STREAM_NO_FID and UVC_QUIRK_MJPEG_NO_EOF. 1266 */ 1267 if (buf) { 1268 buf->buf.field = V4L2_FIELD_NONE; 1269 buf->buf.sequence = stream->sequence; 1270 buf->buf.vb2_buf.timestamp = 1271 ktime_to_ns(uvc_video_get_time()); 1272 } 1273 } 1274 1275 uvc_video_clock_decode(stream, buf, data, len); 1276 uvc_video_stats_decode(stream, data, len); 1277 1278 /* 1279 * Store the payload FID bit and return immediately when the buffer is 1280 * NULL. 1281 */ 1282 if (buf == NULL) { 1283 stream->last_fid = fid; 1284 return -ENODATA; 1285 } 1286 1287 /* Mark the buffer as bad if the error bit is set. */ 1288 if (data[1] & UVC_STREAM_ERR) { 1289 uvc_dbg(stream->dev, FRAME, 1290 "Marking buffer as bad (error bit set)\n"); 1291 buf->error = 1; 1292 } 1293 1294 /* 1295 * Synchronize to the input stream by waiting for the FID bit to be 1296 * toggled when the buffer state is not UVC_BUF_STATE_ACTIVE. 1297 * stream->last_fid is initialized to -1, so the first isochronous 1298 * frame will always be in sync. 1299 * 1300 * If the device doesn't toggle the FID bit, invert stream->last_fid 1301 * when the EOF bit is set to force synchronisation on the next packet. 1302 */ 1303 if (buf->state != UVC_BUF_STATE_ACTIVE) { 1304 if (fid == stream->last_fid) { 1305 uvc_dbg(stream->dev, FRAME, 1306 "Dropping payload (out of sync)\n"); 1307 if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) && 1308 (data[1] & UVC_STREAM_EOF)) 1309 stream->last_fid ^= UVC_STREAM_FID; 1310 return -ENODATA; 1311 } 1312 1313 /* TODO: Handle PTS and SCR. */ 1314 buf->state = UVC_BUF_STATE_ACTIVE; 1315 if (meta_buf) 1316 meta_buf->state = UVC_BUF_STATE_ACTIVE; 1317 } 1318 1319 stream->last_fid = fid; 1320 1321 return header_len; 1322 } 1323 1324 static inline enum dma_data_direction uvc_stream_dir( 1325 struct uvc_streaming *stream) 1326 { 1327 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) 1328 return DMA_FROM_DEVICE; 1329 else 1330 return DMA_TO_DEVICE; 1331 } 1332 1333 /* 1334 * uvc_video_decode_data_work: Asynchronous memcpy processing 1335 * 1336 * Copy URB data to video buffers in process context, releasing buffer 1337 * references and requeuing the URB when done. 1338 */ 1339 static void uvc_video_copy_data_work(struct work_struct *work) 1340 { 1341 struct uvc_urb *uvc_urb = container_of(work, struct uvc_urb, work); 1342 unsigned int i; 1343 int ret; 1344 1345 for (i = 0; i < uvc_urb->async_operations; i++) { 1346 struct uvc_copy_op *op = &uvc_urb->copy_operations[i]; 1347 1348 memcpy(op->dst, op->src, op->len); 1349 1350 /* Release reference taken on this buffer. */ 1351 uvc_queue_buffer_release(op->buf); 1352 } 1353 1354 ret = usb_submit_urb(uvc_urb->urb, GFP_KERNEL); 1355 if (ret < 0) 1356 dev_err(&uvc_urb->stream->intf->dev, 1357 "Failed to resubmit video URB (%d).\n", ret); 1358 } 1359 1360 static void uvc_video_decode_data(struct uvc_urb *uvc_urb, 1361 struct uvc_buffer *buf, const u8 *data, int len) 1362 { 1363 unsigned int active_op = uvc_urb->async_operations; 1364 struct uvc_copy_op *op = &uvc_urb->copy_operations[active_op]; 1365 unsigned int maxlen; 1366 1367 if (len <= 0) 1368 return; 1369 1370 maxlen = buf->length - buf->bytesused; 1371 1372 /* Take a buffer reference for async work. */ 1373 kref_get(&buf->ref); 1374 1375 op->buf = buf; 1376 op->src = data; 1377 op->dst = buf->mem + buf->bytesused; 1378 op->len = min_t(unsigned int, len, maxlen); 1379 1380 buf->bytesused += op->len; 1381 1382 /* Complete the current frame if the buffer size was exceeded. */ 1383 if (len > maxlen) { 1384 uvc_dbg(uvc_urb->stream->dev, FRAME, 1385 "Frame complete (overflow)\n"); 1386 buf->error = 1; 1387 buf->state = UVC_BUF_STATE_READY; 1388 } 1389 1390 uvc_urb->async_operations++; 1391 } 1392 1393 static void uvc_video_decode_end(struct uvc_streaming *stream, 1394 struct uvc_buffer *buf, const u8 *data, int len) 1395 { 1396 /* Mark the buffer as done if the EOF marker is set. */ 1397 if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) { 1398 uvc_dbg(stream->dev, FRAME, "Frame complete (EOF found)\n"); 1399 if (data[0] == len) 1400 uvc_dbg(stream->dev, FRAME, "EOF in empty payload\n"); 1401 buf->state = UVC_BUF_STATE_READY; 1402 if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) 1403 stream->last_fid ^= UVC_STREAM_FID; 1404 } 1405 } 1406 1407 /* 1408 * Video payload encoding is handled by uvc_video_encode_header() and 1409 * uvc_video_encode_data(). Only bulk transfers are currently supported. 1410 * 1411 * uvc_video_encode_header is called at the start of a payload. It adds header 1412 * data to the transfer buffer and returns the header size. As the only known 1413 * UVC output device transfers a whole frame in a single payload, the EOF bit 1414 * is always set in the header. 1415 * 1416 * uvc_video_encode_data is called for every URB and copies the data from the 1417 * video buffer to the transfer buffer. 1418 */ 1419 static int uvc_video_encode_header(struct uvc_streaming *stream, 1420 struct uvc_buffer *buf, u8 *data, int len) 1421 { 1422 data[0] = 2; /* Header length */ 1423 data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF 1424 | (stream->last_fid & UVC_STREAM_FID); 1425 return 2; 1426 } 1427 1428 static int uvc_video_encode_data(struct uvc_streaming *stream, 1429 struct uvc_buffer *buf, u8 *data, int len) 1430 { 1431 struct uvc_video_queue *queue = &stream->queue; 1432 unsigned int nbytes; 1433 void *mem; 1434 1435 /* Copy video data to the URB buffer. */ 1436 mem = buf->mem + queue->buf_used; 1437 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used); 1438 nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size, 1439 nbytes); 1440 memcpy(data, mem, nbytes); 1441 1442 queue->buf_used += nbytes; 1443 1444 return nbytes; 1445 } 1446 1447 /* ------------------------------------------------------------------------ 1448 * Metadata 1449 */ 1450 1451 /* 1452 * Additionally to the payload headers we also want to provide the user with USB 1453 * Frame Numbers and system time values. The resulting buffer is thus composed 1454 * of blocks, containing a 64-bit timestamp in nanoseconds, a 16-bit USB Frame 1455 * Number, and a copy of the payload header. 1456 * 1457 * Ideally we want to capture all payload headers for each frame. However, their 1458 * number is unknown and unbound. We thus drop headers that contain no vendor 1459 * data and that either contain no SCR value or an SCR value identical to the 1460 * previous header. 1461 */ 1462 static void uvc_video_decode_meta(struct uvc_streaming *stream, 1463 struct uvc_buffer *meta_buf, 1464 const u8 *mem, unsigned int length) 1465 { 1466 struct uvc_meta_buf *meta; 1467 size_t len_std = 2; 1468 bool has_pts, has_scr; 1469 unsigned long flags; 1470 unsigned int sof; 1471 ktime_t time; 1472 const u8 *scr; 1473 1474 if (length <= 2 || !meta_buf || meta_buf->state != UVC_BUF_STATE_ACTIVE) 1475 return; 1476 1477 has_pts = mem[1] & UVC_STREAM_PTS; 1478 has_scr = mem[1] & UVC_STREAM_SCR; 1479 1480 if (has_pts) { 1481 len_std += 4; 1482 scr = mem + 6; 1483 } else { 1484 scr = mem + 2; 1485 } 1486 1487 if (has_scr) 1488 len_std += 6; 1489 1490 if (stream->meta.format == V4L2_META_FMT_UVC) 1491 length = len_std; 1492 1493 if (length == len_std && (!has_scr || 1494 !memcmp(scr, stream->clock.last_scr, 6))) 1495 return; 1496 1497 if (meta_buf->length - meta_buf->bytesused < 1498 length + sizeof(meta->ns) + sizeof(meta->sof)) { 1499 meta_buf->error = 1; 1500 return; 1501 } 1502 1503 meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused); 1504 local_irq_save(flags); 1505 time = uvc_video_get_time(); 1506 sof = usb_get_current_frame_number(stream->dev->udev); 1507 local_irq_restore(flags); 1508 put_unaligned(ktime_to_ns(time), &meta->ns); 1509 put_unaligned(sof, &meta->sof); 1510 1511 if (has_scr) 1512 memcpy(stream->clock.last_scr, scr, 6); 1513 1514 meta->length = mem[0]; 1515 meta->flags = mem[1]; 1516 memcpy(meta->buf, &mem[2], length - 2); 1517 meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof); 1518 1519 uvc_dbg(stream->dev, FRAME, 1520 "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n", 1521 __func__, ktime_to_ns(time), meta->sof, meta->length, 1522 meta->flags, 1523 has_pts ? *(u32 *)meta->buf : 0, 1524 has_scr ? *(u32 *)scr : 0, 1525 has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0); 1526 } 1527 1528 /* ------------------------------------------------------------------------ 1529 * URB handling 1530 */ 1531 1532 /* 1533 * Set error flag for incomplete buffer. 1534 */ 1535 static void uvc_video_validate_buffer(const struct uvc_streaming *stream, 1536 struct uvc_buffer *buf) 1537 { 1538 if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused && 1539 !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED)) 1540 buf->error = 1; 1541 } 1542 1543 /* 1544 * Completion handler for video URBs. 1545 */ 1546 1547 static void uvc_video_next_buffers(struct uvc_streaming *stream, 1548 struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf) 1549 { 1550 uvc_video_validate_buffer(stream, *video_buf); 1551 1552 if (*meta_buf) { 1553 struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf; 1554 const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf; 1555 1556 vb2_meta->sequence = vb2_video->sequence; 1557 vb2_meta->field = vb2_video->field; 1558 vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp; 1559 1560 (*meta_buf)->state = UVC_BUF_STATE_READY; 1561 if (!(*meta_buf)->error) 1562 (*meta_buf)->error = (*video_buf)->error; 1563 *meta_buf = uvc_queue_next_buffer(&stream->meta.queue, 1564 *meta_buf); 1565 } 1566 *video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf); 1567 } 1568 1569 static void uvc_video_decode_isoc(struct uvc_urb *uvc_urb, 1570 struct uvc_buffer *buf, struct uvc_buffer *meta_buf) 1571 { 1572 struct urb *urb = uvc_urb->urb; 1573 struct uvc_streaming *stream = uvc_urb->stream; 1574 u8 *mem; 1575 int ret, i; 1576 1577 for (i = 0; i < urb->number_of_packets; ++i) { 1578 if (urb->iso_frame_desc[i].status < 0) { 1579 uvc_dbg(stream->dev, FRAME, 1580 "USB isochronous frame lost (%d)\n", 1581 urb->iso_frame_desc[i].status); 1582 /* Mark the buffer as faulty. */ 1583 if (buf != NULL) 1584 buf->error = 1; 1585 continue; 1586 } 1587 1588 /* Decode the payload header. */ 1589 mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset; 1590 do { 1591 ret = uvc_video_decode_start(stream, buf, meta_buf, mem, 1592 urb->iso_frame_desc[i].actual_length); 1593 if (ret == -EAGAIN) 1594 uvc_video_next_buffers(stream, &buf, &meta_buf); 1595 } while (ret == -EAGAIN); 1596 1597 if (ret < 0) 1598 continue; 1599 1600 uvc_video_decode_meta(stream, meta_buf, mem, ret); 1601 1602 /* Decode the payload data. */ 1603 uvc_video_decode_data(uvc_urb, buf, mem + ret, 1604 urb->iso_frame_desc[i].actual_length - ret); 1605 1606 /* Process the header again. */ 1607 uvc_video_decode_end(stream, buf, mem, 1608 urb->iso_frame_desc[i].actual_length); 1609 1610 if (buf->state == UVC_BUF_STATE_READY) 1611 uvc_video_next_buffers(stream, &buf, &meta_buf); 1612 } 1613 } 1614 1615 static void uvc_video_decode_bulk(struct uvc_urb *uvc_urb, 1616 struct uvc_buffer *buf, struct uvc_buffer *meta_buf) 1617 { 1618 struct urb *urb = uvc_urb->urb; 1619 struct uvc_streaming *stream = uvc_urb->stream; 1620 u8 *mem; 1621 int len, ret; 1622 1623 /* 1624 * Ignore ZLPs if they're not part of a frame, otherwise process them 1625 * to trigger the end of payload detection. 1626 */ 1627 if (urb->actual_length == 0 && stream->bulk.header_size == 0) 1628 return; 1629 1630 mem = urb->transfer_buffer; 1631 len = urb->actual_length; 1632 stream->bulk.payload_size += len; 1633 1634 /* 1635 * If the URB is the first of its payload, decode and save the 1636 * header. 1637 */ 1638 if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) { 1639 do { 1640 ret = uvc_video_decode_start(stream, buf, meta_buf, mem, 1641 len); 1642 if (ret == -EAGAIN) 1643 uvc_video_next_buffers(stream, &buf, &meta_buf); 1644 } while (ret == -EAGAIN); 1645 1646 /* If an error occurred skip the rest of the payload. */ 1647 if (ret < 0 || buf == NULL) { 1648 stream->bulk.skip_payload = 1; 1649 } else { 1650 memcpy(stream->bulk.header, mem, ret); 1651 stream->bulk.header_size = ret; 1652 1653 uvc_video_decode_meta(stream, meta_buf, mem, ret); 1654 1655 mem += ret; 1656 len -= ret; 1657 } 1658 } 1659 1660 /* 1661 * The buffer queue might have been cancelled while a bulk transfer 1662 * was in progress, so we can reach here with buf equal to NULL. Make 1663 * sure buf is never dereferenced if NULL. 1664 */ 1665 1666 /* Prepare video data for processing. */ 1667 if (!stream->bulk.skip_payload && buf != NULL) 1668 uvc_video_decode_data(uvc_urb, buf, mem, len); 1669 1670 /* 1671 * Detect the payload end by a URB smaller than the maximum size (or 1672 * a payload size equal to the maximum) and process the header again. 1673 */ 1674 if (urb->actual_length < urb->transfer_buffer_length || 1675 stream->bulk.payload_size >= stream->bulk.max_payload_size) { 1676 if (!stream->bulk.skip_payload && buf != NULL) { 1677 uvc_video_decode_end(stream, buf, stream->bulk.header, 1678 stream->bulk.payload_size); 1679 if (buf->state == UVC_BUF_STATE_READY) 1680 uvc_video_next_buffers(stream, &buf, &meta_buf); 1681 } 1682 1683 stream->bulk.header_size = 0; 1684 stream->bulk.skip_payload = 0; 1685 stream->bulk.payload_size = 0; 1686 } 1687 } 1688 1689 static void uvc_video_encode_bulk(struct uvc_urb *uvc_urb, 1690 struct uvc_buffer *buf, struct uvc_buffer *meta_buf) 1691 { 1692 struct urb *urb = uvc_urb->urb; 1693 struct uvc_streaming *stream = uvc_urb->stream; 1694 1695 u8 *mem = urb->transfer_buffer; 1696 int len = stream->urb_size, ret; 1697 1698 if (buf == NULL) { 1699 urb->transfer_buffer_length = 0; 1700 return; 1701 } 1702 1703 /* If the URB is the first of its payload, add the header. */ 1704 if (stream->bulk.header_size == 0) { 1705 ret = uvc_video_encode_header(stream, buf, mem, len); 1706 stream->bulk.header_size = ret; 1707 stream->bulk.payload_size += ret; 1708 mem += ret; 1709 len -= ret; 1710 } 1711 1712 /* Process video data. */ 1713 ret = uvc_video_encode_data(stream, buf, mem, len); 1714 1715 stream->bulk.payload_size += ret; 1716 len -= ret; 1717 1718 if (buf->bytesused == stream->queue.buf_used || 1719 stream->bulk.payload_size == stream->bulk.max_payload_size) { 1720 if (buf->bytesused == stream->queue.buf_used) { 1721 stream->queue.buf_used = 0; 1722 buf->state = UVC_BUF_STATE_READY; 1723 buf->buf.sequence = ++stream->sequence; 1724 uvc_queue_next_buffer(&stream->queue, buf); 1725 stream->last_fid ^= UVC_STREAM_FID; 1726 } 1727 1728 stream->bulk.header_size = 0; 1729 stream->bulk.payload_size = 0; 1730 } 1731 1732 urb->transfer_buffer_length = stream->urb_size - len; 1733 } 1734 1735 static void uvc_video_complete(struct urb *urb) 1736 { 1737 struct uvc_urb *uvc_urb = urb->context; 1738 struct uvc_streaming *stream = uvc_urb->stream; 1739 struct uvc_video_queue *queue = &stream->queue; 1740 struct uvc_video_queue *qmeta = &stream->meta.queue; 1741 struct vb2_queue *vb2_qmeta = stream->meta.queue.vdev.queue; 1742 struct uvc_buffer *buf = NULL; 1743 struct uvc_buffer *buf_meta = NULL; 1744 int ret; 1745 1746 switch (urb->status) { 1747 case 0: 1748 break; 1749 1750 default: 1751 dev_warn(&stream->intf->dev, 1752 "Non-zero status (%d) in video completion handler.\n", 1753 urb->status); 1754 fallthrough; 1755 case -ENOENT: /* usb_poison_urb() called. */ 1756 if (stream->frozen) 1757 return; 1758 fallthrough; 1759 case -ECONNRESET: /* usb_unlink_urb() called. */ 1760 case -ESHUTDOWN: /* The endpoint is being disabled. */ 1761 uvc_queue_cancel(queue, urb->status == -ESHUTDOWN); 1762 if (vb2_qmeta) 1763 uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN); 1764 return; 1765 } 1766 1767 buf = uvc_queue_get_current_buffer(queue); 1768 1769 if (vb2_qmeta) 1770 buf_meta = uvc_queue_get_current_buffer(qmeta); 1771 1772 /* Re-initialise the URB async work. */ 1773 uvc_urb->async_operations = 0; 1774 1775 /* 1776 * Process the URB headers, and optionally queue expensive memcpy tasks 1777 * to be deferred to a work queue. 1778 */ 1779 stream->decode(uvc_urb, buf, buf_meta); 1780 1781 /* If no async work is needed, resubmit the URB immediately. */ 1782 if (!uvc_urb->async_operations) { 1783 ret = usb_submit_urb(uvc_urb->urb, GFP_ATOMIC); 1784 if (ret < 0) 1785 dev_err(&stream->intf->dev, 1786 "Failed to resubmit video URB (%d).\n", ret); 1787 return; 1788 } 1789 1790 queue_work(stream->async_wq, &uvc_urb->work); 1791 } 1792 1793 /* 1794 * Free transfer buffers. 1795 */ 1796 static void uvc_free_urb_buffers(struct uvc_streaming *stream, 1797 unsigned int size) 1798 { 1799 struct usb_device *udev = stream->dev->udev; 1800 struct uvc_urb *uvc_urb; 1801 1802 for_each_uvc_urb(uvc_urb, stream) { 1803 if (!uvc_urb->buffer) 1804 continue; 1805 1806 usb_free_noncoherent(udev, size, uvc_urb->buffer, 1807 uvc_stream_dir(stream), uvc_urb->sgt); 1808 uvc_urb->buffer = NULL; 1809 uvc_urb->sgt = NULL; 1810 } 1811 1812 stream->urb_size = 0; 1813 } 1814 1815 static bool uvc_alloc_urb_buffer(struct uvc_streaming *stream, 1816 struct uvc_urb *uvc_urb, unsigned int size, 1817 gfp_t gfp_flags) 1818 { 1819 struct usb_device *udev = stream->dev->udev; 1820 1821 uvc_urb->buffer = usb_alloc_noncoherent(udev, size, gfp_flags, 1822 &uvc_urb->dma, 1823 uvc_stream_dir(stream), 1824 &uvc_urb->sgt); 1825 return !!uvc_urb->buffer; 1826 } 1827 1828 /* 1829 * Allocate transfer buffers. This function can be called with buffers 1830 * already allocated when resuming from suspend, in which case it will 1831 * return without touching the buffers. 1832 * 1833 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the 1834 * system is too low on memory try successively smaller numbers of packets 1835 * until allocation succeeds. 1836 * 1837 * Return the number of allocated packets on success or 0 when out of memory. 1838 */ 1839 static int uvc_alloc_urb_buffers(struct uvc_streaming *stream, 1840 unsigned int size, unsigned int psize, gfp_t gfp_flags) 1841 { 1842 unsigned int npackets; 1843 unsigned int i; 1844 1845 /* Buffers are already allocated, bail out. */ 1846 if (stream->urb_size) 1847 return stream->urb_size / psize; 1848 1849 /* 1850 * Compute the number of packets. Bulk endpoints might transfer UVC 1851 * payloads across multiple URBs. 1852 */ 1853 npackets = DIV_ROUND_UP(size, psize); 1854 if (npackets > UVC_MAX_PACKETS) 1855 npackets = UVC_MAX_PACKETS; 1856 1857 /* Retry allocations until one succeed. */ 1858 for (; npackets > 0; npackets /= 2) { 1859 unsigned int urb_size = psize * npackets; 1860 1861 for (i = 0; i < UVC_URBS; ++i) { 1862 struct uvc_urb *uvc_urb = &stream->uvc_urb[i]; 1863 1864 if (!uvc_alloc_urb_buffer(stream, uvc_urb, urb_size, 1865 gfp_flags)) { 1866 uvc_free_urb_buffers(stream, urb_size); 1867 break; 1868 } 1869 1870 uvc_urb->stream = stream; 1871 } 1872 1873 if (i == UVC_URBS) { 1874 uvc_dbg(stream->dev, VIDEO, 1875 "Allocated %u URB buffers of %ux%u bytes each\n", 1876 UVC_URBS, npackets, psize); 1877 stream->urb_size = urb_size; 1878 return npackets; 1879 } 1880 } 1881 1882 uvc_dbg(stream->dev, VIDEO, 1883 "Failed to allocate URB buffers (%u bytes per packet)\n", 1884 psize); 1885 return 0; 1886 } 1887 1888 /* 1889 * Uninitialize isochronous/bulk URBs and free transfer buffers. 1890 */ 1891 static void uvc_video_stop_transfer(struct uvc_streaming *stream, 1892 int free_buffers) 1893 { 1894 struct uvc_urb *uvc_urb; 1895 1896 uvc_video_stats_stop(stream); 1897 1898 /* 1899 * We must poison the URBs rather than kill them to ensure that even 1900 * after the completion handler returns, any asynchronous workqueues 1901 * will be prevented from resubmitting the URBs. 1902 */ 1903 for_each_uvc_urb(uvc_urb, stream) 1904 usb_poison_urb(uvc_urb->urb); 1905 1906 flush_workqueue(stream->async_wq); 1907 1908 for_each_uvc_urb(uvc_urb, stream) { 1909 usb_free_urb(uvc_urb->urb); 1910 uvc_urb->urb = NULL; 1911 } 1912 1913 if (free_buffers) 1914 uvc_free_urb_buffers(stream, stream->urb_size); 1915 } 1916 1917 /* 1918 * Initialize isochronous URBs and allocate transfer buffers. The packet size 1919 * is given by the endpoint. 1920 */ 1921 static int uvc_init_video_isoc(struct uvc_streaming *stream, 1922 struct usb_host_endpoint *ep, gfp_t gfp_flags) 1923 { 1924 struct urb *urb; 1925 struct uvc_urb *uvc_urb; 1926 unsigned int npackets, i; 1927 u32 psize; 1928 u32 size; 1929 1930 psize = usb_endpoint_max_periodic_payload(stream->dev->udev, ep); 1931 size = stream->ctrl.dwMaxVideoFrameSize; 1932 1933 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags); 1934 if (npackets == 0) 1935 return -ENOMEM; 1936 1937 size = npackets * psize; 1938 1939 for_each_uvc_urb(uvc_urb, stream) { 1940 urb = usb_alloc_urb(npackets, gfp_flags); 1941 if (urb == NULL) { 1942 uvc_video_stop_transfer(stream, 1); 1943 return -ENOMEM; 1944 } 1945 1946 urb->dev = stream->dev->udev; 1947 urb->context = uvc_urb; 1948 urb->pipe = usb_rcvisocpipe(stream->dev->udev, 1949 ep->desc.bEndpointAddress); 1950 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP; 1951 urb->transfer_dma = uvc_urb->dma; 1952 urb->interval = ep->desc.bInterval; 1953 urb->transfer_buffer = uvc_urb->buffer; 1954 urb->complete = uvc_video_complete; 1955 urb->number_of_packets = npackets; 1956 urb->transfer_buffer_length = size; 1957 urb->sgt = uvc_urb->sgt; 1958 1959 for (i = 0; i < npackets; ++i) { 1960 urb->iso_frame_desc[i].offset = i * psize; 1961 urb->iso_frame_desc[i].length = psize; 1962 } 1963 1964 uvc_urb->urb = urb; 1965 } 1966 1967 return 0; 1968 } 1969 1970 /* 1971 * Initialize bulk URBs and allocate transfer buffers. The packet size is 1972 * given by the endpoint. 1973 */ 1974 static int uvc_init_video_bulk(struct uvc_streaming *stream, 1975 struct usb_host_endpoint *ep, gfp_t gfp_flags) 1976 { 1977 struct urb *urb; 1978 struct uvc_urb *uvc_urb; 1979 unsigned int npackets, pipe; 1980 u16 psize; 1981 u32 size; 1982 1983 psize = usb_endpoint_maxp(&ep->desc); 1984 size = stream->ctrl.dwMaxPayloadTransferSize; 1985 stream->bulk.max_payload_size = size; 1986 1987 npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags); 1988 if (npackets == 0) 1989 return -ENOMEM; 1990 1991 size = npackets * psize; 1992 1993 if (usb_endpoint_dir_in(&ep->desc)) 1994 pipe = usb_rcvbulkpipe(stream->dev->udev, 1995 ep->desc.bEndpointAddress); 1996 else 1997 pipe = usb_sndbulkpipe(stream->dev->udev, 1998 ep->desc.bEndpointAddress); 1999 2000 if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) 2001 size = 0; 2002 2003 for_each_uvc_urb(uvc_urb, stream) { 2004 urb = usb_alloc_urb(0, gfp_flags); 2005 if (urb == NULL) { 2006 uvc_video_stop_transfer(stream, 1); 2007 return -ENOMEM; 2008 } 2009 2010 usb_fill_bulk_urb(urb, stream->dev->udev, pipe, uvc_urb->buffer, 2011 size, uvc_video_complete, uvc_urb); 2012 urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP; 2013 urb->transfer_dma = uvc_urb->dma; 2014 urb->sgt = uvc_urb->sgt; 2015 2016 uvc_urb->urb = urb; 2017 } 2018 2019 return 0; 2020 } 2021 2022 /* 2023 * Initialize isochronous/bulk URBs and allocate transfer buffers. 2024 */ 2025 static int uvc_video_start_transfer(struct uvc_streaming *stream, 2026 gfp_t gfp_flags) 2027 { 2028 struct usb_interface *intf = stream->intf; 2029 struct usb_host_endpoint *ep; 2030 struct uvc_urb *uvc_urb; 2031 unsigned int i; 2032 int ret; 2033 2034 stream->sequence = -1; 2035 stream->last_fid = -1; 2036 stream->bulk.header_size = 0; 2037 stream->bulk.skip_payload = 0; 2038 stream->bulk.payload_size = 0; 2039 2040 uvc_video_stats_start(stream); 2041 2042 if (intf->num_altsetting > 1) { 2043 struct usb_host_endpoint *best_ep = NULL; 2044 unsigned int best_psize = UINT_MAX; 2045 unsigned int bandwidth; 2046 unsigned int altsetting; 2047 int intfnum = stream->intfnum; 2048 2049 /* Isochronous endpoint, select the alternate setting. */ 2050 bandwidth = stream->ctrl.dwMaxPayloadTransferSize; 2051 2052 if (bandwidth == 0) { 2053 uvc_dbg(stream->dev, VIDEO, 2054 "Device requested null bandwidth, defaulting to lowest\n"); 2055 bandwidth = 1; 2056 } else { 2057 uvc_dbg(stream->dev, VIDEO, 2058 "Device requested %u B/frame bandwidth\n", 2059 bandwidth); 2060 } 2061 2062 for (i = 0; i < intf->num_altsetting; ++i) { 2063 struct usb_host_interface *alts; 2064 unsigned int psize; 2065 2066 alts = &intf->altsetting[i]; 2067 ep = uvc_find_endpoint(alts, 2068 stream->header.bEndpointAddress); 2069 if (ep == NULL) 2070 continue; 2071 2072 /* Check if the bandwidth is high enough. */ 2073 psize = usb_endpoint_max_periodic_payload(stream->dev->udev, ep); 2074 if (psize >= bandwidth && psize < best_psize) { 2075 altsetting = alts->desc.bAlternateSetting; 2076 best_psize = psize; 2077 best_ep = ep; 2078 } 2079 } 2080 2081 if (best_ep == NULL) { 2082 uvc_dbg(stream->dev, VIDEO, 2083 "No fast enough alt setting for requested bandwidth\n"); 2084 return -EIO; 2085 } 2086 2087 uvc_dbg(stream->dev, VIDEO, 2088 "Selecting alternate setting %u (%u B/frame bandwidth)\n", 2089 altsetting, best_psize); 2090 2091 /* 2092 * Some devices, namely the Logitech C910 and B910, are unable 2093 * to recover from a USB autosuspend, unless the alternate 2094 * setting of the streaming interface is toggled. 2095 */ 2096 if (stream->dev->quirks & UVC_QUIRK_WAKE_AUTOSUSPEND) { 2097 usb_set_interface(stream->dev->udev, intfnum, 2098 altsetting); 2099 usb_set_interface(stream->dev->udev, intfnum, 0); 2100 } 2101 2102 ret = usb_set_interface(stream->dev->udev, intfnum, altsetting); 2103 if (ret < 0) 2104 return ret; 2105 2106 ret = uvc_init_video_isoc(stream, best_ep, gfp_flags); 2107 } else { 2108 /* Bulk endpoint, proceed to URB initialization. */ 2109 ep = uvc_find_endpoint(&intf->altsetting[0], 2110 stream->header.bEndpointAddress); 2111 if (ep == NULL) 2112 return -EIO; 2113 2114 /* Reject broken descriptors. */ 2115 if (usb_endpoint_maxp(&ep->desc) == 0) 2116 return -EIO; 2117 2118 ret = uvc_init_video_bulk(stream, ep, gfp_flags); 2119 } 2120 2121 if (ret < 0) 2122 return ret; 2123 2124 /* Submit the URBs. */ 2125 for_each_uvc_urb(uvc_urb, stream) { 2126 ret = usb_submit_urb(uvc_urb->urb, gfp_flags); 2127 if (ret < 0) { 2128 dev_err(&stream->intf->dev, 2129 "Failed to submit URB %u (%d).\n", 2130 uvc_urb_index(uvc_urb), ret); 2131 uvc_video_stop_transfer(stream, 1); 2132 return ret; 2133 } 2134 } 2135 2136 /* 2137 * The Logitech C920 temporarily forgets that it should not be adjusting 2138 * Exposure Absolute during init so restore controls to stored values. 2139 */ 2140 if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT) 2141 uvc_ctrl_restore_values(stream->dev); 2142 2143 return 0; 2144 } 2145 2146 /* -------------------------------------------------------------------------- 2147 * Suspend/resume 2148 */ 2149 2150 /* 2151 * Stop streaming without disabling the video queue. 2152 * 2153 * To let userspace applications resume without trouble, we must not touch the 2154 * video buffers in any way. We mark the device as frozen to make sure the URB 2155 * completion handler won't try to cancel the queue when we kill the URBs. 2156 */ 2157 int uvc_video_suspend(struct uvc_streaming *stream) 2158 { 2159 if (!uvc_queue_streaming(&stream->queue)) 2160 return 0; 2161 2162 stream->frozen = 1; 2163 uvc_video_stop_transfer(stream, 0); 2164 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2165 return 0; 2166 } 2167 2168 /* 2169 * Reconfigure the video interface and restart streaming if it was enabled 2170 * before suspend. 2171 * 2172 * If an error occurs, disable the video queue. This will wake all pending 2173 * buffers, making sure userspace applications are notified of the problem 2174 * instead of waiting forever. 2175 */ 2176 int uvc_video_resume(struct uvc_streaming *stream, int reset) 2177 { 2178 int ret; 2179 2180 /* 2181 * If the bus has been reset on resume, set the alternate setting to 0. 2182 * This should be the default value, but some devices crash or otherwise 2183 * misbehave if they don't receive a SET_INTERFACE request before any 2184 * other video control request. 2185 */ 2186 if (reset) 2187 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2188 2189 stream->frozen = 0; 2190 2191 uvc_video_clock_reset(&stream->clock); 2192 2193 if (!uvc_queue_streaming(&stream->queue)) 2194 return 0; 2195 2196 ret = uvc_commit_video(stream, &stream->ctrl); 2197 if (ret < 0) 2198 return ret; 2199 2200 return uvc_video_start_transfer(stream, GFP_NOIO); 2201 } 2202 2203 /* ------------------------------------------------------------------------ 2204 * Video device 2205 */ 2206 2207 /* 2208 * Initialize the UVC video device by switching to alternate setting 0 and 2209 * retrieve the default format. 2210 * 2211 * Some cameras (namely the Fuji Finepix) set the format and frame 2212 * indexes to zero. The UVC standard doesn't clearly make this a spec 2213 * violation, so try to silently fix the values if possible. 2214 * 2215 * This function is called before registering the device with V4L. 2216 */ 2217 int uvc_video_init(struct uvc_streaming *stream) 2218 { 2219 struct uvc_streaming_control *probe = &stream->ctrl; 2220 const struct uvc_format *format = NULL; 2221 const struct uvc_frame *frame = NULL; 2222 struct uvc_urb *uvc_urb; 2223 unsigned int i; 2224 int ret; 2225 2226 if (stream->nformats == 0) { 2227 dev_info(&stream->intf->dev, 2228 "No supported video formats found.\n"); 2229 return -EINVAL; 2230 } 2231 2232 atomic_set(&stream->active, 0); 2233 2234 /* 2235 * Alternate setting 0 should be the default, yet the XBox Live Vision 2236 * Cam (and possibly other devices) crash or otherwise misbehave if 2237 * they don't receive a SET_INTERFACE request before any other video 2238 * control request. 2239 */ 2240 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2241 2242 /* 2243 * Set the streaming probe control with default streaming parameters 2244 * retrieved from the device. Webcams that don't support GET_DEF 2245 * requests on the probe control will just keep their current streaming 2246 * parameters. 2247 */ 2248 if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0) 2249 uvc_set_video_ctrl(stream, probe, 1); 2250 2251 /* 2252 * Initialize the streaming parameters with the probe control current 2253 * value. This makes sure SET_CUR requests on the streaming commit 2254 * control will always use values retrieved from a successful GET_CUR 2255 * request on the probe control, as required by the UVC specification. 2256 */ 2257 ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR); 2258 2259 /* 2260 * Elgato Cam Link 4k can be in a stalled state if the resolution of 2261 * the external source has changed while the firmware initializes. 2262 * Once in this state, the device is useless until it receives a 2263 * USB reset. It has even been observed that the stalled state will 2264 * continue even after unplugging the device. 2265 */ 2266 if (ret == -EPROTO && 2267 usb_match_one_id(stream->dev->intf, &elgato_cam_link_4k)) { 2268 dev_err(&stream->intf->dev, "Elgato Cam Link 4K firmware crash detected\n"); 2269 dev_err(&stream->intf->dev, "Resetting the device, unplug and replug to recover\n"); 2270 usb_reset_device(stream->dev->udev); 2271 } 2272 2273 if (ret < 0) 2274 return ret; 2275 2276 /* 2277 * Check if the default format descriptor exists. Use the first 2278 * available format otherwise. 2279 */ 2280 for (i = stream->nformats; i > 0; --i) { 2281 format = &stream->formats[i-1]; 2282 if (format->index == probe->bFormatIndex) 2283 break; 2284 } 2285 2286 if (format->nframes == 0) { 2287 dev_info(&stream->intf->dev, 2288 "No frame descriptor found for the default format.\n"); 2289 return -EINVAL; 2290 } 2291 2292 /* 2293 * Zero bFrameIndex might be correct. Stream-based formats (including 2294 * MPEG-2 TS and DV) do not support frames but have a dummy frame 2295 * descriptor with bFrameIndex set to zero. If the default frame 2296 * descriptor is not found, use the first available frame. 2297 */ 2298 for (i = format->nframes; i > 0; --i) { 2299 frame = &format->frames[i-1]; 2300 if (frame->bFrameIndex == probe->bFrameIndex) 2301 break; 2302 } 2303 2304 probe->bFormatIndex = format->index; 2305 probe->bFrameIndex = frame->bFrameIndex; 2306 2307 stream->def_format = format; 2308 stream->cur_format = format; 2309 stream->cur_frame = frame; 2310 2311 /* Select the video decoding function */ 2312 if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { 2313 if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT) 2314 stream->decode = uvc_video_decode_isight; 2315 else if (stream->intf->num_altsetting > 1) 2316 stream->decode = uvc_video_decode_isoc; 2317 else 2318 stream->decode = uvc_video_decode_bulk; 2319 } else { 2320 if (stream->intf->num_altsetting == 1) 2321 stream->decode = uvc_video_encode_bulk; 2322 else { 2323 dev_info(&stream->intf->dev, 2324 "Isochronous endpoints are not supported for video output devices.\n"); 2325 return -EINVAL; 2326 } 2327 } 2328 2329 /* Prepare asynchronous work items. */ 2330 for_each_uvc_urb(uvc_urb, stream) 2331 INIT_WORK(&uvc_urb->work, uvc_video_copy_data_work); 2332 2333 return 0; 2334 } 2335 2336 int uvc_video_start_streaming(struct uvc_streaming *stream) 2337 { 2338 int ret; 2339 2340 ret = uvc_video_clock_init(&stream->clock); 2341 if (ret < 0) 2342 return ret; 2343 2344 /* Commit the streaming parameters. */ 2345 ret = uvc_commit_video(stream, &stream->ctrl); 2346 if (ret < 0) 2347 goto error_commit; 2348 2349 ret = uvc_video_start_transfer(stream, GFP_KERNEL); 2350 if (ret < 0) 2351 goto error_video; 2352 2353 return 0; 2354 2355 error_video: 2356 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2357 error_commit: 2358 uvc_video_clock_cleanup(&stream->clock); 2359 2360 return ret; 2361 } 2362 2363 void uvc_video_stop_streaming(struct uvc_streaming *stream) 2364 { 2365 uvc_video_stop_transfer(stream, 1); 2366 2367 if (stream->intf->num_altsetting > 1) { 2368 usb_set_interface(stream->dev->udev, stream->intfnum, 0); 2369 } else { 2370 /* 2371 * UVC doesn't specify how to inform a bulk-based device 2372 * when the video stream is stopped. Windows sends a 2373 * CLEAR_FEATURE(HALT) request to the video streaming 2374 * bulk endpoint, mimic the same behaviour. 2375 */ 2376 unsigned int epnum = stream->header.bEndpointAddress 2377 & USB_ENDPOINT_NUMBER_MASK; 2378 unsigned int dir = stream->header.bEndpointAddress 2379 & USB_ENDPOINT_DIR_MASK; 2380 unsigned int pipe; 2381 2382 pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir; 2383 usb_clear_halt(stream->dev->udev, pipe); 2384 } 2385 2386 uvc_video_clock_cleanup(&stream->clock); 2387 } 2388