1 /*
2  *	Video for Linux Two
3  *
4  *	A generic video device interface for the LINUX operating system
5  *	using a set of device structures/vectors for low level operations.
6  *
7  *	This file replaces the videodev.c file that comes with the
8  *	regular kernel distribution.
9  *
10  *	This program is free software; you can redistribute it and/or
11  *	modify it under the terms of the GNU General Public License
12  *	as published by the Free Software Foundation; either version
13  *	2 of the License, or (at your option) any later version.
14  *
15  * Author:	Bill Dirks <bill@thedirks.org>
16  *		based on code by Alan Cox, <alan@cymru.net>
17  *
18  */
19 
20 /*
21  * Video capture interface for Linux
22  *
23  *	A generic video device interface for the LINUX operating system
24  *	using a set of device structures/vectors for low level operations.
25  *
26  *		This program is free software; you can redistribute it and/or
27  *		modify it under the terms of the GNU General Public License
28  *		as published by the Free Software Foundation; either version
29  *		2 of the License, or (at your option) any later version.
30  *
31  * Author:	Alan Cox, <alan@lxorguk.ukuu.org.uk>
32  *
33  * Fixes:
34  */
35 
36 /*
37  * Video4linux 1/2 integration by Justin Schoeman
38  * <justin@suntiger.ee.up.ac.za>
39  * 2.4 PROCFS support ported from 2.4 kernels by
40  *  Iñaki García Etxebarria <garetxe@euskalnet.net>
41  * Makefile fix by "W. Michael Petullo" <mike@flyn.org>
42  * 2.4 devfs support ported from 2.4 kernels by
43  *  Dan Merillat <dan@merillat.org>
44  * Added Gerd Knorrs v4l1 enhancements (Justin Schoeman)
45  */
46 
47 #include <linux/module.h>
48 #include <linux/types.h>
49 #include <linux/kernel.h>
50 #include <linux/mm.h>
51 #include <linux/string.h>
52 #include <linux/errno.h>
53 #include <linux/i2c.h>
54 #if defined(CONFIG_SPI)
55 #include <linux/spi/spi.h>
56 #endif
57 #include <asm/uaccess.h>
58 #include <asm/pgtable.h>
59 #include <asm/io.h>
60 #include <asm/div64.h>
61 #include <media/v4l2-common.h>
62 #include <media/v4l2-device.h>
63 #include <media/v4l2-ctrls.h>
64 
65 #include <linux/videodev2.h>
66 
67 MODULE_AUTHOR("Bill Dirks, Justin Schoeman, Gerd Knorr");
68 MODULE_DESCRIPTION("misc helper functions for v4l2 device drivers");
69 MODULE_LICENSE("GPL");
70 
71 /*
72  *
73  *	V 4 L 2   D R I V E R   H E L P E R   A P I
74  *
75  */
76 
77 /*
78  *  Video Standard Operations (contributed by Michael Schimek)
79  */
80 
81 /* Helper functions for control handling			     */
82 
83 /* Check for correctness of the ctrl's value based on the data from
84    struct v4l2_queryctrl and the available menu items. Note that
85    menu_items may be NULL, in that case it is ignored. */
86 int v4l2_ctrl_check(struct v4l2_ext_control *ctrl, struct v4l2_queryctrl *qctrl,
87 		const char * const *menu_items)
88 {
89 	if (qctrl->flags & V4L2_CTRL_FLAG_DISABLED)
90 		return -EINVAL;
91 	if (qctrl->flags & V4L2_CTRL_FLAG_GRABBED)
92 		return -EBUSY;
93 	if (qctrl->type == V4L2_CTRL_TYPE_STRING)
94 		return 0;
95 	if (qctrl->type == V4L2_CTRL_TYPE_BUTTON ||
96 	    qctrl->type == V4L2_CTRL_TYPE_INTEGER64 ||
97 	    qctrl->type == V4L2_CTRL_TYPE_CTRL_CLASS)
98 		return 0;
99 	if (ctrl->value < qctrl->minimum || ctrl->value > qctrl->maximum)
100 		return -ERANGE;
101 	if (qctrl->type == V4L2_CTRL_TYPE_MENU && menu_items != NULL) {
102 		if (menu_items[ctrl->value] == NULL ||
103 		    menu_items[ctrl->value][0] == '\0')
104 			return -EINVAL;
105 	}
106 	if (qctrl->type == V4L2_CTRL_TYPE_BITMASK &&
107 			(ctrl->value & ~qctrl->maximum))
108 		return -ERANGE;
109 	return 0;
110 }
111 EXPORT_SYMBOL(v4l2_ctrl_check);
112 
113 /* Fill in a struct v4l2_queryctrl */
114 int v4l2_ctrl_query_fill(struct v4l2_queryctrl *qctrl, s32 min, s32 max, s32 step, s32 def)
115 {
116 	const char *name;
117 
118 	v4l2_ctrl_fill(qctrl->id, &name, &qctrl->type,
119 		       &min, &max, &step, &def, &qctrl->flags);
120 
121 	if (name == NULL)
122 		return -EINVAL;
123 
124 	qctrl->minimum = min;
125 	qctrl->maximum = max;
126 	qctrl->step = step;
127 	qctrl->default_value = def;
128 	qctrl->reserved[0] = qctrl->reserved[1] = 0;
129 	strlcpy(qctrl->name, name, sizeof(qctrl->name));
130 	return 0;
131 }
132 EXPORT_SYMBOL(v4l2_ctrl_query_fill);
133 
134 /* Fill in a struct v4l2_querymenu based on the struct v4l2_queryctrl and
135    the menu. The qctrl pointer may be NULL, in which case it is ignored.
136    If menu_items is NULL, then the menu items are retrieved using
137    v4l2_ctrl_get_menu. */
138 int v4l2_ctrl_query_menu(struct v4l2_querymenu *qmenu, struct v4l2_queryctrl *qctrl,
139 	       const char * const *menu_items)
140 {
141 	int i;
142 
143 	qmenu->reserved = 0;
144 	if (menu_items == NULL)
145 		menu_items = v4l2_ctrl_get_menu(qmenu->id);
146 	if (menu_items == NULL ||
147 	    (qctrl && (qmenu->index < qctrl->minimum || qmenu->index > qctrl->maximum)))
148 		return -EINVAL;
149 	for (i = 0; i < qmenu->index && menu_items[i]; i++) ;
150 	if (menu_items[i] == NULL || menu_items[i][0] == '\0')
151 		return -EINVAL;
152 	strlcpy(qmenu->name, menu_items[qmenu->index], sizeof(qmenu->name));
153 	return 0;
154 }
155 EXPORT_SYMBOL(v4l2_ctrl_query_menu);
156 
157 /* Fill in a struct v4l2_querymenu based on the specified array of valid
158    menu items (terminated by V4L2_CTRL_MENU_IDS_END).
159    Use this if there are 'holes' in the list of valid menu items. */
160 int v4l2_ctrl_query_menu_valid_items(struct v4l2_querymenu *qmenu, const u32 *ids)
161 {
162 	const char * const *menu_items = v4l2_ctrl_get_menu(qmenu->id);
163 
164 	qmenu->reserved = 0;
165 	if (menu_items == NULL || ids == NULL)
166 		return -EINVAL;
167 	while (*ids != V4L2_CTRL_MENU_IDS_END) {
168 		if (*ids++ == qmenu->index) {
169 			strlcpy(qmenu->name, menu_items[qmenu->index],
170 					sizeof(qmenu->name));
171 			return 0;
172 		}
173 	}
174 	return -EINVAL;
175 }
176 EXPORT_SYMBOL(v4l2_ctrl_query_menu_valid_items);
177 
178 /* ctrl_classes points to an array of u32 pointers, the last element is
179    a NULL pointer. Each u32 array is a 0-terminated array of control IDs.
180    Each array must be sorted low to high and belong to the same control
181    class. The array of u32 pointers must also be sorted, from low class IDs
182    to high class IDs.
183 
184    This function returns the first ID that follows after the given ID.
185    When no more controls are available 0 is returned. */
186 u32 v4l2_ctrl_next(const u32 * const * ctrl_classes, u32 id)
187 {
188 	u32 ctrl_class = V4L2_CTRL_ID2CLASS(id);
189 	const u32 *pctrl;
190 
191 	if (ctrl_classes == NULL)
192 		return 0;
193 
194 	/* if no query is desired, then check if the ID is part of ctrl_classes */
195 	if ((id & V4L2_CTRL_FLAG_NEXT_CTRL) == 0) {
196 		/* find class */
197 		while (*ctrl_classes && V4L2_CTRL_ID2CLASS(**ctrl_classes) != ctrl_class)
198 			ctrl_classes++;
199 		if (*ctrl_classes == NULL)
200 			return 0;
201 		pctrl = *ctrl_classes;
202 		/* find control ID */
203 		while (*pctrl && *pctrl != id) pctrl++;
204 		return *pctrl ? id : 0;
205 	}
206 	id &= V4L2_CTRL_ID_MASK;
207 	id++;	/* select next control */
208 	/* find first class that matches (or is greater than) the class of
209 	   the ID */
210 	while (*ctrl_classes && V4L2_CTRL_ID2CLASS(**ctrl_classes) < ctrl_class)
211 		ctrl_classes++;
212 	/* no more classes */
213 	if (*ctrl_classes == NULL)
214 		return 0;
215 	pctrl = *ctrl_classes;
216 	/* find first ctrl within the class that is >= ID */
217 	while (*pctrl && *pctrl < id) pctrl++;
218 	if (*pctrl)
219 		return *pctrl;
220 	/* we are at the end of the controls of the current class. */
221 	/* continue with next class if available */
222 	ctrl_classes++;
223 	if (*ctrl_classes == NULL)
224 		return 0;
225 	return **ctrl_classes;
226 }
227 EXPORT_SYMBOL(v4l2_ctrl_next);
228 
229 /* I2C Helper functions */
230 
231 #if IS_ENABLED(CONFIG_I2C)
232 
233 void v4l2_i2c_subdev_init(struct v4l2_subdev *sd, struct i2c_client *client,
234 		const struct v4l2_subdev_ops *ops)
235 {
236 	v4l2_subdev_init(sd, ops);
237 	sd->flags |= V4L2_SUBDEV_FL_IS_I2C;
238 	/* the owner is the same as the i2c_client's driver owner */
239 	sd->owner = client->driver->driver.owner;
240 	sd->dev = &client->dev;
241 	/* i2c_client and v4l2_subdev point to one another */
242 	v4l2_set_subdevdata(sd, client);
243 	i2c_set_clientdata(client, sd);
244 	/* initialize name */
245 	snprintf(sd->name, sizeof(sd->name), "%s %d-%04x",
246 		client->driver->driver.name, i2c_adapter_id(client->adapter),
247 		client->addr);
248 }
249 EXPORT_SYMBOL_GPL(v4l2_i2c_subdev_init);
250 
251 /* Load an i2c sub-device. */
252 struct v4l2_subdev *v4l2_i2c_new_subdev_board(struct v4l2_device *v4l2_dev,
253 		struct i2c_adapter *adapter, struct i2c_board_info *info,
254 		const unsigned short *probe_addrs)
255 {
256 	struct v4l2_subdev *sd = NULL;
257 	struct i2c_client *client;
258 
259 	BUG_ON(!v4l2_dev);
260 
261 	request_module(I2C_MODULE_PREFIX "%s", info->type);
262 
263 	/* Create the i2c client */
264 	if (info->addr == 0 && probe_addrs)
265 		client = i2c_new_probed_device(adapter, info, probe_addrs,
266 					       NULL);
267 	else
268 		client = i2c_new_device(adapter, info);
269 
270 	/* Note: by loading the module first we are certain that c->driver
271 	   will be set if the driver was found. If the module was not loaded
272 	   first, then the i2c core tries to delay-load the module for us,
273 	   and then c->driver is still NULL until the module is finally
274 	   loaded. This delay-load mechanism doesn't work if other drivers
275 	   want to use the i2c device, so explicitly loading the module
276 	   is the best alternative. */
277 	if (client == NULL || client->driver == NULL)
278 		goto error;
279 
280 	/* Lock the module so we can safely get the v4l2_subdev pointer */
281 	if (!try_module_get(client->driver->driver.owner))
282 		goto error;
283 	sd = i2c_get_clientdata(client);
284 
285 	/* Register with the v4l2_device which increases the module's
286 	   use count as well. */
287 	if (v4l2_device_register_subdev(v4l2_dev, sd))
288 		sd = NULL;
289 	/* Decrease the module use count to match the first try_module_get. */
290 	module_put(client->driver->driver.owner);
291 
292 error:
293 	/* If we have a client but no subdev, then something went wrong and
294 	   we must unregister the client. */
295 	if (client && sd == NULL)
296 		i2c_unregister_device(client);
297 	return sd;
298 }
299 EXPORT_SYMBOL_GPL(v4l2_i2c_new_subdev_board);
300 
301 struct v4l2_subdev *v4l2_i2c_new_subdev(struct v4l2_device *v4l2_dev,
302 		struct i2c_adapter *adapter, const char *client_type,
303 		u8 addr, const unsigned short *probe_addrs)
304 {
305 	struct i2c_board_info info;
306 
307 	/* Setup the i2c board info with the device type and
308 	   the device address. */
309 	memset(&info, 0, sizeof(info));
310 	strlcpy(info.type, client_type, sizeof(info.type));
311 	info.addr = addr;
312 
313 	return v4l2_i2c_new_subdev_board(v4l2_dev, adapter, &info, probe_addrs);
314 }
315 EXPORT_SYMBOL_GPL(v4l2_i2c_new_subdev);
316 
317 /* Return i2c client address of v4l2_subdev. */
318 unsigned short v4l2_i2c_subdev_addr(struct v4l2_subdev *sd)
319 {
320 	struct i2c_client *client = v4l2_get_subdevdata(sd);
321 
322 	return client ? client->addr : I2C_CLIENT_END;
323 }
324 EXPORT_SYMBOL_GPL(v4l2_i2c_subdev_addr);
325 
326 /* Return a list of I2C tuner addresses to probe. Use only if the tuner
327    addresses are unknown. */
328 const unsigned short *v4l2_i2c_tuner_addrs(enum v4l2_i2c_tuner_type type)
329 {
330 	static const unsigned short radio_addrs[] = {
331 #if IS_ENABLED(CONFIG_MEDIA_TUNER_TEA5761)
332 		0x10,
333 #endif
334 		0x60,
335 		I2C_CLIENT_END
336 	};
337 	static const unsigned short demod_addrs[] = {
338 		0x42, 0x43, 0x4a, 0x4b,
339 		I2C_CLIENT_END
340 	};
341 	static const unsigned short tv_addrs[] = {
342 		0x42, 0x43, 0x4a, 0x4b,		/* tda8290 */
343 		0x60, 0x61, 0x62, 0x63, 0x64,
344 		I2C_CLIENT_END
345 	};
346 
347 	switch (type) {
348 	case ADDRS_RADIO:
349 		return radio_addrs;
350 	case ADDRS_DEMOD:
351 		return demod_addrs;
352 	case ADDRS_TV:
353 		return tv_addrs;
354 	case ADDRS_TV_WITH_DEMOD:
355 		return tv_addrs + 4;
356 	}
357 	return NULL;
358 }
359 EXPORT_SYMBOL_GPL(v4l2_i2c_tuner_addrs);
360 
361 #endif /* defined(CONFIG_I2C) */
362 
363 #if defined(CONFIG_SPI)
364 
365 /* Load an spi sub-device. */
366 
367 void v4l2_spi_subdev_init(struct v4l2_subdev *sd, struct spi_device *spi,
368 		const struct v4l2_subdev_ops *ops)
369 {
370 	v4l2_subdev_init(sd, ops);
371 	sd->flags |= V4L2_SUBDEV_FL_IS_SPI;
372 	/* the owner is the same as the spi_device's driver owner */
373 	sd->owner = spi->dev.driver->owner;
374 	sd->dev = &spi->dev;
375 	/* spi_device and v4l2_subdev point to one another */
376 	v4l2_set_subdevdata(sd, spi);
377 	spi_set_drvdata(spi, sd);
378 	/* initialize name */
379 	strlcpy(sd->name, spi->dev.driver->name, sizeof(sd->name));
380 }
381 EXPORT_SYMBOL_GPL(v4l2_spi_subdev_init);
382 
383 struct v4l2_subdev *v4l2_spi_new_subdev(struct v4l2_device *v4l2_dev,
384 		struct spi_master *master, struct spi_board_info *info)
385 {
386 	struct v4l2_subdev *sd = NULL;
387 	struct spi_device *spi = NULL;
388 
389 	BUG_ON(!v4l2_dev);
390 
391 	if (info->modalias[0])
392 		request_module(info->modalias);
393 
394 	spi = spi_new_device(master, info);
395 
396 	if (spi == NULL || spi->dev.driver == NULL)
397 		goto error;
398 
399 	if (!try_module_get(spi->dev.driver->owner))
400 		goto error;
401 
402 	sd = spi_get_drvdata(spi);
403 
404 	/* Register with the v4l2_device which increases the module's
405 	   use count as well. */
406 	if (v4l2_device_register_subdev(v4l2_dev, sd))
407 		sd = NULL;
408 
409 	/* Decrease the module use count to match the first try_module_get. */
410 	module_put(spi->dev.driver->owner);
411 
412 error:
413 	/* If we have a client but no subdev, then something went wrong and
414 	   we must unregister the client. */
415 	if (spi && sd == NULL)
416 		spi_unregister_device(spi);
417 
418 	return sd;
419 }
420 EXPORT_SYMBOL_GPL(v4l2_spi_new_subdev);
421 
422 #endif /* defined(CONFIG_SPI) */
423 
424 /* Clamp x to be between min and max, aligned to a multiple of 2^align.  min
425  * and max don't have to be aligned, but there must be at least one valid
426  * value.  E.g., min=17,max=31,align=4 is not allowed as there are no multiples
427  * of 16 between 17 and 31.  */
428 static unsigned int clamp_align(unsigned int x, unsigned int min,
429 				unsigned int max, unsigned int align)
430 {
431 	/* Bits that must be zero to be aligned */
432 	unsigned int mask = ~((1 << align) - 1);
433 
434 	/* Round to nearest aligned value */
435 	if (align)
436 		x = (x + (1 << (align - 1))) & mask;
437 
438 	/* Clamp to aligned value of min and max */
439 	if (x < min)
440 		x = (min + ~mask) & mask;
441 	else if (x > max)
442 		x = max & mask;
443 
444 	return x;
445 }
446 
447 /* Bound an image to have a width between wmin and wmax, and height between
448  * hmin and hmax, inclusive.  Additionally, the width will be a multiple of
449  * 2^walign, the height will be a multiple of 2^halign, and the overall size
450  * (width*height) will be a multiple of 2^salign.  The image may be shrunk
451  * or enlarged to fit the alignment constraints.
452  *
453  * The width or height maximum must not be smaller than the corresponding
454  * minimum.  The alignments must not be so high there are no possible image
455  * sizes within the allowed bounds.  wmin and hmin must be at least 1
456  * (don't use 0).  If you don't care about a certain alignment, specify 0,
457  * as 2^0 is 1 and one byte alignment is equivalent to no alignment.  If
458  * you only want to adjust downward, specify a maximum that's the same as
459  * the initial value.
460  */
461 void v4l_bound_align_image(u32 *w, unsigned int wmin, unsigned int wmax,
462 			   unsigned int walign,
463 			   u32 *h, unsigned int hmin, unsigned int hmax,
464 			   unsigned int halign, unsigned int salign)
465 {
466 	*w = clamp_align(*w, wmin, wmax, walign);
467 	*h = clamp_align(*h, hmin, hmax, halign);
468 
469 	/* Usually we don't need to align the size and are done now. */
470 	if (!salign)
471 		return;
472 
473 	/* How much alignment do we have? */
474 	walign = __ffs(*w);
475 	halign = __ffs(*h);
476 	/* Enough to satisfy the image alignment? */
477 	if (walign + halign < salign) {
478 		/* Max walign where there is still a valid width */
479 		unsigned int wmaxa = __fls(wmax ^ (wmin - 1));
480 		/* Max halign where there is still a valid height */
481 		unsigned int hmaxa = __fls(hmax ^ (hmin - 1));
482 
483 		/* up the smaller alignment until we have enough */
484 		do {
485 			if (halign >= hmaxa ||
486 			    (walign <= halign && walign < wmaxa)) {
487 				*w = clamp_align(*w, wmin, wmax, walign + 1);
488 				walign = __ffs(*w);
489 			} else {
490 				*h = clamp_align(*h, hmin, hmax, halign + 1);
491 				halign = __ffs(*h);
492 			}
493 		} while (halign + walign < salign);
494 	}
495 }
496 EXPORT_SYMBOL_GPL(v4l_bound_align_image);
497 
498 /**
499  * v4l_match_dv_timings - check if two timings match
500  * @t1 - compare this v4l2_dv_timings struct...
501  * @t2 - with this struct.
502  * @pclock_delta - the allowed pixelclock deviation.
503  *
504  * Compare t1 with t2 with a given margin of error for the pixelclock.
505  */
506 bool v4l_match_dv_timings(const struct v4l2_dv_timings *t1,
507 			  const struct v4l2_dv_timings *t2,
508 			  unsigned pclock_delta)
509 {
510 	if (t1->type != t2->type || t1->type != V4L2_DV_BT_656_1120)
511 		return false;
512 	if (t1->bt.width == t2->bt.width &&
513 	    t1->bt.height == t2->bt.height &&
514 	    t1->bt.interlaced == t2->bt.interlaced &&
515 	    t1->bt.polarities == t2->bt.polarities &&
516 	    t1->bt.pixelclock >= t2->bt.pixelclock - pclock_delta &&
517 	    t1->bt.pixelclock <= t2->bt.pixelclock + pclock_delta &&
518 	    t1->bt.hfrontporch == t2->bt.hfrontporch &&
519 	    t1->bt.vfrontporch == t2->bt.vfrontporch &&
520 	    t1->bt.vsync == t2->bt.vsync &&
521 	    t1->bt.vbackporch == t2->bt.vbackporch &&
522 	    (!t1->bt.interlaced ||
523 		(t1->bt.il_vfrontporch == t2->bt.il_vfrontporch &&
524 		 t1->bt.il_vsync == t2->bt.il_vsync &&
525 		 t1->bt.il_vbackporch == t2->bt.il_vbackporch)))
526 		return true;
527 	return false;
528 }
529 EXPORT_SYMBOL_GPL(v4l_match_dv_timings);
530 
531 /*
532  * CVT defines
533  * Based on Coordinated Video Timings Standard
534  * version 1.1 September 10, 2003
535  */
536 
537 #define CVT_PXL_CLK_GRAN	250000	/* pixel clock granularity */
538 
539 /* Normal blanking */
540 #define CVT_MIN_V_BPORCH	7	/* lines */
541 #define CVT_MIN_V_PORCH_RND	3	/* lines */
542 #define CVT_MIN_VSYNC_BP	550	/* min time of vsync + back porch (us) */
543 
544 /* Normal blanking for CVT uses GTF to calculate horizontal blanking */
545 #define CVT_CELL_GRAN		8	/* character cell granularity */
546 #define CVT_M			600	/* blanking formula gradient */
547 #define CVT_C			40	/* blanking formula offset */
548 #define CVT_K			128	/* blanking formula scaling factor */
549 #define CVT_J			20	/* blanking formula scaling factor */
550 #define CVT_C_PRIME (((CVT_C - CVT_J) * CVT_K / 256) + CVT_J)
551 #define CVT_M_PRIME (CVT_K * CVT_M / 256)
552 
553 /* Reduced Blanking */
554 #define CVT_RB_MIN_V_BPORCH    7       /* lines  */
555 #define CVT_RB_V_FPORCH        3       /* lines  */
556 #define CVT_RB_MIN_V_BLANK   460     /* us     */
557 #define CVT_RB_H_SYNC         32       /* pixels */
558 #define CVT_RB_H_BPORCH       80       /* pixels */
559 #define CVT_RB_H_BLANK       160       /* pixels */
560 
561 /** v4l2_detect_cvt - detect if the given timings follow the CVT standard
562  * @frame_height - the total height of the frame (including blanking) in lines.
563  * @hfreq - the horizontal frequency in Hz.
564  * @vsync - the height of the vertical sync in lines.
565  * @polarities - the horizontal and vertical polarities (same as struct
566  *		v4l2_bt_timings polarities).
567  * @fmt - the resulting timings.
568  *
569  * This function will attempt to detect if the given values correspond to a
570  * valid CVT format. If so, then it will return true, and fmt will be filled
571  * in with the found CVT timings.
572  */
573 bool v4l2_detect_cvt(unsigned frame_height, unsigned hfreq, unsigned vsync,
574 		u32 polarities, struct v4l2_dv_timings *fmt)
575 {
576 	int  v_fp, v_bp, h_fp, h_bp, hsync;
577 	int  frame_width, image_height, image_width;
578 	bool reduced_blanking;
579 	unsigned pix_clk;
580 
581 	if (vsync < 4 || vsync > 7)
582 		return false;
583 
584 	if (polarities == V4L2_DV_VSYNC_POS_POL)
585 		reduced_blanking = false;
586 	else if (polarities == V4L2_DV_HSYNC_POS_POL)
587 		reduced_blanking = true;
588 	else
589 		return false;
590 
591 	/* Vertical */
592 	if (reduced_blanking) {
593 		v_fp = CVT_RB_V_FPORCH;
594 		v_bp = (CVT_RB_MIN_V_BLANK * hfreq + 999999) / 1000000;
595 		v_bp -= vsync + v_fp;
596 
597 		if (v_bp < CVT_RB_MIN_V_BPORCH)
598 			v_bp = CVT_RB_MIN_V_BPORCH;
599 	} else {
600 		v_fp = CVT_MIN_V_PORCH_RND;
601 		v_bp = (CVT_MIN_VSYNC_BP * hfreq + 999999) / 1000000 - vsync;
602 
603 		if (v_bp < CVT_MIN_V_BPORCH)
604 			v_bp = CVT_MIN_V_BPORCH;
605 	}
606 	image_height = (frame_height - v_fp - vsync - v_bp + 1) & ~0x1;
607 
608 	/* Aspect ratio based on vsync */
609 	switch (vsync) {
610 	case 4:
611 		image_width = (image_height * 4) / 3;
612 		break;
613 	case 5:
614 		image_width = (image_height * 16) / 9;
615 		break;
616 	case 6:
617 		image_width = (image_height * 16) / 10;
618 		break;
619 	case 7:
620 		/* special case */
621 		if (image_height == 1024)
622 			image_width = (image_height * 5) / 4;
623 		else if (image_height == 768)
624 			image_width = (image_height * 15) / 9;
625 		else
626 			return false;
627 		break;
628 	default:
629 		return false;
630 	}
631 
632 	image_width = image_width & ~7;
633 
634 	/* Horizontal */
635 	if (reduced_blanking) {
636 		pix_clk = (image_width + CVT_RB_H_BLANK) * hfreq;
637 		pix_clk = (pix_clk / CVT_PXL_CLK_GRAN) * CVT_PXL_CLK_GRAN;
638 
639 		h_bp = CVT_RB_H_BPORCH;
640 		hsync = CVT_RB_H_SYNC;
641 		h_fp = CVT_RB_H_BLANK - h_bp - hsync;
642 
643 		frame_width = image_width + CVT_RB_H_BLANK;
644 	} else {
645 		int h_blank;
646 		unsigned ideal_duty_cycle = CVT_C_PRIME - (CVT_M_PRIME * 1000) / hfreq;
647 
648 		h_blank = (image_width * ideal_duty_cycle + (100 - ideal_duty_cycle) / 2) /
649 						(100 - ideal_duty_cycle);
650 		h_blank = h_blank - h_blank % (2 * CVT_CELL_GRAN);
651 
652 		if (h_blank * 100 / image_width < 20) {
653 			h_blank = image_width / 5;
654 			h_blank = (h_blank + 0x7) & ~0x7;
655 		}
656 
657 		pix_clk = (image_width + h_blank) * hfreq;
658 		pix_clk = (pix_clk / CVT_PXL_CLK_GRAN) * CVT_PXL_CLK_GRAN;
659 
660 		h_bp = h_blank / 2;
661 		frame_width = image_width + h_blank;
662 
663 		hsync = (frame_width * 8 + 50) / 100;
664 		hsync = hsync - hsync % CVT_CELL_GRAN;
665 		h_fp = h_blank - hsync - h_bp;
666 	}
667 
668 	fmt->bt.polarities = polarities;
669 	fmt->bt.width = image_width;
670 	fmt->bt.height = image_height;
671 	fmt->bt.hfrontporch = h_fp;
672 	fmt->bt.vfrontporch = v_fp;
673 	fmt->bt.hsync = hsync;
674 	fmt->bt.vsync = vsync;
675 	fmt->bt.hbackporch = frame_width - image_width - h_fp - hsync;
676 	fmt->bt.vbackporch = frame_height - image_height - v_fp - vsync;
677 	fmt->bt.pixelclock = pix_clk;
678 	fmt->bt.standards = V4L2_DV_BT_STD_CVT;
679 	if (reduced_blanking)
680 		fmt->bt.flags |= V4L2_DV_FL_REDUCED_BLANKING;
681 	return true;
682 }
683 EXPORT_SYMBOL_GPL(v4l2_detect_cvt);
684 
685 /*
686  * GTF defines
687  * Based on Generalized Timing Formula Standard
688  * Version 1.1 September 2, 1999
689  */
690 
691 #define GTF_PXL_CLK_GRAN	250000	/* pixel clock granularity */
692 
693 #define GTF_MIN_VSYNC_BP	550	/* min time of vsync + back porch (us) */
694 #define GTF_V_FP		1	/* vertical front porch (lines) */
695 #define GTF_CELL_GRAN		8	/* character cell granularity */
696 
697 /* Default */
698 #define GTF_D_M			600	/* blanking formula gradient */
699 #define GTF_D_C			40	/* blanking formula offset */
700 #define GTF_D_K			128	/* blanking formula scaling factor */
701 #define GTF_D_J			20	/* blanking formula scaling factor */
702 #define GTF_D_C_PRIME ((((GTF_D_C - GTF_D_J) * GTF_D_K) / 256) + GTF_D_J)
703 #define GTF_D_M_PRIME ((GTF_D_K * GTF_D_M) / 256)
704 
705 /* Secondary */
706 #define GTF_S_M			3600	/* blanking formula gradient */
707 #define GTF_S_C			40	/* blanking formula offset */
708 #define GTF_S_K			128	/* blanking formula scaling factor */
709 #define GTF_S_J			35	/* blanking formula scaling factor */
710 #define GTF_S_C_PRIME ((((GTF_S_C - GTF_S_J) * GTF_S_K) / 256) + GTF_S_J)
711 #define GTF_S_M_PRIME ((GTF_S_K * GTF_S_M) / 256)
712 
713 /** v4l2_detect_gtf - detect if the given timings follow the GTF standard
714  * @frame_height - the total height of the frame (including blanking) in lines.
715  * @hfreq - the horizontal frequency in Hz.
716  * @vsync - the height of the vertical sync in lines.
717  * @polarities - the horizontal and vertical polarities (same as struct
718  *		v4l2_bt_timings polarities).
719  * @aspect - preferred aspect ratio. GTF has no method of determining the
720  *		aspect ratio in order to derive the image width from the
721  *		image height, so it has to be passed explicitly. Usually
722  *		the native screen aspect ratio is used for this. If it
723  *		is not filled in correctly, then 16:9 will be assumed.
724  * @fmt - the resulting timings.
725  *
726  * This function will attempt to detect if the given values correspond to a
727  * valid GTF format. If so, then it will return true, and fmt will be filled
728  * in with the found GTF timings.
729  */
730 bool v4l2_detect_gtf(unsigned frame_height,
731 		unsigned hfreq,
732 		unsigned vsync,
733 		u32 polarities,
734 		struct v4l2_fract aspect,
735 		struct v4l2_dv_timings *fmt)
736 {
737 	int pix_clk;
738 	int  v_fp, v_bp, h_fp, hsync;
739 	int frame_width, image_height, image_width;
740 	bool default_gtf;
741 	int h_blank;
742 
743 	if (vsync != 3)
744 		return false;
745 
746 	if (polarities == V4L2_DV_VSYNC_POS_POL)
747 		default_gtf = true;
748 	else if (polarities == V4L2_DV_HSYNC_POS_POL)
749 		default_gtf = false;
750 	else
751 		return false;
752 
753 	/* Vertical */
754 	v_fp = GTF_V_FP;
755 	v_bp = (GTF_MIN_VSYNC_BP * hfreq + 999999) / 1000000 - vsync;
756 	image_height = (frame_height - v_fp - vsync - v_bp + 1) & ~0x1;
757 
758 	if (aspect.numerator == 0 || aspect.denominator == 0) {
759 		aspect.numerator = 16;
760 		aspect.denominator = 9;
761 	}
762 	image_width = ((image_height * aspect.numerator) / aspect.denominator);
763 
764 	/* Horizontal */
765 	if (default_gtf)
766 		h_blank = ((image_width * GTF_D_C_PRIME * hfreq) -
767 					(image_width * GTF_D_M_PRIME * 1000) +
768 			(hfreq * (100 - GTF_D_C_PRIME) + GTF_D_M_PRIME * 1000) / 2) /
769 			(hfreq * (100 - GTF_D_C_PRIME) + GTF_D_M_PRIME * 1000);
770 	else
771 		h_blank = ((image_width * GTF_S_C_PRIME * hfreq) -
772 					(image_width * GTF_S_M_PRIME * 1000) +
773 			(hfreq * (100 - GTF_S_C_PRIME) + GTF_S_M_PRIME * 1000) / 2) /
774 			(hfreq * (100 - GTF_S_C_PRIME) + GTF_S_M_PRIME * 1000);
775 
776 	h_blank = h_blank - h_blank % (2 * GTF_CELL_GRAN);
777 	frame_width = image_width + h_blank;
778 
779 	pix_clk = (image_width + h_blank) * hfreq;
780 	pix_clk = pix_clk / GTF_PXL_CLK_GRAN * GTF_PXL_CLK_GRAN;
781 
782 	hsync = (frame_width * 8 + 50) / 100;
783 	hsync = hsync - hsync % GTF_CELL_GRAN;
784 
785 	h_fp = h_blank / 2 - hsync;
786 
787 	fmt->bt.polarities = polarities;
788 	fmt->bt.width = image_width;
789 	fmt->bt.height = image_height;
790 	fmt->bt.hfrontporch = h_fp;
791 	fmt->bt.vfrontporch = v_fp;
792 	fmt->bt.hsync = hsync;
793 	fmt->bt.vsync = vsync;
794 	fmt->bt.hbackporch = frame_width - image_width - h_fp - hsync;
795 	fmt->bt.vbackporch = frame_height - image_height - v_fp - vsync;
796 	fmt->bt.pixelclock = pix_clk;
797 	fmt->bt.standards = V4L2_DV_BT_STD_GTF;
798 	if (!default_gtf)
799 		fmt->bt.flags |= V4L2_DV_FL_REDUCED_BLANKING;
800 	return true;
801 }
802 EXPORT_SYMBOL_GPL(v4l2_detect_gtf);
803 
804 /** v4l2_calc_aspect_ratio - calculate the aspect ratio based on bytes
805  *	0x15 and 0x16 from the EDID.
806  * @hor_landscape - byte 0x15 from the EDID.
807  * @vert_portrait - byte 0x16 from the EDID.
808  *
809  * Determines the aspect ratio from the EDID.
810  * See VESA Enhanced EDID standard, release A, rev 2, section 3.6.2:
811  * "Horizontal and Vertical Screen Size or Aspect Ratio"
812  */
813 struct v4l2_fract v4l2_calc_aspect_ratio(u8 hor_landscape, u8 vert_portrait)
814 {
815 	struct v4l2_fract aspect = { 16, 9 };
816 	u32 tmp;
817 	u8 ratio;
818 
819 	/* Nothing filled in, fallback to 16:9 */
820 	if (!hor_landscape && !vert_portrait)
821 		return aspect;
822 	/* Both filled in, so they are interpreted as the screen size in cm */
823 	if (hor_landscape && vert_portrait) {
824 		aspect.numerator = hor_landscape;
825 		aspect.denominator = vert_portrait;
826 		return aspect;
827 	}
828 	/* Only one is filled in, so interpret them as a ratio:
829 	   (val + 99) / 100 */
830 	ratio = hor_landscape | vert_portrait;
831 	/* Change some rounded values into the exact aspect ratio */
832 	if (ratio == 79) {
833 		aspect.numerator = 16;
834 		aspect.denominator = 9;
835 	} else if (ratio == 34) {
836 		aspect.numerator = 4;
837 		aspect.numerator = 3;
838 	} else if (ratio == 68) {
839 		aspect.numerator = 15;
840 		aspect.numerator = 9;
841 	} else {
842 		aspect.numerator = hor_landscape + 99;
843 		aspect.denominator = 100;
844 	}
845 	if (hor_landscape)
846 		return aspect;
847 	/* The aspect ratio is for portrait, so swap numerator and denominator */
848 	tmp = aspect.denominator;
849 	aspect.denominator = aspect.numerator;
850 	aspect.numerator = tmp;
851 	return aspect;
852 }
853 EXPORT_SYMBOL_GPL(v4l2_calc_aspect_ratio);
854 
855 const struct v4l2_frmsize_discrete *v4l2_find_nearest_format(
856 		const struct v4l2_discrete_probe *probe,
857 		s32 width, s32 height)
858 {
859 	int i;
860 	u32 error, min_error = UINT_MAX;
861 	const struct v4l2_frmsize_discrete *size, *best = NULL;
862 
863 	if (!probe)
864 		return best;
865 
866 	for (i = 0, size = probe->sizes; i < probe->num_sizes; i++, size++) {
867 		error = abs(size->width - width) + abs(size->height - height);
868 		if (error < min_error) {
869 			min_error = error;
870 			best = size;
871 		}
872 		if (!error)
873 			break;
874 	}
875 
876 	return best;
877 }
878 EXPORT_SYMBOL_GPL(v4l2_find_nearest_format);
879 
880 void v4l2_get_timestamp(struct timeval *tv)
881 {
882 	struct timespec ts;
883 
884 	ktime_get_ts(&ts);
885 	tv->tv_sec = ts.tv_sec;
886 	tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
887 }
888 EXPORT_SYMBOL_GPL(v4l2_get_timestamp);
889