media: i2c: imx219: Replace register addresses with macros
[platform/kernel/linux-starfive.git] / drivers / media / i2c / imx219.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * A V4L2 driver for Sony IMX219 cameras.
4  * Copyright (C) 2019, Raspberry Pi (Trading) Ltd
5  *
6  * Based on Sony imx258 camera driver
7  * Copyright (C) 2018 Intel Corporation
8  *
9  * DT / fwnode changes, and regulator / GPIO control taken from imx214 driver
10  * Copyright 2018 Qtechnology A/S
11  *
12  * Flip handling taken from the Sony IMX319 driver.
13  * Copyright (C) 2018 Intel Corporation
14  *
15  */
16
17 #include <linux/clk.h>
18 #include <linux/delay.h>
19 #include <linux/gpio/consumer.h>
20 #include <linux/i2c.h>
21 #include <linux/module.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/regulator/consumer.h>
24
25 #include <media/v4l2-cci.h>
26 #include <media/v4l2-ctrls.h>
27 #include <media/v4l2-device.h>
28 #include <media/v4l2-event.h>
29 #include <media/v4l2-fwnode.h>
30 #include <media/v4l2-mediabus.h>
31
32 /* Chip ID */
33 #define IMX219_REG_CHIP_ID              CCI_REG16(0x0000)
34 #define IMX219_CHIP_ID                  0x0219
35
36 #define IMX219_REG_MODE_SELECT          CCI_REG8(0x0100)
37 #define IMX219_MODE_STANDBY             0x00
38 #define IMX219_MODE_STREAMING           0x01
39
40 #define IMX219_REG_CSI_LANE_MODE        CCI_REG8(0x0114)
41 #define IMX219_CSI_2_LANE_MODE          0x01
42 #define IMX219_CSI_4_LANE_MODE          0x03
43
44 #define IMX219_REG_DPHY_CTRL            CCI_REG8(0x0128)
45 #define IMX219_DPHY_CTRL_TIMING_AUTO    0
46 #define IMX219_DPHY_CTRL_TIMING_MANUAL  1
47
48 #define IMX219_REG_EXCK_FREQ            CCI_REG16(0x012a)
49 #define IMX219_EXCK_FREQ(n)             ((n) * 256)             /* n expressed in MHz */
50
51 /* Analog gain control */
52 #define IMX219_REG_ANALOG_GAIN          CCI_REG8(0x0157)
53 #define IMX219_ANA_GAIN_MIN             0
54 #define IMX219_ANA_GAIN_MAX             232
55 #define IMX219_ANA_GAIN_STEP            1
56 #define IMX219_ANA_GAIN_DEFAULT         0x0
57
58 /* Digital gain control */
59 #define IMX219_REG_DIGITAL_GAIN         CCI_REG16(0x0158)
60 #define IMX219_DGTL_GAIN_MIN            0x0100
61 #define IMX219_DGTL_GAIN_MAX            0x0fff
62 #define IMX219_DGTL_GAIN_DEFAULT        0x0100
63 #define IMX219_DGTL_GAIN_STEP           1
64
65 /* Exposure control */
66 #define IMX219_REG_EXPOSURE             CCI_REG16(0x015a)
67 #define IMX219_EXPOSURE_MIN             4
68 #define IMX219_EXPOSURE_STEP            1
69 #define IMX219_EXPOSURE_DEFAULT         0x640
70 #define IMX219_EXPOSURE_MAX             65535
71
72 /* V_TIMING internal */
73 #define IMX219_REG_VTS                  CCI_REG16(0x0160)
74 #define IMX219_VTS_15FPS                0x0dc6
75 #define IMX219_VTS_30FPS_1080P          0x06e3
76 #define IMX219_VTS_30FPS_BINNED         0x06e3
77 #define IMX219_VTS_30FPS_640x480        0x06e3
78 #define IMX219_VTS_MAX                  0xffff
79
80 #define IMX219_VBLANK_MIN               4
81
82 /*Frame Length Line*/
83 #define IMX219_FLL_MIN                  0x08a6
84 #define IMX219_FLL_MAX                  0xffff
85 #define IMX219_FLL_STEP                 1
86 #define IMX219_FLL_DEFAULT              0x0c98
87
88 /* HBLANK control - read only */
89 #define IMX219_PPL_DEFAULT              3448
90
91 #define IMX219_REG_LINE_LENGTH_A        CCI_REG16(0x0162)
92 #define IMX219_REG_X_ADD_STA_A          CCI_REG16(0x0164)
93 #define IMX219_REG_X_ADD_END_A          CCI_REG16(0x0166)
94 #define IMX219_REG_Y_ADD_STA_A          CCI_REG16(0x0168)
95 #define IMX219_REG_Y_ADD_END_A          CCI_REG16(0x016a)
96 #define IMX219_REG_X_OUTPUT_SIZE        CCI_REG16(0x016c)
97 #define IMX219_REG_Y_OUTPUT_SIZE        CCI_REG16(0x016e)
98 #define IMX219_REG_X_ODD_INC_A          CCI_REG8(0x0170)
99 #define IMX219_REG_Y_ODD_INC_A          CCI_REG8(0x0171)
100 #define IMX219_REG_ORIENTATION          CCI_REG8(0x0172)
101
102 /* Binning  Mode */
103 #define IMX219_REG_BINNING_MODE         CCI_REG16(0x0174)
104 #define IMX219_BINNING_NONE             0x0000
105 #define IMX219_BINNING_2X2              0x0101
106 #define IMX219_BINNING_2X2_ANALOG       0x0303
107
108 #define IMX219_REG_CSI_DATA_FORMAT_A    CCI_REG16(0x018c)
109
110 /* PLL Settings */
111 #define IMX219_REG_VTPXCK_DIV           CCI_REG8(0x0301)
112 #define IMX219_REG_VTSYCK_DIV           CCI_REG8(0x0303)
113 #define IMX219_REG_PREPLLCK_VT_DIV      CCI_REG8(0x0304)
114 #define IMX219_REG_PREPLLCK_OP_DIV      CCI_REG8(0x0305)
115 #define IMX219_REG_PLL_VT_MPY           CCI_REG16(0x0306)
116 #define IMX219_REG_OPPXCK_DIV           CCI_REG8(0x0309)
117 #define IMX219_REG_OPSYCK_DIV           CCI_REG8(0x030b)
118 #define IMX219_REG_PLL_OP_MPY           CCI_REG16(0x030c)
119
120 /* Test Pattern Control */
121 #define IMX219_REG_TEST_PATTERN         CCI_REG16(0x0600)
122 #define IMX219_TEST_PATTERN_DISABLE     0
123 #define IMX219_TEST_PATTERN_SOLID_COLOR 1
124 #define IMX219_TEST_PATTERN_COLOR_BARS  2
125 #define IMX219_TEST_PATTERN_GREY_COLOR  3
126 #define IMX219_TEST_PATTERN_PN9         4
127
128 /* Test pattern colour components */
129 #define IMX219_REG_TESTP_RED            CCI_REG16(0x0602)
130 #define IMX219_REG_TESTP_GREENR         CCI_REG16(0x0604)
131 #define IMX219_REG_TESTP_BLUE           CCI_REG16(0x0606)
132 #define IMX219_REG_TESTP_GREENB         CCI_REG16(0x0608)
133 #define IMX219_TESTP_COLOUR_MIN         0
134 #define IMX219_TESTP_COLOUR_MAX         0x03ff
135 #define IMX219_TESTP_COLOUR_STEP        1
136 #define IMX219_TESTP_RED_DEFAULT        IMX219_TESTP_COLOUR_MAX
137 #define IMX219_TESTP_GREENR_DEFAULT     0
138 #define IMX219_TESTP_BLUE_DEFAULT       0
139 #define IMX219_TESTP_GREENB_DEFAULT     0
140
141 #define IMX219_REG_TP_WINDOW_WIDTH      CCI_REG16(0x0624)
142 #define IMX219_REG_TP_WINDOW_HEIGHT     CCI_REG16(0x0626)
143
144 /* External clock frequency is 24.0M */
145 #define IMX219_XCLK_FREQ                24000000
146
147 /* Pixel rate is fixed for all the modes */
148 #define IMX219_PIXEL_RATE               182400000
149 #define IMX219_PIXEL_RATE_4LANE         280800000
150
151 #define IMX219_DEFAULT_LINK_FREQ        456000000
152 #define IMX219_DEFAULT_LINK_FREQ_4LANE  363000000
153
154 /* IMX219 native and active pixel array size. */
155 #define IMX219_NATIVE_WIDTH             3296U
156 #define IMX219_NATIVE_HEIGHT            2480U
157 #define IMX219_PIXEL_ARRAY_LEFT         8U
158 #define IMX219_PIXEL_ARRAY_TOP          8U
159 #define IMX219_PIXEL_ARRAY_WIDTH        3280U
160 #define IMX219_PIXEL_ARRAY_HEIGHT       2464U
161
162 struct imx219_reg_list {
163         unsigned int num_of_regs;
164         const struct cci_reg_sequence *regs;
165 };
166
167 /* Mode : resolution and related config&values */
168 struct imx219_mode {
169         /* Frame width */
170         unsigned int width;
171         /* Frame height */
172         unsigned int height;
173
174         /* Analog crop rectangle. */
175         struct v4l2_rect crop;
176
177         /* V-timing */
178         unsigned int vts_def;
179
180         /* Default register values */
181         struct imx219_reg_list reg_list;
182
183         /* 2x2 binning is used */
184         bool binning;
185 };
186
187 static const struct cci_reg_sequence imx219_common_regs[] = {
188         { IMX219_REG_MODE_SELECT, 0x00 },       /* Mode Select */
189
190         /* To Access Addresses 3000-5fff, send the following commands */
191         { CCI_REG8(0x30eb), 0x0c },
192         { CCI_REG8(0x30eb), 0x05 },
193         { CCI_REG8(0x300a), 0xff },
194         { CCI_REG8(0x300b), 0xff },
195         { CCI_REG8(0x30eb), 0x05 },
196         { CCI_REG8(0x30eb), 0x09 },
197
198         /* PLL Clock Table */
199         { IMX219_REG_VTPXCK_DIV, 5 },
200         { IMX219_REG_VTSYCK_DIV, 1 },
201         { IMX219_REG_PREPLLCK_VT_DIV, 3 },      /* 0x03 = AUTO set */
202         { IMX219_REG_PREPLLCK_OP_DIV, 3 },      /* 0x03 = AUTO set */
203         { IMX219_REG_PLL_VT_MPY, 57 },
204         { IMX219_REG_OPSYCK_DIV, 1 },
205         { IMX219_REG_PLL_OP_MPY, 114 },
206
207         /* Undocumented registers */
208         { CCI_REG8(0x455e), 0x00 },
209         { CCI_REG8(0x471e), 0x4b },
210         { CCI_REG8(0x4767), 0x0f },
211         { CCI_REG8(0x4750), 0x14 },
212         { CCI_REG8(0x4540), 0x00 },
213         { CCI_REG8(0x47b4), 0x14 },
214         { CCI_REG8(0x4713), 0x30 },
215         { CCI_REG8(0x478b), 0x10 },
216         { CCI_REG8(0x478f), 0x10 },
217         { CCI_REG8(0x4793), 0x10 },
218         { CCI_REG8(0x4797), 0x0e },
219         { CCI_REG8(0x479b), 0x0e },
220
221         /* Frame Bank Register Group "A" */
222         { IMX219_REG_LINE_LENGTH_A, 3448 },
223         { IMX219_REG_X_ODD_INC_A, 1 },
224         { IMX219_REG_Y_ODD_INC_A, 1 },
225
226         /* Output setup registers */
227         { IMX219_REG_CSI_LANE_MODE, IMX219_CSI_2_LANE_MODE },
228         { IMX219_REG_DPHY_CTRL, IMX219_DPHY_CTRL_TIMING_AUTO },
229         { IMX219_REG_EXCK_FREQ, IMX219_EXCK_FREQ(IMX219_XCLK_FREQ / 1000000) },
230 };
231
232 /*
233  * Register sets lifted off the i2C interface from the Raspberry Pi firmware
234  * driver.
235  * 3280x2464 = mode 2, 1920x1080 = mode 1, 1640x1232 = mode 4, 640x480 = mode 7.
236  */
237 static const struct cci_reg_sequence mode_3280x2464_regs[] = {
238         { IMX219_REG_X_ADD_STA_A, 0 },
239         { IMX219_REG_X_ADD_END_A, 3279 },
240         { IMX219_REG_Y_ADD_STA_A, 0 },
241         { IMX219_REG_Y_ADD_END_A, 2463 },
242         { IMX219_REG_X_OUTPUT_SIZE, 3280 },
243         { IMX219_REG_Y_OUTPUT_SIZE, 2464 },
244         { IMX219_REG_TP_WINDOW_WIDTH, 3280 },
245         { IMX219_REG_TP_WINDOW_HEIGHT, 2464 },
246 };
247
248 static const struct cci_reg_sequence mode_1920_1080_regs[] = {
249         { IMX219_REG_X_ADD_STA_A, 680 },
250         { IMX219_REG_X_ADD_END_A, 2599 },
251         { IMX219_REG_Y_ADD_STA_A, 692 },
252         { IMX219_REG_Y_ADD_END_A, 1771 },
253         { IMX219_REG_X_OUTPUT_SIZE, 1920 },
254         { IMX219_REG_Y_OUTPUT_SIZE, 1080 },
255         { IMX219_REG_TP_WINDOW_WIDTH, 1920 },
256         { IMX219_REG_TP_WINDOW_HEIGHT, 1080 },
257 };
258
259 static const struct cci_reg_sequence mode_1640_1232_regs[] = {
260         { IMX219_REG_X_ADD_STA_A, 0 },
261         { IMX219_REG_X_ADD_END_A, 3279 },
262         { IMX219_REG_Y_ADD_STA_A, 0 },
263         { IMX219_REG_Y_ADD_END_A, 2463 },
264         { IMX219_REG_X_OUTPUT_SIZE, 1640 },
265         { IMX219_REG_Y_OUTPUT_SIZE, 1232 },
266         { IMX219_REG_TP_WINDOW_WIDTH, 1640 },
267         { IMX219_REG_TP_WINDOW_HEIGHT, 1232 },
268 };
269
270 static const struct cci_reg_sequence mode_640_480_regs[] = {
271         { IMX219_REG_X_ADD_STA_A, 1000 },
272         { IMX219_REG_X_ADD_END_A, 2279 },
273         { IMX219_REG_Y_ADD_STA_A, 752 },
274         { IMX219_REG_Y_ADD_END_A, 1711 },
275         { IMX219_REG_X_OUTPUT_SIZE, 640 },
276         { IMX219_REG_Y_OUTPUT_SIZE, 480 },
277         { IMX219_REG_TP_WINDOW_WIDTH, 1640 },
278         { IMX219_REG_TP_WINDOW_HEIGHT, 1232 },
279 };
280
281 static const struct cci_reg_sequence raw8_framefmt_regs[] = {
282         { IMX219_REG_CSI_DATA_FORMAT_A, 0x0808 },
283         { IMX219_REG_OPPXCK_DIV, 8 },
284 };
285
286 static const struct cci_reg_sequence raw10_framefmt_regs[] = {
287         { IMX219_REG_CSI_DATA_FORMAT_A, 0x0a0a },
288         { IMX219_REG_OPPXCK_DIV, 10 },
289 };
290
291 static const s64 imx219_link_freq_menu[] = {
292         IMX219_DEFAULT_LINK_FREQ,
293 };
294
295 static const s64 imx219_link_freq_4lane_menu[] = {
296         IMX219_DEFAULT_LINK_FREQ_4LANE,
297 };
298
299 static const char * const imx219_test_pattern_menu[] = {
300         "Disabled",
301         "Color Bars",
302         "Solid Color",
303         "Grey Color Bars",
304         "PN9"
305 };
306
307 static const int imx219_test_pattern_val[] = {
308         IMX219_TEST_PATTERN_DISABLE,
309         IMX219_TEST_PATTERN_COLOR_BARS,
310         IMX219_TEST_PATTERN_SOLID_COLOR,
311         IMX219_TEST_PATTERN_GREY_COLOR,
312         IMX219_TEST_PATTERN_PN9,
313 };
314
315 /* regulator supplies */
316 static const char * const imx219_supply_name[] = {
317         /* Supplies can be enabled in any order */
318         "VANA",  /* Analog (2.8V) supply */
319         "VDIG",  /* Digital Core (1.8V) supply */
320         "VDDL",  /* IF (1.2V) supply */
321 };
322
323 #define IMX219_NUM_SUPPLIES ARRAY_SIZE(imx219_supply_name)
324
325 /*
326  * The supported formats.
327  * This table MUST contain 4 entries per format, to cover the various flip
328  * combinations in the order
329  * - no flip
330  * - h flip
331  * - v flip
332  * - h&v flips
333  */
334 static const u32 imx219_mbus_formats[] = {
335         MEDIA_BUS_FMT_SRGGB10_1X10,
336         MEDIA_BUS_FMT_SGRBG10_1X10,
337         MEDIA_BUS_FMT_SGBRG10_1X10,
338         MEDIA_BUS_FMT_SBGGR10_1X10,
339
340         MEDIA_BUS_FMT_SRGGB8_1X8,
341         MEDIA_BUS_FMT_SGRBG8_1X8,
342         MEDIA_BUS_FMT_SGBRG8_1X8,
343         MEDIA_BUS_FMT_SBGGR8_1X8,
344 };
345
346 /*
347  * Initialisation delay between XCLR low->high and the moment when the sensor
348  * can start capture (i.e. can leave software stanby) must be not less than:
349  *   t4 + max(t5, t6 + <time to initialize the sensor register over I2C>)
350  * where
351  *   t4 is fixed, and is max 200uS,
352  *   t5 is fixed, and is 6000uS,
353  *   t6 depends on the sensor external clock, and is max 32000 clock periods.
354  * As per sensor datasheet, the external clock must be from 6MHz to 27MHz.
355  * So for any acceptable external clock t6 is always within the range of
356  * 1185 to 5333 uS, and is always less than t5.
357  * For this reason this is always safe to wait (t4 + t5) = 6200 uS, then
358  * initialize the sensor over I2C, and then exit the software standby.
359  *
360  * This start-up time can be optimized a bit more, if we start the writes
361  * over I2C after (t4+t6), but before (t4+t5) expires. But then sensor
362  * initialization over I2C may complete before (t4+t5) expires, and we must
363  * ensure that capture is not started before (t4+t5).
364  *
365  * This delay doesn't account for the power supply startup time. If needed,
366  * this should be taken care of via the regulator framework. E.g. in the
367  * case of DT for regulator-fixed one should define the startup-delay-us
368  * property.
369  */
370 #define IMX219_XCLR_MIN_DELAY_US        6200
371 #define IMX219_XCLR_DELAY_RANGE_US      1000
372
373 /* Mode configs */
374 static const struct imx219_mode supported_modes[] = {
375         {
376                 /* 8MPix 15fps mode */
377                 .width = 3280,
378                 .height = 2464,
379                 .crop = {
380                         .left = IMX219_PIXEL_ARRAY_LEFT,
381                         .top = IMX219_PIXEL_ARRAY_TOP,
382                         .width = 3280,
383                         .height = 2464
384                 },
385                 .vts_def = IMX219_VTS_15FPS,
386                 .reg_list = {
387                         .num_of_regs = ARRAY_SIZE(mode_3280x2464_regs),
388                         .regs = mode_3280x2464_regs,
389                 },
390                 .binning = false,
391         },
392         {
393                 /* 1080P 30fps cropped */
394                 .width = 1920,
395                 .height = 1080,
396                 .crop = {
397                         .left = 688,
398                         .top = 700,
399                         .width = 1920,
400                         .height = 1080
401                 },
402                 .vts_def = IMX219_VTS_30FPS_1080P,
403                 .reg_list = {
404                         .num_of_regs = ARRAY_SIZE(mode_1920_1080_regs),
405                         .regs = mode_1920_1080_regs,
406                 },
407                 .binning = false,
408         },
409         {
410                 /* 2x2 binned 30fps mode */
411                 .width = 1640,
412                 .height = 1232,
413                 .crop = {
414                         .left = IMX219_PIXEL_ARRAY_LEFT,
415                         .top = IMX219_PIXEL_ARRAY_TOP,
416                         .width = 3280,
417                         .height = 2464
418                 },
419                 .vts_def = IMX219_VTS_30FPS_BINNED,
420                 .reg_list = {
421                         .num_of_regs = ARRAY_SIZE(mode_1640_1232_regs),
422                         .regs = mode_1640_1232_regs,
423                 },
424                 .binning = true,
425         },
426         {
427                 /* 640x480 30fps mode */
428                 .width = 640,
429                 .height = 480,
430                 .crop = {
431                         .left = 1008,
432                         .top = 760,
433                         .width = 1280,
434                         .height = 960
435                 },
436                 .vts_def = IMX219_VTS_30FPS_640x480,
437                 .reg_list = {
438                         .num_of_regs = ARRAY_SIZE(mode_640_480_regs),
439                         .regs = mode_640_480_regs,
440                 },
441                 .binning = true,
442         },
443 };
444
445 struct imx219 {
446         struct v4l2_subdev sd;
447         struct media_pad pad;
448
449         struct regmap *regmap;
450         struct clk *xclk; /* system clock to IMX219 */
451         u32 xclk_freq;
452
453         struct gpio_desc *reset_gpio;
454         struct regulator_bulk_data supplies[IMX219_NUM_SUPPLIES];
455
456         struct v4l2_ctrl_handler ctrl_handler;
457         /* V4L2 Controls */
458         struct v4l2_ctrl *pixel_rate;
459         struct v4l2_ctrl *link_freq;
460         struct v4l2_ctrl *exposure;
461         struct v4l2_ctrl *vflip;
462         struct v4l2_ctrl *hflip;
463         struct v4l2_ctrl *vblank;
464         struct v4l2_ctrl *hblank;
465
466         /* Current mode */
467         const struct imx219_mode *mode;
468
469         /* Streaming on/off */
470         bool streaming;
471
472         /* Two or Four lanes */
473         u8 lanes;
474 };
475
476 static inline struct imx219 *to_imx219(struct v4l2_subdev *_sd)
477 {
478         return container_of(_sd, struct imx219, sd);
479 }
480
481 /* Get bayer order based on flip setting. */
482 static u32 imx219_get_format_code(struct imx219 *imx219, u32 code)
483 {
484         unsigned int i;
485
486         for (i = 0; i < ARRAY_SIZE(imx219_mbus_formats); i++)
487                 if (imx219_mbus_formats[i] == code)
488                         break;
489
490         if (i >= ARRAY_SIZE(imx219_mbus_formats))
491                 i = 0;
492
493         i = (i & ~3) | (imx219->vflip->val ? 2 : 0) |
494             (imx219->hflip->val ? 1 : 0);
495
496         return imx219_mbus_formats[i];
497 }
498
499 static int imx219_set_ctrl(struct v4l2_ctrl *ctrl)
500 {
501         struct imx219 *imx219 =
502                 container_of(ctrl->handler, struct imx219, ctrl_handler);
503         struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
504         int ret = 0;
505
506         if (ctrl->id == V4L2_CID_VBLANK) {
507                 int exposure_max, exposure_def;
508
509                 /* Update max exposure while meeting expected vblanking */
510                 exposure_max = imx219->mode->height + ctrl->val - 4;
511                 exposure_def = (exposure_max < IMX219_EXPOSURE_DEFAULT) ?
512                         exposure_max : IMX219_EXPOSURE_DEFAULT;
513                 __v4l2_ctrl_modify_range(imx219->exposure,
514                                          imx219->exposure->minimum,
515                                          exposure_max, imx219->exposure->step,
516                                          exposure_def);
517         }
518
519         /*
520          * Applying V4L2 control value only happens
521          * when power is up for streaming
522          */
523         if (pm_runtime_get_if_in_use(&client->dev) == 0)
524                 return 0;
525
526         switch (ctrl->id) {
527         case V4L2_CID_ANALOGUE_GAIN:
528                 cci_write(imx219->regmap, IMX219_REG_ANALOG_GAIN,
529                           ctrl->val, &ret);
530                 break;
531         case V4L2_CID_EXPOSURE:
532                 cci_write(imx219->regmap, IMX219_REG_EXPOSURE,
533                           ctrl->val, &ret);
534                 break;
535         case V4L2_CID_DIGITAL_GAIN:
536                 cci_write(imx219->regmap, IMX219_REG_DIGITAL_GAIN,
537                           ctrl->val, &ret);
538                 break;
539         case V4L2_CID_TEST_PATTERN:
540                 cci_write(imx219->regmap, IMX219_REG_TEST_PATTERN,
541                           imx219_test_pattern_val[ctrl->val], &ret);
542                 break;
543         case V4L2_CID_HFLIP:
544         case V4L2_CID_VFLIP:
545                 cci_write(imx219->regmap, IMX219_REG_ORIENTATION,
546                           imx219->hflip->val | imx219->vflip->val << 1, &ret);
547                 break;
548         case V4L2_CID_VBLANK:
549                 cci_write(imx219->regmap, IMX219_REG_VTS,
550                           imx219->mode->height + ctrl->val, &ret);
551                 break;
552         case V4L2_CID_TEST_PATTERN_RED:
553                 cci_write(imx219->regmap, IMX219_REG_TESTP_RED,
554                           ctrl->val, &ret);
555                 break;
556         case V4L2_CID_TEST_PATTERN_GREENR:
557                 cci_write(imx219->regmap, IMX219_REG_TESTP_GREENR,
558                           ctrl->val, &ret);
559                 break;
560         case V4L2_CID_TEST_PATTERN_BLUE:
561                 cci_write(imx219->regmap, IMX219_REG_TESTP_BLUE,
562                           ctrl->val, &ret);
563                 break;
564         case V4L2_CID_TEST_PATTERN_GREENB:
565                 cci_write(imx219->regmap, IMX219_REG_TESTP_GREENB,
566                           ctrl->val, &ret);
567                 break;
568         default:
569                 dev_info(&client->dev,
570                          "ctrl(id:0x%x,val:0x%x) is not handled\n",
571                          ctrl->id, ctrl->val);
572                 ret = -EINVAL;
573                 break;
574         }
575
576         pm_runtime_put(&client->dev);
577
578         return ret;
579 }
580
581 static const struct v4l2_ctrl_ops imx219_ctrl_ops = {
582         .s_ctrl = imx219_set_ctrl,
583 };
584
585 static void imx219_update_pad_format(struct imx219 *imx219,
586                                      const struct imx219_mode *mode,
587                                      struct v4l2_mbus_framefmt *fmt, u32 code)
588 {
589         /* Bayer order varies with flips */
590         fmt->code = imx219_get_format_code(imx219, code);
591         fmt->width = mode->width;
592         fmt->height = mode->height;
593         fmt->field = V4L2_FIELD_NONE;
594         fmt->colorspace = V4L2_COLORSPACE_RAW;
595         fmt->quantization = V4L2_QUANTIZATION_FULL_RANGE;
596         fmt->xfer_func = V4L2_XFER_FUNC_NONE;
597 }
598
599 static int imx219_init_cfg(struct v4l2_subdev *sd,
600                            struct v4l2_subdev_state *state)
601 {
602         struct imx219 *imx219 = to_imx219(sd);
603         struct v4l2_mbus_framefmt *format;
604         struct v4l2_rect *crop;
605
606         /* Initialize the format. */
607         format = v4l2_subdev_get_pad_format(sd, state, 0);
608         imx219_update_pad_format(imx219, &supported_modes[0], format,
609                                  MEDIA_BUS_FMT_SRGGB10_1X10);
610
611         /* Initialize the crop rectangle. */
612         crop = v4l2_subdev_get_pad_crop(sd, state, 0);
613         crop->top = IMX219_PIXEL_ARRAY_TOP;
614         crop->left = IMX219_PIXEL_ARRAY_LEFT;
615         crop->width = IMX219_PIXEL_ARRAY_WIDTH;
616         crop->height = IMX219_PIXEL_ARRAY_HEIGHT;
617
618         return 0;
619 }
620
621 static int imx219_enum_mbus_code(struct v4l2_subdev *sd,
622                                  struct v4l2_subdev_state *sd_state,
623                                  struct v4l2_subdev_mbus_code_enum *code)
624 {
625         struct imx219 *imx219 = to_imx219(sd);
626
627         if (code->index >= (ARRAY_SIZE(imx219_mbus_formats) / 4))
628                 return -EINVAL;
629
630         code->code = imx219_get_format_code(imx219, imx219_mbus_formats[code->index * 4]);
631
632         return 0;
633 }
634
635 static int imx219_enum_frame_size(struct v4l2_subdev *sd,
636                                   struct v4l2_subdev_state *sd_state,
637                                   struct v4l2_subdev_frame_size_enum *fse)
638 {
639         struct imx219 *imx219 = to_imx219(sd);
640         u32 code;
641
642         if (fse->index >= ARRAY_SIZE(supported_modes))
643                 return -EINVAL;
644
645         code = imx219_get_format_code(imx219, fse->code);
646         if (fse->code != code)
647                 return -EINVAL;
648
649         fse->min_width = supported_modes[fse->index].width;
650         fse->max_width = fse->min_width;
651         fse->min_height = supported_modes[fse->index].height;
652         fse->max_height = fse->min_height;
653
654         return 0;
655 }
656
657 static int imx219_set_pad_format(struct v4l2_subdev *sd,
658                                  struct v4l2_subdev_state *sd_state,
659                                  struct v4l2_subdev_format *fmt)
660 {
661         struct imx219 *imx219 = to_imx219(sd);
662         const struct imx219_mode *mode;
663         int exposure_max, exposure_def, hblank;
664         struct v4l2_mbus_framefmt *format;
665         struct v4l2_rect *crop;
666
667         mode = v4l2_find_nearest_size(supported_modes,
668                                       ARRAY_SIZE(supported_modes),
669                                       width, height,
670                                       fmt->format.width, fmt->format.height);
671
672         imx219_update_pad_format(imx219, mode, &fmt->format, fmt->format.code);
673
674         format = v4l2_subdev_get_pad_format(sd, sd_state, 0);
675         crop = v4l2_subdev_get_pad_crop(sd, sd_state, 0);
676
677         *format = fmt->format;
678         *crop = mode->crop;
679
680         if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) {
681                 imx219->mode = mode;
682                 /* Update limits and set FPS to default */
683                 __v4l2_ctrl_modify_range(imx219->vblank, IMX219_VBLANK_MIN,
684                                          IMX219_VTS_MAX - mode->height, 1,
685                                          mode->vts_def - mode->height);
686                 __v4l2_ctrl_s_ctrl(imx219->vblank,
687                                    mode->vts_def - mode->height);
688                 /* Update max exposure while meeting expected vblanking */
689                 exposure_max = mode->vts_def - 4;
690                 exposure_def = (exposure_max < IMX219_EXPOSURE_DEFAULT) ?
691                         exposure_max : IMX219_EXPOSURE_DEFAULT;
692                 __v4l2_ctrl_modify_range(imx219->exposure,
693                                          imx219->exposure->minimum,
694                                          exposure_max, imx219->exposure->step,
695                                          exposure_def);
696                 /*
697                  * Currently PPL is fixed to IMX219_PPL_DEFAULT, so hblank
698                  * depends on mode->width only, and is not changeble in any
699                  * way other than changing the mode.
700                  */
701                 hblank = IMX219_PPL_DEFAULT - mode->width;
702                 __v4l2_ctrl_modify_range(imx219->hblank, hblank, hblank, 1,
703                                          hblank);
704         }
705
706         return 0;
707 }
708
709 static int imx219_set_framefmt(struct imx219 *imx219,
710                                const struct v4l2_mbus_framefmt *format)
711 {
712         switch (format->code) {
713         case MEDIA_BUS_FMT_SRGGB8_1X8:
714         case MEDIA_BUS_FMT_SGRBG8_1X8:
715         case MEDIA_BUS_FMT_SGBRG8_1X8:
716         case MEDIA_BUS_FMT_SBGGR8_1X8:
717                 return cci_multi_reg_write(imx219->regmap, raw8_framefmt_regs,
718                                            ARRAY_SIZE(raw8_framefmt_regs), NULL);
719
720         case MEDIA_BUS_FMT_SRGGB10_1X10:
721         case MEDIA_BUS_FMT_SGRBG10_1X10:
722         case MEDIA_BUS_FMT_SGBRG10_1X10:
723         case MEDIA_BUS_FMT_SBGGR10_1X10:
724                 return cci_multi_reg_write(imx219->regmap, raw10_framefmt_regs,
725                                            ARRAY_SIZE(raw10_framefmt_regs), NULL);
726         }
727
728         return -EINVAL;
729 }
730
731 static int imx219_set_binning(struct imx219 *imx219,
732                               const struct v4l2_mbus_framefmt *format)
733 {
734         if (!imx219->mode->binning)
735                 return cci_write(imx219->regmap, IMX219_REG_BINNING_MODE,
736                                  IMX219_BINNING_NONE, NULL);
737
738         switch (format->code) {
739         case MEDIA_BUS_FMT_SRGGB8_1X8:
740         case MEDIA_BUS_FMT_SGRBG8_1X8:
741         case MEDIA_BUS_FMT_SGBRG8_1X8:
742         case MEDIA_BUS_FMT_SBGGR8_1X8:
743                 return cci_write(imx219->regmap, IMX219_REG_BINNING_MODE,
744                                  IMX219_BINNING_2X2_ANALOG, NULL);
745
746         case MEDIA_BUS_FMT_SRGGB10_1X10:
747         case MEDIA_BUS_FMT_SGRBG10_1X10:
748         case MEDIA_BUS_FMT_SGBRG10_1X10:
749         case MEDIA_BUS_FMT_SBGGR10_1X10:
750                 return cci_write(imx219->regmap, IMX219_REG_BINNING_MODE,
751                                  IMX219_BINNING_2X2, NULL);
752         }
753
754         return -EINVAL;
755 }
756
757 static int imx219_get_selection(struct v4l2_subdev *sd,
758                                 struct v4l2_subdev_state *sd_state,
759                                 struct v4l2_subdev_selection *sel)
760 {
761         switch (sel->target) {
762         case V4L2_SEL_TGT_CROP: {
763                 sel->r = *v4l2_subdev_get_pad_crop(sd, sd_state, 0);
764                 return 0;
765         }
766
767         case V4L2_SEL_TGT_NATIVE_SIZE:
768                 sel->r.top = 0;
769                 sel->r.left = 0;
770                 sel->r.width = IMX219_NATIVE_WIDTH;
771                 sel->r.height = IMX219_NATIVE_HEIGHT;
772
773                 return 0;
774
775         case V4L2_SEL_TGT_CROP_DEFAULT:
776         case V4L2_SEL_TGT_CROP_BOUNDS:
777                 sel->r.top = IMX219_PIXEL_ARRAY_TOP;
778                 sel->r.left = IMX219_PIXEL_ARRAY_LEFT;
779                 sel->r.width = IMX219_PIXEL_ARRAY_WIDTH;
780                 sel->r.height = IMX219_PIXEL_ARRAY_HEIGHT;
781
782                 return 0;
783         }
784
785         return -EINVAL;
786 }
787
788 static int imx219_configure_lanes(struct imx219 *imx219)
789 {
790         return cci_write(imx219->regmap, IMX219_REG_CSI_LANE_MODE,
791                          imx219->lanes == 2 ? IMX219_CSI_2_LANE_MODE :
792                          IMX219_CSI_4_LANE_MODE, NULL);
793 };
794
795 static int imx219_start_streaming(struct imx219 *imx219,
796                                   struct v4l2_subdev_state *state)
797 {
798         struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
799         const struct v4l2_mbus_framefmt *format;
800         const struct imx219_reg_list *reg_list;
801         int ret;
802
803         ret = pm_runtime_resume_and_get(&client->dev);
804         if (ret < 0)
805                 return ret;
806
807         /* Send all registers that are common to all modes */
808         ret = cci_multi_reg_write(imx219->regmap, imx219_common_regs,
809                                   ARRAY_SIZE(imx219_common_regs), NULL);
810         if (ret) {
811                 dev_err(&client->dev, "%s failed to send mfg header\n", __func__);
812                 goto err_rpm_put;
813         }
814
815         /* Configure two or four Lane mode */
816         ret = imx219_configure_lanes(imx219);
817         if (ret) {
818                 dev_err(&client->dev, "%s failed to configure lanes\n", __func__);
819                 goto err_rpm_put;
820         }
821
822         /* Apply default values of current mode */
823         reg_list = &imx219->mode->reg_list;
824         ret = cci_multi_reg_write(imx219->regmap, reg_list->regs,
825                                   reg_list->num_of_regs, NULL);
826         if (ret) {
827                 dev_err(&client->dev, "%s failed to set mode\n", __func__);
828                 goto err_rpm_put;
829         }
830
831         format = v4l2_subdev_get_pad_format(&imx219->sd, state, 0);
832         ret = imx219_set_framefmt(imx219, format);
833         if (ret) {
834                 dev_err(&client->dev, "%s failed to set frame format: %d\n",
835                         __func__, ret);
836                 goto err_rpm_put;
837         }
838
839         ret = imx219_set_binning(imx219, format);
840         if (ret) {
841                 dev_err(&client->dev, "%s failed to set binning: %d\n",
842                         __func__, ret);
843                 goto err_rpm_put;
844         }
845
846         /* Apply customized values from user */
847         ret =  __v4l2_ctrl_handler_setup(imx219->sd.ctrl_handler);
848         if (ret)
849                 goto err_rpm_put;
850
851         /* set stream on register */
852         ret = cci_write(imx219->regmap, IMX219_REG_MODE_SELECT,
853                         IMX219_MODE_STREAMING, NULL);
854         if (ret)
855                 goto err_rpm_put;
856
857         /* vflip and hflip cannot change during streaming */
858         __v4l2_ctrl_grab(imx219->vflip, true);
859         __v4l2_ctrl_grab(imx219->hflip, true);
860
861         return 0;
862
863 err_rpm_put:
864         pm_runtime_put(&client->dev);
865         return ret;
866 }
867
868 static void imx219_stop_streaming(struct imx219 *imx219)
869 {
870         struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
871         int ret;
872
873         /* set stream off register */
874         ret = cci_write(imx219->regmap, IMX219_REG_MODE_SELECT,
875                         IMX219_MODE_STANDBY, NULL);
876         if (ret)
877                 dev_err(&client->dev, "%s failed to set stream\n", __func__);
878
879         __v4l2_ctrl_grab(imx219->vflip, false);
880         __v4l2_ctrl_grab(imx219->hflip, false);
881
882         pm_runtime_put(&client->dev);
883 }
884
885 static int imx219_set_stream(struct v4l2_subdev *sd, int enable)
886 {
887         struct imx219 *imx219 = to_imx219(sd);
888         struct v4l2_subdev_state *state;
889         int ret = 0;
890
891         state = v4l2_subdev_lock_and_get_active_state(sd);
892
893         if (imx219->streaming == enable)
894                 goto unlock;
895
896         if (enable) {
897                 /*
898                  * Apply default & customized values
899                  * and then start streaming.
900                  */
901                 ret = imx219_start_streaming(imx219, state);
902                 if (ret)
903                         goto unlock;
904         } else {
905                 imx219_stop_streaming(imx219);
906         }
907
908         imx219->streaming = enable;
909
910 unlock:
911         v4l2_subdev_unlock_state(state);
912         return ret;
913 }
914
915 /* Power/clock management functions */
916 static int imx219_power_on(struct device *dev)
917 {
918         struct v4l2_subdev *sd = dev_get_drvdata(dev);
919         struct imx219 *imx219 = to_imx219(sd);
920         int ret;
921
922         ret = regulator_bulk_enable(IMX219_NUM_SUPPLIES,
923                                     imx219->supplies);
924         if (ret) {
925                 dev_err(dev, "%s: failed to enable regulators\n",
926                         __func__);
927                 return ret;
928         }
929
930         ret = clk_prepare_enable(imx219->xclk);
931         if (ret) {
932                 dev_err(dev, "%s: failed to enable clock\n",
933                         __func__);
934                 goto reg_off;
935         }
936
937         gpiod_set_value_cansleep(imx219->reset_gpio, 1);
938         usleep_range(IMX219_XCLR_MIN_DELAY_US,
939                      IMX219_XCLR_MIN_DELAY_US + IMX219_XCLR_DELAY_RANGE_US);
940
941         return 0;
942
943 reg_off:
944         regulator_bulk_disable(IMX219_NUM_SUPPLIES, imx219->supplies);
945
946         return ret;
947 }
948
949 static int imx219_power_off(struct device *dev)
950 {
951         struct v4l2_subdev *sd = dev_get_drvdata(dev);
952         struct imx219 *imx219 = to_imx219(sd);
953
954         gpiod_set_value_cansleep(imx219->reset_gpio, 0);
955         regulator_bulk_disable(IMX219_NUM_SUPPLIES, imx219->supplies);
956         clk_disable_unprepare(imx219->xclk);
957
958         return 0;
959 }
960
961 static int __maybe_unused imx219_suspend(struct device *dev)
962 {
963         struct v4l2_subdev *sd = dev_get_drvdata(dev);
964         struct imx219 *imx219 = to_imx219(sd);
965
966         if (imx219->streaming)
967                 imx219_stop_streaming(imx219);
968
969         return 0;
970 }
971
972 static int __maybe_unused imx219_resume(struct device *dev)
973 {
974         struct v4l2_subdev *sd = dev_get_drvdata(dev);
975         struct imx219 *imx219 = to_imx219(sd);
976         struct v4l2_subdev_state *state;
977         int ret;
978
979         if (imx219->streaming) {
980                 state = v4l2_subdev_lock_and_get_active_state(sd);
981                 ret = imx219_start_streaming(imx219, state);
982                 v4l2_subdev_unlock_state(state);
983                 if (ret)
984                         goto error;
985         }
986
987         return 0;
988
989 error:
990         imx219_stop_streaming(imx219);
991         imx219->streaming = false;
992
993         return ret;
994 }
995
996 static int imx219_get_regulators(struct imx219 *imx219)
997 {
998         struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
999         unsigned int i;
1000
1001         for (i = 0; i < IMX219_NUM_SUPPLIES; i++)
1002                 imx219->supplies[i].supply = imx219_supply_name[i];
1003
1004         return devm_regulator_bulk_get(&client->dev,
1005                                        IMX219_NUM_SUPPLIES,
1006                                        imx219->supplies);
1007 }
1008
1009 /* Verify chip ID */
1010 static int imx219_identify_module(struct imx219 *imx219)
1011 {
1012         struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1013         int ret;
1014         u64 val;
1015
1016         ret = cci_read(imx219->regmap, IMX219_REG_CHIP_ID, &val, NULL);
1017         if (ret) {
1018                 dev_err(&client->dev, "failed to read chip id %x\n",
1019                         IMX219_CHIP_ID);
1020                 return ret;
1021         }
1022
1023         if (val != IMX219_CHIP_ID) {
1024                 dev_err(&client->dev, "chip id mismatch: %x!=%llx\n",
1025                         IMX219_CHIP_ID, val);
1026                 return -EIO;
1027         }
1028
1029         return 0;
1030 }
1031
1032 static const struct v4l2_subdev_core_ops imx219_core_ops = {
1033         .subscribe_event = v4l2_ctrl_subdev_subscribe_event,
1034         .unsubscribe_event = v4l2_event_subdev_unsubscribe,
1035 };
1036
1037 static const struct v4l2_subdev_video_ops imx219_video_ops = {
1038         .s_stream = imx219_set_stream,
1039 };
1040
1041 static const struct v4l2_subdev_pad_ops imx219_pad_ops = {
1042         .init_cfg = imx219_init_cfg,
1043         .enum_mbus_code = imx219_enum_mbus_code,
1044         .get_fmt = v4l2_subdev_get_fmt,
1045         .set_fmt = imx219_set_pad_format,
1046         .get_selection = imx219_get_selection,
1047         .enum_frame_size = imx219_enum_frame_size,
1048 };
1049
1050 static const struct v4l2_subdev_ops imx219_subdev_ops = {
1051         .core = &imx219_core_ops,
1052         .video = &imx219_video_ops,
1053         .pad = &imx219_pad_ops,
1054 };
1055
1056
1057 static unsigned long imx219_get_pixel_rate(struct imx219 *imx219)
1058 {
1059         return (imx219->lanes == 2) ? IMX219_PIXEL_RATE : IMX219_PIXEL_RATE_4LANE;
1060 }
1061
1062 /* Initialize control handlers */
1063 static int imx219_init_controls(struct imx219 *imx219)
1064 {
1065         struct i2c_client *client = v4l2_get_subdevdata(&imx219->sd);
1066         struct v4l2_ctrl_handler *ctrl_hdlr;
1067         unsigned int height = imx219->mode->height;
1068         struct v4l2_fwnode_device_properties props;
1069         int exposure_max, exposure_def, hblank;
1070         int i, ret;
1071
1072         ctrl_hdlr = &imx219->ctrl_handler;
1073         ret = v4l2_ctrl_handler_init(ctrl_hdlr, 12);
1074         if (ret)
1075                 return ret;
1076
1077         /* By default, PIXEL_RATE is read only */
1078         imx219->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1079                                                V4L2_CID_PIXEL_RATE,
1080                                                imx219_get_pixel_rate(imx219),
1081                                                imx219_get_pixel_rate(imx219), 1,
1082                                                imx219_get_pixel_rate(imx219));
1083
1084         imx219->link_freq =
1085                 v4l2_ctrl_new_int_menu(ctrl_hdlr, &imx219_ctrl_ops,
1086                                        V4L2_CID_LINK_FREQ,
1087                                        ARRAY_SIZE(imx219_link_freq_menu) - 1, 0,
1088                                        (imx219->lanes == 2) ? imx219_link_freq_menu :
1089                                        imx219_link_freq_4lane_menu);
1090         if (imx219->link_freq)
1091                 imx219->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY;
1092
1093         /* Initial vblank/hblank/exposure parameters based on current mode */
1094         imx219->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1095                                            V4L2_CID_VBLANK, IMX219_VBLANK_MIN,
1096                                            IMX219_VTS_MAX - height, 1,
1097                                            imx219->mode->vts_def - height);
1098         hblank = IMX219_PPL_DEFAULT - imx219->mode->width;
1099         imx219->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1100                                            V4L2_CID_HBLANK, hblank, hblank,
1101                                            1, hblank);
1102         if (imx219->hblank)
1103                 imx219->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY;
1104         exposure_max = imx219->mode->vts_def - 4;
1105         exposure_def = (exposure_max < IMX219_EXPOSURE_DEFAULT) ?
1106                 exposure_max : IMX219_EXPOSURE_DEFAULT;
1107         imx219->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1108                                              V4L2_CID_EXPOSURE,
1109                                              IMX219_EXPOSURE_MIN, exposure_max,
1110                                              IMX219_EXPOSURE_STEP,
1111                                              exposure_def);
1112
1113         v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_ANALOGUE_GAIN,
1114                           IMX219_ANA_GAIN_MIN, IMX219_ANA_GAIN_MAX,
1115                           IMX219_ANA_GAIN_STEP, IMX219_ANA_GAIN_DEFAULT);
1116
1117         v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_DIGITAL_GAIN,
1118                           IMX219_DGTL_GAIN_MIN, IMX219_DGTL_GAIN_MAX,
1119                           IMX219_DGTL_GAIN_STEP, IMX219_DGTL_GAIN_DEFAULT);
1120
1121         imx219->hflip = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1122                                           V4L2_CID_HFLIP, 0, 1, 1, 0);
1123         if (imx219->hflip)
1124                 imx219->hflip->flags |= V4L2_CTRL_FLAG_MODIFY_LAYOUT;
1125
1126         imx219->vflip = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1127                                           V4L2_CID_VFLIP, 0, 1, 1, 0);
1128         if (imx219->vflip)
1129                 imx219->vflip->flags |= V4L2_CTRL_FLAG_MODIFY_LAYOUT;
1130
1131         v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &imx219_ctrl_ops,
1132                                      V4L2_CID_TEST_PATTERN,
1133                                      ARRAY_SIZE(imx219_test_pattern_menu) - 1,
1134                                      0, 0, imx219_test_pattern_menu);
1135         for (i = 0; i < 4; i++) {
1136                 /*
1137                  * The assumption is that
1138                  * V4L2_CID_TEST_PATTERN_GREENR == V4L2_CID_TEST_PATTERN_RED + 1
1139                  * V4L2_CID_TEST_PATTERN_BLUE   == V4L2_CID_TEST_PATTERN_RED + 2
1140                  * V4L2_CID_TEST_PATTERN_GREENB == V4L2_CID_TEST_PATTERN_RED + 3
1141                  */
1142                 v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops,
1143                                   V4L2_CID_TEST_PATTERN_RED + i,
1144                                   IMX219_TESTP_COLOUR_MIN,
1145                                   IMX219_TESTP_COLOUR_MAX,
1146                                   IMX219_TESTP_COLOUR_STEP,
1147                                   IMX219_TESTP_COLOUR_MAX);
1148                 /* The "Solid color" pattern is white by default */
1149         }
1150
1151         if (ctrl_hdlr->error) {
1152                 ret = ctrl_hdlr->error;
1153                 dev_err(&client->dev, "%s control init failed (%d)\n",
1154                         __func__, ret);
1155                 goto error;
1156         }
1157
1158         ret = v4l2_fwnode_device_parse(&client->dev, &props);
1159         if (ret)
1160                 goto error;
1161
1162         ret = v4l2_ctrl_new_fwnode_properties(ctrl_hdlr, &imx219_ctrl_ops,
1163                                               &props);
1164         if (ret)
1165                 goto error;
1166
1167         imx219->sd.ctrl_handler = ctrl_hdlr;
1168
1169         return 0;
1170
1171 error:
1172         v4l2_ctrl_handler_free(ctrl_hdlr);
1173
1174         return ret;
1175 }
1176
1177 static void imx219_free_controls(struct imx219 *imx219)
1178 {
1179         v4l2_ctrl_handler_free(imx219->sd.ctrl_handler);
1180 }
1181
1182 static int imx219_check_hwcfg(struct device *dev, struct imx219 *imx219)
1183 {
1184         struct fwnode_handle *endpoint;
1185         struct v4l2_fwnode_endpoint ep_cfg = {
1186                 .bus_type = V4L2_MBUS_CSI2_DPHY
1187         };
1188         int ret = -EINVAL;
1189
1190         endpoint = fwnode_graph_get_next_endpoint(dev_fwnode(dev), NULL);
1191         if (!endpoint) {
1192                 dev_err(dev, "endpoint node not found\n");
1193                 return -EINVAL;
1194         }
1195
1196         if (v4l2_fwnode_endpoint_alloc_parse(endpoint, &ep_cfg)) {
1197                 dev_err(dev, "could not parse endpoint\n");
1198                 goto error_out;
1199         }
1200
1201         /* Check the number of MIPI CSI2 data lanes */
1202         if (ep_cfg.bus.mipi_csi2.num_data_lanes != 2 &&
1203             ep_cfg.bus.mipi_csi2.num_data_lanes != 4) {
1204                 dev_err(dev, "only 2 or 4 data lanes are currently supported\n");
1205                 goto error_out;
1206         }
1207         imx219->lanes = ep_cfg.bus.mipi_csi2.num_data_lanes;
1208
1209         /* Check the link frequency set in device tree */
1210         if (!ep_cfg.nr_of_link_frequencies) {
1211                 dev_err(dev, "link-frequency property not found in DT\n");
1212                 goto error_out;
1213         }
1214
1215         if (ep_cfg.nr_of_link_frequencies != 1 ||
1216            (ep_cfg.link_frequencies[0] != ((imx219->lanes == 2) ?
1217             IMX219_DEFAULT_LINK_FREQ : IMX219_DEFAULT_LINK_FREQ_4LANE))) {
1218                 dev_err(dev, "Link frequency not supported: %lld\n",
1219                         ep_cfg.link_frequencies[0]);
1220                 goto error_out;
1221         }
1222
1223         ret = 0;
1224
1225 error_out:
1226         v4l2_fwnode_endpoint_free(&ep_cfg);
1227         fwnode_handle_put(endpoint);
1228
1229         return ret;
1230 }
1231
1232 static int imx219_probe(struct i2c_client *client)
1233 {
1234         struct device *dev = &client->dev;
1235         struct imx219 *imx219;
1236         int ret;
1237
1238         imx219 = devm_kzalloc(&client->dev, sizeof(*imx219), GFP_KERNEL);
1239         if (!imx219)
1240                 return -ENOMEM;
1241
1242         v4l2_i2c_subdev_init(&imx219->sd, client, &imx219_subdev_ops);
1243
1244         /* Check the hardware configuration in device tree */
1245         if (imx219_check_hwcfg(dev, imx219))
1246                 return -EINVAL;
1247
1248         imx219->regmap = devm_cci_regmap_init_i2c(client, 16);
1249         if (IS_ERR(imx219->regmap)) {
1250                 ret = PTR_ERR(imx219->regmap);
1251                 dev_err(dev, "failed to initialize CCI: %d\n", ret);
1252                 return ret;
1253         }
1254
1255         /* Get system clock (xclk) */
1256         imx219->xclk = devm_clk_get(dev, NULL);
1257         if (IS_ERR(imx219->xclk)) {
1258                 dev_err(dev, "failed to get xclk\n");
1259                 return PTR_ERR(imx219->xclk);
1260         }
1261
1262         imx219->xclk_freq = clk_get_rate(imx219->xclk);
1263         if (imx219->xclk_freq != IMX219_XCLK_FREQ) {
1264                 dev_err(dev, "xclk frequency not supported: %d Hz\n",
1265                         imx219->xclk_freq);
1266                 return -EINVAL;
1267         }
1268
1269         ret = imx219_get_regulators(imx219);
1270         if (ret) {
1271                 dev_err(dev, "failed to get regulators\n");
1272                 return ret;
1273         }
1274
1275         /* Request optional enable pin */
1276         imx219->reset_gpio = devm_gpiod_get_optional(dev, "reset",
1277                                                      GPIOD_OUT_HIGH);
1278
1279         /*
1280          * The sensor must be powered for imx219_identify_module()
1281          * to be able to read the CHIP_ID register
1282          */
1283         ret = imx219_power_on(dev);
1284         if (ret)
1285                 return ret;
1286
1287         ret = imx219_identify_module(imx219);
1288         if (ret)
1289                 goto error_power_off;
1290
1291         /* Set default mode to max resolution */
1292         imx219->mode = &supported_modes[0];
1293
1294         /* sensor doesn't enter LP-11 state upon power up until and unless
1295          * streaming is started, so upon power up switch the modes to:
1296          * streaming -> standby
1297          */
1298         ret = cci_write(imx219->regmap, IMX219_REG_MODE_SELECT,
1299                         IMX219_MODE_STREAMING, NULL);
1300         if (ret < 0)
1301                 goto error_power_off;
1302
1303         usleep_range(100, 110);
1304
1305         /* put sensor back to standby mode */
1306         ret = cci_write(imx219->regmap, IMX219_REG_MODE_SELECT,
1307                         IMX219_MODE_STANDBY, NULL);
1308         if (ret < 0)
1309                 goto error_power_off;
1310
1311         usleep_range(100, 110);
1312
1313         ret = imx219_init_controls(imx219);
1314         if (ret)
1315                 goto error_power_off;
1316
1317         /* Initialize subdev */
1318         imx219->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE |
1319                             V4L2_SUBDEV_FL_HAS_EVENTS;
1320         imx219->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
1321
1322         /* Initialize source pad */
1323         imx219->pad.flags = MEDIA_PAD_FL_SOURCE;
1324
1325         ret = media_entity_pads_init(&imx219->sd.entity, 1, &imx219->pad);
1326         if (ret) {
1327                 dev_err(dev, "failed to init entity pads: %d\n", ret);
1328                 goto error_handler_free;
1329         }
1330
1331         imx219->sd.state_lock = imx219->ctrl_handler.lock;
1332         ret = v4l2_subdev_init_finalize(&imx219->sd);
1333         if (ret < 0) {
1334                 dev_err(dev, "subdev init error: %d\n", ret);
1335                 goto error_media_entity;
1336         }
1337
1338         ret = v4l2_async_register_subdev_sensor(&imx219->sd);
1339         if (ret < 0) {
1340                 dev_err(dev, "failed to register sensor sub-device: %d\n", ret);
1341                 goto error_subdev_cleanup;
1342         }
1343
1344         /* Enable runtime PM and turn off the device */
1345         pm_runtime_set_active(dev);
1346         pm_runtime_enable(dev);
1347         pm_runtime_idle(dev);
1348
1349         return 0;
1350
1351 error_subdev_cleanup:
1352         v4l2_subdev_cleanup(&imx219->sd);
1353
1354 error_media_entity:
1355         media_entity_cleanup(&imx219->sd.entity);
1356
1357 error_handler_free:
1358         imx219_free_controls(imx219);
1359
1360 error_power_off:
1361         imx219_power_off(dev);
1362
1363         return ret;
1364 }
1365
1366 static void imx219_remove(struct i2c_client *client)
1367 {
1368         struct v4l2_subdev *sd = i2c_get_clientdata(client);
1369         struct imx219 *imx219 = to_imx219(sd);
1370
1371         v4l2_async_unregister_subdev(sd);
1372         v4l2_subdev_cleanup(sd);
1373         media_entity_cleanup(&sd->entity);
1374         imx219_free_controls(imx219);
1375
1376         pm_runtime_disable(&client->dev);
1377         if (!pm_runtime_status_suspended(&client->dev))
1378                 imx219_power_off(&client->dev);
1379         pm_runtime_set_suspended(&client->dev);
1380 }
1381
1382 static const struct of_device_id imx219_dt_ids[] = {
1383         { .compatible = "sony,imx219" },
1384         { /* sentinel */ }
1385 };
1386 MODULE_DEVICE_TABLE(of, imx219_dt_ids);
1387
1388 static const struct dev_pm_ops imx219_pm_ops = {
1389         SET_SYSTEM_SLEEP_PM_OPS(imx219_suspend, imx219_resume)
1390         SET_RUNTIME_PM_OPS(imx219_power_off, imx219_power_on, NULL)
1391 };
1392
1393 static struct i2c_driver imx219_i2c_driver = {
1394         .driver = {
1395                 .name = "imx219",
1396                 .of_match_table = imx219_dt_ids,
1397                 .pm = &imx219_pm_ops,
1398         },
1399         .probe = imx219_probe,
1400         .remove = imx219_remove,
1401 };
1402
1403 module_i2c_driver(imx219_i2c_driver);
1404
1405 MODULE_AUTHOR("Dave Stevenson <dave.stevenson@raspberrypi.com");
1406 MODULE_DESCRIPTION("Sony IMX219 sensor driver");
1407 MODULE_LICENSE("GPL v2");