summaryrefslogtreecommitdiff
path: root/samsung/panel/panel-samsung-drv.c
blob: 80eb6f2b5655c75e2f8ba43051788e9e773b1c71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
// SPDX-License-Identifier: GPL-2.0-only
/*
 * MIPI-DSI based Samsung common panel driver.
 *
 * Copyright (c) 2019 Samsung Electronics Co., Ltd
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of_platform.h>
#include <linux/of_gpio.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>
#include <linux/sysfs.h>
#include <uapi/linux/sched/types.h>
#include <drm/drm_atomic.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_encoder.h>
#include <drm/drm_mipi_dsi.h>
#include <drm/drm_panel.h>
#include <drm/drm_print.h>
#include <drm/drm_probe_helper.h>
#include <drm/drm_vblank.h>
#include <video/mipi_display.h>

#include <trace/dpu_trace.h>
#include "../exynos_drm_connector.h"
#include "../exynos_drm_dsim.h"
#include "panel-samsung-drv.h"

#define PANEL_ID_REG		0xA1
#define PANEL_ID_LEN		7
#define PANEL_ID_OFFSET		6
#define PANEL_ID_READ_SIZE	(PANEL_ID_LEN + PANEL_ID_OFFSET)
#define PANEL_SLSI_DDIC_ID_REG	0xD6
#define PANEL_SLSI_DDIC_ID_LEN	5

static const char ext_info_regs[] = { 0xDA, 0xDB, 0xDC };
#define EXT_INFO_SIZE ARRAY_SIZE(ext_info_regs)

#define exynos_connector_to_panel(c)					\
	container_of((c), struct exynos_panel, exynos_connector)

#define bridge_to_exynos_panel(b) \
	container_of((b), struct exynos_panel, bridge)

static void exynos_panel_set_backlight_state(struct exynos_panel *ctx,
					enum exynos_panel_state panel_state);
static ssize_t exynos_panel_parse_byte_buf(char *input_str, size_t input_len,
					   const char **out_buf);
static int parse_u32_buf(char *src, size_t src_len, u32 *out, size_t out_len);
static const struct exynos_panel_mode *exynos_panel_get_mode(struct exynos_panel *ctx,
							     const struct drm_display_mode *mode);
static void panel_update_local_hbm_locked(struct exynos_panel *ctx, bool enable);
static void exynos_panel_check_mipi_sync_timing(struct drm_crtc *crtc,
					 const struct exynos_panel_mode *current_mode,
					 struct exynos_panel *ctx);

static inline bool is_backlight_off_state(const struct backlight_device *bl)
{
	return (bl->props.state & BL_STATE_STANDBY) != 0;
}

static inline bool is_backlight_lp_state(const struct backlight_device *bl)
{
	return (bl->props.state & BL_STATE_LP) != 0;
}

int exynos_panel_configure_te2_edges(struct exynos_panel *ctx,
				     u32 *timings, bool lp_mode)
{
	struct te2_mode_data *data;
	const u32 *t;
	int i;

	if (!ctx || !timings)
		return -EINVAL;

	t = timings;

	for_each_te2_timing(ctx, lp_mode, data, i) {
		data->timing.rising_edge = t[0];
		data->timing.falling_edge = t[1];
		t += 2;
	}

	return 0;
}
EXPORT_SYMBOL(exynos_panel_configure_te2_edges);

ssize_t exynos_panel_get_te2_edges(struct exynos_panel *ctx,
				   char *buf, bool lp_mode)
{
	struct te2_mode_data *data;
	size_t len = 0;
	int i;

	if (!ctx)
		return -EINVAL;

	for_each_te2_timing(ctx, lp_mode, data, i) {
		len += scnprintf(buf + len, PAGE_SIZE - len, "%dx%d@%d",
				 data->mode->hdisplay, data->mode->vdisplay,
				 drm_mode_vrefresh(data->mode));

		if (data->binned_lp)
			len += scnprintf(buf + len, PAGE_SIZE - len, "-lp_%s",
					 data->binned_lp->name);

		len += scnprintf(buf + len, PAGE_SIZE - len,
				 " rising %u falling %u\n",
				 data->timing.rising_edge,
				 data->timing.falling_edge);
	}

	return len;
}
EXPORT_SYMBOL(exynos_panel_get_te2_edges);

int exynos_panel_get_current_mode_te2(struct exynos_panel *ctx,
				      struct exynos_panel_te2_timing *timing)
{
	struct te2_mode_data *data;
	const struct drm_display_mode *mode;
	u32 bl_th = 0;
	bool lp_mode;
	int i;

	if (!ctx)
		return -EINVAL;

	if (!ctx->current_mode)
		return -EAGAIN;

	mode = &ctx->current_mode->mode;
	lp_mode = ctx->current_mode->exynos_mode.is_lp_mode;

	if (lp_mode && !ctx->desc->num_binned_lp) {
		dev_warn(ctx->dev, "Missing LP mode command set\n");
		return -EINVAL;
	}

	if (lp_mode && !ctx->current_binned_lp)
		return -EAGAIN;

	if (ctx->current_binned_lp)
		bl_th = ctx->current_binned_lp->bl_threshold;

	for_each_te2_timing(ctx, lp_mode, data, i) {
		if (data->mode != mode)
			continue;

		if (data->binned_lp && data->binned_lp->bl_threshold != bl_th)
			continue;

		timing->rising_edge = data->timing.rising_edge;
		timing->falling_edge = data->timing.falling_edge;

		dev_dbg(ctx->dev,
			"found TE2 timing %s at %dHz: rising %u falling %u\n",
			!lp_mode ? "normal" : "LP", drm_mode_vrefresh(mode),
			timing->rising_edge, timing->falling_edge);

		return 0;
	}

	dev_warn(ctx->dev, "failed to find %s TE2 timing at %dHz\n",
		 !lp_mode ? "normal" : "LP", drm_mode_vrefresh(mode));

	return -EINVAL;
}
EXPORT_SYMBOL(exynos_panel_get_current_mode_te2);

static void exynos_panel_update_te2(struct exynos_panel *ctx)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;

	if (!is_panel_active(ctx) || !funcs || !funcs->update_te2)
		return;

	funcs->update_te2(ctx);

	if (ctx->bl)
		te2_state_changed(ctx->bl);
}

static int exynos_panel_parse_gpios(struct exynos_panel *ctx)
{
	struct device *dev = ctx->dev;

	dev_dbg(ctx->dev, "%s +\n", __func__);

	if (IS_ENABLED(CONFIG_BOARD_EMULATOR)) {
		dev_info(ctx->dev, "no reset/enable pins on emulator\n");
		return 0;
	}

	ctx->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_ASIS);
	if (IS_ERR(ctx->reset_gpio)) {
		dev_err(ctx->dev, "failed to get reset-gpios %ld",
				PTR_ERR(ctx->reset_gpio));
		return PTR_ERR(ctx->reset_gpio);
	}

	ctx->enable_gpio = devm_gpiod_get(dev, "enable", GPIOD_OUT_LOW);
	if (IS_ERR(ctx->enable_gpio))
		ctx->enable_gpio = NULL;

	dev_dbg(ctx->dev, "%s -\n", __func__);
	return 0;
}

static int exynos_panel_parse_regulators(struct exynos_panel *ctx)
{
	struct device *dev = ctx->dev;
	struct regulator *reg;
	int ret;

	ctx->vddi = devm_regulator_get(dev, "vddi");
	if (IS_ERR(ctx->vddi)) {
		dev_warn(ctx->dev, "failed to get panel vddi.\n");
		return -EPROBE_DEFER;
	}

	ctx->vci = devm_regulator_get(dev, "vci");
	if (IS_ERR(ctx->vci)) {
		dev_warn(ctx->dev, "failed to get panel vci.\n");
		return -EPROBE_DEFER;
	}

	reg = devm_regulator_get_optional(dev, "vddd");
	if (!PTR_ERR_OR_ZERO(reg)) {
		pr_info("panel vddd found\n");
		ctx->vddd = reg;
	}

	ret = of_property_read_u32(dev->of_node, "vddd-normal-microvolt", &ctx->vddd_normal_uV);
	if (ret)
		ctx->vddd_normal_uV = 0;

	ret = of_property_read_u32(dev->of_node, "vddd-lp-microvolt", &ctx->vddd_lp_uV);
	if (ret) {
		ctx->vddd_lp_uV = 0;
		if (ctx->vddd_normal_uV != 0) {
			pr_warn("ignore vddd normal %u\n", ctx->vddd_normal_uV);
			ctx->vddd_normal_uV = 0;
		}
	}

	reg = devm_regulator_get_optional(dev, "vddr_en");
	if (!PTR_ERR_OR_ZERO(reg)) {
		dev_dbg(ctx->dev, "panel vddr_en found\n");
		ctx->vddr_en = reg;
	}

	reg = devm_regulator_get_optional(dev, "vddr");
	if (!PTR_ERR_OR_ZERO(reg)) {
		dev_dbg(ctx->dev, "panel vddr found\n");
		ctx->vddr = reg;
	}

	return 0;
}

int exynos_panel_read_id(struct exynos_panel *ctx)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	char buf[PANEL_ID_READ_SIZE];
	int ret;

	ret = mipi_dsi_dcs_read(dsi, ctx->desc->panel_id_reg ? : PANEL_ID_REG,
				buf, PANEL_ID_READ_SIZE);
	if (ret != PANEL_ID_READ_SIZE) {
		dev_warn(ctx->dev, "Unable to read panel id (%d)\n", ret);
		return ret;
	}

	exynos_bin2hex(buf + PANEL_ID_OFFSET, PANEL_ID_LEN,
		       ctx->panel_id, sizeof(ctx->panel_id));

	return 0;
}
EXPORT_SYMBOL(exynos_panel_read_id);

int exynos_panel_read_ddic_id(struct exynos_panel *ctx)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	char buf[PANEL_SLSI_DDIC_ID_LEN] = {0};
	int ret;

	EXYNOS_DCS_BUF_ADD_AND_FLUSH(ctx, 0xF0, 0x5A, 0x5A);
	ret = mipi_dsi_dcs_read(dsi, PANEL_SLSI_DDIC_ID_REG,
				buf, PANEL_SLSI_DDIC_ID_LEN);
	EXYNOS_DCS_BUF_ADD_AND_FLUSH(ctx, 0xF0, 0xA5, 0xA5);
	if (ret != PANEL_SLSI_DDIC_ID_LEN) {
		dev_warn(ctx->dev, "Unable to read DDIC id (%d)\n", ret);
		return ret;
	}

	exynos_bin2hex(buf, PANEL_SLSI_DDIC_ID_LEN,
				ctx->panel_id, sizeof(ctx->panel_id));
	return 0;
}
EXPORT_SYMBOL(exynos_panel_read_ddic_id);

static int exynos_panel_read_extinfo(struct exynos_panel *ctx)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	char buf[EXT_INFO_SIZE];
	int i, ret;

	for (i = 0; i < EXT_INFO_SIZE; i++) {
		ret = mipi_dsi_dcs_read(dsi, ext_info_regs[i], buf + i, 1);
		if (ret != 1) {
			dev_warn(ctx->dev,
				 "Unable to read panel extinfo (0x%x: %d)\n",
				 ext_info_regs[i], ret);
			return ret;
		}

	}
	exynos_bin2hex(buf, i, ctx->panel_extinfo, sizeof(ctx->panel_extinfo));

	return 0;
}

void exynos_panel_get_panel_rev(struct exynos_panel *ctx, u8 rev)
{
	switch (rev) {
	case 0:
		ctx->panel_rev = PANEL_REV_PROTO1;
		break;
	case 1:
		ctx->panel_rev = PANEL_REV_PROTO1_1;
		break;
	case 2:
		ctx->panel_rev = PANEL_REV_PROTO1_2;
		break;
	case 8:
		ctx->panel_rev = PANEL_REV_EVT1;
		break;
	case 9:
		ctx->panel_rev = PANEL_REV_EVT1_1;
		break;
	case 0xA:
		ctx->panel_rev = PANEL_REV_EVT1_2;
		break;
	case 0xC:
		ctx->panel_rev = PANEL_REV_DVT1;
		break;
	case 0xD:
		ctx->panel_rev = PANEL_REV_DVT1_1;
		break;
	case 0x10:
		ctx->panel_rev = PANEL_REV_PVT;
		break;
	default:
		dev_warn(ctx->dev,
			 "unknown rev from panel (0x%x), default to latest\n",
			 rev);
		ctx->panel_rev = PANEL_REV_LATEST;
		return;
	}

	dev_info(ctx->dev, "panel_rev: 0x%x\n", ctx->panel_rev);
}
EXPORT_SYMBOL(exynos_panel_get_panel_rev);

int exynos_panel_init(struct exynos_panel *ctx)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	int ret;

	if (ctx->initialized)
		return 0;

	ret = exynos_panel_read_extinfo(ctx);
	if (!ret)
		ctx->initialized = true;

	if (funcs && funcs->get_panel_rev) {
		u32 id;

		if (kstrtou32(ctx->panel_extinfo, 16, &id)) {
			dev_warn(ctx->dev,
				 "failed to get panel extinfo, default to latest\n");
			ctx->panel_rev = PANEL_REV_LATEST;
		} else {
			funcs->get_panel_rev(ctx, id);
		}
	} else {
		dev_warn(ctx->dev,
			 "unable to get panel rev, default to latest\n");
		ctx->panel_rev = PANEL_REV_LATEST;
	}

	if (funcs && funcs->read_id)
		ret = funcs->read_id(ctx);
	else
		ret = exynos_panel_read_id(ctx);
	if (ret)
		return ret;

	if (funcs && funcs->panel_init)
		funcs->panel_init(ctx);

	return ret;
}
EXPORT_SYMBOL(exynos_panel_init);

void exynos_panel_reset(struct exynos_panel *ctx)
{
	dev_dbg(ctx->dev, "%s +\n", __func__);

	if (IS_ENABLED(CONFIG_BOARD_EMULATOR))
		return;

	gpiod_set_value(ctx->reset_gpio, 1);
	usleep_range(5000, 6000);
	gpiod_set_value(ctx->reset_gpio, 0);
	usleep_range(5000, 6000);
	gpiod_set_value(ctx->reset_gpio, 1);
	usleep_range(10000, 11000);

	dev_dbg(ctx->dev, "%s -\n", __func__);

	exynos_panel_init(ctx);
}
EXPORT_SYMBOL(exynos_panel_reset);

static void _exynos_panel_set_vddd_voltage(struct exynos_panel *ctx, bool is_lp)
{
	u32 uv = is_lp ? ctx->vddd_lp_uV : ctx->vddd_normal_uV;

	if (!uv || !ctx->vddd)
		return;
	if (regulator_set_voltage(ctx->vddd, uv, uv))
		dev_err(ctx->dev, "failed to set vddd at %u uV\n", uv);
}

static int _exynos_panel_set_power(struct exynos_panel *ctx, bool on)
{
	int ret;

	if (on) {
		if (ctx->enable_gpio) {
			gpiod_set_value(ctx->enable_gpio, 1);
			usleep_range(10000, 11000);
		}

		if (ctx->vddi) {
			ret = regulator_enable(ctx->vddi);
			if (ret) {
				dev_err(ctx->dev, "vddi enable failed\n");
				return ret;
			}
			usleep_range(5000, 6000);
		}

		if (ctx->vddd) {
			ret = regulator_enable(ctx->vddd);
			if (ret) {
				dev_err(ctx->dev, "vddd enable failed\n");
				return ret;
			}
		}

		if (ctx->vci) {
			ret = regulator_enable(ctx->vci);
			if (ret) {
				dev_err(ctx->dev, "vci enable failed\n");
				return ret;
			}
		}

		if (ctx->vddr_en) {
			ret = regulator_enable(ctx->vddr_en);
			if (ret) {
				dev_err(ctx->dev, "vddr_en enable failed\n");
				return ret;
			}
			usleep_range(2 * 1000, 2 * 1000 + 10);
		}

		if (ctx->vddr) {
			ret = regulator_enable(ctx->vddr);
			if (ret) {
				dev_err(ctx->dev, "vddr enable failed\n");
				return ret;
			}
		}
	} else {
		gpiod_set_value(ctx->reset_gpio, 0);
		if (ctx->enable_gpio)
			gpiod_set_value(ctx->enable_gpio, 0);

		if (ctx->vddr) {
			ret = regulator_disable(ctx->vddr);
			if (ret) {
				dev_err(ctx->dev, "vddr disable failed\n");
				return ret;
			}
		}

		if (ctx->vddr_en) {
			ret = regulator_disable(ctx->vddr_en);
			if (ret) {
				dev_err(ctx->dev, "vddr_en disable failed\n");
				return ret;
			}
		}

		if (ctx->vddd) {
			ret = regulator_disable(ctx->vddd);
			if (ret) {
				dev_err(ctx->dev, "vddd disable failed\n");
				return ret;
			}
		}

		if (ctx->vddi) {
			ret = regulator_disable(ctx->vddi);
			if (ret) {
				dev_err(ctx->dev, "vddi disable failed\n");
				return ret;
			}
		}

		if (ctx->vci > 0) {
			ret = regulator_disable(ctx->vci);
			if (ret) {
				dev_err(ctx->dev, "vci disable failed\n");
				return ret;
			}
		}
	}

	return 0;
}

int exynos_panel_set_power(struct exynos_panel *ctx, bool on)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	int ret;

	if (IS_ENABLED(CONFIG_BOARD_EMULATOR))
		return 0;

	if (funcs && funcs->set_power)
		ret = funcs->set_power(ctx, on);
	else
		ret = _exynos_panel_set_power(ctx, on);

	if (ret) {
		dev_err(ctx->dev, "failed to set power: ret %d \n", ret);
		return ret;
	}

	ctx->bl->props.power = on ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN;

	return 0;
}
EXPORT_SYMBOL(exynos_panel_set_power);

static void exynos_panel_handoff(struct exynos_panel *ctx)
{
	ctx->enabled = gpiod_get_raw_value(ctx->reset_gpio) > 0;
	_exynos_panel_set_vddd_voltage(ctx, false);
	if (ctx->enabled) {
		dev_info(ctx->dev, "panel enabled at boot\n");
		ctx->panel_state = PANEL_STATE_HANDOFF;
		exynos_panel_set_power(ctx, true);
	} else {
		ctx->panel_state = PANEL_STATE_UNINITIALIZED;
		gpiod_direction_output(ctx->reset_gpio, 0);
	}
}

static int exynos_panel_parse_dt(struct exynos_panel *ctx)
{
	int ret = 0;
	u32 orientation = DRM_MODE_PANEL_ORIENTATION_NORMAL;

	if (IS_ERR_OR_NULL(ctx->dev->of_node)) {
		dev_err(ctx->dev, "no device tree information of exynos panel\n");
		return -EINVAL;
	}

	ret = exynos_panel_parse_gpios(ctx);
	if (ret)
		goto err;

	ret = exynos_panel_parse_regulators(ctx);
	if (ret)
		goto err;

	ctx->touch_dev = of_parse_phandle(ctx->dev->of_node, "touch", 0);

	of_property_read_u32(ctx->dev->of_node, "orientation", &orientation);
	if (orientation > DRM_MODE_PANEL_ORIENTATION_RIGHT_UP) {
		dev_warn(ctx->dev, "invalid display orientation %d\n", orientation);
		orientation = DRM_MODE_PANEL_ORIENTATION_NORMAL;
	}
	ctx->orientation = orientation;

err:
	return ret;
}

static void exynos_panel_mode_set_name(struct drm_display_mode *mode)
{
	scnprintf(mode->name, DRM_DISPLAY_MODE_LEN, "%dx%dx%d",
		  mode->hdisplay, mode->vdisplay, drm_mode_vrefresh(mode));
}

int exynos_panel_get_modes(struct drm_panel *panel, struct drm_connector *connector)
{
	struct exynos_panel *ctx =
		container_of(panel, struct exynos_panel, panel);
	struct drm_display_mode *preferred_mode = NULL;
	const struct exynos_panel_mode *current_mode = ctx->current_mode;
	int i;

	dev_dbg(ctx->dev, "%s +\n", __func__);

	for (i = 0; i < ctx->desc->num_modes; i++) {
		const struct exynos_panel_mode *pmode = &ctx->desc->modes[i];
		struct drm_display_mode *mode;

		mode = drm_mode_duplicate(connector->dev, &pmode->mode);
		if (!mode)
			return -ENOMEM;

		if (!mode->name[0])
			exynos_panel_mode_set_name(mode);

		mode->type |= DRM_MODE_TYPE_DRIVER;
		drm_mode_probed_add(connector, mode);

		dev_dbg(ctx->dev, "added display mode: %s\n", mode->name);

		if (!preferred_mode || (mode->type & DRM_MODE_TYPE_PREFERRED)) {
			preferred_mode = mode;
			/* if enabled at boot, assume preferred mode was set */
			if ((ctx->panel_state == PANEL_STATE_HANDOFF) && !current_mode)
				ctx->current_mode = pmode;
		}
	}

	if (preferred_mode) {
		dev_dbg(ctx->dev, "preferred display mode: %s\n", preferred_mode->name);
		preferred_mode->type |= DRM_MODE_TYPE_PREFERRED;
		connector->display_info.width_mm = preferred_mode->width_mm;
		connector->display_info.height_mm = preferred_mode->height_mm;
	}

	dev_dbg(ctx->dev, "%s -\n", __func__);

	return i;
}
EXPORT_SYMBOL(exynos_panel_get_modes);

int exynos_panel_disable(struct drm_panel *panel)
{
	struct exynos_panel *ctx =
		container_of(panel, struct exynos_panel, panel);
	const struct exynos_panel_funcs *exynos_panel_func;

	ctx->enabled = false;
	ctx->hbm_mode = HBM_OFF;
	ctx->dimming_on = false;
	ctx->self_refresh_active = false;
	ctx->panel_idle_vrefresh = 0;
	ctx->current_binned_lp = NULL;
	ctx->cabc_mode = CABC_OFF;
	ctx->current_cabc_mode = CABC_OFF;

	exynos_panel_func = ctx->desc->exynos_panel_func;
	if (exynos_panel_func) {
		if (exynos_panel_func->set_local_hbm_mode) {
			cancel_delayed_work_sync(&ctx->hbm.local_hbm.timeout_work);
			ctx->hbm.local_hbm.state = LOCAL_HBM_DISABLED;
			sysfs_notify(&ctx->bl->dev.kobj, NULL, "local_hbm_mode");
		}
	}

	mutex_lock(&ctx->mode_lock);
	exynos_panel_send_cmd_set(ctx, ctx->desc->off_cmd_set);
	mutex_unlock(&ctx->mode_lock);
	dev_dbg(ctx->dev, "%s\n", __func__);
	return 0;
}
EXPORT_SYMBOL(exynos_panel_disable);

int exynos_panel_unprepare(struct drm_panel *panel)
{
	struct exynos_panel *ctx =
		container_of(panel, struct exynos_panel, panel);

	dev_dbg(ctx->dev, "%s +\n", __func__);
	exynos_panel_set_power(ctx, false);
	dev_dbg(ctx->dev, "%s -\n", __func__);
	return 0;
}
EXPORT_SYMBOL(exynos_panel_unprepare);

int exynos_panel_prepare(struct drm_panel *panel)
{
	struct exynos_panel *ctx =
		container_of(panel, struct exynos_panel, panel);

	dev_dbg(ctx->dev, "%s +\n", __func__);
	exynos_panel_set_power(ctx, true);
	dev_dbg(ctx->dev, "%s -\n", __func__);

	return 0;
}
EXPORT_SYMBOL(exynos_panel_prepare);

void exynos_panel_send_cmd_set_flags(struct exynos_panel *ctx,
				     const struct exynos_dsi_cmd_set *cmd_set, u32 flags)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	const struct exynos_dsi_cmd *c;
	const struct exynos_dsi_cmd *last_cmd = NULL;
	const u32 async_mask = PANEL_CMD_SET_BATCH | PANEL_CMD_SET_QUEUE;
	u16 dsi_flags = 0;

	if (!cmd_set || !cmd_set->num_cmd)
		return;

	/* shouldn't have both queue and batch set together */
	WARN_ON((flags & async_mask) == async_mask);

	if (flags & PANEL_CMD_SET_IGNORE_VBLANK)
		dsi_flags |= EXYNOS_DSI_MSG_IGNORE_VBLANK;

	/* if not batched or queued, all commands should be sent out immediately */
	if (!(flags & async_mask))
		dsi_flags |= MIPI_DSI_MSG_LASTCOMMAND;

	c = &cmd_set->cmds[cmd_set->num_cmd - 1];
	if (!c->panel_rev) {
		last_cmd = c;
	} else {
		for (; c >= cmd_set->cmds; c--) {
			if (c->panel_rev & ctx->panel_rev) {
				last_cmd = c;
				break;
			}
		}
	}

	/* no commands to transfer */
	if (!last_cmd)
		return;

	for (c = cmd_set->cmds; c <= last_cmd; c++) {
		u32 delay_ms = c->delay_ms;

		if (ctx->panel_rev && !(c->panel_rev & ctx->panel_rev))
			continue;

		if ((c == last_cmd) && !(flags & PANEL_CMD_SET_QUEUE))
			dsi_flags |= MIPI_DSI_MSG_LASTCOMMAND;

		exynos_dsi_dcs_write_buffer(dsi, c->cmd, c->cmd_len, dsi_flags);
		if (delay_ms)
			usleep_range(delay_ms * 1000, delay_ms * 1000 + 10);
	}
}
EXPORT_SYMBOL(exynos_panel_send_cmd_set_flags);

void exynos_panel_set_lp_mode(struct exynos_panel *ctx, const struct exynos_panel_mode *pmode)
{
	exynos_panel_send_cmd_set(ctx, ctx->desc->lp_cmd_set);

	dev_info(ctx->dev, "enter %dhz LP mode\n", drm_mode_vrefresh(&pmode->mode));
}
EXPORT_SYMBOL(exynos_panel_set_lp_mode);

void exynos_panel_set_binned_lp(struct exynos_panel *ctx, const u16 brightness)
{
	int i;
	const struct exynos_binned_lp *binned_lp;
	struct backlight_device *bl = ctx->bl;
	bool is_lp_state;
	enum exynos_panel_state panel_state;

	for (i = 0; i < ctx->desc->num_binned_lp; i++) {
		binned_lp = &ctx->desc->binned_lp[i];
		if (brightness <= binned_lp->bl_threshold)
			break;
	}
	if (i == ctx->desc->num_binned_lp)
		return;

	mutex_lock(&ctx->bl_state_lock);
	is_lp_state = is_backlight_lp_state(bl);
	mutex_unlock(&ctx->bl_state_lock);

	mutex_lock(&ctx->lp_state_lock);

	if (is_lp_state && ctx->current_binned_lp &&
	    binned_lp->bl_threshold == ctx->current_binned_lp->bl_threshold) {
		mutex_unlock(&ctx->lp_state_lock);
		return;
	}

	exynos_panel_send_cmd_set(ctx, &binned_lp->cmd_set);

	ctx->current_binned_lp = binned_lp;
	dev_dbg(ctx->dev, "enter lp_%s\n", ctx->current_binned_lp->name);

	mutex_unlock(&ctx->lp_state_lock);

	panel_state = !binned_lp->bl_threshold ? PANEL_STATE_BLANK : PANEL_STATE_LP;
	exynos_panel_set_backlight_state(ctx, panel_state);

	if (bl)
		sysfs_notify(&bl->dev.kobj, NULL, "lp_state");

	if (panel_state == PANEL_STATE_LP)
		exynos_panel_update_te2(ctx);
}
EXPORT_SYMBOL(exynos_panel_set_binned_lp);

int exynos_panel_set_brightness(struct exynos_panel *exynos_panel, u16 br)
{
	u16 brightness;

	if (exynos_panel->current_mode->exynos_mode.is_lp_mode) {
		const struct exynos_panel_funcs *funcs;

		funcs = exynos_panel->desc->exynos_panel_func;
		if (funcs && funcs->set_binned_lp)
			funcs->set_binned_lp(exynos_panel, br);
		return 0;
	}

	brightness = (br & 0xff) << 8 | br >> 8;

	return exynos_dcs_set_brightness(exynos_panel, brightness);
}
EXPORT_SYMBOL(exynos_panel_set_brightness);

static int exynos_get_brightness(struct backlight_device *bl)
{
	return bl->props.brightness;
}

static void exynos_panel_set_cabc(struct exynos_panel *ctx, enum exynos_cabc_mode cabc_mode)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	struct backlight_device *bl = ctx->bl;
	u8 mode;
	bool force_off = (bl->props.brightness <= ctx->desc->min_brightness);

	if (!funcs || !funcs->set_cabc_mode)
		return;

	/* force off will not change the cabc_mode node */
	mode = !force_off ? cabc_mode : CABC_OFF;
	if (ctx->current_cabc_mode != mode) {
		funcs->set_cabc_mode(ctx, mode);
		ctx->current_cabc_mode = mode;
	}
	ctx->cabc_mode = cabc_mode;
	dev_dbg(ctx->dev, "set cabc mode: %d, force_off: %d\n", cabc_mode, force_off);
}

static int exynos_bl_find_range(struct exynos_panel *ctx,
				int brightness, u32 *range)
{
	u32 i;

	if (!ctx->bl_notifier.num_ranges)
		return -EOPNOTSUPP;

	mutex_lock(&ctx->bl_state_lock);

	for (i = 0; i < ctx->bl_notifier.num_ranges; i++) {
		if (brightness <= ctx->bl_notifier.ranges[i]) {
			*range = i;
			mutex_unlock(&ctx->bl_state_lock);

			return 0;
		}
	}

	mutex_unlock(&ctx->bl_state_lock);

	dev_warn(ctx->dev, "failed to find bl range\n");

	return -EINVAL;
}

static int exynos_update_status(struct backlight_device *bl)
{
	struct exynos_panel *ctx = bl_get_data(bl);
	int brightness = bl->props.brightness;
	int min_brightness = ctx->desc->min_brightness ? : 1;
	u32 bl_range = 0;

	if (!is_panel_active(ctx)) {
		dev_dbg(ctx->dev, "panel is not enabled\n");
		return -EPERM;
	}

	/* check if backlight is forced off */
	if (bl->props.power != FB_BLANK_UNBLANK)
		brightness = 0;

	min_brightness =
		ctx->desc->lower_min_brightness ? ctx->desc->lower_min_brightness : min_brightness;
	if (brightness && brightness < min_brightness)
		brightness = min_brightness;

	dev_info(ctx->dev, "req: %d, br: %d\n", bl->props.brightness,
		brightness);

	mutex_lock(&ctx->mode_lock);
	if (ctx->panel.backlight && !ctx->bl_ctrl_dcs) {
		backlight_device_set_brightness(ctx->panel.backlight,
			brightness);
	} else if (ctx->desc->exynos_panel_func) {
		const struct exynos_panel_funcs *funcs =
			ctx->desc->exynos_panel_func;

		if (funcs->set_brightness)
			funcs->set_brightness(ctx, brightness);
	} else {
		exynos_dcs_set_brightness(ctx, brightness);
	}

	if (!ctx->hbm_mode &&
	    exynos_bl_find_range(ctx, brightness, &bl_range) >= 0 &&
	    bl_range != ctx->bl_notifier.current_range) {
		ctx->bl_notifier.current_range = bl_range;

		sysfs_notify(&ctx->bl->dev.kobj, NULL, "brightness");

		dev_dbg(ctx->dev, "bl range is changed to %d\n",
			ctx->bl_notifier.current_range);
	}

	if (ctx->cabc_mode && brightness)
		exynos_panel_set_cabc(ctx, ctx->cabc_mode);
	mutex_unlock(&ctx->mode_lock);
	return 0;
}

static const struct backlight_ops exynos_backlight_ops = {
	.get_brightness = exynos_get_brightness,
	.update_status = exynos_update_status,
};

static ssize_t serial_number_show(struct device *dev,
				  struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	const struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	if (!ctx->initialized)
		return -EPERM;

	if (!strcmp(ctx->panel_id, ""))
		return -EINVAL;

	return snprintf(buf, PAGE_SIZE, "%s\n", ctx->panel_id);
}

static ssize_t panel_extinfo_show(struct device *dev,
				  struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	const struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	if (!ctx->initialized)
		return -EPERM;

	return snprintf(buf, PAGE_SIZE, "%s\n", ctx->panel_extinfo);
}

static ssize_t panel_name_show(struct device *dev,
				  struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	const char *p;

	/* filter priority info in the dsi device name */
	p = strstr(dsi->name, ":");
	if (!p)
		p = dsi->name;
	else
		p++;

	return snprintf(buf, PAGE_SIZE, "%s\n", p);
}

static ssize_t gamma_store(struct device *dev, struct device_attribute *attr,
			   const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	const struct exynos_panel_funcs *funcs;
	size_t len, ret;
	char *input_buf;
	const char *out_buf;

	if (!is_panel_active(ctx))
		return -EPERM;

	funcs = ctx->desc->exynos_panel_func;
	if (!funcs || !funcs->gamma_store)
		return -EOPNOTSUPP;

	if (!strncmp(buf, DEFAULT_GAMMA_STR, strlen(DEFAULT_GAMMA_STR))) {
		if (!funcs->restore_native_gamma)
			return -EOPNOTSUPP;
		else
			ret = funcs->restore_native_gamma(ctx);

		return ret ? : count;
	}

	input_buf = kstrndup(buf, count, GFP_KERNEL);
	if (!input_buf)
		return -ENOMEM;

	len = exynos_panel_parse_byte_buf(input_buf, count, &out_buf);
	kfree(input_buf);
	if (len <= 0)
		return len;

	ret = funcs->gamma_store(ctx, out_buf, len);
	kfree(out_buf);

	return ret ? : count;
}

static ssize_t set_te2_timing(struct exynos_panel *ctx, size_t count,
			      const char *buf, bool lp_mode)
{
	char *buf_dup;
	ssize_t type_len, data_len;
	u32 timing[MAX_TE2_TYPE * 2] = {0};
	const struct exynos_panel_funcs *funcs;

	if (!is_panel_active(ctx))
		return -EPERM;

	funcs = ctx->desc->exynos_panel_func;
	if (!funcs || !funcs->configure_te2_edges || !funcs->update_te2)
		return -EINVAL;

	if (!count)
		return -EINVAL;

	buf_dup = kstrndup(buf, count, GFP_KERNEL);
	if (!buf_dup)
		return -ENOMEM;

	type_len = exynos_get_te2_type_len(ctx, lp_mode);
	data_len = parse_u32_buf(buf_dup, count + 1, timing, type_len * 2);
	if (data_len != type_len * 2) {
		dev_warn(ctx->dev,
			 "invalid number of TE2 %s timing: expected %ld but actual %ld\n",
			 lp_mode ? "LP" : "normal",
			 type_len * 2, data_len);
		kfree(buf_dup);
		return -EINVAL;
	}

	mutex_lock(&ctx->mode_lock);
	funcs->configure_te2_edges(ctx, timing, lp_mode);
	exynos_panel_update_te2(ctx);
	mutex_unlock(&ctx->mode_lock);

	kfree(buf_dup);

	return count;
}

static ssize_t get_te2_timing(struct exynos_panel *ctx, char *buf, bool lp_mode)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	size_t len;

	if (!funcs || !funcs->get_te2_edges)
		return -EPERM;

	mutex_lock(&ctx->mode_lock);
	len = funcs->get_te2_edges(ctx, buf, lp_mode);
	mutex_unlock(&ctx->mode_lock);

	return len;
}

static ssize_t te2_timing_store(struct device *dev,
				struct device_attribute *attr,
				const char *buf, size_t count)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	ssize_t ret;

	if (!is_panel_initialized(ctx))
		return -EAGAIN;

	ret = set_te2_timing(ctx, count, buf, false);
	if (ret < 0)
		dev_err(ctx->dev,
			"failed to set normal mode TE2 timing: ret %ld\n", ret);

	return ret;
}

static ssize_t te2_timing_show(struct device *dev,
			       struct device_attribute *attr, char *buf)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	ssize_t ret;

	if (!is_panel_initialized(ctx))
		return -EAGAIN;

	ret = get_te2_timing(ctx, buf, false);
	if (ret < 0)
		dev_err(ctx->dev,
			"failed to get normal mode TE2 timing: ret %ld\n", ret);

	return ret;
}

static ssize_t te2_lp_timing_store(struct device *dev,
				   struct device_attribute *attr,
				   const char *buf, size_t count)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	ssize_t ret;

	if (!is_panel_initialized(ctx))
		return -EAGAIN;

	ret = set_te2_timing(ctx, count, buf, true);
	if (ret < 0)
		dev_err(ctx->dev,
			"failed to set LP mode TE2 timing: ret %ld\n", ret);

	return ret;
}

static ssize_t te2_lp_timing_show(struct device *dev,
				  struct device_attribute *attr, char *buf)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	ssize_t ret;

	if (!ctx->initialized)
		return -EAGAIN;

	ret = get_te2_timing(ctx, buf, true);
	if (ret < 0)
		dev_err(ctx->dev,
			"failed to get LP mode TE2 timing: ret %ld\n", ret);

	return ret;
}

unsigned int panel_get_idle_time_delta(struct exynos_panel *ctx)
{
	const ktime_t now = ktime_get();
	const enum exynos_panel_idle_mode idle_mode = (ctx->current_mode) ?
					ctx->current_mode->idle_mode : IDLE_MODE_UNSUPPORTED;
	unsigned int delta_ms = UINT_MAX;

	if (idle_mode == IDLE_MODE_ON_INACTIVITY) {
		delta_ms = ktime_ms_delta(now, ctx->last_mode_set_ts);
	} else if (idle_mode == IDLE_MODE_ON_SELF_REFRESH) {
		const ktime_t ts = max3(ctx->last_self_refresh_active_ts,
					ctx->last_mode_set_ts, ctx->last_panel_idle_set_ts);

		delta_ms = ktime_ms_delta(now, ts);
	} else {
		dev_dbg(ctx->dev, "%s: unsupported idle mode %d", __func__, idle_mode);
	}

	return delta_ms;
}
EXPORT_SYMBOL(panel_get_idle_time_delta);

static bool panel_idle_queue_delayed_work(struct exynos_panel *ctx)
{
	const unsigned int delta_ms = panel_get_idle_time_delta(ctx);

	if (delta_ms < ctx->idle_delay_ms) {
		const unsigned int delay_ms = ctx->idle_delay_ms - delta_ms;

		dev_dbg(ctx->dev, "%s: last mode %ums ago, schedule idle in %ums\n",
			__func__, delta_ms, delay_ms);

		mod_delayed_work(system_highpri_wq, &ctx->idle_work,
					msecs_to_jiffies(delay_ms));
		return true;
	}

	return false;
}

static void panel_update_idle_mode_locked(struct exynos_panel *ctx)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;

	WARN_ON(!mutex_is_locked(&ctx->mode_lock));

	if (unlikely(!ctx->current_mode || !funcs))
		return;

	if (!is_panel_active(ctx) || !funcs->set_self_refresh)
		return;

	if (ctx->idle_delay_ms && ctx->self_refresh_active && panel_idle_queue_delayed_work(ctx))
		return;

	if (delayed_work_pending(&ctx->idle_work)) {
		dev_dbg(ctx->dev, "%s: cancelling delayed idle work\n", __func__);
		cancel_delayed_work(&ctx->idle_work);
	}

	if (funcs->set_self_refresh(ctx, ctx->self_refresh_active)) {
		exynos_panel_update_te2(ctx);
		ctx->last_self_refresh_active_ts = ktime_get();
	}
}

static void panel_idle_work(struct work_struct *work)
{
	struct exynos_panel *ctx = container_of(work, struct exynos_panel, idle_work.work);

	dev_dbg(ctx->dev, "%s\n", __func__);

	mutex_lock(&ctx->mode_lock);
	panel_update_idle_mode_locked(ctx);
	mutex_unlock(&ctx->mode_lock);
}

static ssize_t panel_idle_store(struct device *dev, struct device_attribute *attr,
				const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	bool idle_enabled;
	int ret;

	ret = kstrtobool(buf, &idle_enabled);
	if (ret) {
		dev_err(dev, "invalid panel idle value\n");
		return ret;
	}

	mutex_lock(&ctx->mode_lock);
	if (idle_enabled != ctx->panel_idle_enabled) {
		ctx->panel_idle_enabled = idle_enabled;

		if (idle_enabled)
			ctx->last_panel_idle_set_ts = ktime_get();

		panel_update_idle_mode_locked(ctx);
	}
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t panel_idle_show(struct device *dev, struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->panel_idle_enabled);
}

static ssize_t panel_need_handle_idle_exit_store(struct device *dev, struct device_attribute *attr,
				const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	bool idle_handle_exit;
	int ret;

	ret = kstrtobool(buf, &idle_handle_exit);
	if (ret) {
		dev_err(dev, "invalid panel idle handle exit value\n");
		return ret;
	}

	mutex_lock(&ctx->mode_lock);
	ctx->panel_need_handle_idle_exit = idle_handle_exit;
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t panel_need_handle_idle_exit_show(struct device *dev,
				struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->panel_need_handle_idle_exit);
}

static ssize_t min_vrefresh_store(struct device *dev, struct device_attribute *attr,
				const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	int min_vrefresh;
	int ret;

	ret = kstrtoint(buf, 0, &min_vrefresh);
	if (ret) {
		dev_err(dev, "invalid min vrefresh value\n");
		return ret;
	}

	mutex_lock(&ctx->mode_lock);
	ctx->min_vrefresh = min_vrefresh;
	panel_update_idle_mode_locked(ctx);
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t min_vrefresh_show(struct device *dev, struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->min_vrefresh);
}

static ssize_t idle_delay_ms_store(struct device *dev, struct device_attribute *attr,
				const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	u32 idle_delay_ms;
	int ret;

	ret = kstrtou32(buf, 0, &idle_delay_ms);
	if (ret) {
		dev_err(dev, "invalid idle delay ms\n");
		return ret;
	}

	mutex_lock(&ctx->mode_lock);
	ctx->idle_delay_ms = idle_delay_ms;
	panel_update_idle_mode_locked(ctx);
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t idle_delay_ms_show(struct device *dev, struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->idle_delay_ms);
}

static ssize_t force_power_on_store(struct device *dev, struct device_attribute *attr,
				const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	bool force_on;
	int ret;

	ret = kstrtobool(buf, &force_on);
	if (ret) {
		dev_err(dev, "invalid force_power_on value\n");
		return ret;
	}

	drm_modeset_lock(&ctx->bridge.base.lock, NULL);
	if (force_on && ctx->panel_state == PANEL_STATE_OFF) {
		drm_panel_prepare(&ctx->panel);
		ctx->panel_state = PANEL_STATE_BLANK;
	}

	ctx->force_power_on = force_on;
	drm_modeset_unlock(&ctx->bridge.base.lock);

	return count;
}

static ssize_t force_power_on_show(struct device *dev, struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->force_power_on);
}

static ssize_t osc2_clk_khz_store(struct device *dev, struct device_attribute *attr,
				  const char *buf, size_t count)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	unsigned int osc2_clk_khz;
	int ret;

	if (!funcs || !funcs->set_osc2_clk_khz)
		return -EOPNOTSUPP;

	ret = kstrtou32(buf, 0, &osc2_clk_khz);
	if (ret) {
		dev_err(dev, "invalid osc2 clock value\n");
		return ret;
	}

	mutex_lock(&ctx->mode_lock);
	if (osc2_clk_khz != ctx->osc2_clk_khz)
		funcs->set_osc2_clk_khz(ctx, osc2_clk_khz);
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t osc2_clk_khz_show(struct device *dev, struct device_attribute *attr, char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	return scnprintf(buf, PAGE_SIZE, "%u\n", ctx->osc2_clk_khz);
}

static ssize_t available_osc2_clk_khz_show(struct device *dev, struct device_attribute *attr,
					   char *buf)
{
	const struct mipi_dsi_device *dsi = to_mipi_dsi_device(dev);
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	ssize_t len;

	if (!funcs || !funcs->list_osc2_clk_khz)
		return -EPERM;

	len = funcs->list_osc2_clk_khz(ctx, buf);
	if (len < 0)
		dev_err(dev, "failed to list OSC2 clocks (%ld)\n", len);

	return len;
}

static DEVICE_ATTR_RO(serial_number);
static DEVICE_ATTR_RO(panel_extinfo);
static DEVICE_ATTR_RO(panel_name);
static DEVICE_ATTR_WO(gamma);
static DEVICE_ATTR_RW(te2_timing);
static DEVICE_ATTR_RW(te2_lp_timing);
static DEVICE_ATTR_RW(panel_idle);
static DEVICE_ATTR_RW(panel_need_handle_idle_exit);
static DEVICE_ATTR_RW(min_vrefresh);
static DEVICE_ATTR_RW(idle_delay_ms);
static DEVICE_ATTR_RW(force_power_on);
static DEVICE_ATTR_RW(osc2_clk_khz);
static DEVICE_ATTR_RO(available_osc2_clk_khz);

static const struct attribute *panel_attrs[] = {
	&dev_attr_serial_number.attr,
	&dev_attr_panel_extinfo.attr,
	&dev_attr_panel_name.attr,
	&dev_attr_gamma.attr,
	&dev_attr_te2_timing.attr,
	&dev_attr_te2_lp_timing.attr,
	&dev_attr_panel_idle.attr,
	&dev_attr_panel_need_handle_idle_exit.attr,
	&dev_attr_min_vrefresh.attr,
	&dev_attr_idle_delay_ms.attr,
	&dev_attr_force_power_on.attr,
	&dev_attr_osc2_clk_khz.attr,
	&dev_attr_available_osc2_clk_khz.attr,
	NULL
};

static void exynos_panel_connector_print_state(struct drm_printer *p,
					       const struct exynos_drm_connector_state *state)
{
	const struct exynos_drm_connector *exynos_connector =
		to_exynos_connector(state->base.connector);
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);
	const struct exynos_panel_desc *desc = ctx->desc;
	int ret;

	ret = mutex_lock_interruptible(&ctx->mode_lock);
	if (ret)
		return;

	drm_printf(p, "\tpanel_state: %d\n", ctx->panel_state);
	drm_printf(p, "\tidle: %s (%s)\n",
		   ctx->panel_idle_vrefresh ? "active" : "inactive",
		   ctx->panel_idle_enabled ? "enabled" : "disabled");

	if (ctx->current_mode) {
		const struct drm_display_mode *m = &ctx->current_mode->mode;

		drm_printf(p, " \tcurrent mode: %dx%d@%d\n", m->hdisplay,
			   m->vdisplay, drm_mode_vrefresh(m));
	}
	drm_printf(p, "\text_info: %s\n", ctx->panel_extinfo);
	drm_printf(p, "\tluminance: [%u, %u] avg: %u\n",
		   desc->min_luminance, desc->max_luminance,
		   desc->max_avg_luminance);
	drm_printf(p, "\thdr_formats: 0x%x\n", desc->hdr_formats);
	drm_printf(p, "\thbm_mode: %u\n", ctx->hbm_mode);
	drm_printf(p, "\tdimming_on: %s\n", ctx->dimming_on ? "true" : "false");
	drm_printf(p, "\tis_partial: %s\n", desc->is_partial ? "true" : "false");

	mutex_unlock(&ctx->mode_lock);
}

/**
 * is_umode_lp_compatible - check switching between provided modes can be seamless during LP
 * @pmode: initial display mode
 * @umode: target display mode
 *
 * Returns true if the switch to target mode can be seamless during LP
 */
static inline bool is_umode_lp_compatible(const struct exynos_panel_mode *pmode,
					  const struct drm_mode_modeinfo *umode)
{
	return pmode->mode.vdisplay == umode->vdisplay && pmode->mode.hdisplay == umode->hdisplay;
}

static int exynos_panel_get_lp_mode(struct exynos_drm_connector *exynos_conn,
				    const struct exynos_drm_connector_state *exynos_state,
				    uint64_t *val)
{
	const struct drm_connector_state *conn_state = &exynos_state->base;
	const struct drm_crtc_state *crtc_state = conn_state->crtc ? conn_state->crtc->state : NULL;
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_conn);
	struct drm_property_blob *blob = ctx->lp_mode_blob;
	const struct exynos_panel_mode *cur_mode;
	struct drm_mode_modeinfo umode;

	if (crtc_state)
		cur_mode = exynos_panel_get_mode(ctx, &crtc_state->mode);
	else
		cur_mode = READ_ONCE(ctx->current_mode);

	if (unlikely(!ctx->desc->lp_mode))
		return -EINVAL;

	if (blob) {
		if (!cur_mode || is_umode_lp_compatible(cur_mode, blob->data)) {
			dev_dbg(ctx->dev, "%s: returning existing lp mode blob\n", __func__);
			*val = blob->base.id;
			return 0;
		}
		ctx->lp_mode_blob = NULL;
		drm_property_blob_put(blob);
	}

	/* when mode count is 0, assume driver is only providing single LP mode */
	if (ctx->desc->lp_mode_count <= 1 || !cur_mode) {
		dev_dbg(ctx->dev, "%s: only single LP mode available\n", __func__);
		drm_mode_convert_to_umode(&umode, &ctx->desc->lp_mode->mode);
	} else {
		int i;

		for (i = 0; i < ctx->desc->lp_mode_count; i++) {
			const struct exynos_panel_mode *lp_mode = &ctx->desc->lp_mode[i];

			drm_mode_convert_to_umode(&umode, &lp_mode->mode);

			if (is_umode_lp_compatible(cur_mode, &umode)) {
				dev_dbg(ctx->dev, "%s: found lp mode: %s for mode:%s\n", __func__,
					lp_mode->mode.name, cur_mode->mode.name);
				break;
			}
		}

		if (i == ctx->desc->lp_mode_count) {
			dev_warn(ctx->dev, "%s: unable to find compatible LP mode for mode: %s\n",
				 __func__, cur_mode->mode.name);
			return -ENOENT;
		}
	}

	blob = drm_property_create_blob(exynos_conn->base.dev, sizeof(umode), &umode);
	if (IS_ERR(blob))
		return PTR_ERR(blob);

	ctx->lp_mode_blob = blob;
	*val = blob->base.id;

	return 0;
}

static int exynos_panel_connector_get_property(
				   struct exynos_drm_connector *exynos_connector,
				   const struct exynos_drm_connector_state *exynos_state,
				   struct drm_property *property,
				   uint64_t *val)
{
	struct exynos_drm_connector_properties *p =
		exynos_drm_connector_get_properties(exynos_connector);
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);

	if (property == p->brightness_level) {
		*val = exynos_state->brightness_level;
		dev_dbg(ctx->dev, "%s: brt(%llu)\n", __func__, *val);
	} else if (property == p->global_hbm_mode) {
		*val = exynos_state->global_hbm_mode;
		dev_dbg(ctx->dev, "%s: global_hbm_mode(%llu)\n", __func__, *val);
	}  else if (property == p->local_hbm_on) {
		*val = exynos_state->local_hbm_on;
		dev_dbg(ctx->dev, "%s: local_hbm_on(%s)\n", __func__, *val ? "true" : "false");
	} else if (property == p->dimming_on) {
		*val = exynos_state->dimming_on;
		dev_dbg(ctx->dev, "%s: dimming_on(%s)\n", __func__, *val ? "true" : "false");
	} else if (property == p->lp_mode) {
		return exynos_panel_get_lp_mode(exynos_connector, exynos_state, val);
	} else if (property == p->mipi_sync) {
		*val = exynos_state->mipi_sync;
		dev_dbg(ctx->dev, "%s: mipi_sync(0x%llx)\n", __func__, *val);
	} else
		return -EINVAL;

	return 0;
}

static int exynos_panel_connector_set_property(
				   struct exynos_drm_connector *exynos_connector,
				   struct exynos_drm_connector_state *exynos_state,
				   struct drm_property *property,
				   uint64_t val)
{
	struct exynos_drm_connector_properties *p =
		exynos_drm_connector_get_properties(exynos_connector);
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);

	if (property == p->brightness_level) {
		exynos_state->pending_update_flags |= HBM_FLAG_BL_UPDATE;
		exynos_state->brightness_level = val;
		dev_dbg(ctx->dev, "%s: brt(%u)\n", __func__, exynos_state->brightness_level);
	} else if (property == p->global_hbm_mode) {
		exynos_state->pending_update_flags |= HBM_FLAG_GHBM_UPDATE;
		exynos_state->global_hbm_mode = val;
		dev_dbg(ctx->dev, "%s: global_hbm_mode(%u)\n", __func__,
			 exynos_state->global_hbm_mode);
	} else if (property == p->local_hbm_on) {
		exynos_state->pending_update_flags |= HBM_FLAG_LHBM_UPDATE;
		exynos_state->local_hbm_on = val;
		dev_dbg(ctx->dev, "%s: local_hbm_on(%s)\n", __func__,
			 exynos_state->local_hbm_on ? "true" : "false");
	} else if (property == p->dimming_on) {
		exynos_state->pending_update_flags |= HBM_FLAG_DIMMING_UPDATE;
		exynos_state->dimming_on = val;
		dev_dbg(ctx->dev, "%s: dimming_on(%s)\n", __func__,
			 exynos_state->dimming_on ? "true" : "false");
	} else if (property == p->mipi_sync) {
		exynos_state->mipi_sync = val;
		dev_dbg(ctx->dev, "%s: mipi_sync(0x%lx)\n", __func__, exynos_state->mipi_sync);
	} else
		return -EINVAL;

	return 0;
}

static const struct exynos_drm_connector_funcs exynos_panel_connector_funcs = {
	.atomic_print_state = exynos_panel_connector_print_state,
	.atomic_get_property = exynos_panel_connector_get_property,
	.atomic_set_property = exynos_panel_connector_set_property,
};

static void exynos_panel_set_dimming(struct exynos_panel *ctx, bool dimming_on)
{
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;

	if (!funcs || !funcs->set_dimming_on)
		return;

	mutex_lock(&ctx->mode_lock);
	if (dimming_on != ctx->dimming_on) {
		funcs->set_dimming_on(ctx, dimming_on);
		panel_update_idle_mode_locked(ctx);
	}
	mutex_unlock(&ctx->mode_lock);
}

static void exynos_panel_pre_commit_properties(
				struct exynos_panel *ctx,
				struct exynos_drm_connector_state *conn_state)
{
	const struct exynos_panel_funcs *exynos_panel_func = ctx->desc->exynos_panel_func;
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	bool mipi_sync;
	bool ghbm_updated = false;

	if (!conn_state->pending_update_flags)
		return;

	dev_info(ctx->dev, "%s: mipi_sync(0x%lx) pending_update_flags(0x%x)\n", __func__,
		conn_state->mipi_sync, conn_state->pending_update_flags);
	DPU_ATRACE_BEGIN(__func__);
	mipi_sync = conn_state->mipi_sync &
		(MIPI_CMD_SYNC_LHBM | MIPI_CMD_SYNC_GHBM | MIPI_CMD_SYNC_BL);

	if ((conn_state->mipi_sync & (MIPI_CMD_SYNC_LHBM | MIPI_CMD_SYNC_GHBM)) &&
		ctx->current_mode->exynos_mode.is_lp_mode) {
		conn_state->pending_update_flags &=
			~(HBM_FLAG_LHBM_UPDATE | HBM_FLAG_GHBM_UPDATE | HBM_FLAG_BL_UPDATE);
		dev_warn(ctx->dev, "%s: avoid LHBM/GHBM/BL updates during lp mode\n",
			__func__);
	}

	if (mipi_sync) {
		exynos_panel_check_mipi_sync_timing(conn_state->base.crtc,
						    ctx->current_mode, ctx);
		exynos_dsi_dcs_write_buffer_force_batch_begin(dsi);
	}

	if ((conn_state->pending_update_flags & HBM_FLAG_GHBM_UPDATE) &&
		exynos_panel_func && exynos_panel_func->set_hbm_mode &&
		(ctx->hbm_mode != conn_state->global_hbm_mode)) {
		DPU_ATRACE_BEGIN("set_hbm");
		mutex_lock(&ctx->mode_lock);
		exynos_panel_func->set_hbm_mode(ctx, conn_state->global_hbm_mode);
		backlight_state_changed(ctx->bl);
		mutex_unlock(&ctx->mode_lock);
		DPU_ATRACE_END("set_hbm");
		ghbm_updated = true;
	}

	if ((conn_state->pending_update_flags & HBM_FLAG_BL_UPDATE) &&
		(ctx->bl->props.brightness != conn_state->brightness_level)) {
		DPU_ATRACE_BEGIN("set_bl");
		ctx->bl->props.brightness = conn_state->brightness_level;
		backlight_update_status(ctx->bl);
		DPU_ATRACE_END("set_bl");
	}

	if ((conn_state->pending_update_flags & HBM_FLAG_LHBM_UPDATE) && exynos_panel_func &&
	    exynos_panel_func->set_local_hbm_mode) {
		DPU_ATRACE_BEGIN("set_lhbm");
		dev_info(ctx->dev, "%s: set LHBM to %d\n", __func__,
			conn_state->local_hbm_on);
		mutex_lock(&ctx->mode_lock);
		panel_update_local_hbm_locked(ctx, conn_state->local_hbm_on);
		mutex_unlock(&ctx->mode_lock);
		DPU_ATRACE_END("set_lhbm");
	}

	if ((conn_state->pending_update_flags & HBM_FLAG_DIMMING_UPDATE) &&
		exynos_panel_func && exynos_panel_func->set_dimming_on &&
		(ctx->dimming_on != conn_state->dimming_on)) {
		DPU_ATRACE_BEGIN("set_dimming");
		exynos_panel_set_dimming(ctx, conn_state->dimming_on);
		DPU_ATRACE_END("set_dimming");
	}

	if (mipi_sync)
		exynos_dsi_dcs_write_buffer_force_batch_end(dsi);

	if (((MIPI_CMD_SYNC_GHBM | MIPI_CMD_SYNC_BL) & conn_state->mipi_sync)
	    && !(MIPI_CMD_SYNC_LHBM & conn_state->mipi_sync)
	    && ctx->desc->dbv_extra_frame) {
		/**
		 * panel needs one extra VSYNC period to apply GHBM/dbv. The frame
		 * update should be delayed.
		 */
		DPU_ATRACE_BEGIN("dbv_wait");
		if (!drm_crtc_vblank_get(conn_state->base.crtc)) {
			drm_crtc_wait_one_vblank(conn_state->base.crtc);
			drm_crtc_vblank_put(conn_state->base.crtc);
		} else {
			pr_warn("%s failed to get vblank for dbv wait\n", __func__);
		}
		DPU_ATRACE_END("dbv_wait");
	}

	if (ghbm_updated)
		sysfs_notify(&ctx->bl->dev.kobj, NULL, "hbm_mode");

	DPU_ATRACE_END(__func__);
}

static void exynos_panel_connector_atomic_pre_commit(
				struct exynos_drm_connector *exynos_connector,
			    struct exynos_drm_connector_state *exynos_old_state,
			    struct exynos_drm_connector_state *exynos_new_state)
{
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);

	exynos_panel_pre_commit_properties(ctx, exynos_new_state);
}

static void exynos_panel_connector_atomic_commit(
				struct exynos_drm_connector *exynos_connector,
			    struct exynos_drm_connector_state *exynos_old_state,
			    struct exynos_drm_connector_state *exynos_new_state)
{
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);
	const struct exynos_panel_funcs *exynos_panel_func = ctx->desc->exynos_panel_func;

	if (!exynos_panel_func)
		return;

	mutex_lock(&ctx->mode_lock);
	if (exynos_panel_func->commit_done && !ctx->current_mode->exynos_mode.is_lp_mode)
		exynos_panel_func->commit_done(ctx);
	mutex_unlock(&ctx->mode_lock);

	ctx->last_commit_ts = ktime_get();
}

static const struct exynos_drm_connector_helper_funcs exynos_panel_connector_helper_funcs = {
	.atomic_pre_commit = exynos_panel_connector_atomic_pre_commit,
	.atomic_commit = exynos_panel_connector_atomic_commit,
};

static int exynos_drm_connector_modes(struct drm_connector *connector)
{
	struct exynos_drm_connector *exynos_connector = to_exynos_connector(connector);
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);
	int ret;

	ret = drm_panel_get_modes(&ctx->panel, connector);
	if (ret < 0) {
		dev_err(ctx->dev, "failed to get panel display modes\n");
		return ret;
	}

	return ret;
}

static const struct exynos_panel_mode *exynos_panel_get_mode(struct exynos_panel *ctx,
							     const struct drm_display_mode *mode)
{
	const struct exynos_panel_mode *pmode;
	int i;

	for (i = 0; i < ctx->desc->num_modes; i++) {
		pmode = &ctx->desc->modes[i];

		if (drm_mode_equal(&pmode->mode, mode))
			return pmode;
	}

	pmode = ctx->desc->lp_mode;
	if (pmode) {
		const size_t count = ctx->desc->lp_mode_count ? : 1;

		for (i = 0; i < count; i++, pmode++)
			if (drm_mode_equal(&pmode->mode, mode))
				return pmode;
	}

	return NULL;
}

static void exynos_drm_connector_attach_touch(struct exynos_panel *ctx,
					      const struct drm_connector_state *connector_state)
{
	struct drm_encoder *encoder = connector_state->best_encoder;
	struct drm_bridge *bridge;

	if (!encoder) {
		dev_warn(ctx->dev, "%s encoder is null\n", __func__);
		return;
	}

	bridge = of_drm_find_bridge(ctx->touch_dev);
	if (!bridge || bridge->dev)
		return;

	drm_bridge_attach(encoder, bridge, &ctx->bridge, 0);
	dev_info(ctx->dev, "attach bridge %p to encoder %p\n", bridge, encoder);
}

/*
 * Check whether transition to new mode can be done seamlessly without having
 * to turn display off before mode change. This is currently only possible if
 * only clocks/refresh rate is changing
 */
static bool exynos_panel_is_mode_seamless(const struct exynos_panel *ctx,
					  const struct exynos_panel_mode *mode)
{
	const struct exynos_panel_funcs *funcs;

	funcs = ctx->desc->exynos_panel_func;
	if (!funcs || !funcs->is_mode_seamless)
		return false;

	return funcs->is_mode_seamless(ctx, mode);
}

static void exynos_panel_set_partial(struct exynos_display_partial *partial,
			const struct exynos_panel_mode *pmode, bool is_partial)
{
	const struct exynos_display_dsc *dsc = &pmode->exynos_mode.dsc;
	const struct drm_display_mode *mode = &pmode->mode;

	partial->enabled = is_partial;
	if (!partial->enabled)
		return;

	if (dsc->enabled) {
		partial->min_width = DIV_ROUND_UP(mode->hdisplay, dsc->slice_count);
		partial->min_height = dsc->slice_height;
	} else {
		partial->min_width = MIN_WIN_BLOCK_WIDTH;
		partial->min_height = MIN_WIN_BLOCK_HEIGHT;
	}
}

static int exynos_drm_connector_check_mode(struct exynos_panel *ctx,
					   struct drm_connector_state *connector_state,
					   struct drm_crtc_state *crtc_state)
{
	struct exynos_drm_connector_state *exynos_connector_state =
		to_exynos_connector_state(connector_state);
	const struct exynos_panel_mode *pmode =
		exynos_panel_get_mode(ctx, &crtc_state->mode);

	if (!pmode) {
		dev_warn(ctx->dev, "invalid mode %s\n", pmode->mode.name);
		return -EINVAL;
	}

	if (crtc_state->connectors_changed || !is_panel_active(ctx))
		exynos_connector_state->seamless_possible = false;
	else
		exynos_connector_state->seamless_possible =
			exynos_panel_is_mode_seamless(ctx, pmode);

	exynos_connector_state->exynos_mode = pmode->exynos_mode;
	exynos_panel_set_partial(&exynos_connector_state->partial, pmode,
			ctx->desc->is_partial);

	return 0;
}

/*
 * this atomic check is called before adjusted mode is populated, this can be used to check only
 * connector state (without adjusted mode), or to decide if modeset may be required
 */
static int exynos_drm_connector_atomic_check(struct drm_connector *connector,
					     struct drm_atomic_state *state)
{
	struct exynos_drm_connector *exynos_connector = to_exynos_connector(connector);
	struct exynos_panel *ctx = exynos_connector_to_panel(exynos_connector);
	struct drm_connector_state *old_conn_state, *new_conn_state, *conn_state;

	old_conn_state = drm_atomic_get_old_connector_state(state, connector);
	new_conn_state = drm_atomic_get_new_connector_state(state, connector);

	if (new_conn_state->crtc)
		conn_state = new_conn_state;
	else if (old_conn_state->crtc)
		conn_state = old_conn_state;
	else
		return 0; /* connector is/was unused */

	if (ctx->touch_dev)
		exynos_drm_connector_attach_touch(ctx, conn_state);

	return 0;
}

static const struct drm_connector_helper_funcs exynos_connector_helper_funcs = {
	.atomic_check = exynos_drm_connector_atomic_check,
	.get_modes = exynos_drm_connector_modes,
};

#ifdef CONFIG_DEBUG_FS

static u8 panel_get_cmd_type(const struct exynos_dsi_cmd *cmd)
{
	if (cmd->type)
		return cmd->type;

	switch (cmd->cmd_len) {
	case 0:
		return -EINVAL;
	case 1:
		return MIPI_DSI_DCS_SHORT_WRITE;
	case 2:
		return MIPI_DSI_DCS_SHORT_WRITE_PARAM;
	default:
		return MIPI_DSI_DCS_LONG_WRITE;
	}
}

static int panel_cmdset_show(struct seq_file *m, void *data)
{
	const struct exynos_dsi_cmd_set *cmdset = m->private;
	const struct exynos_dsi_cmd *cmd;
	u8 type;
	int i;

	for (i = 0; i < cmdset->num_cmd; i++) {
		cmd = &cmdset->cmds[i];

		type = panel_get_cmd_type(cmd);
		seq_printf(m, "0x%02x ", type);
		seq_hex_dump(m, "\t", DUMP_PREFIX_NONE, 16, 1, cmd->cmd, cmd->cmd_len, false);

		if (cmd->delay_ms)
			seq_printf(m, "wait \t%dms\n", cmd->delay_ms);
	}

	return 0;
}
DEFINE_SHOW_ATTRIBUTE(panel_cmdset);

void exynos_panel_debugfs_create_cmdset(struct exynos_panel *ctx,
					struct dentry *parent,
					const struct exynos_dsi_cmd_set *cmdset,
					const char *name)

{
	if (!cmdset)
		return;

	debugfs_create_file(name, 0600, parent, (void *)cmdset, &panel_cmdset_fops);
}
EXPORT_SYMBOL(exynos_panel_debugfs_create_cmdset);

static int panel_gamma_show(struct seq_file *m, void *data)
{
	struct exynos_panel *ctx = m->private;
	const struct exynos_panel_funcs *funcs;
	const struct drm_display_mode *mode;
	int i;

	funcs = ctx->desc->exynos_panel_func;
	for_each_display_mode(i, mode, ctx) {
		seq_printf(m, "\n=== %dhz Mode Gamma ===\n", drm_mode_vrefresh(mode));
		funcs->print_gamma(m, mode);
	}

	return 0;
}
DEFINE_SHOW_ATTRIBUTE(panel_gamma);

static int panel_debugfs_add(struct exynos_panel *ctx, struct dentry *parent)
{
	const struct exynos_panel_desc *desc = ctx->desc;
	const struct exynos_panel_funcs *funcs = desc->exynos_panel_func;
	struct dentry *root;

	debugfs_create_u32("rev", 0600, parent, &ctx->panel_rev);

	if (!funcs)
		return -EINVAL;

	if (funcs->print_gamma)
		debugfs_create_file("gamma", 0600, parent, ctx, &panel_gamma_fops);

	root = debugfs_create_dir("cmdsets", ctx->debugfs_entry);
	if (!root) {
		dev_err(ctx->dev, "can't create cmdset dir\n");
		return -EFAULT;
	}
	ctx->debugfs_cmdset_entry = root;

	exynos_panel_debugfs_create_cmdset(ctx, root, desc->off_cmd_set, "off");

	if (desc->lp_mode) {
		struct dentry *lpd;
		int i;

		if (desc->binned_lp) {
			lpd = debugfs_create_dir("lp", root);
			if (!lpd) {
				dev_err(ctx->dev, "can't create lp dir\n");
				return -EFAULT;
			}

			for (i = 0; i < desc->num_binned_lp; i++) {
				const struct exynos_binned_lp *b = &desc->binned_lp[i];

				exynos_panel_debugfs_create_cmdset(ctx, lpd, &b->cmd_set, b->name);
			}
		} else {
			lpd = root;
		}
		exynos_panel_debugfs_create_cmdset(ctx, lpd, desc->lp_cmd_set, "lp_entry");
	}

	return 0;
}

static ssize_t exynos_dsi_dcs_transfer(struct mipi_dsi_device *dsi, u8 type,
				     const void *data, size_t len, u16 flags)
{
	const struct mipi_dsi_host_ops *ops = dsi->host->ops;
	struct mipi_dsi_msg msg = {
		.channel = dsi->channel,
		.tx_buf = data,
		.tx_len = len,
		.type = type,
	};

	if (!ops || !ops->transfer)
		return -ENOSYS;

	msg.flags = flags;
	if (dsi->mode_flags & MIPI_DSI_MODE_LPM)
		msg.flags |= MIPI_DSI_MSG_USE_LPM;

	return ops->transfer(dsi->host, &msg);
}

ssize_t exynos_dsi_dcs_write_buffer(struct mipi_dsi_device *dsi,
				  const void *data, size_t len, u16 flags)
{
	u8 type;

	switch (len) {
	case 0:
		/* allow flag only messages to dsim */
		type = 0;
		break;

	case 1:
		type = MIPI_DSI_DCS_SHORT_WRITE;
		break;

	case 2:
		type = MIPI_DSI_DCS_SHORT_WRITE_PARAM;
		break;

	default:
		type = MIPI_DSI_DCS_LONG_WRITE;
		break;
	}

	return exynos_dsi_dcs_transfer(dsi, type, data, len, flags);
}
EXPORT_SYMBOL(exynos_dsi_dcs_write_buffer);

static int exynos_dsi_name_show(struct seq_file *m, void *data)
{
	struct mipi_dsi_device *dsi = m->private;

	seq_puts(m, dsi->name);
	seq_putc(m, '\n');

	return 0;
}
DEFINE_SHOW_ATTRIBUTE(exynos_dsi_name);

static ssize_t parse_byte_buf(u8 *out, size_t len, char *src)
{
	const char *skip = "\n ";
	size_t i = 0;
	int rc = 0;
	char *s;

	while (src && !rc && i < len) {
		s = strsep(&src, skip);
		if (*s != '\0') {
			rc = kstrtou8(s, 16, out + i);
			i++;
		}
	}

	return rc ? : i;
}

static ssize_t exynos_panel_parse_byte_buf(char *input_str, size_t input_len,
					   const char **out_buf)
{
	size_t len = (input_len + 1) / 2;
	size_t rc;
	char *out;

	out = kzalloc(len, GFP_KERNEL);
	if (!out)
		return -ENOMEM;

	rc = parse_byte_buf(out, len, input_str);
	if (rc <= 0) {
		kfree(out);
		return rc;
	}

	*out_buf = out;

	return rc;
}

struct exynos_dsi_reg_data {
	struct mipi_dsi_device *dsi;
	u8 address;
	u8 type;
	u16 flags;
	size_t count;
};

static ssize_t exynos_dsi_payload_write(struct file *file,
			       const char __user *user_buf,
			       size_t count, loff_t *ppos)
{
	struct seq_file *m = file->private_data;
	struct exynos_dsi_reg_data *reg_data = m->private;
	char *buf;
	char *payload;
	size_t len;
	int ret;

	buf = memdup_user_nul(user_buf, count);
	if (IS_ERR(buf))
		return PTR_ERR(buf);

	/* calculate length for worst case (1 digit per byte + whitespace) */
	len = (count + 1) / 2;
	payload = kmalloc(len, GFP_KERNEL);
	if (!payload) {
		kfree(buf);
		return -ENOMEM;
	}

	ret = parse_byte_buf(payload, len, buf);
	if (ret <= 0) {
		ret = -EINVAL;
	} else if (reg_data->type) {
		ret = exynos_dsi_dcs_transfer(reg_data->dsi, reg_data->type,
					    payload, ret, reg_data->flags);
	} else {
		ret = exynos_dsi_dcs_write_buffer(reg_data->dsi, payload, ret,
						reg_data->flags);
	}

	kfree(buf);
	kfree(payload);

	return ret ? : count;
}

static int exynos_dsi_payload_show(struct seq_file *m, void *data)
{
	struct exynos_dsi_reg_data *reg_data = m->private;
	char *buf;
	ssize_t rc;

	if (!reg_data->count)
		return -EINVAL;

	buf = kmalloc(reg_data->count, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	rc = mipi_dsi_dcs_read(reg_data->dsi, reg_data->address, buf,
			       reg_data->count);
	if (rc > 0) {
		seq_hex_dump(m, "", DUMP_PREFIX_NONE, 16, 1, buf, rc, false);
		rc = 0;
	} else if (rc == 0) {
		pr_debug("no response back\n");
	}
	kfree(buf);

	return 0;
}

static int exynos_dsi_payload_open(struct inode *inode, struct file *file)
{
	return single_open(file, exynos_dsi_payload_show, inode->i_private);
}

static const struct file_operations exynos_dsi_payload_fops = {
	.owner		= THIS_MODULE,
	.open		= exynos_dsi_payload_open,
	.write		= exynos_dsi_payload_write,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

static int exynos_reset_panel(struct exynos_panel *ctx)
{
	if (!ctx) {
		pr_debug("reset_panel: exynos_panel not exist\n");
		return -EPERM;
	}

	if (IS_ERR_OR_NULL(ctx->reset_gpio)) {
		pr_debug("reset_panel: reset_gpio is invalid\n");
		return -EPERM;
	}

	gpiod_set_value(ctx->reset_gpio, 0);
	pr_info("reset_panel: pull reset_gpio to low to reset panel\n");

	return 0;
}

static ssize_t exynos_debugfs_reset_panel(struct file *file,
			       const char __user *user_buf,
			       size_t count, loff_t *ppos)
{
	bool reset_panel;
	int ret;
	struct mipi_dsi_device *dsi = file->private_data;
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	if (!is_panel_active(ctx))
		return -EPERM;

	ret = kstrtobool_from_user(user_buf, count, &reset_panel);
	if (ret)
		return ret;

	if (reset_panel) {
		ret = exynos_reset_panel(ctx);
		if (ret) {
			pr_debug("reset_panel: reset panel failed\n");
			return ret;
		}
	}

	return count;
}

static const struct file_operations exynos_reset_panel_fops = {
	.open = simple_open,
	.write = exynos_debugfs_reset_panel,
};

static ssize_t exynos_debugfs_op_hz_write(struct file *file,
			       const char __user *user_buf,
			       size_t count, loff_t *ppos)
{
	uint32_t hz;
	int ret;
	struct seq_file *m = file->private_data;
	struct mipi_dsi_device *dsi = m->private;
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	const struct exynos_panel_funcs *funcs;

	if (!is_panel_active(ctx))
		return -EPERM;

	funcs = ctx->desc->exynos_panel_func;
	if (!count || !funcs || !funcs->set_op_hz)
		return -EINVAL;

	ret = kstrtou32_from_user(user_buf, count, 0, &hz);
	if (ret) {
		dev_err(ctx->dev, "invalid op rate value\n");
		return ret;
	}

	mutex_lock(&ctx->mode_lock);
	ret = funcs->set_op_hz(ctx, hz);
	mutex_unlock(&ctx->mode_lock);
	if (ret) {
		dev_err(ctx->dev, "failed to set op rate: %d Hz\n", hz);
		return ret;
	}

	return count;
}

static int exynos_debugfs_op_hz_show(struct seq_file *m, void *data)
{
	struct mipi_dsi_device *dsi = m->private;
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);
	const struct exynos_panel_funcs *funcs;

	if (!is_panel_active(ctx))
		return -EPERM;

	funcs = ctx->desc->exynos_panel_func;
	if (!funcs || !funcs->set_op_hz)
		return -EINVAL;

	seq_printf(m, "%d\n", ctx->op_hz);
	return 0;
}

static int exynos_debugfs_op_hz_open(struct inode *inode, struct file *file)
{
	return single_open(file, exynos_debugfs_op_hz_show, inode->i_private);
}

static const struct file_operations exynos_op_hz_fops = {
	.owner = THIS_MODULE,
	.open = exynos_debugfs_op_hz_open,
	.write = exynos_debugfs_op_hz_write,
	.read = seq_read,
};

static int exynos_dsi_debugfs_add(struct mipi_dsi_device *dsi,
			 struct dentry *parent)
{
	struct dentry *reg_root;
	struct exynos_dsi_reg_data *reg_data;
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	reg_root = debugfs_create_dir("reg", parent);
	if (!reg_root)
		return -EFAULT;

	reg_data = devm_kzalloc(&dsi->dev, sizeof(*reg_data), GFP_KERNEL);
	if (!reg_data)
		return -ENOMEM;

	reg_data->dsi = dsi;
	reg_data->flags = MIPI_DSI_MSG_LASTCOMMAND;

	debugfs_create_u8("address", 0600, reg_root, &reg_data->address);
	debugfs_create_u8("type", 0600, reg_root, &reg_data->type);
	debugfs_create_size_t("count", 0600, reg_root, &reg_data->count);
	debugfs_create_u16("flags", 0600, reg_root, &reg_data->flags);
	debugfs_create_file("payload", 0600, reg_root, reg_data,
			    &exynos_dsi_payload_fops);

	debugfs_create_file("name", 0600, parent, dsi, &exynos_dsi_name_fops);
	debugfs_create_file("reset_panel",0200, parent, dsi, &exynos_reset_panel_fops);

	if (ctx && ctx->desc->exynos_panel_func &&
		ctx->desc->exynos_panel_func->set_op_hz)
		debugfs_create_file("op_hz",0600, parent, dsi, &exynos_op_hz_fops);

	return 0;
}

static int exynos_debugfs_panel_add(struct exynos_panel *ctx, struct dentry *parent)
{
	struct dentry *root;

	if (!parent)
		return -EINVAL;

	root = debugfs_create_dir("panel", parent);
	if (!root)
		return -EPERM;

	ctx->debugfs_entry = root;

	return 0;
}

static void exynos_debugfs_panel_remove(struct exynos_panel *ctx)
{
	if (!ctx->debugfs_entry)
		return;

	debugfs_remove_recursive(ctx->debugfs_entry);

	ctx->debugfs_entry = NULL;
}
#else
static int panel_debugfs_add(struct exynos_panel *ctx, struct dentry *parent)
{
	return 0;
}

static int exynos_dsi_debugfs_add(struct mipi_dsi_device *dsi,
			 struct dentry *parent)
{
	return 0;
}

static int exynos_debugfs_panel_add(struct exynos_panel *ctx, struct dentry *parent)
{
	return 0;
}

static void exynos_debugfs_panel_remove(struct exynos_panel *ctx)
{
	return;
}
#endif

static ssize_t hbm_mode_store(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	const struct exynos_panel_mode *pmode;
	u32 hbm_mode;
	int ret;

	if (!funcs || !funcs->set_hbm_mode) {
		dev_err(ctx->dev, "HBM is not supported\n");
		return -ENOTSUPP;
	}

	mutex_lock(&ctx->mode_lock);
	pmode = ctx->current_mode;

	if (!is_panel_active(ctx) || !pmode) {
		dev_err(ctx->dev, "panel is not enabled\n");
		ret = -EPERM;
		goto unlock;
	}

	if (pmode->exynos_mode.is_lp_mode) {
		dev_dbg(ctx->dev, "hbm unsupported in LP mode\n");
		ret = -EPERM;
		goto unlock;
	}

	ret = kstrtouint(buf, 0, &hbm_mode);
	if (ret || (hbm_mode >= HBM_STATE_MAX)) {
		dev_err(ctx->dev, "invalid hbm_mode value\n");
		goto unlock;
	}

	if (hbm_mode != ctx->hbm_mode) {
		funcs->set_hbm_mode(ctx, hbm_mode);
		backlight_state_changed(bd);
	}

unlock:
	mutex_unlock(&ctx->mode_lock);

	return ret ? : count;
}

static ssize_t hbm_mode_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);

	return scnprintf(buf, PAGE_SIZE, "%u\n", ctx->hbm_mode);
}

static DEVICE_ATTR_RW(hbm_mode);

static ssize_t cabc_mode_store(struct device *dev, struct device_attribute *attr, const char *buf,
			       size_t count)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);
	u32 cabc_mode;
	int ret;

	if (!is_panel_active(ctx)) {
		dev_err(ctx->dev, "panel is not enabled\n");
		return -EPERM;
	}

	ret = kstrtouint(buf, 0, &cabc_mode);
	if (ret || (cabc_mode > CABC_MOVIE_MODE)) {
		dev_err(ctx->dev, "invalid cabc_mode value");
		return -EINVAL;
	}

	mutex_lock(&ctx->mode_lock);
	exynos_panel_set_cabc(ctx, cabc_mode);
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t cabc_mode_show(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);
	const char *mode;

	switch (ctx->cabc_mode) {
	case CABC_OFF:
		mode = "OFF";
		break;
	case CABC_UI_MODE:
		mode = "UI";
		break;
	case CABC_STILL_MODE:
		mode = "STILL";
		break;
	case CABC_MOVIE_MODE:
		mode = "MOVIE";
		break;
	default:
		dev_err(ctx->dev, "unknown CABC mode : %d\n", ctx->cabc_mode);
		return -EINVAL;
	}

	return scnprintf(buf, PAGE_SIZE, "%s\n", mode);
}

static DEVICE_ATTR_RW(cabc_mode);

static ssize_t dimming_on_store(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);
	bool dimming_on;
	int ret;

	if (!is_panel_active(ctx)) {
		dev_err(ctx->dev, "panel is not enabled\n");
		return -EPERM;
	}

	ret = kstrtobool(buf, &dimming_on);
	if (ret) {
		dev_err(ctx->dev, "invalid dimming_on value\n");
		return ret;
	}

	exynos_panel_set_dimming(ctx, dimming_on);

	return count;
}

static ssize_t dimming_on_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->dimming_on);
}
static DEVICE_ATTR_RW(dimming_on);

static struct drm_crtc *get_exynos_panel_connector_crtc(struct exynos_panel *ctx)
{
	struct drm_mode_config *config;
	struct drm_crtc *crtc = NULL;

	config = &ctx->exynos_connector.base.dev->mode_config;
	drm_modeset_lock(&config->connection_mutex, NULL);
	if (ctx->exynos_connector.base.state)
		crtc = ctx->exynos_connector.base.state->crtc;
	drm_modeset_unlock(&config->connection_mutex);
	return crtc;
}

static ssize_t local_hbm_mode_store(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	bool local_hbm_en;
	int ret;
	struct drm_crtc *crtc = get_exynos_panel_connector_crtc(ctx);

	if (!is_panel_active(ctx)) {
		dev_err(ctx->dev, "panel is not enabled\n");
		return -EPERM;
	}

	if (!funcs || !funcs->set_local_hbm_mode) {
		dev_err(ctx->dev, "Local HBM is not supported\n");
		return -ENOTSUPP;
	}

	ret = kstrtobool(buf, &local_hbm_en);
	if (ret) {
		dev_err(ctx->dev, "invalid local_hbm_mode value\n");
		return ret;
	}

	if (crtc && !drm_crtc_vblank_get(crtc)) {
		struct drm_vblank_crtc vblank = crtc->dev->vblank[crtc->index];
		u32 delay_us = vblank.framedur_ns / 2000;

		drm_crtc_wait_one_vblank(crtc);
		drm_crtc_vblank_put(crtc);
		/* wait for 0.5 frame to send to ensure it is done in one frame */
		usleep_range(delay_us, delay_us + 10);
	}

	dev_info(ctx->dev, "%s: set LHBM to %d\n", __func__, local_hbm_en);
	mutex_lock(&ctx->mode_lock);
	panel_update_local_hbm_locked(ctx, local_hbm_en);
	mutex_unlock(&ctx->mode_lock);

	return count;
}

static ssize_t local_hbm_mode_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->hbm.local_hbm.state);
}
static DEVICE_ATTR_RW(local_hbm_mode);

static ssize_t local_hbm_max_timeout_store(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);
	int ret;

	ret = kstrtou32(buf, 0, &ctx->hbm.local_hbm.max_timeout_ms);
	if (ret) {
		dev_err(ctx->dev, "invalid local_hbm_max_timeout_ms value\n");
		return ret;
	}

	return count;
}

static ssize_t local_hbm_max_timeout_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->hbm.local_hbm.max_timeout_ms);
}

static DEVICE_ATTR_RW(local_hbm_max_timeout);

static ssize_t state_show(struct device *dev,
			  struct device_attribute *attr, char *buf)
{
	struct backlight_device *bl = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bl);
	bool show_mode = true;
	const char *statestr;
	int rc, ret_cnt;

	mutex_lock(&ctx->bl_state_lock);

	if (is_backlight_off_state(bl)) {
		statestr = "Off";
		show_mode = false;
	} else if (is_backlight_lp_state(bl)) {
		statestr = "LP";
	} else if (IS_HBM_ON(ctx->hbm_mode)) {
		statestr = IS_HBM_ON_IRC_OFF(ctx->hbm_mode) ?
				"HBM IRC_OFF" : "HBM";
	} else {
		statestr = "On";
	}

	mutex_unlock(&ctx->bl_state_lock);

	ret_cnt = scnprintf(buf, PAGE_SIZE, "%s\n", statestr);
	rc = ret_cnt;

	if (rc > 0 && show_mode) {
		const struct exynos_panel_mode *pmode;

		mutex_lock(&ctx->mode_lock);
		pmode = ctx->current_mode;
		mutex_unlock(&ctx->mode_lock);
		if (pmode) {
			/* overwrite \n and continue the string */
			const u8 str_len = ret_cnt - 1;

			ret_cnt = scnprintf(buf + str_len, PAGE_SIZE - str_len,
				      ": %dx%d@%d\n",
				      pmode->mode.hdisplay, pmode->mode.vdisplay,
				      exynos_get_actual_vrefresh(ctx));
			if (ret_cnt > 0)
				rc = str_len + ret_cnt;
		}
	}

	dev_dbg(ctx->dev, "%s: %s\n", __func__, rc > 0 ? buf : "");

	return rc;
}

static DEVICE_ATTR_RO(state);

static ssize_t lp_state_show(struct device *dev,
			     struct device_attribute *attr, char *buf)
{
	struct backlight_device *bl = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bl);
	int rc;

	mutex_lock(&ctx->bl_state_lock);

	if (!is_backlight_lp_state(bl)) {
		dev_warn(ctx->dev, "panel is not in LP mode\n");
		mutex_unlock(&ctx->bl_state_lock);
		return -EPERM;
	}

	if (!ctx->current_binned_lp) {
		dev_warn(ctx->dev, "LP state is null\n");
		mutex_unlock(&ctx->bl_state_lock);
		return -EINVAL;
	}

	mutex_lock(&ctx->lp_state_lock);
	rc = scnprintf(buf, PAGE_SIZE, "%s\n", ctx->current_binned_lp->name);
	mutex_unlock(&ctx->lp_state_lock);

	mutex_unlock(&ctx->bl_state_lock);

	dev_dbg(ctx->dev, "%s: %s\n", __func__, buf);

	return rc;
}

static DEVICE_ATTR_RO(lp_state);

static ssize_t te2_state_show(struct device *dev,
			      struct device_attribute *attr, char *buf)
{
	struct backlight_device *bl = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bl);
	const struct exynos_panel_mode *pmode;
	int rc = 0;

	if (!is_panel_active(ctx))
		return -EPERM;

	mutex_lock(&ctx->mode_lock);
	pmode = ctx->current_mode;
	mutex_unlock(&ctx->mode_lock);
	if (pmode) {
		bool fixed = ctx->te2.option == TE2_OPT_FIXED;
		bool lp_mode = pmode->exynos_mode.is_lp_mode;
		int vrefresh;

		if (fixed)
			vrefresh = lp_mode ? FIXED_TE2_VREFRESH_LP : FIXED_TE2_VREFRESH_NORMAL;
		else
			vrefresh = exynos_get_actual_vrefresh(ctx);

		rc = scnprintf(buf, PAGE_SIZE, "%s-te2@%d\n",
			       fixed ? "fixed" : "changeable", vrefresh);
	}

	dev_dbg(ctx->dev, "%s: %s\n", __func__, rc > 0 ? buf : "");

	return rc;
}

static DEVICE_ATTR_RO(te2_state);

static ssize_t dim_brightness_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct backlight_device *bd = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bd);

	return scnprintf(buf, PAGE_SIZE, "%d\n", ctx->desc->lower_min_brightness);
}

static DEVICE_ATTR_RO(dim_brightness);

static int parse_u32_buf(char *src, size_t src_len, u32 *out, size_t out_len)
{
	int rc = 0, cnt = 0;
	char *str;
	const char *delim = " ";

	if (!src || !src_len || !out || !out_len)
		return -EINVAL;

	/* src_len is the length of src including null character '\0' */
	if (strnlen(src, src_len) == src_len)
		return -EINVAL;

	for (str = strsep(&src, delim); str != NULL; str = strsep(&src, delim)) {
		rc = kstrtou32(str, 0, out + cnt);
		if (rc)
			return -EINVAL;

		cnt++;

		if (out_len == cnt)
			break;
	}

	return cnt;
}

static ssize_t als_table_store(struct device *dev,
			       struct device_attribute *attr,
			       const char *buf, size_t count)
{
	struct backlight_device *bl = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bl);
	ssize_t bl_num_ranges;
	char *buf_dup;
	u32 ranges[MAX_BL_RANGES] = {0};
	u32 i;

	if (count == 0)
		return -EINVAL;

	buf_dup = kstrndup(buf, count, GFP_KERNEL);
	if (!buf_dup)
		return -ENOMEM;

	if (strlen(buf_dup) != count) {
		kfree(buf_dup);
		return -EINVAL;
	}

	bl_num_ranges = parse_u32_buf(buf_dup, count + 1,
				      ranges, MAX_BL_RANGES);
	if (bl_num_ranges < 0 || bl_num_ranges > MAX_BL_RANGES) {
		dev_warn(ctx->dev, "exceed max number of bl range\n");
		kfree(buf_dup);
		return -EINVAL;
	}

	mutex_lock(&ctx->bl_state_lock);

	ctx->bl_notifier.num_ranges = bl_num_ranges;
	for (i = 0; i < ctx->bl_notifier.num_ranges; i++)
		ctx->bl_notifier.ranges[i] = ranges[i];

	mutex_unlock(&ctx->bl_state_lock);

	kfree(buf_dup);

	return count;
}

static ssize_t als_table_show(struct device *dev,
			      struct device_attribute *attr, char *buf)
{
	struct backlight_device *bl = to_backlight_device(dev);
	struct exynos_panel *ctx = bl_get_data(bl);
	ssize_t rc = 0;
	size_t len = 0;
	u32 i = 0;

	mutex_lock(&ctx->bl_state_lock);

	for (i = 0; i < ctx->bl_notifier.num_ranges; i++) {
		rc = scnprintf(buf + len, PAGE_SIZE - len,
			       "%u ", ctx->bl_notifier.ranges[i]);
		if (rc < 0) {
			mutex_unlock(&ctx->bl_state_lock);
			return -EINVAL;
		}

		len += rc;
	}

	mutex_unlock(&ctx->bl_state_lock);

	len += scnprintf(buf + len, PAGE_SIZE - len, "\n");

	return len;
}

static DEVICE_ATTR_RW(als_table);

static struct attribute *bl_device_attrs[] = {
	&dev_attr_hbm_mode.attr,
	&dev_attr_dimming_on.attr,
	&dev_attr_local_hbm_mode.attr,
	&dev_attr_local_hbm_max_timeout.attr,
	&dev_attr_dim_brightness.attr,
	&dev_attr_state.attr,
	&dev_attr_lp_state.attr,
	&dev_attr_te2_state.attr,
	&dev_attr_als_table.attr,
	NULL,
};
ATTRIBUTE_GROUPS(bl_device);

static int exynos_panel_attach_brightness_capability(struct exynos_drm_connector *exynos_conn,
				const struct brightness_capability *brt_capability)
{
	struct exynos_drm_connector_properties *p =
		exynos_drm_connector_get_properties(exynos_conn);
	struct drm_property_blob *blob;

	blob = drm_property_create_blob(exynos_conn->base.dev,
				 sizeof(struct brightness_capability),
				 brt_capability);
	if (IS_ERR(blob))
		return PTR_ERR(blob);
	drm_object_attach_property(&exynos_conn->base.base, p->brightness_capability, blob->base.id);

	return 0;
}

static unsigned long get_backlight_state_from_panel(struct backlight_device *bl,
					enum exynos_panel_state panel_state)
{
	unsigned long state = bl->props.state;

	switch (panel_state) {
	case PANEL_STATE_NORMAL:
		state &= ~(BL_STATE_STANDBY | BL_STATE_LP);
		break;
	case PANEL_STATE_LP:
		state &= ~(BL_STATE_STANDBY);
		state |= BL_STATE_LP;
		break;
	case PANEL_STATE_MODESET: /* no change */
		break;
	case PANEL_STATE_OFF:
	case PANEL_STATE_BLANK:
	default:
		state &= ~(BL_STATE_LP);
		state |= BL_STATE_STANDBY;
		break;
	}

	return state;
}

static void exynos_panel_set_backlight_state(struct exynos_panel *ctx,
					enum exynos_panel_state panel_state)
{
	struct backlight_device *bl = ctx->bl;
	unsigned long state;
	bool state_changed = false;

	if (!bl)
		return;

	mutex_lock(&ctx->bl_state_lock);

	state = get_backlight_state_from_panel(bl, panel_state);
	if (state != bl->props.state) {
		bl->props.state = state;
		state_changed = true;
	}

	mutex_unlock(&ctx->bl_state_lock);

	if (state_changed) {
		backlight_state_changed(bl);
		dev_info(ctx->dev, "%s: panel:%d, bl:0x%x\n", __func__,
			 panel_state, bl->props.state);
	}
}

static int exynos_panel_attach_properties(struct exynos_panel *ctx)
{
	struct exynos_drm_connector_properties *p =
		exynos_drm_connector_get_properties(&ctx->exynos_connector);
	struct drm_mode_object *obj = &ctx->exynos_connector.base.base;
	const struct exynos_panel_desc *desc = ctx->desc;
	int ret = 0;

	if (!p || !desc)
		return -ENOENT;

	drm_object_attach_property(obj, p->min_luminance, desc->min_luminance);
	drm_object_attach_property(obj, p->max_luminance, desc->max_luminance);
	drm_object_attach_property(obj, p->max_avg_luminance, desc->max_avg_luminance);
	drm_object_attach_property(obj, p->hdr_formats, desc->hdr_formats);
	drm_object_attach_property(obj, p->brightness_level, 0);
	drm_object_attach_property(obj, p->global_hbm_mode, 0);
	drm_object_attach_property(obj, p->local_hbm_on, 0);
	drm_object_attach_property(obj, p->dimming_on, 0);
	drm_object_attach_property(obj, p->mipi_sync, 0);
	drm_object_attach_property(obj, p->is_partial, desc->is_partial);
	drm_object_attach_property(obj, p->panel_idle_support, desc->is_panel_idle_supported);
	drm_object_attach_property(obj, p->panel_orientation, ctx->orientation);
	drm_object_attach_property(obj, p->vrr_switch_duration, desc->vrr_switch_duration);

	if (desc->brt_capability) {
		ret = exynos_panel_attach_brightness_capability(&ctx->exynos_connector,
				desc->brt_capability);
		if (ret)
			dev_err(ctx->dev, "Failed to attach brightness capability (%d)\n", ret);
	}

	if (desc->lp_mode)
		drm_object_attach_property(obj, p->lp_mode, 0);

	return ret;
}

static const char *exynos_panel_get_sysfs_name(struct exynos_panel *ctx)
{
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	const char *p = !IS_ERR(dsi) ? dsi->name : NULL;

	if (p == NULL || p[1] != ':' || p[0] == '0')
		return "primary-panel";
	if (p[0] == '1')
		return "secondary-panel";

	dev_err(ctx->dev, "unsupported dsi device name %s\n", dsi->name);
	return "primary-panel";
}

static int exynos_panel_bridge_attach(struct drm_bridge *bridge,
				      enum drm_bridge_attach_flags flags)
{
	struct drm_device *dev = bridge->dev;
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);
	struct drm_connector *connector = &ctx->exynos_connector.base;
	const char *sysfs_name = exynos_panel_get_sysfs_name(ctx);
	int ret;

	ret = exynos_drm_connector_init(dev, &ctx->exynos_connector,
					&exynos_panel_connector_funcs,
					&exynos_panel_connector_helper_funcs,
					DRM_MODE_CONNECTOR_DSI);
	if (ret) {
		dev_err(ctx->dev, "failed to initialize connector with drm\n");
		return ret;
	}

	ret = exynos_panel_attach_properties(ctx);
	if (ret) {
		dev_err(ctx->dev, "failed to attach connector properties\n");
		return ret;
	}

	drm_connector_helper_add(connector, &exynos_connector_helper_funcs);

	drm_connector_register(connector);

	drm_connector_attach_encoder(connector, bridge->encoder);
	connector->funcs->reset(connector);
	connector->status = connector_status_connected;
	connector->state->self_refresh_aware = true;
	if (ctx->desc->exynos_panel_func && ctx->desc->exynos_panel_func->commit_done)
		ctx->exynos_connector.needs_commit = true;

	ret = sysfs_create_link(&connector->kdev->kobj, &ctx->dev->kobj,
				"panel");
	if (ret)
		dev_warn(ctx->dev, "unable to link panel sysfs (%d)\n", ret);

	exynos_debugfs_panel_add(ctx, connector->debugfs_entry);
	exynos_dsi_debugfs_add(to_mipi_dsi_device(ctx->dev), ctx->debugfs_entry);
	panel_debugfs_add(ctx, ctx->debugfs_entry);

	drm_kms_helper_hotplug_event(connector->dev);


	ret = sysfs_create_link(&bridge->dev->dev->kobj, &ctx->dev->kobj, sysfs_name);
	if (ret)
		dev_warn(ctx->dev, "unable to link %s sysfs (%d)\n", sysfs_name, ret);
	else
		dev_dbg(ctx->dev, "succeed to link %s sysfs\n", sysfs_name);

	return 0;
}

static void exynos_panel_bridge_detach(struct drm_bridge *bridge)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);
	struct drm_connector *connector = &ctx->exynos_connector.base;
	const char *sysfs_name = exynos_panel_get_sysfs_name(ctx);

	sysfs_remove_link(&bridge->dev->dev->kobj, sysfs_name);

	exynos_debugfs_panel_remove(ctx);
	sysfs_remove_link(&connector->kdev->kobj, "panel");
	drm_connector_unregister(connector);
	drm_connector_cleanup(&ctx->exynos_connector.base);
}

static void exynos_panel_bridge_enable(struct drm_bridge *bridge,
				       struct drm_bridge_state *old_bridge_state)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);
	bool need_update_backlight = false;
	bool is_active;
	const bool is_lp_mode = ctx->current_mode &&
				ctx->current_mode->exynos_mode.is_lp_mode;

	mutex_lock(&ctx->mode_lock);
	if (ctx->panel_state == PANEL_STATE_HANDOFF) {
		is_active = !exynos_panel_init(ctx);
	} else if (ctx->panel_state == PANEL_STATE_HANDOFF_MODESET) {
		if (!exynos_panel_init(ctx)) {
			ctx->panel_state = PANEL_STATE_MODESET;
			mutex_unlock(&ctx->mode_lock);
			drm_panel_disable(&ctx->panel);
			mutex_lock(&ctx->mode_lock);
		}
		is_active = false;
	} else {
		is_active = is_panel_active(ctx);
	}

	/* avoid turning on panel again if already enabled (ex. while booting or self refresh) */
	if (!is_active) {
		drm_panel_enable(&ctx->panel);
		need_update_backlight = true;
	}
	ctx->panel_state = is_lp_mode ? PANEL_STATE_LP : PANEL_STATE_NORMAL;

	if (ctx->self_refresh_active) {
		dev_dbg(ctx->dev, "self refresh state : %s\n", __func__);

		ctx->self_refresh_active = false;
		panel_update_idle_mode_locked(ctx);
	} else {
		exynos_panel_set_backlight_state(ctx, ctx->panel_state);

		/* For the case of OFF->AOD, TE2 will be updated in backlight_update_status */
		if (ctx->panel_state == PANEL_STATE_NORMAL)
			exynos_panel_update_te2(ctx);

		if (bridge->encoder) {
			struct dsim_device *dsim = encoder_to_dsim(bridge->encoder);

			/* Enable error flag detection for the primary dsi */
			if (dsim->irq_err_fg >= 0)
				enable_irq(dsim->irq_err_fg);
		}
	}
	mutex_unlock(&ctx->mode_lock);

	if (need_update_backlight && ctx->bl)
		backlight_update_status(ctx->bl);
}

/*
 * this atomic check is called after adjusted mode is populated, so it's safe to modify
 * adjusted_mode if needed at this point
 */
static int exynos_panel_bridge_atomic_check(struct drm_bridge *bridge,
					    struct drm_bridge_state *bridge_state,
					    struct drm_crtc_state *new_crtc_state,
					    struct drm_connector_state *conn_state)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);
	struct drm_atomic_state *state = new_crtc_state->state;
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	int ret;

	if (unlikely(!new_crtc_state))
		return 0;

	if (funcs && funcs->atomic_check) {
		ret = funcs->atomic_check(ctx, state);
		if (ret)
			return ret;
	}

	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
		return 0;

	if (ctx->panel_state == PANEL_STATE_HANDOFF) {
		struct drm_crtc_state *old_crtc_state =
			drm_atomic_get_old_crtc_state(state, new_crtc_state->crtc);

		if (!old_crtc_state->enable)
			old_crtc_state->self_refresh_active = true;
	}

	return exynos_drm_connector_check_mode(ctx, conn_state, new_crtc_state);
}

static void exynos_panel_bridge_pre_enable(struct drm_bridge *bridge,
					   struct drm_bridge_state *old_bridge_state)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);

	if (ctx->panel_state == PANEL_STATE_BLANK) {
		const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;

		if (funcs && funcs->panel_reset)
			funcs->panel_reset(ctx);
	} else if (!is_panel_enabled(ctx)) {
		drm_panel_prepare(&ctx->panel);
	}
}

static void exynos_panel_bridge_disable(struct drm_bridge *bridge,
					struct drm_bridge_state *old_bridge_state)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);
	const struct drm_connector_state *conn_state = ctx->exynos_connector.base.state;
	struct exynos_drm_connector_state *exynos_conn_state =
		to_exynos_connector_state(conn_state);
	struct drm_crtc_state *crtc_state = !conn_state->crtc ? NULL : conn_state->crtc->state;
	const bool self_refresh_active = crtc_state && crtc_state->self_refresh_active;

	if (self_refresh_active && !exynos_conn_state->blanked_mode) {
		mutex_lock(&ctx->mode_lock);
		dev_dbg(ctx->dev, "self refresh state : %s\n", __func__);

		ctx->self_refresh_active = true;
		panel_update_idle_mode_locked(ctx);
		mutex_unlock(&ctx->mode_lock);
	} else {
		if (bridge->encoder) {
			struct dsim_device *dsim = encoder_to_dsim(bridge->encoder);

			if (dsim->irq_err_fg >= 0)
				disable_irq_nosync(dsim->irq_err_fg);
		}

		if (exynos_conn_state->blanked_mode) {
			/* blanked mode takes precedence over normal modeset */
			ctx->panel_state = PANEL_STATE_BLANK;
		} else if (crtc_state && crtc_state->mode_changed &&
		    drm_atomic_crtc_effectively_active(crtc_state)) {
			if (ctx->desc->delay_dsc_reg_init_us) {
				struct exynos_display_mode *exynos_mode =
							&exynos_conn_state->exynos_mode;

				exynos_mode->dsc.delay_reg_init_us =
							ctx->desc->delay_dsc_reg_init_us;
			}

			ctx->panel_state = PANEL_STATE_MODESET;
		} else if (ctx->force_power_on) {
			/* force blank state instead of power off */
			ctx->panel_state = PANEL_STATE_BLANK;
		} else {
			ctx->panel_state = PANEL_STATE_OFF;
		}

		drm_panel_disable(&ctx->panel);
	}
}

static void exynos_panel_bridge_post_disable(struct drm_bridge *bridge,
					     struct drm_bridge_state *old_bridge_state)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);

	/* fully power off only if panel is in full off mode */
	if (!is_panel_enabled(ctx))
		drm_panel_unprepare(&ctx->panel);

	exynos_panel_set_backlight_state(ctx, ctx->panel_state);
}

/* Get the VSYNC start time within a TE period */
static u64 exynos_panel_vsync_start_time_us(u32 te_us, u32 te_period_us)
{
	/* Approximate the VSYNC start time with TE falling edge. */
	if (te_us > 0 && te_us < te_period_us)
		return te_us * 105 / 100; /* add 5% for variation */

	/* Approximate the TE falling edge with 55% TE width */
	return te_period_us * 55 / 100;
}

/* avoid accumulate te varaince cause predicted value is not accurate enough */
#define ACCEPTABLE_TE_PERIOD_DETLA_NS	(3 * NSEC_PER_SEC)
static ktime_t exynos_panel_te_ts_prediction(struct exynos_panel *ctx, ktime_t last_te,
					     s64 since_last_te_us, u32 te_period_us)
{
	const struct exynos_panel_desc *desc = ctx->desc;
	s64 rr_switch_delta_us;
	u32 te_period_before_rr_switch_us;
	u32 rr_switch_applied_duration;
	s64 te_period_delta_ns;

	if (!desc || last_te == 0)
		return 0;

	rr_switch_delta_us = ktime_us_delta(last_te, ctx->last_rr_switch_ts);
	te_period_before_rr_switch_us = ctx->last_rr != 0 ? USEC_PER_SEC / ctx->last_rr : 0;

	if (ctx->last_rr_switch_ts == ctx->last_lp_exit_ts) {
		/* new refresh rate should take effect at first vsync after exiting AOD mode */
		rr_switch_applied_duration = 0;
	} else {
		/* If vrr_switch_duration is not set that mean we don't know the new refresh rate
		 * take effect timing. It may take effect at first or second vsync after sending
		 * rr switch commands.
		 */
		rr_switch_applied_duration = desc->vrr_switch_duration != 0 ?
						(desc->vrr_switch_duration - 1) : 1;
	}

	if (rr_switch_delta_us < 0 && te_period_before_rr_switch_us != 0) {
		ktime_t first_te_after_rr_switch;

		te_period_delta_ns = ((-rr_switch_delta_us / te_period_before_rr_switch_us) + 1) *
					te_period_before_rr_switch_us * NSEC_PER_USEC;

		if (te_period_delta_ns < ACCEPTABLE_TE_PERIOD_DETLA_NS) {
			first_te_after_rr_switch = last_te + te_period_delta_ns;
			rr_switch_delta_us =
				ktime_us_delta(first_te_after_rr_switch, ctx->last_rr_switch_ts);
		}
	}

	if (rr_switch_delta_us > (rr_switch_applied_duration * te_period_before_rr_switch_us)) {
		te_period_delta_ns =
			(since_last_te_us / te_period_us) * te_period_us * NSEC_PER_USEC;

		if (te_period_delta_ns < ACCEPTABLE_TE_PERIOD_DETLA_NS)
			return (last_te + te_period_delta_ns);
	}

	return 0;
}

static void exynos_panel_check_mipi_sync_timing(struct drm_crtc *crtc,
						const struct exynos_panel_mode *current_mode,
						struct exynos_panel *ctx)
{
	u32 te_period_us;
	int retry;
	u64 left, right;
	bool vblank_taken = false;
	bool rr_applied = false;

	if (WARN_ON(!current_mode))
		return;

	DPU_ATRACE_BEGIN("mipi_time_window");
	te_period_us = USEC_PER_SEC / drm_mode_vrefresh(&current_mode->mode);
	pr_debug("%s: check mode_set timing enter. te %d\n", __func__, te_period_us);

	/*
	 * Safe time window to send RR (refresh rate) command illustrated below. RR switch
	 * and scanout need to happen in the same VSYNC period because the frame content might
	 * be adjusted specific to this RR.
	 *
	 * An estimation is [55% * TE_duration, TE_duration - 1ms] before driver has the
	 * accurate TE pulse width (VSYNC rising is a bit ahead of TE falling edge).
	 *
	 *         -->|     |<-- safe time window to send RR
	 *
	 *        +----+     +----+     +-+
	 *        |    |     |    |     | |
	 * TE   --+    +-----+    +-----+ +---
	 *               RR  SCANOUT
	 *
	 *            |          |       |
	 *            |          |       |
	 * VSYNC------+----------+-------+----
	 *            RR1        RR2
	 */
	left = exynos_panel_vsync_start_time_us(current_mode->exynos_mode.te_usec, te_period_us);
	right = te_period_us - USEC_PER_MSEC;
	/* check for next TE every 1ms */
	retry = te_period_us / USEC_PER_MSEC + 1;

	do {
		ktime_t last_te = 0, now, predicted_te;
		s64 since_last_te_us;
		s64 rr_switch_delta_us;
		s64 te_period_before_rr_switch_us;

		drm_crtc_vblank_count_and_time(crtc, &last_te);
		now = ktime_get();
		since_last_te_us = ktime_us_delta(now, last_te);
		/* Need a vblank as a reference point */
		predicted_te =
			exynos_panel_te_ts_prediction(ctx, last_te, since_last_te_us, te_period_us);
		if (predicted_te) {
			DPU_ATRACE_BEGIN("predicted_te");
			last_te = predicted_te;
			since_last_te_us = ktime_us_delta(now, last_te);
			rr_applied = true;
			DPU_ATRACE_END("predicted_te");
		} else if (since_last_te_us > te_period_us) {
			DPU_ATRACE_BEGIN("time_window_wait_crtc");
			if (vblank_taken || !drm_crtc_vblank_get(crtc)) {
				drm_crtc_wait_one_vblank(crtc);
				vblank_taken = true;
			} else {
				pr_warn("%s failed to get vblank for ref point.\n", __func__);
			}
			DPU_ATRACE_END("time_window_wait_crtc");
			continue;
		}

		/**
		 * If a refresh rate switch happens right before last_te. last_te is not reliable
		 * because it could be for the new refresh rate or the old refresh rate.
		 * Wait another vblank in this case.
		 */
		rr_switch_delta_us = ktime_us_delta(last_te, ctx->last_rr_switch_ts);
		te_period_before_rr_switch_us = ctx->last_rr != 0 ? USEC_PER_SEC / ctx->last_rr : 0;
		if (rr_switch_delta_us > 0 && rr_switch_delta_us < te_period_before_rr_switch_us &&
				!rr_applied) {
			DPU_ATRACE_BEGIN("time_window_wait_crtc2");
			if (vblank_taken || !drm_crtc_vblank_get(crtc)) {
				drm_crtc_wait_one_vblank(crtc);
				vblank_taken = true;
			} else {
				pr_warn("%s failed to get vblank for rr wait\n", __func__);
			}
			DPU_ATRACE_END("time_window_wait_crtc2");
			continue;
		}

		if (since_last_te_us <= right) {
			if (since_last_te_us < left) {
				u32 delay_us = left - since_last_te_us;

				DPU_ATRACE_BEGIN("time_window_wait");
				usleep_range(delay_us, delay_us + 100);
				DPU_ATRACE_END("time_window_wait");
				/*
				 * if a mode switch happens, a TE signal might
				 * happen during the sleep. need to re-sync
				 */
				continue;
			}
			break;
		}
		/* retry in 1ms */
		usleep_range(USEC_PER_MSEC, USEC_PER_MSEC + 100);
	} while (--retry > 0);

	if (vblank_taken)
		drm_crtc_vblank_put(crtc);

	pr_debug("%s: check mode_set timing exit.\n", __func__);
	DPU_ATRACE_END("mipi_time_window");
}

static bool panel_update_local_hbm_notimeout(struct exynos_panel *ctx, bool enable)
{
	const struct exynos_panel_mode *pmode;
	struct local_hbm *lhbm = &ctx->hbm.local_hbm;

	if (!ctx->desc->exynos_panel_func->set_local_hbm_mode)
		return false;

	if (!is_local_hbm_disabled(ctx) == enable)
		return false;

	pmode = ctx->current_mode;
	if (unlikely(pmode == NULL)) {
		dev_err(ctx->dev, "%s: unknown current mode\n", __func__);
		return false;
	}

	if (enable && !ctx->desc->no_lhbm_rr_constraints) {
		const int vrefresh = drm_mode_vrefresh(&pmode->mode);
		/* only allow to turn on LHBM at peak refresh rate to comply with HW constraint */
		if (ctx->peak_vrefresh && vrefresh != ctx->peak_vrefresh) {
			dev_err(ctx->dev, "unexpected mode `%s` while enabling LHBM, give up\n",
				pmode->mode.name);
			return false;
		}
	}

	if (is_local_hbm_post_enabling_supported(ctx)) {
		if (enable) {
			lhbm->en_cmd_ts = ktime_get();
			kthread_queue_work(&lhbm->worker, &lhbm->post_work);
		} else {
			kthread_cancel_work_sync(&lhbm->post_work);
		}
	}

	DPU_ATRACE_BEGIN(__func__);
	lhbm->state = enable ? (is_local_hbm_post_enabling_supported(ctx) ? LOCAL_HBM_ENABLING :
									    LOCAL_HBM_ENABLED) :
			       LOCAL_HBM_DISABLED;
	ctx->desc->exynos_panel_func->set_local_hbm_mode(ctx, enable);
	sysfs_notify(&ctx->bl->dev.kobj, NULL, "local_hbm_mode");
	DPU_ATRACE_END(__func__);

	return true;
}

static void panel_update_local_hbm_locked(struct exynos_panel *ctx, bool enable)
{
	if (enable) {
		/* reset timeout timer if re-enabling lhbm */
		if (!is_local_hbm_disabled(ctx)) {
			mod_delayed_work(ctx->hbm.wq, &ctx->hbm.local_hbm.timeout_work,
					 msecs_to_jiffies(ctx->hbm.local_hbm.max_timeout_ms));
			return;
		}

		if (!panel_update_local_hbm_notimeout(ctx, true))
			return;
		queue_delayed_work(ctx->hbm.wq, &ctx->hbm.local_hbm.timeout_work,
				   msecs_to_jiffies(ctx->hbm.local_hbm.max_timeout_ms));
	} else {
		cancel_delayed_work(&ctx->hbm.local_hbm.timeout_work);
		panel_update_local_hbm_notimeout(ctx, false);
	}
}

static void exynos_panel_bridge_mode_set(struct drm_bridge *bridge,
				  const struct drm_display_mode *mode,
				  const struct drm_display_mode *adjusted_mode)
{
	struct exynos_panel *ctx = bridge_to_exynos_panel(bridge);
	struct mipi_dsi_device *dsi = to_mipi_dsi_device(ctx->dev);
	struct drm_connector_state *connector_state = ctx->exynos_connector.base.state;
	struct drm_crtc *crtc = connector_state->crtc;
	struct exynos_drm_connector_state *exynos_connector_state =
				      to_exynos_connector_state(connector_state);
	const struct exynos_panel_mode *pmode = exynos_panel_get_mode(ctx, mode);
	const struct exynos_panel_funcs *funcs = ctx->desc->exynos_panel_func;
	const struct exynos_panel_mode *old_mode;
	bool need_update_backlight = false;
	bool come_out_lp_mode = false;

	if (WARN_ON(!pmode))
		return;

	mutex_lock(&ctx->mode_lock);
	old_mode = ctx->current_mode;

	if (old_mode == pmode) {
		mutex_unlock(&ctx->mode_lock);
		return;
	}

	if (ctx->panel_state == PANEL_STATE_HANDOFF) {
		dev_warn(ctx->dev, "mode change at boot to %s\n", adjusted_mode->name);
		ctx->panel_state = PANEL_STATE_HANDOFF_MODESET;
	}

	dev_dbg(ctx->dev, "changing display mode to %dx%d@%d\n",
		pmode->mode.hdisplay, pmode->mode.vdisplay, drm_mode_vrefresh(&pmode->mode));

	dsi->mode_flags = pmode->exynos_mode.mode_flags;
	ctx->last_mode_set_ts = ktime_get();

	DPU_ATRACE_BEGIN(__func__);
	if (funcs) {
		const bool is_active = is_panel_active(ctx);
		const bool was_lp_mode = old_mode && old_mode->exynos_mode.is_lp_mode;
		const bool is_lp_mode = pmode->exynos_mode.is_lp_mode;
		bool state_changed = false;

		if (is_lp_mode && funcs->set_lp_mode) {
			if (is_active) {
				if (!is_local_hbm_disabled(ctx) && funcs->set_local_hbm_mode) {
					dev_warn(ctx->dev,
						"LHBM is on when switching to LP mode(%s), turn off LHBM first\n",
						pmode->mode.name);
					panel_update_local_hbm_locked(ctx, false);
				}
				funcs->set_lp_mode(ctx, pmode);
				ctx->panel_state = PANEL_STATE_LP;
				need_update_backlight = true;
			}
			_exynos_panel_set_vddd_voltage(ctx, true);
		} else if (was_lp_mode && !is_lp_mode) {
			_exynos_panel_set_vddd_voltage(ctx, false);
			if (is_active && funcs->set_nolp_mode) {
				funcs->set_nolp_mode(ctx, pmode);
				ctx->panel_state = PANEL_STATE_NORMAL;
				need_update_backlight = true;
				state_changed = true;
				come_out_lp_mode = true;
			}
			ctx->current_binned_lp = NULL;
		} else if (funcs->mode_set) {
			if ((MIPI_CMD_SYNC_REFRESH_RATE & exynos_connector_state->mipi_sync) &&
					is_active && old_mode)
				exynos_panel_check_mipi_sync_timing(crtc, old_mode, ctx);

			if (is_active) {
				if (!is_local_hbm_disabled(ctx) &&
				    !ctx->desc->no_lhbm_rr_constraints)
					dev_warn(ctx->dev,
						"do mode change (`%s`) unexpectedly when LHBM is ON\n",
						pmode->mode.name);

				funcs->mode_set(ctx, pmode);
				state_changed = true;
			} else {
				dev_warn(ctx->dev,
					"don't do mode change (`%s`) when panel isn't in interactive mode\n",
					pmode->mode.name);
			}
		}

		ctx->current_mode = pmode;

		if (state_changed) {
			if (was_lp_mode)
				exynos_panel_set_backlight_state(
					ctx, is_active ? PANEL_STATE_NORMAL : PANEL_STATE_OFF);
			else if (ctx->bl)
				backlight_state_changed(ctx->bl);

			if (!is_lp_mode)
				exynos_panel_update_te2(ctx);
		}
	} else {
		ctx->current_mode = pmode;
	}

	if (old_mode && drm_mode_vrefresh(&pmode->mode) != drm_mode_vrefresh(&old_mode->mode)) {
		ctx->last_rr_switch_ts = ktime_get();
		ctx->last_rr = drm_mode_vrefresh(&old_mode->mode);
		if (come_out_lp_mode)
			ctx->last_lp_exit_ts = ctx->last_rr_switch_ts;
	}

	mutex_unlock(&ctx->mode_lock);

	if (need_update_backlight && ctx->bl)
		backlight_update_status(ctx->bl);

	DPU_ATRACE_INT("panel_fps", drm_mode_vrefresh(mode));
	DPU_ATRACE_END(__func__);
}

static void local_hbm_timeout_work(struct work_struct *work)
{
	struct exynos_panel *ctx =
			 container_of(work, struct exynos_panel, hbm.local_hbm.timeout_work.work);

	dev_dbg(ctx->dev, "%s\n", __func__);

	dev_info(ctx->dev, "%s: turn off LHBM\n", __func__);
	mutex_lock(&ctx->mode_lock);
	panel_update_local_hbm_notimeout(ctx, false);
	mutex_unlock(&ctx->mode_lock);
	sysfs_notify(&ctx->bl->dev.kobj, NULL, "local_hbm_mode");
}

static void local_hbm_wait_and_notify_effectiveness(struct exynos_panel *ctx,
						     struct drm_crtc *crtc, u32 frames)
{
	const u32 per_frame_us = get_current_frame_duration_us(ctx);

	if (frames == 0)
		return;

	if (crtc) {
		u32 i;

		for (i = 0; i < frames; i++) {
			drm_crtc_wait_one_vblank(crtc);
			if (ctx->hbm.local_hbm.next_vblank_ts == 0)
				ctx->hbm.local_hbm.next_vblank_ts = ktime_get();
		}
	} else {
		u32 delay_us = ktime_us_delta(ktime_get(), ctx->hbm.local_hbm.en_cmd_ts);
		int remaining_us = (per_frame_us * frames) - delay_us;

		if (remaining_us > 0)
			usleep_range(remaining_us, remaining_us + 10);
	}
	/* wait for 0.8 frame time to ensure finishing LHBM spot scanout */
	usleep_range(per_frame_us * 4 / 5, (per_frame_us * 4 / 5) + 10);
	dev_dbg(ctx->dev, "%s: effectiveness delay(us): %lld(EN), %lld(TE)\n", __func__,
		ktime_us_delta(ktime_get(), ctx->hbm.local_hbm.en_cmd_ts),
		ctx->hbm.local_hbm.next_vblank_ts ?
			ktime_us_delta(ktime_get(), ctx->hbm.local_hbm.next_vblank_ts) :
			0);
	if (ctx->hbm.local_hbm.state == LOCAL_HBM_ENABLING) {
		ctx->hbm.local_hbm.state = LOCAL_HBM_ENABLED;
		sysfs_notify(&ctx->bl->dev.kobj, NULL, "local_hbm_mode");
	} else {
		dev_warn(ctx->dev, "%s: LHBM state = %d before becoming effective\n", __func__,
			 ctx->hbm.local_hbm.state);
	}
}

static void local_hbm_post_work(struct kthread_work *work)
{
	struct exynos_panel *ctx = container_of(work, struct exynos_panel, hbm.local_hbm.post_work);
	const struct exynos_panel_desc *desc = ctx->desc;
	struct drm_crtc *crtc = get_exynos_panel_connector_crtc(ctx);

	DPU_ATRACE_BEGIN(__func__);
	if (crtc && drm_crtc_vblank_get(crtc))
		crtc = NULL;
	ctx->hbm.local_hbm.next_vblank_ts = 0;

	/* TODO: delay time might be inaccurate if refresh rate changes around here */
	local_hbm_wait_and_notify_effectiveness(ctx, crtc, desc->lhbm_effective_delay_frames);

	if (crtc)
		drm_crtc_vblank_put(crtc);
	DPU_ATRACE_END(__func__);
}

static void hbm_data_init(struct exynos_panel *ctx)
{
	ctx->hbm.local_hbm.gamma_para_ready = false;
	ctx->hbm.local_hbm.max_timeout_ms = LOCAL_HBM_MAX_TIMEOUT_MS;
	ctx->hbm.local_hbm.state = LOCAL_HBM_DISABLED;
	ctx->hbm.wq = create_singlethread_workqueue("hbm_workq");
	if (!ctx->hbm.wq)
		dev_err(ctx->dev, "failed to create hbm workq!\n");
	else {
		INIT_DELAYED_WORK(&ctx->hbm.local_hbm.timeout_work, local_hbm_timeout_work);
	}

	if (is_local_hbm_post_enabling_supported(ctx)) {
		kthread_init_worker(&ctx->hbm.local_hbm.worker);
		ctx->hbm.local_hbm.thread =
			kthread_run(kthread_worker_fn, &ctx->hbm.local_hbm.worker, "lhbm_kthread");
		if (IS_ERR(ctx->hbm.local_hbm.thread))
			dev_err(ctx->dev, "failed to run display lhbm kthread\n");
		else {
			struct sched_param param = {
				.sched_priority = 2, // MAX_RT_PRIO - 1,
			};

			sched_setscheduler_nocheck(ctx->hbm.local_hbm.thread, SCHED_FIFO, &param);
			kthread_init_work(&ctx->hbm.local_hbm.post_work, local_hbm_post_work);
		}
	}
}

static void exynos_panel_te2_init(struct exynos_panel *ctx)
{
	struct te2_mode_data *data;
	const struct exynos_binned_lp *binned_lp;
	int i, j;
	int lp_idx = ctx->desc->num_modes;
	int lp_mode_count = ctx->desc->lp_mode_count ? : 1;
	int mode_count = ctx->desc->num_modes + lp_mode_count * (ctx->desc->num_binned_lp - 1);

	for (i = 0; i < ctx->desc->num_modes; i++) {
		const struct exynos_panel_mode *pmode = &ctx->desc->modes[i];

		data = &ctx->te2.mode_data[i];
		data->mode = &pmode->mode;
		data->timing.rising_edge = pmode->te2_timing.rising_edge;
		data->timing.falling_edge = pmode->te2_timing.falling_edge;
	}

	for (i = 0; i < lp_mode_count; i++) {
		int lp_mode_offset = lp_idx + i * (ctx->desc->num_binned_lp - 1);

		for_each_exynos_binned_lp(j, binned_lp, ctx) {
			int idx;

			/* ignore the first binned entry (off) */
			if (j == 0)
				continue;

			idx = lp_mode_offset + j - 1;
			if (idx >= mode_count) {
				dev_warn(ctx->dev,
					 "idx %d exceeds mode size %d\n", idx, mode_count);
				return;
			}

			data = &ctx->te2.mode_data[idx];
			data->mode = &ctx->desc->lp_mode[i].mode;
			data->binned_lp = binned_lp;
			data->timing.rising_edge =
					binned_lp->te2_timing.rising_edge;
			data->timing.falling_edge =
					binned_lp->te2_timing.falling_edge;
		}
	}

	ctx->te2.option = TE2_OPT_CHANGEABLE;
}

static const struct drm_bridge_funcs exynos_panel_bridge_funcs = {
	.attach = exynos_panel_bridge_attach,
	.detach = exynos_panel_bridge_detach,
	.atomic_check = exynos_panel_bridge_atomic_check,
	.atomic_pre_enable = exynos_panel_bridge_pre_enable,
	.atomic_enable = exynos_panel_bridge_enable,
	.atomic_disable = exynos_panel_bridge_disable,
	.atomic_post_disable = exynos_panel_bridge_post_disable,
	.atomic_duplicate_state = drm_atomic_helper_bridge_duplicate_state,
	.atomic_destroy_state = drm_atomic_helper_bridge_destroy_state,
	.atomic_reset = drm_atomic_helper_bridge_reset,
	.mode_set = exynos_panel_bridge_mode_set,
};

#ifdef CONFIG_OF
static void devm_backlight_release(void *data)
{
	struct backlight_device *bd = data;

	if (bd)
		put_device(&bd->dev);
}

static int exynos_panel_of_backlight(struct exynos_panel *ctx)
{
	struct device *dev;
	struct device_node *np;
	struct backlight_device *bd;
	int ret;

	dev = ctx->panel.dev;
	if (!dev)
		return -EINVAL;

	if (!dev->of_node)
		return 0;

	np = of_parse_phandle(dev->of_node, "backlight", 0);
	if (!np)
		return 0;

	bd = of_find_backlight_by_node(np);
	of_node_put(np);
	if (IS_ERR_OR_NULL(bd))
		return -EPROBE_DEFER;
	ctx->panel.backlight = bd;
	ret = devm_add_action(dev, devm_backlight_release, bd);
	if (ret) {
		put_device(&bd->dev);
		return ret;
	}
	ctx->bl_ctrl_dcs = of_property_read_bool(dev->of_node, "bl-ctrl-dcs");
	dev_info(ctx->dev, "succeed to register devtree backlight phandle\n");
	return 0;
}
#else
static int exynos_panel_of_backlight(struct exynos_panel *ctx)
{
	return 0;
}
#endif

int exynos_panel_common_init(struct mipi_dsi_device *dsi,
				struct exynos_panel *ctx)
{
	static atomic_t panel_index = ATOMIC_INIT(-1);
	struct device *dev = &dsi->dev;
	int ret = 0;
	char name[32];
	const struct exynos_panel_funcs *exynos_panel_func;
	int i;

	dev_dbg(dev, "%s +\n", __func__);

	mipi_dsi_set_drvdata(dsi, ctx);
	ctx->dev = dev;
	ctx->desc = of_device_get_match_data(dev);

	dsi->lanes = ctx->desc->data_lane_cnt;
	dsi->format = MIPI_DSI_FMT_RGB888;

	ret = exynos_panel_parse_dt(ctx);
	if (ret)
		return ret;

	scnprintf(name, sizeof(name), "panel%d-backlight", atomic_inc_return(&panel_index));

	ctx->bl = devm_backlight_device_register(ctx->dev, name, dev,
			ctx, &exynos_backlight_ops, NULL);
	if (IS_ERR(ctx->bl)) {
		dev_err(ctx->dev, "failed to register backlight device\n");
		return PTR_ERR(ctx->bl);
	}
	ctx->bl->props.max_brightness = ctx->desc->max_brightness;
	ctx->bl->props.brightness = ctx->desc->dft_brightness;

	exynos_panel_func = ctx->desc->exynos_panel_func;
	if (exynos_panel_func && (exynos_panel_func->set_hbm_mode
				  || exynos_panel_func->set_local_hbm_mode))
		hbm_data_init(ctx);

	if (exynos_panel_func && exynos_panel_func->get_te2_edges &&
	    exynos_panel_func->configure_te2_edges &&
	    exynos_panel_func->update_te2)
		exynos_panel_te2_init(ctx);

	if (ctx->desc->bl_num_ranges) {
		ctx->bl_notifier.num_ranges = ctx->desc->bl_num_ranges;
		if (ctx->bl_notifier.num_ranges > MAX_BL_RANGES) {
			dev_warn(ctx->dev, "exceed max number of bl range\n");
			ctx->bl_notifier.num_ranges = MAX_BL_RANGES;
		}

		for (i = 0; i < ctx->bl_notifier.num_ranges; i++)
			ctx->bl_notifier.ranges[i] = ctx->desc->bl_range[i];
	}

	for (i = 0; i < ctx->desc->num_modes; i++) {
		const struct exynos_panel_mode *pmode = &ctx->desc->modes[i];
		const int vrefresh = drm_mode_vrefresh(&pmode->mode);

		if (ctx->peak_vrefresh < vrefresh)
			ctx->peak_vrefresh = vrefresh;
	}

	ctx->panel_idle_enabled = exynos_panel_func && exynos_panel_func->set_self_refresh != NULL;
	INIT_DELAYED_WORK(&ctx->idle_work, panel_idle_work);

	mutex_init(&ctx->mode_lock);
	mutex_init(&ctx->bl_state_lock);
	mutex_init(&ctx->lp_state_lock);

	drm_panel_init(&ctx->panel, dev, ctx->desc->panel_func, DRM_MODE_CONNECTOR_DSI);

	ret = exynos_panel_of_backlight(ctx);
	if (ret) {
		dev_err(ctx->dev, "failed to register devtree backlight (%d)\n", ret);
		return ret;
	}

	drm_panel_add(&ctx->panel);

	ctx->bridge.funcs = &exynos_panel_bridge_funcs;
#ifdef CONFIG_OF
	ctx->bridge.of_node = ctx->dev->of_node;
#endif
	drm_bridge_add(&ctx->bridge);

	ret = sysfs_create_files(&dev->kobj, panel_attrs);
	if (ret)
		pr_warn("unable to add panel sysfs files (%d)\n", ret);

	ret = sysfs_create_groups(&ctx->bl->dev.kobj, bl_device_groups);
	if (ret)
		dev_err(ctx->dev, "unable to create bl_device_groups groups\n");

	if (exynos_panel_func && exynos_panel_func->set_cabc_mode) {
		ret = sysfs_create_file(&ctx->bl->dev.kobj, &dev_attr_cabc_mode.attr);
		if (ret)
			dev_err(ctx->dev, "unable to create cabc_mode\n");
	}
	exynos_panel_handoff(ctx);

	ret = mipi_dsi_attach(dsi);
	if (ret)
		goto err_panel;

	dev_info(ctx->dev, "samsung common panel driver has been probed\n");

	return 0;

err_panel:
	drm_panel_remove(&ctx->panel);
	dev_err(ctx->dev, "failed to probe samsung panel driver(%d)\n", ret);

	return ret;
}
EXPORT_SYMBOL(exynos_panel_common_init);

int exynos_panel_probe(struct mipi_dsi_device *dsi)
{
	struct exynos_panel *ctx;

	ctx = devm_kzalloc(&dsi->dev, sizeof(struct exynos_panel), GFP_KERNEL);
	if (!ctx)
		return -ENOMEM;

	return exynos_panel_common_init(dsi, ctx);
}
EXPORT_SYMBOL(exynos_panel_probe);

int exynos_panel_remove(struct mipi_dsi_device *dsi)
{
	struct exynos_panel *ctx = mipi_dsi_get_drvdata(dsi);

	mipi_dsi_detach(dsi);
	drm_panel_remove(&ctx->panel);
	drm_bridge_remove(&ctx->bridge);

	sysfs_remove_groups(&ctx->bl->dev.kobj, bl_device_groups);
	sysfs_remove_file(&ctx->bl->dev.kobj, &dev_attr_cabc_mode.attr);
	devm_backlight_device_unregister(ctx->dev, ctx->bl);

	return 0;
}
EXPORT_SYMBOL(exynos_panel_remove);

MODULE_AUTHOR("Jiun Yu <jiun.yu@samsung.com>");
MODULE_DESCRIPTION("MIPI-DSI based Samsung common panel driver");
MODULE_LICENSE("GPL");