GNU Linux-libre 4.9.309-gnu1
[releases.git] / drivers / media / i2c / smiapp / smiapp-core.c
1 /*
2  * drivers/media/i2c/smiapp/smiapp-core.c
3  *
4  * Generic driver for SMIA/SMIA++ compliant camera modules
5  *
6  * Copyright (C) 2010--2012 Nokia Corporation
7  * Contact: Sakari Ailus <sakari.ailus@iki.fi>
8  *
9  * Based on smiapp driver by Vimarsh Zutshi
10  * Based on jt8ev1.c by Vimarsh Zutshi
11  * Based on smia-sensor.c by Tuukka Toivonen <tuukkat76@gmail.com>
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * version 2 as published by the Free Software Foundation.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  */
22
23 #include <linux/clk.h>
24 #include <linux/delay.h>
25 #include <linux/device.h>
26 #include <linux/gpio.h>
27 #include <linux/gpio/consumer.h>
28 #include <linux/module.h>
29 #include <linux/regulator/consumer.h>
30 #include <linux/slab.h>
31 #include <linux/smiapp.h>
32 #include <linux/v4l2-mediabus.h>
33 #include <media/v4l2-device.h>
34 #include <media/v4l2-of.h>
35
36 #include "smiapp.h"
37
38 #define SMIAPP_ALIGN_DIM(dim, flags)    \
39         ((flags) & V4L2_SEL_FLAG_GE     \
40          ? ALIGN((dim), 2)              \
41          : (dim) & ~1)
42
43 /*
44  * smiapp_module_idents - supported camera modules
45  */
46 static const struct smiapp_module_ident smiapp_module_idents[] = {
47         SMIAPP_IDENT_L(0x01, 0x022b, -1, "vs6555"),
48         SMIAPP_IDENT_L(0x01, 0x022e, -1, "vw6558"),
49         SMIAPP_IDENT_L(0x07, 0x7698, -1, "ovm7698"),
50         SMIAPP_IDENT_L(0x0b, 0x4242, -1, "smiapp-003"),
51         SMIAPP_IDENT_L(0x0c, 0x208a, -1, "tcm8330md"),
52         SMIAPP_IDENT_LQ(0x0c, 0x2134, -1, "tcm8500md", &smiapp_tcm8500md_quirk),
53         SMIAPP_IDENT_L(0x0c, 0x213e, -1, "et8en2"),
54         SMIAPP_IDENT_L(0x0c, 0x2184, -1, "tcm8580md"),
55         SMIAPP_IDENT_LQ(0x0c, 0x560f, -1, "jt8ew9", &smiapp_jt8ew9_quirk),
56         SMIAPP_IDENT_LQ(0x10, 0x4141, -1, "jt8ev1", &smiapp_jt8ev1_quirk),
57         SMIAPP_IDENT_LQ(0x10, 0x4241, -1, "imx125es", &smiapp_imx125es_quirk),
58 };
59
60 /*
61  *
62  * Dynamic Capability Identification
63  *
64  */
65
66 static int smiapp_read_frame_fmt(struct smiapp_sensor *sensor)
67 {
68         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
69         u32 fmt_model_type, fmt_model_subtype, ncol_desc, nrow_desc;
70         unsigned int i;
71         int rval;
72         int line_count = 0;
73         int embedded_start = -1, embedded_end = -1;
74         int image_start = 0;
75
76         rval = smiapp_read(sensor, SMIAPP_REG_U8_FRAME_FORMAT_MODEL_TYPE,
77                            &fmt_model_type);
78         if (rval)
79                 return rval;
80
81         rval = smiapp_read(sensor, SMIAPP_REG_U8_FRAME_FORMAT_MODEL_SUBTYPE,
82                            &fmt_model_subtype);
83         if (rval)
84                 return rval;
85
86         ncol_desc = (fmt_model_subtype
87                      & SMIAPP_FRAME_FORMAT_MODEL_SUBTYPE_NCOLS_MASK)
88                 >> SMIAPP_FRAME_FORMAT_MODEL_SUBTYPE_NCOLS_SHIFT;
89         nrow_desc = fmt_model_subtype
90                 & SMIAPP_FRAME_FORMAT_MODEL_SUBTYPE_NROWS_MASK;
91
92         dev_dbg(&client->dev, "format_model_type %s\n",
93                 fmt_model_type == SMIAPP_FRAME_FORMAT_MODEL_TYPE_2BYTE
94                 ? "2 byte" :
95                 fmt_model_type == SMIAPP_FRAME_FORMAT_MODEL_TYPE_4BYTE
96                 ? "4 byte" : "is simply bad");
97
98         for (i = 0; i < ncol_desc + nrow_desc; i++) {
99                 u32 desc;
100                 u32 pixelcode;
101                 u32 pixels;
102                 char *which;
103                 char *what;
104
105                 if (fmt_model_type == SMIAPP_FRAME_FORMAT_MODEL_TYPE_2BYTE) {
106                         rval = smiapp_read(
107                                 sensor,
108                                 SMIAPP_REG_U16_FRAME_FORMAT_DESCRIPTOR_2(i),
109                                 &desc);
110                         if (rval)
111                                 return rval;
112
113                         pixelcode =
114                                 (desc
115                                  & SMIAPP_FRAME_FORMAT_DESC_2_PIXELCODE_MASK)
116                                 >> SMIAPP_FRAME_FORMAT_DESC_2_PIXELCODE_SHIFT;
117                         pixels = desc & SMIAPP_FRAME_FORMAT_DESC_2_PIXELS_MASK;
118                 } else if (fmt_model_type
119                            == SMIAPP_FRAME_FORMAT_MODEL_TYPE_4BYTE) {
120                         rval = smiapp_read(
121                                 sensor,
122                                 SMIAPP_REG_U32_FRAME_FORMAT_DESCRIPTOR_4(i),
123                                 &desc);
124                         if (rval)
125                                 return rval;
126
127                         pixelcode =
128                                 (desc
129                                  & SMIAPP_FRAME_FORMAT_DESC_4_PIXELCODE_MASK)
130                                 >> SMIAPP_FRAME_FORMAT_DESC_4_PIXELCODE_SHIFT;
131                         pixels = desc & SMIAPP_FRAME_FORMAT_DESC_4_PIXELS_MASK;
132                 } else {
133                         dev_dbg(&client->dev,
134                                 "invalid frame format model type %d\n",
135                                 fmt_model_type);
136                         return -EINVAL;
137                 }
138
139                 if (i < ncol_desc)
140                         which = "columns";
141                 else
142                         which = "rows";
143
144                 switch (pixelcode) {
145                 case SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_EMBEDDED:
146                         what = "embedded";
147                         break;
148                 case SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_DUMMY:
149                         what = "dummy";
150                         break;
151                 case SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_BLACK:
152                         what = "black";
153                         break;
154                 case SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_DARK:
155                         what = "dark";
156                         break;
157                 case SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_VISIBLE:
158                         what = "visible";
159                         break;
160                 default:
161                         what = "invalid";
162                         dev_dbg(&client->dev, "pixelcode %d\n", pixelcode);
163                         break;
164                 }
165
166                 dev_dbg(&client->dev, "%s pixels: %d %s\n",
167                         what, pixels, which);
168
169                 if (i < ncol_desc)
170                         continue;
171
172                 /* Handle row descriptors */
173                 if (pixelcode
174                     == SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_EMBEDDED) {
175                         embedded_start = line_count;
176                 } else {
177                         if (pixelcode == SMIAPP_FRAME_FORMAT_DESC_PIXELCODE_VISIBLE
178                             || pixels >= sensor->limits[SMIAPP_LIMIT_MIN_FRAME_LENGTH_LINES] / 2)
179                                 image_start = line_count;
180                         if (embedded_start != -1 && embedded_end == -1)
181                                 embedded_end = line_count;
182                 }
183                 line_count += pixels;
184         }
185
186         if (embedded_start == -1 || embedded_end == -1) {
187                 embedded_start = 0;
188                 embedded_end = 0;
189         }
190
191         sensor->image_start = image_start;
192
193         dev_dbg(&client->dev, "embedded data from lines %d to %d\n",
194                 embedded_start, embedded_end);
195         dev_dbg(&client->dev, "image data starts at line %d\n", image_start);
196
197         return 0;
198 }
199
200 static int smiapp_pll_configure(struct smiapp_sensor *sensor)
201 {
202         struct smiapp_pll *pll = &sensor->pll;
203         int rval;
204
205         rval = smiapp_write(
206                 sensor, SMIAPP_REG_U16_VT_PIX_CLK_DIV, pll->vt.pix_clk_div);
207         if (rval < 0)
208                 return rval;
209
210         rval = smiapp_write(
211                 sensor, SMIAPP_REG_U16_VT_SYS_CLK_DIV, pll->vt.sys_clk_div);
212         if (rval < 0)
213                 return rval;
214
215         rval = smiapp_write(
216                 sensor, SMIAPP_REG_U16_PRE_PLL_CLK_DIV, pll->pre_pll_clk_div);
217         if (rval < 0)
218                 return rval;
219
220         rval = smiapp_write(
221                 sensor, SMIAPP_REG_U16_PLL_MULTIPLIER, pll->pll_multiplier);
222         if (rval < 0)
223                 return rval;
224
225         /* Lane op clock ratio does not apply here. */
226         rval = smiapp_write(
227                 sensor, SMIAPP_REG_U32_REQUESTED_LINK_BIT_RATE_MBPS,
228                 DIV_ROUND_UP(pll->op.sys_clk_freq_hz, 1000000 / 256 / 256));
229         if (rval < 0 || sensor->minfo.smiapp_profile == SMIAPP_PROFILE_0)
230                 return rval;
231
232         rval = smiapp_write(
233                 sensor, SMIAPP_REG_U16_OP_PIX_CLK_DIV, pll->op.pix_clk_div);
234         if (rval < 0)
235                 return rval;
236
237         return smiapp_write(
238                 sensor, SMIAPP_REG_U16_OP_SYS_CLK_DIV, pll->op.sys_clk_div);
239 }
240
241 static int smiapp_pll_try(struct smiapp_sensor *sensor,
242                           struct smiapp_pll *pll)
243 {
244         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
245         struct smiapp_pll_limits lim = {
246                 .min_pre_pll_clk_div = sensor->limits[SMIAPP_LIMIT_MIN_PRE_PLL_CLK_DIV],
247                 .max_pre_pll_clk_div = sensor->limits[SMIAPP_LIMIT_MAX_PRE_PLL_CLK_DIV],
248                 .min_pll_ip_freq_hz = sensor->limits[SMIAPP_LIMIT_MIN_PLL_IP_FREQ_HZ],
249                 .max_pll_ip_freq_hz = sensor->limits[SMIAPP_LIMIT_MAX_PLL_IP_FREQ_HZ],
250                 .min_pll_multiplier = sensor->limits[SMIAPP_LIMIT_MIN_PLL_MULTIPLIER],
251                 .max_pll_multiplier = sensor->limits[SMIAPP_LIMIT_MAX_PLL_MULTIPLIER],
252                 .min_pll_op_freq_hz = sensor->limits[SMIAPP_LIMIT_MIN_PLL_OP_FREQ_HZ],
253                 .max_pll_op_freq_hz = sensor->limits[SMIAPP_LIMIT_MAX_PLL_OP_FREQ_HZ],
254
255                 .op.min_sys_clk_div = sensor->limits[SMIAPP_LIMIT_MIN_OP_SYS_CLK_DIV],
256                 .op.max_sys_clk_div = sensor->limits[SMIAPP_LIMIT_MAX_OP_SYS_CLK_DIV],
257                 .op.min_pix_clk_div = sensor->limits[SMIAPP_LIMIT_MIN_OP_PIX_CLK_DIV],
258                 .op.max_pix_clk_div = sensor->limits[SMIAPP_LIMIT_MAX_OP_PIX_CLK_DIV],
259                 .op.min_sys_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MIN_OP_SYS_CLK_FREQ_HZ],
260                 .op.max_sys_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MAX_OP_SYS_CLK_FREQ_HZ],
261                 .op.min_pix_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MIN_OP_PIX_CLK_FREQ_HZ],
262                 .op.max_pix_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MAX_OP_PIX_CLK_FREQ_HZ],
263
264                 .vt.min_sys_clk_div = sensor->limits[SMIAPP_LIMIT_MIN_VT_SYS_CLK_DIV],
265                 .vt.max_sys_clk_div = sensor->limits[SMIAPP_LIMIT_MAX_VT_SYS_CLK_DIV],
266                 .vt.min_pix_clk_div = sensor->limits[SMIAPP_LIMIT_MIN_VT_PIX_CLK_DIV],
267                 .vt.max_pix_clk_div = sensor->limits[SMIAPP_LIMIT_MAX_VT_PIX_CLK_DIV],
268                 .vt.min_sys_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MIN_VT_SYS_CLK_FREQ_HZ],
269                 .vt.max_sys_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MAX_VT_SYS_CLK_FREQ_HZ],
270                 .vt.min_pix_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MIN_VT_PIX_CLK_FREQ_HZ],
271                 .vt.max_pix_clk_freq_hz = sensor->limits[SMIAPP_LIMIT_MAX_VT_PIX_CLK_FREQ_HZ],
272
273                 .min_line_length_pck_bin = sensor->limits[SMIAPP_LIMIT_MIN_LINE_LENGTH_PCK_BIN],
274                 .min_line_length_pck = sensor->limits[SMIAPP_LIMIT_MIN_LINE_LENGTH_PCK],
275         };
276
277         return smiapp_pll_calculate(&client->dev, &lim, pll);
278 }
279
280 static int smiapp_pll_update(struct smiapp_sensor *sensor)
281 {
282         struct smiapp_pll *pll = &sensor->pll;
283         int rval;
284
285         pll->binning_horizontal = sensor->binning_horizontal;
286         pll->binning_vertical = sensor->binning_vertical;
287         pll->link_freq =
288                 sensor->link_freq->qmenu_int[sensor->link_freq->val];
289         pll->scale_m = sensor->scale_m;
290         pll->bits_per_pixel = sensor->csi_format->compressed;
291
292         rval = smiapp_pll_try(sensor, pll);
293         if (rval < 0)
294                 return rval;
295
296         __v4l2_ctrl_s_ctrl_int64(sensor->pixel_rate_parray,
297                                  pll->pixel_rate_pixel_array);
298         __v4l2_ctrl_s_ctrl_int64(sensor->pixel_rate_csi, pll->pixel_rate_csi);
299
300         return 0;
301 }
302
303
304 /*
305  *
306  * V4L2 Controls handling
307  *
308  */
309
310 static void __smiapp_update_exposure_limits(struct smiapp_sensor *sensor)
311 {
312         struct v4l2_ctrl *ctrl = sensor->exposure;
313         int max;
314
315         max = sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].height
316                 + sensor->vblank->val
317                 - sensor->limits[SMIAPP_LIMIT_COARSE_INTEGRATION_TIME_MAX_MARGIN];
318
319         __v4l2_ctrl_modify_range(ctrl, ctrl->minimum, max, ctrl->step, max);
320 }
321
322 /*
323  * Order matters.
324  *
325  * 1. Bits-per-pixel, descending.
326  * 2. Bits-per-pixel compressed, descending.
327  * 3. Pixel order, same as in pixel_order_str. Formats for all four pixel
328  *    orders must be defined.
329  */
330 static const struct smiapp_csi_data_format smiapp_csi_data_formats[] = {
331         { MEDIA_BUS_FMT_SGRBG16_1X16, 16, 16, SMIAPP_PIXEL_ORDER_GRBG, },
332         { MEDIA_BUS_FMT_SRGGB16_1X16, 16, 16, SMIAPP_PIXEL_ORDER_RGGB, },
333         { MEDIA_BUS_FMT_SBGGR16_1X16, 16, 16, SMIAPP_PIXEL_ORDER_BGGR, },
334         { MEDIA_BUS_FMT_SGBRG16_1X16, 16, 16, SMIAPP_PIXEL_ORDER_GBRG, },
335         { MEDIA_BUS_FMT_SGRBG14_1X14, 14, 14, SMIAPP_PIXEL_ORDER_GRBG, },
336         { MEDIA_BUS_FMT_SRGGB14_1X14, 14, 14, SMIAPP_PIXEL_ORDER_RGGB, },
337         { MEDIA_BUS_FMT_SBGGR14_1X14, 14, 14, SMIAPP_PIXEL_ORDER_BGGR, },
338         { MEDIA_BUS_FMT_SGBRG14_1X14, 14, 14, SMIAPP_PIXEL_ORDER_GBRG, },
339         { MEDIA_BUS_FMT_SGRBG12_1X12, 12, 12, SMIAPP_PIXEL_ORDER_GRBG, },
340         { MEDIA_BUS_FMT_SRGGB12_1X12, 12, 12, SMIAPP_PIXEL_ORDER_RGGB, },
341         { MEDIA_BUS_FMT_SBGGR12_1X12, 12, 12, SMIAPP_PIXEL_ORDER_BGGR, },
342         { MEDIA_BUS_FMT_SGBRG12_1X12, 12, 12, SMIAPP_PIXEL_ORDER_GBRG, },
343         { MEDIA_BUS_FMT_SGRBG10_1X10, 10, 10, SMIAPP_PIXEL_ORDER_GRBG, },
344         { MEDIA_BUS_FMT_SRGGB10_1X10, 10, 10, SMIAPP_PIXEL_ORDER_RGGB, },
345         { MEDIA_BUS_FMT_SBGGR10_1X10, 10, 10, SMIAPP_PIXEL_ORDER_BGGR, },
346         { MEDIA_BUS_FMT_SGBRG10_1X10, 10, 10, SMIAPP_PIXEL_ORDER_GBRG, },
347         { MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, 10, 8, SMIAPP_PIXEL_ORDER_GRBG, },
348         { MEDIA_BUS_FMT_SRGGB10_DPCM8_1X8, 10, 8, SMIAPP_PIXEL_ORDER_RGGB, },
349         { MEDIA_BUS_FMT_SBGGR10_DPCM8_1X8, 10, 8, SMIAPP_PIXEL_ORDER_BGGR, },
350         { MEDIA_BUS_FMT_SGBRG10_DPCM8_1X8, 10, 8, SMIAPP_PIXEL_ORDER_GBRG, },
351         { MEDIA_BUS_FMT_SGRBG8_1X8, 8, 8, SMIAPP_PIXEL_ORDER_GRBG, },
352         { MEDIA_BUS_FMT_SRGGB8_1X8, 8, 8, SMIAPP_PIXEL_ORDER_RGGB, },
353         { MEDIA_BUS_FMT_SBGGR8_1X8, 8, 8, SMIAPP_PIXEL_ORDER_BGGR, },
354         { MEDIA_BUS_FMT_SGBRG8_1X8, 8, 8, SMIAPP_PIXEL_ORDER_GBRG, },
355 };
356
357 static const char *pixel_order_str[] = { "GRBG", "RGGB", "BGGR", "GBRG" };
358
359 #define to_csi_format_idx(fmt) (((unsigned long)(fmt)                   \
360                                  - (unsigned long)smiapp_csi_data_formats) \
361                                 / sizeof(*smiapp_csi_data_formats))
362
363 static u32 smiapp_pixel_order(struct smiapp_sensor *sensor)
364 {
365         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
366         int flip = 0;
367
368         if (sensor->hflip) {
369                 if (sensor->hflip->val)
370                         flip |= SMIAPP_IMAGE_ORIENTATION_HFLIP;
371
372                 if (sensor->vflip->val)
373                         flip |= SMIAPP_IMAGE_ORIENTATION_VFLIP;
374         }
375
376         flip ^= sensor->hvflip_inv_mask;
377
378         dev_dbg(&client->dev, "flip %d\n", flip);
379         return sensor->default_pixel_order ^ flip;
380 }
381
382 static void smiapp_update_mbus_formats(struct smiapp_sensor *sensor)
383 {
384         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
385         unsigned int csi_format_idx =
386                 to_csi_format_idx(sensor->csi_format) & ~3;
387         unsigned int internal_csi_format_idx =
388                 to_csi_format_idx(sensor->internal_csi_format) & ~3;
389         unsigned int pixel_order = smiapp_pixel_order(sensor);
390
391         sensor->mbus_frame_fmts =
392                 sensor->default_mbus_frame_fmts << pixel_order;
393         sensor->csi_format =
394                 &smiapp_csi_data_formats[csi_format_idx + pixel_order];
395         sensor->internal_csi_format =
396                 &smiapp_csi_data_formats[internal_csi_format_idx
397                                          + pixel_order];
398
399         BUG_ON(max(internal_csi_format_idx, csi_format_idx) + pixel_order
400                >= ARRAY_SIZE(smiapp_csi_data_formats));
401
402         dev_dbg(&client->dev, "new pixel order %s\n",
403                 pixel_order_str[pixel_order]);
404 }
405
406 static const char * const smiapp_test_patterns[] = {
407         "Disabled",
408         "Solid Colour",
409         "Eight Vertical Colour Bars",
410         "Colour Bars With Fade to Grey",
411         "Pseudorandom Sequence (PN9)",
412 };
413
414 static int smiapp_set_ctrl(struct v4l2_ctrl *ctrl)
415 {
416         struct smiapp_sensor *sensor =
417                 container_of(ctrl->handler, struct smiapp_subdev, ctrl_handler)
418                         ->sensor;
419         u32 orient = 0;
420         int exposure;
421         int rval;
422
423         switch (ctrl->id) {
424         case V4L2_CID_ANALOGUE_GAIN:
425                 return smiapp_write(
426                         sensor,
427                         SMIAPP_REG_U16_ANALOGUE_GAIN_CODE_GLOBAL, ctrl->val);
428
429         case V4L2_CID_EXPOSURE:
430                 return smiapp_write(
431                         sensor,
432                         SMIAPP_REG_U16_COARSE_INTEGRATION_TIME, ctrl->val);
433
434         case V4L2_CID_HFLIP:
435         case V4L2_CID_VFLIP:
436                 if (sensor->streaming)
437                         return -EBUSY;
438
439                 if (sensor->hflip->val)
440                         orient |= SMIAPP_IMAGE_ORIENTATION_HFLIP;
441
442                 if (sensor->vflip->val)
443                         orient |= SMIAPP_IMAGE_ORIENTATION_VFLIP;
444
445                 orient ^= sensor->hvflip_inv_mask;
446                 rval = smiapp_write(sensor,
447                                     SMIAPP_REG_U8_IMAGE_ORIENTATION,
448                                     orient);
449                 if (rval < 0)
450                         return rval;
451
452                 smiapp_update_mbus_formats(sensor);
453
454                 return 0;
455
456         case V4L2_CID_VBLANK:
457                 exposure = sensor->exposure->val;
458
459                 __smiapp_update_exposure_limits(sensor);
460
461                 if (exposure > sensor->exposure->maximum) {
462                         sensor->exposure->val =
463                                 sensor->exposure->maximum;
464                         rval = smiapp_set_ctrl(
465                                 sensor->exposure);
466                         if (rval < 0)
467                                 return rval;
468                 }
469
470                 return smiapp_write(
471                         sensor, SMIAPP_REG_U16_FRAME_LENGTH_LINES,
472                         sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].height
473                         + ctrl->val);
474
475         case V4L2_CID_HBLANK:
476                 return smiapp_write(
477                         sensor, SMIAPP_REG_U16_LINE_LENGTH_PCK,
478                         sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].width
479                         + ctrl->val);
480
481         case V4L2_CID_LINK_FREQ:
482                 if (sensor->streaming)
483                         return -EBUSY;
484
485                 return smiapp_pll_update(sensor);
486
487         case V4L2_CID_TEST_PATTERN: {
488                 unsigned int i;
489
490                 for (i = 0; i < ARRAY_SIZE(sensor->test_data); i++)
491                         v4l2_ctrl_activate(
492                                 sensor->test_data[i],
493                                 ctrl->val ==
494                                 V4L2_SMIAPP_TEST_PATTERN_MODE_SOLID_COLOUR);
495
496                 return smiapp_write(
497                         sensor, SMIAPP_REG_U16_TEST_PATTERN_MODE, ctrl->val);
498         }
499
500         case V4L2_CID_TEST_PATTERN_RED:
501                 return smiapp_write(
502                         sensor, SMIAPP_REG_U16_TEST_DATA_RED, ctrl->val);
503
504         case V4L2_CID_TEST_PATTERN_GREENR:
505                 return smiapp_write(
506                         sensor, SMIAPP_REG_U16_TEST_DATA_GREENR, ctrl->val);
507
508         case V4L2_CID_TEST_PATTERN_BLUE:
509                 return smiapp_write(
510                         sensor, SMIAPP_REG_U16_TEST_DATA_BLUE, ctrl->val);
511
512         case V4L2_CID_TEST_PATTERN_GREENB:
513                 return smiapp_write(
514                         sensor, SMIAPP_REG_U16_TEST_DATA_GREENB, ctrl->val);
515
516         case V4L2_CID_PIXEL_RATE:
517                 /* For v4l2_ctrl_s_ctrl_int64() used internally. */
518                 return 0;
519
520         default:
521                 return -EINVAL;
522         }
523 }
524
525 static const struct v4l2_ctrl_ops smiapp_ctrl_ops = {
526         .s_ctrl = smiapp_set_ctrl,
527 };
528
529 static int smiapp_init_controls(struct smiapp_sensor *sensor)
530 {
531         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
532         int rval;
533
534         rval = v4l2_ctrl_handler_init(&sensor->pixel_array->ctrl_handler, 12);
535         if (rval)
536                 return rval;
537
538         sensor->pixel_array->ctrl_handler.lock = &sensor->mutex;
539
540         sensor->analog_gain = v4l2_ctrl_new_std(
541                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
542                 V4L2_CID_ANALOGUE_GAIN,
543                 sensor->limits[SMIAPP_LIMIT_ANALOGUE_GAIN_CODE_MIN],
544                 sensor->limits[SMIAPP_LIMIT_ANALOGUE_GAIN_CODE_MAX],
545                 max(sensor->limits[SMIAPP_LIMIT_ANALOGUE_GAIN_CODE_STEP], 1U),
546                 sensor->limits[SMIAPP_LIMIT_ANALOGUE_GAIN_CODE_MIN]);
547
548         /* Exposure limits will be updated soon, use just something here. */
549         sensor->exposure = v4l2_ctrl_new_std(
550                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
551                 V4L2_CID_EXPOSURE, 0, 0, 1, 0);
552
553         sensor->hflip = v4l2_ctrl_new_std(
554                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
555                 V4L2_CID_HFLIP, 0, 1, 1, 0);
556         sensor->vflip = v4l2_ctrl_new_std(
557                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
558                 V4L2_CID_VFLIP, 0, 1, 1, 0);
559
560         sensor->vblank = v4l2_ctrl_new_std(
561                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
562                 V4L2_CID_VBLANK, 0, 1, 1, 0);
563
564         if (sensor->vblank)
565                 sensor->vblank->flags |= V4L2_CTRL_FLAG_UPDATE;
566
567         sensor->hblank = v4l2_ctrl_new_std(
568                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
569                 V4L2_CID_HBLANK, 0, 1, 1, 0);
570
571         if (sensor->hblank)
572                 sensor->hblank->flags |= V4L2_CTRL_FLAG_UPDATE;
573
574         sensor->pixel_rate_parray = v4l2_ctrl_new_std(
575                 &sensor->pixel_array->ctrl_handler, &smiapp_ctrl_ops,
576                 V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1);
577
578         v4l2_ctrl_new_std_menu_items(&sensor->pixel_array->ctrl_handler,
579                                      &smiapp_ctrl_ops, V4L2_CID_TEST_PATTERN,
580                                      ARRAY_SIZE(smiapp_test_patterns) - 1,
581                                      0, 0, smiapp_test_patterns);
582
583         if (sensor->pixel_array->ctrl_handler.error) {
584                 dev_err(&client->dev,
585                         "pixel array controls initialization failed (%d)\n",
586                         sensor->pixel_array->ctrl_handler.error);
587                 return sensor->pixel_array->ctrl_handler.error;
588         }
589
590         sensor->pixel_array->sd.ctrl_handler =
591                 &sensor->pixel_array->ctrl_handler;
592
593         v4l2_ctrl_cluster(2, &sensor->hflip);
594
595         rval = v4l2_ctrl_handler_init(&sensor->src->ctrl_handler, 0);
596         if (rval)
597                 return rval;
598
599         sensor->src->ctrl_handler.lock = &sensor->mutex;
600
601         sensor->pixel_rate_csi = v4l2_ctrl_new_std(
602                 &sensor->src->ctrl_handler, &smiapp_ctrl_ops,
603                 V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1);
604
605         if (sensor->src->ctrl_handler.error) {
606                 dev_err(&client->dev,
607                         "src controls initialization failed (%d)\n",
608                         sensor->src->ctrl_handler.error);
609                 return sensor->src->ctrl_handler.error;
610         }
611
612         sensor->src->sd.ctrl_handler = &sensor->src->ctrl_handler;
613
614         return 0;
615 }
616
617 /*
618  * For controls that require information on available media bus codes
619  * and linke frequencies.
620  */
621 static int smiapp_init_late_controls(struct smiapp_sensor *sensor)
622 {
623         unsigned long *valid_link_freqs = &sensor->valid_link_freqs[
624                 sensor->csi_format->compressed - SMIAPP_COMPRESSED_BASE];
625         unsigned int max, i;
626
627         for (i = 0; i < ARRAY_SIZE(sensor->test_data); i++) {
628                 int max_value = (1 << sensor->csi_format->width) - 1;
629
630                 sensor->test_data[i] = v4l2_ctrl_new_std(
631                                 &sensor->pixel_array->ctrl_handler,
632                                 &smiapp_ctrl_ops, V4L2_CID_TEST_PATTERN_RED + i,
633                                 0, max_value, 1, max_value);
634         }
635
636         for (max = 0; sensor->hwcfg->op_sys_clock[max + 1]; max++);
637
638         sensor->link_freq = v4l2_ctrl_new_int_menu(
639                 &sensor->src->ctrl_handler, &smiapp_ctrl_ops,
640                 V4L2_CID_LINK_FREQ, __fls(*valid_link_freqs),
641                 __ffs(*valid_link_freqs), sensor->hwcfg->op_sys_clock);
642
643         return sensor->src->ctrl_handler.error;
644 }
645
646 static void smiapp_free_controls(struct smiapp_sensor *sensor)
647 {
648         unsigned int i;
649
650         for (i = 0; i < sensor->ssds_used; i++)
651                 v4l2_ctrl_handler_free(&sensor->ssds[i].ctrl_handler);
652 }
653
654 static int smiapp_get_limits(struct smiapp_sensor *sensor, int const *limit,
655                              unsigned int n)
656 {
657         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
658         unsigned int i;
659         u32 val;
660         int rval;
661
662         for (i = 0; i < n; i++) {
663                 rval = smiapp_read(
664                         sensor, smiapp_reg_limits[limit[i]].addr, &val);
665                 if (rval)
666                         return rval;
667                 sensor->limits[limit[i]] = val;
668                 dev_dbg(&client->dev, "0x%8.8x \"%s\" = %u, 0x%x\n",
669                         smiapp_reg_limits[limit[i]].addr,
670                         smiapp_reg_limits[limit[i]].what, val, val);
671         }
672
673         return 0;
674 }
675
676 static int smiapp_get_all_limits(struct smiapp_sensor *sensor)
677 {
678         unsigned int i;
679         int rval;
680
681         for (i = 0; i < SMIAPP_LIMIT_LAST; i++) {
682                 rval = smiapp_get_limits(sensor, &i, 1);
683                 if (rval < 0)
684                         return rval;
685         }
686
687         if (sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN] == 0)
688                 smiapp_replace_limit(sensor, SMIAPP_LIMIT_SCALER_N_MIN, 16);
689
690         return 0;
691 }
692
693 static int smiapp_get_limits_binning(struct smiapp_sensor *sensor)
694 {
695         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
696         static u32 const limits[] = {
697                 SMIAPP_LIMIT_MIN_FRAME_LENGTH_LINES_BIN,
698                 SMIAPP_LIMIT_MAX_FRAME_LENGTH_LINES_BIN,
699                 SMIAPP_LIMIT_MIN_LINE_LENGTH_PCK_BIN,
700                 SMIAPP_LIMIT_MAX_LINE_LENGTH_PCK_BIN,
701                 SMIAPP_LIMIT_MIN_LINE_BLANKING_PCK_BIN,
702                 SMIAPP_LIMIT_FINE_INTEGRATION_TIME_MIN_BIN,
703                 SMIAPP_LIMIT_FINE_INTEGRATION_TIME_MAX_MARGIN_BIN,
704         };
705         static u32 const limits_replace[] = {
706                 SMIAPP_LIMIT_MIN_FRAME_LENGTH_LINES,
707                 SMIAPP_LIMIT_MAX_FRAME_LENGTH_LINES,
708                 SMIAPP_LIMIT_MIN_LINE_LENGTH_PCK,
709                 SMIAPP_LIMIT_MAX_LINE_LENGTH_PCK,
710                 SMIAPP_LIMIT_MIN_LINE_BLANKING_PCK,
711                 SMIAPP_LIMIT_FINE_INTEGRATION_TIME_MIN,
712                 SMIAPP_LIMIT_FINE_INTEGRATION_TIME_MAX_MARGIN,
713         };
714         unsigned int i;
715         int rval;
716
717         if (sensor->limits[SMIAPP_LIMIT_BINNING_CAPABILITY] ==
718             SMIAPP_BINNING_CAPABILITY_NO) {
719                 for (i = 0; i < ARRAY_SIZE(limits); i++)
720                         sensor->limits[limits[i]] =
721                                 sensor->limits[limits_replace[i]];
722
723                 return 0;
724         }
725
726         rval = smiapp_get_limits(sensor, limits, ARRAY_SIZE(limits));
727         if (rval < 0)
728                 return rval;
729
730         /*
731          * Sanity check whether the binning limits are valid. If not,
732          * use the non-binning ones.
733          */
734         if (sensor->limits[SMIAPP_LIMIT_MIN_FRAME_LENGTH_LINES_BIN]
735             && sensor->limits[SMIAPP_LIMIT_MIN_LINE_LENGTH_PCK_BIN]
736             && sensor->limits[SMIAPP_LIMIT_MIN_LINE_BLANKING_PCK_BIN])
737                 return 0;
738
739         for (i = 0; i < ARRAY_SIZE(limits); i++) {
740                 dev_dbg(&client->dev,
741                         "replace limit 0x%8.8x \"%s\" = %d, 0x%x\n",
742                         smiapp_reg_limits[limits[i]].addr,
743                         smiapp_reg_limits[limits[i]].what,
744                         sensor->limits[limits_replace[i]],
745                         sensor->limits[limits_replace[i]]);
746                 sensor->limits[limits[i]] =
747                         sensor->limits[limits_replace[i]];
748         }
749
750         return 0;
751 }
752
753 static int smiapp_get_mbus_formats(struct smiapp_sensor *sensor)
754 {
755         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
756         struct smiapp_pll *pll = &sensor->pll;
757         unsigned int type, n;
758         unsigned int i, pixel_order;
759         int rval;
760
761         rval = smiapp_read(
762                 sensor, SMIAPP_REG_U8_DATA_FORMAT_MODEL_TYPE, &type);
763         if (rval)
764                 return rval;
765
766         dev_dbg(&client->dev, "data_format_model_type %d\n", type);
767
768         rval = smiapp_read(sensor, SMIAPP_REG_U8_PIXEL_ORDER,
769                            &pixel_order);
770         if (rval)
771                 return rval;
772
773         if (pixel_order >= ARRAY_SIZE(pixel_order_str)) {
774                 dev_dbg(&client->dev, "bad pixel order %d\n", pixel_order);
775                 return -EINVAL;
776         }
777
778         dev_dbg(&client->dev, "pixel order %d (%s)\n", pixel_order,
779                 pixel_order_str[pixel_order]);
780
781         switch (type) {
782         case SMIAPP_DATA_FORMAT_MODEL_TYPE_NORMAL:
783                 n = SMIAPP_DATA_FORMAT_MODEL_TYPE_NORMAL_N;
784                 break;
785         case SMIAPP_DATA_FORMAT_MODEL_TYPE_EXTENDED:
786                 n = SMIAPP_DATA_FORMAT_MODEL_TYPE_EXTENDED_N;
787                 break;
788         default:
789                 return -EINVAL;
790         }
791
792         sensor->default_pixel_order = pixel_order;
793         sensor->mbus_frame_fmts = 0;
794
795         for (i = 0; i < n; i++) {
796                 unsigned int fmt, j;
797
798                 rval = smiapp_read(
799                         sensor,
800                         SMIAPP_REG_U16_DATA_FORMAT_DESCRIPTOR(i), &fmt);
801                 if (rval)
802                         return rval;
803
804                 dev_dbg(&client->dev, "%u: bpp %u, compressed %u\n",
805                         i, fmt >> 8, (u8)fmt);
806
807                 for (j = 0; j < ARRAY_SIZE(smiapp_csi_data_formats); j++) {
808                         const struct smiapp_csi_data_format *f =
809                                 &smiapp_csi_data_formats[j];
810
811                         if (f->pixel_order != SMIAPP_PIXEL_ORDER_GRBG)
812                                 continue;
813
814                         if (f->width != fmt >> 8 || f->compressed != (u8)fmt)
815                                 continue;
816
817                         dev_dbg(&client->dev, "jolly good! %d\n", j);
818
819                         sensor->default_mbus_frame_fmts |= 1 << j;
820                 }
821         }
822
823         /* Figure out which BPP values can be used with which formats. */
824         pll->binning_horizontal = 1;
825         pll->binning_vertical = 1;
826         pll->scale_m = sensor->scale_m;
827
828         for (i = 0; i < ARRAY_SIZE(smiapp_csi_data_formats); i++) {
829                 const struct smiapp_csi_data_format *f =
830                         &smiapp_csi_data_formats[i];
831                 unsigned long *valid_link_freqs =
832                         &sensor->valid_link_freqs[
833                                 f->compressed - SMIAPP_COMPRESSED_BASE];
834                 unsigned int j;
835
836                 BUG_ON(f->compressed < SMIAPP_COMPRESSED_BASE);
837                 BUG_ON(f->compressed > SMIAPP_COMPRESSED_MAX);
838
839                 if (!(sensor->default_mbus_frame_fmts & 1 << i))
840                         continue;
841
842                 pll->bits_per_pixel = f->compressed;
843
844                 for (j = 0; sensor->hwcfg->op_sys_clock[j]; j++) {
845                         pll->link_freq = sensor->hwcfg->op_sys_clock[j];
846
847                         rval = smiapp_pll_try(sensor, pll);
848                         dev_dbg(&client->dev, "link freq %u Hz, bpp %u %s\n",
849                                 pll->link_freq, pll->bits_per_pixel,
850                                 rval ? "not ok" : "ok");
851                         if (rval)
852                                 continue;
853
854                         set_bit(j, valid_link_freqs);
855                 }
856
857                 if (!*valid_link_freqs) {
858                         dev_info(&client->dev,
859                                  "no valid link frequencies for %u bpp\n",
860                                  f->compressed);
861                         sensor->default_mbus_frame_fmts &= ~BIT(i);
862                         continue;
863                 }
864
865                 if (!sensor->csi_format
866                     || f->width > sensor->csi_format->width
867                     || (f->width == sensor->csi_format->width
868                         && f->compressed > sensor->csi_format->compressed)) {
869                         sensor->csi_format = f;
870                         sensor->internal_csi_format = f;
871                 }
872         }
873
874         if (!sensor->csi_format) {
875                 dev_err(&client->dev, "no supported mbus code found\n");
876                 return -EINVAL;
877         }
878
879         smiapp_update_mbus_formats(sensor);
880
881         return 0;
882 }
883
884 static void smiapp_update_blanking(struct smiapp_sensor *sensor)
885 {
886         struct v4l2_ctrl *vblank = sensor->vblank;
887         struct v4l2_ctrl *hblank = sensor->hblank;
888         int min, max;
889
890         min = max_t(int,
891                     sensor->limits[SMIAPP_LIMIT_MIN_FRAME_BLANKING_LINES],
892                     sensor->limits[SMIAPP_LIMIT_MIN_FRAME_LENGTH_LINES_BIN] -
893                     sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].height);
894         max = sensor->limits[SMIAPP_LIMIT_MAX_FRAME_LENGTH_LINES_BIN] -
895                 sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].height;
896
897         __v4l2_ctrl_modify_range(vblank, min, max, vblank->step, min);
898
899         min = max_t(int,
900                     sensor->limits[SMIAPP_LIMIT_MIN_LINE_LENGTH_PCK_BIN] -
901                     sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].width,
902                     sensor->limits[SMIAPP_LIMIT_MIN_LINE_BLANKING_PCK_BIN]);
903         max = sensor->limits[SMIAPP_LIMIT_MAX_LINE_LENGTH_PCK_BIN] -
904                 sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].width;
905
906         __v4l2_ctrl_modify_range(hblank, min, max, hblank->step, min);
907
908         __smiapp_update_exposure_limits(sensor);
909 }
910
911 static int smiapp_update_mode(struct smiapp_sensor *sensor)
912 {
913         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
914         unsigned int binning_mode;
915         int rval;
916
917         dev_dbg(&client->dev, "frame size: %dx%d\n",
918                 sensor->src->crop[SMIAPP_PAD_SRC].width,
919                 sensor->src->crop[SMIAPP_PAD_SRC].height);
920         dev_dbg(&client->dev, "csi format width: %d\n",
921                 sensor->csi_format->width);
922
923         /* Binning has to be set up here; it affects limits */
924         if (sensor->binning_horizontal == 1 &&
925             sensor->binning_vertical == 1) {
926                 binning_mode = 0;
927         } else {
928                 u8 binning_type =
929                         (sensor->binning_horizontal << 4)
930                         | sensor->binning_vertical;
931
932                 rval = smiapp_write(
933                         sensor, SMIAPP_REG_U8_BINNING_TYPE, binning_type);
934                 if (rval < 0)
935                         return rval;
936
937                 binning_mode = 1;
938         }
939         rval = smiapp_write(sensor, SMIAPP_REG_U8_BINNING_MODE, binning_mode);
940         if (rval < 0)
941                 return rval;
942
943         /* Get updated limits due to binning */
944         rval = smiapp_get_limits_binning(sensor);
945         if (rval < 0)
946                 return rval;
947
948         rval = smiapp_pll_update(sensor);
949         if (rval < 0)
950                 return rval;
951
952         /* Output from pixel array, including blanking */
953         smiapp_update_blanking(sensor);
954
955         dev_dbg(&client->dev, "vblank\t\t%d\n", sensor->vblank->val);
956         dev_dbg(&client->dev, "hblank\t\t%d\n", sensor->hblank->val);
957
958         dev_dbg(&client->dev, "real timeperframe\t100/%d\n",
959                 sensor->pll.pixel_rate_pixel_array /
960                 ((sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].width
961                   + sensor->hblank->val) *
962                  (sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].height
963                   + sensor->vblank->val) / 100));
964
965         return 0;
966 }
967
968 /*
969  *
970  * SMIA++ NVM handling
971  *
972  */
973 static int smiapp_read_nvm(struct smiapp_sensor *sensor,
974                            unsigned char *nvm)
975 {
976         u32 i, s, p, np, v;
977         int rval = 0, rval2;
978
979         np = sensor->nvm_size / SMIAPP_NVM_PAGE_SIZE;
980         for (p = 0; p < np; p++) {
981                 rval = smiapp_write(
982                         sensor,
983                         SMIAPP_REG_U8_DATA_TRANSFER_IF_1_PAGE_SELECT, p);
984                 if (rval)
985                         goto out;
986
987                 rval = smiapp_write(sensor,
988                                     SMIAPP_REG_U8_DATA_TRANSFER_IF_1_CTRL,
989                                     SMIAPP_DATA_TRANSFER_IF_1_CTRL_EN |
990                                     SMIAPP_DATA_TRANSFER_IF_1_CTRL_RD_EN);
991                 if (rval)
992                         goto out;
993
994                 for (i = 1000; i > 0; i--) {
995                         rval = smiapp_read(
996                                 sensor,
997                                 SMIAPP_REG_U8_DATA_TRANSFER_IF_1_STATUS, &s);
998
999                         if (rval)
1000                                 goto out;
1001
1002                         if (s & SMIAPP_DATA_TRANSFER_IF_1_STATUS_RD_READY)
1003                                 break;
1004
1005                 }
1006                 if (!i) {
1007                         rval = -ETIMEDOUT;
1008                         goto out;
1009                 }
1010
1011                 for (i = 0; i < SMIAPP_NVM_PAGE_SIZE; i++) {
1012                         rval = smiapp_read(
1013                                 sensor,
1014                                 SMIAPP_REG_U8_DATA_TRANSFER_IF_1_DATA_0 + i,
1015                                 &v);
1016                         if (rval)
1017                                 goto out;
1018
1019                         *nvm++ = v;
1020                 }
1021         }
1022
1023 out:
1024         rval2 = smiapp_write(sensor, SMIAPP_REG_U8_DATA_TRANSFER_IF_1_CTRL, 0);
1025         if (rval < 0)
1026                 return rval;
1027         else
1028                 return rval2;
1029 }
1030
1031 /*
1032  *
1033  * SMIA++ CCI address control
1034  *
1035  */
1036 static int smiapp_change_cci_addr(struct smiapp_sensor *sensor)
1037 {
1038         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
1039         int rval;
1040         u32 val;
1041
1042         client->addr = sensor->hwcfg->i2c_addr_dfl;
1043
1044         rval = smiapp_write(sensor,
1045                             SMIAPP_REG_U8_CCI_ADDRESS_CONTROL,
1046                             sensor->hwcfg->i2c_addr_alt << 1);
1047         if (rval)
1048                 return rval;
1049
1050         client->addr = sensor->hwcfg->i2c_addr_alt;
1051
1052         /* verify addr change went ok */
1053         rval = smiapp_read(sensor, SMIAPP_REG_U8_CCI_ADDRESS_CONTROL, &val);
1054         if (rval)
1055                 return rval;
1056
1057         if (val != sensor->hwcfg->i2c_addr_alt << 1)
1058                 return -ENODEV;
1059
1060         return 0;
1061 }
1062
1063 /*
1064  *
1065  * SMIA++ Mode Control
1066  *
1067  */
1068 static int smiapp_setup_flash_strobe(struct smiapp_sensor *sensor)
1069 {
1070         struct smiapp_flash_strobe_parms *strobe_setup;
1071         unsigned int ext_freq = sensor->hwcfg->ext_clk;
1072         u32 tmp;
1073         u32 strobe_adjustment;
1074         u32 strobe_width_high_rs;
1075         int rval;
1076
1077         strobe_setup = sensor->hwcfg->strobe_setup;
1078
1079         /*
1080          * How to calculate registers related to strobe length. Please
1081          * do not change, or if you do at least know what you're
1082          * doing. :-)
1083          *
1084          * Sakari Ailus <sakari.ailus@iki.fi> 2010-10-25
1085          *
1086          * flash_strobe_length [us] / 10^6 = (tFlash_strobe_width_ctrl
1087          *      / EXTCLK freq [Hz]) * flash_strobe_adjustment
1088          *
1089          * tFlash_strobe_width_ctrl E N, [1 - 0xffff]
1090          * flash_strobe_adjustment E N, [1 - 0xff]
1091          *
1092          * The formula above is written as below to keep it on one
1093          * line:
1094          *
1095          * l / 10^6 = w / e * a
1096          *
1097          * Let's mark w * a by x:
1098          *
1099          * x = w * a
1100          *
1101          * Thus, we get:
1102          *
1103          * x = l * e / 10^6
1104          *
1105          * The strobe width must be at least as long as requested,
1106          * thus rounding upwards is needed.
1107          *
1108          * x = (l * e + 10^6 - 1) / 10^6
1109          * -----------------------------
1110          *
1111          * Maximum possible accuracy is wanted at all times. Thus keep
1112          * a as small as possible.
1113          *
1114          * Calculate a, assuming maximum w, with rounding upwards:
1115          *
1116          * a = (x + (2^16 - 1) - 1) / (2^16 - 1)
1117          * -------------------------------------
1118          *
1119          * Thus, we also get w, with that a, with rounding upwards:
1120          *
1121          * w = (x + a - 1) / a
1122          * -------------------
1123          *
1124          * To get limits:
1125          *
1126          * x E [1, (2^16 - 1) * (2^8 - 1)]
1127          *
1128          * Substituting maximum x to the original formula (with rounding),
1129          * the maximum l is thus
1130          *
1131          * (2^16 - 1) * (2^8 - 1) * 10^6 = l * e + 10^6 - 1
1132          *
1133          * l = (10^6 * (2^16 - 1) * (2^8 - 1) - 10^6 + 1) / e
1134          * --------------------------------------------------
1135          *
1136          * flash_strobe_length must be clamped between 1 and
1137          * (10^6 * (2^16 - 1) * (2^8 - 1) - 10^6 + 1) / EXTCLK freq.
1138          *
1139          * Then,
1140          *
1141          * flash_strobe_adjustment = ((flash_strobe_length *
1142          *      EXTCLK freq + 10^6 - 1) / 10^6 + (2^16 - 1) - 1) / (2^16 - 1)
1143          *
1144          * tFlash_strobe_width_ctrl = ((flash_strobe_length *
1145          *      EXTCLK freq + 10^6 - 1) / 10^6 +
1146          *      flash_strobe_adjustment - 1) / flash_strobe_adjustment
1147          */
1148         tmp = div_u64(1000000ULL * ((1 << 16) - 1) * ((1 << 8) - 1) -
1149                       1000000 + 1, ext_freq);
1150         strobe_setup->strobe_width_high_us =
1151                 clamp_t(u32, strobe_setup->strobe_width_high_us, 1, tmp);
1152
1153         tmp = div_u64(((u64)strobe_setup->strobe_width_high_us * (u64)ext_freq +
1154                         1000000 - 1), 1000000ULL);
1155         strobe_adjustment = (tmp + (1 << 16) - 1 - 1) / ((1 << 16) - 1);
1156         strobe_width_high_rs = (tmp + strobe_adjustment - 1) /
1157                                 strobe_adjustment;
1158
1159         rval = smiapp_write(sensor, SMIAPP_REG_U8_FLASH_MODE_RS,
1160                             strobe_setup->mode);
1161         if (rval < 0)
1162                 goto out;
1163
1164         rval = smiapp_write(sensor, SMIAPP_REG_U8_FLASH_STROBE_ADJUSTMENT,
1165                             strobe_adjustment);
1166         if (rval < 0)
1167                 goto out;
1168
1169         rval = smiapp_write(
1170                 sensor, SMIAPP_REG_U16_TFLASH_STROBE_WIDTH_HIGH_RS_CTRL,
1171                 strobe_width_high_rs);
1172         if (rval < 0)
1173                 goto out;
1174
1175         rval = smiapp_write(sensor, SMIAPP_REG_U16_TFLASH_STROBE_DELAY_RS_CTRL,
1176                             strobe_setup->strobe_delay);
1177         if (rval < 0)
1178                 goto out;
1179
1180         rval = smiapp_write(sensor, SMIAPP_REG_U16_FLASH_STROBE_START_POINT,
1181                             strobe_setup->stobe_start_point);
1182         if (rval < 0)
1183                 goto out;
1184
1185         rval = smiapp_write(sensor, SMIAPP_REG_U8_FLASH_TRIGGER_RS,
1186                             strobe_setup->trigger);
1187
1188 out:
1189         sensor->hwcfg->strobe_setup->trigger = 0;
1190
1191         return rval;
1192 }
1193
1194 /* -----------------------------------------------------------------------------
1195  * Power management
1196  */
1197
1198 static int smiapp_power_on(struct smiapp_sensor *sensor)
1199 {
1200         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
1201         unsigned int sleep;
1202         int rval;
1203
1204         rval = regulator_enable(sensor->vana);
1205         if (rval) {
1206                 dev_err(&client->dev, "failed to enable vana regulator\n");
1207                 return rval;
1208         }
1209         usleep_range(1000, 1000);
1210
1211         rval = clk_prepare_enable(sensor->ext_clk);
1212         if (rval < 0) {
1213                 dev_dbg(&client->dev, "failed to enable xclk\n");
1214                 goto out_xclk_fail;
1215         }
1216         usleep_range(1000, 1000);
1217
1218         gpiod_set_value(sensor->xshutdown, 1);
1219
1220         sleep = SMIAPP_RESET_DELAY(sensor->hwcfg->ext_clk);
1221         usleep_range(sleep, sleep);
1222
1223         /*
1224          * Failures to respond to the address change command have been noticed.
1225          * Those failures seem to be caused by the sensor requiring a longer
1226          * boot time than advertised. An additional 10ms delay seems to work
1227          * around the issue, but the SMIA++ I2C write retry hack makes the delay
1228          * unnecessary. The failures need to be investigated to find a proper
1229          * fix, and a delay will likely need to be added here if the I2C write
1230          * retry hack is reverted before the root cause of the boot time issue
1231          * is found.
1232          */
1233
1234         if (sensor->hwcfg->i2c_addr_alt) {
1235                 rval = smiapp_change_cci_addr(sensor);
1236                 if (rval) {
1237                         dev_err(&client->dev, "cci address change error\n");
1238                         goto out_cci_addr_fail;
1239                 }
1240         }
1241
1242         rval = smiapp_write(sensor, SMIAPP_REG_U8_SOFTWARE_RESET,
1243                             SMIAPP_SOFTWARE_RESET);
1244         if (rval < 0) {
1245                 dev_err(&client->dev, "software reset failed\n");
1246                 goto out_cci_addr_fail;
1247         }
1248
1249         if (sensor->hwcfg->i2c_addr_alt) {
1250                 rval = smiapp_change_cci_addr(sensor);
1251                 if (rval) {
1252                         dev_err(&client->dev, "cci address change error\n");
1253                         goto out_cci_addr_fail;
1254                 }
1255         }
1256
1257         rval = smiapp_write(sensor, SMIAPP_REG_U16_COMPRESSION_MODE,
1258                             SMIAPP_COMPRESSION_MODE_SIMPLE_PREDICTOR);
1259         if (rval) {
1260                 dev_err(&client->dev, "compression mode set failed\n");
1261                 goto out_cci_addr_fail;
1262         }
1263
1264         rval = smiapp_write(
1265                 sensor, SMIAPP_REG_U16_EXTCLK_FREQUENCY_MHZ,
1266                 sensor->hwcfg->ext_clk / (1000000 / (1 << 8)));
1267         if (rval) {
1268                 dev_err(&client->dev, "extclk frequency set failed\n");
1269                 goto out_cci_addr_fail;
1270         }
1271
1272         rval = smiapp_write(sensor, SMIAPP_REG_U8_CSI_LANE_MODE,
1273                             sensor->hwcfg->lanes - 1);
1274         if (rval) {
1275                 dev_err(&client->dev, "csi lane mode set failed\n");
1276                 goto out_cci_addr_fail;
1277         }
1278
1279         rval = smiapp_write(sensor, SMIAPP_REG_U8_FAST_STANDBY_CTRL,
1280                             SMIAPP_FAST_STANDBY_CTRL_IMMEDIATE);
1281         if (rval) {
1282                 dev_err(&client->dev, "fast standby set failed\n");
1283                 goto out_cci_addr_fail;
1284         }
1285
1286         rval = smiapp_write(sensor, SMIAPP_REG_U8_CSI_SIGNALLING_MODE,
1287                             sensor->hwcfg->csi_signalling_mode);
1288         if (rval) {
1289                 dev_err(&client->dev, "csi signalling mode set failed\n");
1290                 goto out_cci_addr_fail;
1291         }
1292
1293         /* DPHY control done by sensor based on requested link rate */
1294         rval = smiapp_write(sensor, SMIAPP_REG_U8_DPHY_CTRL,
1295                             SMIAPP_DPHY_CTRL_UI);
1296         if (rval < 0)
1297                 return rval;
1298
1299         rval = smiapp_call_quirk(sensor, post_poweron);
1300         if (rval) {
1301                 dev_err(&client->dev, "post_poweron quirks failed\n");
1302                 goto out_cci_addr_fail;
1303         }
1304
1305         /* Are we still initialising...? If yes, return here. */
1306         if (!sensor->pixel_array)
1307                 return 0;
1308
1309         rval = v4l2_ctrl_handler_setup(
1310                 &sensor->pixel_array->ctrl_handler);
1311         if (rval)
1312                 goto out_cci_addr_fail;
1313
1314         rval = v4l2_ctrl_handler_setup(&sensor->src->ctrl_handler);
1315         if (rval)
1316                 goto out_cci_addr_fail;
1317
1318         mutex_lock(&sensor->mutex);
1319         rval = smiapp_update_mode(sensor);
1320         mutex_unlock(&sensor->mutex);
1321         if (rval < 0)
1322                 goto out_cci_addr_fail;
1323
1324         return 0;
1325
1326 out_cci_addr_fail:
1327         gpiod_set_value(sensor->xshutdown, 0);
1328         clk_disable_unprepare(sensor->ext_clk);
1329
1330 out_xclk_fail:
1331         regulator_disable(sensor->vana);
1332         return rval;
1333 }
1334
1335 static void smiapp_power_off(struct smiapp_sensor *sensor)
1336 {
1337         /*
1338          * Currently power/clock to lens are enable/disabled separately
1339          * but they are essentially the same signals. So if the sensor is
1340          * powered off while the lens is powered on the sensor does not
1341          * really see a power off and next time the cci address change
1342          * will fail. So do a soft reset explicitly here.
1343          */
1344         if (sensor->hwcfg->i2c_addr_alt)
1345                 smiapp_write(sensor,
1346                              SMIAPP_REG_U8_SOFTWARE_RESET,
1347                              SMIAPP_SOFTWARE_RESET);
1348
1349         gpiod_set_value(sensor->xshutdown, 0);
1350         clk_disable_unprepare(sensor->ext_clk);
1351         usleep_range(5000, 5000);
1352         regulator_disable(sensor->vana);
1353         sensor->streaming = false;
1354 }
1355
1356 static int smiapp_set_power(struct v4l2_subdev *subdev, int on)
1357 {
1358         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1359         int ret = 0;
1360
1361         mutex_lock(&sensor->power_mutex);
1362
1363         if (on && !sensor->power_count) {
1364                 /* Power on and perform initialisation. */
1365                 ret = smiapp_power_on(sensor);
1366                 if (ret < 0)
1367                         goto out;
1368         } else if (!on && sensor->power_count == 1) {
1369                 smiapp_power_off(sensor);
1370         }
1371
1372         /* Update the power count. */
1373         sensor->power_count += on ? 1 : -1;
1374         WARN_ON(sensor->power_count < 0);
1375
1376 out:
1377         mutex_unlock(&sensor->power_mutex);
1378         return ret;
1379 }
1380
1381 /* -----------------------------------------------------------------------------
1382  * Video stream management
1383  */
1384
1385 static int smiapp_start_streaming(struct smiapp_sensor *sensor)
1386 {
1387         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
1388         int rval;
1389
1390         mutex_lock(&sensor->mutex);
1391
1392         rval = smiapp_write(sensor, SMIAPP_REG_U16_CSI_DATA_FORMAT,
1393                             (sensor->csi_format->width << 8) |
1394                             sensor->csi_format->compressed);
1395         if (rval)
1396                 goto out;
1397
1398         rval = smiapp_pll_configure(sensor);
1399         if (rval)
1400                 goto out;
1401
1402         /* Analog crop start coordinates */
1403         rval = smiapp_write(sensor, SMIAPP_REG_U16_X_ADDR_START,
1404                             sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].left);
1405         if (rval < 0)
1406                 goto out;
1407
1408         rval = smiapp_write(sensor, SMIAPP_REG_U16_Y_ADDR_START,
1409                             sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].top);
1410         if (rval < 0)
1411                 goto out;
1412
1413         /* Analog crop end coordinates */
1414         rval = smiapp_write(
1415                 sensor, SMIAPP_REG_U16_X_ADDR_END,
1416                 sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].left
1417                 + sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].width - 1);
1418         if (rval < 0)
1419                 goto out;
1420
1421         rval = smiapp_write(
1422                 sensor, SMIAPP_REG_U16_Y_ADDR_END,
1423                 sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].top
1424                 + sensor->pixel_array->crop[SMIAPP_PA_PAD_SRC].height - 1);
1425         if (rval < 0)
1426                 goto out;
1427
1428         /*
1429          * Output from pixel array, including blanking, is set using
1430          * controls below. No need to set here.
1431          */
1432
1433         /* Digital crop */
1434         if (sensor->limits[SMIAPP_LIMIT_DIGITAL_CROP_CAPABILITY]
1435             == SMIAPP_DIGITAL_CROP_CAPABILITY_INPUT_CROP) {
1436                 rval = smiapp_write(
1437                         sensor, SMIAPP_REG_U16_DIGITAL_CROP_X_OFFSET,
1438                         sensor->scaler->crop[SMIAPP_PAD_SINK].left);
1439                 if (rval < 0)
1440                         goto out;
1441
1442                 rval = smiapp_write(
1443                         sensor, SMIAPP_REG_U16_DIGITAL_CROP_Y_OFFSET,
1444                         sensor->scaler->crop[SMIAPP_PAD_SINK].top);
1445                 if (rval < 0)
1446                         goto out;
1447
1448                 rval = smiapp_write(
1449                         sensor, SMIAPP_REG_U16_DIGITAL_CROP_IMAGE_WIDTH,
1450                         sensor->scaler->crop[SMIAPP_PAD_SINK].width);
1451                 if (rval < 0)
1452                         goto out;
1453
1454                 rval = smiapp_write(
1455                         sensor, SMIAPP_REG_U16_DIGITAL_CROP_IMAGE_HEIGHT,
1456                         sensor->scaler->crop[SMIAPP_PAD_SINK].height);
1457                 if (rval < 0)
1458                         goto out;
1459         }
1460
1461         /* Scaling */
1462         if (sensor->limits[SMIAPP_LIMIT_SCALING_CAPABILITY]
1463             != SMIAPP_SCALING_CAPABILITY_NONE) {
1464                 rval = smiapp_write(sensor, SMIAPP_REG_U16_SCALING_MODE,
1465                                     sensor->scaling_mode);
1466                 if (rval < 0)
1467                         goto out;
1468
1469                 rval = smiapp_write(sensor, SMIAPP_REG_U16_SCALE_M,
1470                                     sensor->scale_m);
1471                 if (rval < 0)
1472                         goto out;
1473         }
1474
1475         /* Output size from sensor */
1476         rval = smiapp_write(sensor, SMIAPP_REG_U16_X_OUTPUT_SIZE,
1477                             sensor->src->crop[SMIAPP_PAD_SRC].width);
1478         if (rval < 0)
1479                 goto out;
1480         rval = smiapp_write(sensor, SMIAPP_REG_U16_Y_OUTPUT_SIZE,
1481                             sensor->src->crop[SMIAPP_PAD_SRC].height);
1482         if (rval < 0)
1483                 goto out;
1484
1485         if ((sensor->limits[SMIAPP_LIMIT_FLASH_MODE_CAPABILITY] &
1486              (SMIAPP_FLASH_MODE_CAPABILITY_SINGLE_STROBE |
1487               SMIAPP_FLASH_MODE_CAPABILITY_MULTIPLE_STROBE)) &&
1488             sensor->hwcfg->strobe_setup != NULL &&
1489             sensor->hwcfg->strobe_setup->trigger != 0) {
1490                 rval = smiapp_setup_flash_strobe(sensor);
1491                 if (rval)
1492                         goto out;
1493         }
1494
1495         rval = smiapp_call_quirk(sensor, pre_streamon);
1496         if (rval) {
1497                 dev_err(&client->dev, "pre_streamon quirks failed\n");
1498                 goto out;
1499         }
1500
1501         rval = smiapp_write(sensor, SMIAPP_REG_U8_MODE_SELECT,
1502                             SMIAPP_MODE_SELECT_STREAMING);
1503
1504 out:
1505         mutex_unlock(&sensor->mutex);
1506
1507         return rval;
1508 }
1509
1510 static int smiapp_stop_streaming(struct smiapp_sensor *sensor)
1511 {
1512         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
1513         int rval;
1514
1515         mutex_lock(&sensor->mutex);
1516         rval = smiapp_write(sensor, SMIAPP_REG_U8_MODE_SELECT,
1517                             SMIAPP_MODE_SELECT_SOFTWARE_STANDBY);
1518         if (rval)
1519                 goto out;
1520
1521         rval = smiapp_call_quirk(sensor, post_streamoff);
1522         if (rval)
1523                 dev_err(&client->dev, "post_streamoff quirks failed\n");
1524
1525 out:
1526         mutex_unlock(&sensor->mutex);
1527         return rval;
1528 }
1529
1530 /* -----------------------------------------------------------------------------
1531  * V4L2 subdev video operations
1532  */
1533
1534 static int smiapp_set_stream(struct v4l2_subdev *subdev, int enable)
1535 {
1536         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1537         int rval;
1538
1539         if (sensor->streaming == enable)
1540                 return 0;
1541
1542         if (enable) {
1543                 sensor->streaming = true;
1544                 rval = smiapp_start_streaming(sensor);
1545                 if (rval < 0)
1546                         sensor->streaming = false;
1547         } else {
1548                 rval = smiapp_stop_streaming(sensor);
1549                 sensor->streaming = false;
1550         }
1551
1552         return rval;
1553 }
1554
1555 static int smiapp_enum_mbus_code(struct v4l2_subdev *subdev,
1556                                  struct v4l2_subdev_pad_config *cfg,
1557                                  struct v4l2_subdev_mbus_code_enum *code)
1558 {
1559         struct i2c_client *client = v4l2_get_subdevdata(subdev);
1560         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1561         unsigned int i;
1562         int idx = -1;
1563         int rval = -EINVAL;
1564
1565         mutex_lock(&sensor->mutex);
1566
1567         dev_err(&client->dev, "subdev %s, pad %d, index %d\n",
1568                 subdev->name, code->pad, code->index);
1569
1570         if (subdev != &sensor->src->sd || code->pad != SMIAPP_PAD_SRC) {
1571                 if (code->index)
1572                         goto out;
1573
1574                 code->code = sensor->internal_csi_format->code;
1575                 rval = 0;
1576                 goto out;
1577         }
1578
1579         for (i = 0; i < ARRAY_SIZE(smiapp_csi_data_formats); i++) {
1580                 if (sensor->mbus_frame_fmts & (1 << i))
1581                         idx++;
1582
1583                 if (idx == code->index) {
1584                         code->code = smiapp_csi_data_formats[i].code;
1585                         dev_err(&client->dev, "found index %d, i %d, code %x\n",
1586                                 code->index, i, code->code);
1587                         rval = 0;
1588                         break;
1589                 }
1590         }
1591
1592 out:
1593         mutex_unlock(&sensor->mutex);
1594
1595         return rval;
1596 }
1597
1598 static u32 __smiapp_get_mbus_code(struct v4l2_subdev *subdev,
1599                                   unsigned int pad)
1600 {
1601         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1602
1603         if (subdev == &sensor->src->sd && pad == SMIAPP_PAD_SRC)
1604                 return sensor->csi_format->code;
1605         else
1606                 return sensor->internal_csi_format->code;
1607 }
1608
1609 static int __smiapp_get_format(struct v4l2_subdev *subdev,
1610                                struct v4l2_subdev_pad_config *cfg,
1611                                struct v4l2_subdev_format *fmt)
1612 {
1613         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
1614
1615         if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1616                 fmt->format = *v4l2_subdev_get_try_format(subdev, cfg, fmt->pad);
1617         } else {
1618                 struct v4l2_rect *r;
1619
1620                 if (fmt->pad == ssd->source_pad)
1621                         r = &ssd->crop[ssd->source_pad];
1622                 else
1623                         r = &ssd->sink_fmt;
1624
1625                 fmt->format.code = __smiapp_get_mbus_code(subdev, fmt->pad);
1626                 fmt->format.width = r->width;
1627                 fmt->format.height = r->height;
1628                 fmt->format.field = V4L2_FIELD_NONE;
1629         }
1630
1631         return 0;
1632 }
1633
1634 static int smiapp_get_format(struct v4l2_subdev *subdev,
1635                              struct v4l2_subdev_pad_config *cfg,
1636                              struct v4l2_subdev_format *fmt)
1637 {
1638         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1639         int rval;
1640
1641         mutex_lock(&sensor->mutex);
1642         rval = __smiapp_get_format(subdev, cfg, fmt);
1643         mutex_unlock(&sensor->mutex);
1644
1645         return rval;
1646 }
1647
1648 static void smiapp_get_crop_compose(struct v4l2_subdev *subdev,
1649                                     struct v4l2_subdev_pad_config *cfg,
1650                                     struct v4l2_rect **crops,
1651                                     struct v4l2_rect **comps, int which)
1652 {
1653         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
1654         unsigned int i;
1655
1656         if (which == V4L2_SUBDEV_FORMAT_ACTIVE) {
1657                 if (crops)
1658                         for (i = 0; i < subdev->entity.num_pads; i++)
1659                                 crops[i] = &ssd->crop[i];
1660                 if (comps)
1661                         *comps = &ssd->compose;
1662         } else {
1663                 if (crops) {
1664                         for (i = 0; i < subdev->entity.num_pads; i++) {
1665                                 crops[i] = v4l2_subdev_get_try_crop(subdev, cfg, i);
1666                                 BUG_ON(!crops[i]);
1667                         }
1668                 }
1669                 if (comps) {
1670                         *comps = v4l2_subdev_get_try_compose(subdev, cfg,
1671                                                              SMIAPP_PAD_SINK);
1672                         BUG_ON(!*comps);
1673                 }
1674         }
1675 }
1676
1677 /* Changes require propagation only on sink pad. */
1678 static void smiapp_propagate(struct v4l2_subdev *subdev,
1679                              struct v4l2_subdev_pad_config *cfg, int which,
1680                              int target)
1681 {
1682         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1683         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
1684         struct v4l2_rect *comp, *crops[SMIAPP_PADS];
1685
1686         smiapp_get_crop_compose(subdev, cfg, crops, &comp, which);
1687
1688         switch (target) {
1689         case V4L2_SEL_TGT_CROP:
1690                 comp->width = crops[SMIAPP_PAD_SINK]->width;
1691                 comp->height = crops[SMIAPP_PAD_SINK]->height;
1692                 if (which == V4L2_SUBDEV_FORMAT_ACTIVE) {
1693                         if (ssd == sensor->scaler) {
1694                                 sensor->scale_m =
1695                                         sensor->limits[
1696                                                 SMIAPP_LIMIT_SCALER_N_MIN];
1697                                 sensor->scaling_mode =
1698                                         SMIAPP_SCALING_MODE_NONE;
1699                         } else if (ssd == sensor->binner) {
1700                                 sensor->binning_horizontal = 1;
1701                                 sensor->binning_vertical = 1;
1702                         }
1703                 }
1704                 /* Fall through */
1705         case V4L2_SEL_TGT_COMPOSE:
1706                 *crops[SMIAPP_PAD_SRC] = *comp;
1707                 break;
1708         default:
1709                 BUG();
1710         }
1711 }
1712
1713 static const struct smiapp_csi_data_format
1714 *smiapp_validate_csi_data_format(struct smiapp_sensor *sensor, u32 code)
1715 {
1716         const struct smiapp_csi_data_format *csi_format = sensor->csi_format;
1717         unsigned int i;
1718
1719         for (i = 0; i < ARRAY_SIZE(smiapp_csi_data_formats); i++) {
1720                 if (sensor->mbus_frame_fmts & (1 << i)
1721                     && smiapp_csi_data_formats[i].code == code)
1722                         return &smiapp_csi_data_formats[i];
1723         }
1724
1725         return csi_format;
1726 }
1727
1728 static int smiapp_set_format_source(struct v4l2_subdev *subdev,
1729                                     struct v4l2_subdev_pad_config *cfg,
1730                                     struct v4l2_subdev_format *fmt)
1731 {
1732         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1733         const struct smiapp_csi_data_format *csi_format,
1734                 *old_csi_format = sensor->csi_format;
1735         unsigned long *valid_link_freqs;
1736         u32 code = fmt->format.code;
1737         unsigned int i;
1738         int rval;
1739
1740         rval = __smiapp_get_format(subdev, cfg, fmt);
1741         if (rval)
1742                 return rval;
1743
1744         /*
1745          * Media bus code is changeable on src subdev's source pad. On
1746          * other source pads we just get format here.
1747          */
1748         if (subdev != &sensor->src->sd)
1749                 return 0;
1750
1751         csi_format = smiapp_validate_csi_data_format(sensor, code);
1752
1753         fmt->format.code = csi_format->code;
1754
1755         if (fmt->which != V4L2_SUBDEV_FORMAT_ACTIVE)
1756                 return 0;
1757
1758         sensor->csi_format = csi_format;
1759
1760         if (csi_format->width != old_csi_format->width)
1761                 for (i = 0; i < ARRAY_SIZE(sensor->test_data); i++)
1762                         __v4l2_ctrl_modify_range(
1763                                 sensor->test_data[i], 0,
1764                                 (1 << csi_format->width) - 1, 1, 0);
1765
1766         if (csi_format->compressed == old_csi_format->compressed)
1767                 return 0;
1768
1769         valid_link_freqs = 
1770                 &sensor->valid_link_freqs[sensor->csi_format->compressed
1771                                           - SMIAPP_COMPRESSED_BASE];
1772
1773         __v4l2_ctrl_modify_range(
1774                 sensor->link_freq, 0,
1775                 __fls(*valid_link_freqs), ~*valid_link_freqs,
1776                 __ffs(*valid_link_freqs));
1777
1778         return smiapp_pll_update(sensor);
1779 }
1780
1781 static int smiapp_set_format(struct v4l2_subdev *subdev,
1782                              struct v4l2_subdev_pad_config *cfg,
1783                              struct v4l2_subdev_format *fmt)
1784 {
1785         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1786         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
1787         struct v4l2_rect *crops[SMIAPP_PADS];
1788
1789         mutex_lock(&sensor->mutex);
1790
1791         if (fmt->pad == ssd->source_pad) {
1792                 int rval;
1793
1794                 rval = smiapp_set_format_source(subdev, cfg, fmt);
1795
1796                 mutex_unlock(&sensor->mutex);
1797
1798                 return rval;
1799         }
1800
1801         /* Sink pad. Width and height are changeable here. */
1802         fmt->format.code = __smiapp_get_mbus_code(subdev, fmt->pad);
1803         fmt->format.width &= ~1;
1804         fmt->format.height &= ~1;
1805         fmt->format.field = V4L2_FIELD_NONE;
1806
1807         fmt->format.width =
1808                 clamp(fmt->format.width,
1809                       sensor->limits[SMIAPP_LIMIT_MIN_X_OUTPUT_SIZE],
1810                       sensor->limits[SMIAPP_LIMIT_MAX_X_OUTPUT_SIZE]);
1811         fmt->format.height =
1812                 clamp(fmt->format.height,
1813                       sensor->limits[SMIAPP_LIMIT_MIN_Y_OUTPUT_SIZE],
1814                       sensor->limits[SMIAPP_LIMIT_MAX_Y_OUTPUT_SIZE]);
1815
1816         smiapp_get_crop_compose(subdev, cfg, crops, NULL, fmt->which);
1817
1818         crops[ssd->sink_pad]->left = 0;
1819         crops[ssd->sink_pad]->top = 0;
1820         crops[ssd->sink_pad]->width = fmt->format.width;
1821         crops[ssd->sink_pad]->height = fmt->format.height;
1822         if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE)
1823                 ssd->sink_fmt = *crops[ssd->sink_pad];
1824         smiapp_propagate(subdev, cfg, fmt->which,
1825                          V4L2_SEL_TGT_CROP);
1826
1827         mutex_unlock(&sensor->mutex);
1828
1829         return 0;
1830 }
1831
1832 /*
1833  * Calculate goodness of scaled image size compared to expected image
1834  * size and flags provided.
1835  */
1836 #define SCALING_GOODNESS                100000
1837 #define SCALING_GOODNESS_EXTREME        100000000
1838 static int scaling_goodness(struct v4l2_subdev *subdev, int w, int ask_w,
1839                             int h, int ask_h, u32 flags)
1840 {
1841         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1842         struct i2c_client *client = v4l2_get_subdevdata(subdev);
1843         int val = 0;
1844
1845         w &= ~1;
1846         ask_w &= ~1;
1847         h &= ~1;
1848         ask_h &= ~1;
1849
1850         if (flags & V4L2_SEL_FLAG_GE) {
1851                 if (w < ask_w)
1852                         val -= SCALING_GOODNESS;
1853                 if (h < ask_h)
1854                         val -= SCALING_GOODNESS;
1855         }
1856
1857         if (flags & V4L2_SEL_FLAG_LE) {
1858                 if (w > ask_w)
1859                         val -= SCALING_GOODNESS;
1860                 if (h > ask_h)
1861                         val -= SCALING_GOODNESS;
1862         }
1863
1864         val -= abs(w - ask_w);
1865         val -= abs(h - ask_h);
1866
1867         if (w < sensor->limits[SMIAPP_LIMIT_MIN_X_OUTPUT_SIZE])
1868                 val -= SCALING_GOODNESS_EXTREME;
1869
1870         dev_dbg(&client->dev, "w %d ask_w %d h %d ask_h %d goodness %d\n",
1871                 w, ask_h, h, ask_h, val);
1872
1873         return val;
1874 }
1875
1876 static void smiapp_set_compose_binner(struct v4l2_subdev *subdev,
1877                                       struct v4l2_subdev_pad_config *cfg,
1878                                       struct v4l2_subdev_selection *sel,
1879                                       struct v4l2_rect **crops,
1880                                       struct v4l2_rect *comp)
1881 {
1882         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1883         unsigned int i;
1884         unsigned int binh = 1, binv = 1;
1885         int best = scaling_goodness(
1886                 subdev,
1887                 crops[SMIAPP_PAD_SINK]->width, sel->r.width,
1888                 crops[SMIAPP_PAD_SINK]->height, sel->r.height, sel->flags);
1889
1890         for (i = 0; i < sensor->nbinning_subtypes; i++) {
1891                 int this = scaling_goodness(
1892                         subdev,
1893                         crops[SMIAPP_PAD_SINK]->width
1894                         / sensor->binning_subtypes[i].horizontal,
1895                         sel->r.width,
1896                         crops[SMIAPP_PAD_SINK]->height
1897                         / sensor->binning_subtypes[i].vertical,
1898                         sel->r.height, sel->flags);
1899
1900                 if (this > best) {
1901                         binh = sensor->binning_subtypes[i].horizontal;
1902                         binv = sensor->binning_subtypes[i].vertical;
1903                         best = this;
1904                 }
1905         }
1906         if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
1907                 sensor->binning_vertical = binv;
1908                 sensor->binning_horizontal = binh;
1909         }
1910
1911         sel->r.width = (crops[SMIAPP_PAD_SINK]->width / binh) & ~1;
1912         sel->r.height = (crops[SMIAPP_PAD_SINK]->height / binv) & ~1;
1913 }
1914
1915 /*
1916  * Calculate best scaling ratio and mode for given output resolution.
1917  *
1918  * Try all of these: horizontal ratio, vertical ratio and smallest
1919  * size possible (horizontally).
1920  *
1921  * Also try whether horizontal scaler or full scaler gives a better
1922  * result.
1923  */
1924 static void smiapp_set_compose_scaler(struct v4l2_subdev *subdev,
1925                                       struct v4l2_subdev_pad_config *cfg,
1926                                       struct v4l2_subdev_selection *sel,
1927                                       struct v4l2_rect **crops,
1928                                       struct v4l2_rect *comp)
1929 {
1930         struct i2c_client *client = v4l2_get_subdevdata(subdev);
1931         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
1932         u32 min, max, a, b, max_m;
1933         u32 scale_m = sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN];
1934         int mode = SMIAPP_SCALING_MODE_HORIZONTAL;
1935         u32 try[4];
1936         u32 ntry = 0;
1937         unsigned int i;
1938         int best = INT_MIN;
1939
1940         sel->r.width = min_t(unsigned int, sel->r.width,
1941                              crops[SMIAPP_PAD_SINK]->width);
1942         sel->r.height = min_t(unsigned int, sel->r.height,
1943                               crops[SMIAPP_PAD_SINK]->height);
1944
1945         a = crops[SMIAPP_PAD_SINK]->width
1946                 * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN] / sel->r.width;
1947         b = crops[SMIAPP_PAD_SINK]->height
1948                 * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN] / sel->r.height;
1949         max_m = crops[SMIAPP_PAD_SINK]->width
1950                 * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN]
1951                 / sensor->limits[SMIAPP_LIMIT_MIN_X_OUTPUT_SIZE];
1952
1953         a = clamp(a, sensor->limits[SMIAPP_LIMIT_SCALER_M_MIN],
1954                   sensor->limits[SMIAPP_LIMIT_SCALER_M_MAX]);
1955         b = clamp(b, sensor->limits[SMIAPP_LIMIT_SCALER_M_MIN],
1956                   sensor->limits[SMIAPP_LIMIT_SCALER_M_MAX]);
1957         max_m = clamp(max_m, sensor->limits[SMIAPP_LIMIT_SCALER_M_MIN],
1958                       sensor->limits[SMIAPP_LIMIT_SCALER_M_MAX]);
1959
1960         dev_dbg(&client->dev, "scaling: a %d b %d max_m %d\n", a, b, max_m);
1961
1962         min = min(max_m, min(a, b));
1963         max = min(max_m, max(a, b));
1964
1965         try[ntry] = min;
1966         ntry++;
1967         if (min != max) {
1968                 try[ntry] = max;
1969                 ntry++;
1970         }
1971         if (max != max_m) {
1972                 try[ntry] = min + 1;
1973                 ntry++;
1974                 if (min != max) {
1975                         try[ntry] = max + 1;
1976                         ntry++;
1977                 }
1978         }
1979
1980         for (i = 0; i < ntry; i++) {
1981                 int this = scaling_goodness(
1982                         subdev,
1983                         crops[SMIAPP_PAD_SINK]->width
1984                         / try[i]
1985                         * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN],
1986                         sel->r.width,
1987                         crops[SMIAPP_PAD_SINK]->height,
1988                         sel->r.height,
1989                         sel->flags);
1990
1991                 dev_dbg(&client->dev, "trying factor %d (%d)\n", try[i], i);
1992
1993                 if (this > best) {
1994                         scale_m = try[i];
1995                         mode = SMIAPP_SCALING_MODE_HORIZONTAL;
1996                         best = this;
1997                 }
1998
1999                 if (sensor->limits[SMIAPP_LIMIT_SCALING_CAPABILITY]
2000                     == SMIAPP_SCALING_CAPABILITY_HORIZONTAL)
2001                         continue;
2002
2003                 this = scaling_goodness(
2004                         subdev, crops[SMIAPP_PAD_SINK]->width
2005                         / try[i]
2006                         * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN],
2007                         sel->r.width,
2008                         crops[SMIAPP_PAD_SINK]->height
2009                         / try[i]
2010                         * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN],
2011                         sel->r.height,
2012                         sel->flags);
2013
2014                 if (this > best) {
2015                         scale_m = try[i];
2016                         mode = SMIAPP_SCALING_MODE_BOTH;
2017                         best = this;
2018                 }
2019         }
2020
2021         sel->r.width =
2022                 (crops[SMIAPP_PAD_SINK]->width
2023                  / scale_m
2024                  * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN]) & ~1;
2025         if (mode == SMIAPP_SCALING_MODE_BOTH)
2026                 sel->r.height =
2027                         (crops[SMIAPP_PAD_SINK]->height
2028                          / scale_m
2029                          * sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN])
2030                         & ~1;
2031         else
2032                 sel->r.height = crops[SMIAPP_PAD_SINK]->height;
2033
2034         if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
2035                 sensor->scale_m = scale_m;
2036                 sensor->scaling_mode = mode;
2037         }
2038 }
2039 /* We're only called on source pads. This function sets scaling. */
2040 static int smiapp_set_compose(struct v4l2_subdev *subdev,
2041                               struct v4l2_subdev_pad_config *cfg,
2042                               struct v4l2_subdev_selection *sel)
2043 {
2044         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2045         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
2046         struct v4l2_rect *comp, *crops[SMIAPP_PADS];
2047
2048         smiapp_get_crop_compose(subdev, cfg, crops, &comp, sel->which);
2049
2050         sel->r.top = 0;
2051         sel->r.left = 0;
2052
2053         if (ssd == sensor->binner)
2054                 smiapp_set_compose_binner(subdev, cfg, sel, crops, comp);
2055         else
2056                 smiapp_set_compose_scaler(subdev, cfg, sel, crops, comp);
2057
2058         *comp = sel->r;
2059         smiapp_propagate(subdev, cfg, sel->which,
2060                          V4L2_SEL_TGT_COMPOSE);
2061
2062         if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE)
2063                 return smiapp_update_mode(sensor);
2064
2065         return 0;
2066 }
2067
2068 static int __smiapp_sel_supported(struct v4l2_subdev *subdev,
2069                                   struct v4l2_subdev_selection *sel)
2070 {
2071         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2072         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
2073
2074         /* We only implement crop in three places. */
2075         switch (sel->target) {
2076         case V4L2_SEL_TGT_CROP:
2077         case V4L2_SEL_TGT_CROP_BOUNDS:
2078                 if (ssd == sensor->pixel_array
2079                     && sel->pad == SMIAPP_PA_PAD_SRC)
2080                         return 0;
2081                 if (ssd == sensor->src
2082                     && sel->pad == SMIAPP_PAD_SRC)
2083                         return 0;
2084                 if (ssd == sensor->scaler
2085                     && sel->pad == SMIAPP_PAD_SINK
2086                     && sensor->limits[SMIAPP_LIMIT_DIGITAL_CROP_CAPABILITY]
2087                     == SMIAPP_DIGITAL_CROP_CAPABILITY_INPUT_CROP)
2088                         return 0;
2089                 return -EINVAL;
2090         case V4L2_SEL_TGT_NATIVE_SIZE:
2091                 if (ssd == sensor->pixel_array
2092                     && sel->pad == SMIAPP_PA_PAD_SRC)
2093                         return 0;
2094                 return -EINVAL;
2095         case V4L2_SEL_TGT_COMPOSE:
2096         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
2097                 if (sel->pad == ssd->source_pad)
2098                         return -EINVAL;
2099                 if (ssd == sensor->binner)
2100                         return 0;
2101                 if (ssd == sensor->scaler
2102                     && sensor->limits[SMIAPP_LIMIT_SCALING_CAPABILITY]
2103                     != SMIAPP_SCALING_CAPABILITY_NONE)
2104                         return 0;
2105                 /* Fall through */
2106         default:
2107                 return -EINVAL;
2108         }
2109 }
2110
2111 static int smiapp_set_crop(struct v4l2_subdev *subdev,
2112                            struct v4l2_subdev_pad_config *cfg,
2113                            struct v4l2_subdev_selection *sel)
2114 {
2115         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2116         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
2117         struct v4l2_rect *src_size, *crops[SMIAPP_PADS];
2118         struct v4l2_rect _r;
2119
2120         smiapp_get_crop_compose(subdev, cfg, crops, NULL, sel->which);
2121
2122         if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
2123                 if (sel->pad == ssd->sink_pad)
2124                         src_size = &ssd->sink_fmt;
2125                 else
2126                         src_size = &ssd->compose;
2127         } else {
2128                 if (sel->pad == ssd->sink_pad) {
2129                         _r.left = 0;
2130                         _r.top = 0;
2131                         _r.width = v4l2_subdev_get_try_format(subdev, cfg, sel->pad)
2132                                 ->width;
2133                         _r.height = v4l2_subdev_get_try_format(subdev, cfg, sel->pad)
2134                                 ->height;
2135                         src_size = &_r;
2136                 } else {
2137                         src_size =
2138                                 v4l2_subdev_get_try_compose(
2139                                         subdev, cfg, ssd->sink_pad);
2140                 }
2141         }
2142
2143         if (ssd == sensor->src && sel->pad == SMIAPP_PAD_SRC) {
2144                 sel->r.left = 0;
2145                 sel->r.top = 0;
2146         }
2147
2148         sel->r.width = min(sel->r.width, src_size->width);
2149         sel->r.height = min(sel->r.height, src_size->height);
2150
2151         sel->r.left = min_t(int, sel->r.left, src_size->width - sel->r.width);
2152         sel->r.top = min_t(int, sel->r.top, src_size->height - sel->r.height);
2153
2154         *crops[sel->pad] = sel->r;
2155
2156         if (ssd != sensor->pixel_array && sel->pad == SMIAPP_PAD_SINK)
2157                 smiapp_propagate(subdev, cfg, sel->which,
2158                                  V4L2_SEL_TGT_CROP);
2159
2160         return 0;
2161 }
2162
2163 static int __smiapp_get_selection(struct v4l2_subdev *subdev,
2164                                   struct v4l2_subdev_pad_config *cfg,
2165                                   struct v4l2_subdev_selection *sel)
2166 {
2167         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2168         struct smiapp_subdev *ssd = to_smiapp_subdev(subdev);
2169         struct v4l2_rect *comp, *crops[SMIAPP_PADS];
2170         struct v4l2_rect sink_fmt;
2171         int ret;
2172
2173         ret = __smiapp_sel_supported(subdev, sel);
2174         if (ret)
2175                 return ret;
2176
2177         smiapp_get_crop_compose(subdev, cfg, crops, &comp, sel->which);
2178
2179         if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
2180                 sink_fmt = ssd->sink_fmt;
2181         } else {
2182                 struct v4l2_mbus_framefmt *fmt =
2183                         v4l2_subdev_get_try_format(subdev, cfg, ssd->sink_pad);
2184
2185                 sink_fmt.left = 0;
2186                 sink_fmt.top = 0;
2187                 sink_fmt.width = fmt->width;
2188                 sink_fmt.height = fmt->height;
2189         }
2190
2191         switch (sel->target) {
2192         case V4L2_SEL_TGT_CROP_BOUNDS:
2193         case V4L2_SEL_TGT_NATIVE_SIZE:
2194                 if (ssd == sensor->pixel_array) {
2195                         sel->r.left = sel->r.top = 0;
2196                         sel->r.width =
2197                                 sensor->limits[SMIAPP_LIMIT_X_ADDR_MAX] + 1;
2198                         sel->r.height =
2199                                 sensor->limits[SMIAPP_LIMIT_Y_ADDR_MAX] + 1;
2200                 } else if (sel->pad == ssd->sink_pad) {
2201                         sel->r = sink_fmt;
2202                 } else {
2203                         sel->r = *comp;
2204                 }
2205                 break;
2206         case V4L2_SEL_TGT_CROP:
2207         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
2208                 sel->r = *crops[sel->pad];
2209                 break;
2210         case V4L2_SEL_TGT_COMPOSE:
2211                 sel->r = *comp;
2212                 break;
2213         }
2214
2215         return 0;
2216 }
2217
2218 static int smiapp_get_selection(struct v4l2_subdev *subdev,
2219                                 struct v4l2_subdev_pad_config *cfg,
2220                                 struct v4l2_subdev_selection *sel)
2221 {
2222         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2223         int rval;
2224
2225         mutex_lock(&sensor->mutex);
2226         rval = __smiapp_get_selection(subdev, cfg, sel);
2227         mutex_unlock(&sensor->mutex);
2228
2229         return rval;
2230 }
2231 static int smiapp_set_selection(struct v4l2_subdev *subdev,
2232                                 struct v4l2_subdev_pad_config *cfg,
2233                                 struct v4l2_subdev_selection *sel)
2234 {
2235         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2236         int ret;
2237
2238         ret = __smiapp_sel_supported(subdev, sel);
2239         if (ret)
2240                 return ret;
2241
2242         mutex_lock(&sensor->mutex);
2243
2244         sel->r.left = max(0, sel->r.left & ~1);
2245         sel->r.top = max(0, sel->r.top & ~1);
2246         sel->r.width = SMIAPP_ALIGN_DIM(sel->r.width, sel->flags);
2247         sel->r.height = SMIAPP_ALIGN_DIM(sel->r.height, sel->flags);
2248
2249         sel->r.width = max_t(unsigned int,
2250                              sensor->limits[SMIAPP_LIMIT_MIN_X_OUTPUT_SIZE],
2251                              sel->r.width);
2252         sel->r.height = max_t(unsigned int,
2253                               sensor->limits[SMIAPP_LIMIT_MIN_Y_OUTPUT_SIZE],
2254                               sel->r.height);
2255
2256         switch (sel->target) {
2257         case V4L2_SEL_TGT_CROP:
2258                 ret = smiapp_set_crop(subdev, cfg, sel);
2259                 break;
2260         case V4L2_SEL_TGT_COMPOSE:
2261                 ret = smiapp_set_compose(subdev, cfg, sel);
2262                 break;
2263         default:
2264                 ret = -EINVAL;
2265         }
2266
2267         mutex_unlock(&sensor->mutex);
2268         return ret;
2269 }
2270
2271 static int smiapp_get_skip_frames(struct v4l2_subdev *subdev, u32 *frames)
2272 {
2273         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2274
2275         *frames = sensor->frame_skip;
2276         return 0;
2277 }
2278
2279 static int smiapp_get_skip_top_lines(struct v4l2_subdev *subdev, u32 *lines)
2280 {
2281         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2282
2283         *lines = sensor->image_start;
2284
2285         return 0;
2286 }
2287
2288 /* -----------------------------------------------------------------------------
2289  * sysfs attributes
2290  */
2291
2292 static ssize_t
2293 smiapp_sysfs_nvm_read(struct device *dev, struct device_attribute *attr,
2294                       char *buf)
2295 {
2296         struct v4l2_subdev *subdev = i2c_get_clientdata(to_i2c_client(dev));
2297         struct i2c_client *client = v4l2_get_subdevdata(subdev);
2298         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2299         unsigned int nbytes;
2300
2301         if (!sensor->dev_init_done)
2302                 return -EBUSY;
2303
2304         if (!sensor->nvm_size) {
2305                 /* NVM not read yet - read it now */
2306                 sensor->nvm_size = sensor->hwcfg->nvm_size;
2307                 if (smiapp_set_power(subdev, 1) < 0)
2308                         return -ENODEV;
2309                 if (smiapp_read_nvm(sensor, sensor->nvm)) {
2310                         dev_err(&client->dev, "nvm read failed\n");
2311                         return -ENODEV;
2312                 }
2313                 smiapp_set_power(subdev, 0);
2314         }
2315         /*
2316          * NVM is still way below a PAGE_SIZE, so we can safely
2317          * assume this for now.
2318          */
2319         nbytes = min_t(unsigned int, sensor->nvm_size, PAGE_SIZE);
2320         memcpy(buf, sensor->nvm, nbytes);
2321
2322         return nbytes;
2323 }
2324 static DEVICE_ATTR(nvm, S_IRUGO, smiapp_sysfs_nvm_read, NULL);
2325
2326 static ssize_t
2327 smiapp_sysfs_ident_read(struct device *dev, struct device_attribute *attr,
2328                         char *buf)
2329 {
2330         struct v4l2_subdev *subdev = i2c_get_clientdata(to_i2c_client(dev));
2331         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2332         struct smiapp_module_info *minfo = &sensor->minfo;
2333
2334         return snprintf(buf, PAGE_SIZE, "%2.2x%4.4x%2.2x\n",
2335                         minfo->manufacturer_id, minfo->model_id,
2336                         minfo->revision_number_major) + 1;
2337 }
2338
2339 static DEVICE_ATTR(ident, S_IRUGO, smiapp_sysfs_ident_read, NULL);
2340
2341 /* -----------------------------------------------------------------------------
2342  * V4L2 subdev core operations
2343  */
2344
2345 static int smiapp_identify_module(struct smiapp_sensor *sensor)
2346 {
2347         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
2348         struct smiapp_module_info *minfo = &sensor->minfo;
2349         unsigned int i;
2350         int rval = 0;
2351
2352         minfo->name = SMIAPP_NAME;
2353
2354         /* Module info */
2355         rval = smiapp_read_8only(sensor, SMIAPP_REG_U8_MANUFACTURER_ID,
2356                                  &minfo->manufacturer_id);
2357         if (!rval)
2358                 rval = smiapp_read_8only(sensor, SMIAPP_REG_U16_MODEL_ID,
2359                                          &minfo->model_id);
2360         if (!rval)
2361                 rval = smiapp_read_8only(sensor,
2362                                          SMIAPP_REG_U8_REVISION_NUMBER_MAJOR,
2363                                          &minfo->revision_number_major);
2364         if (!rval)
2365                 rval = smiapp_read_8only(sensor,
2366                                          SMIAPP_REG_U8_REVISION_NUMBER_MINOR,
2367                                          &minfo->revision_number_minor);
2368         if (!rval)
2369                 rval = smiapp_read_8only(sensor,
2370                                          SMIAPP_REG_U8_MODULE_DATE_YEAR,
2371                                          &minfo->module_year);
2372         if (!rval)
2373                 rval = smiapp_read_8only(sensor,
2374                                          SMIAPP_REG_U8_MODULE_DATE_MONTH,
2375                                          &minfo->module_month);
2376         if (!rval)
2377                 rval = smiapp_read_8only(sensor, SMIAPP_REG_U8_MODULE_DATE_DAY,
2378                                          &minfo->module_day);
2379
2380         /* Sensor info */
2381         if (!rval)
2382                 rval = smiapp_read_8only(sensor,
2383                                          SMIAPP_REG_U8_SENSOR_MANUFACTURER_ID,
2384                                          &minfo->sensor_manufacturer_id);
2385         if (!rval)
2386                 rval = smiapp_read_8only(sensor,
2387                                          SMIAPP_REG_U16_SENSOR_MODEL_ID,
2388                                          &minfo->sensor_model_id);
2389         if (!rval)
2390                 rval = smiapp_read_8only(sensor,
2391                                          SMIAPP_REG_U8_SENSOR_REVISION_NUMBER,
2392                                          &minfo->sensor_revision_number);
2393         if (!rval)
2394                 rval = smiapp_read_8only(sensor,
2395                                          SMIAPP_REG_U8_SENSOR_FIRMWARE_VERSION,
2396                                          &minfo->sensor_firmware_version);
2397
2398         /* SMIA */
2399         if (!rval)
2400                 rval = smiapp_read_8only(sensor, SMIAPP_REG_U8_SMIA_VERSION,
2401                                          &minfo->smia_version);
2402         if (!rval)
2403                 rval = smiapp_read_8only(sensor, SMIAPP_REG_U8_SMIAPP_VERSION,
2404                                          &minfo->smiapp_version);
2405
2406         if (rval) {
2407                 dev_err(&client->dev, "sensor detection failed\n");
2408                 return -ENODEV;
2409         }
2410
2411         dev_dbg(&client->dev, "module 0x%2.2x-0x%4.4x\n",
2412                 minfo->manufacturer_id, minfo->model_id);
2413
2414         dev_dbg(&client->dev,
2415                 "module revision 0x%2.2x-0x%2.2x date %2.2d-%2.2d-%2.2d\n",
2416                 minfo->revision_number_major, minfo->revision_number_minor,
2417                 minfo->module_year, minfo->module_month, minfo->module_day);
2418
2419         dev_dbg(&client->dev, "sensor 0x%2.2x-0x%4.4x\n",
2420                 minfo->sensor_manufacturer_id, minfo->sensor_model_id);
2421
2422         dev_dbg(&client->dev,
2423                 "sensor revision 0x%2.2x firmware version 0x%2.2x\n",
2424                 minfo->sensor_revision_number, minfo->sensor_firmware_version);
2425
2426         dev_dbg(&client->dev, "smia version %2.2d smiapp version %2.2d\n",
2427                 minfo->smia_version, minfo->smiapp_version);
2428
2429         /*
2430          * Some modules have bad data in the lvalues below. Hope the
2431          * rvalues have better stuff. The lvalues are module
2432          * parameters whereas the rvalues are sensor parameters.
2433          */
2434         if (!minfo->manufacturer_id && !minfo->model_id) {
2435                 minfo->manufacturer_id = minfo->sensor_manufacturer_id;
2436                 minfo->model_id = minfo->sensor_model_id;
2437                 minfo->revision_number_major = minfo->sensor_revision_number;
2438         }
2439
2440         for (i = 0; i < ARRAY_SIZE(smiapp_module_idents); i++) {
2441                 if (smiapp_module_idents[i].manufacturer_id
2442                     != minfo->manufacturer_id)
2443                         continue;
2444                 if (smiapp_module_idents[i].model_id != minfo->model_id)
2445                         continue;
2446                 if (smiapp_module_idents[i].flags
2447                     & SMIAPP_MODULE_IDENT_FLAG_REV_LE) {
2448                         if (smiapp_module_idents[i].revision_number_major
2449                             < minfo->revision_number_major)
2450                                 continue;
2451                 } else {
2452                         if (smiapp_module_idents[i].revision_number_major
2453                             != minfo->revision_number_major)
2454                                 continue;
2455                 }
2456
2457                 minfo->name = smiapp_module_idents[i].name;
2458                 minfo->quirk = smiapp_module_idents[i].quirk;
2459                 break;
2460         }
2461
2462         if (i >= ARRAY_SIZE(smiapp_module_idents))
2463                 dev_warn(&client->dev,
2464                          "no quirks for this module; let's hope it's fully compliant\n");
2465
2466         dev_dbg(&client->dev, "the sensor is called %s, ident %2.2x%4.4x%2.2x\n",
2467                 minfo->name, minfo->manufacturer_id, minfo->model_id,
2468                 minfo->revision_number_major);
2469
2470         return 0;
2471 }
2472
2473 static const struct v4l2_subdev_ops smiapp_ops;
2474 static const struct v4l2_subdev_internal_ops smiapp_internal_ops;
2475 static const struct media_entity_operations smiapp_entity_ops;
2476
2477 static int smiapp_register_subdevs(struct smiapp_sensor *sensor)
2478 {
2479         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
2480         struct smiapp_subdev *ssds[] = {
2481                 sensor->scaler,
2482                 sensor->binner,
2483                 sensor->pixel_array,
2484         };
2485         unsigned int i;
2486         int rval;
2487
2488         for (i = 0; i < SMIAPP_SUBDEVS - 1; i++) {
2489                 struct smiapp_subdev *this = ssds[i + 1];
2490                 struct smiapp_subdev *last = ssds[i];
2491
2492                 if (!last)
2493                         continue;
2494
2495                 rval = media_entity_pads_init(&this->sd.entity,
2496                                          this->npads, this->pads);
2497                 if (rval) {
2498                         dev_err(&client->dev,
2499                                 "media_entity_pads_init failed\n");
2500                         return rval;
2501                 }
2502
2503                 rval = v4l2_device_register_subdev(sensor->src->sd.v4l2_dev,
2504                                                    &this->sd);
2505                 if (rval) {
2506                         dev_err(&client->dev,
2507                                 "v4l2_device_register_subdev failed\n");
2508                         return rval;
2509                 }
2510
2511                 rval = media_create_pad_link(&this->sd.entity,
2512                                              this->source_pad,
2513                                              &last->sd.entity,
2514                                              last->sink_pad,
2515                                              MEDIA_LNK_FL_ENABLED |
2516                                              MEDIA_LNK_FL_IMMUTABLE);
2517                 if (rval) {
2518                         dev_err(&client->dev,
2519                                 "media_create_pad_link failed\n");
2520                         return rval;
2521                 }
2522         }
2523
2524         return 0;
2525 }
2526
2527 static void smiapp_cleanup(struct smiapp_sensor *sensor)
2528 {
2529         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
2530
2531         device_remove_file(&client->dev, &dev_attr_nvm);
2532         device_remove_file(&client->dev, &dev_attr_ident);
2533
2534         smiapp_free_controls(sensor);
2535 }
2536
2537 static int smiapp_init(struct smiapp_sensor *sensor)
2538 {
2539         struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd);
2540         struct smiapp_pll *pll = &sensor->pll;
2541         struct smiapp_subdev *last = NULL;
2542         unsigned int i;
2543         int rval;
2544
2545         sensor->vana = devm_regulator_get(&client->dev, "vana");
2546         if (IS_ERR(sensor->vana)) {
2547                 dev_err(&client->dev, "could not get regulator for vana\n");
2548                 return PTR_ERR(sensor->vana);
2549         }
2550
2551         sensor->ext_clk = devm_clk_get(&client->dev, NULL);
2552         if (IS_ERR(sensor->ext_clk)) {
2553                 dev_err(&client->dev, "could not get clock (%ld)\n",
2554                         PTR_ERR(sensor->ext_clk));
2555                 return -EPROBE_DEFER;
2556         }
2557
2558         rval = clk_set_rate(sensor->ext_clk,
2559                             sensor->hwcfg->ext_clk);
2560         if (rval < 0) {
2561                 dev_err(&client->dev,
2562                         "unable to set clock freq to %u\n",
2563                         sensor->hwcfg->ext_clk);
2564                 return rval;
2565         }
2566
2567         sensor->xshutdown = devm_gpiod_get_optional(&client->dev, "xshutdown",
2568                                                     GPIOD_OUT_LOW);
2569         if (IS_ERR(sensor->xshutdown))
2570                 return PTR_ERR(sensor->xshutdown);
2571
2572         rval = smiapp_power_on(sensor);
2573         if (rval)
2574                 return -ENODEV;
2575
2576         rval = smiapp_identify_module(sensor);
2577         if (rval) {
2578                 rval = -ENODEV;
2579                 goto out_power_off;
2580         }
2581
2582         rval = smiapp_get_all_limits(sensor);
2583         if (rval) {
2584                 rval = -ENODEV;
2585                 goto out_power_off;
2586         }
2587
2588         /*
2589          * Handle Sensor Module orientation on the board.
2590          *
2591          * The application of H-FLIP and V-FLIP on the sensor is modified by
2592          * the sensor orientation on the board.
2593          *
2594          * For SMIAPP_BOARD_SENSOR_ORIENT_180 the default behaviour is to set
2595          * both H-FLIP and V-FLIP for normal operation which also implies
2596          * that a set/unset operation for user space HFLIP and VFLIP v4l2
2597          * controls will need to be internally inverted.
2598          *
2599          * Rotation also changes the bayer pattern.
2600          */
2601         if (sensor->hwcfg->module_board_orient ==
2602             SMIAPP_MODULE_BOARD_ORIENT_180)
2603                 sensor->hvflip_inv_mask = SMIAPP_IMAGE_ORIENTATION_HFLIP |
2604                                           SMIAPP_IMAGE_ORIENTATION_VFLIP;
2605
2606         rval = smiapp_call_quirk(sensor, limits);
2607         if (rval) {
2608                 dev_err(&client->dev, "limits quirks failed\n");
2609                 goto out_power_off;
2610         }
2611
2612         if (sensor->limits[SMIAPP_LIMIT_BINNING_CAPABILITY]) {
2613                 u32 val;
2614
2615                 rval = smiapp_read(sensor,
2616                                    SMIAPP_REG_U8_BINNING_SUBTYPES, &val);
2617                 if (rval < 0) {
2618                         rval = -ENODEV;
2619                         goto out_power_off;
2620                 }
2621                 sensor->nbinning_subtypes = min_t(u8, val,
2622                                                   SMIAPP_BINNING_SUBTYPES);
2623
2624                 for (i = 0; i < sensor->nbinning_subtypes; i++) {
2625                         rval = smiapp_read(
2626                                 sensor, SMIAPP_REG_U8_BINNING_TYPE_n(i), &val);
2627                         if (rval < 0) {
2628                                 rval = -ENODEV;
2629                                 goto out_power_off;
2630                         }
2631                         sensor->binning_subtypes[i] =
2632                                 *(struct smiapp_binning_subtype *)&val;
2633
2634                         dev_dbg(&client->dev, "binning %xx%x\n",
2635                                 sensor->binning_subtypes[i].horizontal,
2636                                 sensor->binning_subtypes[i].vertical);
2637                 }
2638         }
2639         sensor->binning_horizontal = 1;
2640         sensor->binning_vertical = 1;
2641
2642         if (device_create_file(&client->dev, &dev_attr_ident) != 0) {
2643                 dev_err(&client->dev, "sysfs ident entry creation failed\n");
2644                 rval = -ENOENT;
2645                 goto out_power_off;
2646         }
2647         /* SMIA++ NVM initialization - it will be read from the sensor
2648          * when it is first requested by userspace.
2649          */
2650         if (sensor->minfo.smiapp_version && sensor->hwcfg->nvm_size) {
2651                 sensor->nvm = devm_kzalloc(&client->dev,
2652                                 sensor->hwcfg->nvm_size, GFP_KERNEL);
2653                 if (sensor->nvm == NULL) {
2654                         dev_err(&client->dev, "nvm buf allocation failed\n");
2655                         rval = -ENOMEM;
2656                         goto out_cleanup;
2657                 }
2658
2659                 if (device_create_file(&client->dev, &dev_attr_nvm) != 0) {
2660                         dev_err(&client->dev, "sysfs nvm entry failed\n");
2661                         rval = -EBUSY;
2662                         goto out_cleanup;
2663                 }
2664         }
2665
2666         /* We consider this as profile 0 sensor if any of these are zero. */
2667         if (!sensor->limits[SMIAPP_LIMIT_MIN_OP_SYS_CLK_DIV] ||
2668             !sensor->limits[SMIAPP_LIMIT_MAX_OP_SYS_CLK_DIV] ||
2669             !sensor->limits[SMIAPP_LIMIT_MIN_OP_PIX_CLK_DIV] ||
2670             !sensor->limits[SMIAPP_LIMIT_MAX_OP_PIX_CLK_DIV]) {
2671                 sensor->minfo.smiapp_profile = SMIAPP_PROFILE_0;
2672         } else if (sensor->limits[SMIAPP_LIMIT_SCALING_CAPABILITY]
2673                    != SMIAPP_SCALING_CAPABILITY_NONE) {
2674                 if (sensor->limits[SMIAPP_LIMIT_SCALING_CAPABILITY]
2675                     == SMIAPP_SCALING_CAPABILITY_HORIZONTAL)
2676                         sensor->minfo.smiapp_profile = SMIAPP_PROFILE_1;
2677                 else
2678                         sensor->minfo.smiapp_profile = SMIAPP_PROFILE_2;
2679                 sensor->scaler = &sensor->ssds[sensor->ssds_used];
2680                 sensor->ssds_used++;
2681         } else if (sensor->limits[SMIAPP_LIMIT_DIGITAL_CROP_CAPABILITY]
2682                    == SMIAPP_DIGITAL_CROP_CAPABILITY_INPUT_CROP) {
2683                 sensor->scaler = &sensor->ssds[sensor->ssds_used];
2684                 sensor->ssds_used++;
2685         }
2686         sensor->binner = &sensor->ssds[sensor->ssds_used];
2687         sensor->ssds_used++;
2688         sensor->pixel_array = &sensor->ssds[sensor->ssds_used];
2689         sensor->ssds_used++;
2690
2691         sensor->scale_m = sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN];
2692
2693         /* prepare PLL configuration input values */
2694         pll->bus_type = SMIAPP_PLL_BUS_TYPE_CSI2;
2695         pll->csi2.lanes = sensor->hwcfg->lanes;
2696         pll->ext_clk_freq_hz = sensor->hwcfg->ext_clk;
2697         pll->scale_n = sensor->limits[SMIAPP_LIMIT_SCALER_N_MIN];
2698         /* Profile 0 sensors have no separate OP clock branch. */
2699         if (sensor->minfo.smiapp_profile == SMIAPP_PROFILE_0)
2700                 pll->flags |= SMIAPP_PLL_FLAG_NO_OP_CLOCKS;
2701
2702         for (i = 0; i < SMIAPP_SUBDEVS; i++) {
2703                 struct {
2704                         struct smiapp_subdev *ssd;
2705                         char *name;
2706                 } const __this[] = {
2707                         { sensor->scaler, "scaler", },
2708                         { sensor->binner, "binner", },
2709                         { sensor->pixel_array, "pixel array", },
2710                 }, *_this = &__this[i];
2711                 struct smiapp_subdev *this = _this->ssd;
2712
2713                 if (!this)
2714                         continue;
2715
2716                 if (this != sensor->src)
2717                         v4l2_subdev_init(&this->sd, &smiapp_ops);
2718
2719                 this->sensor = sensor;
2720
2721                 if (this == sensor->pixel_array) {
2722                         this->npads = 1;
2723                 } else {
2724                         this->npads = 2;
2725                         this->source_pad = 1;
2726                 }
2727
2728                 snprintf(this->sd.name,
2729                          sizeof(this->sd.name), "%s %s %d-%4.4x",
2730                          sensor->minfo.name, _this->name,
2731                          i2c_adapter_id(client->adapter), client->addr);
2732
2733                 this->sink_fmt.width =
2734                         sensor->limits[SMIAPP_LIMIT_X_ADDR_MAX] + 1;
2735                 this->sink_fmt.height =
2736                         sensor->limits[SMIAPP_LIMIT_Y_ADDR_MAX] + 1;
2737                 this->compose.width = this->sink_fmt.width;
2738                 this->compose.height = this->sink_fmt.height;
2739                 this->crop[this->source_pad] = this->compose;
2740                 this->pads[this->source_pad].flags = MEDIA_PAD_FL_SOURCE;
2741                 if (this != sensor->pixel_array) {
2742                         this->crop[this->sink_pad] = this->compose;
2743                         this->pads[this->sink_pad].flags = MEDIA_PAD_FL_SINK;
2744                 }
2745
2746                 this->sd.entity.ops = &smiapp_entity_ops;
2747
2748                 if (last == NULL) {
2749                         last = this;
2750                         continue;
2751                 }
2752
2753                 this->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
2754                 this->sd.internal_ops = &smiapp_internal_ops;
2755                 this->sd.owner = THIS_MODULE;
2756                 v4l2_set_subdevdata(&this->sd, client);
2757
2758                 last = this;
2759         }
2760
2761         dev_dbg(&client->dev, "profile %d\n", sensor->minfo.smiapp_profile);
2762
2763         sensor->pixel_array->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
2764
2765         /* final steps */
2766         smiapp_read_frame_fmt(sensor);
2767         rval = smiapp_init_controls(sensor);
2768         if (rval < 0)
2769                 goto out_cleanup;
2770
2771         rval = smiapp_call_quirk(sensor, init);
2772         if (rval)
2773                 goto out_cleanup;
2774
2775         rval = smiapp_get_mbus_formats(sensor);
2776         if (rval) {
2777                 rval = -ENODEV;
2778                 goto out_cleanup;
2779         }
2780
2781         rval = smiapp_init_late_controls(sensor);
2782         if (rval) {
2783                 rval = -ENODEV;
2784                 goto out_cleanup;
2785         }
2786
2787         mutex_lock(&sensor->mutex);
2788         rval = smiapp_update_mode(sensor);
2789         mutex_unlock(&sensor->mutex);
2790         if (rval) {
2791                 dev_err(&client->dev, "update mode failed\n");
2792                 goto out_cleanup;
2793         }
2794
2795         sensor->streaming = false;
2796         sensor->dev_init_done = true;
2797
2798         smiapp_power_off(sensor);
2799
2800         return 0;
2801
2802 out_cleanup:
2803         smiapp_cleanup(sensor);
2804
2805 out_power_off:
2806         smiapp_power_off(sensor);
2807         return rval;
2808 }
2809
2810 static int smiapp_registered(struct v4l2_subdev *subdev)
2811 {
2812         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2813         struct i2c_client *client = v4l2_get_subdevdata(subdev);
2814         int rval;
2815
2816         if (!client->dev.of_node) {
2817                 rval = smiapp_init(sensor);
2818                 if (rval)
2819                         return rval;
2820         }
2821
2822         rval = smiapp_register_subdevs(sensor);
2823         if (rval)
2824                 smiapp_cleanup(sensor);
2825
2826         return rval;
2827 }
2828
2829 static int smiapp_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
2830 {
2831         struct smiapp_subdev *ssd = to_smiapp_subdev(sd);
2832         struct smiapp_sensor *sensor = ssd->sensor;
2833         u32 mbus_code =
2834                 smiapp_csi_data_formats[smiapp_pixel_order(sensor)].code;
2835         unsigned int i;
2836
2837         mutex_lock(&sensor->mutex);
2838
2839         for (i = 0; i < ssd->npads; i++) {
2840                 struct v4l2_mbus_framefmt *try_fmt =
2841                         v4l2_subdev_get_try_format(sd, fh->pad, i);
2842                 struct v4l2_rect *try_crop = v4l2_subdev_get_try_crop(sd, fh->pad, i);
2843                 struct v4l2_rect *try_comp;
2844
2845                 try_fmt->width = sensor->limits[SMIAPP_LIMIT_X_ADDR_MAX] + 1;
2846                 try_fmt->height = sensor->limits[SMIAPP_LIMIT_Y_ADDR_MAX] + 1;
2847                 try_fmt->code = mbus_code;
2848                 try_fmt->field = V4L2_FIELD_NONE;
2849
2850                 try_crop->top = 0;
2851                 try_crop->left = 0;
2852                 try_crop->width = try_fmt->width;
2853                 try_crop->height = try_fmt->height;
2854
2855                 if (ssd != sensor->pixel_array)
2856                         continue;
2857
2858                 try_comp = v4l2_subdev_get_try_compose(sd, fh->pad, i);
2859                 *try_comp = *try_crop;
2860         }
2861
2862         mutex_unlock(&sensor->mutex);
2863
2864         return smiapp_set_power(sd, 1);
2865 }
2866
2867 static int smiapp_close(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
2868 {
2869         return smiapp_set_power(sd, 0);
2870 }
2871
2872 static const struct v4l2_subdev_video_ops smiapp_video_ops = {
2873         .s_stream = smiapp_set_stream,
2874 };
2875
2876 static const struct v4l2_subdev_core_ops smiapp_core_ops = {
2877         .s_power = smiapp_set_power,
2878 };
2879
2880 static const struct v4l2_subdev_pad_ops smiapp_pad_ops = {
2881         .enum_mbus_code = smiapp_enum_mbus_code,
2882         .get_fmt = smiapp_get_format,
2883         .set_fmt = smiapp_set_format,
2884         .get_selection = smiapp_get_selection,
2885         .set_selection = smiapp_set_selection,
2886 };
2887
2888 static const struct v4l2_subdev_sensor_ops smiapp_sensor_ops = {
2889         .g_skip_frames = smiapp_get_skip_frames,
2890         .g_skip_top_lines = smiapp_get_skip_top_lines,
2891 };
2892
2893 static const struct v4l2_subdev_ops smiapp_ops = {
2894         .core = &smiapp_core_ops,
2895         .video = &smiapp_video_ops,
2896         .pad = &smiapp_pad_ops,
2897         .sensor = &smiapp_sensor_ops,
2898 };
2899
2900 static const struct media_entity_operations smiapp_entity_ops = {
2901         .link_validate = v4l2_subdev_link_validate,
2902 };
2903
2904 static const struct v4l2_subdev_internal_ops smiapp_internal_src_ops = {
2905         .registered = smiapp_registered,
2906         .open = smiapp_open,
2907         .close = smiapp_close,
2908 };
2909
2910 static const struct v4l2_subdev_internal_ops smiapp_internal_ops = {
2911         .open = smiapp_open,
2912         .close = smiapp_close,
2913 };
2914
2915 /* -----------------------------------------------------------------------------
2916  * I2C Driver
2917  */
2918
2919 #ifdef CONFIG_PM
2920
2921 static int smiapp_suspend(struct device *dev)
2922 {
2923         struct i2c_client *client = to_i2c_client(dev);
2924         struct v4l2_subdev *subdev = i2c_get_clientdata(client);
2925         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2926         bool streaming;
2927
2928         BUG_ON(mutex_is_locked(&sensor->mutex));
2929
2930         if (sensor->power_count == 0)
2931                 return 0;
2932
2933         if (sensor->streaming)
2934                 smiapp_stop_streaming(sensor);
2935
2936         streaming = sensor->streaming;
2937
2938         smiapp_power_off(sensor);
2939
2940         /* save state for resume */
2941         sensor->streaming = streaming;
2942
2943         return 0;
2944 }
2945
2946 static int smiapp_resume(struct device *dev)
2947 {
2948         struct i2c_client *client = to_i2c_client(dev);
2949         struct v4l2_subdev *subdev = i2c_get_clientdata(client);
2950         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
2951         int rval;
2952
2953         if (sensor->power_count == 0)
2954                 return 0;
2955
2956         rval = smiapp_power_on(sensor);
2957         if (rval)
2958                 return rval;
2959
2960         if (sensor->streaming)
2961                 rval = smiapp_start_streaming(sensor);
2962
2963         return rval;
2964 }
2965
2966 #else
2967
2968 #define smiapp_suspend  NULL
2969 #define smiapp_resume   NULL
2970
2971 #endif /* CONFIG_PM */
2972
2973 static struct smiapp_hwconfig *smiapp_get_hwconfig(struct device *dev)
2974 {
2975         struct smiapp_hwconfig *hwcfg;
2976         struct v4l2_of_endpoint *bus_cfg;
2977         struct device_node *ep;
2978         int i;
2979         int rval;
2980
2981         if (!dev->of_node)
2982                 return dev->platform_data;
2983
2984         ep = of_graph_get_next_endpoint(dev->of_node, NULL);
2985         if (!ep)
2986                 return NULL;
2987
2988         bus_cfg = v4l2_of_alloc_parse_endpoint(ep);
2989         if (IS_ERR(bus_cfg))
2990                 goto out_err;
2991
2992         hwcfg = devm_kzalloc(dev, sizeof(*hwcfg), GFP_KERNEL);
2993         if (!hwcfg)
2994                 goto out_err;
2995
2996         switch (bus_cfg->bus_type) {
2997         case V4L2_MBUS_CSI2:
2998                 hwcfg->csi_signalling_mode = SMIAPP_CSI_SIGNALLING_MODE_CSI2;
2999                 break;
3000                 /* FIXME: add CCP2 support. */
3001         default:
3002                 goto out_err;
3003         }
3004
3005         hwcfg->lanes = bus_cfg->bus.mipi_csi2.num_data_lanes;
3006         dev_dbg(dev, "lanes %u\n", hwcfg->lanes);
3007
3008         /* NVM size is not mandatory */
3009         of_property_read_u32(dev->of_node, "nokia,nvm-size",
3010                                     &hwcfg->nvm_size);
3011
3012         rval = of_property_read_u32(dev->of_node, "clock-frequency",
3013                                     &hwcfg->ext_clk);
3014         if (rval) {
3015                 dev_warn(dev, "can't get clock-frequency\n");
3016                 goto out_err;
3017         }
3018
3019         dev_dbg(dev, "nvm %d, clk %d, csi %d\n", hwcfg->nvm_size,
3020                 hwcfg->ext_clk, hwcfg->csi_signalling_mode);
3021
3022         if (!bus_cfg->nr_of_link_frequencies) {
3023                 dev_warn(dev, "no link frequencies defined\n");
3024                 goto out_err;
3025         }
3026
3027         hwcfg->op_sys_clock = devm_kcalloc(
3028                 dev, bus_cfg->nr_of_link_frequencies + 1 /* guardian */,
3029                 sizeof(*hwcfg->op_sys_clock), GFP_KERNEL);
3030         if (!hwcfg->op_sys_clock)
3031                 goto out_err;
3032
3033         for (i = 0; i < bus_cfg->nr_of_link_frequencies; i++) {
3034                 hwcfg->op_sys_clock[i] = bus_cfg->link_frequencies[i];
3035                 dev_dbg(dev, "freq %d: %lld\n", i, hwcfg->op_sys_clock[i]);
3036         }
3037
3038         v4l2_of_free_endpoint(bus_cfg);
3039         of_node_put(ep);
3040         return hwcfg;
3041
3042 out_err:
3043         v4l2_of_free_endpoint(bus_cfg);
3044         of_node_put(ep);
3045         return NULL;
3046 }
3047
3048 static int smiapp_probe(struct i2c_client *client,
3049                         const struct i2c_device_id *devid)
3050 {
3051         struct smiapp_sensor *sensor;
3052         struct smiapp_hwconfig *hwcfg = smiapp_get_hwconfig(&client->dev);
3053         int rval;
3054
3055         if (hwcfg == NULL)
3056                 return -ENODEV;
3057
3058         sensor = devm_kzalloc(&client->dev, sizeof(*sensor), GFP_KERNEL);
3059         if (sensor == NULL)
3060                 return -ENOMEM;
3061
3062         sensor->hwcfg = hwcfg;
3063         mutex_init(&sensor->mutex);
3064         mutex_init(&sensor->power_mutex);
3065         sensor->src = &sensor->ssds[sensor->ssds_used];
3066
3067         v4l2_i2c_subdev_init(&sensor->src->sd, client, &smiapp_ops);
3068         sensor->src->sd.internal_ops = &smiapp_internal_src_ops;
3069         sensor->src->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
3070         sensor->src->sensor = sensor;
3071
3072         sensor->src->pads[0].flags = MEDIA_PAD_FL_SOURCE;
3073         rval = media_entity_pads_init(&sensor->src->sd.entity, 2,
3074                                  sensor->src->pads);
3075         if (rval < 0)
3076                 return rval;
3077
3078         if (client->dev.of_node) {
3079                 rval = smiapp_init(sensor);
3080                 if (rval)
3081                         goto out_media_entity_cleanup;
3082         }
3083
3084         rval = v4l2_async_register_subdev(&sensor->src->sd);
3085         if (rval < 0)
3086                 goto out_media_entity_cleanup;
3087
3088         return 0;
3089
3090 out_media_entity_cleanup:
3091         media_entity_cleanup(&sensor->src->sd.entity);
3092
3093         return rval;
3094 }
3095
3096 static int smiapp_remove(struct i2c_client *client)
3097 {
3098         struct v4l2_subdev *subdev = i2c_get_clientdata(client);
3099         struct smiapp_sensor *sensor = to_smiapp_sensor(subdev);
3100         unsigned int i;
3101
3102         v4l2_async_unregister_subdev(subdev);
3103
3104         if (sensor->power_count) {
3105                 gpiod_set_value(sensor->xshutdown, 0);
3106                 clk_disable_unprepare(sensor->ext_clk);
3107                 sensor->power_count = 0;
3108         }
3109
3110         for (i = 0; i < sensor->ssds_used; i++) {
3111                 v4l2_device_unregister_subdev(&sensor->ssds[i].sd);
3112                 media_entity_cleanup(&sensor->ssds[i].sd.entity);
3113         }
3114         smiapp_cleanup(sensor);
3115
3116         return 0;
3117 }
3118
3119 static const struct of_device_id smiapp_of_table[] = {
3120         { .compatible = "nokia,smia" },
3121         { },
3122 };
3123 MODULE_DEVICE_TABLE(of, smiapp_of_table);
3124
3125 static const struct i2c_device_id smiapp_id_table[] = {
3126         { SMIAPP_NAME, 0 },
3127         { },
3128 };
3129 MODULE_DEVICE_TABLE(i2c, smiapp_id_table);
3130
3131 static const struct dev_pm_ops smiapp_pm_ops = {
3132         .suspend        = smiapp_suspend,
3133         .resume         = smiapp_resume,
3134 };
3135
3136 static struct i2c_driver smiapp_i2c_driver = {
3137         .driver = {
3138                 .of_match_table = smiapp_of_table,
3139                 .name = SMIAPP_NAME,
3140                 .pm = &smiapp_pm_ops,
3141         },
3142         .probe  = smiapp_probe,
3143         .remove = smiapp_remove,
3144         .id_table = smiapp_id_table,
3145 };
3146
3147 module_i2c_driver(smiapp_i2c_driver);
3148
3149 MODULE_AUTHOR("Sakari Ailus <sakari.ailus@iki.fi>");
3150 MODULE_DESCRIPTION("Generic SMIA/SMIA++ camera module driver");
3151 MODULE_LICENSE("GPL");