summaryrefslogtreecommitdiffstats
path: root/services/java/com/android/server/am/ProcessTracker.java
blob: d78fd5c8b908dd6945a2d4307b2069a8a201e26e (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
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * 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.
 */

package com.android.server.am;

import android.app.AppGlobals;
import android.content.pm.IPackageManager;
import android.os.Parcel;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.text.format.DateFormat;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.AtomicFile;
import android.util.Slog;
import android.util.SparseArray;
import android.util.TimeUtils;
import android.webkit.WebViewFactory;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.ArrayUtils;
import com.android.server.ProcessMap;
import dalvik.system.VMRuntime;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

public final class ProcessTracker {
    static final String TAG = "ProcessTracker";
    static final boolean DEBUG = false;

    public static final int STATE_NOTHING = -1;
    public static final int STATE_PERSISTENT = 0;
    public static final int STATE_TOP = 1;
    public static final int STATE_IMPORTANT_FOREGROUND = 2;
    public static final int STATE_IMPORTANT_BACKGROUND = 3;
    public static final int STATE_BACKUP = 4;
    public static final int STATE_HEAVY_WEIGHT = 5;
    public static final int STATE_SERVICE = 6;
    public static final int STATE_SERVICE_RESTARTING = 7;
    public static final int STATE_RECEIVER = 8;
    public static final int STATE_HOME = 9;
    public static final int STATE_LAST_ACTIVITY = 10;
    public static final int STATE_CACHED_ACTIVITY = 11;
    public static final int STATE_CACHED_ACTIVITY_CLIENT = 12;
    public static final int STATE_CACHED_EMPTY = 13;
    public static final int STATE_COUNT = STATE_CACHED_EMPTY+1;

    static final int[] ALL_PROC_STATES = new int[] { STATE_PERSISTENT,
            STATE_TOP, STATE_IMPORTANT_FOREGROUND, STATE_IMPORTANT_BACKGROUND, STATE_BACKUP,
            STATE_HEAVY_WEIGHT, STATE_SERVICE, STATE_SERVICE_RESTARTING, STATE_RECEIVER,
            STATE_HOME, STATE_LAST_ACTIVITY, STATE_CACHED_ACTIVITY,
            STATE_CACHED_ACTIVITY_CLIENT, STATE_CACHED_EMPTY
    };

    static final int[] NON_CACHED_PROC_STATES = new int[] { STATE_PERSISTENT,
            STATE_TOP, STATE_IMPORTANT_FOREGROUND,
            STATE_IMPORTANT_BACKGROUND, STATE_BACKUP, STATE_HEAVY_WEIGHT,
            STATE_SERVICE, STATE_SERVICE_RESTARTING, STATE_RECEIVER, STATE_HOME
    };

    public static final int PSS_SAMPLE_COUNT = 0;
    public static final int PSS_MINIMUM = 1;
    public static final int PSS_AVERAGE = 2;
    public static final int PSS_MAXIMUM = 3;
    public static final int PSS_USS_MINIMUM = 4;
    public static final int PSS_USS_AVERAGE = 5;
    public static final int PSS_USS_MAXIMUM = 6;
    public static final int PSS_COUNT = PSS_USS_MAXIMUM+1;

    public static final int ADJ_NOTHING = -1;
    public static final int ADJ_MEM_FACTOR_NORMAL = 0;
    public static final int ADJ_MEM_FACTOR_MODERATE = 1;
    public static final int ADJ_MEM_FACTOR_LOW = 2;
    public static final int ADJ_MEM_FACTOR_CRITICAL = 3;
    public static final int ADJ_MEM_FACTOR_COUNT = ADJ_MEM_FACTOR_CRITICAL+1;
    public static final int ADJ_SCREEN_MOD = ADJ_MEM_FACTOR_COUNT;
    public static final int ADJ_SCREEN_OFF = 0;
    public static final int ADJ_SCREEN_ON = ADJ_SCREEN_MOD;
    public static final int ADJ_COUNT = ADJ_SCREEN_ON*2;

    static final int[] ALL_SCREEN_ADJ = new int[] { ADJ_SCREEN_OFF, ADJ_SCREEN_ON };
    static final int[] ALL_MEM_ADJ = new int[] { ADJ_MEM_FACTOR_NORMAL, ADJ_MEM_FACTOR_MODERATE,
            ADJ_MEM_FACTOR_LOW, ADJ_MEM_FACTOR_CRITICAL };

    // Most data is kept in a sparse data structure: an integer array which integer
    // holds the type of the entry, and the identifier for a long array that data
    // exists in and the offset into the array to find it.  The constants below
    // define the encoding of that data in an integer.

    // Where the "type"/"state" part of the data appears in an offset integer.
    static int OFFSET_TYPE_SHIFT = 0;
    static int OFFSET_TYPE_MASK = 0xff;

    // Where the "which array" part of the data appears in an offset integer.
    static int OFFSET_ARRAY_SHIFT = 8;
    static int OFFSET_ARRAY_MASK = 0xff;

    // Where the "index into array" part of the data appears in an offset integer.
    static int OFFSET_INDEX_SHIFT = 16;
    static int OFFSET_INDEX_MASK = 0xffff;

    static final String[] STATE_NAMES = new String[] {
            "Persistent", "Top       ", "Imp Fg    ", "Imp Bg    ",
            "Backup    ", "Heavy Wght", "Service   ", "Service Rs",
            "Receiver  ", "Home      ",
            "Last Act  ", "Cch Act   ", "Cch CliAct", "Cch Empty "
    };

    static final String[] ADJ_SCREEN_NAMES_CSV = new String[] {
            "off", "on"
    };

    static final String[] ADJ_MEM_NAMES_CSV = new String[] {
            "norm", "mod",  "low", "crit"
    };

    static final String[] STATE_NAMES_CSV = new String[] {
            "pers", "top", "impfg", "impbg", "backup", "heavy",
            "service", "service-rs", "receiver", "home", "lastact",
            "cch-activity", "cch-aclient", "cch-empty"
    };

    static final String[] ADJ_SCREEN_TAGS = new String[] {
            "0", "1"
    };

    static final String[] ADJ_MEM_TAGS = new String[] {
            "n", "m",  "l", "c"
    };

    static final String[] STATE_TAGS = new String[] {
            "p", "t", "f", "b", "u", "w",
            "s", "x", "r", "h", "l", "a", "c", "e"
    };

    // Map from process states to the states we track.
    static final int[] PROCESS_STATE_TO_STATE = new int[] {
            STATE_PERSISTENT,               // ActivityManager.PROCESS_STATE_PERSISTENT
            STATE_PERSISTENT,               // ActivityManager.PROCESS_STATE_PERSISTENT_UI
            STATE_TOP,                      // ActivityManager.PROCESS_STATE_TOP
            STATE_IMPORTANT_FOREGROUND,     // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
            STATE_IMPORTANT_BACKGROUND,     // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
            STATE_BACKUP,                   // ActivityManager.PROCESS_STATE_BACKUP
            STATE_HEAVY_WEIGHT,             // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
            STATE_SERVICE,                  // ActivityManager.PROCESS_STATE_SERVICE
            STATE_RECEIVER,                 // ActivityManager.PROCESS_STATE_RECEIVER
            STATE_HOME,                     // ActivityManager.PROCESS_STATE_HOME
            STATE_LAST_ACTIVITY,            // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
            STATE_CACHED_ACTIVITY,          // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
            STATE_CACHED_ACTIVITY_CLIENT,   // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
            STATE_CACHED_EMPTY,             // ActivityManager.PROCESS_STATE_CACHED_EMPTY
    };

    static final String CSV_SEP = "\t";

    static final int MAX_HISTORIC_STATES = 4;   // Maximum number of historic states we will keep.
    static final String STATE_FILE_PREFIX = "state-"; // Prefix to use for state filenames.
    static final String STATE_FILE_SUFFIX = ".bin"; // Suffix to use for state filenames.
    static final String STATE_FILE_CHECKIN_SUFFIX = ".ci"; // State files that have checked in.
    static long WRITE_PERIOD = 30*60*1000;      // Write file every 30 minutes or so.
    static long COMMIT_PERIOD = 24*60*60*1000;  // Commit current stats every day.

    final Object mLock;
    final File mBaseDir;
    State mState;
    boolean mCommitPending;
    boolean mShuttingDown;
    int mLastMemOnlyState = -1;
    boolean mMemFactorLowered;

    final ReentrantLock mWriteLock = new ReentrantLock();

    public static final class ProcessState {
        final State mState;
        final ProcessState mCommonProcess;
        final String mPackage;
        final int mUid;
        final String mName;

        int[] mDurationsTable;
        int mDurationsTableSize;

        //final long[] mDurations = new long[STATE_COUNT*ADJ_COUNT];
        int mCurState = STATE_NOTHING;
        long mStartTime;

        int mLastPssState = STATE_NOTHING;
        long mLastPssTime;
        int[] mPssTable;
        int mPssTableSize;

        int mNumStartedServices;

        int mNumExcessiveWake;
        int mNumExcessiveCpu;

        boolean mMultiPackage;

        long mTmpTotalTime;

        /**
         * Create a new top-level process state, for the initial case where there is only
         * a single package running in a process.  The initial state is not running.
         */
        public ProcessState(State state, String pkg, int uid, String name) {
            mState = state;
            mCommonProcess = this;
            mPackage = pkg;
            mUid = uid;
            mName = name;
        }

        /**
         * Create a new per-package process state for an existing top-level process
         * state.  The current running state of the top-level process is also copied,
         * marked as started running at 'now'.
         */
        public ProcessState(ProcessState commonProcess, String pkg, int uid, String name,
                long now) {
            mState = commonProcess.mState;
            mCommonProcess = commonProcess;
            mPackage = pkg;
            mUid = uid;
            mName = name;
            mCurState = commonProcess.mCurState;
            mStartTime = now;
        }

        ProcessState clone(String pkg, long now) {
            ProcessState pnew = new ProcessState(this, pkg, mUid, mName, now);
            if (mDurationsTable != null) {
                mState.mAddLongTable = new int[mDurationsTable.length];
                mState.mAddLongTableSize = 0;
                for (int i=0; i<mDurationsTableSize; i++) {
                    int origEnt = mDurationsTable[i];
                    int type = (origEnt>>OFFSET_TYPE_SHIFT)&OFFSET_TYPE_MASK;
                    int newOff = mState.addLongData(i, type, 1);
                    mState.mAddLongTable[i] = newOff | type;
                    mState.setLong(newOff, 0, mState.getLong(origEnt, 0));
                }
                pnew.mDurationsTable = mState.mAddLongTable;
                pnew.mDurationsTableSize = mState.mAddLongTableSize;
            }
            if (mPssTable != null) {
                mState.mAddLongTable = new int[mPssTable.length];
                mState.mAddLongTableSize = 0;
                for (int i=0; i<mPssTableSize; i++) {
                    int origEnt = mPssTable[i];
                    int type = (origEnt>>OFFSET_TYPE_SHIFT)&OFFSET_TYPE_MASK;
                    int newOff = mState.addLongData(i, type, PSS_COUNT);
                    mState.mAddLongTable[i] = newOff | type;
                    for (int j=0; j<PSS_COUNT; j++) {
                        mState.setLong(newOff, j, mState.getLong(origEnt, j));
                    }
                }
                pnew.mPssTable = mState.mAddLongTable;
                pnew.mPssTableSize = mState.mAddLongTableSize;
            }
            pnew.mNumExcessiveWake = mNumExcessiveWake;
            pnew.mNumExcessiveCpu = mNumExcessiveCpu;
            pnew.mNumStartedServices = mNumStartedServices;
            return pnew;
        }

        void resetSafely(long now) {
            mDurationsTable = null;
            mDurationsTableSize = 0;
            mStartTime = now;
            mLastPssState = STATE_NOTHING;
            mLastPssTime = 0;
            mPssTable = null;
            mPssTableSize = 0;
            mNumExcessiveWake = 0;
            mNumExcessiveCpu = 0;
        }

        void writeToParcel(Parcel out, long now) {
            commitStateTime(now);
            out.writeInt(mMultiPackage ? 1 : 0);
            out.writeInt(mDurationsTableSize);
            for (int i=0; i<mDurationsTableSize; i++) {
                if (DEBUG) Slog.i(TAG, "Writing in " + mName + " dur #" + i + ": "
                        + State.printLongOffset(mDurationsTable[i]));
                out.writeInt(mDurationsTable[i]);
            }
            out.writeInt(mPssTableSize);
            for (int i=0; i<mPssTableSize; i++) {
                if (DEBUG) Slog.i(TAG, "Writing in " + mName + " pss #" + i + ": "
                        + State.printLongOffset(mPssTable[i]));
                out.writeInt(mPssTable[i]);
            }
            out.writeInt(mNumExcessiveWake);
            out.writeInt(mNumExcessiveCpu);
        }

        boolean readFromParcel(Parcel in, boolean fully) {
            boolean multiPackage = in.readInt() != 0;
            if (fully) {
                mMultiPackage = multiPackage;
            }
            if (DEBUG) Slog.d(TAG, "Reading durations table...");
            mDurationsTable = mState.readTableFromParcel(in, mName, "durations");
            if (mDurationsTable == State.BAD_TABLE) {
                return false;
            }
            mDurationsTableSize = mDurationsTable != null ? mDurationsTable.length : 0;
            if (DEBUG) Slog.d(TAG, "Reading pss table...");
            mPssTable = mState.readTableFromParcel(in, mName, "pss");
            if (mPssTable == State.BAD_TABLE) {
                return false;
            }
            mPssTableSize = mPssTable != null ? mPssTable.length : 0;
            mNumExcessiveWake = in.readInt();
            mNumExcessiveCpu = in.readInt();
            return true;
        }

        /**
         * Update the current state of the given list of processes.
         *
         * @param state Current ActivityManager.PROCESS_STATE_*
         * @param memFactor Current mem factor constant.
         * @param now Current time.
         * @param pkgList Processes to update.
         */
        public void setState(int state, int memFactor, long now,
                ArrayMap<String, ProcessTracker.ProcessState> pkgList) {
            if (state < 0) {
                state = mNumStartedServices > 0
                        ? (STATE_SERVICE_RESTARTING+(memFactor*STATE_COUNT)) : STATE_NOTHING;
            } else {
                state = PROCESS_STATE_TO_STATE[state] + (memFactor*STATE_COUNT);
            }

            // First update the common process.
            mCommonProcess.setState(state, now);

            // If the common process is not multi-package, there is nothing else to do.
            if (!mCommonProcess.mMultiPackage) {
                return;
            }

            if (pkgList != null) {
                for (int ip=pkgList.size()-1; ip>=0; ip--) {
                    pullFixedProc(pkgList, ip).setState(state, now);
                }
            }
        }

        void setState(int state, long now) {
            if (mCurState != state) {
                //Slog.i(TAG, "Setting state in " + mName + "/" + mPackage + ": " + state);
                commitStateTime(now);
                mCurState = state;
            }
        }

        void commitStateTime(long now) {
            if (mCurState != STATE_NOTHING) {
                long dur = now - mStartTime;
                if (dur > 0) {
                    int idx = State.binarySearch(mDurationsTable, mDurationsTableSize, mCurState);
                    int off;
                    if (idx >= 0) {
                        off = mDurationsTable[idx];
                    } else {
                        mState.mAddLongTable = mDurationsTable;
                        mState.mAddLongTableSize = mDurationsTableSize;
                        off = mState.addLongData(~idx, mCurState, 1);
                        mDurationsTable = mState.mAddLongTable;
                        mDurationsTableSize = mState.mAddLongTableSize;
                    }
                    long[] longs = mState.mLongs.get((off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK);
                    longs[(off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK] += dur;
                }
            }
            mStartTime = now;
        }

        void incStartedServices(int memFactor, long now) {
            if (mCommonProcess != this) {
                mCommonProcess.incStartedServices(memFactor, now);
            }
            mNumStartedServices++;
            if (mNumStartedServices == 1 && mCurState == STATE_NOTHING) {
                setState(STATE_NOTHING, memFactor, now, null);
            }
        }

        void decStartedServices(int memFactor, long now) {
            if (mCommonProcess != this) {
                mCommonProcess.decStartedServices(memFactor, now);
            }
            mNumStartedServices--;
            if (mNumStartedServices == 0 && mCurState == STATE_SERVICE_RESTARTING) {
                setState(STATE_NOTHING, memFactor, now, null);
            } else if (mNumStartedServices < 0) {
                throw new IllegalStateException("Proc started services underrun: pkg="
                        + mPackage + " uid=" + mUid + " name=" + mName);
            }
        }

        public void addPss(long pss, long uss, boolean always) {
            if (!always) {
                if (mLastPssState == mCurState && SystemClock.uptimeMillis()
                        < (mLastPssTime+(30*1000))) {
                    return;
                }
            }
            mLastPssState = mCurState;
            mLastPssTime = SystemClock.uptimeMillis();
            if (mCurState != STATE_NOTHING) {
                int idx = State.binarySearch(mPssTable, mPssTableSize, mCurState);
                int off;
                if (idx >= 0) {
                    off = mPssTable[idx];
                } else {
                    mState.mAddLongTable = mPssTable;
                    mState.mAddLongTableSize = mPssTableSize;
                    off = mState.addLongData(~idx, mCurState, PSS_COUNT);
                    mPssTable = mState.mAddLongTable;
                    mPssTableSize = mState.mAddLongTableSize;
                }
                long[] longs = mState.mLongs.get((off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK);
                idx = (off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK;
                long count = longs[idx+PSS_SAMPLE_COUNT];
                if (count == 0) {
                    longs[idx+PSS_SAMPLE_COUNT] = 1;
                    longs[idx+PSS_MINIMUM] = pss;
                    longs[idx+PSS_AVERAGE] = pss;
                    longs[idx+PSS_MAXIMUM] = pss;
                    longs[idx+PSS_USS_MINIMUM] = uss;
                    longs[idx+PSS_USS_AVERAGE] = uss;
                    longs[idx+PSS_USS_MAXIMUM] = uss;
                } else {
                    longs[idx+PSS_SAMPLE_COUNT] = count+1;
                    if (longs[idx+PSS_MINIMUM] > pss) {
                        longs[idx+PSS_MINIMUM] = pss;
                    }
                    longs[idx+PSS_AVERAGE] = (long)(
                            ((longs[idx+PSS_AVERAGE]*(double)count)+pss) / (count+1) );
                    if (longs[idx+PSS_MAXIMUM] < pss) {
                        longs[idx+PSS_MAXIMUM] = pss;
                    }
                    if (longs[idx+PSS_USS_MINIMUM] > uss) {
                        longs[idx+PSS_USS_MINIMUM] = uss;
                    }
                    longs[idx+PSS_USS_AVERAGE] = (long)(
                            ((longs[idx+PSS_USS_AVERAGE]*(double)count)+uss) / (count+1) );
                    if (longs[idx+PSS_USS_MAXIMUM] < uss) {
                        longs[idx+PSS_USS_MAXIMUM] = uss;
                    }
                }
            }
        }

        public void reportExcessiveWake(ArrayMap<String, ProcessTracker.ProcessState> pkgList) {
            mCommonProcess.mNumExcessiveWake++;
            if (!mCommonProcess.mMultiPackage) {
                return;
            }

            for (int ip=pkgList.size()-1; ip>=0; ip--) {
                pullFixedProc(pkgList, ip).mNumExcessiveWake++;
            }
        }

        public void reportExcessiveCpu(ArrayMap<String, ProcessTracker.ProcessState> pkgList) {
            mCommonProcess.mNumExcessiveCpu++;
            if (!mCommonProcess.mMultiPackage) {
                return;
            }

            for (int ip=pkgList.size()-1; ip>=0; ip--) {
                pullFixedProc(pkgList, ip).mNumExcessiveCpu++;
            }
        }

        ProcessState pullFixedProc(String pkgName) {
            if (mMultiPackage) {
                // The array map is still pointing to a common process state
                // that is now shared across packages.  Update it to point to
                // the new per-package state.
                ProcessState proc = mState.mPackages.get(pkgName, mUid).mProcesses.get(mName);
                if (proc == null) {
                    throw new IllegalStateException("Didn't create per-package process");
                }
                return proc;
            }
            return this;
        }

        private ProcessState pullFixedProc(ArrayMap<String, ProcessTracker.ProcessState> pkgList,
                int index) {
            ProcessState proc = pkgList.valueAt(index);
            if (proc.mMultiPackage) {
                // The array map is still pointing to a common process state
                // that is now shared across packages.  Update it to point to
                // the new per-package state.
                proc = mState.mPackages.get(pkgList.keyAt(index),
                        proc.mUid).mProcesses.get(proc.mName);
                if (proc == null) {
                    throw new IllegalStateException("Didn't create per-package process");
                }
                pkgList.setValueAt(index, proc);
            }
            return proc;
        }

        long getDuration(int state, long now) {
            int idx = State.binarySearch(mDurationsTable, mDurationsTableSize, state);
            long time = idx >= 0 ? mState.getLong(mDurationsTable[idx], 0) : 0;
            if (mCurState == state) {
                time += now - mStartTime;
            }
            return time;
        }

        long getPssSampleCount(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_SAMPLE_COUNT) : 0;
        }

        long getPssMinimum(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_MINIMUM) : 0;
        }

        long getPssAverage(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_AVERAGE) : 0;
        }

        long getPssMaximum(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_MAXIMUM) : 0;
        }

        long getPssUssMinimum(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_USS_MINIMUM) : 0;
        }

        long getPssUssAverage(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_USS_AVERAGE) : 0;
        }

        long getPssUssMaximum(int state) {
            int idx = State.binarySearch(mPssTable, mPssTableSize, state);
            return idx >= 0 ? mState.getLong(mPssTable[idx], PSS_USS_MAXIMUM) : 0;
        }
    }

    public static final class ServiceState {
        final State mState;
        final String mPackage;
        ProcessState mProc;

        int mActive = 1;

        static final int SERVICE_STARTED = 0;
        static final int SERVICE_BOUND = 1;
        static final int SERVICE_EXEC = 2;
        static final int SERVICE_COUNT = 3;

        int[] mDurationsTable;
        int mDurationsTableSize;

        int mStartedCount;
        int mStartedState = STATE_NOTHING;
        long mStartedStartTime;

        int mBoundCount;
        int mBoundState = STATE_NOTHING;
        long mBoundStartTime;

        int mExecCount;
        int mExecState = STATE_NOTHING;
        long mExecStartTime;

        ServiceState(State state, String pkg, ProcessState proc) {
            mState = state;
            mPackage = pkg;
            mProc = proc;
        }

        void makeActive() {
            mActive++;
        }

        void makeInactive() {
            /*
            RuntimeException here = new RuntimeException("here");
            here.fillInStackTrace();
            Slog.i(TAG, "Making " + this + " inactive", here);
            */
            mActive--;
        }

        boolean isActive() {
            return mActive > 0;
        }

        void resetSafely(long now) {
            mDurationsTable = null;
            mDurationsTableSize = 0;
            mStartedCount = mStartedState != STATE_NOTHING ? 1 : 0;
            mBoundCount = mBoundState != STATE_NOTHING ? 1 : 0;
            mExecCount = mExecState != STATE_NOTHING ? 1 : 0;
            mStartedStartTime = mBoundStartTime = mExecStartTime = now;
        }

        void writeToParcel(Parcel out, long now) {
            if (mStartedState != STATE_NOTHING) {
                addStateTime(SERVICE_STARTED, mStartedState, now - mStartedStartTime);
                mStartedStartTime = now;
            }
            if (mBoundState != STATE_NOTHING) {
                addStateTime(SERVICE_BOUND, mBoundState, now - mBoundStartTime);
                mBoundStartTime = now;
            }
            if (mExecState != STATE_NOTHING) {
                addStateTime(SERVICE_EXEC, mExecState, now - mExecStartTime);
                mExecStartTime = now;
            }
            out.writeInt(mDurationsTableSize);
            for (int i=0; i<mDurationsTableSize; i++) {
                if (DEBUG) Slog.i(TAG, "Writing service in " + mPackage + " dur #" + i + ": "
                        + State.printLongOffset(mDurationsTable[i]));
                out.writeInt(mDurationsTable[i]);
            }
            out.writeInt(mStartedCount);
            out.writeInt(mBoundCount);
            out.writeInt(mExecCount);
        }

        boolean readFromParcel(Parcel in) {
            if (DEBUG) Slog.d(TAG, "Reading durations table...");
            mDurationsTable = mState.readTableFromParcel(in, mPackage, "service");
            if (mDurationsTable == State.BAD_TABLE) {
                return false;
            }
            mStartedCount = in.readInt();
            mBoundCount = in.readInt();
            mExecCount = in.readInt();
            return true;
        }

        void addStateTime(int opType, int memFactor, long time) {
            if (time > 0) {
                int state = opType + (memFactor*SERVICE_COUNT);
                int idx = State.binarySearch(mDurationsTable, mDurationsTableSize, state);
                int off;
                if (idx >= 0) {
                    off = mDurationsTable[idx];
                } else {
                    mState.mAddLongTable = mDurationsTable;
                    mState.mAddLongTableSize = mDurationsTableSize;
                    off = mState.addLongData(~idx, state, 1);
                    mDurationsTable = mState.mAddLongTable;
                    mDurationsTableSize = mState.mAddLongTableSize;
                }
                long[] longs = mState.mLongs.get((off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK);
                longs[(off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK] += time;
            }
        }

        public void setStarted(boolean started, int memFactor, long now) {
            if (mActive <= 0) {
                throw new IllegalStateException("Service " + this + " has mActive=" + mActive);
            }
            int state = started ? memFactor : STATE_NOTHING;
            if (mStartedState != state) {
                if (mStartedState != STATE_NOTHING) {
                    addStateTime(SERVICE_STARTED, mStartedState, now - mStartedStartTime);
                } else if (started) {
                    mStartedCount++;
                }
                mStartedState = state;
                mStartedStartTime = now;
                if (mProc != null) {
                    mProc = mProc.pullFixedProc(mPackage);
                    if (started) {
                        mProc.incStartedServices(memFactor, now);
                    } else {
                        mProc.decStartedServices(memFactor, now);
                    }
                }
            }
        }

        public void setBound(boolean bound, int memFactor, long now) {
            if (mActive <= 0) {
                throw new IllegalStateException("Service " + this + " has mActive=" + mActive);
            }
            int state = bound ? memFactor : STATE_NOTHING;
            if (mBoundState != state) {
                if (mBoundState != STATE_NOTHING) {
                    addStateTime(SERVICE_BOUND, mBoundState, now - mBoundStartTime);
                } else if (bound) {
                    mBoundCount++;
                }
                mBoundState = state;
                mBoundStartTime = now;
            }
        }

        public void setExecuting(boolean executing, int memFactor, long now) {
            if (mActive <= 0) {
                throw new IllegalStateException("Service " + this + " has mActive=" + mActive);
            }
            int state = executing ? memFactor : STATE_NOTHING;
            if (mExecState != state) {
                if (mExecState != STATE_NOTHING) {
                    addStateTime(SERVICE_EXEC, mExecState, now - mExecStartTime);
                } else if (executing) {
                    mExecCount++;
                }
                mExecState = state;
                mExecStartTime = now;
            }
        }

        long getStartDuration(int opType, int memFactor, long now) {
            switch (opType) {
                case SERVICE_STARTED:
                    return getDuration(opType, mStartedState, mStartedStartTime, memFactor, now);
                case SERVICE_BOUND:
                    return getDuration(opType, mBoundState, mBoundStartTime, memFactor, now);
                case SERVICE_EXEC:
                    return getDuration(opType, mExecState, mExecStartTime, memFactor, now);
                default:
                    throw new IllegalArgumentException("Bad opType: " + opType);
            }
        }


        private long getDuration(int opType, int curState, long startTime, int memFactor,
                long now) {
            int state = opType + (memFactor*SERVICE_COUNT);
            int idx = State.binarySearch(mDurationsTable, mDurationsTableSize, state);
            long time = idx >= 0 ? mState.getLong(mDurationsTable[idx], 0) : 0;
            if (curState == memFactor) {
                time += now - startTime;
            }
            return time;
        }
    }

    public static final class PackageState {
        final ArrayMap<String, ProcessState> mProcesses = new ArrayMap<String, ProcessState>();
        final ArrayMap<String, ServiceState> mServices = new ArrayMap<String, ServiceState>();
        final int mUid;

        public PackageState(int uid) {
            mUid = uid;
        }
    }

    static final class State {
        // Current version of the parcel format.
        private static final int PARCEL_VERSION = 9;
        // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
        private static final int MAGIC = 0x50535453;

        static final int FLAG_COMPLETE = 1<<0;
        static final int FLAG_SHUTDOWN = 1<<1;
        static final int FLAG_SYSPROPS = 1<<2;

        final File mBaseDir;
        final ProcessTracker mProcessTracker;
        AtomicFile mFile;
        String mReadError;

        long mTimePeriodStartClock;
        String mTimePeriodStartClockStr;
        long mTimePeriodStartRealtime;
        long mTimePeriodEndRealtime;
        String mRuntime;
        String mWebView;
        boolean mRunning;
        int mFlags;

        final ProcessMap<PackageState> mPackages = new ProcessMap<PackageState>();
        final ProcessMap<ProcessState> mProcesses = new ProcessMap<ProcessState>();
        final long[] mMemFactorDurations = new long[ADJ_COUNT];
        int mMemFactor = STATE_NOTHING;
        long mStartTime;

        static final int LONGS_SIZE = 4096;
        final ArrayList<long[]> mLongs = new ArrayList<long[]>();
        int mNextLong;

        int[] mAddLongTable;
        int mAddLongTableSize;

        final Object mPendingWriteLock = new Object();
        AtomicFile mPendingWriteFile;
        Parcel mPendingWrite;
        boolean mPendingWriteCommitted;
        long mLastWriteTime;

        State(File baseDir, ProcessTracker tracker) {
            mBaseDir = baseDir;
            reset();
            mProcessTracker = tracker;
        }

        State(String file) {
            mBaseDir = null;
            reset();
            mFile = new AtomicFile(new File(file));
            mProcessTracker = null;
            readLocked();
        }

        void reset() {
            if (DEBUG && mFile != null) Slog.d(TAG, "Resetting state of " + mFile.getBaseFile());
            resetCommon();
            mPackages.getMap().clear();
            mProcesses.getMap().clear();
            mMemFactor = STATE_NOTHING;
            mStartTime = 0;
            if (DEBUG && mFile != null) Slog.d(TAG, "State reset; now " + mFile.getBaseFile());
        }

        void resetSafely() {
            if (DEBUG && mFile != null) Slog.d(TAG, "Safely resetting state of " + mFile.getBaseFile());
            resetCommon();
            long now = SystemClock.uptimeMillis();
            ArrayMap<String, SparseArray<ProcessState>> procMap = mProcesses.getMap();
            for (int ip=procMap.size()-1; ip>=0; ip--) {
                SparseArray<ProcessState> uids = procMap.valueAt(ip);
                for (int iu=uids.size()-1; iu>=0; iu--) {
                    uids.valueAt(iu).resetSafely(now);
                }
            }
            ArrayMap<String, SparseArray<PackageState>> pkgMap = mPackages.getMap();
            for (int ip=pkgMap.size()-1; ip>=0; ip--) {
                SparseArray<PackageState> uids = pkgMap.valueAt(ip);
                for (int iu=uids.size()-1; iu>=0; iu--) {
                    PackageState pkgState = uids.valueAt(iu);
                    for (int iproc=pkgState.mProcesses.size()-1; iproc>=0; iproc--) {
                        pkgState.mProcesses.valueAt(iproc).resetSafely(now);
                    }
                    for (int isvc=pkgState.mServices.size()-1; isvc>=0; isvc--) {
                        ServiceState ss = pkgState.mServices.valueAt(isvc);
                        if (ss.isActive()) {
                            pkgState.mServices.valueAt(isvc).resetSafely(now);
                        } else {
                            pkgState.mServices.removeAt(isvc);
                        }
                    }
                }
            }
            mStartTime = SystemClock.uptimeMillis();
            if (DEBUG && mFile != null) Slog.d(TAG, "State reset; now " + mFile.getBaseFile());
        }

        private void resetCommon() {
            mLastWriteTime = SystemClock.uptimeMillis();
            mTimePeriodStartClock = System.currentTimeMillis();
            buildTimePeriodStartClockStr();
            mTimePeriodStartRealtime = mTimePeriodEndRealtime = SystemClock.elapsedRealtime();
            mLongs.clear();
            mLongs.add(new long[LONGS_SIZE]);
            mNextLong = 0;
            Arrays.fill(mMemFactorDurations, 0);
            mStartTime = 0;
            mReadError = null;
            mFlags = 0;
            evaluateSystemProperties(true);
        }

        public boolean evaluateSystemProperties(boolean update) {
            boolean changed = false;
            String runtime = SystemProperties.get("persist.sys.dalvik.vm.lib",
                    VMRuntime.getRuntime().vmLibrary());
            if (!Objects.equals(runtime, mRuntime)) {
                changed = true;
                if (update) {
                    mRuntime = runtime;
                }
            }
            String webview = WebViewFactory.useExperimentalWebView() ? "chromeview" : "webview";
            if (!Objects.equals(webview, mWebView)) {
                changed = true;
                if (update) {
                    mWebView = webview;
                }
            }
            return changed;
        }

        private void buildTimePeriodStartClockStr() {
            mTimePeriodStartClockStr = DateFormat.format("yyyy-MM-dd-HH-mm-ss",
                    mTimePeriodStartClock).toString();
            if (mBaseDir != null) {
                mFile = new AtomicFile(new File(mBaseDir,
                        STATE_FILE_PREFIX + mTimePeriodStartClockStr + STATE_FILE_SUFFIX));
            }
        }

        static byte[] readFully(FileInputStream stream) throws java.io.IOException {
            int pos = 0;
            int avail = stream.available();
            byte[] data = new byte[avail];
            while (true) {
                int amt = stream.read(data, pos, data.length-pos);
                //Log.i("foo", "Read " + amt + " bytes at " + pos
                //        + " of avail " + data.length);
                if (amt <= 0) {
                    //Log.i("foo", "**** FINISHED READING: pos=" + pos
                    //        + " len=" + data.length);
                    return data;
                }
                pos += amt;
                avail = stream.available();
                if (avail > data.length-pos) {
                    byte[] newData = new byte[pos+avail];
                    System.arraycopy(data, 0, newData, 0, pos);
                    data = newData;
                }
            }
        }

        boolean readLocked() {
            try {
                FileInputStream stream = mFile.openRead();

                byte[] raw = readFully(stream);
                Parcel in = Parcel.obtain();
                in.unmarshall(raw, 0, raw.length);
                in.setDataPosition(0);
                stream.close();

                readFromParcel(in);
                if (mReadError != null) {
                    Slog.w(TAG, "Ignoring existing stats; " + mReadError);
                    if (DEBUG) {
                        ArrayMap<String, SparseArray<ProcessState>> procMap = mProcesses.getMap();
                        final int NPROC = procMap.size();
                        for (int ip=0; ip<NPROC; ip++) {
                            Slog.w(TAG, "Process: " + procMap.keyAt(ip));
                            SparseArray<ProcessState> uids = procMap.valueAt(ip);
                            final int NUID = uids.size();
                            for (int iu=0; iu<NUID; iu++) {
                                Slog.w(TAG, "  Uid " + uids.keyAt(iu) + ": " + uids.valueAt(iu));
                            }
                        }
                        ArrayMap<String, SparseArray<PackageState>> pkgMap = mPackages.getMap();
                        final int NPKG = pkgMap.size();
                        for (int ip=0; ip<NPKG; ip++) {
                            Slog.w(TAG, "Package: " + pkgMap.keyAt(ip));
                            SparseArray<PackageState> uids = pkgMap.valueAt(ip);
                            final int NUID = uids.size();
                            for (int iu=0; iu<NUID; iu++) {
                                Slog.w(TAG, "  Uid: " + uids.keyAt(iu));
                                PackageState pkgState = uids.valueAt(iu);
                                final int NPROCS = pkgState.mProcesses.size();
                                for (int iproc=0; iproc<NPROCS; iproc++) {
                                    Slog.w(TAG, "    Process " + pkgState.mProcesses.keyAt(iproc)
                                            + ": " + pkgState.mProcesses.valueAt(iproc));
                                }
                                final int NSRVS = pkgState.mServices.size();
                                for (int isvc=0; isvc<NSRVS; isvc++) {
                                    Slog.w(TAG, "    Service " + pkgState.mServices.keyAt(isvc)
                                            + ": " + pkgState.mServices.valueAt(isvc));
                                }
                            }
                        }
                    }
                    return false;
                }
            } catch (Throwable e) {
                mReadError = "caught exception: " + e;
                Slog.e(TAG, "Error reading process statistics", e);
                return false;
            }
            return true;
        }

        static final int[] BAD_TABLE = new int[0];

        private int[] readTableFromParcel(Parcel in, String name, String what) {
            final int size = in.readInt();
            if (size < 0) {
                Slog.w(TAG, "Ignoring existing stats; bad " + what + " table size: " + size);
                return BAD_TABLE;
            }
            if (size == 0) {
                return null;
            }
            final int[] table = new int[size];
            for (int i=0; i<size; i++) {
                table[i] = in.readInt();
                if (DEBUG) Slog.i(TAG, "Reading in " + name + " table #" + i + ": "
                        + State.printLongOffset(table[i]));
                if (!validateLongOffset(table[i])) {
                    Slog.w(TAG, "Ignoring existing stats; bad " + what + " table entry: "
                            + State.printLongOffset(table[i]));
                    return null;
                }
            }
            return table;
        }

        private void writeStateLocked(boolean sync, final boolean commit) {
            synchronized (mPendingWriteLock) {
                long now = SystemClock.uptimeMillis();
                if (mPendingWrite == null || !mPendingWriteCommitted) {
                    mPendingWrite = Parcel.obtain();
                    mTimePeriodEndRealtime = SystemClock.elapsedRealtime();
                    if (commit) {
                        mFlags |= State.FLAG_COMPLETE;
                    }
                    writeToParcel(mPendingWrite);
                    mPendingWriteFile = new AtomicFile(mFile.getBaseFile());
                    mPendingWriteCommitted = commit;
                }
                if (commit) {
                    resetSafely();
                } else {
                    mLastWriteTime = SystemClock.uptimeMillis();
                }
                Slog.i(TAG, "Prepared write state in " + (SystemClock.uptimeMillis()-now) + "ms");
                if (!sync) {
                    BackgroundThread.getHandler().post(new Runnable() {
                        @Override public void run() {
                            performWriteState();
                        }
                    });
                    return;
                }
            }

            performWriteState();
        }

        void performWriteState() {
            if (DEBUG) Slog.d(TAG, "Performing write to " + mFile.getBaseFile());
            Parcel data;
            AtomicFile file;
            synchronized (mPendingWriteLock) {
                data = mPendingWrite;
                file = mPendingWriteFile;
                mPendingWriteCommitted = false;
                if (data == null) {
                    return;
                }
                mPendingWrite = null;
                mPendingWriteFile = null;
                if (mProcessTracker != null) {
                    mProcessTracker.mWriteLock.lock();
                }
            }

            FileOutputStream stream = null;
            try {
                stream = file.startWrite();
                stream.write(data.marshall());
                stream.flush();
                file.finishWrite(stream);
                if (DEBUG) Slog.d(TAG, "Write completed successfully!");
            } catch (IOException e) {
                Slog.w(TAG, "Error writing process statistics", e);
                file.failWrite(stream);
            } finally {
                data.recycle();
                if (mProcessTracker != null) {
                    mProcessTracker.trimHistoricStatesWriteLocked();
                    mProcessTracker.mWriteLock.unlock();
                }
            }

        }

        void writeToParcel(Parcel out) {
            long now = SystemClock.uptimeMillis();
            out.writeInt(MAGIC);
            out.writeInt(PARCEL_VERSION);
            out.writeInt(STATE_COUNT);
            out.writeInt(ADJ_COUNT);
            out.writeInt(PSS_COUNT);
            out.writeInt(LONGS_SIZE);

            out.writeLong(mTimePeriodStartClock);
            out.writeLong(mTimePeriodStartRealtime);
            out.writeLong(mTimePeriodEndRealtime);
            out.writeString(mRuntime);
            out.writeString(mWebView);
            out.writeInt(mFlags);

            out.writeInt(mLongs.size());
            out.writeInt(mNextLong);
            for (int i=0; i<(mLongs.size()-1); i++) {
                out.writeLongArray(mLongs.get(i));
            }
            long[] lastLongs = mLongs.get(mLongs.size()-1);
            for (int i=0; i<mNextLong; i++) {
                out.writeLong(lastLongs[i]);
                if (DEBUG) Slog.d(TAG, "Writing last long #" + i + ": " + lastLongs[i]);
            }

            if (mMemFactor != STATE_NOTHING) {
                mMemFactorDurations[mMemFactor] += now - mStartTime;
                mStartTime = now;
            }
            out.writeLongArray(mMemFactorDurations);

            ArrayMap<String, SparseArray<ProcessState>> procMap = mProcesses.getMap();
            final int NPROC = procMap.size();
            out.writeInt(NPROC);
            for (int ip=0; ip<NPROC; ip++) {
                out.writeString(procMap.keyAt(ip));
                SparseArray<ProcessState> uids = procMap.valueAt(ip);
                final int NUID = uids.size();
                out.writeInt(NUID);
                for (int iu=0; iu<NUID; iu++) {
                    out.writeInt(uids.keyAt(iu));
                    ProcessState proc = uids.valueAt(iu);
                    out.writeString(proc.mPackage);
                    proc.writeToParcel(out, now);
                }
            }
            ArrayMap<String, SparseArray<PackageState>> pkgMap = mPackages.getMap();
            final int NPKG = pkgMap.size();
            out.writeInt(NPKG);
            for (int ip=0; ip<NPKG; ip++) {
                out.writeString(pkgMap.keyAt(ip));
                SparseArray<PackageState> uids = pkgMap.valueAt(ip);
                final int NUID = uids.size();
                out.writeInt(NUID);
                for (int iu=0; iu<NUID; iu++) {
                    out.writeInt(uids.keyAt(iu));
                    PackageState pkgState = uids.valueAt(iu);
                    final int NPROCS = pkgState.mProcesses.size();
                    out.writeInt(NPROCS);
                    for (int iproc=0; iproc<NPROCS; iproc++) {
                        out.writeString(pkgState.mProcesses.keyAt(iproc));
                        ProcessState proc = pkgState.mProcesses.valueAt(iproc);
                        if (proc.mCommonProcess == proc) {
                            // This is the same as the common process we wrote above.
                            out.writeInt(0);
                        } else {
                            // There is separate data for this package's process.
                            out.writeInt(1);
                            proc.writeToParcel(out, now);
                        }
                    }
                    final int NSRVS = pkgState.mServices.size();
                    out.writeInt(NSRVS);
                    for (int isvc=0; isvc<NSRVS; isvc++) {
                        out.writeString(pkgState.mServices.keyAt(isvc));
                        ServiceState svc = pkgState.mServices.valueAt(isvc);
                        svc.writeToParcel(out, now);
                    }
                }
            }
        }

        private boolean readCheckedInt(Parcel in, int val, String what) {
            int got;
            if ((got=in.readInt()) != val) {
                mReadError = "bad " + what + ": " + got;
                return false;
            }
            return true;
        }

        private void readFromParcel(Parcel in) {
            final boolean hadData = mPackages.getMap().size() > 0
                    || mProcesses.getMap().size() > 0;
            if (hadData) {
                resetSafely();
            }

            if (!readCheckedInt(in, MAGIC, "magic number")) {
                return;
            }
            int version = in.readInt();
            if (version != PARCEL_VERSION && version != 6) {
                mReadError = "bad version: " + version;
                return;
            }
            if (!readCheckedInt(in, STATE_COUNT, "state count")) {
                return;
            }
            if (!readCheckedInt(in, ADJ_COUNT, "adj count")) {
                return;
            }
            if (!readCheckedInt(in, PSS_COUNT, "pss count")) {
                return;
            }
            if (!readCheckedInt(in, LONGS_SIZE, "longs size")) {
                return;
            }

            mTimePeriodStartClock = in.readLong();
            buildTimePeriodStartClockStr();
            mTimePeriodStartRealtime = in.readLong();
            mTimePeriodEndRealtime = in.readLong();
            if (version ==  PARCEL_VERSION) {
                mRuntime = in.readString();
                mWebView = in.readString();
            }
            mFlags = in.readInt();

            final int NLONGS = in.readInt();
            final int NEXTLONG = in.readInt();
            mLongs.clear();
            for (int i=0; i<(NLONGS-1); i++) {
                while (i >= mLongs.size()) {
                    mLongs.add(new long[LONGS_SIZE]);
                }
                in.readLongArray(mLongs.get(i));
            }
            long[] longs = new long[LONGS_SIZE];
            mNextLong = NEXTLONG;
            for (int i=0; i<NEXTLONG; i++) {
                longs[i] = in.readLong();
                if (DEBUG) Slog.d(TAG, "Reading last long #" + i + ": " + longs[i]);
            }
            mLongs.add(longs);

            in.readLongArray(mMemFactorDurations);

            int NPROC = in.readInt();
            if (NPROC < 0) {
                mReadError = "bad process count: " + NPROC;
                return;
            }
            while (NPROC > 0) {
                NPROC--;
                String procName = in.readString();
                if (procName == null) {
                    mReadError = "bad process name";
                    return;
                }
                int NUID = in.readInt();
                if (NUID < 0) {
                    mReadError = "bad uid count: " + NUID;
                    return;
                }
                while (NUID > 0) {
                    NUID--;
                    int uid = in.readInt();
                    if (uid < 0) {
                        mReadError = "bad uid: " + uid;
                        return;
                    }
                    String pkgName = in.readString();
                    if (pkgName == null) {
                        mReadError = "bad process package name";
                        return;
                    }
                    ProcessState proc = hadData ? mProcesses.get(procName, uid) : null;
                    if (proc != null) {
                        if (!proc.readFromParcel(in, false)) {
                            return;
                        }
                    } else {
                        proc = new ProcessState(this, pkgName, uid, procName);
                        if (!proc.readFromParcel(in, true)) {
                            return;
                        }
                    }
                    if (DEBUG) Slog.d(TAG, "Adding process: " + procName + " " + uid + " " + proc);
                    mProcesses.put(procName, uid, proc);
                }
            }

            if (DEBUG) Slog.d(TAG, "Read " + mProcesses.getMap().size() + " processes");

            int NPKG = in.readInt();
            if (NPKG < 0) {
                mReadError = "bad package count: " + NPKG;
                return;
            }
            while (NPKG > 0) {
                NPKG--;
                String pkgName = in.readString();
                if (pkgName == null) {
                    mReadError = "bad package name";
                    return;
                }
                int NUID = in.readInt();
                if (NUID < 0) {
                    mReadError = "bad uid count: " + NUID;
                    return;
                }
                while (NUID > 0) {
                    NUID--;
                    int uid = in.readInt();
                    if (uid < 0) {
                        mReadError = "bad uid: " + uid;
                        return;
                    }
                    PackageState pkgState = new PackageState(uid);
                    mPackages.put(pkgName, uid, pkgState);
                    int NPROCS = in.readInt();
                    if (NPROCS < 0) {
                        mReadError = "bad package process count: " + NPROCS;
                        return;
                    }
                    while (NPROCS > 0) {
                        NPROCS--;
                        String procName = in.readString();
                        if (procName == null) {
                            mReadError = "bad package process name";
                            return;
                        }
                        int hasProc = in.readInt();
                        if (DEBUG) Slog.d(TAG, "Reading package " + pkgName + " " + uid
                                + " process " + procName + " hasProc=" + hasProc);
                        ProcessState commonProc = mProcesses.get(procName, uid);
                        if (DEBUG) Slog.d(TAG, "Got common proc " + procName + " " + uid
                                + ": " + commonProc);
                        if (commonProc == null) {
                            mReadError = "no common proc: " + procName;
                            return;
                        }
                        if (hasProc != 0) {
                            // The process for this package is unique to the package; we
                            // need to load it.  We don't need to do anything about it if
                            // it is not unique because if someone later looks for it
                            // they will find and use it from the global procs.
                            ProcessState proc = hadData ? pkgState.mProcesses.get(procName) : null;
                            if (proc != null) {
                                if (!proc.readFromParcel(in, false)) {
                                    return;
                                }
                            } else {
                                proc = new ProcessState(commonProc, pkgName, uid, procName, 0);
                                if (!proc.readFromParcel(in, true)) {
                                    return;
                                }
                            }
                            if (DEBUG) Slog.d(TAG, "Adding package " + pkgName + " process: "
                                    + procName + " " + uid + " " + proc);
                            pkgState.mProcesses.put(procName, proc);
                        } else {
                            if (DEBUG) Slog.d(TAG, "Adding package " + pkgName + " process: "
                                    + procName + " " + uid + " " + commonProc);
                            pkgState.mProcesses.put(procName, commonProc);
                        }
                    }
                    int NSRVS = in.readInt();
                    if (NSRVS < 0) {
                        mReadError = "bad package service count: " + NSRVS;
                        return;
                    }
                    while (NSRVS > 0) {
                        NSRVS--;
                        String serviceName = in.readString();
                        if (serviceName == null) {
                            mReadError = "bad package service name";
                            return;
                        }
                        ServiceState serv = hadData ? pkgState.mServices.get(serviceName) : null;
                        if (serv == null) {
                            serv = new ServiceState(this, pkgName, null);
                        }
                        if (!serv.readFromParcel(in)) {
                            return;
                        }
                        if (DEBUG) Slog.d(TAG, "Adding package " + pkgName + " service: "
                                + serviceName + " " + uid + " " + serv);
                        pkgState.mServices.put(serviceName, serv);
                    }
                }
            }

            if (DEBUG) Slog.d(TAG, "Successfully read procstats!");
        }

        int addLongData(int index, int type, int num) {
            int tableLen = mAddLongTable != null ? mAddLongTable.length : 0;
            if (mAddLongTableSize >= tableLen) {
                int newSize = ArrayUtils.idealIntArraySize(tableLen + 1);
                int[] newTable = new int[newSize];
                if (tableLen > 0) {
                    System.arraycopy(mAddLongTable, 0, newTable, 0, tableLen);
                }
                mAddLongTable = newTable;
            }
            if (mAddLongTableSize > 0 && mAddLongTableSize - index != 0) {
                System.arraycopy(mAddLongTable, index, mAddLongTable, index + 1,
                        mAddLongTableSize - index);
            }
            int off = allocLongData(num);
            mAddLongTable[index] = type | off;
            mAddLongTableSize++;
            return off;
        }

        int allocLongData(int num) {
            int whichLongs = mLongs.size()-1;
            long[] longs = mLongs.get(whichLongs);
            if (mNextLong + num > longs.length) {
                longs = new long[LONGS_SIZE];
                mLongs.add(longs);
                whichLongs++;
                mNextLong = 0;
            }
            int off = (whichLongs<<OFFSET_ARRAY_SHIFT) | (mNextLong<<OFFSET_INDEX_SHIFT);
            mNextLong += num;
            return off;
        }

        boolean validateLongOffset(int off) {
            int arr = (off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK;
            if (arr >= mLongs.size()) {
                return false;
            }
            int idx = (off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK;
            if (idx >= LONGS_SIZE) {
                return false;
            }
            if (DEBUG) Slog.d(TAG, "Validated long " + printLongOffset(off)
                    + ": " + getLong(off, 0));
            return true;
        }

        static String printLongOffset(int off) {
            StringBuilder sb = new StringBuilder(16);
            sb.append("a"); sb.append((off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK);
            sb.append("i"); sb.append((off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK);
            sb.append("t"); sb.append((off>>OFFSET_TYPE_SHIFT)&OFFSET_TYPE_MASK);
            return sb.toString();
        }

        void setLong(int off, int index, long value) {
            long[] longs = mLongs.get((off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK);
            longs[index + ((off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK)] = value;
        }

        long getLong(int off, int index) {
            long[] longs = mLongs.get((off>>OFFSET_ARRAY_SHIFT)&OFFSET_ARRAY_MASK);
            return longs[index + ((off>>OFFSET_INDEX_SHIFT)&OFFSET_INDEX_MASK)];
        }

        static int binarySearch(int[] array, int size, int value) {
            int lo = 0;
            int hi = size - 1;

            while (lo <= hi) {
                int mid = (lo + hi) >>> 1;
                int midVal = (array[mid] >> OFFSET_TYPE_SHIFT) & OFFSET_TYPE_MASK;

                if (midVal < value) {
                    lo = mid + 1;
                } else if (midVal > value) {
                    hi = mid - 1;
                } else {
                    return mid;  // value found
                }
            }
            return ~lo;  // value not present
        }

        PackageState getPackageStateLocked(String packageName, int uid) {
            PackageState as = mPackages.get(packageName, uid);
            if (as != null) {
                return as;
            }
            as = new PackageState(uid);
            mPackages.put(packageName, uid, as);
            return as;
        }

        ProcessState getProcessStateLocked(String packageName, int uid, String processName) {
            final PackageState pkgState = getPackageStateLocked(packageName, uid);
            ProcessState ps = pkgState.mProcesses.get(processName);
            if (ps != null) {
                return ps;
            }
            ProcessState commonProc = mProcesses.get(processName, uid);
            if (commonProc == null) {
                commonProc = new ProcessState(this, packageName, uid, processName);
                mProcesses.put(processName, uid, commonProc);
            }
            if (!commonProc.mMultiPackage) {
                if (packageName.equals(commonProc.mPackage)) {
                    // This common process is not in use by multiple packages, and
                    // is for the calling package, so we can just use it directly.
                    ps = commonProc;
                } else {
                    // This common process has not been in use by multiple packages,
                    // but it was created for a different package than the caller.
                    // We need to convert it to a multi-package process.
                    commonProc.mMultiPackage = true;
                    // The original package it was created for now needs to point
                    // to its own copy.
                    long now = SystemClock.uptimeMillis();
                    pkgState.mProcesses.put(commonProc.mName, commonProc.clone(
                            commonProc.mPackage, now));
                    ps = new ProcessState(commonProc, packageName, uid, processName, now);
                }
            } else {
                // The common process is for multiple packages, we need to create a
                // separate object for the per-package data.
                ps = new ProcessState(commonProc, packageName, uid, processName,
                        SystemClock.uptimeMillis());
            }
            pkgState.mProcesses.put(processName, ps);
            return ps;
        }

        void dumpLocked(PrintWriter pw, String reqPackage, long now, boolean dumpAll) {
            long totalTime = dumpSingleTime(null, null, mMemFactorDurations, mMemFactor,
                    mStartTime, now);
            ArrayMap<String, SparseArray<PackageState>> pkgMap = mPackages.getMap();
            boolean printedHeader = false;
            for (int ip=0; ip<pkgMap.size(); ip++) {
                String pkgName = pkgMap.keyAt(ip);
                if (reqPackage != null && !reqPackage.equals(pkgName)) {
                    continue;
                }
                SparseArray<PackageState> uids = pkgMap.valueAt(ip);
                for (int iu=0; iu<uids.size(); iu++) {
                    int uid = uids.keyAt(iu);
                    PackageState pkgState = uids.valueAt(iu);
                    final int NPROCS = pkgState.mProcesses.size();
                    final int NSRVS = pkgState.mServices.size();
                    if (NPROCS > 0 || NSRVS > 0) {
                        if (!printedHeader) {
                            pw.println("Per-Package Process Stats:");
                            printedHeader = true;
                        }
                        pw.print("  * "); pw.print(pkgName); pw.print(" / ");
                                UserHandle.formatUid(pw, uid); pw.println(":");
                    }
                    if (dumpAll) {
                        for (int iproc=0; iproc<NPROCS; iproc++) {
                            ProcessState proc = pkgState.mProcesses.valueAt(iproc);
                            pw.print("      Process ");
                            pw.print(pkgState.mProcesses.keyAt(iproc));
                            pw.print(" (");
                            pw.print(proc.mDurationsTableSize);
                            pw.print(" entries)");
                            pw.println(":");
                            dumpProcessState(pw, "        ", proc, ALL_SCREEN_ADJ, ALL_MEM_ADJ,
                                    ALL_PROC_STATES, now);
                            dumpProcessPss(pw, "        ", proc, ALL_SCREEN_ADJ, ALL_MEM_ADJ,
                                    ALL_PROC_STATES);
                            if (dumpAll) {
                                pw.print("        mNumStartedServices=");
                                        pw.println(proc.mNumStartedServices);
                            }
                        }
                    } else {
                        ArrayList<ProcessState> procs = new ArrayList<ProcessState>();
                        for (int iproc=0; iproc<NPROCS; iproc++) {
                            procs.add(pkgState.mProcesses.valueAt(iproc));
                        }
                        dumpProcessSummaryLocked(pw, "      ", procs, ALL_SCREEN_ADJ, ALL_MEM_ADJ,
                                NON_CACHED_PROC_STATES, now, totalTime);
                    }
                    for (int isvc=0; isvc<NSRVS; isvc++) {
                        if (dumpAll) {
                            pw.print("      Service ");
                        } else {
                            pw.print("      * ");
                        }
                        pw.print(pkgState.mServices.keyAt(isvc));
                        pw.println(":");
                        ServiceState svc = pkgState.mServices.valueAt(isvc);
                        dumpServiceStats(pw, "        ", "          ", "    ", "Started", svc,
                                svc.mStartedCount, ServiceState.SERVICE_STARTED, svc.mStartedState,
                                svc.mStartedStartTime, now, totalTime, dumpAll);
                        dumpServiceStats(pw, "        ", "          ", "      ", "Bound", svc,
                                svc.mBoundCount, ServiceState.SERVICE_BOUND, svc.mBoundState,
                                svc.mBoundStartTime, now, totalTime, dumpAll);
                        dumpServiceStats(pw, "        ", "          ", "  ", "Executing", svc,
                                svc.mExecCount, ServiceState.SERVICE_EXEC, svc.mExecState,
                                svc.mExecStartTime, now, totalTime, dumpAll);
                    }
                }
            }

            if (reqPackage == null) {
                ArrayMap<String, SparseArray<ProcessState>> procMap = mProcesses.getMap();
                printedHeader = false;
                for (int ip=0; ip<procMap.size(); ip++) {
                    String procName = procMap.keyAt(ip);
                    SparseArray<ProcessState> uids = procMap.valueAt(ip);
                    for (int iu=0; iu<uids.size(); iu++) {
                        int uid = uids.keyAt(iu);
                        ProcessState proc = uids.valueAt(iu);
                        if (proc.mDurationsTableSize == 0 && proc.mCurState == STATE_NOTHING
                                && proc.mPssTableSize == 0) {
                            continue;
                        }
                        if (!printedHeader) {
                            pw.println("Process Stats:");
                            printedHeader = true;
                        }
                        pw.print("  * "); pw.print(procName); pw.print(" / ");
                                UserHandle.formatUid(pw, uid);
                                pw.print(" ("); pw.print(proc.mDurationsTableSize);
                                pw.print(" entries)"); pw.println(":");
                        dumpProcessState(pw, "        ", proc, ALL_SCREEN_ADJ, ALL_MEM_ADJ,
                                ALL_PROC_STATES, now);
                        dumpProcessPss(pw, "        ", proc, ALL_SCREEN_ADJ, ALL_MEM_ADJ,
                                ALL_PROC_STATES);
                    }
                }

                pw.println();
                pw.println("Summary:");
                dumpSummaryLocked(pw, reqPackage, now);
            } else {
                pw.println();
                dumpTotalsLocked(pw, now);
            }

            if (dumpAll) {
                pw.println();
                pw.println("Internal state:");
                pw.print("  mFile="); pw.println(mFile.getBaseFile());
                pw.print("  Num long arrays: "); pw.println(mLongs.size());
                pw.print("  Next long entry: "); pw.println(mNextLong);
                pw.print("  mRunning="); pw.println(mRunning);
            }
        }

        static long dumpSingleServiceTime(PrintWriter pw, String prefix, ServiceState service,
                int serviceType, int curState, long curStartTime, long now) {
            long totalTime = 0;
            int printedScreen = -1;
            for (int iscreen=0; iscreen<ADJ_COUNT; iscreen+=ADJ_SCREEN_MOD) {
                int printedMem = -1;
                for (int imem=0; imem<ADJ_MEM_FACTOR_COUNT; imem++) {
                    int state = imem+iscreen;
                    long time = service.getDuration(serviceType, curState, curStartTime,
                            state, now);
                    String running = "";
                    if (curState == state) {
                        time += now - curStartTime;
                        if (pw != null) {
                            running = " (running)";
                        }
                    }
                    if (time != 0) {
                        if (pw != null) {
                            pw.print(prefix);
                            printScreenLabel(pw, printedScreen != iscreen
                                    ? iscreen : STATE_NOTHING);
                            printedScreen = iscreen;
                            printMemLabel(pw, printedMem != imem ? imem : STATE_NOTHING);
                            printedMem = imem;
                            TimeUtils.formatDuration(time, pw); pw.println(running);
                        }
                        totalTime += time;
                    }
                }
            }
            if (totalTime != 0 && pw != null) {
                pw.print(prefix);
                printScreenLabel(pw, STATE_NOTHING);
                pw.print("TOTAL: ");
                TimeUtils.formatDuration(totalTime, pw);
                pw.println();
            }
            return totalTime;
        }

        void dumpServiceStats(PrintWriter pw, String prefix, String prefixInner,
                String headerPrefix, String header, ServiceState service,
                int count, int serviceType, int state, long startTime, long now, long totalTime,
                boolean dumpAll) {
            if (count != 0) {
                if (dumpAll) {
                    pw.print(prefix); pw.print(header);
                    pw.print(" op count "); pw.print(count); pw.println(":");
                    dumpSingleServiceTime(pw, prefixInner, service, serviceType, state, startTime,
                            now);
                } else {
                    long myTime = dumpSingleServiceTime(null, null, service, serviceType, state,
                            startTime, now);
                    pw.print(prefix); pw.print(headerPrefix); pw.print(header);
                    pw.print(" count "); pw.print(count);
                    pw.print(" / time ");
                    printPercent(pw, (double)myTime/(double)totalTime);
                    pw.println();
                }
            }
        }

        void dumpSummaryLocked(PrintWriter pw, String reqPackage, long now) {
            long totalTime = dumpSingleTime(null, null, mMemFactorDurations, mMemFactor,
                    mStartTime, now);
            dumpFilteredSummaryLocked(pw, null, "  ", ALL_SCREEN_ADJ, ALL_MEM_ADJ,
                    NON_CACHED_PROC_STATES, now, totalTime, reqPackage);
            pw.println();
            dumpTotalsLocked(pw, now);
        }

        void dumpTotalsLocked(PrintWriter pw, long now) {
            pw.println("Run time Stats:");
            dumpSingleTime(pw, "  ", mMemFactorDurations, mMemFactor, mStartTime, now);
            pw.println();
            pw.print("          Start time: ");
            pw.print(DateFormat.format("yyyy-MM-dd HH:mm:ss", mTimePeriodStartClock));
            pw.println();
            pw.print("  Total elapsed time: ");
            TimeUtils.formatDuration(
                    (mRunning ? SystemClock.elapsedRealtime() : mTimePeriodEndRealtime)
                            - mTimePeriodStartRealtime, pw);
            boolean partial = true;
            if ((mFlags&FLAG_SHUTDOWN) != 0) {
                pw.print(" (shutdown)");
                partial = false;
            }
            if ((mFlags&FLAG_SYSPROPS) != 0) {
                pw.print(" (sysprops)");
                partial = false;
            }
            if ((mFlags&FLAG_COMPLETE) != 0) {
                pw.print(" (complete)");
                partial = false;
            }
            if (partial) {
                pw.print(" (partial)");
            }
            pw.print(' ');
            pw.print(mRuntime);
            pw.print(' ');
            pw.print(mWebView);
            pw.println();
        }

        void dumpFilteredSummaryLocked(PrintWriter pw, String header, String prefix,
                int[] screenStates, int[] memStates, int[] procStates, long now, long totalTime,
                String reqPackage) {
            ArrayList<ProcessState> procs = collectProcessesLocked(screenStates, memStates,
                    procStates, now, reqPackage);
            if (procs.size() > 0) {
                if (header != null) {
                    pw.println();
                    pw.println(header);
                }
                dumpProcessSummaryLocked(pw, prefix, procs, screenStates, memStates, procStates,
                        now, totalTime);
            }
        }

        ArrayList<ProcessState> collectProcessesLocked(int[] screenStates, int[] memStates,
                int[] procStates, long now, String reqPackage) {
            ArraySet<ProcessState> foundProcs = new ArraySet<ProcessState>();
            ArrayMap<String, SparseArray<PackageState>> pkgMap = mPackages.getMap();
            for (int ip=0; ip<pkgMap.size(); ip++) {
                if (reqPackage != null && !reqPackage.equals(pkgMap.keyAt(ip))) {
                    continue;
                }
                SparseArray<PackageState> procs = pkgMap.valueAt(ip);
                for (int iu=0; iu<procs.size(); iu++) {
                    PackageState state = procs.valueAt(iu);
                    for (int iproc=0; iproc<state.mProcesses.size(); iproc++) {
                        ProcessState proc = state.mProcesses.valueAt(iproc);
                        foundProcs.add(proc.mCommonProcess);
                    }
                }
            }
            ArrayList<ProcessState> outProcs = new ArrayList<ProcessState>(foundProcs.size());
            for (int i=0; i<foundProcs.size(); i++) {
                ProcessState proc = foundProcs.valueAt(i);
                if (computeProcessTimeLocked(proc, screenStates, memStates,
                        procStates, now) > 0) {
                    outProcs.add(proc);
                }
            }
            Collections.sort(outProcs, new Comparator<ProcessState>() {
                @Override
                public int compare(ProcessState lhs, ProcessState rhs) {
                    if (lhs.mTmpTotalTime < rhs.mTmpTotalTime) {
                        return -1;
                    } else if (lhs.mTmpTotalTime > rhs.mTmpTotalTime) {
                        return 1;
                    }
                    return 0;
                }
            });
            return outProcs;
        }

        String collapseString(String pkgName, String itemName) {
            if (itemName.startsWith(pkgName)) {
                final int ITEMLEN = itemName.length();
                final int PKGLEN = pkgName.length();
                if (ITEMLEN == PKGLEN) {
                    return "";
                } else if (ITEMLEN >= PKGLEN) {
                    if (itemName.charAt(PKGLEN) == '.') {
                        return itemName.substring(PKGLEN);
                    }
                }
            }
            return itemName;
        }

        void dumpCheckinLocked(PrintWriter pw, String reqPackage) {
            final long now = SystemClock.uptimeMillis();
            ArrayMap<String, SparseArray<PackageState>> pkgMap = mPackages.getMap();
            pw.println("vers,3");
            pw.print("period,"); pw.print(mTimePeriodStartClockStr);
            pw.print(","); pw.print(mTimePeriodStartRealtime); pw.print(",");
            pw.print(mRunning ? SystemClock.elapsedRealtime() : mTimePeriodEndRealtime);
            boolean partial = true;
            if ((mFlags&FLAG_SHUTDOWN) != 0) {
                pw.print(",shutdown");
                partial = false;
            }
            if ((mFlags&FLAG_SYSPROPS) != 0) {
                pw.print(",sysprops");
                partial = false;
            }
            if ((mFlags&FLAG_COMPLETE) != 0) {
                pw.print(",complete");
                partial = false;
            }
            if (partial) {
                pw.print(",partial");
            }
            pw.println();
            pw.print("config,"); pw.print(mRuntime); pw.print(','); pw.println(mWebView);
            for (int ip=0; ip<pkgMap.size(); ip++) {
                String pkgName = pkgMap.keyAt(ip);
                if (reqPackage != null && !reqPackage.equals(pkgName)) {
                    continue;
                }
                SparseArray<PackageState> uids = pkgMap.valueAt(ip);
                for (int iu=0; iu<uids.size(); iu++) {
                    int uid = uids.keyAt(iu);
                    PackageState pkgState = uids.valueAt(iu);
                    final int NPROCS = pkgState.mProcesses.size();
                    final int NSRVS = pkgState.mServices.size();
                    for (int iproc=0; iproc<NPROCS; iproc++) {
                        ProcessState proc = pkgState.mProcesses.valueAt(iproc);
                        pw.print("pkgproc,");
                        pw.print(pkgName);
                        pw.print(",");
                        pw.print(uid);
                        pw.print(",");
                        pw.print(collapseString(pkgName, pkgState.mProcesses.keyAt(iproc)));
                        dumpAllProcessStateCheckin(pw, proc, now);
                        pw.println();
                        if (proc.mPssTableSize > 0) {
                            pw.print("pkgpss,");
                            pw.print(pkgName);
                            pw.print(",");
                            pw.print(uid);
                            pw.print(",");
                            pw.print(collapseString(pkgName, pkgState.mProcesses.keyAt(iproc)));
                            dumpAllProcessPssCheckin(pw, proc);
                            pw.println();
                        }
                        if (proc.mNumExcessiveWake > 0 || proc.mNumExcessiveCpu > 0) {
                            pw.print("pkgkills,");
                            pw.print(pkgName);
                            pw.print(",");
                            pw.print(uid);
                            pw.print(",");
                            pw.print(collapseString(pkgName, pkgState.mProcesses.keyAt(iproc)));
                            pw.print(",");
                            pw.print(proc.mNumExcessiveWake);
                            pw.print(",");
                            pw.print(proc.mNumExcessiveCpu);
                            pw.println();
                        }
                    }
                    for (int isvc=0; isvc<NSRVS; isvc++) {
                        String serviceName = collapseString(pkgName,
                                pkgState.mServices.keyAt(isvc));
                        ServiceState svc = pkgState.mServices.valueAt(isvc);
                        dumpServiceTimeCheckin(pw, "pkgsvc-start", pkgName, uid, serviceName,
                                svc, ServiceState.SERVICE_STARTED, svc.mStartedCount,
                                svc.mStartedState, svc.mStartedStartTime, now);
                        dumpServiceTimeCheckin(pw, "pkgsvc-bound", pkgName, uid, serviceName,
                                svc, ServiceState.SERVICE_BOUND, svc.mBoundCount,
                                svc.mBoundState, svc.mBoundStartTime, now);
                        dumpServiceTimeCheckin(pw, "pkgsvc-exec", pkgName, uid, serviceName,
                                svc, ServiceState.SERVICE_EXEC, svc.mExecCount,
                                svc.mExecState, svc.mExecStartTime, now);
                    }
                }
            }

            ArrayMap<String, SparseArray<ProcessState>> procMap = mProcesses.getMap();
            for (int ip=0; ip<procMap.size(); ip++) {
                String procName = procMap.keyAt(ip);
                SparseArray<ProcessState> uids = procMap.valueAt(ip);
                for (int iu=0; iu<uids.size(); iu++) {
                    int uid = uids.keyAt(iu);
                    ProcessState procState = uids.valueAt(iu);
                    if (procState.mDurationsTableSize > 0) {
                        pw.print("proc,");
                        pw.print(procName);
                        pw.print(",");
                        pw.print(uid);
                        dumpAllProcessStateCheckin(pw, procState, now);
                        pw.println();
                    }
                    if (procState.mPssTableSize > 0) {
                        pw.print("pss,");
                        pw.print(procName);
                        pw.print(",");
                        pw.print(uid);
                        dumpAllProcessPssCheckin(pw, procState);
                        pw.println();
                    }
                    if (procState.mNumExcessiveWake > 0 || procState.mNumExcessiveCpu > 0) {
                        pw.print("kills,");
                        pw.print(procName);
                        pw.print(",");
                        pw.print(uid);
                        pw.print(",");
                        pw.print(procState.mNumExcessiveWake);
                        pw.print(",");
                        pw.print(procState.mNumExcessiveCpu);
                        pw.println();
                    }
                }
            }
            pw.print("total");
            dumpAdjTimesCheckin(pw, ",", mMemFactorDurations, mMemFactor,
                    mStartTime, now);
            pw.println();
        }
    }

    public ProcessTracker(Object lock, File file) {
        mLock = lock;
        mBaseDir = file;
        mBaseDir.mkdirs();
        mState = new State(mBaseDir, this);
        mState.mRunning = true;
        SystemProperties.addChangeCallback(new Runnable() {
            @Override public void run() {
                synchronized (mLock) {
                    if (mState.evaluateSystemProperties(false)) {
                        mState.mFlags |= State.FLAG_SYSPROPS;
                        mState.writeStateLocked(true, true);
                        mState.evaluateSystemProperties(true);
                    }
                }
            }
        });
    }

    public ProcessState getProcessStateLocked(String packageName, int uid, String processName) {
        return mState.getProcessStateLocked(packageName, uid, processName);
    }

    public ServiceState getServiceStateLocked(String packageName, int uid,
            String processName, String className) {
        final PackageState as = mState.getPackageStateLocked(packageName, uid);
        ServiceState ss = as.mServices.get(className);
        if (ss != null) {
            ss.makeActive();
            return ss;
        }
        final ProcessState ps = mState.getProcessStateLocked(packageName, uid, processName);
        ss = new ServiceState(mState, packageName, ps);
        as.mServices.put(className, ss);
        return ss;
    }

    public boolean isMemFactorLowered() {
        return mMemFactorLowered;
    }

    public boolean setMemFactorLocked(int memFactor, boolean screenOn, long now) {
        mMemFactorLowered = memFactor < mLastMemOnlyState;
        mLastMemOnlyState = memFactor;
        if (screenOn) {
            memFactor += ADJ_SCREEN_ON;
        }
        if (memFactor != mState.mMemFactor) {
            if (mState.mMemFactor != STATE_NOTHING) {
                mState.mMemFactorDurations[mState.mMemFactor] += now - mState.mStartTime;
            }
            mState.mMemFactor = memFactor;
            mState.mStartTime = now;
            ArrayMap<String, SparseArray<PackageState>> pmap = mState.mPackages.getMap();
            for (int i=0; i<pmap.size(); i++) {
                SparseArray<PackageState> uids = pmap.valueAt(i);
                for (int j=0; j<uids.size(); j++) {
                    PackageState pkg = uids.valueAt(j);
                    ArrayMap<String, ServiceState> services = pkg.mServices;
                    for (int k=0; k<services.size(); k++) {
                        ServiceState service = services.valueAt(k);
                        if (service.isActive()) {
                            if (service.mStartedState != STATE_NOTHING) {
                                service.setStarted(true, memFactor, now);
                            }
                            if (service.mBoundState != STATE_NOTHING) {
                                service.setBound(true, memFactor, now);
                            }
                            if (service.mExecState != STATE_NOTHING) {
                                service.setExecuting(true, memFactor, now);
                            }
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    public int getMemFactorLocked() {
        return mState.mMemFactor != STATE_NOTHING ? mState.mMemFactor : 0;
    }

    public void readLocked() {
        mState.readLocked();
    }

    public boolean shouldWriteNowLocked(long now) {
        if (now > (mState.mLastWriteTime+WRITE_PERIOD)) {
            if (SystemClock.elapsedRealtime() > (mState.mTimePeriodStartRealtime+COMMIT_PERIOD)) {
                mCommitPending = true;
            }
            return true;
        }
        return false;
    }

    public void shutdownLocked() {
        Slog.w(TAG, "Writing process stats before shutdown...");
        mState.mFlags |= State.FLAG_SHUTDOWN;
        writeStateSyncLocked();
        mShuttingDown = true;
    }

    public void writeStateAsyncLocked() {
        writeStateLocked(false);
    }

    public void writeStateSyncLocked() {
        writeStateLocked(true);
    }

    private void writeStateLocked(boolean sync) {
        if (mShuttingDown) {
            return;
        }
        boolean commitPending = mCommitPending;
        mCommitPending = false;
        mState.writeStateLocked(sync, commitPending);
    }

    private ArrayList<String> getCommittedFiles(int minNum, boolean inclAll) {
        File[] files = mBaseDir.listFiles();
        if (files == null || files.length <= minNum) {
            return null;
        }
        ArrayList<String> filesArray = new ArrayList<String>(files.length);
        String currentFile = mState.mFile.getBaseFile().getPath();
        if (DEBUG) Slog.d(TAG, "Collecting " + files.length + " files except: " + currentFile);
        for (int i=0; i<files.length; i++) {
            File file = files[i];
            String fileStr = file.getPath();
            if (DEBUG) Slog.d(TAG, "Collecting: " + fileStr);
            if (!inclAll && fileStr.endsWith(STATE_FILE_CHECKIN_SUFFIX)) {
                if (DEBUG) Slog.d(TAG, "Skipping: already checked in");
                continue;
            }
            if (fileStr.equals(currentFile)) {
                if (DEBUG) Slog.d(TAG, "Skipping: current stats");
                continue;
            }
            filesArray.add(fileStr);
        }
        Collections.sort(filesArray);
        return filesArray;
    }

    public void trimHistoricStatesWriteLocked() {
        ArrayList<String> filesArray = getCommittedFiles(MAX_HISTORIC_STATES, true);
        if (filesArray == null) {
            return;
        }
        while (filesArray.size() > MAX_HISTORIC_STATES) {
            String file = filesArray.remove(0);
            Slog.i(TAG, "Pruning old procstats: " + file);
            (new File(file)).delete();
        }
    }

    static private void printScreenLabel(PrintWriter pw, int offset) {
        switch (offset) {
            case ADJ_NOTHING:
                pw.print("             ");
                break;
            case ADJ_SCREEN_OFF:
                pw.print("Screen Off / ");
                break;
            case ADJ_SCREEN_ON:
                pw.print("Screen On  / ");
                break;
            default:
                pw.print("?????????? / ");
                break;
        }
    }

    static private void printScreenLabelCsv(PrintWriter pw, int offset) {
        switch (offset) {
            case ADJ_NOTHING:
                break;
            case ADJ_SCREEN_OFF:
                pw.print(ADJ_SCREEN_NAMES_CSV[0]);
                break;
            case ADJ_SCREEN_ON:
                pw.print(ADJ_SCREEN_NAMES_CSV[1]);
                break;
            default:
                pw.print("???");
                break;
        }
    }

    static private void printMemLabel(PrintWriter pw, int offset) {
        switch (offset) {
            case ADJ_NOTHING:
                pw.print("       ");
                break;
            case ADJ_MEM_FACTOR_NORMAL:
                pw.print("Norm / ");
                break;
            case ADJ_MEM_FACTOR_MODERATE:
                pw.print("Mod  / ");
                break;
            case ADJ_MEM_FACTOR_LOW:
                pw.print("Low  / ");
                break;
            case ADJ_MEM_FACTOR_CRITICAL:
                pw.print("Crit / ");
                break;
            default:
                pw.print("???? / ");
                break;
        }
    }

    static private void printMemLabelCsv(PrintWriter pw, int offset) {
        if (offset >= ADJ_MEM_FACTOR_NORMAL) {
            if (offset <= ADJ_MEM_FACTOR_CRITICAL) {
                pw.print(ADJ_MEM_NAMES_CSV[offset]);
            } else {
                pw.print("???");
            }
        }
    }

    static long dumpSingleTime(PrintWriter pw, String prefix, long[] durations,
            int curState, long curStartTime, long now) {
        long totalTime = 0;
        int printedScreen = -1;
        for (int iscreen=0; iscreen<ADJ_COUNT; iscreen+=ADJ_SCREEN_MOD) {
            int printedMem = -1;
            for (int imem=0; imem<ADJ_MEM_FACTOR_COUNT; imem++) {
                int state = imem+iscreen;
                long time = durations[state];
                String running = "";
                if (curState == state) {
                    time += now - curStartTime;
                    if (pw != null) {
                        running = " (running)";
                    }
                }
                if (time != 0) {
                    if (pw != null) {
                        pw.print(prefix);
                        printScreenLabel(pw, printedScreen != iscreen
                                ? iscreen : STATE_NOTHING);
                        printedScreen = iscreen;
                        printMemLabel(pw, printedMem != imem ? imem : STATE_NOTHING);
                        printedMem = imem;
                        TimeUtils.formatDuration(time, pw); pw.println(running);
                    }
                    totalTime += time;
                }
            }
        }
        if (totalTime != 0 && pw != null) {
            pw.print(prefix);
            printScreenLabel(pw, STATE_NOTHING);
            pw.print("TOTAL: ");
            TimeUtils.formatDuration(totalTime, pw);
            pw.println();
        }
        return totalTime;
    }

    static void dumpAdjTimesCheckin(PrintWriter pw, String sep, long[] durations,
            int curState, long curStartTime, long now) {
        for (int iscreen=0; iscreen<ADJ_COUNT; iscreen+=ADJ_SCREEN_MOD) {
            for (int imem=0; imem<ADJ_MEM_FACTOR_COUNT; imem++) {
                int state = imem+iscreen;
                long time = durations[state];
                if (curState == state) {
                    time += now - curStartTime;
                }
                if (time != 0) {
                    printAdjTagAndValue(pw, state, time);
                }
            }
        }
    }

    static void dumpServiceTimeCheckin(PrintWriter pw, String label, String packageName,
            int uid, String serviceName, ServiceState svc, int serviceType, int opCount,
            int curState, long curStartTime, long now) {
        if (opCount <= 0) {
            return;
        }
        pw.print(label);
        pw.print(",");
        pw.print(packageName);
        pw.print(",");
        pw.print(uid);
        pw.print(",");
        pw.print(serviceName);
        pw.print(",");
        pw.print(opCount);
        boolean didCurState = false;
        for (int i=0; i<svc.mDurationsTableSize; i++) {
            int off = svc.mDurationsTable[i];
            int type = (off>>OFFSET_TYPE_SHIFT)&OFFSET_TYPE_MASK;
            int memFactor = type / ServiceState.SERVICE_COUNT;
            type %= ServiceState.SERVICE_COUNT;
            if (type != serviceType) {
                continue;
            }
            long time = svc.mState.getLong(off, 0);
            if (curState == memFactor) {
                didCurState = true;
                time += now - curStartTime;
            }
            printAdjTagAndValue(pw, memFactor, time);
        }
        if (!didCurState && curState != STATE_NOTHING) {
            printAdjTagAndValue(pw, curState, now - curStartTime);
        }
        pw.println();
    }

    static final class ProcessDataCollection {
        final int[] screenStates;
        final int[] memStates;
        final int[] procStates;

        long totalTime;
        long numPss;
        long minPss;
        long avgPss;
        long maxPss;
        long minUss;
        long avgUss;
        long maxUss;

        ProcessDataCollection(int[] _screenStates, int[] _memStates, int[] _procStates) {
            screenStates = _screenStates;
            memStates = _memStates;
            procStates = _procStates;
        }

        void print(PrintWriter pw, long overallTime, boolean full) {
            printPercent(pw, (double) totalTime / (double) overallTime);
            if (numPss > 0) {
                pw.print(" (");
                printSizeValue(pw, minPss * 1024);
                pw.print("-");
                printSizeValue(pw, avgPss * 1024);
                pw.print("-");
                printSizeValue(pw, maxPss * 1024);
                pw.print("/");
                printSizeValue(pw, minUss * 1024);
                pw.print("-");
                printSizeValue(pw, avgUss * 1024);
                pw.print("-");
                printSizeValue(pw, maxUss * 1024);
                if (full) {
                    pw.print(" over ");
                    pw.print(numPss);
                }
                pw.print(")");
            }
        }
    }

    static void computeProcessData(ProcessState proc, ProcessDataCollection data, long now) {
        data.totalTime = 0;
        data.numPss = data.minPss = data.avgPss = data.maxPss =
                data.minUss = data.avgUss = data.maxUss = 0;
        for (int is=0; is<data.screenStates.length; is++) {
            for (int im=0; im<data.memStates.length; im++) {
                for (int ip=0; ip<data.procStates.length; ip++) {
                    int bucket = ((data.screenStates[is] + data.memStates[im]) * STATE_COUNT)
                            + data.procStates[ip];
                    data.totalTime += proc.getDuration(bucket, now);
                    long samples = proc.getPssSampleCount(bucket);
                    if (samples > 0) {
                        long minPss = proc.getPssMinimum(bucket);
                        long avgPss = proc.getPssAverage(bucket);
                        long maxPss = proc.getPssMaximum(bucket);
                        long minUss = proc.getPssUssMinimum(bucket);
                        long avgUss = proc.getPssUssAverage(bucket);
                        long maxUss = proc.getPssUssMaximum(bucket);
                        if (data.numPss == 0) {
                            data.minPss = minPss;
                            data.avgPss = avgPss;
                            data.maxPss = maxPss;
                            data.minUss = minUss;
                            data.avgUss = avgUss;
                            data.maxUss = maxUss;
                        } else {
                            if (minPss < data.minPss) {
                                data.minPss = minPss;
                            }
                            data.avgPss = (long)( ((data.avgPss*(double)data.numPss)
                                    + (avgPss*(double)samples)) / (data.numPss+samples) );
                            if (maxPss > data.maxPss) {
                                data.maxPss = maxPss;
                            }
                            if (minUss < data.minUss) {
                                data.minUss = minUss;
                            }
                            data.avgUss = (long)( ((data.avgUss*(double)data.numPss)
                                    + (avgUss*(double)samples)) / (data.numPss+samples) );
                            if (maxUss > data.maxUss) {
                                data.maxUss = maxUss;
                            }
                        }
                        data.numPss += samples;
                    }
                }
            }
        }
    }

    static long computeProcessTimeLocked(ProcessState proc, int[] screenStates, int[] memStates,
                int[] procStates, long now) {
        long totalTime = 0;
        /*
        for (int i=0; i<proc.mDurationsTableSize; i++) {
            int val = proc.mDurationsTable[i];
            totalTime += proc.mState.getLong(val, 0);
            if ((val&0xff) == proc.mCurState) {
                totalTime += now - proc.mStartTime;
            }
        }
        */
        for (int is=0; is<screenStates.length; is++) {
            for (int im=0; im<memStates.length; im++) {
                for (int ip=0; ip<procStates.length; ip++) {
                    int bucket = ((screenStates[is] + memStates[im]) * STATE_COUNT)
                            + procStates[ip];
                    totalTime += proc.getDuration(bucket, now);
                }
            }
        }
        proc.mTmpTotalTime = totalTime;
        return totalTime;
    }

    static void dumpProcessState(PrintWriter pw, String prefix, ProcessState proc,
            int[] screenStates, int[] memStates, int[] procStates, long now) {
        long totalTime = 0;
        int printedScreen = -1;
        for (int is=0; is<screenStates.length; is++) {
            int printedMem = -1;
            for (int im=0; im<memStates.length; im++) {
                for (int ip=0; ip<procStates.length; ip++) {
                    final int iscreen = screenStates[is];
                    final int imem = memStates[im];
                    final int bucket = ((iscreen + imem) * STATE_COUNT) + procStates[ip];
                    long time = proc.getDuration(bucket, now);
                    String running = "";
                    if (proc.mCurState == bucket) {
                        running = " (running)";
                    }
                    if (time != 0) {
                        pw.print(prefix);
                        if (screenStates.length > 1) {
                            printScreenLabel(pw, printedScreen != iscreen
                                    ? iscreen : STATE_NOTHING);
                            printedScreen = iscreen;
                        }
                        if (memStates.length > 1) {
                            printMemLabel(pw, printedMem != imem ? imem : STATE_NOTHING);
                            printedMem = imem;
                        }
                        pw.print(STATE_NAMES[procStates[ip]]); pw.print(": ");
                        TimeUtils.formatDuration(time, pw); pw.println(running);
                        totalTime += time;
                    }
                }
            }
        }
        if (totalTime != 0) {
            pw.print(prefix);
            if (screenStates.length > 1) {
                printScreenLabel(pw, STATE_NOTHING);
            }
            if (memStates.length > 1) {
                printMemLabel(pw, STATE_NOTHING);
            }
            pw.print("TOTAL     : ");
            TimeUtils.formatDuration(totalTime, pw);
            pw.println();
        }
    }

    static void dumpProcessPss(PrintWriter pw, String prefix, ProcessState proc, int[] screenStates,
            int[] memStates, int[] procStates) {
        boolean printedHeader = false;
        int printedScreen = -1;
        for (int is=0; is<screenStates.length; is++) {
            int printedMem = -1;
            for (int im=0; im<memStates.length; im++) {
                for (int ip=0; ip<procStates.length; ip++) {
                    final int iscreen = screenStates[is];
                    final int imem = memStates[im];
                    final int bucket = ((iscreen + imem) * STATE_COUNT) + procStates[ip];
                    long count = proc.getPssSampleCount(bucket);
                    if (count > 0) {
                        if (!printedHeader) {
                            pw.print(prefix);
                            pw.print("PSS/USS (");
                            pw.print(proc.mPssTableSize);
                            pw.println(" entries):");
                            printedHeader = true;
                        }
                        pw.print(prefix);
                        pw.print("  ");
                        if (screenStates.length > 1) {
                            printScreenLabel(pw, printedScreen != iscreen
                                    ? iscreen : STATE_NOTHING);
                            printedScreen = iscreen;
                        }
                        if (memStates.length > 1) {
                            printMemLabel(pw, printedMem != imem ? imem : STATE_NOTHING);
                            printedMem = imem;
                        }
                        pw.print(STATE_NAMES[procStates[ip]]); pw.print(": ");
                        pw.print(count);
                        pw.print(" samples ");
                        printSizeValue(pw, proc.getPssMinimum(bucket) * 1024);
                        pw.print(" ");
                        printSizeValue(pw, proc.getPssAverage(bucket) * 1024);
                        pw.print(" ");
                        printSizeValue(pw, proc.getPssMaximum(bucket) * 1024);
                        pw.print(" / ");
                        printSizeValue(pw, proc.getPssUssMinimum(bucket) * 1024);
                        pw.print(" ");
                        printSizeValue(pw, proc.getPssUssAverage(bucket) * 1024);
                        pw.print(" ");
                        printSizeValue(pw, proc.getPssUssMaximum(bucket) * 1024);
                        pw.println();
                    }
                }
            }
        }
        if (proc.mNumExcessiveWake != 0) {
            pw.print(prefix); pw.print("Killed for excessive wake locks: ");
                    pw.print(proc.mNumExcessiveWake); pw.println(" times");
        }
        if (proc.mNumExcessiveCpu != 0) {
            pw.print(prefix); pw.print("Killed for excessive CPU use: ");
                    pw.print(proc.mNumExcessiveCpu); pw.println(" times");
        }
    }

    static void dumpStateHeadersCsv(PrintWriter pw, String sep, int[] screenStates,
            int[] memStates, int[] procStates) {
        final int NS = screenStates != null ? screenStates.length : 1;
        final int NM = memStates != null ? memStates.length : 1;
        final int NP = procStates != null ? procStates.length : 1;
        for (int is=0; is<NS; is++) {
            for (int im=0; im<NM; im++) {
                for (int ip=0; ip<NP; ip++) {
                    pw.print(sep);
                    boolean printed = false;
                    if (screenStates != null && screenStates.length > 1) {
                        printScreenLabelCsv(pw, screenStates[is]);
                        printed = true;
                    }
                    if (memStates != null && memStates.length > 1) {
                        if (printed) {
                            pw.print("-");
                        }
                        printMemLabelCsv(pw, memStates[im]);
                        printed = true;
                    }
                    if (procStates != null && procStates.length > 1) {
                        if (printed) {
                            pw.print("-");
                        }
                        pw.print(STATE_NAMES_CSV[procStates[ip]]);
                    }
                }
            }
        }
    }

    static void dumpProcessStateCsv(PrintWriter pw, ProcessState proc,
            boolean sepScreenStates, int[] screenStates, boolean sepMemStates, int[] memStates,
            boolean sepProcStates, int[] procStates, long now) {
        final int NSS = sepScreenStates ? screenStates.length : 1;
        final int NMS = sepMemStates ? memStates.length : 1;
        final int NPS = sepProcStates ? procStates.length : 1;
        for (int iss=0; iss<NSS; iss++) {
            for (int ims=0; ims<NMS; ims++) {
                for (int ips=0; ips<NPS; ips++) {
                    final int vsscreen = sepScreenStates ? screenStates[iss] : 0;
                    final int vsmem = sepMemStates ? memStates[ims] : 0;
                    final int vsproc = sepProcStates ? procStates[ips] : 0;
                    final int NSA = sepScreenStates ? 1 : screenStates.length;
                    final int NMA = sepMemStates ? 1 : memStates.length;
                    final int NPA = sepProcStates ? 1 : procStates.length;
                    long totalTime = 0;
                    for (int isa=0; isa<NSA; isa++) {
                        for (int ima=0; ima<NMA; ima++) {
                            for (int ipa=0; ipa<NPA; ipa++) {
                                final int vascreen = sepScreenStates ? 0 : screenStates[isa];
                                final int vamem = sepMemStates ? 0 : memStates[ima];
                                final int vaproc = sepProcStates ? 0 : procStates[ipa];
                                final int bucket = ((vsscreen + vascreen + vsmem + vamem)
                                        * STATE_COUNT) + vsproc + vaproc;
                                totalTime += proc.getDuration(bucket, now);
                            }
                        }
                    }
                    pw.print(CSV_SEP);
                    pw.print(totalTime);
                }
            }
        }
    }

    static void dumpProcessList(PrintWriter pw, String prefix, ArrayList<ProcessState> procs,
            int[] screenStates, int[] memStates, int[] procStates, long now) {
        String innerPrefix = prefix + "  ";
        for (int i=procs.size()-1; i>=0; i--) {
            ProcessState proc = procs.get(i);
            pw.print(prefix);
            pw.print(proc.mName);
            pw.print(" / ");
            UserHandle.formatUid(pw, proc.mUid);
            pw.print(" (");
            pw.print(proc.mDurationsTableSize);
            pw.print(" entries)");
            pw.println(":");
            dumpProcessState(pw, innerPrefix, proc, screenStates, memStates, procStates, now);
            if (proc.mPssTableSize > 0) {
                dumpProcessPss(pw, innerPrefix, proc, screenStates, memStates, procStates);
            }
        }
    }

    static void dumpProcessSummaryDetails(PrintWriter pw, ProcessState proc, String prefix,
            String label, int[] screenStates, int[] memStates, int[] procStates,
            long now, long totalTime, boolean full) {
        ProcessDataCollection totals = new ProcessDataCollection(screenStates,
                memStates, procStates);
        computeProcessData(proc, totals, now);
        if (totals.totalTime != 0 || totals.numPss != 0) {
            if (prefix != null) {
                pw.print(prefix);
            }
            if (label != null) {
                pw.print(label);
            }
            totals.print(pw, totalTime, full);
            if (prefix != null) {
                pw.println();
            }
        }
    }

    static void dumpProcessSummaryLocked(PrintWriter pw, String prefix,
            ArrayList<ProcessState> procs, int[] screenStates, int[] memStates, int[] procStates,
            long now, long totalTime) {
        for (int i=procs.size()-1; i>=0; i--) {
            ProcessState proc = procs.get(i);
            pw.print(prefix);
            pw.print("* ");
            pw.print(proc.mName);
            pw.print(" / ");
            UserHandle.formatUid(pw, proc.mUid);
            pw.println(":");
            dumpProcessSummaryDetails(pw, proc, prefix, "         TOTAL: ", screenStates, memStates,
                    procStates, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "    Persistent: ", screenStates, memStates,
                    new int[] { STATE_PERSISTENT }, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "           Top: ", screenStates, memStates,
                    new int[] {STATE_TOP}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "        Imp Fg: ", screenStates, memStates,
                    new int[] { STATE_IMPORTANT_FOREGROUND }, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "        Imp Bg: ", screenStates, memStates,
                    new int[] {STATE_IMPORTANT_BACKGROUND}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "        Backup: ", screenStates, memStates,
                    new int[] {STATE_BACKUP}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "     Heavy Wgt: ", screenStates, memStates,
                    new int[] {STATE_HEAVY_WEIGHT}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "       Service: ", screenStates, memStates,
                    new int[] {STATE_SERVICE}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "    Service Rs: ", screenStates, memStates,
                    new int[] {STATE_SERVICE_RESTARTING}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "      Receiver: ", screenStates, memStates,
                    new int[] {STATE_RECEIVER}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "          Home: ", screenStates, memStates,
                    new int[] {STATE_HOME}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "    (Last Act): ", screenStates, memStates,
                    new int[] {STATE_LAST_ACTIVITY}, now, totalTime, true);
            dumpProcessSummaryDetails(pw, proc, prefix, "      (Cached): ", screenStates, memStates,
                    new int[] {STATE_CACHED_ACTIVITY, STATE_CACHED_ACTIVITY_CLIENT,
                            STATE_CACHED_EMPTY}, now, totalTime, true);
        }
    }

    static void printPercent(PrintWriter pw, double fraction) {
        fraction *= 100;
        if (fraction < 1) {
            pw.print(String.format("%.2f", fraction));
        } else if (fraction < 10) {
            pw.print(String.format("%.1f", fraction));
        } else {
            pw.print(String.format("%.0f", fraction));
        }
        pw.print("%");
    }

    static void printSizeValue(PrintWriter pw, long number) {
        float result = number;
        String suffix = "";
        if (result > 900) {
            suffix = "KB";
            result = result / 1024;
        }
        if (result > 900) {
            suffix = "MB";
            result = result / 1024;
        }
        if (result > 900) {
            suffix = "GB";
            result = result / 1024;
        }
        if (result > 900) {
            suffix = "TB";
            result = result / 1024;
        }
        if (result > 900) {
            suffix = "PB";
            result = result / 1024;
        }
        String value;
        if (result < 1) {
            value = String.format("%.2f", result);
        } else if (result < 10) {
            value = String.format("%.1f", result);
        } else if (result < 100) {
            value = String.format("%.0f", result);
        } else {
            value = String.format("%.0f", result);
        }
        pw.print(value);
        pw.print(suffix);
    }

    static void dumpProcessListCsv(PrintWriter pw, ArrayList<ProcessState> procs,
            boolean sepScreenStates, int[] screenStates, boolean sepMemStates, int[] memStates,
            boolean sepProcStates, int[] procStates, long now) {
        pw.print("process");
        pw.print(CSV_SEP);
        pw.print("uid");
        dumpStateHeadersCsv(pw, CSV_SEP, sepScreenStates ? screenStates : null,
                sepMemStates ? memStates : null,
                sepProcStates ? procStates : null);
        pw.println();
        for (int i=procs.size()-1; i>=0; i--) {
            ProcessState proc = procs.get(i);
            pw.print(proc.mName);
            pw.print(CSV_SEP);
            UserHandle.formatUid(pw, proc.mUid);
            dumpProcessStateCsv(pw, proc, sepScreenStates, screenStates,
                    sepMemStates, memStates, sepProcStates, procStates, now);
            pw.println();
        }
    }

    boolean dumpFilteredProcessesCsvLocked(PrintWriter pw, String header,
            boolean sepScreenStates, int[] screenStates, boolean sepMemStates, int[] memStates,
            boolean sepProcStates, int[] procStates, long now, String reqPackage) {
        ArrayList<ProcessState> procs = mState.collectProcessesLocked(screenStates, memStates,
                procStates, now, reqPackage);
        if (procs.size() > 0) {
            if (header != null) {
                pw.println(header);
            }
            dumpProcessListCsv(pw, procs, sepScreenStates, screenStates,
                    sepMemStates, memStates, sepProcStates, procStates, now);
            return true;
        }
        return false;
    }

    static int printArrayEntry(PrintWriter pw, String[] array, int value, int mod) {
        int index = value/mod;
        if (index >= 0 && index < array.length) {
            pw.print(array[index]);
        } else {
            pw.print('?');
        }
        return value - index*mod;
    }

    static void printProcStateTag(PrintWriter pw, int state) {
        state = printArrayEntry(pw, ADJ_SCREEN_TAGS,  state, ADJ_SCREEN_MOD*STATE_COUNT);
        state = printArrayEntry(pw, ADJ_MEM_TAGS,  state, STATE_COUNT);
        printArrayEntry(pw, STATE_TAGS,  state, 1);
    }

    static void printAdjTag(PrintWriter pw, int state) {
        state = printArrayEntry(pw, ADJ_SCREEN_TAGS,  state, ADJ_SCREEN_MOD);
        printArrayEntry(pw, ADJ_MEM_TAGS, state, 1);
    }

    static void printProcStateTagAndValue(PrintWriter pw, int state, long value) {
        pw.print(',');
        printProcStateTag(pw, state);
        pw.print(':');
        pw.print(value);
    }

    static void printAdjTagAndValue(PrintWriter pw, int state, long value) {
        pw.print(',');
        printAdjTag(pw, state);
        pw.print(':');
        pw.print(value);
    }

    static void dumpAllProcessStateCheckin(PrintWriter pw, ProcessState proc, long now) {
        boolean didCurState = false;
        for (int i=0; i<proc.mDurationsTableSize; i++) {
            int off = proc.mDurationsTable[i];
            int type = (off>>OFFSET_TYPE_SHIFT)&OFFSET_TYPE_MASK;
            long time = proc.mState.getLong(off, 0);
            if (proc.mCurState == type) {
                didCurState = true;
                time += now - proc.mStartTime;
            }
            printProcStateTagAndValue(pw, type, time);
        }
        if (!didCurState && proc.mCurState != STATE_NOTHING) {
            printProcStateTagAndValue(pw, proc.mCurState, now - proc.mStartTime);
        }
    }

    static void dumpAllProcessPssCheckin(PrintWriter pw, ProcessState proc) {
        for (int i=0; i<proc.mPssTableSize; i++) {
            int off = proc.mPssTable[i];
            int type = (off>>OFFSET_TYPE_SHIFT)&OFFSET_TYPE_MASK;
            long count = proc.mState.getLong(off, PSS_SAMPLE_COUNT);
            long min = proc.mState.getLong(off, PSS_MINIMUM);
            long avg = proc.mState.getLong(off, PSS_AVERAGE);
            long max = proc.mState.getLong(off, PSS_MAXIMUM);
            long umin = proc.mState.getLong(off, PSS_USS_MINIMUM);
            long uavg = proc.mState.getLong(off, PSS_USS_AVERAGE);
            long umax = proc.mState.getLong(off, PSS_USS_MAXIMUM);
            pw.print(',');
            printProcStateTag(pw, type);
            pw.print(':');
            pw.print(count);
            pw.print(':');
            pw.print(min);
            pw.print(':');
            pw.print(avg);
            pw.print(':');
            pw.print(max);
            pw.print(':');
            pw.print(umin);
            pw.print(':');
            pw.print(uavg);
            pw.print(':');
            pw.print(umax);
        }
    }

    static int[] parseStateList(String[] states, int mult, String arg, boolean[] outSep,
            String[] outError) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        int lastPos = 0;
        for (int i=0; i<=arg.length(); i++) {
            char c = i < arg.length() ? arg.charAt(i) : 0;
            if (c != ',' && c != '+' && c != ' ' && c != 0) {
                continue;
            }
            boolean isSep = c == ',';
            if (lastPos == 0) {
                // We now know the type of op.
                outSep[0] = isSep;
            } else if (c != 0 && outSep[0] != isSep) {
                outError[0] = "inconsistent separators (can't mix ',' with '+')";
                return null;
            }
            if (lastPos < (i-1)) {
                String str = arg.substring(lastPos, i);
                for (int j=0; j<states.length; j++) {
                    if (str.equals(states[j])) {
                        res.add(j);
                        str = null;
                        break;
                    }
                }
                if (str != null) {
                    outError[0] = "invalid word \"" + str + "\"";
                    return null;
                }
            }
            lastPos = i + 1;
        }

        int[] finalRes = new int[res.size()];
        for (int i=0; i<res.size(); i++) {
            finalRes[i] = res.get(i) * mult;
        }
        return finalRes;
    }

    static private void dumpHelp(PrintWriter pw) {
        pw.println("Process stats (procstats) dump options:");
        pw.println("    [--checkin|-c|--csv] [--csv-screen] [--csv-proc] [--csv-mem]");
        pw.println("    [--details] [--current] [--commit] [--write] [-h] [<package.name>]");
        pw.println("  --checkin: perform a checkin: print and delete old committed states.");
        pw.println("  --c: print only state in checkin format.");
        pw.println("  --csv: output data suitable for putting in a spreadsheet.");
        pw.println("  --csv-screen: on, off.");
        pw.println("  --csv-mem: norm, mod, low, crit.");
        pw.println("  --csv-proc: pers, top, fore, vis, precept, backup,");
        pw.println("    service, home, prev, cached");
        pw.println("  --details: dump all execution details, not just summary.");
        pw.println("  --current: only dump current state.");
        pw.println("  --commit: commit current stats to disk and reset to start new stats.");
        pw.println("  --write: write current in-memory stats to disk.");
        pw.println("  --read: replace current stats with last-written stats.");
        pw.println("  -a: print everything.");
        pw.println("  -h: print this help text.");
        pw.println("  <package.name>: optional name of package to filter output by.");
    }

    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        final long now = SystemClock.uptimeMillis();

        boolean isCheckin = false;
        boolean isCompact = false;
        boolean isCsv = false;
        boolean currentOnly = false;
        boolean dumpDetails = false;
        boolean dumpAll = false;
        String reqPackage = null;
        boolean csvSepScreenStats = false;
        int[] csvScreenStats = new int[] {ADJ_SCREEN_OFF, ADJ_SCREEN_ON};
        boolean csvSepMemStats = false;
        int[] csvMemStats = new int[] {ADJ_MEM_FACTOR_CRITICAL};
        boolean csvSepProcStats = true;
        int[] csvProcStats = ALL_PROC_STATES;
        if (args != null) {
            for (int i=0; i<args.length; i++) {
                String arg = args[i];
                if ("--checkin".equals(arg)) {
                    isCheckin = true;
                } else if ("-c".equals(arg)) {
                    isCompact = true;
                } else if ("--csv".equals(arg)) {
                    isCsv = true;
                } else if ("--csv-screen".equals(arg)) {
                    i++;
                    if (i >= args.length) {
                        pw.println("Error: argument required for --csv-screen");
                        dumpHelp(pw);
                        return;
                    }
                    boolean[] sep = new boolean[1];
                    String[] error = new String[1];
                    csvScreenStats = parseStateList(ADJ_SCREEN_NAMES_CSV, ADJ_SCREEN_MOD,
                            args[i], sep, error);
                    if (csvScreenStats == null) {
                        pw.println("Error in \"" + args[i] + "\": " + error[0]);
                        dumpHelp(pw);
                        return;
                    }
                    csvSepScreenStats = sep[0];
                } else if ("--csv-mem".equals(arg)) {
                    i++;
                    if (i >= args.length) {
                        pw.println("Error: argument required for --csv-mem");
                        dumpHelp(pw);
                        return;
                    }
                    boolean[] sep = new boolean[1];
                    String[] error = new String[1];
                    csvMemStats = parseStateList(ADJ_MEM_NAMES_CSV, 1, args[i], sep, error);
                    if (csvMemStats == null) {
                        pw.println("Error in \"" + args[i] + "\": " + error[0]);
                        dumpHelp(pw);
                        return;
                    }
                    csvSepMemStats = sep[0];
                } else if ("--csv-proc".equals(arg)) {
                    i++;
                    if (i >= args.length) {
                        pw.println("Error: argument required for --csv-proc");
                        dumpHelp(pw);
                        return;
                    }
                    boolean[] sep = new boolean[1];
                    String[] error = new String[1];
                    csvProcStats = parseStateList(STATE_NAMES_CSV, 1, args[i], sep, error);
                    if (csvProcStats == null) {
                        pw.println("Error in \"" + args[i] + "\": " + error[0]);
                        dumpHelp(pw);
                        return;
                    }
                    csvSepProcStats = sep[0];
                } else if ("--details".equals(arg)) {
                    dumpDetails = true;
                } else if ("--current".equals(arg)) {
                    currentOnly = true;
                } else if ("--commit".equals(arg)) {
                    mState.mFlags |= State.FLAG_COMPLETE;
                    mState.writeStateLocked(true, true);
                    pw.println("Process stats committed.");
                    return;
                } else if ("--write".equals(arg)) {
                    writeStateSyncLocked();
                    pw.println("Process stats written.");
                    return;
                } else if ("--read".equals(arg)) {
                    readLocked();
                    pw.println("Process stats read.");
                    return;
                } else if ("-h".equals(arg)) {
                    dumpHelp(pw);
                    return;
                } else if ("-a".equals(arg)) {
                    dumpDetails = true;
                    dumpAll = true;
                } else if (arg.length() > 0 && arg.charAt(0) == '-'){
                    pw.println("Unknown option: " + arg);
                    dumpHelp(pw);
                    return;
                } else {
                    // Not an option, last argument must be a package name.
                    try {
                        IPackageManager pm = AppGlobals.getPackageManager();
                        if (pm.getPackageUid(arg, UserHandle.getCallingUserId()) >= 0) {
                            reqPackage = arg;
                            // Include all details, since we know we are only going to
                            // be dumping a smaller set of data.  In fact only the details
                            // container per-package data, so that are needed to be able
                            // to dump anything at all when filtering by package.
                            dumpDetails = true;
                        }
                    } catch (RemoteException e) {
                    }
                    if (reqPackage == null) {
                        pw.println("Unknown package: " + arg);
                        dumpHelp(pw);
                        return;
                    }
                }
            }
        }

        if (isCsv) {
            pw.print("Processes running summed over");
            if (!csvSepScreenStats) {
                for (int i=0; i<csvScreenStats.length; i++) {
                    pw.print(" ");
                    printScreenLabelCsv(pw, csvScreenStats[i]);
                }
            }
            if (!csvSepMemStats) {
                for (int i=0; i<csvMemStats.length; i++) {
                    pw.print(" ");
                    printMemLabelCsv(pw, csvMemStats[i]);
                }
            }
            if (!csvSepProcStats) {
                for (int i=0; i<csvProcStats.length; i++) {
                    pw.print(" ");
                    pw.print(STATE_NAMES_CSV[csvProcStats[i]]);
                }
            }
            pw.println();
            synchronized (mLock) {
                dumpFilteredProcessesCsvLocked(pw, null,
                        csvSepScreenStats, csvScreenStats, csvSepMemStats, csvMemStats,
                        csvSepProcStats, csvProcStats, now, reqPackage);
                /*
                dumpFilteredProcessesCsvLocked(pw, "Processes running while critical mem:",
                        false, new int[] {ADJ_SCREEN_OFF, ADJ_SCREEN_ON},
                        true, new int[] {ADJ_MEM_FACTOR_CRITICAL},
                        true, new int[] {STATE_PERSISTENT, STATE_TOP, STATE_FOREGROUND, STATE_VISIBLE,
                                STATE_PERCEPTIBLE, STATE_BACKUP, STATE_SERVICE, STATE_HOME,
                                STATE_PREVIOUS, STATE_CACHED},
                        now, reqPackage);
                dumpFilteredProcessesCsvLocked(pw, "Processes running over all mem:",
                        false, new int[] {ADJ_SCREEN_OFF, ADJ_SCREEN_ON},
                        false, new int[] {ADJ_MEM_FACTOR_CRITICAL, ADJ_MEM_FACTOR_LOW,
                                ADJ_MEM_FACTOR_MODERATE, ADJ_MEM_FACTOR_MODERATE},
                        true, new int[] {STATE_PERSISTENT, STATE_TOP, STATE_FOREGROUND, STATE_VISIBLE,
                                STATE_PERCEPTIBLE, STATE_BACKUP, STATE_SERVICE, STATE_HOME,
                                STATE_PREVIOUS, STATE_CACHED},
                        now, reqPackage);
                */
            }
            return;
        }

        boolean sepNeeded = false;
        if (!currentOnly || isCheckin) {
            mWriteLock.lock();
            try {
                ArrayList<String> files = getCommittedFiles(0, !isCheckin);
                if (files != null) {
                    for (int i=0; i<files.size(); i++) {
                        if (DEBUG) Slog.d(TAG, "Retrieving state: " + files.get(i));
                        try {
                            State state = new State(files.get(i));
                            if (state.mReadError != null) {
                                if (isCheckin || isCompact) pw.print("err,");
                                pw.print("Failure reading "); pw.print(files.get(i));
                                pw.print("; "); pw.println(state.mReadError);
                                if (DEBUG) Slog.d(TAG, "Deleting state: " + files.get(i));
                                (new File(files.get(i))).delete();
                                continue;
                            }
                            String fileStr = state.mFile.getBaseFile().getPath();
                            boolean checkedIn = fileStr.endsWith(STATE_FILE_CHECKIN_SUFFIX);
                            if (isCheckin || isCompact) {
                                // Don't really need to lock because we uniquely own this object.
                                state.dumpCheckinLocked(pw, reqPackage);
                            } else {
                                if (sepNeeded) {
                                    pw.println();
                                } else {
                                    sepNeeded = true;
                                }
                                pw.print("COMMITTED STATS FROM ");
                                pw.print(state.mTimePeriodStartClockStr);
                                if (checkedIn) pw.print(" (checked in)");
                                pw.println(":");
                                // Don't really need to lock because we uniquely own this object.
                                if (dumpDetails) {
                                    state.dumpLocked(pw, reqPackage, now, dumpAll);
                                } else {
                                    state.dumpSummaryLocked(pw, reqPackage, now);
                                }
                            }
                            if (isCheckin) {
                                // Rename file suffix to mark that it has checked in.
                                state.mFile.getBaseFile().renameTo(new File(
                                        fileStr + STATE_FILE_CHECKIN_SUFFIX));
                            }
                        } catch (Throwable e) {
                            pw.print("**** FAILURE DUMPING STATE: "); pw.println(files.get(i));
                            e.printStackTrace(pw);
                        }
                    }
                }
            } finally {
                mWriteLock.unlock();
            }
        }
        if (!isCheckin) {
            synchronized (mLock) {
                if (isCompact) {
                    mState.dumpCheckinLocked(pw, reqPackage);
                } else {
                    if (sepNeeded) {
                        pw.println();
                        pw.println("CURRENT STATS:");
                    }
                    if (dumpDetails) {
                        mState.dumpLocked(pw, reqPackage, now, dumpAll);
                    } else {
                        mState.dumpSummaryLocked(pw, reqPackage, now);
                    }
                }
            }
        }
    }
}