xref: /openbmc/linux/drivers/media/v4l2-core/v4l2-ctrls-core.c (revision 8268d067508b0fb9988b5423a8539a21caba5f44)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * V4L2 controls framework core implementation.
4  *
5  * Copyright (C) 2010-2021  Hans Verkuil <hverkuil-cisco@xs4all.nl>
6  */
7 
8 #include <linux/export.h>
9 #include <linux/mm.h>
10 #include <linux/slab.h>
11 #include <media/v4l2-ctrls.h>
12 #include <media/v4l2-event.h>
13 #include <media/v4l2-fwnode.h>
14 
15 #include "v4l2-ctrls-priv.h"
16 
17 static const union v4l2_ctrl_ptr ptr_null;
18 
19 static void fill_event(struct v4l2_event *ev, struct v4l2_ctrl *ctrl,
20 		       u32 changes)
21 {
22 	memset(ev, 0, sizeof(*ev));
23 	ev->type = V4L2_EVENT_CTRL;
24 	ev->id = ctrl->id;
25 	ev->u.ctrl.changes = changes;
26 	ev->u.ctrl.type = ctrl->type;
27 	ev->u.ctrl.flags = user_flags(ctrl);
28 	if (ctrl->is_ptr)
29 		ev->u.ctrl.value64 = 0;
30 	else
31 		ev->u.ctrl.value64 = *ctrl->p_cur.p_s64;
32 	ev->u.ctrl.minimum = ctrl->minimum;
33 	ev->u.ctrl.maximum = ctrl->maximum;
34 	if (ctrl->type == V4L2_CTRL_TYPE_MENU
35 	    || ctrl->type == V4L2_CTRL_TYPE_INTEGER_MENU)
36 		ev->u.ctrl.step = 1;
37 	else
38 		ev->u.ctrl.step = ctrl->step;
39 	ev->u.ctrl.default_value = ctrl->default_value;
40 }
41 
42 void send_initial_event(struct v4l2_fh *fh, struct v4l2_ctrl *ctrl)
43 {
44 	struct v4l2_event ev;
45 	u32 changes = V4L2_EVENT_CTRL_CH_FLAGS;
46 
47 	if (!(ctrl->flags & V4L2_CTRL_FLAG_WRITE_ONLY))
48 		changes |= V4L2_EVENT_CTRL_CH_VALUE;
49 	fill_event(&ev, ctrl, changes);
50 	v4l2_event_queue_fh(fh, &ev);
51 }
52 
53 void send_event(struct v4l2_fh *fh, struct v4l2_ctrl *ctrl, u32 changes)
54 {
55 	struct v4l2_event ev;
56 	struct v4l2_subscribed_event *sev;
57 
58 	if (list_empty(&ctrl->ev_subs))
59 		return;
60 	fill_event(&ev, ctrl, changes);
61 
62 	list_for_each_entry(sev, &ctrl->ev_subs, node)
63 		if (sev->fh != fh ||
64 		    (sev->flags & V4L2_EVENT_SUB_FL_ALLOW_FEEDBACK))
65 			v4l2_event_queue_fh(sev->fh, &ev);
66 }
67 
68 static bool std_equal(const struct v4l2_ctrl *ctrl, u32 idx,
69 		      union v4l2_ctrl_ptr ptr1,
70 		      union v4l2_ctrl_ptr ptr2)
71 {
72 	switch (ctrl->type) {
73 	case V4L2_CTRL_TYPE_BUTTON:
74 		return false;
75 	case V4L2_CTRL_TYPE_STRING:
76 		idx *= ctrl->elem_size;
77 		/* strings are always 0-terminated */
78 		return !strcmp(ptr1.p_char + idx, ptr2.p_char + idx);
79 	case V4L2_CTRL_TYPE_INTEGER64:
80 		return ptr1.p_s64[idx] == ptr2.p_s64[idx];
81 	case V4L2_CTRL_TYPE_U8:
82 		return ptr1.p_u8[idx] == ptr2.p_u8[idx];
83 	case V4L2_CTRL_TYPE_U16:
84 		return ptr1.p_u16[idx] == ptr2.p_u16[idx];
85 	case V4L2_CTRL_TYPE_U32:
86 		return ptr1.p_u32[idx] == ptr2.p_u32[idx];
87 	default:
88 		if (ctrl->is_int)
89 			return ptr1.p_s32[idx] == ptr2.p_s32[idx];
90 		idx *= ctrl->elem_size;
91 		return !memcmp(ptr1.p_const + idx, ptr2.p_const + idx,
92 			       ctrl->elem_size);
93 	}
94 }
95 
96 /* Default intra MPEG-2 quantisation coefficients, from the specification. */
97 static const u8 mpeg2_intra_quant_matrix[64] = {
98 	8,  16, 16, 19, 16, 19, 22, 22,
99 	22, 22, 22, 22, 26, 24, 26, 27,
100 	27, 27, 26, 26, 26, 26, 27, 27,
101 	27, 29, 29, 29, 34, 34, 34, 29,
102 	29, 29, 27, 27, 29, 29, 32, 32,
103 	34, 34, 37, 38, 37, 35, 35, 34,
104 	35, 38, 38, 40, 40, 40, 48, 48,
105 	46, 46, 56, 56, 58, 69, 69, 83
106 };
107 
108 static void std_init_compound(const struct v4l2_ctrl *ctrl, u32 idx,
109 			      union v4l2_ctrl_ptr ptr)
110 {
111 	struct v4l2_ctrl_mpeg2_sequence *p_mpeg2_sequence;
112 	struct v4l2_ctrl_mpeg2_picture *p_mpeg2_picture;
113 	struct v4l2_ctrl_mpeg2_quantisation *p_mpeg2_quant;
114 	struct v4l2_ctrl_vp8_frame *p_vp8_frame;
115 	struct v4l2_ctrl_vp9_frame *p_vp9_frame;
116 	struct v4l2_ctrl_fwht_params *p_fwht_params;
117 	void *p = ptr.p + idx * ctrl->elem_size;
118 
119 	if (ctrl->p_def.p_const)
120 		memcpy(p, ctrl->p_def.p_const, ctrl->elem_size);
121 	else
122 		memset(p, 0, ctrl->elem_size);
123 
124 	switch ((u32)ctrl->type) {
125 	case V4L2_CTRL_TYPE_MPEG2_SEQUENCE:
126 		p_mpeg2_sequence = p;
127 
128 		/* 4:2:0 */
129 		p_mpeg2_sequence->chroma_format = 1;
130 		break;
131 	case V4L2_CTRL_TYPE_MPEG2_PICTURE:
132 		p_mpeg2_picture = p;
133 
134 		/* interlaced top field */
135 		p_mpeg2_picture->picture_structure = V4L2_MPEG2_PIC_TOP_FIELD;
136 		p_mpeg2_picture->picture_coding_type =
137 					V4L2_MPEG2_PIC_CODING_TYPE_I;
138 		break;
139 	case V4L2_CTRL_TYPE_MPEG2_QUANTISATION:
140 		p_mpeg2_quant = p;
141 
142 		memcpy(p_mpeg2_quant->intra_quantiser_matrix,
143 		       mpeg2_intra_quant_matrix,
144 		       ARRAY_SIZE(mpeg2_intra_quant_matrix));
145 		/*
146 		 * The default non-intra MPEG-2 quantisation
147 		 * coefficients are all 16, as per the specification.
148 		 */
149 		memset(p_mpeg2_quant->non_intra_quantiser_matrix, 16,
150 		       sizeof(p_mpeg2_quant->non_intra_quantiser_matrix));
151 		break;
152 	case V4L2_CTRL_TYPE_VP8_FRAME:
153 		p_vp8_frame = p;
154 		p_vp8_frame->num_dct_parts = 1;
155 		break;
156 	case V4L2_CTRL_TYPE_VP9_FRAME:
157 		p_vp9_frame = p;
158 		p_vp9_frame->profile = 0;
159 		p_vp9_frame->bit_depth = 8;
160 		p_vp9_frame->flags |= V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING |
161 			V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING;
162 		break;
163 	case V4L2_CTRL_TYPE_FWHT_PARAMS:
164 		p_fwht_params = p;
165 		p_fwht_params->version = V4L2_FWHT_VERSION;
166 		p_fwht_params->width = 1280;
167 		p_fwht_params->height = 720;
168 		p_fwht_params->flags = V4L2_FWHT_FL_PIXENC_YUV |
169 			(2 << V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET);
170 		break;
171 	}
172 }
173 
174 static void std_init(const struct v4l2_ctrl *ctrl, u32 idx,
175 		     union v4l2_ctrl_ptr ptr)
176 {
177 	switch (ctrl->type) {
178 	case V4L2_CTRL_TYPE_STRING:
179 		idx *= ctrl->elem_size;
180 		memset(ptr.p_char + idx, ' ', ctrl->minimum);
181 		ptr.p_char[idx + ctrl->minimum] = '\0';
182 		break;
183 	case V4L2_CTRL_TYPE_INTEGER64:
184 		ptr.p_s64[idx] = ctrl->default_value;
185 		break;
186 	case V4L2_CTRL_TYPE_INTEGER:
187 	case V4L2_CTRL_TYPE_INTEGER_MENU:
188 	case V4L2_CTRL_TYPE_MENU:
189 	case V4L2_CTRL_TYPE_BITMASK:
190 	case V4L2_CTRL_TYPE_BOOLEAN:
191 		ptr.p_s32[idx] = ctrl->default_value;
192 		break;
193 	case V4L2_CTRL_TYPE_BUTTON:
194 	case V4L2_CTRL_TYPE_CTRL_CLASS:
195 		ptr.p_s32[idx] = 0;
196 		break;
197 	case V4L2_CTRL_TYPE_U8:
198 		ptr.p_u8[idx] = ctrl->default_value;
199 		break;
200 	case V4L2_CTRL_TYPE_U16:
201 		ptr.p_u16[idx] = ctrl->default_value;
202 		break;
203 	case V4L2_CTRL_TYPE_U32:
204 		ptr.p_u32[idx] = ctrl->default_value;
205 		break;
206 	default:
207 		std_init_compound(ctrl, idx, ptr);
208 		break;
209 	}
210 }
211 
212 static void std_log(const struct v4l2_ctrl *ctrl)
213 {
214 	union v4l2_ctrl_ptr ptr = ctrl->p_cur;
215 
216 	if (ctrl->is_array) {
217 		unsigned i;
218 
219 		for (i = 0; i < ctrl->nr_of_dims; i++)
220 			pr_cont("[%u]", ctrl->dims[i]);
221 		pr_cont(" ");
222 	}
223 
224 	switch (ctrl->type) {
225 	case V4L2_CTRL_TYPE_INTEGER:
226 		pr_cont("%d", *ptr.p_s32);
227 		break;
228 	case V4L2_CTRL_TYPE_BOOLEAN:
229 		pr_cont("%s", *ptr.p_s32 ? "true" : "false");
230 		break;
231 	case V4L2_CTRL_TYPE_MENU:
232 		pr_cont("%s", ctrl->qmenu[*ptr.p_s32]);
233 		break;
234 	case V4L2_CTRL_TYPE_INTEGER_MENU:
235 		pr_cont("%lld", ctrl->qmenu_int[*ptr.p_s32]);
236 		break;
237 	case V4L2_CTRL_TYPE_BITMASK:
238 		pr_cont("0x%08x", *ptr.p_s32);
239 		break;
240 	case V4L2_CTRL_TYPE_INTEGER64:
241 		pr_cont("%lld", *ptr.p_s64);
242 		break;
243 	case V4L2_CTRL_TYPE_STRING:
244 		pr_cont("%s", ptr.p_char);
245 		break;
246 	case V4L2_CTRL_TYPE_U8:
247 		pr_cont("%u", (unsigned)*ptr.p_u8);
248 		break;
249 	case V4L2_CTRL_TYPE_U16:
250 		pr_cont("%u", (unsigned)*ptr.p_u16);
251 		break;
252 	case V4L2_CTRL_TYPE_U32:
253 		pr_cont("%u", (unsigned)*ptr.p_u32);
254 		break;
255 	case V4L2_CTRL_TYPE_H264_SPS:
256 		pr_cont("H264_SPS");
257 		break;
258 	case V4L2_CTRL_TYPE_H264_PPS:
259 		pr_cont("H264_PPS");
260 		break;
261 	case V4L2_CTRL_TYPE_H264_SCALING_MATRIX:
262 		pr_cont("H264_SCALING_MATRIX");
263 		break;
264 	case V4L2_CTRL_TYPE_H264_SLICE_PARAMS:
265 		pr_cont("H264_SLICE_PARAMS");
266 		break;
267 	case V4L2_CTRL_TYPE_H264_DECODE_PARAMS:
268 		pr_cont("H264_DECODE_PARAMS");
269 		break;
270 	case V4L2_CTRL_TYPE_H264_PRED_WEIGHTS:
271 		pr_cont("H264_PRED_WEIGHTS");
272 		break;
273 	case V4L2_CTRL_TYPE_FWHT_PARAMS:
274 		pr_cont("FWHT_PARAMS");
275 		break;
276 	case V4L2_CTRL_TYPE_VP8_FRAME:
277 		pr_cont("VP8_FRAME");
278 		break;
279 	case V4L2_CTRL_TYPE_HDR10_CLL_INFO:
280 		pr_cont("HDR10_CLL_INFO");
281 		break;
282 	case V4L2_CTRL_TYPE_HDR10_MASTERING_DISPLAY:
283 		pr_cont("HDR10_MASTERING_DISPLAY");
284 		break;
285 	case V4L2_CTRL_TYPE_MPEG2_QUANTISATION:
286 		pr_cont("MPEG2_QUANTISATION");
287 		break;
288 	case V4L2_CTRL_TYPE_MPEG2_SEQUENCE:
289 		pr_cont("MPEG2_SEQUENCE");
290 		break;
291 	case V4L2_CTRL_TYPE_MPEG2_PICTURE:
292 		pr_cont("MPEG2_PICTURE");
293 		break;
294 	case V4L2_CTRL_TYPE_VP9_COMPRESSED_HDR:
295 		pr_cont("VP9_COMPRESSED_HDR");
296 		break;
297 	case V4L2_CTRL_TYPE_VP9_FRAME:
298 		pr_cont("VP9_FRAME");
299 		break;
300 	default:
301 		pr_cont("unknown type %d", ctrl->type);
302 		break;
303 	}
304 }
305 
306 /*
307  * Round towards the closest legal value. Be careful when we are
308  * close to the maximum range of the control type to prevent
309  * wrap-arounds.
310  */
311 #define ROUND_TO_RANGE(val, offset_type, ctrl)			\
312 ({								\
313 	offset_type offset;					\
314 	if ((ctrl)->maximum >= 0 &&				\
315 	    val >= (ctrl)->maximum - (s32)((ctrl)->step / 2))	\
316 		val = (ctrl)->maximum;				\
317 	else							\
318 		val += (s32)((ctrl)->step / 2);			\
319 	val = clamp_t(typeof(val), val,				\
320 		      (ctrl)->minimum, (ctrl)->maximum);	\
321 	offset = (val) - (ctrl)->minimum;			\
322 	offset = (ctrl)->step * (offset / (u32)(ctrl)->step);	\
323 	val = (ctrl)->minimum + offset;				\
324 	0;							\
325 })
326 
327 /* Validate a new control */
328 
329 #define zero_padding(s) \
330 	memset(&(s).padding, 0, sizeof((s).padding))
331 #define zero_reserved(s) \
332 	memset(&(s).reserved, 0, sizeof((s).reserved))
333 
334 static int
335 validate_vp9_lf_params(struct v4l2_vp9_loop_filter *lf)
336 {
337 	unsigned int i;
338 
339 	if (lf->flags & ~(V4L2_VP9_LOOP_FILTER_FLAG_DELTA_ENABLED |
340 			  V4L2_VP9_LOOP_FILTER_FLAG_DELTA_UPDATE))
341 		return -EINVAL;
342 
343 	/* That all values are in the accepted range. */
344 	if (lf->level > GENMASK(5, 0))
345 		return -EINVAL;
346 
347 	if (lf->sharpness > GENMASK(2, 0))
348 		return -EINVAL;
349 
350 	for (i = 0; i < ARRAY_SIZE(lf->ref_deltas); i++)
351 		if (lf->ref_deltas[i] < -63 || lf->ref_deltas[i] > 63)
352 			return -EINVAL;
353 
354 	for (i = 0; i < ARRAY_SIZE(lf->mode_deltas); i++)
355 		if (lf->mode_deltas[i] < -63 || lf->mode_deltas[i] > 63)
356 			return -EINVAL;
357 
358 	zero_reserved(*lf);
359 	return 0;
360 }
361 
362 static int
363 validate_vp9_quant_params(struct v4l2_vp9_quantization *quant)
364 {
365 	if (quant->delta_q_y_dc < -15 || quant->delta_q_y_dc > 15 ||
366 	    quant->delta_q_uv_dc < -15 || quant->delta_q_uv_dc > 15 ||
367 	    quant->delta_q_uv_ac < -15 || quant->delta_q_uv_ac > 15)
368 		return -EINVAL;
369 
370 	zero_reserved(*quant);
371 	return 0;
372 }
373 
374 static int
375 validate_vp9_seg_params(struct v4l2_vp9_segmentation *seg)
376 {
377 	unsigned int i, j;
378 
379 	if (seg->flags & ~(V4L2_VP9_SEGMENTATION_FLAG_ENABLED |
380 			   V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP |
381 			   V4L2_VP9_SEGMENTATION_FLAG_TEMPORAL_UPDATE |
382 			   V4L2_VP9_SEGMENTATION_FLAG_UPDATE_DATA |
383 			   V4L2_VP9_SEGMENTATION_FLAG_ABS_OR_DELTA_UPDATE))
384 		return -EINVAL;
385 
386 	for (i = 0; i < ARRAY_SIZE(seg->feature_enabled); i++) {
387 		if (seg->feature_enabled[i] &
388 		    ~V4L2_VP9_SEGMENT_FEATURE_ENABLED_MASK)
389 			return -EINVAL;
390 	}
391 
392 	for (i = 0; i < ARRAY_SIZE(seg->feature_data); i++) {
393 		static const int range[] = { 255, 63, 3, 0 };
394 
395 		for (j = 0; j < ARRAY_SIZE(seg->feature_data[j]); j++) {
396 			if (seg->feature_data[i][j] < -range[j] ||
397 			    seg->feature_data[i][j] > range[j])
398 				return -EINVAL;
399 		}
400 	}
401 
402 	zero_reserved(*seg);
403 	return 0;
404 }
405 
406 static int
407 validate_vp9_compressed_hdr(struct v4l2_ctrl_vp9_compressed_hdr *hdr)
408 {
409 	if (hdr->tx_mode > V4L2_VP9_TX_MODE_SELECT)
410 		return -EINVAL;
411 
412 	return 0;
413 }
414 
415 static int
416 validate_vp9_frame(struct v4l2_ctrl_vp9_frame *frame)
417 {
418 	int ret;
419 
420 	/* Make sure we're not passed invalid flags. */
421 	if (frame->flags & ~(V4L2_VP9_FRAME_FLAG_KEY_FRAME |
422 		  V4L2_VP9_FRAME_FLAG_SHOW_FRAME |
423 		  V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT |
424 		  V4L2_VP9_FRAME_FLAG_INTRA_ONLY |
425 		  V4L2_VP9_FRAME_FLAG_ALLOW_HIGH_PREC_MV |
426 		  V4L2_VP9_FRAME_FLAG_REFRESH_FRAME_CTX |
427 		  V4L2_VP9_FRAME_FLAG_PARALLEL_DEC_MODE |
428 		  V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING |
429 		  V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING |
430 		  V4L2_VP9_FRAME_FLAG_COLOR_RANGE_FULL_SWING))
431 		return -EINVAL;
432 
433 	if (frame->flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT &&
434 	    frame->flags & V4L2_VP9_FRAME_FLAG_REFRESH_FRAME_CTX)
435 		return -EINVAL;
436 
437 	if (frame->profile > V4L2_VP9_PROFILE_MAX)
438 		return -EINVAL;
439 
440 	if (frame->reset_frame_context > V4L2_VP9_RESET_FRAME_CTX_ALL)
441 		return -EINVAL;
442 
443 	if (frame->frame_context_idx >= V4L2_VP9_NUM_FRAME_CTX)
444 		return -EINVAL;
445 
446 	/*
447 	 * Profiles 0 and 1 only support 8-bit depth, profiles 2 and 3 only 10
448 	 * and 12 bit depths.
449 	 */
450 	if ((frame->profile < 2 && frame->bit_depth != 8) ||
451 	    (frame->profile >= 2 &&
452 	     (frame->bit_depth != 10 && frame->bit_depth != 12)))
453 		return -EINVAL;
454 
455 	/* Profile 0 and 2 only accept YUV 4:2:0. */
456 	if ((frame->profile == 0 || frame->profile == 2) &&
457 	    (!(frame->flags & V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING) ||
458 	     !(frame->flags & V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING)))
459 		return -EINVAL;
460 
461 	/* Profile 1 and 3 only accept YUV 4:2:2, 4:4:0 and 4:4:4. */
462 	if ((frame->profile == 1 || frame->profile == 3) &&
463 	    ((frame->flags & V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING) &&
464 	     (frame->flags & V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING)))
465 		return -EINVAL;
466 
467 	if (frame->interpolation_filter > V4L2_VP9_INTERP_FILTER_SWITCHABLE)
468 		return -EINVAL;
469 
470 	/*
471 	 * According to the spec, tile_cols_log2 shall be less than or equal
472 	 * to 6.
473 	 */
474 	if (frame->tile_cols_log2 > 6)
475 		return -EINVAL;
476 
477 	if (frame->reference_mode > V4L2_VP9_REFERENCE_MODE_SELECT)
478 		return -EINVAL;
479 
480 	ret = validate_vp9_lf_params(&frame->lf);
481 	if (ret)
482 		return ret;
483 
484 	ret = validate_vp9_quant_params(&frame->quant);
485 	if (ret)
486 		return ret;
487 
488 	ret = validate_vp9_seg_params(&frame->seg);
489 	if (ret)
490 		return ret;
491 
492 	zero_reserved(*frame);
493 	return 0;
494 }
495 
496 /*
497  * Compound controls validation requires setting unused fields/flags to zero
498  * in order to properly detect unchanged controls with std_equal's memcmp.
499  */
500 static int std_validate_compound(const struct v4l2_ctrl *ctrl, u32 idx,
501 				 union v4l2_ctrl_ptr ptr)
502 {
503 	struct v4l2_ctrl_mpeg2_sequence *p_mpeg2_sequence;
504 	struct v4l2_ctrl_mpeg2_picture *p_mpeg2_picture;
505 	struct v4l2_ctrl_vp8_frame *p_vp8_frame;
506 	struct v4l2_ctrl_fwht_params *p_fwht_params;
507 	struct v4l2_ctrl_h264_sps *p_h264_sps;
508 	struct v4l2_ctrl_h264_pps *p_h264_pps;
509 	struct v4l2_ctrl_h264_pred_weights *p_h264_pred_weights;
510 	struct v4l2_ctrl_h264_slice_params *p_h264_slice_params;
511 	struct v4l2_ctrl_h264_decode_params *p_h264_dec_params;
512 	struct v4l2_ctrl_hevc_sps *p_hevc_sps;
513 	struct v4l2_ctrl_hevc_pps *p_hevc_pps;
514 	struct v4l2_ctrl_hevc_slice_params *p_hevc_slice_params;
515 	struct v4l2_ctrl_hdr10_mastering_display *p_hdr10_mastering;
516 	struct v4l2_ctrl_hevc_decode_params *p_hevc_decode_params;
517 	struct v4l2_area *area;
518 	void *p = ptr.p + idx * ctrl->elem_size;
519 	unsigned int i;
520 
521 	switch ((u32)ctrl->type) {
522 	case V4L2_CTRL_TYPE_MPEG2_SEQUENCE:
523 		p_mpeg2_sequence = p;
524 
525 		switch (p_mpeg2_sequence->chroma_format) {
526 		case 1: /* 4:2:0 */
527 		case 2: /* 4:2:2 */
528 		case 3: /* 4:4:4 */
529 			break;
530 		default:
531 			return -EINVAL;
532 		}
533 		break;
534 
535 	case V4L2_CTRL_TYPE_MPEG2_PICTURE:
536 		p_mpeg2_picture = p;
537 
538 		switch (p_mpeg2_picture->intra_dc_precision) {
539 		case 0: /* 8 bits */
540 		case 1: /* 9 bits */
541 		case 2: /* 10 bits */
542 		case 3: /* 11 bits */
543 			break;
544 		default:
545 			return -EINVAL;
546 		}
547 
548 		switch (p_mpeg2_picture->picture_structure) {
549 		case V4L2_MPEG2_PIC_TOP_FIELD:
550 		case V4L2_MPEG2_PIC_BOTTOM_FIELD:
551 		case V4L2_MPEG2_PIC_FRAME:
552 			break;
553 		default:
554 			return -EINVAL;
555 		}
556 
557 		switch (p_mpeg2_picture->picture_coding_type) {
558 		case V4L2_MPEG2_PIC_CODING_TYPE_I:
559 		case V4L2_MPEG2_PIC_CODING_TYPE_P:
560 		case V4L2_MPEG2_PIC_CODING_TYPE_B:
561 			break;
562 		default:
563 			return -EINVAL;
564 		}
565 		zero_reserved(*p_mpeg2_picture);
566 		break;
567 
568 	case V4L2_CTRL_TYPE_MPEG2_QUANTISATION:
569 		break;
570 
571 	case V4L2_CTRL_TYPE_FWHT_PARAMS:
572 		p_fwht_params = p;
573 		if (p_fwht_params->version < V4L2_FWHT_VERSION)
574 			return -EINVAL;
575 		if (!p_fwht_params->width || !p_fwht_params->height)
576 			return -EINVAL;
577 		break;
578 
579 	case V4L2_CTRL_TYPE_H264_SPS:
580 		p_h264_sps = p;
581 
582 		/* Some syntax elements are only conditionally valid */
583 		if (p_h264_sps->pic_order_cnt_type != 0) {
584 			p_h264_sps->log2_max_pic_order_cnt_lsb_minus4 = 0;
585 		} else if (p_h264_sps->pic_order_cnt_type != 1) {
586 			p_h264_sps->num_ref_frames_in_pic_order_cnt_cycle = 0;
587 			p_h264_sps->offset_for_non_ref_pic = 0;
588 			p_h264_sps->offset_for_top_to_bottom_field = 0;
589 			memset(&p_h264_sps->offset_for_ref_frame, 0,
590 			       sizeof(p_h264_sps->offset_for_ref_frame));
591 		}
592 
593 		if (!V4L2_H264_SPS_HAS_CHROMA_FORMAT(p_h264_sps)) {
594 			p_h264_sps->chroma_format_idc = 1;
595 			p_h264_sps->bit_depth_luma_minus8 = 0;
596 			p_h264_sps->bit_depth_chroma_minus8 = 0;
597 
598 			p_h264_sps->flags &=
599 				~V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS;
600 
601 			if (p_h264_sps->chroma_format_idc < 3)
602 				p_h264_sps->flags &=
603 					~V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE;
604 		}
605 
606 		if (p_h264_sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY)
607 			p_h264_sps->flags &=
608 				~V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD;
609 
610 		/*
611 		 * Chroma 4:2:2 format require at least High 4:2:2 profile.
612 		 *
613 		 * The H264 specification and well-known parser implementations
614 		 * use profile-idc values directly, as that is clearer and
615 		 * less ambiguous. We do the same here.
616 		 */
617 		if (p_h264_sps->profile_idc < 122 &&
618 		    p_h264_sps->chroma_format_idc > 1)
619 			return -EINVAL;
620 		/* Chroma 4:4:4 format require at least High 4:2:2 profile */
621 		if (p_h264_sps->profile_idc < 244 &&
622 		    p_h264_sps->chroma_format_idc > 2)
623 			return -EINVAL;
624 		if (p_h264_sps->chroma_format_idc > 3)
625 			return -EINVAL;
626 
627 		if (p_h264_sps->bit_depth_luma_minus8 > 6)
628 			return -EINVAL;
629 		if (p_h264_sps->bit_depth_chroma_minus8 > 6)
630 			return -EINVAL;
631 		if (p_h264_sps->log2_max_frame_num_minus4 > 12)
632 			return -EINVAL;
633 		if (p_h264_sps->pic_order_cnt_type > 2)
634 			return -EINVAL;
635 		if (p_h264_sps->log2_max_pic_order_cnt_lsb_minus4 > 12)
636 			return -EINVAL;
637 		if (p_h264_sps->max_num_ref_frames > V4L2_H264_REF_LIST_LEN)
638 			return -EINVAL;
639 		break;
640 
641 	case V4L2_CTRL_TYPE_H264_PPS:
642 		p_h264_pps = p;
643 
644 		if (p_h264_pps->num_slice_groups_minus1 > 7)
645 			return -EINVAL;
646 		if (p_h264_pps->num_ref_idx_l0_default_active_minus1 >
647 		    (V4L2_H264_REF_LIST_LEN - 1))
648 			return -EINVAL;
649 		if (p_h264_pps->num_ref_idx_l1_default_active_minus1 >
650 		    (V4L2_H264_REF_LIST_LEN - 1))
651 			return -EINVAL;
652 		if (p_h264_pps->weighted_bipred_idc > 2)
653 			return -EINVAL;
654 		/*
655 		 * pic_init_qp_minus26 shall be in the range of
656 		 * -(26 + QpBdOffset_y) to +25, inclusive,
657 		 *  where QpBdOffset_y is 6 * bit_depth_luma_minus8
658 		 */
659 		if (p_h264_pps->pic_init_qp_minus26 < -62 ||
660 		    p_h264_pps->pic_init_qp_minus26 > 25)
661 			return -EINVAL;
662 		if (p_h264_pps->pic_init_qs_minus26 < -26 ||
663 		    p_h264_pps->pic_init_qs_minus26 > 25)
664 			return -EINVAL;
665 		if (p_h264_pps->chroma_qp_index_offset < -12 ||
666 		    p_h264_pps->chroma_qp_index_offset > 12)
667 			return -EINVAL;
668 		if (p_h264_pps->second_chroma_qp_index_offset < -12 ||
669 		    p_h264_pps->second_chroma_qp_index_offset > 12)
670 			return -EINVAL;
671 		break;
672 
673 	case V4L2_CTRL_TYPE_H264_SCALING_MATRIX:
674 		break;
675 
676 	case V4L2_CTRL_TYPE_H264_PRED_WEIGHTS:
677 		p_h264_pred_weights = p;
678 
679 		if (p_h264_pred_weights->luma_log2_weight_denom > 7)
680 			return -EINVAL;
681 		if (p_h264_pred_weights->chroma_log2_weight_denom > 7)
682 			return -EINVAL;
683 		break;
684 
685 	case V4L2_CTRL_TYPE_H264_SLICE_PARAMS:
686 		p_h264_slice_params = p;
687 
688 		if (p_h264_slice_params->slice_type != V4L2_H264_SLICE_TYPE_B)
689 			p_h264_slice_params->flags &=
690 				~V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED;
691 
692 		if (p_h264_slice_params->colour_plane_id > 2)
693 			return -EINVAL;
694 		if (p_h264_slice_params->cabac_init_idc > 2)
695 			return -EINVAL;
696 		if (p_h264_slice_params->disable_deblocking_filter_idc > 2)
697 			return -EINVAL;
698 		if (p_h264_slice_params->slice_alpha_c0_offset_div2 < -6 ||
699 		    p_h264_slice_params->slice_alpha_c0_offset_div2 > 6)
700 			return -EINVAL;
701 		if (p_h264_slice_params->slice_beta_offset_div2 < -6 ||
702 		    p_h264_slice_params->slice_beta_offset_div2 > 6)
703 			return -EINVAL;
704 
705 		if (p_h264_slice_params->slice_type == V4L2_H264_SLICE_TYPE_I ||
706 		    p_h264_slice_params->slice_type == V4L2_H264_SLICE_TYPE_SI)
707 			p_h264_slice_params->num_ref_idx_l0_active_minus1 = 0;
708 		if (p_h264_slice_params->slice_type != V4L2_H264_SLICE_TYPE_B)
709 			p_h264_slice_params->num_ref_idx_l1_active_minus1 = 0;
710 
711 		if (p_h264_slice_params->num_ref_idx_l0_active_minus1 >
712 		    (V4L2_H264_REF_LIST_LEN - 1))
713 			return -EINVAL;
714 		if (p_h264_slice_params->num_ref_idx_l1_active_minus1 >
715 		    (V4L2_H264_REF_LIST_LEN - 1))
716 			return -EINVAL;
717 		zero_reserved(*p_h264_slice_params);
718 		break;
719 
720 	case V4L2_CTRL_TYPE_H264_DECODE_PARAMS:
721 		p_h264_dec_params = p;
722 
723 		if (p_h264_dec_params->nal_ref_idc > 3)
724 			return -EINVAL;
725 		for (i = 0; i < V4L2_H264_NUM_DPB_ENTRIES; i++) {
726 			struct v4l2_h264_dpb_entry *dpb_entry =
727 				&p_h264_dec_params->dpb[i];
728 
729 			zero_reserved(*dpb_entry);
730 		}
731 		zero_reserved(*p_h264_dec_params);
732 		break;
733 
734 	case V4L2_CTRL_TYPE_VP8_FRAME:
735 		p_vp8_frame = p;
736 
737 		switch (p_vp8_frame->num_dct_parts) {
738 		case 1:
739 		case 2:
740 		case 4:
741 		case 8:
742 			break;
743 		default:
744 			return -EINVAL;
745 		}
746 		zero_padding(p_vp8_frame->segment);
747 		zero_padding(p_vp8_frame->lf);
748 		zero_padding(p_vp8_frame->quant);
749 		zero_padding(p_vp8_frame->entropy);
750 		zero_padding(p_vp8_frame->coder_state);
751 		break;
752 
753 	case V4L2_CTRL_TYPE_HEVC_SPS:
754 		p_hevc_sps = p;
755 
756 		if (!(p_hevc_sps->flags & V4L2_HEVC_SPS_FLAG_PCM_ENABLED)) {
757 			p_hevc_sps->pcm_sample_bit_depth_luma_minus1 = 0;
758 			p_hevc_sps->pcm_sample_bit_depth_chroma_minus1 = 0;
759 			p_hevc_sps->log2_min_pcm_luma_coding_block_size_minus3 = 0;
760 			p_hevc_sps->log2_diff_max_min_pcm_luma_coding_block_size = 0;
761 		}
762 
763 		if (!(p_hevc_sps->flags &
764 		      V4L2_HEVC_SPS_FLAG_LONG_TERM_REF_PICS_PRESENT))
765 			p_hevc_sps->num_long_term_ref_pics_sps = 0;
766 		break;
767 
768 	case V4L2_CTRL_TYPE_HEVC_PPS:
769 		p_hevc_pps = p;
770 
771 		if (!(p_hevc_pps->flags &
772 		      V4L2_HEVC_PPS_FLAG_CU_QP_DELTA_ENABLED))
773 			p_hevc_pps->diff_cu_qp_delta_depth = 0;
774 
775 		if (!(p_hevc_pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED)) {
776 			p_hevc_pps->num_tile_columns_minus1 = 0;
777 			p_hevc_pps->num_tile_rows_minus1 = 0;
778 			memset(&p_hevc_pps->column_width_minus1, 0,
779 			       sizeof(p_hevc_pps->column_width_minus1));
780 			memset(&p_hevc_pps->row_height_minus1, 0,
781 			       sizeof(p_hevc_pps->row_height_minus1));
782 
783 			p_hevc_pps->flags &=
784 				~V4L2_HEVC_PPS_FLAG_LOOP_FILTER_ACROSS_TILES_ENABLED;
785 		}
786 
787 		if (p_hevc_pps->flags &
788 		    V4L2_HEVC_PPS_FLAG_PPS_DISABLE_DEBLOCKING_FILTER) {
789 			p_hevc_pps->pps_beta_offset_div2 = 0;
790 			p_hevc_pps->pps_tc_offset_div2 = 0;
791 		}
792 
793 		zero_padding(*p_hevc_pps);
794 		break;
795 
796 	case V4L2_CTRL_TYPE_HEVC_DECODE_PARAMS:
797 		p_hevc_decode_params = p;
798 
799 		if (p_hevc_decode_params->num_active_dpb_entries >
800 		    V4L2_HEVC_DPB_ENTRIES_NUM_MAX)
801 			return -EINVAL;
802 
803 		for (i = 0; i < p_hevc_decode_params->num_active_dpb_entries;
804 		     i++) {
805 			struct v4l2_hevc_dpb_entry *dpb_entry =
806 				&p_hevc_decode_params->dpb[i];
807 
808 			zero_padding(*dpb_entry);
809 		}
810 		break;
811 
812 	case V4L2_CTRL_TYPE_HEVC_SLICE_PARAMS:
813 		p_hevc_slice_params = p;
814 
815 		zero_padding(p_hevc_slice_params->pred_weight_table);
816 		zero_padding(*p_hevc_slice_params);
817 		break;
818 
819 	case V4L2_CTRL_TYPE_HDR10_CLL_INFO:
820 		break;
821 
822 	case V4L2_CTRL_TYPE_HDR10_MASTERING_DISPLAY:
823 		p_hdr10_mastering = p;
824 
825 		for (i = 0; i < 3; ++i) {
826 			if (p_hdr10_mastering->display_primaries_x[i] <
827 				V4L2_HDR10_MASTERING_PRIMARIES_X_LOW ||
828 			    p_hdr10_mastering->display_primaries_x[i] >
829 				V4L2_HDR10_MASTERING_PRIMARIES_X_HIGH ||
830 			    p_hdr10_mastering->display_primaries_y[i] <
831 				V4L2_HDR10_MASTERING_PRIMARIES_Y_LOW ||
832 			    p_hdr10_mastering->display_primaries_y[i] >
833 				V4L2_HDR10_MASTERING_PRIMARIES_Y_HIGH)
834 				return -EINVAL;
835 		}
836 
837 		if (p_hdr10_mastering->white_point_x <
838 			V4L2_HDR10_MASTERING_WHITE_POINT_X_LOW ||
839 		    p_hdr10_mastering->white_point_x >
840 			V4L2_HDR10_MASTERING_WHITE_POINT_X_HIGH ||
841 		    p_hdr10_mastering->white_point_y <
842 			V4L2_HDR10_MASTERING_WHITE_POINT_Y_LOW ||
843 		    p_hdr10_mastering->white_point_y >
844 			V4L2_HDR10_MASTERING_WHITE_POINT_Y_HIGH)
845 			return -EINVAL;
846 
847 		if (p_hdr10_mastering->max_display_mastering_luminance <
848 			V4L2_HDR10_MASTERING_MAX_LUMA_LOW ||
849 		    p_hdr10_mastering->max_display_mastering_luminance >
850 			V4L2_HDR10_MASTERING_MAX_LUMA_HIGH ||
851 		    p_hdr10_mastering->min_display_mastering_luminance <
852 			V4L2_HDR10_MASTERING_MIN_LUMA_LOW ||
853 		    p_hdr10_mastering->min_display_mastering_luminance >
854 			V4L2_HDR10_MASTERING_MIN_LUMA_HIGH)
855 			return -EINVAL;
856 
857 		/* The following restriction comes from ITU-T Rec. H.265 spec */
858 		if (p_hdr10_mastering->max_display_mastering_luminance ==
859 			V4L2_HDR10_MASTERING_MAX_LUMA_LOW &&
860 		    p_hdr10_mastering->min_display_mastering_luminance ==
861 			V4L2_HDR10_MASTERING_MIN_LUMA_HIGH)
862 			return -EINVAL;
863 
864 		break;
865 
866 	case V4L2_CTRL_TYPE_HEVC_SCALING_MATRIX:
867 		break;
868 
869 	case V4L2_CTRL_TYPE_VP9_COMPRESSED_HDR:
870 		return validate_vp9_compressed_hdr(p);
871 
872 	case V4L2_CTRL_TYPE_VP9_FRAME:
873 		return validate_vp9_frame(p);
874 
875 	case V4L2_CTRL_TYPE_AREA:
876 		area = p;
877 		if (!area->width || !area->height)
878 			return -EINVAL;
879 		break;
880 
881 	default:
882 		return -EINVAL;
883 	}
884 
885 	return 0;
886 }
887 
888 static int std_validate(const struct v4l2_ctrl *ctrl, u32 idx,
889 			union v4l2_ctrl_ptr ptr)
890 {
891 	size_t len;
892 	u64 offset;
893 	s64 val;
894 
895 	switch ((u32)ctrl->type) {
896 	case V4L2_CTRL_TYPE_INTEGER:
897 		return ROUND_TO_RANGE(ptr.p_s32[idx], u32, ctrl);
898 	case V4L2_CTRL_TYPE_INTEGER64:
899 		/*
900 		 * We can't use the ROUND_TO_RANGE define here due to
901 		 * the u64 divide that needs special care.
902 		 */
903 		val = ptr.p_s64[idx];
904 		if (ctrl->maximum >= 0 && val >= ctrl->maximum - (s64)(ctrl->step / 2))
905 			val = ctrl->maximum;
906 		else
907 			val += (s64)(ctrl->step / 2);
908 		val = clamp_t(s64, val, ctrl->minimum, ctrl->maximum);
909 		offset = val - ctrl->minimum;
910 		do_div(offset, ctrl->step);
911 		ptr.p_s64[idx] = ctrl->minimum + offset * ctrl->step;
912 		return 0;
913 	case V4L2_CTRL_TYPE_U8:
914 		return ROUND_TO_RANGE(ptr.p_u8[idx], u8, ctrl);
915 	case V4L2_CTRL_TYPE_U16:
916 		return ROUND_TO_RANGE(ptr.p_u16[idx], u16, ctrl);
917 	case V4L2_CTRL_TYPE_U32:
918 		return ROUND_TO_RANGE(ptr.p_u32[idx], u32, ctrl);
919 
920 	case V4L2_CTRL_TYPE_BOOLEAN:
921 		ptr.p_s32[idx] = !!ptr.p_s32[idx];
922 		return 0;
923 
924 	case V4L2_CTRL_TYPE_MENU:
925 	case V4L2_CTRL_TYPE_INTEGER_MENU:
926 		if (ptr.p_s32[idx] < ctrl->minimum || ptr.p_s32[idx] > ctrl->maximum)
927 			return -ERANGE;
928 		if (ptr.p_s32[idx] < BITS_PER_LONG_LONG &&
929 		    (ctrl->menu_skip_mask & BIT_ULL(ptr.p_s32[idx])))
930 			return -EINVAL;
931 		if (ctrl->type == V4L2_CTRL_TYPE_MENU &&
932 		    ctrl->qmenu[ptr.p_s32[idx]][0] == '\0')
933 			return -EINVAL;
934 		return 0;
935 
936 	case V4L2_CTRL_TYPE_BITMASK:
937 		ptr.p_s32[idx] &= ctrl->maximum;
938 		return 0;
939 
940 	case V4L2_CTRL_TYPE_BUTTON:
941 	case V4L2_CTRL_TYPE_CTRL_CLASS:
942 		ptr.p_s32[idx] = 0;
943 		return 0;
944 
945 	case V4L2_CTRL_TYPE_STRING:
946 		idx *= ctrl->elem_size;
947 		len = strlen(ptr.p_char + idx);
948 		if (len < ctrl->minimum)
949 			return -ERANGE;
950 		if ((len - (u32)ctrl->minimum) % (u32)ctrl->step)
951 			return -ERANGE;
952 		return 0;
953 
954 	default:
955 		return std_validate_compound(ctrl, idx, ptr);
956 	}
957 }
958 
959 static const struct v4l2_ctrl_type_ops std_type_ops = {
960 	.equal = std_equal,
961 	.init = std_init,
962 	.log = std_log,
963 	.validate = std_validate,
964 };
965 
966 void v4l2_ctrl_notify(struct v4l2_ctrl *ctrl, v4l2_ctrl_notify_fnc notify, void *priv)
967 {
968 	if (!ctrl)
969 		return;
970 	if (!notify) {
971 		ctrl->call_notify = 0;
972 		return;
973 	}
974 	if (WARN_ON(ctrl->handler->notify && ctrl->handler->notify != notify))
975 		return;
976 	ctrl->handler->notify = notify;
977 	ctrl->handler->notify_priv = priv;
978 	ctrl->call_notify = 1;
979 }
980 EXPORT_SYMBOL(v4l2_ctrl_notify);
981 
982 /* Copy the one value to another. */
983 static void ptr_to_ptr(struct v4l2_ctrl *ctrl,
984 		       union v4l2_ctrl_ptr from, union v4l2_ctrl_ptr to)
985 {
986 	if (ctrl == NULL)
987 		return;
988 	memcpy(to.p, from.p_const, ctrl->elems * ctrl->elem_size);
989 }
990 
991 /* Copy the new value to the current value. */
992 void new_to_cur(struct v4l2_fh *fh, struct v4l2_ctrl *ctrl, u32 ch_flags)
993 {
994 	bool changed;
995 
996 	if (ctrl == NULL)
997 		return;
998 
999 	/* has_changed is set by cluster_changed */
1000 	changed = ctrl->has_changed;
1001 	if (changed)
1002 		ptr_to_ptr(ctrl, ctrl->p_new, ctrl->p_cur);
1003 
1004 	if (ch_flags & V4L2_EVENT_CTRL_CH_FLAGS) {
1005 		/* Note: CH_FLAGS is only set for auto clusters. */
1006 		ctrl->flags &=
1007 			~(V4L2_CTRL_FLAG_INACTIVE | V4L2_CTRL_FLAG_VOLATILE);
1008 		if (!is_cur_manual(ctrl->cluster[0])) {
1009 			ctrl->flags |= V4L2_CTRL_FLAG_INACTIVE;
1010 			if (ctrl->cluster[0]->has_volatiles)
1011 				ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
1012 		}
1013 		fh = NULL;
1014 	}
1015 	if (changed || ch_flags) {
1016 		/* If a control was changed that was not one of the controls
1017 		   modified by the application, then send the event to all. */
1018 		if (!ctrl->is_new)
1019 			fh = NULL;
1020 		send_event(fh, ctrl,
1021 			(changed ? V4L2_EVENT_CTRL_CH_VALUE : 0) | ch_flags);
1022 		if (ctrl->call_notify && changed && ctrl->handler->notify)
1023 			ctrl->handler->notify(ctrl, ctrl->handler->notify_priv);
1024 	}
1025 }
1026 
1027 /* Copy the current value to the new value */
1028 void cur_to_new(struct v4l2_ctrl *ctrl)
1029 {
1030 	if (ctrl == NULL)
1031 		return;
1032 	ptr_to_ptr(ctrl, ctrl->p_cur, ctrl->p_new);
1033 }
1034 
1035 /* Copy the new value to the request value */
1036 void new_to_req(struct v4l2_ctrl_ref *ref)
1037 {
1038 	if (!ref)
1039 		return;
1040 	ptr_to_ptr(ref->ctrl, ref->ctrl->p_new, ref->p_req);
1041 	ref->valid_p_req = true;
1042 }
1043 
1044 /* Copy the current value to the request value */
1045 void cur_to_req(struct v4l2_ctrl_ref *ref)
1046 {
1047 	if (!ref)
1048 		return;
1049 	ptr_to_ptr(ref->ctrl, ref->ctrl->p_cur, ref->p_req);
1050 	ref->valid_p_req = true;
1051 }
1052 
1053 /* Copy the request value to the new value */
1054 void req_to_new(struct v4l2_ctrl_ref *ref)
1055 {
1056 	if (!ref)
1057 		return;
1058 	if (ref->valid_p_req)
1059 		ptr_to_ptr(ref->ctrl, ref->p_req, ref->ctrl->p_new);
1060 	else
1061 		ptr_to_ptr(ref->ctrl, ref->ctrl->p_cur, ref->ctrl->p_new);
1062 }
1063 
1064 /* Control range checking */
1065 int check_range(enum v4l2_ctrl_type type,
1066 		s64 min, s64 max, u64 step, s64 def)
1067 {
1068 	switch (type) {
1069 	case V4L2_CTRL_TYPE_BOOLEAN:
1070 		if (step != 1 || max > 1 || min < 0)
1071 			return -ERANGE;
1072 		fallthrough;
1073 	case V4L2_CTRL_TYPE_U8:
1074 	case V4L2_CTRL_TYPE_U16:
1075 	case V4L2_CTRL_TYPE_U32:
1076 	case V4L2_CTRL_TYPE_INTEGER:
1077 	case V4L2_CTRL_TYPE_INTEGER64:
1078 		if (step == 0 || min > max || def < min || def > max)
1079 			return -ERANGE;
1080 		return 0;
1081 	case V4L2_CTRL_TYPE_BITMASK:
1082 		if (step || min || !max || (def & ~max))
1083 			return -ERANGE;
1084 		return 0;
1085 	case V4L2_CTRL_TYPE_MENU:
1086 	case V4L2_CTRL_TYPE_INTEGER_MENU:
1087 		if (min > max || def < min || def > max)
1088 			return -ERANGE;
1089 		/* Note: step == menu_skip_mask for menu controls.
1090 		   So here we check if the default value is masked out. */
1091 		if (step && ((1 << def) & step))
1092 			return -EINVAL;
1093 		return 0;
1094 	case V4L2_CTRL_TYPE_STRING:
1095 		if (min > max || min < 0 || step < 1 || def)
1096 			return -ERANGE;
1097 		return 0;
1098 	default:
1099 		return 0;
1100 	}
1101 }
1102 
1103 /* Validate a new control */
1104 int validate_new(const struct v4l2_ctrl *ctrl, union v4l2_ctrl_ptr p_new)
1105 {
1106 	unsigned idx;
1107 	int err = 0;
1108 
1109 	for (idx = 0; !err && idx < ctrl->elems; idx++)
1110 		err = ctrl->type_ops->validate(ctrl, idx, p_new);
1111 	return err;
1112 }
1113 
1114 /* Set the handler's error code if it wasn't set earlier already */
1115 static inline int handler_set_err(struct v4l2_ctrl_handler *hdl, int err)
1116 {
1117 	if (hdl->error == 0)
1118 		hdl->error = err;
1119 	return err;
1120 }
1121 
1122 /* Initialize the handler */
1123 int v4l2_ctrl_handler_init_class(struct v4l2_ctrl_handler *hdl,
1124 				 unsigned nr_of_controls_hint,
1125 				 struct lock_class_key *key, const char *name)
1126 {
1127 	mutex_init(&hdl->_lock);
1128 	hdl->lock = &hdl->_lock;
1129 	lockdep_set_class_and_name(hdl->lock, key, name);
1130 	INIT_LIST_HEAD(&hdl->ctrls);
1131 	INIT_LIST_HEAD(&hdl->ctrl_refs);
1132 	hdl->nr_of_buckets = 1 + nr_of_controls_hint / 8;
1133 	hdl->buckets = kvmalloc_array(hdl->nr_of_buckets,
1134 				      sizeof(hdl->buckets[0]),
1135 				      GFP_KERNEL | __GFP_ZERO);
1136 	hdl->error = hdl->buckets ? 0 : -ENOMEM;
1137 	v4l2_ctrl_handler_init_request(hdl);
1138 	return hdl->error;
1139 }
1140 EXPORT_SYMBOL(v4l2_ctrl_handler_init_class);
1141 
1142 /* Free all controls and control refs */
1143 void v4l2_ctrl_handler_free(struct v4l2_ctrl_handler *hdl)
1144 {
1145 	struct v4l2_ctrl_ref *ref, *next_ref;
1146 	struct v4l2_ctrl *ctrl, *next_ctrl;
1147 	struct v4l2_subscribed_event *sev, *next_sev;
1148 
1149 	if (hdl == NULL || hdl->buckets == NULL)
1150 		return;
1151 
1152 	v4l2_ctrl_handler_free_request(hdl);
1153 
1154 	mutex_lock(hdl->lock);
1155 	/* Free all nodes */
1156 	list_for_each_entry_safe(ref, next_ref, &hdl->ctrl_refs, node) {
1157 		list_del(&ref->node);
1158 		kfree(ref);
1159 	}
1160 	/* Free all controls owned by the handler */
1161 	list_for_each_entry_safe(ctrl, next_ctrl, &hdl->ctrls, node) {
1162 		list_del(&ctrl->node);
1163 		list_for_each_entry_safe(sev, next_sev, &ctrl->ev_subs, node)
1164 			list_del(&sev->node);
1165 		kvfree(ctrl);
1166 	}
1167 	kvfree(hdl->buckets);
1168 	hdl->buckets = NULL;
1169 	hdl->cached = NULL;
1170 	hdl->error = 0;
1171 	mutex_unlock(hdl->lock);
1172 	mutex_destroy(&hdl->_lock);
1173 }
1174 EXPORT_SYMBOL(v4l2_ctrl_handler_free);
1175 
1176 /* For backwards compatibility: V4L2_CID_PRIVATE_BASE should no longer
1177    be used except in G_CTRL, S_CTRL, QUERYCTRL and QUERYMENU when dealing
1178    with applications that do not use the NEXT_CTRL flag.
1179 
1180    We just find the n-th private user control. It's O(N), but that should not
1181    be an issue in this particular case. */
1182 static struct v4l2_ctrl_ref *find_private_ref(
1183 		struct v4l2_ctrl_handler *hdl, u32 id)
1184 {
1185 	struct v4l2_ctrl_ref *ref;
1186 
1187 	id -= V4L2_CID_PRIVATE_BASE;
1188 	list_for_each_entry(ref, &hdl->ctrl_refs, node) {
1189 		/* Search for private user controls that are compatible with
1190 		   VIDIOC_G/S_CTRL. */
1191 		if (V4L2_CTRL_ID2WHICH(ref->ctrl->id) == V4L2_CTRL_CLASS_USER &&
1192 		    V4L2_CTRL_DRIVER_PRIV(ref->ctrl->id)) {
1193 			if (!ref->ctrl->is_int)
1194 				continue;
1195 			if (id == 0)
1196 				return ref;
1197 			id--;
1198 		}
1199 	}
1200 	return NULL;
1201 }
1202 
1203 /* Find a control with the given ID. */
1204 struct v4l2_ctrl_ref *find_ref(struct v4l2_ctrl_handler *hdl, u32 id)
1205 {
1206 	struct v4l2_ctrl_ref *ref;
1207 	int bucket;
1208 
1209 	id &= V4L2_CTRL_ID_MASK;
1210 
1211 	/* Old-style private controls need special handling */
1212 	if (id >= V4L2_CID_PRIVATE_BASE)
1213 		return find_private_ref(hdl, id);
1214 	bucket = id % hdl->nr_of_buckets;
1215 
1216 	/* Simple optimization: cache the last control found */
1217 	if (hdl->cached && hdl->cached->ctrl->id == id)
1218 		return hdl->cached;
1219 
1220 	/* Not in cache, search the hash */
1221 	ref = hdl->buckets ? hdl->buckets[bucket] : NULL;
1222 	while (ref && ref->ctrl->id != id)
1223 		ref = ref->next;
1224 
1225 	if (ref)
1226 		hdl->cached = ref; /* cache it! */
1227 	return ref;
1228 }
1229 
1230 /* Find a control with the given ID. Take the handler's lock first. */
1231 struct v4l2_ctrl_ref *find_ref_lock(struct v4l2_ctrl_handler *hdl, u32 id)
1232 {
1233 	struct v4l2_ctrl_ref *ref = NULL;
1234 
1235 	if (hdl) {
1236 		mutex_lock(hdl->lock);
1237 		ref = find_ref(hdl, id);
1238 		mutex_unlock(hdl->lock);
1239 	}
1240 	return ref;
1241 }
1242 
1243 /* Find a control with the given ID. */
1244 struct v4l2_ctrl *v4l2_ctrl_find(struct v4l2_ctrl_handler *hdl, u32 id)
1245 {
1246 	struct v4l2_ctrl_ref *ref = find_ref_lock(hdl, id);
1247 
1248 	return ref ? ref->ctrl : NULL;
1249 }
1250 EXPORT_SYMBOL(v4l2_ctrl_find);
1251 
1252 /* Allocate a new v4l2_ctrl_ref and hook it into the handler. */
1253 int handler_new_ref(struct v4l2_ctrl_handler *hdl,
1254 		    struct v4l2_ctrl *ctrl,
1255 		    struct v4l2_ctrl_ref **ctrl_ref,
1256 		    bool from_other_dev, bool allocate_req)
1257 {
1258 	struct v4l2_ctrl_ref *ref;
1259 	struct v4l2_ctrl_ref *new_ref;
1260 	u32 id = ctrl->id;
1261 	u32 class_ctrl = V4L2_CTRL_ID2WHICH(id) | 1;
1262 	int bucket = id % hdl->nr_of_buckets;	/* which bucket to use */
1263 	unsigned int size_extra_req = 0;
1264 
1265 	if (ctrl_ref)
1266 		*ctrl_ref = NULL;
1267 
1268 	/*
1269 	 * Automatically add the control class if it is not yet present and
1270 	 * the new control is not a compound control.
1271 	 */
1272 	if (ctrl->type < V4L2_CTRL_COMPOUND_TYPES &&
1273 	    id != class_ctrl && find_ref_lock(hdl, class_ctrl) == NULL)
1274 		if (!v4l2_ctrl_new_std(hdl, NULL, class_ctrl, 0, 0, 0, 0))
1275 			return hdl->error;
1276 
1277 	if (hdl->error)
1278 		return hdl->error;
1279 
1280 	if (allocate_req)
1281 		size_extra_req = ctrl->elems * ctrl->elem_size;
1282 	new_ref = kzalloc(sizeof(*new_ref) + size_extra_req, GFP_KERNEL);
1283 	if (!new_ref)
1284 		return handler_set_err(hdl, -ENOMEM);
1285 	new_ref->ctrl = ctrl;
1286 	new_ref->from_other_dev = from_other_dev;
1287 	if (size_extra_req)
1288 		new_ref->p_req.p = &new_ref[1];
1289 
1290 	INIT_LIST_HEAD(&new_ref->node);
1291 
1292 	mutex_lock(hdl->lock);
1293 
1294 	/* Add immediately at the end of the list if the list is empty, or if
1295 	   the last element in the list has a lower ID.
1296 	   This ensures that when elements are added in ascending order the
1297 	   insertion is an O(1) operation. */
1298 	if (list_empty(&hdl->ctrl_refs) || id > node2id(hdl->ctrl_refs.prev)) {
1299 		list_add_tail(&new_ref->node, &hdl->ctrl_refs);
1300 		goto insert_in_hash;
1301 	}
1302 
1303 	/* Find insert position in sorted list */
1304 	list_for_each_entry(ref, &hdl->ctrl_refs, node) {
1305 		if (ref->ctrl->id < id)
1306 			continue;
1307 		/* Don't add duplicates */
1308 		if (ref->ctrl->id == id) {
1309 			kfree(new_ref);
1310 			goto unlock;
1311 		}
1312 		list_add(&new_ref->node, ref->node.prev);
1313 		break;
1314 	}
1315 
1316 insert_in_hash:
1317 	/* Insert the control node in the hash */
1318 	new_ref->next = hdl->buckets[bucket];
1319 	hdl->buckets[bucket] = new_ref;
1320 	if (ctrl_ref)
1321 		*ctrl_ref = new_ref;
1322 	if (ctrl->handler == hdl) {
1323 		/* By default each control starts in a cluster of its own.
1324 		 * new_ref->ctrl is basically a cluster array with one
1325 		 * element, so that's perfect to use as the cluster pointer.
1326 		 * But only do this for the handler that owns the control.
1327 		 */
1328 		ctrl->cluster = &new_ref->ctrl;
1329 		ctrl->ncontrols = 1;
1330 	}
1331 
1332 unlock:
1333 	mutex_unlock(hdl->lock);
1334 	return 0;
1335 }
1336 
1337 /* Add a new control */
1338 static struct v4l2_ctrl *v4l2_ctrl_new(struct v4l2_ctrl_handler *hdl,
1339 			const struct v4l2_ctrl_ops *ops,
1340 			const struct v4l2_ctrl_type_ops *type_ops,
1341 			u32 id, const char *name, enum v4l2_ctrl_type type,
1342 			s64 min, s64 max, u64 step, s64 def,
1343 			const u32 dims[V4L2_CTRL_MAX_DIMS], u32 elem_size,
1344 			u32 flags, const char * const *qmenu,
1345 			const s64 *qmenu_int, const union v4l2_ctrl_ptr p_def,
1346 			void *priv)
1347 {
1348 	struct v4l2_ctrl *ctrl;
1349 	unsigned sz_extra;
1350 	unsigned nr_of_dims = 0;
1351 	unsigned elems = 1;
1352 	bool is_array;
1353 	unsigned tot_ctrl_size;
1354 	unsigned idx;
1355 	void *data;
1356 	int err;
1357 
1358 	if (hdl->error)
1359 		return NULL;
1360 
1361 	while (dims && dims[nr_of_dims]) {
1362 		elems *= dims[nr_of_dims];
1363 		nr_of_dims++;
1364 		if (nr_of_dims == V4L2_CTRL_MAX_DIMS)
1365 			break;
1366 	}
1367 	is_array = nr_of_dims > 0;
1368 
1369 	/* Prefill elem_size for all types handled by std_type_ops */
1370 	switch ((u32)type) {
1371 	case V4L2_CTRL_TYPE_INTEGER64:
1372 		elem_size = sizeof(s64);
1373 		break;
1374 	case V4L2_CTRL_TYPE_STRING:
1375 		elem_size = max + 1;
1376 		break;
1377 	case V4L2_CTRL_TYPE_U8:
1378 		elem_size = sizeof(u8);
1379 		break;
1380 	case V4L2_CTRL_TYPE_U16:
1381 		elem_size = sizeof(u16);
1382 		break;
1383 	case V4L2_CTRL_TYPE_U32:
1384 		elem_size = sizeof(u32);
1385 		break;
1386 	case V4L2_CTRL_TYPE_MPEG2_SEQUENCE:
1387 		elem_size = sizeof(struct v4l2_ctrl_mpeg2_sequence);
1388 		break;
1389 	case V4L2_CTRL_TYPE_MPEG2_PICTURE:
1390 		elem_size = sizeof(struct v4l2_ctrl_mpeg2_picture);
1391 		break;
1392 	case V4L2_CTRL_TYPE_MPEG2_QUANTISATION:
1393 		elem_size = sizeof(struct v4l2_ctrl_mpeg2_quantisation);
1394 		break;
1395 	case V4L2_CTRL_TYPE_FWHT_PARAMS:
1396 		elem_size = sizeof(struct v4l2_ctrl_fwht_params);
1397 		break;
1398 	case V4L2_CTRL_TYPE_H264_SPS:
1399 		elem_size = sizeof(struct v4l2_ctrl_h264_sps);
1400 		break;
1401 	case V4L2_CTRL_TYPE_H264_PPS:
1402 		elem_size = sizeof(struct v4l2_ctrl_h264_pps);
1403 		break;
1404 	case V4L2_CTRL_TYPE_H264_SCALING_MATRIX:
1405 		elem_size = sizeof(struct v4l2_ctrl_h264_scaling_matrix);
1406 		break;
1407 	case V4L2_CTRL_TYPE_H264_SLICE_PARAMS:
1408 		elem_size = sizeof(struct v4l2_ctrl_h264_slice_params);
1409 		break;
1410 	case V4L2_CTRL_TYPE_H264_DECODE_PARAMS:
1411 		elem_size = sizeof(struct v4l2_ctrl_h264_decode_params);
1412 		break;
1413 	case V4L2_CTRL_TYPE_H264_PRED_WEIGHTS:
1414 		elem_size = sizeof(struct v4l2_ctrl_h264_pred_weights);
1415 		break;
1416 	case V4L2_CTRL_TYPE_VP8_FRAME:
1417 		elem_size = sizeof(struct v4l2_ctrl_vp8_frame);
1418 		break;
1419 	case V4L2_CTRL_TYPE_HEVC_SPS:
1420 		elem_size = sizeof(struct v4l2_ctrl_hevc_sps);
1421 		break;
1422 	case V4L2_CTRL_TYPE_HEVC_PPS:
1423 		elem_size = sizeof(struct v4l2_ctrl_hevc_pps);
1424 		break;
1425 	case V4L2_CTRL_TYPE_HEVC_SLICE_PARAMS:
1426 		elem_size = sizeof(struct v4l2_ctrl_hevc_slice_params);
1427 		break;
1428 	case V4L2_CTRL_TYPE_HEVC_SCALING_MATRIX:
1429 		elem_size = sizeof(struct v4l2_ctrl_hevc_scaling_matrix);
1430 		break;
1431 	case V4L2_CTRL_TYPE_HEVC_DECODE_PARAMS:
1432 		elem_size = sizeof(struct v4l2_ctrl_hevc_decode_params);
1433 		break;
1434 	case V4L2_CTRL_TYPE_HDR10_CLL_INFO:
1435 		elem_size = sizeof(struct v4l2_ctrl_hdr10_cll_info);
1436 		break;
1437 	case V4L2_CTRL_TYPE_HDR10_MASTERING_DISPLAY:
1438 		elem_size = sizeof(struct v4l2_ctrl_hdr10_mastering_display);
1439 		break;
1440 	case V4L2_CTRL_TYPE_VP9_COMPRESSED_HDR:
1441 		elem_size = sizeof(struct v4l2_ctrl_vp9_compressed_hdr);
1442 		break;
1443 	case V4L2_CTRL_TYPE_VP9_FRAME:
1444 		elem_size = sizeof(struct v4l2_ctrl_vp9_frame);
1445 		break;
1446 	case V4L2_CTRL_TYPE_AREA:
1447 		elem_size = sizeof(struct v4l2_area);
1448 		break;
1449 	default:
1450 		if (type < V4L2_CTRL_COMPOUND_TYPES)
1451 			elem_size = sizeof(s32);
1452 		break;
1453 	}
1454 	tot_ctrl_size = elem_size * elems;
1455 
1456 	/* Sanity checks */
1457 	if (id == 0 || name == NULL || !elem_size ||
1458 	    id >= V4L2_CID_PRIVATE_BASE ||
1459 	    (type == V4L2_CTRL_TYPE_MENU && qmenu == NULL) ||
1460 	    (type == V4L2_CTRL_TYPE_INTEGER_MENU && qmenu_int == NULL)) {
1461 		handler_set_err(hdl, -ERANGE);
1462 		return NULL;
1463 	}
1464 	err = check_range(type, min, max, step, def);
1465 	if (err) {
1466 		handler_set_err(hdl, err);
1467 		return NULL;
1468 	}
1469 	if (is_array &&
1470 	    (type == V4L2_CTRL_TYPE_BUTTON ||
1471 	     type == V4L2_CTRL_TYPE_CTRL_CLASS)) {
1472 		handler_set_err(hdl, -EINVAL);
1473 		return NULL;
1474 	}
1475 
1476 	sz_extra = 0;
1477 	if (type == V4L2_CTRL_TYPE_BUTTON)
1478 		flags |= V4L2_CTRL_FLAG_WRITE_ONLY |
1479 			V4L2_CTRL_FLAG_EXECUTE_ON_WRITE;
1480 	else if (type == V4L2_CTRL_TYPE_CTRL_CLASS)
1481 		flags |= V4L2_CTRL_FLAG_READ_ONLY;
1482 	else if (type == V4L2_CTRL_TYPE_INTEGER64 ||
1483 		 type == V4L2_CTRL_TYPE_STRING ||
1484 		 type >= V4L2_CTRL_COMPOUND_TYPES ||
1485 		 is_array)
1486 		sz_extra += 2 * tot_ctrl_size;
1487 
1488 	if (type >= V4L2_CTRL_COMPOUND_TYPES && p_def.p_const)
1489 		sz_extra += elem_size;
1490 
1491 	ctrl = kvzalloc(sizeof(*ctrl) + sz_extra, GFP_KERNEL);
1492 	if (ctrl == NULL) {
1493 		handler_set_err(hdl, -ENOMEM);
1494 		return NULL;
1495 	}
1496 
1497 	INIT_LIST_HEAD(&ctrl->node);
1498 	INIT_LIST_HEAD(&ctrl->ev_subs);
1499 	ctrl->handler = hdl;
1500 	ctrl->ops = ops;
1501 	ctrl->type_ops = type_ops ? type_ops : &std_type_ops;
1502 	ctrl->id = id;
1503 	ctrl->name = name;
1504 	ctrl->type = type;
1505 	ctrl->flags = flags;
1506 	ctrl->minimum = min;
1507 	ctrl->maximum = max;
1508 	ctrl->step = step;
1509 	ctrl->default_value = def;
1510 	ctrl->is_string = !is_array && type == V4L2_CTRL_TYPE_STRING;
1511 	ctrl->is_ptr = is_array || type >= V4L2_CTRL_COMPOUND_TYPES || ctrl->is_string;
1512 	ctrl->is_int = !ctrl->is_ptr && type != V4L2_CTRL_TYPE_INTEGER64;
1513 	ctrl->is_array = is_array;
1514 	ctrl->elems = elems;
1515 	ctrl->nr_of_dims = nr_of_dims;
1516 	if (nr_of_dims)
1517 		memcpy(ctrl->dims, dims, nr_of_dims * sizeof(dims[0]));
1518 	ctrl->elem_size = elem_size;
1519 	if (type == V4L2_CTRL_TYPE_MENU)
1520 		ctrl->qmenu = qmenu;
1521 	else if (type == V4L2_CTRL_TYPE_INTEGER_MENU)
1522 		ctrl->qmenu_int = qmenu_int;
1523 	ctrl->priv = priv;
1524 	ctrl->cur.val = ctrl->val = def;
1525 	data = &ctrl[1];
1526 
1527 	if (!ctrl->is_int) {
1528 		ctrl->p_new.p = data;
1529 		ctrl->p_cur.p = data + tot_ctrl_size;
1530 	} else {
1531 		ctrl->p_new.p = &ctrl->val;
1532 		ctrl->p_cur.p = &ctrl->cur.val;
1533 	}
1534 
1535 	if (type >= V4L2_CTRL_COMPOUND_TYPES && p_def.p_const) {
1536 		ctrl->p_def.p = ctrl->p_cur.p + tot_ctrl_size;
1537 		memcpy(ctrl->p_def.p, p_def.p_const, elem_size);
1538 	}
1539 
1540 	for (idx = 0; idx < elems; idx++) {
1541 		ctrl->type_ops->init(ctrl, idx, ctrl->p_cur);
1542 		ctrl->type_ops->init(ctrl, idx, ctrl->p_new);
1543 	}
1544 
1545 	if (handler_new_ref(hdl, ctrl, NULL, false, false)) {
1546 		kvfree(ctrl);
1547 		return NULL;
1548 	}
1549 	mutex_lock(hdl->lock);
1550 	list_add_tail(&ctrl->node, &hdl->ctrls);
1551 	mutex_unlock(hdl->lock);
1552 	return ctrl;
1553 }
1554 
1555 struct v4l2_ctrl *v4l2_ctrl_new_custom(struct v4l2_ctrl_handler *hdl,
1556 			const struct v4l2_ctrl_config *cfg, void *priv)
1557 {
1558 	bool is_menu;
1559 	struct v4l2_ctrl *ctrl;
1560 	const char *name = cfg->name;
1561 	const char * const *qmenu = cfg->qmenu;
1562 	const s64 *qmenu_int = cfg->qmenu_int;
1563 	enum v4l2_ctrl_type type = cfg->type;
1564 	u32 flags = cfg->flags;
1565 	s64 min = cfg->min;
1566 	s64 max = cfg->max;
1567 	u64 step = cfg->step;
1568 	s64 def = cfg->def;
1569 
1570 	if (name == NULL)
1571 		v4l2_ctrl_fill(cfg->id, &name, &type, &min, &max, &step,
1572 								&def, &flags);
1573 
1574 	is_menu = (type == V4L2_CTRL_TYPE_MENU ||
1575 		   type == V4L2_CTRL_TYPE_INTEGER_MENU);
1576 	if (is_menu)
1577 		WARN_ON(step);
1578 	else
1579 		WARN_ON(cfg->menu_skip_mask);
1580 	if (type == V4L2_CTRL_TYPE_MENU && !qmenu) {
1581 		qmenu = v4l2_ctrl_get_menu(cfg->id);
1582 	} else if (type == V4L2_CTRL_TYPE_INTEGER_MENU && !qmenu_int) {
1583 		handler_set_err(hdl, -EINVAL);
1584 		return NULL;
1585 	}
1586 
1587 	ctrl = v4l2_ctrl_new(hdl, cfg->ops, cfg->type_ops, cfg->id, name,
1588 			type, min, max,
1589 			is_menu ? cfg->menu_skip_mask : step, def,
1590 			cfg->dims, cfg->elem_size,
1591 			flags, qmenu, qmenu_int, cfg->p_def, priv);
1592 	if (ctrl)
1593 		ctrl->is_private = cfg->is_private;
1594 	return ctrl;
1595 }
1596 EXPORT_SYMBOL(v4l2_ctrl_new_custom);
1597 
1598 /* Helper function for standard non-menu controls */
1599 struct v4l2_ctrl *v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl,
1600 			const struct v4l2_ctrl_ops *ops,
1601 			u32 id, s64 min, s64 max, u64 step, s64 def)
1602 {
1603 	const char *name;
1604 	enum v4l2_ctrl_type type;
1605 	u32 flags;
1606 
1607 	v4l2_ctrl_fill(id, &name, &type, &min, &max, &step, &def, &flags);
1608 	if (type == V4L2_CTRL_TYPE_MENU ||
1609 	    type == V4L2_CTRL_TYPE_INTEGER_MENU ||
1610 	    type >= V4L2_CTRL_COMPOUND_TYPES) {
1611 		handler_set_err(hdl, -EINVAL);
1612 		return NULL;
1613 	}
1614 	return v4l2_ctrl_new(hdl, ops, NULL, id, name, type,
1615 			     min, max, step, def, NULL, 0,
1616 			     flags, NULL, NULL, ptr_null, NULL);
1617 }
1618 EXPORT_SYMBOL(v4l2_ctrl_new_std);
1619 
1620 /* Helper function for standard menu controls */
1621 struct v4l2_ctrl *v4l2_ctrl_new_std_menu(struct v4l2_ctrl_handler *hdl,
1622 			const struct v4l2_ctrl_ops *ops,
1623 			u32 id, u8 _max, u64 mask, u8 _def)
1624 {
1625 	const char * const *qmenu = NULL;
1626 	const s64 *qmenu_int = NULL;
1627 	unsigned int qmenu_int_len = 0;
1628 	const char *name;
1629 	enum v4l2_ctrl_type type;
1630 	s64 min;
1631 	s64 max = _max;
1632 	s64 def = _def;
1633 	u64 step;
1634 	u32 flags;
1635 
1636 	v4l2_ctrl_fill(id, &name, &type, &min, &max, &step, &def, &flags);
1637 
1638 	if (type == V4L2_CTRL_TYPE_MENU)
1639 		qmenu = v4l2_ctrl_get_menu(id);
1640 	else if (type == V4L2_CTRL_TYPE_INTEGER_MENU)
1641 		qmenu_int = v4l2_ctrl_get_int_menu(id, &qmenu_int_len);
1642 
1643 	if ((!qmenu && !qmenu_int) || (qmenu_int && max > qmenu_int_len)) {
1644 		handler_set_err(hdl, -EINVAL);
1645 		return NULL;
1646 	}
1647 	return v4l2_ctrl_new(hdl, ops, NULL, id, name, type,
1648 			     0, max, mask, def, NULL, 0,
1649 			     flags, qmenu, qmenu_int, ptr_null, NULL);
1650 }
1651 EXPORT_SYMBOL(v4l2_ctrl_new_std_menu);
1652 
1653 /* Helper function for standard menu controls with driver defined menu */
1654 struct v4l2_ctrl *v4l2_ctrl_new_std_menu_items(struct v4l2_ctrl_handler *hdl,
1655 			const struct v4l2_ctrl_ops *ops, u32 id, u8 _max,
1656 			u64 mask, u8 _def, const char * const *qmenu)
1657 {
1658 	enum v4l2_ctrl_type type;
1659 	const char *name;
1660 	u32 flags;
1661 	u64 step;
1662 	s64 min;
1663 	s64 max = _max;
1664 	s64 def = _def;
1665 
1666 	/* v4l2_ctrl_new_std_menu_items() should only be called for
1667 	 * standard controls without a standard menu.
1668 	 */
1669 	if (v4l2_ctrl_get_menu(id)) {
1670 		handler_set_err(hdl, -EINVAL);
1671 		return NULL;
1672 	}
1673 
1674 	v4l2_ctrl_fill(id, &name, &type, &min, &max, &step, &def, &flags);
1675 	if (type != V4L2_CTRL_TYPE_MENU || qmenu == NULL) {
1676 		handler_set_err(hdl, -EINVAL);
1677 		return NULL;
1678 	}
1679 	return v4l2_ctrl_new(hdl, ops, NULL, id, name, type,
1680 			     0, max, mask, def, NULL, 0,
1681 			     flags, qmenu, NULL, ptr_null, NULL);
1682 
1683 }
1684 EXPORT_SYMBOL(v4l2_ctrl_new_std_menu_items);
1685 
1686 /* Helper function for standard compound controls */
1687 struct v4l2_ctrl *v4l2_ctrl_new_std_compound(struct v4l2_ctrl_handler *hdl,
1688 				const struct v4l2_ctrl_ops *ops, u32 id,
1689 				const union v4l2_ctrl_ptr p_def)
1690 {
1691 	const char *name;
1692 	enum v4l2_ctrl_type type;
1693 	u32 flags;
1694 	s64 min, max, step, def;
1695 
1696 	v4l2_ctrl_fill(id, &name, &type, &min, &max, &step, &def, &flags);
1697 	if (type < V4L2_CTRL_COMPOUND_TYPES) {
1698 		handler_set_err(hdl, -EINVAL);
1699 		return NULL;
1700 	}
1701 	return v4l2_ctrl_new(hdl, ops, NULL, id, name, type,
1702 			     min, max, step, def, NULL, 0,
1703 			     flags, NULL, NULL, p_def, NULL);
1704 }
1705 EXPORT_SYMBOL(v4l2_ctrl_new_std_compound);
1706 
1707 /* Helper function for standard integer menu controls */
1708 struct v4l2_ctrl *v4l2_ctrl_new_int_menu(struct v4l2_ctrl_handler *hdl,
1709 			const struct v4l2_ctrl_ops *ops,
1710 			u32 id, u8 _max, u8 _def, const s64 *qmenu_int)
1711 {
1712 	const char *name;
1713 	enum v4l2_ctrl_type type;
1714 	s64 min;
1715 	u64 step;
1716 	s64 max = _max;
1717 	s64 def = _def;
1718 	u32 flags;
1719 
1720 	v4l2_ctrl_fill(id, &name, &type, &min, &max, &step, &def, &flags);
1721 	if (type != V4L2_CTRL_TYPE_INTEGER_MENU) {
1722 		handler_set_err(hdl, -EINVAL);
1723 		return NULL;
1724 	}
1725 	return v4l2_ctrl_new(hdl, ops, NULL, id, name, type,
1726 			     0, max, 0, def, NULL, 0,
1727 			     flags, NULL, qmenu_int, ptr_null, NULL);
1728 }
1729 EXPORT_SYMBOL(v4l2_ctrl_new_int_menu);
1730 
1731 /* Add the controls from another handler to our own. */
1732 int v4l2_ctrl_add_handler(struct v4l2_ctrl_handler *hdl,
1733 			  struct v4l2_ctrl_handler *add,
1734 			  bool (*filter)(const struct v4l2_ctrl *ctrl),
1735 			  bool from_other_dev)
1736 {
1737 	struct v4l2_ctrl_ref *ref;
1738 	int ret = 0;
1739 
1740 	/* Do nothing if either handler is NULL or if they are the same */
1741 	if (!hdl || !add || hdl == add)
1742 		return 0;
1743 	if (hdl->error)
1744 		return hdl->error;
1745 	mutex_lock(add->lock);
1746 	list_for_each_entry(ref, &add->ctrl_refs, node) {
1747 		struct v4l2_ctrl *ctrl = ref->ctrl;
1748 
1749 		/* Skip handler-private controls. */
1750 		if (ctrl->is_private)
1751 			continue;
1752 		/* And control classes */
1753 		if (ctrl->type == V4L2_CTRL_TYPE_CTRL_CLASS)
1754 			continue;
1755 		/* Filter any unwanted controls */
1756 		if (filter && !filter(ctrl))
1757 			continue;
1758 		ret = handler_new_ref(hdl, ctrl, NULL, from_other_dev, false);
1759 		if (ret)
1760 			break;
1761 	}
1762 	mutex_unlock(add->lock);
1763 	return ret;
1764 }
1765 EXPORT_SYMBOL(v4l2_ctrl_add_handler);
1766 
1767 bool v4l2_ctrl_radio_filter(const struct v4l2_ctrl *ctrl)
1768 {
1769 	if (V4L2_CTRL_ID2WHICH(ctrl->id) == V4L2_CTRL_CLASS_FM_TX)
1770 		return true;
1771 	if (V4L2_CTRL_ID2WHICH(ctrl->id) == V4L2_CTRL_CLASS_FM_RX)
1772 		return true;
1773 	switch (ctrl->id) {
1774 	case V4L2_CID_AUDIO_MUTE:
1775 	case V4L2_CID_AUDIO_VOLUME:
1776 	case V4L2_CID_AUDIO_BALANCE:
1777 	case V4L2_CID_AUDIO_BASS:
1778 	case V4L2_CID_AUDIO_TREBLE:
1779 	case V4L2_CID_AUDIO_LOUDNESS:
1780 		return true;
1781 	default:
1782 		break;
1783 	}
1784 	return false;
1785 }
1786 EXPORT_SYMBOL(v4l2_ctrl_radio_filter);
1787 
1788 /* Cluster controls */
1789 void v4l2_ctrl_cluster(unsigned ncontrols, struct v4l2_ctrl **controls)
1790 {
1791 	bool has_volatiles = false;
1792 	int i;
1793 
1794 	/* The first control is the master control and it must not be NULL */
1795 	if (WARN_ON(ncontrols == 0 || controls[0] == NULL))
1796 		return;
1797 
1798 	for (i = 0; i < ncontrols; i++) {
1799 		if (controls[i]) {
1800 			controls[i]->cluster = controls;
1801 			controls[i]->ncontrols = ncontrols;
1802 			if (controls[i]->flags & V4L2_CTRL_FLAG_VOLATILE)
1803 				has_volatiles = true;
1804 		}
1805 	}
1806 	controls[0]->has_volatiles = has_volatiles;
1807 }
1808 EXPORT_SYMBOL(v4l2_ctrl_cluster);
1809 
1810 void v4l2_ctrl_auto_cluster(unsigned ncontrols, struct v4l2_ctrl **controls,
1811 			    u8 manual_val, bool set_volatile)
1812 {
1813 	struct v4l2_ctrl *master = controls[0];
1814 	u32 flag = 0;
1815 	int i;
1816 
1817 	v4l2_ctrl_cluster(ncontrols, controls);
1818 	WARN_ON(ncontrols <= 1);
1819 	WARN_ON(manual_val < master->minimum || manual_val > master->maximum);
1820 	WARN_ON(set_volatile && !has_op(master, g_volatile_ctrl));
1821 	master->is_auto = true;
1822 	master->has_volatiles = set_volatile;
1823 	master->manual_mode_value = manual_val;
1824 	master->flags |= V4L2_CTRL_FLAG_UPDATE;
1825 
1826 	if (!is_cur_manual(master))
1827 		flag = V4L2_CTRL_FLAG_INACTIVE |
1828 			(set_volatile ? V4L2_CTRL_FLAG_VOLATILE : 0);
1829 
1830 	for (i = 1; i < ncontrols; i++)
1831 		if (controls[i])
1832 			controls[i]->flags |= flag;
1833 }
1834 EXPORT_SYMBOL(v4l2_ctrl_auto_cluster);
1835 
1836 /*
1837  * Obtain the current volatile values of an autocluster and mark them
1838  * as new.
1839  */
1840 void update_from_auto_cluster(struct v4l2_ctrl *master)
1841 {
1842 	int i;
1843 
1844 	for (i = 1; i < master->ncontrols; i++)
1845 		cur_to_new(master->cluster[i]);
1846 	if (!call_op(master, g_volatile_ctrl))
1847 		for (i = 1; i < master->ncontrols; i++)
1848 			if (master->cluster[i])
1849 				master->cluster[i]->is_new = 1;
1850 }
1851 
1852 /*
1853  * Return non-zero if one or more of the controls in the cluster has a new
1854  * value that differs from the current value.
1855  */
1856 static int cluster_changed(struct v4l2_ctrl *master)
1857 {
1858 	bool changed = false;
1859 	unsigned int idx;
1860 	int i;
1861 
1862 	for (i = 0; i < master->ncontrols; i++) {
1863 		struct v4l2_ctrl *ctrl = master->cluster[i];
1864 		bool ctrl_changed = false;
1865 
1866 		if (!ctrl)
1867 			continue;
1868 
1869 		if (ctrl->flags & V4L2_CTRL_FLAG_EXECUTE_ON_WRITE) {
1870 			changed = true;
1871 			ctrl_changed = true;
1872 		}
1873 
1874 		/*
1875 		 * Set has_changed to false to avoid generating
1876 		 * the event V4L2_EVENT_CTRL_CH_VALUE
1877 		 */
1878 		if (ctrl->flags & V4L2_CTRL_FLAG_VOLATILE) {
1879 			ctrl->has_changed = false;
1880 			continue;
1881 		}
1882 
1883 		for (idx = 0; !ctrl_changed && idx < ctrl->elems; idx++)
1884 			ctrl_changed = !ctrl->type_ops->equal(ctrl, idx,
1885 				ctrl->p_cur, ctrl->p_new);
1886 		ctrl->has_changed = ctrl_changed;
1887 		changed |= ctrl->has_changed;
1888 	}
1889 	return changed;
1890 }
1891 
1892 /*
1893  * Core function that calls try/s_ctrl and ensures that the new value is
1894  * copied to the current value on a set.
1895  * Must be called with ctrl->handler->lock held.
1896  */
1897 int try_or_set_cluster(struct v4l2_fh *fh, struct v4l2_ctrl *master,
1898 		       bool set, u32 ch_flags)
1899 {
1900 	bool update_flag;
1901 	int ret;
1902 	int i;
1903 
1904 	/*
1905 	 * Go through the cluster and either validate the new value or
1906 	 * (if no new value was set), copy the current value to the new
1907 	 * value, ensuring a consistent view for the control ops when
1908 	 * called.
1909 	 */
1910 	for (i = 0; i < master->ncontrols; i++) {
1911 		struct v4l2_ctrl *ctrl = master->cluster[i];
1912 
1913 		if (!ctrl)
1914 			continue;
1915 
1916 		if (!ctrl->is_new) {
1917 			cur_to_new(ctrl);
1918 			continue;
1919 		}
1920 		/*
1921 		 * Check again: it may have changed since the
1922 		 * previous check in try_or_set_ext_ctrls().
1923 		 */
1924 		if (set && (ctrl->flags & V4L2_CTRL_FLAG_GRABBED))
1925 			return -EBUSY;
1926 	}
1927 
1928 	ret = call_op(master, try_ctrl);
1929 
1930 	/* Don't set if there is no change */
1931 	if (ret || !set || !cluster_changed(master))
1932 		return ret;
1933 	ret = call_op(master, s_ctrl);
1934 	if (ret)
1935 		return ret;
1936 
1937 	/* If OK, then make the new values permanent. */
1938 	update_flag = is_cur_manual(master) != is_new_manual(master);
1939 
1940 	for (i = 0; i < master->ncontrols; i++) {
1941 		/*
1942 		 * If we switch from auto to manual mode, and this cluster
1943 		 * contains volatile controls, then all non-master controls
1944 		 * have to be marked as changed. The 'new' value contains
1945 		 * the volatile value (obtained by update_from_auto_cluster),
1946 		 * which now has to become the current value.
1947 		 */
1948 		if (i && update_flag && is_new_manual(master) &&
1949 		    master->has_volatiles && master->cluster[i])
1950 			master->cluster[i]->has_changed = true;
1951 
1952 		new_to_cur(fh, master->cluster[i], ch_flags |
1953 			((update_flag && i > 0) ? V4L2_EVENT_CTRL_CH_FLAGS : 0));
1954 	}
1955 	return 0;
1956 }
1957 
1958 /* Activate/deactivate a control. */
1959 void v4l2_ctrl_activate(struct v4l2_ctrl *ctrl, bool active)
1960 {
1961 	/* invert since the actual flag is called 'inactive' */
1962 	bool inactive = !active;
1963 	bool old;
1964 
1965 	if (ctrl == NULL)
1966 		return;
1967 
1968 	if (inactive)
1969 		/* set V4L2_CTRL_FLAG_INACTIVE */
1970 		old = test_and_set_bit(4, &ctrl->flags);
1971 	else
1972 		/* clear V4L2_CTRL_FLAG_INACTIVE */
1973 		old = test_and_clear_bit(4, &ctrl->flags);
1974 	if (old != inactive)
1975 		send_event(NULL, ctrl, V4L2_EVENT_CTRL_CH_FLAGS);
1976 }
1977 EXPORT_SYMBOL(v4l2_ctrl_activate);
1978 
1979 void __v4l2_ctrl_grab(struct v4l2_ctrl *ctrl, bool grabbed)
1980 {
1981 	bool old;
1982 
1983 	if (ctrl == NULL)
1984 		return;
1985 
1986 	lockdep_assert_held(ctrl->handler->lock);
1987 
1988 	if (grabbed)
1989 		/* set V4L2_CTRL_FLAG_GRABBED */
1990 		old = test_and_set_bit(1, &ctrl->flags);
1991 	else
1992 		/* clear V4L2_CTRL_FLAG_GRABBED */
1993 		old = test_and_clear_bit(1, &ctrl->flags);
1994 	if (old != grabbed)
1995 		send_event(NULL, ctrl, V4L2_EVENT_CTRL_CH_FLAGS);
1996 }
1997 EXPORT_SYMBOL(__v4l2_ctrl_grab);
1998 
1999 /* Call s_ctrl for all controls owned by the handler */
2000 int __v4l2_ctrl_handler_setup(struct v4l2_ctrl_handler *hdl)
2001 {
2002 	struct v4l2_ctrl *ctrl;
2003 	int ret = 0;
2004 
2005 	if (hdl == NULL)
2006 		return 0;
2007 
2008 	lockdep_assert_held(hdl->lock);
2009 
2010 	list_for_each_entry(ctrl, &hdl->ctrls, node)
2011 		ctrl->done = false;
2012 
2013 	list_for_each_entry(ctrl, &hdl->ctrls, node) {
2014 		struct v4l2_ctrl *master = ctrl->cluster[0];
2015 		int i;
2016 
2017 		/* Skip if this control was already handled by a cluster. */
2018 		/* Skip button controls and read-only controls. */
2019 		if (ctrl->done || ctrl->type == V4L2_CTRL_TYPE_BUTTON ||
2020 		    (ctrl->flags & V4L2_CTRL_FLAG_READ_ONLY))
2021 			continue;
2022 
2023 		for (i = 0; i < master->ncontrols; i++) {
2024 			if (master->cluster[i]) {
2025 				cur_to_new(master->cluster[i]);
2026 				master->cluster[i]->is_new = 1;
2027 				master->cluster[i]->done = true;
2028 			}
2029 		}
2030 		ret = call_op(master, s_ctrl);
2031 		if (ret)
2032 			break;
2033 	}
2034 
2035 	return ret;
2036 }
2037 EXPORT_SYMBOL_GPL(__v4l2_ctrl_handler_setup);
2038 
2039 int v4l2_ctrl_handler_setup(struct v4l2_ctrl_handler *hdl)
2040 {
2041 	int ret;
2042 
2043 	if (hdl == NULL)
2044 		return 0;
2045 
2046 	mutex_lock(hdl->lock);
2047 	ret = __v4l2_ctrl_handler_setup(hdl);
2048 	mutex_unlock(hdl->lock);
2049 
2050 	return ret;
2051 }
2052 EXPORT_SYMBOL(v4l2_ctrl_handler_setup);
2053 
2054 /* Log the control name and value */
2055 static void log_ctrl(const struct v4l2_ctrl *ctrl,
2056 		     const char *prefix, const char *colon)
2057 {
2058 	if (ctrl->flags & (V4L2_CTRL_FLAG_DISABLED | V4L2_CTRL_FLAG_WRITE_ONLY))
2059 		return;
2060 	if (ctrl->type == V4L2_CTRL_TYPE_CTRL_CLASS)
2061 		return;
2062 
2063 	pr_info("%s%s%s: ", prefix, colon, ctrl->name);
2064 
2065 	ctrl->type_ops->log(ctrl);
2066 
2067 	if (ctrl->flags & (V4L2_CTRL_FLAG_INACTIVE |
2068 			   V4L2_CTRL_FLAG_GRABBED |
2069 			   V4L2_CTRL_FLAG_VOLATILE)) {
2070 		if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
2071 			pr_cont(" inactive");
2072 		if (ctrl->flags & V4L2_CTRL_FLAG_GRABBED)
2073 			pr_cont(" grabbed");
2074 		if (ctrl->flags & V4L2_CTRL_FLAG_VOLATILE)
2075 			pr_cont(" volatile");
2076 	}
2077 	pr_cont("\n");
2078 }
2079 
2080 /* Log all controls owned by the handler */
2081 void v4l2_ctrl_handler_log_status(struct v4l2_ctrl_handler *hdl,
2082 				  const char *prefix)
2083 {
2084 	struct v4l2_ctrl *ctrl;
2085 	const char *colon = "";
2086 	int len;
2087 
2088 	if (!hdl)
2089 		return;
2090 	if (!prefix)
2091 		prefix = "";
2092 	len = strlen(prefix);
2093 	if (len && prefix[len - 1] != ' ')
2094 		colon = ": ";
2095 	mutex_lock(hdl->lock);
2096 	list_for_each_entry(ctrl, &hdl->ctrls, node)
2097 		if (!(ctrl->flags & V4L2_CTRL_FLAG_DISABLED))
2098 			log_ctrl(ctrl, prefix, colon);
2099 	mutex_unlock(hdl->lock);
2100 }
2101 EXPORT_SYMBOL(v4l2_ctrl_handler_log_status);
2102 
2103 int v4l2_ctrl_new_fwnode_properties(struct v4l2_ctrl_handler *hdl,
2104 				    const struct v4l2_ctrl_ops *ctrl_ops,
2105 				    const struct v4l2_fwnode_device_properties *p)
2106 {
2107 	if (p->orientation != V4L2_FWNODE_PROPERTY_UNSET) {
2108 		u32 orientation_ctrl;
2109 
2110 		switch (p->orientation) {
2111 		case V4L2_FWNODE_ORIENTATION_FRONT:
2112 			orientation_ctrl = V4L2_CAMERA_ORIENTATION_FRONT;
2113 			break;
2114 		case V4L2_FWNODE_ORIENTATION_BACK:
2115 			orientation_ctrl = V4L2_CAMERA_ORIENTATION_BACK;
2116 			break;
2117 		case V4L2_FWNODE_ORIENTATION_EXTERNAL:
2118 			orientation_ctrl = V4L2_CAMERA_ORIENTATION_EXTERNAL;
2119 			break;
2120 		default:
2121 			return -EINVAL;
2122 		}
2123 		if (!v4l2_ctrl_new_std_menu(hdl, ctrl_ops,
2124 					    V4L2_CID_CAMERA_ORIENTATION,
2125 					    V4L2_CAMERA_ORIENTATION_EXTERNAL, 0,
2126 					    orientation_ctrl))
2127 			return hdl->error;
2128 	}
2129 
2130 	if (p->rotation != V4L2_FWNODE_PROPERTY_UNSET) {
2131 		if (!v4l2_ctrl_new_std(hdl, ctrl_ops,
2132 				       V4L2_CID_CAMERA_SENSOR_ROTATION,
2133 				       p->rotation, p->rotation, 1,
2134 				       p->rotation))
2135 			return hdl->error;
2136 	}
2137 
2138 	return hdl->error;
2139 }
2140 EXPORT_SYMBOL(v4l2_ctrl_new_fwnode_properties);
2141