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

#define super IORegistryEntry

static void ack_timer_expired(thread_call_param_t);
static void settle_timer_expired(thread_call_param_t);
void PMreceiveCmd ( OSObject *,  void *, void *, void *, void * );
static void PM_idle_timer_expired(OSObject *, IOTimerEventSource *);
static void c_PM_Clamp_Timer_Expired (OSObject * client,IOTimerEventSource *);
void tellAppWithResponse ( OSObject * object, void * context);
void tellClientWithResponse ( OSObject * object, void * context);
void tellClient ( OSObject * object, void * context);
IOReturn serializedAllowPowerChange ( OSObject *, void *, void *, void *, void *);
IOReturn serializedCancelPowerChange ( OSObject *, void *, void *, void *, void *);

extern const IORegistryPlane * gIOPowerPlane;


// and there's 1000 nanoseconds in a microsecond:
#define ns_per_us 1000


// The current change note is processed by a state machine.
// Inputs are acks from interested parties, ack from the controlling driver,
// ack timeouts, settle timeout, and powerStateDidChange from the parent.
// These are the states:

enum {
    IOPMour_prechange_03 = 1,
    IOPMour_prechange_04,
    IOPMour_prechange_05,
    IOPMour_prechange_1,
    IOPMour_prechange_2,
    IOPMour_prechange_3,
    IOPMour_prechange_4,
    IOPMparent_down_0,
    IOPMparent_down_05,
    IOPMparent_down_2,
    IOPMparent_down_3,
    IOPMparent_down_4,
    IOPMparent_down_5,
    IOPMparent_down_6,
    IOPMparent_up_0,
    IOPMparent_up_1,
    IOPMparent_up_4,
    IOPMparent_up_5,
    IOPMparent_up_6,
    IOPMfinished
    };

enum {				// values of outofbandparameter
	kNotifyApps,
	kNotifyPriority
};

struct context {		// used for applyToInterested
    OSArray *	responseFlags;
    UInt16	serialNumber;
    UInt16 	counter;
    UInt32	maxTimeRequested;
    int		msgType;
    IOService *	us;
    IOLock *	flags_lock;
    unsigned long stateNumber;
    IOPMPowerFlags stateFlags;
};

                                // five minutes in microseconds
#define FIVE_MINUTES 5*60*1000000
#define k30seconds 30*1000000

/*
 There are two different kinds of power state changes.  One is initiated by a subclassed device object which has either
 decided to change power state, or its controlling driver has suggested it, or some other driver wants to use the
 idle device and has asked it to become usable.  The second kind of power state change is initiated by the power
 domain parent.  The two are handled slightly differently.

There is a queue of so-called change notifications, or change notes for short.  Usually the queue is empty, and when
 it isn't, usually there is one change note in it, but since it's possible to have more than one power state change pending
 at one time, a queue is implemented.  Example:  the subclass device decides it's idle and initiates a change to a lower
 power state.  This causes interested parties to be notified, but they don't all acknowledge right away.  This causes the
 change note to sit in the queue until all the acks are received.  During this time, the device decides it isn't idle anymore and
 wants to raise power back up again.  This change can't be started, however, because the previous one isn't complete yet,
 so the second one waits in the queue.  During this time, the parent decides to lower or raise the power state of the entire
 power domain and notifies the device, and that notification goes into the queue, too, and can't be actioned until the
 others are.

 This is how a power change initiated by the subclass device is handled:
 First, all interested parties are notified of the change via their powerStateWillChangeTo method.  If they all don't
 acknowledge via return code, then we have to wait.  If they do, or when they finally all acknowledge via our
 acknowledgePowerChange method, then we can continue.  We call the controlling driver, instructing it to change to
 the new state.  Then we wait for power to settle.  If there is no settling-time, or after it has passed, we notify
 interested parties again, this time via their powerStateDidChangeTo methods.  When they have all acked, we're done.
 If we lowered power and don't need the power domain to be in its current power state, we suggest to the parent that
 it lower the power domain state.

 This is how a change to a lower power domain state initiated by the parent is handled:
 First, we figure out what power state we will be in when the new domain state is reached.  Then all interested parties are
 notified that we are moving to that new state.  When they have acknowledged, we call the controlling driver to assume
 that state and we wait for power to settle.  Then we acknowledge our preparedness to our parent.  When all its interested
 parties have acknowledged, it lowers power and then notifies its interested parties again.  When we get this call, we notify
 our interested parties that the power state has changed, and when they have all acknowledged, we're done.

 This is how a change to a higher power domain state initiated by the parent is handled:
 We figure out what power state we will be in when the new domain state is reached.  If it is different from our current
 state we acknowledge the parent.  When all the parent's interested parties have acknowledged, it raises power in the
domain and waits for power to settle.  Then it  notifies everyone that the new state has been reached.  When we get this call,
 we call the controlling driver, instructing it  to assume the new state, and wait for power to settle.  Then we notify our interested
 parties.  When they all acknowledge  we are done.

 In either of the two cases above, it is possible that we will not be changing state even though the domain is.  Examples:
 A change to a lower domain state may not affect us because we are already in a low enough state, and
 We will not take advantage of a change to a higher domain state, because we have no need of the higher power.
 In such a case, there is nothing to do but acknowledge the parent.  So when the parent calls our powerDomainWillChange
 method, and we decide that we will not be changing state, we merely acknowledge the parent, via return code, and wait.
 When the parent subsequently calls powerStateDidChange, we acknowledge again via return code, and the change is complete.

 Power state changes are processed in a state machine, and since there are four varieties of power state changes, there are
 four major paths through the state machine:

 The fourth is nearly trivial.  In this path, the parent is changing the domain state, but we are not changing the device state.
 The change starts when the parent calls powerDomainWillChange.  All we do is acknowledge the parent.
When the parent calls powerStateDidChange, we acknowledge the parent again, and we're done.

 The first is fairly simple.  It starts when a power domain child calls requestPowerDomainState and we decide to change power states
 to accomodate the child, or if our power-controlling driver calls changePowerStateTo, or if some other driver which is using our
 device calls makeUsable, or if a subclassed object calls changePowerStateToPriv.  These are all power changes initiated by us, not
 forced upon us by the parent.  We start by notifying interested parties.  If they all acknowledge via return code, we can go
 on to state "our_prechange_1".  Otherwise, we start the ack timer and wait for the stragglers to acknowlege by calling
 acknowledgePowerChange.  We move on to state "our_prechange_1" when all the stragglers have acknowledged,
 or when the ack timer expires on all those which didn't acknowledge.  In "our_prechange_1" we call the power-controlling
 driver to change the power state of the hardware.  If it returns saying it has done so, we go on to state "our_prechange_2".
 Otherwise, we have to wait for it, so we set the ack timer and wait.  When it calls acknowledgeSetPowerState, or when the
 ack timer expires, we go on.  In "our_prechange_2", we look in the power state array to see if there is any settle time required
 when changing from our current state to the new state.  If not, we go right away to "our_prechange_3".  Otherwise, we
 set the settle timer and wait.  When it expires, we move on.  In "our_prechange_3" state, we notify all our interested parties
 via their powerStateDidChange methods that we have finished changing power state.  If they all acknowledge via return
 code, we move on to "our_prechange_4".  Otherwise we set the ack timer and wait.  When they have all acknowledged, or
 when the ack timer has expired for those that didn't, we move on to "our_prechange_4", where we remove the used
 change note from the head of the queue and start the next one if one exists.

 Parent-initiated changes are more complex in the state machine.  First, power going up and power going down are handled
 differently, so they have different paths throught the state machine.  Second, we can acknowledge the parent's notification
 in two different ways, so each of the parent paths is really two.

 When the parent calls our powerDomainWillChange method, notifying us that it will lower power in the domain, we decide
 what state that will put our device in.  Then we embark on the state machine path "IOPMparent_down_1"
 and "IOPMparent_down_2", in which we notify interested parties of the upcoming change,  instruct our driver to make
 the change, check for settle time, and notify interested parties of the completed change.   If we get to the end of this path without
 stalling due to an interested party which didn't acknowledge via return code, due to the controlling driver not able to change
 state right away, or due to a non-zero settling time, then we return IOPMAckImplied to the parent, and we're done with the change.
 If we do stall in any of those states, we return IOPMWillAckLater to the parent and enter the parallel path "IOPMparent_down_4"
 "IOPMparent_down_5", and "IOPMparent_down_3", where we continue with the same processing, except that at the end we
 acknowledge the parent explicitly via acknowledgePowerChange, and we're done with the change.
Then when the parent calls us at powerStateDidChange we acknowledging via return code, because we have already made
 the power change.  In any case, when we are done we remove the used change note from the head of the queue and start on the next one.

 The case of the parent raising power in the domain is handled similarly in that there are parallel paths, one for no-stall
 that ends in implicit acknowleging the parent, and one that has stalled at least once that ends in explicit acknowledging
 the parent.  This case is different, though in that our device changes state in the second half, after the parent calls
 powerStateDidChange rather than before, as in the power-lowering case.

 When the parent calls our powerDomainWillChange method, notifying us that it will raise power in the domain, we acknowledge
 via return code, because there's really nothing we can do until the power is actually raised in the domain.
 When the parent calls us at powerStateDidChange, we start by notifying our interested parties.  If they all acknowledge via return code,
 we go on to" IOPMparent_up_1" to instruct the driver to raise its power level. After that, we check for any
 necessary settling time in "IOPMparent_up_2", and we notify all interested parties that power has changed
 in "IOPMparent_up_3".  If none of these operations stall, we acknowledge the parent via return code, release
 the change note, and start the next, if there is one.  If one of them does stall, we enter the parallel path  "IOPMparent_up_0",
 "IOPMparent_up_4", "IOPMparent_up_5", and "IOPMparent_up_6", which ends with
 our explicit acknowledgement to the parent.

*/


const char priv_key[ ] = "Power Management private data";
const char prot_key[ ] = "Power Management protected data";


void IOService::PMinit ( void )
{
    if ( ! initialized ) {

        pm_vars =  new IOPMprot;					// make space for our variables
        priv = new IOPMpriv;
        pm_vars->init();
        priv->init();
        
        setProperty(prot_key, (OSObject *) pm_vars);			// add these to the properties
        setProperty(priv_key, (OSObject *) priv);

        priv->owner = this;
        pm_vars->theNumberOfPowerStates = 0;				// then initialize them
        priv->we_are_root = false;
        pm_vars->theControllingDriver = NULL;
        priv->our_lock = IOLockAlloc();
        priv->flags_lock = IOLockAlloc();
        priv->queue_lock = IOLockAlloc();
        pm_vars->childLock = IOLockAlloc();
        pm_vars->parentLock = IOLockAlloc();
        priv->interestedDrivers = new IOPMinformeeList;
        priv->interestedDrivers->initialize();
        priv->changeList = new IOPMchangeNoteList;
        priv->changeList->initialize();
        pm_vars->aggressiveness = 0;
        for (unsigned int i = 0; i <= kMaxType; i++) {
	     pm_vars->current_aggressiveness_values[i] = 0;
	     pm_vars->current_aggressiveness_valid[i] = false;
        }
        pm_vars->myCurrentState =  0;
        priv->imminentState = 0;
        priv->ourDesiredPowerState = 0;
        pm_vars->parentsCurrentPowerFlags = 0;
        pm_vars->maxCapability = 0;
        priv->driverDesire = 0;
        priv->deviceDesire = 0;
        priv->initial_change = true;
        priv->need_to_become_usable = false;
        priv->previousRequest = 0;
        priv->device_overrides = false;
        priv->machine_state = IOPMfinished;
        pm_vars->commandQueue = NULL;
        priv->timerEventSrc = NULL;
        priv->clampTimerEventSrc = NULL;
        pm_vars->PMworkloop = NULL;
        priv->activityLock = NULL;
        pm_vars->ourName = getName();
        pm_vars->thePlatform = getPlatform();
        pm_vars->parentsKnowState = false;
        assert( pm_vars->thePlatform != 0 );
        priv->clampOn = false;
        pm_vars->serialNumber = 0;
        pm_vars->responseFlags = NULL;
        pm_vars->doNotPowerDown = true;
        pm_vars->PMcommandGate = NULL;
        priv->ackTimer = thread_call_allocate((thread_call_func_t)ack_timer_expired, (thread_call_param_t)this);
        priv->settleTimer = thread_call_allocate((thread_call_func_t)settle_timer_expired, (thread_call_param_t)this);
        initialized = true;
    }
}


//*********************************************************************************
// PMfree
//
// Free up the data created in PMinit, if it exists.
//*********************************************************************************
void IOService::PMfree ( void )
{
    if ( priv ) {
        if (  priv->clampTimerEventSrc != NULL ) {
            getPMworkloop()->removeEventSource(priv->clampTimerEventSrc);
            priv->clampTimerEventSrc->release();
            priv->clampTimerEventSrc = NULL;
        }
        if (  priv->timerEventSrc != NULL ) {
            pm_vars->PMworkloop->removeEventSource(priv->timerEventSrc);
            priv->timerEventSrc->release();
            priv->timerEventSrc = NULL;
        }
        if ( priv->settleTimer ) {
            thread_call_cancel(priv->settleTimer);
            thread_call_free(priv->settleTimer);
            priv->settleTimer = NULL;
        }
        if ( priv->ackTimer ) {
            thread_call_cancel(priv->ackTimer);
            thread_call_free(priv->ackTimer);
            priv->ackTimer = NULL;
        }
        if ( priv->our_lock ) {
            IOLockFree(priv->our_lock);
            priv->our_lock = NULL;
        }
        if ( priv->flags_lock ) {
            IOLockFree(priv->flags_lock);
            priv->flags_lock = NULL;
        }
        if ( priv->activityLock ) {
            IOLockFree(priv->activityLock);
            priv->activityLock = NULL;
        }
        priv->interestedDrivers->release();
        priv->changeList->release();
        priv->release();				// remove instance variables
    }
    
    if ( pm_vars ) {
        if ( pm_vars->commandQueue ) {
            pm_vars->commandQueue->release();
            pm_vars->commandQueue = NULL;
        }
        if ( pm_vars->PMcommandGate ) {
            pm_vars->PMcommandGate->release();
            pm_vars->PMcommandGate = NULL;
        }
        if ( pm_vars->PMworkloop ) {
            // The work loop object returned from getPMworkLoop() is
            // never retained, therefore it should not be released.
            // pm_vars->PMworkloop->release();
            pm_vars->PMworkloop = NULL;
        }
        if ( pm_vars->responseFlags ) {
            pm_vars->responseFlags->release();
            pm_vars->responseFlags = NULL;
        }
        pm_vars->release();				// remove instance variables
    }
}


//*********************************************************************************
// PMstop
//
// Disconnect the node from its parents and children in the Power Plane.
//*********************************************************************************
void IOService::PMstop ( void )
{
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;
    IOService *		theChild;
    IOService *		theParent;

    removeProperty(prot_key);			// remove the properties
    removeProperty(priv_key);
    
    iter = getParentIterator(gIOPowerPlane);	// detach parents

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                theParent = (IOService *)connection->copyParentEntry(gIOPowerPlane);
                if ( theParent ) {
                    theParent->removePowerChild(connection);
                    theParent->release();
                }
            }
        }
        iter->release();
    }
    detachAbove( gIOPowerPlane );		// detach IOConnections   
    
    pm_vars->parentsKnowState = false;		// no more power state changes

    iter = getChildIterator(gIOPowerPlane);	// detach children

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                theChild = ((IOService *)(connection->copyChildEntry(gIOPowerPlane)));
                if ( theChild ) {
                    connection->detachFromChild(theChild,gIOPowerPlane);	// detach nub from child
                    theChild->release();
                }
                detachFromChild(connection,gIOPowerPlane);			// detach us from nub
            }
        }
        iter->release();
    }

    // Remove all interested drivers from the list, including the power
    // controlling driver.
    //
    // Usually, the controlling driver and the policy-maker functionality
    // are implemented by the same object, and without the deregistration,
    // the object will be holding an extra retain on itself, and cannot
    // be freed.

    if ( priv && priv->interestedDrivers )
    {
        IOPMinformee * informee;

        while (( informee = priv->interestedDrivers->firstInList() ))
            deRegisterInterestedDriver( informee->whatObject );
    }
}


//*********************************************************************************
// joinPMtree
//
// A policy-maker calls its nub here when initializing, to be attached into
// the power management hierarchy.  The default function is to call the
// platform expert, which knows how to do it.  This method is overridden
// by a nub subclass which may either know how to do it, or may need
// to take other action.
//
// This may be the only "power management" method used in a nub,
// meaning it may not be initialized for power management.
//*********************************************************************************
void IOService::joinPMtree ( IOService * driver )
{
    IOPlatformExpert * thePlatform;

    thePlatform = getPlatform();
    assert(thePlatform != 0 );
    thePlatform->PMRegisterDevice(this,driver);
}


//*********************************************************************************
// youAreRoot
//
// Power Managment is informing us that we are the root power domain.
// The only difference between us and any other power domain is that
// we have no parent and therefore never call it.
//*********************************************************************************
IOReturn IOService::youAreRoot ( void )
{    
    priv-> we_are_root = true;
    pm_vars->parentsKnowState = true;
    attachToParent( getRegistryRoot(),gIOPowerPlane );
    
    return IOPMNoErr;
}


//*********************************************************************************
// setPowerParent
//
// Power Management is informing us who our parent is.
// If we have a controlling driver, find out, given our newly-informed
// power domain state, what state it would be in, and then tell it
// to assume that state.
//*********************************************************************************
IOReturn IOService::setPowerParent ( IOPowerConnection * theParent, bool stateKnown, IOPMPowerFlags currentState )
{
    OSIterator *			iter;
    OSObject *			next;
    IOPowerConnection *	connection;
    unsigned long		tempDesire;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogSetParent,stateKnown,currentState);
    
    IOLockLock(pm_vars->parentLock);
    
    if ( stateKnown && ((pm_vars->PMworkloop == NULL) || (pm_vars->PMcommandGate == NULL)) ) {
        getPMworkloop();						// we have a path to the root
        if ( pm_vars->PMworkloop != NULL ) {				// find out the workloop
            if ( pm_vars->PMcommandGate == NULL ) {			// and make our command gate
                pm_vars->PMcommandGate = IOCommandGate::commandGate((OSObject *)this);
                if ( pm_vars->PMcommandGate != NULL ) {
                    pm_vars->PMworkloop->addEventSource(pm_vars->PMcommandGate);
                }
            }
        }
    }
    
    IOLockUnlock(pm_vars->parentLock);

    theParent->setParentCurrentPowerFlags(currentState);	// set our connection data
    theParent->setParentKnowsState(stateKnown);

    pm_vars->parentsKnowState = true;				// combine parent knowledge
    pm_vars->parentsCurrentPowerFlags = 0;
    
    iter = getParentIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                pm_vars->parentsKnowState &= connection->parentKnowsState();
                pm_vars->parentsCurrentPowerFlags |= connection->parentCurrentPowerFlags();
            }
        }
        iter->release();
    }
    
    if ( (pm_vars->theControllingDriver != NULL) &&
         (pm_vars->parentsKnowState) ) {
        pm_vars->maxCapability = pm_vars->theControllingDriver->maxCapabilityForDomainState(pm_vars->parentsCurrentPowerFlags);
        tempDesire = priv->deviceDesire;			// initially change into the state we are already in
        priv->deviceDesire = pm_vars->theControllingDriver->initialPowerStateForDomainState(pm_vars->parentsCurrentPowerFlags);
        computeDesiredState();
        priv->previousRequest = 0xffffffff;
        changeState();
        priv->deviceDesire = tempDesire;			// put this back like before
    }
    
   return IOPMNoErr;
}


//*********************************************************************************
// addPowerChild
//
// Power Management is informing us who our children are.
//*********************************************************************************
IOReturn IOService::addPowerChild ( IOService * theChild )
{
    IOPowerConnection *	connection;
    unsigned int        i;

    if ( ! initialized ) {
        return IOPMNotYetInitialized;	// we're not a power-managed IOService
    }

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAddChild,0,0);

    connection = new IOPowerConnection;			// make a nub

    connection->init();
    connection->start(this);
    connection->setAwaitingAck(false);

    attachToChild( connection,gIOPowerPlane );			// connect it up
    connection->attachToChild( theChild,gIOPowerPlane );
    connection->release();
    
    if ( (pm_vars->theControllingDriver == NULL) ||		// tell it the current state of the power domain
         ! (inPlane(gIOPowerPlane)) ||
       ! (pm_vars->parentsKnowState) ) {
        theChild->setPowerParent(connection,false,0);
        if ( inPlane(gIOPowerPlane) ) {
            for (i = 0; i <= kMaxType; i++) {
                if ( pm_vars->current_aggressiveness_valid[i] ) {
                    theChild->setAggressiveness (i, pm_vars->current_aggressiveness_values[i]);
                }
            }
        }
    }
    else {
        theChild->setPowerParent(connection,true,pm_vars->thePowerStates[pm_vars->myCurrentState].outputPowerCharacter);
        for (i = 0; i <= kMaxType; i++) {
            if ( pm_vars->current_aggressiveness_valid[i] ) {
                theChild->setAggressiveness (i, pm_vars->current_aggressiveness_values[i]);
            }
        }
        add_child_to_active_change(connection);							// catch it up if change is in progress
    }
    
    return IOPMNoErr;
}


//*********************************************************************************
// removePowerChild
//
//*********************************************************************************
IOReturn IOService::removePowerChild ( IOPowerConnection * theNub )
{
    IORegistryEntry * theChild;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogRemoveChild,0,0);

    theNub->retain();
    
    theChild = theNub->copyChildEntry(gIOPowerPlane);			// detach nub from child
    if ( theChild ) {
        theNub->detachFromChild(theChild, gIOPowerPlane);
        theChild->release();
    }
    detachFromChild(theNub,gIOPowerPlane);				// detach from the nub
    
    if ( theNub->getAwaitingAck() ) {					// are we awaiting an ack from this child?
        theNub->setAwaitingAck(false);					// yes, pretend we got one
        if ( acquire_lock() ) {
            if (priv->head_note_pendingAcks != 0 ) {
                priv->head_note_pendingAcks -= 1;			// that's one fewer ack to worry about
                if ( priv->head_note_pendingAcks == 0 ) {		// is that the last?
                    stop_ack_timer();					// yes, stop the timer
                    IOUnlock(priv->our_lock);
                    all_acked();					// and now we can continue our power change
                }
                else {
                    IOUnlock(priv->our_lock);
                }
            }
            else {
                IOUnlock(priv->our_lock);
            }
        }
    }
    
    theNub->release();

    if ( (pm_vars->theControllingDriver == NULL) ||	// if not fully initialized
         ! (inPlane(gIOPowerPlane)) ||
       ! (pm_vars->parentsKnowState) ) {
        return IOPMNoErr;				// we can do no more
    }

    computeDesiredState();				// this may be different now
    changeState();					// change state if we can now tolerate lower power

    return IOPMNoErr;
}


//*********************************************************************************
// registerPowerDriver
//
// A driver has called us volunteering to control power to our device.
// If the power state array it provides is richer than the one we already
// know about (supplied by an earlier volunteer), then accept the offer.
// Notify all interested parties of our power state, which we now know.
//*********************************************************************************

IOReturn IOService::registerPowerDriver ( IOService * controllingDriver, IOPMPowerState* powerStates, unsigned long numberOfStates  )
{
    unsigned long i;
    unsigned long tempDesire;

    if ( (numberOfStates > pm_vars->theNumberOfPowerStates) && (numberOfStates > 1) ) {
        if (  priv->changeList->currentChange() == -1 ) {
            if ( controllingDriver != NULL ) {
                if ( numberOfStates <= IOPMMaxPowerStates ) {
                    switch ( powerStates[0].version  ) {
                        case 1:
                            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogControllingDriver,
                                                                    (unsigned long)numberOfStates, (unsigned long)powerStates[0].version);
                            for ( i = 0; i < numberOfStates; i++ ) {
                                pm_vars->thePowerStates[i] = powerStates[i];
                            }
                                break;
                        case 2:
                            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogControllingDriver,
                                                                    (unsigned long) numberOfStates,(unsigned long) powerStates[0].version);
                            for ( i = 0; i < numberOfStates; i++ ) {
                                pm_vars->thePowerStates[i].version = powerStates[i].version;
                                pm_vars->thePowerStates[i].capabilityFlags = powerStates[i].capabilityFlags;
                                pm_vars->thePowerStates[i].outputPowerCharacter = powerStates[i].outputPowerCharacter;
                                pm_vars->thePowerStates[i].inputPowerRequirement = powerStates[i].inputPowerRequirement;
                                pm_vars->thePowerStates[i].staticPower = powerStates[i].staticPower;
                                pm_vars->thePowerStates[i].unbudgetedPower = powerStates[i].unbudgetedPower;
                                pm_vars->thePowerStates[i].powerToAttain = powerStates[i].powerToAttain;
                                pm_vars->thePowerStates[i].timeToAttain = powerStates[i].timeToAttain;
                                pm_vars->thePowerStates[i].settleUpTime = powerStates[i].settleUpTime;
                                pm_vars->thePowerStates[i].timeToLower = powerStates[i].timeToLower;
                                pm_vars->thePowerStates[i].settleDownTime = powerStates[i].settleDownTime;
                                pm_vars->thePowerStates[i].powerDomainBudget = powerStates[i].powerDomainBudget;
                            }
                                break;
                        default:
                            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogControllingDriverErr1,
                                                                    (unsigned long)powerStates[0].version,0);
                            return IOPMNoErr;
                    }

                    pm_vars->myCharacterFlags = 0;	// make a mask of all the character bits we know about
                    for ( i = 0; i < numberOfStates; i++ ) {
                        pm_vars->myCharacterFlags |= pm_vars->thePowerStates[i].outputPowerCharacter;
                    }
                    
                   pm_vars->theNumberOfPowerStates = numberOfStates;
                    pm_vars->theControllingDriver = controllingDriver;
                    if ( priv->interestedDrivers->findItem(controllingDriver) == NULL ) {	// register it as interested
                        registerInterestedDriver (controllingDriver );				// unless already done
                    }
                    if ( priv->need_to_become_usable ) {
                        priv->need_to_become_usable = false;
                        priv->deviceDesire = pm_vars->theNumberOfPowerStates - 1;
                    }

                    if ( inPlane(gIOPowerPlane) &&
                         (pm_vars->parentsKnowState) ) {
                        pm_vars->maxCapability = pm_vars->theControllingDriver->maxCapabilityForDomainState(pm_vars->parentsCurrentPowerFlags);
                        tempDesire = priv->deviceDesire;			// initially change into the state we are already in
                        priv->deviceDesire = pm_vars->theControllingDriver->initialPowerStateForDomainState(pm_vars->parentsCurrentPowerFlags);
                        computeDesiredState();
                        changeState();
                        priv->deviceDesire = tempDesire;			// put this back like before
                    }
                }
                else {
                    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogControllingDriverErr2,(unsigned long)numberOfStates,0);
                }
            }
            else {
                pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogControllingDriverErr4,0,0);
            }
        }
    }
    else {
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogControllingDriverErr5,(unsigned long)numberOfStates,0);
    }
    return IOPMNoErr;
}

//*********************************************************************************
// registerInterestedDriver
//
// Add the caller to our list of interested drivers and return our current
// power state.  If we don't have a power-controlling driver yet, we will
// call this interested driver again later when we do get a driver and find
// out what the current power state of the device is.
//*********************************************************************************

IOPMPowerFlags IOService::registerInterestedDriver ( IOService * theDriver )
{
    IOPMinformee * newInformee;
    IOPMPowerFlags futureCapability;

    if (theDriver == NULL ) {
        return 0;
    }

    newInformee = new IOPMinformee;				// make new driver node
    newInformee->initialize(theDriver);
    priv->interestedDrivers->addToList(newInformee);			// add it to list of drivers

    if ( (pm_vars->theControllingDriver == NULL) ||
         ! (inPlane(gIOPowerPlane)) ||
       ! (pm_vars->parentsKnowState) ) {
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogInterestedDriver,IOPMNotPowerManaged,0);
        return IOPMNotPowerManaged;					// can't tell it a state yet
    }

    switch (priv->machine_state) {					// can we notify new driver of a change in progress?
        case IOPMour_prechange_1:
        case IOPMour_prechange_4:
        case IOPMparent_down_4:
        case IOPMparent_down_6:
        case IOPMparent_up_0:
        case IOPMparent_up_6:
            futureCapability = priv->head_note_capabilityFlags;			// yes, remember what we tell it
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogInterestedDriver,(unsigned long)futureCapability,1);
            add_driver_to_active_change(newInformee);				// notify it
            return futureCapability;						// and return the same thing
    }

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogInterestedDriver,
                                            (unsigned long) pm_vars->thePowerStates[pm_vars->myCurrentState].capabilityFlags,2);
    return  pm_vars->thePowerStates[pm_vars->myCurrentState].capabilityFlags;	// no, return current capability
}


//*********************************************************************************
// deRegisterInterestedDriver
//
//*********************************************************************************
IOReturn IOService::deRegisterInterestedDriver ( IOService * theDriver )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogRemoveDriver,0,0);

    priv->interestedDrivers->removeFromList(theDriver);				  // remove the departing driver

    return IOPMNoErr;
}


//*********************************************************************************
// acknowledgePowerChange
//
// After we notified one of the interested drivers or a power-domain child
// of an impending change in power, it has called to say it is now
// prepared for the change.  If this object is the last to
// acknowledge this change, we take whatever action we have been waiting
// for.
// That may include acknowledging to our parent.  In this case, we do it
// last of all to insure that this doesn't cause the parent to call us some-
// where else and alter data we are relying on here (like the very existance
// of a "current change note".)
//*********************************************************************************

IOReturn IOService::acknowledgePowerChange ( IOService * whichObject )
{
   IOPMinformee *	ackingObject;
   unsigned long	childPower = kIOPMUnknown;
   IOService *		theChild;

    ackingObject =  priv->interestedDrivers->findItem(whichObject);				// one of our interested drivers?
   if ( ackingObject == NULL ) {
       if ( ! isChild(whichObject,gIOPowerPlane) ) {
           pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAcknowledgeErr1,0,0);
           kprintf("errant driver: %s\n",whichObject->getName());
           return IOPMNoErr;							// no, just return
       }
       else {
           pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogChildAcknowledge,priv->head_note_pendingAcks,0);
       }
   }
   else {
       pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogDriverAcknowledge,priv->head_note_pendingAcks,0);
   }

   if (! acquire_lock() ) {
       return IOPMNoErr;
   }

   if (priv->head_note_pendingAcks != 0 ) {					// yes, make sure we're expecting acks
       if ( ackingObject != NULL ) {						// it's an interested driver
           if ( ackingObject->timer != 0 ) {					// make sure we're expecting this ack
               ackingObject->timer = 0;						// mark it acked
               priv->head_note_pendingAcks -= 1;				// that's one fewer to worry about
               if ( priv->head_note_pendingAcks == 0 ) {			// is that the last?
                   stop_ack_timer();						// yes, stop the timer
                   IOUnlock(priv->our_lock);
                   all_acked();							// and now we can continue
                   return IOPMNoErr;
               }
           }
           else {
               pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAcknowledgeErr2,0,0);	// this driver has already acked
           kprintf("errant driver: %s\n",whichObject->getName());
           }
       }
       else {									// it's a child
            if ( ((IOPowerConnection *)whichObject)->getAwaitingAck() ) {	// make sure we're expecting this ack
                priv->head_note_pendingAcks -= 1;				// that's one fewer to worry about
                ((IOPowerConnection *)whichObject)->setAwaitingAck(false);
                theChild = (IOService *)whichObject->copyChildEntry(gIOPowerPlane);
                if ( theChild ) {
                    childPower = theChild->currentPowerConsumption();
                    theChild->release();
                }
                if ( childPower == kIOPMUnknown ) {
                    pm_vars->thePowerStates[priv->head_note_state].staticPower = kIOPMUnknown;
                }
                else {
                    if ( pm_vars->thePowerStates[priv->head_note_state].staticPower != kIOPMUnknown ) {
                        pm_vars->thePowerStates[priv->head_note_state].staticPower += childPower;
                    }
                }
                if ( priv->head_note_pendingAcks == 0 ) {				// is that the last?
                    stop_ack_timer();							// yes, stop the timer
                    IOUnlock(priv->our_lock);
                    all_acked();							// and now we can continue
                    return IOPMNoErr;
                }
            }
	}
    }
   else {
       pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAcknowledgeErr3,0,0);	// not expecting anybody to ack
       kprintf("errant driver: %s\n",whichObject->getName());
   }
   IOUnlock(priv->our_lock);
   return IOPMNoErr;
}

//*********************************************************************************
// acknowledgeSetPowerState
//
// After we instructed our controlling driver to change power states,
// it has called to say it has finished doing so.
// We continue to process the power state change.
//*********************************************************************************

IOReturn IOService::acknowledgeSetPowerState ( void )
{
    if (! acquire_lock() ) {
        return IOPMNoErr;
    }
    if ( priv->driver_timer == -1 ) {
        priv->driver_timer = 0;				// driver is acking instead of using return code
    }
    else {
        if ( priv->driver_timer > 0 ) {			// are we expecting this?
            stop_ack_timer();				// yes, stop the timer
            priv->driver_timer = 0;
            IOUnlock(priv->our_lock);
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogDriverAcknowledgeSet,0,0);
            driver_acked();
            return IOPMNoErr;
        }
        else {
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAcknowledgeErr4,0,0);		// no
        }
    }
    IOUnlock(priv->our_lock);
    return IOPMNoErr;
}


//*********************************************************************************
// driver_acked
//
// Either the controlling driver has called acknowledgeSetPowerState
// or the acknowledgement timer has expired while waiting for that.
// We carry on processing the current change note.
//*********************************************************************************

void IOService::driver_acked ( void )
{
    switch (priv->machine_state) {
        case IOPMour_prechange_2:
            our_prechange_2();
            break;
        case IOPMparent_down_5:
            parent_down_5();
            break;
        case IOPMparent_up_4:
            parent_up_4();
            break;
    }
}


//*********************************************************************************
// powerDomainWillChangeTo
//
// Called by the power-hierarchy parent notifying of a new power state
// in the power domain.
// We enqueue a parent power-change to our queue of power changes.
// This may or may not cause us to change power, depending on what
// kind of change is occuring in the domain.
//*********************************************************************************

IOReturn IOService::powerDomainWillChangeTo ( IOPMPowerFlags newPowerStateFlags, IOPowerConnection * whichParent )
{
    OSIterator *			iter;
    OSObject *			next;
    IOPowerConnection *	connection;
    unsigned long		newStateNumber;
    IOPMPowerFlags		combinedPowerFlags;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogWillChange,(unsigned long)newPowerStateFlags,0);

    if ( ! inPlane(gIOPowerPlane) ) {
        return IOPMAckImplied;						// somebody goofed
    }

    IOLockLock(pm_vars->parentLock);
    
    if ( (pm_vars->PMworkloop == NULL) || (pm_vars->PMcommandGate == NULL) ) {
        getPMworkloop();						// we have a path to the root,
        if ( pm_vars->PMworkloop != NULL ) {				// so find out the workloop
            if ( pm_vars->PMcommandGate == NULL ) {			// and make our command gate
                pm_vars->PMcommandGate = IOCommandGate::commandGate((OSObject *)this);
                if ( pm_vars->PMcommandGate != NULL ) {
                    pm_vars->PMworkloop->addEventSource(pm_vars->PMcommandGate);
                }
            }
        }
    }
    
    IOLockUnlock(pm_vars->parentLock);

    combinedPowerFlags = 0;						// combine parents' power states
    
    iter = getParentIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                if ( connection == whichParent ){
                    combinedPowerFlags |= newPowerStateFlags;
                }
                else {
                    combinedPowerFlags |= connection->parentCurrentPowerFlags();
                }
            }
        }
        iter->release();
    }
    
    if  ( pm_vars->theControllingDriver == NULL ) {					// we can't take any more action
        return IOPMAckImplied;
    }
    newStateNumber = pm_vars->theControllingDriver->maxCapabilityForDomainState(combinedPowerFlags);
    return enqueuePowerChange(IOPMParentInitiated | IOPMDomainWillChange,
                            newStateNumber,combinedPowerFlags,whichParent,newPowerStateFlags);	//make the change
}


//*********************************************************************************
// powerDomainDidChangeTo
//
// Called by the power-hierarchy parent after the power state of the power domain
// has settled at a new level.
// We enqueue a parent power-change to our queue of power changes.
// This may or may not cause us to change power, depending on what
// kind of change is occuring in the domain.
//*********************************************************************************

IOReturn IOService::powerDomainDidChangeTo ( IOPMPowerFlags newPowerStateFlags, IOPowerConnection * whichParent )
{
    unsigned long newStateNumber;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogDidChange,newPowerStateFlags,0);

    setParentInfo(newPowerStateFlags,whichParent);

    if ( pm_vars->theControllingDriver == NULL ) {
        return IOPMAckImplied;
    }

    newStateNumber = pm_vars->theControllingDriver->maxCapabilityForDomainState(pm_vars->parentsCurrentPowerFlags);
    return enqueuePowerChange(IOPMParentInitiated | IOPMDomainDidChange,
                    newStateNumber,pm_vars->parentsCurrentPowerFlags,whichParent,0);	// tell interested parties about it
}


//*********************************************************************************
// setParentInfo
//
// Set our connection data for one specific parent, and then combine all the parent
// data together.
//*********************************************************************************

void IOService::setParentInfo ( IOPMPowerFlags newPowerStateFlags, IOPowerConnection * whichParent )
{
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;
    
    whichParent->setParentCurrentPowerFlags(newPowerStateFlags);		// set our connection data
    whichParent->setParentKnowsState(true);

    IOLockLock(pm_vars->parentLock);
    
    pm_vars->parentsCurrentPowerFlags = 0;					// recompute our parent info
    pm_vars->parentsKnowState = true;

    iter = getParentIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                pm_vars->parentsKnowState &= connection->parentKnowsState();
                pm_vars->parentsCurrentPowerFlags |= connection->parentCurrentPowerFlags();
            }
        }
        iter->release();
    }
    IOLockUnlock(pm_vars->parentLock);
}


//*********************************************************************************
// requestPowerDomainState
//
// The kIOPMPreventIdleSleep and/or kIOPMPreventIdleSleep bits may be be set in the parameter.
// It is not considered part of the state specification.
//*********************************************************************************
IOReturn IOService::requestPowerDomainState ( IOPMPowerFlags desiredState, IOPowerConnection * whichChild, unsigned long specification )
{
    unsigned long	i;
    unsigned long	computedState;
    unsigned long	theDesiredState = desiredState & ~(kIOPMPreventIdleSleep | kIOPMPreventSystemSleep);
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogRequestDomain,
                                (unsigned long)desiredState,(unsigned long)specification);

    if ( pm_vars->theControllingDriver == NULL) {
        return IOPMNotYetInitialized;
    }

    switch (specification) {
        case IOPMLowestState:
            i = 0;
            while ( i < pm_vars->theNumberOfPowerStates ) {
                if ( ( pm_vars->thePowerStates[i].outputPowerCharacter & theDesiredState) == (theDesiredState & pm_vars->myCharacterFlags) ) {
                    break;
                }
                i++;
            }
                if ( i >= pm_vars->theNumberOfPowerStates ) {
                return IOPMNoSuchState;
           }
            break;

        case IOPMNextLowerState:
            i = pm_vars->myCurrentState - 1;
            while ( i >= 0 ) {
                if ( ( pm_vars->thePowerStates[i].outputPowerCharacter & theDesiredState) == (theDesiredState & pm_vars->myCharacterFlags) ) {
                    break;
                }
                i--;
            }
            if ( i < 0 ) {
                return IOPMNoSuchState;
            }
            break;

        case IOPMHighestState:
            i = pm_vars->theNumberOfPowerStates;
            while ( i >= 0 ) {
                i--;
                if ( ( pm_vars->thePowerStates[i].outputPowerCharacter & theDesiredState) == (theDesiredState & pm_vars->myCharacterFlags) ) {
                    break;
                }
            }
            if ( i < 0 ) {
                return IOPMNoSuchState;
            }
            break;

        case IOPMNextHigherState:
            i = pm_vars->myCurrentState + 1;
            while ( i < pm_vars->theNumberOfPowerStates ) {
                if ( ( pm_vars->thePowerStates[i].outputPowerCharacter & theDesiredState) == (theDesiredState & pm_vars->myCharacterFlags) ) {
                    break;
                }
            i++;
            }
                if ( i == pm_vars->theNumberOfPowerStates ) {
                return IOPMNoSuchState;
            }
            break;

        default:
            return IOPMBadSpecification;
    }

    computedState = i;
    
    IOLockLock(pm_vars->childLock);

// A child's desires has changed.  We need to rebuild the child-clamp bits in our
// power state array.  Start by clearing the bits in each power state.
    
    for ( i = 0; i < pm_vars->theNumberOfPowerStates; i++ ) {
        pm_vars->thePowerStates[i].capabilityFlags &= ~(kIOPMChildClamp | kIOPMChildClamp2);
    }

// Now loop through the children.  When we encounter the calling child, save
// the computed state as this child's desire.  And while we're at it, set the ChildClamp bits
// in any of our states that some child has requested with clamp on.

    iter = getChildIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                if ( connection == whichChild ) {
                    connection->setDesiredDomainState(computedState);
                    connection->setPreventIdleSleepFlag(desiredState & kIOPMPreventIdleSleep);
                    connection->setPreventSystemSleepFlag(desiredState & kIOPMPreventSystemSleep);
                    connection->setChildHasRequestedPower();
                }
                if ( connection->getPreventIdleSleepFlag() ) {
                    pm_vars->thePowerStates[connection->getDesiredDomainState()].capabilityFlags |= kIOPMChildClamp;
                }
                if ( connection->getPreventSystemSleepFlag() ) {
                    pm_vars->thePowerStates[connection->getDesiredDomainState()].capabilityFlags |= kIOPMChildClamp2;
                }
            }
        }
        iter->release();
    }
        
    IOLockUnlock(pm_vars->childLock);
    
    computeDesiredState();				// this may be different now

   if ( inPlane(gIOPowerPlane) &&
        (pm_vars->parentsKnowState) ) {
       changeState();					// change state if all children can now tolerate lower power
   }
   
   if ( priv->clampOn ) {				// are we clamped on, waiting for this child?
       priv->clampOn = false;				// yes, remove the clamp
       changePowerStateToPriv(0);
   }
   
   return IOPMNoErr;
}


//*********************************************************************************
// temporaryPowerClampOn
//
// A power domain wants to clamp its power on till it has children which
// will thendetermine the power domain state.
//
// We enter the highest state until addPowerChild is called.
//*********************************************************************************

IOReturn IOService::temporaryPowerClampOn ( void )
{
    priv->clampOn = true;
    makeUsable();
    return IOPMNoErr;
}


//*********************************************************************************
// makeUsable
//
// Some client of our device is asking that we become usable.  Although
// this has not come from a subclassed device object, treat it exactly
// as if it had.  In this way, subsequent requests for lower power from
// a subclassed device object will pre-empt this request.
//
// We treat this as a subclass object request to switch to the
// highest power state.
//*********************************************************************************

IOReturn IOService::makeUsable ( void )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogMakeUsable,0,0);

    if ( pm_vars->theControllingDriver == NULL ) {
        priv->need_to_become_usable = true;
        return IOPMNoErr;
    }
    priv->deviceDesire = pm_vars->theNumberOfPowerStates - 1;
    computeDesiredState();
    if ( inPlane(gIOPowerPlane) && (pm_vars->parentsKnowState) ) {
        return changeState();
    }
    return IOPMNoErr;
}


//*********************************************************************************
// currentCapability
//
//*********************************************************************************

IOPMPowerFlags IOService::currentCapability ( void )
{
    if ( pm_vars->theControllingDriver == NULL ) {
        return 0;
    }
    else {
        return   pm_vars->thePowerStates[pm_vars->myCurrentState].capabilityFlags;
    }
}


//*********************************************************************************
// changePowerStateTo
//
// For some reason, our power-controlling driver has decided it needs to change
// power state.  We enqueue the power change so that appropriate parties
// will be notified, and then we will instruct the driver to make the change.
//*********************************************************************************

IOReturn IOService::changePowerStateTo ( unsigned long ordinal )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogChangeStateTo,ordinal,0);

    if ( ordinal >= pm_vars->theNumberOfPowerStates ) {
        return IOPMParameterError;
    }
    priv->driverDesire = ordinal;
    computeDesiredState();
    if ( inPlane(gIOPowerPlane) && (pm_vars->parentsKnowState) ) {
        return changeState();
    }

    return IOPMNoErr;
}

//*********************************************************************************
// changePowerStateToPriv
//
// For some reason, a subclassed device object has decided it needs to change
// power state.  We enqueue the power change so that appropriate parties
// will be notified, and then we will instruct the driver to make the change.
//*********************************************************************************

IOReturn IOService::changePowerStateToPriv ( unsigned long ordinal )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogChangeStateToPriv,ordinal,0);

    if ( pm_vars->theControllingDriver == NULL) {
        return IOPMNotYetInitialized;
    }
    if ( ordinal >= pm_vars->theNumberOfPowerStates ) {
        return IOPMParameterError;
    }
    priv->deviceDesire = ordinal;
    computeDesiredState();
    if ( inPlane(gIOPowerPlane) && (pm_vars->parentsKnowState) ) {
        return changeState();
    }

    return IOPMNoErr;
}


//*********************************************************************************
// computeDesiredState
//
//*********************************************************************************

void IOService::computeDesiredState ( void )
{
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;
    unsigned long	newDesiredState = 0;

    // Compute the maximum  of our children's desires, our controlling driver's desire, and the subclass device's desire.

    if ( !  priv->device_overrides ) {
        iter = getChildIterator(gIOPowerPlane);

        if ( iter ) {
            while ( (next = iter->getNextObject()) ) {
                if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                    if ( connection->getDesiredDomainState() > newDesiredState ) {
                        newDesiredState = connection->getDesiredDomainState();
                    }
                }
            }
            iter->release();
        }
        
        if (  priv->driverDesire > newDesiredState ) {
            newDesiredState =  priv->driverDesire;
        }
    }

    if ( priv->deviceDesire > newDesiredState ) {
        newDesiredState = priv->deviceDesire;
    }

    priv->ourDesiredPowerState = newDesiredState;
}


//*********************************************************************************
// changeState
//
// A subclass object, our controlling driver, or a power domain child
// has asked for a different power state.  Here we compute what new
// state we should enter and enqueue the change (or start it).
//*********************************************************************************

IOReturn IOService::changeState ( void )
{
    if ( (pm_vars->theControllingDriver == NULL) ||	// if not fully initialized
         ! (inPlane(gIOPowerPlane)) ||
       ! (pm_vars->parentsKnowState) ) {
        return IOPMNoErr;				// we can do no more
    }
    
    return enqueuePowerChange(IOPMWeInitiated,priv->ourDesiredPowerState,0,0,0);
}


//*********************************************************************************
// currentPowerConsumption
//
//*********************************************************************************

unsigned long IOService::currentPowerConsumption ( void )
{
    if ( pm_vars->theControllingDriver == NULL ) {
        return kIOPMUnknown;
    }
    if ( pm_vars->thePowerStates[pm_vars->myCurrentState].capabilityFlags & kIOPMStaticPowerValid ) {
        return  pm_vars->thePowerStates[pm_vars->myCurrentState].staticPower;
    }
    return kIOPMUnknown;
}

//*********************************************************************************
// activityTickle
//
// The activity tickle with parameter kIOPMSubclassPolicyis not handled
// here and should have been intercepted by the subclass.
// The tickle with parameter kIOPMSuperclassPolicy1 causes the activity
// flag to be set, and the device state checked.  If the device has been
// powered down, it is powered up again.
//*********************************************************************************

bool IOService::activityTickle ( unsigned long type, unsigned long stateNumber=0 )
{
    AbsoluteTime uptime;

    if ( type == kIOPMSuperclassPolicy1 ) {
        if ( (priv->activityLock == NULL) ||
             (pm_vars->theControllingDriver == NULL) ||
             (pm_vars->commandQueue == NULL) ) {
            return true;
        }
        IOTakeLock(priv->activityLock);
        priv->device_active = true;

        clock_get_uptime(&uptime);
        priv->device_active_timestamp = uptime;

        if ( pm_vars->myCurrentState >= stateNumber) {
            IOUnlock(priv->activityLock);
            return true;
        }
        IOUnlock(priv->activityLock);				// send a message on the command queue
        pm_vars->commandQueue->enqueueCommand(true, (void *)kIOPMUnidleDevice, (void *)stateNumber);
        return false;
    }
    return true;
}

//*********************************************************************************
// getPMworkloop
//
// A child is calling to get a pointer to the Power Management workloop.
// We got it or get it from one of our parents.
//*********************************************************************************

IOWorkLoop * IOService::getPMworkloop ( void )
{
IOService * nub;
IOService * parent;

    if ( ! inPlane(gIOPowerPlane) ) {
        return NULL;
    }
    if ( pm_vars->PMworkloop == NULL ) {				// we have no workloop yet
        nub = (IOService *)copyParentEntry(gIOPowerPlane);
        if ( nub ) {
            parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
            nub->release();
            if ( parent ) {						// ask one of our parents for the workloop
                pm_vars->PMworkloop = parent->getPMworkloop();
                parent->release();
            }
        }
    }
    return  pm_vars->PMworkloop;
}


//*********************************************************************************
// setIdleTimerPeriod
//
// A subclass policy-maker is going to use our standard idleness
// detection service.  Make a command queue and an idle timer and
// connect them to the power management workloop.  Finally,
// start the timer.
//*********************************************************************************

IOReturn  IOService::setIdleTimerPeriod ( unsigned long period )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMsetIdleTimerPeriod,period, 0);

    priv->idle_timer_period = period;

    if ( period > 0 ) {
        if ( getPMworkloop() == NULL ) {
            return kIOReturnError;
        }

        if (pm_vars->commandQueue == NULL ) {		// make the command queue
            pm_vars->commandQueue = IOCommandQueue::commandQueue(this, PMreceiveCmd);
            if (!  pm_vars->commandQueue ||
                (  pm_vars->PMworkloop->addEventSource( pm_vars->commandQueue) != kIOReturnSuccess) ) {
                return kIOReturnError;
            }
        }
       						 // make the timer event
        if (  priv->timerEventSrc == NULL ) {
            priv->timerEventSrc = IOTimerEventSource::timerEventSource(this,
                                                    PM_idle_timer_expired);
            if ( !  priv->timerEventSrc ||
                 ( pm_vars->PMworkloop->addEventSource(  priv->timerEventSrc) != kIOReturnSuccess) ) {
                return kIOReturnError;
            }
        }

        if ( priv->activityLock == NULL ) {
            priv->activityLock = IOLockAlloc();
        }

        start_PM_idle_timer();
    }
    return IOPMNoErr;
}


//*********************************************************************************
// start_PM_idle_timer
//
// The parameter is a pointer to us.  Use it to call our timeout method.
//*********************************************************************************
void IOService::start_PM_idle_timer ( void )
{
    AbsoluteTime uptime;
    AbsoluteTime delta;
    UInt64       delta_ns;
    UInt64       delta_secs;
    UInt64       delay_secs;

    IOLockLock(priv->activityLock);

    clock_get_uptime(&uptime);

   /* Calculate time difference using funky macro from clock.h.
    */
    delta = uptime;
    SUB_ABSOLUTETIME(&delta, &(priv->device_active_timestamp));

   /* Figure it in seconds.
    */
    absolutetime_to_nanoseconds(delta, &delta_ns);
    delta_secs = delta_ns / NSEC_PER_SEC;

   /* Be paranoid about delta somehow exceeding timer period.
    */
    if (delta_secs < priv->idle_timer_period ) {
        delay_secs = priv->idle_timer_period - delta_secs;
    } else {
        delay_secs = priv->idle_timer_period;
    }

    priv->timerEventSrc->setTimeout(delay_secs, NSEC_PER_SEC);

    IOLockUnlock(priv->activityLock);
    return;
}


//*********************************************************************************
// PM_idle_timer_expired
//
// The parameter is a pointer to us.  Use it to call our timeout method.
//*********************************************************************************

void PM_idle_timer_expired(OSObject * ourSelves, IOTimerEventSource *)
{
    ((IOService *)ourSelves)->PM_idle_timer_expiration();
}


//*********************************************************************************
// PM_idle_timer_expiration
//
// The idle timer has expired.  If there has been activity since the last
// expiration, just restart the timer and return.  If there has not been
// activity, switch to the next lower power state and restart the timer.
//*********************************************************************************

void IOService::PM_idle_timer_expiration ( void )
{
    if ( ! initialized ) {
        return;					// we're unloading
    }

    if (  priv->idle_timer_period > 0 ) {
        IOTakeLock(priv->activityLock);
        if ( priv->device_active ) {
            priv->device_active = false;
            IOUnlock(priv->activityLock);
            start_PM_idle_timer();
            return;
        }
        if ( pm_vars->myCurrentState > 0 ) {
            IOUnlock(priv->activityLock);
            changePowerStateToPriv(pm_vars->myCurrentState - 1);
            start_PM_idle_timer();
            return;
        }
        IOUnlock(priv->activityLock);
        start_PM_idle_timer();
    }
}



// **********************************************************************************
// PMreceiveCmd
//
//
//
// **********************************************************************************
void PMreceiveCmd ( OSObject * theDriver,  void * command, void * param1, void * param2, void *param3 )
{
   ((IOService *)theDriver)->command_received(command,param1,param2,param3);
}


// **********************************************************************************
// command_received
//
// We have received a command from ourselves on the command queue.
// This is to prevent races with timer-expiration code.
// **********************************************************************************
void IOService::command_received ( void * command, void *stateNumber , void * , void *)
{
    if ( ! initialized ) {
        return;					// we're unloading
    }

    if ( command == (void *)kIOPMUnidleDevice ) {
        if ( (pm_vars->myCurrentState < (unsigned long)stateNumber) &&
            (priv->imminentState < (unsigned long)stateNumber) ) {
            changePowerStateToPriv((unsigned long)stateNumber);
        }
    }
}


//*********************************************************************************
// setAggressiveness
//
// Pass on the input parameters to all power domain children. All those which are
// power domains will pass it on to their children, etc.
//*********************************************************************************

IOReturn IOService::setAggressiveness ( unsigned long type, unsigned long newLevel )
{
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;
    IOService *         child;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogSetAggressiveness,type, newLevel);

    if ( type <= kMaxType ) {
        pm_vars->current_aggressiveness_values[type] = newLevel;
        pm_vars->current_aggressiveness_valid[type] = true;
    }

    iter = getChildIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                child = ((IOService *)(connection->copyChildEntry(gIOPowerPlane)));
                if ( child ) {
                    child->setAggressiveness(type, newLevel);
                    child->release();
                }
            }
        }
        iter->release();
    }

    return IOPMNoErr;
}

//*********************************************************************************
// getAggressiveness
//
// Called by the user client.
//*********************************************************************************

IOReturn IOService::getAggressiveness ( unsigned long type, unsigned long * currentLevel )
{
  if ( type <= kMaxType ) {
        *currentLevel = pm_vars->current_aggressiveness_values[type];
  }
    return kIOReturnSuccess;
}

//*********************************************************************************
// systemWake
//
// Pass this to all power domain children. All those which are
// power domains will pass it on to their children, etc.
//*********************************************************************************

IOReturn IOService::systemWake ( void )
{
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;
    IOService *		theChild;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogSystemWake,0, 0);

    iter = getChildIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                theChild = (IOService *)connection->copyChildEntry(gIOPowerPlane);
                if ( theChild ) {
                	theChild->systemWake();
                        theChild->release();
                }
            }
        }
        iter->release();
    }

    if ( pm_vars->theControllingDriver != NULL ) {
        if ( pm_vars->theControllingDriver->didYouWakeSystem() ) {
            makeUsable();
        }
    }

    return IOPMNoErr;
}


//*********************************************************************************
// temperatureCriticalForZone
//
//*********************************************************************************

IOReturn IOService::temperatureCriticalForZone ( IOService * whichZone )
{
    IOService * theParent;
    IOService * theNub;
    
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogCriticalTemp,0,0);

    if ( inPlane(gIOPowerPlane) && ! (priv->we_are_root) ) {
        theNub = (IOService *)copyParentEntry(gIOPowerPlane);
        if ( theNub ) {
            theParent = (IOService *)theNub->copyParentEntry(gIOPowerPlane);
            theNub->release();
            if ( theParent ) {
                theParent->temperatureCriticalForZone(whichZone);
                theParent->release();
            }
        }
    }
    return IOPMNoErr;
}


//*********************************************************************************
// powerOverrideOnPriv
//
//*********************************************************************************


IOReturn IOService::powerOverrideOnPriv ( void )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogOverrideOn,0,0);

    priv->device_overrides = true;	// turn on the override
    computeDesiredState();
    return changeState();		// change state if that changed something
}


//*********************************************************************************
// powerOverrideOffPriv
//
//*********************************************************************************
IOReturn IOService::powerOverrideOffPriv ( void )
{
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogOverrideOff,0,0);

    priv->device_overrides = false;	// turn off the override
    computeDesiredState();
    if( priv->clampOn)
        return makeUsable();
    else
        return changeState();		// change state if that changed something
}


//*********************************************************************************
// enqueuePowerChange
//
// Allocate a new state change notification, initialize it with fields from the
// caller, and add it to the tail of the list of pending power changes.
//
// If it is early enough in the list, and almost all the time it is the only one in
// the list, start the power change.
//
// In rare instances, this change will preempt the previous change in the list.
// If the previous change is un-actioned in any way (because we are still
// processing an even earlier power change), and if both the previous change
// in the list and this change are initiated by us (not the parent), then we
// needn't perform the previous change, so we collapse the list a little.
//*********************************************************************************

IOReturn IOService::enqueuePowerChange ( unsigned long flags,  unsigned long whatStateOrdinal, unsigned long domainState, IOPowerConnection * whichParent, unsigned long singleParentState )
{
    long	newNote;
    long	previousNote;

// Create and initialize the new change note

    IOLockLock(priv->queue_lock);
    newNote = priv->changeList->createChangeNote();
    if ( newNote == -1 ) {
        IOLockUnlock(priv->queue_lock);
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogEnqueueErr,0,0);
        return IOPMAckImplied;			// uh-oh, our list is full
    }

    priv->changeList->changeNote[newNote].newStateNumber = whatStateOrdinal;
    priv->changeList->changeNote[newNote].outputPowerCharacter =  pm_vars->thePowerStates[whatStateOrdinal].outputPowerCharacter;
    priv->changeList->changeNote[newNote].inputPowerRequirement =  pm_vars->thePowerStates[whatStateOrdinal].inputPowerRequirement;
    priv->changeList->changeNote[newNote].capabilityFlags =  pm_vars->thePowerStates[whatStateOrdinal].capabilityFlags;
    priv->changeList->changeNote[newNote].flags = flags;
    if (flags & IOPMParentInitiated ) {
        priv->changeList->changeNote[newNote].domainState =  domainState;
        priv->changeList->changeNote[newNote].parent =  whichParent;
        whichParent->retain();
        priv->changeList->changeNote[newNote].singleParentState =  singleParentState;
    }

    previousNote = priv->changeList->previousChangeNote(newNote);

    if ( previousNote == -1 ) {

        // Queue is empty, we can start this change.

        if (flags & IOPMWeInitiated ) {
            IOLockUnlock(priv->queue_lock);
            start_our_change(newNote);
            return 0;
        }
        else {
            IOLockUnlock(priv->queue_lock);
            return start_parent_change(newNote);
        }
    }

    // The queue is not empty.  Try to collapse this new change and the previous one in queue into one change.
    // This is possible only if both changes are initiated by us, and neither has been started yet.
    // Do this more than once if possible.

    // (A change is started iff it is at the head of the queue)

    while ( (previousNote != priv->head_note) &&  (previousNote != -1) &&
            (priv->changeList->changeNote[newNote].flags &  priv->changeList->changeNote[previousNote].flags &  IOPMWeInitiated)  ) {
        priv->changeList->changeNote[previousNote].outputPowerCharacter = priv->changeList->changeNote[newNote].outputPowerCharacter;
        priv->changeList->changeNote[previousNote].inputPowerRequirement = priv->changeList->changeNote[newNote].inputPowerRequirement;
        priv->changeList->changeNote[previousNote].capabilityFlags =priv-> changeList->changeNote[newNote].capabilityFlags;
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogCollapseQueue,priv->changeList->changeNote[newNote].newStateNumber,
                                                                    priv->changeList->changeNote[previousNote].newStateNumber);
        priv->changeList->changeNote[previousNote].newStateNumber = priv->changeList->changeNote[newNote].newStateNumber;
        priv->changeList->releaseTailChangeNote();
        newNote = previousNote;
        previousNote = priv->changeList->previousChangeNote(newNote);
    }
    IOLockUnlock(priv->queue_lock);
    return IOPMWillAckLater;				// in any case, we can't start yet
}

//*********************************************************************************
// notifyAll
//
// Notify all interested parties either that a change is impending or that the
// previously-notified change is done and power has settled.
// The parameter identifies whether this is the
// pre-change notification or the post-change notification.
//
//*********************************************************************************

IOReturn IOService::notifyAll ( bool is_prechange )
{
    IOPMinformee *		nextObject;
    OSIterator *			iter;
    OSObject *			next;
    IOPowerConnection *	connection;

    // To prevent acknowledgePowerChange from finishing the change note and removing it from the queue if
    // some driver calls it, we inflate the number of pending acks so it cannot become zero.  We'll fix it later.

    priv->head_note_pendingAcks =1;

    // OK, we will go through the lists of interested drivers and power domain children
    // and notify each one of this change.
    nextObject =  priv->interestedDrivers->firstInList();		// notify interested drivers
    while (  nextObject != NULL ) {
        priv->head_note_pendingAcks +=1;
        if (! inform(nextObject, is_prechange) ) {
        }
        nextObject  =  priv->interestedDrivers->nextInList(nextObject);
    }

    if (! acquire_lock() ) {
        return IOPMNoErr;
    }
    if ( priv->head_note_pendingAcks > 1 ) {					// did they all ack?
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,0,0);	// no
        start_ack_timer();
    }
    IOUnlock(priv->our_lock);							// either way

    iter = getChildIterator(gIOPowerPlane);				// notify children
    pm_vars->thePowerStates[priv->head_note_state].staticPower = 0;     // summing their power consumption

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                priv->head_note_pendingAcks +=1;
                notifyChild(connection, is_prechange);
            }
        }
        iter->release();
    }

    if (! acquire_lock() ) {
        return IOPMNoErr;
    }
    priv->head_note_pendingAcks -= 1;			// now make this real
    if (priv->head_note_pendingAcks == 0 ) {		// is it all acked?
        IOUnlock(priv->our_lock);			// yes
        return IOPMAckImplied;				// return ack to parent
    }
    IOUnlock(priv->our_lock);				// no
    return IOPMWillAckLater;
}


//*********************************************************************************
// notifyChild
//
// Notify a power domain child of an upcoming power change.
//
// If the object acknowledges the current change, we return TRUE.
//*********************************************************************************

bool IOService::notifyChild ( IOPowerConnection * theNub, bool is_prechange )
{
    IOReturn		k = IOPMAckImplied;
    unsigned long	childPower;
    IOService *		theChild = (IOService *)(theNub->copyChildEntry(gIOPowerPlane));

   theNub->setAwaitingAck(true);					// in case they don't ack
   
   if ( ! theChild ) {
        return true;
   }
   
   if ( is_prechange ) {
	k = theChild->powerDomainWillChangeTo(priv->head_note_outputFlags,theNub);
   }
   else {
	k = theChild->powerDomainDidChangeTo(priv->head_note_outputFlags,theNub);
   }

   if ( k == IOPMAckImplied ) {						// did the return code ack?
	priv->head_note_pendingAcks -=1;				// yes
        theNub->setAwaitingAck(false);
        childPower = theChild->currentPowerConsumption();
        if ( childPower == kIOPMUnknown ) {
            pm_vars->thePowerStates[priv->head_note_state].staticPower = kIOPMUnknown;
        }
        else {
            if ( pm_vars->thePowerStates[priv->head_note_state].staticPower != kIOPMUnknown ) {
                pm_vars->thePowerStates[priv->head_note_state].staticPower += childPower;
            }
        }
        theChild->release();
	return true;
   }
   theChild->release();
   return false;
}


//*********************************************************************************
// inform
//
// Notify an interested driver of an upcoming power change.
//
// If the object acknowledges the current change, we return TRUE.
//*********************************************************************************

bool IOService::inform ( IOPMinformee * nextObject, bool is_prechange )
{
    IOReturn k = IOPMAckImplied;

   nextObject->timer = -1;					// initialize this

   if ( is_prechange ) {
       pm_vars->thePlatform->PMLog (pm_vars->ourName,PMlogInformDriverPreChange,
                                    (unsigned long)priv->head_note_capabilityFlags,(unsigned long)priv->head_note_state);
       k = nextObject->whatObject->powerStateWillChangeTo( priv->head_note_capabilityFlags,priv->head_note_state,this);
   }
   else {
       pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogInformDriverPostChange,
                                   (unsigned long)priv->head_note_capabilityFlags,(unsigned long)priv->head_note_state);
       k = nextObject->whatObject->powerStateDidChangeTo(priv->head_note_capabilityFlags,priv->head_note_state,this);
   }
   if ( nextObject->timer == 0 ) {				// did it ack behind our back?
       return true;						// yes
   }
   if ( k ==IOPMAckImplied ) {					// no, did the return code ack?
       nextObject->timer = 0;					// yes
       priv->head_note_pendingAcks -= 1;
       return true;
   }
   if ( k < 0 ) {
       nextObject->timer = 0;					// somebody goofed
       priv-> head_note_pendingAcks -= 1;
       return true;
  }
   nextObject->timer = (k * ns_per_us / ACK_TIMER_PERIOD) + 1;	// no, it's a timer
   return false;
}


//*********************************************************************************
// our_prechange_03
//
// All registered applications and kernel clients have positively acknowledged our
// intention of lowering power.  Here we notify them all that we will definitely
// lower the power.  If we don't have to wait for any of them to acknowledge, we
// carry on by notifying interested drivers.  Otherwise, we do wait.
//*********************************************************************************

void IOService::our_prechange_03 ( void )
{
    priv->machine_state = IOPMour_prechange_04;		// next state
    if ( tellChangeDown1(priv->head_note_state) ) {  	// are we waiting for responses?
        our_prechange_04();                     	// no, notify priority clients
    }
}


//*********************************************************************************
// our_prechange_04
//
// All registered applications and kernel clients have positively acknowledged our
// intention of lowering power.  Here we notify "priority" clients that we are
// lowering power.  If we don't have to wait for any of them to acknowledge, we
// carry on by notifying interested drivers.  Otherwise, we do wait.
//*********************************************************************************

void IOService::our_prechange_04 ( void )
{
    priv->machine_state = IOPMour_prechange_05;		// next state
    if ( tellChangeDown2(priv->head_note_state) ) {  	// are we waiting for responses?
        return our_prechange_05();                      // no, notify interested drivers
    }
}


//*********************************************************************************
// our_prechange_05
//
// All registered applications and kernel clients have acknowledged our notification
// that we are lowering power.  Here we notify interested drivers.  If we don't have
// to wait for any of them to acknowledge, we instruct our power driver to make the change.
// Otherwise, we do wait.
//*********************************************************************************

void IOService::our_prechange_05 ( void )
{
    priv->machine_state = IOPMour_prechange_1;		// no, in case they don't all ack
    if ( notifyAll(true) == IOPMAckImplied ) {
        our_prechange_1();
    }
}


//*********************************************************************************
// our_prechange_1
//
// All interested drivers have acknowledged our pre-change notification of a power
// change we initiated.  Here we instruct our controlling driver to make
// the change to the hardware.  If it does so, we continue processing
// (waiting for settle and notifying interested parties post-change.)
// If it doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

void IOService::our_prechange_1 ( void )
{
    if ( instruct_driver(priv->head_note_state) == IOPMAckImplied ) {
        our_prechange_2();					// it's done, carry on
    }
    else {
        priv->machine_state = IOPMour_prechange_2;		// it's not, wait for it
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,0,0);
        start_ack_timer();
    }
}


//*********************************************************************************
// our_prechange_2
//
// Our controlling driver has changed power state on the hardware
// during a power change we initiated.  Here we see if we need to wait
// for power to settle before continuing.  If not, we continue processing
// (notifying interested parties post-change).  If so, we wait and
// continue later.
//*********************************************************************************

void IOService::our_prechange_2 ( void )
{
    priv->settle_time = compute_settle_time();
    if ( priv->settle_time == 0 ) {
       our_prechange_3();
    }
    else {
        priv->machine_state = IOPMour_prechange_3;
        startSettleTimer(priv->settle_time);
    }
}


//*********************************************************************************
// our_prechange_3
//
// Power has settled on a power change we initiated.  Here we notify
// all our interested parties post-change.  If they all acknowledge, we're
// done with this change note, and we can start on the next one.
// Otherwise we have to wait for acknowledgements and finish up later.
//*********************************************************************************

void IOService::our_prechange_3 ( void )
{
    priv->machine_state = IOPMour_prechange_4;		// in case they don't all ack
    if ( notifyAll(false) == IOPMAckImplied ) {
        our_prechange_4();
    }
}


//*********************************************************************************
// our_prechange_4
//
// Power has settled on a power change we initiated, and
// all our interested parties have acknowledged.  We're
// done with this change note, and we can start on the next one.
//*********************************************************************************

void IOService::our_prechange_4 ( void )
{
    all_done();
}


//*********************************************************************************
// parent_down_0
//
// All applications and kernel clients have been notified of a power lowering
// initiated by the parent and we didn't have to wait for any responses.  Here
// we notify any priority clients.  If they all ack, we continue with the power change.
// If at least one doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

IOReturn IOService::parent_down_0 ( void )
{
    priv->machine_state = IOPMparent_down_05;           // in case they don't all ack
    if ( tellChangeDown2(priv->head_note_state) ) {  	// are we waiting for responses?
        return parent_down_02();			// no, notify interested drivers
    }
    return IOPMWillAckLater;                            // they didn't
}


//*********************************************************************************
// parent_down_02
//
// All priority kernel clients have been notified of a power lowering
// initiated by the parent and we didn't have to wait for any responses.  Here
// we notify any interested drivers and power domain children.  If they all ack,
// we continue with the power change.
// If at least one doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

IOReturn IOService::parent_down_02 ( void )
{
    priv->machine_state = IOPMparent_down_4;            // in case they don't all ack
    if ( notifyAll(true) == IOPMAckImplied ) {
        return parent_down_1();                         // they did
    }
    return IOPMWillAckLater;                            // they didn't
}


//*********************************************************************************
// parent_down_04
//
// All applications and kernel clients have been notified of a power lowering
// initiated by the parent and we had to wait for responses.  Here
// we notify any priority clients.  If they all ack, we continue with the power change.
// If at least one doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

void IOService::parent_down_04 ( void )
{
    priv->machine_state = IOPMparent_down_05;           // in case they don't all ack
    if ( tellChangeDown2(priv->head_note_state) ) {  	// are we waiting for responses?
        parent_down_05();				// no, notify interested drivers
    }
}


//*********************************************************************************
// parent_down_05
//
// All applications and kernel clients have been notified of a power lowering
// initiated by the parent and we had to wait for their responses.  Here we notify
// any interested drivers and power domain children.  If they all ack, we continue
// with the power change.
// If at least one doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

void IOService::parent_down_05 ( void )
{
    priv->machine_state = IOPMparent_down_4;            // in case they don't all ack
    if ( notifyAll(true) == IOPMAckImplied ) {
        parent_down_4();                                // they did
    }
}


//*********************************************************************************
// parent_down_1
//
// All parties have acknowledged our pre-change notification of a power
// lowering initiated by the parent.  Here we instruct our controlling driver
// to put the hardware in the state it needs to be in when the domain is
// lowered.  If it does so, we continue processing
// (waiting for settle and acknowledging the parent.)
// If it doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

IOReturn IOService::parent_down_1 ( void )
{
    if ( instruct_driver(priv->head_note_state) == IOPMAckImplied ) {
        return parent_down_2();			// it's done, carry on
    }
    priv->machine_state = IOPMparent_down_5;	// it's not, wait for it
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,0,0);
    start_ack_timer();
    return IOPMWillAckLater;
}


//*********************************************************************************
// parent_down_4
//
// We had to wait for it, but all parties have acknowledged our pre-change
// notification of a power lowering initiated by the parent.
// Here we instruct our controlling driver
// to put the hardware in the state it needs to be in when the domain is
// lowered.  If it does so, we continue processing
// (waiting for settle and acknowledging the parent.)
// If it doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

void IOService::parent_down_4 ( void )
{
    if ( instruct_driver(priv->head_note_state) == IOPMAckImplied ) {
        parent_down_5();					// it's done, carry on
    }
    else {
        priv-> machine_state = IOPMparent_down_5;	// it's not, wait for it
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,0,0);
        start_ack_timer();
    }
}


//*********************************************************************************
// parent_down_2
//
// Our controlling driver has changed power state on the hardware
// during a power change initiated by our parent.  Here we see if we need
// to wait for power to settle before continuing.  If not, we continue
// processing (acknowledging our preparedness to the parent).
// If so, we wait and continue later.
//*********************************************************************************

IOReturn IOService::parent_down_2 ( void )
{
    IOService * nub;
    
    priv->settle_time = compute_settle_time();
    if ( priv->settle_time == 0 ) {
        priv->machine_state = IOPMparent_down_6;	// in case they don't all ack
        if ( notifyAll(false) == IOPMAckImplied ) {
            nub = priv->head_note_parent;
            all_done();
            nub->release();
            return IOPMAckImplied;
        }
        return IOPMWillAckLater;			// they didn't
   }
   else {
       priv->machine_state = IOPMparent_down_3;
       startSettleTimer(priv->settle_time);
       return IOPMWillAckLater;
   }
}


//*********************************************************************************
// parent_down_5
//
// Our controlling driver has changed power state on the hardware
// during a power change initiated by our parent.  We have had to wait
// for acknowledgement from interested parties, or we have had to wait
// for the controlling driver to change the state.  Here we see if we need
// to wait for power to settle before continuing.  If not, we continue
// processing (acknowledging our preparedness to the parent).
// If so, we wait and continue later.
//*********************************************************************************

void IOService::parent_down_5 ( void )
{
    priv->settle_time = compute_settle_time();
    if ( priv->settle_time == 0 ) {
        parent_down_3();
   }
   else {
       priv->machine_state = IOPMparent_down_3;
       startSettleTimer(priv->settle_time);
   }
}


//*********************************************************************************
// parent_down_3
//
// Power has settled on a power change initiated by our parent.  Here we
// notify interested parties.
//*********************************************************************************

void IOService::parent_down_3 ( void )
{
    IORegistryEntry *	nub;
    IOService * 	parent;

    priv->machine_state = IOPMparent_down_6;	// in case they don't all ack
    if ( notifyAll(false) == IOPMAckImplied ) {
        nub = priv->head_note_parent;
        all_done();
        parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
        if ( parent ) {
            parent->acknowledgePowerChange((IOService *)nub);
            parent->release();
        }
        nub->release();
    }
}


//*********************************************************************************
// parent_down_6
//
// We had to wait for it, but all parties have acknowledged our post-change
// notification of a power  lowering initiated by the parent.
// Here we acknowledge the parent.
// We are done with this change note, and we can start on the next one.
//*********************************************************************************

void IOService::parent_down_6 ( void )
{
    IORegistryEntry *	nub;
    IOService *		parent;
    
    nub = priv->head_note_parent;
    all_done();
    parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
    if ( parent ) {
        parent->acknowledgePowerChange((IOService *)nub);
        parent->release();
    }
    nub->release();
}


//*********************************************************************************
// parent_up_0
//
// Our parent has informed us via powerStateDidChange that it has
// raised the power in our power domain, and we have had to wait
// for some interested party to acknowledge our notification.
//   Here we instruct our controlling
// driver to program the hardware to take advantage of the higher domain
// power.  If it does so, we continue processing
// (waiting for settle and notifying interested parties post-change.)
// If it doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

void IOService::parent_up_0 ( void )
{
    if ( instruct_driver(priv->head_note_state) == IOPMAckImplied ) {
        parent_up_4();					// it did it, carry on
    }
    else {
        priv->machine_state = IOPMparent_up_4;	// it didn't, wait for it
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,0,0);
        start_ack_timer();
    }
}


//*********************************************************************************
// parent_up_1
//
// Our parent has informed us via powerStateDidChange that it has
// raised the power in our power domain.  Here we instruct our controlling
// driver to program the hardware to take advantage of the higher domain
// power.  If it does so, we continue processing
// (waiting for settle and notifying interested parties post-change.)
// If it doesn't, we have to wait for it to acknowledge and then continue.
//*********************************************************************************

IOReturn IOService::parent_up_1 ( void )
{
    if ( instruct_driver(priv->head_note_state) == IOPMAckImplied ) {
        return parent_up_2();				// it did it, carry on
    }
    else {
        priv->machine_state = IOPMparent_up_4;	// it didn't, wait for it
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,0,0);
        start_ack_timer();
        return IOPMWillAckLater;
    }
}


//*********************************************************************************
// parent_up_2
//
// Our controlling driver has changed power state on the hardware
// during a power raise initiated by the parent.  Here we see if we need to wait
// for power to settle before continuing.  If not, we continue processing
// (notifying interested parties post-change).  If so, we wait and
// continue later.
//*********************************************************************************

IOReturn IOService::parent_up_2 ( void )
{
    priv->settle_time = compute_settle_time();
    if ( priv->settle_time == 0 ) {
        return parent_up_3();
  }
  else {
      priv->machine_state = IOPMparent_up_5;
      startSettleTimer(priv->settle_time);
      return IOPMWillAckLater;
  }
}


//*********************************************************************************
// parent_up_4
//
// Our controlling driver has changed power state on the hardware
// during a power raise initiated by the parent, but we had to wait for it.
// Here we see if we need to wait for power to settle before continuing.
// If not, we continue processing  (notifying interested parties post-change).
// If so, we wait and continue later.
//*********************************************************************************

void IOService::parent_up_4 ( void )
{
    priv->settle_time = compute_settle_time();
    if ( priv->settle_time == 0 ) {
        parent_up_5();
  }
  else {
      priv->machine_state = IOPMparent_up_5;
      startSettleTimer(priv->settle_time);
  }
}


//*********************************************************************************
// parent_up_3
//
// No power settling was required on a power raise initiated by the parent.
// Here we notify all our interested parties post-change.  If they all acknowledge,
// we're done with this change note, and we can start on the next one.
// Otherwise we have to wait for acknowledgements and finish up later.
//*********************************************************************************

IOReturn IOService::parent_up_3 ( void )
{
    IOService * nub;
    
    priv->machine_state = IOPMparent_up_6;	// in case they don't all ack
    if ( notifyAll(false) == IOPMAckImplied ) {
        nub = priv->head_note_parent;
        all_done();
        nub->release();
        return IOPMAckImplied;
    }
    return IOPMWillAckLater;			// they didn't
}


//*********************************************************************************
// parent_up_5
//
// Power has settled on a power raise initiated by the parent.
// Here we notify all our interested parties post-change.  If they all acknowledge,
// we're done with this change note, and we can start on the next one.
// Otherwise we have to wait for acknowledgements and finish up later.
//*********************************************************************************

void IOService::parent_up_5 ( void )
{
    priv->machine_state = IOPMparent_up_6;	// in case they don't all ack
    if ( notifyAll(false) == IOPMAckImplied ) {
        parent_up_6();
    }
}


//*********************************************************************************
// parent_up_6
//
// All parties have acknowledged our post-change notification of a power
// raising initiated by the parent.  Here we acknowledge the parent.
// We are done with this change note, and we can start on the next one.
//*********************************************************************************

void IOService::parent_up_6 ( void )
{
    IORegistryEntry *	nub;
    IOService *		parent;
    
    nub = priv->head_note_parent;
    all_done();
    parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
    if ( parent ) {
        parent->acknowledgePowerChange((IOService *)nub);
        parent->release();
    }
    nub->release();
}


//*********************************************************************************
// all_done
//
// A power change is complete, and the used post-change note is at
// the head of the queue.  Remove it and set myCurrentState to the result
// of the change.  Start up the next change in queue.
//*********************************************************************************

void IOService::all_done ( void )
{
    unsigned long	previous_state;
    IORegistryEntry *	nub;
    IOService *		parent;
    
    priv->machine_state = IOPMfinished;

    if ( priv->head_note_flags & IOPMWeInitiated ) {				// our power change
        if ( !( priv->head_note_flags & IOPMNotDone) ) {			// could our driver switch to the new state?
            if ( pm_vars->myCurrentState < priv->head_note_state ) {		// yes, did power raise?
                tellChangeUp (priv->head_note_state);				// yes, inform clients and apps
            }
            else {
                if ( !  priv->we_are_root ) {					// no, if this lowers our
                    ask_parent(priv->head_note_state);				// power requirements, tell the parent
                }
            }
            previous_state = pm_vars->myCurrentState;
            pm_vars->myCurrentState = priv->head_note_state;			// either way
            priv->imminentState = pm_vars->myCurrentState;
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogChangeDone,(unsigned long)pm_vars->myCurrentState,0);
            powerChangeDone(previous_state);					// inform subclass policy-maker
        }
//        else {									// no
//            pm_vars->myCurrentState = pm_vars->theControllingDriver->powerStateForDomainState(pm_vars->parentsCurrentPowerFlags);
//        }
    }
    if ( priv->head_note_flags & IOPMParentInitiated) {				// parent's power change
        if ( ((priv->head_note_flags & IOPMDomainWillChange) && (pm_vars->myCurrentState >= priv->head_note_state)) ||
             ((priv->head_note_flags & IOPMDomainDidChange) && (pm_vars->myCurrentState < priv->head_note_state)) ) {
            if ( pm_vars->myCurrentState < priv->head_note_state ) {		// did power raise?
                tellChangeUp (priv->head_note_state);				// yes, inform clients and apps
            }
            previous_state = pm_vars->myCurrentState;				// either way
            pm_vars->myCurrentState = priv->head_note_state;
            priv->imminentState = pm_vars->myCurrentState;
            pm_vars->maxCapability = pm_vars->theControllingDriver->maxCapabilityForDomainState(priv->head_note_domainState);

            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogChangeDone,(unsigned long)pm_vars->myCurrentState,0);
            powerChangeDone(previous_state);					// inform subclass policy-maker
        }
    }

    IOLockLock(priv->queue_lock);
    priv->changeList->releaseHeadChangeNote();					// we're done with this
        
    priv->head_note = priv->changeList->currentChange();			// start next one in queue
    if ( priv->head_note != -1 ) {

        IOLockUnlock(priv->queue_lock);
        if (priv->changeList->changeNote[priv->head_note].flags & IOPMWeInitiated ) {
            start_our_change(priv->head_note);
        }
        else {
            nub = priv->changeList->changeNote[priv->head_note].parent;
            if ( start_parent_change(priv->head_note) == IOPMAckImplied ) {
                parent = (IOService *)nub->copyParentEntry(gIOPowerPlane);
                if ( parent ) {
                    parent->acknowledgePowerChange((IOService *)nub);
                    parent->release();
                }
            }
        }
    }
    IOLockUnlock(priv->queue_lock);
}



//*********************************************************************************
// all_acked
//
// A driver or child has acknowledged our notification of an upcoming power
// change, and this acknowledgement is the last one pending
// before we change power or after changing power.
//
//*********************************************************************************

void IOService::all_acked ( void )
{
    switch (priv->machine_state) {
       case IOPMour_prechange_1:
           our_prechange_1();
           break;
       case IOPMour_prechange_4:
           our_prechange_4();
           break;
       case IOPMparent_down_4:
           parent_down_4();	
           break;
       case IOPMparent_down_6:
           parent_down_6();
           break;
       case IOPMparent_up_0:
           parent_up_0();
           break;
       case IOPMparent_up_6:
           parent_up_6();
           break;
   }
}


//*********************************************************************************
// settleTimerExpired
//
// Power has settled after our last change.  Notify interested parties that
// there is a new power state.
//*********************************************************************************

void IOService::settleTimerExpired ( void )
{
    if ( ! initialized ) {
        return;					// we're unloading
    }

    switch (priv->machine_state) {
        case IOPMour_prechange_3:
            our_prechange_3();
            break;
        case IOPMparent_down_3:
            parent_down_3();
            break;
        case IOPMparent_up_5:
            parent_up_5();
            break;
    }
}


//*********************************************************************************
// compute_settle_time
//
// Compute the power-settling delay in microseconds for the
// change from myCurrentState to head_note_state.
//*********************************************************************************

unsigned long IOService::compute_settle_time ( void )
{
    unsigned long totalTime;
    unsigned long i;

    totalTime = 0;						// compute total time to attain the new state
    i = pm_vars->myCurrentState;
    if ( priv->head_note_state < pm_vars->myCurrentState ) {	// we're lowering power
        while ( i > priv->head_note_state ) {
            totalTime +=  pm_vars->thePowerStates[i].settleDownTime;
            i--;
        }
    }

    if ( priv->head_note_state > pm_vars->myCurrentState ) {	// we're raising power
        while ( i < priv->head_note_state ) {
            totalTime +=  pm_vars->thePowerStates[i+1].settleUpTime;
            i++;
        }
    }

    return totalTime;
}


//*********************************************************************************
// startSettleTimer
//
// Enter with a power-settling delay in microseconds and start a nano-second
// timer for that delay.
//*********************************************************************************

IOReturn IOService::startSettleTimer ( unsigned long delay )
{
    AbsoluteTime	deadline;
    
    clock_interval_to_deadline(delay, kMicrosecondScale, &deadline);

    thread_call_enter_delayed(priv->settleTimer, deadline);

    return IOPMNoErr;
}

//*********************************************************************************
// ack_timer_ticked
//
// The acknowledgement timeout periodic timer has ticked.
// If we are awaiting acks for a power change notification,
// we decrement the timer word of each interested driver which hasn't acked.
// If a timer word becomes zero, we pretend the driver aknowledged.
// If we are waiting for the controlling driver to change the power
// state of the hardware, we decrement its timer word, and if it becomes
// zero, we pretend the driver acknowledged.
//*********************************************************************************

void IOService::ack_timer_ticked ( void )
{
    IOPMinformee * nextObject;

    if ( ! initialized ) {
        return;					// we're unloading
    }

    if (! acquire_lock() ) {
        return;
    }
    
    switch (priv->machine_state) {
        case IOPMour_prechange_2:
        case IOPMparent_down_5:
        case IOPMparent_up_4:
            if ( priv->driver_timer != 0 ) {                            // are we waiting for our driver to make its change?
                priv->driver_timer -= 1;                                // yes, tick once
                if ( priv->driver_timer == 0 ) {                        // it's tardy, we'll go on without it
                    IOUnlock(priv->our_lock);
                    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogCtrlDriverTardy,0,0);
                    driver_acked();
                }
                else {                                                  // still waiting, set timer again
                    start_ack_timer();
                    IOUnlock(priv->our_lock);
                }
            }
            else {
                IOUnlock(priv->our_lock);
            }
            break;

        case IOPMour_prechange_1:
        case IOPMour_prechange_4:
        case IOPMparent_down_4:
        case IOPMparent_down_6:
        case IOPMparent_up_0:
        case IOPMparent_up_6:
            if (priv->head_note_pendingAcks != 0 ) {                    // are we waiting for interested parties to acknowledge?
                nextObject =  priv->interestedDrivers->firstInList();   // yes, go through the list of interested drivers
                while (  nextObject != NULL ) {                         // and check each one
                    if ( nextObject->timer > 0 ) {
                        nextObject->timer -= 1;
                        if ( nextObject->timer == 0 ) {                 // this one should have acked by now
                            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogIntDriverTardy,0,0);
                            kprintf("interested driver tardy: %s\n",nextObject->whatObject->getName());
                            priv->head_note_pendingAcks -= 1;
                        }
                    }
                    nextObject  =  priv->interestedDrivers->nextInList(nextObject);
                }
                if ( priv->head_note_pendingAcks == 0 ) {       // is that the last?
                    IOUnlock(priv->our_lock);
                    all_acked();                                // yes, we can continue
                }
                else {                                          // no, set timer again
                    start_ack_timer();
                    IOUnlock(priv->our_lock);
                }
            }
            else {
                IOUnlock(priv->our_lock);
            }
            break;

        case IOPMparent_down_0:                                 // apps didn't respond to parent-down notification
            IOUnlock(priv->our_lock);
            IOLockLock(priv->flags_lock);
            if (pm_vars->responseFlags) {
                pm_vars->responseFlags->release();              // get rid of this stuff
                pm_vars->responseFlags = NULL;
            }
            IOLockUnlock(priv->flags_lock);
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientTardy,0,5);
            parent_down_04();                                   // carry on with the change
            break;
            
        case IOPMparent_down_05:
            IOUnlock(priv->our_lock);
            IOLockLock(priv->flags_lock);
            if (pm_vars->responseFlags) {
                pm_vars->responseFlags->release();              // get rid of this stuff
                pm_vars->responseFlags = NULL;
            }
            IOLockUnlock(priv->flags_lock);
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientTardy,0,1);
            parent_down_05();                                   // carry on with the change
            break;
            
        case IOPMour_prechange_03:                              // apps didn't respond to our power-down request
            IOUnlock(priv->our_lock);
            IOLockLock(priv->flags_lock);
            if (pm_vars->responseFlags) {
                pm_vars->responseFlags->release();              // get rid of this stuff
                pm_vars->responseFlags = NULL;
            }
            IOLockUnlock(priv->flags_lock);
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientTardy,0,2);
            tellNoChangeDown(priv->head_note_state);		// rescind the request
            priv->head_note_flags |= IOPMNotDone;		// mark the change note un-actioned
            all_done();						// and we're done
            break;
            
        case IOPMour_prechange_04:                              // clients didn't respond to our power-down note
            IOUnlock(priv->our_lock);
            IOLockLock(priv->flags_lock);
            if (pm_vars->responseFlags) {
                pm_vars->responseFlags->release();              // get rid of this stuff
                pm_vars->responseFlags = NULL;
            }
            IOLockUnlock(priv->flags_lock);
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientTardy,0,4);
            our_prechange_04();                               	// carry on with the change
            break;
            
        case IOPMour_prechange_05:                              // apps didn't respond to our power-down notification
            IOUnlock(priv->our_lock);
            IOLockLock(priv->flags_lock);
            if (pm_vars->responseFlags) {
                pm_vars->responseFlags->release();              // get rid of this stuff
                pm_vars->responseFlags = NULL;
            }
            IOLockUnlock(priv->flags_lock);
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientTardy,0,3);
            our_prechange_05();                               	// carry on with the change
            break;
            
        default:
            IOUnlock(priv->our_lock);                           // not waiting for acks
            break;
    }
}


//*********************************************************************************
// start_ack_timer
//
//*********************************************************************************

void IOService::start_ack_timer ( void )
{
    AbsoluteTime	deadline;

    clock_interval_to_deadline(ACK_TIMER_PERIOD, kNanosecondScale, &deadline);
    
    thread_call_enter_delayed(priv->ackTimer, deadline);
}


//*********************************************************************************
// stop_ack_timer
//
//*********************************************************************************

void IOService::stop_ack_timer ( void )
{
    thread_call_cancel(priv->ackTimer);
}


//*********************************************************************************
// c-language timer expiration functions
//
//*********************************************************************************

static void ack_timer_expired ( thread_call_param_t us)
{
    ((IOService *)us)->ack_timer_ticked();
}


static void settle_timer_expired ( thread_call_param_t us)
{
    ((IOService *)us)->settleTimerExpired();
}


//*********************************************************************************
// add_child_to_active_change
//
// A child has just registered with us.  If there is
// currently a change in progress, get the new party involved: if we
// have notified all parties and are waiting for acks, notify the new
// party.
//*********************************************************************************

IOReturn IOService::add_child_to_active_change ( IOPowerConnection * newObject )
{
    if (! acquire_lock() ) {
        return IOPMNoErr;
    }

    switch (priv->machine_state) {
        case IOPMour_prechange_1:
        case IOPMparent_down_4:
        case IOPMparent_up_0:
            priv->head_note_pendingAcks += 2;		// one for this child and one to prevent
            IOUnlock(priv->our_lock);			// incoming acks from changing our state
            notifyChild(newObject, true);
            if (! acquire_lock() ) {
                --priv->head_note_pendingAcks;		// put it back
                return IOPMNoErr;
            }
            if ( --priv->head_note_pendingAcks == 0 ) {	// are we still waiting for acks?
                stop_ack_timer();			// no, stop the timer
                IOUnlock(priv->our_lock);
                all_acked();				// and now we can continue
                return IOPMNoErr;
            }
            break;
        case IOPMour_prechange_4:
        case IOPMparent_down_6:
        case IOPMparent_up_6:
            priv->head_note_pendingAcks += 2;		// one for this child and one to prevent
            IOUnlock(priv->our_lock);			// incoming acks from changing our state
            notifyChild(newObject, false);
            if (! acquire_lock() ) {
                --priv->head_note_pendingAcks;		// put it back
                return IOPMNoErr;
            }
            if ( --priv->head_note_pendingAcks == 0 ) {	// are we still waiting for acks?
                stop_ack_timer();			// no, stop the timer
                IOUnlock(priv->our_lock);
                all_acked();				// and now we can continue
                return IOPMNoErr;
            }
            break;
    }
    IOUnlock(priv->our_lock);
    return IOPMNoErr;
}


//*********************************************************************************
// add_driver_to_active_change
//
// An interested driver has just registered with us.  If there is
// currently a change in progress, get the new party involved: if we
// have notified all parties and are waiting for acks, notify the new
// party.
//*********************************************************************************

IOReturn IOService::add_driver_to_active_change ( IOPMinformee * newObject )
{
    if (! acquire_lock() ) {
        return IOPMNoErr;
    }

    switch (priv->machine_state) {
        case IOPMour_prechange_1:
        case IOPMparent_down_4:
        case IOPMparent_up_0:
            priv->head_note_pendingAcks += 2;		// one for this driver and one to prevent
            IOUnlock(priv->our_lock);			// incoming acks from changing our state
            inform(newObject, true);			// inform the driver
            if (! acquire_lock() ) {
                --priv->head_note_pendingAcks;		// put it back
                return IOPMNoErr;
            }
            if ( --priv->head_note_pendingAcks == 0 ) {	// are we still waiting for acks?
                stop_ack_timer();			// no, stop the timer
                IOUnlock(priv->our_lock);
                all_acked();				// and now we can continue
                return IOPMNoErr;
            }
            break;
        case IOPMour_prechange_4:
        case IOPMparent_down_6:
        case IOPMparent_up_6:
            priv->head_note_pendingAcks += 2;		// one for this driver and one to prevent
            IOUnlock(priv->our_lock);			// incoming acks from changing our state
            inform(newObject, false);			// inform the driver
            if (! acquire_lock() ) {
                --priv->head_note_pendingAcks;		// put it back
                return IOPMNoErr;
            }
            if ( --priv->head_note_pendingAcks == 0 ) {	// are we still waiting for acks?
                stop_ack_timer();			// no, stop the timer
                IOUnlock(priv->our_lock);
                all_acked();				// and now we can continue
                return IOPMNoErr;
            }
            break;
    }
    IOUnlock(priv->our_lock);
    return IOPMNoErr;
}


//*********************************************************************************
// start_parent_change
//
// Here we begin the processing of a change note  initiated by our parent
// which is at the head of the queue.
//
// It is possible for the change to be processed to completion and removed from the queue.
// There are several possible interruptions to the processing, though, and they are:
// we may have to wait for interested parties to acknowledge our pre-change notification,
// we may have to wait for our controlling driver to change the hardware power state,
// there may be a settling time after changing the hardware power state,
// we may have to wait for interested parties to acknowledge our post-change notification,
// we may have to wait for the acknowledgement timer expiration to substitute for the
// acknowledgement from a failing driver.
//*********************************************************************************

IOReturn IOService::start_parent_change ( unsigned long queue_head )
{
    priv->head_note = queue_head;
    priv->head_note_flags = priv-> changeList->changeNote[priv->head_note].flags;
    priv->head_note_state =  priv->changeList->changeNote[priv->head_note].newStateNumber;
    priv->imminentState = priv->head_note_state;
    priv->head_note_outputFlags =  priv->changeList->changeNote[priv->head_note].outputPowerCharacter;
    priv->head_note_domainState = priv->changeList->changeNote[priv->head_note].domainState;
    priv->head_note_parent = priv->changeList->changeNote[priv->head_note].parent;
    priv->head_note_capabilityFlags =  priv->changeList->changeNote[priv->head_note].capabilityFlags;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartParentChange,
                    (unsigned long)priv->head_note_state,(unsigned long)pm_vars->myCurrentState);

    ask_parent( priv->ourDesiredPowerState);			// if we need something and haven't told the parent, do so

    if ( priv->head_note_state < pm_vars->myCurrentState ) {    // power domain is lowering
        setParentInfo(priv->changeList->changeNote[priv->head_note].singleParentState,priv->head_note_parent);
	priv->initial_change = false;
        priv->machine_state = IOPMparent_down_0;                // tell apps and kernel clients
        if ( tellChangeDown1(priv->head_note_state) ) {  	// are we waiting for responses?
            return parent_down_0();                             // no, notify priority clients
        }
       return IOPMWillAckLater;                                 // yes
    }

    if ( priv->head_note_state > pm_vars->myCurrentState ) {		// parent is raising power, we may or may not
        if ( priv->ourDesiredPowerState > pm_vars->myCurrentState ) {
           if ( priv->ourDesiredPowerState < priv->head_note_state ) {
               priv->head_note_state = priv->ourDesiredPowerState;	// we do, but not all the way
               priv->imminentState = priv->head_note_state;
               priv->head_note_outputFlags =   pm_vars->thePowerStates[priv->head_note_state].outputPowerCharacter;
               priv->head_note_capabilityFlags =   pm_vars->thePowerStates[priv->head_note_state].capabilityFlags;
               pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAmendParentChange,(unsigned long)priv->head_note_state,0);
            }
        }
        else {
            priv->head_note_state = pm_vars->myCurrentState;		// we don't
            priv->imminentState = priv->head_note_state;
            priv->head_note_outputFlags =   pm_vars->thePowerStates[priv->head_note_state].outputPowerCharacter;
            priv->head_note_capabilityFlags =   pm_vars->thePowerStates[priv->head_note_state].capabilityFlags;
            pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAmendParentChange,(unsigned long)priv->head_note_state,0);
        }
    }

    if ( (priv->head_note_state > pm_vars->myCurrentState) &&
         (priv->head_note_flags & IOPMDomainDidChange) ) {		// changing up
        priv->initial_change = false;
	priv->machine_state = IOPMparent_up_0;
	if (  notifyAll(true) == IOPMAckImplied ) {
            return parent_up_1();
	}
	return IOPMWillAckLater;					// they didn't all ack
    }

    all_done();
    return IOPMAckImplied;						// a null change or power will go up
}


//*********************************************************************************
// start_our_change
//
// Here we begin the processing of a change note  initiated by us
// which is at the head of the queue.
//
// It is possible for the change to be processed to completion and removed from the queue.
// There are several possible interruptions to the processing, though, and they are:
// we may have to wait for interested parties to acknowledge our pre-change notification,
// changes initiated by the parent will wait in the middle for powerStateDidChange,
// we may have to wait for our controlling driver to change the hardware power state,
// there may be a settling time after changing the hardware power state,
// we may have to wait for interested parties to acknowledge our post-change notification,
// we may have to wait for the acknowledgement timer expiration to substitute for the
// acknowledgement from a failing driver.
//*********************************************************************************

void IOService::start_our_change ( unsigned long queue_head )
{
    priv->head_note = queue_head;
    priv->head_note_flags =  priv->changeList->changeNote[priv->head_note].flags;
    priv->head_note_state =  priv->changeList->changeNote[priv->head_note].newStateNumber;
    priv->imminentState = priv->head_note_state;
    priv->head_note_outputFlags =  priv->changeList->changeNote[priv->head_note].outputPowerCharacter;
    priv->head_note_capabilityFlags =  priv->changeList->changeNote[priv->head_note].capabilityFlags;

    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartDeviceChange,
                (unsigned long)priv->head_note_state,(unsigned long)pm_vars->myCurrentState);

    if ( priv->head_note_capabilityFlags & IOPMNotAttainable ) {	// can our driver switch to the new state?
        if ( !  priv->we_are_root ) {					// no, ask the parent to do it then
            ask_parent(priv->head_note_state);
        }
        priv-> head_note_flags |= IOPMNotDone;				// mark the change note un-actioned
        all_done();							// and we're done
        return;
    }
                                                                        // is there enough power in the domain?
    if ( (pm_vars->maxCapability < priv->head_note_state) && (!  priv->we_are_root) ) {
        if ( !  priv->we_are_root ) {					// no, ask the parent to raise it
            ask_parent(priv->head_note_state);
        }
        priv->head_note_flags |= IOPMNotDone;				// no, mark the change note un-actioned
        all_done();							// and we're done
        return;								// till the parent raises power
    }

    if ( !  priv->initial_change ) {
        if ( priv->head_note_state == pm_vars->myCurrentState ) {
            all_done();						// we initiated a null change; forget it
            return;
        }
    }
    priv->initial_change = false;

    if ( priv->head_note_state < pm_vars->myCurrentState ) {	// dropping power?
        priv->machine_state = IOPMour_prechange_03;		// yes, in case we have to wait for acks
        pm_vars->doNotPowerDown = false;
        if ( askChangeDown(priv->head_note_state) ) {  		// ask apps and kernel clients if we can drop power
            if ( pm_vars->doNotPowerDown ) {			// don't have to wait, did any clients veto?
                tellNoChangeDown(priv->head_note_state);	// yes, rescind the warning
                priv-> head_note_flags |= IOPMNotDone;		// mark the change note un-actioned
                all_done();					// and we're done
            }
            else {
                our_prechange_03();				// no, tell'em we're dropping power
            }
        }
    }
    else {
        if ( !  priv->we_are_root ) {				// we are raising power
            ask_parent(priv->head_note_state);			// if this changes our power requirement, tell the parent
        }
        priv->machine_state = IOPMour_prechange_1;		// in case they don't all ack
        if ( notifyAll(true) == IOPMAckImplied ) {		// notify interested drivers and children
            our_prechange_1();
        }
    }
}


//*********************************************************************************
// ask_parent
//
// Call the power domain parent to ask for a higher power state in the domain
// or to suggest a lower power state.
//*********************************************************************************

IOReturn IOService::ask_parent ( unsigned long requestedState )
{
    OSIterator *	iter;
    OSObject *		next;
    IOPowerConnection *	connection;
    IOService *		parent;
    unsigned long	ourRequest = pm_vars->thePowerStates[requestedState].inputPowerRequirement;

    if ( pm_vars->thePowerStates[requestedState].capabilityFlags & (kIOPMChildClamp | kIOPMPreventIdleSleep) ) {
        ourRequest |= kIOPMPreventIdleSleep;
    }
    if ( pm_vars->thePowerStates[requestedState].capabilityFlags & (kIOPMChildClamp2 | kIOPMPreventSystemSleep) ) {
        ourRequest |= kIOPMPreventSystemSleep;
    }
    
    if ( priv->previousRequest == ourRequest ) {	// is this a new desire?
        return IOPMNoErr;				// no, the parent knows already, just return
    }

    if (  priv->we_are_root ) {
        return IOPMNoErr;
    }
    priv->previousRequest =  ourRequest;

    iter = getParentIterator(gIOPowerPlane);

    if ( iter ) {
        while ( (next = iter->getNextObject()) ) {
            if ( (connection = OSDynamicCast(IOPowerConnection,next)) ) {
                parent = (IOService *)connection->copyParentEntry(gIOPowerPlane);
                if ( parent ) {
                    if ( parent->requestPowerDomainState(ourRequest,connection,IOPMLowestState)!= IOPMNoErr ) {
                        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogRequestDenied,
                                                                (unsigned long)priv->previousRequest,0);
                    }
                    parent->release();
                }
            }
        }
        iter->release();
    }

    return IOPMNoErr;
}


//*********************************************************************************
// instruct_driver
//
// Call the controlling driver and have it change the power state of the
// hardware.  If it returns IOPMAckImplied, the change is complete, and
// we return IOPMAckImplied.  Otherwise, it will ack when the change
// is done; we return IOPMWillAckLater.
//*********************************************************************************
IOReturn IOService::instruct_driver ( unsigned long newState )
{
    IOReturn return_code;

    if (  pm_vars->thePowerStates[newState].capabilityFlags & IOPMNotAttainable ) {	// can our driver switch to the desired state?
        return IOPMAckImplied;						// no, so don't try
    }
    priv->driver_timer = -1;
    
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogProgramHardware,newState,0);

    return_code = pm_vars->theControllingDriver->setPowerState( newState,this );	// yes, instruct it
    if ( return_code == IOPMAckImplied ) {					// it finished
        priv->driver_timer = 0;
        return IOPMAckImplied;
    }

    if ( priv->driver_timer == 0 ) {						// it acked behind our back
        return IOPMAckImplied;
    }

    if ( return_code < 0 ) {							// somebody goofed
        return IOPMAckImplied;
    }
    priv->driver_timer = (return_code * ns_per_us / ACK_TIMER_PERIOD) + 1;	// it didn't finish
    return IOPMWillAckLater;
}


//*********************************************************************************
// acquire_lock
//
// We are acquiring the lock we use to protect our queue head from
// simutaneous access by a thread which calls acknowledgePowerStateChange
// or acknowledgeSetPowerState and the ack timer expiration thread.
// Return TRUE if we acquire the lock, and the queue head didn't change
// while we were acquiring the lock (and maybe blocked).
// If there is no queue head, or it changes while we are blocked,
// return FALSE with the lock unlocked.
//*********************************************************************************

bool IOService::acquire_lock ( void )
{
    long current_change_note;

    current_change_note = priv->head_note;
    if ( current_change_note == -1 ) {
        return FALSE;
    }

    IOTakeLock(priv->our_lock);
    if ( current_change_note == priv->head_note ) {
        return TRUE;
    }
    else {					// we blocked and something changed radically
        IOUnlock(priv->our_lock);		// so there's nothing to do any more
        return FALSE;
    }
}


//*********************************************************************************
// askChangeDown
//
// Ask registered applications and kernel clients if we can change to a lower
// power state.
//
// Subclass can override this to send a different message type.  Parameter is
// the destination state number.
//
// Return true if we don't have to wait for acknowledgements
//*********************************************************************************

bool IOService::askChangeDown ( unsigned long stateNum )
{
    return tellClientsWithResponse(kIOMessageCanDevicePowerOff);
}


//*********************************************************************************
// tellChangeDown1
//
// Notify registered applications and kernel clients that we are definitely
// dropping power.
//
// Return true if we don't have to wait for acknowledgements
//*********************************************************************************

bool IOService::tellChangeDown1 ( unsigned long stateNum )
{
    pm_vars->outofbandparameter = kNotifyApps;
    return tellChangeDown(stateNum);
}


//*********************************************************************************
// tellChangeDown2
//
// Notify priority clients that we are definitely dropping power.
//
// Return true if we don't have to wait for acknowledgements
//*********************************************************************************

bool IOService::tellChangeDown2 ( unsigned long stateNum )
{
    pm_vars->outofbandparameter = kNotifyPriority;
    return tellChangeDown(stateNum);
}


//*********************************************************************************
// tellChangeDown
//
// Notify registered applications and kernel clients that we are definitely
// dropping power.
//
// Subclass can override this to send a different message type.  Parameter is
// the destination state number.
//
// Return true if we don't have to wait for acknowledgements
//*********************************************************************************

bool IOService::tellChangeDown ( unsigned long stateNum )
{
    return tellClientsWithResponse(kIOMessageDeviceWillPowerOff);
}


//*********************************************************************************
// tellClientsWithResponse
//
// Notify registered applications and kernel clients that we are definitely
// dropping power.
//
// Return true if we don't have to wait for acknowledgements
//*********************************************************************************

bool IOService::tellClientsWithResponse ( int messageType )
{
    struct context      theContext;
    AbsoluteTime        deadline;
    OSBoolean *         aBool;

    pm_vars->responseFlags = OSArray::withCapacity( 1 );
    pm_vars->serialNumber += 1;
    
    theContext.responseFlags = pm_vars->responseFlags;
    theContext.serialNumber = pm_vars->serialNumber;
    theContext.flags_lock = priv->flags_lock;
    theContext.counter = 1;
    theContext.msgType = messageType;
    theContext.us = this;
    theContext.maxTimeRequested = 0;
    theContext.stateNumber = priv->head_note_state;
    theContext.stateFlags = priv->head_note_capabilityFlags;

    IOLockLock(priv->flags_lock);
    aBool = OSBoolean::withBoolean(false);		// position zero is false to   
    theContext.responseFlags->setObject(0,aBool);	// prevent allowCancelCommon from succeeding
    aBool->release();
    IOLockUnlock(priv->flags_lock);

    switch ( pm_vars->outofbandparameter ) {
        case kNotifyApps:
            applyToInterested(gIOAppPowerStateInterest,tellAppWithResponse,(void *)&theContext);
            applyToInterested(gIOGeneralInterest,tellClientWithResponse,(void *)&theContext);
            break;
        case kNotifyPriority:
            applyToInterested(gIOPriorityPowerStateInterest,tellClientWithResponse,(void *)&theContext);
            break;
    }

    if (! acquire_lock() ) {
        return true;
    }
    IOLockLock(priv->flags_lock);
    aBool = OSBoolean::withBoolean(true);		// now fix position zero
    theContext.responseFlags->replaceObject(0,aBool);
    aBool->release();
    IOLockUnlock(priv->flags_lock);
    
    if ( ! checkForDone() ) { 				// we have to wait for somebody
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogStartAckTimer,theContext.maxTimeRequested,0);
        clock_interval_to_deadline(theContext.maxTimeRequested / 1000, kMillisecondScale, &deadline);
        
        thread_call_enter_delayed(priv->ackTimer, deadline);
    
        IOUnlock(priv->our_lock);			// yes
        return false;
    }
    
    IOUnlock(priv->our_lock);
    IOLockLock(priv->flags_lock);
    pm_vars->responseFlags->release();			// everybody responded    
    pm_vars->responseFlags = NULL;
    IOLockUnlock(priv->flags_lock);
    
    return true;
}


//*********************************************************************************
// tellAppWithResponse
//
// We send a message to an application, and we expect a response, so we compute a
// cookie we can identify the response with.
//*********************************************************************************
void tellAppWithResponse ( OSObject * object, void * context)
{
    struct context *    theContext = (struct context *)context;
    UInt32              refcon;
    OSBoolean *         aBool;
    
    if( OSDynamicCast( IOService, object) ) {
        IOLockLock(theContext->flags_lock);
        aBool = OSBoolean::withBoolean(true);
        theContext->responseFlags->setObject(theContext->counter,aBool);
        aBool->release();
        IOLockUnlock(theContext->flags_lock);
    }
    else {
        refcon = ((theContext->serialNumber & 0xFFFF)<<16) + (theContext->counter & 0xFFFF);
        IOLockLock(theContext->flags_lock);
        aBool = OSBoolean::withBoolean(false);
        theContext->responseFlags->setObject(theContext->counter,aBool);
        aBool->release();
        IOLockUnlock(theContext->flags_lock);
        theContext->us->messageClient(theContext->msgType,object,(void *)refcon);
        if ( theContext->maxTimeRequested < k30seconds ) {
            theContext->maxTimeRequested = k30seconds;
        }
    }
    theContext->counter += 1;
}


//*********************************************************************************
// tellClientWithResponse
//
// We send a message to an in-kernel client, and we expect a response, so we compute a
// cookie we can identify the response with.
// If it doesn't understand the notification (it is not power-management savvy)
// we won't wait for it to prepare for sleep.  If it tells us via a return code
// in the passed struct that it is currently ready, we won't wait for it to prepare.
// If it tells us via the return code in the struct that it does need time, we will chill.
//*********************************************************************************
void tellClientWithResponse ( OSObject * object, void * context)
{
    struct context *			theContext = (struct context *)context;
    IOPowerStateChangeNotification	notify;
    UInt32              		refcon;
    IOReturn    			retCode;
    OSBoolean * 			aBool;
    OSObject *				theFlag;
    
    refcon = ((theContext->serialNumber & 0xFFFF)<<16) + (theContext->counter & 0xFFFF);
    IOLockLock(theContext->flags_lock);
    aBool = OSBoolean::withBoolean(false);
    theContext->responseFlags->setObject(theContext->counter,aBool);
    aBool->release();
    IOLockUnlock(theContext->flags_lock);

    notify.powerRef = (void *)refcon;
    notify.returnValue = 0;
    notify.stateNumber = theContext->stateNumber;
    notify.stateFlags = theContext->stateFlags;
    retCode = theContext->us->messageClient(theContext->msgType,object,(void *)&notify);
    if ( retCode == kIOReturnSuccess ) {
        if ( notify.returnValue == 0 ) {						// client doesn't want time to respond
            IOLockLock(theContext->flags_lock);
            aBool = OSBoolean::withBoolean(true);
            theContext->responseFlags->replaceObject(theContext->counter,aBool);	// so set its flag true
            aBool->release();
            IOLockUnlock(theContext->flags_lock);
        }
        else {
            IOLockLock(theContext->flags_lock);
            theFlag = theContext->responseFlags->getObject(theContext->counter);	// it does want time, and it hasn't
            if ( theFlag != 0 ) {							// responded yet
                if ( ((OSBoolean *)theFlag)->isFalse() ) {				// so note its time requirement
                    if ( theContext->maxTimeRequested < notify.returnValue ) {
                        theContext->maxTimeRequested = notify.returnValue;
                    }
                }
            }
            IOLockUnlock(theContext->flags_lock);
        }
    }
    else {									// not a client of ours
        IOLockLock(theContext->flags_lock);
        aBool = OSBoolean::withBoolean(true);					// so we won't be waiting for response
        theContext->responseFlags->replaceObject(theContext->counter,aBool);
        aBool->release();
        IOLockUnlock(theContext->flags_lock);
    }
    theContext->counter += 1;
}


//*********************************************************************************
// tellNoChangeDown
//
// Notify registered applications and kernel clients that we are not
// dropping power.
//
// Subclass can override this to send a different message type.  Parameter is
// the aborted destination state number.
//*********************************************************************************

void IOService::tellNoChangeDown ( unsigned long )
{
    return tellClients(kIOMessageDeviceWillNotPowerOff);
}


//*********************************************************************************
// tellChangeUp
//
// Notify registered applications and kernel clients that we are raising power.
//
// Subclass can override this to send a different message type.  Parameter is
// the aborted destination state number.
//*********************************************************************************

void IOService::tellChangeUp ( unsigned long )
{
    return tellClients(kIOMessageDeviceHasPoweredOn);
}


//*********************************************************************************
// tellClients
//
// Notify registered applications and kernel clients of something.
//*********************************************************************************

void IOService::tellClients ( int messageType )
{
    struct context theContext;

    theContext.msgType = messageType;
    theContext.us = this;
    theContext.stateNumber = priv->head_note_state;
    theContext.stateFlags = priv->head_note_capabilityFlags;

    applyToInterested(gIOAppPowerStateInterest,tellClient,(void *)&theContext);
    applyToInterested(gIOGeneralInterest,tellClient,(void *)&theContext);
}


//*********************************************************************************
// tellClient
//
// Notify a registered application or kernel client of something.
//*********************************************************************************
void tellClient ( OSObject * object, void * context)
{
    struct context *			theContext = (struct context *)context;
    IOPowerStateChangeNotification	notify;

    notify.powerRef	= (void *) 0;
    notify.returnValue	= 0;
    notify.stateNumber	= theContext->stateNumber;
    notify.stateFlags	= theContext->stateFlags;

    theContext->us->messageClient(theContext->msgType,object, &notify);
}


// **********************************************************************************
// checkForDone
//
// **********************************************************************************
bool IOService::checkForDone ( void )
{
    int i = 0;
    OSObject * theFlag;

    IOLockLock(priv->flags_lock);
    if ( pm_vars->responseFlags == NULL ) {
        IOLockUnlock(priv->flags_lock);
        return true;
    }
    for ( i = 0; ; i++ ) {
        theFlag = pm_vars->responseFlags->getObject(i);
        if ( theFlag == NULL ) {
            break;
        }
        if ( ((OSBoolean *)theFlag)->isFalse() ) {
            IOLockUnlock(priv->flags_lock);
            return false;
        }
    }
    IOLockUnlock(priv->flags_lock);
    return true;
}


// **********************************************************************************
// responseValid
//
// **********************************************************************************
bool IOService::responseValid ( unsigned long x )
{
    UInt16 serialComponent;
    UInt16 ordinalComponent;
    OSObject * theFlag;
    unsigned long refcon = (unsigned long)x;
    OSBoolean * aBool;
    
    serialComponent = (refcon>>16) & 0xFFFF;
    ordinalComponent = refcon & 0xFFFF;
    
    if ( serialComponent != pm_vars->serialNumber ) {
        return false;
    }
    
    IOLockLock(priv->flags_lock);
    if ( pm_vars->responseFlags == NULL ) {
        IOLockUnlock(priv->flags_lock);
        return false;
    }
    
    theFlag = pm_vars->responseFlags->getObject(ordinalComponent);
    
    if ( theFlag == 0 ) {
        IOLockUnlock(priv->flags_lock);
        return false;
    }
    
    if ( ((OSBoolean *)theFlag)->isFalse() ) {
        aBool = OSBoolean::withBoolean(true);
        pm_vars->responseFlags->replaceObject(ordinalComponent,aBool);
        aBool->release();
    }
    
    IOLockUnlock(priv->flags_lock);
    return true;
}


// **********************************************************************************
// allowPowerChange
//
// Our power state is about to lower, and we have notified applications
// and kernel clients, and one of them has acknowledged.  If this is the last to do
// so, and all acknowledgements are positive, we continue with the power change.
//
// We serialize this processing with timer expiration with a command gate on the
// power management workloop, which the timer expiration is command gated to as well.
// **********************************************************************************
IOReturn IOService::allowPowerChange ( unsigned long refcon )
{
    if ( ! initialized ) {
        return kIOReturnSuccess;				// we're unloading
    }

    return pm_vars->PMcommandGate->runAction(serializedAllowPowerChange,(void *)refcon);
}
    
    
IOReturn serializedAllowPowerChange ( OSObject *owner, void * refcon, void *, void *, void *)
{
    return ((IOService *)owner)->serializedAllowPowerChange2((unsigned long)refcon);
}

IOReturn IOService::serializedAllowPowerChange2 ( unsigned long refcon )
{
    if ( ! responseValid(refcon) ) {							// response valid?
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAcknowledgeErr5,refcon,0);
        return kIOReturnSuccess;                                			// no, just return
    }
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientAcknowledge,refcon,0);

    return allowCancelCommon();
}


// **********************************************************************************
// cancelPowerChange
//
// Our power state is about to lower, and we have notified applications
// and kernel clients, and one of them has vetoed the change.  If this is the last
// client to respond, we abandon the power change.
//
// We serialize this processing with timer expiration with a command gate on the
// power management workloop, which the timer expiration is command gated to as well.
// **********************************************************************************
IOReturn IOService::cancelPowerChange ( unsigned long refcon )
{
    if ( ! initialized ) {
        return kIOReturnSuccess;				// we're unloading
    }

    return pm_vars->PMcommandGate->runAction(serializedCancelPowerChange,(void *)refcon);
}
    
    
IOReturn serializedCancelPowerChange ( OSObject *owner, void * refcon, void *, void *, void *)
{
    return ((IOService *)owner)->serializedCancelPowerChange2((unsigned long)refcon);
}

IOReturn IOService::serializedCancelPowerChange2 ( unsigned long refcon )
{
    if ( ! responseValid(refcon) ) {							// response valid?
        pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogAcknowledgeErr5,refcon,0);
        return kIOReturnSuccess;							// no, just return
    }
    pm_vars->thePlatform->PMLog(pm_vars->ourName,PMlogClientCancel,refcon,0);
    
    pm_vars->doNotPowerDown = true;

    return allowCancelCommon();
}


// **********************************************************************************
// allowCancelCommon
//
// **********************************************************************************
IOReturn IOService::allowCancelCommon ( void )
{
    if (! acquire_lock() ) {
        return kIOReturnSuccess;
    }

    if ( checkForDone() ) {                                     // is this the last response?
        stop_ack_timer();                                       // yes, stop the timer
        IOUnlock(priv->our_lock);
        IOLockLock(priv->flags_lock);
        if ( pm_vars->responseFlags ) {
            pm_vars->responseFlags->release();
            pm_vars->responseFlags = NULL;
        }
        IOLockUnlock(priv->flags_lock);
        switch (priv->machine_state) {
            case IOPMour_prechange_03:				// our change, was it vetoed?
                if ( ! pm_vars->doNotPowerDown ) {
                    our_prechange_03();                         // no, we can continue
                }
                else {
                    tellNoChangeDown(priv->head_note_state);	// yes, rescind the warning
                    priv->head_note_flags |= IOPMNotDone;	// mark the change note un-actioned
                    all_done();					// and we're done
                }
                break;
            case IOPMour_prechange_04:
                our_prechange_04();  
                break;
            case IOPMour_prechange_05:
                our_prechange_05();                             // our change, continue
                break;
            case IOPMparent_down_0:
                parent_down_04();                               // parent change, continue
                break;
            case IOPMparent_down_05:
                parent_down_05();                               // parent change, continue
                break;
        }
    }

    IOUnlock(priv->our_lock);					// not done yet
    return kIOReturnSuccess;
}


//*********************************************************************************
// clampPowerOn
//
// Set to highest available power state for a minimum of duration milliseconds
//*********************************************************************************

#define kFiveMinutesInNanoSeconds (300 * NSEC_PER_SEC)

void IOService::clampPowerOn (unsigned long duration)
{
  changePowerStateToPriv (pm_vars->theNumberOfPowerStates-1);

  if (  priv->clampTimerEventSrc == NULL ) {
    priv->clampTimerEventSrc = IOTimerEventSource::timerEventSource(this,
                                                    c_PM_Clamp_Timer_Expired);

    IOWorkLoop * workLoop = getPMworkloop ();

    if ( !priv->clampTimerEventSrc || !workLoop ||
       ( workLoop->addEventSource(  priv->clampTimerEventSrc) != kIOReturnSuccess) ) {

    }
  }

    priv->clampTimerEventSrc->setTimeout(kFiveMinutesInNanoSeconds, NSEC_PER_SEC);
}

//*********************************************************************************
// PM_Clamp_Timer_Expired
//
// called when clamp timer expires...set power state to 0.
//*********************************************************************************

void IOService::PM_Clamp_Timer_Expired (void)
{
    if ( ! initialized ) {
        return;					// we're unloading
    }

  changePowerStateToPriv (0);
}

//*********************************************************************************
// c_PM_clamp_Timer_Expired (C Func)
//
// Called when our clamp timer expires...we will call the object method.
//*********************************************************************************

void c_PM_Clamp_Timer_Expired (OSObject * client, IOTimerEventSource *)
{
  if (client)
    ((IOService *)client)->PM_Clamp_Timer_Expired ();
}


//*********************************************************************************
// setPowerState
//
// Does nothing here.  This should be implemented in a subclass driver.
//*********************************************************************************

IOReturn IOService::setPowerState ( unsigned long powerStateOrdinal, IOService* whatDevice )
{
    return IOPMNoErr;
}


//*********************************************************************************
// maxCapabilityForDomainState
//
// Finds the highest power state in the array whose input power
// requirement is equal to the input parameter.  Where a more intelligent
// decision is possible, override this in the subclassed driver.
//*********************************************************************************

unsigned long IOService::maxCapabilityForDomainState ( IOPMPowerFlags domainState )
{
   int i;

   if (pm_vars->theNumberOfPowerStates == 0 ) {
       return 0;
   }
   for ( i = (pm_vars->theNumberOfPowerStates)-1; i >= 0; i-- ) {
       if (  (domainState & pm_vars->thePowerStates[i].inputPowerRequirement) == pm_vars->thePowerStates[i].inputPowerRequirement ) {
           return i;
       }
   }
   return 0;
}


//*********************************************************************************
// initialPowerStateForDomainState
//
// Finds the highest power state in the array whose input power
// requirement is equal to the input parameter.  Where a more intelligent
// decision is possible, override this in the subclassed driver.
//*********************************************************************************

unsigned long IOService::initialPowerStateForDomainState ( IOPMPowerFlags domainState )
{
  int i;

   if (pm_vars->theNumberOfPowerStates == 0 ) {
      return 0;
  }
   for ( i = (pm_vars->theNumberOfPowerStates)-1; i >= 0; i-- ) {
       if (  (domainState & pm_vars->thePowerStates[i].inputPowerRequirement) == pm_vars->thePowerStates[i].inputPowerRequirement ) {
          return i;
      }
  }
  return 0;
}


//*********************************************************************************
// powerStateForDomainState
//
// Finds the highest power state in the array whose input power
// requirement is equal to the input parameter.  Where a more intelligent
// decision is possible, override this in the subclassed driver.
//*********************************************************************************

unsigned long IOService::powerStateForDomainState ( IOPMPowerFlags domainState )
{
  int i;

   if (pm_vars->theNumberOfPowerStates == 0 ) {
      return 0;
  }
   for ( i = (pm_vars->theNumberOfPowerStates)-1; i >= 0; i-- ) {
       if (  (domainState & pm_vars->thePowerStates[i].inputPowerRequirement) == pm_vars->thePowerStates[i].inputPowerRequirement ) {
          return i;
      }
  }
  return 0;
}


//*********************************************************************************
// didYouWakeSystem
//
// Does nothing here.  This should be implemented in a subclass driver.
//*********************************************************************************

bool IOService::didYouWakeSystem  ( void )
{
    return false;
}


//*********************************************************************************
// powerStateWillChangeTo
//
// Does nothing here.  This should be implemented in a subclass driver.
//*********************************************************************************

IOReturn IOService::powerStateWillChangeTo ( IOPMPowerFlags, unsigned long, IOService*)
{
    return 0;
}


//*********************************************************************************
// powerStateDidChangeTo
//
// Does nothing here.  This should be implemented in a subclass driver.
//*********************************************************************************

IOReturn IOService::powerStateDidChangeTo ( IOPMPowerFlags, unsigned long, IOService*)
{
    return 0;
}


//*********************************************************************************
// powerChangeDone
//
// Does nothing here.  This should be implemented in a subclass policy-maker.
//*********************************************************************************

void IOService::powerChangeDone ( unsigned long )
{
}


//*********************************************************************************
// newTemperature
//
// Does nothing here.  This should be implemented in a subclass driver.
//*********************************************************************************

IOReturn IOService::newTemperature ( long currentTemp, IOService * whichZone )

{
    return IOPMNoErr;
}


#undef super
#define super OSObject

OSDefineMetaClassAndStructors(IOPMprot, OSObject)
//*********************************************************************************
// serialize
//
// Serialize protected instance variables for debug output.
//*********************************************************************************
bool IOPMprot::serialize(OSSerialize *s) const
{
    OSString * theOSString;
    char * buffer;
    char * ptr;
    int i;
    bool	rtn_code;

    buffer = ptr = IONew(char, 2000);
    if(!buffer)
        return false;

    ptr += sprintf(ptr,"{ theNumberOfPowerStates = %d, ",(unsigned int)theNumberOfPowerStates);

    if ( theNumberOfPowerStates != 0 ) {
        ptr += sprintf(ptr,"version %d, ",(unsigned int)thePowerStates[0].version);
    }

    if ( theNumberOfPowerStates != 0 ) {
        for ( i = 0; i < (int)theNumberOfPowerStates; i++ ) {
            ptr += sprintf(ptr,"power state %d = { ",i);
            ptr += sprintf(ptr,"capabilityFlags %08x, ",(unsigned int)thePowerStates[i].capabilityFlags);
            ptr += sprintf(ptr,"outputPowerCharacter %08x, ",(unsigned int)thePowerStates[i].outputPowerCharacter);
            ptr += sprintf(ptr,"inputPowerRequirement %08x, ",(unsigned int)thePowerStates[i].inputPowerRequirement);
            ptr += sprintf(ptr,"staticPower %d, ",(unsigned int)thePowerStates[i].staticPower);
            ptr += sprintf(ptr,"unbudgetedPower %d, ",(unsigned int)thePowerStates[i].unbudgetedPower);
            ptr += sprintf(ptr,"powerToAttain %d, ",(unsigned int)thePowerStates[i].powerToAttain);
            ptr += sprintf(ptr,"timeToAttain %d, ",(unsigned int)thePowerStates[i].timeToAttain);
            ptr += sprintf(ptr,"settleUpTime %d, ",(unsigned int)thePowerStates[i].settleUpTime);
            ptr += sprintf(ptr,"timeToLower %d, ",(unsigned int)thePowerStates[i].timeToLower);
            ptr += sprintf(ptr,"settleDownTime %d, ",(unsigned int)thePowerStates[i].settleDownTime);
            ptr += sprintf(ptr,"powerDomainBudget %d }, ",(unsigned int)thePowerStates[i].powerDomainBudget);
        }
    }

    ptr += sprintf(ptr,"aggressiveness = %d, ",(unsigned int)aggressiveness);
    ptr += sprintf(ptr,"myCurrentState = %d, ",(unsigned int)myCurrentState);
    ptr += sprintf(ptr,"parentsCurrentPowerFlags = %08x, ",(unsigned int)parentsCurrentPowerFlags);
    ptr += sprintf(ptr,"maxCapability = %d }",(unsigned int)maxCapability);

    theOSString = OSString::withCString(buffer);
    rtn_code = theOSString->serialize(s);
    theOSString->release();
    IODelete(buffer, char, 2000);

    return rtn_code;
}


#undef super
#define super OSObject

OSDefineMetaClassAndStructors(IOPMpriv, OSObject)
//*********************************************************************************
// serialize
//
// Serialize private instance variables for debug output.
//*********************************************************************************
bool IOPMpriv::serialize(OSSerialize *s) const
{
    OSString *			theOSString;
    bool			rtn_code;
    char * 			buffer;
    char * 			ptr;
    IOPMinformee * 		nextObject;

    buffer = ptr = IONew(char, 2000);
    if(!buffer)
        return false;

    ptr += sprintf(ptr,"{ this object = %08x",(unsigned int)owner);
    if ( we_are_root ) {
        ptr += sprintf(ptr," (root)");
    }
    ptr += sprintf(ptr,", ");

    nextObject = interestedDrivers->firstInList();			// display interested drivers
    while (  nextObject != NULL ) {
        ptr += sprintf(ptr,"interested driver = %08x, ",(unsigned int)nextObject->whatObject);
        nextObject  =  interestedDrivers->nextInList(nextObject);
    }

    if ( machine_state != IOPMfinished ) {
        ptr += sprintf(ptr,"machine_state = %d, ",(unsigned int)machine_state);
        ptr += sprintf(ptr,"driver_timer = %d, ",(unsigned int)driver_timer);
        ptr += sprintf(ptr,"settle_time = %d, ",(unsigned int)settle_time);
        ptr += sprintf(ptr,"head_note_flags = %08x, ",(unsigned int)head_note_flags);
        ptr += sprintf(ptr,"head_note_state = %d, ",(unsigned int)head_note_state);
        ptr += sprintf(ptr,"head_note_outputFlags = %08x, ",(unsigned int)head_note_outputFlags);
        ptr += sprintf(ptr,"head_note_domainState = %08x, ",(unsigned int)head_note_domainState);
        ptr += sprintf(ptr,"head_note_capabilityFlags = %08x, ",(unsigned int)head_note_capabilityFlags);
        ptr += sprintf(ptr,"head_note_pendingAcks = %d, ",(unsigned int)head_note_pendingAcks);
    }

    if ( device_overrides ) {
        ptr += sprintf(ptr,"device overrides, ");
    }
    ptr += sprintf(ptr,"driverDesire = %d, ",(unsigned int)driverDesire);
    ptr += sprintf(ptr,"deviceDesire = %d, ",(unsigned int)deviceDesire);
    ptr += sprintf(ptr,"ourDesiredPowerState = %d, ",(unsigned int)ourDesiredPowerState);
    ptr += sprintf(ptr,"previousRequest = %d }",(unsigned int)previousRequest);

    theOSString =  OSString::withCString(buffer);
    rtn_code = theOSString->serialize(s);
    theOSString->release();
    IODelete(buffer, char, 2000);

    return rtn_code;
}