Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*	$NetBSD: sysmon_envsys.c,v 1.144.4.1 2020/06/07 16:40:00 martin Exp $	*/

/*-
 * Copyright (c) 2007, 2008 Juan Romero Pardines.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*-
 * Copyright (c) 2000 Zembu Labs, Inc.
 * All rights reserved.
 *
 * Author: Jason R. Thorpe <thorpej@zembu.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Zembu Labs, Inc.
 * 4. Neither the name of Zembu Labs nor the names of its employees may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ZEMBU LABS, INC. ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WAR-
 * RANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DIS-
 * CLAIMED.  IN NO EVENT SHALL ZEMBU LABS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Environmental sensor framework for sysmon, exported to userland
 * with proplib(3).
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: sysmon_envsys.c,v 1.144.4.1 2020/06/07 16:40:00 martin Exp $");

#include <sys/param.h>
#include <sys/types.h>
#include <sys/conf.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/mutex.h>
#include <sys/kmem.h>
#include <sys/rndsource.h>
#include <sys/module.h>
#include <sys/once.h>

#include <dev/sysmon/sysmonvar.h>
#include <dev/sysmon/sysmon_envsysvar.h>
#include <dev/sysmon/sysmon_taskq.h>

kmutex_t sme_global_mtx;

prop_dictionary_t sme_propd;

struct sysmon_envsys_lh sysmon_envsys_list;

static uint32_t sysmon_envsys_next_sensor_index;
static struct sysmon_envsys *sysmon_envsys_find_40(u_int);

static void sysmon_envsys_destroy_plist(prop_array_t);
static void sme_remove_userprops(void);
static int sme_add_property_dictionary(struct sysmon_envsys *, prop_array_t,
				       prop_dictionary_t);
static sme_event_drv_t * sme_add_sensor_dictionary(struct sysmon_envsys *,
	prop_array_t, prop_dictionary_t, envsys_data_t *);
static void sme_initial_refresh(void *);
static uint32_t sme_get_max_value(struct sysmon_envsys *,
     bool (*)(const envsys_data_t*), bool);

MODULE(MODULE_CLASS_DRIVER, sysmon_envsys, "sysmon,sysmon_taskq,sysmon_power");

static struct sysmon_opvec sysmon_envsys_opvec = {    
        sysmonopen_envsys, sysmonclose_envsys, sysmonioctl_envsys,
        NULL, NULL, NULL
};

ONCE_DECL(once_envsys);

static int
sme_preinit(void)
{

	LIST_INIT(&sysmon_envsys_list);
	mutex_init(&sme_global_mtx, MUTEX_DEFAULT, IPL_NONE);
	sme_propd = prop_dictionary_create();

	return 0;
}

/*
 * sysmon_envsys_init:
 *
 * 	+ Initialize global mutex, dictionary and the linked list.
 */
int
sysmon_envsys_init(void)
{
	int error;

	(void)RUN_ONCE(&once_envsys, sme_preinit);

	error = sysmon_attach_minor(SYSMON_MINOR_ENVSYS, &sysmon_envsys_opvec);

	return error;
}

int
sysmon_envsys_fini(void)
{
	int error;

	if ( ! LIST_EMPTY(&sysmon_envsys_list))
		error = EBUSY;
	else
		error = sysmon_attach_minor(SYSMON_MINOR_ENVSYS, NULL);

	if (error == 0)
		mutex_destroy(&sme_global_mtx);

	// XXX: prop_dictionary ???

	return error;
}

/*
 * sysmonopen_envsys:
 *
 *	+ Open the system monitor device.
 */
int
sysmonopen_envsys(dev_t dev, int flag, int mode, struct lwp *l)
{
	return 0;
}

/*
 * sysmonclose_envsys:
 *
 *	+ Close the system monitor device.
 */
int
sysmonclose_envsys(dev_t dev, int flag, int mode, struct lwp *l)
{
	return 0;
}

/*
 * sysmonioctl_envsys:
 *
 *	+ Perform a sysmon envsys control request.
 */
int
sysmonioctl_envsys(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
{
	struct sysmon_envsys *sme = NULL;
	int error = 0;
	u_int oidx;

	switch (cmd) {
	/*
	 * To update the global dictionary with latest data from devices.
	 */
	case ENVSYS_GETDICTIONARY:
	    {
		struct plistref *plist = (struct plistref *)data;

		/*
		 * Update dictionaries on all sysmon envsys devices
		 * registered.
		 */		
		mutex_enter(&sme_global_mtx);
		LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
			sysmon_envsys_acquire(sme, false);
			error = sme_update_dictionary(sme);
			if (error) {
				DPRINTF(("%s: sme_update_dictionary, "
				    "error=%d\n", __func__, error));
				sysmon_envsys_release(sme, false);
				mutex_exit(&sme_global_mtx);
				return error;
			}
			sysmon_envsys_release(sme, false);
		}
		mutex_exit(&sme_global_mtx);
		/*
		 * Copy global dictionary to userland.
		 */
		error = prop_dictionary_copyout_ioctl(plist, cmd, sme_propd);
		break;
	    }
	/*
	 * To set properties on multiple devices.
	 */
	case ENVSYS_SETDICTIONARY:
	    {
		const struct plistref *plist = (const struct plistref *)data;
		prop_dictionary_t udict;
		prop_object_iterator_t iter, iter2;
		prop_object_t obj, obj2;
		prop_array_t array_u, array_k;
		const char *devname = NULL;

		if ((flag & FWRITE) == 0)
			return EPERM;

		/*
		 * Get dictionary from userland.
		 */
		error = prop_dictionary_copyin_ioctl(plist, cmd, &udict);
		if (error) {
			DPRINTF(("%s: copyin_ioctl error=%d\n",
			    __func__, error));
			break;
		}

		iter = prop_dictionary_iterator(udict);
		if (!iter) {
			prop_object_release(udict);
			return ENOMEM;
		}

		/*
		 * Iterate over the userland dictionary and process
		 * the list of devices.
		 */
		while ((obj = prop_object_iterator_next(iter))) {
			array_u = prop_dictionary_get_keysym(udict, obj);
			if (prop_object_type(array_u) != PROP_TYPE_ARRAY) {
				prop_object_iterator_release(iter);
				prop_object_release(udict);
				return EINVAL;
			}
			
			devname = prop_dictionary_keysym_cstring_nocopy(obj);
			DPRINTF(("%s: processing the '%s' array requests\n",
			    __func__, devname));

			/*
			 * find the correct sme device.
			 */
			sme = sysmon_envsys_find(devname);
			if (!sme) {
				DPRINTF(("%s: NULL sme\n", __func__));
				prop_object_iterator_release(iter);
				prop_object_release(udict);
				return EINVAL;
			}

			/*
			 * Find the correct array object with the string
			 * supplied by the userland dictionary.
			 */
			array_k = prop_dictionary_get(sme_propd, devname);
			if (prop_object_type(array_k) != PROP_TYPE_ARRAY) {
				DPRINTF(("%s: array device failed\n",
				    __func__));
				sysmon_envsys_release(sme, false);
				prop_object_iterator_release(iter);
				prop_object_release(udict);
				return EINVAL;
			}

			iter2 = prop_array_iterator(array_u);
			if (!iter2) {
				sysmon_envsys_release(sme, false);
				prop_object_iterator_release(iter);
				prop_object_release(udict);
				return ENOMEM;
			}

			/*
			 * Iterate over the array of dictionaries to
			 * process the list of sensors and properties.
			 */
			while ((obj2 = prop_object_iterator_next(iter2))) {
				/* 
				 * do the real work now.
				 */
				error = sme_userset_dictionary(sme,
							       obj2,
							       array_k);
				if (error) {
					sysmon_envsys_release(sme, false);
					prop_object_iterator_release(iter2);
					prop_object_iterator_release(iter);
					prop_object_release(udict);
					return error;
				}
			}

			sysmon_envsys_release(sme, false);
			prop_object_iterator_release(iter2);
		}

		prop_object_iterator_release(iter);
		prop_object_release(udict);
		break;
	    }
	/*
	 * To remove all properties from all devices registered.
	 */
	case ENVSYS_REMOVEPROPS:
	    {
		const struct plistref *plist = (const struct plistref *)data;
		prop_dictionary_t udict;
		prop_object_t obj;

		if ((flag & FWRITE) == 0)
			return EPERM;

		error = prop_dictionary_copyin_ioctl(plist, cmd, &udict);
		if (error) {
			DPRINTF(("%s: copyin_ioctl error=%d\n",
			    __func__, error));
			break;
		}

		obj = prop_dictionary_get(udict, "envsys-remove-props");
		if (!obj || !prop_bool_true(obj)) {
			DPRINTF(("%s: invalid 'envsys-remove-props'\n",
			     __func__));
			return EINVAL;
		}

		prop_object_release(udict);
		sme_remove_userprops();

		break;
	    }
	/*
	 * Compatibility ioctls with the old interface, only implemented
	 * ENVSYS_GTREDATA and ENVSYS_GTREINFO; enough to make old
	 * applications work.
	 */
	case ENVSYS_GTREDATA:
	    {
		struct envsys_tre_data *tred = (void *)data;
		envsys_data_t *edata = NULL;
		bool found = false;

		tred->validflags = 0;

		sme = sysmon_envsys_find_40(tred->sensor);
		if (!sme)
			break;

		oidx = tred->sensor;
		tred->sensor = SME_SENSOR_IDX(sme, tred->sensor);

		DPRINTFOBJ(("%s: sensor=%d oidx=%d dev=%s nsensors=%d\n",
		    __func__, tred->sensor, oidx, sme->sme_name,
		    sme->sme_nsensors));

		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
			if (edata->sensor == tred->sensor) {
				found = true;
				break;
			}
		}

		if (!found) {
			sysmon_envsys_release(sme, false);
			error = ENODEV;
			break;
		}

		if (tred->sensor < sme->sme_nsensors) {
			if ((sme->sme_flags & SME_POLL_ONLY) == 0) {
				mutex_enter(&sme->sme_mtx);
				sysmon_envsys_refresh_sensor(sme, edata);
				mutex_exit(&sme->sme_mtx);
			}

			/* 
			 * copy required values to the old interface.
			 */
			tred->sensor = edata->sensor;
			tred->cur.data_us = edata->value_cur;
			tred->cur.data_s = edata->value_cur;
			tred->max.data_us = edata->value_max;
			tred->max.data_s = edata->value_max;
			tred->min.data_us = edata->value_min;
			tred->min.data_s = edata->value_min;
			tred->avg.data_us = 0;
			tred->avg.data_s = 0;
			if (edata->units == ENVSYS_BATTERY_CHARGE)
				tred->units = ENVSYS_INDICATOR;
			else
				tred->units = edata->units;

			tred->validflags |= ENVSYS_FVALID;
			tred->validflags |= ENVSYS_FCURVALID;

			if (edata->flags & ENVSYS_FPERCENT) {
				tred->validflags |= ENVSYS_FMAXVALID;
				tred->validflags |= ENVSYS_FFRACVALID;
			}

			if (edata->state == ENVSYS_SINVALID) {
				tred->validflags &= ~ENVSYS_FCURVALID;
				tred->cur.data_us = tred->cur.data_s = 0;
			}

			DPRINTFOBJ(("%s: sensor=%s tred->cur.data_s=%d\n",
			    __func__, edata->desc, tred->cur.data_s));
			DPRINTFOBJ(("%s: tred->validflags=%d tred->units=%d"
			    " tred->sensor=%d\n", __func__, tred->validflags,
			    tred->units, tred->sensor));
		}
		tred->sensor = oidx;
		sysmon_envsys_release(sme, false);

		break;
	    }
	case ENVSYS_GTREINFO:
	    {
		struct envsys_basic_info *binfo = (void *)data;
		envsys_data_t *edata = NULL;
		bool found = false;

		binfo->validflags = 0;

		sme = sysmon_envsys_find_40(binfo->sensor);
		if (!sme)
			break;

		oidx = binfo->sensor;
		binfo->sensor = SME_SENSOR_IDX(sme, binfo->sensor);

		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
			if (edata->sensor == binfo->sensor) {
				found = true;
				break;
			}
		}

		if (!found) {
			sysmon_envsys_release(sme, false);
			error = ENODEV;
			break;
		}

		binfo->validflags |= ENVSYS_FVALID;

		if (binfo->sensor < sme->sme_nsensors) {
			if (edata->units == ENVSYS_BATTERY_CHARGE)
				binfo->units = ENVSYS_INDICATOR;
			else
				binfo->units = edata->units;

			/*
			 * previously, the ACPI sensor names included the
			 * device name. Include that in compatibility code.
			 */
			if (strncmp(sme->sme_name, "acpi", 4) == 0)
				(void)snprintf(binfo->desc, sizeof(binfo->desc),
				    "%s %s", sme->sme_name, edata->desc);
			else
				(void)strlcpy(binfo->desc, edata->desc,
				    sizeof(binfo->desc));
		}

		DPRINTFOBJ(("%s: binfo->units=%d binfo->validflags=%d\n",
		    __func__, binfo->units, binfo->validflags));
		DPRINTFOBJ(("%s: binfo->desc=%s binfo->sensor=%d\n",
		    __func__, binfo->desc, binfo->sensor));

		binfo->sensor = oidx;
		sysmon_envsys_release(sme, false);

		break;
	    }
	default:
		error = ENOTTY;
		break;
	}

	return error;
}

/*
 * sysmon_envsys_create:
 * 
 * 	+ Allocates a new sysmon_envsys object and initializes the
 * 	  stuff for sensors and events.
 */
struct sysmon_envsys *
sysmon_envsys_create(void)
{
	struct sysmon_envsys *sme;

	CTASSERT(SME_CALLOUT_INVALID == 0);

	sme = kmem_zalloc(sizeof(*sme), KM_SLEEP);
	TAILQ_INIT(&sme->sme_sensors_list);
	LIST_INIT(&sme->sme_events_list);
	mutex_init(&sme->sme_mtx, MUTEX_DEFAULT, IPL_NONE);
	mutex_init(&sme->sme_work_mtx, MUTEX_DEFAULT, IPL_NONE);
	cv_init(&sme->sme_condvar, "sme_wait");

	return sme;
}

/*
 * sysmon_envsys_destroy:
 *
 * 	+ Removes all sensors from the tail queue, destroys the callout
 * 	  and frees the sysmon_envsys object.
 */
void
sysmon_envsys_destroy(struct sysmon_envsys *sme)
{
	envsys_data_t *edata;

	KASSERT(sme != NULL);

	while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
		edata = TAILQ_FIRST(&sme->sme_sensors_list);
		TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
	}
	mutex_destroy(&sme->sme_mtx);
	mutex_destroy(&sme->sme_work_mtx);
	cv_destroy(&sme->sme_condvar);
	kmem_free(sme, sizeof(*sme));
}

/*
 * sysmon_envsys_sensor_attach:
 *
 * 	+ Attaches a sensor into a sysmon_envsys device checking that units
 * 	  is set to a valid type and description is unique and not empty.
 */
int
sysmon_envsys_sensor_attach(struct sysmon_envsys *sme, envsys_data_t *edata)
{
	const struct sme_descr_entry *sdt_units;
	envsys_data_t *oedata;

	KASSERT(sme != NULL || edata != NULL);

	/* 
	 * Find the correct units for this sensor.
	 */
	sdt_units = sme_find_table_entry(SME_DESC_UNITS, edata->units);
	if (sdt_units == NULL || sdt_units->type == -1)
		return EINVAL;

	/*
	 * Check that description is not empty or duplicate.
	 */
	if (strlen(edata->desc) == 0)
		return EINVAL;

	mutex_enter(&sme->sme_mtx);
	sysmon_envsys_acquire(sme, true);
	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
		if (strcmp(oedata->desc, edata->desc) == 0) {
			sysmon_envsys_release(sme, true);
			mutex_exit(&sme->sme_mtx);
			return EEXIST;
		}
	}
	/*
	 * Ok, the sensor has been added into the device queue.
	 */
	TAILQ_INSERT_TAIL(&sme->sme_sensors_list, edata, sensors_head);

	/*
	 * Give the sensor an index position.
	 */
	edata->sensor = sme->sme_nsensors;
	sme->sme_nsensors++;
	sysmon_envsys_release(sme, true);
	mutex_exit(&sme->sme_mtx);

	DPRINTF(("%s: attached #%d (%s), units=%d (%s)\n",
	    __func__, edata->sensor, edata->desc,
	    sdt_units->type, sdt_units->desc));

	return 0;
}

/*
 * sysmon_envsys_sensor_detach:
 *
 * 	+ Detachs a sensor from a sysmon_envsys device and decrements the
 * 	  sensors count on success.
 */
int
sysmon_envsys_sensor_detach(struct sysmon_envsys *sme, envsys_data_t *edata)
{
	envsys_data_t *oedata;
	bool found = false;
	bool destroy = false;

	KASSERT(sme != NULL || edata != NULL);

	/*
	 * Check the sensor is already on the list.
	 */
	mutex_enter(&sme->sme_mtx);
	sysmon_envsys_acquire(sme, true);
	TAILQ_FOREACH(oedata, &sme->sme_sensors_list, sensors_head) {
		if (oedata->sensor == edata->sensor) {
			found = true;
			break;
		}
	}

	if (!found) {
		sysmon_envsys_release(sme, true);
		mutex_exit(&sme->sme_mtx);
		return EINVAL;
	}

	/*
	 * remove it, unhook from rnd(4), and decrement the sensors count.
	 */
	if (oedata->flags & ENVSYS_FHAS_ENTROPY)
		rnd_detach_source(&oedata->rnd_src);
	sme_event_unregister_sensor(sme, edata);
	if (LIST_EMPTY(&sme->sme_events_list)) {
		if (sme->sme_callout_state == SME_CALLOUT_READY)
			sme_events_halt_callout(sme);
		destroy = true;
	}
	TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
	sme->sme_nsensors--;
	sysmon_envsys_release(sme, true);
	mutex_exit(&sme->sme_mtx);

	if (destroy)
		sme_events_destroy(sme);

	return 0;
}


/*
 * sysmon_envsys_register:
 *
 *	+ Register a sysmon envsys device.
 *	+ Create array of dictionaries for a device.
 */
int
sysmon_envsys_register(struct sysmon_envsys *sme)
{
	struct sme_evdrv {
		SLIST_ENTRY(sme_evdrv) evdrv_head;
		sme_event_drv_t *evdrv;
	};
	SLIST_HEAD(, sme_evdrv) sme_evdrv_list;
	struct sme_evdrv *evdv = NULL;
	struct sysmon_envsys *lsme;
	prop_array_t array = NULL;
	prop_dictionary_t dict, dict2;
	envsys_data_t *edata = NULL;
	sme_event_drv_t *this_evdrv;
	int nevent;
	int error = 0;
	char rnd_name[sizeof(edata->rnd_src.name)];

	KASSERT(sme != NULL);
	KASSERT(sme->sme_name != NULL);

	(void)RUN_ONCE(&once_envsys, sme_preinit);

	/*
	 * Check if requested sysmon_envsys device is valid
	 * and does not exist already in the list.
	 */
	mutex_enter(&sme_global_mtx);
	LIST_FOREACH(lsme, &sysmon_envsys_list, sme_list) {
	       if (strcmp(lsme->sme_name, sme->sme_name) == 0) {
			mutex_exit(&sme_global_mtx);
			return EEXIST;
	       }
	}
	mutex_exit(&sme_global_mtx);

	/*
	 * sanity check: if SME_DISABLE_REFRESH is not set,
	 * the sme_refresh function callback must be non NULL.
	 */
	if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
		if (!sme->sme_refresh)
			return EINVAL;

	/*
	 * If the list of sensors is empty, there's no point to continue...
	 */
	if (TAILQ_EMPTY(&sme->sme_sensors_list)) {
		DPRINTF(("%s: sensors list empty for %s\n", __func__,
		    sme->sme_name));
		return ENOTSUP;
	}

	/* 
	 * Initialize the singly linked list for driver events.
	 */
	SLIST_INIT(&sme_evdrv_list);

	array = prop_array_create();
	if (!array)
		return ENOMEM;

	/*
	 * Iterate over all sensors and create a dictionary per sensor.
	 * We must respect the order in which the sensors were added.
	 */
	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
		dict = prop_dictionary_create();
		if (!dict) {
			error = ENOMEM;
			goto out2;
		}

		/*
		 * Create all objects in sensor's dictionary.
		 */
		this_evdrv = sme_add_sensor_dictionary(sme, array,
						       dict, edata);
		if (this_evdrv) {
			evdv = kmem_zalloc(sizeof(*evdv), KM_SLEEP);
			evdv->evdrv = this_evdrv;
			SLIST_INSERT_HEAD(&sme_evdrv_list, evdv, evdrv_head);
		}
	}

	/* 
	 * If the array does not contain any object (sensor), there's
	 * no need to attach the driver.
	 */
	if (prop_array_count(array) == 0) {
		error = EINVAL;
		DPRINTF(("%s: empty array for '%s'\n", __func__,
		    sme->sme_name));
		goto out;
	}

	/*
	 * Add the dictionary for the global properties of this device.
	 */
	dict2 = prop_dictionary_create();
	if (!dict2) {
		error = ENOMEM;
		goto out;
	}

	error = sme_add_property_dictionary(sme, array, dict2);
	if (error) {
		prop_object_release(dict2);
		goto out;
	}

	/*
	 * Add the array into the global dictionary for the driver.
	 *
	 * <dict>
	 * 	<key>foo0</key>
	 * 	<array>
	 * 		...
	 */
	mutex_enter(&sme_global_mtx);
	if (!prop_dictionary_set(sme_propd, sme->sme_name, array)) {
		error = EINVAL;
		mutex_exit(&sme_global_mtx);
		DPRINTF(("%s: prop_dictionary_set for '%s'\n", __func__,
		    sme->sme_name));
		goto out;
	}

	/*
	 * Add the device into the list.
	 */
	LIST_INSERT_HEAD(&sysmon_envsys_list, sme, sme_list);
	sme->sme_fsensor = sysmon_envsys_next_sensor_index;
	sysmon_envsys_next_sensor_index += sme->sme_nsensors;
	mutex_exit(&sme_global_mtx);

out:
	/*
	 * No errors?  Make an initial data refresh if was requested,
	 * then register the events that were set in the driver.  Do
	 * the refresh first in case it is needed to establish the
	 * limits or max_value needed by some events.
	 */
	if (error == 0) {
		nevent = 0;

		/*
		 * Hook the sensor into rnd(4) entropy pool if requested
		 */
		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
			if (edata->flags & ENVSYS_FHAS_ENTROPY) {
				uint32_t rnd_type, rnd_flag = 0;
				size_t n;
				int tail = 1;

				snprintf(rnd_name, sizeof(rnd_name), "%s-%s",
				    sme->sme_name, edata->desc);
				n = strlen(rnd_name);
				/*
				 * 1) Remove trailing white space(s).
				 * 2) If space exist, replace it with '-'
				 */
				while (--n) {
					if (rnd_name[n] == ' ') {
						if (tail != 0)
							rnd_name[n] = '\0';
						else
							rnd_name[n] = '-';
					} else
						tail = 0;
				}
				rnd_flag |= RND_FLAG_COLLECT_TIME;
				rnd_flag |= RND_FLAG_ESTIMATE_TIME;

				switch (edata->units) {
				    case ENVSYS_STEMP:
				    case ENVSYS_SFANRPM:
				    case ENVSYS_INTEGER:
					rnd_type = RND_TYPE_ENV;
					rnd_flag |= RND_FLAG_COLLECT_VALUE;
					rnd_flag |= RND_FLAG_ESTIMATE_VALUE;
					break;
				    case ENVSYS_SVOLTS_AC:
				    case ENVSYS_SVOLTS_DC:
				    case ENVSYS_SOHMS:
				    case ENVSYS_SWATTS:
				    case ENVSYS_SAMPS:
				    case ENVSYS_SWATTHOUR:
				    case ENVSYS_SAMPHOUR:
					rnd_type = RND_TYPE_POWER;
					rnd_flag |= RND_FLAG_COLLECT_VALUE;
					rnd_flag |= RND_FLAG_ESTIMATE_VALUE;
					break;
				    default:
					rnd_type = RND_TYPE_UNKNOWN;
					break;
				}
				rnd_attach_source(&edata->rnd_src, rnd_name,
				    rnd_type, rnd_flag);
			}
		}

		if (sme->sme_flags & SME_INIT_REFRESH) {
			sysmon_task_queue_sched(0, sme_initial_refresh, sme);
			DPRINTF(("%s: scheduled initial refresh for '%s'\n",
				__func__, sme->sme_name));
		}
		SLIST_FOREACH(evdv, &sme_evdrv_list, evdrv_head) {
			sysmon_task_queue_sched(0,
			    sme_event_drvadd, evdv->evdrv);
			nevent++;
		}
		DPRINTF(("%s: driver '%s' registered (nsens=%d nevent=%d)\n",
		    __func__, sme->sme_name, sme->sme_nsensors, nevent));
	}

out2:
	while (!SLIST_EMPTY(&sme_evdrv_list)) {
		evdv = SLIST_FIRST(&sme_evdrv_list);
		SLIST_REMOVE_HEAD(&sme_evdrv_list, evdrv_head);
		kmem_free(evdv, sizeof(*evdv));
	}
	if (!error)
		return 0;

	/*
	 * Ugh... something wasn't right; unregister all events and sensors
	 * previously assigned and destroy the array with all its objects.
	 */
	DPRINTF(("%s: failed to register '%s' (%d)\n", __func__,
	    sme->sme_name, error));

	sme_event_unregister_all(sme);
	while (!TAILQ_EMPTY(&sme->sme_sensors_list)) {
		edata = TAILQ_FIRST(&sme->sme_sensors_list);
		TAILQ_REMOVE(&sme->sme_sensors_list, edata, sensors_head);
	}
	sysmon_envsys_destroy_plist(array);
	return error;
}

/*
 * sysmon_envsys_destroy_plist:
 *
 * 	+ Remove all objects from the array of dictionaries that is
 * 	  created in a sysmon envsys device.
 */
static void
sysmon_envsys_destroy_plist(prop_array_t array)
{
	prop_object_iterator_t iter, iter2;
	prop_dictionary_t dict;
	prop_object_t obj;

	KASSERT(array != NULL);
	KASSERT(prop_object_type(array) == PROP_TYPE_ARRAY);

	DPRINTFOBJ(("%s: objects in array=%d\n", __func__,
	    prop_array_count(array)));

	iter = prop_array_iterator(array);
	if (!iter)
		return;

	while ((dict = prop_object_iterator_next(iter))) {
		KASSERT(prop_object_type(dict) == PROP_TYPE_DICTIONARY);
		iter2 = prop_dictionary_iterator(dict);
		if (!iter2)
			goto out;
		DPRINTFOBJ(("%s: iterating over dictionary\n", __func__));
		while ((obj = prop_object_iterator_next(iter2)) != NULL) {
			DPRINTFOBJ(("%s: obj=%s\n", __func__,
			    prop_dictionary_keysym_cstring_nocopy(obj)));
			prop_dictionary_remove(dict,
			    prop_dictionary_keysym_cstring_nocopy(obj));
			prop_object_iterator_reset(iter2);
		}
		prop_object_iterator_release(iter2);
		DPRINTFOBJ(("%s: objects in dictionary:%d\n",
		    __func__, prop_dictionary_count(dict)));
		prop_object_release(dict);
	}

out:
	prop_object_iterator_release(iter);
	prop_object_release(array);
}

/*
 * sysmon_envsys_unregister:
 *
 *	+ Unregister a sysmon envsys device.
 */
void
sysmon_envsys_unregister(struct sysmon_envsys *sme)
{
	prop_array_t array;
	struct sysmon_envsys *osme;
	envsys_data_t *edata;

	KASSERT(sme != NULL);

	/*
	 * Decrement global sensors counter and the first_sensor index
	 * for remaining devices in the list (only used for compatibility
	 * with previous API), and remove the device from the list.
	 */
	mutex_enter(&sme_global_mtx);
	sysmon_envsys_next_sensor_index -= sme->sme_nsensors;
	LIST_FOREACH(osme, &sysmon_envsys_list, sme_list) {
		if (osme->sme_fsensor >= sme->sme_fsensor)
			osme->sme_fsensor -= sme->sme_nsensors;
	}
	LIST_REMOVE(sme, sme_list);
	mutex_exit(&sme_global_mtx);

	while ((edata = TAILQ_FIRST(&sme->sme_sensors_list)) != NULL) {
		sysmon_envsys_sensor_detach(sme, edata);
	}

	/*
	 * Unregister all events associated with device.
	 */
	sme_event_unregister_all(sme);

	/*
	 * Remove the device (and all its objects) from the global dictionary.
	 */
	array = prop_dictionary_get(sme_propd, sme->sme_name);
	if (array && prop_object_type(array) == PROP_TYPE_ARRAY) {
		mutex_enter(&sme_global_mtx);
		prop_dictionary_remove(sme_propd, sme->sme_name);
		mutex_exit(&sme_global_mtx);
		sysmon_envsys_destroy_plist(array);
	}
	/*
	 * And finally destroy the sysmon_envsys object.
	 */
	sysmon_envsys_destroy(sme);
}

/*
 * sysmon_envsys_find:
 *
 *	+ Find a sysmon envsys device and mark it as busy
 *	  once it's available.
 */
struct sysmon_envsys *
sysmon_envsys_find(const char *name)
{
	struct sysmon_envsys *sme;

	mutex_enter(&sme_global_mtx);
	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
		if (strcmp(sme->sme_name, name) == 0) {
			sysmon_envsys_acquire(sme, false);
			break;
		}
	}
	mutex_exit(&sme_global_mtx);

	return sme;
}

/*
 * Compatibility function with the old API.
 */
struct sysmon_envsys *
sysmon_envsys_find_40(u_int idx)
{
	struct sysmon_envsys *sme;

	mutex_enter(&sme_global_mtx);
	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
		if (idx >= sme->sme_fsensor &&
	    	    idx < (sme->sme_fsensor + sme->sme_nsensors)) {
			sysmon_envsys_acquire(sme, false);
			break;
		}
	}
	mutex_exit(&sme_global_mtx);

	return sme;
}

/*
 * sysmon_envsys_acquire:
 *
 * 	+ Wait until a sysmon envsys device is available and mark
 * 	  it as busy.
 */
void
sysmon_envsys_acquire(struct sysmon_envsys *sme, bool locked)
{
	KASSERT(sme != NULL);

	if (locked) {
		while (sme->sme_flags & SME_FLAG_BUSY)
			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
		sme->sme_flags |= SME_FLAG_BUSY;
	} else {
		mutex_enter(&sme->sme_mtx);
		while (sme->sme_flags & SME_FLAG_BUSY)
			cv_wait(&sme->sme_condvar, &sme->sme_mtx);
		sme->sme_flags |= SME_FLAG_BUSY;
		mutex_exit(&sme->sme_mtx);
	}
}

/*
 * sysmon_envsys_release:
 *
 * 	+ Unmark a sysmon envsys device as busy, and notify
 * 	  waiters.
 */
void
sysmon_envsys_release(struct sysmon_envsys *sme, bool locked)
{
	KASSERT(sme != NULL);

	if (locked) {
		sme->sme_flags &= ~SME_FLAG_BUSY;
		cv_broadcast(&sme->sme_condvar);
	} else {
		mutex_enter(&sme->sme_mtx);
		sme->sme_flags &= ~SME_FLAG_BUSY;
		cv_broadcast(&sme->sme_condvar);
		mutex_exit(&sme->sme_mtx);
	}
}

/*
 * sme_initial_refresh:
 * 	
 * 	+ Do an initial refresh of the sensors in a device just after
 * 	  interrupts are enabled in the autoconf(9) process.
 *
 */
static void
sme_initial_refresh(void *arg)
{
	struct sysmon_envsys *sme = arg;
	envsys_data_t *edata;

	mutex_enter(&sme->sme_mtx);
	sysmon_envsys_acquire(sme, true);
	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head)
		sysmon_envsys_refresh_sensor(sme, edata);
	sysmon_envsys_release(sme, true);
	mutex_exit(&sme->sme_mtx);
}

/*
 * sme_sensor_dictionary_get:
 *
 * 	+ Returns a dictionary of a device specified by its index
 * 	  position.
 */
prop_dictionary_t
sme_sensor_dictionary_get(prop_array_t array, const char *index)
{
	prop_object_iterator_t iter;
	prop_dictionary_t dict;
	prop_object_t obj;

	KASSERT(array != NULL || index != NULL);

	iter = prop_array_iterator(array);
	if (!iter)
		return NULL;

	while ((dict = prop_object_iterator_next(iter))) {
		obj = prop_dictionary_get(dict, "index");
		if (prop_string_equals_cstring(obj, index))
			break;
	}

	prop_object_iterator_release(iter);
	return dict;
}

/*
 * sme_remove_userprops:
 *
 * 	+ Remove all properties from all devices that were set by
 * 	  the ENVSYS_SETDICTIONARY ioctl.
 */
static void
sme_remove_userprops(void)
{
	struct sysmon_envsys *sme;
	prop_array_t array;
	prop_dictionary_t sdict;
	envsys_data_t *edata = NULL;
	char tmp[ENVSYS_DESCLEN];
	char rnd_name[sizeof(edata->rnd_src.name)];
	sysmon_envsys_lim_t lims;
	const struct sme_descr_entry *sdt_units;
	uint32_t props;
	int ptype;

	mutex_enter(&sme_global_mtx);
	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
		sysmon_envsys_acquire(sme, false);
		array = prop_dictionary_get(sme_propd, sme->sme_name);

		TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
			(void)snprintf(tmp, sizeof(tmp), "sensor%d",
				       edata->sensor);
			sdict = sme_sensor_dictionary_get(array, tmp);
			KASSERT(sdict != NULL);

			ptype = 0;
			if (edata->upropset & PROP_BATTCAP) {
				prop_dictionary_remove(sdict,
				    "critical-capacity");
				ptype = PENVSYS_EVENT_CAPACITY;
			}

			if (edata->upropset & PROP_BATTWARN) {
				prop_dictionary_remove(sdict,
				    "warning-capacity");
				ptype = PENVSYS_EVENT_CAPACITY;
			}

			if (edata->upropset & PROP_BATTHIGH) {
				prop_dictionary_remove(sdict,
				    "high-capacity");
				ptype = PENVSYS_EVENT_CAPACITY;
			}

			if (edata->upropset & PROP_BATTMAX) {
				prop_dictionary_remove(sdict,
				    "maximum-capacity");
				ptype = PENVSYS_EVENT_CAPACITY;
			}
			if (edata->upropset & PROP_WARNMAX) {
				prop_dictionary_remove(sdict, "warning-max");
				ptype = PENVSYS_EVENT_LIMITS;
			}

			if (edata->upropset & PROP_WARNMIN) {
				prop_dictionary_remove(sdict, "warning-min");
				ptype = PENVSYS_EVENT_LIMITS;
			}

			if (edata->upropset & PROP_CRITMAX) {
				prop_dictionary_remove(sdict, "critical-max");
				ptype = PENVSYS_EVENT_LIMITS;
			}

			if (edata->upropset & PROP_CRITMIN) {
				prop_dictionary_remove(sdict, "critical-min");
				ptype = PENVSYS_EVENT_LIMITS;
			}
			if (edata->upropset & PROP_RFACT) {
				(void)sme_sensor_upint32(sdict, "rfact", 0);
				edata->rfact = 0;
			}

			if (edata->upropset & PROP_DESC)
				(void)sme_sensor_upstring(sdict,
			  	    "description", edata->desc);

			if (ptype == 0)
				continue;

			/*
			 * If there were any limit values removed, we
			 * need to revert to initial limits.
			 *
			 * First, tell the driver that we need it to 
			 * restore any h/w limits which may have been 
			 * changed to stored, boot-time values.
			 */
			if (sme->sme_set_limits) {
				DPRINTF(("%s: reset limits for %s %s\n",
					__func__, sme->sme_name, edata->desc));
				(*sme->sme_set_limits)(sme, edata, NULL, NULL);
			}

			/*
			 * Next, we need to retrieve those initial limits.
			 */
			props = 0;
			edata->upropset &= ~PROP_LIMITS;
			if (sme->sme_get_limits) {
				DPRINTF(("%s: retrieve limits for %s %s\n",
					__func__, sme->sme_name, edata->desc));
				lims = edata->limits;
				(*sme->sme_get_limits)(sme, edata, &lims,
						       &props);
			}

			/*
			 * If the sensor is providing entropy data,
			 * get rid of the rndsrc;  we'll provide a new
			 * one shortly.
			 */
			if (edata->flags & ENVSYS_FHAS_ENTROPY)
				rnd_detach_source(&edata->rnd_src);

			/*
			 * Remove the old limits event, if any
			 */
			sme_event_unregister(sme, edata->desc,
			    PENVSYS_EVENT_LIMITS);

			/*
			 * Create and install a new event (which will
			 * update the dictionary) with the correct
			 * units.
			 */
			sdt_units = sme_find_table_entry(SME_DESC_UNITS,
			    edata->units);

			if (props & PROP_LIMITS) {
				DPRINTF(("%s: install limits for %s %s\n",
					__func__, sme->sme_name, edata->desc));

				sme_event_register(sdict, edata, sme,
				    &lims, props, PENVSYS_EVENT_LIMITS,
				    sdt_units->crittype);
			}

			/* Finally, if the sensor provides entropy,
			 * create an additional event entry and attach
			 * the rndsrc
			 */
			if (edata->flags & ENVSYS_FHAS_ENTROPY) {
				sme_event_register(sdict, edata, sme,
				    &lims, props, PENVSYS_EVENT_NULL,
				    sdt_units->crittype);
				snprintf(rnd_name, sizeof(rnd_name), "%s-%s",
				    sme->sme_name, edata->desc);
				rnd_attach_source(&edata->rnd_src, rnd_name,
				    RND_TYPE_ENV, RND_FLAG_COLLECT_VALUE|
						  RND_FLAG_COLLECT_TIME|
						  RND_FLAG_ESTIMATE_VALUE|
						  RND_FLAG_ESTIMATE_TIME);
			}
		}

		/*
		 * Restore default timeout value.
		 */
		sme->sme_events_timeout = SME_EVENTS_DEFTIMEOUT;

		/*
		 * Note that we need to hold the sme_mtx while calling
		 * sme_schedule_callout().  Thus to avoid dropping,
		 * reacquiring, and dropping it again, we just tell
		 * sme_envsys_release() that the mutex is already owned.
		 */
		mutex_enter(&sme->sme_mtx);
		sme_schedule_callout(sme);
		sysmon_envsys_release(sme, true);
		mutex_exit(&sme->sme_mtx);
	}
	mutex_exit(&sme_global_mtx);
}

/*
 * sme_add_property_dictionary:
 * 
 * 	+ Add global properties into a device.
 */
static int
sme_add_property_dictionary(struct sysmon_envsys *sme, prop_array_t array,
			    prop_dictionary_t dict)
{
	prop_dictionary_t pdict;
	const char *class;
	int error = 0;

	pdict = prop_dictionary_create();
	if (!pdict)
		return EINVAL;

	/*
	 * Add the 'refresh-timeout' and 'dev-class' objects into the
	 * 'device-properties' dictionary.
	 *
	 * 	...
	 * 	<dict>
	 * 		<key>device-properties</key>
	 * 		<dict>
	 * 			<key>refresh-timeout</key>
	 * 			<integer>120</integer<
	 *			<key>device-class</key>
	 *			<string>class_name</string>
	 * 		</dict>
	 * 	</dict>
	 * 	...
	 *
	 */
	if (sme->sme_events_timeout == 0) {
		sme->sme_events_timeout = SME_EVENTS_DEFTIMEOUT;
		mutex_enter(&sme->sme_mtx);
		sme_schedule_callout(sme);
		mutex_exit(&sme->sme_mtx);
	}

	if (!prop_dictionary_set_uint64(pdict, "refresh-timeout",
					sme->sme_events_timeout)) {
		error = EINVAL;
		goto out;
	}
	if (sme->sme_class == SME_CLASS_BATTERY)
		class = "battery";
	else if (sme->sme_class == SME_CLASS_ACADAPTER)
		class = "ac-adapter";
	else
		class = "other";
	if (!prop_dictionary_set_cstring_nocopy(pdict, "device-class", class)) {
		error = EINVAL;
		goto out;
	}

	if (!prop_dictionary_set(dict, "device-properties", pdict)) {
		error = EINVAL;
		goto out;
	}

	/*
	 * Add the device dictionary into the sysmon envsys array.
	 */
	if (!prop_array_add(array, dict))
		error = EINVAL;

out:
	prop_object_release(pdict);
	return error;
}

/*
 * sme_add_sensor_dictionary:
 *
 * 	+ Adds the sensor objects into the dictionary and returns a pointer
 * 	  to a sme_event_drv_t object if a monitoring flag was set
 * 	  (or NULL otherwise).
 */
static sme_event_drv_t *
sme_add_sensor_dictionary(struct sysmon_envsys *sme, prop_array_t array,
		    	  prop_dictionary_t dict, envsys_data_t *edata)
{
	const struct sme_descr_entry *sdt;
	int error;
	sme_event_drv_t *sme_evdrv_t = NULL;
	char indexstr[ENVSYS_DESCLEN];
	bool mon_supported, allow_rfact;

	/*
	 * Add the index sensor string.
	 *
	 * 		...
	 * 		<key>index</eyr
	 * 		<string>sensor0</string>
	 * 		...
	 */
	(void)snprintf(indexstr, sizeof(indexstr), "sensor%d", edata->sensor);
	if (sme_sensor_upstring(dict, "index", indexstr))
		goto bad;

	/*
	 * 		...
	 * 		<key>description</key>
	 * 		<string>blah blah</string>
	 * 		...
	 */
	if (sme_sensor_upstring(dict, "description", edata->desc))
		goto bad;

	/*
	 * Add the monitoring boolean object:
	 *
	 * 		...
	 * 		<key>monitoring-supported</key>
	 * 		<true/>
	 *		...
	 * 
	 * always false on Battery {capacity,charge}, Drive and Indicator types.
	 * They cannot be monitored.
	 *
	 */
	if ((edata->flags & ENVSYS_FMONNOTSUPP) ||
	    (edata->units == ENVSYS_INDICATOR) ||
	    (edata->units == ENVSYS_DRIVE) ||
	    (edata->units == ENVSYS_BATTERY_CAPACITY) ||
	    (edata->units == ENVSYS_BATTERY_CHARGE))
		mon_supported = false;
	else
		mon_supported = true;
	if (sme_sensor_upbool(dict, "monitoring-supported", mon_supported))
		goto out;

	/*
	 * Add the allow-rfact boolean object, true if
	 * ENVSYS_FCHANGERFACT is set, false otherwise.
	 *
	 * 		...
	 * 		<key>allow-rfact</key>
	 * 		<true/>
	 * 		...
	 */
	if (edata->units == ENVSYS_SVOLTS_DC ||
	    edata->units == ENVSYS_SVOLTS_AC) {
		if (edata->flags & ENVSYS_FCHANGERFACT)
			allow_rfact = true;
		else
			allow_rfact = false;
		if (sme_sensor_upbool(dict, "allow-rfact", allow_rfact))
			goto out;
	}

	error = sme_update_sensor_dictionary(dict, edata,
			(edata->state == ENVSYS_SVALID));
	if (error < 0)
		goto bad;
	else if (error)
		goto out;

	/*
	 * 	...
	 * </dict>
	 *
	 * Add the dictionary into the array.
	 *
	 */
	if (!prop_array_add(array, dict)) {
		DPRINTF(("%s: prop_array_add\n", __func__));
		goto bad;
	}

	/*
	 * Register new event(s) if any monitoring flag was set or if
	 * the sensor provides entropy for rnd(4).
	 */
	if (edata->flags & (ENVSYS_FMONANY | ENVSYS_FHAS_ENTROPY)) {
		sme_evdrv_t = kmem_zalloc(sizeof(*sme_evdrv_t), KM_SLEEP);
		sme_evdrv_t->sed_sdict = dict;
		sme_evdrv_t->sed_edata = edata;
		sme_evdrv_t->sed_sme = sme;
		sdt = sme_find_table_entry(SME_DESC_UNITS, edata->units);
		sme_evdrv_t->sed_powertype = sdt->crittype;
	}

out:
	return sme_evdrv_t;

bad:
	prop_object_release(dict);
	return NULL;
}

/*
 * Find the maximum of all currently reported values.
 * The provided callback decides whether a sensor is part of the
 * maximum calculation (by returning true) or ignored (callback
 * returns false). Example usage: callback selects temperature
 * sensors in a given thermal zone, the function calculates the
 * maximum currently reported temperature in this zone.
 * If the parameter "refresh" is true, new values will be aquired
 * from the hardware, if not, the last reported value will be used.
 */
uint32_t
sysmon_envsys_get_max_value(bool (*predicate)(const envsys_data_t*),
	bool refresh)
{
	struct sysmon_envsys *sme;
	uint32_t maxv, v;

	maxv = 0;
	mutex_enter(&sme_global_mtx);
	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {
		sysmon_envsys_acquire(sme, false);
		v = sme_get_max_value(sme, predicate, refresh);
		sysmon_envsys_release(sme, false);
		if (v > maxv)
			maxv = v;
	}
	mutex_exit(&sme_global_mtx);
	return maxv;
}

static uint32_t
sme_get_max_value(struct sysmon_envsys *sme,
    bool (*predicate)(const envsys_data_t*),
    bool refresh)
{
	envsys_data_t *edata;
	uint32_t maxv, v;

	/* 
	 * Iterate over all sensors that match the predicate
	 */
	maxv = 0;
	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
		if (!(*predicate)(edata))
			continue;

		/* 
		 * refresh sensor data
		 */
		mutex_enter(&sme->sme_mtx);
		sysmon_envsys_refresh_sensor(sme, edata);
		mutex_exit(&sme->sme_mtx);

		v = edata->value_cur;
		if (v > maxv)
			maxv = v;

	}

	return maxv;
}

/*
 * sme_update_dictionary:
 *
 * 	+ Update per-sensor dictionaries with new values if there were
 * 	  changes, otherwise the object in dictionary is untouched.
 */
int
sme_update_dictionary(struct sysmon_envsys *sme)
{
	envsys_data_t *edata;
	prop_object_t array, dict, obj, obj2;
	int error = 0;

	/* 
	 * Retrieve the array of dictionaries in device.
	 */
	array = prop_dictionary_get(sme_propd, sme->sme_name);
	if (prop_object_type(array) != PROP_TYPE_ARRAY) {
		DPRINTF(("%s: not an array (%s)\n", __func__, sme->sme_name));
		return EINVAL;
	}

	/*
	 * Get the last dictionary on the array, this contains the
	 * 'device-properties' sub-dictionary.
	 */
	obj = prop_array_get(array, prop_array_count(array) - 1);
	if (!obj || prop_object_type(obj) != PROP_TYPE_DICTIONARY) {
		DPRINTF(("%s: not a device-properties dictionary\n", __func__));
		return EINVAL;
	}

	obj2 = prop_dictionary_get(obj, "device-properties");
	if (!obj2)
		return EINVAL;

	/*
	 * Update the 'refresh-timeout' property.
	 */
	if (!prop_dictionary_set_uint64(obj2, "refresh-timeout",
					sme->sme_events_timeout))
		return EINVAL;

	/* 
	 * - iterate over all sensors.
	 * - fetch new data.
	 * - check if data in dictionary is different than new data.
	 * - update dictionary if there were changes.
	 */
	DPRINTF(("%s: updating '%s' with nsensors=%d\n", __func__,
	    sme->sme_name, sme->sme_nsensors));

	/*
	 * Don't bother with locking when traversing the queue,
	 * the device is already marked as busy; if a sensor
	 * is going to be removed or added it will have to wait.
	 */
	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
		/* 
		 * refresh sensor data via sme_envsys_refresh_sensor
		 */
		mutex_enter(&sme->sme_mtx);
		sysmon_envsys_refresh_sensor(sme, edata);
		mutex_exit(&sme->sme_mtx);

		/* 
		 * retrieve sensor's dictionary.
		 */
		dict = prop_array_get(array, edata->sensor);
		if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) {
			DPRINTF(("%s: not a dictionary (%d:%s)\n",
			    __func__, edata->sensor, sme->sme_name));
			return EINVAL;
		}

		/* 
		 * update sensor's state.
		 */
		error = sme_update_sensor_dictionary(dict, edata, true);

		if (error)
			break;
	}

	return error;
}

int
sme_update_sensor_dictionary(prop_object_t dict, envsys_data_t *edata,
	bool value_update)
{
	const struct sme_descr_entry *sdt;
	int error = 0;

	sdt = sme_find_table_entry(SME_DESC_STATES, edata->state);
	if (sdt == NULL) {
		printf("sme_update_sensor_dictionary: cannot update sensor %d "
		    "state %d unknown\n", edata->sensor, edata->state);
		return EINVAL;
	}

	DPRINTFOBJ(("%s: sensor #%d type=%d (%s) flags=%d\n", __func__,
	    edata->sensor, sdt->type, sdt->desc, edata->flags));

	error = sme_sensor_upstring(dict, "state", sdt->desc);
	if (error)
		return (-error);

	/* 
	 * update sensor's type.
	 */
	sdt = sme_find_table_entry(SME_DESC_UNITS, edata->units);
	if (sdt == NULL)
		return EINVAL;

	DPRINTFOBJ(("%s: sensor #%d units=%d (%s)\n", __func__, edata->sensor,
	    sdt->type, sdt->desc));

	error = sme_sensor_upstring(dict, "type", sdt->desc);
	if (error)
		return (-error);

	if (value_update) {
		/* 
		 * update sensor's current value.
		 */
		error = sme_sensor_upint32(dict, "cur-value", edata->value_cur);
		if (error)
			return error;
	}

	/*
	 * Battery charge and Indicator types do not
	 * need the remaining objects, so skip them.
	 */
	if (edata->units == ENVSYS_INDICATOR ||
	    edata->units == ENVSYS_BATTERY_CHARGE)
		return error;

	/* 
	 * update sensor flags.
	 */
	if (edata->flags & ENVSYS_FPERCENT) {
		error = sme_sensor_upbool(dict, "want-percentage", true);
		if (error)
			return error;
	}

	if (value_update) {
		/*
		 * update sensor's {max,min}-value.
		 */
		if (edata->flags & ENVSYS_FVALID_MAX) {
			error = sme_sensor_upint32(dict, "max-value",
						   edata->value_max);
			if (error)
				return error;
		}

		if (edata->flags & ENVSYS_FVALID_MIN) {
			error = sme_sensor_upint32(dict, "min-value",
						   edata->value_min);
			if (error)
				return error;
		}

		/* 
		 * update 'rpms' only for ENVSYS_SFANRPM sensors.
		 */
		if (edata->units == ENVSYS_SFANRPM) {
			error = sme_sensor_upuint32(dict, "rpms", edata->rpms);
			if (error)
				return error;
		}

		/* 
		 * update 'rfact' only for ENVSYS_SVOLTS_[AD]C sensors.
		 */
		if (edata->units == ENVSYS_SVOLTS_AC ||
		    edata->units == ENVSYS_SVOLTS_DC) {
			error = sme_sensor_upint32(dict, "rfact", edata->rfact);
			if (error)
				return error;
		}
	}

	/* 
	 * update 'drive-state' only for ENVSYS_DRIVE sensors.
	 */
	if (edata->units == ENVSYS_DRIVE) {
		sdt = sme_find_table_entry(SME_DESC_DRIVE_STATES,
					   edata->value_cur);
		if (sdt == NULL)
			return EINVAL;
		error = sme_sensor_upstring(dict, "drive-state", sdt->desc);
		if (error)
			return error;
	}

	/* 
	 * update 'battery-capacity' only for ENVSYS_BATTERY_CAPACITY
	 * sensors.
	 */
	if (edata->units == ENVSYS_BATTERY_CAPACITY) {
		sdt = sme_find_table_entry(SME_DESC_BATTERY_CAPACITY,
		    edata->value_cur);
		if (sdt == NULL)
			return EINVAL;
		error = sme_sensor_upstring(dict, "battery-capacity",
					    sdt->desc);
		if (error)
			return error;
	}

	return error;
}

/*
 * sme_userset_dictionary:
 *
 * 	+ Parse the userland dictionary and run the appropiate tasks
 * 	  that were specified.
 */
int
sme_userset_dictionary(struct sysmon_envsys *sme, prop_dictionary_t udict,
		       prop_array_t array)
{
	const struct sme_descr_entry *sdt;
	envsys_data_t *edata;
	prop_dictionary_t dict, tdict = NULL;
	prop_object_t obj, obj1, obj2, tobj = NULL;
	uint32_t props;
	uint64_t refresh_timo = 0;
	sysmon_envsys_lim_t lims;
	int i, error = 0;
	const char *blah;
	bool targetfound = false;

	/*
	 * The user wanted to change the refresh timeout value for this
	 * device.
	 *
	 * Get the 'device-properties' object from the userland dictionary.
	 */
	obj = prop_dictionary_get(udict, "device-properties");
	if (obj && prop_object_type(obj) == PROP_TYPE_DICTIONARY) {
		/*
		 * Get the 'refresh-timeout' property for this device.
		 */
		obj1 = prop_dictionary_get(obj, "refresh-timeout");
		if (obj1 && prop_object_type(obj1) == PROP_TYPE_NUMBER) {
			targetfound = true;
			refresh_timo =
			    prop_number_unsigned_integer_value(obj1);
			if (refresh_timo < 1)
				error = EINVAL;
			else {
				mutex_enter(&sme->sme_mtx);
				if (sme->sme_events_timeout != refresh_timo) {
					sme->sme_events_timeout = refresh_timo;
					sme_schedule_callout(sme);
				}
				mutex_exit(&sme->sme_mtx);
			}
		}
		return error;

	} else if (!obj) {
		/* 
		 * Get sensor's index from userland dictionary.
		 */
		obj = prop_dictionary_get(udict, "index");
		if (!obj)
			return EINVAL;
		if (prop_object_type(obj) != PROP_TYPE_STRING) {
			DPRINTF(("%s: 'index' not a string\n", __func__));
			return EINVAL;
		}
	} else
		return EINVAL;

	/*
	 * Don't bother with locking when traversing the queue,
	 * the device is already marked as busy; if a sensor
	 * is going to be removed or added it will have to wait.
	 */
	TAILQ_FOREACH(edata, &sme->sme_sensors_list, sensors_head) {
		/*
		 * Get a dictionary and check if it's our sensor by checking
		 * at its index position.
		 */
		dict = prop_array_get(array, edata->sensor);
		obj1 = prop_dictionary_get(dict, "index");

		/* 
		 * is it our sensor?
		 */
		if (!prop_string_equals(obj1, obj))
			continue;

		props = 0;

		/*
		 * Check if a new description operation was
		 * requested by the user and set new description.
		 */
		obj2 = prop_dictionary_get(udict, "description");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_STRING) {
			targetfound = true;
			blah = prop_string_cstring_nocopy(obj2);

			/*
			 * Check for duplicate description.
			 */
			for (i = 0; i < sme->sme_nsensors; i++) {
				if (i == edata->sensor)
					continue;
				tdict = prop_array_get(array, i);
				tobj =
				    prop_dictionary_get(tdict, "description");
				if (prop_string_equals(obj2, tobj)) {
					error = EEXIST;
					goto out;
				}
			}

			/*
			 * Update the object in dictionary.
			 */
			mutex_enter(&sme->sme_mtx);
			error = sme_sensor_upstring(dict,
						    "description",
						    blah);
			if (error) {
				mutex_exit(&sme->sme_mtx);
				goto out;
			}

			DPRINTF(("%s: sensor%d changed desc to: %s\n",
			    __func__, edata->sensor, blah));
			edata->upropset |= PROP_DESC;
			mutex_exit(&sme->sme_mtx);
		}

		/* 
		 * did the user want to change the rfact?
		 */
		obj2 = prop_dictionary_get(udict, "rfact");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			if (edata->flags & ENVSYS_FCHANGERFACT) {
				mutex_enter(&sme->sme_mtx);
				edata->rfact = prop_number_integer_value(obj2);
				edata->upropset |= PROP_RFACT;
				mutex_exit(&sme->sme_mtx);
				DPRINTF(("%s: sensor%d changed rfact to %d\n",
				    __func__, edata->sensor, edata->rfact));
			} else {
				error = ENOTSUP;
				goto out;
			}
		}

		sdt = sme_find_table_entry(SME_DESC_UNITS, edata->units);

		/* 
		 * did the user want to set a critical capacity event?
		 */
		obj2 = prop_dictionary_get(udict, "critical-capacity");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_critmin = prop_number_integer_value(obj2);
			props |= PROP_BATTCAP;
		}

		/* 
		 * did the user want to set a warning capacity event?
		 */
		obj2 = prop_dictionary_get(udict, "warning-capacity");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_warnmin = prop_number_integer_value(obj2);
			props |= PROP_BATTWARN;
		}

		/* 
		 * did the user want to set a high capacity event?
		 */
		obj2 = prop_dictionary_get(udict, "high-capacity");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_warnmin = prop_number_integer_value(obj2);
			props |= PROP_BATTHIGH;
		}

		/* 
		 * did the user want to set a maximum capacity event?
		 */
		obj2 = prop_dictionary_get(udict, "maximum-capacity");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_warnmin = prop_number_integer_value(obj2);
			props |= PROP_BATTMAX;
		}

		/* 
		 * did the user want to set a critical max event?
		 */
		obj2 = prop_dictionary_get(udict, "critical-max");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_critmax = prop_number_integer_value(obj2);
			props |= PROP_CRITMAX;
		}

		/* 
		 * did the user want to set a warning max event?
		 */
		obj2 = prop_dictionary_get(udict, "warning-max");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_warnmax = prop_number_integer_value(obj2);
			props |= PROP_WARNMAX;
		}

		/* 
		 * did the user want to set a critical min event?
		 */
		obj2 = prop_dictionary_get(udict, "critical-min");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_critmin = prop_number_integer_value(obj2);
			props |= PROP_CRITMIN;
		}

		/* 
		 * did the user want to set a warning min event?
		 */
		obj2 = prop_dictionary_get(udict, "warning-min");
		if (obj2 && prop_object_type(obj2) == PROP_TYPE_NUMBER) {
			targetfound = true;
			lims.sel_warnmin = prop_number_integer_value(obj2);
			props |= PROP_WARNMIN;
		}

		if (props && (edata->flags & ENVSYS_FMONNOTSUPP) != 0) {
			error = ENOTSUP;
			goto out;
		}
		if (props || (edata->flags & ENVSYS_FHAS_ENTROPY) != 0) {
			error = sme_event_register(dict, edata, sme, &lims,
					props,
					(edata->flags & ENVSYS_FPERCENT)?
						PENVSYS_EVENT_CAPACITY:
						PENVSYS_EVENT_LIMITS,
					sdt->crittype);
			if (error == EEXIST)
				error = 0;
			if (error) 
				goto out;
		}

		/*
		 * All objects in dictionary were processed.
		 */
		break;
	}

out:
	/* 
	 * invalid target? return the error.
	 */
	if (!targetfound)
		error = EINVAL;

	return error;
}

/*
 * + sysmon_envsys_foreach_sensor
 *
 *	Walk through the devices' sensor lists and execute the callback.
 *	If the callback returns false, the remainder of the current
 *	device's sensors are skipped.
 */
void   
sysmon_envsys_foreach_sensor(sysmon_envsys_callback_t func, void *arg,
			     bool refresh)
{
	struct sysmon_envsys *sme;
	envsys_data_t *sensor;

	mutex_enter(&sme_global_mtx);
	LIST_FOREACH(sme, &sysmon_envsys_list, sme_list) {

		sysmon_envsys_acquire(sme, false);
		TAILQ_FOREACH(sensor, &sme->sme_sensors_list, sensors_head) {
			if (refresh) {
				mutex_enter(&sme->sme_mtx);
				sysmon_envsys_refresh_sensor(sme, sensor);
				mutex_exit(&sme->sme_mtx);
			}
			if (!(*func)(sme, sensor, arg))
				break;
		}
		sysmon_envsys_release(sme, false);
	}
	mutex_exit(&sme_global_mtx);
}

/*
 * Call the sensor's refresh function, and collect/stir entropy
 */
void
sysmon_envsys_refresh_sensor(struct sysmon_envsys *sme, envsys_data_t *edata)
{

	if ((sme->sme_flags & SME_DISABLE_REFRESH) == 0)
		(*sme->sme_refresh)(sme, edata);

	if (edata->flags & ENVSYS_FHAS_ENTROPY &&
	    edata->state != ENVSYS_SINVALID &&
	    edata->value_prev != edata->value_cur)
		rnd_add_uint32(&edata->rnd_src, edata->value_cur);
	edata->value_prev = edata->value_cur;
}

static
int
sysmon_envsys_modcmd(modcmd_t cmd, void *arg)
{
        int ret;
 
        switch (cmd) { 
        case MODULE_CMD_INIT:
                ret = sysmon_envsys_init();
                break;
 
        case MODULE_CMD_FINI:
                ret = sysmon_envsys_fini();
                break; 
   
        case MODULE_CMD_STAT:
        default:
                ret = ENOTTY;
        }
  
        return ret; 
}