summaryrefslogtreecommitdiff
path: root/usr/src/cmd/picl/plugins/sun4u/excalibur/envd/piclenvd.c
blob: 976a45887b4903ee6403996f1d8352a88aa3d281 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * This file contains the environmental PICL plug-in module.
 */


/*
 * Excalibur system contains up to two CPU and two PCI MAX1617 temperature
 * devices, each consisting of two sensors: die and ambient. Each sensor is
 * represented as a different minor device and the current temperature is read
 * via an I2C_GET_TEMPERATURE ioctl call to the max1617 driver. Additionally,
 * the MAX1617 device supports both a low and high temperature limit, which
 * can trigger an alert condition, causing power supply to turn off.
 *
 * The environmental monitor defines the following thresholds per sensor:
 *
 *	high_power_off		high hard shutdown
 *	high_shutdown		high soft shutdown limit
 *	high_warning		high warning limit
 *	low_warning		low warning limit
 *	low_shutdown		low soft shutdown limit
 *	low_power_off		low hard shutdown limit
 *
 * Above mentioned threshold values can be changed via "piclenvd.conf"
 * configuration file.
 *
 * Environmental monitoring is done by the "envthr" thread. It periodically
 * monitors both CPU die and CPU ambient temperatures and takes appropriate
 * action depending upon the current temperature and threshold values for
 * that sensor. If the temperature reaches the high_shutdown limit or the
 * low_shutdown limit, and remains there for over shutdown_interval seconds,
 * it forces a graceful system shutdown via tuneable shutdown_cmd string
 * variable. Otherwise, if the temperature reaches the high_warning limit
 * or the low_warning limit, it logs and prints a message on the console.
 * This message will be printed at most at "warning_interval" seconds
 * interval, which is also a tuneable variable.
 *
 * Excalibur system contains three fans: cpu, system and power supply. The
 * cpu and system fans are under software control and their speed can be
 * set to a value in the range 0 through 63. However, the software has no
 * control over the power supply fan's speed (it's automatically controlled
 * by the hardware), but it can turn it ON or OFF. When in EStar mode (i.e.
 * the lowest power state), the environmental monitor turns off the power
 * supply fan.
 *
 * Each fan is represented as a different minor device and the fan speed
 * can be controlled by writing to the TDA8444 device driver. Note that
 * these devices are read only and the driver caches the last speed set
 * for each fan, thus allowing an interface to read the current fan speed
 * also.
 *
 * The policy to control fan speed depends upon the sensor. For CPU die
 * sensor, different policy is used depending upon whether the temperature
 * is rising, falling or steady state. In case of CPU ambient sensor, only
 * one policy (speed proportional to the current temperature) is used.
 *
 * The power state monitoring is done by the "pmthr" thread. It uses the
 * PM_GET_STATE_CHANGE and PM_GET_STATE_CHANGE_WAIT ioctl commands to pick
 * up any power state change events. It processes all queued power state
 * change events and determines the curret lowest power state and saves it
 * in cur_lpstate variable.
 *
 * Once the "envthr" and "pmthr" threads have been started, they are never
 * killed. This is desirable so that we can do environmental monitoring
 * during reinit process.  The "envd_rwlock" reader/writer lock is used
 * to protect initialization of global state during reinit process against
 * the "envthr" and "pmthr" trying to reference that state.
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/sysmacros.h>
#include <limits.h>
#include <string.h>
#include <stdarg.h>
#include <alloca.h>
#include <unistd.h>
#include <sys/processor.h>
#include <syslog.h>
#include <errno.h>
#include <fcntl.h>
#include <picl.h>
#include <picltree.h>
#include <picldefs.h>
#include <pthread.h>
#include <signal.h>
#include <libdevinfo.h>
#include <sys/pm.h>
#include <sys/open.h>
#include <sys/time.h>
#include <sys/utsname.h>
#include <sys/systeminfo.h>
#include <sys/i2c/clients/max1617.h>
#include <sys/i2c/clients/i2c_client.h>
#include <sys/xcalwd.h>
#include "envd.h"

static pthread_rwlock_t	envd_rwlock = PTHREAD_RWLOCK_INITIALIZER;

/*
 * PICL plguin
 */
static void piclenvd_register(void);
static void piclenvd_init(void);
static void piclenvd_fini(void);
extern void env_picl_setup(void);
extern void env_picl_destroy(void);

#pragma	init(piclenvd_register)

static picld_plugin_reg_t my_reg_info = {
	PICLD_PLUGIN_VERSION_1,
	PICLD_PLUGIN_CRITICAL,
	"SUNW_piclenvd",
	piclenvd_init,
	piclenvd_fini,
};


/*
 * Default threshold values for CPU junction/die and ambient sensors
 */
static sensor_thresh_t cpu_die_thresh_default = {
	CPU_DIE_LOW_POWER_OFF, CPU_DIE_HIGH_POWER_OFF,
	CPU_DIE_LOW_SHUTDOWN, CPU_DIE_HIGH_SHUTDOWN,
	CPU_DIE_LOW_WARNING, CPU_DIE_HIGH_WARNING,
	MAX1617_MIN_TEMP, MAX1617_MAX_TEMP,
	POLICY_TARGET_TEMP, 2,
	CPU_DIE_NORMAL_TARGET, CPU_DIE_OTHER_TARGET,
	0, 0, 0, 0
};

static sensor_thresh_t cpu_amb_thresh_default = {
	CPU_AMB_LOW_POWER_OFF, CPU_AMB_HIGH_POWER_OFF,
	CPU_AMB_LOW_SHUTDOWN, CPU_AMB_HIGH_SHUTDOWN,
	CPU_AMB_LOW_WARNING, CPU_AMB_HIGH_WARNING,
	MAX1617_MIN_TEMP, MAX1617_MAX_TEMP,
	POLICY_LINEAR, 2,
	CPU_AMB_LOW_NOMINAL, CPU_AMB_HIGH_NOMINAL,
	0, 0, 0, 0
};


/*
 * Dummy sensor threshold data structure for processing threshold tuneables
 */
static sensor_thresh_t	dummy_thresh;

/*
 * Temperature related constants for fan speed adjustment
 */
#define	AVG_TEMP_HYSTERESIS	0.25
#define	RISING_TEMP_MARGIN	6
#define	FALLING_TEMP_MARGIN	3

/*
 * tuneable variables
 */
#define	FAN_SLOW_ADJUSTMENT	20		/* in percentage */
#define	FAN_INCREMENT_LIMIT	6		/* absolute value */
#define	FAN_DECREMENT_LIMIT	1		/* absolute value */
#define	DEVFSADM_CMD 		"/usr/sbin/devfsadm -i max1617"
#define	FRU_DEVFSADM_CMD 	"/usr/sbin/devfsadm -i seeprom"

int		env_debug;
static int	sensor_poll_interval;
static int	warning_interval;
static int	warning_duration;
static int	shutdown_interval;
static int	fan_slow_adjustment;
static int	fan_incr_limit;
static int	fan_decr_limit;
static int	disable_piclenvd;
static int	disable_warning;
static int	disable_power_off;
static int	disable_shutdown;

static char	shutdown_cmd[128];
static char	devfsadm_cmd[128];
static char	fru_devfsadm_cmd[128];
static sensor_thresh_t cpu0_die_thresh, cpu0_amb_thresh;
static sensor_thresh_t cpu1_die_thresh, cpu1_amb_thresh;

/*
 * Temperature sensors
 */

static env_sensor_t envd_sensors[] = {
	{ SENSOR_CPU0_DIE, CPU0_DIE_SENSOR_DEVFS, &cpu0_die_thresh,
	    CPU0_FRU_DEVFS, CPU_FRU_DIE_SENSOR,
	    SFLAG_TARGET_TEMP | SFLAG_CPU_DIE_SENSOR, -1},
	{ SENSOR_CPU0_AMB, CPU0_AMB_SENSOR_DEVFS, &cpu0_amb_thresh,
	    CPU0_FRU_DEVFS, CPU_FRU_AMB_SENSOR, SFLAG_CPU_AMB_SENSOR, -1},
	{ SENSOR_CPU1_DIE, CPU1_DIE_SENSOR_DEVFS, &cpu1_die_thresh,
	    CPU1_FRU_DEVFS, CPU_FRU_DIE_SENSOR,
	    SFLAG_TARGET_TEMP | SFLAG_CPU_DIE_SENSOR, -1},
	{ SENSOR_CPU1_AMB, CPU1_AMB_SENSOR_DEVFS, &cpu1_amb_thresh,
	    CPU1_FRU_DEVFS, CPU_FRU_AMB_SENSOR, SFLAG_CPU_AMB_SENSOR, -1},
	{ NULL, NULL, NULL, NULL, 0, 0, -1}
};


/*
 * Fan devices
 */
static env_fan_t envd_system_fan = {
	ENV_SYSTEM_FAN, ENV_SYSTEM_FAN_DEVFS,
	SYSTEM_FAN_SPEED_MIN, SYSTEM_FAN_SPEED_MAX, -1, -1,
};

static env_fan_t envd_cpu_fan = {
	ENV_CPU_FAN, ENV_CPU_FAN_DEVFS,
	CPU_FAN_SPEED_MIN, CPU_FAN_SPEED_MAX, -1, -1,
};

static env_fan_t envd_psupply_fan = {
	ENV_PSUPPLY_FAN, ENV_PSUPPLY_FAN_DEVFS,
	PSUPPLY_FAN_SPEED_MIN, PSUPPLY_FAN_SPEED_MAX, -1, -1,
};

static env_fan_t *envd_fans[] = {
	&envd_system_fan,
	&envd_cpu_fan,
	&envd_psupply_fan,
	NULL
};

/*
 * Linked list of devices advertising lpm-ranges
 */
static lpm_dev_t	*lpm_devices = NULL;

/*
 * Excalibur lpm to system-fan speed
 * lpm values must be monotonically increasing (avoid divide-by-zero)
 */
static point_t	excal_lpm_system_fan_tbl[] = {
	/* {lpm, fspeed} */
	{18, 12},
	{25, 20},
	{33, 26},
	{44, 32},
	{51, 39},
	{63, 52},
	{64, 63}
};

static table_t	lpm_fspeed = {
	sizeof (excal_lpm_system_fan_tbl)/ sizeof (point_t),
	excal_lpm_system_fan_tbl
};

/*
 * Sensor to fan map
 */
typedef struct {
	char	*sensor_name;
	char	*fan_name;
} sensor_fan_map_t;

static sensor_fan_map_t sensor_fan_map[] = {
	{SENSOR_CPU0_DIE, ENV_CPU_FAN},
	{SENSOR_CPU1_DIE, ENV_CPU_FAN},
	{SENSOR_CPU0_AMB, ENV_SYSTEM_FAN},
	{SENSOR_CPU1_AMB, ENV_SYSTEM_FAN},
	{NULL, NULL}
};

/*
 * Sensor to PM device map
 */
struct sensor_pmdev {
	int		sensor_id;
	char		*sensor_name;
	char		*pmdev_name;
	char		*speed_comp_name;
	int		speed_comp;
	int		full_power;
	int		cur_power;
	env_sensor_t	*sensorp;
	sensor_pmdev_t	*next;
};

#define	SPEED_COMPONENT_NAME	"CPU Speed"

static sensor_pmdev_t sensor_pmdevs[] = {
	{SENSOR_CPU0_ID, SENSOR_CPU0_DIE, NULL, SPEED_COMPONENT_NAME},
	{SENSOR_CPU1_ID, SENSOR_CPU1_DIE, NULL, SPEED_COMPONENT_NAME},
	{-1, NULL, NULL, NULL}
};

/*
 * Environmental thread variables
 */
static boolean_t	system_shutdown_started = B_FALSE;
static boolean_t	envthr_created = B_FALSE;	/* envthr created */
static pthread_t	envthr_tid;		/* envthr thread ID */
static pthread_attr_t	thr_attr;

/*
 * Power management thread (pmthr) variables
 */
static boolean_t	pmdev_names_init = B_FALSE;
static pthread_t	pmthr_tid;		/* pmthr thread ID */
static int		pmthr_exists = B_FALSE;	/* pmthr exists */
static int		pm_fd = -1;		/* PM device file descriptor */
static int		cur_lpstate;		/* cur low power state */

/*
 * Miscellaneous variables and declarations
 */
static int	fru_devfsadm_invoked = 0;
static int	devfsadm_invoked = 0;
static char	tokdel[] = " \t\n\r";
static uint_t	envd_sleep(uint_t);

/*
 * Tuneable data structure/array and processing functions
 */

typedef struct {
	char		*name;		/* keyword */
	int		(*func)(char *, char *, void *, int, char *, int);
					/* tuneable processing function */
	void		*arg1;		/* tuneable arg1 (memory address) */
	int		arg2;		/* tuneable arg2 (size or flags) */
} env_tuneable_t;

static int process_int_tuneable(char *keyword, char *buf, void *addr,
    int size, char *fname, int line);
static int process_string_tuneable(char *keyword, char *buf, void *addr,
    int size, char *fname, int line);
static int process_threshold_tuneable(char *keyword, char *buf, void *addr,
    int flags, char *fname, int line);
static void process_env_conf_file(void);

static env_tuneable_t env_tuneables[] = {
	{"low_power_off", process_threshold_tuneable,
	    &dummy_thresh.low_power_off, 0},
	{"low_shutdown", process_threshold_tuneable,
	    &dummy_thresh.low_shutdown, 0},
	{"low_warning", process_threshold_tuneable,
	    &dummy_thresh.low_warning, 0},
	{"high_power_off", process_threshold_tuneable,
	    &dummy_thresh.high_power_off, 0},
	{"high_shutdown", process_threshold_tuneable,
	    &dummy_thresh.high_shutdown, 0},
	{"high_warning", process_threshold_tuneable,
	    &dummy_thresh.high_warning, 0},
	{"force_cpu_fan", process_int_tuneable, &envd_cpu_fan.forced_speed,
	    sizeof (envd_cpu_fan.forced_speed)},
	{"force_system_fan", process_int_tuneable,
	    &envd_system_fan.forced_speed,
	    sizeof (envd_system_fan.forced_speed)},

	{"cpu_amb_low_power_off", process_threshold_tuneable,
	    &dummy_thresh.low_power_off, SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_low_shutdown", process_threshold_tuneable,
	    &dummy_thresh.low_shutdown, SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_low_warning", process_threshold_tuneable,
	    &dummy_thresh.low_warning, SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_low_nominal", process_threshold_tuneable,
	    &dummy_thresh.policy_data[LOW_NOMINAL_LOC], SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_high_power_off", process_threshold_tuneable,
	    &dummy_thresh.high_power_off, SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_high_shutdown", process_threshold_tuneable,
	    &dummy_thresh.high_shutdown, SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_high_warning", process_threshold_tuneable,
	    &dummy_thresh.high_warning, SFLAG_CPU_AMB_SENSOR},
	{"cpu_amb_high_nominal", process_threshold_tuneable,
	    &dummy_thresh.policy_data[HIGH_NOMINAL_LOC], SFLAG_CPU_AMB_SENSOR},

	{"cpu_die_low_power_off", process_threshold_tuneable,
	    &dummy_thresh.low_power_off, SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_low_shutdown", process_threshold_tuneable,
	    &dummy_thresh.low_shutdown, SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_low_warning", process_threshold_tuneable,
	    &dummy_thresh.low_warning, SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_normal_target", process_threshold_tuneable,
	    &dummy_thresh.policy_data[0], SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_high_power_off", process_threshold_tuneable,
	    &dummy_thresh.high_power_off, SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_high_shutdown", process_threshold_tuneable,
	    &dummy_thresh.high_shutdown, SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_high_warning", process_threshold_tuneable,
	    &dummy_thresh.high_warning, SFLAG_CPU_DIE_SENSOR},
	{"cpu_die_other_target", process_threshold_tuneable,
	    &dummy_thresh.policy_data[1], SFLAG_CPU_DIE_SENSOR},

	{"sensor_poll_interval", process_int_tuneable, &sensor_poll_interval,
	    sizeof (sensor_poll_interval)},
	{"warning_interval", process_int_tuneable, &warning_interval,
	    sizeof (warning_interval)},
	{"warning_duration", process_int_tuneable, &warning_duration,
	    sizeof (warning_duration)},
	{"disable_piclenvd", process_int_tuneable, &disable_piclenvd,
	    sizeof (disable_piclenvd)},
	{"disable_power_off", process_int_tuneable, &disable_power_off,
	    sizeof (disable_power_off)},
	{"disable_warning", process_int_tuneable, &disable_warning,
	    sizeof (disable_warning)},
	{"disable_shutdown", process_int_tuneable, &disable_shutdown,
	    sizeof (disable_shutdown)},
	{"shutdown_interval", process_int_tuneable, &shutdown_interval,
	    sizeof (shutdown_interval)},
	{"shutdown_cmd", process_string_tuneable, &shutdown_cmd[0],
	    sizeof (shutdown_cmd)},
	{"devfsadm_cmd", process_string_tuneable, &devfsadm_cmd[0],
	    sizeof (devfsadm_cmd)},
	{"fru_devfsadm_cmd", process_string_tuneable, &fru_devfsadm_cmd[0],
	    sizeof (fru_devfsadm_cmd)},
	{"fan_slow_adjustment", process_int_tuneable, &fan_slow_adjustment,
	    sizeof (fan_slow_adjustment)},
	{"fan_incr_limit", process_int_tuneable, &fan_incr_limit,
	    sizeof (fan_incr_limit)},
	{"fan_decr_limit", process_int_tuneable, &fan_decr_limit,
	    sizeof (fan_decr_limit)},
	{"env_debug", process_int_tuneable, &env_debug, sizeof (env_debug)},
	{ NULL, NULL, NULL, 0}
};

static void
fini_table(table_t *tblp)
{
	if (tblp == NULL)
		return;
	free(tblp->xymap);
	free(tblp);
}

static table_t *
init_table(int npoints)
{
	table_t		*tblp;
	point_t		*xy;

	if (npoints == 0)
		return (NULL);

	if ((tblp = malloc(sizeof (*tblp))) == NULL)
		return (NULL);

	if ((xy = malloc(sizeof (*xy) * npoints)) == NULL) {
		free(tblp);
		return (NULL);
	}

	tblp->nentries = npoints;
	tblp->xymap = xy;

	return (tblp);
}

/*
 * Temp-LPM Table format:
 * temp, lpm, temp, lpm, ...
 */
static table_t *
parse_lpm_ranges(uint32_t *bufp, size_t nbytes)
{
	int	nentries;
	table_t	*tblp = NULL;
	int	i;

	if (bufp == NULL)
		return (NULL);

	/*
	 * Table should have at least 2 points
	 * and all points should have x and y values
	 */
	if ((nbytes < (2 * sizeof (point_t))) ||
	    (nbytes & (sizeof (point_t) - 1))) {
		if (env_debug)
			envd_log(LOG_ERR, ENV_INVALID_PROPERTY_FORMAT,
			    LPM_RANGES_PROPERTY);
		return (NULL);
	}

	/* number of entries in the temp-lpm table */
	nentries = nbytes/sizeof (point_t);

	tblp = init_table(nentries);
	if (tblp == NULL)
		return (tblp);

	/* copy the tuples */
	tblp->xymap[0].x = (int)*bufp++;
	tblp->xymap[0].y = (int)*bufp++;
	for (i = 1; i < nentries; ++i) {
		tblp->xymap[i].x = (int)*bufp++;
		tblp->xymap[i].y = (int)*bufp++;
		if (tblp->xymap[i].x <= tblp->xymap[i - 1].x) {
			fini_table(tblp);
			if (env_debug)
				envd_log(LOG_ERR, ENV_INVALID_PROPERTY_FORMAT,
				    LPM_RANGES_PROPERTY);
			return (NULL);
		}
	}

	return (tblp);
}

/*
 * function: calculates y for a given x based on a table of points
 * for monotonically increasing x values.
 * 'tbl' specifies the table to use, 'val' specifies the 'x', returns 'y'
 */
static int
y_of_x(table_t *tbl, int xval)
{
	int		i;
	int		entries;
	point_t		*xymap;
	float		newval;
	float		dy, dx, slope;

	entries = tbl->nentries;
	xymap = tbl->xymap;
	if (xval <= xymap[0].x)
		return (xymap[0].y);
	else if (xval >= xymap[entries - 1].x)
		return (xymap[entries - 1].y);

	for (i = 1; i < entries - 1; i++) {
		if (xval == xymap[i].x)
			return (xymap[i].y);
		if (xval < xymap[i].x)
			break;
	}

	/*
	 * Use linear interpolation
	 */
	dy = (float)(xymap[i].y - xymap[i-1].y);
	dx = (float)(xymap[i].x - xymap[i-1].x);
	slope = dy/dx;
	newval = xymap[i - 1].y + slope * (xval - xymap[i - 1].x);
	return ((int)(newval + (newval >= 0 ? 0.5 : -0.5)));
}

static int
get_lpm_speed(lpm_dev_t *lpmdevs, int temp)
{
	lpm_dev_t	*devp;
	int		lpm;
	int		speed;
	int		maxspeed;

	if (lpmdevs == NULL)
		return (0);
	maxspeed = 0;
	for (devp = lpmdevs; devp != NULL; devp = devp->next) {
		if (devp->temp_lpm_tbl == NULL)
			continue;
		lpm = y_of_x(devp->temp_lpm_tbl, temp);
		if (env_debug)
			envd_log(LOG_INFO, "ambient %d lpm %d\n", temp, lpm);
		speed = y_of_x(&lpm_fspeed, lpm);
		maxspeed = maxspeed > speed ? maxspeed : speed;
		if (env_debug)
			envd_log(LOG_INFO, "lpm %d fanspeed %d\n", lpm, speed);
	}
	return (maxspeed);
}

/*
 * Callback function used by ptree_walk_tree_by_class
 */
static int
cb_lpm(picl_nodehdl_t nodeh, void *args)
{
	lpm_dev_t	**retp = (lpm_dev_t **)args;
	int		err;
	ptree_propinfo_t	pinfo;
	picl_prophdl_t		proph;
	size_t			psize;
	void			*bufp;
	table_t			*temp_lpm_tbl;
	lpm_dev_t		*newdev;

	err = ptree_get_prop_by_name(nodeh, LPM_RANGES_PROPERTY, &proph);
	if (err != PICL_SUCCESS)
		return (PICL_WALK_CONTINUE);

	err = ptree_get_propinfo(proph, &pinfo);
	if ((err != PICL_SUCCESS) ||
	    (pinfo.piclinfo.type != PICL_PTYPE_BYTEARRAY))
		return (PICL_WALK_CONTINUE);
	psize = pinfo.piclinfo.size;
	bufp = alloca(psize);

	err = ptree_get_propval(proph, bufp, psize);
	if (err != PICL_SUCCESS)
		return (PICL_WALK_CONTINUE);

	temp_lpm_tbl = parse_lpm_ranges(bufp, psize);
	if (temp_lpm_tbl == NULL) {
		return (PICL_WALK_CONTINUE);
	}

	newdev = malloc(sizeof (*newdev));
	if (newdev == NULL) {
		fini_table(temp_lpm_tbl);
		return (PICL_WALK_TERMINATE);
	}

	memset(newdev, 0, sizeof (*newdev));

	newdev->nodeh = nodeh;
	newdev->temp_lpm_tbl = temp_lpm_tbl;

	/* add newdev to the list */
	newdev->next = *retp;
	*retp = newdev;

	return (PICL_WALK_CONTINUE);
}

/*
 * Find all devices advertising "lpm-ranges" property, parse and store
 * the lpm tables for each device
 */
static int
setup_lpm_devices(lpm_dev_t **devpp)
{
	picl_nodehdl_t	plath;
	int		err;
	lpm_dev_t	*lpmp;

	err = ptree_get_node_by_path("/platform", &plath);
	if (err != PICL_SUCCESS)
		return (err);

	lpmp = NULL;
	err = ptree_walk_tree_by_class(plath, NULL, (void *)&lpmp, cb_lpm);
	if (err == PICL_SUCCESS)
		*devpp = lpmp;
	return (err);
}

/*
 * Remove all lpm_devices and their tables.
 */
static void
delete_lpm_devices(void)
{
	lpm_dev_t	*devp, *next;

	(void) pthread_rwlock_wrlock(&envd_rwlock);

	if (lpm_devices == NULL) {
		(void) pthread_rwlock_unlock(&envd_rwlock);
		return;
	}

	devp = lpm_devices;

	while (devp != NULL) {
		fini_table(devp->temp_lpm_tbl);
		next = devp->next;
		free(devp);
		devp = next;
	}

	lpm_devices = NULL;

	(void) pthread_rwlock_unlock(&envd_rwlock);
}

/*
 * Translate observed (measured) temperature into expected (correct)
 * temperature
 */
static int
xlate_obs2exp(env_sensor_t *sensorp, tempr_t temp)
{
	int		i, entries, new_temp, denominator;
	tempr_map_t	*map;
	float		ftemp;

	entries = sensorp->obs2exp_cnt;
	map = sensorp->obs2exp_map;
	if (entries < 2 || map == NULL)  {
		/* no map or can't map it */
		new_temp = temp;
	} else {
		/*
		 * Any point beyond the range specified by the map is
		 * extrapolated using either the first two or the last
		 * two entries in the map.
		 */
		for (i = 1; i < entries-1; i++)
			if (temp < map[i].observed)
				break;
		/*
		 * Interpolate/extrapolate the temperature using linear
		 * equation with map[i-1] and map[i] being the two ends
		 * of the line segment.
		 */
		denominator = map[i].observed - map[i-1].observed;
		if (denominator == 0) {
			/*
			 * Infinite slope. Since the temperature reading
			 * resolution is 1C, force denominator to 1 to
			 * avoid divide by zero.
			 */
			denominator = 1;
		}
		ftemp = map[i-1].expected +  (temp - map[i-1].observed) *
		    (float)(map[i].expected - map[i-1].expected)/denominator;
		new_temp = (int)(ftemp + (ftemp >= 0 ? 0.5 : -0.5));
	}

	return (new_temp);
}


/*
 * Translate expected (correct) temperature into observed (measured)
 * temperature
 */
static int
xlate_exp2obs(env_sensor_t *sensorp, tempr_t temp)
{
	int		i, entries, new_temp, denominator;
	tempr_map_t	*map;
	float		ftemp;
	sensor_thresh_t	*threshp = sensorp->temp_thresh;

	entries = sensorp->obs2exp_cnt;
	map = sensorp->obs2exp_map;
	if (entries < 2 || map == NULL)
		/* no map or can't map it */
		new_temp = temp;
	else {
		/*
		 * Any point beyond the range specified by the map is
		 * extrapolated using either the first two or the last
		 * two entries in the map.
		 */
		for (i = 1; i < entries-1; i++)
			if (temp < map[i].expected)
				break;

		/*
		 * Interpolate/extrapolate the temperature using linear
		 * equation with map[i-1] and map[i] being the two ends
		 * of the line segment.
		 */
		denominator = map[i].expected - map[i-1].expected;
		if (denominator == 0) {
			/*
			 * Infinite slope. Since the temperature reading
			 * resolution is 1C, force denominator to 1 to
			 * avoid divide by zero.
			 */
			denominator = 1;
		}
		ftemp = map[i-1].observed + (temp - map[i-1].expected) *
		    (float)(map[i].observed - map[i-1].observed)/denominator;
		new_temp = (int)(ftemp + (ftemp >= 0 ? 0.5 : -0.5));
	}

	if (threshp) {
		if (new_temp > threshp->max_limit)
			new_temp = threshp->max_limit;
		else if (new_temp < threshp->min_limit)
			new_temp = threshp->min_limit;
	}

	return (new_temp);
}


/*
 * Check if the specified FRU is present.
 * Returns 1 if present; 0 otherwise.
 */
static int
fru_present(char *path)
{
	char		*p, physpath[PATH_MAX];
	di_node_t	root_node;
	int		fru_present = 0;

	/*
	 * Construct FRU device path by stripping minor
	 * node name from the path and use di_init() to
	 * see if the node exists.
	 */
	(void) strlcpy(physpath, path, sizeof (physpath));
	p = strrchr(physpath, ':');
	if (p != NULL)
		*p = '\0';
	if ((root_node = di_init(physpath, DINFOMINOR)) != DI_NODE_NIL) {
		di_fini(root_node);
		fru_present = 1;
	}
	return (fru_present);
}


/*
 * Get environmental segment from the specified FRU SEEPROM
 */
static int
get_envseg(int fd, void **envsegp, int *envseglenp)
{
	int			i, segcnt, envseglen;
	section_layout_t	section;
	segment_layout_t	segment;
	uint8_t			*envseg;

	if (lseek(fd, (long)SECTION_HDR_OFFSET, 0) == -1L ||
	    read(fd, &section, sizeof (section)) != sizeof (section)) {
		return (EINVAL);
	}

	/*
	 * Verify we have the correct section and contents are valid
	 * For now, we don't verify the CRC.
	 */
	if (section.header_tag != SECTION_HDR_TAG ||
	    GET_UNALIGN16(&section.header_version[0]) != SECTION_HDR_VER) {
		if (env_debug)
			envd_log(LOG_INFO,
			    "Invalid section header tag:%x  version:%x\n",
			    section.header_tag,
			    GET_UNALIGN16(&section.header_version));
		return (EINVAL);
	}

	/*
	 * Locate our environmental segment
	 */
	segcnt = section.segment_count;
	for (i = 0; i < segcnt; i++) {
		if (read(fd, &segment, sizeof (segment)) != sizeof (segment)) {
			return (errno);
		}
		if (env_debug > 1)
			envd_log(LOG_INFO,
			    "Seg name: %x  desc:%x off:%x  len:%x\n",
			    GET_UNALIGN16(&segment.name),
			    GET_UNALIGN32(&segment.descriptor[0]),
			    GET_UNALIGN16(&segment.offset),
			    GET_UNALIGN16(&segment.length));

		if (GET_UNALIGN16(&segment.name) == ENVSEG_NAME)
			break;
	}

	if (i >= segcnt) {
		return (ENOENT);
	}

	/*
	 * Allocate memory to hold the environmental segment data.
	 */
	envseglen = GET_UNALIGN16(&segment.length);
	if ((envseg = malloc(envseglen)) == NULL) {
		return (ENOMEM);
	}

	if (lseek(fd, (long)GET_UNALIGN16(&segment.offset), 0) == -1L ||
	    read(fd, envseg, envseglen) != envseglen) {
		(void) free(envseg);
		return (EIO);
	}

	*envsegp = envseg;
	*envseglenp = envseglen;

	if (env_debug > 1) {
		char	msgbuf[256];
		for (i = 0; i < envseglen; i++) {
			(void) sprintf(&msgbuf[3*(i&0xf)], "%2x ", envseg[i]);
			if ((i & 0xf) == 0xf || i == (envseglen-1))
				envd_log(LOG_INFO, "envseg[%2x]: %s\n",
				    (i & ~0xf), msgbuf);
		}
	}

	return (0);
}


/*
 * Get all environmental segments
 */
static fruenvseg_t *
get_fru_envsegs(void)
{
	env_sensor_t		*sensorp;
	fruenvseg_t		*frup, *fruenvsegs;
	envseg_layout_t		*envsegp;
	void			*envsegbufp;
	int			fd, envseglen, hdrlen;
	char			path[PATH_MAX];

	fruenvsegs = NULL;
	for (sensorp = &envd_sensors[0]; sensorp->name != NULL; sensorp++) {
		if (sensorp->fru == NULL)
			continue;

		for (frup = fruenvsegs; frup != NULL; frup = frup->next)
			if (strcmp(frup->fru, sensorp->fru) == 0)
				break;

		if (frup != NULL)
			continue;

		frup = (fruenvseg_t *)malloc(sizeof (fruenvseg_t));
		if (frup == NULL)
			continue;

		/* add this FRU to our list */
		frup->fru = sensorp->fru;
		frup->envsegbufp = NULL;
		frup->envseglen = 0;
		frup->next = fruenvsegs;
		fruenvsegs = frup;

		/*
		 * Now get the environmental segment from this FRU
		 */
		(void) strcpy(path, "/devices");
		(void) strlcat(path, sensorp->fru, sizeof (path));
	retry:
		errno = 0;
		fd = open(path, O_RDONLY);
		if (env_debug > 1)
			envd_log(LOG_INFO,
			    "fru SEEPROM: %s fd: %d  errno:%d\n",
			    path, fd, errno);
		if (fd == -1 && errno == ENOENT && fru_present(frup->fru)) {
			if (fru_devfsadm_invoked ||
			    fru_devfsadm_cmd[0] == '\0') {
				envd_log(LOG_CRIT, ENV_FRU_OPEN_FAIL,
				    sensorp->fru, errno, strerror(errno));
				continue;

			}
			/*
			 * FRU is present but no path exists as
			 * someone rebooted the system without
			 * "-r" option. Let's invoke "devfsadm"
			 * once to create seeprom nodes and try
			 * again so that we can monitor all
			 * accessible sensors properly and prevent
			 * any CPU overheating.
			 */
			if (env_debug)
				envd_log(LOG_INFO,
				    "Invoking '%s' to create FRU nodes\n",
				    fru_devfsadm_cmd);
			fru_devfsadm_invoked = 1;
			(void) system(fru_devfsadm_cmd);
			goto retry;
		}

		/*
		 * Read environmental segment from this FRU SEEPROM
		 */
		if (get_envseg(fd, &envsegbufp, &envseglen) == 0) {
			/*
			 * Validate envseg version number and header length
			 */
			envsegp = (envseg_layout_t *)envsegbufp;
			hdrlen = sizeof (envseg_layout_t) -
			    sizeof (envseg_sensor_t) +
			    (envsegp->sensor_count) * sizeof (envseg_sensor_t);

			if (envsegp->version != ENVSEG_VERSION ||
			    envseglen < hdrlen) {
				/*
				 * version mismatch or header not big enough
				 */
				envd_log(LOG_CRIT, ENV_FRU_BAD_ENVSEG,
				    sensorp->fru, errno, strerror(errno));
				if (envsegbufp != NULL)
					(void) free(envsegbufp);
			} else {
				frup->envseglen = envseglen;
				frup->envsegbufp = envsegbufp;
			}
		}
		(void) close(fd);
	}
	return (fruenvsegs);
}

/*
 * Process environmental segment for all FRUs.
 */
static void
process_fru_envseg()
{
	env_sensor_t		*sensorp;
	sensor_thresh_t		*threshp;
	envseg_layout_t		*envsegp;
	envseg_sensor_data_t	*datap;
	fruenvseg_t		*frup, *fruenvsegs;
	int			i, envseglen, sensorcnt;
	uint_t			offset, length, mapentries;

	/*
	 * Lookup/read environmental segments from FRU SEEPROMs and
	 * process it. Note that we read each SEEPROM once as it's
	 * a slow device.
	 */
	fruenvsegs = get_fru_envsegs();

	for (sensorp = &envd_sensors[0]; sensorp->name != NULL; sensorp++) {
		if (sensorp->fru == NULL)
			continue;

		/*
		 * Locate our FRU environmental segment
		 */
		for (frup = fruenvsegs; frup != NULL; frup = frup->next)
			if (strcmp(frup->fru, sensorp->fru) == 0)
				break;
		if (frup == NULL || frup->envsegbufp == NULL)
			continue;

		envsegp = (envseg_layout_t *)frup->envsegbufp;
		envseglen = frup->envseglen;
		sensorcnt = envsegp->sensor_count;

		/*
		 * Locate our sensor data record entry
		 */
		for (i = 0; i < sensorcnt; i++) {
			uint32_t	id;

			id = GET_UNALIGN32(&envsegp->sensors[i].sensor_id[0]);
			if (env_debug > 1)
				envd_log(LOG_INFO, " sensor[%d]: id:%x\n",
				    i, id);
			if (id == sensorp->fru_sensor)
				break;
		}

		if (i >= sensorcnt)
			continue;

		/*
		 * Validate offset/length of our sensor data record
		 */
		offset = (uint_t)GET_UNALIGN16(&envsegp->sensors[i].offset);
		datap =  (envseg_sensor_data_t *)((intptr_t)frup->envsegbufp +
		    offset);
		mapentries =  GET_UNALIGN16(&datap->obs2exp_cnt);
		length = sizeof (envseg_sensor_data_t) - sizeof (envseg_map_t) +
		    mapentries * sizeof (envseg_map_t);

		if (env_debug > 1)
			envd_log(LOG_INFO, "Found sensor_id:%x idx:%x "
			"off:%x #maps:%x expected length:%x\n",
				sensorp->fru_sensor, i, offset,
				mapentries, length);

		if (offset >= envseglen || (offset+length) > envseglen) {
			/* corrupted sensor record */
			envd_log(LOG_CRIT, ENV_FRU_BAD_SENSOR_ENTRY,
			    sensorp->fru_sensor, sensorp->name, sensorp->fru);
			continue;
		}

		if (env_debug > 1) {
			/* print threshold values */
			envd_log(LOG_INFO,
			    "Thresholds: HPwrOff %d  HShutDn %d  HWarn %d\n",
			    datap->high_power_off, datap->high_shutdown,
			    datap->high_warning);
			envd_log(LOG_INFO,
			    "Thresholds: LWarn %d  LShutDn %d  LPwrOff %d\n",
			    datap->low_warning, datap->low_shutdown,
			    datap->low_power_off);

			/* print policy data */
			envd_log(LOG_INFO,
			    " Policy type: %d #%d data: %x %x %x %x %x %x\n",
			    datap->policy_type, datap->policy_entries,
			    datap->policy_data[0], datap->policy_data[1],
			    datap->policy_data[2], datap->policy_data[3],
			    datap->policy_data[4], datap->policy_data[5]);

			/* print map table */
			for (i = 0; i < mapentries; i++) {
				envd_log(LOG_INFO, " Map pair# %d: %d %d\n",
				    i, datap->obs2exp_map[i].observed,
				    datap->obs2exp_map[i].expected);
			}
		}


		/*
		 * Copy threshold values
		 */
		threshp = sensorp->temp_thresh;
		threshp->high_power_off = datap->high_power_off;
		threshp->high_shutdown = datap->high_shutdown;
		threshp->high_warning = datap->high_warning;
		threshp->low_warning = datap->low_warning;
		threshp->low_shutdown = datap->low_shutdown;
		threshp->low_power_off = datap->low_power_off;

		/*
		 * Copy policy data
		 */
		threshp->policy_type = datap->policy_type;
		threshp->policy_entries = datap->policy_entries;
		for (i = 0; i < MAX_POLICY_ENTRIES; i++)
			threshp->policy_data[i] =
			    (tempr_t)datap->policy_data[i];

		/*
		 * Copy temperature mapping info (discard duplicate entries)
		 */
		if (sensorp->obs2exp_map) {
			(void) free(sensorp->obs2exp_map);
			sensorp->obs2exp_map = NULL;
			sensorp->obs2exp_cnt = 0;
		}
		if (mapentries > 0) {
			tempr_map_t	*map;
			int		cnt;
			tempr_t		observed, expected;

			map = (tempr_map_t *)malloc(mapentries *
			    sizeof (tempr_map_t));

			if (map == NULL) {
				envd_log(LOG_CRIT, ENV_FRU_SENSOR_MAP_NOMEM,
				    sensorp->fru_sensor, sensorp->name,
				    sensorp->fru);
				continue;
			}

			for (i = 0, cnt = 0; i < mapentries; i++) {

				observed = (tempr_t)
				    datap->obs2exp_map[i].observed;
				expected = (tempr_t)
				    datap->obs2exp_map[i].expected;

				/* ignore if duplicate entry */
				if (cnt > 0 &&
				    observed == map[cnt-1].observed &&
				    expected == map[cnt-1].expected) {
					continue;
				}
				map[cnt].observed = observed;
				map[cnt].expected = expected;
				cnt++;
			}
			sensorp->obs2exp_cnt = cnt;
			sensorp->obs2exp_map = map;
		}

		if (env_debug > 2 && sensorp->obs2exp_cnt > 1) {
			char	msgbuf[256];

			envd_log(LOG_INFO,
			    "Measured --> Correct temperature table "
			    "for sensor: %s\n", sensorp->name);
			for (i = -128; i < 128; i++) {
				(void) sprintf(&msgbuf[6*(i&0x7)], "%6d",
				    xlate_obs2exp(sensorp, i));
				if ((i &0x7) == 0x7)
					envd_log(LOG_INFO,
					    "%8d: %s\n", (i & ~0x7), msgbuf);
			}
			if ((i & 0x7) != 0)
				(void) printf("%8d: %s\n", (i & ~0x7), msgbuf);

			envd_log(LOG_INFO,
			    "Correct --> Measured temperature table "
			    "for sensor: %s\n", sensorp->name);
			for (i = -128; i < 128; i++) {
				(void) sprintf(&msgbuf[6*(i&0x7)], "%6d",
				    xlate_exp2obs(sensorp, i));
				if ((i &0x7) == 0x7)
					envd_log(LOG_INFO,
					    "%8d: %s\n", (i & ~0x7), msgbuf);
			}
			if ((i & 0x7) != 0)
				envd_log(LOG_INFO,
				    "%8d: %s\n", (i & ~0x7), msgbuf);
		}
	}

	/*
	 * Deallocate environmental segment list
	 */
	while (fruenvsegs) {
		frup = fruenvsegs;
		fruenvsegs = frup->next;
		if (frup->envsegbufp != NULL)
			(void) free(frup->envsegbufp);
		(void) free(frup);
	}
}

/*
 * Lookup fan and return a pointer to env_fan_t data structure.
 */
env_fan_t *
fan_lookup(char *name)
{
	int		i;
	env_fan_t	*fanp;

	for (i = 0; (fanp = envd_fans[i]) != NULL; i++) {
		if (strcmp(fanp->name, name) == 0)
			return (fanp);
	}
	return (NULL);
}

/*
 * Lookup sensor and return a pointer to env_sensor_t data structure.
 */
env_sensor_t *
sensor_lookup(char *name)
{
	env_sensor_t	*sensorp;

	for (sensorp = &envd_sensors[0]; sensorp->name != NULL; sensorp++) {
		if (strcmp(sensorp->name, name) == 0)
			return (sensorp);
	}
	return (NULL);
}

/*
 * Get current temperature
 * Returns -1 on error, 0 if successful
 */
int
get_temperature(env_sensor_t *sensorp, tempr_t *temp)
{
	int	fd = sensorp->fd;
	int	retval = 0;
	int	expected_temp;

	if (fd == -1)
		retval = -1;
	else if (ioctl(fd, I2C_GET_TEMPERATURE, temp) == -1) {
		retval = -1;
		if (sensorp->error == 0) {
			sensorp->error = 1;
			envd_log(LOG_WARNING, ENV_SENSOR_ACCESS_FAIL,
			    sensorp->name, errno, strerror(errno));
		}
	} else if (sensorp->error != 0) {
		sensorp->error = 0;
		envd_log(LOG_WARNING, ENV_SENSOR_ACCESS_OK, sensorp->name);
	} else if (sensorp->obs2exp_map != NULL) {
		expected_temp = xlate_obs2exp(sensorp, (tempr_t)*temp);
		if (env_debug > 1)
			envd_log(LOG_INFO,
			    "sensor: %-13s temp:%d  CORRECED to %d\n",
			    sensorp->name, *temp, (tempr_t)expected_temp);
		*temp = (tempr_t)expected_temp;
	}

	return (retval);
}

/*
 * Get current fan speed
 * Returns -1 on error, 0 if successful
 */
int
get_fan_speed(env_fan_t *fanp, fanspeed_t *fanspeedp)
{
	int	fan_fd;
	int	retval = 0;

	fan_fd = fanp->fd;
	if (fan_fd == -1 || read(fan_fd, fanspeedp, sizeof (fanspeed_t)) !=
	    sizeof (fanspeed_t))
		retval = -1;
	return (retval);
}

/*
 * Set fan speed
 * Returns -1 on error, 0 if successful
 */
static int
set_fan_speed(env_fan_t *fanp, fanspeed_t fanspeed)
{
	int	fan_fd;
	int	retval = 0;

	fan_fd = fanp->fd;
	if (fan_fd == -1 || write(fan_fd, &fanspeed, sizeof (fanspeed)) !=
	    sizeof (fanspeed_t))
		retval = -1;
	return (retval);
}


/*
 * close all fan devices
 */
static void
envd_close_fans(void)
{
	int		i;
	env_fan_t	*fanp;

	for (i = 0; (fanp = envd_fans[i]) != NULL; i++) {
		if (fanp->fd != -1) {
			(void) close(fanp->fd);
			fanp->fd = -1;
		}
	}
}

/*
 * Close sensor devices
 */
static void
envd_close_sensors(void)
{
	env_sensor_t	*sensorp;

	for (sensorp = &envd_sensors[0]; sensorp->name != NULL; sensorp++) {
		if (sensorp->fd != -1) {
			(void) close(sensorp->fd);
			sensorp->fd = -1;
		}
	}
}

/*
 * Open PM device
 */
static void
envd_open_pm(void)
{
	pm_fd = open(PM_DEVICE, O_RDONLY);
	if (pm_fd != -1)
		(void) fcntl(pm_fd, F_SETFD, FD_CLOEXEC);
}

/*
 * Close PM device
 */
static void
envd_close_pm(void)
{
	if (pm_fd != -1) {
		(void) close(pm_fd);
		pm_fd = -1;
	}
}

/*
 * Open fan devices and initialize per fan data structure.
 * Returns #fans found.
 */
static int
envd_setup_fans(void)
{
	int		i, fd;
	fanspeed_t	speed;
	env_fan_t	*fanp;
	char		path[PATH_MAX];
	int		fancnt = 0;
	char		*fan_name;
	sensor_fan_map_t *sfmap;
	env_sensor_t	*sensorp;
	int		sensor_cnt;

	for (i = 0; (fanp = envd_fans[i]) != NULL; i++) {
		if (fanp->fd == -1) {
			fanp->sensor_cnt = 0;
			fanp->cur_speed = 0;
			fanp->prev_speed = 0;

			(void) strcpy(path, "/devices");
			(void) strlcat(path, fanp->devfs_path, sizeof (path));
			fd = open(path, O_RDWR);
			if (fd == -1) {
				envd_log(LOG_CRIT,
				    ENV_FAN_OPEN_FAIL, fanp->name,
				    fanp->devfs_path, errno, strerror(errno));
				fanp->present = B_FALSE;
				continue;
			}
			(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
			fanp->fd = fd;
			fanp->present = B_TRUE;
		}
		fancnt++;

		/*
		 * Set initial speed and update cur_speed/prev_speed
		 */
		if (fanp->forced_speed >= 0) {
			speed = (fanspeed_t)fanp->forced_speed;
			if (speed > fanp->speed_max)
				speed = fanp->speed_max;
			if (!disable_piclenvd)
				(void) set_fan_speed(fanp, speed);
		} else if (get_fan_speed(fanp, &speed) == -1) {
			/*
			 * The Fan driver does not know the current fan speed.
			 * Initialize all ON/OFF fans to ON state and all
			 * variable speed fans under software control to 50%
			 * of the max speed and reread the fan to get the
			 * current speed.
			 */
			speed = (fanp == &envd_psupply_fan) ?
				fanp->speed_max : fanp->speed_max/2;
			if (!disable_piclenvd) {
				(void) set_fan_speed(fanp, speed);
				if (get_fan_speed(fanp, &speed) == -1)
					continue;
			}
		}
		fanp->cur_speed = speed;
		fanp->prev_speed = speed;

		/*
		 * Process sensor_fan_map[] table and initialize sensors[]
		 * array for this fan.
		 */
		fan_name = fanp->name;
		for (sensor_cnt = 0, sfmap = &sensor_fan_map[0];
		    sfmap->sensor_name != NULL; sfmap++) {
			if (strcmp(sfmap->fan_name, fan_name) != 0)
				continue;
			sensorp = sensor_lookup(sfmap->sensor_name);
			if (sensorp != NULL && sensor_cnt < SENSORS_PER_FAN) {
				fanp->sensors[sensor_cnt] = sensorp;
				sensor_cnt++;
			}
		}
		fanp->sensor_cnt = sensor_cnt;
	}

	return (fancnt);
}


/*
 * Adjust specified sensor target temperature and fan adjustment rate
 */

static void
adjust_sensor_target(env_sensor_t *sensorp)
{
	int		target, index;
	sensor_pmdev_t	*pmdevp;
	sensor_thresh_t	*threshp;
	float		rate;

	/*
	 * Look at current power state of all power managed devices
	 * associated with this sensor and look up the desired target
	 * temperature and pick the lowest one of those values. Also,
	 * calculate the rate of change based upon whether one or more
	 * of the associated power managed devices are not running at
	 * full power mode.
	 */

	if (sensorp == NULL || (threshp = sensorp->temp_thresh) == NULL ||
	    threshp->policy_type != POLICY_TARGET_TEMP)
		return;

	target = threshp->policy_data[0];
	rate = 1.0;
	for (pmdevp = sensorp->pmdevp; pmdevp != NULL; pmdevp = pmdevp->next) {
		index = pmdevp->full_power - pmdevp->cur_power;
		if (index <= 0)
			continue;

		/* not running at full power */
		if (index >= threshp->policy_entries)
			index = threshp->policy_entries - 1;
		if (target > threshp->policy_data[index])
			target = threshp->policy_data[index];
		if (rate > (float)fan_slow_adjustment/100)
			rate = (float)fan_slow_adjustment/100;
		if (env_debug > 1)
			envd_log(LOG_INFO,
			    "pmdev: %-13s new_target:%d  cur:%d power:%d/%d\n",
			    pmdevp->pmdev_name, target, sensorp->target_temp,
			    pmdevp->cur_power, pmdevp->full_power);
	}

	if (env_debug)
		envd_log(LOG_INFO,
		    "sensor: %-13s new_target:%d  cur:%d power:%d/%d\n",
		    sensorp->name, target, sensorp->target_temp,
		    ((sensorp->pmdevp) ? sensorp->pmdevp->cur_power : -1),
		    ((sensorp->pmdevp) ? sensorp->pmdevp->full_power : -1));

	sensorp->fan_adjustment_rate = rate;
	sensorp->target_temp = target;
}

/*
 * Update current power level of all PM devices we are tracking and adjust
 * the target temperature associated with the corresponding sensor.
 *
 * Returns 1 if one or more pmdev power level was adjusted; 0 otherwise.
 */
static int
update_pmdev_power()
{
	sensor_pmdev_t	*pmdevp;
	pm_req_t	pmreq;
	int		cur_power;
	int		updated = 0;

	for (pmdevp = sensor_pmdevs; pmdevp->pmdev_name != NULL; pmdevp++) {
		pmreq.physpath = pmdevp->pmdev_name;
		pmreq.data = NULL;
		pmreq.datasize = 0;
		pmreq.component = pmdevp->speed_comp;
		cur_power = ioctl(pm_fd, PM_GET_CURRENT_POWER, &pmreq);
		if (pmdevp->cur_power != cur_power) {
			pmdevp->cur_power = cur_power;
			if (pmdevp->sensorp) {
				adjust_sensor_target(pmdevp->sensorp);
				updated = 1;
			}
		}
	}
	return (updated);
}

/*
 * Check if the specified sensor is present.
 * Returns 1 if present; 0 otherwise.
 *
 * Note that we don't use ptree_get_node_by_path() here to detect
 * if a temperature device is present as we don't want to make
 * "devtree" a critical plugin.
 */
static int
envd_sensor_present(env_sensor_t *sensorp)
{
	char		*p, physpath[PATH_MAX];
	di_node_t	root_node;
	int		sensor_present = 0;

	/*
	 * Construct temperature device path by stripping minor
	 * node name from the devfs_path and use di_init() to
	 * see if the node exists.
	 */
	(void) strcpy(physpath, sensorp->devfs_path);
	p = strrchr(physpath, ':');
	if (p != NULL)
		*p = '\0';
	if ((root_node = di_init(physpath, DINFOMINOR)) != DI_NODE_NIL) {
		di_fini(root_node);
		sensor_present = 1;
	}
	return (sensor_present);
}

/*
 * Open temperature sensor devices and initialize per sensor data structure.
 * Returns #sensors found.
 */
static int
envd_setup_sensors(void)
{
	tempr_t		temp;
	env_sensor_t	*sensorp;
	char		path[PATH_MAX];
	int		sensorcnt = 0;
	int		sensor_present;
	sensor_thresh_t	*threshp;
	sensor_pmdev_t	*pmdevp;

	for (sensorp = &envd_sensors[0]; sensorp->name != NULL; sensorp++) {
		if (sensorp->fd != -1) {
			/* Don't reinitialize opened sensor */
			threshp = sensorp->temp_thresh;
			sensorp->pmdevp = NULL;
		} else {
			/* Initialize sensor's initial state */
			sensorp->shutdown_initiated = B_FALSE;
			sensorp->warning_tstamp = 0;
			sensorp->warning_start = 0;
			sensorp->shutdown_tstamp = 0;
			sensorp->pmdevp = NULL;
			sensorp->fan_adjustment_rate = 1.0;

			threshp = sensorp->temp_thresh;
			temp = (threshp && threshp->policy_entries > 0) ?
			    threshp->policy_data[0] : 0;
			sensorp->target_temp = temp;
			sensorp->cur_temp = temp;
			sensorp->avg_temp = temp;
			sensorp->prev_avg_temp = temp;
			sensorp->error = 0;

			(void) strcpy(path, "/devices");
			(void) strlcat(path, sensorp->devfs_path,
			    sizeof (path));
		retry:
			sensorp->fd = open(path, O_RDWR);
			if (sensorp->fd == -1) {
				sensor_present = envd_sensor_present(sensorp);
				if (sensor_present && !devfsadm_invoked &&
				    devfsadm_cmd[0] != '\0') {
					/*
					 * Sensor is present but no path
					 * exists as someone rebooted the
					 * system without "-r" option. Let's
					 * invoke "devfsadm" once to create
					 * max1617 sensors paths in /devices
					 * subtree and try again so that we
					 * can monitor all accessible sensors
					 * and prevent any CPU overheating.
					 *
					 * Note that this routine is always
					 * called in main thread context and
					 * serialized with respect to other
					 * plugins' initialization. Hence, it's
					 * safe to use system(3C) call here.
					 */
					devfsadm_invoked = 1;
					(void) system(devfsadm_cmd);
					goto retry;
				}
				if (sensor_present)
					envd_log(LOG_CRIT,
					    ENV_SENSOR_OPEN_FAIL,
					    sensorp->name,
					    sensorp->devfs_path, errno,
					    strerror(errno));
				sensorp->present = B_FALSE;
				continue;
			}
			(void) fcntl(sensorp->fd, F_SETFD, FD_CLOEXEC);
			sensorp->present = B_TRUE;

			/*
			 * Set cur_temp field to the current temperature value
			 */
			if (get_temperature(sensorp, &temp) == 0) {
				sensorp->cur_temp = temp;
				sensorp->avg_temp = temp;
			}
		}
		sensorcnt++;

		/*
		 * Set low_power_off and high_power_off limits
		 */
		if (threshp && !disable_power_off) {
			temp = xlate_exp2obs(sensorp, threshp->low_power_off);
			if (env_debug > 1)
				envd_log(LOG_INFO, "sensor: %-13s low_power_"
				"off set to %d (real %d)\n", sensorp->name,
				    (int)temp, threshp->low_power_off);
			(void) ioctl(sensorp->fd, MAX1617_SET_LOW_LIMIT, &temp);

			temp = xlate_exp2obs(sensorp, threshp->high_power_off);
			if (env_debug > 1)
				envd_log(LOG_INFO, "sensor: %-13s high_power_"
				"off set to %d (real %d)\n", sensorp->name,
				    (int)temp, threshp->high_power_off);
			(void) ioctl(sensorp->fd, MAX1617_SET_HIGH_LIMIT,
			    &temp);
		}
	}

	/*
	 * Locate "CPU Speed" component for any PM devices associated with
	 * the sensors.
	 */
	for (pmdevp = sensor_pmdevs; pmdevp->sensor_name; pmdevp++) {
		int		i, ncomp;
		char		physpath[PATH_MAX];
		pm_req_t	pmreq;

		pmdevp->speed_comp = -1;
		pmdevp->full_power = -1;
		pmdevp->cur_power = -1;
		pmdevp->next = NULL;
		pmdevp->sensorp = sensorp = sensor_lookup(pmdevp->sensor_name);

		/*
		 * Lookup speed component and get full and current power
		 * level for that component.
		 */
		pmreq.physpath = pmdevp->pmdev_name;
		pmreq.data = physpath;
		pmreq.datasize = sizeof (physpath);

		ncomp = ioctl(pm_fd, PM_GET_NUM_COMPONENTS, &pmreq);
		for (i = 0; i < ncomp; i++) {
			pmreq.component = i;
			physpath[0] = '\0';
			if (ioctl(pm_fd, PM_GET_COMPONENT_NAME, &pmreq) <= 0)
				continue;
			if (strcasecmp(pmreq.data, pmdevp->speed_comp_name))
				continue;
			pmdevp->speed_comp = i;


			/*
			 * Get full power and current power level
			 */
			pmdevp->full_power = ioctl(pm_fd, PM_GET_FULL_POWER,
			    &pmreq);

			pmdevp->cur_power = ioctl(pm_fd, PM_GET_CURRENT_POWER,
			    &pmreq);

			if (sensorp) {
				pmdevp->next = sensorp->pmdevp;
				sensorp->pmdevp = pmdevp;
				adjust_sensor_target(sensorp);
			}
			break;
		}
		if (env_debug > 1)
			envd_log(LOG_INFO,
			    "sensor:%s %p pmdev:%s comp:%s %d power:%d/%d\n",
			    pmdevp->sensor_name, pmdevp->sensorp,
			    pmdevp->pmdev_name, pmdevp->speed_comp_name,
			    pmdevp->speed_comp, pmdevp->cur_power,
			    pmdevp->full_power);
	}
	return (sensorcnt);
}

/*
 * Read all temperature sensors and take appropriate action based
 * upon temperature threshols associated with each sensor. Possible
 * actions are:
 *
 *	temperature > high_shutdown
 *	temperature < low_shutdown
 *		Gracefully shutdown the system and log/print a message
 *		on the system console provided the temperature has been
 *		in shutdown range for "shutdown_interval" seconds.
 *
 *	high_warning < temperature <= high_shutdown
 *	low_warning  > temperature >= low_shutdown
 *		Log/print a warning message on the system console at most
 *		once every "warning_interval" seconds.
 *
 * Note that the current temperature is recorded in the "cur_temp" field
 * within each env_sensor_t structure.
 */
static void
monitor_sensors(void)
{
	tempr_t 	temp;
	env_sensor_t	*sensorp;
	sensor_thresh_t	*threshp;
	time_t		ct;
	char		msgbuf[BUFSIZ];
	char		syscmd[BUFSIZ];

	for (sensorp = &envd_sensors[0]; sensorp->name != NULL; sensorp++) {
		if (get_temperature(sensorp, &temp) < 0)
			continue;

		sensorp->prev_avg_temp = sensorp->avg_temp;
		sensorp->cur_temp = temp;
		sensorp->avg_temp = (sensorp->avg_temp + temp)/2;
		threshp = sensorp->temp_thresh;

		if (env_debug)
			envd_log(LOG_INFO,
			"sensor: %-13s temp  prev_avg:%6.2f  "
			"cur:%d avg_temp:%6.2f power:%d/%d target:%d\n",
			    sensorp->name, sensorp->prev_avg_temp,
			    temp, sensorp->avg_temp, ((sensorp->pmdevp) ?
			    sensorp->pmdevp->cur_power : -1),
			    ((sensorp->pmdevp) ? sensorp->pmdevp->full_power :
			    -1), sensorp->target_temp);


		/*
		 * If this sensor already triggered system shutdown, don't
		 * log any more shutdown/warning messages for it.
		 */
		if (sensorp->shutdown_initiated || threshp == NULL)
			continue;

		/*
		 * Check for the temperature in warning and shutdown range
		 * and take appropriate action.
		 */
		if (TEMP_IN_WARNING_RANGE(temp, threshp) && !disable_warning) {
			/*
			 * Check if the temperature has been in warning
			 * range during last warning_duration interval.
			 * If so, the temperature is truly in warning
			 * range and we need to log a warning message,
			 * but no more than once every warning_interval
			 * seconds.
			 */
			time_t	wtstamp = sensorp->warning_tstamp;

			ct = (time_t)(gethrtime() / NANOSEC);
			if (sensorp->warning_start == 0)
				sensorp->warning_start = ct;
			if (((ct - sensorp->warning_start) >=
			    warning_duration) && (wtstamp == 0 ||
			    (ct - wtstamp) >= warning_interval)) {
				envd_log(LOG_CRIT, ENV_WARNING_MSG,
				    sensorp->name, temp,
				    threshp->low_warning,
				    threshp->high_warning);
				sensorp->warning_tstamp = ct;
			}
		} else if (sensorp->warning_start != 0)
			sensorp->warning_start = 0;

		if (TEMP_IN_SHUTDOWN_RANGE(temp, threshp) &&
		    !disable_shutdown) {
			ct = (time_t)(gethrtime() / NANOSEC);
			if (sensorp->shutdown_tstamp == 0)
				sensorp->shutdown_tstamp = ct;

			/*
			 * Shutdown the system if the temperature remains
			 * in the shutdown range for over shutdown_interval
			 * seconds.
			 */
			if ((ct - sensorp->shutdown_tstamp) >=
			    shutdown_interval) {
				/* log error */
				sensorp->shutdown_initiated = B_TRUE;
				(void) snprintf(msgbuf, sizeof (msgbuf),
				    ENV_SHUTDOWN_MSG, sensorp->name,
				    temp, threshp->low_shutdown,
				    threshp->high_shutdown);
				envd_log(LOG_ALERT, msgbuf);

				/* shutdown the system (only once) */
				if (system_shutdown_started == B_FALSE) {
					(void) snprintf(syscmd, sizeof (syscmd),
					    "%s \"%s\"", shutdown_cmd, msgbuf);
					envd_log(LOG_ALERT, syscmd);
					system_shutdown_started = B_TRUE;
					(void) system(syscmd);
				}
			}
		} else if (sensorp->shutdown_tstamp != 0)
			sensorp->shutdown_tstamp = 0;
	}
}


/*
 * Adjust fan speed based upon the current temperature value of various
 * sensors affected by the specified fan.
 */
static int
adjust_fan_speed(env_fan_t *fanp, lpm_dev_t *devp)
{
	int		i;
	fanspeed_t	fanspeed;
	float		speed, cur_speed, new_speed, max_speed, min_speed;
	env_sensor_t	*sensorp;
	sensor_thresh_t	*threshp;
	tempr_t		temp;
	float		avg_temp, tempdiff, targetdiff;
	int		av_ambient;
	int		amb_cnt;


	/*
	 * Get current fan speed
	 */
	if (get_fan_speed(fanp, &fanspeed) < 0)
		return (-1);
	cur_speed = fanp->cur_speed;
	if (fanspeed != (int)cur_speed)
		cur_speed = (float)fanspeed;

	/*
	 * Calculate new fan speed for each sensor and pick the largest one.
	 */
	min_speed = fanp->speed_min;
	max_speed = fanp->speed_max;
	speed = 0;
	av_ambient = 0;
	amb_cnt = 0;

	for (i = 0; i < fanp->sensor_cnt; i++) {
		sensorp = fanp->sensors[i];
		if (sensorp == NULL || sensorp->fd == -1 ||
		    sensorp->temp_thresh == NULL)
			continue;

		temp = sensorp->cur_temp;
		avg_temp = sensorp->avg_temp;
		threshp = sensorp->temp_thresh;

		/*
		 * Note ambient temperatures to determine lpm for system fan
		 */
		if ((devp != NULL) &&
		    (sensorp->flags & SFLAG_CPU_AMB_SENSOR)) {
			av_ambient += temp;
			amb_cnt++;
		}

		/*
		 * If the current temperature is above the warning
		 * threshold, use max fan speed.
		 */
		if (temp >= threshp->high_warning) {
			speed = max_speed;
			break;
		} else if (temp <= threshp->low_warning) {
			speed = min_speed;
			break;
		}

		if (threshp->policy_type == POLICY_TARGET_TEMP) {
			/*
			 * Try to achieve the desired target temperature.
			 * Calculate new fan speed based upon whether the
			 * temperature is rising, falling or steady state.
			 * Also take into consideration the current fan
			 * speed as well as the desired target temperature.
			 */
			float	delta, speed_change;
			float	multiplier;

			targetdiff = avg_temp - sensorp->target_temp;
			tempdiff = avg_temp - sensorp->prev_avg_temp;

			if (tempdiff > AVG_TEMP_HYSTERESIS) {
				/*
				 * Temperature is rising. Increase fan
				 * speed 0.5% for every 1C above the
				 * (target - RISING_TEMP_MARGIN) limit.
				 * Also take into consideration temperature
				 * rising rate and the current fan speed.
				 */
				delta = max_speed * .005 *
				    (RISING_TEMP_MARGIN + targetdiff);
				if (delta <= 0)
					multiplier = 0;
				else
					multiplier = tempdiff/4 +
					    ((cur_speed < max_speed/2) ?
					    2 : 1);
			} else if (tempdiff < -AVG_TEMP_HYSTERESIS) {
				/*
				 * Temperature is falling. Decrease fan
				 * speed 0.5% for every 1C below the
				 * (target + FALLING_TEMP_MARGIN) limit.
				 * Also take into consideration temperature
				 * falling rate and the current fan speed.
				 */
				delta = -max_speed * .005 *
				    (FALLING_TEMP_MARGIN - targetdiff);
				if (delta >= 0)
					multiplier = 0;
				else
					multiplier = -tempdiff/4 +
					    ((cur_speed > max_speed/2) ?
					    2 : 1);
			} else {
				/*
				 * Temperature is changing very slowly.
				 * Adjust fan speed by 0.4% for every 1C
				 * below/above the target temperature.
				 */
				delta = max_speed * .004 * targetdiff;
				multiplier = 1.0;
			}


			/*
			 * Enforece some bounds on multiplier and the
			 * speed change.
			 */
			multiplier = MIN(multiplier, 3.0);
			speed_change = delta * multiplier *
			    sensorp->fan_adjustment_rate;
			speed_change = MIN(speed_change, fan_incr_limit);
			speed_change = MAX(speed_change, -fan_decr_limit);
			new_speed = cur_speed + speed_change;

			if (env_debug > 1)
				envd_log(LOG_INFO,
				"sensor: %-8s temp/diff:%d/%3.1f  "
				"target/diff:%d/%3.1f  change:%4.2f x "
				"%4.2f x %4.2f speed %5.2f -> %5.2f\n",
				    sensorp->name, temp, tempdiff,
				    sensorp->target_temp, targetdiff, delta,
				    multiplier, sensorp->fan_adjustment_rate,
				    cur_speed, new_speed);
		} else if (threshp->policy_type == POLICY_LINEAR) {
			/*
			 * Set fan speed linearly within the operating
			 * range specified by the policy_data[LOW_NOMINAL_LOC]
			 * and policy_data[HIGH_NOMINAL_LOC] threshold values.
			 * Fan speed is set to minimum value at LOW_NOMINAL
			 * and to maximum value at HIGH_NOMINAL value.
			 */
			new_speed = min_speed + (max_speed - min_speed) *
			    (avg_temp - threshp->policy_data[LOW_NOMINAL_LOC])/
			    (threshp->policy_data[HIGH_NOMINAL_LOC] -
			    threshp->policy_data[LOW_NOMINAL_LOC]);
			if (env_debug > 1)
				envd_log(LOG_INFO,
				"sensor: %-8s policy: linear, cur_speed %5.2f"\
				" new_speed: %5.2f\n", sensorp->name, cur_speed,
				    new_speed);
		} else {
			new_speed = cur_speed;
		}
		speed = MAX(speed, new_speed);
	}

	/*
	 * Adjust speed using lpm tables
	 */
	if (amb_cnt > 0) {
		av_ambient = (av_ambient >= 0 ?
			(int)(0.5 + (float)av_ambient/(float)amb_cnt):
			(int)(-0.5 + (float)av_ambient/(float)amb_cnt));
		speed = MAX(speed, (fanspeed_t)get_lpm_speed(devp, av_ambient));
	}

	speed = MIN(speed, max_speed);
	speed = MAX(speed, min_speed);

	/*
	 * Record and update fan speed, if different.
	 */
	fanp->prev_speed = fanp->cur_speed;
	fanp->cur_speed = speed;
	if ((fanspeed_t)speed != fanspeed) {
		fanspeed = (fanspeed_t)speed;
		(void) set_fan_speed(fanp, fanspeed);
	}
	if (env_debug)
		envd_log(LOG_INFO,
		    "fan: %-16s speed cur:%6.2f  new:%6.2f\n",
		    fanp->name, fanp->prev_speed, fanp->cur_speed);

	return (0);
}
/*
 * This is the environment thread, which monitors the current temperature
 * and power managed state and controls system fan speed.  Temperature is
 * polled every sensor-poll_interval seconds duration.
 */
/*ARGSUSED*/
static void *
envthr(void *args)
{
	env_sensor_t	*sensorp;
	fanspeed_t 	fan_speed;
	env_fan_t	*pmfanp = &envd_psupply_fan;
	int		to;
	int		xwd = -1;

	for (sensorp = &envd_sensors[0]; sensorp->name != NULL;
	    sensorp++) {
		if (sensorp->obs2exp_map)
			(void) free(sensorp->obs2exp_map);
		sensorp->obs2exp_map = NULL;
		sensorp->obs2exp_cnt = 0;
	}

	/*
	 * Process environmental segment data, if present,
	 * in the FRU SEEPROM.
	 */
	process_fru_envseg();

	/*
	 * Process tuneable parameters
	 */
	process_env_conf_file();

	/*
	 * Setup temperature sensors and fail if we can't open
	 * at least one sensor.
	 */
	if (envd_setup_sensors() <= 0) {
		envd_close_pm();
		return (NULL);
	}

	to = 3 * sensor_poll_interval + 1;
	xwd = open(XCALWD_DEVFS, O_RDONLY);
	if (xwd < 0) {
		envd_log(LOG_CRIT, ENV_WATCHDOG_INIT_FAIL, errno,
		    strerror(errno));
	} else if (ioctl(xwd, XCALWD_STOPWATCHDOG) < 0 ||
	    ioctl(xwd, XCALWD_STARTWATCHDOG, &to) < 0) {
		envd_log(LOG_CRIT, ENV_WATCHDOG_INIT_FAIL, errno,
		    strerror(errno));
		(void) close(xwd);
		xwd = -1;
	}

	/*
	 * Setup fan device (don't fail even if we can't access
	 * the fan as we can still monitor temeperature.
	 */
	(void) envd_setup_fans();

	for (;;) {
		(void) pthread_rwlock_rdlock(&envd_rwlock);

		/*
		 * If no "pmthr" thread, then we need to update the
		 * current power level for all power managed deviecs
		 * so that we can determine correct target temperature.
		 */
		if (pmthr_exists == B_FALSE)
			(void) update_pmdev_power();

		if (xwd >= 0)
			(void) ioctl(xwd, XCALWD_KEEPALIVE);

		if (!disable_piclenvd) {
			/*
			 * Monitor current temperature for all sensors
			 * (current temperature is recorded in the "cur_temp"
			 * field within each sensor data structure)
			 */
			monitor_sensors();

			/*
			 * Adjust CPU and system fan speed
			 */
			if (envd_cpu_fan.forced_speed < 0)
				(void) adjust_fan_speed(&envd_cpu_fan, NULL);
			if (envd_system_fan.forced_speed < 0)
				(void) adjust_fan_speed(&envd_system_fan,
					lpm_devices);

			/*
			 * Turn off power supply fan if in lowest power state.
			 */
			fan_speed = (cur_lpstate) ? pmfanp->speed_min :
			    pmfanp->speed_max;

			if (env_debug)
				envd_log(LOG_INFO,
				"fan: %-16s speed cur:%6.2f  new:%6.2f "
				"low-power:%d\n", pmfanp->name,
				    (float)pmfanp->cur_speed,
				    (float)fan_speed, cur_lpstate);

			if (fan_speed != (fanspeed_t)pmfanp->cur_speed &&
			    set_fan_speed(pmfanp, fan_speed) == 0)
				pmfanp->cur_speed = fan_speed;
		}
		(void) pthread_rwlock_unlock(&envd_rwlock);

		/*
		 * Wait for sensor_poll_interval seconds before polling
		 * again. Note that we use our own envd_sleep() routine
		 * as sleep() in POSIX thread library gets affected by
		 * the wall clock time being set back.
		 */
		(void) envd_sleep(sensor_poll_interval);
	}
	/*NOTREACHED*/
	return (NULL);
}

/*
 * This is the power management thread, which monitors all power state
 * change events and wakes up the "envthr" thread when the system enters
 * or exits the lowest power state.
 */
/*ARGSUSED*/
static void *
pmthr(void *args)
{
	pm_state_change_t	pmstate;
	char			physpath[PATH_MAX];

	pmstate.physpath = physpath;
	pmstate.size = sizeof (physpath);
	cur_lpstate = 0;

	for (;;) {
		/*
		 * Get PM state change events to check if the system
		 * is in lowest power state and wake up the "envthr"
		 * thread when the power state changes.
		 *
		 * To minimize polling, we use the blocking interface
		 * to get the power state change event here.
		 */
		if (ioctl(pm_fd, PM_GET_STATE_CHANGE_WAIT, &pmstate) != 0) {
			if (errno != EINTR)
				break;
			continue;
		}

		/*
		 * Extract the lowest power state from the last queued
		 * state change events. We pick up queued state change
		 * events using the non-blocking interface and wake up
		 * the "envthr" thread only after consuming all the
		 * state change events queued at that time.
		 */
		do {
			if (env_debug > 1)  {
				envd_log(LOG_INFO,
				"pmstate event:0x%x flags:%x comp:%d "
				"oldval:%d newval:%d path:%s\n",
				    pmstate.event, pmstate.flags,
				    pmstate.component, pmstate.old_level,
				    pmstate.new_level, pmstate.physpath);
			}
			cur_lpstate =
			    (pmstate.flags & PSC_ALL_LOWEST) ? 1 : 0;
		} while (ioctl(pm_fd, PM_GET_STATE_CHANGE, &pmstate) == 0);

		/*
		 * Update current PM state for the components we are
		 * tracking. In case of CPU devices, PM state change
		 * event can be generated even before the state change
		 * takes effect, hence we need to get the current state
		 * for all CPU devices every time and recalculate the
		 * target temperature. We do this once after consuming
		 * all the queued events.
		 */

		(void) pthread_rwlock_rdlock(&envd_rwlock);
		(void) update_pmdev_power();
		(void) pthread_rwlock_unlock(&envd_rwlock);
	}

	/*
	 * We won't be able to monitor lowest power state any longer,
	 * hence reset it.
	 */
	cur_lpstate = 0;
	envd_log(LOG_ERR, PM_THREAD_EXITING, errno, strerror(errno));
	pmthr_exists = B_FALSE;
	return (NULL);
}


/*
 * Process sensor threshold related tuneables
 */
static int
process_threshold_tuneable(char *keyword, char *buf, void *dummy_thresh_addr,
    int flags, char *fname, int line)
{
	int		retval = 0;
	long		val;
	void		*addr;
	char		*endp, *sname;
	env_sensor_t	*sensorp;

	/*
	 * Tuneable entry can be in one of the following formats:
	 *
	 *	threshold-keyword <int-value>
	 *	threshold-keyword <int-value> <sensor-name> ...
	 *
	 * Convert threshold value into integer value and check for
	 * optional sensor name. If no sensor name is specified, then
	 * the tuneable applies to all sensors specified by the "flags".
	 * Otherwise, it is applicable to the specified sensors.
	 *
	 * Note that the dummy_thresh_addr is the address of the threshold
	 * to be changed and is converted into offset by subtracting the
	 * base dummy_thresh address. This offset is added to the base
	 * address of the threshold structure to be update to determine
	 * the final memory address to be modified.
	 */

	errno = 0;
	val = strtol(buf, &endp, 0);
	sname = strtok(endp, tokdel);

	if (errno != 0 || val != (tempr_t)val) {
		retval = -1;
		envd_log(LOG_INFO, ENV_CONF_INT_EXPECTED, fname, line, keyword);
	} else if (flags == 0 && sname == NULL) {
		envd_log(LOG_INFO, "SUNW_piclenvd: file:%s line:%d SKIPPED"
		    " as no sensor specified.\n", fname, line, keyword);
		retval = -1;
	} else if (sname == NULL) {
		int	cnt = 0;

		for (sensorp = &envd_sensors[0]; sensorp->name; sensorp++) {
			if (sensorp->temp_thresh == NULL ||
			    (sensorp->flags & flags) == 0)
				continue;

			/*
			 * Convert dummy_thresh_addr into memory address
			 * for this sensor threshold values.
			 */
			addr = (char *)sensorp->temp_thresh +
			    (int)((char *)dummy_thresh_addr -
			    (char *)&dummy_thresh);

			*(tempr_t *)addr = (tempr_t)val;
			cnt++;
			if (env_debug)
				envd_log(LOG_INFO, "SUNW_piclenvd: file:%s "
				"line:%d %s = %d for sensor: '%s'\n",
				    fname, line, keyword, val, sensorp->name);
		}
		if (cnt == 0)
			envd_log(LOG_INFO, "SUNW_piclenvd: file:%s line:%d "
			"%s SKIPPED as no matching sensor found.\n",
			    fname, line, keyword);
	} else {
		/* apply threshold value to the specified sensors */
		do {
			sensorp = sensor_lookup(sname);
			if (sensorp == NULL || sensorp->temp_thresh == NULL ||
			    (flags && (sensorp->flags & flags) == 0)) {
				envd_log(LOG_INFO,
				"SUNW_piclenvd: file:%s line:%d %s SKIPPED"
				" for '%s' as not a valid sensor.\n",
				    fname, line, keyword, sname);
				continue;
			}
			/*
			 * Convert dummy_thresh_addr into memory address
			 * for this sensor threshold values.
			 */
			addr = (char *)sensorp->temp_thresh +
			    (int)((char *)dummy_thresh_addr -
			    (char *)&dummy_thresh);

			*(tempr_t *)addr = (tempr_t)val;
			if (env_debug)
				envd_log(LOG_INFO, "SUNW_piclenvd: file:%s "
				"line:%d %s = %d for sensor: '%s'\n",
				    fname, line, keyword, val, sensorp->name);
		} while ((sname = strtok(NULL, tokdel)) != NULL);
	}
	return (retval);
}


/*
 * Process integer tuneables
 */
static int
process_int_tuneable(char *keyword, char *buf, void *addr, int size,
    char *fname, int line)
{
	int	retval = 0;
	char	*endp;
	long	val;

	/*
	 * Convert input into integer value and ensure that there is
	 * no other token in the buffer.
	 */
	errno = 0;
	val = strtol(buf, &endp, 0);
	if (errno != 0 || strtok(endp, tokdel) != NULL)
		retval = -1;
	else {
		switch (size) {
		case 1:
			if (val != (int8_t)val)
				retval = -1;
			else
				*(int8_t *)addr = (int8_t)val;
			break;
		case 2:
			if (val != (short)val)
				retval = -1;
			else
				*(short *)addr = (short)val;
			break;
		case 4:
			*(int *)addr = (int)val;
			break;
		default:
			retval = -1;
		}
	}

	if (retval == -1)
		envd_log(LOG_INFO, ENV_CONF_INT_EXPECTED,
		    fname, line, keyword);
	else if (env_debug)
		envd_log(LOG_INFO, "SUNW_piclenvd: file:%s line:%d %s = %d\n",
		    fname, line, keyword, val);

	return (retval);
}


/*
 * Process string tuneables
 *
 * String value must be within double quotes.  Skip over initial white
 * spaces before looking for string value.
 */
static int
process_string_tuneable(char *keyword, char *buf, void *addr, int size,
    char *fname, int line)
{
	int	retval = 0;
	char	c, *p, *strend;

	/* Skip over white spaces */
	buf += strspn(buf, tokdel);

	/*
	 * Parse srting and locate string end (handling escaped double quotes
	 * and other characters)
	 */
	if (buf[0] != '"')
		strend = NULL;
	else {
		for (p = buf+1; (c = *p) != '\0'; p++)
			if (c == '"' || (c == '\\' && *++p == '\0'))
				break;
		strend = (*p == '"') ? p : NULL;
	}

	if (strend == NULL || (strend-buf) > size ||
	    strtok(strend+1, tokdel) != NULL) {
		envd_log(LOG_WARNING, ENV_CONF_STRING_EXPECTED,
		    fname, line, keyword, size);
		retval = -1;
	} else {
		*strend = '\0';
		(void) strcpy(addr, (caddr_t)buf+1);
		if (env_debug)
			envd_log(LOG_INFO, "SUNW_piclenvd: file:%s line:%d "
			    "%s = \"%s\"\n", fname, line, keyword, buf+1);
	}

	return (retval);
}


/*
 * Process configuration file
 */
static void
process_env_conf_file(void)
{
	int		line, len, toklen;
	char		buf[BUFSIZ];
	FILE		*fp;
	env_tuneable_t	*tunep;
	char		nmbuf[SYS_NMLN];
	char		fname[PATH_MAX];
	char		*tok, *valuep;
	int		skip_line = 0;

	if (sysinfo(SI_PLATFORM, nmbuf, sizeof (nmbuf)) == -1)
		return;

	(void) snprintf(fname, sizeof (fname), PICLD_PLAT_PLUGIN_DIRF, nmbuf);
	(void) strlcat(fname, ENV_CONF_FILE, sizeof (fname));
	fp = fopen(fname, "r");
	if (fp == NULL)
		return;

	/*
	 * Blank lines or lines starting with "#" or "*" in the first
	 * column are ignored. All other lines are assumed to contain
	 * input in the following format:
	 *
	 *	keyword value
	 *
	 * where the "value" can be a signed integer or string (in
	 * double quotes) depending upon the keyword.
	 */

	for (line = 1; fgets(buf, sizeof (buf), fp) != NULL; line++) {
		len = strlen(buf);
		if (len <= 0)
			continue;

		/* skip long lines */
		if (buf[len-1] != '\n') {
			skip_line = 1;
			continue;
		} else if (skip_line) {
			skip_line = 0;
			continue;
		} else
			buf[len-1] = '\0';

		/* skip comments */
		if (buf[0] == '*' || buf[0] == '#')
			continue;

		/*
		 * Skip over white space to get the keyword
		 */
		tok = buf + strspn(buf, tokdel);
		if (*tok == '\0')
			continue;			/* blank line */

		toklen = strcspn(tok, tokdel);
		tok[toklen] = '\0';

		/* Get possible location for value (within current line) */
		valuep = tok + toklen + 1;
		if (valuep > buf+len)
			valuep = buf + len;

		/*
		 * Lookup the keyword and process value accordingly
		 */
		for (tunep = &env_tuneables[0]; tunep->name != NULL; tunep++) {
			if (strcasecmp(tunep->name, tok) == 0) {
				(void) (*tunep->func)(tok, valuep,
				    tunep->arg1, tunep->arg2, fname, line);
				break;
			}
		}

		if (tunep->name == NULL)
			envd_log(LOG_INFO, ENV_CONF_UNSUPPORTED_KEYWORD,
			    fname, line, tok);
	}
	(void) fclose(fp);
}

/*
 * Setup envrionmental monitor state and start threads to monitor
 * temperature and power management state.
 * Returns -1 on error, 0 if successful.
 */

static int
envd_setup(void)
{
	char		*valp, *endp;
	int		val;
	int		err;

	if (pthread_attr_init(&thr_attr) != 0 ||
	    pthread_attr_setscope(&thr_attr, PTHREAD_SCOPE_SYSTEM) != 0)
		return (-1);

	if (pm_fd == -1)
		envd_open_pm();

	/*
	 * Setup lpm devices
	 */
	lpm_devices = NULL;
	if ((err = setup_lpm_devices(&lpm_devices)) != PICL_SUCCESS) {
		if (env_debug)
			envd_log(LOG_ERR, "setup_lpm_devices failed err = %d\n",
				err);
	}

	/*
	 * Initialize global state to initial startup values
	 */
	sensor_poll_interval = SENSOR_POLL_INTERVAL;
	fan_slow_adjustment = FAN_SLOW_ADJUSTMENT;
	fan_incr_limit = FAN_INCREMENT_LIMIT;
	fan_decr_limit = FAN_DECREMENT_LIMIT;
	warning_interval = WARNING_INTERVAL;
	warning_duration = WARNING_DURATION;
	shutdown_interval = SHUTDOWN_INTERVAL;
	disable_piclenvd = 0;
	disable_power_off = 0;
	disable_shutdown = 0;
	disable_warning = 0;

	(void) strlcpy(shutdown_cmd, SHUTDOWN_CMD, sizeof (shutdown_cmd));
	(void) strlcpy(devfsadm_cmd, DEVFSADM_CMD, sizeof (devfsadm_cmd));
	(void) strlcpy(fru_devfsadm_cmd, FRU_DEVFSADM_CMD,
	    sizeof (fru_devfsadm_cmd));
	envd_cpu_fan.forced_speed = -1;
	envd_system_fan.forced_speed = -1;

	(void) memcpy(&cpu0_die_thresh, &cpu_die_thresh_default,
	    sizeof (cpu_die_thresh_default));
	(void) memcpy(&cpu0_amb_thresh, &cpu_amb_thresh_default,
	    sizeof (cpu_amb_thresh_default));
	(void) memcpy(&cpu1_die_thresh, &cpu_die_thresh_default,
	    sizeof (cpu_die_thresh_default));
	(void) memcpy(&cpu1_amb_thresh, &cpu_amb_thresh_default,
	    sizeof (cpu_amb_thresh_default));

	if ((valp = getenv("SUNW_piclenvd_debug")) != NULL) {
		val = strtol(valp, &endp, 0);
		if (strtok(endp, tokdel) == NULL)
			env_debug = val;
	}

	/*
	 * Create a thread to monitor temperature and control fan
	 * speed.
	 */
	if (envthr_created == B_FALSE && pthread_create(&envthr_tid,
	    &thr_attr, envthr, (void *)NULL) != 0) {
		envd_close_fans();
		envd_close_sensors();
		envd_close_pm();
		envd_log(LOG_CRIT, ENV_THREAD_CREATE_FAILED);
		return (-1);
	}
	envthr_created = B_TRUE;

	/*
	 * Create a thread to monitor PM state
	 */
	if (pmthr_exists == B_FALSE) {
		if (pm_fd == -1 || pthread_create(&pmthr_tid, &thr_attr,
		    pmthr, (void *)NULL) != 0) {
			envd_log(LOG_CRIT, PM_THREAD_CREATE_FAILED);
		} else
			pmthr_exists = B_TRUE;
	}
	return (0);
}

/*
 * Callback function used by ptree_walk_tree_by_class for the cpu class
 */
static int
cb_cpu(picl_nodehdl_t nodeh, void *args)
{
	sensor_pmdev_t		*pmdevp;
	int			err;
	ptree_propinfo_t	pinfo;
	picl_prophdl_t		proph;
	size_t			psize;
	int			id;

	/* Get CPU's ID, it is an int */
	err = ptree_get_propval_by_name(nodeh, PICL_PROP_ID, &id, sizeof (int));
	if (err != PICL_SUCCESS)
		return (PICL_WALK_CONTINUE);

	/* Get the pmdevp for the CPU */
	pmdevp = sensor_pmdevs;
	while (pmdevp->sensor_id != -1) {
		if (id == pmdevp->sensor_id)
			break;
		pmdevp++;
	}

	/* Return if didn't find the pmdevp for the cpu id */
	if (pmdevp->sensor_id == -1)
		return (PICL_WALK_CONTINUE);

	/* Get the devfs-path property */
	err = ptree_get_prop_by_name(nodeh, PICL_PROP_DEVFS_PATH, &proph);
	if (err != PICL_SUCCESS)
		return (PICL_WALK_CONTINUE);

	err = ptree_get_propinfo(proph, &pinfo);
	if ((err != PICL_SUCCESS) ||
	    (pinfo.piclinfo.type != PICL_PTYPE_CHARSTRING))
		return (PICL_WALK_CONTINUE);

	psize = pinfo.piclinfo.size;
	pmdevp->pmdev_name = malloc(psize);
	if (pmdevp->pmdev_name == NULL)
		return (PICL_WALK_CONTINUE);

	err = ptree_get_propval(proph, pmdevp->pmdev_name, psize);
	if (err != PICL_SUCCESS)
		return (PICL_WALK_CONTINUE);

	return (PICL_WALK_CONTINUE);
}

/*
 * Find the CPU's in the picl tree, set the devfs-path for pmdev_name
 */
static void
setup_pmdev_names()
{
	picl_nodehdl_t	plath;
	int		err;

	err = ptree_get_node_by_path(PLATFORM_PATH, &plath);
	if (err != PICL_SUCCESS)
		return;

	err = ptree_walk_tree_by_class(plath, PICL_CLASS_CPU, NULL, cb_cpu);
}


static void
piclenvd_register(void)
{
	picld_plugin_register(&my_reg_info);
}

static void
piclenvd_init(void)
{
	/*
	 * Setup the names for the pm sensors, we do it just the first time
	 */
	if (pmdev_names_init == B_FALSE) {
		(void) setup_pmdev_names();
		pmdev_names_init = B_TRUE;
	}

	/*
	 * Start environmental monitor/threads
	 */
	(void) pthread_rwlock_wrlock(&envd_rwlock);
	if (envd_setup() != 0) {
		(void) pthread_rwlock_unlock(&envd_rwlock);
		envd_log(LOG_CRIT, ENVD_PLUGIN_INIT_FAILED);
		return;
	}
	(void) pthread_rwlock_unlock(&envd_rwlock);

	/*
	 * Now setup/populate PICL tree
	 */
	env_picl_setup();
}

static void
piclenvd_fini(void)
{
	/*
	 * Delete the lpm device list. After this the lpm information
	 * will not be used in determining the fan speed, till the lpm
	 * device information is initialized by setup_lpm_devices called
	 * by envd_setup.
	 */
	delete_lpm_devices();

	/*
	 * Invoke env_picl_destroy() to remove any PICL nodes/properties
	 * (including volatile properties) we created. Once this call
	 * returns, there can't be any more calls from the PICL framework
	 * to get current temperature or fan speed.
	 */
	env_picl_destroy();

	/*
	 * Since this is a critical plug-in, we know that it won't be
	 * unloaded and will be reinited again unless picld process is
	 * going away. Therefore, it's okay to let "envthr" and "pmthr"
	 * continue so that we can monitor the environment during SIGHUP
	 * handling also.
	 */
}

/*VARARGS2*/
void
envd_log(int pri, const char *fmt, ...)
{
	va_list	ap;

	va_start(ap, fmt);
	vsyslog(pri, fmt, ap);
	va_end(ap);
}

#ifdef __lint
/*
 * Redefine sigwait to posix style external declaration so that LINT
 * does not check against libc version of sigwait() and complain as
 * it uses different number of arguments.
 */
#define	sigwait	my_posix_sigwait
extern int my_posix_sigwait(const sigset_t *set, int *sig);
#endif

/*
 * sleep() in libpthread gets affected by time being set back, hence
 * can cause the "envthr" not to wakeup for extended duration. For
 * now, we implement our own sleep() routine below using alarm().
 * This will work only if SIGALRM is masked off in all other threads.
 * Note that SIGALRM signal is masked off in the main thread, hence
 * in all threads, including the envthr, the one calling this routine.
 *
 * Note that SIGALRM and alarm() can't be used by any other thread
 * in this manner.
 */

static unsigned int
envd_sleep(unsigned int sleep_tm)
{
	int  		sig;
	unsigned int	unslept;
	sigset_t	alrm_mask;

	if (sleep_tm == 0)
		return (0);

	(void) sigemptyset(&alrm_mask);
	(void) sigaddset(&alrm_mask, SIGALRM);

	(void) alarm(sleep_tm);
	(void) sigwait(&alrm_mask, &sig);

	unslept = alarm(0);
	return (unslept);
}