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