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