GNU Linux-libre 4.14.265-gnu1
[releases.git] / drivers / staging / media / atomisp / i2c / ov2722.c
1 /*
2  * Support for OmniVision OV2722 1080p HD camera sensor.
3  *
4  * Copyright (c) 2013 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  */
16
17 #include <linux/module.h>
18 #include <linux/types.h>
19 #include <linux/kernel.h>
20 #include <linux/mm.h>
21 #include <linux/string.h>
22 #include <linux/errno.h>
23 #include <linux/init.h>
24 #include <linux/kmod.h>
25 #include <linux/device.h>
26 #include <linux/delay.h>
27 #include <linux/slab.h>
28 #include <linux/i2c.h>
29 #include <linux/gpio.h>
30 #include <linux/moduleparam.h>
31 #include <media/v4l2-device.h>
32 #include "../include/linux/atomisp_gmin_platform.h"
33 #include <linux/acpi.h>
34 #include <linux/io.h>
35
36 #include "ov2722.h"
37
38 /* i2c read/write stuff */
39 static int ov2722_read_reg(struct i2c_client *client,
40                            u16 data_length, u16 reg, u16 *val)
41 {
42         int err;
43         struct i2c_msg msg[2];
44         unsigned char data[6];
45
46         if (!client->adapter) {
47                 dev_err(&client->dev, "%s error, no client->adapter\n",
48                         __func__);
49                 return -ENODEV;
50         }
51
52         if (data_length != OV2722_8BIT && data_length != OV2722_16BIT
53                                         && data_length != OV2722_32BIT) {
54                 dev_err(&client->dev, "%s error, invalid data length\n",
55                         __func__);
56                 return -EINVAL;
57         }
58
59         memset(msg, 0 , sizeof(msg));
60
61         msg[0].addr = client->addr;
62         msg[0].flags = 0;
63         msg[0].len = I2C_MSG_LENGTH;
64         msg[0].buf = data;
65
66         /* high byte goes out first */
67         data[0] = (u8)(reg >> 8);
68         data[1] = (u8)(reg & 0xff);
69
70         msg[1].addr = client->addr;
71         msg[1].len = data_length;
72         msg[1].flags = I2C_M_RD;
73         msg[1].buf = data;
74
75         err = i2c_transfer(client->adapter, msg, 2);
76         if (err != 2) {
77                 if (err >= 0)
78                         err = -EIO;
79                 dev_err(&client->dev,
80                         "read from offset 0x%x error %d", reg, err);
81                 return err;
82         }
83
84         *val = 0;
85         /* high byte comes first */
86         if (data_length == OV2722_8BIT)
87                 *val = (u8)data[0];
88         else if (data_length == OV2722_16BIT)
89                 *val = be16_to_cpu(*(u16 *)&data[0]);
90         else
91                 *val = be32_to_cpu(*(u32 *)&data[0]);
92
93         return 0;
94 }
95
96 static int ov2722_i2c_write(struct i2c_client *client, u16 len, u8 *data)
97 {
98         struct i2c_msg msg;
99         const int num_msg = 1;
100         int ret;
101
102         msg.addr = client->addr;
103         msg.flags = 0;
104         msg.len = len;
105         msg.buf = data;
106         ret = i2c_transfer(client->adapter, &msg, 1);
107
108         return ret == num_msg ? 0 : -EIO;
109 }
110
111 static int ov2722_write_reg(struct i2c_client *client, u16 data_length,
112                                                         u16 reg, u16 val)
113 {
114         int ret;
115         unsigned char data[4] = {0};
116         u16 *wreg = (u16 *)data;
117         const u16 len = data_length + sizeof(u16); /* 16-bit address + data */
118
119         if (data_length != OV2722_8BIT && data_length != OV2722_16BIT) {
120                 dev_err(&client->dev,
121                         "%s error, invalid data_length\n", __func__);
122                 return -EINVAL;
123         }
124
125         /* high byte goes out first */
126         *wreg = cpu_to_be16(reg);
127
128         if (data_length == OV2722_8BIT) {
129                 data[2] = (u8)(val);
130         } else {
131                 /* OV2722_16BIT */
132                 u16 *wdata = (u16 *)&data[2];
133                 *wdata = cpu_to_be16(val);
134         }
135
136         ret = ov2722_i2c_write(client, len, data);
137         if (ret)
138                 dev_err(&client->dev,
139                         "write error: wrote 0x%x to offset 0x%x error %d",
140                         val, reg, ret);
141
142         return ret;
143 }
144
145 /*
146  * ov2722_write_reg_array - Initializes a list of OV2722 registers
147  * @client: i2c driver client structure
148  * @reglist: list of registers to be written
149  *
150  * This function initializes a list of registers. When consecutive addresses
151  * are found in a row on the list, this function creates a buffer and sends
152  * consecutive data in a single i2c_transfer().
153  *
154  * __ov2722_flush_reg_array, __ov2722_buf_reg_array() and
155  * __ov2722_write_reg_is_consecutive() are internal functions to
156  * ov2722_write_reg_array_fast() and should be not used anywhere else.
157  *
158  */
159
160 static int __ov2722_flush_reg_array(struct i2c_client *client,
161                                     struct ov2722_write_ctrl *ctrl)
162 {
163         u16 size;
164
165         if (ctrl->index == 0)
166                 return 0;
167
168         size = sizeof(u16) + ctrl->index; /* 16-bit address + data */
169         ctrl->buffer.addr = cpu_to_be16(ctrl->buffer.addr);
170         ctrl->index = 0;
171
172         return ov2722_i2c_write(client, size, (u8 *)&ctrl->buffer);
173 }
174
175 static int __ov2722_buf_reg_array(struct i2c_client *client,
176                                   struct ov2722_write_ctrl *ctrl,
177                                   const struct ov2722_reg *next)
178 {
179         int size;
180         u16 *data16;
181
182         switch (next->type) {
183         case OV2722_8BIT:
184                 size = 1;
185                 ctrl->buffer.data[ctrl->index] = (u8)next->val;
186                 break;
187         case OV2722_16BIT:
188                 size = 2;
189                 data16 = (u16 *)&ctrl->buffer.data[ctrl->index];
190                 *data16 = cpu_to_be16((u16)next->val);
191                 break;
192         default:
193                 return -EINVAL;
194         }
195
196         /* When first item is added, we need to store its starting address */
197         if (ctrl->index == 0)
198                 ctrl->buffer.addr = next->reg;
199
200         ctrl->index += size;
201
202         /*
203          * Buffer cannot guarantee free space for u32? Better flush it to avoid
204          * possible lack of memory for next item.
205          */
206         if (ctrl->index + sizeof(u16) >= OV2722_MAX_WRITE_BUF_SIZE)
207                 return __ov2722_flush_reg_array(client, ctrl);
208
209         return 0;
210 }
211
212 static int __ov2722_write_reg_is_consecutive(struct i2c_client *client,
213                                              struct ov2722_write_ctrl *ctrl,
214                                              const struct ov2722_reg *next)
215 {
216         if (ctrl->index == 0)
217                 return 1;
218
219         return ctrl->buffer.addr + ctrl->index == next->reg;
220 }
221
222 static int ov2722_write_reg_array(struct i2c_client *client,
223                                   const struct ov2722_reg *reglist)
224 {
225         const struct ov2722_reg *next = reglist;
226         struct ov2722_write_ctrl ctrl;
227         int err;
228
229         ctrl.index = 0;
230         for (; next->type != OV2722_TOK_TERM; next++) {
231                 switch (next->type & OV2722_TOK_MASK) {
232                 case OV2722_TOK_DELAY:
233                         err = __ov2722_flush_reg_array(client, &ctrl);
234                         if (err)
235                                 return err;
236                         msleep(next->val);
237                         break;
238                 default:
239                         /*
240                          * If next address is not consecutive, data needs to be
241                          * flushed before proceed.
242                          */
243                         if (!__ov2722_write_reg_is_consecutive(client, &ctrl,
244                                                                 next)) {
245                                 err = __ov2722_flush_reg_array(client, &ctrl);
246                                 if (err)
247                                         return err;
248                         }
249                         err = __ov2722_buf_reg_array(client, &ctrl, next);
250                         if (err) {
251                                 dev_err(&client->dev, "%s: write error, aborted\n",
252                                          __func__);
253                                 return err;
254                         }
255                         break;
256                 }
257         }
258
259         return __ov2722_flush_reg_array(client, &ctrl);
260 }
261 static int ov2722_g_focal(struct v4l2_subdev *sd, s32 *val)
262 {
263         *val = (OV2722_FOCAL_LENGTH_NUM << 16) | OV2722_FOCAL_LENGTH_DEM;
264         return 0;
265 }
266
267 static int ov2722_g_fnumber(struct v4l2_subdev *sd, s32 *val)
268 {
269         /*const f number for imx*/
270         *val = (OV2722_F_NUMBER_DEFAULT_NUM << 16) | OV2722_F_NUMBER_DEM;
271         return 0;
272 }
273
274 static int ov2722_g_fnumber_range(struct v4l2_subdev *sd, s32 *val)
275 {
276         *val = (OV2722_F_NUMBER_DEFAULT_NUM << 24) |
277                 (OV2722_F_NUMBER_DEM << 16) |
278                 (OV2722_F_NUMBER_DEFAULT_NUM << 8) | OV2722_F_NUMBER_DEM;
279         return 0;
280 }
281
282 static int ov2722_get_intg_factor(struct i2c_client *client,
283                                 struct camera_mipi_info *info,
284                                 const struct ov2722_resolution *res)
285 {
286         struct v4l2_subdev *sd = i2c_get_clientdata(client);
287         struct ov2722_device *dev = NULL;
288         struct atomisp_sensor_mode_data *buf = &info->data;
289         const unsigned int ext_clk_freq_hz = 19200000;
290         const unsigned int pll_invariant_div = 10;
291         unsigned int pix_clk_freq_hz;
292         u16 pre_pll_clk_div;
293         u16 pll_multiplier;
294         u16 op_pix_clk_div;
295         u16 reg_val;
296         int ret;
297
298         if (!info)
299                 return -EINVAL;
300
301         dev = to_ov2722_sensor(sd);
302
303         /* pixel clock calculattion */
304         ret =  ov2722_read_reg(client, OV2722_8BIT,
305                                 OV2722_SC_CMMN_PLL_CTRL3, &pre_pll_clk_div);
306         if (ret)
307                 return ret;
308
309         ret =  ov2722_read_reg(client, OV2722_8BIT,
310                                 OV2722_SC_CMMN_PLL_MULTIPLIER, &pll_multiplier);
311         if (ret)
312                 return ret;
313
314         ret =  ov2722_read_reg(client, OV2722_8BIT,
315                                 OV2722_SC_CMMN_PLL_DEBUG_OPT, &op_pix_clk_div);
316         if (ret)
317                 return ret;
318
319         pre_pll_clk_div = (pre_pll_clk_div & 0x70) >> 4;
320         if (0 == pre_pll_clk_div)
321                 return -EINVAL;
322
323         pll_multiplier = pll_multiplier & 0x7f;
324         op_pix_clk_div = op_pix_clk_div & 0x03;
325         pix_clk_freq_hz = ext_clk_freq_hz / pre_pll_clk_div * pll_multiplier
326                                 * op_pix_clk_div / pll_invariant_div;
327
328         dev->vt_pix_clk_freq_mhz = pix_clk_freq_hz;
329         buf->vt_pix_clk_freq_mhz = pix_clk_freq_hz;
330
331         /* get integration time */
332         buf->coarse_integration_time_min = OV2722_COARSE_INTG_TIME_MIN;
333         buf->coarse_integration_time_max_margin =
334                                         OV2722_COARSE_INTG_TIME_MAX_MARGIN;
335
336         buf->fine_integration_time_min = OV2722_FINE_INTG_TIME_MIN;
337         buf->fine_integration_time_max_margin =
338                                         OV2722_FINE_INTG_TIME_MAX_MARGIN;
339
340         buf->fine_integration_time_def = OV2722_FINE_INTG_TIME_MIN;
341         buf->frame_length_lines = res->lines_per_frame;
342         buf->line_length_pck = res->pixels_per_line;
343         buf->read_mode = res->bin_mode;
344
345         /* get the cropping and output resolution to ISP for this mode. */
346         ret =  ov2722_read_reg(client, OV2722_16BIT,
347                                         OV2722_H_CROP_START_H, &reg_val);
348         if (ret)
349                 return ret;
350         buf->crop_horizontal_start = reg_val;
351
352         ret =  ov2722_read_reg(client, OV2722_16BIT,
353                                         OV2722_V_CROP_START_H, &reg_val);
354         if (ret)
355                 return ret;
356         buf->crop_vertical_start = reg_val;
357
358         ret = ov2722_read_reg(client, OV2722_16BIT,
359                                         OV2722_H_CROP_END_H, &reg_val);
360         if (ret)
361                 return ret;
362         buf->crop_horizontal_end = reg_val;
363
364         ret = ov2722_read_reg(client, OV2722_16BIT,
365                                         OV2722_V_CROP_END_H, &reg_val);
366         if (ret)
367                 return ret;
368         buf->crop_vertical_end = reg_val;
369
370         ret = ov2722_read_reg(client, OV2722_16BIT,
371                                         OV2722_H_OUTSIZE_H, &reg_val);
372         if (ret)
373                 return ret;
374         buf->output_width = reg_val;
375
376         ret = ov2722_read_reg(client, OV2722_16BIT,
377                                         OV2722_V_OUTSIZE_H, &reg_val);
378         if (ret)
379                 return ret;
380         buf->output_height = reg_val;
381
382         buf->binning_factor_x = res->bin_factor_x ?
383                                         res->bin_factor_x : 1;
384         buf->binning_factor_y = res->bin_factor_y ?
385                                         res->bin_factor_y : 1;
386         return 0;
387 }
388
389 static long __ov2722_set_exposure(struct v4l2_subdev *sd, int coarse_itg,
390                                  int gain, int digitgain)
391
392 {
393         struct i2c_client *client = v4l2_get_subdevdata(sd);
394         struct ov2722_device *dev = to_ov2722_sensor(sd);
395         u16 hts, vts;
396         int ret;
397
398         dev_dbg(&client->dev, "set_exposure without group hold\n");
399
400         /* clear VTS_DIFF on manual mode */
401         ret = ov2722_write_reg(client, OV2722_16BIT, OV2722_VTS_DIFF_H, 0);
402         if (ret)
403                 return ret;
404
405         hts = dev->pixels_per_line;
406         vts = dev->lines_per_frame;
407
408         if ((coarse_itg + OV2722_COARSE_INTG_TIME_MAX_MARGIN) > vts)
409                 vts = coarse_itg + OV2722_COARSE_INTG_TIME_MAX_MARGIN;
410
411         coarse_itg <<= 4;
412         digitgain <<= 2;
413
414         ret = ov2722_write_reg(client, OV2722_16BIT,
415                                 OV2722_VTS_H, vts);
416         if (ret)
417                 return ret;
418
419         ret = ov2722_write_reg(client, OV2722_16BIT,
420                                 OV2722_HTS_H, hts);
421         if (ret)
422                 return ret;
423
424         /* set exposure */
425         ret = ov2722_write_reg(client, OV2722_8BIT,
426                                         OV2722_AEC_PK_EXPO_L,
427                                         coarse_itg & 0xff);
428         if (ret)
429                 return ret;
430
431         ret = ov2722_write_reg(client, OV2722_16BIT,
432                                         OV2722_AEC_PK_EXPO_H,
433                                         (coarse_itg >> 8) & 0xfff);
434         if (ret)
435                 return ret;
436
437         /* set analog gain */
438         ret = ov2722_write_reg(client, OV2722_16BIT,
439                                         OV2722_AGC_ADJ_H, gain);
440         if (ret)
441                 return ret;
442
443         /* set digital gain */
444         ret = ov2722_write_reg(client, OV2722_16BIT,
445                                 OV2722_MWB_GAIN_R_H, digitgain);
446         if (ret)
447                 return ret;
448
449         ret = ov2722_write_reg(client, OV2722_16BIT,
450                                 OV2722_MWB_GAIN_G_H, digitgain);
451         if (ret)
452                 return ret;
453
454         ret = ov2722_write_reg(client, OV2722_16BIT,
455                                 OV2722_MWB_GAIN_B_H, digitgain);
456
457         return ret;
458 }
459
460 static int ov2722_set_exposure(struct v4l2_subdev *sd, int exposure,
461         int gain, int digitgain)
462 {
463         struct ov2722_device *dev = to_ov2722_sensor(sd);
464         int ret;
465
466         mutex_lock(&dev->input_lock);
467         ret = __ov2722_set_exposure(sd, exposure, gain, digitgain);
468         mutex_unlock(&dev->input_lock);
469
470         return ret;
471 }
472
473 static long ov2722_s_exposure(struct v4l2_subdev *sd,
474                                struct atomisp_exposure *exposure)
475 {
476         int exp = exposure->integration_time[0];
477         int gain = exposure->gain[0];
478         int digitgain = exposure->gain[1];
479
480         /* we should not accept the invalid value below. */
481         if (gain == 0) {
482                 struct i2c_client *client = v4l2_get_subdevdata(sd);
483                 v4l2_err(client, "%s: invalid value\n", __func__);
484                 return -EINVAL;
485         }
486
487         return ov2722_set_exposure(sd, exp, gain, digitgain);
488 }
489
490 static long ov2722_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
491 {
492
493         switch (cmd) {
494         case ATOMISP_IOC_S_EXPOSURE:
495                 return ov2722_s_exposure(sd, arg);
496         default:
497                 return -EINVAL;
498         }
499         return 0;
500 }
501
502 /* This returns the exposure time being used. This should only be used
503  * for filling in EXIF data, not for actual image processing.
504  */
505 static int ov2722_q_exposure(struct v4l2_subdev *sd, s32 *value)
506 {
507         struct i2c_client *client = v4l2_get_subdevdata(sd);
508         u16 reg_v, reg_v2;
509         int ret;
510
511         /* get exposure */
512         ret = ov2722_read_reg(client, OV2722_8BIT,
513                                         OV2722_AEC_PK_EXPO_L,
514                                         &reg_v);
515         if (ret)
516                 goto err;
517
518         ret = ov2722_read_reg(client, OV2722_8BIT,
519                                         OV2722_AEC_PK_EXPO_M,
520                                         &reg_v2);
521         if (ret)
522                 goto err;
523
524         reg_v += reg_v2 << 8;
525         ret = ov2722_read_reg(client, OV2722_8BIT,
526                                         OV2722_AEC_PK_EXPO_H,
527                                         &reg_v2);
528         if (ret)
529                 goto err;
530
531         *value = reg_v + (((u32)reg_v2 << 16));
532 err:
533         return ret;
534 }
535
536 static int ov2722_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
537 {
538         struct ov2722_device *dev =
539             container_of(ctrl->handler, struct ov2722_device, ctrl_handler);
540         int ret = 0;
541         unsigned int val;
542         switch (ctrl->id) {
543         case V4L2_CID_EXPOSURE_ABSOLUTE:
544                 ret = ov2722_q_exposure(&dev->sd, &ctrl->val);
545                 break;
546         case V4L2_CID_FOCAL_ABSOLUTE:
547                 ret = ov2722_g_focal(&dev->sd, &ctrl->val);
548                 break;
549         case V4L2_CID_FNUMBER_ABSOLUTE:
550                 ret = ov2722_g_fnumber(&dev->sd, &ctrl->val);
551                 break;
552         case V4L2_CID_FNUMBER_RANGE:
553                 ret = ov2722_g_fnumber_range(&dev->sd, &ctrl->val);
554                 break;
555         case V4L2_CID_LINK_FREQ:
556                 val = ov2722_res[dev->fmt_idx].mipi_freq;
557                 if (val == 0)
558                         return -EINVAL;
559
560                 ctrl->val = val * 1000; /* To Hz */
561                 break;
562         default:
563                 ret = -EINVAL;
564         }
565
566         return ret;
567 }
568
569 static const struct v4l2_ctrl_ops ctrl_ops = {
570         .g_volatile_ctrl = ov2722_g_volatile_ctrl
571 };
572
573 struct v4l2_ctrl_config ov2722_controls[] = {
574         {
575          .ops = &ctrl_ops,
576          .id = V4L2_CID_EXPOSURE_ABSOLUTE,
577          .type = V4L2_CTRL_TYPE_INTEGER,
578          .name = "exposure",
579          .min = 0x0,
580          .max = 0xffff,
581          .step = 0x01,
582          .def = 0x00,
583          .flags = 0,
584          },
585         {
586          .ops = &ctrl_ops,
587          .id = V4L2_CID_FOCAL_ABSOLUTE,
588          .type = V4L2_CTRL_TYPE_INTEGER,
589          .name = "focal length",
590          .min = OV2722_FOCAL_LENGTH_DEFAULT,
591          .max = OV2722_FOCAL_LENGTH_DEFAULT,
592          .step = 0x01,
593          .def = OV2722_FOCAL_LENGTH_DEFAULT,
594          .flags = 0,
595          },
596         {
597          .ops = &ctrl_ops,
598          .id = V4L2_CID_FNUMBER_ABSOLUTE,
599          .type = V4L2_CTRL_TYPE_INTEGER,
600          .name = "f-number",
601          .min = OV2722_F_NUMBER_DEFAULT,
602          .max = OV2722_F_NUMBER_DEFAULT,
603          .step = 0x01,
604          .def = OV2722_F_NUMBER_DEFAULT,
605          .flags = 0,
606          },
607         {
608          .ops = &ctrl_ops,
609          .id = V4L2_CID_FNUMBER_RANGE,
610          .type = V4L2_CTRL_TYPE_INTEGER,
611          .name = "f-number range",
612          .min = OV2722_F_NUMBER_RANGE,
613          .max = OV2722_F_NUMBER_RANGE,
614          .step = 0x01,
615          .def = OV2722_F_NUMBER_RANGE,
616          .flags = 0,
617          },
618         {
619          .ops = &ctrl_ops,
620          .id = V4L2_CID_LINK_FREQ,
621          .name = "Link Frequency",
622          .type = V4L2_CTRL_TYPE_INTEGER,
623          .min = 1,
624          .max = 1500000 * 1000,
625          .step = 1,
626          .def = 1,
627          .flags = V4L2_CTRL_FLAG_VOLATILE | V4L2_CTRL_FLAG_READ_ONLY,
628          },
629 };
630
631 static int ov2722_init(struct v4l2_subdev *sd)
632 {
633         struct ov2722_device *dev = to_ov2722_sensor(sd);
634
635         mutex_lock(&dev->input_lock);
636
637         /* restore settings */
638         ov2722_res = ov2722_res_preview;
639         N_RES = N_RES_PREVIEW;
640
641         mutex_unlock(&dev->input_lock);
642
643         return 0;
644 }
645
646 static int power_ctrl(struct v4l2_subdev *sd, bool flag)
647 {
648         int ret = -1;
649         struct ov2722_device *dev = to_ov2722_sensor(sd);
650
651         if (!dev || !dev->platform_data)
652                 return -ENODEV;
653
654         /* Non-gmin platforms use the legacy callback */
655         if (dev->platform_data->power_ctrl)
656                 return dev->platform_data->power_ctrl(sd, flag);
657
658         if (flag) {
659                 ret = dev->platform_data->v1p8_ctrl(sd, 1);
660                 if (ret == 0) {
661                         ret = dev->platform_data->v2p8_ctrl(sd, 1);
662                         if (ret)
663                                 dev->platform_data->v1p8_ctrl(sd, 0);
664                 }
665         } else {
666                 ret = dev->platform_data->v1p8_ctrl(sd, 0);
667                 ret |= dev->platform_data->v2p8_ctrl(sd, 0);
668         }
669
670         return ret;
671 }
672
673 static int gpio_ctrl(struct v4l2_subdev *sd, bool flag)
674 {
675         struct ov2722_device *dev = to_ov2722_sensor(sd);
676         int ret = -1;
677
678         if (!dev || !dev->platform_data)
679                 return -ENODEV;
680
681         /* Non-gmin platforms use the legacy callback */
682         if (dev->platform_data->gpio_ctrl)
683                 return dev->platform_data->gpio_ctrl(sd, flag);
684
685         /* Note: the GPIO order is asymmetric: always RESET#
686          * before PWDN# when turning it on or off.
687          */
688         ret = dev->platform_data->gpio0_ctrl(sd, flag);
689         /*
690          *ov2722 PWDN# active high when pull down,opposite to the convention
691          */
692         ret |= dev->platform_data->gpio1_ctrl(sd, !flag);
693         return ret;
694 }
695
696 static int power_up(struct v4l2_subdev *sd)
697 {
698         struct ov2722_device *dev = to_ov2722_sensor(sd);
699         struct i2c_client *client = v4l2_get_subdevdata(sd);
700         int ret;
701
702         if (!dev->platform_data) {
703                 dev_err(&client->dev,
704                         "no camera_sensor_platform_data");
705                 return -ENODEV;
706         }
707
708         /* power control */
709         ret = power_ctrl(sd, 1);
710         if (ret)
711                 goto fail_power;
712
713         /* according to DS, at least 5ms is needed between DOVDD and PWDN */
714         usleep_range(5000, 6000);
715
716         /* gpio ctrl */
717         ret = gpio_ctrl(sd, 1);
718         if (ret) {
719                 ret = gpio_ctrl(sd, 0);
720                 if (ret)
721                         goto fail_power;
722         }
723
724         /* flis clock control */
725         ret = dev->platform_data->flisclk_ctrl(sd, 1);
726         if (ret)
727                 goto fail_clk;
728
729         /* according to DS, 20ms is needed between PWDN and i2c access */
730         msleep(20);
731
732         return 0;
733
734 fail_clk:
735         gpio_ctrl(sd, 0);
736 fail_power:
737         power_ctrl(sd, 0);
738         dev_err(&client->dev, "sensor power-up failed\n");
739
740         return ret;
741 }
742
743 static int power_down(struct v4l2_subdev *sd)
744 {
745         struct ov2722_device *dev = to_ov2722_sensor(sd);
746         struct i2c_client *client = v4l2_get_subdevdata(sd);
747         int ret = 0;
748
749         if (!dev->platform_data) {
750                 dev_err(&client->dev,
751                         "no camera_sensor_platform_data");
752                 return -ENODEV;
753         }
754
755         ret = dev->platform_data->flisclk_ctrl(sd, 0);
756         if (ret)
757                 dev_err(&client->dev, "flisclk failed\n");
758
759         /* gpio ctrl */
760         ret = gpio_ctrl(sd, 0);
761         if (ret) {
762                 ret = gpio_ctrl(sd, 0);
763                 if (ret)
764                         dev_err(&client->dev, "gpio failed 2\n");
765         }
766
767         /* power control */
768         ret = power_ctrl(sd, 0);
769         if (ret)
770                 dev_err(&client->dev, "vprog failed.\n");
771
772         return ret;
773 }
774
775 static int ov2722_s_power(struct v4l2_subdev *sd, int on)
776 {
777         int ret;
778         if (on == 0)
779                 return power_down(sd);
780         else {
781                 ret = power_up(sd);
782                 if (!ret)
783                         return ov2722_init(sd);
784         }
785         return ret;
786 }
787
788 /*
789  * distance - calculate the distance
790  * @res: resolution
791  * @w: width
792  * @h: height
793  *
794  * Get the gap between resolution and w/h.
795  * res->width/height smaller than w/h wouldn't be considered.
796  * Returns the value of gap or -1 if fail.
797  */
798 #define LARGEST_ALLOWED_RATIO_MISMATCH 800
799 static int distance(struct ov2722_resolution *res, u32 w, u32 h)
800 {
801         unsigned int w_ratio = (res->width << 13) / w;
802         unsigned int h_ratio;
803         int match;
804
805         if (h == 0)
806                 return -1;
807         h_ratio = (res->height << 13) / h;
808         if (h_ratio == 0)
809                 return -1;
810         match   = abs(((w_ratio << 13) / h_ratio) - 8192);
811
812         if ((w_ratio < 8192) || (h_ratio < 8192) ||
813             (match > LARGEST_ALLOWED_RATIO_MISMATCH))
814                 return -1;
815
816         return w_ratio + h_ratio;
817 }
818
819 /* Return the nearest higher resolution index */
820 static int nearest_resolution_index(int w, int h)
821 {
822         int i;
823         int idx = -1;
824         int dist;
825         int min_dist = INT_MAX;
826         struct ov2722_resolution *tmp_res = NULL;
827
828         for (i = 0; i < N_RES; i++) {
829                 tmp_res = &ov2722_res[i];
830                 dist = distance(tmp_res, w, h);
831                 if (dist == -1)
832                         continue;
833                 if (dist < min_dist) {
834                         min_dist = dist;
835                         idx = i;
836                 }
837         }
838
839         return idx;
840 }
841
842 static int get_resolution_index(int w, int h)
843 {
844         int i;
845
846         for (i = 0; i < N_RES; i++) {
847                 if (w != ov2722_res[i].width)
848                         continue;
849                 if (h != ov2722_res[i].height)
850                         continue;
851
852                 return i;
853         }
854
855         return -1;
856 }
857
858 /* TODO: remove it. */
859 static int startup(struct v4l2_subdev *sd)
860 {
861         struct ov2722_device *dev = to_ov2722_sensor(sd);
862         struct i2c_client *client = v4l2_get_subdevdata(sd);
863         int ret = 0;
864
865         ret = ov2722_write_reg(client, OV2722_8BIT,
866                                         OV2722_SW_RESET, 0x01);
867         if (ret) {
868                 dev_err(&client->dev, "ov2722 reset err.\n");
869                 return ret;
870         }
871
872         ret = ov2722_write_reg_array(client, ov2722_res[dev->fmt_idx].regs);
873         if (ret) {
874                 dev_err(&client->dev, "ov2722 write register err.\n");
875                 return ret;
876         }
877
878         return ret;
879 }
880
881 static int ov2722_set_fmt(struct v4l2_subdev *sd,
882                           struct v4l2_subdev_pad_config *cfg,
883                           struct v4l2_subdev_format *format)
884 {
885         struct v4l2_mbus_framefmt *fmt = &format->format;
886         struct ov2722_device *dev = to_ov2722_sensor(sd);
887         struct i2c_client *client = v4l2_get_subdevdata(sd);
888         struct camera_mipi_info *ov2722_info = NULL;
889         int ret = 0;
890         int idx;
891         if (format->pad)
892                 return -EINVAL;
893         if (!fmt)
894                 return -EINVAL;
895         ov2722_info = v4l2_get_subdev_hostdata(sd);
896         if (!ov2722_info)
897                 return -EINVAL;
898
899         mutex_lock(&dev->input_lock);
900         idx = nearest_resolution_index(fmt->width, fmt->height);
901         if (idx == -1) {
902                 /* return the largest resolution */
903                 fmt->width = ov2722_res[N_RES - 1].width;
904                 fmt->height = ov2722_res[N_RES - 1].height;
905         } else {
906                 fmt->width = ov2722_res[idx].width;
907                 fmt->height = ov2722_res[idx].height;
908         }
909         fmt->code = MEDIA_BUS_FMT_SGRBG10_1X10;
910         if (format->which == V4L2_SUBDEV_FORMAT_TRY) {
911                 cfg->try_fmt = *fmt;
912                 mutex_unlock(&dev->input_lock);
913                 return 0;
914         }
915
916         dev->fmt_idx = get_resolution_index(fmt->width, fmt->height);
917         if (dev->fmt_idx == -1) {
918                 dev_err(&client->dev, "get resolution fail\n");
919                 mutex_unlock(&dev->input_lock);
920                 return -EINVAL;
921         }
922
923         dev->pixels_per_line = ov2722_res[dev->fmt_idx].pixels_per_line;
924         dev->lines_per_frame = ov2722_res[dev->fmt_idx].lines_per_frame;
925
926         ret = startup(sd);
927         if (ret) {
928                 int i = 0;
929                 dev_err(&client->dev, "ov2722 startup err, retry to power up\n");
930                 for (i = 0; i < OV2722_POWER_UP_RETRY_NUM; i++) {
931                         dev_err(&client->dev,
932                                 "ov2722 retry to power up %d/%d times, result: ",
933                                 i + 1, OV2722_POWER_UP_RETRY_NUM);
934                         power_down(sd);
935                         ret = power_up(sd);
936                         if (ret) {
937                                 dev_err(&client->dev, "power up failed, continue\n");
938                                 continue;
939                         }
940                         ret = startup(sd);
941                         if (ret) {
942                                 dev_err(&client->dev, " startup FAILED!\n");
943                         } else {
944                                 dev_err(&client->dev, " startup SUCCESS!\n");
945                                 break;
946                         }
947                 }
948                 if (ret) {
949                         dev_err(&client->dev, "ov2722 startup err\n");
950                         goto err;
951                 }
952         }
953
954         ret = ov2722_get_intg_factor(client, ov2722_info,
955                                         &ov2722_res[dev->fmt_idx]);
956         if (ret)
957                 dev_err(&client->dev, "failed to get integration_factor\n");
958
959 err:
960         mutex_unlock(&dev->input_lock);
961         return ret;
962 }
963 static int ov2722_get_fmt(struct v4l2_subdev *sd,
964                           struct v4l2_subdev_pad_config *cfg,
965                           struct v4l2_subdev_format *format)
966 {
967         struct v4l2_mbus_framefmt *fmt = &format->format;
968         struct ov2722_device *dev = to_ov2722_sensor(sd);
969
970         if (format->pad)
971                 return -EINVAL;
972         if (!fmt)
973                 return -EINVAL;
974
975         fmt->width = ov2722_res[dev->fmt_idx].width;
976         fmt->height = ov2722_res[dev->fmt_idx].height;
977         fmt->code = MEDIA_BUS_FMT_SBGGR10_1X10;
978
979         return 0;
980 }
981
982 static int ov2722_detect(struct i2c_client *client)
983 {
984         struct i2c_adapter *adapter = client->adapter;
985         u16 high, low;
986         int ret;
987         u16 id;
988         u8 revision;
989
990         if (!i2c_check_functionality(adapter, I2C_FUNC_I2C))
991                 return -ENODEV;
992
993         ret = ov2722_read_reg(client, OV2722_8BIT,
994                                         OV2722_SC_CMMN_CHIP_ID_H, &high);
995         if (ret) {
996                 dev_err(&client->dev, "sensor_id_high = 0x%x\n", high);
997                 return -ENODEV;
998         }
999         ret = ov2722_read_reg(client, OV2722_8BIT,
1000                                         OV2722_SC_CMMN_CHIP_ID_L, &low);
1001         id = (high << 8) | low;
1002
1003         if ((id != OV2722_ID) && (id != OV2720_ID)) {
1004                 dev_err(&client->dev, "sensor ID error\n");
1005                 return -ENODEV;
1006         }
1007
1008         ret = ov2722_read_reg(client, OV2722_8BIT,
1009                                         OV2722_SC_CMMN_SUB_ID, &high);
1010         revision = (u8) high & 0x0f;
1011
1012         dev_dbg(&client->dev, "sensor_revision = 0x%x\n", revision);
1013         dev_dbg(&client->dev, "detect ov2722 success\n");
1014         return 0;
1015 }
1016
1017 static int ov2722_s_stream(struct v4l2_subdev *sd, int enable)
1018 {
1019         struct ov2722_device *dev = to_ov2722_sensor(sd);
1020         struct i2c_client *client = v4l2_get_subdevdata(sd);
1021         int ret;
1022
1023         mutex_lock(&dev->input_lock);
1024
1025         ret = ov2722_write_reg(client, OV2722_8BIT, OV2722_SW_STREAM,
1026                                 enable ? OV2722_START_STREAMING :
1027                                 OV2722_STOP_STREAMING);
1028
1029         mutex_unlock(&dev->input_lock);
1030         return ret;
1031 }
1032
1033 static int ov2722_s_config(struct v4l2_subdev *sd,
1034                            int irq, void *platform_data)
1035 {
1036         struct ov2722_device *dev = to_ov2722_sensor(sd);
1037         struct i2c_client *client = v4l2_get_subdevdata(sd);
1038         int ret = 0;
1039
1040         if (!platform_data)
1041                 return -ENODEV;
1042
1043         dev->platform_data =
1044                 (struct camera_sensor_platform_data *)platform_data;
1045
1046         mutex_lock(&dev->input_lock);
1047         if (dev->platform_data->platform_init) {
1048                 ret = dev->platform_data->platform_init(client);
1049                 if (ret) {
1050                         dev_err(&client->dev, "platform init err\n");
1051                         goto platform_init_failed;
1052                 }
1053         }
1054
1055         /* power off the module, then power on it in future
1056          * as first power on by board may not fulfill the
1057          * power on sequqence needed by the module
1058          */
1059         ret = power_down(sd);
1060         if (ret) {
1061                 dev_err(&client->dev, "ov2722 power-off err.\n");
1062                 goto fail_power_off;
1063         }
1064
1065         ret = power_up(sd);
1066         if (ret) {
1067                 dev_err(&client->dev, "ov2722 power-up err.\n");
1068                 goto fail_power_on;
1069         }
1070
1071         ret = dev->platform_data->csi_cfg(sd, 1);
1072         if (ret)
1073                 goto fail_csi_cfg;
1074
1075         /* config & detect sensor */
1076         ret = ov2722_detect(client);
1077         if (ret) {
1078                 dev_err(&client->dev, "ov2722_detect err s_config.\n");
1079                 goto fail_csi_cfg;
1080         }
1081
1082         /* turn off sensor, after probed */
1083         ret = power_down(sd);
1084         if (ret) {
1085                 dev_err(&client->dev, "ov2722 power-off err.\n");
1086                 goto fail_csi_cfg;
1087         }
1088         mutex_unlock(&dev->input_lock);
1089
1090         return 0;
1091
1092 fail_csi_cfg:
1093         dev->platform_data->csi_cfg(sd, 0);
1094 fail_power_on:
1095         power_down(sd);
1096         dev_err(&client->dev, "sensor power-gating failed\n");
1097 fail_power_off:
1098         if (dev->platform_data->platform_deinit)
1099                 dev->platform_data->platform_deinit();
1100 platform_init_failed:
1101         mutex_unlock(&dev->input_lock);
1102         return ret;
1103 }
1104
1105 static int ov2722_g_parm(struct v4l2_subdev *sd,
1106                         struct v4l2_streamparm *param)
1107 {
1108         struct ov2722_device *dev = to_ov2722_sensor(sd);
1109         struct i2c_client *client = v4l2_get_subdevdata(sd);
1110
1111         if (!param)
1112                 return -EINVAL;
1113
1114         if (param->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1115                 dev_err(&client->dev,  "unsupported buffer type.\n");
1116                 return -EINVAL;
1117         }
1118
1119         memset(param, 0, sizeof(*param));
1120         param->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1121
1122         if (dev->fmt_idx >= 0 && dev->fmt_idx < N_RES) {
1123                 param->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1124                 param->parm.capture.timeperframe.numerator = 1;
1125                 param->parm.capture.capturemode = dev->run_mode;
1126                 param->parm.capture.timeperframe.denominator =
1127                         ov2722_res[dev->fmt_idx].fps;
1128         }
1129         return 0;
1130 }
1131
1132 static int ov2722_s_parm(struct v4l2_subdev *sd,
1133                         struct v4l2_streamparm *param)
1134 {
1135         struct ov2722_device *dev = to_ov2722_sensor(sd);
1136         dev->run_mode = param->parm.capture.capturemode;
1137
1138         mutex_lock(&dev->input_lock);
1139         switch (dev->run_mode) {
1140         case CI_MODE_VIDEO:
1141                 ov2722_res = ov2722_res_video;
1142                 N_RES = N_RES_VIDEO;
1143                 break;
1144         case CI_MODE_STILL_CAPTURE:
1145                 ov2722_res = ov2722_res_still;
1146                 N_RES = N_RES_STILL;
1147                 break;
1148         default:
1149                 ov2722_res = ov2722_res_preview;
1150                 N_RES = N_RES_PREVIEW;
1151         }
1152         mutex_unlock(&dev->input_lock);
1153         return 0;
1154 }
1155
1156 static int ov2722_g_frame_interval(struct v4l2_subdev *sd,
1157                                    struct v4l2_subdev_frame_interval *interval)
1158 {
1159         struct ov2722_device *dev = to_ov2722_sensor(sd);
1160
1161         interval->interval.numerator = 1;
1162         interval->interval.denominator = ov2722_res[dev->fmt_idx].fps;
1163
1164         return 0;
1165 }
1166
1167 static int ov2722_enum_mbus_code(struct v4l2_subdev *sd,
1168                                  struct v4l2_subdev_pad_config *cfg,
1169                                  struct v4l2_subdev_mbus_code_enum *code)
1170 {
1171         if (code->index >= MAX_FMTS)
1172                 return -EINVAL;
1173
1174         code->code = MEDIA_BUS_FMT_SBGGR10_1X10;
1175         return 0;
1176 }
1177
1178 static int ov2722_enum_frame_size(struct v4l2_subdev *sd,
1179                                   struct v4l2_subdev_pad_config *cfg,
1180                                   struct v4l2_subdev_frame_size_enum *fse)
1181 {
1182         int index = fse->index;
1183
1184         if (index >= N_RES)
1185                 return -EINVAL;
1186
1187         fse->min_width = ov2722_res[index].width;
1188         fse->min_height = ov2722_res[index].height;
1189         fse->max_width = ov2722_res[index].width;
1190         fse->max_height = ov2722_res[index].height;
1191
1192         return 0;
1193
1194 }
1195
1196
1197 static int ov2722_g_skip_frames(struct v4l2_subdev *sd, u32 *frames)
1198 {
1199         struct ov2722_device *dev = to_ov2722_sensor(sd);
1200
1201         mutex_lock(&dev->input_lock);
1202         *frames = ov2722_res[dev->fmt_idx].skip_frames;
1203         mutex_unlock(&dev->input_lock);
1204
1205         return 0;
1206 }
1207
1208 static const struct v4l2_subdev_sensor_ops ov2722_sensor_ops = {
1209         .g_skip_frames  = ov2722_g_skip_frames,
1210 };
1211
1212 static const struct v4l2_subdev_video_ops ov2722_video_ops = {
1213         .s_stream = ov2722_s_stream,
1214         .g_parm = ov2722_g_parm,
1215         .s_parm = ov2722_s_parm,
1216         .g_frame_interval = ov2722_g_frame_interval,
1217 };
1218
1219 static const struct v4l2_subdev_core_ops ov2722_core_ops = {
1220         .s_power = ov2722_s_power,
1221         .ioctl = ov2722_ioctl,
1222 };
1223
1224 static const struct v4l2_subdev_pad_ops ov2722_pad_ops = {
1225         .enum_mbus_code = ov2722_enum_mbus_code,
1226         .enum_frame_size = ov2722_enum_frame_size,
1227         .get_fmt = ov2722_get_fmt,
1228         .set_fmt = ov2722_set_fmt,
1229 };
1230
1231 static const struct v4l2_subdev_ops ov2722_ops = {
1232         .core = &ov2722_core_ops,
1233         .video = &ov2722_video_ops,
1234         .pad = &ov2722_pad_ops,
1235         .sensor = &ov2722_sensor_ops,
1236 };
1237
1238 static int ov2722_remove(struct i2c_client *client)
1239 {
1240         struct v4l2_subdev *sd = i2c_get_clientdata(client);
1241         struct ov2722_device *dev = to_ov2722_sensor(sd);
1242         dev_dbg(&client->dev, "ov2722_remove...\n");
1243
1244         if (dev->platform_data->platform_deinit)
1245                 dev->platform_data->platform_deinit();
1246
1247         dev->platform_data->csi_cfg(sd, 0);
1248         v4l2_ctrl_handler_free(&dev->ctrl_handler);
1249         v4l2_device_unregister_subdev(sd);
1250
1251         atomisp_gmin_remove_subdev(sd);
1252
1253         media_entity_cleanup(&dev->sd.entity);
1254         kfree(dev);
1255
1256         return 0;
1257 }
1258
1259 static int __ov2722_init_ctrl_handler(struct ov2722_device *dev)
1260 {
1261         struct v4l2_ctrl_handler *hdl;
1262         unsigned int i;
1263         hdl = &dev->ctrl_handler;
1264         v4l2_ctrl_handler_init(&dev->ctrl_handler, ARRAY_SIZE(ov2722_controls));
1265         for (i = 0; i < ARRAY_SIZE(ov2722_controls); i++)
1266                 v4l2_ctrl_new_custom(&dev->ctrl_handler, &ov2722_controls[i],
1267                                      NULL);
1268
1269         dev->link_freq = v4l2_ctrl_find(&dev->ctrl_handler, V4L2_CID_LINK_FREQ);
1270
1271         if (dev->ctrl_handler.error || !dev->link_freq)
1272                 return dev->ctrl_handler.error;
1273
1274         dev->sd.ctrl_handler = hdl;
1275
1276         return 0;
1277 }
1278
1279 static int ov2722_probe(struct i2c_client *client,
1280                         const struct i2c_device_id *id)
1281 {
1282         struct ov2722_device *dev;
1283         void *ovpdev;
1284         int ret;
1285         struct acpi_device *adev;
1286
1287         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1288         if (!dev) {
1289                 dev_err(&client->dev, "out of memory\n");
1290                 return -ENOMEM;
1291         }
1292
1293         mutex_init(&dev->input_lock);
1294
1295         dev->fmt_idx = 0;
1296         v4l2_i2c_subdev_init(&(dev->sd), client, &ov2722_ops);
1297
1298         ovpdev = client->dev.platform_data;
1299         adev = ACPI_COMPANION(&client->dev);
1300         if (adev) {
1301                 adev->power.flags.power_resources = 0;
1302                 ovpdev = gmin_camera_platform_data(&dev->sd,
1303                                                    ATOMISP_INPUT_FORMAT_RAW_10,
1304                                                    atomisp_bayer_order_grbg);
1305         }
1306
1307         ret = ov2722_s_config(&dev->sd, client->irq, ovpdev);
1308         if (ret)
1309                 goto out_free;
1310
1311         ret = __ov2722_init_ctrl_handler(dev);
1312         if (ret)
1313                 goto out_ctrl_handler_free;
1314
1315         dev->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
1316         dev->pad.flags = MEDIA_PAD_FL_SOURCE;
1317         dev->format.code = MEDIA_BUS_FMT_SBGGR10_1X10;
1318         dev->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
1319
1320         ret = media_entity_pads_init(&dev->sd.entity, 1, &dev->pad);
1321         if (ret)
1322                 ov2722_remove(client);
1323
1324         if (ACPI_HANDLE(&client->dev))
1325                 ret = atomisp_register_i2c_module(&dev->sd, ovpdev, RAW_CAMERA);
1326
1327         return ret;
1328
1329 out_ctrl_handler_free:
1330         v4l2_ctrl_handler_free(&dev->ctrl_handler);
1331
1332 out_free:
1333         v4l2_device_unregister_subdev(&dev->sd);
1334         kfree(dev);
1335         return ret;
1336 }
1337
1338 MODULE_DEVICE_TABLE(i2c, ov2722_id);
1339
1340 static const struct acpi_device_id ov2722_acpi_match[] = {
1341         { "INT33FB" },
1342         {},
1343 };
1344
1345 MODULE_DEVICE_TABLE(acpi, ov2722_acpi_match);
1346
1347 static struct i2c_driver ov2722_driver = {
1348         .driver = {
1349                 .name = OV2722_NAME,
1350                 .acpi_match_table = ACPI_PTR(ov2722_acpi_match),
1351         },
1352         .probe = ov2722_probe,
1353         .remove = ov2722_remove,
1354         .id_table = ov2722_id,
1355 };
1356
1357 static int init_ov2722(void)
1358 {
1359         return i2c_add_driver(&ov2722_driver);
1360 }
1361
1362 static void exit_ov2722(void)
1363 {
1364
1365         i2c_del_driver(&ov2722_driver);
1366 }
1367
1368 module_init(init_ov2722);
1369 module_exit(exit_ov2722);
1370
1371 MODULE_AUTHOR("Wei Liu <wei.liu@intel.com>");
1372 MODULE_DESCRIPTION("A low-level driver for OmniVision 2722 sensors");
1373 MODULE_LICENSE("GPL");