388cfd012212c81170389fb721cde0bdf40a3d00
[platform/kernel/linux-rpi.git] / drivers / staging / media / imx / imx7-mipi-csis.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Freescale i.MX7 SoC series MIPI-CSI V3.3 receiver driver
4  *
5  * Copyright (C) 2019 Linaro Ltd
6  * Copyright (C) 2015-2016 Freescale Semiconductor, Inc. All Rights Reserved.
7  * Copyright (C) 2011 - 2013 Samsung Electronics Co., Ltd.
8  *
9  */
10
11 #include <linux/clk.h>
12 #include <linux/debugfs.h>
13 #include <linux/delay.h>
14 #include <linux/errno.h>
15 #include <linux/interrupt.h>
16 #include <linux/io.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/of.h>
21 #include <linux/of_device.h>
22 #include <linux/platform_device.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/regulator/consumer.h>
25 #include <linux/reset.h>
26 #include <linux/spinlock.h>
27
28 #include <media/v4l2-common.h>
29 #include <media/v4l2-device.h>
30 #include <media/v4l2-fwnode.h>
31 #include <media/v4l2-mc.h>
32 #include <media/v4l2-subdev.h>
33
34 #define CSIS_DRIVER_NAME                        "imx7-mipi-csis"
35
36 #define CSIS_PAD_SINK                           0
37 #define CSIS_PAD_SOURCE                         1
38 #define CSIS_PADS_NUM                           2
39
40 #define MIPI_CSIS_DEF_PIX_WIDTH                 640
41 #define MIPI_CSIS_DEF_PIX_HEIGHT                480
42
43 /* Register map definition */
44
45 /* CSIS common control */
46 #define MIPI_CSIS_CMN_CTRL                      0x04
47 #define MIPI_CSIS_CMN_CTRL_UPDATE_SHADOW        BIT(16)
48 #define MIPI_CSIS_CMN_CTRL_INTER_MODE           BIT(10)
49 #define MIPI_CSIS_CMN_CTRL_UPDATE_SHADOW_CTRL   BIT(2)
50 #define MIPI_CSIS_CMN_CTRL_RESET                BIT(1)
51 #define MIPI_CSIS_CMN_CTRL_ENABLE               BIT(0)
52
53 #define MIPI_CSIS_CMN_CTRL_LANE_NR_OFFSET       8
54 #define MIPI_CSIS_CMN_CTRL_LANE_NR_MASK         (3 << 8)
55
56 /* CSIS clock control */
57 #define MIPI_CSIS_CLK_CTRL                      0x08
58 #define MIPI_CSIS_CLK_CTRL_CLKGATE_TRAIL_CH3(x) ((x) << 28)
59 #define MIPI_CSIS_CLK_CTRL_CLKGATE_TRAIL_CH2(x) ((x) << 24)
60 #define MIPI_CSIS_CLK_CTRL_CLKGATE_TRAIL_CH1(x) ((x) << 20)
61 #define MIPI_CSIS_CLK_CTRL_CLKGATE_TRAIL_CH0(x) ((x) << 16)
62 #define MIPI_CSIS_CLK_CTRL_CLKGATE_EN_MSK       (0xf << 4)
63 #define MIPI_CSIS_CLK_CTRL_WCLK_SRC             BIT(0)
64
65 /* CSIS Interrupt mask */
66 #define MIPI_CSIS_INT_MSK                       0x10
67 #define MIPI_CSIS_INT_MSK_EVEN_BEFORE           BIT(31)
68 #define MIPI_CSIS_INT_MSK_EVEN_AFTER            BIT(30)
69 #define MIPI_CSIS_INT_MSK_ODD_BEFORE            BIT(29)
70 #define MIPI_CSIS_INT_MSK_ODD_AFTER             BIT(28)
71 #define MIPI_CSIS_INT_MSK_FRAME_START           BIT(24)
72 #define MIPI_CSIS_INT_MSK_FRAME_END             BIT(20)
73 #define MIPI_CSIS_INT_MSK_ERR_SOT_HS            BIT(16)
74 #define MIPI_CSIS_INT_MSK_ERR_LOST_FS           BIT(12)
75 #define MIPI_CSIS_INT_MSK_ERR_LOST_FE           BIT(8)
76 #define MIPI_CSIS_INT_MSK_ERR_OVER              BIT(4)
77 #define MIPI_CSIS_INT_MSK_ERR_WRONG_CFG         BIT(3)
78 #define MIPI_CSIS_INT_MSK_ERR_ECC               BIT(2)
79 #define MIPI_CSIS_INT_MSK_ERR_CRC               BIT(1)
80 #define MIPI_CSIS_INT_MSK_ERR_UNKNOWN           BIT(0)
81
82 /* CSIS Interrupt source */
83 #define MIPI_CSIS_INT_SRC                       0x14
84 #define MIPI_CSIS_INT_SRC_EVEN_BEFORE           BIT(31)
85 #define MIPI_CSIS_INT_SRC_EVEN_AFTER            BIT(30)
86 #define MIPI_CSIS_INT_SRC_EVEN                  BIT(30)
87 #define MIPI_CSIS_INT_SRC_ODD_BEFORE            BIT(29)
88 #define MIPI_CSIS_INT_SRC_ODD_AFTER             BIT(28)
89 #define MIPI_CSIS_INT_SRC_ODD                   (0x3 << 28)
90 #define MIPI_CSIS_INT_SRC_NON_IMAGE_DATA        (0xf << 28)
91 #define MIPI_CSIS_INT_SRC_FRAME_START           BIT(24)
92 #define MIPI_CSIS_INT_SRC_FRAME_END             BIT(20)
93 #define MIPI_CSIS_INT_SRC_ERR_SOT_HS            BIT(16)
94 #define MIPI_CSIS_INT_SRC_ERR_LOST_FS           BIT(12)
95 #define MIPI_CSIS_INT_SRC_ERR_LOST_FE           BIT(8)
96 #define MIPI_CSIS_INT_SRC_ERR_OVER              BIT(4)
97 #define MIPI_CSIS_INT_SRC_ERR_WRONG_CFG         BIT(3)
98 #define MIPI_CSIS_INT_SRC_ERR_ECC               BIT(2)
99 #define MIPI_CSIS_INT_SRC_ERR_CRC               BIT(1)
100 #define MIPI_CSIS_INT_SRC_ERR_UNKNOWN           BIT(0)
101 #define MIPI_CSIS_INT_SRC_ERRORS                0xfffff
102
103 /* D-PHY status control */
104 #define MIPI_CSIS_DPHY_STATUS                   0x20
105 #define MIPI_CSIS_DPHY_STATUS_ULPS_DAT          BIT(8)
106 #define MIPI_CSIS_DPHY_STATUS_STOPSTATE_DAT     BIT(4)
107 #define MIPI_CSIS_DPHY_STATUS_ULPS_CLK          BIT(1)
108 #define MIPI_CSIS_DPHY_STATUS_STOPSTATE_CLK     BIT(0)
109
110 /* D-PHY common control */
111 #define MIPI_CSIS_DPHY_CMN_CTRL                 0x24
112 #define MIPI_CSIS_DPHY_CMN_CTRL_HSSETTLE(n)     ((n) << 24)
113 #define MIPI_CSIS_DPHY_CMN_CTRL_HSSETTLE_MASK   GENMASK(31, 24)
114 #define MIPI_CSIS_DPHY_CMN_CTRL_CLKSETTLE(n)    ((n) << 22)
115 #define MIPI_CSIS_DPHY_CMN_CTRL_CLKSETTLE_MASK  GENMASK(23, 22)
116 #define MIPI_CSIS_DPHY_CMN_CTRL_DPDN_SWAP_CLK   BIT(6)
117 #define MIPI_CSIS_DPHY_CMN_CTRL_DPDN_SWAP_DAT   BIT(5)
118 #define MIPI_CSIS_DPHY_CMN_CTRL_ENABLE_DAT      BIT(1)
119 #define MIPI_CSIS_DPHY_CMN_CTRL_ENABLE_CLK      BIT(0)
120 #define MIPI_CSIS_DPHY_CMN_CTRL_ENABLE          (0x1f << 0)
121
122 /* D-PHY Master and Slave Control register Low */
123 #define MIPI_CSIS_DPHY_BCTRL_L                  0x30
124 #define MIPI_CSIS_DPHY_BCTRL_L_USER_DATA_PATTERN_LOW(n)         (((n) & 3U) << 30)
125 #define MIPI_CSIS_DPHY_BCTRL_L_BIAS_REF_VOLT_715MV              (0 << 28)
126 #define MIPI_CSIS_DPHY_BCTRL_L_BIAS_REF_VOLT_724MV              (1 << 28)
127 #define MIPI_CSIS_DPHY_BCTRL_L_BIAS_REF_VOLT_733MV              (2 << 28)
128 #define MIPI_CSIS_DPHY_BCTRL_L_BIAS_REF_VOLT_706MV              (3 << 28)
129 #define MIPI_CSIS_DPHY_BCTRL_L_BGR_CHOPPER_FREQ_3MHZ            (0 << 27)
130 #define MIPI_CSIS_DPHY_BCTRL_L_BGR_CHOPPER_FREQ_1_5MHZ          (1 << 27)
131 #define MIPI_CSIS_DPHY_BCTRL_L_VREG12_EXTPWR_EN_CTL             BIT(26)
132 #define MIPI_CSIS_DPHY_BCTRL_L_REG_12P_LVL_CTL_1_2V             (0 << 24)
133 #define MIPI_CSIS_DPHY_BCTRL_L_REG_12P_LVL_CTL_1_23V            (1 << 24)
134 #define MIPI_CSIS_DPHY_BCTRL_L_REG_12P_LVL_CTL_1_17V            (2 << 24)
135 #define MIPI_CSIS_DPHY_BCTRL_L_REG_12P_LVL_CTL_1_26V            (3 << 24)
136 #define MIPI_CSIS_DPHY_BCTRL_L_REG_1P2_LVL_SEL                  BIT(23)
137 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_HYS_LVL_80MV               (0 << 21)
138 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_HYS_LVL_100MV              (1 << 21)
139 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_HYS_LVL_120MV              (2 << 21)
140 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_HYS_LVL_140MV              (3 << 21)
141 #define MIPI_CSIS_DPHY_BCTRL_L_VREF_SRC_SEL                     BIT(20)
142 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_VREF_LVL_715MV             (0 << 18)
143 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_VREF_LVL_743MV             (1 << 18)
144 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_VREF_LVL_650MV             (2 << 18)
145 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_VREF_LVL_682MV             (3 << 18)
146 #define MIPI_CSIS_DPHY_BCTRL_L_LP_RX_PULSE_REJECT               BIT(17)
147 #define MIPI_CSIS_DPHY_BCTRL_L_MSTRCLK_LP_SLEW_RATE_DOWN_0      (0 << 15)
148 #define MIPI_CSIS_DPHY_BCTRL_L_MSTRCLK_LP_SLEW_RATE_DOWN_15P    (1 << 15)
149 #define MIPI_CSIS_DPHY_BCTRL_L_MSTRCLK_LP_SLEW_RATE_DOWN_30P    (3 << 15)
150 #define MIPI_CSIS_DPHY_BCTRL_L_MSTRCLK_LP_SLEW_RATE_UP          BIT(14)
151 #define MIPI_CSIS_DPHY_BCTRL_L_LP_CD_HYS_60MV                   (0 << 13)
152 #define MIPI_CSIS_DPHY_BCTRL_L_LP_CD_HYS_70MV                   (1 << 13)
153 #define MIPI_CSIS_DPHY_BCTRL_L_BGR_CHOPPER_EN                   BIT(12)
154 #define MIPI_CSIS_DPHY_BCTRL_L_ERRCONTENTION_LP_EN              BIT(11)
155 #define MIPI_CSIS_DPHY_BCTRL_L_TXTRIGGER_CLK_EN                 BIT(10)
156 #define MIPI_CSIS_DPHY_BCTRL_L_B_DPHYCTRL(n)                    (((n) * 25 / 1000000) << 0)
157
158 /* D-PHY Master and Slave Control register High */
159 #define MIPI_CSIS_DPHY_BCTRL_H                  0x34
160 /* D-PHY Slave Control register Low */
161 #define MIPI_CSIS_DPHY_SCTRL_L                  0x38
162 /* D-PHY Slave Control register High */
163 #define MIPI_CSIS_DPHY_SCTRL_H                  0x3c
164
165 /* ISP Configuration register */
166 #define MIPI_CSIS_ISP_CONFIG_CH(n)              (0x40 + (n) * 0x10)
167 #define MIPI_CSIS_ISPCFG_MEM_FULL_GAP_MSK       (0xff << 24)
168 #define MIPI_CSIS_ISPCFG_MEM_FULL_GAP(x)        ((x) << 24)
169 #define MIPI_CSIS_ISPCFG_PIXEL_MODE_SINGLE      (0 << 12)
170 #define MIPI_CSIS_ISPCFG_PIXEL_MODE_DUAL        (1 << 12)
171 #define MIPI_CSIS_ISPCFG_PIXEL_MODE_QUAD        (2 << 12)       /* i.MX8M[MNP] only */
172 #define MIPI_CSIS_ISPCFG_ALIGN_32BIT            BIT(11)
173 #define MIPI_CSIS_ISPCFG_FMT(fmt)               ((fmt) << 2)
174 #define MIPI_CSIS_ISPCFG_FMT_MASK               (0x3f << 2)
175
176 /* ISP Image Resolution register */
177 #define MIPI_CSIS_ISP_RESOL_CH(n)               (0x44 + (n) * 0x10)
178 #define CSIS_MAX_PIX_WIDTH                      0xffff
179 #define CSIS_MAX_PIX_HEIGHT                     0xffff
180
181 /* ISP SYNC register */
182 #define MIPI_CSIS_ISP_SYNC_CH(n)                (0x48 + (n) * 0x10)
183 #define MIPI_CSIS_ISP_SYNC_HSYNC_LINTV_OFFSET   18
184 #define MIPI_CSIS_ISP_SYNC_VSYNC_SINTV_OFFSET   12
185 #define MIPI_CSIS_ISP_SYNC_VSYNC_EINTV_OFFSET   0
186
187 /* ISP shadow registers */
188 #define MIPI_CSIS_SDW_CONFIG_CH(n)              (0x80 + (n) * 0x10)
189 #define MIPI_CSIS_SDW_RESOL_CH(n)               (0x84 + (n) * 0x10)
190 #define MIPI_CSIS_SDW_SYNC_CH(n)                (0x88 + (n) * 0x10)
191
192 /* Debug control register */
193 #define MIPI_CSIS_DBG_CTRL                      0xc0
194 #define MIPI_CSIS_DBG_INTR_MSK                  0xc4
195 #define MIPI_CSIS_DBG_INTR_MSK_DT_NOT_SUPPORT   BIT(25)
196 #define MIPI_CSIS_DBG_INTR_MSK_DT_IGNORE        BIT(24)
197 #define MIPI_CSIS_DBG_INTR_MSK_ERR_FRAME_SIZE   BIT(20)
198 #define MIPI_CSIS_DBG_INTR_MSK_TRUNCATED_FRAME  BIT(16)
199 #define MIPI_CSIS_DBG_INTR_MSK_EARLY_FE         BIT(12)
200 #define MIPI_CSIS_DBG_INTR_MSK_EARLY_FS         BIT(8)
201 #define MIPI_CSIS_DBG_INTR_MSK_CAM_VSYNC_FALL   BIT(4)
202 #define MIPI_CSIS_DBG_INTR_MSK_CAM_VSYNC_RISE   BIT(0)
203 #define MIPI_CSIS_DBG_INTR_SRC                  0xc8
204 #define MIPI_CSIS_DBG_INTR_SRC_DT_NOT_SUPPORT   BIT(25)
205 #define MIPI_CSIS_DBG_INTR_SRC_DT_IGNORE        BIT(24)
206 #define MIPI_CSIS_DBG_INTR_SRC_ERR_FRAME_SIZE   BIT(20)
207 #define MIPI_CSIS_DBG_INTR_SRC_TRUNCATED_FRAME  BIT(16)
208 #define MIPI_CSIS_DBG_INTR_SRC_EARLY_FE         BIT(12)
209 #define MIPI_CSIS_DBG_INTR_SRC_EARLY_FS         BIT(8)
210 #define MIPI_CSIS_DBG_INTR_SRC_CAM_VSYNC_FALL   BIT(4)
211 #define MIPI_CSIS_DBG_INTR_SRC_CAM_VSYNC_RISE   BIT(0)
212
213 #define MIPI_CSIS_FRAME_COUNTER_CH(n)           (0x0100 + (n) * 4)
214
215 /* Non-image packet data buffers */
216 #define MIPI_CSIS_PKTDATA_ODD                   0x2000
217 #define MIPI_CSIS_PKTDATA_EVEN                  0x3000
218 #define MIPI_CSIS_PKTDATA_SIZE                  SZ_4K
219
220 #define DEFAULT_SCLK_CSIS_FREQ                  166000000UL
221
222 /* MIPI CSI-2 Data Types */
223 #define MIPI_CSI2_DATA_TYPE_YUV420_8            0x18
224 #define MIPI_CSI2_DATA_TYPE_YUV420_10           0x19
225 #define MIPI_CSI2_DATA_TYPE_LE_YUV420_8         0x1a
226 #define MIPI_CSI2_DATA_TYPE_CS_YUV420_8         0x1c
227 #define MIPI_CSI2_DATA_TYPE_CS_YUV420_10        0x1d
228 #define MIPI_CSI2_DATA_TYPE_YUV422_8            0x1e
229 #define MIPI_CSI2_DATA_TYPE_YUV422_10           0x1f
230 #define MIPI_CSI2_DATA_TYPE_RGB565              0x22
231 #define MIPI_CSI2_DATA_TYPE_RGB666              0x23
232 #define MIPI_CSI2_DATA_TYPE_RGB888              0x24
233 #define MIPI_CSI2_DATA_TYPE_RAW6                0x28
234 #define MIPI_CSI2_DATA_TYPE_RAW7                0x29
235 #define MIPI_CSI2_DATA_TYPE_RAW8                0x2a
236 #define MIPI_CSI2_DATA_TYPE_RAW10               0x2b
237 #define MIPI_CSI2_DATA_TYPE_RAW12               0x2c
238 #define MIPI_CSI2_DATA_TYPE_RAW14               0x2d
239 #define MIPI_CSI2_DATA_TYPE_USER(x)             (0x30 + (x))
240
241 enum {
242         ST_POWERED      = 1,
243         ST_STREAMING    = 2,
244         ST_SUSPENDED    = 4,
245 };
246
247 struct mipi_csis_event {
248         bool debug;
249         u32 mask;
250         const char * const name;
251         unsigned int counter;
252 };
253
254 static const struct mipi_csis_event mipi_csis_events[] = {
255         /* Errors */
256         { false, MIPI_CSIS_INT_SRC_ERR_SOT_HS,          "SOT Error" },
257         { false, MIPI_CSIS_INT_SRC_ERR_LOST_FS,         "Lost Frame Start Error" },
258         { false, MIPI_CSIS_INT_SRC_ERR_LOST_FE,         "Lost Frame End Error" },
259         { false, MIPI_CSIS_INT_SRC_ERR_OVER,            "FIFO Overflow Error" },
260         { false, MIPI_CSIS_INT_SRC_ERR_WRONG_CFG,       "Wrong Configuration Error" },
261         { false, MIPI_CSIS_INT_SRC_ERR_ECC,             "ECC Error" },
262         { false, MIPI_CSIS_INT_SRC_ERR_CRC,             "CRC Error" },
263         { false, MIPI_CSIS_INT_SRC_ERR_UNKNOWN,         "Unknown Error" },
264         { true, MIPI_CSIS_DBG_INTR_SRC_DT_NOT_SUPPORT,  "Data Type Not Supported" },
265         { true, MIPI_CSIS_DBG_INTR_SRC_DT_IGNORE,       "Data Type Ignored" },
266         { true, MIPI_CSIS_DBG_INTR_SRC_ERR_FRAME_SIZE,  "Frame Size Error" },
267         { true, MIPI_CSIS_DBG_INTR_SRC_TRUNCATED_FRAME, "Truncated Frame" },
268         { true, MIPI_CSIS_DBG_INTR_SRC_EARLY_FE,        "Early Frame End" },
269         { true, MIPI_CSIS_DBG_INTR_SRC_EARLY_FS,        "Early Frame Start" },
270         /* Non-image data receive events */
271         { false, MIPI_CSIS_INT_SRC_EVEN_BEFORE,         "Non-image data before even frame" },
272         { false, MIPI_CSIS_INT_SRC_EVEN_AFTER,          "Non-image data after even frame" },
273         { false, MIPI_CSIS_INT_SRC_ODD_BEFORE,          "Non-image data before odd frame" },
274         { false, MIPI_CSIS_INT_SRC_ODD_AFTER,           "Non-image data after odd frame" },
275         /* Frame start/end */
276         { false, MIPI_CSIS_INT_SRC_FRAME_START,         "Frame Start" },
277         { false, MIPI_CSIS_INT_SRC_FRAME_END,           "Frame End" },
278         { true, MIPI_CSIS_DBG_INTR_SRC_CAM_VSYNC_FALL,  "VSYNC Falling Edge" },
279         { true, MIPI_CSIS_DBG_INTR_SRC_CAM_VSYNC_RISE,  "VSYNC Rising Edge" },
280 };
281
282 #define MIPI_CSIS_NUM_EVENTS ARRAY_SIZE(mipi_csis_events)
283
284 enum mipi_csis_clk {
285         MIPI_CSIS_CLK_PCLK,
286         MIPI_CSIS_CLK_WRAP,
287         MIPI_CSIS_CLK_PHY,
288         MIPI_CSIS_CLK_AXI,
289 };
290
291 static const char * const mipi_csis_clk_id[] = {
292         "pclk",
293         "wrap",
294         "phy",
295         "axi",
296 };
297
298 enum mipi_csis_version {
299         MIPI_CSIS_V3_3,
300         MIPI_CSIS_V3_6_3,
301 };
302
303 struct mipi_csis_info {
304         enum mipi_csis_version version;
305         unsigned int num_clocks;
306 };
307
308 struct csi_state {
309         struct device *dev;
310         void __iomem *regs;
311         struct clk_bulk_data *clks;
312         struct reset_control *mrst;
313         struct regulator *mipi_phy_regulator;
314         const struct mipi_csis_info *info;
315
316         struct v4l2_subdev sd;
317         struct media_pad pads[CSIS_PADS_NUM];
318         struct v4l2_async_notifier notifier;
319         struct v4l2_subdev *src_sd;
320
321         struct v4l2_mbus_config_mipi_csi2 bus;
322         u32 clk_frequency;
323         u32 hs_settle;
324         u32 clk_settle;
325
326         struct mutex lock;      /* Protect csis_fmt, format_mbus and state */
327         const struct csis_pix_format *csis_fmt;
328         struct v4l2_mbus_framefmt format_mbus;
329         u32 state;
330
331         spinlock_t slock;       /* Protect events */
332         struct mipi_csis_event events[MIPI_CSIS_NUM_EVENTS];
333         struct dentry *debugfs_root;
334         struct {
335                 bool enable;
336                 u32 hs_settle;
337                 u32 clk_settle;
338         } debug;
339 };
340
341 /* -----------------------------------------------------------------------------
342  * Format helpers
343  */
344
345 struct csis_pix_format {
346         u32 code;
347         u32 data_type;
348         u8 width;
349 };
350
351 static const struct csis_pix_format mipi_csis_formats[] = {
352         /* YUV formats. */
353         {
354                 .code = MEDIA_BUS_FMT_UYVY8_1X16,
355                 .data_type = MIPI_CSI2_DATA_TYPE_YUV422_8,
356                 .width = 16,
357         },
358         /* RAW (Bayer and greyscale) formats. */
359         {
360                 .code = MEDIA_BUS_FMT_SBGGR8_1X8,
361                 .data_type = MIPI_CSI2_DATA_TYPE_RAW8,
362                 .width = 8,
363         }, {
364                 .code = MEDIA_BUS_FMT_SGBRG8_1X8,
365                 .data_type = MIPI_CSI2_DATA_TYPE_RAW8,
366                 .width = 8,
367         }, {
368                 .code = MEDIA_BUS_FMT_SGRBG8_1X8,
369                 .data_type = MIPI_CSI2_DATA_TYPE_RAW8,
370                 .width = 8,
371         }, {
372                 .code = MEDIA_BUS_FMT_SRGGB8_1X8,
373                 .data_type = MIPI_CSI2_DATA_TYPE_RAW8,
374                 .width = 8,
375         }, {
376                 .code = MEDIA_BUS_FMT_Y8_1X8,
377                 .data_type = MIPI_CSI2_DATA_TYPE_RAW8,
378                 .width = 8,
379         }, {
380                 .code = MEDIA_BUS_FMT_SBGGR10_1X10,
381                 .data_type = MIPI_CSI2_DATA_TYPE_RAW10,
382                 .width = 10,
383         }, {
384                 .code = MEDIA_BUS_FMT_SGBRG10_1X10,
385                 .data_type = MIPI_CSI2_DATA_TYPE_RAW10,
386                 .width = 10,
387         }, {
388                 .code = MEDIA_BUS_FMT_SGRBG10_1X10,
389                 .data_type = MIPI_CSI2_DATA_TYPE_RAW10,
390                 .width = 10,
391         }, {
392                 .code = MEDIA_BUS_FMT_SRGGB10_1X10,
393                 .data_type = MIPI_CSI2_DATA_TYPE_RAW10,
394                 .width = 10,
395         }, {
396                 .code = MEDIA_BUS_FMT_Y10_1X10,
397                 .data_type = MIPI_CSI2_DATA_TYPE_RAW10,
398                 .width = 10,
399         }, {
400                 .code = MEDIA_BUS_FMT_SBGGR12_1X12,
401                 .data_type = MIPI_CSI2_DATA_TYPE_RAW12,
402                 .width = 12,
403         }, {
404                 .code = MEDIA_BUS_FMT_SGBRG12_1X12,
405                 .data_type = MIPI_CSI2_DATA_TYPE_RAW12,
406                 .width = 12,
407         }, {
408                 .code = MEDIA_BUS_FMT_SGRBG12_1X12,
409                 .data_type = MIPI_CSI2_DATA_TYPE_RAW12,
410                 .width = 12,
411         }, {
412                 .code = MEDIA_BUS_FMT_SRGGB12_1X12,
413                 .data_type = MIPI_CSI2_DATA_TYPE_RAW12,
414                 .width = 12,
415         }, {
416                 .code = MEDIA_BUS_FMT_Y12_1X12,
417                 .data_type = MIPI_CSI2_DATA_TYPE_RAW12,
418                 .width = 12,
419         }, {
420                 .code = MEDIA_BUS_FMT_SBGGR14_1X14,
421                 .data_type = MIPI_CSI2_DATA_TYPE_RAW14,
422                 .width = 14,
423         }, {
424                 .code = MEDIA_BUS_FMT_SGBRG14_1X14,
425                 .data_type = MIPI_CSI2_DATA_TYPE_RAW14,
426                 .width = 14,
427         }, {
428                 .code = MEDIA_BUS_FMT_SGRBG14_1X14,
429                 .data_type = MIPI_CSI2_DATA_TYPE_RAW14,
430                 .width = 14,
431         }, {
432                 .code = MEDIA_BUS_FMT_SRGGB14_1X14,
433                 .data_type = MIPI_CSI2_DATA_TYPE_RAW14,
434                 .width = 14,
435         }
436 };
437
438 static const struct csis_pix_format *find_csis_format(u32 code)
439 {
440         unsigned int i;
441
442         for (i = 0; i < ARRAY_SIZE(mipi_csis_formats); i++)
443                 if (code == mipi_csis_formats[i].code)
444                         return &mipi_csis_formats[i];
445         return NULL;
446 }
447
448 /* -----------------------------------------------------------------------------
449  * Hardware configuration
450  */
451
452 static inline u32 mipi_csis_read(struct csi_state *state, u32 reg)
453 {
454         return readl(state->regs + reg);
455 }
456
457 static inline void mipi_csis_write(struct csi_state *state, u32 reg, u32 val)
458 {
459         writel(val, state->regs + reg);
460 }
461
462 static void mipi_csis_enable_interrupts(struct csi_state *state, bool on)
463 {
464         mipi_csis_write(state, MIPI_CSIS_INT_MSK, on ? 0xffffffff : 0);
465         mipi_csis_write(state, MIPI_CSIS_DBG_INTR_MSK, on ? 0xffffffff : 0);
466 }
467
468 static void mipi_csis_sw_reset(struct csi_state *state)
469 {
470         u32 val = mipi_csis_read(state, MIPI_CSIS_CMN_CTRL);
471
472         mipi_csis_write(state, MIPI_CSIS_CMN_CTRL,
473                         val | MIPI_CSIS_CMN_CTRL_RESET);
474         usleep_range(10, 20);
475 }
476
477 static void mipi_csis_system_enable(struct csi_state *state, int on)
478 {
479         u32 val, mask;
480
481         val = mipi_csis_read(state, MIPI_CSIS_CMN_CTRL);
482         if (on)
483                 val |= MIPI_CSIS_CMN_CTRL_ENABLE;
484         else
485                 val &= ~MIPI_CSIS_CMN_CTRL_ENABLE;
486         mipi_csis_write(state, MIPI_CSIS_CMN_CTRL, val);
487
488         val = mipi_csis_read(state, MIPI_CSIS_DPHY_CMN_CTRL);
489         val &= ~MIPI_CSIS_DPHY_CMN_CTRL_ENABLE;
490         if (on) {
491                 mask = (1 << (state->bus.num_data_lanes + 1)) - 1;
492                 val |= (mask & MIPI_CSIS_DPHY_CMN_CTRL_ENABLE);
493         }
494         mipi_csis_write(state, MIPI_CSIS_DPHY_CMN_CTRL, val);
495 }
496
497 /* Called with the state.lock mutex held */
498 static void __mipi_csis_set_format(struct csi_state *state)
499 {
500         struct v4l2_mbus_framefmt *mf = &state->format_mbus;
501         u32 val;
502
503         /* Color format */
504         val = mipi_csis_read(state, MIPI_CSIS_ISP_CONFIG_CH(0));
505         val &= ~(MIPI_CSIS_ISPCFG_ALIGN_32BIT | MIPI_CSIS_ISPCFG_FMT_MASK);
506         val |= MIPI_CSIS_ISPCFG_FMT(state->csis_fmt->data_type);
507         mipi_csis_write(state, MIPI_CSIS_ISP_CONFIG_CH(0), val);
508
509         /* Pixel resolution */
510         val = mf->width | (mf->height << 16);
511         mipi_csis_write(state, MIPI_CSIS_ISP_RESOL_CH(0), val);
512 }
513
514 static int mipi_csis_calculate_params(struct csi_state *state)
515 {
516         s64 link_freq;
517         u32 lane_rate;
518
519         /* Calculate the line rate from the pixel rate. */
520         link_freq = v4l2_get_link_freq(state->src_sd->ctrl_handler,
521                                        state->csis_fmt->width,
522                                        state->bus.num_data_lanes * 2);
523         if (link_freq < 0) {
524                 dev_err(state->dev, "Unable to obtain link frequency: %d\n",
525                         (int)link_freq);
526                 return link_freq;
527         }
528
529         lane_rate = link_freq * 2;
530
531         if (lane_rate < 80000000 || lane_rate > 1500000000) {
532                 dev_dbg(state->dev, "Out-of-bound lane rate %u\n", lane_rate);
533                 return -EINVAL;
534         }
535
536         /*
537          * The HSSETTLE counter value is document in a table, but can also
538          * easily be calculated. Hardcode the CLKSETTLE value to 0 for now
539          * (which is documented as corresponding to CSI-2 v0.87 to v1.00) until
540          * we figure out how to compute it correctly.
541          */
542         state->hs_settle = (lane_rate - 5000000) / 45000000;
543         state->clk_settle = 0;
544
545         dev_dbg(state->dev, "lane rate %u, Tclk_settle %u, Ths_settle %u\n",
546                 lane_rate, state->clk_settle, state->hs_settle);
547
548         if (state->debug.hs_settle < 0xff) {
549                 dev_dbg(state->dev, "overriding Ths_settle with %u\n",
550                         state->debug.hs_settle);
551                 state->hs_settle = state->debug.hs_settle;
552         }
553
554         if (state->debug.clk_settle < 4) {
555                 dev_dbg(state->dev, "overriding Tclk_settle with %u\n",
556                         state->debug.clk_settle);
557                 state->clk_settle = state->debug.clk_settle;
558         }
559
560         return 0;
561 }
562
563 static void mipi_csis_set_params(struct csi_state *state)
564 {
565         int lanes = state->bus.num_data_lanes;
566         u32 val;
567
568         val = mipi_csis_read(state, MIPI_CSIS_CMN_CTRL);
569         val &= ~MIPI_CSIS_CMN_CTRL_LANE_NR_MASK;
570         val |= (lanes - 1) << MIPI_CSIS_CMN_CTRL_LANE_NR_OFFSET;
571         if (state->info->version == MIPI_CSIS_V3_3)
572                 val |= MIPI_CSIS_CMN_CTRL_INTER_MODE;
573         mipi_csis_write(state, MIPI_CSIS_CMN_CTRL, val);
574
575         __mipi_csis_set_format(state);
576
577         mipi_csis_write(state, MIPI_CSIS_DPHY_CMN_CTRL,
578                         MIPI_CSIS_DPHY_CMN_CTRL_HSSETTLE(state->hs_settle) |
579                         MIPI_CSIS_DPHY_CMN_CTRL_CLKSETTLE(state->clk_settle));
580
581         val = (0 << MIPI_CSIS_ISP_SYNC_HSYNC_LINTV_OFFSET)
582             | (0 << MIPI_CSIS_ISP_SYNC_VSYNC_SINTV_OFFSET)
583             | (0 << MIPI_CSIS_ISP_SYNC_VSYNC_EINTV_OFFSET);
584         mipi_csis_write(state, MIPI_CSIS_ISP_SYNC_CH(0), val);
585
586         val = mipi_csis_read(state, MIPI_CSIS_CLK_CTRL);
587         val |= MIPI_CSIS_CLK_CTRL_WCLK_SRC;
588         val |= MIPI_CSIS_CLK_CTRL_CLKGATE_TRAIL_CH0(15);
589         val &= ~MIPI_CSIS_CLK_CTRL_CLKGATE_EN_MSK;
590         mipi_csis_write(state, MIPI_CSIS_CLK_CTRL, val);
591
592         mipi_csis_write(state, MIPI_CSIS_DPHY_BCTRL_L,
593                         MIPI_CSIS_DPHY_BCTRL_L_BIAS_REF_VOLT_715MV |
594                         MIPI_CSIS_DPHY_BCTRL_L_BGR_CHOPPER_FREQ_3MHZ |
595                         MIPI_CSIS_DPHY_BCTRL_L_REG_12P_LVL_CTL_1_2V |
596                         MIPI_CSIS_DPHY_BCTRL_L_LP_RX_HYS_LVL_80MV |
597                         MIPI_CSIS_DPHY_BCTRL_L_LP_RX_VREF_LVL_715MV |
598                         MIPI_CSIS_DPHY_BCTRL_L_LP_CD_HYS_60MV |
599                         MIPI_CSIS_DPHY_BCTRL_L_B_DPHYCTRL(20000000));
600         mipi_csis_write(state, MIPI_CSIS_DPHY_BCTRL_H, 0);
601
602         /* Update the shadow register. */
603         val = mipi_csis_read(state, MIPI_CSIS_CMN_CTRL);
604         mipi_csis_write(state, MIPI_CSIS_CMN_CTRL,
605                         val | MIPI_CSIS_CMN_CTRL_UPDATE_SHADOW |
606                         MIPI_CSIS_CMN_CTRL_UPDATE_SHADOW_CTRL);
607 }
608
609 static int mipi_csis_clk_enable(struct csi_state *state)
610 {
611         return clk_bulk_prepare_enable(state->info->num_clocks, state->clks);
612 }
613
614 static void mipi_csis_clk_disable(struct csi_state *state)
615 {
616         clk_bulk_disable_unprepare(state->info->num_clocks, state->clks);
617 }
618
619 static int mipi_csis_clk_get(struct csi_state *state)
620 {
621         unsigned int i;
622         int ret;
623
624         state->clks = devm_kcalloc(state->dev, state->info->num_clocks,
625                                    sizeof(*state->clks), GFP_KERNEL);
626
627         if (!state->clks)
628                 return -ENOMEM;
629
630         for (i = 0; i < state->info->num_clocks; i++)
631                 state->clks[i].id = mipi_csis_clk_id[i];
632
633         ret = devm_clk_bulk_get(state->dev, state->info->num_clocks,
634                                 state->clks);
635         if (ret < 0)
636                 return ret;
637
638         /* Set clock rate */
639         ret = clk_set_rate(state->clks[MIPI_CSIS_CLK_WRAP].clk,
640                            state->clk_frequency);
641         if (ret < 0)
642                 dev_err(state->dev, "set rate=%d failed: %d\n",
643                         state->clk_frequency, ret);
644
645         return ret;
646 }
647
648 static void mipi_csis_start_stream(struct csi_state *state)
649 {
650         mipi_csis_sw_reset(state);
651         mipi_csis_set_params(state);
652         mipi_csis_system_enable(state, true);
653         mipi_csis_enable_interrupts(state, true);
654 }
655
656 static void mipi_csis_stop_stream(struct csi_state *state)
657 {
658         mipi_csis_enable_interrupts(state, false);
659         mipi_csis_system_enable(state, false);
660 }
661
662 static irqreturn_t mipi_csis_irq_handler(int irq, void *dev_id)
663 {
664         struct csi_state *state = dev_id;
665         unsigned long flags;
666         unsigned int i;
667         u32 status;
668         u32 dbg_status;
669
670         status = mipi_csis_read(state, MIPI_CSIS_INT_SRC);
671         dbg_status = mipi_csis_read(state, MIPI_CSIS_DBG_INTR_SRC);
672
673         spin_lock_irqsave(&state->slock, flags);
674
675         /* Update the event/error counters */
676         if ((status & MIPI_CSIS_INT_SRC_ERRORS) || state->debug.enable) {
677                 for (i = 0; i < MIPI_CSIS_NUM_EVENTS; i++) {
678                         struct mipi_csis_event *event = &state->events[i];
679
680                         if ((!event->debug && (status & event->mask)) ||
681                             (event->debug && (dbg_status & event->mask)))
682                                 event->counter++;
683                 }
684         }
685         spin_unlock_irqrestore(&state->slock, flags);
686
687         mipi_csis_write(state, MIPI_CSIS_INT_SRC, status);
688         mipi_csis_write(state, MIPI_CSIS_DBG_INTR_SRC, dbg_status);
689
690         return IRQ_HANDLED;
691 }
692
693 /* -----------------------------------------------------------------------------
694  * PHY regulator and reset
695  */
696
697 static int mipi_csis_phy_enable(struct csi_state *state)
698 {
699         if (state->info->version != MIPI_CSIS_V3_3)
700                 return 0;
701
702         return regulator_enable(state->mipi_phy_regulator);
703 }
704
705 static int mipi_csis_phy_disable(struct csi_state *state)
706 {
707         if (state->info->version != MIPI_CSIS_V3_3)
708                 return 0;
709
710         return regulator_disable(state->mipi_phy_regulator);
711 }
712
713 static void mipi_csis_phy_reset(struct csi_state *state)
714 {
715         if (state->info->version != MIPI_CSIS_V3_3)
716                 return;
717
718         reset_control_assert(state->mrst);
719         msleep(20);
720         reset_control_deassert(state->mrst);
721 }
722
723 static int mipi_csis_phy_init(struct csi_state *state)
724 {
725         if (state->info->version != MIPI_CSIS_V3_3)
726                 return 0;
727
728         /* Get MIPI PHY reset and regulator. */
729         state->mrst = devm_reset_control_get_exclusive(state->dev, NULL);
730         if (IS_ERR(state->mrst))
731                 return PTR_ERR(state->mrst);
732
733         state->mipi_phy_regulator = devm_regulator_get(state->dev, "phy");
734         if (IS_ERR(state->mipi_phy_regulator))
735                 return PTR_ERR(state->mipi_phy_regulator);
736
737         return regulator_set_voltage(state->mipi_phy_regulator, 1000000,
738                                      1000000);
739 }
740
741 /* -----------------------------------------------------------------------------
742  * Debug
743  */
744
745 static void mipi_csis_clear_counters(struct csi_state *state)
746 {
747         unsigned long flags;
748         unsigned int i;
749
750         spin_lock_irqsave(&state->slock, flags);
751         for (i = 0; i < MIPI_CSIS_NUM_EVENTS; i++)
752                 state->events[i].counter = 0;
753         spin_unlock_irqrestore(&state->slock, flags);
754 }
755
756 static void mipi_csis_log_counters(struct csi_state *state, bool non_errors)
757 {
758         unsigned int num_events = non_errors ? MIPI_CSIS_NUM_EVENTS
759                                 : MIPI_CSIS_NUM_EVENTS - 8;
760         unsigned long flags;
761         unsigned int i;
762
763         spin_lock_irqsave(&state->slock, flags);
764
765         for (i = 0; i < num_events; ++i) {
766                 if (state->events[i].counter > 0 || state->debug.enable)
767                         dev_info(state->dev, "%s events: %d\n",
768                                  state->events[i].name,
769                                  state->events[i].counter);
770         }
771         spin_unlock_irqrestore(&state->slock, flags);
772 }
773
774 static int mipi_csis_dump_regs(struct csi_state *state)
775 {
776         static const struct {
777                 u32 offset;
778                 const char * const name;
779         } registers[] = {
780                 { MIPI_CSIS_CMN_CTRL, "CMN_CTRL" },
781                 { MIPI_CSIS_CLK_CTRL, "CLK_CTRL" },
782                 { MIPI_CSIS_INT_MSK, "INT_MSK" },
783                 { MIPI_CSIS_DPHY_STATUS, "DPHY_STATUS" },
784                 { MIPI_CSIS_DPHY_CMN_CTRL, "DPHY_CMN_CTRL" },
785                 { MIPI_CSIS_DPHY_SCTRL_L, "DPHY_SCTRL_L" },
786                 { MIPI_CSIS_DPHY_SCTRL_H, "DPHY_SCTRL_H" },
787                 { MIPI_CSIS_ISP_CONFIG_CH(0), "ISP_CONFIG_CH0" },
788                 { MIPI_CSIS_ISP_RESOL_CH(0), "ISP_RESOL_CH0" },
789                 { MIPI_CSIS_SDW_CONFIG_CH(0), "SDW_CONFIG_CH0" },
790                 { MIPI_CSIS_SDW_RESOL_CH(0), "SDW_RESOL_CH0" },
791                 { MIPI_CSIS_DBG_CTRL, "DBG_CTRL" },
792                 { MIPI_CSIS_FRAME_COUNTER_CH(0), "FRAME_COUNTER_CH0" },
793         };
794
795         unsigned int i;
796         u32 cfg;
797
798         dev_info(state->dev, "--- REGISTERS ---\n");
799
800         for (i = 0; i < ARRAY_SIZE(registers); i++) {
801                 cfg = mipi_csis_read(state, registers[i].offset);
802                 dev_info(state->dev, "%14s: 0x%08x\n", registers[i].name, cfg);
803         }
804
805         return 0;
806 }
807
808 static int mipi_csis_dump_regs_show(struct seq_file *m, void *private)
809 {
810         struct csi_state *state = m->private;
811
812         return mipi_csis_dump_regs(state);
813 }
814 DEFINE_SHOW_ATTRIBUTE(mipi_csis_dump_regs);
815
816 static void mipi_csis_debugfs_init(struct csi_state *state)
817 {
818         state->debug.hs_settle = UINT_MAX;
819         state->debug.clk_settle = UINT_MAX;
820
821         state->debugfs_root = debugfs_create_dir(dev_name(state->dev), NULL);
822
823         debugfs_create_bool("debug_enable", 0600, state->debugfs_root,
824                             &state->debug.enable);
825         debugfs_create_file("dump_regs", 0600, state->debugfs_root, state,
826                             &mipi_csis_dump_regs_fops);
827         debugfs_create_u32("tclk_settle", 0600, state->debugfs_root,
828                            &state->debug.clk_settle);
829         debugfs_create_u32("ths_settle", 0600, state->debugfs_root,
830                            &state->debug.hs_settle);
831 }
832
833 static void mipi_csis_debugfs_exit(struct csi_state *state)
834 {
835         debugfs_remove_recursive(state->debugfs_root);
836 }
837
838 /* -----------------------------------------------------------------------------
839  * V4L2 subdev operations
840  */
841
842 static struct csi_state *mipi_sd_to_csis_state(struct v4l2_subdev *sdev)
843 {
844         return container_of(sdev, struct csi_state, sd);
845 }
846
847 static int mipi_csis_s_stream(struct v4l2_subdev *sd, int enable)
848 {
849         struct csi_state *state = mipi_sd_to_csis_state(sd);
850         int ret;
851
852         if (enable) {
853                 ret = mipi_csis_calculate_params(state);
854                 if (ret < 0)
855                         return ret;
856
857                 mipi_csis_clear_counters(state);
858
859                 ret = pm_runtime_resume_and_get(state->dev);
860                 if (ret < 0)
861                         return ret;
862
863                 ret = v4l2_subdev_call(state->src_sd, core, s_power, 1);
864                 if (ret < 0 && ret != -ENOIOCTLCMD)
865                         goto done;
866         }
867
868         mutex_lock(&state->lock);
869
870         if (enable) {
871                 if (state->state & ST_SUSPENDED) {
872                         ret = -EBUSY;
873                         goto unlock;
874                 }
875
876                 mipi_csis_start_stream(state);
877                 ret = v4l2_subdev_call(state->src_sd, video, s_stream, 1);
878                 if (ret < 0)
879                         goto unlock;
880
881                 mipi_csis_log_counters(state, true);
882
883                 state->state |= ST_STREAMING;
884         } else {
885                 v4l2_subdev_call(state->src_sd, video, s_stream, 0);
886                 ret = v4l2_subdev_call(state->src_sd, core, s_power, 0);
887                 if (ret == -ENOIOCTLCMD)
888                         ret = 0;
889                 mipi_csis_stop_stream(state);
890                 state->state &= ~ST_STREAMING;
891                 if (state->debug.enable)
892                         mipi_csis_log_counters(state, true);
893         }
894
895 unlock:
896         mutex_unlock(&state->lock);
897
898 done:
899         if (!enable || ret < 0)
900                 pm_runtime_put(state->dev);
901
902         return ret;
903 }
904
905 static struct v4l2_mbus_framefmt *
906 mipi_csis_get_format(struct csi_state *state,
907                      struct v4l2_subdev_state *sd_state,
908                      enum v4l2_subdev_format_whence which,
909                      unsigned int pad)
910 {
911         if (which == V4L2_SUBDEV_FORMAT_TRY)
912                 return v4l2_subdev_get_try_format(&state->sd, sd_state, pad);
913
914         return &state->format_mbus;
915 }
916
917 static int mipi_csis_init_cfg(struct v4l2_subdev *sd,
918                               struct v4l2_subdev_state *sd_state)
919 {
920         struct csi_state *state = mipi_sd_to_csis_state(sd);
921         struct v4l2_mbus_framefmt *fmt_sink;
922         struct v4l2_mbus_framefmt *fmt_source;
923         enum v4l2_subdev_format_whence which;
924
925         which = sd_state ? V4L2_SUBDEV_FORMAT_TRY : V4L2_SUBDEV_FORMAT_ACTIVE;
926         fmt_sink = mipi_csis_get_format(state, sd_state, which, CSIS_PAD_SINK);
927
928         fmt_sink->code = MEDIA_BUS_FMT_UYVY8_1X16;
929         fmt_sink->width = MIPI_CSIS_DEF_PIX_WIDTH;
930         fmt_sink->height = MIPI_CSIS_DEF_PIX_HEIGHT;
931         fmt_sink->field = V4L2_FIELD_NONE;
932
933         fmt_sink->colorspace = V4L2_COLORSPACE_SMPTE170M;
934         fmt_sink->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(fmt_sink->colorspace);
935         fmt_sink->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(fmt_sink->colorspace);
936         fmt_sink->quantization =
937                 V4L2_MAP_QUANTIZATION_DEFAULT(false, fmt_sink->colorspace,
938                                               fmt_sink->ycbcr_enc);
939
940         /*
941          * When called from mipi_csis_subdev_init() to initialize the active
942          * configuration, cfg is NULL, which indicates there's no source pad
943          * configuration to set.
944          */
945         if (!sd_state)
946                 return 0;
947
948         fmt_source = mipi_csis_get_format(state, sd_state, which,
949                                           CSIS_PAD_SOURCE);
950         *fmt_source = *fmt_sink;
951
952         return 0;
953 }
954
955 static int mipi_csis_get_fmt(struct v4l2_subdev *sd,
956                              struct v4l2_subdev_state *sd_state,
957                              struct v4l2_subdev_format *sdformat)
958 {
959         struct csi_state *state = mipi_sd_to_csis_state(sd);
960         struct v4l2_mbus_framefmt *fmt;
961
962         fmt = mipi_csis_get_format(state, sd_state, sdformat->which,
963                                    sdformat->pad);
964
965         mutex_lock(&state->lock);
966         sdformat->format = *fmt;
967         mutex_unlock(&state->lock);
968
969         return 0;
970 }
971
972 static int mipi_csis_enum_mbus_code(struct v4l2_subdev *sd,
973                                     struct v4l2_subdev_state *sd_state,
974                                     struct v4l2_subdev_mbus_code_enum *code)
975 {
976         struct csi_state *state = mipi_sd_to_csis_state(sd);
977
978         /*
979          * The CSIS can't transcode in any way, the source format is identical
980          * to the sink format.
981          */
982         if (code->pad == CSIS_PAD_SOURCE) {
983                 struct v4l2_mbus_framefmt *fmt;
984
985                 if (code->index > 0)
986                         return -EINVAL;
987
988                 fmt = mipi_csis_get_format(state, sd_state, code->which,
989                                            code->pad);
990                 code->code = fmt->code;
991                 return 0;
992         }
993
994         if (code->pad != CSIS_PAD_SINK)
995                 return -EINVAL;
996
997         if (code->index >= ARRAY_SIZE(mipi_csis_formats))
998                 return -EINVAL;
999
1000         code->code = mipi_csis_formats[code->index].code;
1001
1002         return 0;
1003 }
1004
1005 static int mipi_csis_set_fmt(struct v4l2_subdev *sd,
1006                              struct v4l2_subdev_state *sd_state,
1007                              struct v4l2_subdev_format *sdformat)
1008 {
1009         struct csi_state *state = mipi_sd_to_csis_state(sd);
1010         struct csis_pix_format const *csis_fmt;
1011         struct v4l2_mbus_framefmt *fmt;
1012         unsigned int align;
1013
1014         /*
1015          * The CSIS can't transcode in any way, the source format can't be
1016          * modified.
1017          */
1018         if (sdformat->pad == CSIS_PAD_SOURCE)
1019                 return mipi_csis_get_fmt(sd, sd_state, sdformat);
1020
1021         if (sdformat->pad != CSIS_PAD_SINK)
1022                 return -EINVAL;
1023
1024         /*
1025          * Validate the media bus code and clamp and align the size.
1026          *
1027          * The total number of bits per line must be a multiple of 8. We thus
1028          * need to align the width for formats that are not multiples of 8
1029          * bits.
1030          */
1031         csis_fmt = find_csis_format(sdformat->format.code);
1032         if (!csis_fmt)
1033                 csis_fmt = &mipi_csis_formats[0];
1034
1035         switch (csis_fmt->width % 8) {
1036         case 0:
1037                 align = 0;
1038                 break;
1039         case 4:
1040                 align = 1;
1041                 break;
1042         case 2:
1043         case 6:
1044                 align = 2;
1045                 break;
1046         default:
1047                 /* 1, 3, 5, 7 */
1048                 align = 3;
1049                 break;
1050         }
1051
1052         v4l_bound_align_image(&sdformat->format.width, 1,
1053                               CSIS_MAX_PIX_WIDTH, align,
1054                               &sdformat->format.height, 1,
1055                               CSIS_MAX_PIX_HEIGHT, 0, 0);
1056
1057         fmt = mipi_csis_get_format(state, sd_state, sdformat->which,
1058                                    sdformat->pad);
1059
1060         mutex_lock(&state->lock);
1061
1062         fmt->code = csis_fmt->code;
1063         fmt->width = sdformat->format.width;
1064         fmt->height = sdformat->format.height;
1065         fmt->colorspace = sdformat->format.colorspace;
1066         fmt->quantization = sdformat->format.quantization;
1067         fmt->xfer_func = sdformat->format.xfer_func;
1068         fmt->ycbcr_enc = sdformat->format.ycbcr_enc;
1069
1070         sdformat->format = *fmt;
1071
1072         /* Propagate the format from sink to source. */
1073         fmt = mipi_csis_get_format(state, sd_state, sdformat->which,
1074                                    CSIS_PAD_SOURCE);
1075         *fmt = sdformat->format;
1076
1077         /* Store the CSIS format descriptor for active formats. */
1078         if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE)
1079                 state->csis_fmt = csis_fmt;
1080
1081         mutex_unlock(&state->lock);
1082
1083         return 0;
1084 }
1085
1086 static int mipi_csis_log_status(struct v4l2_subdev *sd)
1087 {
1088         struct csi_state *state = mipi_sd_to_csis_state(sd);
1089
1090         mutex_lock(&state->lock);
1091         mipi_csis_log_counters(state, true);
1092         if (state->debug.enable && (state->state & ST_POWERED))
1093                 mipi_csis_dump_regs(state);
1094         mutex_unlock(&state->lock);
1095
1096         return 0;
1097 }
1098
1099 static const struct v4l2_subdev_core_ops mipi_csis_core_ops = {
1100         .log_status     = mipi_csis_log_status,
1101 };
1102
1103 static const struct v4l2_subdev_video_ops mipi_csis_video_ops = {
1104         .s_stream       = mipi_csis_s_stream,
1105 };
1106
1107 static const struct v4l2_subdev_pad_ops mipi_csis_pad_ops = {
1108         .init_cfg               = mipi_csis_init_cfg,
1109         .enum_mbus_code         = mipi_csis_enum_mbus_code,
1110         .get_fmt                = mipi_csis_get_fmt,
1111         .set_fmt                = mipi_csis_set_fmt,
1112 };
1113
1114 static const struct v4l2_subdev_ops mipi_csis_subdev_ops = {
1115         .core   = &mipi_csis_core_ops,
1116         .video  = &mipi_csis_video_ops,
1117         .pad    = &mipi_csis_pad_ops,
1118 };
1119
1120 /* -----------------------------------------------------------------------------
1121  * Media entity operations
1122  */
1123
1124 static int mipi_csis_link_setup(struct media_entity *entity,
1125                                 const struct media_pad *local_pad,
1126                                 const struct media_pad *remote_pad, u32 flags)
1127 {
1128         struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1129         struct csi_state *state = mipi_sd_to_csis_state(sd);
1130         struct v4l2_subdev *remote_sd;
1131
1132         dev_dbg(state->dev, "link setup %s -> %s", remote_pad->entity->name,
1133                 local_pad->entity->name);
1134
1135         /* We only care about the link to the source. */
1136         if (!(local_pad->flags & MEDIA_PAD_FL_SINK))
1137                 return 0;
1138
1139         remote_sd = media_entity_to_v4l2_subdev(remote_pad->entity);
1140
1141         if (flags & MEDIA_LNK_FL_ENABLED) {
1142                 if (state->src_sd)
1143                         return -EBUSY;
1144
1145                 state->src_sd = remote_sd;
1146         } else {
1147                 state->src_sd = NULL;
1148         }
1149
1150         return 0;
1151 }
1152
1153 static const struct media_entity_operations mipi_csis_entity_ops = {
1154         .link_setup     = mipi_csis_link_setup,
1155         .link_validate  = v4l2_subdev_link_validate,
1156         .get_fwnode_pad = v4l2_subdev_get_fwnode_pad_1_to_1,
1157 };
1158
1159 /* -----------------------------------------------------------------------------
1160  * Async subdev notifier
1161  */
1162
1163 static struct csi_state *
1164 mipi_notifier_to_csis_state(struct v4l2_async_notifier *n)
1165 {
1166         return container_of(n, struct csi_state, notifier);
1167 }
1168
1169 static int mipi_csis_notify_bound(struct v4l2_async_notifier *notifier,
1170                                   struct v4l2_subdev *sd,
1171                                   struct v4l2_async_subdev *asd)
1172 {
1173         struct csi_state *state = mipi_notifier_to_csis_state(notifier);
1174         struct media_pad *sink = &state->sd.entity.pads[CSIS_PAD_SINK];
1175
1176         return v4l2_create_fwnode_links_to_pad(sd, sink, 0);
1177 }
1178
1179 static const struct v4l2_async_notifier_operations mipi_csis_notify_ops = {
1180         .bound = mipi_csis_notify_bound,
1181 };
1182
1183 static int mipi_csis_async_register(struct csi_state *state)
1184 {
1185         struct v4l2_fwnode_endpoint vep = {
1186                 .bus_type = V4L2_MBUS_CSI2_DPHY,
1187         };
1188         struct v4l2_async_subdev *asd;
1189         struct fwnode_handle *ep;
1190         unsigned int i;
1191         int ret;
1192
1193         v4l2_async_nf_init(&state->notifier);
1194
1195         ep = fwnode_graph_get_endpoint_by_id(dev_fwnode(state->dev), 0, 0,
1196                                              FWNODE_GRAPH_ENDPOINT_NEXT);
1197         if (!ep)
1198                 return -ENOTCONN;
1199
1200         ret = v4l2_fwnode_endpoint_parse(ep, &vep);
1201         if (ret)
1202                 goto err_parse;
1203
1204         for (i = 0; i < vep.bus.mipi_csi2.num_data_lanes; ++i) {
1205                 if (vep.bus.mipi_csi2.data_lanes[i] != i + 1) {
1206                         dev_err(state->dev,
1207                                 "data lanes reordering is not supported");
1208                         ret = -EINVAL;
1209                         goto err_parse;
1210                 }
1211         }
1212
1213         state->bus = vep.bus.mipi_csi2;
1214
1215         dev_dbg(state->dev, "data lanes: %d\n", state->bus.num_data_lanes);
1216         dev_dbg(state->dev, "flags: 0x%08x\n", state->bus.flags);
1217
1218         asd = v4l2_async_nf_add_fwnode_remote(&state->notifier, ep,
1219                                               struct v4l2_async_subdev);
1220         if (IS_ERR(asd)) {
1221                 ret = PTR_ERR(asd);
1222                 goto err_parse;
1223         }
1224
1225         fwnode_handle_put(ep);
1226
1227         state->notifier.ops = &mipi_csis_notify_ops;
1228
1229         ret = v4l2_async_subdev_nf_register(&state->sd, &state->notifier);
1230         if (ret)
1231                 return ret;
1232
1233         return v4l2_async_register_subdev(&state->sd);
1234
1235 err_parse:
1236         fwnode_handle_put(ep);
1237
1238         return ret;
1239 }
1240
1241 /* -----------------------------------------------------------------------------
1242  * Suspend/resume
1243  */
1244
1245 static int mipi_csis_pm_suspend(struct device *dev, bool runtime)
1246 {
1247         struct v4l2_subdev *sd = dev_get_drvdata(dev);
1248         struct csi_state *state = mipi_sd_to_csis_state(sd);
1249         int ret = 0;
1250
1251         mutex_lock(&state->lock);
1252         if (state->state & ST_POWERED) {
1253                 mipi_csis_stop_stream(state);
1254                 ret = mipi_csis_phy_disable(state);
1255                 if (ret)
1256                         goto unlock;
1257                 mipi_csis_clk_disable(state);
1258                 state->state &= ~ST_POWERED;
1259                 if (!runtime)
1260                         state->state |= ST_SUSPENDED;
1261         }
1262
1263 unlock:
1264         mutex_unlock(&state->lock);
1265
1266         return ret ? -EAGAIN : 0;
1267 }
1268
1269 static int mipi_csis_pm_resume(struct device *dev, bool runtime)
1270 {
1271         struct v4l2_subdev *sd = dev_get_drvdata(dev);
1272         struct csi_state *state = mipi_sd_to_csis_state(sd);
1273         int ret = 0;
1274
1275         mutex_lock(&state->lock);
1276         if (!runtime && !(state->state & ST_SUSPENDED))
1277                 goto unlock;
1278
1279         if (!(state->state & ST_POWERED)) {
1280                 ret = mipi_csis_phy_enable(state);
1281                 if (ret)
1282                         goto unlock;
1283
1284                 state->state |= ST_POWERED;
1285                 mipi_csis_clk_enable(state);
1286         }
1287         if (state->state & ST_STREAMING)
1288                 mipi_csis_start_stream(state);
1289
1290         state->state &= ~ST_SUSPENDED;
1291
1292 unlock:
1293         mutex_unlock(&state->lock);
1294
1295         return ret ? -EAGAIN : 0;
1296 }
1297
1298 static int __maybe_unused mipi_csis_suspend(struct device *dev)
1299 {
1300         return mipi_csis_pm_suspend(dev, false);
1301 }
1302
1303 static int __maybe_unused mipi_csis_resume(struct device *dev)
1304 {
1305         return mipi_csis_pm_resume(dev, false);
1306 }
1307
1308 static int __maybe_unused mipi_csis_runtime_suspend(struct device *dev)
1309 {
1310         return mipi_csis_pm_suspend(dev, true);
1311 }
1312
1313 static int __maybe_unused mipi_csis_runtime_resume(struct device *dev)
1314 {
1315         return mipi_csis_pm_resume(dev, true);
1316 }
1317
1318 static const struct dev_pm_ops mipi_csis_pm_ops = {
1319         SET_RUNTIME_PM_OPS(mipi_csis_runtime_suspend, mipi_csis_runtime_resume,
1320                            NULL)
1321         SET_SYSTEM_SLEEP_PM_OPS(mipi_csis_suspend, mipi_csis_resume)
1322 };
1323
1324 /* -----------------------------------------------------------------------------
1325  * Probe/remove & platform driver
1326  */
1327
1328 static int mipi_csis_subdev_init(struct csi_state *state)
1329 {
1330         struct v4l2_subdev *sd = &state->sd;
1331
1332         v4l2_subdev_init(sd, &mipi_csis_subdev_ops);
1333         sd->owner = THIS_MODULE;
1334         snprintf(sd->name, sizeof(sd->name), "csis-%s",
1335                  dev_name(state->dev));
1336
1337         sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
1338         sd->ctrl_handler = NULL;
1339
1340         sd->entity.function = MEDIA_ENT_F_VID_IF_BRIDGE;
1341         sd->entity.ops = &mipi_csis_entity_ops;
1342
1343         sd->dev = state->dev;
1344
1345         state->csis_fmt = &mipi_csis_formats[0];
1346         mipi_csis_init_cfg(sd, NULL);
1347
1348         state->pads[CSIS_PAD_SINK].flags = MEDIA_PAD_FL_SINK
1349                                          | MEDIA_PAD_FL_MUST_CONNECT;
1350         state->pads[CSIS_PAD_SOURCE].flags = MEDIA_PAD_FL_SOURCE
1351                                            | MEDIA_PAD_FL_MUST_CONNECT;
1352         return media_entity_pads_init(&sd->entity, CSIS_PADS_NUM,
1353                                       state->pads);
1354 }
1355
1356 static int mipi_csis_parse_dt(struct csi_state *state)
1357 {
1358         struct device_node *node = state->dev->of_node;
1359
1360         if (of_property_read_u32(node, "clock-frequency",
1361                                  &state->clk_frequency))
1362                 state->clk_frequency = DEFAULT_SCLK_CSIS_FREQ;
1363
1364         return 0;
1365 }
1366
1367 static int mipi_csis_probe(struct platform_device *pdev)
1368 {
1369         struct device *dev = &pdev->dev;
1370         struct csi_state *state;
1371         int irq;
1372         int ret;
1373
1374         state = devm_kzalloc(dev, sizeof(*state), GFP_KERNEL);
1375         if (!state)
1376                 return -ENOMEM;
1377
1378         mutex_init(&state->lock);
1379         spin_lock_init(&state->slock);
1380
1381         state->dev = dev;
1382         state->info = of_device_get_match_data(dev);
1383
1384         memcpy(state->events, mipi_csis_events, sizeof(state->events));
1385
1386         /* Parse DT properties. */
1387         ret = mipi_csis_parse_dt(state);
1388         if (ret < 0) {
1389                 dev_err(dev, "Failed to parse device tree: %d\n", ret);
1390                 return ret;
1391         }
1392
1393         /* Acquire resources. */
1394         state->regs = devm_platform_ioremap_resource(pdev, 0);
1395         if (IS_ERR(state->regs))
1396                 return PTR_ERR(state->regs);
1397
1398         irq = platform_get_irq(pdev, 0);
1399         if (irq < 0)
1400                 return irq;
1401
1402         ret = mipi_csis_phy_init(state);
1403         if (ret < 0)
1404                 return ret;
1405
1406         ret = mipi_csis_clk_get(state);
1407         if (ret < 0)
1408                 return ret;
1409
1410         /* Reset PHY and enable the clocks. */
1411         mipi_csis_phy_reset(state);
1412
1413         ret = mipi_csis_clk_enable(state);
1414         if (ret < 0) {
1415                 dev_err(state->dev, "failed to enable clocks: %d\n", ret);
1416                 return ret;
1417         }
1418
1419         /* Now that the hardware is initialized, request the interrupt. */
1420         ret = devm_request_irq(dev, irq, mipi_csis_irq_handler, 0,
1421                                dev_name(dev), state);
1422         if (ret) {
1423                 dev_err(dev, "Interrupt request failed\n");
1424                 goto disable_clock;
1425         }
1426
1427         /* Initialize and register the subdev. */
1428         ret = mipi_csis_subdev_init(state);
1429         if (ret < 0)
1430                 goto disable_clock;
1431
1432         platform_set_drvdata(pdev, &state->sd);
1433
1434         ret = mipi_csis_async_register(state);
1435         if (ret < 0) {
1436                 dev_err(dev, "async register failed: %d\n", ret);
1437                 goto cleanup;
1438         }
1439
1440         /* Initialize debugfs. */
1441         mipi_csis_debugfs_init(state);
1442
1443         /* Enable runtime PM. */
1444         pm_runtime_enable(dev);
1445         if (!pm_runtime_enabled(dev)) {
1446                 ret = mipi_csis_pm_resume(dev, true);
1447                 if (ret < 0)
1448                         goto unregister_all;
1449         }
1450
1451         dev_info(dev, "lanes: %d, freq: %u\n",
1452                  state->bus.num_data_lanes, state->clk_frequency);
1453
1454         return 0;
1455
1456 unregister_all:
1457         mipi_csis_debugfs_exit(state);
1458 cleanup:
1459         media_entity_cleanup(&state->sd.entity);
1460         v4l2_async_nf_unregister(&state->notifier);
1461         v4l2_async_nf_cleanup(&state->notifier);
1462         v4l2_async_unregister_subdev(&state->sd);
1463 disable_clock:
1464         mipi_csis_clk_disable(state);
1465         mutex_destroy(&state->lock);
1466
1467         return ret;
1468 }
1469
1470 static int mipi_csis_remove(struct platform_device *pdev)
1471 {
1472         struct v4l2_subdev *sd = platform_get_drvdata(pdev);
1473         struct csi_state *state = mipi_sd_to_csis_state(sd);
1474
1475         mipi_csis_debugfs_exit(state);
1476         v4l2_async_nf_unregister(&state->notifier);
1477         v4l2_async_nf_cleanup(&state->notifier);
1478         v4l2_async_unregister_subdev(&state->sd);
1479
1480         pm_runtime_disable(&pdev->dev);
1481         mipi_csis_pm_suspend(&pdev->dev, true);
1482         mipi_csis_clk_disable(state);
1483         media_entity_cleanup(&state->sd.entity);
1484         mutex_destroy(&state->lock);
1485         pm_runtime_set_suspended(&pdev->dev);
1486
1487         return 0;
1488 }
1489
1490 static const struct of_device_id mipi_csis_of_match[] = {
1491         {
1492                 .compatible = "fsl,imx7-mipi-csi2",
1493                 .data = &(const struct mipi_csis_info){
1494                         .version = MIPI_CSIS_V3_3,
1495                         .num_clocks = 3,
1496                 },
1497         }, {
1498                 .compatible = "fsl,imx8mm-mipi-csi2",
1499                 .data = &(const struct mipi_csis_info){
1500                         .version = MIPI_CSIS_V3_6_3,
1501                         .num_clocks = 4,
1502                 },
1503         },
1504         { /* sentinel */ },
1505 };
1506 MODULE_DEVICE_TABLE(of, mipi_csis_of_match);
1507
1508 static struct platform_driver mipi_csis_driver = {
1509         .probe          = mipi_csis_probe,
1510         .remove         = mipi_csis_remove,
1511         .driver         = {
1512                 .of_match_table = mipi_csis_of_match,
1513                 .name           = CSIS_DRIVER_NAME,
1514                 .pm             = &mipi_csis_pm_ops,
1515         },
1516 };
1517
1518 module_platform_driver(mipi_csis_driver);
1519
1520 MODULE_DESCRIPTION("i.MX7 & i.MX8 MIPI CSI-2 receiver driver");
1521 MODULE_LICENSE("GPL v2");
1522 MODULE_ALIAS("platform:imx7-mipi-csi2");