summaryrefslogtreecommitdiff
path: root/plugins/tv/display/core.c
blob: 24bcb4bb757cfb30adce1b9246147b1a07e896a4 (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
/*
 * deviced
 *
 * Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * @file	core.c
 * @brief	Power manager main loop.
 *
 * This file includes Main loop, the FSM, signal processing.
 */
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <vconf-keys.h>
#include <sys/time.h>

#include "ambient-mode.h"
#include "util.h"
#include "core.h"
#include "device-node.h"
#include "lock-detector.h"
#include "display-ops.h"
#include "core/devices.h"
#include "core/device-notifier.h"
#include "core/udev.h"
#include "core/list.h"
#include "core/common.h"
#include "core/config-parser.h"
#include "core/launch.h"
#include "apps/apps.h"
#include "extcon/extcon.h"
#include "battery/power-supply.h"
#include "power/power-handler.h"
#include "dd-display.h"
#include "display/display-dpms.h"

#define DISPLAY_CONF_FILE    "/etc/deviced/display.conf"

/**
 * @addtogroup POWER_MANAGER
 * @{
 */

#define SET_BRIGHTNESS_IN_BOOTLOADER	"/usr/bin/save_blenv SLP_LCD_BRIGHT"
#define LOCK_SCREEN_INPUT_TIMEOUT	10000
#define LOCK_SCREEN_CONTROL_TIMEOUT	5000
#define ALWAYS_ON_TIMEOUT			3600000
#define LATE_LCD_TRANSIT			1

#define PID_MAX			6

#define GESTURE_STR		"gesture"
#define POWER_KEY_STR		"powerkey"
#define TOUCH_STR		"touch"
#define EVENT_STR		"event"
#define TIMEOUT_STR		"timeout"
#define PROXI_STR		"proximity"
#define PALM_STR		"palm"
#define UNKNOWN_STR		"unknown"

#define METHOD_APP_STATUS		"CheckAppStatus"

#define PM_WAKEUP		0
#define PM_SUSPEND		1

extern void init_pm_internal();
extern int get_charging_status(int *val);
extern void init_save_userlock(void);

unsigned int pm_status_flag;
static int trans_condition;

static void (*power_saving_func) (int onoff);
static enum device_ops_status status = DEVICE_OPS_STATUS_UNINIT;

int pm_cur_state;
int pm_old_state;
guint timeout_src_id;
int system_wakeup_flag = false;
static unsigned int custom_normal_timeout = 0;
static unsigned int custom_dim_timeout = 0;
static int custom_holdkey_block = false;
static int custom_change_pid = -1;
static char *custom_change_name;
static bool hallic_open = true;
static guint lock_timeout_id;
static guint transit_timer;
static int lock_screen_timeout = LOCK_SCREEN_INPUT_TIMEOUT;
static long displayoff_time;
static struct timeval lcdon_tv;
static int lcd_paneloff_mode = false;
static int stay_touchscreen_off = false;
dd_list *lcdon_ops;
/*
 * The two variables(lcdon_broadcast, pmstate_suspend) must be set initial
 * state because it should be sent from previous state at booting time.
 */
static bool lcdon_broadcast = true;
static int pmstate_suspend = PM_SUSPEND;

static bool touch_blocked = false;

/* default transition, action fuctions */
static int default_trans(int evt);
static int default_action(int timeout);
static int default_check(int curr, int next);

static gboolean del_normal_cond(void *data);
static gboolean del_dim_cond(void *data);
static gboolean del_off_cond(void *data);

static gboolean pmlock_normal_check(void *data);
static gboolean pmlock_dim_check(void *data);
static gboolean pmlock_off_check(void *data);

static int default_proc_change_state(unsigned int cond, pid_t pid);
static int (*proc_change_state)(unsigned int cond, pid_t pid) = default_proc_change_state;

struct state states[S_END] = {
	{ S_START,    "S_START",    NULL,          NULL,           NULL,          NULL            },
	{ S_NORMAL,   "S_NORMAL",   default_trans, default_action, default_check, del_normal_cond },
	{ S_LCDDIM,   "S_LCDDIM",   default_trans, default_action, default_check, del_dim_cond    },
	{ S_LCDOFF,   "S_LCDOFF",   default_trans, default_action, default_check, del_off_cond    },
	{ S_STANDBY,  "S_STANDBY",  NULL,          NULL,           NULL,          NULL            },
	{ S_SLEEP,    "S_SLEEP",    default_trans, default_action, default_check, NULL            },
	{ S_POWEROFF, "S_POWEROFF", NULL,          NULL,           NULL,          NULL            },
};

static int trans_table[S_END][EVENT_END] = {
	/* Timeout,   Input */
	{ S_START,    S_START    }, /* S_START */
	{ S_LCDDIM,   S_NORMAL   }, /* S_NORMAL */
	{ S_LCDOFF,   S_NORMAL   }, /* S_LCDDIM */
	{ S_SLEEP,    S_NORMAL   }, /* S_LCDOFF */
	{ S_SLEEP,    S_STANDBY  }, /* S_STANDBY */
	{ S_LCDOFF,   S_NORMAL   }, /* S_SLEEP */
	{ S_POWEROFF, S_POWEROFF }, /* S_POWEROFF */
};

static GSourceFunc warning_cb[S_END] = {
	NULL, pmlock_normal_check, pmlock_dim_check, pmlock_off_check,
};

enum signal_type {
	SIGNAL_INVALID = 0,
	SIGNAL_PRE,
	SIGNAL_POST,
	SIGNAL_MAX,
};

enum platform_control {
	PLATFORM_DISPLAY_OFF,
	PLATFORM_DISPLAY_ON,
};

static const char *lcdon_sig_lookup[SIGNAL_MAX] = {
	[SIGNAL_PRE]  = "LCDOn",
	[SIGNAL_POST] = "LCDOnCompleted",
};
static const char *lcdoff_sig_lookup[SIGNAL_MAX] = {
	[SIGNAL_PRE]  = "LCDOff",
	[SIGNAL_POST] = "LCDOffCompleted",
};

#define SHIFT_UNLOCK		4
#define SHIFT_CHANGE_STATE	7
#define CHANGE_STATE_BIT	0xF00	/* 1111 0000 0000 */
#define SHIFT_LOCK_FLAG	16
#define SHIFT_CHANGE_TIMEOUT	20
#define CUSTOM_TIMEOUT_BIT	0x1
#define CUSTOM_HOLDKEY_BIT	0x2
#define HOLD_KEY_BLOCK_BIT	0x1
#define TIMEOUT_NONE		(-1)

#define S_COVER_TIMEOUT			8000
#define GET_HOLDKEY_BLOCK_STATE(x) ((x >> SHIFT_LOCK_FLAG) & HOLD_KEY_BLOCK_BIT)
#define BOOTING_DONE_WATING_TIME	60000	/* 1 minute */
#define LOCK_TIME_WARNING		60	/* 60 seconds */

#define ACTIVE_ACT "active"
#define INACTIVE_ACT "inactive"

#define LOCK_SCREEN_WATING_TIME		300	/* 0.3 second */
#define LONG_PRESS_INTERVAL             2       /* 2 seconds */
#define SAMPLING_INTERVAL		1	/* 1 sec */
#define BRIGHTNESS_CHANGE_STEP		10
#define LCD_ALWAYS_ON			0
#define ACCEL_SENSOR_ON			1
#define CONTINUOUS_SAMPLING		1
#define LCDOFF_TIMEOUT			500	/* milli second */

#define DIFF_TIMEVAL_MS(a, b) \
	(((a.tv_sec * 1000000 + a.tv_usec) - \
	(b.tv_sec * 1000000 + b.tv_usec)) \
	/ 1000)

struct display_config display_conf = {
	.lock_wait_time		= LOCK_SCREEN_WATING_TIME,
	.longpress_interval	= LONG_PRESS_INTERVAL,
	.lightsensor_interval	= SAMPLING_INTERVAL,
	.lcdoff_timeout		= LCDOFF_TIMEOUT,
	.brightness_change_step	= BRIGHTNESS_CHANGE_STEP,
	.lcd_always_on		= LCD_ALWAYS_ON,
	.dimming		= 1,
	.framerate_app		= {0, 0, 0, 0},
	.control_display	= 0,
	.powerkey_doublepress	= 0,
	.accel_sensor_on	= ACCEL_SENSOR_ON,
	.continuous_sampling	= CONTINUOUS_SAMPLING,
	.timeout_enable		= true,
	.input_support		= true,
	.lockcheck_timeout	= 600,
	.aod_enter_level	= 40,
	.aod_tsp 		= true,
	.touch_wakeup		= false,
	.sleep_support          = true,
};

struct display_function_info display_info = {
	.update_auto_brightness		= NULL,
	.set_autobrightness_min		= NULL,
	.reset_autobrightness_min	= NULL,
	.face_detection			= NULL,
};

typedef struct _pm_lock_node {
	pid_t pid;
	guint timeout_id;
	guint warning_id;
	time_t time;
	bool holdkey_block;
	bool background;
	bool broadcast_warning;
} PmLockNode;

static dd_list *cond_head[S_END];

static void set_process_active(bool flag, pid_t pid)
{
	int ret;

	if (pid >= INTERNAL_LOCK_BASE)
		return;

	/* Send dbug to resourced */
	ret = dbus_handle_emit_dbus_signal(NULL,
							RESOURCED_PATH_PROCESS,
						    RESOURCED_INTERFACE_PROCESS,
						    RESOURCED_METHOD_ACTIVE,
						    g_variant_new("(si)", (flag ? ACTIVE_ACT : INACTIVE_ACT), pid));
	if (ret < 0)
		_E("Failed to send dbus signal to resourced.");
}

bool check_lock_state(int state)
{
	dd_list *elem;
	PmLockNode *t;

	DD_LIST_FOREACH(cond_head[state], elem, t) {
		if (t->background == false)
			return true;
	}

	return false;
}

void change_state_action(enum state_t state, int (*func)(int timeout))
{
	_I("[%s] 'action' is changed.", states[state].name);
	states[state].action = func;
}

void change_state_trans(enum state_t state, int (*func)(int evt))
{
	_I("[%s] 'trans' is changed.", states[state].name);
	states[state].trans = func;
}

void change_state_check(enum state_t state, int (*func)(int curr, int next))
{
	_I("[%s] 'check' is changed.", states[state].name);
	states[state].check = func;
}

void change_state_name(enum state_t state, char *name)
{
	_I("[%s] 'name' is changed.", states[state].name);
	states[state].name = name;
}

void change_trans_table(enum state_t state, enum state_t next)
{
	_I("[%s] 'timeout trans table' is changed.", states[state].name);
	trans_table[state][EVENT_TIMEOUT] = next;
}

void change_proc_change_state(int (*func)(unsigned int cond, pid_t pid))
{
	_I("'proc change state' is changed.");
	proc_change_state = func;
}

static inline long clock_gettime_to_long(void)
{
	struct timespec now;
	int ret;

	ret = clock_gettime(CLOCK_REALTIME, &now);

	if (ret < 0) {
		_E("Failed to clock gettime!");
		return 0;
	}

	return SEC_TO_MSEC(now.tv_sec) + NSEC_TO_MSEC(now.tv_nsec);
}

static int display_brightness_changed(void *data)
{
	int brt, ret;

	brt = DATA_VALUE_INT(data);

	ret = dbus_handle_emit_dbus_signal(NULL,
							DEVICED_PATH_DISPLAY,
							DEVICED_INTERFACE_DISPLAY,
							"Brightness",
							g_variant_new("(i)", brt));
	if (ret < 0)
		_E("Failed to send dbus signal Brightness.");

	return 0;
}

static int display_auto_brightness_sensing(void *data)
{
	if (!transit_timer)
		return 0;

	g_source_remove(transit_timer);
	transit_timer = 0;

	return 0;
}

static void broadcast_lcd_on(enum signal_type type, enum device_flags flags)
{
	const char *str;
	const char *signal;
	int ret;
	long diff = 0;

	if (type <= SIGNAL_INVALID || type >= SIGNAL_MAX) {
		_E("Invalid signal type(%d).", type);
		return;
	}

	if (type == SIGNAL_PRE && displayoff_time != 0)
		diff = clock_gettime_to_long() - displayoff_time;

	if (flags & LCD_ON_BY_GESTURE)
		str = GESTURE_STR;
	else if (flags & LCD_ON_BY_POWER_KEY)
		str = POWER_KEY_STR;
	else if (flags & LCD_ON_BY_EVENT)
		str = EVENT_STR;
	else if (flags & LCD_ON_BY_TOUCH)
		str = TOUCH_STR;
	else
		str = UNKNOWN_STR;

	signal = lcdon_sig_lookup[type];
	_I("lcdstep : Broadcast signal(%s:%s).", signal, str);
	ret = dbus_handle_emit_dbus_signal(NULL,
						DEVICED_PATH_DISPLAY,
						DEVICED_INTERFACE_DISPLAY,
						signal,
						g_variant_new("(si)", str, diff));
	if (ret < 0)
		_E("Failed to send dbus signal(%s)", signal);
}

static void broadcast_lcd_off(enum signal_type type, enum device_flags flags)
{
	const char *str;
	const char *signal;
	int ret;

	if (type <= SIGNAL_INVALID || type >= SIGNAL_MAX) {
		_E("Invalid signal type(%d).", type);
		return;
	}

	if (type == SIGNAL_PRE)
		displayoff_time = clock_gettime_to_long();

	signal = lcdoff_sig_lookup[type];

	if (flags & LCD_OFF_BY_POWER_KEY)
		str = POWER_KEY_STR;
	else if (flags & LCD_OFF_BY_TIMEOUT)
		str = TIMEOUT_STR;
	else if (flags & LCD_OFF_BY_EVENT)
		str = EVENT_STR;
	else
		str = UNKNOWN_STR;

	_I("lcdstep : Broadcast signal(%s).", signal);
	ret = dbus_handle_emit_dbus_signal(NULL,
						DEVICED_PATH_DISPLAY,
						DEVICED_INTERFACE_DISPLAY,
						signal,
						g_variant_new("(s)", str));
	if (ret < 0)
		_E("Failed to send dbus signal(%s)", signal);
}

void broadcast_lcd_off_late(enum device_flags flags)
{
	static enum device_flags late_flags;

	if (flags & LCD_OFF_LATE_MODE)
		broadcast_lcd_off(SIGNAL_POST, late_flags);
	else
		late_flags = flags;
}

static unsigned long get_lcd_on_flags(void)
{
	unsigned long flags = NORMAL_MODE;

	if (lcd_paneloff_mode)
		flags |= LCD_PANEL_OFF_MODE;

	if (ambient_get_condition() == true) {
		flags |= AMBIENT_MODE;
		flags |= LCD_PHASED_TRANSIT_MODE;
	}

	return flags;
}

bool touch_event_blocked(void)
{
	return touch_blocked;
}

static gboolean late_transit_on(void *data)
{
	if (!transit_timer)
		return G_SOURCE_REMOVE;

	g_source_remove(transit_timer);
	transit_timer = 0;

	backlight_ops.transit_state(DPMS_ON);
	return G_SOURCE_REMOVE;
}

void lcd_on_procedure(int state, enum device_flags flag)
{
	dd_list *l = NULL;
	const struct device_ops *ops = NULL;
	unsigned long flags = get_lcd_on_flags();
	flags |= flag;

	/*
	 * Display on procedure
	 * step 1. broadcast lcd on signal with cause
	 * step 2. set brightness
	 * step 3. set pmstate of vconf
	 * step 4. display on operate
	 *  - a. display on
	 *  - b. TSP(touch screen) and touchkey enable
	 * step 5. broadcast lcd on complete siganl
	 * step 6. key backlight enable
	 */
	_I("[lcdstep] %lu", flags);

	if (flags & AMBIENT_MODE) {
		if (ambient_get_state() == false && backlight_ops.get_lcd_power() == DPMS_ON)
			return;
		ambient_set_state(false);
	}

	/* send LCDOn dbus signal */
	if (!lcdon_broadcast)
		broadcast_lcd_on(SIGNAL_PRE, flags);

	if (!(flags & LCD_PHASED_TRANSIT_MODE)) {
		/* Update brightness level */
		if (state == LCD_DIM)
			backlight_ops.dim();
		else if (state == LCD_NORMAL)
			backlight_ops.update();
	}

	if (state == LCD_NORMAL)
		set_setting_pmstate(S_NORMAL);
	else if (state == LCD_DIM)
		set_setting_pmstate(S_LCDDIM);

	DD_LIST_FOREACH(lcdon_ops, l, ops)
		ops->start(flags);

	if (!lcdon_broadcast) {
	broadcast_lcd_on(SIGNAL_POST, flags);
		if (flags & LCD_PHASED_TRANSIT_MODE)
			transit_timer = g_timeout_add_seconds(LATE_LCD_TRANSIT,
				late_transit_on, NULL);
		lcdon_broadcast = true;
	}

	if (CHECK_OPS(keyfilter_ops, backlight_enable))
		keyfilter_ops->backlight_enable(true);

	touch_blocked = false;
}

static unsigned long get_lcd_off_flags(void)
{
	unsigned long flags = NORMAL_MODE;

	if (ambient_get_condition() == true) {
		flags |= AMBIENT_MODE;
		flags |= LCD_PHASED_TRANSIT_MODE;
	}

	if (stay_touchscreen_off)
		flags |= TOUCH_SCREEN_OFF_MODE;

	return flags;
}

inline void lcd_off_procedure(enum device_flags flag)
{
	dd_list *l = NULL;
	const struct device_ops *ops = NULL;
	unsigned long flags = get_lcd_off_flags();
	flags |= flag;

	/*
	 * Display off procedure
	 * step 0. enhance mode off using nofity (e.g mdnie, HBM, LBM)
	 * step 1. broadcast lcd off signal with cause
	 * step 2. set pmstate of vconf
	 * step 3. display off operate
	 *  - a. display off
	 *  - b. TSP(touch screen) and touchkey disable
	 * step 4. broadcast lcd off complete siganl
	 */
	_I("[lcdstep] %lu", flags);

	device_notify(DEVICE_NOTIFIER_LCD_OFF, NULL);

	touch_blocked = true;

	if (flags & AMBIENT_MODE) {
		if (ambient_get_state() == true)
			return;
		ambient_set_state(true);
	}

	if (lcdon_broadcast) {
		broadcast_lcd_off(SIGNAL_PRE, flags);
		lcdon_broadcast = false;
	}
	set_setting_pmstate(S_LCDOFF);

	if (CHECK_OPS(keyfilter_ops, backlight_enable))
		keyfilter_ops->backlight_enable(false);

	if (transit_timer) {
		g_source_remove(transit_timer);
		transit_timer = 0;
	}

	if (flags & LCD_PHASED_TRANSIT_MODE)
		backlight_ops.transit_state(DPMS_OFF);

	DD_LIST_FOREACH(lcdon_ops, l, ops)
		ops->stop(flags);

	if (flags & AMBIENT_MODE)
		broadcast_lcd_off_late(flags);
	else
		broadcast_lcd_off(SIGNAL_POST, flags);
}

void set_stay_touchscreen_off(int val)
{
	_I("Stay touch screen off: %d", val);
	stay_touchscreen_off = val;

	if (disp_plgn.pm_change_internal)
		disp_plgn.pm_change_internal(INTERNAL_LOCK_PM, LCD_NORMAL);
}

void set_lcd_paneloff_mode(int val)
{
	_I("Lcd paneloff mode: %d", val);
	lcd_paneloff_mode = val;

	if (disp_plgn.pm_change_internal)
		disp_plgn.pm_change_internal(INTERNAL_LOCK_PM, LCD_NORMAL);
}

int low_battery_state(int val)
{
	switch (val) {
	case VCONFKEY_SYSMAN_BAT_POWER_OFF:
	case VCONFKEY_SYSMAN_BAT_CRITICAL_LOW:
	case VCONFKEY_SYSMAN_BAT_REAL_POWER_OFF:
		return true;
	}
	return false;
}

int get_hallic_open(void)
{
	return hallic_open;
}

static int refresh_app_cond()
{
	trans_condition = 0;

	if (check_lock_state(S_NORMAL))
		trans_condition = trans_condition | MASK_NORMAL;
	if (check_lock_state(S_LCDDIM))
		trans_condition = trans_condition | MASK_DIM;
	if (check_lock_state(S_LCDOFF))
		trans_condition = trans_condition | MASK_OFF;

	return 0;
}

static void makeup_trans_condition(void)
{
	check_processes(S_NORMAL);
	check_processes(S_LCDDIM);
	check_processes(S_LCDOFF);
	refresh_app_cond();
}

static PmLockNode *find_node(enum state_t s_index, pid_t pid)
{
	dd_list *elem;
	PmLockNode *t = NULL;

	DD_LIST_FOREACH(cond_head[s_index], elem, t) {
		if (t->pid == pid)
			return t;
	}

	return NULL;
}

static PmLockNode *add_node(enum state_t s_index, pid_t pid, guint timeout_id,
		bool holdkey_block)
{
	guint warning_id = 0;
	PmLockNode *n;
	time_t now;

	n = (PmLockNode *) malloc(sizeof(PmLockNode));
	if (n == NULL) {
		_E("Not enough memory, add cond. fail");
		return NULL;
	}

	if (pid < INTERNAL_LOCK_BASE)
		warning_id = g_timeout_add_seconds(display_conf.lightsensor_interval,
			warning_cb[s_index], (void *)((intptr_t)pid));

	time(&now);
	n->pid = pid;
	n->timeout_id = timeout_id;
	n->warning_id = warning_id;
	n->time = now;
	n->holdkey_block = holdkey_block;
	n->background = false;
	n->broadcast_warning = true;
	DD_LIST_APPEND(cond_head[s_index], n);

	refresh_app_cond();
	return n;
}

static int del_node(enum state_t s_index, PmLockNode *n)
{
	if (n == NULL)
		return 0;

	DD_LIST_REMOVE(cond_head[s_index], n);

	/* delete timer */
	if (n->timeout_id) {
		g_source_remove(n->timeout_id);
		n->timeout_id = 0;
	}
	if (n->warning_id) {
		g_source_remove(n->warning_id);
		n->warning_id = 0;
	}

	free(n);
	refresh_app_cond();
	return 0;
}

static void print_node(int next)
{
	int ret;
	dd_list *elem;
	PmLockNode *n;
	char buf[30];
	time_t now;
	double diff;

	if (next <= S_START || next >= S_END)
		return;

	time(&now);
	DD_LIST_FOREACH(cond_head[next], elem, n) {
		diff = difftime(now, n->time);
		ctime_r(&n->time, buf);

		if (diff > LOCK_TIME_WARNING) {
			if (diff > LOCK_TIME_WARNING * 60 && n->pid < INTERNAL_LOCK_BASE && n->broadcast_warning) {
				ret = dbus_handle_emit_dbus_signal(NULL,
										DEVICED_PATH_DISPLAY,
										DEVICED_INTERFACE_DISPLAY,
										"pmlock_over",
										g_variant_new("(i)", n->pid));
				if (ret < 0)
					_E("Failed to send dbus signal pmlock_over.");
                                n->broadcast_warning = false;
			}
			_W("Over(%.0f s) pid( %5d) lock time(%s)", diff, n->pid, buf);
		} else
			_I("Pid(%5d) lock time(%s)", n->pid, buf);
	}
}

void get_pname(pid_t pid, char *pname)
{
	char buf[PATH_MAX];
	int cmdline, r;

	if (pid >= INTERNAL_LOCK_BASE)
		snprintf(buf, PATH_MAX, "/proc/%d/cmdline", getpid());
	else
		snprintf(buf, PATH_MAX, "/proc/%d/cmdline", pid);

	cmdline = open(buf, O_RDONLY);
	if (cmdline < 0) {
		pname[0] = '\0';
		_E("Process(%d) does not exist now(may be dead without unlock).", pid);
		return;
	}

	r = read(cmdline, pname, PATH_MAX);
	if ((r >= 0) && (r < PATH_MAX))
		pname[r] = '\0';
	else
		pname[0] = '\0';

	close(cmdline);
}

static void del_state_cond(void *data, enum state_t state)
{
	PmLockNode *tmp = NULL;
	pid_t pid;

	if (!data)
		return;

	/* A passed data is a pid_t type data, not a 64bit data. */
	pid = (pid_t)((intptr_t)data);
	_I("delete prohibit dim condition by timeout (%d)", pid);

	if (pid == INTERNAL_LOCK_AMBIENT)
		ambient_check_invalid_state(pid);

	tmp = find_node(state, pid);
	del_node(state, tmp);
	set_unlock_time(pid, state);

	if (!timeout_src_id)
		states[pm_cur_state].trans(EVENT_TIMEOUT);

	if (state == S_LCDOFF)
		set_process_active(false, pid);
}

static gboolean del_normal_cond(void *data)
{
	del_state_cond(data, S_NORMAL);
	return G_SOURCE_REMOVE;
}

static gboolean del_dim_cond(void *data)
{
	del_state_cond(data, S_LCDDIM);
	return G_SOURCE_REMOVE;
}

static gboolean del_off_cond(void *data)
{
	del_state_cond(data, S_LCDOFF);
	return G_SOURCE_REMOVE;
}

static void pmlock_check_cb(GVariant *var, void *user_data, GError *err)
{
	pid_t pid;
	int ret, state;
	char *app_id;

	if (!var)
		return;

	if (!dh_get_param_from_var(var, "(iis)", &pid,  &state, &app_id)) {
		_E("Failed to notify low: no message(%s)", g_variant_get_type_string(var));
		goto out;
	}

	_W("%s(%d) was requested pmlock for a long time.", app_id, pid);
	ret = dbus_handle_emit_dbus_signal(NULL,
						DEVICED_PATH_DISPLAY,
						DEVICED_INTERFACE_DISPLAY,
						"pmlock_expired",
						g_variant_new("(i)", pid));
	if (ret < 0)
		_E("Failed to send dbus pmlock_expired");

out:
	g_variant_unref(var);
}

/*
 * Any process is possible many time lock, deviced can not know malicious
 * or good process. so infinity or more then 1 min lock process, deviced
 * will be checked it to resoured. And then, it will be asked quit or maintain to user.
	 */
static void pmlock_check(void *data, char *st)
{
	const char *arr[2];
	char chr_pid[PID_MAX];
	pid_t pid;
	int ret;

	if (!data || !st)
		return;

	if (!strncmp(st, "lcdoff", 4) && backlight_ops.get_lcd_power() == DPMS_ON) {
		_D("Lcd state is PM_LCD_POWER_ON");
		return;
	}

	pid = (pid_t)((intptr_t)data);
	snprintf(chr_pid, sizeof(chr_pid), "%d", pid);

	arr[0] = chr_pid;
	arr[1] = st;

	ret = dbus_handle_method_async_with_reply(RESOURCED_BUS_NAME,
		RESOURCED_PATH_PROCESS,
		RESOURCED_INTERFACE_PROCESS,
		METHOD_APP_STATUS,
		"is", arr, pmlock_check_cb, -1, NULL);
	if (ret < 0)
		_E("Failed to call dbus method");
}

static gboolean pmlock_normal_check(void *data)
{
	pmlock_check(data, "normal");
	return G_SOURCE_CONTINUE;
}

static gboolean pmlock_dim_check(void *data)
{
	pmlock_check(data, "lcddim");
	return G_SOURCE_CONTINUE;
}

static gboolean pmlock_off_check(void *data)
{
	pmlock_check(data, "lcdoff");
	return G_SOURCE_CONTINUE;
}

/* timeout handler  */
gboolean timeout_handler(void *data)
{
	_I("Time out state %s", states[pm_cur_state].name);

	if (timeout_src_id) {
		g_source_remove(timeout_src_id);
		timeout_src_id = 0;
	}

	states[pm_cur_state].trans(EVENT_TIMEOUT);
	return G_SOURCE_REMOVE;
}

void reset_timeout(int timeout)
{
	if (!display_conf.timeout_enable)
		return;

	_I("Reset timeout(%d ms).", timeout);
	if (timeout_src_id != 0) {
		g_source_remove(timeout_src_id);
		timeout_src_id = 0;
	}

	if (trans_table[pm_cur_state][EVENT_TIMEOUT] == pm_cur_state)
		return;

	if (timeout > 0)
		timeout_src_id = g_timeout_add_seconds(MSEC_TO_SEC((double)timeout),
		    timeout_handler, NULL);
	else if (timeout == 0)
		states[pm_cur_state].trans(EVENT_TIMEOUT);
}

/* get configurations from setting */
static int get_lcd_timeout_from_settings(void)
{
	int i;
	int val = 0;

	for (i = 0; i < S_END; i++) {
		switch (states[i].state) {
		case S_NORMAL:
			get_run_timeout(&val);
			break;
		case S_LCDDIM:
			get_dim_timeout(&val);
			break;
		case S_LCDOFF:
			val = display_conf.lcdoff_timeout;
			break;
		default:
			/* This state doesn't need to set time out. */
			val = 0;
			break;
		}
		if (val > 0)
			states[i].timeout = val;

		_I("State(%s) timeout(%d) ms", states[i].name,
			states[i].timeout);
	}

	return 0;
}

static void update_display_time(void)
{
	int run_timeout, val;

	/* first priority : s cover */
	if (!hallic_open) {
		states[S_NORMAL].timeout = S_COVER_TIMEOUT;
		_I("S cover closed: Timeout(%d ms) is set by normal.",
		    S_COVER_TIMEOUT);
		return;
	}

	/* second priority : custom timeout */
	if (custom_normal_timeout > 0) {
		states[S_NORMAL].timeout = custom_normal_timeout;
		states[S_LCDDIM].timeout = custom_dim_timeout;
		_I("CUSTOM : timeout is set by normal(%d ms), dim(%d ms)",
		    custom_normal_timeout, custom_dim_timeout);
		return;
	}

	/* third priority : lock state */
	if ((__get_lock_screen_state() == VCONFKEY_IDLE_LOCK) &&
	    !get_lock_screen_bg_state()) {
		/* timeout is different according to key or event. */
		states[S_NORMAL].timeout = lock_screen_timeout;
		_I("LOCK: Timeout(%d ms) is set by normal.",
		    lock_screen_timeout);
		return;
	}

	/* default setting */
	get_run_timeout(&run_timeout);

	/* for sdk
	 * if the run_timeout is zero, it regards AlwaysOn state
	 */
	if (run_timeout == 0 || display_conf.lcd_always_on) {
		run_timeout = ALWAYS_ON_TIMEOUT;
		_I("LCD always on.");
	}

	states[S_NORMAL].timeout = run_timeout;

	get_dim_timeout(&val);
	states[S_LCDDIM].timeout = val;

	_I("Normal: NORMAL timeout is set by %d ms", states[S_NORMAL].timeout);
	_I("Normal: DIM timeout is set by %d ms", states[S_LCDDIM].timeout);
}

static void update_display_locktime(int time)
{
	lock_screen_timeout = time;
	update_display_time();
}

void set_dim_state(bool on)
{
	_I("Dim state is %d.", on);
	update_display_time();
	states[pm_cur_state].trans(EVENT_INPUT);
}

static void broadcast_pm_suspend(void)
{
	int ret;

	if (pmstate_suspend)
		return;

	_D("PM will be changed to sleep.");

	pmstate_suspend = PM_SUSPEND;
	ret = dbus_handle_emit_dbus_signal(NULL,
							DEVICED_PATH_DISPLAY,
							DEVICED_INTERFACE_DISPLAY,
							"sleep",
							NULL);
	if (ret < 0)
		_E("Failed to send dbus signal sleep.");
}

static void broadcast_pm_wakeup(void)
{
	int ret;

	if (!pmstate_suspend)
		return;

	 _D("PM is changed to wakeup.");

	 pmstate_suspend = PM_WAKEUP;
	 ret = dbus_handle_emit_dbus_signal(NULL,
							 DEVICED_PATH_DISPLAY,
							 DEVICED_INTERFACE_DISPLAY,
							 "wakeup",
							 NULL);
	 if (ret < 0)
		 _E("Failed to send dbus signal wakeup.");

}

void lcd_on_direct(enum device_flags flags)
{
	if (power_ops.get_power_lock_support()
	    && pm_cur_state == S_SLEEP) {
		broadcast_pm_wakeup();
		power_ops.power_lock();
		pm_cur_state = S_NORMAL;
	}

	_D("lcd is on directly");
	gettimeofday(&lcdon_tv, NULL);
	lcd_on_procedure(LCD_NORMAL, flags);

	update_display_locktime(LOCK_SCREEN_INPUT_TIMEOUT);
}

static inline bool check_lcd_is_on(void)
{
	if (backlight_ops.get_lcd_power() != DPMS_ON)
		return false;

	return true;
}

static int check_lock_condition(enum state_t state)
{
	dd_list *elem;
	PmLockNode *t = NULL;
	int ret = false;
	pid_t owner = getpid();

	_D("check holdkey block : state of %s", states[state].name);

	DD_LIST_FOREACH(cond_head[state], elem, t) {
		if (t->pid != owner && t->background == false) {
			ret = true;
			_I("state change was blocked by pid(%d)!", t->pid);
			break;
		}
	}

	return ret;
}

static gboolean timer_refresh_cb(gpointer data)
{
	struct state *st;

	/* state transition */
	pm_old_state = pm_cur_state;
	pm_cur_state = S_NORMAL;
	st = &states[pm_cur_state];

	if (st->action)
		st->action(st->timeout);

	return 0;
}

int custom_lcdon(int timeout)
{
	struct state *st;

	if (timeout <= 0)
		return -EINVAL;

	if (check_lcd_is_on() == false)
		lcd_on_direct(LCD_ON_BY_GESTURE);

	_I("Custom lcd on timeout(%d ms).", timeout);
	if (set_custom_lcdon_timeout(timeout) == true)
		update_display_time();

	/* state transition */
	pm_old_state = pm_cur_state;
	pm_cur_state = S_NORMAL;
	st = &states[pm_cur_state];

	/* enter action */
	if (st->action)
		st->action(st->timeout);

	g_idle_add(timer_refresh_cb, NULL);

	return 0;
}

int custom_lcdoff(enum device_flags flag)
{
	struct state *st;

	check_processes(S_NORMAL);
	check_processes(S_LCDDIM);

	/* check holdkey block flag in lock node */
	if (check_lock_condition(S_NORMAL) || check_lock_condition(S_LCDDIM)) {
		/*
		 * When another proccess is normal lock, device is received call then,
		 * call app can be changed to lcd state by proximity.
		 * If proximity is near then normal lock will be unlocked.
		 */
		if (flag & LCD_OFF_BY_PROXIMITY) {
			_I("custom lcd off by proximity, delete normal lock");
			delete_condition(S_NORMAL);
		} else {
			_I("skip custom lcd off");
			return -ECANCELED;
		}
	}

	_I("custom lcd off by flag(%d)", flag);
	if (backlight_ops.get_lcd_power() == DPMS_ON)
		lcd_off_procedure(flag);

	if (set_custom_lcdon_timeout(0) == true)
		update_display_time();

	/* state transition */
	pm_old_state = pm_cur_state;
	pm_cur_state = S_LCDOFF;
	st = &states[pm_cur_state];

	/* enter action */
	if (st->action)
		st->action(st->timeout);

	return 0;
}

static int display_platform_on(char *reason, int timeout)
{
	struct state *st;
	int flag;
	int str_len;

	str_len = strlen(reason);

	if (!strncmp(reason, GESTURE_STR, str_len))
		flag = LCD_ON_BY_GESTURE;
	else if (!strncmp(reason, EVENT_STR, str_len))
		flag = LCD_ON_BY_EVENT;
	else {
		_E("Reason is unkown(%s)", reason);
		return -EINVAL;
	}

	if (timeout <= 0) {
		_E("Cannot setting timeout %d", timeout);
		return -EINVAL;
	}

	if (check_lcd_is_on() == false)
		lcd_on_direct(flag);

	_I("platform lcd on by %s (%d ms)", reason, timeout);
	if (set_custom_lcdon_timeout(timeout) == true)
		update_display_time();

	/* state transition */
	pm_old_state = pm_cur_state;
	pm_cur_state = S_NORMAL;
	st = &states[pm_cur_state];

	/* enter action */
	if (st->action)
		st->action(st->timeout);

	return 0;
}

static int display_platform_off(char *reason)
{
	struct state *st;
	int flag;
	int str_len;

	str_len = strlen(reason);

	if (!strncmp(reason, GESTURE_STR, str_len)) {
		check_processes(S_NORMAL);
		check_processes(S_LCDDIM);

		/* check holdkey block flag in lock node */
		if (check_lock_condition(S_NORMAL) || check_lock_condition(S_LCDDIM)) {
			_I("skip platform lcd off by gesture");
			return -ECANCELED;
		}
		flag = LCD_OFF_BY_GESTURE;
	} else if (!strncmp(reason, PALM_STR, str_len)) {
		delete_condition(S_NORMAL);
		delete_condition(S_LCDDIM);

		flag = LCD_OFF_BY_PALM;
	} else {
		_E("Reason is unkown(%s)", reason);
		return -EINVAL;
	}

	_I("platform lcd off by %s", reason);
	if (backlight_ops.get_lcd_power() == DPMS_ON)
		lcd_off_procedure(flag);

	/* state transition */
	pm_old_state = pm_cur_state;
	pm_cur_state = S_LCDOFF;
	st = &states[pm_cur_state];

	/* enter action */
	if (st->action)
		st->action(st->timeout);

	return 0;
}

int display_platform_control(int type, char *reason, int timeout)
{
	int ret;

	switch (type) {
	case PLATFORM_DISPLAY_ON:
		ret = display_platform_on(reason, timeout);
		break;
	case PLATFORM_DISPLAY_OFF:
		ret = display_platform_off(reason);
		break;
	default:
		_E("Unkown type(%d)", type);
		ret = -EINVAL;
	}

	return ret;
}

static void default_proc_change_state_action(enum state_t next, int timeout)
{
	struct state *st;

	pm_old_state = pm_cur_state;
	pm_cur_state = next;

	st = &states[pm_cur_state];

	if (st && st->action) {
		if (timeout < 0)
			st->action(st->timeout);
		else
			st->action(timeout);
	}
}

static int default_proc_change_state(unsigned int cond, pid_t pid)
{
	enum state_t next;

	next = GET_COND_STATE(cond);
	_I("Change process(%d) state to %s.", pid, states[next].name);

	switch (next) {
	case S_NORMAL:
		if (check_lcd_is_on() == false)
			lcd_on_direct(LCD_ON_BY_EVENT);
		update_display_locktime(LOCK_SCREEN_CONTROL_TIMEOUT);
		default_proc_change_state_action(next, -1);
		break;
	case S_LCDDIM:
		default_proc_change_state_action(next, -1);
		break;
	case S_LCDOFF:
		if (backlight_ops.get_lcd_power() == DPMS_ON)
			lcd_off_procedure(LCD_OFF_BY_EVENT);
		if (set_custom_lcdon_timeout(0))
			update_display_time();
		default_proc_change_state_action(next, -1);
		break;
	case S_SLEEP:
		_I("Dangerous requests.");
		/* at first LCD_OFF and then goto sleep */
		/* state transition */
		default_proc_change_state_action(S_LCDOFF, TIMEOUT_NONE);
		delete_condition(S_NORMAL);
		delete_condition(S_LCDDIM);
		delete_condition(S_LCDOFF);
		if (lcdon_broadcast) {
			_I("broadcast lcd off signal at non-lcd device");
			broadcast_lcd_off(SIGNAL_PRE, 0);
			broadcast_lcd_off(SIGNAL_POST, 0);
		}
		default_proc_change_state_action(S_SLEEP, TIMEOUT_NONE);
		break;

	default:
		return -EINVAL;
	}

	return 0;
}

/* update transition condition for application requrements */
static void update_lock_timer(PMMsg *data,
		PmLockNode *node, guint timeout_id)
{
	time_t now;

	if (data->timeout > 0) {
		time(&now);
		node->time = now;
	}

	if (node->timeout_id)
		g_source_remove(node->timeout_id);
	node->timeout_id = timeout_id;
}

static void proc_condition_lock(PMMsg *data)
{
	PmLockNode *tmp;
	guint cond_timeout_id = 0;
	char pname[PATH_MAX];
	pid_t pid = data->pid;
	enum state_t state;
	int holdkey_block;
	bool value = true;
	unsigned int flags;

	state = GET_COND_STATE(data->cond);
	if (state == S_START)
		return;

	flags = GET_COND_FLAG(data->cond);
	get_pname(pid, pname);

	if (state == S_LCDOFF && pm_cur_state == S_SLEEP &&
	    power_ops.get_power_lock() == POWER_UNLOCK)
		proc_change_state(data->cond, INTERNAL_LOCK_PM);

	if (data->timeout > 0) {
		/* To pass a pid_t data through the timer infrastructure
		 * without memory allocation, a pid_t data becomes typecast
		 * to intptr_t and void *(64bit) type. */
		cond_timeout_id = g_timeout_add_seconds(
				MSEC_TO_SEC((double)data->timeout),
				states[state].timeout_cb,
				(void*)((intptr_t)pid));
		if (!cond_timeout_id)
			_E("Failed to register display timer.");
	}

	holdkey_block = GET_COND_FLAG(data->cond) & PM_FLAG_BLOCK_HOLDKEY;

	tmp = find_node(state, pid);
	if (!tmp)
		add_node(state, pid, cond_timeout_id, holdkey_block);
	else {
		update_lock_timer(data, tmp, cond_timeout_id);
		tmp->holdkey_block = holdkey_block;
	}

	if (state == S_LCDOFF)
		set_process_active(true, pid);

	_I("[%s] locked by %5d with %u ms", states[state].name, pid, data->timeout);
	/* for debug */
	_SD("be requested LOCK info pname(%s), holdkeyblock(%d) flags(%d)",
	    pname, holdkey_block, flags);
	set_lock_time(pid, pname, state);

	device_notify(DEVICE_NOTIFIER_DISPLAY_LOCK, (void *)&value);
}

static void proc_condition_unlock(PMMsg *data)
{
	pid_t pid = data->pid;
	enum state_t state;
	PmLockNode *tmp;
	char pname[PATH_MAX];
	bool value = false;
	unsigned int flags;

	state = GET_COND_STATE(data->cond);
	if (!state)
		return;

	flags = GET_COND_FLAG(data->cond);
	get_pname(pid, pname);

	tmp = find_node(state, pid);
	del_node(state, tmp);

	if (state == S_LCDOFF)
		set_process_active(false, pid);

	_I("[%s] unlocked by %5d", states[state].name, pid);
	/* for debug */
	_SD("be requested UNLOCK info pname(%s) flag(%d)", pname, flags);
	set_unlock_time(pid, state);

	device_notify(DEVICE_NOTIFIER_DISPLAY_LOCK, (void *)&value);
}

static int proc_condition(PMMsg *data)
{
	unsigned int flags;

	if (IS_COND_REQUEST_LOCK(data->cond))
		proc_condition_lock(data);

	if (IS_COND_REQUEST_UNLOCK(data->cond))
		proc_condition_unlock(data);

	if (!display_conf.timeout_enable)
		return 0;

	flags = GET_COND_FLAG(data->cond);
	if (flags == 0) {
		/* guard time for suspend */
		if (pm_cur_state == S_LCDOFF)
			reset_timeout(states[S_LCDOFF].timeout);
	} else {
		if (flags & PM_FLAG_RESET_TIMER)
			reset_timeout(states[pm_cur_state].timeout);
	}

	if (!timeout_src_id)
		states[pm_cur_state].trans(EVENT_TIMEOUT);

	return 0;
}

/* If some changed, return 1 */
int check_processes(enum state_t prohibit_state)
{
	dd_list *elem, *next;
	PmLockNode *t = NULL;
	int ret = 0;

	DD_LIST_FOREACH_SAFE(cond_head[prohibit_state], elem, next, t) {
		if (t->pid < INTERNAL_LOCK_BASE && kill(t->pid, 0) == -1) {
			_E("%d process does not exist, delete the REQ"
				" - prohibit state %d ",
				t->pid, prohibit_state);
			if (t->pid == custom_change_pid) {
				get_lcd_timeout_from_settings();
				custom_normal_timeout = custom_dim_timeout = 0;
				custom_change_pid = -1;
			}
			ret = 1;
			set_unlock_time(t->pid, prohibit_state);
			del_node(prohibit_state, t);
		}
	}

	return ret;
}

int check_holdkey_block(enum state_t state)
{
	dd_list *elem;
	PmLockNode *t = NULL;
	int ret = 0;

	_I("Check holdkey block: state of %s", states[state].name);

	if (custom_holdkey_block == true) {
		_I("Custom hold key blocked by pid(%d).",
			custom_change_pid);
		return 1;
	}

	DD_LIST_FOREACH(cond_head[state], elem, t) {
		if (t->holdkey_block == true) {
			ret = 1;
			_I("Hold key blocked by pid(%d).", t->pid);
			break;
		}
	}

	return ret;
}

int delete_condition(enum state_t state)
{
	dd_list *elem, *next;
	PmLockNode *t = NULL;

	_I("delete condition : state of %s", states[state].name);

	if (!cond_head[state])
		return 0;

	DD_LIST_FOREACH_SAFE(cond_head[state], elem, next, t) {
		if (t->timeout_id > 0) {
			g_source_remove(t->timeout_id);
			t->timeout_id = 0;
		}
		if (state == S_LCDOFF)
			set_process_active(false, t->pid);
		_I("delete node of pid(%d)", t->pid);
		set_unlock_time(t->pid, state);
		del_node(state, t);
	}

	DD_LIST_FREE_LIST(cond_head[state]);
	cond_head[state] = NULL;

	return 0;
}

void update_lcdoff_source(int source)
{
	int ret;

	switch (source) {
	case VCONFKEY_PM_LCDOFF_BY_TIMEOUT:
		_I("LCD OFF by timeout.");
		break;
	case VCONFKEY_PM_LCDOFF_BY_POWERKEY:
		_I("LCD OFF by powerkey.");
		break;
	default:
		_E("Invalid value(%d).", source);
		return;
	}
	ret = vconf_set_int(VCONFKEY_PM_LCDOFF_SOURCE, source);
	if (ret < 0)
		_E("Failed to set vconf value for lcd off source: %d", vconf_get_ext_errno());
}

#ifdef ENABLE_PM_LOG

typedef struct _pm_history {
	time_t time;
	enum pm_log_type log_type;
	int keycode;
} pm_history;

static int max_history_count = MAX_LOG_COUNT;
static pm_history pm_history_log[MAX_LOG_COUNT] = {{0, }, };
static int history_count = 0;

static const char history_string[PM_LOG_MAX][15] = {
	"PRESS", "LONG PRESS", "RELEASE", "LCD ON", "LCD ON COMPL", "LCD ON FAIL",
	"LCD DIM", "LCD DIM FAIL", "LCD OFF", "LCD OFF COMPL", "LCD OFF FAIL",
	"LCD FAIL", "SLEEP"};

void pm_history_init()
{
	memset(pm_history_log, 0x0, sizeof(pm_history_log));
	history_count = 0;
	max_history_count = MAX_LOG_COUNT;
}

void pm_history_save(enum pm_log_type log_type, int code)
{
	time_t now;

	time(&now);
	pm_history_log[history_count].time = now;
	pm_history_log[history_count].log_type = log_type;
	pm_history_log[history_count].keycode = code;
	history_count++;

	if (history_count >= max_history_count)
		history_count = 0;
}

void pm_history_print(int fd, int count)
{
	int start_index, index, i;
	int ret;
	char buf[255];
	char time_buf[30];

	if (count <= 0 || count > max_history_count)
		return;

	start_index = (history_count - count + max_history_count)
		    % max_history_count;

	for (i = 0; i < count; i++) {
		index = (start_index + i) % max_history_count;

		if (pm_history_log[index].time == 0)
			continue;

		if (pm_history_log[index].log_type < PM_LOG_MIN ||
		    pm_history_log[index].log_type >= PM_LOG_MAX)
			continue;
		ctime_r(&pm_history_log[index].time, time_buf);
		snprintf(buf, sizeof(buf), "[%3d] %15s %3d %s",
			index,
			history_string[pm_history_log[index].log_type],
			pm_history_log[index].keycode,
			time_buf);
		ret = write(fd, buf, strlen(buf));
		if (ret < 0)
			_E("Write() failed: %d", errno);
	}
}
#endif

void print_info(int fd)
{
	int s_index = 0;
	char buf[255];
	int i = 1;
	int ret;
	char pname[PATH_MAX];
	PmLockNode *t;
	dd_list *elem;
	char time_buf[30];

	if (fd < 0)
		return;

	snprintf(buf, sizeof(buf),
		"\n==========================================="
		"===========================\n");
	ret = write(fd, buf, strlen(buf));
	if (ret < 0)
		_E("Write() failed: %d", errno);
	snprintf(buf, sizeof(buf), "Timeout Info: Run[%dms] Dim[%dms] Off[%dms]\n",
		 states[S_NORMAL].timeout,
		 states[S_LCDDIM].timeout, states[S_LCDOFF].timeout);
	ret = write(fd, buf, strlen(buf));
	if (ret < 0)
		_E("Write() failed: %d", errno);

	snprintf(buf, sizeof(buf), "Tran. Locked : %s %s %s\n",
		 (trans_condition & MASK_NORMAL) ? states[S_NORMAL].name : "-",
		 (trans_condition & MASK_DIM) ? states[S_LCDDIM].name : "-",
		 (trans_condition & MASK_OFF) ? states[S_LCDOFF].name : "-");
	ret = write(fd, buf, strlen(buf));
	if (ret < 0)
		_E("Write() failed: %d", errno);

	snprintf(buf, sizeof(buf), "Current State: %s\n",
		states[pm_cur_state].name);
	ret = write(fd, buf, strlen(buf));
	if (ret < 0)
		_E("Write() failed: %d", errno);

	snprintf(buf, sizeof(buf), "Current Lock Conditions: \n");
	ret = write(fd, buf, strlen(buf));
	if (ret < 0)
		_E("Write() failed: %d", errno);

	for (s_index = S_NORMAL; s_index < S_END; s_index++) {
		DD_LIST_FOREACH(cond_head[s_index], elem, t) {
			get_pname((pid_t)t->pid, pname);
			ctime_r(&t->time, time_buf);
			snprintf(buf, sizeof(buf),
				 " %d: [%s] locked by pid %d %s %s",
				 i++, states[s_index].name, t->pid, pname, time_buf);
			ret = write(fd, buf, strlen(buf));
			if (ret < 0)
				_E("Write() failed: %d", errno);
		}
	}

	print_lock_info_list(fd);

#ifdef ENABLE_PM_LOG
	pm_history_print(fd, 250);
#endif
}

void save_display_log(char *path)
{
	int fd, ret;
	char buf[255];
	time_t now_time;
	char time_buf[30];

	_D("internal state is saved!");

	time(&now_time);
	ctime_r(&now_time, time_buf);

	fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644);
	if (fd != -1) {
		snprintf(buf, sizeof(buf),
			"\npm_state_log now-time : %d(s) %s\n\n",
			(int)now_time, time_buf);
		ret = write(fd, buf, strlen(buf));
		if (ret < 0)
			_E("write() failed (%d)", errno);

		snprintf(buf, sizeof(buf), "pm_status_flag: %x\n", pm_status_flag);
		ret = write(fd, buf, strlen(buf));
		if (ret < 0)
			_E("write() failed (%d)", errno);

		if (disp_plgn.get_lock_screen_state ) {
			snprintf(buf, sizeof(buf), "screen lock status : %d\n",
				disp_plgn.get_lock_screen_state());
			ret = write(fd, buf, strlen(buf));
			if (ret < 0)
				_E("write() failed (%d)", errno);
		}
		print_info(fd);
		close(fd);
	}

	fd = open("/dev/console", O_WRONLY);
	if (fd != -1) {
		print_info(fd);
		close(fd);
	}
}

/* SIGHUP signal handler
 * For debug... print info to syslog
 */
static void sig_hup(int signo)
{
	_I("received sig hub %d", signo);

	pm_save_logdump();
}

int check_lcdoff_direct(void)
{
	int ret, lock, cradle;
	int hdmi_state;

	if (pm_old_state != S_NORMAL)
		return false;

	if (pm_cur_state != S_LCDDIM)
		return false;

	if (!display_conf.dimming)
		return true;

	lock = __get_lock_screen_state();
	if (lock != VCONFKEY_IDLE_LOCK && hallic_open)
		return false;

	hdmi_state = extcon_get_status(EXTCON_CABLE_HDMI);
	if (hdmi_state)
		return false;

	ret = vconf_get_int(VCONFKEY_SYSMAN_CRADLE_STATUS, &cradle);
	if (ret >= 0 && cradle == DOCK_SOUND)
		return false;
	else if (ret < 0)
		_E("Failed to get vconf value for cradle status: %d", vconf_get_ext_errno());

	_D("Goto LCDOFF direct: lock(%d) hdmi(%d) cradle(%d).", lock, hdmi_state, cradle);

	return true;
}

static int __check_lcdoff_lock_state(void)
{
	if (cond_head[S_LCDOFF] != NULL)
		return true;

	return false;
}

/*
 * default transition function
 *   1. call check
 *   2. transition
 *   3. call enter action function
 */
static int default_trans(int evt)
{
	struct state *st = &states[pm_cur_state];
	int next_state;

	next_state = (enum state_t)trans_table[pm_cur_state][evt];

	/* check conditions */
	while (st->check && !st->check(pm_cur_state, next_state)) {
		/* There is a condition. */
		_I("%s locked. Trans to %s failed.", states[pm_cur_state].name,
		       states[next_state].name);
		if (!check_processes(pm_cur_state)) {
			/* This is valid condition
			 * The application that sent the condition is running now. */
			return -1;
		}
	}

	/* state transition */
	pm_old_state = pm_cur_state;
	pm_cur_state = next_state;
	st = &states[pm_cur_state];

	/* enter action */
	if (st->action) {
		if (pm_cur_state == S_LCDOFF)
			update_lcdoff_source(VCONFKEY_PM_LCDOFF_BY_TIMEOUT);

		if (pm_cur_state == S_NORMAL || pm_cur_state == S_LCDOFF)
			if (set_custom_lcdon_timeout(0) == true)
				update_display_time();

		if (check_lcdoff_direct() == true) {
			/* enter next state directly */
			states[pm_cur_state].trans(EVENT_TIMEOUT);
		} else {
			st->action(st->timeout);
		}
	}

	return 0;
}

static gboolean lcd_on_expired(void *data)
{
	int lock_state, ret;

	if (lock_timeout_id)
		lock_timeout_id = 0;

	/* check state of lock */
	ret = vconf_get_int(VCONFKEY_IDLE_LOCK_STATE, &lock_state);
	if (ret > 0 && lock_state == VCONFKEY_IDLE_LOCK)
		return G_SOURCE_REMOVE;
	else if (ret < 0)
		_E("Failed to get vconf value for idle lock state: %d", vconf_get_ext_errno());

	/* lock screen is not launched yet, but lcd is on */
	if (check_lcd_is_on() == false)
		lcd_on_procedure(LCD_NORMAL, NORMAL_MODE);

	return G_SOURCE_REMOVE;
}

static inline void stop_lock_timer(void)
{
	if (lock_timeout_id) {
		g_source_remove(lock_timeout_id);
		lock_timeout_id = 0;
	}
}

static void check_lock_screen(void)
{
	int lock_state, ret;

	stop_lock_timer();

	/* check state of lock */
	ret = vconf_get_int(VCONFKEY_IDLE_LOCK_STATE, &lock_state);
	if (ret < 0 || lock_state == VCONFKEY_IDLE_LOCK) {
		if (ret < 0)
			_E("Failed to get vconf value for idle lock state: %d", vconf_get_ext_errno());
		goto lcd_on;
	}

	/* Use time to check lock is done. */
	lock_timeout_id = g_timeout_add(display_conf.lock_wait_time,
	    lcd_on_expired, NULL);

	return;

lcd_on:
	if (check_lcd_is_on() == false)
		lcd_on_procedure(LCD_NORMAL, NORMAL_MODE);
}

/* default enter action function */
static int default_action(int timeout)
{
	int wakeup_count = -1;
	time_t now;
	double diff;
	static time_t last_update_time = 0;
	static int last_timeout = 0;
	struct timeval now_tv;

	if (status != DEVICE_OPS_STATUS_START) {
		_E("Display is not started.");
		return -EINVAL;
	}

	if (pm_cur_state != S_SLEEP && !(pm_cur_state == S_LCDOFF && display_conf.sleep_support == false)) {
		if (pm_cur_state == S_NORMAL &&
		    lcdon_tv.tv_sec != 0) {
			gettimeofday(&now_tv, NULL);
			timeout -= DIFF_TIMEVAL_MS(now_tv, lcdon_tv);
			lcdon_tv.tv_sec = 0;
		}
		/* set timer with current state timeout */
		reset_timeout(timeout);

		if (pm_cur_state == S_NORMAL) {
			time(&last_update_time);
			last_timeout = timeout;
		} else {
			_I("Timout set: %s state %d ms",
			    states[pm_cur_state].name, timeout);
		}
	}

	if (pm_cur_state != pm_old_state && pm_cur_state != S_SLEEP) {
		if (power_ops.get_power_lock_support()) {
			broadcast_pm_wakeup();
			power_ops.power_lock();
		}
		set_setting_pmstate(pm_cur_state);
		device_notify(DEVICE_NOTIFIER_LCD, (void *)&pm_cur_state);
	}

	if (pm_old_state == S_NORMAL && pm_cur_state != S_NORMAL) {
		time(&now);
		diff = difftime(now, last_update_time);
		_I("S_NORMAL is changed to %s (timeout=%d ms diff=%.0f s).",
		    states[pm_cur_state].name, last_timeout, diff);
	}

	switch (pm_cur_state) {
	case S_NORMAL:
		/*
		 * normal state : backlight on and restore
		 * the previous brightness
		 */
		if (pm_old_state == S_LCDOFF || pm_old_state == S_SLEEP)
			check_lock_screen();
		else if (pm_old_state == S_LCDDIM)
			backlight_ops.update();

		if (check_lcd_is_on() == false)
			lcd_on_procedure(LCD_NORMAL, NORMAL_MODE);
		break;

	case S_LCDDIM:
		if (pm_old_state == S_NORMAL &&
		    backlight_ops.get_custom_status())
			backlight_ops.save_custom_brightness();
		/* lcd dim state : dim the brightness */
		backlight_ops.dim();

		if (pm_old_state == S_LCDOFF || pm_old_state == S_SLEEP)
			lcd_on_procedure(LCD_DIM, NORMAL_MODE);
		break;

	case S_LCDOFF:
		if (pm_old_state != S_SLEEP && pm_old_state != S_LCDOFF) {
			stop_lock_timer();
			/* lcd off state : turn off the backlight */
			if (backlight_ops.get_lcd_power() == DPMS_ON)
				lcd_off_procedure(LCD_OFF_BY_TIMEOUT);
		}

		if (backlight_ops.get_lcd_power() == DPMS_ON
		    || lcd_paneloff_mode)
			lcd_off_procedure(LCD_OFF_BY_TIMEOUT);
		break;

	case S_SLEEP:
		if (pm_old_state != S_SLEEP && pm_old_state != S_LCDOFF)
			stop_lock_timer();

		if (backlight_ops.get_lcd_power() == DPMS_ON)
			lcd_off_procedure(LCD_OFF_BY_TIMEOUT);

		if (!power_ops.get_power_lock_support()) {
			/* sleep state : set system mode to SUSPEND */
			if (power_ops.get_wakeup_count(&wakeup_count) < 0)
				_E("Wakeup count read error.");

			if (wakeup_count < 0) {
				_I("Wakup Event. Can not enter suspend mode.");
				goto go_lcd_off;
			}

			if (power_ops.set_wakeup_count(wakeup_count) < 0) {
				_E("Wakeup count write error.");
				goto go_lcd_off;
			}
		}
		goto go_suspend;
	}

	return 0;

go_suspend:
#ifdef ENABLE_PM_LOG
	pm_history_save(PM_LOG_SLEEP, pm_cur_state);
#endif
	broadcast_pm_suspend();
	if (power_ops.get_power_lock_support()) {
		if (power_ops.enable_autosleep)
			power_ops.enable_autosleep();

		if (power_ops.power_unlock() < 0)
			_E("Power unlock state error.");
	} else {
		power_ops.suspend();
		_I("system wakeup!!");
		system_wakeup_flag = true;
		/* Resume !! */
		if (power_ops.check_wakeup_src() == EVENT_DEVICE)
			/* system waked up by devices */
			states[pm_cur_state].trans(EVENT_DEVICE);
		else
			/* system waked up by user input */
			states[pm_cur_state].trans(EVENT_INPUT);
	}
	return 0;

go_lcd_off:
	if (!power_ops.get_power_lock_support()) {
		/* Resume !! */
		states[pm_cur_state].trans(EVENT_DEVICE);
	}
	return 0;
}

/*
 * default check function
 *   return
 *    0 : can't transit, others : transitable
 */
static int default_check(int curr, int next)
{
	int trans_cond;

	makeup_trans_condition();

	trans_cond = trans_condition & MASK_BIT;

	if (next == S_NORMAL) /* S_NORMAL is exceptional */
		return 1;

	switch (curr) {
	case S_NORMAL:
		trans_cond = trans_cond & MASK_NORMAL;
		break;
	case S_LCDDIM:
		trans_cond = trans_cond & MASK_DIM;
		break;
	case S_LCDOFF:
		trans_cond = trans_cond & MASK_OFF;
		break;
	default:
		trans_cond = 0;
		break;
	}

	if (trans_cond != 0) {
		print_node(curr);
		return 0;
	}

	return 1;		/* transitable */
}

static void default_saving_mode(int onoff)
{
	if (onoff)
		pm_status_flag |= PWRSV_FLAG;
	else
		pm_status_flag &= ~PWRSV_FLAG;

	if (pm_cur_state == S_NORMAL)
		backlight_ops.update();
}

static int poll_callback(int condition, PMMsg *data)
{
	static time_t last_t;
	time_t now;

	if (status != DEVICE_OPS_STATUS_START) {
		_E("Display logic is not started.");
		return -ECANCELED;
	}

	if (condition == INPUT_POLL_EVENT) {
		if (pm_cur_state == S_LCDOFF || pm_cur_state == S_SLEEP)
			_I("Input event signal at Display Off");
		time(&now);
		if (last_t != now ||
		    pm_cur_state == S_LCDOFF ||
		    pm_cur_state == S_SLEEP) {
			states[pm_cur_state].trans(EVENT_INPUT);
			last_t = now;
		}
	}

	if (condition == PM_CONTROL_EVENT) {
		proc_condition(data);

		if (IS_COND_REQUEST_CHANGE(data->cond))
			proc_change_state(data->cond, data->pid);
	}

	return 0;
}

static int update_setting(int key_idx, int val)
{
	char buf[PATH_MAX];
	int ret;

	switch (key_idx) {
	case SETTING_TO_NORMAL:
		update_display_time();
		states[pm_cur_state].trans(EVENT_INPUT);
		break;
	case SETTING_HALLIC_OPEN:
		hallic_open = val;
		update_display_time();
		if (pm_cur_state == S_NORMAL || pm_cur_state == S_LCDDIM)
			states[pm_cur_state].trans(EVENT_INPUT);
		else if (pm_cur_state == S_SLEEP && hallic_open)
			proc_change_state(S_LCDOFF, INTERNAL_LOCK_HALLIC);
		break;
	case SETTING_LOW_BATT:
		if (low_battery_state(val)) {
			if (!(pm_status_flag & CHRGR_FLAG))
				power_saving_func(true);
			pm_status_flag |= LOWBT_FLAG;
		} else {
			if (pm_status_flag & PWRSV_FLAG)
				power_saving_func(false);
			pm_status_flag &= ~LOWBT_FLAG;
			pm_status_flag &= ~BRTCH_FLAG;
			ret = vconf_set_bool(VCONFKEY_PM_BRIGHTNESS_CHANGED_IN_LPM, false);
			if (ret < 0)
				_E("Failed to set vconf value for brightness changed in lpm: %d", vconf_get_ext_errno());
		}
		break;
	case SETTING_CHARGING:
		if (val) {
			if (pm_status_flag & LOWBT_FLAG) {
				power_saving_func(false);
				pm_status_flag &= ~LOWBT_FLAG;
			}
			pm_status_flag |= CHRGR_FLAG;
		} else {
			int bat_state;
			ret = vconf_get_int(VCONFKEY_SYSMAN_BATTERY_STATUS_LOW,
				&bat_state);
			if (ret < 0) {
				bat_state = VCONFKEY_SYSMAN_BAT_NORMAL;
				_E("Failed to get vconf value for battery status low: %d", vconf_get_ext_errno());
			}
			if (low_battery_state(bat_state)) {
				power_saving_func(true);
				pm_status_flag |= LOWBT_FLAG;
			}
			pm_status_flag &= ~CHRGR_FLAG;
		}
		break;
	case SETTING_BRT_LEVEL:
		if (pm_status_flag & PWRSV_FLAG) {
			pm_status_flag |= BRTCH_FLAG;
			ret = vconf_set_bool(VCONFKEY_PM_BRIGHTNESS_CHANGED_IN_LPM, true);
			if (ret < 0)
				_E("Failed to set vconf value for brightness changed in lpm: %d", vconf_get_ext_errno());
			_I("Brightness changed in low battery,"
				"escape dim state.");
		}
		backlight_ops.set_default_brt(val);
		snprintf(buf, sizeof(buf), "%d", val);
		_D("Brightness set in bl(%d).", val);
		launch_evenif_exist(SET_BRIGHTNESS_IN_BOOTLOADER, buf);
		break;
	case SETTING_LOCK_SCREEN:
		set_lock_screen_state(val);
		if (val == VCONFKEY_IDLE_UNLOCK) {
			if (CHECK_OPS(keyfilter_ops, backlight_enable))
				keyfilter_ops->backlight_enable(false);
		}

		/* LCD on if lock screen show before waiting time */
		if (pm_cur_state == S_NORMAL &&
		    val == VCONFKEY_IDLE_LOCK &&
		    backlight_ops.get_lcd_power() != DPMS_ON)
			lcd_on_procedure(LCD_NORMAL, LCD_ON_BY_EVENT);
		stop_lock_timer();
		update_display_time();
		if (pm_cur_state == S_NORMAL)
			states[pm_cur_state].trans(EVENT_INPUT);
		break;
	case SETTING_LOCK_SCREEN_BG:
		set_lock_screen_bg_state(val);
		update_display_time();
		if (pm_cur_state == S_NORMAL)
			states[pm_cur_state].trans(EVENT_INPUT);
		break;
	case SETTING_POWEROFF:
		switch (val) {
		case POWEROFF_TYPE_NONE:
			pm_status_flag &= ~PWROFF_FLAG;
			break;
		case POWEROFF_TYPE_DIRECT:
		case POWEROFF_TYPE_RESTART:
			pm_status_flag |= PWROFF_FLAG;
			break;
		}
		break;
	case SETTING_POWER_CUSTOM_BRIGHTNESS:
		if (val == VCONFKEY_PM_CUSTOM_BRIGHTNESS_ON)
			backlight_ops.set_custom_status(true);
		else
			backlight_ops.set_custom_status(false);
		break;

	default:
		return -1;
	}
	return 0;
}

static void check_seed_status(void)
{
	int ret = -1;
	int tmp = 0;
	int bat_state;
	int brt = 0;
	int lock_state;

	/* Charging check */
	if ((get_charging_status(&tmp) == 0) && (tmp > 0))
		pm_status_flag |= CHRGR_FLAG;

	ret = get_setting_brightness(&tmp);
	if (ret != 0 || (tmp < PM_MIN_BRIGHTNESS || tmp > PM_MAX_BRIGHTNESS)) {
		_I("Failed to read vconf value for brightness.");
		brt = PM_DEFAULT_BRIGHTNESS;
		if (tmp < PM_MIN_BRIGHTNESS || tmp > PM_MAX_BRIGHTNESS) {
			ret = vconf_set_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, brt);
			if (ret < 0)
				_E("Failed to set vconf value for lcd brightness: %d", vconf_get_ext_errno());
		}
		tmp = brt;
	}
	_I("Set brightness(%d) from setting app.", tmp);
	backlight_ops.set_default_brt(tmp);
	backlight_ops.set_brightness(tmp);

	ret = vconf_get_int(VCONFKEY_SYSMAN_BATTERY_STATUS_LOW, &bat_state);
	if (ret < 0) {
		bat_state = VCONFKEY_SYSMAN_BAT_NORMAL;
		_E("Failed to get vconf value for battery status low: %d", vconf_get_ext_errno());
	}
	if (low_battery_state(bat_state)) {
		if (!(pm_status_flag & CHRGR_FLAG)) {
			power_saving_func(true);
			pm_status_flag |= LOWBT_FLAG;
		}
	}

	/* lock screen check */
	ret = vconf_get_int(VCONFKEY_IDLE_LOCK_STATE, &lock_state);
	if (ret < 0) {
		lock_state = -1;
		_E("Failed to get vconf value for idle lock state: %d", vconf_get_ext_errno());
	}
	set_lock_screen_state(lock_state);
	if (lock_state == VCONFKEY_IDLE_LOCK) {
		states[S_NORMAL].timeout = lock_screen_timeout;
		_I("LCD NORMAL timeout(%d ms) is set"
			" for lock screen.", lock_screen_timeout);
	}

	return;
}

static void init_lcd_operation(void)
{
	const struct device_ops *ops = NULL;

	ops = find_device("display");
	if (!check_default(ops))
		DD_LIST_APPEND(lcdon_ops, ops);

	ops = find_device("touchkey");
	if (!check_default(ops))
		DD_LIST_APPEND(lcdon_ops, ops);

	ops = find_device("touchscreen");
	if (!check_default(ops))
		DD_LIST_APPEND(lcdon_ops, ops);
}

static void exit_lcd_operation(void)
{
	dd_list *l = NULL;
	dd_list *l_next = NULL;
	const struct device_ops *ops = NULL;

	DD_LIST_FOREACH_SAFE(lcdon_ops, l, l_next, ops)
		DD_LIST_REMOVE_LIST(lcdon_ops, l);
}

enum {
	INIT_SETTING = 0,
	INIT_INTERFACE,
	INIT_POLL,
	INIT_FIFO,
	INIT_DBUS,
	INIT_END
};

static const char *errMSG[INIT_END] = {
	[INIT_SETTING] = "setting init error",
	[INIT_INTERFACE] = "lowlevel interface(sysfs or others) init error",
	[INIT_POLL] = "input devices poll init error",
	[INIT_FIFO] = "FIFO poll init error",
	[INIT_DBUS] = "d-bus init error",
};

int set_lcd_timeout(int on, int dim, int holdkey_block, const char *name)
{
	if (on == 0 && dim == 0) {
		_I("LCD timeout changed: default setting");
		custom_normal_timeout = custom_dim_timeout = 0;
	} else if (on < 0 || dim < 0) {
		_E("Failed to set value(on=%d dim=%d).", on, dim);
		return -EINVAL;
	} else {
		_I("LCD timeout changed: on=%ds dim=%ds", on, dim);
		custom_normal_timeout = SEC_TO_MSEC(on);
		custom_dim_timeout = SEC_TO_MSEC(dim);
	}
	/* Apply new backlight time */
	update_display_time();
	if (pm_cur_state == S_NORMAL)
		states[pm_cur_state].trans(EVENT_INPUT);

	if (holdkey_block) {
		custom_holdkey_block = true;
		_I("Hold key disabled.");
	} else {
		custom_holdkey_block = false;
		_I("Hold key enabled.");
	}

	if (custom_change_name) {
		free(custom_change_name);
		custom_change_name = 0;
	}

	if (custom_normal_timeout == 0 &&
	    custom_dim_timeout == 0 &&
	    !holdkey_block)
		return 0;

	custom_change_name = strndup(name, strlen(name));
	if (!custom_change_name) {
		_E("Failed to malloc.");
		custom_normal_timeout = custom_dim_timeout = 0;
		custom_holdkey_block = false;
		return -ENOMEM;
	}

	return 0;
}

void reset_lcd_timeout(GDBusConnection *conn,
	const gchar     *sender,
	const gchar     *unique_name,
	gpointer         data)
{
	if (!sender)
		return;

	if (!custom_change_name)
		return;

	if (strcmp(sender, custom_change_name))
		return;

	_I("reset lcd timeout: Set default timeout. sender=%s", sender);

	free(custom_change_name);
	custom_change_name = 0;
	custom_normal_timeout = custom_dim_timeout = 0;
	custom_holdkey_block = false;

	update_display_time();
	if (pm_cur_state == S_NORMAL)
		states[pm_cur_state].trans(EVENT_INPUT);
}

static int booting_done(void *data)
{
	static bool done = false;

	if (data != NULL) {
	done = *(int*)data;
		if (done)
			return 0;
		_I("booting done, unlock LCD_OFF");
		if (disp_plgn.pm_unlock_internal) {
			disp_plgn.pm_unlock_internal(INTERNAL_LOCK_BOOTING, LCD_NORMAL, PM_SLEEP_MARGIN);
			disp_plgn.pm_unlock_internal(INTERNAL_LOCK_BOOTING, LCD_OFF, PM_SLEEP_MARGIN);
		}
	}

	return 0;
}

static int process_background(void *data)
{
	pid_t pid;
	PmLockNode *node;

	pid = *(pid_t *)data;

	node = find_node(S_NORMAL, pid);
	if (node) {
		node->background = true;
		_I("%d pid is background, then PM will be unlocked LCD_NORMAL", pid);
	}

	return 0;
}

static int process_foreground(void *data)
{
	pid_t pid;
	PmLockNode *node;

	pid = *(pid_t *)data;

	node = find_node(S_NORMAL, pid);
	if (node) {
		node->background = false;
		_I("Process(%d) is background, then PM will be unlocked LCD_NORMAL.", pid);
	}

	return 0;
}

static int battery_health_changed(void *data)
{
	int health = DATA_VALUE_INT(data);

	_I("battery health change %d", health);

	if (health == HEALTH_GOOD) {
		pm_status_flag &= ~BATTERY_FLAG;
		pm_status_flag &= ~DIMSTAY_FLAG;
	} else if (health == HEALTH_LOW || health == HEALTH_HIGH || health == HEALTH_OVP) {
		pm_status_flag |= BATTERY_FLAG;
		pm_status_flag |= DIMSTAY_FLAG;
	}

	if (backlight_ops.get_lcd_power() == DPMS_ON)
		backlight_ops.update();

	return 0;
}

static int display_load_config(struct parse_result *result, void *user_data)
{
	struct display_config *c = user_data;

	_D("display_load_config: section=%s name=%s value=%s", result->section, result->name, result->value);

	if (!c)
		return -EINVAL;

	if (!MATCH(result->section, "Display"))
		return 0;

	if (MATCH(result->name, "LockScreenWaitingTime")) {
		SET_CONF(c->lock_wait_time, atof(result->value));
		_D("lock wait time is %.3f", c->lock_wait_time);
	} else if (MATCH(result->name, "LongPressInterval")) {
		SET_CONF(c->longpress_interval, atof(result->value));
		_D("long press interval is %.3f", c->longpress_interval);
	} else if (MATCH(result->name, "LightSensorSamplingInterval")) {
		SET_CONF(c->lightsensor_interval, atof(result->value));
		_D("lightsensor interval is %.3f", c->lightsensor_interval);
	} else if (MATCH(result->name, "LCDOffTimeout")) {
		SET_CONF(c->lcdoff_timeout, atoi(result->value));
		_D("lcdoff timeout is %d ms", c->lcdoff_timeout);
	} else if (MATCH(result->name, "BrightnessChangeStep")) {
		SET_CONF(c->brightness_change_step, atoi(result->value));
		_D("brightness change step is %d", c->brightness_change_step);
	} else if (MATCH(result->name, "LCDAlwaysOn")) {
		c->lcd_always_on = (MATCH(result->value, "yes") ? 1 : 0);
		_D("LCD always on is %d", c->lcd_always_on);
	} else if (MATCH(result->name, "Dimming")) {
		c->dimming = (MATCH(result->value, "yes") ? 1 : 0);
		 _D("Dimming is %d", c->dimming);
	} else if (MATCH(result->name, "ChangedFrameRateAllowed")) {
		if (strstr(result->value, "setting")) {
			c->framerate_app[REFRESH_SETTING] = 1;
			_D("framerate app is Setting");
		}
		if (strstr(result->value, "all")) {
			memset(c->framerate_app, 1, sizeof(c->framerate_app));
			_D("framerate app is All");
		}
	} else if (MATCH(result->name, "ControlDisplay")) {
		c->control_display = (MATCH(result->value, "yes") ? 1 : 0);
		_D("ControlDisplay is %d", c->control_display);
	} else if (MATCH(result->name, "PowerKeyDoublePressSupport")) {
		c->powerkey_doublepress = (MATCH(result->value, "yes") ? 1 : 0);
		_D("PowerKeyDoublePressSupport is %d", c->powerkey_doublepress);
	} else if (MATCH(result->name, "AccelSensorOn")) {
		c->accel_sensor_on = (MATCH(result->value, "yes") ? 1 : 0);
		_D("AccelSensorOn is %d", c->accel_sensor_on);
	} else if (MATCH(result->name, "ContinuousSampling")) {
		c->continuous_sampling = (MATCH(result->value, "yes") ? 1 : 0);
		_D("ContinuousSampling is %d", c->continuous_sampling);
	} else if (MATCH(result->name, "TimeoutEnable")) {
		c->timeout_enable = (MATCH(result->value, "yes") ? true : false);
		_D("Timeout is %s", c->timeout_enable ? "enalbed" : "disabled");
	} else if (MATCH(result->name, "InputSupport")) {
		c->input_support = (MATCH(result->value, "yes") ? true : false);
		_D("Input is %s", c->input_support ? "supported" : "NOT supported");
	} else if (MATCH(result->name, "LockCheckTimeout")) {
		SET_CONF(c->lockcheck_timeout, atoi(result->value));
		_D("LockCheckTimeout is %d", c->lockcheck_timeout);
	} else if (MATCH(result->name, "AODTSP")) {
		c->aod_tsp = (MATCH(result->value, "yes") ? true : false);
		_D("TSP control at is %d at aod", c->aod_tsp);
	} else if (MATCH(result->name, "SleepSupport")) {
		c->sleep_support = (MATCH(result->value, "yes") ? true : false);
		_D("SleepSupport is %d", c->sleep_support);
	}

	return 0;
}

static gboolean lcd_on_wm_ready(gpointer data)
{
	int timeout;

	if (!check_wm_ready())
		return G_SOURCE_CONTINUE;

	switch (pm_cur_state) {
	case S_NORMAL:
	case S_LCDDIM:
		lcd_on_procedure(LCD_NORMAL, LCD_ON_BY_EVENT);
		if (display_conf.timeout_enable) {
			timeout = states[S_NORMAL].timeout;
			/* check minimun lcd on time */
			if (timeout < SEC_TO_MSEC(DEFAULT_NORMAL_TIMEOUT))
				timeout = SEC_TO_MSEC(DEFAULT_NORMAL_TIMEOUT);
			reset_timeout(timeout);
		}
		break;
	default:
		break;
	}

	return G_SOURCE_REMOVE;
}

static void add_timer_for_wm_ready(void)
{
	guint id = g_timeout_add(500/* milliseconds */, lcd_on_wm_ready, NULL);
	if (id == 0)
		_E("Failed to add wm_ready timeout.");
}

/**
 * Power manager Main
 *
 */
static int display_probe(void *data)
{
	int ret;

	/**
	 * load display service
	 * if there is no display shared library,
	 * deviced does not provide any method and function of display.
	 */
	ret = display_service_load();
	if (ret)
		return ret;

	/* display_plugin instance initialization */
	init_pm_internal();
	disp_plgn.check_lcdoff_lock_state = __check_lcdoff_lock_state;

	return 0;
}

static int input_init_handler(void)
{
	if (!display_conf.input_support)
		return 0;

	g_idle_add(init_input, NULL);

	return 0;
}

static void esd_action(void)
{
	const struct device_ops *touchscreen_ops = NULL;

	_I("ESD on");

	touchscreen_ops = find_device("touchscreen");

	if (!check_default(touchscreen_ops))
		touchscreen_ops->stop(NORMAL_MODE);
	backlight_ops.off(NORMAL_MODE);
	backlight_ops.on(NORMAL_MODE);
	if (!check_default(touchscreen_ops))
		touchscreen_ops->start(NORMAL_MODE);
}

static void lcd_uevent_changed(struct udev_device *dev)
{
	const char *devpath;
	const char *action;

	devpath = udev_device_get_devpath(dev);
	if (!devpath)
		return;

	if (!fnmatch(LCD_ESD_PATH, devpath, 0)) {
		action = udev_device_get_action(dev);
		if (!strcmp(action, UDEV_CHANGE))
			esd_action();
	}
}

static const struct uevent_handler lcd_uevent_ops = {
	.subsystem      = LCD_EVENT_SUBSYSTEM,
	.uevent_func    = lcd_uevent_changed,
	.data           = NULL,
};

static void display_init(void *data)
{
	int ret, i;
	unsigned int flags = (WITHOUT_STARTNOTI | FLAG_X_DPMS);
	int timeout = 0;
	bool wm_ready;

	_I("Start power manager.");

	signal(SIGHUP, sig_hup);

	power_saving_func = default_saving_mode;

	/* load configutation */
	ret = config_parse(DISPLAY_CONF_FILE, display_load_config, &display_conf);
	if (ret < 0)
		_W("Failed to load '%s', use default value: %d",
		    DISPLAY_CONF_FILE, ret);

	register_kernel_uevent_control(&lcd_uevent_ops);

	register_notifier(DEVICE_NOTIFIER_BOOTING_DONE, booting_done);
	register_notifier(DEVICE_NOTIFIER_PROCESS_BACKGROUND, process_background);
	register_notifier(DEVICE_NOTIFIER_PROCESS_FOREGROUND, process_foreground);
	register_notifier(DEVICE_NOTIFIER_BATTERY_HEALTH, battery_health_changed);
	register_notifier(DEVICE_NOTIFIER_DISPLAY_BRIGHTNESS, display_brightness_changed);
	register_notifier(DEVICE_NOTIFIER_LCD_AUTOBRT_SENSING, display_auto_brightness_sensing);

	init_save_userlock();

	for (i = INIT_SETTING; i < INIT_END; i++) {
		switch (i) {
		case INIT_SETTING:
			ret = init_setting(update_setting);
			break;
		case INIT_INTERFACE:
			if (display_conf.timeout_enable)
				get_lcd_timeout_from_settings();
			ret = init_sysfs(flags);
			break;
		case INIT_POLL:
			_I("input init");
			pm_callback = poll_callback;
			ret = input_init_handler();

			pm_lock_detector_init();
			break;
		case INIT_DBUS:
			_I("Dbus init.");
			ret = init_pm_dbus();
			break;
		}
		if (ret != 0) {
			_E("Failed to init: %s", errMSG[i]);
			break;
		}
	}

	if (i == INIT_END) {
		display_ops_init(NULL);
#ifdef ENABLE_PM_LOG
		pm_history_init();
#endif
		init_lcd_operation();
		check_seed_status();

		/* In smd test, TSP should be turned off if display panel is not existed. */
		if (backlight_ops.get_lcd_power() == -ENOENT) {
			_I("Display panel is not existed.");
			lcd_direct_control(DPMS_OFF, NORMAL_MODE);
			exit_lcd_operation();
		}

		/* wm_ready needs to be checked
		 * since display manager can be launched later than deviced.
		 * In the case, display cannot be turned on at the first booting */
		wm_ready = check_wm_ready();
		if (wm_ready)
			lcd_on_procedure(LCD_NORMAL, LCD_ON_BY_EVENT);
		else
			add_timer_for_wm_ready();

		if (display_conf.lcd_always_on) {
			_I("LCD always on.");
			trans_table[S_NORMAL][EVENT_TIMEOUT] = S_NORMAL;
		}

		if (flags & WITHOUT_STARTNOTI) {	/* start without noti */
			_I("Start Power managing without noti");
			if (power_ops.get_power_lock_support()) {
				broadcast_pm_wakeup();
				power_ops.power_lock();
			}
			pm_cur_state = S_NORMAL;
			ret = vconf_set_int(VCONFKEY_PM_STATE, pm_cur_state);
			if (ret < 0)
				_E("Failed to set vconf value for pm cur state: %d", vconf_get_ext_errno());

			status = DEVICE_OPS_STATUS_START;
			if (display_conf.timeout_enable) {
				timeout = states[S_NORMAL].timeout;
				/* check minimun lcd on time */
				if (timeout < SEC_TO_MSEC(DEFAULT_NORMAL_TIMEOUT))
					timeout = SEC_TO_MSEC(DEFAULT_NORMAL_TIMEOUT);

				if (disp_plgn.pm_lock_internal)
					disp_plgn.pm_lock_internal(INTERNAL_LOCK_BOOTING, LCD_NORMAL,
							STAY_CUR_STATE, timeout);
			}

			/*
			 * Lock lcd off until booting is done.
			 * deviced guarantees all booting script is executing.
			 * Last script of booting unlocks this suspend blocking state.
			 */
			if (disp_plgn.pm_lock_internal)
				disp_plgn.pm_lock_internal(INTERNAL_LOCK_BOOTING, LCD_OFF,
						STAY_CUR_STATE, BOOTING_DONE_WATING_TIME);
		}

		if (display_conf.input_support)
			if (CHECK_OPS(keyfilter_ops, init))
				keyfilter_ops->init();
	}
}

static void display_exit(void *data)
{
	int i = INIT_END;

	status = DEVICE_OPS_STATUS_STOP;

	/* Set current state to S_NORMAL */
	pm_cur_state = S_NORMAL;
	set_setting_pmstate(pm_cur_state);
	/* timeout is not needed */
	reset_timeout(TIMEOUT_NONE);

	if (CHECK_OPS(keyfilter_ops, exit))
		keyfilter_ops->exit();

	unregister_kernel_uevent_control(&lcd_uevent_ops);

	display_ops_exit(NULL);

	for (i = i - 1; i >= INIT_SETTING; i--) {
		switch (i) {
		case INIT_SETTING:
			exit_setting();
			break;
		case INIT_INTERFACE:
			exit_sysfs();
			break;
		case INIT_POLL:
			unregister_notifier(DEVICE_NOTIFIER_BOOTING_DONE, booting_done);
			unregister_notifier(DEVICE_NOTIFIER_PROCESS_BACKGROUND, process_background);
			unregister_notifier(DEVICE_NOTIFIER_PROCESS_FOREGROUND, process_foreground);
			unregister_notifier(DEVICE_NOTIFIER_BATTERY_HEALTH, battery_health_changed);
			unregister_notifier(DEVICE_NOTIFIER_DISPLAY_BRIGHTNESS, display_brightness_changed);

			exit_input();
			break;
		}
	}

	exit_lcd_operation();
	free_lock_info_list();

	/* free display service */
	display_service_free();

	_I("Stop power manager.");
}

static int display_start(enum device_flags flags)
{
	/* NORMAL MODE */
	if (flags & NORMAL_MODE) {
		if (flags & LCD_PANEL_OFF_MODE)
			/* standby on */
			backlight_ops.standby(true);
		else
			/* normal lcd on */
			backlight_ops.on(flags);

		return 0;
	}

	/* CORE LOGIC MODE */
	if (!(flags & CORE_LOGIC_MODE))
		return 0;

	if (status == DEVICE_OPS_STATUS_START)
		return -EALREADY;

	if (display_probe(NULL) < 0)
		return -EPERM;

	display_init(NULL);

	return 0;
}

static int display_stop(enum device_flags flags)
{
	/* NORMAL MODE */
	if (flags & NORMAL_MODE || flags & FORCE_OFF_MODE) {
		backlight_ops.off(flags);
		return 0;
	}

	/* CORE LOGIC MODE */
	if (!(flags & CORE_LOGIC_MODE))
		return 0;

	if (status == DEVICE_OPS_STATUS_STOP)
		return -EALREADY;

	display_exit(NULL);

	return 0;
}

static int display_status(void)
{
	return status;
}

static const struct device_ops display_device_ops = {
	.priority = DEVICE_PRIORITY_HIGH,
	DECLARE_NAME_LEN("display"),
	.probe    = display_probe,
	.init     = display_init,
	.exit     = display_exit,
	.start    = display_start,
	.stop     = display_stop,
	.status   = display_status,
};

DEVICE_OPS_REGISTER(&display_device_ops)

/**
 * @}
 */