Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
/*
 * Copyright (c) 1998-2006 Apple Computer, Inc. All rights reserved.
 * Copyright (c) 2007-2021 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

#define IOKIT_ENABLE_SHARED_PTR

#include <AssertMacros.h>
#include <IOKit/IOLib.h>
#include <IOKit/IONVRAM.h>
#include <IOKit/IOPlatformExpert.h>
#include <IOKit/IOUserClient.h>
#include <IOKit/IOKitKeys.h>
#include <IOKit/IOKitKeysPrivate.h>
#include <IOKit/IOBSD.h>
#include <kern/debug.h>
#include <os/system_event_log.h>
#include <sys/csr.h>

#define super IOService

OSDefineMetaClassAndStructors(IODTNVRAM, IOService);

class IONVRAMCHRPHandler;
class IONVRAMV3Handler;

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

#define MAX_VAR_NAME_SIZE     63

#define kNVRAMBankSizeKey    "nvram-bank-size"
#define kNVRAMBankCountKey   "nvram-bank-count"
#define kNVRAMCurrentBankKey "nvram-current-bank"

#define kCurrentGenerationCountKey "Generation"
#define kCurrentNVRAMVersionKey    "Version"

#define kNVRAMCommonUsedKey    "CommonUsed"
#define kNVRAMSystemUsedKey    "SystemUsed"

#define kIONVRAMPrivilege       kIOClientPrivilegeAdministrator

#define MIN_SYNC_NOW_INTERVAL 15*60 /* Minimum 15 Minutes interval mandated */

#if defined(DEBUG) || defined(DEVELOPMENT)
#define DEBUG_IFERROR(err, fmt, args...)                                     \
({                                                                           \
	if ((err != kIOReturnSuccess) || gNVRAMLogging)                          \
	IOLog("%s:%s:%u - " fmt, __FILE_NAME__, __FUNCTION__, __LINE__, ##args); \
})

#define DEBUG_INFO(fmt, args...)                                             \
({                                                                           \
	if (gNVRAMLogging)                                                       \
	IOLog("%s:%s:%u - " fmt, __FILE_NAME__, __FUNCTION__, __LINE__, ##args); \
})

#define DEBUG_ALWAYS(fmt, args...)                                           \
({                                                                           \
	IOLog("%s:%s:%u - " fmt, __FILE_NAME__, __FUNCTION__, __LINE__, ##args); \
})
#else
#define DEBUG_IFERROR(err, fmt, args...) (void)NULL
#define DEBUG_INFO(fmt, args...) (void)NULL
#define DEBUG_ALWAYS(fmt, args...) (void)NULL
#endif

#define DEBUG_ERROR DEBUG_ALWAYS

#define SAFE_TO_LOCK() (preemption_enabled() && !panic_active())

#define CONTROLLERLOCK()                     \
({                                           \
	if (SAFE_TO_LOCK())                  \
	        IOLockLock(_controllerLock); \
})

#define CONTROLLERUNLOCK()                     \
({                                             \
	if (SAFE_TO_LOCK())                    \
	        IOLockUnlock(_controllerLock); \
})

#define NVRAMREADLOCK()                       \
({                                            \
	if (SAFE_TO_LOCK())                   \
	        IORWLockRead(_variableLock);  \
})

#define NVRAMWRITELOCK()                      \
({                                            \
	if (SAFE_TO_LOCK())                   \
	        IORWLockWrite(_variableLock); \
})

#define NVRAMUNLOCK()                          \
({                                             \
	if (SAFE_TO_LOCK())                    \
	        IORWLockUnlock(_variableLock); \
})

#define NVRAMLOCKASSERTHELD()                                       \
({                                                                  \
	if (SAFE_TO_LOCK())                                         \
	        IORWLockAssert(_variableLock, kIORWLockAssertHeld); \
})

#define NVRAMLOCKASSERTEXCLUSIVE()                                   \
({                                                                   \
	if (SAFE_TO_LOCK())                                          \
	        IORWLockAssert(_variableLock, kIORWLockAssertWrite); \
})

// MOD = Write, Delete
// RST = Reset, Obliterate
// RD  = Read
// DEL = Delete
#define ENT_MOD_RST     ((1 << kIONVRAMOperationWrite) | (1 << kIONVRAMOperationDelete) | (1 << kIONVRAMOperationObliterate) | (1 << kIONVRAMOperationReset))
#define ENT_MOD_RD      ((1 << kIONVRAMOperationRead) | (1 << kIONVRAMOperationWrite) | (1 << kIONVRAMOperationDelete))
#define ENT_MOD         ((1 << kIONVRAMOperationWrite) | (1 << kIONVRAMOperationDelete))
#define ENT_RST         ((1 << kIONVRAMOperationObliterate) | (1 << kIONVRAMOperationReset))
#define ENT_RD          ((1 << kIONVRAMOperationRead))
#define ENT_DEL         ((1 << kIONVRAMOperationDelete))

enum NVRAMVersion {
	kNVRAMVersionUnknown,
	kNVRAMVersion1,       // Legacy, banks, 0x800 common partition size
	kNVRAMVersion2,       // V1 but with (0x2000 - sizeof(struct apple_nvram_header) - sizeof(struct chrp_nvram_header)) common region
	kNVRAMVersion3,       // New EFI based format
	kNVRAMVersionMax
};

// Guid for Apple System Boot variables
// 40A0DDD2-77F8-4392-B4A3-1E7304206516
UUID_DEFINE(gAppleSystemVariableGuid, 0x40, 0xA0, 0xDD, 0xD2, 0x77, 0xF8, 0x43, 0x92, 0xB4, 0xA3, 0x1E, 0x73, 0x04, 0x20, 0x65, 0x16);

// Apple NVRAM Variable namespace (APPLE_VENDOR_OS_VARIABLE_GUID)
// 7C436110-AB2A-4BBB-A880-FE41995C9F82
UUID_DEFINE(gAppleNVRAMGuid, 0x7C, 0x43, 0x61, 0x10, 0xAB, 0x2A, 0x4B, 0xBB, 0xA8, 0x80, 0xFE, 0x41, 0x99, 0x5C, 0x9F, 0x82);

// Prefix for kernel-only variables
#define KERNEL_ONLY_VAR_NAME_PREFIX "krn."

static TUNABLE(bool, gNVRAMLogging, "nvram-log", false);
static bool gInternalBuild = false;

// allowlist variables from macboot that need to be set/get from system region if present
static const char * const gNVRAMSystemList[] = { IONVRAMSystemVariableList, nullptr };

typedef struct {
	const char *name;
	IONVRAMVariableType type;
} VariableTypeEntry;

static const
VariableTypeEntry gVariableTypes[] = {
	{"auto-boot?", kOFVariableTypeBoolean},
	{"boot-args", kOFVariableTypeString},
	{"boot-command", kOFVariableTypeString},
	{"boot-device", kOFVariableTypeString},
	{"boot-file", kOFVariableTypeString},
	{"boot-screen", kOFVariableTypeString},
	{"boot-script", kOFVariableTypeString},
	{"console-screen", kOFVariableTypeString},
	{"default-client-ip", kOFVariableTypeString},
	{"default-gateway-ip", kOFVariableTypeString},
	{"default-mac-address?", kOFVariableTypeBoolean},
	{"default-router-ip", kOFVariableTypeString},
	{"default-server-ip", kOFVariableTypeString},
	{"default-subnet-mask", kOFVariableTypeString},
	{"diag-device", kOFVariableTypeString},
	{"diag-file", kOFVariableTypeString},
	{"diag-switch?", kOFVariableTypeBoolean},
	{"fcode-debug?", kOFVariableTypeBoolean},
	{"input-device", kOFVariableTypeString},
	{"input-device-1", kOFVariableTypeString},
	{"little-endian?", kOFVariableTypeBoolean},
	{"ldm", kOFVariableTypeBoolean},
	{"load-base", kOFVariableTypeNumber},
	{"mouse-device", kOFVariableTypeString},
	{"nvramrc", kOFVariableTypeString},
	{"oem-banner", kOFVariableTypeString},
	{"oem-banner?", kOFVariableTypeBoolean},
	{"oem-logo", kOFVariableTypeString},
	{"oem-logo?", kOFVariableTypeBoolean},
	{"output-device", kOFVariableTypeString},
	{"output-device-1", kOFVariableTypeString},
	{"pci-probe-list", kOFVariableTypeNumber},
	{"pci-probe-mask", kOFVariableTypeNumber},
	{"real-base", kOFVariableTypeNumber},
	{"real-mode?", kOFVariableTypeBoolean},
	{"real-size", kOFVariableTypeNumber},
	{"screen-#columns", kOFVariableTypeNumber},
	{"screen-#rows", kOFVariableTypeNumber},
	{"security-mode", kOFVariableTypeString},
	{"selftest-#megs", kOFVariableTypeNumber},
	{"use-generic?", kOFVariableTypeBoolean},
	{"use-nvramrc?", kOFVariableTypeBoolean},
	{"virt-base", kOFVariableTypeNumber},
	{"virt-size", kOFVariableTypeNumber},
	// Variables used for testing
	{"test-bool", kOFVariableTypeBoolean},
	{"test-num", kOFVariableTypeNumber},
	{"test-str", kOFVariableTypeString},
	{"test-data", kOFVariableTypeData},
#if !defined(__x86_64__)
	{"acc-cm-override-charger-count", kOFVariableTypeNumber},
	{"acc-cm-override-count", kOFVariableTypeNumber},
	{"acc-mb-ld-lifetime", kOFVariableTypeNumber},
	{"com.apple.System.boot-nonce", kOFVariableTypeString},
	{"darkboot", kOFVariableTypeBoolean},
	{"enter-tdm-mode", kOFVariableTypeBoolean},
#endif /* !defined(__x86_64__) */
	{nullptr, kOFVariableTypeData} // Default type to return
};

union VariablePermission {
	struct {
		uint64_t UserWrite            :1;
		uint64_t RootRequired         :1;
		uint64_t KernelOnly           :1;
		uint64_t ResetNVRAMOnlyDelete :1;
		uint64_t NeverAllowedToDelete :1;
		uint64_t SystemReadHidden     :1;
		uint64_t FullAccess           :1;
		uint64_t Reserved:57;
	} Bits;
	uint64_t Uint64;
};

typedef struct {
	const char *name;
	VariablePermission p;
} VariablePermissionEntry;

static const
VariablePermissionEntry gVariablePermissions[] = {
	{"aapl,pci", .p.Bits.RootRequired = 1},
	{"battery-health", .p.Bits.RootRequired = 1,
	 .p.Bits.NeverAllowedToDelete = 1},
	{"boot-image", .p.Bits.UserWrite = 1},
	{"com.apple.System.fp-state", .p.Bits.KernelOnly = 1},
	{"fm-account-masked", .p.Bits.RootRequired = 1,
	 .p.Bits.NeverAllowedToDelete = 1},
	{"fm-activation-locked", .p.Bits.RootRequired = 1,
	 .p.Bits.NeverAllowedToDelete = 1},
	{"fm-spkeys", .p.Bits.RootRequired = 1,
	 .p.Bits.NeverAllowedToDelete = 1},
	{"fm-spstatus", .p.Bits.RootRequired = 1,
	 .p.Bits.NeverAllowedToDelete = 1},
	{"policy-nonce-digests", .p.Bits.ResetNVRAMOnlyDelete = 1}, // Deleting this via user triggered obliterate leave J273a unable to boot
	{"recoveryos-passcode-blob", .p.Bits.SystemReadHidden = 1},
	{"security-password", .p.Bits.RootRequired = 1},
	{"system-passcode-lock-blob", .p.Bits.SystemReadHidden = 1},

#if !defined(__x86_64__)
	{"acc-cm-override-charger-count", .p.Bits.KernelOnly = 1},
	{"acc-cm-override-count", .p.Bits.KernelOnly = 1},
	{"acc-mb-ld-lifetime", .p.Bits.KernelOnly = 1},
	{"backlight-level", .p.Bits.UserWrite = 1},
	{"backlight-nits", .p.Bits.UserWrite = 1},
	{"ldm", .p.Bits.KernelOnly = 1},
	{"com.apple.System.boot-nonce", .p.Bits.KernelOnly = 1},
	{"com.apple.System.sep.art", .p.Bits.KernelOnly = 1},
	{"darkboot", .p.Bits.UserWrite = 1},
	{"nonce-seeds", .p.Bits.KernelOnly = 1},
#endif /* !defined(__x86_64__) */
	// Variables used for testing permissions
	{"testSysReadHidden", .p.Bits.SystemReadHidden = 1},
	{"testKernelOnly", .p.Bits.KernelOnly = 1},
	{"testResetOnlyDel", .p.Bits.ResetNVRAMOnlyDelete = 1},
	{"testNeverDel", .p.Bits.NeverAllowedToDelete = 1},
	{"testUserWrite", .p.Bits.UserWrite = 1},
	{"testRootReq", .p.Bits.RootRequired = 1},
	{nullptr, {.Bits.FullAccess = 1}} // Default access
};

typedef struct {
	const uint8_t checkOp;
	const uuid_t  *varGuid;
	const char    *varName;
	const char    *varEntitlement;
} VariableEntitlementEntry;

// variable-guid pair entries that require entitlement check to do specified nvram operations
static const
VariableEntitlementEntry gVariableEntitlements[] = {
	{ENT_MOD_RST, &gAppleNVRAMGuid, "ownership-warning", "com.apple.private.iokit.ddl-write"},
	{ENT_MOD, &gAppleSystemVariableGuid, "BluetoothInfo", "com.apple.private.iokit.nvram-bluetooth"},
	{ENT_MOD, &gAppleSystemVariableGuid, "BluetoothUHEDevices", "com.apple.private.iokit.nvram-bluetooth"},
	{ENT_MOD, &gAppleNVRAMGuid, "bluetoothExternalDongleFailed", "com.apple.private.iokit.nvram-bluetooth"},
	{ENT_MOD, &gAppleNVRAMGuid, "bluetoothInternalControllerInfo", "com.apple.private.iokit.nvram-bluetooth"},
	// Variables used for testing entitlement
	{ENT_MOD_RST, &gAppleNVRAMGuid, "testEntModRst", "com.apple.private.iokit.testEntModRst"},
	{ENT_MOD_RST, &gAppleSystemVariableGuid, "testEntModRstSys", "com.apple.private.iokit.testEntModRst"},
	{ENT_RST, &gAppleNVRAMGuid, "testEntRst", "com.apple.private.iokit.testEntRst"},
	{ENT_RST, &gAppleSystemVariableGuid, "testEntRstSys", "com.apple.private.iokit.testEntRst"},
	{ENT_RD, &gAppleNVRAMGuid, "testEntRd", "com.apple.private.iokit.testEntRd"},
	{ENT_RD, &gAppleSystemVariableGuid, "testEntRdSys", "com.apple.private.iokit.testEntRd"},
	{ENT_DEL, &gAppleNVRAMGuid, "testEntDel", "com.apple.private.iokit.testEntDel"},
	{ENT_DEL, &gAppleSystemVariableGuid, "testEntDelSys", "com.apple.private.iokit.testEntDel"},
	{0, &UUID_NULL, nullptr, nullptr}
};

static NVRAMPartitionType
getPartitionTypeForGUID(const uuid_t guid)
{
	if (uuid_compare(guid, gAppleSystemVariableGuid) == 0) {
		return kIONVRAMPartitionSystem;
	} else {
		return kIONVRAMPartitionCommon;
	}
}

static IONVRAMVariableType
getVariableType(const char *propName)
{
	const VariableTypeEntry *entry;

	entry = gVariableTypes;
	while (entry->name != nullptr) {
		if (strcmp(entry->name, propName) == 0) {
			break;
		}
		entry++;
	}

	return entry->type;
}

static IONVRAMVariableType
getVariableType(const OSSymbol *propSymbol)
{
	return getVariableType(propSymbol->getCStringNoCopy());
}

static VariablePermission
getVariablePermission(const char *propName)
{
	const VariablePermissionEntry *entry;

	entry = gVariablePermissions;
	while (entry->name != nullptr) {
		if (strcmp(entry->name, propName) == 0) {
			break;
		}
		entry++;
	}

	return entry->p;
}

static bool
variableInAllowList(const char *varName)
{
	unsigned int i = 0;

	while (gNVRAMSystemList[i] != nullptr) {
		if (strcmp(varName, gNVRAMSystemList[i]) == 0) {
			return true;
		}
		i++;
	}

	return false;
}

static bool
verifyWriteSizeLimit(const uuid_t varGuid, const char *variableName, size_t propDataSize)
{
	if (variableInAllowList(variableName)) {
		if (strnstr(variableName, "breadcrumbs", strlen(variableName)) != NULL) {
			return propDataSize <= 1024;
		} else {
			return propDataSize <= 768;
		}
	}

	return true;
}

#if defined(DEBUG) || defined(DEVELOPMENT)
static const char *
getNVRAMOpString(IONVRAMOperation op)
{
	switch (op) {
	case kIONVRAMOperationRead:
		return "Read";
	case kIONVRAMOperationWrite:
		return "Write";
	case kIONVRAMOperationDelete:
		return "Delete";
	case kIONVRAMOperationObliterate:
		return "Obliterate";
	case kIONVRAMOperationReset:
		return "Reset";
	case kIONVRAMOperationInit:
		return "Init";
	default:
		return "Unknown";
	}
}
#endif

/*
 * Parse a variable name of the form "GUID:name".
 * If the name cannot be parsed, substitute the Apple global variable GUID.
 * Returns TRUE if a GUID was found in the name, FALSE otherwise.
 * The guidResult and nameResult arguments may be nullptr if you just want
 * to check the format of the string.
 */
static bool
parseVariableName(const char *key, uuid_t *guidResult, const char **nameResult)
{
	uuid_string_t temp    = {0};
	size_t        keyLen  = strlen(key);
	bool          ok      = false;
	const char    *name   = key;
	uuid_t        guid;

	if (keyLen > sizeof(temp)) {
		// check for at least UUID + ":" + more
		memcpy(temp, key, sizeof(temp) - 1);

		if ((uuid_parse(temp, guid) == 0) &&
		    (key[sizeof(temp) - 1] == ':')) {
			name = key + sizeof(temp);
			ok     = true;
		}
	}

	if (guidResult) {
		ok ? uuid_copy(*guidResult, guid) : uuid_copy(*guidResult, gAppleNVRAMGuid);
	}
	if (nameResult) {
		*nameResult = name;
	}

	return ok;
}

static bool
parseVariableName(const OSSymbol *key, uuid_t *guidResult, const char **nameResult)
{
	return parseVariableName(key->getCStringNoCopy(), guidResult, nameResult);
}

/**
 * @brief Translates(if needed) varGuid and stores it in destGuid
 *
 * @param varGuid       guid to translate
 * @param variableName  variable name attached to the guid
 * @param destGuid      translated guid is saved here
 * @param systemActive  boolean to indicate if it has system partition size > 0
 */
static void
translateGUID(const uuid_t varGuid, const char *variableName, uuid_t destGuid, bool systemActive)
{
	if (varGuid == nullptr || variableName == nullptr || destGuid == nullptr) {
		DEBUG_ERROR("nullptr passed as an argument\n");
		return;
	}

	bool systemGuid = uuid_compare(varGuid, gAppleSystemVariableGuid) == 0;

	if (systemActive) {
		if (variableInAllowList(variableName)) {
			DEBUG_INFO("Using system GUID due to allow list\n");
			uuid_copy(destGuid, gAppleSystemVariableGuid);
		} else if (systemGuid) {
			DEBUG_INFO("System GUID used\n");
			uuid_copy(destGuid, gAppleSystemVariableGuid);
		} else {
			DEBUG_INFO("Use given guid\n");
			uuid_copy(destGuid, varGuid);
		}
	} else if (systemGuid) {
		DEBUG_INFO("Overriding to Apple guid\n");
		uuid_copy(destGuid, gAppleNVRAMGuid);
	} else {
		DEBUG_INFO("Use given guid\n");
		uuid_copy(destGuid, varGuid);
	}
}

/**
 * @brief Checks if the variable-guid(translated) pair is present in gVariableEntitlements and if so,
 *        does it have the required entitlement for the NVRAM operation passed in
 *
 * @param varGuid       guid for the variable to be checked, this gets translated by translateGUID
 * @param varName       variable name
 * @param op            NVRAM operation
 * @param systemActive  used to pass into translateGUID to get the correct guid to check against
 * @param veChecked     if variable entitlement is checked, this is set to true
 * @return true         if variable wasn't present in gVariableEntitlements,
 *                      entitlement check wasn't required for operation passed in,
 *                      or if entitlement check returned true
 * @return false        if varName/varGuid/veChecked was NULL or if entitlement check returned false
 */
static bool
verifyVarEntitlement(const uuid_t varGuid, const char *varName, IONVRAMOperation op, bool systemActive, bool *veChecked)
{
	if (varGuid == nullptr || varName == nullptr || veChecked == nullptr) {
		DEBUG_ERROR("nullptr passed as an argument\n");
		return false;
	}

	uuid_t translatedGuid;
	const VariableEntitlementEntry *entry;
	*veChecked = false;

	translateGUID(varGuid, varName, translatedGuid, systemActive);

	entry = gVariableEntitlements;
	while ((entry != nullptr) && (entry->varName != nullptr)) {
		if ((strcmp(entry->varName, varName) == 0) && (uuid_compare(translatedGuid, *(entry->varGuid)) == 0)) {
			// check if task entitlement check is required for this operation
			if (entry->checkOp & (1 << op)) {
				*veChecked = true;
				DEBUG_INFO("Checking entitlement %s for %s for operation %s\n", entry->varEntitlement, varName, getNVRAMOpString(op));
				return IOCurrentTaskHasEntitlement(entry->varEntitlement);
			}
			break;
		}
		entry++;
	}

	return true;
}

static bool
kernelOnlyVar(const uuid_t varGuid, const char *varName)
{
	if (strncmp(varName, KERNEL_ONLY_VAR_NAME_PREFIX, sizeof(KERNEL_ONLY_VAR_NAME_PREFIX) - 1) == 0) {
		return true;
	}

	return false;
}

static bool
verifyPermission(IONVRAMOperation op, const uuid_t varGuid, const char *varName, const bool systemActive)
{
	VariablePermission perm;
	bool kernel, varEntitled, writeEntitled = false, readEntitled = false, allowList, systemGuid = false, systemEntitled = false, systemInternalEntitled = false, systemAllow, systemReadHiddenAllow = false;
	bool admin = false;
	bool ok = false;

	if (verifyVarEntitlement(varGuid, varName, op, systemActive, &varEntitled) == false) {
		goto exit;
	}

	perm = getVariablePermission(varName);

	kernel = current_task() == kernel_task;

	if (perm.Bits.KernelOnly || kernelOnlyVar(varGuid, varName)) {
		DEBUG_INFO("KernelOnly access for %s, kernel=%d\n", varName, kernel);
		ok = kernel;
		goto exit;
	}

	allowList              = variableInAllowList(varName);
	systemGuid             = uuid_compare(varGuid, gAppleSystemVariableGuid) == 0;
	admin                  = IOUserClient::clientHasPrivilege(current_task(), kIONVRAMPrivilege) == kIOReturnSuccess;
	writeEntitled          = IOCurrentTaskHasEntitlement(kIONVRAMWriteAccessKey);
	readEntitled           = IOCurrentTaskHasEntitlement(kIONVRAMReadAccessKey);
	systemEntitled         = IOCurrentTaskHasEntitlement(kIONVRAMSystemAllowKey);
	systemInternalEntitled = IOCurrentTaskHasEntitlement(kIONVRAMSystemInternalAllowKey);
	systemReadHiddenAllow  = IOCurrentTaskHasEntitlement(kIONVRAMSystemHiddenAllowKey);

	systemAllow = systemEntitled || (systemInternalEntitled && gInternalBuild) || kernel;

	switch (op) {
	case kIONVRAMOperationRead:
		if (systemGuid && perm.Bits.SystemReadHidden) {
			ok = systemReadHiddenAllow;
		} else if (kernel || admin || readEntitled || perm.Bits.FullAccess || varEntitled) {
			ok = true;
		}
		break;

	case kIONVRAMOperationWrite:
		if (kernel || perm.Bits.UserWrite || admin || writeEntitled || varEntitled) {
			if (systemGuid) {
				if (allowList) {
					if (!systemAllow) {
						DEBUG_ERROR("Allowed write to system region when NOT entitled for %s\n", varName);
					}
				} else if (varEntitled) {
					DEBUG_INFO("Allowed write to system region using variable specific entitlement for %s\n", varName);
				} else if (!systemAllow) {
					DEBUG_ERROR("Not entitled for system region writes for %s\n", varName);
					break;
				}
			}
			ok = true;
		}
		break;

	case kIONVRAMOperationDelete:
	case kIONVRAMOperationObliterate:
	case kIONVRAMOperationReset:
		if (perm.Bits.NeverAllowedToDelete) {
			DEBUG_INFO("Never allowed to delete %s\n", varName);
			break;
		} else if ((op == kIONVRAMOperationObliterate) && perm.Bits.ResetNVRAMOnlyDelete) {
			DEBUG_INFO("Not allowed to obliterate %s\n", varName);
			break;
		} else if ((op == kIONVRAMOperationDelete) && perm.Bits.ResetNVRAMOnlyDelete) {
			DEBUG_INFO("Only allowed to delete %s via NVRAM reset\n", varName);
			break;
		}

		if (kernel || perm.Bits.UserWrite || admin || writeEntitled || varEntitled) {
			if (systemGuid) {
				if (allowList) {
					if (!systemAllow) {
						DEBUG_ERROR("Allowed delete to system region when NOT entitled for %s\n", varName);
					}
				} else if (varEntitled) {
					DEBUG_INFO("Allowed delete to system region using variable specific entitlement for %s\n", varName);
				} else if (!systemAllow) {
					DEBUG_ERROR("Not entitled for system region deletes for %s\n", varName);
					break;
				}
			}
			ok = true;
		}
		break;

	case kIONVRAMOperationInit:
		break;
	}

exit:
	DEBUG_INFO("Permission for %s of %s %s: kern=%d, adm=%d, wE=%d, rE=%d, sG=%d, sEd=%d, sIEd=%d, sRHA=%d, UW=%d, vE=%d\n", getNVRAMOpString(op), varName, ok ? "granted" : "denied",
	    kernel, admin, writeEntitled, readEntitled, systemGuid, systemEntitled, systemInternalEntitled, systemReadHiddenAllow, perm.Bits.UserWrite, varEntitled);

	return ok;
}

static bool
verifyPermission(IONVRAMOperation op, const OSSymbol *canonicalKey, const bool systemActive)
{
	const char *varName;
	uuid_t varGuid;

	parseVariableName(canonicalKey->getCStringNoCopy(), &varGuid, &varName);

	return verifyPermission(op, varGuid, varName, systemActive);
}

static bool
skipKey(const OSSymbol *aKey)
{
	return aKey->isEqualTo(kIORegistryEntryAllowableSetPropertiesKey) ||
	       aKey->isEqualTo(kIORegistryEntryDefaultLockingSetPropertiesKey) ||
	       aKey->isEqualTo(kIOClassNameOverrideKey) ||
	       aKey->isEqualTo(kIOBSDNameKey) ||
	       aKey->isEqualTo(kIOBSDNamesKey) ||
	       aKey->isEqualTo(kIOBSDMajorKey) ||
	       aKey->isEqualTo(kIOBSDMinorKey) ||
	       aKey->isEqualTo(kIOBSDUnitKey) ||
	       aKey->isEqualTo(kIOUserServicePropertiesKey) ||
	       aKey->isEqualTo(kIOExclaveAssignedKey) ||
	       aKey->isEqualTo(kIOMatchCategoryKey);
}

static OSSharedPtr<const OSSymbol>
keyWithGuidAndCString(const uuid_t guid, const char * cstring)
{
	size_t                      length;
	OSSharedPtr<const OSSymbol> symbolObj;
	char                        *canonicalString;

	length = sizeof(uuid_string_t) - 1 + sizeof(':') + strlen(cstring) + 1;

	canonicalString = (char *) IOMallocData(length);
	if (canonicalString == nullptr) {
		return NULL;
	}

	uuid_unparse(guid, *((uuid_string_t*)canonicalString));
	canonicalString[sizeof(uuid_string_t) - 1] = ':';

	strlcpy(&canonicalString[sizeof(uuid_string_t)], cstring, length - sizeof(uuid_string_t));

	symbolObj = OSSymbol::withCString(canonicalString);
	IOFreeData(canonicalString, length);

	return symbolObj;
}

static void
dumpDict(const OSDictionary *dict)
{
	const OSSymbol                    *key;
	OSSharedPtr<OSCollectionIterator> iter;
	unsigned int                      count = 0;

	iter = OSCollectionIterator::withCollection(dict);
	if (iter == nullptr) {
		DEBUG_ERROR("failed to create iterator\n");
		goto exit;
	}

	DEBUG_INFO("Dumping dict...\n");
	while ((key = OSDynamicCast(OSSymbol, iter->getNextObject()))) {
		count++;
		DEBUG_INFO("%u: %s\n", count, key->getCStringNoCopy());
	}

exit:
	return;
}

// ************************** IODTNVRAMPlatformNotifier ****************************
// private IOService based class for passing notifications to IODTNVRAM

class IODTNVRAMPlatformNotifier : public IOService
{
	OSDeclareDefaultStructors(IODTNVRAMPlatformNotifier)
private:
	IODTNVRAM *_provider;

public:
	bool start(IOService * provider) APPLE_KEXT_OVERRIDE;

	virtual IOReturn callPlatformFunction( const OSSymbol * functionName,
	    bool waitForFunction,
	    void *param1, void *param2,
	    void *param3, void *param4 ) APPLE_KEXT_OVERRIDE;
};

OSDefineMetaClassAndStructors(IODTNVRAMPlatformNotifier, IOService)

bool
IODTNVRAMPlatformNotifier::start(IOService * provider)
{
	OSSharedPtr<OSSerializer> serializer;
	OSSharedPtr<OSNumber> value = OSNumber::withNumber(1000, 32);

	_provider = OSDynamicCast(IODTNVRAM, provider);
	require(_provider != nullptr, error);

	setProperty(gIOPlatformWakeActionKey, value.get());

	require(super::start(provider), error);

	registerService();

	return true;

error:
	stop(provider);

	return false;
}

#include <IOKit/IOHibernatePrivate.h>
#include <IOKit/pwr_mgt/RootDomain.h>
static const OSSharedPtr<const OSSymbol> gIOHibernateStateKey = OSSymbol::withCString(kIOHibernateStateKey);

static uint32_t
hibernateState(void)
{
	OSSharedPtr<OSData> data = OSDynamicPtrCast<OSData>(IOService::getPMRootDomain()->copyProperty(gIOHibernateStateKey.get()->getCStringNoCopy()));
	uint32_t hibernateState = 0;
	if ((data != NULL) && (data->getLength() == sizeof(hibernateState))) {
		memcpy(&hibernateState, data->getBytesNoCopy(), sizeof(hibernateState));
	}
	return hibernateState;
}

IOReturn
IODTNVRAMPlatformNotifier::callPlatformFunction( const OSSymbol * functionName,
    bool waitForFunction,
    void *param1, void *param2,
    void *param3, void *param4 )
{
	if ((functionName == gIOPlatformWakeActionKey) &&
	    (hibernateState() == kIOHibernateStateWakingFromHibernate)) {
		DEBUG_INFO("waking from hibernate\n");
		_provider->reload();
		return kIOReturnSuccess;
	}

	return super::callPlatformFunction(functionName, waitForFunction, param1, param2, param3, param4);
}


// ************************** IODTNVRAMDiags ****************************
// private IOService based class for passing notifications to IODTNVRAM
#define kIODTNVRAMDiagsStatsKey   "Stats"
#define kIODTNVRAMDiagsInitKey    "Init"
#define kIODTNVRAMDiagsReadKey    "Read"
#define kIODTNVRAMDiagsWriteKey   "Write"
#define kIODTNVRAMDiagsDeleteKey  "Delete"
#define kIODTNVRAMDiagsNameKey    "Name"
#define kIODTNVRAMDiagsSizeKey    "Size"
#define kIODTNVRAMDiagsPresentKey "Present"

// private IOService based class for publishing diagnostic info for IODTNVRAM
class IODTNVRAMDiags : public IOService
{
	OSDeclareDefaultStructors(IODTNVRAMDiags)
private:
	IODTNVRAM                 *_provider;
	IORWLock                  *_variableLock;
	OSSharedPtr<OSDictionary> _stats;

	bool serializeStats(void *, OSSerialize * serializer);

public:
	bool start(IOService * provider) APPLE_KEXT_OVERRIDE;
	void logVariable(NVRAMPartitionType region, IONVRAMOperation op, const char *name, void *data);
};

OSDefineMetaClassAndStructors(IODTNVRAMDiags, IOService)

bool
IODTNVRAMDiags::start(IOService * provider)
{
	OSSharedPtr<OSSerializer> serializer;

	_provider = OSDynamicCast(IODTNVRAM, provider);
	require(_provider != nullptr, error);

	require(super::start(provider), error);

	_variableLock = IORWLockAlloc();
	require(_variableLock != nullptr, error);

	_stats = OSDictionary::withCapacity(1);
	require(_stats != nullptr, error);

	serializer = OSSerializer::forTarget(this, OSMemberFunctionCast(OSSerializerCallback, this, &IODTNVRAMDiags::serializeStats));
	require(serializer != nullptr, error);

	setProperty(kIODTNVRAMDiagsStatsKey, serializer.get());

	registerService();

	return true;

error:
	stop(provider);

	return false;
}

void
IODTNVRAMDiags::logVariable(NVRAMPartitionType region, IONVRAMOperation op, const char *name, void *data)
{
	// "Stats"        : OSDictionary
	// - "XX:varName" : OSDictionary, XX is the region value prefix to distinguish which dictionary the variable is in
	//   - "Init"     : OSBoolean True/present if variable present at initialization
	//   - "Read"     : OSNumber count
	//   - "Write"    : OSNumber count
	//   - "Delete"   : OSNumber count
	//   - "Size"     : OSNumber size, latest size from either init or write
	//   - "Present"  : OSBoolean True/False if variable is present or not
	char                      *entryKey;
	size_t                    entryKeySize;
	OSSharedPtr<OSDictionary> existingEntry;
	OSSharedPtr<OSNumber>     currentCount;
	OSSharedPtr<OSNumber>     varSize;
	const char                *opCountKey = nullptr;

	entryKeySize = strlen("XX:") + strlen(name) +  1;
	entryKey = IONewData(char, entryKeySize);
	require(entryKey, exit);

	snprintf(entryKey, entryKeySize, "%02X:%s", region, name);

	NVRAMWRITELOCK();
	existingEntry.reset(OSDynamicCast(OSDictionary, _stats->getObject(entryKey)), OSRetain);

	if (existingEntry == nullptr) {
		existingEntry = OSDictionary::withCapacity(4);
	}

	switch (op) {
	case kIONVRAMOperationRead:
		opCountKey = kIODTNVRAMDiagsReadKey;
		if (existingEntry->getObject(kIODTNVRAMDiagsPresentKey) == nullptr) {
			existingEntry->setObject(kIODTNVRAMDiagsPresentKey, kOSBooleanFalse);
		}
		break;
	case kIONVRAMOperationWrite:
		opCountKey = kIODTNVRAMDiagsWriteKey;
		varSize = OSNumber::withNumber((size_t)data, 64);
		existingEntry->setObject(kIODTNVRAMDiagsSizeKey, varSize);
		existingEntry->setObject(kIODTNVRAMDiagsPresentKey, kOSBooleanTrue);
		break;
	case kIONVRAMOperationDelete:
	case kIONVRAMOperationObliterate:
	case kIONVRAMOperationReset:
		opCountKey = kIODTNVRAMDiagsDeleteKey;
		existingEntry->setObject(kIODTNVRAMDiagsPresentKey, kOSBooleanFalse);
		break;
	case kIONVRAMOperationInit:
		varSize = OSNumber::withNumber((size_t)data, 64);
		existingEntry->setObject(kIODTNVRAMDiagsInitKey, varSize);
		existingEntry->setObject(kIODTNVRAMDiagsSizeKey, varSize);
		existingEntry->setObject(kIODTNVRAMDiagsPresentKey, kOSBooleanTrue);
		break;
	default:
		goto unlock;
	}

	if (opCountKey) {
		currentCount.reset(OSDynamicCast(OSNumber, existingEntry->getObject(opCountKey)), OSRetain);

		if (currentCount == nullptr) {
			currentCount = OSNumber::withNumber(1, 64);
		} else {
			currentCount->addValue(1);
		}

		existingEntry->setObject(opCountKey, currentCount);
	}

	_stats->setObject(entryKey, existingEntry);

unlock:
	NVRAMUNLOCK();

exit:
	IODeleteData(entryKey, char, entryKeySize);

	return;
}

bool
IODTNVRAMDiags::serializeStats(void *, OSSerialize * serializer)
{
	bool ok;

	NVRAMREADLOCK();
	ok = _stats->serialize(serializer);
	NVRAMUNLOCK();

	return ok;
}

// ************************** IODTNVRAMVariables ****************************

// private IOService based class for publishing distinct dictionary properties on
// for easy ioreg access since the serializeProperties call is overloaded and is used
// as variable access
class IODTNVRAMVariables : public IOService
{
	OSDeclareDefaultStructors(IODTNVRAMVariables)
private:
	IODTNVRAM        *_provider;
	uuid_t           _guid;
	bool             _systemActive;

public:
	bool                    init(const uuid_t guid, const bool systemActive);
	virtual bool            start(IOService * provider) APPLE_KEXT_OVERRIDE;

	virtual bool            serializeProperties(OSSerialize *s) const APPLE_KEXT_OVERRIDE;
	virtual OSPtr<OSObject> copyProperty(const OSSymbol *aKey) const APPLE_KEXT_OVERRIDE;
	virtual OSObject        *getProperty(const OSSymbol *aKey) const APPLE_KEXT_OVERRIDE;
	virtual bool            setProperty(const OSSymbol *aKey, OSObject *anObject) APPLE_KEXT_OVERRIDE;
	virtual IOReturn        setProperties(OSObject *properties) APPLE_KEXT_OVERRIDE;
	virtual void            removeProperty(const OSSymbol *aKey) APPLE_KEXT_OVERRIDE;
};

OSDefineMetaClassAndStructors(IODTNVRAMVariables, IOService)

bool
IODTNVRAMVariables::init(const uuid_t guid, const bool systemActive)
{
	require(super::init(), fail);

	uuid_copy(_guid, guid);
	_systemActive = systemActive;

	return true;

fail:
	return false;
}

bool
IODTNVRAMVariables::start(IOService * provider)
{
	_provider = OSDynamicCast(IODTNVRAM, provider);
	if (_provider == nullptr) {
		goto error;
	}

	if (!super::start(provider)) {
		goto error;
	}

	registerService();

	return true;

error:
	stop(provider);

	return false;
}

bool
IODTNVRAMVariables::serializeProperties(OSSerialize *s) const
{
	const OSSymbol                    *key;
	OSSharedPtr<OSDictionary>         dict;
	OSSharedPtr<OSCollectionIterator> iter;
	OSSharedPtr<OSDictionary>         localVariables = _provider->_varDict;
	bool                              ok = false;

	dict = OSDictionary::withCapacity(localVariables->getCount());
	if (dict == nullptr) {
		DEBUG_ERROR("No dictionary\n");
		goto exit;
	}

	iter = OSCollectionIterator::withCollection(localVariables.get());
	if (iter == nullptr) {
		DEBUG_ERROR("failed to create iterator\n");
		goto exit;
	}

	while ((key = OSDynamicCast(OSSymbol, iter->getNextObject()))) {
		if (verifyPermission(kIONVRAMOperationRead, key, _systemActive)) {
			uuid_t guid;
			const char *name;

			parseVariableName(key, &guid, &name);

			if (uuid_compare(_guid, guid) == 0) {
				OSSharedPtr<const OSSymbol> sym = OSSymbol::withCString(name);
				dict->setObject(sym.get(), localVariables->getObject(key));
			}
		}
	}

	ok = dict->serialize(s);

exit:
	DEBUG_INFO("ok=%d\n", ok);
	return ok;
}

OSPtr<OSObject>
IODTNVRAMVariables::copyProperty(const OSSymbol *aKey) const
{
	if (_provider && !skipKey(aKey)) {
		DEBUG_INFO("aKey=%s\n", aKey->getCStringNoCopy());

		return _provider->copyPropertyWithGUIDAndName(_guid, aKey->getCStringNoCopy());
	} else {
		return nullptr;
	}
}

OSObject *
IODTNVRAMVariables::getProperty(const OSSymbol *aKey) const
{
	OSSharedPtr<OSObject> theObject = copyProperty(aKey);

	return theObject.get();
}

bool
IODTNVRAMVariables::setProperty(const OSSymbol *aKey, OSObject *anObject)
{
	if (_provider) {
		return _provider->setPropertyWithGUIDAndName(_guid, aKey->getCStringNoCopy(), anObject) == kIOReturnSuccess;
	} else {
		return false;
	}
}

IOReturn
IODTNVRAMVariables::setProperties(OSObject *properties)
{
	IOReturn                          ret = kIOReturnSuccess;
	OSObject                          *object;
	const OSSymbol                    *key;
	OSDictionary                      *dict;
	OSSharedPtr<OSCollectionIterator> iter;

	dict = OSDynamicCast(OSDictionary, properties);
	if (dict == nullptr) {
		DEBUG_ERROR("Not a dictionary\n");
		return kIOReturnBadArgument;
	}

	iter = OSCollectionIterator::withCollection(dict);
	if (iter == nullptr) {
		DEBUG_ERROR("Couldn't create iterator\n");
		return kIOReturnBadArgument;
	}

	while (ret == kIOReturnSuccess) {
		key = OSDynamicCast(OSSymbol, iter->getNextObject());
		if (key == nullptr) {
			break;
		}

		object = dict->getObject(key);
		if (object == nullptr) {
			continue;
		}

		ret = _provider->setPropertyWithGUIDAndName(_guid, key->getCStringNoCopy(), object);
	}

	DEBUG_INFO("ret=%#08x\n", ret);

	return ret;
}

void
IODTNVRAMVariables::removeProperty(const OSSymbol *aKey)
{
	_provider->removePropertyWithGUIDAndName(_guid, aKey->getCStringNoCopy());
}

// ************************** Format Handlers ***************************
class IODTNVRAMFormatHandler
{
protected:
	uint32_t _bankSize;
	uint32_t _bankCount;
	uint32_t _currentBank;

public:
	virtual
	~IODTNVRAMFormatHandler();
	virtual bool     getNVRAMProperties(void);
	virtual IOReturn unserializeVariables(void) = 0;
	virtual IOReturn setVariable(const uuid_t varGuid, const char *variableName, OSObject *object) = 0;
	virtual bool     setController(IONVRAMController *_nvramController) = 0;
	virtual bool     sync(void) = 0;
	virtual IOReturn flush(const uuid_t guid, IONVRAMOperation op) = 0;
	virtual void     reload(void) = 0;
	virtual uint32_t getGeneration(void) const = 0;
	virtual uint32_t getVersion(void) const = 0;
	virtual uint32_t getSystemUsed(void) const = 0;
	virtual uint32_t getCommonUsed(void) const = 0;
	virtual bool     getSystemPartitionActive(void) const = 0;
};

IODTNVRAMFormatHandler::~IODTNVRAMFormatHandler()
{
}

bool
IODTNVRAMFormatHandler::getNVRAMProperties()
{
	bool                         ok    = false;
	OSSharedPtr<IORegistryEntry> entry;
	OSSharedPtr<OSObject>        prop;
	OSData *                     data;

	entry = IORegistryEntry::fromPath("/chosen", gIODTPlane);
	require_action(entry, exit, DEBUG_ERROR("Unable to find chosen node\n"));

	prop = entry->copyProperty(kNVRAMBankSizeKey);
	require_action(prop, exit, DEBUG_ERROR("Unable to find %s property\n", kNVRAMBankSizeKey));

	data = OSDynamicCast(OSData, prop.get());
	require(data, exit);

	_bankSize = *((uint32_t *)data->getBytesNoCopy());

	prop = entry->copyProperty(kNVRAMBankCountKey);
	require_action(prop, exit, DEBUG_ERROR("Unable to find %s property\n", kNVRAMBankCountKey));

	data = OSDynamicCast(OSData, prop.get());
	require(data, exit);

	_bankCount = *((uint32_t *)data->getBytesNoCopy());

	prop = entry->copyProperty(kNVRAMCurrentBankKey);
	require_action(prop, exit, DEBUG_ERROR("Unable to find %s property\n", kNVRAMCurrentBankKey));

	data = OSDynamicCast(OSData, prop.get());
	require(data, exit);

	_currentBank = *((uint32_t *)data->getBytesNoCopy());

	ok = true;

	DEBUG_ALWAYS("_bankSize=%#X, _bankCount=%#X, _currentBank=%#X\n", _bankSize, _bankCount, _currentBank);

exit:
	return ok;
}

#include "IONVRAMCHRPHandler.cpp"

#include "IONVRAMV3Handler.cpp"

// **************************** IODTNVRAM *********************************

bool
IODTNVRAM::init(IORegistryEntry *old, const IORegistryPlane *plane)
{
	OSSharedPtr<OSDictionary> dict;

	DEBUG_INFO("...\n");

	require(super::init(old, plane), fail);

#if XNU_TARGET_OS_OSX
#if CONFIG_CSR
	gInternalBuild = (csr_check(CSR_ALLOW_APPLE_INTERNAL) == 0);
	DEBUG_INFO("gInternalBuild = %d\n", gInternalBuild);
#endif // CONFIG_CSR
#endif // XNU_TARGET_OS_OSX

	_variableLock = IORWLockAlloc();
	require(_variableLock != nullptr, fail);

	_controllerLock = IOLockAlloc();
	require(_controllerLock != nullptr, fail);

	// Clear the IORegistryEntry property table
	dict =  OSDictionary::withCapacity(1);
	require(dict != nullptr, fail);

	setPropertyTable(dict.get());
	dict.reset();

	return true;

fail:
	return false;
}

bool
IODTNVRAM::start(IOService *provider)
{
	OSSharedPtr<OSNumber> version;

	DEBUG_INFO("...\n");

	require(super::start(provider), fail);

	// Check if our overridden init function was called
	// If not, skip any additional initialization being done here.
	// This is not an error we just need to successfully exit this function to allow
	// AppleEFIRuntime to proceed and take over operation
	require_action(_controllerLock != nullptr, no_common, DEBUG_INFO("x86 init\n"));

	_diags = new IODTNVRAMDiags;
	if (!_diags || !_diags->init()) {
		DEBUG_ERROR("Unable to create/init the diags service\n");
		OSSafeReleaseNULL(_diags);
		goto fail;
	}

	if (!_diags->attach(this)) {
		DEBUG_ERROR("Unable to attach the diags service!\n");
		OSSafeReleaseNULL(_diags);
		goto fail;
	}

	if (!_diags->start(this)) {
		DEBUG_ERROR("Unable to start the diags service!\n");
		_diags->detach(this);
		OSSafeReleaseNULL(_diags);
		goto fail;
	}

	_notifier = new IODTNVRAMPlatformNotifier;
	if (!_notifier || !_notifier->init()) {
		DEBUG_ERROR("Unable to create/init the notifier service\n");
		OSSafeReleaseNULL(_notifier);
		goto fail;
	}

	if (!_notifier->attach(this)) {
		DEBUG_ERROR("Unable to attach the notifier service!\n");
		OSSafeReleaseNULL(_notifier);
		goto fail;
	}

	if (!_notifier->start(this)) {
		DEBUG_ERROR("Unable to start the notifier service!\n");
		_notifier->detach(this);
		OSSafeReleaseNULL(_notifier);
		goto fail;
	}

	// This will load the proxied variable data which will call back into
	// IODTNVRAM for the variable sets which will also update the system/common services
	initImageFormat();

	version = OSNumber::withNumber(_format->getVersion(), 32);
	_diags->setProperty(kCurrentNVRAMVersionKey, version.get());

	if (_format->getSystemUsed()) {
		_systemService = new IODTNVRAMVariables;

		if (!_systemService || !_systemService->init(gAppleSystemVariableGuid, _format->getSystemPartitionActive())) {
			DEBUG_ERROR("Unable to start the system service!\n");
			OSSafeReleaseNULL(_systemService);
			goto no_system;
		}

		_systemService->setName("options-system");

		if (!_systemService->attach(this)) {
			DEBUG_ERROR("Unable to attach the system service!\n");
			OSSafeReleaseNULL(_systemService);
			goto no_system;
		}

		if (!_systemService->start(this)) {
			DEBUG_ERROR("Unable to start the system service!\n");
			_systemService->detach(this);
			OSSafeReleaseNULL(_systemService);
			goto no_system;
		}
	}

no_system:
	_commonService = new IODTNVRAMVariables;

	if (!_commonService || !_commonService->init(gAppleNVRAMGuid, _format->getSystemPartitionActive())) {
		DEBUG_ERROR("Unable to start the common service!\n");
		OSSafeReleaseNULL(_commonService);
		goto no_common;
	}

	_commonService->setName("options-common");

	if (!_commonService->attach(this)) {
		DEBUG_ERROR("Unable to attach the common service!\n");
		OSSafeReleaseNULL(_commonService);
		goto no_common;
	}

	if (!_commonService->start(this)) {
		DEBUG_ERROR("Unable to start the common service!\n");
		_commonService->detach(this);
		OSSafeReleaseNULL(_commonService);
		goto no_common;
	}

no_common:
	return true;

fail:
	stop(provider);
	return false;
}

void
IODTNVRAM::initImageFormat(void)
{
	OSSharedPtr<IORegistryEntry> entry;
	OSSharedPtr<OSObject>        prop;
	const char                   *proxyDataKey = "nvram-proxy-data";
	const char                   *bankSizeKey = "nvram-bank-size";
	OSData                       *data = nullptr;
	uint32_t                     size = 0;
	const uint8_t                *image = nullptr;

	entry = IORegistryEntry::fromPath("/chosen", gIODTPlane);

	require(entry != nullptr, skip);

	prop = entry->copyProperty(bankSizeKey);
	require(prop != nullptr, skip);

	data = OSDynamicCast(OSData, prop.get());
	require(data != nullptr, skip);

	size = *((uint32_t*)data->getBytesNoCopy());
	require_action(size != 0, skip, panic("NVRAM size is 0 bytes, possibly due to bad config with iBoot + xnu mismatch"));
	DEBUG_ALWAYS("NVRAM size is %u bytes\n", size);

	prop = entry->copyProperty(proxyDataKey);
	require(prop != nullptr, skip);

	data = OSDynamicCast(OSData, prop.get());
	require_action(data != nullptr, skip, DEBUG_ERROR("No proxy data!\n"));

	image = (const uint8_t *)data->getBytesNoCopy();

skip:
	if (IONVRAMV3Handler::isValidImage(image, size)) {
		_format = IONVRAMV3Handler::init(this, image, size, _varDict);
		require_action(_format, skip, panic("IONVRAMV3Handler creation failed\n"));
	} else {
		_format = IONVRAMCHRPHandler::init(this, image, size, _varDict);
		require_action(_format, skip, panic("IONVRAMCHRPHandler creation failed\n"));
	}

	_format->unserializeVariables();

	dumpDict(_varDict.get());

#if defined(RELEASE)
	if (entry != nullptr) {
		entry->removeProperty(proxyDataKey);
	}
#endif

	_lastDeviceSync = 0;
	_freshInterval = true;
}

void
IODTNVRAM::registerNVRAMController(IONVRAMController *controller)
{
	DEBUG_INFO("setting controller\n");

	NVRAMWRITELOCK();
	CONTROLLERLOCK();

	_format->setController(controller);

	CONTROLLERUNLOCK();
	NVRAMUNLOCK();

	return;
}

bool
IODTNVRAM::safeToSync(void)
{
	AbsoluteTime delta;
	UInt64       delta_ns;
	SInt32       delta_secs;

	// delta interval went by
	clock_get_uptime(&delta);

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

	if ((delta_secs > (_lastDeviceSync + MIN_SYNC_NOW_INTERVAL)) || _freshInterval) {
		_lastDeviceSync = delta_secs;
		_freshInterval = false;
		return true;
	}

	return false;
}

void
IODTNVRAM::syncInternal(bool rateLimit)
{
	DEBUG_INFO("rateLimit=%d\n", rateLimit);

	if (!SAFE_TO_LOCK()) {
		DEBUG_INFO("cannot lock\n");
		return;
	}

	// Rate limit requests to sync. Drivers that need this rate limiting will
	// shadow the data and only write to flash when they get a sync call
	if (rateLimit) {
		if (safeToSync() == false) {
			DEBUG_INFO("safeToSync()=false\n");
			return;
		}
	}

	DEBUG_INFO("Calling sync()\n");
	record_system_event(SYSTEM_EVENT_TYPE_INFO, SYSTEM_EVENT_SUBSYSTEM_NVRAM, "sync", "triggered");

	NVRAMREADLOCK();
	CONTROLLERLOCK();

	_format->sync();

	CONTROLLERUNLOCK();
	NVRAMUNLOCK();

	if (_diags) {
		OSSharedPtr<OSNumber> generation = OSNumber::withNumber(_format->getGeneration(), 32);
		_diags->setProperty(kCurrentGenerationCountKey, generation.get());
	}
}

void
IODTNVRAM::sync(void)
{
	syncInternal(false);
}

void
IODTNVRAM::reload(void)
{
	_format->reload();
}

bool
IODTNVRAM::serializeProperties(OSSerialize *s) const
{
	const OSSymbol                    *canonicalKey;
	OSSharedPtr<OSDictionary>         localVarDict, returnDict;
	OSSharedPtr<OSCollectionIterator> iter;
	bool                              ok = false;
	unsigned int                      totalCapacity = 0;
	uuid_t                            varGuid;
	const char *                      varName;

	NVRAMREADLOCK();
	if (_varDict) {
		localVarDict = OSDictionary::withDictionary(_varDict.get());
	}
	NVRAMUNLOCK();

	if (localVarDict != nullptr) {
		totalCapacity =  localVarDict->getCapacity();
	}

	returnDict = OSDictionary::withCapacity(totalCapacity);

	if (returnDict == nullptr) {
		DEBUG_ERROR("No dictionary\n");
		goto exit;
	}

	// Copy system entries first if present then copy unique other entries
	iter = OSCollectionIterator::withCollection(localVarDict.get());
	if (iter == nullptr) {
		DEBUG_ERROR("failed to create iterator\n");
		goto exit;
	}

	while ((canonicalKey = OSDynamicCast(OSSymbol, iter->getNextObject()))) {
		parseVariableName(canonicalKey, &varGuid, &varName);

		if ((uuid_compare(varGuid, gAppleSystemVariableGuid) == 0) &&
		    verifyPermission(kIONVRAMOperationRead, varGuid, varName, _format->getSystemPartitionActive())) {
			OSSharedPtr<const OSSymbol> returnKey = OSSymbol::withCString(varName);
			returnDict->setObject(returnKey.get(), localVarDict->getObject(canonicalKey));
		}
	}

	iter.reset();

	iter = OSCollectionIterator::withCollection(localVarDict.get());
	if (iter == nullptr) {
		DEBUG_ERROR("failed to create iterator\n");
		goto exit;
	}

	while ((canonicalKey = OSDynamicCast(OSSymbol, iter->getNextObject()))) {
		parseVariableName(canonicalKey, &varGuid, &varName);

		if (uuid_compare(varGuid, gAppleNVRAMGuid) == 0) {
			if (returnDict->getObject(varName) != nullptr) {
				// Skip non uniques
				continue;
			}

			if (verifyPermission(kIONVRAMOperationRead, varGuid, varName, _format->getSystemPartitionActive())) {
				OSSharedPtr<const OSSymbol> returnKey = OSSymbol::withCString(varName);
				returnDict->setObject(returnKey.get(), localVarDict->getObject(canonicalKey));
			}
		}
	}

	ok = returnDict->serialize(s);

exit:
	DEBUG_INFO("ok=%d\n", ok);

	return ok;
}

IOReturn
IODTNVRAM::flushGUID(const uuid_t guid, IONVRAMOperation op)
{
	IOReturn ret = kIOReturnSuccess;

	if (_format->getSystemPartitionActive() && (uuid_compare(guid, gAppleSystemVariableGuid) == 0)) {
		ret = _format->flush(guid, op);

		DEBUG_INFO("system variables flushed, ret=%08x\n", ret);
	} else if (uuid_compare(guid, gAppleNVRAMGuid) == 0) {
		ret = _format->flush(guid, op);

		DEBUG_INFO("common variables flushed, ret=%08x\n", ret);
	}

	return ret;
}

bool
IODTNVRAM::handleSpecialVariables(const char *name, const uuid_t guid, const OSObject *obj, IOReturn *error)
{
	IOReturn ret = kIOReturnSuccess;
	bool special = false;

	NVRAMLOCKASSERTEXCLUSIVE();

	// ResetNVRam flushes both regions in one call
	// Obliterate can flush either separately
	if (strcmp(name, "ObliterateNVRam") == 0) {
		special = true;
		ret = flushGUID(guid, kIONVRAMOperationObliterate);
	} else if (strcmp(name, "ResetNVRam") == 0) {
		special = true;
		ret = flushGUID(gAppleSystemVariableGuid, kIONVRAMOperationReset);

		if (ret != kIOReturnSuccess) {
			goto exit;
		}

		ret = flushGUID(gAppleNVRAMGuid, kIONVRAMOperationReset);
	}

exit:
	if (error) {
		*error = ret;
	}

	return special;
}

OSSharedPtr<OSObject>
IODTNVRAM::copyPropertyWithGUIDAndName(const uuid_t guid, const char *name) const
{
	OSSharedPtr<const OSSymbol> canonicalKey;
	OSSharedPtr<OSObject>       theObject;
	uuid_t                      newGuid;

	if (_varDict == nullptr) {
		DEBUG_INFO("No dictionary\n");
		goto exit;
	}

	if (!verifyPermission(kIONVRAMOperationRead, guid, name, _format->getSystemPartitionActive())) {
		DEBUG_INFO("Not privileged\n");
		goto exit;
	}

	translateGUID(guid, name, newGuid, _format->getSystemPartitionActive());

	canonicalKey = keyWithGuidAndCString(newGuid, name);

	NVRAMREADLOCK();
	theObject.reset(_varDict->getObject(canonicalKey.get()), OSRetain);
	NVRAMUNLOCK();

	if (_diags) {
		_diags->logVariable(getPartitionTypeForGUID(newGuid), kIONVRAMOperationRead, name, NULL);
	}

	if (theObject != nullptr) {
		DEBUG_INFO("%s has object\n", canonicalKey.get()->getCStringNoCopy());
	} else {
		DEBUG_INFO("%s no entry\n", canonicalKey.get()->getCStringNoCopy());
	}

exit:
	return theObject;
}

OSSharedPtr<OSObject>
IODTNVRAM::copyProperty(const OSSymbol *aKey) const
{
	const char            *variableName;
	uuid_t                varGuid;

	if (skipKey(aKey)) {
		return nullptr;
	}
	DEBUG_INFO("aKey=%s\n", aKey->getCStringNoCopy());

	parseVariableName(aKey->getCStringNoCopy(), &varGuid, &variableName);

	return copyPropertyWithGUIDAndName(varGuid, variableName);
}

OSSharedPtr<OSObject>
IODTNVRAM::copyProperty(const char *aKey) const
{
	OSSharedPtr<const OSSymbol> keySymbol;
	OSSharedPtr<OSObject>       theObject;

	keySymbol = OSSymbol::withCString(aKey);
	if (keySymbol != nullptr) {
		theObject = copyProperty(keySymbol.get());
	}

	return theObject;
}

OSObject *
IODTNVRAM::getProperty(const OSSymbol *aKey) const
{
	// The shared pointer gets released at the end of the function,
	// and returns a view into theObject.
	OSSharedPtr<OSObject> theObject = copyProperty(aKey);

	return theObject.get();
}

OSObject *
IODTNVRAM::getProperty(const char *aKey) const
{
	// The shared pointer gets released at the end of the function,
	// and returns a view into theObject.
	OSSharedPtr<OSObject> theObject = copyProperty(aKey);

	return theObject.get();
}

IOReturn
IODTNVRAM::setPropertyWithGUIDAndName(const uuid_t guid, const char *name, OSObject *anObject)
{
	IOReturn              ret = kIOReturnSuccess;
	bool                  remove = false;
	OSString              *tmpString = nullptr;
	OSSharedPtr<OSObject> propObject;
	OSSharedPtr<OSObject> sharedObject(anObject, OSRetain);
	bool                  deletePropertyKey, syncNowPropertyKey, forceSyncNowPropertyKey;
	bool                  ok;
	size_t                propDataSize = 0;
	uuid_t                newGuid;

	deletePropertyKey = strncmp(name, kIONVRAMDeletePropertyKey, sizeof(kIONVRAMDeletePropertyKey)) == 0;
	syncNowPropertyKey = strncmp(name, kIONVRAMSyncNowPropertyKey, sizeof(kIONVRAMSyncNowPropertyKey)) == 0;
	forceSyncNowPropertyKey = strncmp(name, kIONVRAMForceSyncNowPropertyKey, sizeof(kIONVRAMForceSyncNowPropertyKey)) == 0;

	if (deletePropertyKey) {
		tmpString = OSDynamicCast(OSString, anObject);
		if (tmpString != nullptr) {
			const char *variableName;
			uuid_t     valueVarGuid;
			bool       guidProvided;
			IOReturn   removeRet;

			guidProvided = parseVariableName(tmpString->getCStringNoCopy(), &valueVarGuid, &variableName);

			// nvram tool will provide a "nvram -d var" or "nvram -d guid:var" as
			// kIONVRAMDeletePropertyKey=var or kIONVRAMDeletePropertyKey=guid:var
			// that will come into this function as (gAppleNVRAMGuid, varname, nullptr)
			// if we provide the "-z" flag to the nvram tool this function will come in as
			// (gAppleSystemVariableGuid, varname, nullptr). We are reparsing the value string,
			// if there is a GUID provided with the value then use that GUID otherwise use the
			// guid that was provided via the node selection or default.
			if (guidProvided == false) {
				DEBUG_INFO("Removing with API provided GUID\n");
				removeRet = removePropertyWithGUIDAndName(guid, variableName);
			} else {
				DEBUG_INFO("Removing with value provided GUID\n");
				removeRet = removePropertyWithGUIDAndName(valueVarGuid, variableName);
			}

			DEBUG_INFO("kIONVRAMDeletePropertyKey found, removeRet=%#08x\n", removeRet);
		} else {
			DEBUG_INFO("kIONVRAMDeletePropertyKey value needs to be an OSString\n");
			ret = kIOReturnError;
		}
		goto exit;
	} else if (syncNowPropertyKey || forceSyncNowPropertyKey) {
		tmpString = OSDynamicCast(OSString, anObject);
		DEBUG_INFO("NVRAM sync key %s found\n", name);
		if (tmpString != nullptr) {
			// We still want to throttle NVRAM commit rate for SyncNow. ForceSyncNow is provided as a really big hammer.
			syncInternal(syncNowPropertyKey);
		} else {
			DEBUG_INFO("%s value needs to be an OSString\n", name);
			ret = kIOReturnError;
		}
		goto exit;
	}

	if (!verifyPermission(kIONVRAMOperationWrite, guid, name, _format->getSystemPartitionActive())) {
		DEBUG_INFO("Not privileged\n");
		ret = kIOReturnNotPrivileged;
		goto exit;
	}

	// Make sure the object is of the correct type.
	switch (getVariableType(name)) {
	case kOFVariableTypeBoolean:
		propObject = OSDynamicPtrCast<OSBoolean>(sharedObject);
		if (propObject) {
			record_system_event(SYSTEM_EVENT_TYPE_INFO, SYSTEM_EVENT_SUBSYSTEM_NVRAM, "write", "%s as bool to %d", name, ((OSBoolean *)propObject.get())->getValue());
		}
		break;

	case kOFVariableTypeNumber:
		propObject = OSDynamicPtrCast<OSNumber>(sharedObject);
		if (propObject) {
			record_system_event(SYSTEM_EVENT_TYPE_INFO, SYSTEM_EVENT_SUBSYSTEM_NVRAM, "write", "%s as number to %#llx", name, ((OSNumber *)propObject.get())->unsigned64BitValue());
		}
		break;

	case kOFVariableTypeString:
		propObject = OSDynamicPtrCast<OSString>(sharedObject);
		if (propObject != nullptr) {
			record_system_event(SYSTEM_EVENT_TYPE_INFO, SYSTEM_EVENT_SUBSYSTEM_NVRAM, "write", "%s as string to %s", name, ((OSString *)propObject.get())->getCStringNoCopy());

			propDataSize = (OSDynamicPtrCast<OSString>(propObject))->getLength();

			if ((strncmp(name, kIONVRAMBootArgsKey, sizeof(kIONVRAMBootArgsKey)) == 0) && (propDataSize >= BOOT_LINE_LENGTH)) {
				DEBUG_ERROR("boot-args size too large for BOOT_LINE_LENGTH, propDataSize=%zu\n", propDataSize);
				ret = kIOReturnNoSpace;
				goto exit;
			}
		}
		break;

	case kOFVariableTypeData:
		propObject = OSDynamicPtrCast<OSData>(sharedObject);
		if (propObject == nullptr) {
			tmpString = OSDynamicCast(OSString, sharedObject.get());
			if (tmpString != nullptr) {
				propObject = OSData::withBytes(tmpString->getCStringNoCopy(),
				    tmpString->getLength());
			}
		}

		if (propObject != nullptr) {
			propDataSize = (OSDynamicPtrCast<OSData>(propObject))->getLength();
			record_system_event(SYSTEM_EVENT_TYPE_INFO, SYSTEM_EVENT_SUBSYSTEM_NVRAM, "write", "%s as data with size %#x", name, ((OSData *)propObject.get())->getLength());
		}

#if defined(XNU_TARGET_OS_OSX)
		if ((propObject != nullptr) && ((OSDynamicPtrCast<OSData>(propObject))->getLength() == 0)) {
			remove = true;
		}
#endif /* defined(XNU_TARGET_OS_OSX) */
		break;
	default:
		break;
	}

	if (propObject == nullptr) {
		DEBUG_ERROR("No property object\n");
		ret = kIOReturnBadArgument;
		goto exit;
	}

	if (!verifyWriteSizeLimit(guid, name, propDataSize)) {
		DEBUG_ERROR("Property data size of %zu too long for %s\n", propDataSize, name);
		ret = kIOReturnNoSpace;
		goto exit;
	}

	NVRAMWRITELOCK();
	ok = handleSpecialVariables(name, guid, propObject.get(), &ret);
	NVRAMUNLOCK();

	if (ok) {
		goto exit;
	}

	if (remove == false) {
		DEBUG_INFO("Adding object\n");

		translateGUID(guid, name, newGuid, _format->getSystemPartitionActive());

		NVRAMWRITELOCK();

		ret = _format->setVariable(newGuid, name, propObject.get());

		NVRAMUNLOCK();
	} else {
		DEBUG_INFO("Removing object\n");
		ret = removePropertyWithGUIDAndName(guid, name);
	}

	if (tmpString) {
		propObject.reset();
	}

exit:
	DEBUG_INFO("ret=%#08x\n", ret);

	return ret;
}

IOReturn
IODTNVRAM::setPropertyInternal(const OSSymbol *aKey, OSObject *anObject)
{
	const char *variableName;
	uuid_t     varGuid;

	DEBUG_INFO("aKey=%s\n", aKey->getCStringNoCopy());

	parseVariableName(aKey->getCStringNoCopy(), &varGuid, &variableName);

	return setPropertyWithGUIDAndName(varGuid, variableName, anObject);
}

bool
IODTNVRAM::setProperty(const OSSymbol *aKey, OSObject *anObject)
{
	return setPropertyInternal(aKey, anObject) == kIOReturnSuccess;
}

void
IODTNVRAM::removeProperty(const OSSymbol *aKey)
{
	IOReturn ret;

	ret = removePropertyInternal(aKey);

	if (ret != kIOReturnSuccess) {
		DEBUG_INFO("removePropertyInternal failed, ret=%#08x\n", ret);
	}
}

IOReturn
IODTNVRAM::removePropertyWithGUIDAndName(const uuid_t guid, const char *name)
{
	IOReturn ret;
	uuid_t   newGuid;

	DEBUG_INFO("name=%s\n", name);

	if (_varDict == nullptr) {
		DEBUG_INFO("No dictionary\n");
		ret = kIOReturnNotFound;
		goto exit;
	}

	if (!verifyPermission(kIONVRAMOperationDelete, guid, name, _format->getSystemPartitionActive())) {
		DEBUG_INFO("Not privileged\n");
		ret = kIOReturnNotPrivileged;
		goto exit;
	}

	translateGUID(guid, name, newGuid, _format->getSystemPartitionActive());

	NVRAMWRITELOCK();

	ret = _format->setVariable(newGuid, name, nullptr);

	if (ret != kIOReturnSuccess) {
		DEBUG_INFO("%s not found\n", name);
		ret = kIOReturnNotFound;
	}

	NVRAMUNLOCK();

	record_system_event(SYSTEM_EVENT_TYPE_INFO, SYSTEM_EVENT_SUBSYSTEM_NVRAM, "delete", "%s", name);

exit:
	return ret;
}

IOReturn
IODTNVRAM::removePropertyInternal(const OSSymbol *aKey)
{
	IOReturn   ret;
	const char *variableName;
	uuid_t     varGuid;

	DEBUG_INFO("aKey=%s\n", aKey->getCStringNoCopy());

	parseVariableName(aKey->getCStringNoCopy(), &varGuid, &variableName);

	ret = removePropertyWithGUIDAndName(varGuid, variableName);

	return ret;
}

IOReturn
IODTNVRAM::setProperties(OSObject *properties)
{
	IOReturn                          ret = kIOReturnSuccess;
	OSObject                          *object;
	const OSSymbol                    *key;
	OSDictionary                      *dict;
	OSSharedPtr<OSCollectionIterator> iter;

	dict = OSDynamicCast(OSDictionary, properties);
	if (dict == nullptr) {
		DEBUG_ERROR("Not a dictionary\n");
		return kIOReturnBadArgument;
	}

	iter = OSCollectionIterator::withCollection(dict);
	if (iter == nullptr) {
		DEBUG_ERROR("Couldn't create iterator\n");
		return kIOReturnBadArgument;
	}

	while (ret == kIOReturnSuccess) {
		key = OSDynamicCast(OSSymbol, iter->getNextObject());
		if (key == nullptr) {
			break;
		}

		object = dict->getObject(key);
		if (object == nullptr) {
			continue;
		}

		ret = setPropertyInternal(key, object);
	}

	DEBUG_INFO("ret=%#08x\n", ret);

	return ret;
}

// ********************** Deprecated ********************

IOReturn
IODTNVRAM::readXPRAM(IOByteCount offset, uint8_t *buffer,
    IOByteCount length)
{
	return kIOReturnUnsupported;
}

IOReturn
IODTNVRAM::writeXPRAM(IOByteCount offset, uint8_t *buffer,
    IOByteCount length)
{
	return kIOReturnUnsupported;
}

IOReturn
IODTNVRAM::readNVRAMProperty(IORegistryEntry *entry,
    const OSSymbol **name,
    OSData **value)
{
	return kIOReturnUnsupported;
}

IOReturn
IODTNVRAM::writeNVRAMProperty(IORegistryEntry *entry,
    const OSSymbol *name,
    OSData *value)
{
	return kIOReturnUnsupported;
}

OSDictionary *
IODTNVRAM::getNVRAMPartitions(void)
{
	return NULL;
}

IOReturn
IODTNVRAM::readNVRAMPartition(const OSSymbol *partitionID,
    IOByteCount offset, uint8_t *buffer,
    IOByteCount length)
{
	return kIOReturnUnsupported;
}

IOReturn
IODTNVRAM::writeNVRAMPartition(const OSSymbol *partitionID,
    IOByteCount offset, uint8_t *buffer,
    IOByteCount length)
{
	return kIOReturnUnsupported;
}

IOByteCount
IODTNVRAM::savePanicInfo(uint8_t *buffer, IOByteCount length)
{
	return 0;
}