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