uvc_video.c 57.7 KB
Newer Older
1 2 3
/*
 *      uvc_video.c  --  USB Video Class driver - Video handling
 *
4 5
 *      Copyright (C) 2005-2010
 *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 7 8 9 10 11 12 13 14 15 16
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 */

#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
17
#include <linux/slab.h>
18 19 20 21
#include <linux/usb.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
A
Arun Sharma 已提交
22
#include <linux/atomic.h>
23 24 25 26 27 28 29 30 31 32
#include <asm/unaligned.h>

#include <media/v4l2-common.h>

#include "uvcvideo.h"

/* ------------------------------------------------------------------------
 * UVC Controls
 */

33 34
static int __uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
			u8 intfnum, u8 cs, void *data, u16 size,
35 36
			int timeout)
{
37
	u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
38 39 40 41 42 43
	unsigned int pipe;

	pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
			      : usb_sndctrlpipe(dev->udev, 0);
	type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;

44
	return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
45
			unit << 8 | intfnum, data, size, timeout);
46 47
}

48
static const char *uvc_query_name(u8 query)
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
{
	switch (query) {
	case UVC_SET_CUR:
		return "SET_CUR";
	case UVC_GET_CUR:
		return "GET_CUR";
	case UVC_GET_MIN:
		return "GET_MIN";
	case UVC_GET_MAX:
		return "GET_MAX";
	case UVC_GET_RES:
		return "GET_RES";
	case UVC_GET_LEN:
		return "GET_LEN";
	case UVC_GET_INFO:
		return "GET_INFO";
	case UVC_GET_DEF:
		return "GET_DEF";
	default:
		return "<invalid>";
	}
}

72 73
int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
			u8 intfnum, u8 cs, void *data, u16 size)
74 75
{
	int ret;
76

77 78
	ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
				UVC_CTRL_CONTROL_TIMEOUT);
79
	if (ret != size) {
80 81 82
		uvc_printk(KERN_ERR, "Failed to query (%s) UVC control %u on "
			"unit %u: %d (exp. %u).\n", uvc_query_name(query), cs,
			unit, ret, size);
83 84 85 86 87 88
		return -EIO;
	}

	return 0;
}

89
static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
90 91
	struct uvc_streaming_control *ctrl)
{
92
	struct uvc_format *format = NULL;
93 94
	struct uvc_frame *frame = NULL;
	unsigned int i;
95

96 97 98 99 100 101
	for (i = 0; i < stream->nformats; ++i) {
		if (stream->format[i].index == ctrl->bFormatIndex) {
			format = &stream->format[i];
			break;
		}
	}
102

103 104
	if (format == NULL)
		return;
105

106 107 108 109 110 111
	for (i = 0; i < format->nframes; ++i) {
		if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
			frame = &format->frame[i];
			break;
		}
	}
112

113 114
	if (frame == NULL)
		return;
115 116 117

	if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
	     (ctrl->dwMaxVideoFrameSize == 0 &&
118
	      stream->dev->uvc_version < 0x0110))
119 120
		ctrl->dwMaxVideoFrameSize =
			frame->dwMaxVideoFrameBufferSize;
121

122 123 124 125 126 127 128 129
	/* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
	 * compute the bandwidth on 16 bits and erroneously sign-extend it to
	 * 32 bits, resulting in a huge bandwidth value. Detect and fix that
	 * condition by setting the 16 MSBs to 0 when they're all equal to 1.
	 */
	if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
		ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;

130 131
	if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
	    stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
132
	    stream->intf->num_altsetting > 1) {
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
		u32 interval;
		u32 bandwidth;

		interval = (ctrl->dwFrameInterval > 100000)
			 ? ctrl->dwFrameInterval
			 : frame->dwFrameInterval[0];

		/* Compute a bandwidth estimation by multiplying the frame
		 * size by the number of video frames per second, divide the
		 * result by the number of USB frames (or micro-frames for
		 * high-speed devices) per second and add the UVC header size
		 * (assumed to be 12 bytes long).
		 */
		bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
		bandwidth *= 10000000 / interval + 1;
		bandwidth /= 1000;
149
		if (stream->dev->udev->speed == USB_SPEED_HIGH)
150 151 152
			bandwidth /= 8;
		bandwidth += 12;

153 154 155 156 157 158 159 160 161
		/* The bandwidth estimate is too low for many cameras. Don't use
		 * maximum packet sizes lower than 1024 bytes to try and work
		 * around the problem. According to measurements done on two
		 * different camera models, the value is high enough to get most
		 * resolutions working while not preventing two simultaneous
		 * VGA streams at 15 fps.
		 */
		bandwidth = max_t(u32, bandwidth, 1024);

162 163
		ctrl->dwMaxPayloadTransferSize = bandwidth;
	}
164 165
}

166
static int uvc_get_video_ctrl(struct uvc_streaming *stream,
167
	struct uvc_streaming_control *ctrl, int probe, u8 query)
168
{
169 170
	u8 *data;
	u16 size;
171 172
	int ret;

173
	size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
174 175 176 177
	if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
			query == UVC_GET_DEF)
		return -EIO;

178 179 180 181
	data = kmalloc(size, GFP_KERNEL);
	if (data == NULL)
		return -ENOMEM;

182
	ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
183
		probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
184
		size, uvc_timeout_param);
185

186
	if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
187 188 189 190
		/* Some cameras, mostly based on Bison Electronics chipsets,
		 * answer a GET_MIN or GET_MAX request with the wCompQuality
		 * field only.
		 */
191
		uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
192 193
			"compliance - GET_MIN/MAX(PROBE) incorrectly "
			"supported. Enabling workaround.\n");
194
		memset(ctrl, 0, sizeof *ctrl);
195 196
		ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
		ret = 0;
197
		goto out;
198
	} else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
199 200 201 202
		/* Many cameras don't support the GET_DEF request on their
		 * video probe control. Warn once and return, the caller will
		 * fall back to GET_CUR.
		 */
203
		uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
204 205 206 207 208 209 210 211 212 213 214
			"compliance - GET_DEF(PROBE) not supported. "
			"Enabling workaround.\n");
		ret = -EIO;
		goto out;
	} else if (ret != size) {
		uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
			"%d (exp. %u).\n", query, probe ? "probe" : "commit",
			ret, size);
		ret = -EIO;
		goto out;
	}
215 216 217 218 219 220 221 222 223 224

	ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
	ctrl->bFormatIndex = data[2];
	ctrl->bFrameIndex = data[3];
	ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
	ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
	ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
	ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
	ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
	ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
225 226
	ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
	ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
227 228

	if (size == 34) {
229
		ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
230 231 232 233 234
		ctrl->bmFramingInfo = data[30];
		ctrl->bPreferedVersion = data[31];
		ctrl->bMinVersion = data[32];
		ctrl->bMaxVersion = data[33];
	} else {
235
		ctrl->dwClockFrequency = stream->dev->clock_frequency;
236 237 238 239 240 241
		ctrl->bmFramingInfo = 0;
		ctrl->bPreferedVersion = 0;
		ctrl->bMinVersion = 0;
		ctrl->bMaxVersion = 0;
	}

242 243 244
	/* Some broken devices return null or wrong dwMaxVideoFrameSize and
	 * dwMaxPayloadTransferSize fields. Try to get the value from the
	 * format and frame descriptors.
245
	 */
246
	uvc_fixup_video_ctrl(stream, ctrl);
247
	ret = 0;
248

249 250 251
out:
	kfree(data);
	return ret;
252 253
}

254
static int uvc_set_video_ctrl(struct uvc_streaming *stream,
255 256
	struct uvc_streaming_control *ctrl, int probe)
{
257 258
	u8 *data;
	u16 size;
259
	int ret;
260

261
	size = stream->dev->uvc_version >= 0x0110 ? 34 : 26;
262 263 264
	data = kzalloc(size, GFP_KERNEL);
	if (data == NULL)
		return -ENOMEM;
265 266 267 268 269 270 271 272 273 274

	*(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
	data[2] = ctrl->bFormatIndex;
	data[3] = ctrl->bFrameIndex;
	*(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
	*(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
	*(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
	*(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
	*(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
	*(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
275 276
	put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
	put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
277 278

	if (size == 34) {
279
		put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
280 281 282 283 284 285
		data[30] = ctrl->bmFramingInfo;
		data[31] = ctrl->bPreferedVersion;
		data[32] = ctrl->bMinVersion;
		data[33] = ctrl->bMaxVersion;
	}

286
	ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
287
		probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
288
		size, uvc_timeout_param);
289 290 291 292 293 294
	if (ret != size) {
		uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
			"%d (exp. %u).\n", probe ? "probe" : "commit",
			ret, size);
		ret = -EIO;
	}
295 296 297

	kfree(data);
	return ret;
298 299
}

300
int uvc_probe_video(struct uvc_streaming *stream,
301 302 303
	struct uvc_streaming_control *probe)
{
	struct uvc_streaming_control probe_min, probe_max;
304
	u16 bandwidth;
305 306 307 308 309 310 311 312 313 314
	unsigned int i;
	int ret;

	/* Perform probing. The device should adjust the requested values
	 * according to its capabilities. However, some devices, namely the
	 * first generation UVC Logitech webcams, don't implement the Video
	 * Probe control properly, and just return the needed bandwidth. For
	 * that reason, if the needed bandwidth exceeds the maximum available
	 * bandwidth, try to lower the quality.
	 */
315 316
	ret = uvc_set_video_ctrl(stream, probe, 1);
	if (ret < 0)
317 318 319
		goto done;

	/* Get the minimum and maximum values for compression settings. */
320 321
	if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
		ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
322 323
		if (ret < 0)
			goto done;
324
		ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
325 326 327 328 329 330 331
		if (ret < 0)
			goto done;

		probe->wCompQuality = probe_max.wCompQuality;
	}

	for (i = 0; i < 2; ++i) {
332
		ret = uvc_set_video_ctrl(stream, probe, 1);
333 334
		if (ret < 0)
			goto done;
335
		ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
336
		if (ret < 0)
337 338
			goto done;

339
		if (stream->intf->num_altsetting == 1)
340 341 342
			break;

		bandwidth = probe->dwMaxPayloadTransferSize;
343
		if (bandwidth <= stream->maxpsize)
344 345
			break;

346
		if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
			ret = -ENOSPC;
			goto done;
		}

		/* TODO: negotiate compression parameters */
		probe->wKeyFrameRate = probe_min.wKeyFrameRate;
		probe->wPFrameRate = probe_min.wPFrameRate;
		probe->wCompQuality = probe_max.wCompQuality;
		probe->wCompWindowSize = probe_min.wCompWindowSize;
	}

done:
	return ret;
}

362 363
static int uvc_commit_video(struct uvc_streaming *stream,
			    struct uvc_streaming_control *probe)
364
{
365
	return uvc_set_video_ctrl(stream, probe, 0);
366 367
}

368 369 370 371
/* -----------------------------------------------------------------------------
 * Clocks and timestamps
 */

372
static inline ktime_t uvc_video_get_time(void)
373 374
{
	if (uvc_clock_param == CLOCK_MONOTONIC)
375
		return ktime_get();
376
	else
377
		return ktime_get_real();
378 379
}

380 381
static void
uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
382
		       const u8 *data, int len)
383 384 385 386 387 388
{
	struct uvc_clock_sample *sample;
	unsigned int header_size;
	bool has_pts = false;
	bool has_scr = false;
	unsigned long flags;
389
	ktime_t time;
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
	u16 host_sof;
	u16 dev_sof;

	switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
	case UVC_STREAM_PTS | UVC_STREAM_SCR:
		header_size = 12;
		has_pts = true;
		has_scr = true;
		break;
	case UVC_STREAM_PTS:
		header_size = 6;
		has_pts = true;
		break;
	case UVC_STREAM_SCR:
		header_size = 8;
		has_scr = true;
		break;
	default:
		header_size = 2;
		break;
	}

	/* Check for invalid headers. */
	if (len < header_size)
		return;

	/* Extract the timestamps:
	 *
	 * - store the frame PTS in the buffer structure
	 * - if the SCR field is present, retrieve the host SOF counter and
	 *   kernel timestamps and store them with the SCR STC and SOF fields
	 *   in the ring buffer
	 */
	if (has_pts && buf != NULL)
		buf->pts = get_unaligned_le32(&data[2]);

	if (!has_scr)
		return;

	/* To limit the amount of data, drop SCRs with an SOF identical to the
	 * previous one.
	 */
	dev_sof = get_unaligned_le16(&data[header_size - 2]);
	if (dev_sof == stream->clock.last_sof)
		return;

	stream->clock.last_sof = dev_sof;

	host_sof = usb_get_current_frame_number(stream->dev->udev);
439
	time = uvc_video_get_time();
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

	/* The UVC specification allows device implementations that can't obtain
	 * the USB frame number to keep their own frame counters as long as they
	 * match the size and frequency of the frame number associated with USB
	 * SOF tokens. The SOF values sent by such devices differ from the USB
	 * SOF tokens by a fixed offset that needs to be estimated and accounted
	 * for to make timestamp recovery as accurate as possible.
	 *
	 * The offset is estimated the first time a device SOF value is received
	 * as the difference between the host and device SOF values. As the two
	 * SOF values can differ slightly due to transmission delays, consider
	 * that the offset is null if the difference is not higher than 10 ms
	 * (negative differences can not happen and are thus considered as an
	 * offset). The video commit control wDelay field should be used to
	 * compute a dynamic threshold instead of using a fixed 10 ms value, but
	 * devices don't report reliable wDelay values.
	 *
	 * See uvc_video_clock_host_sof() for an explanation regarding why only
	 * the 8 LSBs of the delta are kept.
	 */
	if (stream->clock.sof_offset == (u16)-1) {
		u16 delta_sof = (host_sof - dev_sof) & 255;
		if (delta_sof >= 10)
			stream->clock.sof_offset = delta_sof;
		else
			stream->clock.sof_offset = 0;
	}

	dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;

	spin_lock_irqsave(&stream->clock.lock, flags);

	sample = &stream->clock.samples[stream->clock.head];
	sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
	sample->dev_sof = dev_sof;
	sample->host_sof = host_sof;
476
	sample->host_time = time;
477 478 479 480 481 482 483 484 485 486

	/* Update the sliding window head and count. */
	stream->clock.head = (stream->clock.head + 1) % stream->clock.size;

	if (stream->clock.count < stream->clock.size)
		stream->clock.count++;

	spin_unlock_irqrestore(&stream->clock.lock, flags);
}

487
static void uvc_video_clock_reset(struct uvc_streaming *stream)
488 489 490 491 492 493 494
{
	struct uvc_clock *clock = &stream->clock;

	clock->head = 0;
	clock->count = 0;
	clock->last_sof = -1;
	clock->sof_offset = -1;
495 496 497 498 499 500 501 502
}

static int uvc_video_clock_init(struct uvc_streaming *stream)
{
	struct uvc_clock *clock = &stream->clock;

	spin_lock_init(&clock->lock);
	clock->size = 32;
503 504 505 506 507 508

	clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
				 GFP_KERNEL);
	if (clock->samples == NULL)
		return -ENOMEM;

509 510
	uvc_video_clock_reset(stream);

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	return 0;
}

static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
{
	kfree(stream->clock.samples);
	stream->clock.samples = NULL;
}

/*
 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
 *
 * Host SOF counters reported by usb_get_current_frame_number() usually don't
 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
 * controller and its configuration.
 *
 * We thus need to recover the SOF value corresponding to the host frame number.
 * As the device and host frame numbers are sampled in a short interval, the
 * difference between their values should be equal to a small delta plus an
 * integer multiple of 256 caused by the host frame number limited precision.
 *
 * To obtain the recovered host SOF value, compute the small delta by masking
 * the high bits of the host frame counter and device SOF difference and add it
 * to the device SOF value.
 */
static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
{
	/* The delta value can be negative. */
	s8 delta_sof;

	delta_sof = (sample->host_sof - sample->dev_sof) & 255;

	return (sample->dev_sof + delta_sof) & 2047;
}

/*
 * uvc_video_clock_update - Update the buffer timestamp
 *
 * This function converts the buffer PTS timestamp to the host clock domain by
 * going through the USB SOF clock domain and stores the result in the V4L2
 * buffer timestamp field.
 *
 * The relationship between the device clock and the host clock isn't known.
 * However, the device and the host share the common USB SOF clock which can be
 * used to recover that relationship.
 *
 * The relationship between the device clock and the USB SOF clock is considered
 * to be linear over the clock samples sliding window and is given by
 *
 * SOF = m * PTS + p
 *
 * Several methods to compute the slope (m) and intercept (p) can be used. As
 * the clock drift should be small compared to the sliding window size, we
 * assume that the line that goes through the points at both ends of the window
 * is a good approximation. Naming those points P1 and P2, we get
 *
 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
 *     + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
 *
 * or
 *
 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)   (1)
 *
575
 * to avoid losing precision in the division. Similarly, the host timestamp is
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
 * computed with
 *
 * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1)	     (2)
 *
 * SOF values are coded on 11 bits by USB. We extend their precision with 16
 * decimal bits, leading to a 11.16 coding.
 *
 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
 * be normalized using the nominal device clock frequency reported through the
 * UVC descriptors.
 *
 * Both the PTS/STC and SOF counters roll over, after a fixed but device
 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
 * sliding window size is smaller than the rollover period, differences computed
 * on unsigned integers will produce the correct result. However, the p term in
 * the linear relations will be miscomputed.
 *
 * To fix the issue, we subtract a constant from the PTS and STC values to bring
 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
 * the 32 bit range without any rollover.
 *
 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
 * computed by (1) will never be smaller than 0. This offset is then compensated
 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
 * SOF value at the end of the sliding window.
 *
 * Finally we subtract a constant from the host timestamps to bring the first
 * timestamp of the sliding window to 1s.
 */
void uvc_video_clock_update(struct uvc_streaming *stream,
609
			    struct vb2_v4l2_buffer *vbuf,
610 611 612 613 614 615
			    struct uvc_buffer *buf)
{
	struct uvc_clock *clock = &stream->clock;
	struct uvc_clock_sample *first;
	struct uvc_clock_sample *last;
	unsigned long flags;
616
	u64 timestamp;
617 618 619 620 621 622 623
	u32 delta_stc;
	u32 y1, y2;
	u32 x1, x2;
	u32 mean;
	u32 sof;
	u64 y;

624 625 626
	if (!uvc_hw_timestamps_param)
		return;

627 628 629 630 631 632 633 634 635 636 637 638
	spin_lock_irqsave(&clock->lock, flags);

	if (clock->count < clock->size)
		goto done;

	first = &clock->samples[clock->head];
	last = &clock->samples[(clock->head - 1) % clock->size];

	/* First step, PTS to SOF conversion. */
	delta_stc = buf->pts - (1UL << 31);
	x1 = first->dev_stc - delta_stc;
	x2 = last->dev_stc - delta_stc;
639 640 641
	if (x1 == x2)
		goto done;

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
	y1 = (first->dev_sof + 2048) << 16;
	y2 = (last->dev_sof + 2048) << 16;
	if (y2 < y1)
		y2 += 2048 << 16;

	y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
	  - (u64)y2 * (u64)x1;
	y = div_u64(y, x2 - x1);

	sof = y;

	uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
		  "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
		  stream->dev->name, buf->pts,
		  y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
		  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
		  x1, x2, y1, y2, clock->sof_offset);

	/* Second step, SOF to host clock conversion. */
	x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
	x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
	if (x2 < x1)
		x2 += 2048 << 16;
665 666 667 668
	if (x1 == x2)
		goto done;

	y1 = NSEC_PER_SEC;
669
	y2 = (u32)ktime_to_ns(ktime_sub(last->host_time, first->host_time)) + y1;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

	/* Interpolated and host SOF timestamps can wrap around at slightly
	 * different times. Handle this by adding or removing 2048 to or from
	 * the computed SOF value to keep it close to the SOF samples mean
	 * value.
	 */
	mean = (x1 + x2) / 2;
	if (mean - (1024 << 16) > sof)
		sof += 2048 << 16;
	else if (sof > mean + (1024 << 16))
		sof -= 2048 << 16;

	y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
	  - (u64)y2 * (u64)x1;
	y = div_u64(y, x2 - x1);

686
	timestamp = ktime_to_ns(first->host_time) + y - y1;
687

688 689
	uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %llu "
		  "buf ts %llu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
690 691
		  stream->dev->name,
		  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
692
		  y, timestamp, vbuf->vb2_buf.timestamp,
693 694 695 696
		  x1, first->host_sof, first->dev_sof,
		  x2, last->host_sof, last->dev_sof, y1, y2);

	/* Update the V4L2 buffer. */
697
	vbuf->vb2_buf.timestamp = timestamp;
698 699

done:
700
	spin_unlock_irqrestore(&clock->lock, flags);
701 702
}

703 704 705 706 707
/* ------------------------------------------------------------------------
 * Stream statistics
 */

static void uvc_video_stats_decode(struct uvc_streaming *stream,
708
		const u8 *data, int len)
709 710
{
	unsigned int header_size;
711 712 713 714 715
	bool has_pts = false;
	bool has_scr = false;
	u16 uninitialized_var(scr_sof);
	u32 uninitialized_var(scr_stc);
	u32 uninitialized_var(pts);
716 717 718

	if (stream->stats.stream.nb_frames == 0 &&
	    stream->stats.frame.nb_packets == 0)
719
		stream->stats.stream.start_ts = ktime_get();
720 721 722 723

	switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
	case UVC_STREAM_PTS | UVC_STREAM_SCR:
		header_size = 12;
724 725
		has_pts = true;
		has_scr = true;
726 727 728
		break;
	case UVC_STREAM_PTS:
		header_size = 6;
729
		has_pts = true;
730 731 732
		break;
	case UVC_STREAM_SCR:
		header_size = 8;
733
		has_scr = true;
734 735 736 737 738 739 740 741 742 743 744 745
		break;
	default:
		header_size = 2;
		break;
	}

	/* Check for invalid headers. */
	if (len < header_size || data[0] < header_size) {
		stream->stats.frame.nb_invalid++;
		return;
	}

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
	/* Extract the timestamps. */
	if (has_pts)
		pts = get_unaligned_le32(&data[2]);

	if (has_scr) {
		scr_stc = get_unaligned_le32(&data[header_size - 6]);
		scr_sof = get_unaligned_le16(&data[header_size - 2]);
	}

	/* Is PTS constant through the whole frame ? */
	if (has_pts && stream->stats.frame.nb_pts) {
		if (stream->stats.frame.pts != pts) {
			stream->stats.frame.nb_pts_diffs++;
			stream->stats.frame.last_pts_diff =
				stream->stats.frame.nb_packets;
		}
	}

	if (has_pts) {
		stream->stats.frame.nb_pts++;
		stream->stats.frame.pts = pts;
	}

	/* Do all frames have a PTS in their first non-empty packet, or before
	 * their first empty packet ?
	 */
	if (stream->stats.frame.size == 0) {
		if (len > header_size)
			stream->stats.frame.has_initial_pts = has_pts;
		if (len == header_size && has_pts)
			stream->stats.frame.has_early_pts = true;
	}

	/* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
	if (has_scr && stream->stats.frame.nb_scr) {
		if (stream->stats.frame.scr_stc != scr_stc)
			stream->stats.frame.nb_scr_diffs++;
	}

	if (has_scr) {
		/* Expand the SOF counter to 32 bits and store its value. */
		if (stream->stats.stream.nb_frames > 0 ||
		    stream->stats.frame.nb_scr > 0)
			stream->stats.stream.scr_sof_count +=
				(scr_sof - stream->stats.stream.scr_sof) % 2048;
		stream->stats.stream.scr_sof = scr_sof;

		stream->stats.frame.nb_scr++;
		stream->stats.frame.scr_stc = scr_stc;
		stream->stats.frame.scr_sof = scr_sof;

		if (scr_sof < stream->stats.stream.min_sof)
			stream->stats.stream.min_sof = scr_sof;
		if (scr_sof > stream->stats.stream.max_sof)
			stream->stats.stream.max_sof = scr_sof;
	}

803 804 805 806 807 808 809 810 811
	/* Record the first non-empty packet number. */
	if (stream->stats.frame.size == 0 && len > header_size)
		stream->stats.frame.first_data = stream->stats.frame.nb_packets;

	/* Update the frame size. */
	stream->stats.frame.size += len - header_size;

	/* Update the packets counters. */
	stream->stats.frame.nb_packets++;
812
	if (len <= header_size)
813 814 815 816 817 818 819 820 821 822
		stream->stats.frame.nb_empty++;

	if (data[1] & UVC_STREAM_ERR)
		stream->stats.frame.nb_errors++;
}

static void uvc_video_stats_update(struct uvc_streaming *stream)
{
	struct uvc_stats_frame *frame = &stream->stats.frame;

823 824 825
	uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
		  "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
		  "last pts/stc/sof %u/%u/%u\n",
826
		  stream->sequence, frame->first_data,
827 828 829 830 831 832
		  frame->nb_packets - frame->nb_empty, frame->nb_packets,
		  frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
		  frame->has_early_pts ? "" : "!",
		  frame->has_initial_pts ? "" : "!",
		  frame->nb_scr_diffs, frame->nb_scr,
		  frame->pts, frame->scr_stc, frame->scr_sof);
833 834 835 836 837 838 839

	stream->stats.stream.nb_frames++;
	stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
	stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
	stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
	stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;

840 841 842 843 844 845 846 847 848 849 850
	if (frame->has_early_pts)
		stream->stats.stream.nb_pts_early++;
	if (frame->has_initial_pts)
		stream->stats.stream.nb_pts_initial++;
	if (frame->last_pts_diff <= frame->first_data)
		stream->stats.stream.nb_pts_constant++;
	if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
		stream->stats.stream.nb_scr_count_ok++;
	if (frame->nb_scr_diffs + 1 == frame->nb_scr)
		stream->stats.stream.nb_scr_diffs_ok++;

851 852 853 854 855 856
	memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
}

size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
			    size_t size)
{
857 858
	unsigned int scr_sof_freq;
	unsigned int duration;
859 860
	size_t count = 0;

861 862 863
	/* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
	 * frequency this will not overflow before more than 1h.
	 */
864 865
	duration = ktime_ms_delta(stream->stats.stream.stop_ts,
				  stream->stats.stream.start_ts);
866 867 868 869 870 871
	if (duration != 0)
		scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
			     / duration;
	else
		scr_sof_freq = 0;

872 873 874 875 876 877 878 879
	count += scnprintf(buf + count, size - count,
			   "frames:  %u\npackets: %u\nempty:   %u\n"
			   "errors:  %u\ninvalid: %u\n",
			   stream->stats.stream.nb_frames,
			   stream->stats.stream.nb_packets,
			   stream->stats.stream.nb_empty,
			   stream->stats.stream.nb_errors,
			   stream->stats.stream.nb_invalid);
880 881 882 883 884 885 886 887 888 889 890 891 892 893
	count += scnprintf(buf + count, size - count,
			   "pts: %u early, %u initial, %u ok\n",
			   stream->stats.stream.nb_pts_early,
			   stream->stats.stream.nb_pts_initial,
			   stream->stats.stream.nb_pts_constant);
	count += scnprintf(buf + count, size - count,
			   "scr: %u count ok, %u diff ok\n",
			   stream->stats.stream.nb_scr_count_ok,
			   stream->stats.stream.nb_scr_diffs_ok);
	count += scnprintf(buf + count, size - count,
			   "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
			   stream->stats.stream.min_sof,
			   stream->stats.stream.max_sof,
			   scr_sof_freq / 1000, scr_sof_freq % 1000);
894 895 896 897 898 899 900

	return count;
}

static void uvc_video_stats_start(struct uvc_streaming *stream)
{
	memset(&stream->stats, 0, sizeof(stream->stats));
901
	stream->stats.stream.min_sof = 2048;
902 903 904 905
}

static void uvc_video_stats_stop(struct uvc_streaming *stream)
{
906
	stream->stats.stream.stop_ts = ktime_get();
907 908
}

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
/* ------------------------------------------------------------------------
 * Video codecs
 */

/* Video payload decoding is handled by uvc_video_decode_start(),
 * uvc_video_decode_data() and uvc_video_decode_end().
 *
 * uvc_video_decode_start is called with URB data at the start of a bulk or
 * isochronous payload. It processes header data and returns the header size
 * in bytes if successful. If an error occurs, it returns a negative error
 * code. The following error codes have special meanings.
 *
 * - EAGAIN informs the caller that the current video buffer should be marked
 *   as done, and that the function should be called again with the same data
 *   and a new video buffer. This is used when end of frame conditions can be
 *   reliably detected at the beginning of the next frame only.
 *
 * If an error other than -EAGAIN is returned, the caller will drop the current
 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
 * made until the next payload. -ENODATA can be used to drop the current
 * payload if no other error code is appropriate.
 *
 * uvc_video_decode_data is called for every URB with URB data. It copies the
 * data to the video buffer.
 *
 * uvc_video_decode_end is called with header data at the end of a bulk or
 * isochronous payload. It performs any additional header data processing and
L
Lucas De Marchi 已提交
936
 * returns 0 or a negative error code if an error occurred. As header data have
937 938 939
 * already been processed by uvc_video_decode_start, this functions isn't
 * required to perform sanity checks a second time.
 *
L
Lucas De Marchi 已提交
940
 * For isochronous transfers where a payload is always transferred in a single
941 942 943 944 945 946 947
 * URB, the three functions will be called in a row.
 *
 * To let the decoder process header data and update its internal state even
 * when no video buffer is available, uvc_video_decode_start must be prepared
 * to be called with a NULL buf parameter. uvc_video_decode_data and
 * uvc_video_decode_end will never be called with a NULL buffer.
 */
948
static int uvc_video_decode_start(struct uvc_streaming *stream,
949
		struct uvc_buffer *buf, const u8 *data, int len)
950
{
951
	u8 fid;
952 953 954 955 956 957

	/* Sanity checks:
	 * - packet must be at least 2 bytes long
	 * - bHeaderLength value must be at least 2 bytes (see above)
	 * - bHeaderLength value can't be larger than the packet size.
	 */
958 959
	if (len < 2 || data[0] < 2 || data[0] > len) {
		stream->stats.frame.nb_invalid++;
960
		return -EINVAL;
961
	}
962 963 964

	fid = data[1] & UVC_STREAM_FID;

965 966 967
	/* Increase the sequence number regardless of any buffer states, so
	 * that discontinuous sequence numbers always indicate lost frames.
	 */
968
	if (stream->last_fid != fid) {
969
		stream->sequence++;
970 971 972 973
		if (stream->sequence)
			uvc_video_stats_update(stream);
	}

974
	uvc_video_clock_decode(stream, buf, data, len);
975
	uvc_video_stats_decode(stream, data, len);
976

977 978 979 980
	/* Store the payload FID bit and return immediately when the buffer is
	 * NULL.
	 */
	if (buf == NULL) {
981
		stream->last_fid = fid;
982 983 984
		return -ENODATA;
	}

985 986 987 988 989 990 991
	/* Mark the buffer as bad if the error bit is set. */
	if (data[1] & UVC_STREAM_ERR) {
		uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
			  "set).\n");
		buf->error = 1;
	}

992 993
	/* Synchronize to the input stream by waiting for the FID bit to be
	 * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
994
	 * stream->last_fid is initialized to -1, so the first isochronous
995 996
	 * frame will always be in sync.
	 *
997
	 * If the device doesn't toggle the FID bit, invert stream->last_fid
998 999 1000
	 * when the EOF bit is set to force synchronisation on the next packet.
	 */
	if (buf->state != UVC_BUF_STATE_ACTIVE) {
1001
		if (fid == stream->last_fid) {
1002 1003
			uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
				"sync).\n");
1004
			if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1005
			    (data[1] & UVC_STREAM_EOF))
1006
				stream->last_fid ^= UVC_STREAM_FID;
1007 1008 1009
			return -ENODATA;
		}

1010 1011
		buf->buf.field = V4L2_FIELD_NONE;
		buf->buf.sequence = stream->sequence;
1012
		buf->buf.vb2_buf.timestamp = uvc_video_get_time();
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
		/* TODO: Handle PTS and SCR. */
		buf->state = UVC_BUF_STATE_ACTIVE;
	}

	/* Mark the buffer as done if we're at the beginning of a new frame.
	 * End of frame detection is better implemented by checking the EOF
	 * bit (FID bit toggling is delayed by one frame compared to the EOF
	 * bit), but some devices don't set the bit at end of frame (and the
	 * last payload can be lost anyway). We thus must check if the FID has
	 * been toggled.
	 *
1025
	 * stream->last_fid is initialized to -1, so the first isochronous
1026 1027 1028 1029
	 * frame will never trigger an end of frame detection.
	 *
	 * Empty buffers (bytesused == 0) don't trigger end of frame detection
	 * as it doesn't make sense to return an empty buffer. This also
1030
	 * avoids detecting end of frame conditions at FID toggling if the
1031 1032
	 * previous payload had the EOF bit set.
	 */
1033
	if (fid != stream->last_fid && buf->bytesused != 0) {
1034 1035
		uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
				"toggled).\n");
1036
		buf->state = UVC_BUF_STATE_READY;
1037 1038 1039
		return -EAGAIN;
	}

1040
	stream->last_fid = fid;
1041 1042 1043 1044

	return data[0];
}

1045
static void uvc_video_decode_data(struct uvc_streaming *stream,
1046
		struct uvc_buffer *buf, const u8 *data, int len)
1047 1048 1049 1050 1051 1052 1053 1054
{
	unsigned int maxlen, nbytes;
	void *mem;

	if (len <= 0)
		return;

	/* Copy the video data to the buffer. */
1055 1056
	maxlen = buf->length - buf->bytesused;
	mem = buf->mem + buf->bytesused;
1057 1058
	nbytes = min((unsigned int)len, maxlen);
	memcpy(mem, data, nbytes);
1059
	buf->bytesused += nbytes;
1060 1061 1062 1063

	/* Complete the current frame if the buffer size was exceeded. */
	if (len > maxlen) {
		uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1064
		buf->error = 1;
1065
		buf->state = UVC_BUF_STATE_READY;
1066 1067 1068
	}
}

1069
static void uvc_video_decode_end(struct uvc_streaming *stream,
1070
		struct uvc_buffer *buf, const u8 *data, int len)
1071 1072
{
	/* Mark the buffer as done if the EOF marker is set. */
1073
	if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1074 1075 1076
		uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
		if (data[0] == len)
			uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1077
		buf->state = UVC_BUF_STATE_READY;
1078 1079
		if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
			stream->last_fid ^= UVC_STREAM_FID;
1080 1081 1082
	}
}

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
/* Video payload encoding is handled by uvc_video_encode_header() and
 * uvc_video_encode_data(). Only bulk transfers are currently supported.
 *
 * uvc_video_encode_header is called at the start of a payload. It adds header
 * data to the transfer buffer and returns the header size. As the only known
 * UVC output device transfers a whole frame in a single payload, the EOF bit
 * is always set in the header.
 *
 * uvc_video_encode_data is called for every URB and copies the data from the
 * video buffer to the transfer buffer.
 */
1094
static int uvc_video_encode_header(struct uvc_streaming *stream,
1095
		struct uvc_buffer *buf, u8 *data, int len)
1096 1097 1098
{
	data[0] = 2;	/* Header length */
	data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1099
		| (stream->last_fid & UVC_STREAM_FID);
1100 1101 1102
	return 2;
}

1103
static int uvc_video_encode_data(struct uvc_streaming *stream,
1104
		struct uvc_buffer *buf, u8 *data, int len)
1105
{
1106
	struct uvc_video_queue *queue = &stream->queue;
1107 1108 1109 1110
	unsigned int nbytes;
	void *mem;

	/* Copy video data to the URB buffer. */
1111 1112
	mem = buf->mem + queue->buf_used;
	nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1113
	nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1114 1115 1116 1117 1118 1119 1120 1121
			nbytes);
	memcpy(data, mem, nbytes);

	queue->buf_used += nbytes;

	return nbytes;
}

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
/* ------------------------------------------------------------------------
 * Metadata
 */

/*
 * Additionally to the payload headers we also want to provide the user with USB
 * Frame Numbers and system time values. The resulting buffer is thus composed
 * of blocks, containing a 64-bit timestamp in  nanoseconds, a 16-bit USB Frame
 * Number, and a copy of the payload header.
 *
 * Ideally we want to capture all payload headers for each frame. However, their
 * number is unknown and unbound. We thus drop headers that contain no vendor
 * data and that either contain no SCR value or an SCR value identical to the
 * previous header.
 */
static void uvc_video_decode_meta(struct uvc_streaming *stream,
				  struct uvc_buffer *meta_buf,
				  const u8 *mem, unsigned int length)
{
	struct uvc_meta_buf *meta;
	size_t len_std = 2;
	bool has_pts, has_scr;
	unsigned long flags;
	unsigned int sof;
	ktime_t time;
	const u8 *scr;

	if (!meta_buf || length == 2)
		return;

	if (meta_buf->length - meta_buf->bytesused <
	    length + sizeof(meta->ns) + sizeof(meta->sof)) {
		meta_buf->error = 1;
		return;
	}

	has_pts = mem[1] & UVC_STREAM_PTS;
	has_scr = mem[1] & UVC_STREAM_SCR;

	if (has_pts) {
		len_std += 4;
		scr = mem + 6;
	} else {
		scr = mem + 2;
	}

	if (has_scr)
		len_std += 6;

	if (stream->meta.format == V4L2_META_FMT_UVC)
		length = len_std;

	if (length == len_std && (!has_scr ||
				  !memcmp(scr, stream->clock.last_scr, 6)))
		return;

	meta = (struct uvc_meta_buf *)((u8 *)meta_buf->mem + meta_buf->bytesused);
	local_irq_save(flags);
	time = uvc_video_get_time();
	sof = usb_get_current_frame_number(stream->dev->udev);
	local_irq_restore(flags);
	put_unaligned(ktime_to_ns(time), &meta->ns);
	put_unaligned(sof, &meta->sof);

	if (has_scr)
		memcpy(stream->clock.last_scr, scr, 6);

	memcpy(&meta->length, mem, length);
	meta_buf->bytesused += length + sizeof(meta->ns) + sizeof(meta->sof);

	uvc_trace(UVC_TRACE_FRAME,
		  "%s(): t-sys %lluns, SOF %u, len %u, flags 0x%x, PTS %u, STC %u frame SOF %u\n",
		  __func__, time, meta->sof, meta->length, meta->flags,
		  has_pts ? *(u32 *)meta->buf : 0,
		  has_scr ? *(u32 *)scr : 0,
		  has_scr ? *(u32 *)(scr + 4) & 0x7ff : 0);
}

1200 1201 1202 1203
/* ------------------------------------------------------------------------
 * URB handling
 */

1204 1205 1206 1207 1208 1209
/*
 * Set error flag for incomplete buffer.
 */
static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
				      struct uvc_buffer *buf)
{
1210
	if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1211 1212 1213 1214
	    !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
		buf->error = 1;
}

1215 1216 1217
/*
 * Completion handler for video URBs.
 */
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238

static void uvc_video_next_buffers(struct uvc_streaming *stream,
		struct uvc_buffer **video_buf, struct uvc_buffer **meta_buf)
{
	if (*meta_buf) {
		struct vb2_v4l2_buffer *vb2_meta = &(*meta_buf)->buf;
		const struct vb2_v4l2_buffer *vb2_video = &(*video_buf)->buf;

		vb2_meta->sequence = vb2_video->sequence;
		vb2_meta->field = vb2_video->field;
		vb2_meta->vb2_buf.timestamp = vb2_video->vb2_buf.timestamp;

		(*meta_buf)->state = UVC_BUF_STATE_READY;
		if (!(*meta_buf)->error)
			(*meta_buf)->error = (*video_buf)->error;
		*meta_buf = uvc_queue_next_buffer(&stream->meta.queue,
						  *meta_buf);
	}
	*video_buf = uvc_queue_next_buffer(&stream->queue, *video_buf);
}

1239
static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1240
			struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1241 1242 1243 1244 1245 1246 1247 1248
{
	u8 *mem;
	int ret, i;

	for (i = 0; i < urb->number_of_packets; ++i) {
		if (urb->iso_frame_desc[i].status < 0) {
			uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
				"lost (%d).\n", urb->iso_frame_desc[i].status);
1249 1250 1251
			/* Mark the buffer as faulty. */
			if (buf != NULL)
				buf->error = 1;
1252 1253 1254 1255 1256 1257
			continue;
		}

		/* Decode the payload header. */
		mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
		do {
1258
			ret = uvc_video_decode_start(stream, buf, mem,
1259
				urb->iso_frame_desc[i].actual_length);
1260 1261
			if (ret == -EAGAIN) {
				uvc_video_validate_buffer(stream, buf);
1262
				uvc_video_next_buffers(stream, &buf, &meta_buf);
1263
			}
1264 1265 1266 1267 1268
		} while (ret == -EAGAIN);

		if (ret < 0)
			continue;

1269 1270
		uvc_video_decode_meta(stream, meta_buf, mem, ret);

1271
		/* Decode the payload data. */
1272
		uvc_video_decode_data(stream, buf, mem + ret,
1273 1274 1275
			urb->iso_frame_desc[i].actual_length - ret);

		/* Process the header again. */
1276
		uvc_video_decode_end(stream, buf, mem,
1277
			urb->iso_frame_desc[i].actual_length);
1278

1279
		if (buf->state == UVC_BUF_STATE_READY) {
1280
			uvc_video_validate_buffer(stream, buf);
1281
			uvc_video_next_buffers(stream, &buf, &meta_buf);
1282
		}
1283 1284 1285
	}
}

1286
static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1287
			struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1288 1289 1290 1291
{
	u8 *mem;
	int len, ret;

1292 1293 1294 1295 1296
	/*
	 * Ignore ZLPs if they're not part of a frame, otherwise process them
	 * to trigger the end of payload detection.
	 */
	if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1297 1298
		return;

1299 1300
	mem = urb->transfer_buffer;
	len = urb->actual_length;
1301
	stream->bulk.payload_size += len;
1302 1303 1304 1305

	/* If the URB is the first of its payload, decode and save the
	 * header.
	 */
1306
	if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1307
		do {
1308
			ret = uvc_video_decode_start(stream, buf, mem, len);
1309
			if (ret == -EAGAIN)
1310
				uvc_video_next_buffers(stream, &buf, &meta_buf);
1311 1312
		} while (ret == -EAGAIN);

L
Lucas De Marchi 已提交
1313
		/* If an error occurred skip the rest of the payload. */
1314
		if (ret < 0 || buf == NULL) {
1315
			stream->bulk.skip_payload = 1;
1316
		} else {
1317 1318
			memcpy(stream->bulk.header, mem, ret);
			stream->bulk.header_size = ret;
1319

1320 1321
			uvc_video_decode_meta(stream, meta_buf, mem, ret);

1322 1323 1324
			mem += ret;
			len -= ret;
		}
1325 1326 1327 1328 1329 1330 1331 1332
	}

	/* The buffer queue might have been cancelled while a bulk transfer
	 * was in progress, so we can reach here with buf equal to NULL. Make
	 * sure buf is never dereferenced if NULL.
	 */

	/* Process video data. */
1333 1334
	if (!stream->bulk.skip_payload && buf != NULL)
		uvc_video_decode_data(stream, buf, mem, len);
1335 1336 1337 1338 1339

	/* Detect the payload end by a URB smaller than the maximum size (or
	 * a payload size equal to the maximum) and process the header again.
	 */
	if (urb->actual_length < urb->transfer_buffer_length ||
1340 1341 1342 1343
	    stream->bulk.payload_size >= stream->bulk.max_payload_size) {
		if (!stream->bulk.skip_payload && buf != NULL) {
			uvc_video_decode_end(stream, buf, stream->bulk.header,
				stream->bulk.payload_size);
1344
			if (buf->state == UVC_BUF_STATE_READY)
1345
				uvc_video_next_buffers(stream, &buf, &meta_buf);
1346 1347
		}

1348 1349 1350
		stream->bulk.header_size = 0;
		stream->bulk.skip_payload = 0;
		stream->bulk.payload_size = 0;
1351 1352 1353
	}
}

1354
static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1355
	struct uvc_buffer *buf, struct uvc_buffer *meta_buf)
1356 1357
{
	u8 *mem = urb->transfer_buffer;
1358
	int len = stream->urb_size, ret;
1359 1360 1361 1362 1363 1364 1365

	if (buf == NULL) {
		urb->transfer_buffer_length = 0;
		return;
	}

	/* If the URB is the first of its payload, add the header. */
1366 1367 1368 1369
	if (stream->bulk.header_size == 0) {
		ret = uvc_video_encode_header(stream, buf, mem, len);
		stream->bulk.header_size = ret;
		stream->bulk.payload_size += ret;
1370 1371 1372 1373 1374
		mem += ret;
		len -= ret;
	}

	/* Process video data. */
1375
	ret = uvc_video_encode_data(stream, buf, mem, len);
1376

1377
	stream->bulk.payload_size += ret;
1378 1379
	len -= ret;

1380
	if (buf->bytesused == stream->queue.buf_used ||
1381
	    stream->bulk.payload_size == stream->bulk.max_payload_size) {
1382
		if (buf->bytesused == stream->queue.buf_used) {
1383
			stream->queue.buf_used = 0;
1384
			buf->state = UVC_BUF_STATE_READY;
1385
			buf->buf.sequence = ++stream->sequence;
1386 1387
			uvc_queue_next_buffer(&stream->queue, buf);
			stream->last_fid ^= UVC_STREAM_FID;
1388 1389
		}

1390 1391
		stream->bulk.header_size = 0;
		stream->bulk.payload_size = 0;
1392 1393
	}

1394
	urb->transfer_buffer_length = stream->urb_size - len;
1395 1396
}

1397 1398
static void uvc_video_complete(struct urb *urb)
{
1399 1400
	struct uvc_streaming *stream = urb->context;
	struct uvc_video_queue *queue = &stream->queue;
1401 1402
	struct uvc_video_queue *qmeta = &stream->meta.queue;
	struct vb2_queue *vb2_qmeta = stream->meta.vdev.queue;
1403
	struct uvc_buffer *buf = NULL;
1404
	struct uvc_buffer *buf_meta = NULL;
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
	unsigned long flags;
	int ret;

	switch (urb->status) {
	case 0:
		break;

	default:
		uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
			"completion handler.\n", urb->status);
1415
		/* fall through */
1416
	case -ENOENT:		/* usb_kill_urb() called. */
1417
		if (stream->frozen)
1418
			return;
1419
		/* fall through */
1420 1421 1422
	case -ECONNRESET:	/* usb_unlink_urb() called. */
	case -ESHUTDOWN:	/* The endpoint is being disabled. */
		uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1423 1424
		if (vb2_qmeta)
			uvc_queue_cancel(qmeta, urb->status == -ESHUTDOWN);
1425 1426 1427 1428 1429 1430 1431 1432 1433
		return;
	}

	spin_lock_irqsave(&queue->irqlock, flags);
	if (!list_empty(&queue->irqqueue))
		buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
				       queue);
	spin_unlock_irqrestore(&queue->irqlock, flags);

1434 1435 1436 1437 1438 1439 1440 1441 1442
	if (vb2_qmeta) {
		spin_lock_irqsave(&qmeta->irqlock, flags);
		if (!list_empty(&qmeta->irqqueue))
			buf_meta = list_first_entry(&qmeta->irqqueue,
						    struct uvc_buffer, queue);
		spin_unlock_irqrestore(&qmeta->irqlock, flags);
	}

	stream->decode(urb, stream, buf, buf_meta);
1443 1444 1445 1446 1447 1448 1449

	if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
		uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
			ret);
	}
}

1450 1451 1452
/*
 * Free transfer buffers.
 */
1453
static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1454 1455 1456 1457
{
	unsigned int i;

	for (i = 0; i < UVC_URBS; ++i) {
1458
		if (stream->urb_buffer[i]) {
1459
#ifndef CONFIG_DMA_NONCOHERENT
1460
			usb_free_coherent(stream->dev->udev, stream->urb_size,
1461
				stream->urb_buffer[i], stream->urb_dma[i]);
1462 1463 1464
#else
			kfree(stream->urb_buffer[i]);
#endif
1465
			stream->urb_buffer[i] = NULL;
1466 1467 1468
		}
	}

1469
	stream->urb_size = 0;
1470 1471 1472 1473 1474 1475 1476
}

/*
 * Allocate transfer buffers. This function can be called with buffers
 * already allocated when resuming from suspend, in which case it will
 * return without touching the buffers.
 *
1477 1478 1479 1480 1481
 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
 * system is too low on memory try successively smaller numbers of packets
 * until allocation succeeds.
 *
 * Return the number of allocated packets on success or 0 when out of memory.
1482
 */
1483
static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1484
	unsigned int size, unsigned int psize, gfp_t gfp_flags)
1485
{
1486
	unsigned int npackets;
1487 1488 1489
	unsigned int i;

	/* Buffers are already allocated, bail out. */
1490 1491
	if (stream->urb_size)
		return stream->urb_size / psize;
1492

1493
	/* Compute the number of packets. Bulk endpoints might transfer UVC
L
Lucas De Marchi 已提交
1494
	 * payloads across multiple URBs.
1495 1496 1497 1498 1499 1500 1501 1502
	 */
	npackets = DIV_ROUND_UP(size, psize);
	if (npackets > UVC_MAX_PACKETS)
		npackets = UVC_MAX_PACKETS;

	/* Retry allocations until one succeed. */
	for (; npackets > 1; npackets /= 2) {
		for (i = 0; i < UVC_URBS; ++i) {
1503
			stream->urb_size = psize * npackets;
1504
#ifndef CONFIG_DMA_NONCOHERENT
1505
			stream->urb_buffer[i] = usb_alloc_coherent(
1506
				stream->dev->udev, stream->urb_size,
1507
				gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1508 1509 1510 1511
#else
			stream->urb_buffer[i] =
			    kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
#endif
1512 1513
			if (!stream->urb_buffer[i]) {
				uvc_free_urb_buffers(stream);
1514 1515 1516 1517 1518
				break;
			}
		}

		if (i == UVC_URBS) {
1519 1520 1521
			uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
				"of %ux%u bytes each.\n", UVC_URBS, npackets,
				psize);
1522
			return npackets;
1523 1524 1525
		}
	}

1526 1527
	uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
		"per packet).\n", psize);
1528 1529 1530
	return 0;
}

1531 1532 1533
/*
 * Uninitialize isochronous/bulk URBs and free transfer buffers.
 */
1534
static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1535 1536 1537 1538
{
	struct urb *urb;
	unsigned int i;

1539 1540
	uvc_video_stats_stop(stream);

1541
	for (i = 0; i < UVC_URBS; ++i) {
1542 1543
		urb = stream->urb[i];
		if (urb == NULL)
1544 1545 1546 1547
			continue;

		usb_kill_urb(urb);
		usb_free_urb(urb);
1548
		stream->urb[i] = NULL;
1549
	}
1550 1551

	if (free_buffers)
1552
		uvc_free_urb_buffers(stream);
1553 1554
}

1555 1556 1557 1558 1559 1560 1561
/*
 * Compute the maximum number of bytes per interval for an endpoint.
 */
static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
					 struct usb_host_endpoint *ep)
{
	u16 psize;
1562
	u16 mult;
1563 1564 1565

	switch (dev->speed) {
	case USB_SPEED_SUPER:
1566
	case USB_SPEED_SUPER_PLUS:
H
Hans Verkuil 已提交
1567
		return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1568 1569
	case USB_SPEED_HIGH:
		psize = usb_endpoint_maxp(&ep->desc);
1570
		mult = usb_endpoint_maxp_mult(&ep->desc);
1571
		return psize * mult;
1572 1573 1574
	case USB_SPEED_WIRELESS:
		psize = usb_endpoint_maxp(&ep->desc);
		return psize;
1575 1576
	default:
		psize = usb_endpoint_maxp(&ep->desc);
1577
		return psize;
1578 1579 1580
	}
}

1581 1582 1583 1584
/*
 * Initialize isochronous URBs and allocate transfer buffers. The packet size
 * is given by the endpoint.
 */
1585
static int uvc_init_video_isoc(struct uvc_streaming *stream,
1586
	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1587 1588 1589
{
	struct urb *urb;
	unsigned int npackets, i, j;
1590 1591
	u16 psize;
	u32 size;
1592

1593
	psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1594
	size = stream->ctrl.dwMaxVideoFrameSize;
1595

1596
	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1597 1598
	if (npackets == 0)
		return -ENOMEM;
1599 1600 1601 1602

	size = npackets * psize;

	for (i = 0; i < UVC_URBS; ++i) {
1603
		urb = usb_alloc_urb(npackets, gfp_flags);
1604
		if (urb == NULL) {
1605
			uvc_uninit_video(stream, 1);
1606 1607 1608
			return -ENOMEM;
		}

1609 1610 1611
		urb->dev = stream->dev->udev;
		urb->context = stream;
		urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1612
				ep->desc.bEndpointAddress);
1613
#ifndef CONFIG_DMA_NONCOHERENT
1614
		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1615 1616 1617 1618
		urb->transfer_dma = stream->urb_dma[i];
#else
		urb->transfer_flags = URB_ISO_ASAP;
#endif
1619
		urb->interval = ep->desc.bInterval;
1620
		urb->transfer_buffer = stream->urb_buffer[i];
1621 1622 1623 1624 1625 1626 1627 1628 1629
		urb->complete = uvc_video_complete;
		urb->number_of_packets = npackets;
		urb->transfer_buffer_length = size;

		for (j = 0; j < npackets; ++j) {
			urb->iso_frame_desc[j].offset = j * psize;
			urb->iso_frame_desc[j].length = psize;
		}

1630
		stream->urb[i] = urb;
1631 1632 1633 1634 1635 1636 1637 1638 1639
	}

	return 0;
}

/*
 * Initialize bulk URBs and allocate transfer buffers. The packet size is
 * given by the endpoint.
 */
1640
static int uvc_init_video_bulk(struct uvc_streaming *stream,
1641
	struct usb_host_endpoint *ep, gfp_t gfp_flags)
1642 1643
{
	struct urb *urb;
1644 1645 1646 1647
	unsigned int npackets, pipe, i;
	u16 psize;
	u32 size;

1648
	psize = usb_endpoint_maxp(&ep->desc);
1649 1650
	size = stream->ctrl.dwMaxPayloadTransferSize;
	stream->bulk.max_payload_size = size;
1651

1652
	npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1653
	if (npackets == 0)
1654 1655
		return -ENOMEM;

1656 1657
	size = npackets * psize;

1658
	if (usb_endpoint_dir_in(&ep->desc))
1659
		pipe = usb_rcvbulkpipe(stream->dev->udev,
1660 1661
				       ep->desc.bEndpointAddress);
	else
1662
		pipe = usb_sndbulkpipe(stream->dev->udev,
1663 1664
				       ep->desc.bEndpointAddress);

1665
	if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1666
		size = 0;
1667 1668

	for (i = 0; i < UVC_URBS; ++i) {
1669
		urb = usb_alloc_urb(0, gfp_flags);
1670
		if (urb == NULL) {
1671
			uvc_uninit_video(stream, 1);
1672 1673 1674
			return -ENOMEM;
		}

1675 1676 1677
		usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
			stream->urb_buffer[i], size, uvc_video_complete,
			stream);
1678
#ifndef CONFIG_DMA_NONCOHERENT
1679
		urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1680
		urb->transfer_dma = stream->urb_dma[i];
1681
#endif
1682

1683
		stream->urb[i] = urb;
1684 1685 1686 1687 1688 1689 1690 1691
	}

	return 0;
}

/*
 * Initialize isochronous/bulk URBs and allocate transfer buffers.
 */
1692
static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1693
{
1694
	struct usb_interface *intf = stream->intf;
1695 1696
	struct usb_host_endpoint *ep;
	unsigned int i;
1697 1698
	int ret;

1699
	stream->sequence = -1;
1700 1701 1702 1703
	stream->last_fid = -1;
	stream->bulk.header_size = 0;
	stream->bulk.skip_payload = 0;
	stream->bulk.payload_size = 0;
1704

1705 1706
	uvc_video_stats_start(stream);

1707
	if (intf->num_altsetting > 1) {
1708
		struct usb_host_endpoint *best_ep = NULL;
1709
		unsigned int best_psize = UINT_MAX;
1710 1711 1712 1713
		unsigned int bandwidth;
		unsigned int uninitialized_var(altsetting);
		int intfnum = stream->intfnum;

1714
		/* Isochronous endpoint, select the alternate setting. */
1715
		bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1716 1717

		if (bandwidth == 0) {
1718 1719
			uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
				"bandwidth, defaulting to lowest.\n");
1720
			bandwidth = 1;
1721 1722 1723
		} else {
			uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
				"B/frame bandwidth.\n", bandwidth);
1724 1725 1726
		}

		for (i = 0; i < intf->num_altsetting; ++i) {
1727 1728 1729
			struct usb_host_interface *alts;
			unsigned int psize;

1730 1731
			alts = &intf->altsetting[i];
			ep = uvc_find_endpoint(alts,
1732
				stream->header.bEndpointAddress);
1733 1734 1735 1736
			if (ep == NULL)
				continue;

			/* Check if the bandwidth is high enough. */
1737
			psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1738
			if (psize >= bandwidth && psize <= best_psize) {
1739
				altsetting = alts->desc.bAlternateSetting;
1740 1741 1742
				best_psize = psize;
				best_ep = ep;
			}
1743 1744
		}

1745
		if (best_ep == NULL) {
1746 1747
			uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
				"for requested bandwidth.\n");
1748
			return -EIO;
1749
		}
1750

1751 1752 1753 1754
		uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
			"(%u B/frame bandwidth).\n", altsetting, best_psize);

		ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1755
		if (ret < 0)
1756 1757
			return ret;

1758
		ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1759 1760 1761
	} else {
		/* Bulk endpoint, proceed to URB initialization. */
		ep = uvc_find_endpoint(&intf->altsetting[0],
1762
				stream->header.bEndpointAddress);
1763 1764 1765
		if (ep == NULL)
			return -EIO;

1766
		ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1767 1768 1769 1770 1771 1772 1773
	}

	if (ret < 0)
		return ret;

	/* Submit the URBs. */
	for (i = 0; i < UVC_URBS; ++i) {
1774 1775
		ret = usb_submit_urb(stream->urb[i], gfp_flags);
		if (ret < 0) {
1776 1777
			uvc_printk(KERN_ERR, "Failed to submit URB %u "
					"(%d).\n", i, ret);
1778
			uvc_uninit_video(stream, 1);
1779 1780 1781 1782
			return ret;
		}
	}

1783 1784 1785 1786 1787 1788
	/* The Logitech C920 temporarily forgets that it should not be adjusting
	 * Exposure Absolute during init so restore controls to stored values.
	 */
	if (stream->dev->quirks & UVC_QUIRK_RESTORE_CTRLS_ON_INIT)
		uvc_ctrl_restore_values(stream->dev);

1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
	return 0;
}

/* --------------------------------------------------------------------------
 * Suspend/resume
 */

/*
 * Stop streaming without disabling the video queue.
 *
 * To let userspace applications resume without trouble, we must not touch the
 * video buffers in any way. We mark the device as frozen to make sure the URB
 * completion handler won't try to cancel the queue when we kill the URBs.
 */
1803
int uvc_video_suspend(struct uvc_streaming *stream)
1804
{
1805
	if (!uvc_queue_streaming(&stream->queue))
1806 1807
		return 0;

1808 1809 1810
	stream->frozen = 1;
	uvc_uninit_video(stream, 0);
	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1811 1812 1813 1814
	return 0;
}

/*
1815
 * Reconfigure the video interface and restart streaming if it was enabled
1816 1817 1818 1819 1820 1821
 * before suspend.
 *
 * If an error occurs, disable the video queue. This will wake all pending
 * buffers, making sure userspace applications are notified of the problem
 * instead of waiting forever.
 */
1822
int uvc_video_resume(struct uvc_streaming *stream, int reset)
1823 1824 1825
{
	int ret;

1826 1827 1828 1829 1830 1831 1832 1833
	/* If the bus has been reset on resume, set the alternate setting to 0.
	 * This should be the default value, but some devices crash or otherwise
	 * misbehave if they don't receive a SET_INTERFACE request before any
	 * other video control request.
	 */
	if (reset)
		usb_set_interface(stream->dev->udev, stream->intfnum, 0);

1834
	stream->frozen = 0;
1835

1836 1837
	uvc_video_clock_reset(stream);

1838 1839 1840
	if (!uvc_queue_streaming(&stream->queue))
		return 0;

1841
	ret = uvc_commit_video(stream, &stream->ctrl);
1842
	if (ret < 0)
1843 1844
		return ret;

1845
	return uvc_init_video(stream, GFP_NOIO);
1846 1847 1848 1849 1850 1851 1852
}

/* ------------------------------------------------------------------------
 * Video device
 */

/*
1853 1854
 * Initialize the UVC video device by switching to alternate setting 0 and
 * retrieve the default format.
1855 1856 1857 1858 1859 1860 1861
 *
 * Some cameras (namely the Fuji Finepix) set the format and frame
 * indexes to zero. The UVC standard doesn't clearly make this a spec
 * violation, so try to silently fix the values if possible.
 *
 * This function is called before registering the device with V4L.
 */
1862
int uvc_video_init(struct uvc_streaming *stream)
1863
{
1864
	struct uvc_streaming_control *probe = &stream->ctrl;
1865 1866 1867 1868 1869
	struct uvc_format *format = NULL;
	struct uvc_frame *frame = NULL;
	unsigned int i;
	int ret;

1870
	if (stream->nformats == 0) {
1871 1872 1873 1874
		uvc_printk(KERN_INFO, "No supported video formats found.\n");
		return -EINVAL;
	}

1875 1876
	atomic_set(&stream->active, 0);

1877 1878 1879 1880 1881
	/* Alternate setting 0 should be the default, yet the XBox Live Vision
	 * Cam (and possibly other devices) crash or otherwise misbehave if
	 * they don't receive a SET_INTERFACE request before any other video
	 * control request.
	 */
1882
	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1883

1884 1885 1886 1887
	/* Set the streaming probe control with default streaming parameters
	 * retrieved from the device. Webcams that don't suport GET_DEF
	 * requests on the probe control will just keep their current streaming
	 * parameters.
1888
	 */
1889 1890
	if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
		uvc_set_video_ctrl(stream, probe, 1);
1891 1892 1893 1894 1895 1896

	/* Initialize the streaming parameters with the probe control current
	 * value. This makes sure SET_CUR requests on the streaming commit
	 * control will always use values retrieved from a successful GET_CUR
	 * request on the probe control, as required by the UVC specification.
	 */
1897
	ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1898
	if (ret < 0)
1899 1900 1901 1902 1903
		return ret;

	/* Check if the default format descriptor exists. Use the first
	 * available format otherwise.
	 */
1904 1905
	for (i = stream->nformats; i > 0; --i) {
		format = &stream->format[i-1];
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
		if (format->index == probe->bFormatIndex)
			break;
	}

	if (format->nframes == 0) {
		uvc_printk(KERN_INFO, "No frame descriptor found for the "
			"default format.\n");
		return -EINVAL;
	}

	/* Zero bFrameIndex might be correct. Stream-based formats (including
	 * MPEG-2 TS and DV) do not support frames but have a dummy frame
	 * descriptor with bFrameIndex set to zero. If the default frame
1919
	 * descriptor is not found, use the first available frame.
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
	 */
	for (i = format->nframes; i > 0; --i) {
		frame = &format->frame[i-1];
		if (frame->bFrameIndex == probe->bFrameIndex)
			break;
	}

	probe->bFormatIndex = format->index;
	probe->bFrameIndex = frame->bFrameIndex;

1930
	stream->def_format = format;
1931 1932
	stream->cur_format = format;
	stream->cur_frame = frame;
1933 1934

	/* Select the video decoding function */
1935 1936 1937 1938 1939
	if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
		if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
			stream->decode = uvc_video_decode_isight;
		else if (stream->intf->num_altsetting > 1)
			stream->decode = uvc_video_decode_isoc;
1940
		else
1941
			stream->decode = uvc_video_decode_bulk;
1942
	} else {
1943 1944
		if (stream->intf->num_altsetting == 1)
			stream->decode = uvc_video_encode_bulk;
1945 1946 1947 1948 1949 1950
		else {
			uvc_printk(KERN_INFO, "Isochronous endpoints are not "
				"supported for video output devices.\n");
			return -EINVAL;
		}
	}
1951 1952 1953 1954 1955 1956 1957

	return 0;
}

/*
 * Enable or disable the video stream.
 */
1958
int uvc_video_enable(struct uvc_streaming *stream, int enable)
1959 1960 1961 1962
{
	int ret;

	if (!enable) {
1963
		uvc_uninit_video(stream, 1);
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
		if (stream->intf->num_altsetting > 1) {
			usb_set_interface(stream->dev->udev,
					  stream->intfnum, 0);
		} else {
			/* UVC doesn't specify how to inform a bulk-based device
			 * when the video stream is stopped. Windows sends a
			 * CLEAR_FEATURE(HALT) request to the video streaming
			 * bulk endpoint, mimic the same behaviour.
			 */
			unsigned int epnum = stream->header.bEndpointAddress
					   & USB_ENDPOINT_NUMBER_MASK;
			unsigned int dir = stream->header.bEndpointAddress
					 & USB_ENDPOINT_DIR_MASK;
			unsigned int pipe;

			pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
			usb_clear_halt(stream->dev->udev, pipe);
		}

1983
		uvc_video_clock_cleanup(stream);
1984 1985 1986
		return 0;
	}

1987
	ret = uvc_video_clock_init(stream);
1988
	if (ret < 0)
1989 1990
		return ret;

1991
	/* Commit the streaming parameters. */
1992
	ret = uvc_commit_video(stream, &stream->ctrl);
1993 1994
	if (ret < 0)
		goto error_commit;
1995

1996
	ret = uvc_init_video(stream, GFP_KERNEL);
1997 1998 1999 2000 2001 2002 2003 2004 2005
	if (ret < 0)
		goto error_video;

	return 0;

error_video:
	usb_set_interface(stream->dev->udev, stream->intfnum, 0);
error_commit:
	uvc_video_clock_cleanup(stream);
2006

2007 2008
	return ret;
}