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