359414c1062105b74d2d39697ecf7950e6ffc77a
[linux-block.git] / drivers / gpu / drm / stm / ltdc.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STMicroelectronics SA 2017
4  *
5  * Authors: Philippe Cornu <philippe.cornu@st.com>
6  *          Yannick Fertre <yannick.fertre@st.com>
7  *          Fabien Dessenne <fabien.dessenne@st.com>
8  *          Mickael Reulier <mickael.reulier@st.com>
9  */
10
11 #include <linux/clk.h>
12 #include <linux/component.h>
13 #include <linux/delay.h>
14 #include <linux/interrupt.h>
15 #include <linux/module.h>
16 #include <linux/of_address.h>
17 #include <linux/of_graph.h>
18 #include <linux/pinctrl/consumer.h>
19 #include <linux/platform_device.h>
20 #include <linux/pm_runtime.h>
21 #include <linux/regmap.h>
22 #include <linux/reset.h>
23
24 #include <drm/drm_atomic.h>
25 #include <drm/drm_atomic_helper.h>
26 #include <drm/drm_blend.h>
27 #include <drm/drm_bridge.h>
28 #include <drm/drm_device.h>
29 #include <drm/drm_edid.h>
30 #include <drm/drm_fb_cma_helper.h>
31 #include <drm/drm_fourcc.h>
32 #include <drm/drm_framebuffer.h>
33 #include <drm/drm_gem_atomic_helper.h>
34 #include <drm/drm_gem_cma_helper.h>
35 #include <drm/drm_of.h>
36 #include <drm/drm_plane_helper.h>
37 #include <drm/drm_probe_helper.h>
38 #include <drm/drm_simple_kms_helper.h>
39 #include <drm/drm_vblank.h>
40
41 #include <video/videomode.h>
42
43 #include "ltdc.h"
44
45 #define NB_CRTC 1
46 #define CRTC_MASK GENMASK(NB_CRTC - 1, 0)
47
48 #define MAX_IRQ 4
49
50 #define HWVER_10200 0x010200
51 #define HWVER_10300 0x010300
52 #define HWVER_20101 0x020101
53 #define HWVER_40100 0x040100
54
55 /*
56  * The address of some registers depends on the HW version: such registers have
57  * an extra offset specified with layer_ofs.
58  */
59 #define LAY_OFS_0       0x80
60 #define LAY_OFS_1       0x100
61 #define LAY_OFS (ldev->caps.layer_ofs)
62
63 /* Global register offsets */
64 #define LTDC_IDR        0x0000          /* IDentification */
65 #define LTDC_LCR        0x0004          /* Layer Count */
66 #define LTDC_SSCR       0x0008          /* Synchronization Size Configuration */
67 #define LTDC_BPCR       0x000C          /* Back Porch Configuration */
68 #define LTDC_AWCR       0x0010          /* Active Width Configuration */
69 #define LTDC_TWCR       0x0014          /* Total Width Configuration */
70 #define LTDC_GCR        0x0018          /* Global Control */
71 #define LTDC_GC1R       0x001C          /* Global Configuration 1 */
72 #define LTDC_GC2R       0x0020          /* Global Configuration 2 */
73 #define LTDC_SRCR       0x0024          /* Shadow Reload Configuration */
74 #define LTDC_GACR       0x0028          /* GAmma Correction */
75 #define LTDC_BCCR       0x002C          /* Background Color Configuration */
76 #define LTDC_IER        0x0034          /* Interrupt Enable */
77 #define LTDC_ISR        0x0038          /* Interrupt Status */
78 #define LTDC_ICR        0x003C          /* Interrupt Clear */
79 #define LTDC_LIPCR      0x0040          /* Line Interrupt Position Conf. */
80 #define LTDC_CPSR       0x0044          /* Current Position Status */
81 #define LTDC_CDSR       0x0048          /* Current Display Status */
82 #define LTDC_EDCR       0x0060          /* External Display Control */
83 #define LTDC_CCRCR      0x007C          /* Computed CRC value */
84 #define LTDC_FUT        0x0090          /* Fifo underrun Threshold */
85
86 /* Layer register offsets */
87 #define LTDC_L1C0R      (ldev->caps.layer_regs[0])      /* L1 configuration 0 */
88 #define LTDC_L1C1R      (ldev->caps.layer_regs[1])      /* L1 configuration 1 */
89 #define LTDC_L1RCR      (ldev->caps.layer_regs[2])      /* L1 reload control */
90 #define LTDC_L1CR       (ldev->caps.layer_regs[3])      /* L1 control register */
91 #define LTDC_L1WHPCR    (ldev->caps.layer_regs[4])      /* L1 window horizontal position configuration */
92 #define LTDC_L1WVPCR    (ldev->caps.layer_regs[5])      /* L1 window vertical position configuration */
93 #define LTDC_L1CKCR     (ldev->caps.layer_regs[6])      /* L1 color keying configuration */
94 #define LTDC_L1PFCR     (ldev->caps.layer_regs[7])      /* L1 pixel format configuration */
95 #define LTDC_L1CACR     (ldev->caps.layer_regs[8])      /* L1 constant alpha configuration */
96 #define LTDC_L1DCCR     (ldev->caps.layer_regs[9])      /* L1 default color configuration */
97 #define LTDC_L1BFCR     (ldev->caps.layer_regs[10])     /* L1 blending factors configuration */
98 #define LTDC_L1BLCR     (ldev->caps.layer_regs[11])     /* L1 burst length configuration */
99 #define LTDC_L1PCR      (ldev->caps.layer_regs[12])     /* L1 planar configuration */
100 #define LTDC_L1CFBAR    (ldev->caps.layer_regs[13])     /* L1 color frame buffer address */
101 #define LTDC_L1CFBLR    (ldev->caps.layer_regs[14])     /* L1 color frame buffer length */
102 #define LTDC_L1CFBLNR   (ldev->caps.layer_regs[15])     /* L1 color frame buffer line number */
103 #define LTDC_L1AFBA0R   (ldev->caps.layer_regs[16])     /* L1 auxiliary frame buffer address 0 */
104 #define LTDC_L1AFBA1R   (ldev->caps.layer_regs[17])     /* L1 auxiliary frame buffer address 1 */
105 #define LTDC_L1AFBLR    (ldev->caps.layer_regs[18])     /* L1 auxiliary frame buffer length */
106 #define LTDC_L1AFBLNR   (ldev->caps.layer_regs[19])     /* L1 auxiliary frame buffer line number */
107 #define LTDC_L1CLUTWR   (ldev->caps.layer_regs[20])     /* L1 CLUT write */
108 #define LTDC_L1CYR0R    (ldev->caps.layer_regs[21])     /* L1 Conversion YCbCr RGB 0 */
109 #define LTDC_L1CYR1R    (ldev->caps.layer_regs[22])     /* L1 Conversion YCbCr RGB 1 */
110 #define LTDC_L1FPF0R    (ldev->caps.layer_regs[23])     /* L1 Flexible Pixel Format 0 */
111 #define LTDC_L1FPF1R    (ldev->caps.layer_regs[24])     /* L1 Flexible Pixel Format 1 */
112
113 /* Bit definitions */
114 #define SSCR_VSH        GENMASK(10, 0)  /* Vertical Synchronization Height */
115 #define SSCR_HSW        GENMASK(27, 16) /* Horizontal Synchronization Width */
116
117 #define BPCR_AVBP       GENMASK(10, 0)  /* Accumulated Vertical Back Porch */
118 #define BPCR_AHBP       GENMASK(27, 16) /* Accumulated Horizontal Back Porch */
119
120 #define AWCR_AAH        GENMASK(10, 0)  /* Accumulated Active Height */
121 #define AWCR_AAW        GENMASK(27, 16) /* Accumulated Active Width */
122
123 #define TWCR_TOTALH     GENMASK(10, 0)  /* TOTAL Height */
124 #define TWCR_TOTALW     GENMASK(27, 16) /* TOTAL Width */
125
126 #define GCR_LTDCEN      BIT(0)          /* LTDC ENable */
127 #define GCR_DEN         BIT(16)         /* Dither ENable */
128 #define GCR_CRCEN       BIT(19)         /* CRC ENable */
129 #define GCR_PCPOL       BIT(28)         /* Pixel Clock POLarity-Inverted */
130 #define GCR_DEPOL       BIT(29)         /* Data Enable POLarity-High */
131 #define GCR_VSPOL       BIT(30)         /* Vertical Synchro POLarity-High */
132 #define GCR_HSPOL       BIT(31)         /* Horizontal Synchro POLarity-High */
133
134 #define GC1R_WBCH       GENMASK(3, 0)   /* Width of Blue CHannel output */
135 #define GC1R_WGCH       GENMASK(7, 4)   /* Width of Green Channel output */
136 #define GC1R_WRCH       GENMASK(11, 8)  /* Width of Red Channel output */
137 #define GC1R_PBEN       BIT(12)         /* Precise Blending ENable */
138 #define GC1R_DT         GENMASK(15, 14) /* Dithering Technique */
139 #define GC1R_GCT        GENMASK(19, 17) /* Gamma Correction Technique */
140 #define GC1R_SHREN      BIT(21)         /* SHadow Registers ENabled */
141 #define GC1R_BCP        BIT(22)         /* Background Colour Programmable */
142 #define GC1R_BBEN       BIT(23)         /* Background Blending ENabled */
143 #define GC1R_LNIP       BIT(24)         /* Line Number IRQ Position */
144 #define GC1R_TP         BIT(25)         /* Timing Programmable */
145 #define GC1R_IPP        BIT(26)         /* IRQ Polarity Programmable */
146 #define GC1R_SPP        BIT(27)         /* Sync Polarity Programmable */
147 #define GC1R_DWP        BIT(28)         /* Dither Width Programmable */
148 #define GC1R_STREN      BIT(29)         /* STatus Registers ENabled */
149 #define GC1R_BMEN       BIT(31)         /* Blind Mode ENabled */
150
151 #define GC2R_EDCA       BIT(0)          /* External Display Control Ability  */
152 #define GC2R_STSAEN     BIT(1)          /* Slave Timing Sync Ability ENabled */
153 #define GC2R_DVAEN      BIT(2)          /* Dual-View Ability ENabled */
154 #define GC2R_DPAEN      BIT(3)          /* Dual-Port Ability ENabled */
155 #define GC2R_BW         GENMASK(6, 4)   /* Bus Width (log2 of nb of bytes) */
156 #define GC2R_EDCEN      BIT(7)          /* External Display Control ENabled */
157
158 #define SRCR_IMR        BIT(0)          /* IMmediate Reload */
159 #define SRCR_VBR        BIT(1)          /* Vertical Blanking Reload */
160
161 #define BCCR_BCBLACK    0x00            /* Background Color BLACK */
162 #define BCCR_BCBLUE     GENMASK(7, 0)   /* Background Color BLUE */
163 #define BCCR_BCGREEN    GENMASK(15, 8)  /* Background Color GREEN */
164 #define BCCR_BCRED      GENMASK(23, 16) /* Background Color RED */
165 #define BCCR_BCWHITE    GENMASK(23, 0)  /* Background Color WHITE */
166
167 #define IER_LIE         BIT(0)          /* Line Interrupt Enable */
168 #define IER_FUIE        BIT(1)          /* Fifo Underrun Interrupt Enable */
169 #define IER_TERRIE      BIT(2)          /* Transfer ERRor Interrupt Enable */
170 #define IER_RRIE        BIT(3)          /* Register Reload Interrupt enable */
171
172 #define CPSR_CYPOS      GENMASK(15, 0)  /* Current Y position */
173
174 #define ISR_LIF         BIT(0)          /* Line Interrupt Flag */
175 #define ISR_FUIF        BIT(1)          /* Fifo Underrun Interrupt Flag */
176 #define ISR_TERRIF      BIT(2)          /* Transfer ERRor Interrupt Flag */
177 #define ISR_RRIF        BIT(3)          /* Register Reload Interrupt Flag */
178
179 #define EDCR_OCYEN      BIT(25)         /* Output Conversion to YCbCr 422: ENable */
180 #define EDCR_OCYSEL     BIT(26)         /* Output Conversion to YCbCr 422: SELection of the CCIR */
181 #define EDCR_OCYCO      BIT(27)         /* Output Conversion to YCbCr 422: Chrominance Order */
182
183 #define LXCR_LEN        BIT(0)          /* Layer ENable */
184 #define LXCR_COLKEN     BIT(1)          /* Color Keying Enable */
185 #define LXCR_CLUTEN     BIT(4)          /* Color Look-Up Table ENable */
186
187 #define LXWHPCR_WHSTPOS GENMASK(11, 0)  /* Window Horizontal StarT POSition */
188 #define LXWHPCR_WHSPPOS GENMASK(27, 16) /* Window Horizontal StoP POSition */
189
190 #define LXWVPCR_WVSTPOS GENMASK(10, 0)  /* Window Vertical StarT POSition */
191 #define LXWVPCR_WVSPPOS GENMASK(26, 16) /* Window Vertical StoP POSition */
192
193 #define LXPFCR_PF       GENMASK(2, 0)   /* Pixel Format */
194 #define PF_FLEXIBLE     0x7             /* Flexible Pixel Format selected */
195
196 #define LXCACR_CONSTA   GENMASK(7, 0)   /* CONSTant Alpha */
197
198 #define LXBFCR_BF2      GENMASK(2, 0)   /* Blending Factor 2 */
199 #define LXBFCR_BF1      GENMASK(10, 8)  /* Blending Factor 1 */
200 #define LXBFCR_BOR      GENMASK(18, 16) /* Blending ORder */
201
202 #define LXCFBLR_CFBLL   GENMASK(12, 0)  /* Color Frame Buffer Line Length */
203 #define LXCFBLR_CFBP    GENMASK(28, 16) /* Color Frame Buffer Pitch in bytes */
204
205 #define LXCFBLNR_CFBLN  GENMASK(10, 0)  /* Color Frame Buffer Line Number */
206
207 #define LXCR_C1R_YIA    BIT(0)          /* Ycbcr 422 Interleaved Ability */
208 #define LXCR_C1R_YSPA   BIT(1)          /* Ycbcr 420 Semi-Planar Ability */
209 #define LXCR_C1R_YFPA   BIT(2)          /* Ycbcr 420 Full-Planar Ability */
210 #define LXCR_C1R_SCA    BIT(31)         /* SCaling Ability*/
211
212 #define LxPCR_YREN      BIT(9)          /* Y Rescale Enable for the color dynamic range */
213 #define LxPCR_OF        BIT(8)          /* Odd pixel First */
214 #define LxPCR_CBF       BIT(7)          /* CB component First */
215 #define LxPCR_YF        BIT(6)          /* Y component First */
216 #define LxPCR_YCM       GENMASK(5, 4)   /* Ycbcr Conversion Mode */
217 #define YCM_I           0x0             /* Interleaved 422 */
218 #define YCM_SP          0x1             /* Semi-Planar 420 */
219 #define YCM_FP          0x2             /* Full-Planar 420 */
220 #define LxPCR_YCEN      BIT(3)          /* YCbCr-to-RGB Conversion Enable */
221
222 #define LXRCR_IMR       BIT(0)          /* IMmediate Reload */
223 #define LXRCR_VBR       BIT(1)          /* Vertical Blanking Reload */
224 #define LXRCR_GRMSK     BIT(2)          /* Global (centralized) Reload MaSKed */
225
226 #define CLUT_SIZE       256
227
228 #define CONSTA_MAX      0xFF            /* CONSTant Alpha MAX= 1.0 */
229 #define BF1_PAXCA       0x600           /* Pixel Alpha x Constant Alpha */
230 #define BF1_CA          0x400           /* Constant Alpha */
231 #define BF2_1PAXCA      0x007           /* 1 - (Pixel Alpha x Constant Alpha) */
232 #define BF2_1CA         0x005           /* 1 - Constant Alpha */
233
234 #define NB_PF           8               /* Max nb of HW pixel format */
235
236 /*
237  * Skip the first value and the second in case CRC was enabled during
238  * the thread irq. This is to be sure CRC value is relevant for the
239  * frame.
240  */
241 #define CRC_SKIP_FRAMES 2
242
243 enum ltdc_pix_fmt {
244         PF_NONE,
245         /* RGB formats */
246         PF_ARGB8888,            /* ARGB [32 bits] */
247         PF_RGBA8888,            /* RGBA [32 bits] */
248         PF_ABGR8888,            /* ABGR [32 bits] */
249         PF_BGRA8888,            /* BGRA [32 bits] */
250         PF_RGB888,              /* RGB [24 bits] */
251         PF_BGR888,              /* BGR [24 bits] */
252         PF_RGB565,              /* RGB [16 bits] */
253         PF_BGR565,              /* BGR [16 bits] */
254         PF_ARGB1555,            /* ARGB A:1 bit RGB:15 bits [16 bits] */
255         PF_ARGB4444,            /* ARGB A:4 bits R/G/B: 4 bits each [16 bits] */
256         /* Indexed formats */
257         PF_L8,                  /* Indexed 8 bits [8 bits] */
258         PF_AL44,                /* Alpha:4 bits + indexed 4 bits [8 bits] */
259         PF_AL88                 /* Alpha:8 bits + indexed 8 bits [16 bits] */
260 };
261
262 /* The index gives the encoding of the pixel format for an HW version */
263 static const enum ltdc_pix_fmt ltdc_pix_fmt_a0[NB_PF] = {
264         PF_ARGB8888,            /* 0x00 */
265         PF_RGB888,              /* 0x01 */
266         PF_RGB565,              /* 0x02 */
267         PF_ARGB1555,            /* 0x03 */
268         PF_ARGB4444,            /* 0x04 */
269         PF_L8,                  /* 0x05 */
270         PF_AL44,                /* 0x06 */
271         PF_AL88                 /* 0x07 */
272 };
273
274 static const enum ltdc_pix_fmt ltdc_pix_fmt_a1[NB_PF] = {
275         PF_ARGB8888,            /* 0x00 */
276         PF_RGB888,              /* 0x01 */
277         PF_RGB565,              /* 0x02 */
278         PF_RGBA8888,            /* 0x03 */
279         PF_AL44,                /* 0x04 */
280         PF_L8,                  /* 0x05 */
281         PF_ARGB1555,            /* 0x06 */
282         PF_ARGB4444             /* 0x07 */
283 };
284
285 static const enum ltdc_pix_fmt ltdc_pix_fmt_a2[NB_PF] = {
286         PF_ARGB8888,            /* 0x00 */
287         PF_ABGR8888,            /* 0x01 */
288         PF_RGBA8888,            /* 0x02 */
289         PF_BGRA8888,            /* 0x03 */
290         PF_RGB565,              /* 0x04 */
291         PF_BGR565,              /* 0x05 */
292         PF_RGB888,              /* 0x06 */
293         PF_NONE                 /* 0x07 */
294 };
295
296 static const u32 ltdc_drm_fmt_a0[] = {
297         DRM_FORMAT_ARGB8888,
298         DRM_FORMAT_XRGB8888,
299         DRM_FORMAT_RGB888,
300         DRM_FORMAT_RGB565,
301         DRM_FORMAT_ARGB1555,
302         DRM_FORMAT_XRGB1555,
303         DRM_FORMAT_ARGB4444,
304         DRM_FORMAT_XRGB4444,
305         DRM_FORMAT_C8
306 };
307
308 static const u32 ltdc_drm_fmt_a1[] = {
309         DRM_FORMAT_ARGB8888,
310         DRM_FORMAT_XRGB8888,
311         DRM_FORMAT_RGB888,
312         DRM_FORMAT_RGB565,
313         DRM_FORMAT_RGBA8888,
314         DRM_FORMAT_RGBX8888,
315         DRM_FORMAT_ARGB1555,
316         DRM_FORMAT_XRGB1555,
317         DRM_FORMAT_ARGB4444,
318         DRM_FORMAT_XRGB4444,
319         DRM_FORMAT_C8
320 };
321
322 static const u32 ltdc_drm_fmt_a2[] = {
323         DRM_FORMAT_ARGB8888,
324         DRM_FORMAT_XRGB8888,
325         DRM_FORMAT_ABGR8888,
326         DRM_FORMAT_XBGR8888,
327         DRM_FORMAT_RGBA8888,
328         DRM_FORMAT_RGBX8888,
329         DRM_FORMAT_BGRA8888,
330         DRM_FORMAT_BGRX8888,
331         DRM_FORMAT_RGB565,
332         DRM_FORMAT_BGR565,
333         DRM_FORMAT_RGB888,
334         DRM_FORMAT_BGR888,
335         DRM_FORMAT_ARGB1555,
336         DRM_FORMAT_XRGB1555,
337         DRM_FORMAT_ARGB4444,
338         DRM_FORMAT_XRGB4444,
339         DRM_FORMAT_C8
340 };
341
342 static const u32 ltdc_drm_fmt_ycbcr_cp[] = {
343         DRM_FORMAT_YUYV,
344         DRM_FORMAT_YVYU,
345         DRM_FORMAT_UYVY,
346         DRM_FORMAT_VYUY
347 };
348
349 static const u32 ltdc_drm_fmt_ycbcr_sp[] = {
350         DRM_FORMAT_NV12,
351         DRM_FORMAT_NV21
352 };
353
354 static const u32 ltdc_drm_fmt_ycbcr_fp[] = {
355         DRM_FORMAT_YUV420,
356         DRM_FORMAT_YVU420
357 };
358
359 /* Layer register offsets */
360 static const u32 ltdc_layer_regs_a0[] = {
361         0x80,   /* L1 configuration 0 */
362         0x00,   /* not available */
363         0x00,   /* not available */
364         0x84,   /* L1 control register */
365         0x88,   /* L1 window horizontal position configuration */
366         0x8c,   /* L1 window vertical position configuration */
367         0x90,   /* L1 color keying configuration */
368         0x94,   /* L1 pixel format configuration */
369         0x98,   /* L1 constant alpha configuration */
370         0x9c,   /* L1 default color configuration */
371         0xa0,   /* L1 blending factors configuration */
372         0x00,   /* not available */
373         0x00,   /* not available */
374         0xac,   /* L1 color frame buffer address */
375         0xb0,   /* L1 color frame buffer length */
376         0xb4,   /* L1 color frame buffer line number */
377         0x00,   /* not available */
378         0x00,   /* not available */
379         0x00,   /* not available */
380         0x00,   /* not available */
381         0xc4,   /* L1 CLUT write */
382         0x00,   /* not available */
383         0x00,   /* not available */
384         0x00,   /* not available */
385         0x00    /* not available */
386 };
387
388 static const u32 ltdc_layer_regs_a1[] = {
389         0x80,   /* L1 configuration 0 */
390         0x84,   /* L1 configuration 1 */
391         0x00,   /* L1 reload control */
392         0x88,   /* L1 control register */
393         0x8c,   /* L1 window horizontal position configuration */
394         0x90,   /* L1 window vertical position configuration */
395         0x94,   /* L1 color keying configuration */
396         0x98,   /* L1 pixel format configuration */
397         0x9c,   /* L1 constant alpha configuration */
398         0xa0,   /* L1 default color configuration */
399         0xa4,   /* L1 blending factors configuration */
400         0xa8,   /* L1 burst length configuration */
401         0x00,   /* not available */
402         0xac,   /* L1 color frame buffer address */
403         0xb0,   /* L1 color frame buffer length */
404         0xb4,   /* L1 color frame buffer line number */
405         0xb8,   /* L1 auxiliary frame buffer address 0 */
406         0xbc,   /* L1 auxiliary frame buffer address 1 */
407         0xc0,   /* L1 auxiliary frame buffer length */
408         0xc4,   /* L1 auxiliary frame buffer line number */
409         0xc8,   /* L1 CLUT write */
410         0x00,   /* not available */
411         0x00,   /* not available */
412         0x00,   /* not available */
413         0x00    /* not available */
414 };
415
416 static const u32 ltdc_layer_regs_a2[] = {
417         0x100,  /* L1 configuration 0 */
418         0x104,  /* L1 configuration 1 */
419         0x108,  /* L1 reload control */
420         0x10c,  /* L1 control register */
421         0x110,  /* L1 window horizontal position configuration */
422         0x114,  /* L1 window vertical position configuration */
423         0x118,  /* L1 color keying configuration */
424         0x11c,  /* L1 pixel format configuration */
425         0x120,  /* L1 constant alpha configuration */
426         0x124,  /* L1 default color configuration */
427         0x128,  /* L1 blending factors configuration */
428         0x12c,  /* L1 burst length configuration */
429         0x130,  /* L1 planar configuration */
430         0x134,  /* L1 color frame buffer address */
431         0x138,  /* L1 color frame buffer length */
432         0x13c,  /* L1 color frame buffer line number */
433         0x140,  /* L1 auxiliary frame buffer address 0 */
434         0x144,  /* L1 auxiliary frame buffer address 1 */
435         0x148,  /* L1 auxiliary frame buffer length */
436         0x14c,  /* L1 auxiliary frame buffer line number */
437         0x150,  /* L1 CLUT write */
438         0x16c,  /* L1 Conversion YCbCr RGB 0 */
439         0x170,  /* L1 Conversion YCbCr RGB 1 */
440         0x174,  /* L1 Flexible Pixel Format 0 */
441         0x178   /* L1 Flexible Pixel Format 1 */
442 };
443
444 static const u64 ltdc_format_modifiers[] = {
445         DRM_FORMAT_MOD_LINEAR,
446         DRM_FORMAT_MOD_INVALID
447 };
448
449 static const struct regmap_config stm32_ltdc_regmap_cfg = {
450         .reg_bits = 32,
451         .val_bits = 32,
452         .reg_stride = sizeof(u32),
453         .max_register = 0x400,
454         .use_relaxed_mmio = true,
455         .cache_type = REGCACHE_NONE,
456 };
457
458 static const u32 ltdc_ycbcr2rgb_coeffs[DRM_COLOR_ENCODING_MAX][DRM_COLOR_RANGE_MAX][2] = {
459         [DRM_COLOR_YCBCR_BT601][DRM_COLOR_YCBCR_LIMITED_RANGE] = {
460                 0x02040199,     /* (b_cb = 516 / r_cr = 409) */
461                 0x006400D0      /* (g_cb = 100 / g_cr = 208) */
462         },
463         [DRM_COLOR_YCBCR_BT601][DRM_COLOR_YCBCR_FULL_RANGE] = {
464                 0x01C60167,     /* (b_cb = 454 / r_cr = 359) */
465                 0x005800B7      /* (g_cb = 88 / g_cr = 183) */
466         },
467         [DRM_COLOR_YCBCR_BT709][DRM_COLOR_YCBCR_LIMITED_RANGE] = {
468                 0x021D01CB,     /* (b_cb = 541 / r_cr = 459) */
469                 0x00370089      /* (g_cb = 55 / g_cr = 137) */
470         },
471         [DRM_COLOR_YCBCR_BT709][DRM_COLOR_YCBCR_FULL_RANGE] = {
472                 0x01DB0193,     /* (b_cb = 475 / r_cr = 403) */
473                 0x00300078      /* (g_cb = 48 / g_cr = 120) */
474         }
475         /* BT2020 not supported */
476 };
477
478 static inline struct ltdc_device *crtc_to_ltdc(struct drm_crtc *crtc)
479 {
480         return (struct ltdc_device *)crtc->dev->dev_private;
481 }
482
483 static inline struct ltdc_device *plane_to_ltdc(struct drm_plane *plane)
484 {
485         return (struct ltdc_device *)plane->dev->dev_private;
486 }
487
488 static inline struct ltdc_device *encoder_to_ltdc(struct drm_encoder *enc)
489 {
490         return (struct ltdc_device *)enc->dev->dev_private;
491 }
492
493 static inline enum ltdc_pix_fmt to_ltdc_pixelformat(u32 drm_fmt)
494 {
495         enum ltdc_pix_fmt pf;
496
497         switch (drm_fmt) {
498         case DRM_FORMAT_ARGB8888:
499         case DRM_FORMAT_XRGB8888:
500                 pf = PF_ARGB8888;
501                 break;
502         case DRM_FORMAT_ABGR8888:
503         case DRM_FORMAT_XBGR8888:
504                 pf = PF_ABGR8888;
505                 break;
506         case DRM_FORMAT_RGBA8888:
507         case DRM_FORMAT_RGBX8888:
508                 pf = PF_RGBA8888;
509                 break;
510         case DRM_FORMAT_BGRA8888:
511         case DRM_FORMAT_BGRX8888:
512                 pf = PF_BGRA8888;
513                 break;
514         case DRM_FORMAT_RGB888:
515                 pf = PF_RGB888;
516                 break;
517         case DRM_FORMAT_BGR888:
518                 pf = PF_BGR888;
519                 break;
520         case DRM_FORMAT_RGB565:
521                 pf = PF_RGB565;
522                 break;
523         case DRM_FORMAT_BGR565:
524                 pf = PF_BGR565;
525                 break;
526         case DRM_FORMAT_ARGB1555:
527         case DRM_FORMAT_XRGB1555:
528                 pf = PF_ARGB1555;
529                 break;
530         case DRM_FORMAT_ARGB4444:
531         case DRM_FORMAT_XRGB4444:
532                 pf = PF_ARGB4444;
533                 break;
534         case DRM_FORMAT_C8:
535                 pf = PF_L8;
536                 break;
537         default:
538                 pf = PF_NONE;
539                 break;
540                 /* Note: There are no DRM_FORMAT for AL44 and AL88 */
541         }
542
543         return pf;
544 }
545
546 static inline u32 ltdc_set_flexible_pixel_format(struct drm_plane *plane, enum ltdc_pix_fmt pix_fmt)
547 {
548         struct ltdc_device *ldev = plane_to_ltdc(plane);
549         u32 lofs = plane->index * LAY_OFS, ret = PF_FLEXIBLE;
550         int psize, alen, apos, rlen, rpos, glen, gpos, blen, bpos;
551
552         switch (pix_fmt) {
553         case PF_BGR888:
554                 psize = 3;
555                 alen = 0; apos = 0; rlen = 8; rpos = 0;
556                 glen = 8; gpos = 8; blen = 8; bpos = 16;
557         break;
558         case PF_ARGB1555:
559                 psize = 2;
560                 alen = 1; apos = 15; rlen = 5; rpos = 10;
561                 glen = 5; gpos = 5;  blen = 5; bpos = 0;
562         break;
563         case PF_ARGB4444:
564                 psize = 2;
565                 alen = 4; apos = 12; rlen = 4; rpos = 8;
566                 glen = 4; gpos = 4; blen = 4; bpos = 0;
567         break;
568         case PF_L8:
569                 psize = 1;
570                 alen = 0; apos = 0; rlen = 8; rpos = 0;
571                 glen = 8; gpos = 0; blen = 8; bpos = 0;
572         break;
573         case PF_AL44:
574                 psize = 1;
575                 alen = 4; apos = 4; rlen = 4; rpos = 0;
576                 glen = 4; gpos = 0; blen = 4; bpos = 0;
577         break;
578         case PF_AL88:
579                 psize = 2;
580                 alen = 8; apos = 8; rlen = 8; rpos = 0;
581                 glen = 8; gpos = 0; blen = 8; bpos = 0;
582         break;
583         default:
584                 ret = NB_PF; /* error case, trace msg is handled by the caller */
585         break;
586         }
587
588         if (ret == PF_FLEXIBLE) {
589                 regmap_write(ldev->regmap, LTDC_L1FPF0R + lofs,
590                              (rlen << 14)  + (rpos << 9) + (alen << 5) + apos);
591
592                 regmap_write(ldev->regmap, LTDC_L1FPF1R + lofs,
593                              (psize << 18) + (blen << 14)  + (bpos << 9) + (glen << 5) + gpos);
594         }
595
596         return ret;
597 }
598
599 /*
600  * All non-alpha color formats derived from native alpha color formats are
601  * either characterized by a FourCC format code
602  */
603 static inline u32 is_xrgb(u32 drm)
604 {
605         return ((drm & 0xFF) == 'X' || ((drm >> 8) & 0xFF) == 'X');
606 }
607
608 static inline void ltdc_set_ycbcr_config(struct drm_plane *plane, u32 drm_pix_fmt)
609 {
610         struct ltdc_device *ldev = plane_to_ltdc(plane);
611         struct drm_plane_state *state = plane->state;
612         u32 lofs = plane->index * LAY_OFS;
613         u32 val;
614
615         switch (drm_pix_fmt) {
616         case DRM_FORMAT_YUYV:
617                 val = (YCM_I << 4) | LxPCR_YF | LxPCR_CBF;
618                 break;
619         case DRM_FORMAT_YVYU:
620                 val = (YCM_I << 4) | LxPCR_YF;
621                 break;
622         case DRM_FORMAT_UYVY:
623                 val = (YCM_I << 4) | LxPCR_CBF;
624                 break;
625         case DRM_FORMAT_VYUY:
626                 val = (YCM_I << 4);
627                 break;
628         case DRM_FORMAT_NV12:
629                 val = (YCM_SP << 4) | LxPCR_CBF;
630                 break;
631         case DRM_FORMAT_NV21:
632                 val = (YCM_SP << 4);
633                 break;
634         case DRM_FORMAT_YUV420:
635         case DRM_FORMAT_YVU420:
636                 val = (YCM_FP << 4);
637                 break;
638         default:
639                 /* RGB or not a YCbCr supported format */
640                 DRM_ERROR("Unsupported pixel format: %u\n", drm_pix_fmt);
641                 return;
642         }
643
644         /* Enable limited range */
645         if (state->color_range == DRM_COLOR_YCBCR_LIMITED_RANGE)
646                 val |= LxPCR_YREN;
647
648         /* enable ycbcr conversion */
649         val |= LxPCR_YCEN;
650
651         regmap_write(ldev->regmap, LTDC_L1PCR + lofs, val);
652 }
653
654 static inline void ltdc_set_ycbcr_coeffs(struct drm_plane *plane)
655 {
656         struct ltdc_device *ldev = plane_to_ltdc(plane);
657         struct drm_plane_state *state = plane->state;
658         enum drm_color_encoding enc = state->color_encoding;
659         enum drm_color_range ran = state->color_range;
660         u32 lofs = plane->index * LAY_OFS;
661
662         if (enc != DRM_COLOR_YCBCR_BT601 && enc != DRM_COLOR_YCBCR_BT709) {
663                 DRM_ERROR("color encoding %d not supported, use bt601 by default\n", enc);
664                 /* set by default color encoding to DRM_COLOR_YCBCR_BT601 */
665                 enc = DRM_COLOR_YCBCR_BT601;
666         }
667
668         if (ran != DRM_COLOR_YCBCR_LIMITED_RANGE && ran != DRM_COLOR_YCBCR_FULL_RANGE) {
669                 DRM_ERROR("color range %d not supported, use limited range by default\n", ran);
670                 /* set by default color range to DRM_COLOR_YCBCR_LIMITED_RANGE */
671                 ran = DRM_COLOR_YCBCR_LIMITED_RANGE;
672         }
673
674         DRM_DEBUG_DRIVER("Color encoding=%d, range=%d\n", enc, ran);
675         regmap_write(ldev->regmap, LTDC_L1CYR0R + lofs,
676                      ltdc_ycbcr2rgb_coeffs[enc][ran][0]);
677         regmap_write(ldev->regmap, LTDC_L1CYR1R + lofs,
678                      ltdc_ycbcr2rgb_coeffs[enc][ran][1]);
679 }
680
681 static inline void ltdc_irq_crc_handle(struct ltdc_device *ldev,
682                                        struct drm_crtc *crtc)
683 {
684         u32 crc;
685         int ret;
686
687         if (ldev->crc_skip_count < CRC_SKIP_FRAMES) {
688                 ldev->crc_skip_count++;
689                 return;
690         }
691
692         /* Get the CRC of the frame */
693         ret = regmap_read(ldev->regmap, LTDC_CCRCR, &crc);
694         if (ret)
695                 return;
696
697         /* Report to DRM the CRC (hw dependent feature) */
698         drm_crtc_add_crc_entry(crtc, true, drm_crtc_accurate_vblank_count(crtc), &crc);
699 }
700
701 static irqreturn_t ltdc_irq_thread(int irq, void *arg)
702 {
703         struct drm_device *ddev = arg;
704         struct ltdc_device *ldev = ddev->dev_private;
705         struct drm_crtc *crtc = drm_crtc_from_index(ddev, 0);
706
707         /* Line IRQ : trigger the vblank event */
708         if (ldev->irq_status & ISR_LIF) {
709                 drm_crtc_handle_vblank(crtc);
710
711                 /* Early return if CRC is not active */
712                 if (ldev->crc_active)
713                         ltdc_irq_crc_handle(ldev, crtc);
714         }
715
716         /* Save FIFO Underrun & Transfer Error status */
717         mutex_lock(&ldev->err_lock);
718         if (ldev->irq_status & ISR_FUIF)
719                 ldev->error_status |= ISR_FUIF;
720         if (ldev->irq_status & ISR_TERRIF)
721                 ldev->error_status |= ISR_TERRIF;
722         mutex_unlock(&ldev->err_lock);
723
724         return IRQ_HANDLED;
725 }
726
727 static irqreturn_t ltdc_irq(int irq, void *arg)
728 {
729         struct drm_device *ddev = arg;
730         struct ltdc_device *ldev = ddev->dev_private;
731
732         /*
733          *  Read & Clear the interrupt status
734          *  In order to write / read registers in this critical section
735          *  very quickly, the regmap functions are not used.
736          */
737         ldev->irq_status = readl_relaxed(ldev->regs + LTDC_ISR);
738         writel_relaxed(ldev->irq_status, ldev->regs + LTDC_ICR);
739
740         return IRQ_WAKE_THREAD;
741 }
742
743 /*
744  * DRM_CRTC
745  */
746
747 static void ltdc_crtc_update_clut(struct drm_crtc *crtc)
748 {
749         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
750         struct drm_color_lut *lut;
751         u32 val;
752         int i;
753
754         if (!crtc->state->color_mgmt_changed || !crtc->state->gamma_lut)
755                 return;
756
757         lut = (struct drm_color_lut *)crtc->state->gamma_lut->data;
758
759         for (i = 0; i < CLUT_SIZE; i++, lut++) {
760                 val = ((lut->red << 8) & 0xff0000) | (lut->green & 0xff00) |
761                         (lut->blue >> 8) | (i << 24);
762                 regmap_write(ldev->regmap, LTDC_L1CLUTWR, val);
763         }
764 }
765
766 static void ltdc_crtc_atomic_enable(struct drm_crtc *crtc,
767                                     struct drm_atomic_state *state)
768 {
769         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
770         struct drm_device *ddev = crtc->dev;
771
772         DRM_DEBUG_DRIVER("\n");
773
774         pm_runtime_get_sync(ddev->dev);
775
776         /* Sets the background color value */
777         regmap_write(ldev->regmap, LTDC_BCCR, BCCR_BCBLACK);
778
779         /* Enable IRQ */
780         regmap_set_bits(ldev->regmap, LTDC_IER, IER_RRIE | IER_FUIE | IER_TERRIE);
781
782         /* Commit shadow registers = update planes at next vblank */
783         if (!ldev->caps.plane_reg_shadow)
784                 regmap_set_bits(ldev->regmap, LTDC_SRCR, SRCR_VBR);
785
786         drm_crtc_vblank_on(crtc);
787 }
788
789 static void ltdc_crtc_atomic_disable(struct drm_crtc *crtc,
790                                      struct drm_atomic_state *state)
791 {
792         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
793         struct drm_device *ddev = crtc->dev;
794         int layer_index = 0;
795
796         DRM_DEBUG_DRIVER("\n");
797
798         drm_crtc_vblank_off(crtc);
799
800         /* Disable all layers */
801         for (layer_index = 0; layer_index < ldev->caps.nb_layers; layer_index++)
802                 regmap_write_bits(ldev->regmap, LTDC_L1CR + layer_index * LAY_OFS,
803                                   LXCR_CLUTEN | LXCR_LEN, 0);
804
805         /* disable IRQ */
806         regmap_clear_bits(ldev->regmap, LTDC_IER, IER_RRIE | IER_FUIE | IER_TERRIE);
807
808         /* immediately commit disable of layers before switching off LTDC */
809         if (!ldev->caps.plane_reg_shadow)
810                 regmap_set_bits(ldev->regmap, LTDC_SRCR, SRCR_IMR);
811
812         pm_runtime_put_sync(ddev->dev);
813 }
814
815 #define CLK_TOLERANCE_HZ 50
816
817 static enum drm_mode_status
818 ltdc_crtc_mode_valid(struct drm_crtc *crtc,
819                      const struct drm_display_mode *mode)
820 {
821         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
822         int target = mode->clock * 1000;
823         int target_min = target - CLK_TOLERANCE_HZ;
824         int target_max = target + CLK_TOLERANCE_HZ;
825         int result;
826
827         result = clk_round_rate(ldev->pixel_clk, target);
828
829         DRM_DEBUG_DRIVER("clk rate target %d, available %d\n", target, result);
830
831         /* Filter modes according to the max frequency supported by the pads */
832         if (result > ldev->caps.pad_max_freq_hz)
833                 return MODE_CLOCK_HIGH;
834
835         /*
836          * Accept all "preferred" modes:
837          * - this is important for panels because panel clock tolerances are
838          *   bigger than hdmi ones and there is no reason to not accept them
839          *   (the fps may vary a little but it is not a problem).
840          * - the hdmi preferred mode will be accepted too, but userland will
841          *   be able to use others hdmi "valid" modes if necessary.
842          */
843         if (mode->type & DRM_MODE_TYPE_PREFERRED)
844                 return MODE_OK;
845
846         /*
847          * Filter modes according to the clock value, particularly useful for
848          * hdmi modes that require precise pixel clocks.
849          */
850         if (result < target_min || result > target_max)
851                 return MODE_CLOCK_RANGE;
852
853         return MODE_OK;
854 }
855
856 static bool ltdc_crtc_mode_fixup(struct drm_crtc *crtc,
857                                  const struct drm_display_mode *mode,
858                                  struct drm_display_mode *adjusted_mode)
859 {
860         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
861         int rate = mode->clock * 1000;
862
863         if (clk_set_rate(ldev->pixel_clk, rate) < 0) {
864                 DRM_ERROR("Cannot set rate (%dHz) for pixel clk\n", rate);
865                 return false;
866         }
867
868         adjusted_mode->clock = clk_get_rate(ldev->pixel_clk) / 1000;
869
870         DRM_DEBUG_DRIVER("requested clock %dkHz, adjusted clock %dkHz\n",
871                          mode->clock, adjusted_mode->clock);
872
873         return true;
874 }
875
876 static void ltdc_crtc_mode_set_nofb(struct drm_crtc *crtc)
877 {
878         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
879         struct drm_device *ddev = crtc->dev;
880         struct drm_connector_list_iter iter;
881         struct drm_connector *connector = NULL;
882         struct drm_encoder *encoder = NULL, *en_iter;
883         struct drm_bridge *bridge = NULL, *br_iter;
884         struct drm_display_mode *mode = &crtc->state->adjusted_mode;
885         u32 hsync, vsync, accum_hbp, accum_vbp, accum_act_w, accum_act_h;
886         u32 total_width, total_height;
887         u32 bus_formats = MEDIA_BUS_FMT_RGB888_1X24;
888         u32 bus_flags = 0;
889         u32 val;
890         int ret;
891
892         /* get encoder from crtc */
893         drm_for_each_encoder(en_iter, ddev)
894                 if (en_iter->crtc == crtc) {
895                         encoder = en_iter;
896                         break;
897                 }
898
899         if (encoder) {
900                 /* get bridge from encoder */
901                 list_for_each_entry(br_iter, &encoder->bridge_chain, chain_node)
902                         if (br_iter->encoder == encoder) {
903                                 bridge = br_iter;
904                                 break;
905                         }
906
907                 /* Get the connector from encoder */
908                 drm_connector_list_iter_begin(ddev, &iter);
909                 drm_for_each_connector_iter(connector, &iter)
910                         if (connector->encoder == encoder)
911                                 break;
912                 drm_connector_list_iter_end(&iter);
913         }
914
915         if (bridge && bridge->timings) {
916                 bus_flags = bridge->timings->input_bus_flags;
917         } else if (connector) {
918                 bus_flags = connector->display_info.bus_flags;
919                 if (connector->display_info.num_bus_formats)
920                         bus_formats = connector->display_info.bus_formats[0];
921         }
922
923         if (!pm_runtime_active(ddev->dev)) {
924                 ret = pm_runtime_get_sync(ddev->dev);
925                 if (ret) {
926                         DRM_ERROR("Failed to set mode, cannot get sync\n");
927                         return;
928                 }
929         }
930
931         DRM_DEBUG_DRIVER("CRTC:%d mode:%s\n", crtc->base.id, mode->name);
932         DRM_DEBUG_DRIVER("Video mode: %dx%d", mode->hdisplay, mode->vdisplay);
933         DRM_DEBUG_DRIVER(" hfp %d hbp %d hsl %d vfp %d vbp %d vsl %d\n",
934                          mode->hsync_start - mode->hdisplay,
935                          mode->htotal - mode->hsync_end,
936                          mode->hsync_end - mode->hsync_start,
937                          mode->vsync_start - mode->vdisplay,
938                          mode->vtotal - mode->vsync_end,
939                          mode->vsync_end - mode->vsync_start);
940
941         /* Convert video timings to ltdc timings */
942         hsync = mode->hsync_end - mode->hsync_start - 1;
943         vsync = mode->vsync_end - mode->vsync_start - 1;
944         accum_hbp = mode->htotal - mode->hsync_start - 1;
945         accum_vbp = mode->vtotal - mode->vsync_start - 1;
946         accum_act_w = accum_hbp + mode->hdisplay;
947         accum_act_h = accum_vbp + mode->vdisplay;
948         total_width = mode->htotal - 1;
949         total_height = mode->vtotal - 1;
950
951         /* Configures the HS, VS, DE and PC polarities. Default Active Low */
952         val = 0;
953
954         if (mode->flags & DRM_MODE_FLAG_PHSYNC)
955                 val |= GCR_HSPOL;
956
957         if (mode->flags & DRM_MODE_FLAG_PVSYNC)
958                 val |= GCR_VSPOL;
959
960         if (bus_flags & DRM_BUS_FLAG_DE_LOW)
961                 val |= GCR_DEPOL;
962
963         if (bus_flags & DRM_BUS_FLAG_PIXDATA_DRIVE_NEGEDGE)
964                 val |= GCR_PCPOL;
965
966         regmap_update_bits(ldev->regmap, LTDC_GCR,
967                            GCR_HSPOL | GCR_VSPOL | GCR_DEPOL | GCR_PCPOL, val);
968
969         /* Set Synchronization size */
970         val = (hsync << 16) | vsync;
971         regmap_update_bits(ldev->regmap, LTDC_SSCR, SSCR_VSH | SSCR_HSW, val);
972
973         /* Set Accumulated Back porch */
974         val = (accum_hbp << 16) | accum_vbp;
975         regmap_update_bits(ldev->regmap, LTDC_BPCR, BPCR_AVBP | BPCR_AHBP, val);
976
977         /* Set Accumulated Active Width */
978         val = (accum_act_w << 16) | accum_act_h;
979         regmap_update_bits(ldev->regmap, LTDC_AWCR, AWCR_AAW | AWCR_AAH, val);
980
981         /* Set total width & height */
982         val = (total_width << 16) | total_height;
983         regmap_update_bits(ldev->regmap, LTDC_TWCR, TWCR_TOTALH | TWCR_TOTALW, val);
984
985         regmap_write(ldev->regmap, LTDC_LIPCR, (accum_act_h + 1));
986
987         /* Configure the output format (hw version dependent) */
988         if (ldev->caps.ycbcr_output) {
989                 /* Input video dynamic_range & colorimetry */
990                 int vic = drm_match_cea_mode(mode);
991                 u32 val;
992
993                 if (vic == 6 || vic == 7 || vic == 21 || vic == 22 ||
994                     vic == 2 || vic == 3 || vic == 17 || vic == 18)
995                         /* ITU-R BT.601 */
996                         val = 0;
997                 else
998                         /* ITU-R BT.709 */
999                         val = EDCR_OCYSEL;
1000
1001                 switch (bus_formats) {
1002                 case MEDIA_BUS_FMT_YUYV8_1X16:
1003                         /* enable ycbcr output converter */
1004                         regmap_write(ldev->regmap, LTDC_EDCR, EDCR_OCYEN | val);
1005                         break;
1006                 case MEDIA_BUS_FMT_YVYU8_1X16:
1007                         /* enable ycbcr output converter & invert chrominance order */
1008                         regmap_write(ldev->regmap, LTDC_EDCR, EDCR_OCYEN | EDCR_OCYCO | val);
1009                         break;
1010                 default:
1011                         /* disable ycbcr output converter */
1012                         regmap_write(ldev->regmap, LTDC_EDCR, 0);
1013                         break;
1014                 }
1015         }
1016 }
1017
1018 static void ltdc_crtc_atomic_flush(struct drm_crtc *crtc,
1019                                    struct drm_atomic_state *state)
1020 {
1021         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
1022         struct drm_device *ddev = crtc->dev;
1023         struct drm_pending_vblank_event *event = crtc->state->event;
1024
1025         DRM_DEBUG_ATOMIC("\n");
1026
1027         ltdc_crtc_update_clut(crtc);
1028
1029         /* Commit shadow registers = update planes at next vblank */
1030         if (!ldev->caps.plane_reg_shadow)
1031                 regmap_set_bits(ldev->regmap, LTDC_SRCR, SRCR_VBR);
1032
1033         if (event) {
1034                 crtc->state->event = NULL;
1035
1036                 spin_lock_irq(&ddev->event_lock);
1037                 if (drm_crtc_vblank_get(crtc) == 0)
1038                         drm_crtc_arm_vblank_event(crtc, event);
1039                 else
1040                         drm_crtc_send_vblank_event(crtc, event);
1041                 spin_unlock_irq(&ddev->event_lock);
1042         }
1043 }
1044
1045 static bool ltdc_crtc_get_scanout_position(struct drm_crtc *crtc,
1046                                            bool in_vblank_irq,
1047                                            int *vpos, int *hpos,
1048                                            ktime_t *stime, ktime_t *etime,
1049                                            const struct drm_display_mode *mode)
1050 {
1051         struct drm_device *ddev = crtc->dev;
1052         struct ltdc_device *ldev = ddev->dev_private;
1053         int line, vactive_start, vactive_end, vtotal;
1054
1055         if (stime)
1056                 *stime = ktime_get();
1057
1058         /* The active area starts after vsync + front porch and ends
1059          * at vsync + front porc + display size.
1060          * The total height also include back porch.
1061          * We have 3 possible cases to handle:
1062          * - line < vactive_start: vpos = line - vactive_start and will be
1063          * negative
1064          * - vactive_start < line < vactive_end: vpos = line - vactive_start
1065          * and will be positive
1066          * - line > vactive_end: vpos = line - vtotal - vactive_start
1067          * and will negative
1068          *
1069          * Computation for the two first cases are identical so we can
1070          * simplify the code and only test if line > vactive_end
1071          */
1072         if (pm_runtime_active(ddev->dev)) {
1073                 regmap_read(ldev->regmap, LTDC_CPSR, &line);
1074                 line &= CPSR_CYPOS;
1075                 regmap_read(ldev->regmap, LTDC_BPCR, &vactive_start);
1076                 vactive_start &= BPCR_AVBP;
1077                 regmap_read(ldev->regmap, LTDC_AWCR, &vactive_end);
1078                 vactive_end &= AWCR_AAH;
1079                 regmap_read(ldev->regmap, LTDC_TWCR, &vtotal);
1080                 vtotal &= TWCR_TOTALH;
1081
1082                 if (line > vactive_end)
1083                         *vpos = line - vtotal - vactive_start;
1084                 else
1085                         *vpos = line - vactive_start;
1086         } else {
1087                 *vpos = 0;
1088         }
1089
1090         *hpos = 0;
1091
1092         if (etime)
1093                 *etime = ktime_get();
1094
1095         return true;
1096 }
1097
1098 static const struct drm_crtc_helper_funcs ltdc_crtc_helper_funcs = {
1099         .mode_valid = ltdc_crtc_mode_valid,
1100         .mode_fixup = ltdc_crtc_mode_fixup,
1101         .mode_set_nofb = ltdc_crtc_mode_set_nofb,
1102         .atomic_flush = ltdc_crtc_atomic_flush,
1103         .atomic_enable = ltdc_crtc_atomic_enable,
1104         .atomic_disable = ltdc_crtc_atomic_disable,
1105         .get_scanout_position = ltdc_crtc_get_scanout_position,
1106 };
1107
1108 static int ltdc_crtc_enable_vblank(struct drm_crtc *crtc)
1109 {
1110         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
1111         struct drm_crtc_state *state = crtc->state;
1112
1113         DRM_DEBUG_DRIVER("\n");
1114
1115         if (state->enable)
1116                 regmap_set_bits(ldev->regmap, LTDC_IER, IER_LIE);
1117         else
1118                 return -EPERM;
1119
1120         return 0;
1121 }
1122
1123 static void ltdc_crtc_disable_vblank(struct drm_crtc *crtc)
1124 {
1125         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
1126
1127         DRM_DEBUG_DRIVER("\n");
1128         regmap_clear_bits(ldev->regmap, LTDC_IER, IER_LIE);
1129 }
1130
1131 static int ltdc_crtc_set_crc_source(struct drm_crtc *crtc, const char *source)
1132 {
1133         struct ltdc_device *ldev = crtc_to_ltdc(crtc);
1134         int ret;
1135
1136         DRM_DEBUG_DRIVER("\n");
1137
1138         if (!crtc)
1139                 return -ENODEV;
1140
1141         if (source && strcmp(source, "auto") == 0) {
1142                 ldev->crc_active = true;
1143                 ret = regmap_set_bits(ldev->regmap, LTDC_GCR, GCR_CRCEN);
1144         } else if (!source) {
1145                 ldev->crc_active = false;
1146                 ret = regmap_clear_bits(ldev->regmap, LTDC_GCR, GCR_CRCEN);
1147         } else {
1148                 ret = -EINVAL;
1149         }
1150
1151         ldev->crc_skip_count = 0;
1152         return ret;
1153 }
1154
1155 static int ltdc_crtc_verify_crc_source(struct drm_crtc *crtc,
1156                                        const char *source, size_t *values_cnt)
1157 {
1158         DRM_DEBUG_DRIVER("\n");
1159
1160         if (!crtc)
1161                 return -ENODEV;
1162
1163         if (source && strcmp(source, "auto") != 0) {
1164                 DRM_DEBUG_DRIVER("Unknown CRC source %s for %s\n",
1165                                  source, crtc->name);
1166                 return -EINVAL;
1167         }
1168
1169         *values_cnt = 1;
1170         return 0;
1171 }
1172
1173 static const struct drm_crtc_funcs ltdc_crtc_funcs = {
1174         .destroy = drm_crtc_cleanup,
1175         .set_config = drm_atomic_helper_set_config,
1176         .page_flip = drm_atomic_helper_page_flip,
1177         .reset = drm_atomic_helper_crtc_reset,
1178         .atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state,
1179         .atomic_destroy_state = drm_atomic_helper_crtc_destroy_state,
1180         .enable_vblank = ltdc_crtc_enable_vblank,
1181         .disable_vblank = ltdc_crtc_disable_vblank,
1182         .get_vblank_timestamp = drm_crtc_vblank_helper_get_vblank_timestamp,
1183 };
1184
1185 static const struct drm_crtc_funcs ltdc_crtc_with_crc_support_funcs = {
1186         .destroy = drm_crtc_cleanup,
1187         .set_config = drm_atomic_helper_set_config,
1188         .page_flip = drm_atomic_helper_page_flip,
1189         .reset = drm_atomic_helper_crtc_reset,
1190         .atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state,
1191         .atomic_destroy_state = drm_atomic_helper_crtc_destroy_state,
1192         .enable_vblank = ltdc_crtc_enable_vblank,
1193         .disable_vblank = ltdc_crtc_disable_vblank,
1194         .get_vblank_timestamp = drm_crtc_vblank_helper_get_vblank_timestamp,
1195         .set_crc_source = ltdc_crtc_set_crc_source,
1196         .verify_crc_source = ltdc_crtc_verify_crc_source,
1197 };
1198
1199 /*
1200  * DRM_PLANE
1201  */
1202
1203 static int ltdc_plane_atomic_check(struct drm_plane *plane,
1204                                    struct drm_atomic_state *state)
1205 {
1206         struct drm_plane_state *new_plane_state = drm_atomic_get_new_plane_state(state,
1207                                                                                  plane);
1208         struct drm_framebuffer *fb = new_plane_state->fb;
1209         u32 src_w, src_h;
1210
1211         DRM_DEBUG_DRIVER("\n");
1212
1213         if (!fb)
1214                 return 0;
1215
1216         /* convert src_ from 16:16 format */
1217         src_w = new_plane_state->src_w >> 16;
1218         src_h = new_plane_state->src_h >> 16;
1219
1220         /* Reject scaling */
1221         if (src_w != new_plane_state->crtc_w || src_h != new_plane_state->crtc_h) {
1222                 DRM_DEBUG_DRIVER("Scaling is not supported");
1223
1224                 return -EINVAL;
1225         }
1226
1227         return 0;
1228 }
1229
1230 static void ltdc_plane_atomic_update(struct drm_plane *plane,
1231                                      struct drm_atomic_state *state)
1232 {
1233         struct ltdc_device *ldev = plane_to_ltdc(plane);
1234         struct drm_plane_state *newstate = drm_atomic_get_new_plane_state(state,
1235                                                                           plane);
1236         struct drm_framebuffer *fb = newstate->fb;
1237         u32 lofs = plane->index * LAY_OFS;
1238         u32 x0 = newstate->crtc_x;
1239         u32 x1 = newstate->crtc_x + newstate->crtc_w - 1;
1240         u32 y0 = newstate->crtc_y;
1241         u32 y1 = newstate->crtc_y + newstate->crtc_h - 1;
1242         u32 src_x, src_y, src_w, src_h;
1243         u32 val, pitch_in_bytes, line_length, line_number, paddr, ahbp, avbp, bpcr;
1244         enum ltdc_pix_fmt pf;
1245
1246         if (!newstate->crtc || !fb) {
1247                 DRM_DEBUG_DRIVER("fb or crtc NULL");
1248                 return;
1249         }
1250
1251         /* convert src_ from 16:16 format */
1252         src_x = newstate->src_x >> 16;
1253         src_y = newstate->src_y >> 16;
1254         src_w = newstate->src_w >> 16;
1255         src_h = newstate->src_h >> 16;
1256
1257         DRM_DEBUG_DRIVER("plane:%d fb:%d (%dx%d)@(%d,%d) -> (%dx%d)@(%d,%d)\n",
1258                          plane->base.id, fb->base.id,
1259                          src_w, src_h, src_x, src_y,
1260                          newstate->crtc_w, newstate->crtc_h,
1261                          newstate->crtc_x, newstate->crtc_y);
1262
1263         regmap_read(ldev->regmap, LTDC_BPCR, &bpcr);
1264
1265         ahbp = (bpcr & BPCR_AHBP) >> 16;
1266         avbp = bpcr & BPCR_AVBP;
1267
1268         /* Configures the horizontal start and stop position */
1269         val = ((x1 + 1 + ahbp) << 16) + (x0 + 1 + ahbp);
1270         regmap_write_bits(ldev->regmap, LTDC_L1WHPCR + lofs,
1271                           LXWHPCR_WHSTPOS | LXWHPCR_WHSPPOS, val);
1272
1273         /* Configures the vertical start and stop position */
1274         val = ((y1 + 1 + avbp) << 16) + (y0 + 1 + avbp);
1275         regmap_write_bits(ldev->regmap, LTDC_L1WVPCR + lofs,
1276                           LXWVPCR_WVSTPOS | LXWVPCR_WVSPPOS, val);
1277
1278         /* Specifies the pixel format */
1279         pf = to_ltdc_pixelformat(fb->format->format);
1280         for (val = 0; val < NB_PF; val++)
1281                 if (ldev->caps.pix_fmt_hw[val] == pf)
1282                         break;
1283
1284         /* Use the flexible color format feature if necessary and available */
1285         if (ldev->caps.pix_fmt_flex && val == NB_PF)
1286                 val = ltdc_set_flexible_pixel_format(plane, pf);
1287
1288         if (val == NB_PF) {
1289                 DRM_ERROR("Pixel format %.4s not supported\n",
1290                           (char *)&fb->format->format);
1291                 val = 0;        /* set by default ARGB 32 bits */
1292         }
1293         regmap_write_bits(ldev->regmap, LTDC_L1PFCR + lofs, LXPFCR_PF, val);
1294
1295         /* Configures the color frame buffer pitch in bytes & line length */
1296         pitch_in_bytes = fb->pitches[0];
1297         line_length = fb->format->cpp[0] *
1298                       (x1 - x0 + 1) + (ldev->caps.bus_width >> 3) - 1;
1299         val = ((pitch_in_bytes << 16) | line_length);
1300         regmap_write_bits(ldev->regmap, LTDC_L1CFBLR + lofs, LXCFBLR_CFBLL | LXCFBLR_CFBP, val);
1301
1302         /* Specifies the constant alpha value */
1303         val = newstate->alpha >> 8;
1304         regmap_write_bits(ldev->regmap, LTDC_L1CACR + lofs, LXCACR_CONSTA, val);
1305
1306         /* Specifies the blending factors */
1307         val = BF1_PAXCA | BF2_1PAXCA;
1308         if (!fb->format->has_alpha)
1309                 val = BF1_CA | BF2_1CA;
1310
1311         /* Manage hw-specific capabilities */
1312         if (ldev->caps.non_alpha_only_l1 &&
1313             plane->type != DRM_PLANE_TYPE_PRIMARY)
1314                 val = BF1_PAXCA | BF2_1PAXCA;
1315
1316         if (ldev->caps.dynamic_zorder) {
1317                 val |= (newstate->normalized_zpos << 16);
1318                 regmap_write_bits(ldev->regmap, LTDC_L1BFCR + lofs,
1319                                   LXBFCR_BF2 | LXBFCR_BF1 | LXBFCR_BOR, val);
1320         } else {
1321                 regmap_write_bits(ldev->regmap, LTDC_L1BFCR + lofs,
1322                                   LXBFCR_BF2 | LXBFCR_BF1, val);
1323         }
1324
1325         /* Configures the frame buffer line number */
1326         line_number = y1 - y0 + 1;
1327         regmap_write_bits(ldev->regmap, LTDC_L1CFBLNR + lofs, LXCFBLNR_CFBLN, line_number);
1328
1329         /* Sets the FB address */
1330         paddr = (u32)drm_fb_cma_get_gem_addr(fb, newstate, 0);
1331
1332         DRM_DEBUG_DRIVER("fb: phys 0x%08x", paddr);
1333         regmap_write(ldev->regmap, LTDC_L1CFBAR + lofs, paddr);
1334
1335         if (ldev->caps.ycbcr_input) {
1336                 if (fb->format->is_yuv) {
1337                         switch (fb->format->format) {
1338                         case DRM_FORMAT_NV12:
1339                         case DRM_FORMAT_NV21:
1340                         /* Configure the auxiliary frame buffer address 0 & 1 */
1341                         paddr = (u32)drm_fb_cma_get_gem_addr(fb, newstate, 1);
1342                         regmap_write(ldev->regmap, LTDC_L1AFBA0R + lofs, paddr);
1343                         regmap_write(ldev->regmap, LTDC_L1AFBA1R + lofs, paddr + 1);
1344
1345                         /* Configure the buffer length */
1346                         val = ((pitch_in_bytes << 16) | line_length);
1347                         regmap_write(ldev->regmap, LTDC_L1AFBLR + lofs, val);
1348
1349                         /* Configure the frame buffer line number */
1350                         val = (line_number >> 1);
1351                         regmap_write(ldev->regmap, LTDC_L1AFBLNR + lofs, val);
1352                         break;
1353                         case DRM_FORMAT_YUV420:
1354                         /* Configure the auxiliary frame buffer address 0 */
1355                         paddr = (u32)drm_fb_cma_get_gem_addr(fb, newstate, 1);
1356                         regmap_write(ldev->regmap, LTDC_L1AFBA0R + lofs, paddr);
1357
1358                         /* Configure the auxiliary frame buffer address 1 */
1359                         paddr = (u32)drm_fb_cma_get_gem_addr(fb, newstate, 2);
1360                         regmap_write(ldev->regmap, LTDC_L1AFBA1R + lofs, paddr);
1361
1362                         line_length = ((fb->format->cpp[0] * (x1 - x0 + 1)) >> 1) +
1363                                       (ldev->caps.bus_width >> 3) - 1;
1364
1365                         /* Configure the buffer length */
1366                         val = (((pitch_in_bytes >> 1) << 16) | line_length);
1367                         regmap_write(ldev->regmap, LTDC_L1AFBLR + lofs, val);
1368
1369                         /* Configure the frame buffer line number */
1370                         val = (line_number >> 1);
1371                         regmap_write(ldev->regmap, LTDC_L1AFBLNR + lofs, val);
1372                         break;
1373                         case DRM_FORMAT_YVU420:
1374                         /* Configure the auxiliary frame buffer address 0 */
1375                         paddr = (u32)drm_fb_cma_get_gem_addr(fb, newstate, 2);
1376                         regmap_write(ldev->regmap, LTDC_L1AFBA0R + lofs, paddr);
1377
1378                         /* Configure the auxiliary frame buffer address 1 */
1379                         paddr = (u32)drm_fb_cma_get_gem_addr(fb, newstate, 1);
1380                         regmap_write(ldev->regmap, LTDC_L1AFBA1R + lofs, paddr);
1381
1382                         line_length = ((fb->format->cpp[0] * (x1 - x0 + 1)) >> 1) +
1383                                       (ldev->caps.bus_width >> 3) - 1;
1384
1385                         /* Configure the buffer length */
1386                         val = (((pitch_in_bytes >> 1) << 16) | line_length);
1387                         regmap_write(ldev->regmap, LTDC_L1AFBLR + lofs, val);
1388
1389                         /* Configure the frame buffer line number */
1390                         val = (line_number >> 1);
1391                         regmap_write(ldev->regmap, LTDC_L1AFBLNR + lofs, val);
1392                         break;
1393                         }
1394
1395                         /* Configure YCbC conversion coefficient */
1396                         ltdc_set_ycbcr_coeffs(plane);
1397
1398                         /* Configure YCbCr format and enable/disable conversion */
1399                         ltdc_set_ycbcr_config(plane, fb->format->format);
1400                 } else {
1401                         /* disable ycbcr conversion */
1402                         regmap_write(ldev->regmap, LTDC_L1PCR + lofs, 0);
1403                 }
1404         }
1405
1406         /* Enable layer and CLUT if needed */
1407         val = fb->format->format == DRM_FORMAT_C8 ? LXCR_CLUTEN : 0;
1408         val |= LXCR_LEN;
1409         regmap_write_bits(ldev->regmap, LTDC_L1CR + lofs, LXCR_LEN | LXCR_CLUTEN, val);
1410
1411         /* Commit shadow registers = update plane at next vblank */
1412         if (ldev->caps.plane_reg_shadow)
1413                 regmap_write_bits(ldev->regmap, LTDC_L1RCR + lofs,
1414                                   LXRCR_IMR | LXRCR_VBR | LXRCR_GRMSK, LXRCR_VBR);
1415
1416         ldev->plane_fpsi[plane->index].counter++;
1417
1418         mutex_lock(&ldev->err_lock);
1419         if (ldev->error_status & ISR_FUIF) {
1420                 DRM_WARN("ltdc fifo underrun: please verify display mode\n");
1421                 ldev->error_status &= ~ISR_FUIF;
1422         }
1423         if (ldev->error_status & ISR_TERRIF) {
1424                 DRM_WARN("ltdc transfer error\n");
1425                 ldev->error_status &= ~ISR_TERRIF;
1426         }
1427         mutex_unlock(&ldev->err_lock);
1428 }
1429
1430 static void ltdc_plane_atomic_disable(struct drm_plane *plane,
1431                                       struct drm_atomic_state *state)
1432 {
1433         struct drm_plane_state *oldstate = drm_atomic_get_old_plane_state(state,
1434                                                                           plane);
1435         struct ltdc_device *ldev = plane_to_ltdc(plane);
1436         u32 lofs = plane->index * LAY_OFS;
1437
1438         /* disable layer */
1439         regmap_write_bits(ldev->regmap, LTDC_L1CR + lofs, LXCR_LEN, 0);
1440
1441         /* Commit shadow registers = update plane at next vblank */
1442         if (ldev->caps.plane_reg_shadow)
1443                 regmap_write_bits(ldev->regmap, LTDC_L1RCR + lofs,
1444                                   LXRCR_IMR | LXRCR_VBR | LXRCR_GRMSK, LXRCR_VBR);
1445
1446         DRM_DEBUG_DRIVER("CRTC:%d plane:%d\n",
1447                          oldstate->crtc->base.id, plane->base.id);
1448 }
1449
1450 static void ltdc_plane_atomic_print_state(struct drm_printer *p,
1451                                           const struct drm_plane_state *state)
1452 {
1453         struct drm_plane *plane = state->plane;
1454         struct ltdc_device *ldev = plane_to_ltdc(plane);
1455         struct fps_info *fpsi = &ldev->plane_fpsi[plane->index];
1456         int ms_since_last;
1457         ktime_t now;
1458
1459         now = ktime_get();
1460         ms_since_last = ktime_to_ms(ktime_sub(now, fpsi->last_timestamp));
1461
1462         drm_printf(p, "\tuser_updates=%dfps\n",
1463                    DIV_ROUND_CLOSEST(fpsi->counter * 1000, ms_since_last));
1464
1465         fpsi->last_timestamp = now;
1466         fpsi->counter = 0;
1467 }
1468
1469 static const struct drm_plane_funcs ltdc_plane_funcs = {
1470         .update_plane = drm_atomic_helper_update_plane,
1471         .disable_plane = drm_atomic_helper_disable_plane,
1472         .destroy = drm_plane_cleanup,
1473         .reset = drm_atomic_helper_plane_reset,
1474         .atomic_duplicate_state = drm_atomic_helper_plane_duplicate_state,
1475         .atomic_destroy_state = drm_atomic_helper_plane_destroy_state,
1476         .atomic_print_state = ltdc_plane_atomic_print_state,
1477 };
1478
1479 static const struct drm_plane_helper_funcs ltdc_plane_helper_funcs = {
1480         .atomic_check = ltdc_plane_atomic_check,
1481         .atomic_update = ltdc_plane_atomic_update,
1482         .atomic_disable = ltdc_plane_atomic_disable,
1483 };
1484
1485 static struct drm_plane *ltdc_plane_create(struct drm_device *ddev,
1486                                            enum drm_plane_type type,
1487                                            int index)
1488 {
1489         unsigned long possible_crtcs = CRTC_MASK;
1490         struct ltdc_device *ldev = ddev->dev_private;
1491         struct device *dev = ddev->dev;
1492         struct drm_plane *plane;
1493         unsigned int i, nb_fmt = 0;
1494         u32 *formats;
1495         u32 drm_fmt;
1496         const u64 *modifiers = ltdc_format_modifiers;
1497         u32 lofs = index * LAY_OFS;
1498         u32 val;
1499         int ret;
1500
1501         /* Allocate the biggest size according to supported color formats */
1502         formats = devm_kzalloc(dev, (ldev->caps.pix_fmt_nb +
1503                                ARRAY_SIZE(ltdc_drm_fmt_ycbcr_cp) +
1504                                ARRAY_SIZE(ltdc_drm_fmt_ycbcr_sp) +
1505                                ARRAY_SIZE(ltdc_drm_fmt_ycbcr_fp)) *
1506                                sizeof(*formats), GFP_KERNEL);
1507
1508         for (i = 0; i < ldev->caps.pix_fmt_nb; i++) {
1509                 drm_fmt = ldev->caps.pix_fmt_drm[i];
1510
1511                 /* Manage hw-specific capabilities */
1512                 if (ldev->caps.non_alpha_only_l1)
1513                         /* XR24 & RX24 like formats supported only on primary layer */
1514                         if (type != DRM_PLANE_TYPE_PRIMARY && is_xrgb(drm_fmt))
1515                                 continue;
1516
1517                 formats[nb_fmt++] = drm_fmt;
1518         }
1519
1520         /* Add YCbCr supported pixel formats */
1521         if (ldev->caps.ycbcr_input) {
1522                 regmap_read(ldev->regmap, LTDC_L1C1R + lofs, &val);
1523                 if (val & LXCR_C1R_YIA) {
1524                         memcpy(&formats[nb_fmt], ltdc_drm_fmt_ycbcr_cp,
1525                                ARRAY_SIZE(ltdc_drm_fmt_ycbcr_cp) * sizeof(*formats));
1526                         nb_fmt += ARRAY_SIZE(ltdc_drm_fmt_ycbcr_cp);
1527                 }
1528                 if (val & LXCR_C1R_YSPA) {
1529                         memcpy(&formats[nb_fmt], ltdc_drm_fmt_ycbcr_sp,
1530                                ARRAY_SIZE(ltdc_drm_fmt_ycbcr_sp) * sizeof(*formats));
1531                         nb_fmt += ARRAY_SIZE(ltdc_drm_fmt_ycbcr_sp);
1532                 }
1533                 if (val & LXCR_C1R_YFPA) {
1534                         memcpy(&formats[nb_fmt], ltdc_drm_fmt_ycbcr_fp,
1535                                ARRAY_SIZE(ltdc_drm_fmt_ycbcr_fp) * sizeof(*formats));
1536                         nb_fmt += ARRAY_SIZE(ltdc_drm_fmt_ycbcr_fp);
1537                 }
1538         }
1539
1540         plane = devm_kzalloc(dev, sizeof(*plane), GFP_KERNEL);
1541         if (!plane)
1542                 return NULL;
1543
1544         ret = drm_universal_plane_init(ddev, plane, possible_crtcs,
1545                                        &ltdc_plane_funcs, formats, nb_fmt,
1546                                        modifiers, type, NULL);
1547         if (ret < 0)
1548                 return NULL;
1549
1550         if (ldev->caps.ycbcr_input) {
1551                 if (val & (LXCR_C1R_YIA | LXCR_C1R_YSPA | LXCR_C1R_YFPA))
1552                         drm_plane_create_color_properties(plane,
1553                                                           BIT(DRM_COLOR_YCBCR_BT601) |
1554                                                           BIT(DRM_COLOR_YCBCR_BT709),
1555                                                           BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
1556                                                           BIT(DRM_COLOR_YCBCR_FULL_RANGE),
1557                                                           DRM_COLOR_YCBCR_BT601,
1558                                                           DRM_COLOR_YCBCR_LIMITED_RANGE);
1559         }
1560
1561         drm_plane_helper_add(plane, &ltdc_plane_helper_funcs);
1562
1563         drm_plane_create_alpha_property(plane);
1564
1565         DRM_DEBUG_DRIVER("plane:%d created\n", plane->base.id);
1566
1567         return plane;
1568 }
1569
1570 static void ltdc_plane_destroy_all(struct drm_device *ddev)
1571 {
1572         struct drm_plane *plane, *plane_temp;
1573
1574         list_for_each_entry_safe(plane, plane_temp,
1575                                  &ddev->mode_config.plane_list, head)
1576                 drm_plane_cleanup(plane);
1577 }
1578
1579 static int ltdc_crtc_init(struct drm_device *ddev, struct drm_crtc *crtc)
1580 {
1581         struct ltdc_device *ldev = ddev->dev_private;
1582         struct drm_plane *primary, *overlay;
1583         unsigned int i;
1584         int ret;
1585
1586         primary = ltdc_plane_create(ddev, DRM_PLANE_TYPE_PRIMARY, 0);
1587         if (!primary) {
1588                 DRM_ERROR("Can not create primary plane\n");
1589                 return -EINVAL;
1590         }
1591
1592         if (ldev->caps.dynamic_zorder)
1593                 drm_plane_create_zpos_property(primary, 0, 0, ldev->caps.nb_layers - 1);
1594         else
1595                 drm_plane_create_zpos_immutable_property(primary, 0);
1596
1597         /* Init CRTC according to its hardware features */
1598         if (ldev->caps.crc)
1599                 ret = drm_crtc_init_with_planes(ddev, crtc, primary, NULL,
1600                                                 &ltdc_crtc_with_crc_support_funcs, NULL);
1601         else
1602                 ret = drm_crtc_init_with_planes(ddev, crtc, primary, NULL,
1603                                                 &ltdc_crtc_funcs, NULL);
1604         if (ret) {
1605                 DRM_ERROR("Can not initialize CRTC\n");
1606                 goto cleanup;
1607         }
1608
1609         drm_crtc_helper_add(crtc, &ltdc_crtc_helper_funcs);
1610
1611         drm_mode_crtc_set_gamma_size(crtc, CLUT_SIZE);
1612         drm_crtc_enable_color_mgmt(crtc, 0, false, CLUT_SIZE);
1613
1614         DRM_DEBUG_DRIVER("CRTC:%d created\n", crtc->base.id);
1615
1616         /* Add planes. Note : the first layer is used by primary plane */
1617         for (i = 1; i < ldev->caps.nb_layers; i++) {
1618                 overlay = ltdc_plane_create(ddev, DRM_PLANE_TYPE_OVERLAY, i);
1619                 if (!overlay) {
1620                         ret = -ENOMEM;
1621                         DRM_ERROR("Can not create overlay plane %d\n", i);
1622                         goto cleanup;
1623                 }
1624                 if (ldev->caps.dynamic_zorder)
1625                         drm_plane_create_zpos_property(overlay, i, 0, ldev->caps.nb_layers - 1);
1626                 else
1627                         drm_plane_create_zpos_immutable_property(overlay, i);
1628         }
1629
1630         return 0;
1631
1632 cleanup:
1633         ltdc_plane_destroy_all(ddev);
1634         return ret;
1635 }
1636
1637 static void ltdc_encoder_disable(struct drm_encoder *encoder)
1638 {
1639         struct drm_device *ddev = encoder->dev;
1640         struct ltdc_device *ldev = ddev->dev_private;
1641
1642         DRM_DEBUG_DRIVER("\n");
1643
1644         /* Disable LTDC */
1645         regmap_clear_bits(ldev->regmap, LTDC_GCR, GCR_LTDCEN);
1646
1647         /* Set to sleep state the pinctrl whatever type of encoder */
1648         pinctrl_pm_select_sleep_state(ddev->dev);
1649 }
1650
1651 static void ltdc_encoder_enable(struct drm_encoder *encoder)
1652 {
1653         struct drm_device *ddev = encoder->dev;
1654         struct ltdc_device *ldev = ddev->dev_private;
1655
1656         DRM_DEBUG_DRIVER("\n");
1657
1658         /* Enable LTDC */
1659         regmap_set_bits(ldev->regmap, LTDC_GCR, GCR_LTDCEN);
1660 }
1661
1662 static void ltdc_encoder_mode_set(struct drm_encoder *encoder,
1663                                   struct drm_display_mode *mode,
1664                                   struct drm_display_mode *adjusted_mode)
1665 {
1666         struct drm_device *ddev = encoder->dev;
1667
1668         DRM_DEBUG_DRIVER("\n");
1669
1670         /*
1671          * Set to default state the pinctrl only with DPI type.
1672          * Others types like DSI, don't need pinctrl due to
1673          * internal bridge (the signals do not come out of the chipset).
1674          */
1675         if (encoder->encoder_type == DRM_MODE_ENCODER_DPI)
1676                 pinctrl_pm_select_default_state(ddev->dev);
1677 }
1678
1679 static const struct drm_encoder_helper_funcs ltdc_encoder_helper_funcs = {
1680         .disable = ltdc_encoder_disable,
1681         .enable = ltdc_encoder_enable,
1682         .mode_set = ltdc_encoder_mode_set,
1683 };
1684
1685 static int ltdc_encoder_init(struct drm_device *ddev, struct drm_bridge *bridge)
1686 {
1687         struct drm_encoder *encoder;
1688         int ret;
1689
1690         encoder = devm_kzalloc(ddev->dev, sizeof(*encoder), GFP_KERNEL);
1691         if (!encoder)
1692                 return -ENOMEM;
1693
1694         encoder->possible_crtcs = CRTC_MASK;
1695         encoder->possible_clones = 0;   /* No cloning support */
1696
1697         drm_simple_encoder_init(ddev, encoder, DRM_MODE_ENCODER_DPI);
1698
1699         drm_encoder_helper_add(encoder, &ltdc_encoder_helper_funcs);
1700
1701         ret = drm_bridge_attach(encoder, bridge, NULL, 0);
1702         if (ret) {
1703                 if (ret != -EPROBE_DEFER)
1704                         drm_encoder_cleanup(encoder);
1705                 return ret;
1706         }
1707
1708         DRM_DEBUG_DRIVER("Bridge encoder:%d created\n", encoder->base.id);
1709
1710         return 0;
1711 }
1712
1713 static int ltdc_get_caps(struct drm_device *ddev)
1714 {
1715         struct ltdc_device *ldev = ddev->dev_private;
1716         u32 bus_width_log2, lcr, gc2r;
1717
1718         /*
1719          * at least 1 layer must be managed & the number of layers
1720          * must not exceed LTDC_MAX_LAYER
1721          */
1722         regmap_read(ldev->regmap, LTDC_LCR, &lcr);
1723
1724         ldev->caps.nb_layers = clamp((int)lcr, 1, LTDC_MAX_LAYER);
1725
1726         /* set data bus width */
1727         regmap_read(ldev->regmap, LTDC_GC2R, &gc2r);
1728         bus_width_log2 = (gc2r & GC2R_BW) >> 4;
1729         ldev->caps.bus_width = 8 << bus_width_log2;
1730         regmap_read(ldev->regmap, LTDC_IDR, &ldev->caps.hw_version);
1731
1732         switch (ldev->caps.hw_version) {
1733         case HWVER_10200:
1734         case HWVER_10300:
1735                 ldev->caps.layer_ofs = LAY_OFS_0;
1736                 ldev->caps.layer_regs = ltdc_layer_regs_a0;
1737                 ldev->caps.pix_fmt_hw = ltdc_pix_fmt_a0;
1738                 ldev->caps.pix_fmt_drm = ltdc_drm_fmt_a0;
1739                 ldev->caps.pix_fmt_nb = ARRAY_SIZE(ltdc_drm_fmt_a0);
1740                 ldev->caps.pix_fmt_flex = false;
1741                 /*
1742                  * Hw older versions support non-alpha color formats derived
1743                  * from native alpha color formats only on the primary layer.
1744                  * For instance, RG16 native format without alpha works fine
1745                  * on 2nd layer but XR24 (derived color format from AR24)
1746                  * does not work on 2nd layer.
1747                  */
1748                 ldev->caps.non_alpha_only_l1 = true;
1749                 ldev->caps.pad_max_freq_hz = 90000000;
1750                 if (ldev->caps.hw_version == HWVER_10200)
1751                         ldev->caps.pad_max_freq_hz = 65000000;
1752                 ldev->caps.nb_irq = 2;
1753                 ldev->caps.ycbcr_input = false;
1754                 ldev->caps.ycbcr_output = false;
1755                 ldev->caps.plane_reg_shadow = false;
1756                 ldev->caps.crc = false;
1757                 ldev->caps.dynamic_zorder = false;
1758                 break;
1759         case HWVER_20101:
1760                 ldev->caps.layer_ofs = LAY_OFS_0;
1761                 ldev->caps.layer_regs = ltdc_layer_regs_a1;
1762                 ldev->caps.pix_fmt_hw = ltdc_pix_fmt_a1;
1763                 ldev->caps.pix_fmt_drm = ltdc_drm_fmt_a1;
1764                 ldev->caps.pix_fmt_nb = ARRAY_SIZE(ltdc_drm_fmt_a1);
1765                 ldev->caps.pix_fmt_flex = false;
1766                 ldev->caps.non_alpha_only_l1 = false;
1767                 ldev->caps.pad_max_freq_hz = 150000000;
1768                 ldev->caps.nb_irq = 4;
1769                 ldev->caps.ycbcr_input = false;
1770                 ldev->caps.ycbcr_output = false;
1771                 ldev->caps.plane_reg_shadow = false;
1772                 ldev->caps.crc = false;
1773                 ldev->caps.dynamic_zorder = false;
1774                 break;
1775         case HWVER_40100:
1776                 ldev->caps.layer_ofs = LAY_OFS_1;
1777                 ldev->caps.layer_regs = ltdc_layer_regs_a2;
1778                 ldev->caps.pix_fmt_hw = ltdc_pix_fmt_a2;
1779                 ldev->caps.pix_fmt_drm = ltdc_drm_fmt_a2;
1780                 ldev->caps.pix_fmt_nb = ARRAY_SIZE(ltdc_drm_fmt_a2);
1781                 ldev->caps.pix_fmt_flex = true;
1782                 ldev->caps.non_alpha_only_l1 = false;
1783                 ldev->caps.pad_max_freq_hz = 90000000;
1784                 ldev->caps.nb_irq = 2;
1785                 ldev->caps.ycbcr_input = true;
1786                 ldev->caps.ycbcr_output = true;
1787                 ldev->caps.plane_reg_shadow = true;
1788                 ldev->caps.crc = true;
1789                 ldev->caps.dynamic_zorder = true;
1790                 break;
1791         default:
1792                 return -ENODEV;
1793         }
1794
1795         return 0;
1796 }
1797
1798 void ltdc_suspend(struct drm_device *ddev)
1799 {
1800         struct ltdc_device *ldev = ddev->dev_private;
1801
1802         DRM_DEBUG_DRIVER("\n");
1803         clk_disable_unprepare(ldev->pixel_clk);
1804 }
1805
1806 int ltdc_resume(struct drm_device *ddev)
1807 {
1808         struct ltdc_device *ldev = ddev->dev_private;
1809         int ret;
1810
1811         DRM_DEBUG_DRIVER("\n");
1812
1813         ret = clk_prepare_enable(ldev->pixel_clk);
1814         if (ret) {
1815                 DRM_ERROR("failed to enable pixel clock (%d)\n", ret);
1816                 return ret;
1817         }
1818
1819         return 0;
1820 }
1821
1822 int ltdc_load(struct drm_device *ddev)
1823 {
1824         struct platform_device *pdev = to_platform_device(ddev->dev);
1825         struct ltdc_device *ldev = ddev->dev_private;
1826         struct device *dev = ddev->dev;
1827         struct device_node *np = dev->of_node;
1828         struct drm_bridge *bridge;
1829         struct drm_panel *panel;
1830         struct drm_crtc *crtc;
1831         struct reset_control *rstc;
1832         struct resource *res;
1833         int irq, i, nb_endpoints;
1834         int ret = -ENODEV;
1835
1836         DRM_DEBUG_DRIVER("\n");
1837
1838         /* Get number of endpoints */
1839         nb_endpoints = of_graph_get_endpoint_count(np);
1840         if (!nb_endpoints)
1841                 return -ENODEV;
1842
1843         ldev->pixel_clk = devm_clk_get(dev, "lcd");
1844         if (IS_ERR(ldev->pixel_clk)) {
1845                 if (PTR_ERR(ldev->pixel_clk) != -EPROBE_DEFER)
1846                         DRM_ERROR("Unable to get lcd clock\n");
1847                 return PTR_ERR(ldev->pixel_clk);
1848         }
1849
1850         if (clk_prepare_enable(ldev->pixel_clk)) {
1851                 DRM_ERROR("Unable to prepare pixel clock\n");
1852                 return -ENODEV;
1853         }
1854
1855         /* Get endpoints if any */
1856         for (i = 0; i < nb_endpoints; i++) {
1857                 ret = drm_of_find_panel_or_bridge(np, 0, i, &panel, &bridge);
1858
1859                 /*
1860                  * If at least one endpoint is -ENODEV, continue probing,
1861                  * else if at least one endpoint returned an error
1862                  * (ie -EPROBE_DEFER) then stop probing.
1863                  */
1864                 if (ret == -ENODEV)
1865                         continue;
1866                 else if (ret)
1867                         goto err;
1868
1869                 if (panel) {
1870                         bridge = drm_panel_bridge_add_typed(panel,
1871                                                             DRM_MODE_CONNECTOR_DPI);
1872                         if (IS_ERR(bridge)) {
1873                                 DRM_ERROR("panel-bridge endpoint %d\n", i);
1874                                 ret = PTR_ERR(bridge);
1875                                 goto err;
1876                         }
1877                 }
1878
1879                 if (bridge) {
1880                         ret = ltdc_encoder_init(ddev, bridge);
1881                         if (ret) {
1882                                 if (ret != -EPROBE_DEFER)
1883                                         DRM_ERROR("init encoder endpoint %d\n", i);
1884                                 goto err;
1885                         }
1886                 }
1887         }
1888
1889         rstc = devm_reset_control_get_exclusive(dev, NULL);
1890
1891         mutex_init(&ldev->err_lock);
1892
1893         if (!IS_ERR(rstc)) {
1894                 reset_control_assert(rstc);
1895                 usleep_range(10, 20);
1896                 reset_control_deassert(rstc);
1897         }
1898
1899         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1900         ldev->regs = devm_ioremap_resource(dev, res);
1901         if (IS_ERR(ldev->regs)) {
1902                 DRM_ERROR("Unable to get ltdc registers\n");
1903                 ret = PTR_ERR(ldev->regs);
1904                 goto err;
1905         }
1906
1907         ldev->regmap = devm_regmap_init_mmio(&pdev->dev, ldev->regs, &stm32_ltdc_regmap_cfg);
1908         if (IS_ERR(ldev->regmap)) {
1909                 DRM_ERROR("Unable to regmap ltdc registers\n");
1910                 ret = PTR_ERR(ldev->regmap);
1911                 goto err;
1912         }
1913
1914         /* Disable interrupts */
1915         regmap_clear_bits(ldev->regmap, LTDC_IER, IER_LIE | IER_RRIE | IER_FUIE | IER_TERRIE);
1916
1917         ret = ltdc_get_caps(ddev);
1918         if (ret) {
1919                 DRM_ERROR("hardware identifier (0x%08x) not supported!\n",
1920                           ldev->caps.hw_version);
1921                 goto err;
1922         }
1923
1924         DRM_DEBUG_DRIVER("ltdc hw version 0x%08x\n", ldev->caps.hw_version);
1925
1926         for (i = 0; i < ldev->caps.nb_irq; i++) {
1927                 irq = platform_get_irq(pdev, i);
1928                 if (irq < 0) {
1929                         ret = irq;
1930                         goto err;
1931                 }
1932
1933                 ret = devm_request_threaded_irq(dev, irq, ltdc_irq,
1934                                                 ltdc_irq_thread, IRQF_ONESHOT,
1935                                                 dev_name(dev), ddev);
1936                 if (ret) {
1937                         DRM_ERROR("Failed to register LTDC interrupt\n");
1938                         goto err;
1939                 }
1940         }
1941
1942         crtc = devm_kzalloc(dev, sizeof(*crtc), GFP_KERNEL);
1943         if (!crtc) {
1944                 DRM_ERROR("Failed to allocate crtc\n");
1945                 ret = -ENOMEM;
1946                 goto err;
1947         }
1948
1949         ret = ltdc_crtc_init(ddev, crtc);
1950         if (ret) {
1951                 DRM_ERROR("Failed to init crtc\n");
1952                 goto err;
1953         }
1954
1955         ret = drm_vblank_init(ddev, NB_CRTC);
1956         if (ret) {
1957                 DRM_ERROR("Failed calling drm_vblank_init()\n");
1958                 goto err;
1959         }
1960
1961         clk_disable_unprepare(ldev->pixel_clk);
1962
1963         pinctrl_pm_select_sleep_state(ddev->dev);
1964
1965         pm_runtime_enable(ddev->dev);
1966
1967         return 0;
1968 err:
1969         for (i = 0; i < nb_endpoints; i++)
1970                 drm_of_panel_bridge_remove(ddev->dev->of_node, 0, i);
1971
1972         clk_disable_unprepare(ldev->pixel_clk);
1973
1974         return ret;
1975 }
1976
1977 void ltdc_unload(struct drm_device *ddev)
1978 {
1979         struct device *dev = ddev->dev;
1980         int nb_endpoints, i;
1981
1982         DRM_DEBUG_DRIVER("\n");
1983
1984         nb_endpoints = of_graph_get_endpoint_count(dev->of_node);
1985
1986         for (i = 0; i < nb_endpoints; i++)
1987                 drm_of_panel_bridge_remove(ddev->dev->of_node, 0, i);
1988
1989         pm_runtime_disable(ddev->dev);
1990 }
1991
1992 MODULE_AUTHOR("Philippe Cornu <philippe.cornu@st.com>");
1993 MODULE_AUTHOR("Yannick Fertre <yannick.fertre@st.com>");
1994 MODULE_AUTHOR("Fabien Dessenne <fabien.dessenne@st.com>");
1995 MODULE_AUTHOR("Mickael Reulier <mickael.reulier@st.com>");
1996 MODULE_DESCRIPTION("STMicroelectronics ST DRM LTDC driver");
1997 MODULE_LICENSE("GPL v2");