GNU Linux-libre 4.14.332-gnu1
[releases.git] / drivers / staging / media / atomisp / i2c / imx / imx.c
1 /*
2  * Support for Sony imx 8MP camera sensor.
3  *
4  * Copyright (c) 2012 Intel Corporation. All Rights Reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License version
8  * 2 as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18  * 02110-1301, USA.
19  *
20  */
21 #include <asm/intel-mid.h>
22 #include "../../include/linux/atomisp_platform.h"
23 #include <linux/bitops.h>
24 #include <linux/device.h>
25 #include <linux/delay.h>
26 #include <linux/errno.h>
27 #include <linux/fs.h>
28 #include <linux/gpio.h>
29 #include <linux/init.h>
30 #include <linux/i2c.h>
31 #include <linux/io.h>
32 #include <linux/kernel.h>
33 #include "../../include/linux/libmsrlisthelper.h"
34 #include <linux/mm.h>
35 #include <linux/kmod.h>
36 #include <linux/module.h>
37 #include <linux/moduleparam.h>
38 #include <linux/string.h>
39 #include <linux/slab.h>
40 #include <linux/types.h>
41 #include <media/v4l2-ctrls.h>
42 #include <media/v4l2-device.h>
43 #include "imx.h"
44
45 /*
46  * The imx135 embedded data info:
47  * embedded data line num: 2
48  * line 0 effective data size(byte): 76
49  * line 1 effective data size(byte): 113
50  */
51 static const uint32_t
52         imx135_embedded_effective_size[IMX135_EMBEDDED_DATA_LINE_NUM]
53         =  {76, 113};
54
55 static enum atomisp_bayer_order imx_bayer_order_mapping[] = {
56         atomisp_bayer_order_rggb,
57         atomisp_bayer_order_grbg,
58         atomisp_bayer_order_gbrg,
59         atomisp_bayer_order_bggr
60 };
61
62 static const unsigned int
63 IMX227_BRACKETING_LUT_FRAME_ENTRY[IMX_MAX_AE_LUT_LENGTH] = {
64         0x0E10, 0x0E1E, 0x0E2C, 0x0E3A, 0x0E48};
65
66 static int
67 imx_read_reg(struct i2c_client *client, u16 len, u16 reg, u16 *val)
68 {
69         struct i2c_msg msg[2];
70         u16 data[IMX_SHORT_MAX];
71         int ret, i;
72         int retry = 0;
73
74         if (len > IMX_BYTE_MAX) {
75                 dev_err(&client->dev, "%s error, invalid data length\n",
76                         __func__);
77                 return -EINVAL;
78         }
79
80         do {
81                 memset(msg, 0 , sizeof(msg));
82                 memset(data, 0 , sizeof(data));
83
84                 msg[0].addr = client->addr;
85                 msg[0].flags = 0;
86                 msg[0].len = I2C_MSG_LENGTH;
87                 msg[0].buf = (u8 *)data;
88                 /* high byte goes first */
89                 data[0] = cpu_to_be16(reg);
90
91                 msg[1].addr = client->addr;
92                 msg[1].len = len;
93                 msg[1].flags = I2C_M_RD;
94                 msg[1].buf = (u8 *)data;
95
96                 ret = i2c_transfer(client->adapter, msg, 2);
97                 if (ret != 2) {
98                         dev_err(&client->dev,
99                           "retrying i2c read from offset 0x%x error %d... %d\n",
100                           reg, ret, retry);
101                         msleep(20);
102                 }
103         } while (ret != 2 && retry++ < I2C_RETRY_COUNT);
104
105         if (ret != 2)
106                 return -EIO;
107
108         /* high byte comes first */
109         if (len == IMX_8BIT) {
110                 *val = (u8)data[0];
111         } else {
112                 /* 16-bit access is default when len > 1 */
113                 for (i = 0; i < (len >> 1); i++)
114                         val[i] = be16_to_cpu(data[i]);
115         }
116
117         return 0;
118 }
119
120 static int imx_i2c_write(struct i2c_client *client, u16 len, u8 *data)
121 {
122         struct i2c_msg msg;
123         int ret;
124         int retry = 0;
125
126         do {
127                 msg.addr = client->addr;
128                 msg.flags = 0;
129                 msg.len = len;
130                 msg.buf = data;
131
132                 ret = i2c_transfer(client->adapter, &msg, 1);
133                 if (ret != 1) {
134                         dev_err(&client->dev,
135                                 "retrying i2c write transfer... %d\n", retry);
136                                 msleep(20);
137                 }
138         } while (ret != 1 && retry++ < I2C_RETRY_COUNT);
139
140         return ret == 1 ? 0 : -EIO;
141 }
142
143 int
144 imx_write_reg(struct i2c_client *client, u16 data_length, u16 reg, u16 val)
145 {
146         int ret;
147         unsigned char data[4] = {0};
148         u16 *wreg = (u16 *)data;
149         const u16 len = data_length + sizeof(u16); /* 16-bit address + data */
150
151         if (data_length != IMX_8BIT && data_length != IMX_16BIT) {
152                 v4l2_err(client, "%s error, invalid data_length\n", __func__);
153                 return -EINVAL;
154         }
155
156         /* high byte goes out first */
157         *wreg = cpu_to_be16(reg);
158
159         if (data_length == IMX_8BIT)
160                 data[2] = (u8)(val);
161         else {
162                 /* IMX_16BIT */
163                 u16 *wdata = (u16 *)&data[2];
164                 *wdata = cpu_to_be16(val);
165         }
166
167         ret = imx_i2c_write(client, len, data);
168         if (ret)
169                 dev_err(&client->dev,
170                         "write error: wrote 0x%x to offset 0x%x error %d",
171                         val, reg, ret);
172
173         return ret;
174 }
175
176 /*
177  * imx_write_reg_array - Initializes a list of imx registers
178  * @client: i2c driver client structure
179  * @reglist: list of registers to be written
180  *
181  * This function initializes a list of registers. When consecutive addresses
182  * are found in a row on the list, this function creates a buffer and sends
183  * consecutive data in a single i2c_transfer().
184  *
185  * __imx_flush_reg_array, __imx_buf_reg_array() and
186  * __imx_write_reg_is_consecutive() are internal functions to
187  * imx_write_reg_array_fast() and should be not used anywhere else.
188  *
189  */
190
191 static int __imx_flush_reg_array(struct i2c_client *client,
192                                      struct imx_write_ctrl *ctrl)
193 {
194         u16 size;
195
196         if (ctrl->index == 0)
197                 return 0;
198
199         size = sizeof(u16) + ctrl->index; /* 16-bit address + data */
200         ctrl->buffer.addr = cpu_to_be16(ctrl->buffer.addr);
201         ctrl->index = 0;
202
203         return imx_i2c_write(client, size, (u8 *)&ctrl->buffer);
204 }
205
206 static int __imx_buf_reg_array(struct i2c_client *client,
207                                    struct imx_write_ctrl *ctrl,
208                                    const struct imx_reg *next)
209 {
210         int size;
211         u16 *data16;
212
213         switch (next->type) {
214         case IMX_8BIT:
215                 size = 1;
216                 ctrl->buffer.data[ctrl->index] = (u8)next->val;
217                 break;
218         case IMX_16BIT:
219                 size = 2;
220                 data16 = (u16 *)&ctrl->buffer.data[ctrl->index];
221                 *data16 = cpu_to_be16((u16)next->val);
222                 break;
223         default:
224                 return -EINVAL;
225         }
226
227         /* When first item is added, we need to store its starting address */
228         if (ctrl->index == 0)
229                 ctrl->buffer.addr = next->sreg;
230
231         ctrl->index += size;
232
233         /*
234          * Buffer cannot guarantee free space for u32? Better flush it to avoid
235          * possible lack of memory for next item.
236          */
237         if (ctrl->index + sizeof(u16) >= IMX_MAX_WRITE_BUF_SIZE)
238                 return __imx_flush_reg_array(client, ctrl);
239
240         return 0;
241 }
242
243 static int
244 __imx_write_reg_is_consecutive(struct i2c_client *client,
245                                    struct imx_write_ctrl *ctrl,
246                                    const struct imx_reg *next)
247 {
248         if (ctrl->index == 0)
249                 return 1;
250
251         return ctrl->buffer.addr + ctrl->index == next->sreg;
252 }
253
254 static int imx_write_reg_array(struct i2c_client *client,
255                                    const struct imx_reg *reglist)
256 {
257         const struct imx_reg *next = reglist;
258         struct imx_write_ctrl ctrl;
259         int err;
260
261         ctrl.index = 0;
262         for (; next->type != IMX_TOK_TERM; next++) {
263                 switch (next->type & IMX_TOK_MASK) {
264                 case IMX_TOK_DELAY:
265                         err = __imx_flush_reg_array(client, &ctrl);
266                         if (err)
267                                 return err;
268                         msleep(next->val);
269                         break;
270
271                 default:
272                         /*
273                          * If next address is not consecutive, data needs to be
274                          * flushed before proceed.
275                          */
276                         if (!__imx_write_reg_is_consecutive(client, &ctrl,
277                                                                 next)) {
278                                 err = __imx_flush_reg_array(client, &ctrl);
279                                 if (err)
280                                         return err;
281                         }
282                         err = __imx_buf_reg_array(client, &ctrl, next);
283                         if (err) {
284                                 v4l2_err(client, "%s: write error, aborted\n",
285                                          __func__);
286                                 return err;
287                         }
288                         break;
289                 }
290         }
291
292         return __imx_flush_reg_array(client, &ctrl);
293 }
294
295 static int __imx_min_fps_diff(int fps, const struct imx_fps_setting *fps_list)
296 {
297         int diff = INT_MAX;
298         int i;
299
300         if (fps == 0)
301                 return 0;
302
303         for (i = 0; i < MAX_FPS_OPTIONS_SUPPORTED; i++) {
304                 if (!fps_list[i].fps)
305                         break;
306                 if (abs(fps_list[i].fps - fps) < diff)
307                         diff = abs(fps_list[i].fps - fps);
308         }
309
310         return diff;
311 }
312
313 static int __imx_nearest_fps_index(int fps,
314                                         const struct imx_fps_setting *fps_list)
315 {
316         int fps_index = 0;
317         int i;
318
319         for (i = 0; i < MAX_FPS_OPTIONS_SUPPORTED; i++) {
320                 if (!fps_list[i].fps)
321                         break;
322                 if (abs(fps_list[i].fps - fps)
323                     < abs(fps_list[fps_index].fps - fps))
324                         fps_index = i;
325         }
326         return fps_index;
327 }
328
329 /*
330  * This is to choose the nearest fps setting above the requested fps
331  * fps_list should be in ascendant order.
332  */
333 static int __imx_above_nearest_fps_index(int fps,
334                                         const struct imx_fps_setting *fps_list)
335 {
336         int fps_index = 0;
337         int i;
338
339         for (i = 0; i < MAX_FPS_OPTIONS_SUPPORTED; i++) {
340                 if (!fps_list[i].fps)
341                         break;
342                 if (fps <= fps_list[i].fps) {
343                         fps_index = i;
344                         break;
345                 }
346         }
347
348         return fps_index;
349 }
350
351 static int imx_get_lanes(struct v4l2_subdev *sd)
352 {
353         struct camera_mipi_info *imx_info = v4l2_get_subdev_hostdata(sd);
354
355         if (!imx_info)
356                 return -ENOSYS;
357         if (imx_info->num_lanes < 1 || imx_info->num_lanes > 4 ||
358             imx_info->num_lanes == 3)
359                 return -EINVAL;
360
361         return imx_info->num_lanes;
362 }
363
364 static int __imx_update_exposure_timing(struct i2c_client *client, u16 exposure,
365                         u16 llp, u16 fll)
366 {
367         struct v4l2_subdev *sd = i2c_get_clientdata(client);
368         struct imx_device *dev = to_imx_sensor(sd);
369         int ret = 0;
370
371         if (dev->sensor_id != IMX227_ID) {
372                 /* Increase the VTS to match exposure + margin */
373                 if (exposure > fll - IMX_INTEGRATION_TIME_MARGIN)
374                         fll = exposure + IMX_INTEGRATION_TIME_MARGIN;
375         }
376
377         ret = imx_write_reg(client, IMX_16BIT,
378                 dev->reg_addr->line_length_pixels, llp);
379         if (ret)
380                 return ret;
381
382         ret = imx_write_reg(client, IMX_16BIT,
383                 dev->reg_addr->frame_length_lines, fll);
384         if (ret)
385                 return ret;
386
387         if (exposure)
388                 ret = imx_write_reg(client, IMX_16BIT,
389                         dev->reg_addr->coarse_integration_time, exposure);
390
391         return ret;
392 }
393
394 static int __imx_update_gain(struct v4l2_subdev *sd, u16 gain)
395 {
396         struct imx_device *dev = to_imx_sensor(sd);
397         struct i2c_client *client = v4l2_get_subdevdata(sd);
398         int ret;
399
400         /* set global gain */
401         ret = imx_write_reg(client, IMX_8BIT, dev->reg_addr->global_gain, gain);
402         if (ret)
403                 return ret;
404
405         /* set short analog gain */
406         if (dev->sensor_id == IMX135_ID)
407                 ret = imx_write_reg(client, IMX_8BIT, IMX_SHORT_AGC_GAIN, gain);
408
409         return ret;
410 }
411
412 static int __imx_update_digital_gain(struct i2c_client *client, u16 digitgain)
413 {
414         struct v4l2_subdev *sd = i2c_get_clientdata(client);
415         struct imx_device *dev = to_imx_sensor(sd);
416         struct imx_write_buffer digit_gain;
417
418         digit_gain.addr = cpu_to_be16(dev->reg_addr->dgc_adj);
419         digit_gain.data[0] = (digitgain >> 8) & 0xFF;
420         digit_gain.data[1] = digitgain & 0xFF;
421
422         if (dev->sensor_id == IMX219_ID) {
423                 return imx_i2c_write(client, IMX219_DGC_LEN, (u8 *)&digit_gain);
424         } else if (dev->sensor_id == IMX227_ID) {
425                 return imx_i2c_write(client, IMX227_DGC_LEN, (u8 *)&digit_gain);
426         } else {
427                 digit_gain.data[2] = (digitgain >> 8) & 0xFF;
428                 digit_gain.data[3] = digitgain & 0xFF;
429                 digit_gain.data[4] = (digitgain >> 8) & 0xFF;
430                 digit_gain.data[5] = digitgain & 0xFF;
431                 digit_gain.data[6] = (digitgain >> 8) & 0xFF;
432                 digit_gain.data[7] = digitgain & 0xFF;
433                 return imx_i2c_write(client, IMX_DGC_LEN, (u8 *)&digit_gain);
434         }
435         return 0;
436 }
437
438 static int imx_set_exposure_gain(struct v4l2_subdev *sd, u16 coarse_itg,
439         u16 gain, u16 digitgain)
440 {
441         struct imx_device *dev = to_imx_sensor(sd);
442         struct i2c_client *client = v4l2_get_subdevdata(sd);
443         int lanes = imx_get_lanes(sd);
444         unsigned int digitgain_scaled;
445         int ret = 0;
446
447         /* Validate exposure:  cannot exceed VTS-4 where VTS is 16bit */
448         coarse_itg = clamp_t(u16, coarse_itg, 0, IMX_MAX_EXPOSURE_SUPPORTED);
449
450         /* Validate gain: must not exceed maximum 8bit value */
451         gain = clamp_t(u16, gain, 0, IMX_MAX_GLOBAL_GAIN_SUPPORTED);
452
453         mutex_lock(&dev->input_lock);
454
455         if (dev->sensor_id == IMX227_ID) {
456                 ret = imx_write_reg_array(client, imx_param_hold);
457                 if (ret) {
458                         mutex_unlock(&dev->input_lock);
459                         return ret;
460                 }
461         }
462
463         /* For imx175, setting gain must be delayed by one */
464         if ((dev->sensor_id == IMX175_ID) && dev->digital_gain)
465                 digitgain_scaled = dev->digital_gain;
466         else
467                 digitgain_scaled = digitgain;
468         /* imx132 with two lanes needs more gain to saturate at max */
469         if (dev->sensor_id == IMX132_ID && lanes > 1) {
470                 digitgain_scaled *= IMX132_2LANES_GAINFACT;
471                 digitgain_scaled >>= IMX132_2LANES_GAINFACT_SHIFT;
472         }
473         /* Validate digital gain: must not exceed 12 bit value*/
474         digitgain_scaled = clamp_t(unsigned int, digitgain_scaled,
475                                    0, IMX_MAX_DIGITAL_GAIN_SUPPORTED);
476
477         ret = __imx_update_exposure_timing(client, coarse_itg,
478                         dev->pixels_per_line, dev->lines_per_frame);
479         if (ret)
480                 goto out;
481         dev->coarse_itg = coarse_itg;
482
483         if (dev->sensor_id == IMX175_ID)
484                 ret = __imx_update_gain(sd, dev->gain);
485         else
486                 ret = __imx_update_gain(sd, gain);
487         if (ret)
488                 goto out;
489         dev->gain = gain;
490
491         ret = __imx_update_digital_gain(client, digitgain_scaled);
492         if (ret)
493                 goto out;
494         dev->digital_gain = digitgain;
495
496 out:
497         if (dev->sensor_id == IMX227_ID)
498                 ret = imx_write_reg_array(client, imx_param_update);
499         mutex_unlock(&dev->input_lock);
500         return ret;
501 }
502
503 static long imx_s_exposure(struct v4l2_subdev *sd,
504                                struct atomisp_exposure *exposure)
505 {
506         return imx_set_exposure_gain(sd, exposure->integration_time[0],
507                                 exposure->gain[0], exposure->gain[1]);
508 }
509
510 /* FIXME -To be updated with real OTP reading */
511 static int imx_g_priv_int_data(struct v4l2_subdev *sd,
512                                    struct v4l2_private_int_data *priv)
513 {
514         struct i2c_client *client = v4l2_get_subdevdata(sd);
515         struct imx_device *dev = to_imx_sensor(sd);
516         u8 __user *to = priv->data;
517         u32 read_size = priv->size;
518         int ret;
519
520         /* No need to copy data if size is 0 */
521         if (!read_size)
522                 goto out;
523
524         if (IS_ERR(dev->otp_data)) {
525                 dev_err(&client->dev, "OTP data not available");
526                 return PTR_ERR(dev->otp_data);
527         }
528         /* Correct read_size value only if bigger than maximum */
529         if (read_size > dev->otp_driver->size)
530                 read_size = dev->otp_driver->size;
531
532         ret = copy_to_user(to, dev->otp_data, read_size);
533         if (ret) {
534                 dev_err(&client->dev, "%s: failed to copy OTP data to user\n",
535                          __func__);
536                 return -EFAULT;
537         }
538 out:
539         /* Return correct size */
540         priv->size = dev->otp_driver->size;
541
542         return 0;
543 }
544
545 static int __imx_init(struct v4l2_subdev *sd, u32 val)
546 {
547         struct i2c_client *client = v4l2_get_subdevdata(sd);
548         struct imx_device *dev = to_imx_sensor(sd);
549         int lanes = imx_get_lanes(sd);
550         int ret;
551
552         if (dev->sensor_id == IMX_ID_DEFAULT)
553                 return 0;
554
555         /* The default is no flip at sensor initialization */
556         dev->h_flip->cur.val = 0;
557         dev->v_flip->cur.val = 0;
558         /* Sets the default FPS */
559         dev->fps_index = 0;
560         dev->curr_res_table = dev->mode_tables->res_preview;
561         dev->entries_curr_table = dev->mode_tables->n_res_preview;
562
563         ret = imx_write_reg_array(client, dev->mode_tables->init_settings);
564         if (ret)
565                 return ret;
566
567         if (dev->sensor_id == IMX132_ID && lanes > 0) {
568                 static const u8 imx132_rglanesel[] = {
569                         IMX132_RGLANESEL_1LANE,         /* 1 lane */
570                         IMX132_RGLANESEL_2LANES,        /* 2 lanes */
571                         IMX132_RGLANESEL_1LANE,         /* undefined */
572                         IMX132_RGLANESEL_4LANES,        /* 4 lanes */
573                 };
574                 ret = imx_write_reg(client, IMX_8BIT,
575                                 IMX132_RGLANESEL, imx132_rglanesel[lanes - 1]);
576         }
577
578         return ret;
579 }
580
581 static int imx_init(struct v4l2_subdev *sd, u32 val)
582 {
583         struct imx_device *dev = to_imx_sensor(sd);
584         int ret = 0;
585
586         mutex_lock(&dev->input_lock);
587         ret = __imx_init(sd, val);
588         mutex_unlock(&dev->input_lock);
589
590         return ret;
591 }
592
593 static long imx_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
594 {
595
596         switch (cmd) {
597         case ATOMISP_IOC_S_EXPOSURE:
598                 return imx_s_exposure(sd, arg);
599         case ATOMISP_IOC_G_SENSOR_PRIV_INT_DATA:
600                 return imx_g_priv_int_data(sd, arg);
601         default:
602                 return -EINVAL;
603         }
604         return 0;
605 }
606
607 static int power_up(struct v4l2_subdev *sd)
608 {
609         struct i2c_client *client = v4l2_get_subdevdata(sd);
610         struct imx_device *dev = to_imx_sensor(sd);
611         int ret;
612
613        /* power control */
614         ret = dev->platform_data->power_ctrl(sd, 1);
615         if (ret)
616                 goto fail_power;
617
618         /* flis clock control */
619         ret = dev->platform_data->flisclk_ctrl(sd, 1);
620         if (ret)
621                 goto fail_clk;
622
623         /* gpio ctrl */
624         ret = dev->platform_data->gpio_ctrl(sd, 1);
625         if (ret) {
626                 dev_err(&client->dev, "gpio failed\n");
627                 goto fail_gpio;
628         }
629
630         return 0;
631 fail_gpio:
632         dev->platform_data->gpio_ctrl(sd, 0);
633 fail_clk:
634         dev->platform_data->flisclk_ctrl(sd, 0);
635 fail_power:
636         dev->platform_data->power_ctrl(sd, 0);
637         dev_err(&client->dev, "sensor power-up failed\n");
638
639         return ret;
640 }
641
642 static int power_down(struct v4l2_subdev *sd)
643 {
644         struct imx_device *dev = to_imx_sensor(sd);
645         struct i2c_client *client = v4l2_get_subdevdata(sd);
646         int ret;
647
648         ret = dev->platform_data->flisclk_ctrl(sd, 0);
649         if (ret)
650                 dev_err(&client->dev, "flisclk failed\n");
651
652         /* gpio ctrl */
653         ret = dev->platform_data->gpio_ctrl(sd, 0);
654         if (ret)
655                 dev_err(&client->dev, "gpio failed\n");
656
657         /* power control */
658         ret = dev->platform_data->power_ctrl(sd, 0);
659         if (ret)
660                 dev_err(&client->dev, "vprog failed.\n");
661
662         return ret;
663 }
664
665 static int __imx_s_power(struct v4l2_subdev *sd, int on)
666 {
667         struct imx_device *dev = to_imx_sensor(sd);
668         int ret = 0;
669         int r = 0;
670
671         if (on == 0) {
672                 ret = power_down(sd);
673                 if (dev->vcm_driver && dev->vcm_driver->power_down)
674                         r = dev->vcm_driver->power_down(sd);
675                 if (ret == 0)
676                         ret = r;
677                 dev->power = 0;
678         } else {
679                 if (dev->vcm_driver && dev->vcm_driver->power_up)
680                         ret = dev->vcm_driver->power_up(sd);
681                 if (ret)
682                         return ret;
683                 ret = power_up(sd);
684                 if (!ret) {
685                         dev->power = 1;
686                         return __imx_init(sd, 0);
687                 }
688         }
689
690         return ret;
691 }
692
693 static int imx_s_power(struct v4l2_subdev *sd, int on)
694 {
695         int ret;
696         struct imx_device *dev = to_imx_sensor(sd);
697
698         mutex_lock(&dev->input_lock);
699         ret = __imx_s_power(sd, on);
700         mutex_unlock(&dev->input_lock);
701
702         return ret;
703 }
704
705 static int imx_get_intg_factor(struct i2c_client *client,
706                                 struct camera_mipi_info *info,
707                                 const struct imx_reg *reglist)
708 {
709         struct v4l2_subdev *sd = i2c_get_clientdata(client);
710         struct imx_device *dev = to_imx_sensor(sd);
711         int lanes = imx_get_lanes(sd);
712         u32 vt_pix_clk_div;
713         u32 vt_sys_clk_div;
714         u32 pre_pll_clk_div;
715         u32 pll_multiplier;
716
717         const int ext_clk_freq_hz = 19200000;
718         struct atomisp_sensor_mode_data *buf = &info->data;
719         int ret;
720         u16 data[IMX_INTG_BUF_COUNT];
721
722         u32 vt_pix_clk_freq_mhz;
723         u32 coarse_integration_time_min;
724         u32 coarse_integration_time_max_margin;
725         u32 read_mode;
726         u32 div;
727
728         if (info == NULL)
729                 return -EINVAL;
730
731         memset(data, 0, IMX_INTG_BUF_COUNT * sizeof(u16));
732         ret = imx_read_reg(client, 1, IMX_VT_PIX_CLK_DIV, data);
733         if (ret)
734                 return ret;
735         vt_pix_clk_div = data[0] & IMX_MASK_5BIT;
736
737         if (dev->sensor_id == IMX132_ID || dev->sensor_id == IMX208_ID) {
738                 static const int rgpltd[] = { 2, 4, 1, 1 };
739                 ret = imx_read_reg(client, 1, IMX132_208_VT_RGPLTD, data);
740                 if (ret)
741                         return ret;
742                 vt_sys_clk_div = rgpltd[data[0] & IMX_MASK_2BIT];
743         } else {
744                 ret = imx_read_reg(client, 1, IMX_VT_SYS_CLK_DIV, data);
745                 if (ret)
746                         return ret;
747                 vt_sys_clk_div = data[0] & IMX_MASK_2BIT;
748         }
749         ret = imx_read_reg(client, 1, IMX_PRE_PLL_CLK_DIV, data);
750         if (ret)
751                 return ret;
752         pre_pll_clk_div = data[0] & IMX_MASK_4BIT;
753
754         ret = imx_read_reg(client, 2,
755                 (dev->sensor_id == IMX132_ID ||
756                  dev->sensor_id == IMX219_ID ||
757                  dev->sensor_id == IMX208_ID) ?
758                 IMX132_208_219_PLL_MULTIPLIER : IMX_PLL_MULTIPLIER, data);
759         if (ret)
760                 return ret;
761         pll_multiplier = data[0] & IMX_MASK_11BIT;
762
763         memset(data, 0, IMX_INTG_BUF_COUNT * sizeof(u16));
764         ret = imx_read_reg(client, 4, IMX_COARSE_INTG_TIME_MIN, data);
765         if (ret)
766                 return ret;
767         coarse_integration_time_min = data[0];
768         coarse_integration_time_max_margin = data[1];
769
770         /* Get the cropping and output resolution to ISP for this mode. */
771         ret =  imx_read_reg(client, 2, dev->reg_addr->horizontal_start_h, data);
772         if (ret)
773                 return ret;
774         buf->crop_horizontal_start = data[0];
775
776         ret = imx_read_reg(client, 2, dev->reg_addr->vertical_start_h, data);
777         if (ret)
778                 return ret;
779         buf->crop_vertical_start = data[0];
780
781         ret = imx_read_reg(client, 2, dev->reg_addr->horizontal_end_h, data);
782         if (ret)
783                 return ret;
784         buf->crop_horizontal_end = data[0];
785
786         ret = imx_read_reg(client, 2, dev->reg_addr->vertical_end_h, data);
787         if (ret)
788                 return ret;
789         buf->crop_vertical_end = data[0];
790
791         ret = imx_read_reg(client, 2,
792                 dev->reg_addr->horizontal_output_size_h, data);
793         if (ret)
794                 return ret;
795         buf->output_width = data[0];
796
797         ret = imx_read_reg(client, 2,
798                 dev->reg_addr->vertical_output_size_h, data);
799         if (ret)
800                 return ret;
801         buf->output_height = data[0];
802
803         memset(data, 0, IMX_INTG_BUF_COUNT * sizeof(u16));
804         if (dev->sensor_id == IMX132_ID || dev->sensor_id == IMX208_ID ||
805                 dev->sensor_id == IMX219_ID)
806                 read_mode = 0;
807         else {
808                 if (dev->sensor_id == IMX227_ID)
809                         ret = imx_read_reg(client, 1, IMX227_READ_MODE, data);
810                 else
811                         ret = imx_read_reg(client, 1, IMX_READ_MODE, data);
812
813                 if (ret)
814                         return ret;
815                 read_mode = data[0] & IMX_MASK_2BIT;
816         }
817
818         div = pre_pll_clk_div*vt_sys_clk_div*vt_pix_clk_div;
819         if (div == 0)
820                 return -EINVAL;
821
822         if (dev->sensor_id == IMX132_ID || dev->sensor_id == IMX208_ID)
823                 vt_pix_clk_freq_mhz = ext_clk_freq_hz / div;
824         else if (dev->sensor_id == IMX227_ID) {
825                 /* according to IMX227 datasheet:
826                  * vt_pix_freq_mhz = * num_of_vt_lanes(4) * ivt_pix_clk_freq_mhz
827                  */
828                 vt_pix_clk_freq_mhz =
829                         (u64)4 * ext_clk_freq_hz * pll_multiplier;
830                 do_div(vt_pix_clk_freq_mhz, div);
831         } else
832                 vt_pix_clk_freq_mhz = 2 * ext_clk_freq_hz / div;
833
834         vt_pix_clk_freq_mhz *= pll_multiplier;
835         if (dev->sensor_id == IMX132_ID && lanes > 0)
836                 vt_pix_clk_freq_mhz *= lanes;
837
838         dev->vt_pix_clk_freq_mhz = vt_pix_clk_freq_mhz;
839
840         buf->vt_pix_clk_freq_mhz = vt_pix_clk_freq_mhz;
841         buf->coarse_integration_time_min = coarse_integration_time_min;
842         buf->coarse_integration_time_max_margin =
843                                 coarse_integration_time_max_margin;
844
845         buf->fine_integration_time_min = IMX_FINE_INTG_TIME;
846         buf->fine_integration_time_max_margin = IMX_FINE_INTG_TIME;
847         buf->fine_integration_time_def = IMX_FINE_INTG_TIME;
848         buf->frame_length_lines = dev->lines_per_frame;
849         buf->line_length_pck = dev->pixels_per_line;
850         buf->read_mode = read_mode;
851
852         if (dev->sensor_id == IMX132_ID || dev->sensor_id == IMX208_ID ||
853                 dev->sensor_id == IMX219_ID) {
854                 buf->binning_factor_x = 1;
855                 buf->binning_factor_y = 1;
856         } else {
857                 if (dev->sensor_id == IMX227_ID)
858                         ret = imx_read_reg(client, 1, IMX227_BINNING_ENABLE,
859                                 data);
860                 else
861                         ret = imx_read_reg(client, 1, IMX_BINNING_ENABLE, data);
862
863                 if (ret)
864                         return ret;
865                 /* 1:binning enabled, 0:disabled */
866                 if (data[0] == 1) {
867                         if (dev->sensor_id == IMX227_ID)
868                                 ret = imx_read_reg(client, 1,
869                                         IMX227_BINNING_TYPE, data);
870                         else
871                                 ret = imx_read_reg(client, 1,
872                                         IMX_BINNING_TYPE, data);
873
874                         if (ret)
875                                 return ret;
876                         buf->binning_factor_x = data[0] >> 4 & 0x0f;
877                         if (!buf->binning_factor_x)
878                                 buf->binning_factor_x = 1;
879                         buf->binning_factor_y = data[0] & 0xf;
880                         if (!buf->binning_factor_y)
881                                 buf->binning_factor_y = 1;
882                         /* WOWRKAROUND, NHD setting for IMX227 should have 4x4
883                          * binning but the register setting does not reflect
884                          * this, I am asking vendor why this happens. this is
885                          * workaround for INTEL BZ 216560.
886                          */
887                         if (dev->sensor_id == IMX227_ID) {
888                                 if (dev->curr_res_table[dev->fmt_idx].width ==
889                                         376 &&
890                                     dev->curr_res_table[dev->fmt_idx].height ==
891                                         656) {
892                                         buf->binning_factor_x = 4;
893                                         buf->binning_factor_y = 4;
894                                 }
895                         }
896                 } else {
897                         buf->binning_factor_x = 1;
898                         buf->binning_factor_y = 1;
899                 }
900         }
901
902         return 0;
903 }
904
905 /* This returns the exposure time being used. This should only be used
906    for filling in EXIF data, not for actual image processing. */
907 static int imx_q_exposure(struct v4l2_subdev *sd, s32 *value)
908 {
909         struct i2c_client *client = v4l2_get_subdevdata(sd);
910         struct imx_device *dev = to_imx_sensor(sd);
911         u16 coarse;
912         int ret;
913
914         /* the fine integration time is currently not calculated */
915         ret = imx_read_reg(client, IMX_16BIT,
916                 dev->reg_addr->coarse_integration_time, &coarse);
917         *value = coarse;
918
919         return ret;
920 }
921
922 static int imx_test_pattern(struct v4l2_subdev *sd)
923 {
924         struct i2c_client *client = v4l2_get_subdevdata(sd);
925         struct imx_device *dev = to_imx_sensor(sd);
926         int ret;
927
928         if (dev->power == 0)
929                 return 0;
930
931         ret = imx_write_reg(client, IMX_16BIT, IMX_TEST_PATTERN_COLOR_R,
932                 (u16)(dev->tp_r->val >> 22));
933         if (ret)
934                 return ret;
935
936         ret = imx_write_reg(client, IMX_16BIT, IMX_TEST_PATTERN_COLOR_GR,
937                 (u16)(dev->tp_gr->val >> 22));
938         if (ret)
939                 return ret;
940
941         ret = imx_write_reg(client, IMX_16BIT, IMX_TEST_PATTERN_COLOR_GB,
942                 (u16)(dev->tp_gb->val >> 22));
943         if (ret)
944                 return ret;
945
946         ret = imx_write_reg(client, IMX_16BIT, IMX_TEST_PATTERN_COLOR_B,
947                 (u16)(dev->tp_b->val >> 22));
948         if (ret)
949                 return ret;
950
951         return imx_write_reg(client, IMX_16BIT, IMX_TEST_PATTERN_MODE,
952                 (u16)(dev->tp_mode->val));
953 }
954
955 static u32 imx_translate_bayer_order(enum atomisp_bayer_order code)
956 {
957         switch (code) {
958         case atomisp_bayer_order_rggb:
959                 return MEDIA_BUS_FMT_SRGGB10_1X10;
960         case atomisp_bayer_order_grbg:
961                 return MEDIA_BUS_FMT_SGRBG10_1X10;
962         case atomisp_bayer_order_bggr:
963                 return MEDIA_BUS_FMT_SBGGR10_1X10;
964         case atomisp_bayer_order_gbrg:
965                 return MEDIA_BUS_FMT_SGBRG10_1X10;
966         }
967         return 0;
968 }
969
970 static int imx_v_flip(struct v4l2_subdev *sd, s32 value)
971 {
972         struct imx_device *dev = to_imx_sensor(sd);
973         struct camera_mipi_info *imx_info = NULL;
974         struct i2c_client *client = v4l2_get_subdevdata(sd);
975         int ret;
976         u16 val;
977
978         if (dev->power == 0)
979                 return -EIO;
980
981         ret = imx_write_reg_array(client, dev->param_hold);
982         if (ret)
983                 return ret;
984
985         ret = imx_read_reg(client, IMX_8BIT,
986                 dev->reg_addr->img_orientation, &val);
987         if (ret)
988                 return ret;
989         if (value)
990                 val |= IMX_VFLIP_BIT;
991         else
992                 val &= ~IMX_VFLIP_BIT;
993
994         ret = imx_write_reg(client, IMX_8BIT,
995                 dev->reg_addr->img_orientation, val);
996         if (ret)
997                 return ret;
998
999         imx_info = v4l2_get_subdev_hostdata(sd);
1000         if (imx_info) {
1001                 val &= (IMX_VFLIP_BIT|IMX_HFLIP_BIT);
1002                 imx_info->raw_bayer_order = imx_bayer_order_mapping[val];
1003                 dev->format.code = imx_translate_bayer_order(
1004                         imx_info->raw_bayer_order);
1005         }
1006
1007         return imx_write_reg_array(client, dev->param_update);
1008 }
1009
1010 static int imx_h_flip(struct v4l2_subdev *sd, s32 value)
1011 {
1012         struct imx_device *dev = to_imx_sensor(sd);
1013         struct camera_mipi_info *imx_info = NULL;
1014         struct i2c_client *client = v4l2_get_subdevdata(sd);
1015         int ret;
1016         u16 val;
1017
1018         if (dev->power == 0)
1019                 return -EIO;
1020
1021         ret = imx_write_reg_array(client, dev->param_hold);
1022         if (ret)
1023                 return ret;
1024         ret = imx_read_reg(client, IMX_8BIT,
1025                 dev->reg_addr->img_orientation, &val);
1026         if (ret)
1027                 return ret;
1028         if (value)
1029                 val |= IMX_HFLIP_BIT;
1030         else
1031                 val &= ~IMX_HFLIP_BIT;
1032         ret = imx_write_reg(client, IMX_8BIT,
1033                 dev->reg_addr->img_orientation, val);
1034         if (ret)
1035                 return ret;
1036
1037         imx_info = v4l2_get_subdev_hostdata(sd);
1038         if (imx_info) {
1039                 val &= (IMX_VFLIP_BIT|IMX_HFLIP_BIT);
1040                 imx_info->raw_bayer_order = imx_bayer_order_mapping[val];
1041                 dev->format.code = imx_translate_bayer_order(
1042                 imx_info->raw_bayer_order);
1043         }
1044
1045         return imx_write_reg_array(client, dev->param_update);
1046 }
1047
1048 static int imx_g_focal(struct v4l2_subdev *sd, s32 *val)
1049 {
1050         *val = (IMX_FOCAL_LENGTH_NUM << 16) | IMX_FOCAL_LENGTH_DEM;
1051         return 0;
1052 }
1053
1054 static int imx_g_fnumber(struct v4l2_subdev *sd, s32 *val)
1055 {
1056         /*const f number for imx*/
1057         *val = (IMX_F_NUMBER_DEFAULT_NUM << 16) | IMX_F_NUMBER_DEM;
1058         return 0;
1059 }
1060
1061 static int imx_g_fnumber_range(struct v4l2_subdev *sd, s32 *val)
1062 {
1063         *val = (IMX_F_NUMBER_DEFAULT_NUM << 24) |
1064                 (IMX_F_NUMBER_DEM << 16) |
1065                 (IMX_F_NUMBER_DEFAULT_NUM << 8) | IMX_F_NUMBER_DEM;
1066         return 0;
1067 }
1068
1069 static int imx_g_bin_factor_x(struct v4l2_subdev *sd, s32 *val)
1070 {
1071         struct imx_device *dev = to_imx_sensor(sd);
1072
1073         *val = dev->curr_res_table[dev->fmt_idx].bin_factor_x;
1074
1075         return 0;
1076 }
1077
1078 static int imx_g_bin_factor_y(struct v4l2_subdev *sd, s32 *val)
1079 {
1080         struct imx_device *dev = to_imx_sensor(sd);
1081
1082         *val = dev->curr_res_table[dev->fmt_idx].bin_factor_y;
1083
1084         return 0;
1085 }
1086
1087 static int imx_t_focus_abs(struct v4l2_subdev *sd, s32 value)
1088 {
1089         struct imx_device *dev = to_imx_sensor(sd);
1090         if (dev->vcm_driver && dev->vcm_driver->t_focus_abs)
1091                 return dev->vcm_driver->t_focus_abs(sd, value);
1092         return 0;
1093 }
1094
1095 static int imx_t_focus_rel(struct v4l2_subdev *sd, s32 value)
1096 {
1097         struct imx_device *dev = to_imx_sensor(sd);
1098         if (dev->vcm_driver && dev->vcm_driver->t_focus_rel)
1099                 return dev->vcm_driver->t_focus_rel(sd, value);
1100         return 0;
1101 }
1102
1103 static int imx_q_focus_status(struct v4l2_subdev *sd, s32 *value)
1104 {
1105         struct imx_device *dev = to_imx_sensor(sd);
1106         if (dev->vcm_driver && dev->vcm_driver->q_focus_status)
1107                 return dev->vcm_driver->q_focus_status(sd, value);
1108         return 0;
1109 }
1110
1111 static int imx_q_focus_abs(struct v4l2_subdev *sd, s32 *value)
1112 {
1113         struct imx_device *dev = to_imx_sensor(sd);
1114         if (dev->vcm_driver && dev->vcm_driver->q_focus_abs)
1115                 return dev->vcm_driver->q_focus_abs(sd, value);
1116         return 0;
1117 }
1118
1119 static int imx_t_vcm_slew(struct v4l2_subdev *sd, s32 value)
1120 {
1121         struct imx_device *dev = to_imx_sensor(sd);
1122         if (dev->vcm_driver && dev->vcm_driver->t_vcm_slew)
1123                 return dev->vcm_driver->t_vcm_slew(sd, value);
1124         return 0;
1125 }
1126
1127 static int imx_t_vcm_timing(struct v4l2_subdev *sd, s32 value)
1128 {
1129         struct imx_device *dev = to_imx_sensor(sd);
1130         if (dev->vcm_driver && dev->vcm_driver->t_vcm_timing)
1131                 return dev->vcm_driver->t_vcm_timing(sd, value);
1132         return 0;
1133 }
1134
1135 static int imx_s_ctrl(struct v4l2_ctrl *ctrl)
1136 {
1137         struct imx_device *dev = container_of(
1138                 ctrl->handler, struct imx_device, ctrl_handler);
1139         struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
1140         int ret = 0;
1141
1142         switch (ctrl->id) {
1143         case V4L2_CID_TEST_PATTERN:
1144                 ret = imx_test_pattern(&dev->sd);
1145                 break;
1146         case V4L2_CID_VFLIP:
1147                 dev_dbg(&client->dev, "%s: CID_VFLIP:%d.\n",
1148                         __func__, ctrl->val);
1149                 ret = imx_v_flip(&dev->sd, ctrl->val);
1150                 break;
1151         case V4L2_CID_HFLIP:
1152                 dev_dbg(&client->dev, "%s: CID_HFLIP:%d.\n",
1153                         __func__, ctrl->val);
1154                 ret = imx_h_flip(&dev->sd, ctrl->val);
1155                 break;
1156         case V4L2_CID_FOCUS_ABSOLUTE:
1157                 ret = imx_t_focus_abs(&dev->sd, ctrl->val);
1158                 break;
1159         case V4L2_CID_FOCUS_RELATIVE:
1160                 ret = imx_t_focus_rel(&dev->sd, ctrl->val);
1161                 break;
1162         case V4L2_CID_VCM_SLEW:
1163                 ret = imx_t_vcm_slew(&dev->sd, ctrl->val);
1164                 break;
1165         case V4L2_CID_VCM_TIMEING:
1166                 ret = imx_t_vcm_timing(&dev->sd, ctrl->val);
1167                 break;
1168         }
1169
1170         return ret;
1171 }
1172
1173 static int imx_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
1174 {
1175         struct imx_device *dev = container_of(
1176                 ctrl->handler, struct imx_device, ctrl_handler);
1177         int ret = 0;
1178         unsigned int val;
1179
1180         switch (ctrl->id) {
1181         case V4L2_CID_EXPOSURE_ABSOLUTE:
1182                 ret = imx_q_exposure(&dev->sd, &ctrl->val);
1183                 break;
1184         case V4L2_CID_FOCUS_ABSOLUTE:
1185                 ret = imx_q_focus_abs(&dev->sd, &ctrl->val);
1186                 break;
1187         case V4L2_CID_FOCUS_STATUS:
1188                 ret = imx_q_focus_status(&dev->sd, &ctrl->val);
1189                 break;
1190         case V4L2_CID_FOCAL_ABSOLUTE:
1191                 ret = imx_g_focal(&dev->sd, &ctrl->val);
1192                 break;
1193         case V4L2_CID_FNUMBER_ABSOLUTE:
1194                 ret = imx_g_fnumber(&dev->sd, &ctrl->val);
1195                 break;
1196         case V4L2_CID_FNUMBER_RANGE:
1197                 ret = imx_g_fnumber_range(&dev->sd, &ctrl->val);
1198                 break;
1199         case V4L2_CID_BIN_FACTOR_HORZ:
1200                 ret = imx_g_bin_factor_x(&dev->sd, &ctrl->val);
1201                 break;
1202         case V4L2_CID_BIN_FACTOR_VERT:
1203                 ret = imx_g_bin_factor_y(&dev->sd, &ctrl->val);
1204                 break;
1205         case V4L2_CID_VBLANK:
1206                 ctrl->val = dev->lines_per_frame -
1207                         dev->curr_res_table[dev->fmt_idx].height;
1208                 break;
1209         case V4L2_CID_HBLANK:
1210                 ctrl->val = dev->pixels_per_line -
1211                         dev->curr_res_table[dev->fmt_idx].width;
1212                 break;
1213         case V4L2_CID_PIXEL_RATE:
1214                 ctrl->val = dev->vt_pix_clk_freq_mhz;
1215                 break;
1216         case V4L2_CID_LINK_FREQ:
1217                 val = dev->curr_res_table[dev->fmt_idx].
1218                                         fps_options[dev->fps_index].mipi_freq;
1219                 if (val == 0)
1220                         val = dev->curr_res_table[dev->fmt_idx].mipi_freq;
1221                 if (val == 0)
1222                         return -EINVAL;
1223                 ctrl->val = val * 1000;                 /* To Hz */
1224                 break;
1225         default:
1226                 return -EINVAL;
1227         }
1228
1229         return ret;
1230 }
1231
1232 static const struct v4l2_ctrl_ops ctrl_ops = {
1233         .s_ctrl = imx_s_ctrl,
1234         .g_volatile_ctrl = imx_g_volatile_ctrl
1235 };
1236
1237 static const struct v4l2_ctrl_config imx_controls[] = {
1238         {
1239                 .ops = &ctrl_ops,
1240                 .id = V4L2_CID_EXPOSURE_ABSOLUTE,
1241                 .type = V4L2_CTRL_TYPE_INTEGER,
1242                 .name = "exposure",
1243                 .min = 0x0,
1244                 .max = 0xffff,
1245                 .step = 0x01,
1246                 .def = 0x00,
1247                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1248         },
1249         {
1250                 .ops = &ctrl_ops,
1251                 .id = V4L2_CID_TEST_PATTERN,
1252                 .type = V4L2_CTRL_TYPE_INTEGER,
1253                 .name = "Test pattern",
1254                 .min = 0,
1255                 .max = 0xffff,
1256                 .step = 1,
1257                 .def = 0,
1258         },
1259         {
1260                 .ops = &ctrl_ops,
1261                 .id = V4L2_CID_TEST_PATTERN_COLOR_R,
1262                 .type = V4L2_CTRL_TYPE_INTEGER,
1263                 .name = "Test pattern solid color R",
1264                 .min = INT_MIN,
1265                 .max = INT_MAX,
1266                 .step = 1,
1267                 .def = 0,
1268         },
1269         {
1270                 .ops = &ctrl_ops,
1271                 .id = V4L2_CID_TEST_PATTERN_COLOR_GR,
1272                 .type = V4L2_CTRL_TYPE_INTEGER,
1273                 .name = "Test pattern solid color GR",
1274                 .min = INT_MIN,
1275                 .max = INT_MAX,
1276                 .step = 1,
1277                 .def = 0,
1278         },
1279         {
1280                 .ops = &ctrl_ops,
1281                 .id = V4L2_CID_TEST_PATTERN_COLOR_GB,
1282                 .type = V4L2_CTRL_TYPE_INTEGER,
1283                 .name = "Test pattern solid color GB",
1284                 .min = INT_MIN,
1285                 .max = INT_MAX,
1286                 .step = 1,
1287                 .def = 0,
1288         },
1289         {
1290                 .ops = &ctrl_ops,
1291                 .id = V4L2_CID_TEST_PATTERN_COLOR_B,
1292                 .type = V4L2_CTRL_TYPE_INTEGER,
1293                 .name = "Test pattern solid color B",
1294                 .min = INT_MIN,
1295                 .max = INT_MAX,
1296                 .step = 1,
1297                 .def = 0,
1298         },
1299         {
1300                 .ops = &ctrl_ops,
1301                 .id = V4L2_CID_VFLIP,
1302                 .type = V4L2_CTRL_TYPE_BOOLEAN,
1303                 .name = "Flip",
1304                 .min = 0,
1305                 .max = 1,
1306                 .step = 1,
1307                 .def = 0,
1308         },
1309         {
1310                 .ops = &ctrl_ops,
1311                 .id = V4L2_CID_HFLIP,
1312                 .type = V4L2_CTRL_TYPE_BOOLEAN,
1313                 .name = "Mirror",
1314                 .min = 0,
1315                 .max = 1,
1316                 .step = 1,
1317                 .def = 0,
1318         },
1319         {
1320                 .ops = &ctrl_ops,
1321                 .id = V4L2_CID_FOCUS_ABSOLUTE,
1322                 .type = V4L2_CTRL_TYPE_INTEGER,
1323                 .name = "focus move absolute",
1324                 .min = 0,
1325                 .max = IMX_MAX_FOCUS_POS,
1326                 .step = 1,
1327                 .def = 0,
1328                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1329         },
1330         {
1331                 .ops = &ctrl_ops,
1332                 .id = V4L2_CID_FOCUS_RELATIVE,
1333                 .type = V4L2_CTRL_TYPE_INTEGER,
1334                 .name = "focus move relative",
1335                 .min = IMX_MAX_FOCUS_NEG,
1336                 .max = IMX_MAX_FOCUS_POS,
1337                 .step = 1,
1338                 .def = 0,
1339                 .flags = 0,
1340         },
1341         {
1342                 .ops = &ctrl_ops,
1343                 .id = V4L2_CID_FOCUS_STATUS,
1344                 .type = V4L2_CTRL_TYPE_INTEGER,
1345                 .name = "focus status",
1346                 .min = 0,
1347                 .max = 100, /* allow enum to grow in the future */
1348                 .step = 1,
1349                 .def = 0,
1350                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1351         },
1352         {
1353                 .ops = &ctrl_ops,
1354                 .id = V4L2_CID_VCM_SLEW,
1355                 .type = V4L2_CTRL_TYPE_INTEGER,
1356                 .name = "vcm slew",
1357                 .min = 0,
1358                 .max = IMX_VCM_SLEW_STEP_MAX,
1359                 .step = 1,
1360                 .def = 0,
1361                 .flags = 0,
1362         },
1363         {
1364                 .ops = &ctrl_ops,
1365                 .id = V4L2_CID_VCM_TIMEING,
1366                 .type = V4L2_CTRL_TYPE_INTEGER,
1367                 .name = "vcm step time",
1368                 .min = 0,
1369                 .max = IMX_VCM_SLEW_TIME_MAX,
1370                 .step = 1,
1371                 .def = 0,
1372                 .flags = 0,
1373         },
1374         {
1375                 .ops = &ctrl_ops,
1376                 .id = V4L2_CID_FOCAL_ABSOLUTE,
1377                 .type = V4L2_CTRL_TYPE_INTEGER,
1378                 .name = "focal length",
1379                 .min = IMX_FOCAL_LENGTH_DEFAULT,
1380                 .max = IMX_FOCAL_LENGTH_DEFAULT,
1381                 .step = 0x01,
1382                 .def = IMX_FOCAL_LENGTH_DEFAULT,
1383                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1384         },
1385         {
1386                 .ops = &ctrl_ops,
1387                 .id = V4L2_CID_FNUMBER_ABSOLUTE,
1388                 .type = V4L2_CTRL_TYPE_INTEGER,
1389                 .name = "f-number",
1390                 .min = IMX_F_NUMBER_DEFAULT,
1391                 .max = IMX_F_NUMBER_DEFAULT,
1392                 .step = 0x01,
1393                 .def = IMX_F_NUMBER_DEFAULT,
1394                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1395         },
1396         {
1397                 .ops = &ctrl_ops,
1398                 .id = V4L2_CID_FNUMBER_RANGE,
1399                 .type = V4L2_CTRL_TYPE_INTEGER,
1400                 .name = "f-number range",
1401                 .min = IMX_F_NUMBER_RANGE,
1402                 .max =  IMX_F_NUMBER_RANGE,
1403                 .step = 0x01,
1404                 .def = IMX_F_NUMBER_RANGE,
1405                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1406         },
1407         {
1408                 .ops = &ctrl_ops,
1409                 .id = V4L2_CID_BIN_FACTOR_HORZ,
1410                 .type = V4L2_CTRL_TYPE_INTEGER,
1411                 .name = "horizontal binning factor",
1412                 .min = 0,
1413                 .max = IMX_BIN_FACTOR_MAX,
1414                 .step = 1,
1415                 .def = 0,
1416                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1417         },
1418         {
1419                 .ops = &ctrl_ops,
1420                 .id = V4L2_CID_BIN_FACTOR_VERT,
1421                 .type = V4L2_CTRL_TYPE_INTEGER,
1422                 .name = "vertical binning factor",
1423                 .min = 0,
1424                 .max = IMX_BIN_FACTOR_MAX,
1425                 .step = 1,
1426                 .def = 0,
1427                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1428         },
1429         {
1430                 .ops = &ctrl_ops,
1431                 .id = V4L2_CID_LINK_FREQ,
1432                 .name = "Link Frequency",
1433                 .type = V4L2_CTRL_TYPE_INTEGER,
1434                 .min = 1,
1435                 .max = 1500000 * 1000,
1436                 .step = 1,
1437                 .def = 1,
1438                 .flags = V4L2_CTRL_FLAG_VOLATILE | V4L2_CTRL_FLAG_READ_ONLY,
1439         },
1440         {
1441                 .ops = &ctrl_ops,
1442                 .id = V4L2_CID_PIXEL_RATE,
1443                 .name = "Pixel Rate",
1444                 .type = V4L2_CTRL_TYPE_INTEGER,
1445                 .min = 0,
1446                 .max = INT_MAX,
1447                 .step = 1,
1448                 .def = 0,
1449                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1450         },
1451         {
1452                 .ops = &ctrl_ops,
1453                 .id = V4L2_CID_HBLANK,
1454                 .name = "Horizontal Blanking",
1455                 .type = V4L2_CTRL_TYPE_INTEGER,
1456                 .min = 0,
1457                 .max = SHRT_MAX,
1458                 .step = 1,
1459                 .def = 0,
1460                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1461         },
1462         {
1463                 .ops = &ctrl_ops,
1464                 .id = V4L2_CID_VBLANK,
1465                 .name = "Vertical Blanking",
1466                 .type = V4L2_CTRL_TYPE_INTEGER,
1467                 .min = 0,
1468                 .max = SHRT_MAX,
1469                 .step = 1,
1470                 .def = 0,
1471                 .flags = V4L2_CTRL_FLAG_VOLATILE,
1472         },
1473         {
1474                 .ops = &ctrl_ops,
1475                 .id = V4L2_CID_HFLIP,
1476                 .name = "Horizontal Flip",
1477                 .type = V4L2_CTRL_TYPE_INTEGER,
1478                 .min = 0,
1479                 .max = 1,
1480                 .step = 1,
1481                 .def = 0,
1482                 .flags = 0,
1483         },
1484         {
1485                 .ops = &ctrl_ops,
1486                 .id = V4L2_CID_VFLIP,
1487                 .name = "Vertical Flip",
1488                 .type = V4L2_CTRL_TYPE_INTEGER,
1489                 .min = 0,
1490                 .max = 1,
1491                 .step = 1,
1492                 .def = 0,
1493                 .flags = 0,
1494         },
1495 };
1496
1497 /*
1498  * distance - calculate the distance
1499  * @res: resolution
1500  * @w: width
1501  * @h: height
1502  *
1503  * Get the gap between resolution and w/h.
1504  * res->width/height smaller than w/h wouldn't be considered.
1505  * Returns the value of gap or -1 if fail.
1506  */
1507 #define LARGEST_ALLOWED_RATIO_MISMATCH 600
1508 static int distance(struct imx_resolution const *res, u32 w, u32 h,
1509                 bool keep_ratio)
1510 {
1511         unsigned int w_ratio;
1512         unsigned int h_ratio;
1513         int match;
1514         unsigned int allowed_ratio_mismatch = LARGEST_ALLOWED_RATIO_MISMATCH;
1515
1516         if (!keep_ratio)
1517                 allowed_ratio_mismatch = ~0;
1518
1519         if (w == 0)
1520                 return -1;
1521         w_ratio = (res->width << 13) / w;
1522         if (h == 0)
1523                 return -1;
1524         h_ratio = (res->height << 13) / h;
1525         if (h_ratio == 0)
1526                 return -1;
1527         match   = abs(((w_ratio << 13) / h_ratio) - ((int)8192));
1528
1529         if ((w_ratio < (int)8192) || (h_ratio < (int)8192)  ||
1530                 (match > allowed_ratio_mismatch))
1531                 return -1;
1532
1533         return w_ratio + h_ratio;
1534 }
1535
1536 /* Return the nearest higher resolution index */
1537 static int nearest_resolution_index(struct v4l2_subdev *sd, int w, int h)
1538 {
1539         int i;
1540         int idx = -1;
1541         int dist;
1542         int fps_diff;
1543         int min_fps_diff = INT_MAX;
1544         int min_dist = INT_MAX;
1545         const struct imx_resolution *tmp_res = NULL;
1546         struct imx_device *dev = to_imx_sensor(sd);
1547         bool again = 1;
1548 retry:
1549         for (i = 0; i < dev->entries_curr_table; i++) {
1550                 tmp_res = &dev->curr_res_table[i];
1551                 dist = distance(tmp_res, w, h, again);
1552                 if (dist == -1)
1553                         continue;
1554                 if (dist < min_dist) {
1555                         min_dist = dist;
1556                         idx = i;
1557                 }
1558                 if (dist == min_dist) {
1559                         fps_diff = __imx_min_fps_diff(dev->targetfps,
1560                                                 tmp_res->fps_options);
1561                         if (fps_diff < min_fps_diff) {
1562                                 min_fps_diff = fps_diff;
1563                                 idx = i;
1564                         }
1565                 }
1566         }
1567
1568         /*
1569          * FIXME!
1570          * only IMX135 for Saltbay and IMX227 use this algorithm
1571          */
1572         if (idx == -1 && again == true && dev->new_res_sel_method) {
1573                 again = false;
1574                 goto retry;
1575         }
1576         return idx;
1577 }
1578
1579 /* Call with ctrl_handler.lock hold */
1580 static int __adjust_hvblank(struct v4l2_subdev *sd)
1581 {
1582         struct i2c_client *client = v4l2_get_subdevdata(sd);
1583         struct imx_device *dev = to_imx_sensor(sd);
1584         u16 new_frame_length_lines, new_line_length_pck;
1585         int ret;
1586
1587         /*
1588          * No need to adjust h/v blank if not set dbg value
1589          * Note that there is no other checking on the h/v blank value,
1590          * as h/v blank can be set to any value above zero for debug purpose
1591          */
1592         if (!dev->v_blank->val || !dev->h_blank->val)
1593                 return 0;
1594
1595         new_frame_length_lines = dev->curr_res_table[dev->fmt_idx].height +
1596                 dev->v_blank->val;
1597         new_line_length_pck = dev->curr_res_table[dev->fmt_idx].width +
1598                 dev->h_blank->val;
1599
1600         ret = imx_write_reg(client, IMX_16BIT,
1601                 dev->reg_addr->line_length_pixels, new_line_length_pck);
1602         if (ret)
1603                 return ret;
1604         ret = imx_write_reg(client, IMX_16BIT,
1605                 dev->reg_addr->frame_length_lines, new_frame_length_lines);
1606         if (ret)
1607                 return ret;
1608
1609         dev->lines_per_frame = new_frame_length_lines;
1610         dev->pixels_per_line = new_line_length_pck;
1611
1612         return 0;
1613 }
1614
1615 static int imx_set_fmt(struct v4l2_subdev *sd,
1616                        struct v4l2_subdev_pad_config *cfg,
1617                        struct v4l2_subdev_format *format)
1618 {
1619         struct v4l2_mbus_framefmt *fmt = &format->format;
1620         struct imx_device *dev = to_imx_sensor(sd);
1621         struct camera_mipi_info *imx_info = NULL;
1622         struct i2c_client *client = v4l2_get_subdevdata(sd);
1623         const struct imx_resolution *res;
1624         int lanes = imx_get_lanes(sd);
1625         int ret;
1626         u16 data, val;
1627          int idx;
1628         if (format->pad)
1629                 return -EINVAL;
1630         if (!fmt)
1631                 return -EINVAL;
1632
1633         imx_info = v4l2_get_subdev_hostdata(sd);
1634         if (imx_info == NULL)
1635                 return -EINVAL;
1636         if ((fmt->width > imx_max_res[dev->sensor_id].res_max_width)
1637                 || (fmt->height > imx_max_res[dev->sensor_id].res_max_height)) {
1638                 fmt->width =  imx_max_res[dev->sensor_id].res_max_width;
1639                 fmt->height = imx_max_res[dev->sensor_id].res_max_height;
1640         } else {
1641                 idx = nearest_resolution_index(sd, fmt->width, fmt->height);
1642
1643                 /*
1644                  * nearest_resolution_index() doesn't return smaller
1645                  *  resolutions. If it fails, it means the requested
1646                  *  resolution is higher than wecan support. Fallback
1647                  *  to highest possible resolution in this case.
1648                  */
1649                 if (idx == -1)
1650                         idx = dev->entries_curr_table - 1;
1651
1652                 fmt->width = dev->curr_res_table[idx].width;
1653                 fmt->height = dev->curr_res_table[idx].height;
1654         }
1655
1656         fmt->code = dev->format.code;
1657     if(format->which == V4L2_SUBDEV_FORMAT_TRY) {
1658                 cfg->try_fmt = *fmt;
1659                 return 0;
1660         }
1661         mutex_lock(&dev->input_lock);
1662
1663         dev->fmt_idx = nearest_resolution_index(sd, fmt->width, fmt->height);
1664         if (dev->fmt_idx == -1) {
1665                 ret = -EINVAL;
1666                 goto out;
1667         }
1668         res = &dev->curr_res_table[dev->fmt_idx];
1669
1670         /* Adjust the FPS selection based on the resolution selected */
1671         dev->fps_index = __imx_nearest_fps_index(dev->targetfps,
1672                                                 res->fps_options);
1673         dev->fps = res->fps_options[dev->fps_index].fps;
1674         dev->regs = res->fps_options[dev->fps_index].regs;
1675         if (!dev->regs)
1676                 dev->regs = res->regs;
1677
1678         ret = imx_write_reg_array(client, dev->regs);
1679         if (ret)
1680                 goto out;
1681
1682         if (dev->sensor_id == IMX132_ID && lanes > 0) {
1683                 static const u8 imx132_rgpltd[] = {
1684                         2,              /* 1 lane:  /1 */
1685                         0,              /* 2 lanes: /2 */
1686                         0,              /* undefined   */
1687                         1,              /* 4 lanes: /4 */
1688                 };
1689                 ret = imx_write_reg(client, IMX_8BIT, IMX132_208_VT_RGPLTD,
1690                                     imx132_rgpltd[lanes - 1]);
1691                 if (ret)
1692                         goto out;
1693         }
1694
1695         dev->pixels_per_line = res->fps_options[dev->fps_index].pixels_per_line;
1696         dev->lines_per_frame = res->fps_options[dev->fps_index].lines_per_frame;
1697
1698         /* dbg h/v blank time */
1699         __adjust_hvblank(sd);
1700
1701         ret = __imx_update_exposure_timing(client, dev->coarse_itg,
1702                 dev->pixels_per_line, dev->lines_per_frame);
1703         if (ret)
1704                 goto out;
1705
1706         ret = __imx_update_gain(sd, dev->gain);
1707         if (ret)
1708                 goto out;
1709
1710         ret = __imx_update_digital_gain(client, dev->digital_gain);
1711         if (ret)
1712                 goto out;
1713
1714         ret = imx_write_reg_array(client, dev->param_update);
1715         if (ret)
1716                 goto out;
1717
1718         ret = imx_get_intg_factor(client, imx_info, dev->regs);
1719         if (ret)
1720                 goto out;
1721
1722         ret = imx_read_reg(client, IMX_8BIT,
1723                 dev->reg_addr->img_orientation, &val);
1724         if (ret)
1725                 goto out;
1726         val &= (IMX_VFLIP_BIT|IMX_HFLIP_BIT);
1727         imx_info->raw_bayer_order = imx_bayer_order_mapping[val];
1728         dev->format.code = imx_translate_bayer_order(
1729                 imx_info->raw_bayer_order);
1730
1731         /*
1732          * Fill meta data info. add imx135 metadata setting for RAW10 format
1733          */
1734         switch (dev->sensor_id) {
1735         case IMX135_ID:
1736                 ret = imx_read_reg(client, 2,
1737                                 IMX135_OUTPUT_DATA_FORMAT_REG, &data);
1738                 if (ret)
1739                         goto out;
1740                 /*
1741                  * The IMX135 can support various resolutions like
1742                  * RAW6/8/10/12/14.
1743                  * 1.The data format is RAW10:
1744                  *   matadata width = current resolution width(pixel) * 10 / 8
1745                  * 2.The data format is RAW6 or RAW8:
1746                  *   matadata width = current resolution width(pixel);
1747                  * 3.other data format(RAW12/14 etc):
1748                  *   TBD.
1749                  */
1750                 if (data == IMX135_OUTPUT_FORMAT_RAW10)
1751                         /* the data format is RAW10. */
1752                         imx_info->metadata_width = res->width * 10 / 8;
1753                 else
1754                         /* The data format is RAW6/8/12/14/ etc. */
1755                         imx_info->metadata_width = res->width;
1756
1757                 imx_info->metadata_height = IMX135_EMBEDDED_DATA_LINE_NUM;
1758
1759                 if (imx_info->metadata_effective_width == NULL)
1760                         imx_info->metadata_effective_width =
1761                                 imx135_embedded_effective_size;
1762
1763                 break;
1764         case IMX227_ID:
1765                 ret = imx_read_reg(client, 2, IMX227_OUTPUT_DATA_FORMAT_REG,
1766                         &data);
1767                 if (ret)
1768                         goto out;
1769                 if (data == IMX227_OUTPUT_FORMAT_RAW10)
1770                         /* the data format is RAW10. */
1771                         imx_info->metadata_width = res->width * 10 / 8;
1772                 else
1773                         /* The data format is RAW6/8/12/14/ etc. */
1774                         imx_info->metadata_width = res->width;
1775
1776                 imx_info->metadata_height = IMX227_EMBEDDED_DATA_LINE_NUM;
1777
1778                 if (imx_info->metadata_effective_width == NULL)
1779                         imx_info->metadata_effective_width =
1780                                 imx227_embedded_effective_size;
1781
1782                 break;
1783         default:
1784                 imx_info->metadata_width = 0;
1785                 imx_info->metadata_height = 0;
1786                 imx_info->metadata_effective_width = NULL;
1787                 break;
1788         }
1789
1790 out:
1791         mutex_unlock(&dev->input_lock);
1792         return ret;
1793 }
1794
1795
1796 static int imx_get_fmt(struct v4l2_subdev *sd,
1797                        struct v4l2_subdev_pad_config *cfg,
1798                        struct v4l2_subdev_format *format)
1799 {
1800         struct v4l2_mbus_framefmt *fmt = &format->format;
1801         struct imx_device *dev = to_imx_sensor(sd);
1802
1803         if (format->pad)
1804                 return -EINVAL;
1805         if (!fmt)
1806                 return -EINVAL;
1807
1808         mutex_lock(&dev->input_lock);
1809         fmt->width = dev->curr_res_table[dev->fmt_idx].width;
1810         fmt->height = dev->curr_res_table[dev->fmt_idx].height;
1811         fmt->code = dev->format.code;
1812         mutex_unlock(&dev->input_lock);
1813         return 0;
1814 }
1815
1816 static int imx_detect(struct i2c_client *client, u16 *id, u8 *revision)
1817 {
1818         struct i2c_adapter *adapter = client->adapter;
1819
1820         /* i2c check */
1821         if (!i2c_check_functionality(adapter, I2C_FUNC_I2C))
1822                 return -ENODEV;
1823
1824         /* check sensor chip ID  */
1825         if (imx_read_reg(client, IMX_16BIT, IMX132_175_208_219_CHIP_ID, id)) {
1826                 v4l2_err(client, "sensor_id = 0x%x\n", *id);
1827                 return -ENODEV;
1828         }
1829
1830         if (*id == IMX132_ID || *id == IMX175_ID ||
1831                 *id == IMX208_ID || *id == IMX219_ID)
1832                 goto found;
1833
1834         if (imx_read_reg(client, IMX_16BIT, IMX134_135_227_CHIP_ID, id)) {
1835                 v4l2_err(client, "sensor_id = 0x%x\n", *id);
1836                 return -ENODEV;
1837         }
1838         if (*id != IMX134_ID && *id != IMX135_ID && *id != IMX227_ID) {
1839                 v4l2_err(client, "no imx sensor found\n");
1840                 return -ENODEV;
1841         }
1842 found:
1843         v4l2_info(client, "sensor_id = 0x%x\n", *id);
1844
1845         /* TODO - need to be updated */
1846         *revision = 0;
1847
1848         return 0;
1849 }
1850
1851 static void __imx_print_timing(struct v4l2_subdev *sd)
1852 {
1853         struct imx_device *dev = to_imx_sensor(sd);
1854         struct i2c_client *client = v4l2_get_subdevdata(sd);
1855         u16 width = dev->curr_res_table[dev->fmt_idx].width;
1856         u16 height = dev->curr_res_table[dev->fmt_idx].height;
1857
1858         dev_dbg(&client->dev, "Dump imx timing in stream on:\n");
1859         dev_dbg(&client->dev, "width: %d:\n", width);
1860         dev_dbg(&client->dev, "height: %d:\n", height);
1861         dev_dbg(&client->dev, "pixels_per_line: %d:\n", dev->pixels_per_line);
1862         dev_dbg(&client->dev, "line per frame: %d:\n", dev->lines_per_frame);
1863         dev_dbg(&client->dev, "pix freq: %d:\n", dev->vt_pix_clk_freq_mhz);
1864         dev_dbg(&client->dev, "init fps: %d:\n", dev->vt_pix_clk_freq_mhz /
1865                         dev->pixels_per_line / dev->lines_per_frame);
1866         dev_dbg(&client->dev, "HBlank: %d nS:\n",
1867                         1000 * (dev->pixels_per_line - width) /
1868                         (dev->vt_pix_clk_freq_mhz / 1000000));
1869         dev_dbg(&client->dev, "VBlank: %d uS:\n",
1870                         (dev->lines_per_frame - height) * dev->pixels_per_line /
1871                         (dev->vt_pix_clk_freq_mhz / 1000000));
1872 }
1873
1874 /*
1875  * imx stream on/off
1876  */
1877 static int imx_s_stream(struct v4l2_subdev *sd, int enable)
1878 {
1879         int ret;
1880         struct i2c_client *client = v4l2_get_subdevdata(sd);
1881         struct imx_device *dev = to_imx_sensor(sd);
1882
1883         mutex_lock(&dev->input_lock);
1884         if (enable) {
1885                 /* Noise reduction & dead pixel applied before streaming */
1886                 if (dev->fw == NULL) {
1887                         dev_warn(&client->dev, "No MSR loaded from library");
1888                 } else {
1889                         ret = apply_msr_data(client, dev->fw);
1890                         if (ret) {
1891                                 mutex_unlock(&dev->input_lock);
1892                                 return ret;
1893                         }
1894                 }
1895                 ret = imx_test_pattern(sd);
1896                 if (ret) {
1897                         v4l2_err(client, "Configure test pattern failed.\n");
1898                         mutex_unlock(&dev->input_lock);
1899                         return ret;
1900                 }
1901                 __imx_print_timing(sd);
1902                 ret = imx_write_reg_array(client, imx_streaming);
1903                 if (ret != 0) {
1904                         v4l2_err(client, "write_reg_array err\n");
1905                         mutex_unlock(&dev->input_lock);
1906                         return ret;
1907                 }
1908                 dev->streaming = 1;
1909                 if (dev->vcm_driver && dev->vcm_driver->t_focus_abs_init)
1910                         dev->vcm_driver->t_focus_abs_init(sd);
1911         } else {
1912                 ret = imx_write_reg_array(client, imx_soft_standby);
1913                 if (ret != 0) {
1914                         v4l2_err(client, "write_reg_array err\n");
1915                         mutex_unlock(&dev->input_lock);
1916                         return ret;
1917                 }
1918                 dev->streaming = 0;
1919                 dev->targetfps = 0;
1920         }
1921         mutex_unlock(&dev->input_lock);
1922
1923         return 0;
1924 }
1925
1926 static int __update_imx_device_settings(struct imx_device *dev, u16 sensor_id)
1927 {
1928         /* IMX on other platform is not supported yet */
1929         return -EINVAL;
1930 }
1931
1932 static int imx_s_config(struct v4l2_subdev *sd,
1933                             int irq, void *pdata)
1934 {
1935         struct imx_device *dev = to_imx_sensor(sd);
1936         struct i2c_client *client = v4l2_get_subdevdata(sd);
1937         u8 sensor_revision;
1938         u16 sensor_id;
1939         int ret;
1940         if (pdata == NULL)
1941                 return -ENODEV;
1942
1943         dev->platform_data = pdata;
1944
1945         mutex_lock(&dev->input_lock);
1946
1947         if (dev->platform_data->platform_init) {
1948                 ret = dev->platform_data->platform_init(client);
1949                 if (ret) {
1950                         mutex_unlock(&dev->input_lock);
1951                         dev_err(&client->dev, "imx platform init err\n");
1952                         return ret;
1953                 }
1954         }
1955         /*
1956          * power off the module first.
1957          *
1958          * As first power on by board have undecided state of power/gpio pins.
1959          */
1960         ret = __imx_s_power(sd, 0);
1961         if (ret) {
1962                 v4l2_err(client, "imx power-down err.\n");
1963                 mutex_unlock(&dev->input_lock);
1964                 return ret;
1965         }
1966
1967         ret = __imx_s_power(sd, 1);
1968         if (ret) {
1969                 v4l2_err(client, "imx power-up err.\n");
1970                 mutex_unlock(&dev->input_lock);
1971                 return ret;
1972         }
1973
1974         ret = dev->platform_data->csi_cfg(sd, 1);
1975         if (ret)
1976                 goto fail_csi_cfg;
1977
1978         /* config & detect sensor */
1979         ret = imx_detect(client, &sensor_id, &sensor_revision);
1980         if (ret) {
1981                 v4l2_err(client, "imx_detect err s_config.\n");
1982                 goto fail_detect;
1983         }
1984
1985         dev->sensor_id = sensor_id;
1986         dev->sensor_revision = sensor_revision;
1987
1988         /* Resolution settings depend on sensor type and platform */
1989         ret = __update_imx_device_settings(dev, dev->sensor_id);
1990         if (ret)
1991                 goto fail_detect;
1992         /* Read sensor's OTP data */
1993         dev->otp_data = dev->otp_driver->otp_read(sd,
1994                 dev->otp_driver->dev_addr, dev->otp_driver->start_addr,
1995                 dev->otp_driver->size);
1996
1997         /* power off sensor */
1998         ret = __imx_s_power(sd, 0);
1999
2000         mutex_unlock(&dev->input_lock);
2001         if (ret)
2002                 v4l2_err(client, "imx power-down err.\n");
2003
2004         return ret;
2005
2006 fail_detect:
2007         dev->platform_data->csi_cfg(sd, 0);
2008 fail_csi_cfg:
2009         __imx_s_power(sd, 0);
2010         if (dev->platform_data->platform_deinit)
2011                 dev->platform_data->platform_deinit();
2012         mutex_unlock(&dev->input_lock);
2013         dev_err(&client->dev, "sensor power-gating failed\n");
2014         return ret;
2015 }
2016
2017 static int
2018 imx_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_pad_config *cfg,
2019                    struct v4l2_subdev_mbus_code_enum *code)
2020 {
2021         struct imx_device *dev = to_imx_sensor(sd);
2022         if (code->index >= MAX_FMTS)
2023                 return -EINVAL;
2024
2025         mutex_lock(&dev->input_lock);
2026         code->code = dev->format.code;
2027         mutex_unlock(&dev->input_lock);
2028         return 0;
2029 }
2030
2031 static int
2032 imx_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_pad_config *cfg,
2033                     struct v4l2_subdev_frame_size_enum *fse)
2034 {
2035         int index = fse->index;
2036         struct imx_device *dev = to_imx_sensor(sd);
2037
2038         mutex_lock(&dev->input_lock);
2039         if (index >= dev->entries_curr_table) {
2040                 mutex_unlock(&dev->input_lock);
2041                 return -EINVAL;
2042         }
2043
2044         fse->min_width = dev->curr_res_table[index].width;
2045         fse->min_height = dev->curr_res_table[index].height;
2046         fse->max_width = dev->curr_res_table[index].width;
2047         fse->max_height = dev->curr_res_table[index].height;
2048         mutex_unlock(&dev->input_lock);
2049         return 0;
2050 }
2051
2052 static int
2053 imx_s_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *param)
2054 {
2055         struct imx_device *dev = to_imx_sensor(sd);
2056
2057         mutex_lock(&dev->input_lock);
2058         dev->run_mode = param->parm.capture.capturemode;
2059
2060         switch (dev->run_mode) {
2061         case CI_MODE_VIDEO:
2062                 dev->curr_res_table = dev->mode_tables->res_video;
2063                 dev->entries_curr_table = dev->mode_tables->n_res_video;
2064                 break;
2065         case CI_MODE_STILL_CAPTURE:
2066                 dev->curr_res_table = dev->mode_tables->res_still;
2067                 dev->entries_curr_table = dev->mode_tables->n_res_still;
2068                 break;
2069         default:
2070                 dev->curr_res_table = dev->mode_tables->res_preview;
2071                 dev->entries_curr_table = dev->mode_tables->n_res_preview;
2072         }
2073         mutex_unlock(&dev->input_lock);
2074         return 0;
2075 }
2076
2077 static int imx_g_frame_interval(struct v4l2_subdev *sd,
2078                                 struct v4l2_subdev_frame_interval *interval)
2079 {
2080         struct imx_device *dev = to_imx_sensor(sd);
2081
2082         mutex_lock(&dev->input_lock);
2083         interval->interval.denominator = dev->fps;
2084         interval->interval.numerator = 1;
2085         mutex_unlock(&dev->input_lock);
2086         return 0;
2087 }
2088
2089 static int __imx_s_frame_interval(struct v4l2_subdev *sd,
2090                         struct v4l2_subdev_frame_interval *interval)
2091 {
2092         struct imx_device *dev = to_imx_sensor(sd);
2093         struct i2c_client *client = v4l2_get_subdevdata(sd);
2094         const struct imx_resolution *res =
2095                                 &dev->curr_res_table[dev->fmt_idx];
2096         struct camera_mipi_info *imx_info = NULL;
2097         unsigned short pixels_per_line;
2098         unsigned short lines_per_frame;
2099         unsigned int fps_index;
2100         int fps;
2101         int ret = 0;
2102
2103
2104         imx_info = v4l2_get_subdev_hostdata(sd);
2105         if (imx_info == NULL)
2106                 return -EINVAL;
2107
2108         if (!interval->interval.numerator)
2109                 interval->interval.numerator = 1;
2110
2111         fps = interval->interval.denominator / interval->interval.numerator;
2112
2113         if (!fps)
2114                 return -EINVAL;
2115
2116         dev->targetfps = fps;
2117         /* No need to proceed further if we are not streaming */
2118         if (!dev->streaming)
2119                 return 0;
2120
2121          /* Ignore if we are already using the required FPS. */
2122         if (fps == dev->fps)
2123                 return 0;
2124
2125         /*
2126          * Start here, sensor is already streaming, so adjust fps dynamically
2127          */
2128         fps_index = __imx_above_nearest_fps_index(fps, res->fps_options);
2129         if (fps > res->fps_options[fps_index].fps) {
2130                 /*
2131                  * if does not have high fps setting, not support increase fps
2132                  * by adjust lines per frame.
2133                  */
2134                 dev_err(&client->dev, "Could not support fps: %d.\n", fps);
2135                 return -EINVAL;
2136         }
2137
2138         if (res->fps_options[fps_index].regs &&
2139             res->fps_options[fps_index].regs != dev->regs) {
2140                 /*
2141                  * if need a new setting, but the new setting has difference
2142                  * with current setting, not use this one, as may have
2143                  * unexpected result, e.g. PLL, IQ.
2144                  */
2145                 dev_dbg(&client->dev,
2146                         "Sensor is streaming, not apply new sensor setting\n");
2147                 if (fps > res->fps_options[dev->fps_index].fps) {
2148                         /*
2149                          * Does not support increase fps based on low fps
2150                          * setting, as the high fps setting could not be used,
2151                          * and fps requested is above current setting fps.
2152                          */
2153                         dev_warn(&client->dev,
2154                         "Could not support fps: %d, keep current: %d.\n",
2155                         fps, dev->fps);
2156                         return 0;
2157                 }
2158         } else {
2159                 dev->fps_index = fps_index;
2160                 dev->fps = res->fps_options[dev->fps_index].fps;
2161         }
2162
2163         /* Update the new frametimings based on FPS */
2164         pixels_per_line = res->fps_options[dev->fps_index].pixels_per_line;
2165         lines_per_frame = res->fps_options[dev->fps_index].lines_per_frame;
2166
2167         if (fps > res->fps_options[fps_index].fps) {
2168                 /*
2169                  * if does not have high fps setting, not support increase fps
2170                  * by adjust lines per frame.
2171                  */
2172                 dev_warn(&client->dev, "Could not support fps: %d. Use:%d.\n",
2173                                 fps, res->fps_options[fps_index].fps);
2174                 goto done;
2175         }
2176
2177         /* if the new setting does not match exactly */
2178         if (dev->fps != fps) {
2179 #define MAX_LINES_PER_FRAME     0xffff
2180                 dev_dbg(&client->dev, "adjusting fps using lines_per_frame\n");
2181                 /*
2182                  * FIXME!
2183                  * 1: check DS on max value of lines_per_frame
2184                  * 2: consider use pixel per line for more range?
2185                  */
2186                 if (dev->lines_per_frame * dev->fps / fps >
2187                         MAX_LINES_PER_FRAME) {
2188                         dev_warn(&client->dev,
2189                 "adjust lines_per_frame out of range, try to use max value.\n");
2190                         lines_per_frame = MAX_LINES_PER_FRAME;
2191                 } else {
2192                         lines_per_frame = lines_per_frame * dev->fps / fps;
2193                 }
2194         }
2195 done:
2196         /* Update the new frametimings based on FPS */
2197         dev->pixels_per_line = pixels_per_line;
2198         dev->lines_per_frame = lines_per_frame;
2199
2200         /* Update the new values so that user side knows the current settings */
2201         ret = __imx_update_exposure_timing(client,
2202                 dev->coarse_itg, dev->pixels_per_line, dev->lines_per_frame);
2203         if (ret)
2204                 return ret;
2205
2206         dev->fps = fps;
2207
2208         ret = imx_get_intg_factor(client, imx_info, dev->regs);
2209         if (ret)
2210                 return ret;
2211
2212         interval->interval.denominator = res->fps_options[dev->fps_index].fps;
2213         interval->interval.numerator = 1;
2214         __imx_print_timing(sd);
2215
2216         return ret;
2217 }
2218
2219 static int imx_s_frame_interval(struct v4l2_subdev *sd,
2220                         struct v4l2_subdev_frame_interval *interval)
2221 {
2222         struct imx_device *dev = to_imx_sensor(sd);
2223         int ret;
2224
2225         mutex_lock(&dev->input_lock);
2226         ret = __imx_s_frame_interval(sd, interval);
2227         mutex_unlock(&dev->input_lock);
2228
2229         return ret;
2230 }
2231 static int imx_g_skip_frames(struct v4l2_subdev *sd, u32 *frames)
2232 {
2233         struct imx_device *dev = to_imx_sensor(sd);
2234
2235         mutex_lock(&dev->input_lock);
2236         *frames = dev->curr_res_table[dev->fmt_idx].skip_frames;
2237         mutex_unlock(&dev->input_lock);
2238
2239         return 0;
2240 }
2241
2242 static const struct v4l2_subdev_sensor_ops imx_sensor_ops = {
2243         .g_skip_frames  = imx_g_skip_frames,
2244 };
2245
2246 static const struct v4l2_subdev_video_ops imx_video_ops = {
2247         .s_stream = imx_s_stream,
2248         .s_parm = imx_s_parm,
2249         .g_frame_interval = imx_g_frame_interval,
2250         .s_frame_interval = imx_s_frame_interval,
2251 };
2252
2253 static const struct v4l2_subdev_core_ops imx_core_ops = {
2254         .s_power = imx_s_power,
2255         .ioctl = imx_ioctl,
2256         .init = imx_init,
2257 };
2258
2259 static const struct v4l2_subdev_pad_ops imx_pad_ops = {
2260         .enum_mbus_code = imx_enum_mbus_code,
2261         .enum_frame_size = imx_enum_frame_size,
2262         .get_fmt = imx_get_fmt,
2263         .set_fmt = imx_set_fmt,
2264 };
2265
2266 static const struct v4l2_subdev_ops imx_ops = {
2267         .core = &imx_core_ops,
2268         .video = &imx_video_ops,
2269         .pad = &imx_pad_ops,
2270         .sensor = &imx_sensor_ops,
2271 };
2272
2273 static const struct media_entity_operations imx_entity_ops = {
2274         .link_setup = NULL,
2275 };
2276
2277 static int imx_remove(struct i2c_client *client)
2278 {
2279         struct v4l2_subdev *sd = i2c_get_clientdata(client);
2280         struct imx_device *dev = to_imx_sensor(sd);
2281
2282         if (dev->platform_data->platform_deinit)
2283                 dev->platform_data->platform_deinit();
2284
2285         media_entity_cleanup(&dev->sd.entity);
2286         v4l2_ctrl_handler_free(&dev->ctrl_handler);
2287         dev->platform_data->csi_cfg(sd, 0);
2288         v4l2_device_unregister_subdev(sd);
2289         release_msr_list(client, dev->fw);
2290         kfree(dev);
2291
2292         return 0;
2293 }
2294
2295 static int __imx_init_ctrl_handler(struct imx_device *dev)
2296 {
2297         struct v4l2_ctrl_handler *hdl;
2298         int i;
2299
2300         hdl = &dev->ctrl_handler;
2301
2302         v4l2_ctrl_handler_init(&dev->ctrl_handler, ARRAY_SIZE(imx_controls));
2303
2304         for (i = 0; i < ARRAY_SIZE(imx_controls); i++)
2305                 v4l2_ctrl_new_custom(&dev->ctrl_handler,
2306                                 &imx_controls[i], NULL);
2307
2308         dev->pixel_rate = v4l2_ctrl_find(&dev->ctrl_handler,
2309                                 V4L2_CID_PIXEL_RATE);
2310         dev->h_blank = v4l2_ctrl_find(&dev->ctrl_handler,
2311                                 V4L2_CID_HBLANK);
2312         dev->v_blank = v4l2_ctrl_find(&dev->ctrl_handler,
2313                                 V4L2_CID_VBLANK);
2314         dev->link_freq = v4l2_ctrl_find(&dev->ctrl_handler,
2315                                 V4L2_CID_LINK_FREQ);
2316         dev->h_flip = v4l2_ctrl_find(&dev->ctrl_handler,
2317                                 V4L2_CID_HFLIP);
2318         dev->v_flip = v4l2_ctrl_find(&dev->ctrl_handler,
2319                                 V4L2_CID_VFLIP);
2320         dev->tp_mode = v4l2_ctrl_find(&dev->ctrl_handler,
2321                                 V4L2_CID_TEST_PATTERN);
2322         dev->tp_r = v4l2_ctrl_find(&dev->ctrl_handler,
2323                                 V4L2_CID_TEST_PATTERN_COLOR_R);
2324         dev->tp_gr = v4l2_ctrl_find(&dev->ctrl_handler,
2325                                 V4L2_CID_TEST_PATTERN_COLOR_GR);
2326         dev->tp_gb = v4l2_ctrl_find(&dev->ctrl_handler,
2327                                 V4L2_CID_TEST_PATTERN_COLOR_GB);
2328         dev->tp_b = v4l2_ctrl_find(&dev->ctrl_handler,
2329                                 V4L2_CID_TEST_PATTERN_COLOR_B);
2330
2331         if (dev->ctrl_handler.error || dev->pixel_rate == NULL
2332                 || dev->h_blank == NULL || dev->v_blank == NULL
2333                 || dev->h_flip == NULL || dev->v_flip == NULL
2334                 || dev->link_freq == NULL) {
2335                 return dev->ctrl_handler.error;
2336         }
2337
2338         dev->ctrl_handler.lock = &dev->input_lock;
2339         dev->sd.ctrl_handler = hdl;
2340         v4l2_ctrl_handler_setup(&dev->ctrl_handler);
2341
2342         return 0;
2343 }
2344
2345 static void imx_update_reg_info(struct imx_device *dev)
2346 {
2347         if (dev->sensor_id == IMX219_ID) {
2348                 dev->reg_addr = &imx219_addr;
2349                 dev->param_hold = imx219_param_hold;
2350                 dev->param_update = imx219_param_update;
2351         } else {
2352                 dev->reg_addr = &imx_addr;
2353                 dev->param_hold = imx_param_hold;
2354                 dev->param_update = imx_param_update;
2355         }
2356 }
2357
2358 static int imx_probe(struct i2c_client *client,
2359                          const struct i2c_device_id *id)
2360 {
2361         struct imx_device *dev;
2362         struct camera_mipi_info *imx_info = NULL;
2363         int ret;
2364         char *msr_file_name = NULL;
2365
2366         /* allocate sensor device & init sub device */
2367         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2368         if (!dev) {
2369                 v4l2_err(client, "%s: out of memory\n", __func__);
2370                 return -ENOMEM;
2371         }
2372
2373         mutex_init(&dev->input_lock);
2374
2375         dev->i2c_id = id->driver_data;
2376         dev->fmt_idx = 0;
2377         dev->sensor_id = IMX_ID_DEFAULT;
2378         dev->vcm_driver = &imx_vcms[IMX_ID_DEFAULT];
2379         dev->digital_gain = 256;
2380
2381         v4l2_i2c_subdev_init(&(dev->sd), client, &imx_ops);
2382
2383         if (client->dev.platform_data) {
2384                 ret = imx_s_config(&dev->sd, client->irq,
2385                                        client->dev.platform_data);
2386                 if (ret)
2387                         goto out_free;
2388         }
2389         imx_info = v4l2_get_subdev_hostdata(&dev->sd);
2390
2391         /*
2392          * sd->name is updated with sensor driver name by the v4l2.
2393          * change it to sensor name in this case.
2394          */
2395         imx_update_reg_info(dev);
2396         snprintf(dev->sd.name, sizeof(dev->sd.name), "%s%x %d-%04x",
2397                 IMX_SUBDEV_PREFIX, dev->sensor_id,
2398                 i2c_adapter_id(client->adapter), client->addr);
2399
2400         ret = __imx_init_ctrl_handler(dev);
2401         if (ret)
2402                 goto out_ctrl_handler_free;
2403
2404         dev->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
2405         dev->pad.flags = MEDIA_PAD_FL_SOURCE;
2406         dev->format.code = imx_translate_bayer_order(
2407                 imx_info->raw_bayer_order);
2408         dev->sd.entity.ops = &imx_entity_ops;
2409         dev->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
2410
2411         ret = media_entity_pads_init(&dev->sd.entity, 1, &dev->pad);
2412         if (ret) {
2413                 imx_remove(client);
2414                 return ret;
2415         }
2416
2417         /* Load the Noise reduction, Dead pixel registers from cpf file*/
2418         if (dev->platform_data->msr_file_name != NULL)
2419                 msr_file_name = dev->platform_data->msr_file_name();
2420         if (msr_file_name) {
2421                 ret = load_msr_list(client, msr_file_name, &dev->fw);
2422                 if (ret) {
2423                         imx_remove(client);
2424                         return ret;
2425                 }
2426         } else {
2427                 dev_warn(&client->dev, "Drvb file not present");
2428         }
2429
2430         return ret;
2431
2432 out_ctrl_handler_free:
2433         v4l2_ctrl_handler_free(&dev->ctrl_handler);
2434
2435 out_free:
2436         v4l2_device_unregister_subdev(&dev->sd);
2437         kfree(dev);
2438         return ret;
2439 }
2440
2441 static const struct i2c_device_id imx_ids[] = {
2442         {IMX_NAME_175, IMX175_ID},
2443         {IMX_NAME_135, IMX135_ID},
2444         {IMX_NAME_135_FUJI, IMX135_FUJI_ID},
2445         {IMX_NAME_134, IMX134_ID},
2446         {IMX_NAME_132, IMX132_ID},
2447         {IMX_NAME_208, IMX208_ID},
2448         {IMX_NAME_219, IMX219_ID},
2449         {IMX_NAME_227, IMX227_ID},
2450         {}
2451 };
2452
2453 MODULE_DEVICE_TABLE(i2c, imx_ids);
2454
2455 static struct i2c_driver imx_driver = {
2456         .driver = {
2457                 .name = IMX_DRIVER,
2458         },
2459         .probe = imx_probe,
2460         .remove = imx_remove,
2461         .id_table = imx_ids,
2462 };
2463
2464 static __init int init_imx(void)
2465 {
2466         return i2c_add_driver(&imx_driver);
2467 }
2468
2469 static __exit void exit_imx(void)
2470 {
2471         i2c_del_driver(&imx_driver);
2472 }
2473
2474 module_init(init_imx);
2475 module_exit(exit_imx);
2476
2477 MODULE_DESCRIPTION("A low-level driver for Sony IMX sensors");
2478 MODULE_AUTHOR("Shenbo Huang <shenbo.huang@intel.com>");
2479 MODULE_LICENSE("GPL");
2480