brintos

brintos / linux-shallow public Read only

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