|
root / base / usr / src / test / zfs-tests / cmd
cmd Plain Text 5370 lines 123.1 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012, 2016 by Delphix. All rights reserved.
#

include $(SRC)/test/zfs-tests/Makefile.com
include $(SRC)/test/Makefile.com
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012, 2016 by Delphix. All rights reserved.
#

include $(SRC)/test/Makefile.com

ROOTOPTPKG = $(ROOT)/opt/zfs-tests
ROOTBIN = $(ROOTOPTPKG)/bin

OBJS = $(PROG:%=%.o)
SRCS = $(OBJS:%.o=%.c)

CMDS = $(PROG:%=$(ROOTBIN)/%)
$(CMDS) : FILEMODE = 0555

CSTD = $(CSTD_GNU99)
CPPFLAGS += -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64

all: $(PROG)

$(PROG): $(OBJS)
	$(LINK.c) $(OBJS) -o $@ $(LDLIBS)
	$(POST_PROCESS)

%.o: ../%.c
	$(COMPILE.c) $<

install: all $(CMDS)

clobber: clean
	-$(RM) $(PROG)

clean:
	-$(RM) $(OBJS)

$(CMDS): $(ROOTBIN) $(PROG)

$(ROOTBIN):
	$(INS.dir)

$(ROOTBIN)/%: %
	$(INS.file)
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2022 Toomas Soome <tsoome@me.com>
#

PROG = btree_test

include $(SRC)/cmd/Makefile.cmd

CPPFLAGS += -I$(SRC)/uts/common/fs/zfs -DDEBUG
LDLIBS += -lavl -lzpool -lumem

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2019 by Delphix. All rights reserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/avl.h>
#include <sys/btree.h>
#include <sys/time.h>
#include <sys/resource.h>

#define	BUFSIZE 256

int seed = 0;
int stress_timeout = 180;
int contents_frequency = 100;
int tree_limit = 64 * 1024;
boolean_t stress_only = B_FALSE;

static void
usage(int exit_value)
{
	(void) fprintf(stderr, "Usage:\tbtree_test -n <test_name>\n");
	(void) fprintf(stderr, "\tbtree_test -s [-r <seed>] [-l <limit>] "
	    "[-t timeout>] [-c check_contents]\n");
	(void) fprintf(stderr, "\tbtree_test [-r <seed>] [-l <limit>] "
	    "[-t timeout>] [-c check_contents]\n");
	(void) fprintf(stderr, "\n    With the -n option, run the named "
	    "negative test. With the -s option,\n");
	(void) fprintf(stderr, "    run the stress test according to the "
	    "other options passed. With\n");
	(void) fprintf(stderr, "    neither, run all the positive tests, "
	    "including the stress test with\n");
	(void) fprintf(stderr, "    the default options.\n");
	(void) fprintf(stderr, "\n    Options that control the stress test\n");
	(void) fprintf(stderr, "\t-c stress iterations after which to compare "
	    "tree contents [default: 100]\n");
	(void) fprintf(stderr, "\t-l the largest value to allow in the tree "
	    "[default: 1M]\n");
	(void) fprintf(stderr, "\t-r random seed [default: from "
	    "gettimeofday()]\n");
	(void) fprintf(stderr, "\t-t seconds to let the stress test run "
	    "[default: 180]\n");
	exit(exit_value);
}

typedef struct int_node {
	avl_node_t node;
	uint64_t data;
} int_node_t;

/*
 * Utility functions
 */

static int
avl_compare(const void *v1, const void *v2)
{
	const int_node_t *n1 = v1;
	const int_node_t *n2 = v2;
	uint64_t a = n1->data;
	uint64_t b = n2->data;

	return (TREE_CMP(a, b));
}

static int
zfs_btree_compare(const void *v1, const void *v2)
{
	const uint64_t *a = v1;
	const uint64_t *b = v2;

	return (TREE_CMP(*a, *b));
}

static void
verify_contents(avl_tree_t *avl, zfs_btree_t *bt)
{
	static int count = 0;
	zfs_btree_index_t bt_idx = {0};
	int_node_t *node;
	uint64_t *data;

	boolean_t forward = count % 2 == 0 ? B_TRUE : B_FALSE;
	count++;

	ASSERT3U(avl_numnodes(avl), ==, zfs_btree_numnodes(bt));
	if (forward == B_TRUE) {
		node = avl_first(avl);
		data = zfs_btree_first(bt, &bt_idx);
	} else {
		node = avl_last(avl);
		data = zfs_btree_last(bt, &bt_idx);
	}

	while (node != NULL) {
		ASSERT3U(*data, ==, node->data);
		if (forward == B_TRUE) {
			data = zfs_btree_next(bt, &bt_idx, &bt_idx);
			node = AVL_NEXT(avl, node);
		} else {
			data = zfs_btree_prev(bt, &bt_idx, &bt_idx);
			node = AVL_PREV(avl, node);
		}
	}
}

static void
verify_node(avl_tree_t *avl, zfs_btree_t *bt, int_node_t *node)
{
	zfs_btree_index_t bt_idx = {0};
	zfs_btree_index_t bt_idx2 = {0};
	int_node_t *inp;
	uint64_t data = node->data;
	uint64_t *rv = NULL;

	ASSERT3U(avl_numnodes(avl), ==, zfs_btree_numnodes(bt));
	ASSERT3P((rv = (uint64_t *)zfs_btree_find(bt, &data, &bt_idx)), !=,
	    NULL);
	ASSERT3S(*rv, ==, data);
	ASSERT3P(zfs_btree_get(bt, &bt_idx), !=, NULL);
	ASSERT3S(data, ==, *(uint64_t *)zfs_btree_get(bt, &bt_idx));

	if ((inp = AVL_NEXT(avl, node)) != NULL) {
		ASSERT3P((rv = zfs_btree_next(bt, &bt_idx, &bt_idx2)), !=,
		    NULL);
		ASSERT3P(rv, ==, zfs_btree_get(bt, &bt_idx2));
		ASSERT3S(inp->data, ==, *rv);
	} else {
		ASSERT3U(data, ==, *(uint64_t *)zfs_btree_last(bt, &bt_idx));
	}

	if ((inp = AVL_PREV(avl, node)) != NULL) {
		ASSERT3P((rv = zfs_btree_prev(bt, &bt_idx, &bt_idx2)), !=,
		    NULL);
		ASSERT3P(rv, ==, zfs_btree_get(bt, &bt_idx2));
		ASSERT3S(inp->data, ==, *rv);
	} else {
		ASSERT3U(data, ==, *(uint64_t *)zfs_btree_first(bt, &bt_idx));
	}
}

/*
 * Tests
 */

/* Verify that zfs_btree_find works correctly with a NULL index. */
static int
find_without_index(zfs_btree_t *bt, char *why)
{
	u_longlong_t *p, i = 12345;

	zfs_btree_add(bt, &i);
	if ((p = (u_longlong_t *)zfs_btree_find(bt, &i, NULL)) == NULL ||
	    *p != i) {
		(void) snprintf(why, BUFSIZE, "Unexpectedly found %llu\n",
		    p == NULL ? 0 : *p);
		return (1);
	}

	i++;

	if ((p = (u_longlong_t *)zfs_btree_find(bt, &i, NULL)) != NULL) {
		(void) snprintf(why, BUFSIZE, "Found bad value: %llu\n", *p);
		return (1);
	}

	return (0);
}

/* Verify simple insertion and removal from the tree. */
static int
insert_find_remove(zfs_btree_t *bt, char *why)
{
	u_longlong_t *p, i = 12345;
	zfs_btree_index_t bt_idx = {0};

	/* Insert 'i' into the tree, and attempt to find it again. */
	zfs_btree_add(bt, &i);
	if ((p = (u_longlong_t *)zfs_btree_find(bt, &i, &bt_idx)) == NULL) {
		(void) snprintf(why, BUFSIZE, "Didn't find value in tree\n");
		return (1);
	} else if (*p != i) {
		(void) snprintf(why, BUFSIZE, "Found (%llu) in tree\n", *p);
		return (1);
	}
	ASSERT3S(zfs_btree_numnodes(bt), ==, 1);
	zfs_btree_verify(bt);

	/* Remove 'i' from the tree, and verify it is not found. */
	zfs_btree_remove(bt, &i);
	if ((p = (u_longlong_t *)zfs_btree_find(bt, &i, &bt_idx)) != NULL) {
		(void) snprintf(why, BUFSIZE,
		    "Found removed value (%llu)\n", *p);
		return (1);
	}
	ASSERT3S(zfs_btree_numnodes(bt), ==, 0);
	zfs_btree_verify(bt);

	return (0);
}

/*
 * Add a number of random entries into a btree and avl tree. Then walk them
 * backwards and forwards while emptying the tree, verifying the trees look
 * the same.
 */
static int
drain_tree(zfs_btree_t *bt, char *why)
{
	uint64_t *p;
	avl_tree_t avl;
	int i = 0;
	int_node_t *node;
	avl_index_t avl_idx = {0};
	zfs_btree_index_t bt_idx = {0};

	avl_create(&avl, avl_compare, sizeof (int_node_t),
	    offsetof(int_node_t, node));

	/* Fill both trees with the same data */
	for (i = 0; i < 64 * 1024; i++) {
		void *ret;

		u_longlong_t randval = random();
		if ((p = (uint64_t *)zfs_btree_find(bt, &randval, &bt_idx)) !=
		    NULL) {
			continue;
		}
		zfs_btree_add_idx(bt, &randval, &bt_idx);

		node = malloc(sizeof (int_node_t));
		ASSERT3P(node, !=, NULL);

		node->data = randval;
		if ((ret = avl_find(&avl, node, &avl_idx)) != NULL) {
			(void) snprintf(why, BUFSIZE,
			    "Found in avl: %llu\n", randval);
			return (1);
		}
		avl_insert(&avl, node, avl_idx);
	}

	/* Remove data from either side of the trees, comparing the data */
	while (avl_numnodes(&avl) != 0) {
		uint64_t *data;

		ASSERT3U(avl_numnodes(&avl), ==, zfs_btree_numnodes(bt));
		if (avl_numnodes(&avl) % 2 == 0) {
			node = avl_first(&avl);
			data = zfs_btree_first(bt, &bt_idx);
		} else {
			node = avl_last(&avl);
			data = zfs_btree_last(bt, &bt_idx);
		}
		ASSERT3U(node->data, ==, *data);
		zfs_btree_remove_idx(bt, &bt_idx);
		avl_remove(&avl, node);

		if (avl_numnodes(&avl) == 0) {
			break;
		}

		node = avl_first(&avl);
		ASSERT3U(node->data, ==,
		    *(uint64_t *)zfs_btree_first(bt, NULL));
		node = avl_last(&avl);
		ASSERT3U(node->data, ==, *(uint64_t *)zfs_btree_last(bt, NULL));
	}
	ASSERT3S(zfs_btree_numnodes(bt), ==, 0);

	void *avl_cookie = NULL;
	while ((node = avl_destroy_nodes(&avl, &avl_cookie)) != NULL)
		free(node);
	avl_destroy(&avl);

	return (0);
}

/*
 * This test uses an avl and btree, and continually processes new random
 * values. Each value is either removed or inserted, depending on whether
 * or not it is found in the tree. The test periodically checks that both
 * trees have the same data and does consistency checks. This stress
 * option can also be run on its own from the command line.
 */
static int
stress_tree(zfs_btree_t *bt, char *why __unused)
{
	avl_tree_t avl;
	int_node_t *node;
	struct timeval tp;
	time_t t0;
	int insertions = 0, removals = 0, iterations = 0;
	u_longlong_t max = 0, min = UINT64_MAX;

	(void) gettimeofday(&tp, NULL);
	t0 = tp.tv_sec;

	avl_create(&avl, avl_compare, sizeof (int_node_t),
	    offsetof(int_node_t, node));

	while (1) {
		zfs_btree_index_t bt_idx = {0};
		avl_index_t avl_idx = {0};

		uint64_t randval = random() % tree_limit;
		node = malloc(sizeof (*node));
		node->data = randval;

		max = randval > max ? randval : max;
		min = randval < min ? randval : min;

		void *ret = avl_find(&avl, node, &avl_idx);
		if (ret == NULL) {
			insertions++;
			avl_insert(&avl, node, avl_idx);
			ASSERT3P(zfs_btree_find(bt, &randval, &bt_idx), ==,
			    NULL);
			zfs_btree_add_idx(bt, &randval, &bt_idx);
			verify_node(&avl, bt, node);
		} else {
			removals++;
			verify_node(&avl, bt, ret);
			zfs_btree_remove(bt, &randval);
			avl_remove(&avl, ret);
			free(ret);
			free(node);
		}

		zfs_btree_verify(bt);

		iterations++;
		if (iterations % contents_frequency == 0) {
			verify_contents(&avl, bt);
		}

		zfs_btree_verify(bt);

		(void) gettimeofday(&tp, NULL);
		if (tp.tv_sec > t0 + stress_timeout) {
			fprintf(stderr, "insertions/removals: %u/%u\nmax/min: "
			    "%llu/%llu\n", insertions, removals, max, min);
			break;
		}
	}

	void *avl_cookie = NULL;
	while ((node = avl_destroy_nodes(&avl, &avl_cookie)) != NULL)
		free(node);
	avl_destroy(&avl);

	if (stress_only) {
		zfs_btree_index_t *idx = NULL;
		uint64_t *rv;

		while ((rv = zfs_btree_destroy_nodes(bt, &idx)) != NULL)
			;
		zfs_btree_verify(bt);
	}

	return (0);
}

/*
 * Verify inserting a duplicate value will cause a crash.
 * Note: negative test; return of 0 is a failure.
 */
static int
insert_duplicate(zfs_btree_t *bt)
{
	uint64_t *p, i = 23456;
	zfs_btree_index_t bt_idx = {0};

	if ((p = (uint64_t *)zfs_btree_find(bt, &i, &bt_idx)) != NULL) {
		fprintf(stderr, "Found value in empty tree.\n");
		return (0);
	}
	zfs_btree_add_idx(bt, &i, &bt_idx);
	if ((p = (uint64_t *)zfs_btree_find(bt, &i, &bt_idx)) == NULL) {
		fprintf(stderr, "Did not find expected value.\n");
		return (0);
	}

	/* Crash on inserting a duplicate */
	zfs_btree_add_idx(bt, &i, NULL);

	return (0);
}

/*
 * Verify removing a non-existent value will cause a crash.
 * Note: negative test; return of 0 is a failure.
 */
static int
remove_missing(zfs_btree_t *bt)
{
	uint64_t *p, i = 23456;
	zfs_btree_index_t bt_idx = {0};

	if ((p = (uint64_t *)zfs_btree_find(bt, &i, &bt_idx)) != NULL) {
		fprintf(stderr, "Found value in empty tree.\n");
		return (0);
	}

	/* Crash removing a nonexistent entry */
	zfs_btree_remove(bt, &i);

	return (0);
}

static int
do_negative_test(zfs_btree_t *bt, char *test_name)
{
	int rval = 0;
	struct rlimit rlim = {0};

	(void) setrlimit(RLIMIT_CORE, &rlim);

	if (strcmp(test_name, "insert_duplicate") == 0) {
		rval = insert_duplicate(bt);
	} else if (strcmp(test_name, "remove_missing") == 0) {
		rval = remove_missing(bt);
	}

	/*
	 * Return 0, since callers will expect non-zero return values for
	 * these tests, and we should have crashed before getting here anyway.
	 */
	(void) fprintf(stderr, "Test: %s returned %d.\n", test_name, rval);
	return (0);
}

typedef struct btree_test {
	const char	*name;
	int		(*func)(zfs_btree_t *, char *);
} btree_test_t;

static btree_test_t test_table[] = {
	{ "insert_find_remove",		insert_find_remove	},
	{ "find_without_index",		find_without_index	},
	{ "drain_tree",			drain_tree		},
	{ "stress_tree",		stress_tree		},
	{ NULL,				NULL			}
};

int
main(int argc, char *argv[])
{
	char *negative_test = NULL;
	int failed_tests = 0;
	struct timeval tp;
	zfs_btree_t bt;
	int c;

	while ((c = getopt(argc, argv, "c:l:n:r:st:")) != -1) {
		switch (c) {
		case 'c':
			contents_frequency = atoi(optarg);
			break;
		case 'l':
			tree_limit = atoi(optarg);
			break;
		case 'n':
			negative_test = optarg;
			break;
		case 'r':
			seed = atoi(optarg);
			break;
		case 's':
			stress_only = B_TRUE;
			break;
		case 't':
			stress_timeout = atoi(optarg);
			break;
		case 'h':
		default:
			usage(1);
			break;
		}
	}
	argc -= optind;
	argv += optind;
	optind = 1;


	if (seed == 0) {
		(void) gettimeofday(&tp, NULL);
		seed = tp.tv_sec;
	}
	srandom(seed);

	zfs_btree_init();
	zfs_btree_create(&bt, zfs_btree_compare, sizeof (uint64_t));

	/*
	 * This runs the named negative test. None of them should
	 * return, as they both cause crashes.
	 */
	if (negative_test) {
		return (do_negative_test(&bt, negative_test));
	}

	fprintf(stderr, "Seed: %u\n", seed);

	/*
	 * This is a stress test that does operations on a btree over the
	 * requested timeout period, verifying them against identical
	 * operations in an avl tree.
	 */
	if (stress_only != 0) {
		return (stress_tree(&bt, NULL));
	}

	/* Do the positive tests */
	btree_test_t *test = &test_table[0];
	while (test->name) {
		int retval;
		uint64_t *rv;
		char why[BUFSIZE] = {0};
		zfs_btree_index_t *idx = NULL;

		(void) fprintf(stdout, "%-20s", test->name);
		retval = test->func(&bt, why);

		if (retval == 0) {
			(void) fprintf(stdout, "ok\n");
		} else {
			(void) fprintf(stdout, "failed with %d\n", retval);
			if (strlen(why) != 0)
				(void) fprintf(stdout, "\t%s\n", why);
			why[0] = '\0';
			failed_tests++;
		}

		/* Remove all the elements and re-verify the tree */
		while ((rv = zfs_btree_destroy_nodes(&bt, &idx)) != NULL)
			;
		zfs_btree_verify(&bt);

		test++;
	}

	zfs_btree_verify(&bt);
	zfs_btree_fini();

	return (failed_tests);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = chg_usr_exec

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pwd.h>

#define	EXECSHELL	"/usr/xpg4/bin/sh"

int
main(int argc, char *argv[])
{
	char *plogin = NULL;
	char cmds[BUFSIZ] = { 0 };
	char sep[] = " ";
	struct passwd *ppw = NULL;
	int i, len;

	if (argc < 3 || strlen(argv[1]) == 0) {
		(void) printf("\tUsage: %s <login> <commands> ...\n", argv[0]);
		return (1);
	}

	plogin = argv[1];
	len = 0;
	for (i = 2; i < argc; i++) {
		(void) snprintf(cmds+len, sizeof (cmds)-len,
		    "%s%s", argv[i], sep);
		len += strlen(argv[i]) + strlen(sep);
	}

	if ((ppw = getpwnam(plogin)) == NULL) {
		perror("getpwnam");
		return (errno);
	}
	if (setgid(ppw->pw_gid) != 0) {
		perror("setgid");
		return (errno);
	}
	if (setuid(ppw->pw_uid) != 0) {
		perror("setuid");
		return (errno);
	}

	if (execl(EXECSHELL, "sh",  "-c", cmds, (char *)NULL) != 0) {
		perror("execl: " EXECSHELL);
		return (errno);
	}

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = devname2devid

include $(SRC)/cmd/Makefile.cmd

LDLIBS += -ldevid

include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <devid.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

/*
 * Usage: devname2devid <devicepath>
 *
 * Examples:
 *	# ./devname2devid /dev/dsk/c1t4d0s0
 *	devid id1,sd@SSEAGATE_ST318404LSUN18G_3BT2G0Z300002146G4CR/a
 *	# ./devname2devid /dev/dsk/c1t4d0
 *	devid id1,sd@SSEAGATE_ST318404LSUN18G_3BT2G0Z300002146G4CR/wd
 *	# ./devname2devid /dev/dsk/c1t4d0s1
 *	devid id1,sd@SSEAGATE_ST318404LSUN18G_3BT2G0Z300002146G4CR/b
 *	#
 *
 * This program accepts a disk or disk slice path and prints a
 * device id.
 *
 * Exit values:
 *	0 - means success
 *	1 - means failure
 *
 */
int
main(int argc, char *argv[])
{
	int		fd;
	ddi_devid_t	devid;
	char		*minor_name, *devidstr, *device;
#ifdef DEBUG
	devid_nmlist_t  *list = NULL;
	char		*search_path;
	int		i;
#endif

	if (argc == 1) {
		(void) printf("%s <devicepath> [search path]\n",
		    argv[0]);
		exit(1);
	}
	device = argv[1];

	if ((fd = open(device, O_RDONLY|O_NDELAY)) < 0) {
		perror(device);
		exit(1);
	}
	if (devid_get(fd, &devid) != 0) {
		perror("devid_get");
		exit(1);
	}
	if (devid_get_minor_name(fd, &minor_name) != 0) {
		perror("devid_get_minor_name");
		exit(1);
	}
	if ((devidstr = devid_str_encode(devid, minor_name)) == 0) {
		perror("devid_str_encode");
		exit(1);
	}

	(void) printf("devid %s\n", devidstr);

	devid_str_free(devidstr);

#ifdef DEBUG
	if (argc == 3) {
		search_path = argv[2];
	} else {
		search_path = "/dev/rdsk";
	}

	if (devid_deviceid_to_nmlist(search_path, devid, DEVID_MINOR_NAME_ALL,
	    &list)) {
		perror("devid_deviceid_to_nmlist");
		exit(1);
	}

	/* loop through list and process device names and numbers */
	for (i = 0; list[i].devname != NULL; i++) {
		(void) printf("devname: %s %p\n", list[i].devname, list[i].dev);
	}
	devid_free_nmlist(list);

#endif /* DEBUG */

	devid_str_free(minor_name);
	devid_free(devid);

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = dir_rd_update

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Assertion:
 *
 *	A read operation and directory update operation performed
 *      concurrently on the same directory can lead to deadlock
 *	on a UFS logging file system, but not on a ZFS file system.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define	TMP_DIR /tmp

static char dirpath[256];

int
main(int argc, char **argv)
{
	char *cp1 = "";
	int i = 0;
	int ret = 0;
	int testdd = 0;
	pid_t pid;
	static const int op_num = 5;

	if (argc == 1) {
		(void) printf("Usage: %s <mount point>\n", argv[0]);
		exit(-1);
	}
	for (i = 0; i < 256; i++) {
		dirpath[i] = 0;
	}

	cp1 = argv[1];
	if (strlen(cp1) >= (sizeof (dirpath) - strlen("TMP_DIR"))) {
		(void) printf("The string length of mount point is "
		    "too large\n");
		exit(-1);
	}
	(void) strcpy(&dirpath[0], (const char *)cp1);
	(void) strcat(&dirpath[strlen(dirpath)], "TMP_DIR");

	ret = mkdir(dirpath, 0777);
	if (ret != 0) {
		if (errno != EEXIST) {
			(void) printf("%s: mkdir(<%s>, 0777) failed: errno "
			    "(decimal)=%d\n", argv[0], dirpath, errno);
			exit(-1);
		}
	}
	testdd = open(dirpath, O_RDONLY|O_RSYNC|O_SYNC|O_DSYNC);
	if (testdd < 0) {
		(void) printf("%s: open(<%s>, O_RDONLY|O_RSYNC|O_SYNC|O_DSYNC)"
		    " failed: errno (decimal)=%d\n", argv[0], dirpath, errno);
		exit(-1);
	} else {
		(void) close(testdd);
	}
	pid = fork();
	if (pid > 0) {
		int fd = open(dirpath, O_RDONLY|O_RSYNC|O_SYNC|O_DSYNC);
		char buf[16];
		int rdret;
		int j = 0;

		while (j < op_num) {
			(void) sleep(1);
			rdret = read(fd, buf, 16);
			if (rdret == -1) {
				(void) printf("readdir failed");
			}
			j++;
		}
	} else if (pid == 0) {
		int fd = open(dirpath, O_RDONLY);
		int chownret;
		int k = 0;

		while (k < op_num) {
			(void) sleep(1);
			chownret = fchown(fd, 0, 0);
			if (chownret == -1) {
				(void) printf("chown failed");
			}

			k++;
		}
	}

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
#

PROG = dos_ro

include $(SRC)/cmd/Makefile.cmd

LDLIBS += -lnvpair

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <attr.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libnvpair.h>

extern const char *__progname;

int vflag = 0;

static int
dosattr_set_ro(int fildes, const char *fname)
{
	nvlist_t	*nvl = NULL;
	int		err;

	err = nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0);
	if (err != 0)
		return (err);

	(void) nvlist_add_boolean_value(nvl, A_READONLY, 1);

	if (fname == NULL) {
		err = fsetattr(fildes, XATTR_VIEW_READWRITE, nvl);
	} else {
		err = setattrat(fildes, XATTR_VIEW_READWRITE, fname, nvl);
	}
	if (err < 0) {
		err = errno;
		if (vflag > 1) {
			(void) fprintf(stderr,
			    "dosattr_set: setattrat (%s), err %d\n",
			    fname, err);
		}
	}

	nvlist_free(nvl);

	return (err);
}

void
usage(void)
{
	(void) fprintf(stderr, "usage: %s [-v] file\n",
	    __progname);
	exit(1);
}

int
main(int argc, char **argv)
{
	char *fname;
	int c, fd, n;

	while ((c = getopt(argc, argv, "v")) != -1) {
		switch (c) {
		case 'v':
			vflag++;
			break;
		case '?':
		default:
			usage();
			break;
		}
	}

	if (optind + 1 != argc)
		usage();
	fname = argv[optind];

	fd = open(fname, O_CREAT | O_RDWR, 0644);
	if (fd < 0) {
		perror(fname);
		exit(1);
	}

	if (vflag)
		(void) fprintf(stderr, "Write 1 (mode 644)\n");
	n = write(fd, "mode 644 OK\n", 12);
	if (n != 12) {
		(void) fprintf(stderr, "write mode 644, err=%d\n", errno);
		exit(1);
	}

	if (vflag)
		(void) fprintf(stderr, "Chmod 444\n");
	n = fchmod(fd, 0444);
	if (n < 0) {
		(void) fprintf(stderr, "chmod 444, err=%d\n", errno);
		exit(1);
	}

	if (vflag)
		(void) fprintf(stderr, "Write 2 (mode 444)\n");
	n = write(fd, "mode 444 OK\n", 12);
	if (n != 12) {
		(void) fprintf(stderr, "write mode 444, err=%d\n", errno);
		exit(1);
	}

	if (vflag)
		(void) fprintf(stderr, "Set DOS R/O\n");
	n = dosattr_set_ro(fd, NULL /* fname? */);
	if (n != 0) {
		(void) fprintf(stderr, "Set R/O, err=%d\n", n);
		exit(1);
	}

	/*
	 * This fails, but write on an already open handle should succeed
	 * the same as when we've set the mode to 444 after open.
	 */
	if (vflag)
		(void) fprintf(stderr, "Write 3 (DOS R/O)\n");
	n = write(fd, "Write DOS RO?\n", 14);
	if (n != 14) {
		(void) fprintf(stderr, "write (DOS R/O), err=%d\n", errno);
		exit(1);
	}

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = file_check

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2022 MNX Cloud, Inc.
 */

#include "../file_common.h"

static unsigned char bigbuffer[BIGBUFFERSIZE];

/*
 * Given a filename, check that the file consists entirely
 * of a particular pattern. If the pattern is not specified a
 * default will be used. For default values see file_common.h
 */
int
main(int argc, char **argv)
{
	int		bigfd;
	long		i, n;
	uchar_t		fillchar = DATA;
	int		bigbuffersize = BIGBUFFERSIZE;
	int64_t		read_count = 0;

	/*
	 * Validate arguments
	 */
	if (argc < 2) {
		(void) printf("Usage: %s filename [pattern]\n",
		    argv[0]);
		exit(1);
	}

	if (argv[2]) {
		fillchar = atoi(argv[2]);
	}

	/*
	 * Read the file contents and check every character
	 * against the supplied pattern. Abort if the
	 * pattern check fails.
	 */
	if ((bigfd = open(argv[1], O_RDONLY)) == -1) {
		(void) printf("open %s failed %d\n", argv[1], errno);
		exit(1);
	}

	do {
		int exitcode;

		if ((n = read(bigfd, &bigbuffer, bigbuffersize)) == -1) {
			exitcode = errno;
			(void) printf("read failed (%ld), %d\n", n, errno);
			exit(exitcode);
		}

		for (i = 0; i < n; i++) {
			if (bigbuffer[i] != fillchar) {
				(void) printf("error %s: 0x%x != 0x%x)\n",
				    argv[1], bigbuffer[i], fillchar);
				exit(1);
			}
		}

		read_count += n;
	} while (n == bigbuffersize);

	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef FILE_COMMON_H
#define	FILE_COMMON_H

/*
 * header file for file_* utilities. These utilities
 * are used by the test cases to perform various file
 * operations (append writes, for example).
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>

#define	BLOCKSZ		8192
#define	DATA		0xa5
#define	DATA_RANGE	120
#define	BIGBUFFERSIZE	0x800000
#define	BIGFILESIZE	20

extern char *optarg;
extern int optind, opterr, optopt;

#ifdef __cplusplus
}
#endif

#endif /* FILE_COMMON_H */
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = file_trunc

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/errno.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <string.h>

#define	FSIZE	256*1024*1024
#define	BSIZE	512

/* Initialize Globals */
static long	fsize = FSIZE;
static size_t	bsize = BSIZE;
static int	count = 0;
static int	rflag = 0;
static int	seed = 0;
static int	vflag = 0;
static int	errflag = 0;
static off_t	offset = 0;
static char	*filename = NULL;

static void usage(char *execname);
static void parse_options(int argc, char *argv[]);
static void do_write(int fd);
static void do_trunc(int fd);

static void
usage(char *execname)
{
	(void) fprintf(stderr,
	    "usage: %s [-b blocksize] [-c count] [-f filesize]"
	    " [-o offset] [-s seed] [-r] [-v] filename\n", execname);
	(void) exit(1);
}

int
main(int argc, char *argv[])
{
	int i;
	int fd = -1;

	parse_options(argc, argv);

	fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);
	if (fd < 0) {
		perror("open");
		exit(3);
	}

	for (i = 0; count == 0 || i < count; i++) {
		(void) do_write(fd);
		(void) do_trunc(fd);
	}

	(void) close(fd);
	return (0);
}

static void
parse_options(int argc, char *argv[])
{
	int c;

	extern char *optarg;
	extern int optind, optopt;

	count = fsize / bsize;
	seed = time(NULL);
	while ((c = getopt(argc, argv, "b:c:f:o:rs:v")) != -1) {
		switch (c) {
			case 'b':
				bsize = atoi(optarg);
				break;

			case 'c':
				count = atoi(optarg);
				break;

			case 'f':
				fsize = atoi(optarg);
				break;

			case 'o':
				offset = atoi(optarg);
				break;

			case 'r':
				rflag++;
				break;

			case 's':
				seed = atoi(optarg);
				break;

			case 'v':
				vflag++;
				break;

			case ':':
				(void) fprintf(stderr,
				    "Option -%c requires an operand\n", optopt);
				errflag++;
				break;

			case '?':
				(void) fprintf(stderr,
				    "Unrecognized option: -%c\n", optopt);
				errflag++;
				break;
		}

		if (errflag) {
			(void) usage(argv[0]);
		}
	}
	if (argc <= optind) {
		(void) fprintf(stderr,
		    "No filename specified\n");
		usage(argv[0]);
	}
	filename = argv[optind];

	if (vflag) {
		(void) fprintf(stderr, "Seed = %d\n", seed);
	}
	srandom(seed);
}

static void
do_write(int fd)
{
	off_t	roffset = 0;
	char	*buf = NULL;
	char	*rbuf = NULL;

	buf = (char *)calloc(1, bsize);
	rbuf = (char *)calloc(1, bsize);
	if (buf == NULL || rbuf == NULL) {
		perror("malloc");
		exit(4);
	}

	roffset = random() % fsize;
	if (lseek64(fd, (offset + roffset), SEEK_SET) < 0) {
		perror("lseek");
		exit(5);
	}

	(void) strcpy(buf, "ZFS Test Suite Truncation Test");
	if (write(fd, buf, bsize) < bsize) {
		perror("write");
		exit(6);
	}

	if (rflag) {
		if (lseek64(fd, (offset + roffset), SEEK_SET) < 0) {
			perror("lseek");
			exit(7);
		}

		if (read(fd, rbuf, bsize) < bsize) {
			perror("read");
			exit(8);
		}

		if (memcmp(buf, rbuf, bsize) != 0) {
			perror("memcmp");
			exit(9);
		}
	}
	if (vflag) {
		(void) fprintf(stderr,
		    "Wrote to offset %lld\n", (offset + roffset));
		if (rflag) {
			(void) fprintf(stderr,
			    "Read back from offset %lld\n", (offset + roffset));
		}
	}

	(void) free(buf);
	(void) free(rbuf);
}

static void
do_trunc(int fd)
{
	off_t   roffset = 0;

	roffset = random() % fsize;
	if (ftruncate64(fd, (offset + roffset))  < 0) {
		perror("truncate");
		exit(7);
	}

	if (vflag) {
		(void) fprintf(stderr,
		    "Truncated at offset %lld\n",
		    (offset + roffset));
	}
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = file_write

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2022 MNX Cloud, Inc.
 */

#include "../file_common.h"
#include <libgen.h>

static unsigned char bigbuffer[BIGBUFFERSIZE];

/*
 * Writes (or appends) a given value to a file repeatedly.
 * See header file for defaults.
 */

static void usage(void);

int
main(int argc, char **argv)
{
	int		bigfd;
	int		c;
	int		oflag = 0;
	int		err = 0;
	int		k;
	long		i;
	int64_t		good_writes = 0;
	uchar_t		nxtfillchar;
	/*
	 * Default Parameters
	 */
	int		write_count = BIGFILESIZE;
	uchar_t		fillchar = DATA;
	int		block_size = BLOCKSZ;
	char		*filename = NULL;
	char		*operation = NULL;
	offset_t	noffset, offset = 0;
	int		verbose = 0;
	int		rsync = 0;
	int		wsync = 0;
	int		exitcode;

	/*
	 * Process Arguments
	 */
	while ((c = getopt(argc, argv, "b:c:d:s:f:o:vwr")) != -1) {
		switch (c) {
			case 'b':
				block_size = atoi(optarg);
				break;
			case 'c':
				write_count = atoi(optarg);
				break;
			case 'd':
				fillchar = atoi(optarg);
				break;
			case 's':
				offset = atoll(optarg);
				break;
			case 'f':
				filename = optarg;
				break;
			case 'o':
				operation = optarg;
				break;
			case 'v':
				verbose = 1;
				break;
			case 'w':
				wsync = 1;
				break;
			case 'r':
				rsync = 1;
				break;
			case '?':
				(void) printf("unknown arg %c\n", optopt);
				usage();
				break;
		}
	}

	/*
	 * Validate Parameters
	 */
	if (!filename) {
		(void) printf("Filename not specified (-f <file>)\n");
		err++;
	}

	if (!operation) {
		(void) printf("Operation not specified (-o <operation>).\n");
		err++;
	}

	if (block_size > BIGBUFFERSIZE) {
		(void) printf("block_size is too large max==%d.\n",
		    BIGBUFFERSIZE);
		err++;
	}

	if (err) usage();

	/*
	 * Prepare the buffer and determine the requested operation
	 */
	nxtfillchar = fillchar;
	k = 0;

	for (i = 0; i < block_size; i++) {
		bigbuffer[i] = nxtfillchar;

		if (fillchar == 0) {
			if ((k % DATA_RANGE) == 0) {
				k = 0;
			}
			nxtfillchar = k++;
		}
	}

	/*
	 * using the strncmp of operation will make the operation match the
	 * first shortest match - as the operations are unique from the first
	 * character this means that we match single character operations
	 */
	if ((strncmp(operation, "create", strlen(operation) + 1)) == 0 ||
	    (strncmp(operation, "overwrite", strlen(operation) + 1)) == 0) {
		oflag = (O_RDWR|O_CREAT);
	} else if ((strncmp(operation, "append", strlen(operation) + 1)) == 0) {
		oflag = (O_RDWR|O_APPEND);
	} else {
		(void) printf("valid operations are <create|append> not '%s'\n",
		    operation);
		usage();
	}

	if (rsync) {
		oflag = oflag | O_RSYNC;
	}

	if (wsync) {
		oflag = oflag | O_SYNC;
	}

	/*
	 * Given an operation (create/overwrite/append), open the file
	 * accordingly and perform a write of the appropriate type.
	 */
	if ((bigfd = open(filename, oflag, 0666)) == -1) {
		exitcode = errno;
		(void) printf("open %s: failed [%s]%d. Aborting!\n", filename,
		    strerror(errno), errno);
		exit(exitcode);
	}
	noffset = llseek(bigfd, offset, SEEK_SET);
	if (noffset != offset) {
		exitcode = errno;
		(void) printf("llseek %s (%lld/%lld) failed [%s]%d.Aborting!\n",
		    filename, offset, noffset, strerror(errno), errno);
		exit(exitcode);
	}

	if (verbose) {
		(void) printf("%s: block_size = %d, write_count = %d, "
		    "offset = %lld, data = %s%d\n", filename, block_size,
		    write_count, offset,
		    (fillchar == 0) ? "0->" : "",
		    (fillchar == 0) ? DATA_RANGE : fillchar);
	}

	for (i = 0; i < write_count; i++) {
		ssize_t n;

		if ((n = write(bigfd, &bigbuffer, block_size)) == -1) {
			exitcode = errno;
			(void) printf("write failed (%ld), good_writes = %lld, "
			    "error: %s[%d]\n", (long)n, good_writes,
			    strerror(errno),
			    errno);
			exit(exitcode);
		}
		good_writes++;
	}

	if (verbose) {
		(void) printf("Success: good_writes = %lld (%lld)\n",
		    good_writes, (good_writes * block_size));
	}

	return (0);
}

static void
usage(void)
{
	char *base = (char *)"file_write";
	char *exec = (char *)getexecname();

	if (exec != NULL)
		exec = strdup(exec);
	if (exec != NULL)
		base = basename(exec);

	(void) printf("Usage: %s [-v] -o {create,overwrite,append} -f file_name"
	    " [-b block_size]\n"
	    "\t[-s offset] [-c write_count] [-d data]\n"
	    "\twhere [data] equal to zero causes chars "
	    "0->%d to be repeated throughout\n", base, DATA_RANGE);

	if (exec) {
		free(exec);
	}

	exit(1);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2014 by Delphix. All rights reserved.
#

PROG = getholes

include $(SRC)/cmd/Makefile.cmd

LDLIBS += -lcmdutils -lumem -lzfs

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2014 by Delphix. All rights reserved.
 */

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <libzfs.h>
#include <umem.h>
#include <stdlib.h>
#include <stddef.h>
#include <sys/types.h>
#include <sys/list.h>
#include <sys/stat.h>
#include <sys/errno.h>

#define	PRINT_HOLE 0x1
#define	PRINT_DATA 0x2
#define	PRINT_VERBOSE 0x4

extern int errno;

static void
usage(char *msg, int exit_value)
{
	(void) fprintf(stderr, "getholes [-dhv] filename\n");
	(void) fprintf(stderr, "%s\n", msg);
	exit(exit_value);
}

typedef struct segment {
	list_node_t	seg_node;
	int		seg_type;
	off_t		seg_offset;
	off_t		seg_len;
} seg_t;

/*
 * Return an appropriate whence value, depending on whether the file begins
 * with a holes or data.
 */
static int
starts_with_hole(int fd)
{
	off_t	off;

	if ((off = lseek(fd, 0, SEEK_HOLE)) == -1) {
		/* ENXIO means no holes were found */
		if (errno == ENXIO)
			return (SEEK_DATA);
		perror("lseek failed");
		exit(1);
	}

	return (off == 0 ? SEEK_HOLE : SEEK_DATA);
}

static void
print_list(list_t *seg_list, char *fname, int options)
{
	uint64_t	lz_holes, bs = 0;
	uint64_t	hole_blks_seen = 0, data_blks_seen = 0;
	seg_t		*seg;

	if (0 == bs)
		if (zfs_get_hole_count(fname, &lz_holes, &bs) != 0) {
			perror("zfs_get_hole_count");
			exit(1);
		}

	while ((seg = list_remove_head(seg_list)) != NULL) {
		if (options & PRINT_VERBOSE)
			(void) fprintf(stdout, "%c %llu:%llu\n",
			    seg->seg_type == SEEK_HOLE ? 'h' : 'd',
			    seg->seg_offset, seg->seg_len);

		if (seg->seg_type == SEEK_HOLE) {
			hole_blks_seen += seg->seg_len / bs;
		} else {
			data_blks_seen += seg->seg_len / bs;
		}
		umem_free(seg, sizeof (seg_t));
	}

	/* Verify libzfs sees the same number of hole blocks found manually. */
	if (lz_holes != hole_blks_seen) {
		(void) fprintf(stderr, "Counted %llu holes, but libzfs found "
		    "%llu\n", hole_blks_seen, lz_holes);
		exit(1);
	}

	if (options & PRINT_HOLE && options & PRINT_DATA) {
		(void) fprintf(stdout, "datablks: %llu\n", data_blks_seen);
		(void) fprintf(stdout, "holeblks: %llu\n", hole_blks_seen);
		return;
	}

	if (options & PRINT_DATA)
		(void) fprintf(stdout, "%llu\n", data_blks_seen);
	if (options & PRINT_HOLE)
		(void) fprintf(stdout, "%llu\n", hole_blks_seen);
}

int
main(int argc, char *argv[])
{
	off_t		len, off = 0;
	int		c, fd, options = 0, whence = SEEK_DATA;
	struct stat	statbuf;
	char		*fname;
	list_t		seg_list;
	seg_t		*seg = NULL;

	list_create(&seg_list, sizeof (seg_t), offsetof(seg_t, seg_node));

	while ((c = getopt(argc, argv, "dhv")) != -1) {
		switch (c) {
		case 'd':
			options |= PRINT_DATA;
			break;
		case 'h':
			options |= PRINT_HOLE;
			break;
		case 'v':
			options |= PRINT_VERBOSE;
			break;
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 1)
		usage("Incorrect number of arguments.", 1);

	if ((fname = argv[0]) == NULL)
		usage("No filename provided.", 1);

	if ((fd = open(fname, O_LARGEFILE | O_RDONLY)) < 0) {
		perror("open failed");
		exit(1);
	}

	if (fstat(fd, &statbuf) != 0) {
		perror("fstat failed");
		exit(1);
	}
	len = statbuf.st_size;

	whence = starts_with_hole(fd);
	while ((off = lseek(fd, off, whence)) != -1) {
		seg_t	*s;

		seg = umem_alloc(sizeof (seg_t), UMEM_DEFAULT);
		seg->seg_type = whence;
		seg->seg_offset = off;

		list_insert_tail(&seg_list, seg);
		if ((s = list_prev(&seg_list, seg)) != NULL)
			s->seg_len = seg->seg_offset - s->seg_offset;

		whence = whence == SEEK_HOLE ? SEEK_DATA : SEEK_HOLE;
	}
	if (errno != ENXIO) {
		perror("lseek failed");
		exit(1);
	}
	(void) close(fd);

	/*
	 * If this file ends with a hole block, then populate the length of
	 * the last segment, otherwise this is the end of the file, so
	 * discard the remaining zero length segment.
	 */
	if (seg && seg->seg_offset != len) {
		seg->seg_len = len - seg->seg_offset;
	} else {
		(void) list_remove_tail(&seg_list);
	}

	print_list(&seg_list, fname, options);
	list_destroy(&seg_list);
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2019 Joyent, Inc.
#

PROG = has_unmap

include $(SRC)/cmd/Makefile.cmd

LDLIBS += -lc

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2019 Joyent, Inc.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/dkio.h>

int
main(int argc, char **argv)
{
	int umap, fd;

	if (argc < 2) {
		fprintf(stderr, "missing disk name\n");
		exit(2);
	}

	if ((fd = open(argv[1], O_RDONLY)) == -1) {
		fprintf(stderr, "couldn't open %s: %s\n", argv[1],
		    strerror(errno));
		exit(2);
	}

	if (ioctl(fd, DKIOC_CANFREE, &umap) < 0) {
		fprintf(stderr, "ioctl failed %s: %s\n", argv[1],
		    strerror(errno));
		exit(2);
	}

	(void) close(fd);

	return (umap ? 0 : 1);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = largest_file

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2012 by Delphix. All rights reserved.
 */

#include "../file_common.h"
#include <sys/param.h>
#include <signal.h>
#include <stdio.h>

/*
 * --------------------------------------------------------------
 *
 *	Assertion:
 *		The last byte of the largest file size can be
 *		accessed without any errors.  Also, the writing
 *		beyond the last byte of the largest file size
 *		will produce an errno of EFBIG.
 *
 * --------------------------------------------------------------
 *	If the write() system call below returns a "1",
 *	then the last byte can be accessed.
 * --------------------------------------------------------------
 */
static void	sigxfsz(int);
static void	usage(char *);

int
main(int argc, char **argv)
{
	int		fd = 0;
	offset_t	offset = (MAXOFFSET_T - 1);
	offset_t	llseek_ret = 0;
	int		write_ret = 0;
	int		err = 0;
	char		mybuf[5];
	char		*testfile;
	mode_t		mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

	if (argc != 2) {
		usage(argv[0]);
	}

	(void) sigset(SIGXFSZ, sigxfsz);

	testfile = strdup(argv[1]);

	fd = open(testfile, O_CREAT | O_RDWR, mode);
	if (fd < 0) {
		perror("Failed to create testfile");
		err = errno;
		goto out;
	}

	llseek_ret = llseek(fd, offset, SEEK_SET);
	if (llseek_ret < 0) {
		perror("Failed to seek to end of testfile");
		err = errno;
		goto out;
	}

	write_ret = write(fd, mybuf, 1);
	if (write_ret < 0) {
		perror("Failed to write to end of file");
		err = errno;
		goto out;
	}

	offset = 0;
	llseek_ret = llseek(fd, offset, SEEK_CUR);
	if (llseek_ret < 0) {
		perror("Failed to seek to end of file");
		err = errno;
		goto out;
	}

	write_ret = write(fd, mybuf, 1);
	if (write_ret < 0) {
		if (errno == EFBIG) {
			(void) printf("write errno=EFBIG: success\n");
			err = 0;
		} else {
			perror("Did not receive EFBIG");
			err = errno;
		}
	} else {
		(void) printf("write completed successfully, test failed\n");
		err = 1;
	}

out:
	(void) unlink(testfile);
	free(testfile);
	return (err);
}

static void
usage(char *name)
{
	(void) printf("%s <testfile>\n", name);
	exit(1);
}

/* ARGSUSED */
static void
sigxfsz(int signo)
{
	(void) printf("\nlargest_file: sigxfsz() caught SIGXFSZ\n");
}
/libzfs_input_check
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2020 Joyent, Inc.
#

PROG = libzfs_input_check

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs

CPPFLAGS += -I$(SRC)/uts/common/fs/zfs
LDLIBS += -lnvpair -lzfs_core
/*
 * CDDL HEADER START
 *
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2018 by Delphix. All rights reserved.
 * Copyright 2020 Joyent, Inc.
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <libzfs_core.h>
#include <unistd.h>

#include <sys/nvpair.h>
#include <sys/vdev_impl.h>
#include <sys/zfs_ioctl.h>
#include <sys/zfs_bootenv.h>

/*
 * Test the nvpair inputs for the non-legacy zfs ioctl commands.
 */

boolean_t unexpected_failures;
int zfs_fd;
const char *active_test;

/*
 * Tracks which zfs_ioc_t commands were tested
 */
boolean_t ioc_tested[256];

/*
 * Legacy ioctls that are skipped (for now)
 */
static unsigned ioc_skip[] = {
	ZFS_IOC_POOL_CREATE,
	ZFS_IOC_POOL_DESTROY,
	ZFS_IOC_POOL_IMPORT,
	ZFS_IOC_POOL_EXPORT,
	ZFS_IOC_POOL_CONFIGS,
	ZFS_IOC_POOL_STATS,
	ZFS_IOC_POOL_TRYIMPORT,
	ZFS_IOC_POOL_SCAN,
	ZFS_IOC_POOL_FREEZE,
	ZFS_IOC_POOL_UPGRADE,
	ZFS_IOC_POOL_GET_HISTORY,

	ZFS_IOC_VDEV_ADD,
	ZFS_IOC_VDEV_REMOVE,
	ZFS_IOC_VDEV_SET_STATE,
	ZFS_IOC_VDEV_ATTACH,
	ZFS_IOC_VDEV_DETACH,
	ZFS_IOC_VDEV_SETPATH,
	ZFS_IOC_VDEV_SETFRU,

	ZFS_IOC_OBJSET_STATS,
	ZFS_IOC_OBJSET_ZPLPROPS,
	ZFS_IOC_DATASET_LIST_NEXT,
	ZFS_IOC_SNAPSHOT_LIST_NEXT,
	ZFS_IOC_SET_PROP,
	ZFS_IOC_DESTROY,
	ZFS_IOC_RENAME,
	ZFS_IOC_RECV,
	ZFS_IOC_SEND,
	ZFS_IOC_INJECT_FAULT,
	ZFS_IOC_CLEAR_FAULT,
	ZFS_IOC_INJECT_LIST_NEXT,
	ZFS_IOC_ERROR_LOG,
	ZFS_IOC_CLEAR,
	ZFS_IOC_PROMOTE,
	ZFS_IOC_DSOBJ_TO_DSNAME,
	ZFS_IOC_OBJ_TO_PATH,
	ZFS_IOC_POOL_SET_PROPS,
	ZFS_IOC_POOL_GET_PROPS,
	ZFS_IOC_SET_FSACL,
	ZFS_IOC_GET_FSACL,
	ZFS_IOC_SHARE,
	ZFS_IOC_INHERIT_PROP,
	ZFS_IOC_SMB_ACL,
	ZFS_IOC_USERSPACE_ONE,
	ZFS_IOC_USERSPACE_MANY,
	ZFS_IOC_USERSPACE_UPGRADE,
	ZFS_IOC_OBJSET_RECVD_PROPS,
	ZFS_IOC_VDEV_SPLIT,
	ZFS_IOC_NEXT_OBJ,
	ZFS_IOC_DIFF,
	ZFS_IOC_TMP_SNAPSHOT,
	ZFS_IOC_OBJ_TO_STATS,
	ZFS_IOC_SPACE_WRITTEN,
	ZFS_IOC_POOL_REGUID,
	ZFS_IOC_SEND_PROGRESS,

#ifndef __sun
	ZFS_IOC_EVENTS_NEXT,
	ZFS_IOC_EVENTS_CLEAR,
	ZFS_IOC_EVENTS_SEEK,
	ZFS_IOC_NEXTBOOT,
	ZFS_IOC_JAIL,
	ZFS_IOC_UNJAIL,
#else
	/* This is still a legacy ioctl in illumos */
	ZFS_IOC_POOL_REOPEN,
#endif
};


#define	IOC_INPUT_TEST(ioc, name, req, opt, err)		\
	IOC_INPUT_TEST_IMPL(ioc, name, req, opt, err, B_FALSE)

#define	IOC_INPUT_TEST_WILD(ioc, name, req, opt, err)		\
	IOC_INPUT_TEST_IMPL(ioc, name, req, opt, err, B_TRUE)

#define	IOC_INPUT_TEST_IMPL(ioc, name, req, opt, err, wild)	\
	do {							\
		active_test = __func__ + 5;			\
		ioc_tested[ioc - ZFS_IOC_FIRST] = B_TRUE;	\
		(void) lzc_ioctl_test(ioc, name, req, opt, err, wild);	\
	} while (0)

/*
 * run a zfs ioctl command, verify expected results and log failures
 */
static void
lzc_ioctl_run(zfs_ioc_t ioc, const char *name, nvlist_t *innvl, int expected)
{
	zfs_cmd_t zc = {"\0"};
	char *packed = NULL;
	const char *variant;
	size_t size = 0;
	int error = 0;

	switch (expected) {
	case ZFS_ERR_IOC_ARG_UNAVAIL:
		variant = "unsupported input";
		break;
	case ZFS_ERR_IOC_ARG_REQUIRED:
		variant = "missing input";
		break;
	case ZFS_ERR_IOC_ARG_BADTYPE:
		variant = "invalid input type";
		break;
	default:
		variant = "valid input";
		break;
	}

	packed = fnvlist_pack(innvl, &size);
	(void) strncpy(zc.zc_name, name, sizeof (zc.zc_name));
	zc.zc_name[sizeof (zc.zc_name) - 1] = '\0';
	zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
	zc.zc_nvlist_src_size = size;
	zc.zc_nvlist_dst_size = MAX(size * 2, 128 * 1024);
	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)malloc(zc.zc_nvlist_dst_size);

	if (ioctl(zfs_fd, ioc, &zc) != 0)
		error = errno;

	if (error != expected) {
		unexpected_failures = B_TRUE;
		(void) fprintf(stderr, "%s: Unexpected result with %s, "
		    "error %d (expecting %d)\n",
		    active_test, variant, error, expected);
	}

	fnvlist_pack_free(packed, size);
	free((void *)(uintptr_t)zc.zc_nvlist_dst);
}

/*
 * Test each ioc for the following ioctl input errors:
 *   ZFS_ERR_IOC_ARG_UNAVAIL	an input argument is not supported by kernel
 *   ZFS_ERR_IOC_ARG_REQUIRED	a required input argument is missing
 *   ZFS_ERR_IOC_ARG_BADTYPE	an input argument has an invalid type
 */
static int
lzc_ioctl_test(zfs_ioc_t ioc, const char *name, nvlist_t *required,
    nvlist_t *optional, int expected_error, boolean_t wildcard)
{
	nvlist_t *input = fnvlist_alloc();
	nvlist_t *future = fnvlist_alloc();
	int error = 0;

	if (required != NULL) {
		for (nvpair_t *pair = nvlist_next_nvpair(required, NULL);
		    pair != NULL; pair = nvlist_next_nvpair(required, pair)) {
			fnvlist_add_nvpair(input, pair);
		}
	}
	if (optional != NULL) {
		for (nvpair_t *pair = nvlist_next_nvpair(optional, NULL);
		    pair != NULL; pair = nvlist_next_nvpair(optional, pair)) {
			fnvlist_add_nvpair(input, pair);
		}
	}

	/*
	 * Generic input run with 'optional' nvlist pair
	 */
	if (!wildcard)
		fnvlist_add_nvlist(input, "optional", future);
	lzc_ioctl_run(ioc, name, input, expected_error);
	if (!wildcard)
		fnvlist_remove(input, "optional");

	/*
	 * Bogus input value
	 */
	if (!wildcard) {
		fnvlist_add_string(input, "bogus_input", "bogus");
		lzc_ioctl_run(ioc, name, input, ZFS_ERR_IOC_ARG_UNAVAIL);
		fnvlist_remove(input, "bogus_input");
	}

	/*
	 * Missing required inputs
	 */
	if (required != NULL) {
		nvlist_t *empty = fnvlist_alloc();
		lzc_ioctl_run(ioc, name, empty, ZFS_ERR_IOC_ARG_REQUIRED);
		nvlist_free(empty);
	}

	/*
	 * Wrong nvpair type
	 */
	if (required != NULL || optional != NULL) {
		/*
		 * switch the type of one of the input pairs
		 */
		for (nvpair_t *pair = nvlist_next_nvpair(input, NULL);
		    pair != NULL; pair = nvlist_next_nvpair(input, pair)) {
			char pname[MAXNAMELEN];
			data_type_t ptype;

			(void) strncpy(pname, nvpair_name(pair),
			    sizeof (pname));
			pname[sizeof (pname) - 1] = '\0';
			ptype = nvpair_type(pair);
			fnvlist_remove_nvpair(input, pair);

			switch (ptype) {
			case DATA_TYPE_STRING:
				fnvlist_add_uint64(input, pname, 42);
				break;
			default:
				fnvlist_add_string(input, pname, "bogus");
				break;
			}
		}
		lzc_ioctl_run(ioc, name, input, ZFS_ERR_IOC_ARG_BADTYPE);
	}

	nvlist_free(future);
	nvlist_free(input);

	return (error);
}

static void
test_pool_sync(const char *pool)
{
	nvlist_t *required = fnvlist_alloc();

	fnvlist_add_boolean_value(required, "force", B_TRUE);

	IOC_INPUT_TEST(ZFS_IOC_POOL_SYNC, pool, required, NULL, 0);

	nvlist_free(required);
}

#ifndef sun
static void
test_pool_reopen(const char *pool)
{
	nvlist_t *required = fnvlist_alloc();

	fnvlist_add_boolean_value(required, "scrub_restart", B_FALSE);

	IOC_INPUT_TEST(ZFS_IOC_POOL_REOPEN, pool, required, NULL, 0);

	nvlist_free(required);
}
#endif

static void
test_pool_checkpoint(const char *pool)
{
	IOC_INPUT_TEST(ZFS_IOC_POOL_CHECKPOINT, pool, NULL, NULL, 0);
}

static void
test_pool_discard_checkpoint(const char *pool)
{
	int err = lzc_pool_checkpoint(pool);
	if (err == 0 || err == ZFS_ERR_CHECKPOINT_EXISTS)
		IOC_INPUT_TEST(ZFS_IOC_POOL_DISCARD_CHECKPOINT, pool, NULL,
		    NULL, 0);
}

static void
test_log_history(const char *pool)
{
	nvlist_t *required = fnvlist_alloc();

	fnvlist_add_string(required, "message", "input check");

	IOC_INPUT_TEST(ZFS_IOC_LOG_HISTORY, pool, required, NULL, 0);

	nvlist_free(required);
}

static void
test_create(const char *pool)
{
	char dataset[MAXNAMELEN + 32];

	(void) snprintf(dataset, sizeof (dataset), "%s/create-fs", pool);

	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *props = fnvlist_alloc();

	fnvlist_add_int32(required, "type", DMU_OST_ZFS);
	fnvlist_add_uint64(props, "recordsize", 8192);
	fnvlist_add_nvlist(optional, "props", props);

	IOC_INPUT_TEST(ZFS_IOC_CREATE, dataset, required, optional, 0);

	nvlist_free(required);
	nvlist_free(optional);
}

static void
test_snapshot(const char *pool, const char *snapshot)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *snaps = fnvlist_alloc();
	nvlist_t *props = fnvlist_alloc();

	fnvlist_add_boolean(snaps, snapshot);
	fnvlist_add_nvlist(required, "snaps", snaps);

	fnvlist_add_string(props, "org.openzfs:launch", "September 17th, 2013");
	fnvlist_add_nvlist(optional, "props", props);

	IOC_INPUT_TEST(ZFS_IOC_SNAPSHOT, pool, required, optional, 0);

	nvlist_free(props);
	nvlist_free(snaps);
	nvlist_free(optional);
	nvlist_free(required);
}

static void
test_space_snaps(const char *snapshot)
{
	nvlist_t *required = fnvlist_alloc();
	fnvlist_add_string(required, "firstsnap", snapshot);

	IOC_INPUT_TEST(ZFS_IOC_SPACE_SNAPS, snapshot, required, NULL, 0);

	nvlist_free(required);
}

static void
test_destroy_snaps(const char *pool, const char *snapshot)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *snaps = fnvlist_alloc();

	fnvlist_add_boolean(snaps, snapshot);
	fnvlist_add_nvlist(required, "snaps", snaps);

	IOC_INPUT_TEST(ZFS_IOC_DESTROY_SNAPS, pool, required, NULL, 0);

	nvlist_free(snaps);
	nvlist_free(required);
}


static void
test_bookmark(const char *pool, const char *snapshot, const char *bookmark)
{
	nvlist_t *required = fnvlist_alloc();

	fnvlist_add_string(required, bookmark, snapshot);

	IOC_INPUT_TEST_WILD(ZFS_IOC_BOOKMARK, pool, required, NULL, 0);

	nvlist_free(required);
}

static void
test_get_bookmarks(const char *dataset)
{
	nvlist_t *optional = fnvlist_alloc();

	fnvlist_add_boolean(optional, "guid");
	fnvlist_add_boolean(optional, "createtxg");
	fnvlist_add_boolean(optional, "creation");

	IOC_INPUT_TEST_WILD(ZFS_IOC_GET_BOOKMARKS, dataset, NULL, optional, 0);

	nvlist_free(optional);
}

static void
test_destroy_bookmarks(const char *pool, const char *bookmark)
{
	nvlist_t *required = fnvlist_alloc();

	fnvlist_add_boolean(required, bookmark);

	IOC_INPUT_TEST_WILD(ZFS_IOC_DESTROY_BOOKMARKS, pool, required, NULL, 0);

	nvlist_free(required);
}

static void
test_clone(const char *snapshot, const char *clone)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *props = fnvlist_alloc();

	fnvlist_add_string(required, "origin", snapshot);

	IOC_INPUT_TEST(ZFS_IOC_CLONE, clone, required, NULL, 0);

	nvlist_free(props);
	nvlist_free(optional);
	nvlist_free(required);
}

static void
test_rollback(const char *dataset, const char *snapshot)
{
	nvlist_t *optional = fnvlist_alloc();

	fnvlist_add_string(optional, "target", snapshot);

	IOC_INPUT_TEST(ZFS_IOC_ROLLBACK, dataset, NULL, optional, B_FALSE);

	nvlist_free(optional);
}

static void
test_hold(const char *pool, const char *snapshot)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *holds = fnvlist_alloc();

	fnvlist_add_string(holds, snapshot, "libzfs_check_hold");
	fnvlist_add_nvlist(required, "holds", holds);
	fnvlist_add_int32(optional, "cleanup_fd", zfs_fd);

	IOC_INPUT_TEST(ZFS_IOC_HOLD, pool, required, optional, 0);

	nvlist_free(holds);
	nvlist_free(optional);
	nvlist_free(required);
}

static void
test_get_holds(const char *snapshot)
{
	IOC_INPUT_TEST(ZFS_IOC_GET_HOLDS, snapshot, NULL, NULL, 0);
}

static void
test_release(const char *pool, const char *snapshot)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *release = fnvlist_alloc();

	fnvlist_add_boolean(release, "libzfs_check_hold");
	fnvlist_add_nvlist(required, snapshot, release);

	IOC_INPUT_TEST_WILD(ZFS_IOC_RELEASE, pool, required, NULL, 0);

	nvlist_free(release);
	nvlist_free(required);
}


static void
test_send_new(const char *snapshot, int fd)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();

	fnvlist_add_int32(required, "fd", fd);

	fnvlist_add_boolean(optional, "largeblockok");
	fnvlist_add_boolean(optional, "embedok");
	fnvlist_add_boolean(optional, "compressok");
	fnvlist_add_boolean(optional, "rawok");

	/*
	 * TODO - Resumable send is harder to set up. So we currently
	 * ignore testing for that variant.
	 */
#if 0
	fnvlist_add_string(optional, "fromsnap", from);
	fnvlist_add_uint64(optional, "resume_object", resumeobj);
	fnvlist_add_uint64(optional, "resume_offset", offset);
#endif
	IOC_INPUT_TEST(ZFS_IOC_SEND_NEW, snapshot, required, optional, 0);

	nvlist_free(optional);
	nvlist_free(required);
}

#ifndef __sun
static void
test_recv_new(const char *dataset, int fd)
{
	dmu_replay_record_t drr = { 0 };
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *props = fnvlist_alloc();
	char snapshot[MAXNAMELEN + 32];
	ssize_t count;

	int cleanup_fd = open(ZFS_DEV, O_RDWR);

	(void) snprintf(snapshot, sizeof (snapshot), "%s@replicant", dataset);

	count = pread(fd, &drr, sizeof (drr), 0);
	if (count != sizeof (drr)) {
		(void) fprintf(stderr, "could not read stream: %s\n",
		    strerror(errno));
	}

	fnvlist_add_string(required, "snapname", snapshot);
	fnvlist_add_byte_array(required, "begin_record", (uchar_t *)&drr,
	    sizeof (drr));
	fnvlist_add_int32(required, "input_fd", fd);

	fnvlist_add_string(props, "org.openzfs:launch", "September 17th, 2013");
	fnvlist_add_nvlist(optional, "localprops", props);
	fnvlist_add_boolean(optional, "force");
	fnvlist_add_int32(optional, "cleanup_fd", cleanup_fd);

	/*
	 * TODO - Resumable receive is harder to set up. So we currently
	 * ignore testing for one.
	 */
#if 0
	fnvlist_add_nvlist(optional, "props", recvdprops);
	fnvlist_add_string(optional, "origin", origin);
	fnvlist_add_boolean(optional, "resumable");
	fnvlist_add_uint64(optional, "action_handle", *action_handle);
#endif
	IOC_INPUT_TEST(ZFS_IOC_RECV_NEW, dataset, required, optional, EBADE);

	nvlist_free(props);
	nvlist_free(optional);
	nvlist_free(required);

	(void) close(cleanup_fd);
}
#endif

static void
test_send_space(const char *snapshot1, const char *snapshot2)
{
	nvlist_t *optional = fnvlist_alloc();

	fnvlist_add_string(optional, "from", snapshot1);
	fnvlist_add_boolean(optional, "largeblockok");
	fnvlist_add_boolean(optional, "embedok");
	fnvlist_add_boolean(optional, "compressok");
	fnvlist_add_boolean(optional, "rawok");

	IOC_INPUT_TEST(ZFS_IOC_SEND_SPACE, snapshot2, NULL, optional, 0);

	nvlist_free(optional);
}

static void
test_remap(const char *dataset)
{
	IOC_INPUT_TEST(ZFS_IOC_REMAP, dataset, NULL, NULL, 0);
}

static void
test_channel_program(const char *pool)
{
	const char *program =
	    "arg = ...\n"
	    "argv = arg[\"argv\"]\n"
	    "return argv[1]";
	char *const argv[1] = { "Hello World!" };
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *args = fnvlist_alloc();

	fnvlist_add_string(required, "program", program);
	fnvlist_add_string_array(args, "argv", argv, 1);
	fnvlist_add_nvlist(required, "arg", args);

	fnvlist_add_boolean_value(optional, "sync", B_TRUE);
	fnvlist_add_uint64(optional, "instrlimit", 1000 * 1000);
	fnvlist_add_uint64(optional, "memlimit", 8192 * 1024);

	IOC_INPUT_TEST(ZFS_IOC_CHANNEL_PROGRAM, pool, required, optional, 0);

	nvlist_free(args);
	nvlist_free(optional);
	nvlist_free(required);
}

#define	WRAPPING_KEY_LEN	32

static void
test_load_key(const char *dataset)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *hidden = fnvlist_alloc();
	uint8_t keydata[WRAPPING_KEY_LEN] = {0};

	fnvlist_add_uint8_array(hidden, "wkeydata", keydata, sizeof (keydata));
	fnvlist_add_nvlist(required, "hidden_args", hidden);
	fnvlist_add_boolean(optional, "noop");

	IOC_INPUT_TEST(ZFS_IOC_LOAD_KEY, dataset, required, optional, EINVAL);
	nvlist_free(hidden);
	nvlist_free(optional);
	nvlist_free(required);
}

static void
test_change_key(const char *dataset)
{
	IOC_INPUT_TEST(ZFS_IOC_CHANGE_KEY, dataset, NULL, NULL, EINVAL);
}

static void
test_unload_key(const char *dataset)
{
	IOC_INPUT_TEST(ZFS_IOC_UNLOAD_KEY, dataset, NULL, NULL, EACCES);
}

static void
test_vdev_initialize(const char *pool)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *vdev_guids = fnvlist_alloc();

	fnvlist_add_uint64(vdev_guids, "path", 0xdeadbeefdeadbeef);
	fnvlist_add_uint64(required, ZPOOL_INITIALIZE_COMMAND,
	    POOL_INITIALIZE_START);
	fnvlist_add_nvlist(required, ZPOOL_INITIALIZE_VDEVS, vdev_guids);

	IOC_INPUT_TEST(ZFS_IOC_POOL_INITIALIZE, pool, required, NULL, EINVAL);
	nvlist_free(vdev_guids);
	nvlist_free(required);
}

static void
test_vdev_trim(const char *pool)
{
	nvlist_t *required = fnvlist_alloc();
	nvlist_t *optional = fnvlist_alloc();
	nvlist_t *vdev_guids = fnvlist_alloc();

	fnvlist_add_uint64(vdev_guids, "path", 0xdeadbeefdeadbeef);
	fnvlist_add_uint64(required, ZPOOL_TRIM_COMMAND, POOL_TRIM_START);
	fnvlist_add_nvlist(required, ZPOOL_TRIM_VDEVS, vdev_guids);
	fnvlist_add_uint64(optional, ZPOOL_TRIM_RATE, 1ULL << 30);
	fnvlist_add_boolean_value(optional, ZPOOL_TRIM_SECURE, B_TRUE);

	IOC_INPUT_TEST(ZFS_IOC_POOL_TRIM, pool, required, optional, EINVAL);
	nvlist_free(vdev_guids);
	nvlist_free(optional);
	nvlist_free(required);
}

static int
zfs_destroy(const char *dataset)
{
	zfs_cmd_t zc = {"\0"};
	int err;

	(void) strncpy(zc.zc_name, dataset, sizeof (zc.zc_name));
	zc.zc_name[sizeof (zc.zc_name) - 1] = '\0';
	zc.zc_objset_type = DMU_OST_ZFS;
	err = ioctl(zfs_fd, ZFS_IOC_DESTROY, &zc);

	return (err == 0 ? 0 : errno);
}

static void
test_get_bootenv(const char *pool)
{
	IOC_INPUT_TEST(ZFS_IOC_GET_BOOTENV, pool, NULL, NULL, 0);
}

static void
test_set_bootenv(const char *pool)
{
	nvlist_t *required = fnvlist_alloc();

	fnvlist_add_uint64(required, "version", VB_RAW);
	fnvlist_add_string(required, GRUB_ENVMAP, "test");

	IOC_INPUT_TEST_WILD(ZFS_IOC_SET_BOOTENV, pool, required, NULL, 0);

	nvlist_free(required);
}

static void
zfs_ioc_input_tests(const char *pool)
{
	char filepath[] = "/tmp/ioc_test_file_XXXXXX";
	char dataset[ZFS_MAX_DATASET_NAME_LEN];
	char snapbase[ZFS_MAX_DATASET_NAME_LEN + 32];
	char snapshot[ZFS_MAX_DATASET_NAME_LEN + 32];
	char bookmark[ZFS_MAX_DATASET_NAME_LEN + 32];
	char backup[ZFS_MAX_DATASET_NAME_LEN];
	char clone[ZFS_MAX_DATASET_NAME_LEN];
	int tmpfd, err;

	/*
	 * Setup names and create a working dataset
	 */
	(void) snprintf(dataset, sizeof (dataset), "%s/test-fs", pool);
	(void) snprintf(snapbase, sizeof (snapbase), "%s@snapbase", dataset);
	(void) snprintf(snapshot, sizeof (snapshot), "%s@snapshot", dataset);
	(void) snprintf(bookmark, sizeof (bookmark), "%s#bookmark", dataset);
	(void) snprintf(clone, sizeof (clone), "%s/test-fs-clone", pool);
	(void) snprintf(backup, sizeof (backup), "%s/backup", pool);

	err = lzc_create(dataset, LZC_DATSET_TYPE_ZFS, NULL, NULL, 0);
	if (err) {
		(void) fprintf(stderr, "could not create '%s': %s\n",
		    dataset, strerror(errno));
		exit(2);
	}

	tmpfd = mkstemp(filepath);
	if (tmpfd < 0) {
		(void) fprintf(stderr, "could not create '%s': %s\n",
		    filepath, strerror(errno));
		exit(2);
	}

	/*
	 * run a test for each ioctl
	 * Note that some test build on previous test operations
	 */
	test_pool_sync(pool);
#ifndef __sun
	test_pool_reopen(pool);
#endif
	test_pool_checkpoint(pool);
	test_pool_discard_checkpoint(pool);
	test_log_history(pool);

	test_create(dataset);
	test_snapshot(pool, snapbase);
	test_snapshot(pool, snapshot);

	test_space_snaps(snapshot);
	test_send_space(snapbase, snapshot);
	test_send_new(snapshot, tmpfd);
#ifndef __sun
	test_recv_new(backup, tmpfd);
#endif

	test_bookmark(pool, snapshot, bookmark);
	test_get_bookmarks(dataset);
	test_destroy_bookmarks(pool, bookmark);

	test_hold(pool, snapshot);
	test_get_holds(snapshot);
	test_release(pool, snapshot);

	test_clone(snapshot, clone);
	(void) zfs_destroy(clone);

	test_rollback(dataset, snapshot);
	test_destroy_snaps(pool, snapshot);
	test_destroy_snaps(pool, snapbase);

	test_remap(dataset);
	test_channel_program(pool);

	test_load_key(dataset);
	test_change_key(dataset);
	test_unload_key(dataset);

	test_vdev_initialize(pool);
	test_vdev_trim(pool);

	test_set_bootenv(pool);
	test_get_bootenv(pool);

	/*
	 * cleanup
	 */
	zfs_cmd_t zc = {"\0"};

	nvlist_t *snaps = fnvlist_alloc();
	fnvlist_add_boolean(snaps, snapshot);
	(void) lzc_destroy_snaps(snaps, B_FALSE, NULL);
	nvlist_free(snaps);

	(void) zfs_destroy(dataset);
	(void) zfs_destroy(backup);

	(void) close(tmpfd);
	(void) unlink(filepath);

	/*
	 * All the unused slots should yield ZFS_ERR_IOC_CMD_UNAVAIL
	 */
	for (int i = 0; i < ARRAY_SIZE(ioc_skip); i++) {
		if (ioc_tested[ioc_skip[i] - ZFS_IOC_FIRST])
			(void) fprintf(stderr, "cmd %d tested, not skipped!\n",
			    (int)(ioc_skip[i] - ZFS_IOC_FIRST));

		ioc_tested[ioc_skip[i] - ZFS_IOC_FIRST] = B_TRUE;
	}

	(void) strncpy(zc.zc_name, pool, sizeof (zc.zc_name));
	zc.zc_name[sizeof (zc.zc_name) - 1] = '\0';

	for (unsigned ioc = ZFS_IOC_FIRST; ioc < ZFS_IOC_LAST; ioc++) {
		unsigned cmd = ioc - ZFS_IOC_FIRST;

		if (ioc_tested[cmd])
			continue;

		if (ioctl(zfs_fd, ioc, &zc) != 0 &&
		    errno != ZFS_ERR_IOC_CMD_UNAVAIL) {
			(void) fprintf(stderr, "cmd %d is missing a test case "
			    "(%d)\n", cmd, errno);
		}
	}
}

enum zfs_ioc_ref {
#ifdef __FreeBSD__
	ZFS_IOC_BASE = 0,
#else
	ZFS_IOC_BASE = ('Z' << 8),
#endif
	ZFS_IOC_PLATFORM_BASE = ZFS_IOC_BASE + 0x80,
};

/*
 * Canonical reference check of /dev/zfs ioctl numbers.
 * These cannot change and new ioctl numbers must be appended.
 */
boolean_t
validate_ioc_values(void)
{
	boolean_t result = B_TRUE;

#define	CHECK(expr) do { \
	if (!(expr)) { \
		result = B_FALSE; \
		fprintf(stderr, "(%s) === FALSE\n", #expr); \
	} \
} while (0)

	CHECK(ZFS_IOC_BASE + 0 == ZFS_IOC_POOL_CREATE);
	CHECK(ZFS_IOC_BASE + 1 == ZFS_IOC_POOL_DESTROY);
	CHECK(ZFS_IOC_BASE + 2 == ZFS_IOC_POOL_IMPORT);
	CHECK(ZFS_IOC_BASE + 3 == ZFS_IOC_POOL_EXPORT);
	CHECK(ZFS_IOC_BASE + 4 == ZFS_IOC_POOL_CONFIGS);
	CHECK(ZFS_IOC_BASE + 5 == ZFS_IOC_POOL_STATS);
	CHECK(ZFS_IOC_BASE + 6 == ZFS_IOC_POOL_TRYIMPORT);
	CHECK(ZFS_IOC_BASE + 7 == ZFS_IOC_POOL_SCAN);
	CHECK(ZFS_IOC_BASE + 8 == ZFS_IOC_POOL_FREEZE);
	CHECK(ZFS_IOC_BASE + 9 == ZFS_IOC_POOL_UPGRADE);
	CHECK(ZFS_IOC_BASE + 10 == ZFS_IOC_POOL_GET_HISTORY);
	CHECK(ZFS_IOC_BASE + 11 == ZFS_IOC_VDEV_ADD);
	CHECK(ZFS_IOC_BASE + 12 == ZFS_IOC_VDEV_REMOVE);
	CHECK(ZFS_IOC_BASE + 13 == ZFS_IOC_VDEV_SET_STATE);
	CHECK(ZFS_IOC_BASE + 14 == ZFS_IOC_VDEV_ATTACH);
	CHECK(ZFS_IOC_BASE + 15 == ZFS_IOC_VDEV_DETACH);
	CHECK(ZFS_IOC_BASE + 16 == ZFS_IOC_VDEV_SETPATH);
	CHECK(ZFS_IOC_BASE + 17 == ZFS_IOC_VDEV_SETFRU);
	CHECK(ZFS_IOC_BASE + 18 == ZFS_IOC_OBJSET_STATS);
	CHECK(ZFS_IOC_BASE + 19 == ZFS_IOC_OBJSET_ZPLPROPS);
	CHECK(ZFS_IOC_BASE + 20 == ZFS_IOC_DATASET_LIST_NEXT);
	CHECK(ZFS_IOC_BASE + 21 == ZFS_IOC_SNAPSHOT_LIST_NEXT);
	CHECK(ZFS_IOC_BASE + 22 == ZFS_IOC_SET_PROP);
	CHECK(ZFS_IOC_BASE + 23 == ZFS_IOC_CREATE);
	CHECK(ZFS_IOC_BASE + 24 == ZFS_IOC_DESTROY);
	CHECK(ZFS_IOC_BASE + 25 == ZFS_IOC_ROLLBACK);
	CHECK(ZFS_IOC_BASE + 26 == ZFS_IOC_RENAME);
	CHECK(ZFS_IOC_BASE + 27 == ZFS_IOC_RECV);
	CHECK(ZFS_IOC_BASE + 28 == ZFS_IOC_SEND);
	CHECK(ZFS_IOC_BASE + 29 == ZFS_IOC_INJECT_FAULT);
	CHECK(ZFS_IOC_BASE + 30 == ZFS_IOC_CLEAR_FAULT);
	CHECK(ZFS_IOC_BASE + 31 == ZFS_IOC_INJECT_LIST_NEXT);
	CHECK(ZFS_IOC_BASE + 32 == ZFS_IOC_ERROR_LOG);
	CHECK(ZFS_IOC_BASE + 33 == ZFS_IOC_CLEAR);
	CHECK(ZFS_IOC_BASE + 34 == ZFS_IOC_PROMOTE);
	CHECK(ZFS_IOC_BASE + 35 == ZFS_IOC_SNAPSHOT);
	CHECK(ZFS_IOC_BASE + 36 == ZFS_IOC_DSOBJ_TO_DSNAME);
	CHECK(ZFS_IOC_BASE + 37 == ZFS_IOC_OBJ_TO_PATH);
	CHECK(ZFS_IOC_BASE + 38 == ZFS_IOC_POOL_SET_PROPS);
	CHECK(ZFS_IOC_BASE + 39 == ZFS_IOC_POOL_GET_PROPS);
	CHECK(ZFS_IOC_BASE + 40 == ZFS_IOC_SET_FSACL);
	CHECK(ZFS_IOC_BASE + 41 == ZFS_IOC_GET_FSACL);
	CHECK(ZFS_IOC_BASE + 42 == ZFS_IOC_SHARE);
	CHECK(ZFS_IOC_BASE + 43 == ZFS_IOC_INHERIT_PROP);
	CHECK(ZFS_IOC_BASE + 44 == ZFS_IOC_SMB_ACL);
	CHECK(ZFS_IOC_BASE + 45 == ZFS_IOC_USERSPACE_ONE);
	CHECK(ZFS_IOC_BASE + 46 == ZFS_IOC_USERSPACE_MANY);
	CHECK(ZFS_IOC_BASE + 47 == ZFS_IOC_USERSPACE_UPGRADE);
	CHECK(ZFS_IOC_BASE + 48 == ZFS_IOC_HOLD);
	CHECK(ZFS_IOC_BASE + 49 == ZFS_IOC_RELEASE);
	CHECK(ZFS_IOC_BASE + 50 == ZFS_IOC_GET_HOLDS);
	CHECK(ZFS_IOC_BASE + 51 == ZFS_IOC_OBJSET_RECVD_PROPS);
	CHECK(ZFS_IOC_BASE + 52 == ZFS_IOC_VDEV_SPLIT);
	CHECK(ZFS_IOC_BASE + 53 == ZFS_IOC_NEXT_OBJ);
	CHECK(ZFS_IOC_BASE + 54 == ZFS_IOC_DIFF);
	CHECK(ZFS_IOC_BASE + 55 == ZFS_IOC_TMP_SNAPSHOT);
	CHECK(ZFS_IOC_BASE + 56 == ZFS_IOC_OBJ_TO_STATS);
	CHECK(ZFS_IOC_BASE + 57 == ZFS_IOC_SPACE_WRITTEN);
	CHECK(ZFS_IOC_BASE + 58 == ZFS_IOC_SPACE_SNAPS);
	CHECK(ZFS_IOC_BASE + 59 == ZFS_IOC_DESTROY_SNAPS);
	CHECK(ZFS_IOC_BASE + 60 == ZFS_IOC_POOL_REGUID);
	CHECK(ZFS_IOC_BASE + 61 == ZFS_IOC_POOL_REOPEN);
	CHECK(ZFS_IOC_BASE + 62 == ZFS_IOC_SEND_PROGRESS);
	CHECK(ZFS_IOC_BASE + 63 == ZFS_IOC_LOG_HISTORY);
	CHECK(ZFS_IOC_BASE + 64 == ZFS_IOC_SEND_NEW);
	CHECK(ZFS_IOC_BASE + 65 == ZFS_IOC_SEND_SPACE);
	CHECK(ZFS_IOC_BASE + 66 == ZFS_IOC_CLONE);
	CHECK(ZFS_IOC_BASE + 67 == ZFS_IOC_BOOKMARK);
	CHECK(ZFS_IOC_BASE + 68 == ZFS_IOC_GET_BOOKMARKS);
	CHECK(ZFS_IOC_BASE + 69 == ZFS_IOC_DESTROY_BOOKMARKS);
#ifndef __sun
	CHECK(ZFS_IOC_BASE + 71 == ZFS_IOC_RECV_NEW);
#endif
	CHECK(ZFS_IOC_BASE + 70 == ZFS_IOC_POOL_SYNC);
	CHECK(ZFS_IOC_BASE + 71 == ZFS_IOC_CHANNEL_PROGRAM);
	CHECK(ZFS_IOC_BASE + 72 == ZFS_IOC_LOAD_KEY);
	CHECK(ZFS_IOC_BASE + 73 == ZFS_IOC_UNLOAD_KEY);
	CHECK(ZFS_IOC_BASE + 74 == ZFS_IOC_CHANGE_KEY);
	CHECK(ZFS_IOC_BASE + 75 == ZFS_IOC_REMAP);
	CHECK(ZFS_IOC_BASE + 76 == ZFS_IOC_POOL_CHECKPOINT);

#ifndef __sun
	CHECK(ZFS_IOC_BASE + 78 == ZFS_IOC_POOL_DISCARD_CHECKPOINT);
	CHECK(ZFS_IOC_PLATFORM_BASE + 1 == ZFS_IOC_EVENTS_NEXT);
	CHECK(ZFS_IOC_PLATFORM_BASE + 2 == ZFS_IOC_EVENTS_CLEAR);
	CHECK(ZFS_IOC_PLATFORM_BASE + 3 == ZFS_IOC_EVENTS_SEEK);
#else
	CHECK(ZFS_IOC_BASE + 77 == ZFS_IOC_POOL_DISCARD_CHECKPOINT);
	CHECK(ZFS_IOC_BASE + 78 == ZFS_IOC_POOL_INITIALIZE);
	CHECK(ZFS_IOC_BASE + 79 == ZFS_IOC_POOL_TRIM);
	CHECK(ZFS_IOC_BASE + 80 == ZFS_IOC_REDACT);
	CHECK(ZFS_IOC_BASE + 81 == ZFS_IOC_GET_BOOKMARK_PROPS);
#endif
	CHECK(ZFS_IOC_PLATFORM_BASE + 7 == ZFS_IOC_SET_BOOTENV);
	CHECK(ZFS_IOC_PLATFORM_BASE + 8 == ZFS_IOC_GET_BOOTENV);

#undef CHECK

	return (result);
}

int
main(int argc, const char *argv[])
{
	if (argc != 2) {
		(void) fprintf(stderr, "usage: %s <pool>\n", argv[0]);
		exit(2);
	}

	if (!validate_ioc_values()) {
		(void) fprintf(stderr, "WARNING: zfs_ioc_t has binary "
		    "incompatible command values\n");
		exit(3);
	}

	(void) libzfs_core_init();
	zfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
	if (zfs_fd < 0) {
		(void) fprintf(stderr, "open: %s\n", strerror(errno));
		libzfs_core_fini();
		exit(2);
	}

	zfs_ioc_input_tests(argv[1]);

	(void) close(zfs_fd);
	libzfs_core_fini();

	return (unexpected_failures);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2016 by Delphix. All rights reserved.
#

PROG = memory_balloon

include $(SRC)/cmd/Makefile.cmd

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

/*
 * Steal memory from the kernel, forcing the ARC to decrease in size, and hold
 * it until the process receives a signal.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

static void
usage(char *progname)
{
	(void) fprintf(stderr, "Usage: %s -f <bytes>\n", progname);
	exit(1);
}

static void
fail(char *err, int rval)
{
	perror(err);
	exit(rval);
}

static void
daemonize(void)
{
	pid_t	pid;

	if ((pid = fork()) < 0) {
		fail("fork", 1);
	} else if (pid != 0) {
		(void) fprintf(stdout, "%ld\n", pid);
		exit(0);
	}

	(void) setsid();
	(void) close(0);
	(void) close(1);
	(void) close(2);
}

int
main(int argc, char *argv[])
{
	int		c;
	boolean_t	fflag = B_FALSE;
	char		*prog = argv[0];
	long long	size;
	char		*stroll_leftovers;
	int		shm_id;
	void		*shm_attached;

	while ((c = getopt(argc, argv, "f")) != -1) {
		switch (c) {
		/* Run in the foreground */
		case 'f':
			fflag = B_TRUE;
			break;
		default:
			usage(prog);
		}
	}

	argc -= optind;
	argv += optind;

	if (argc != 1)
		usage(prog);
	size = strtoll(argv[0], &stroll_leftovers, 10);
	if (size <= 0)
		fail("invalid size in bytes", 1);

	if ((shm_id = shmget(IPC_PRIVATE, size, IPC_CREAT|IPC_EXCL)) == -1)
		fail("shmget", 1);
	if ((shm_attached = shmat(shm_id, NULL, SHM_SHARE_MMU)) == (void *)-1)
		fail("shmat", 1);

	if (fflag == B_FALSE)
		daemonize();
	(void) pause();

	/* NOTREACHED */
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = mkbusy

include $(SRC)/cmd/Makefile.cmd

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2012 by Delphix. All rights reserved.
 */

/*
 * Make a directory busy. If the argument is an existing file or directory,
 * simply open it directly and pause. If not, verify that the parent directory
 * exists, and create a new file in that directory.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

static void
usage(char *progname)
{
	(void) fprintf(stderr, "Usage: %s <dirname|filename>\n", progname);
	exit(1);
}

static void
fail(char *err, int rval)
{
	perror(err);
	exit(rval);
}

static void
daemonize(void)
{
	pid_t	pid;

	if ((pid = fork()) < 0) {
		fail("fork", 1);
	} else if (pid != 0) {
		(void) fprintf(stdout, "%ld\n", pid);
		exit(0);
	}

	(void) setsid();
	(void) close(0);
	(void) close(1);
	(void) close(2);
}

int
main(int argc, char *argv[])
{
	int		ret, c;
	boolean_t	isdir = B_FALSE;
	boolean_t	fflag = B_FALSE;
	boolean_t	rflag = B_FALSE;
	struct stat	sbuf;
	char		*fpath = NULL;
	char		*prog = argv[0];

	while ((c = getopt(argc, argv, "fr")) != -1) {
		switch (c) {
		/* Open the file or directory read only */
		case 'r':
			rflag = B_TRUE;
			break;
		/* Run in the foreground */
		case 'f':
			fflag = B_TRUE;
			break;
		default:
			usage(prog);
		}
	}

	argc -= optind;
	argv += optind;

	if (argc != 1)
		usage(prog);

	if ((ret = stat(argv[0], &sbuf)) != 0) {
		char	*arg, *dname, *fname;
		int	arglen, dlen, flen;
		char	*slash;

		/*
		 * The argument supplied doesn't exist. Copy the path, and
		 * remove the trailing slash if presnt.
		 */
		if ((arg = strdup(argv[0])) == NULL)
			fail("strdup", 1);
		arglen = strlen(arg);
		if (arg[arglen - 1] == '/')
			arg[arglen - 1] = '\0';

		/*
		 * Get the directory and file names, using the current directory
		 * if the provided path doesn't specify a directory at all.
		 */
		if ((slash = strrchr(arg, '/')) == NULL) {
			dname = strdup(".");
			fname = strdup(arg);
		} else {
			*slash = '\0';
			dname = strdup(arg);
			fname = strdup(slash + 1);
		}
		free(arg);
		if (dname == NULL || fname == NULL)
			fail("strdup", 1);
		dlen = strlen(dname);
		flen = strlen(fname);

		/* The directory portion of the path must exist */
		if ((ret = stat(dname, &sbuf)) != 0 || !(sbuf.st_mode &
		    S_IFDIR))
			usage(prog);

		if ((fpath = (char *)malloc(dlen + 1 + flen + 1)) == NULL)
			fail("malloc", 1);
		(void) memset(fpath, '\0', dlen + 1 + flen + 1);

		(void) strncpy(fpath, dname, dlen);
		fpath[dlen] = '/';
		(void) strncat(fpath, fname, flen);
		free(dname);
		free(fname);
	} else if ((sbuf.st_mode & S_IFMT) == S_IFREG ||
	    (sbuf.st_mode & S_IFMT) == S_IFLNK ||
	    (sbuf.st_mode & S_IFMT) == S_IFCHR ||
	    (sbuf.st_mode & S_IFMT) == S_IFBLK) {
		fpath = strdup(argv[0]);
	} else if ((sbuf.st_mode & S_IFMT) == S_IFDIR) {
		fpath = strdup(argv[0]);
		isdir = B_TRUE;
	} else {
		usage(prog);
	}

	if (fpath == NULL)
		fail("strdup", 1);

	if (isdir == B_FALSE) {
		int	fd, flags;
		mode_t	mode = S_IRUSR | S_IWUSR;

		flags = rflag == B_FALSE ? O_CREAT | O_RDWR : O_RDONLY;

		if ((fd = open(fpath, flags, mode)) < 0)
			fail("open", 1);
	} else {
		DIR	*dp;

		if ((dp = opendir(fpath)) == NULL)
			fail("opendir", 1);
	}
	free(fpath);

	if (fflag == B_FALSE)
		daemonize();
	(void) pause();

	/* NOTREACHED */
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2016 by Delphix. All rights reserved.
#

PROG = mkfiles

include $(SRC)/cmd/Makefile.cmd

LDLIBS += -lc

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2016 by Delphix. All rights reserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/param.h>

#define	MAX_INT_LENGTH 10

static void
usage(char *msg, int exit_value)
{
	(void) fprintf(stderr, "mkfiles basename max_file [min_file]\n");
	(void) fprintf(stderr, "%s\n", msg);
	exit(exit_value);
}

int
main(int argc, char **argv)
{
	unsigned int numfiles = 0;
	unsigned int first_file = 0;
	unsigned int i;
	char buf[MAXPATHLEN];

	if (argc < 3 || argc > 4)
		usage("Invalid number of arguments", -1);

	if (sscanf(argv[2], "%u", &numfiles) != 1)
		usage("Invalid maximum file", -2);

	if (argc == 4 && sscanf(argv[3], "%u", &first_file) != 1)
		usage("Invalid first file", -3);

	if (numfiles < first_file)
		usage("First file larger than last file", -3);

	for (i = first_file; i < first_file + numfiles; i++) {
		int fd;
		(void) snprintf(buf, MAXPATHLEN, "%s%u", argv[1], i);
		if ((fd = open(buf, O_CREAT | O_EXCL, O_RDWR)) == -1) {
			(void) fprintf(stderr, "Failed to create %s %s\n", buf,
			    strerror(errno));
			return (-4);
		}
		(void) close(fd);
	}
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2014 by Delphix. All rights reserved.
#

PROG = mkholes

include $(SRC)/cmd/Makefile.cmd

LDLIBS += -lumem -lcmdutils

include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2014 by Delphix. All rights reserved.
 */

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <umem.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/list.h>

extern int errno;

typedef enum {
	SEG_HOLE,
	SEG_DATA,
	SEG_TYPES
} seg_type_t;

typedef struct segment {
	list_node_t	seg_node;
	seg_type_t	seg_type;
	off_t		seg_offset;
	off_t		seg_len;
} seg_t;

static int
no_memory(void) {
	(void) fprintf(stderr, "malloc failed\n");
	return (UMEM_CALLBACK_EXIT(255));
}

static void
usage(char *msg, int exit_value)
{
	(void) fprintf(stderr, "mkholes [-d|h offset:length] ... filename\n");
	(void) fprintf(stderr, "%s\n", msg);
	exit(exit_value);
}

static char *
get_random_buffer(size_t len)
{
	int	rand_fd;
	char	*buf;

	buf = umem_alloc(len, UMEM_NOFAIL);

	/*
	 * Fill the buffer from /dev/urandom to counteract the
	 * effects of compression.
	 */
	if ((rand_fd = open("/dev/urandom", O_RDONLY)) < 0) {
		perror("open /dev/urandom failed");
		exit(1);
	}

	if (read(rand_fd, buf, len) < 0) {
		perror("read /dev/urandom failed");
		exit(1);
	}

	(void) close(rand_fd);

	return (buf);
}

static void
push_segment(list_t *seg_list, seg_type_t seg_type, char *optarg)
{
	char		*off_str, *len_str;
	static off_t	file_size = 0;
	off_t		off, len;
	seg_t		*seg;

	off_str = strtok(optarg, ":");
	len_str = strtok(NULL, ":");

	if (off_str == NULL || len_str == NULL)
		usage("Bad offset or length", 1);

	off = strtoull(off_str, NULL, 0);
	len = strtoull(len_str, NULL, 0);

	if (file_size >= off + len)
		usage("Ranges must ascend and may not overlap.", 1);
	file_size = off + len;

	seg = umem_alloc(sizeof (seg_t), UMEM_NOFAIL);
	seg->seg_type = seg_type;
	seg->seg_offset = off;
	seg->seg_len = len;

	list_insert_tail(seg_list, seg);
}

int
main(int argc, char *argv[])
{
	int	c, fd;
	char	*fname;
	list_t	seg_list;
	seg_t	*seg;

	umem_nofail_callback(no_memory);
	list_create(&seg_list, sizeof (seg_t), offsetof(seg_t, seg_node));

	while ((c = getopt(argc, argv, "d:h:")) != -1) {
		switch (c) {
		case 'd':
			push_segment(&seg_list, SEG_DATA, optarg);
			break;
		case 'h':
			push_segment(&seg_list, SEG_HOLE, optarg);
			break;
		}
	}
	argc -= optind;
	argv += optind;

	if ((fname = argv[0]) == NULL)
		usage("No filename specified", 1);
	fname = argv[0];

	if ((fd = open(fname, O_LARGEFILE | O_RDWR | O_CREAT | O_SYNC,
	    00666)) < 0) {
		perror("open failed");
		exit(1);
	}

	while ((seg = list_remove_head(&seg_list)) != NULL) {
		char	*buf, *vbuf;
		off_t	off = seg->seg_offset;
		off_t	len = seg->seg_len;

		if (seg->seg_type == SEG_HOLE) {
			struct flock	fl;
			off_t bytes_read = 0;
			ssize_t readlen = 1024 * 1024 * 16;

			fl.l_whence = SEEK_SET;
			fl.l_start = off;
			fl.l_len = len;
			if (fcntl(fd, F_FREESP, &fl) != 0) {
				perror("freesp failed");
				exit(1);
			}

			buf = (char *)umem_alloc(readlen, UMEM_NOFAIL);
			vbuf = (char *)umem_zalloc(readlen, UMEM_NOFAIL);
			while (bytes_read < len) {
				ssize_t bytes = pread(fd, buf, readlen, off);
				if (bytes < 0) {
					perror("pread hole failed");
					exit(1);
				}

				if (memcmp(buf, vbuf, bytes) != 0) {
					(void) fprintf(stderr, "Read back hole "
					    "didn't match.\n");
					exit(1);
				}
				bytes_read += bytes;
				off += bytes;
			}

			umem_free(buf, readlen);
			umem_free(vbuf, readlen);
			umem_free(seg, sizeof (seg_t));
		} else if (seg->seg_type == SEG_DATA) {
			buf = get_random_buffer(len);
			vbuf = (char *)umem_alloc(len, UMEM_NOFAIL);
			if ((pwrite(fd, buf, len, off)) < 0) {
				perror("pwrite failed");
				exit(1);
			}

			if ((pread(fd, vbuf, len, off)) != len) {
				perror("pread failed");
				exit(1);
			}

			if (memcmp(buf, vbuf, len) != 0) {
				(void) fprintf(stderr, "Read back buf didn't "
				    "match.\n");
				exit(1);
			}

			umem_free(buf, len);
			umem_free(vbuf, len);
			umem_free(seg, sizeof (seg_t));
		}
	}

	(void) close(fd);
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = mktree

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2022 MNX Cloud, Inc.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/param.h>

#define	TYPE_D 'D'
#define	TYPE_F 'F'

extern int errno;

static char fdname[MAXPATHLEN] = {0};
static char *pbasedir = NULL;
static int nlevel = 2;
static int ndir = 2;
static int nfile = 2;

static void  usage(char *this);
static void  crtfile(char *pname);
static char *getfdname(char *pdir, char type, int level, int dir, int file);
static int   mktree(char *pbasedir, int level);

int
main(int argc, char *argv[])
{
	int c, ret;

	while ((c = getopt(argc, argv, "b:l:d:f:")) != -1) {
		switch (c) {
		case 'b':
			pbasedir = optarg;
			break;
		case 'l':
			nlevel = atoi(optarg);
			break;
		case 'd':
			ndir = atoi(optarg);
			break;
		case 'f':
			nfile = atoi(optarg);
			break;
		case '?':
			usage(argv[0]);
		}
	}
	if (nlevel < 0 || ndir < 0 || nfile < 0 || pbasedir == NULL) {
		usage(argv[0]);
	}

	ret = mktree(pbasedir, 1);

	return (ret);
}

static void
usage(char *this)
{
	(void) fprintf(stderr,
	    "\tUsage: %s -b <base_dir> -l [nlevel] -d [ndir] -f [nfile]\n",
	    this);
	exit(1);
}

static int
mktree(char *pdir, int level)
{
	int d, f;
	char dname[MAXPATHLEN] = {0};
	char fname[MAXPATHLEN] = {0};

	if (level > nlevel) {
		return (1);
	}

	for (d = 0; d < ndir; d++) {
		(void) memset(dname, '\0', sizeof (dname));
		(void) strcpy(dname, getfdname(pdir, TYPE_D, level, d, 0));

		if (mkdir(dname, 0777) != 0) {
			int exitcode = errno;
			(void) fprintf(stderr, "mkdir(%s) failed."
			    "\n[%d]: %s.\n",
			    dname, errno, strerror(errno));
			exit(exitcode);
		}

		/*
		 * No sub-directory need be created, only create files in it.
		 */
		if (mktree(dname, level+1) != 0) {
			for (f = 0; f < nfile; f++) {
				(void) memset(fname, '\0', sizeof (fname));
				(void) strcpy(fname,
				    getfdname(dname, TYPE_F, level+1, d, f));
				crtfile(fname);
			}
		}
	}

	for (f = 0; f < nfile; f++) {
		(void) memset(fname, '\0', sizeof (fname));
		(void) strcpy(fname, getfdname(pdir, TYPE_F, level, d, f));
		crtfile(fname);
	}

	return (0);
}

static char *
getfdname(char *pdir, char type, int level, int dir, int file)
{
	(void) snprintf(fdname, sizeof (fdname),
	    "%s/%c-l%dd%df%d", pdir, type, level, dir, file);
	return (fdname);
}

static void
crtfile(char *pname)
{
	int fd = -1;
	int afd = -1;
	int i, size;
	int exitcode;
	char *context = "0123456789ABCDF";
	char *pbuf;

	if (pname == NULL) {
		exit(1);
	}

	size = sizeof (char) * 1024;
	pbuf = (char *)valloc(size);
	for (i = 0; i < size / strlen(context); i++) {
		int offset = i * strlen(context);
		(void) snprintf(pbuf+offset, size-offset, "%s", context);
	}

	if ((fd = open(pname, O_CREAT|O_RDWR, 0777)) < 0) {
		exitcode = errno;
		(void) fprintf(stderr, "open(%s, O_CREAT|O_RDWR, 0777) failed."
		    "\n[%d]: %s.\n", pname, errno, strerror(errno));
		exit(exitcode);
	}
	if (write(fd, pbuf, 1024) < 1024) {
		exitcode = errno;
		(void) fprintf(stderr, "write(fd, pbuf, 1024) failed."
		    "\n[%d]: %s.\n", errno, strerror(errno));
		exit(exitcode);
	}

	if ((afd = openat(fd, "xattr", O_CREAT | O_RDWR | O_XATTR, 0777)) < 0) {
		exitcode = errno;
		(void) fprintf(stderr, "openat failed.\n[%d]: %s.\n",
		    errno, strerror(errno));
		exit(exitcode);
	}
	if (write(afd, pbuf, 1024) < 1024) {
		exitcode = errno;
		(void) fprintf(stderr, "write(afd, pbuf, 1024) failed."
		    "\n[%d]: %s.\n", errno, strerror(errno));
		exit(exitcode);
	}

	(void) close(afd);
	(void) close(fd);
	free(pbuf);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = mmapwrite

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <pthread.h>

/*
 * --------------------------------------------------------------------
 * Bug Id: 5032643
 *
 * Simply writing to a file and mmaping that file at the same time can
 * result in deadlock.  Nothing perverse like writing from the file's
 * own mapping is required.
 * --------------------------------------------------------------------
 */

static void *
mapper(void *fdp)
{
	void *addr;
	int fd = *(int *)fdp;

	if ((addr =
	    mmap(0, 8192, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
		perror("mmap");
		exit(1);
	}
	for (;;) {
		if (mmap(addr, 8192, PROT_READ,
		    MAP_SHARED|MAP_FIXED, fd, 0) == MAP_FAILED) {
			perror("mmap");
			exit(1);
		}
	}
	/* NOTREACHED */
	return ((void *)1);
}

int
main(int argc, char **argv)
{
	int fd;
	char buf[BUFSIZ];

	if (argc != 2) {
		(void) printf("usage: %s <file name>\n", argv[0]);
		exit(1);
	}

	if ((fd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1) {
		perror("open");
		exit(1);
	}

	if (pthread_create(NULL, NULL, mapper, &fd) != 0) {
		perror("pthread_create");
		exit(1);
	}
	for (;;) {
		if (write(fd, buf, sizeof (buf)) == -1) {
			perror("write");
			exit(1);
		}
	}

	/* NOTREACHED */
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = randfree_file

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2012 by Delphix. All rights reserved.
 */

/*
 * Copyright (c) 2018, Joyent, Inc.
 */

#include "../file_common.h"

/*
 * Create a file with assigned size and then free the specified
 * section of the file
 */

static void usage(char *progname);

static void
usage(char *progname)
{
	(void) fprintf(stderr,
	    "usage: %s [-l filesize] [-s start-offset]"
	    "[-n section-len] filename\n", progname);
	exit(1);
}

int
main(int argc, char *argv[])
{
	char *filename = NULL;
	char *buf;
	size_t filesize = 0;
	off_t start_off = 0;
	off_t off_len = 0;
	int  fd, ch;
	struct flock fl;
	mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

	while ((ch = getopt(argc, argv, "l:s:n:")) != EOF) {
		switch (ch) {
		case 'l':
			filesize = atoll(optarg);
			break;
		case 's':
			start_off = atoll(optarg);
			break;
		case 'n':
			off_len = atoll(optarg);
			break;
		default:
			usage(argv[0]);
			break;
		}
	}

	if (optind == argc - 1)
		filename = argv[optind];
	else
		usage(argv[0]);

	buf = (char *)malloc(filesize);

	if ((fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, mode)) < 0) {
		perror("open");
		free(buf);
		return (1);
	}
	if (write(fd, buf, filesize) < filesize) {
		perror("write");
		free(buf);
		return (1);
	}
	fl.l_whence = SEEK_SET;
	fl.l_start = start_off;
	fl.l_len = off_len;
	if (fcntl(fd, F_FREESP, &fl) != 0) {
		perror("fcntl");
		free(buf);
		return (1);
	}

	free(buf);
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2017 by Delphix. All rights reserved.
#

PROG = randwritecomp

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2017 by Delphix. All rights reserved.
 */

/*
 * The following is defined so the source can use
 * lrand48() and srand48().
 */
#define	__EXTENSIONS__

#include "../file_common.h"

/*
 * The following sample was derived from real-world data
 * of a production Oracle database.
 */
static uint64_t size_distribution[] = {
	0,
	1499018,
	352084,
	1503485,
	4206227,
	5626657,
	5387001,
	3733756,
	2233094,
	874652,
	238635,
	81434,
	33357,
	13106,
	2009,
	1,
	23660,
};


static uint64_t distribution_n;

static uint8_t randbuf[BLOCKSZ];

static void
rwc_pwrite(int fd, const void *buf, size_t nbytes, off_t offset)
{
	size_t nleft = nbytes;
	ssize_t nwrite = 0;

	nwrite = pwrite(fd, buf, nbytes, offset);
	if (nwrite < 0) {
		perror("pwrite");
		exit(EXIT_FAILURE);
	}

	nleft -= nwrite;
	if (nleft != 0) {
		(void) fprintf(stderr, "warning: pwrite: "
		    "wrote %zu out of %zu bytes\n",
		    (nbytes - nleft), nbytes);
	}
}

static void
fillbuf(char *buf)
{
	uint64_t rv = lrand48() % distribution_n;
	uint64_t sum = 0;

	uint64_t i;
	for (i = 0;
	    i < sizeof (size_distribution) / sizeof (size_distribution[0]);
	    i++) {
		sum += size_distribution[i];
		if (rv < sum)
			break;
	}

	bcopy(randbuf, buf, BLOCKSZ);
	if (i == 0)
		bzero(buf, BLOCKSZ - 10);
	else if (i < 16)
		bzero(buf, BLOCKSZ - i * 512 + 256);
	/*LINTED: E_BAD_PTR_CAST_ALIGN*/
	((uint32_t *)buf)[0] = lrand48();
}

static void
exit_usage(void)
{
	(void) printf("usage: ");
	(void) printf("randwritecomp <file> [-s] [nwrites]\n");
	exit(EXIT_FAILURE);
}

static void
sequential_writes(int fd, char *buf, uint64_t nblocks, int64_t n)
{
	for (int64_t i = 0; n == -1 || i < n; i++) {
		fillbuf(buf);

		static uint64_t j = 0;
		if (j == 0)
			j = lrand48() % nblocks;
		rwc_pwrite(fd, buf, BLOCKSZ, j * BLOCKSZ);
		j++;
		if (j >= nblocks)
			j = 0;
	}
}

static void
random_writes(int fd, char *buf, uint64_t nblocks, int64_t n)
{
	for (int64_t i = 0; n == -1 || i < n; i++) {
		fillbuf(buf);
		rwc_pwrite(fd, buf, BLOCKSZ, (lrand48() % nblocks) * BLOCKSZ);
	}
}

int
main(int argc, char *argv[])
{
	int fd, err;
	char *filename = NULL;
	char buf[BLOCKSZ];
	struct stat ss;
	uint64_t nblocks;
	int64_t n = -1;
	int sequential = 0;

	if (argc < 2)
		exit_usage();

	argv++;
	if (strcmp("-s", argv[0]) == 0) {
		sequential = 1;
		argv++;
	}

	if (argv[0] == NULL)
		exit_usage();
	else
		filename = argv[0];

	argv++;
	if (argv[0] != NULL)
		n = strtoull(argv[0], NULL, 0);

	fd = open(filename, O_RDWR|O_CREAT, 0666);
	err = fstat(fd, &ss);
	if (err != 0) {
		(void) fprintf(stderr,
		    "error: fstat returned error code %d\n", err);
		exit(EXIT_FAILURE);
	}

	nblocks = ss.st_size / BLOCKSZ;
	if (nblocks == 0) {
		(void) fprintf(stderr, "error: "
		    "file is too small (min allowed size is %d bytes)\n",
		    BLOCKSZ);
		exit(EXIT_FAILURE);
	}

	srand48(getpid());
	for (int i = 0; i < BLOCKSZ; i++)
		randbuf[i] = lrand48();

	distribution_n = 0;
	for (uint64_t i = 0;
	    i < sizeof (size_distribution) / sizeof (size_distribution[0]);
	    i++) {
		distribution_n += size_distribution[i];
	}

	if (sequential)
		sequential_writes(fd, buf, nblocks, n);
	else
		random_writes(fd, buf, nblocks, n);

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = readmmap

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * --------------------------------------------------------------
 *	BugId 5047993 : Getting bad read data.
 *
 *	Usage: readmmap <filename>
 *
 *	where:
 *		filename is an absolute path to the file name.
 *
 *	Return values:
 *		1 : error
 *		0 : no errors
 * --------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>

int
main(int argc, char **argv)
{
	char *filename = "badfile";
	size_t size = 4395;
	size_t idx = 0;
	char *buf = NULL;
	char *map = NULL;
	int fd = -1, bytes, retval = 0;
	unsigned seed;

	if (argc < 2 || optind == argc) {
		(void) fprintf(stderr,
		    "usage: %s <file name>\n", argv[0]);
		exit(1);
	}

	if ((buf = calloc(1, size)) == NULL) {
		perror("calloc");
		exit(1);
	}

	filename = argv[optind];

	(void) remove(filename);

	fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);
	if (fd == -1) {
		perror("open to create");
		retval = 1;
		goto end;
	}

	bytes = write(fd, buf, size);
	if (bytes != size) {
		(void) printf("short write: %d != %ud\n", bytes, size);
		retval = 1;
		goto end;
	}

	map = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	if (map == MAP_FAILED) {
		perror("mmap");
		retval = 1;
		goto end;
	}
	seed = time(NULL);
	srandom(seed);

	idx = random() % size;
	map[idx] = 1;

	if (msync(map, size, MS_SYNC) != 0) {
		perror("msync");
		retval = 1;
		goto end;
	}

	if (munmap(map, size) != 0) {
		perror("munmap");
		retval = 1;
		goto end;
	}

	bytes = pread(fd, buf, size, 0);
	if (bytes != size) {
		(void) printf("short read: %d != %ud\n", bytes, size);
		retval = 1;
		goto end;
	}

	if (buf[idx] != 1) {
		(void) printf(
		    "bad data from read!  got buf[%ud]=%d, expected 1\n",
		    idx, buf[idx]);
		retval = 1;
		goto end;
	}

	(void) printf("good data from read: buf[%ud]=1\n", idx);
end:
	if (fd != -1) {
		(void) close(fd);
	}
	if (buf != NULL) {
		free(buf);
	}

	return (retval);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = rename_dir

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2012 by Delphix. All rights reserved.
 */

/*
 * Assertion:
 * Create two directory trees in zfs filesystem, and rename
 * directory across the directory structure. ZFS can handle
 * the race situation.
 */

/*
 * Need to create the following directory structures before
 * running this program:
 *
 * mkdir -p 1/2/3/4/5 a/b/c/d/e
 */


#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <strings.h>

int
main()
{
	int i = 1;

	switch (fork()) {
	case -1:
		perror("fork");
		exit(1);
		break;
	case 0:
		while (i > 0) {
			int c_count = 0;
			if (rename("a/b/c", "1/2/3/c") == 0)
				c_count++;
			if (rename("1/2/3/c", "a/b/c") == 0)
				c_count++;
			if (c_count) {
				(void) fprintf(stderr, "c_count: %d", c_count);
			}
		}
		break;
	default:
		while (i > 0) {
			int p_count = 0;
			if (rename("1", "a/b/c/d/e/1") == 0)
				p_count++;
			if (rename("a/b/c/d/e/1", "1") == 0)
				p_count++;
			if (p_count) {
				(void) fprintf(stderr, "p_count: %d", p_count);
			}
		}
		break;
	}

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012 by Delphix. All rights reserved.
#

PROG = rm_lnkcnt_zero_file

include $(SRC)/cmd/Makefile.cmd
include ../Makefile.subdirs
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2012 by Delphix. All rights reserved.
 */

/*
 * --------------------------------------------------------------------
 * The purpose of this test is to see if the bug reported (#4723351) for
 * UFS exists when using a ZFS file system.
 * --------------------------------------------------------------------
 *
 */
#define	_REENTRANT 1
#include <stdio.h>
#include <fcntl.h>
#include <pthread.h>
#include <thread.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>

static const int TRUE = 1;
static char *filebase;

static int
pickidx()
{
	return (random() % 1000);
}

/* ARGSUSED */
static void *
mover(void *a)
{
	char buf[256];
	int idx, len, ret;

	len = strlen(filebase) + 5;

	while (TRUE) {
		idx = pickidx();
		(void) snprintf(buf, len, "%s.%03d", filebase, idx);
		ret = rename(filebase, buf);
		if (ret < 0 && errno != ENOENT)
			(void) perror("renaming file");
	}

	return (NULL);
}

/* ARGSUSED */
static void *
cleaner(void *a)
{
	char buf[256];
	int idx, len, ret;

	len = strlen(filebase) + 5;

	while (TRUE) {
		idx = pickidx();
		(void) snprintf(buf, len, "%s.%03d", filebase, idx);
		ret = remove(buf);
		if (ret < 0 && errno != ENOENT)
			(void) perror("removing file");
	}

	return (NULL);
}

static void *
writer(void *a)
{
	int *fd = (int *)a;

	while (TRUE) {
		(void) close (*fd);
		*fd = open(filebase, O_APPEND | O_RDWR | O_CREAT, 0644);
		if (*fd < 0)
			perror("refreshing file");
		(void) write(*fd, "test\n", 5);
	}

	return (NULL);
}

int
main(int argc, char **argv)
{
	int fd;
	pthread_t tid;

	if (argc == 1) {
		(void) printf("Usage: %s <filebase>\n", argv[0]);
		exit(-1);
	}

	filebase = argv[1];
	fd = open(filebase, O_APPEND | O_RDWR | O_CREAT, 0644);
	if (fd < 0) {
		perror("creating test file");
		exit(-1);
	}

	(void) thr_setconcurrency(4);	/* 3 threads + main */
	(void) pthread_create(&tid, NULL, mover, NULL);
	(void) pthread_create(&tid, NULL, cleaner, NULL);
	(void) pthread_create(&tid, NULL, writer, (void *) &fd);

	while (TRUE) {
		int ret;
		struct stat st;

		ret = stat(filebase, &st);
		if (ret == 0 && (st.st_nlink > 2 || st.st_nlink < 1)) {
			(void) printf("st.st_nlink = %d, exiting\n", \
			    (int)st.st_nlink);
			exit(0);
		}
		(void) sleep(1);
	}

	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012, 2016 by Delphix. All rights reserved.
#

include $(SRC)/Makefile.master

ROOTOPTPKG = $(ROOT)/opt/zfs-tests
TARGETDIR = $(ROOTOPTPKG)/bin

include $(SRC)/test/zfs-tests/Makefile.com
#!/usr/bin/ksh

#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright (c) 2012, 2016 by Delphix. All rights reserved.
# Copyright 2014, OmniTI Computer Consulting, Inc. All rights reserved.
# Copyright 2021 Tintri by DDN, Inc. All rights reserved.
# Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
#

export LC_ALL=C.UTF-8
export PATH="/usr/bin"
export NOINUSE_CHECK=1
export STF_SUITE="/opt/zfs-tests"
export COMMON="$STF_SUITE/runfiles/common.run"
export STF_TOOLS="/opt/test-runner/stf"
export PATHDIR=""
runner="/opt/test-runner/bin/run"
auto_detect=false

if [[ -z "$TESTFAIL_CALLBACKS" ]] ; then
	export TESTFAIL_CALLBACKS="$STF_SUITE/callbacks/zfs_dbgmsg"
fi

function fail
{
	echo $1
	exit ${2:-1}
}

function find_disks
{
	typeset all_disks=$(echo '' | sudo -k format | awk \
	    '/c[0-9]/ {print $2}')
	typeset used_disks=$(zpool status | awk \
	    '/c[0-9]+(t[0-9a-fA-F]+)?d[0-9]+/ {print $1}' | sed -E \
	    's/(s|p)[0-9]+//g')

	typeset disk used avail_disks
	for disk in $all_disks; do
		for used in $used_disks; do
			[[ "$disk" == "$used" ]] && continue 2
		done
		[[ -n $avail_disks ]] && avail_disks="$avail_disks $disk"
		[[ -z $avail_disks ]] && avail_disks="$disk"
	done

	echo $avail_disks
}

function find_rpool
{
	typeset ds=$(mount | awk '/^\/ / {print $3}')
	echo ${ds%%/*}
}

function find_runfile
{
	typeset distro=
	if [[ -d /opt/delphix && -h /etc/delphix/version ]]; then
		distro=delphix
	elif grep -qs OpenIndiana /etc/release; then
		distro=openindiana
	elif grep -qs OmniOS /etc/release; then
		distro=omnios
	fi

	[[ -n $distro ]] && echo $COMMON,$STF_SUITE/runfiles/$distro.run
}

function verify_id
{
	[[ $(id -u) == "0" ]] && fail "This script must not be run as root."

	sudo -k -n id >/dev/null 2>&1 ||
		fail "User must be able to sudo without a password."
}

function verify_disks
{
	typeset disk
	typeset path
	typeset -lu expected_size
	typeset -lu size

	# Ensure disks are large enough for the tests: no less than 10GB
	# and large enough for a crash dump plus overheads: the disk partition
	# table (about 34k), zpool with 4.5MB for pool label and 128k for pool
	# data, so we round up pool data + labels to 5MB.
	expected_size=$(sudo -k -n dumpadm -epH)
	(( expected_size = expected_size + 5 * 1024 * 1024 ))

	if (( expected_size < 10 * 1024 * 1024 * 1024 )); then
		(( expected_size = 10 * 1024 * 1024 * 1024 ))
	fi

	for disk in $DISKS; do
		case $disk in
		/*) path=$disk;;
		*) path=/dev/rdsk/${disk}s0
		esac
		set -A disksize $(sudo -k prtvtoc $path 2>&1 |
			awk '$3 == "bytes/sector" ||
			    ($3 == "accessible" && $4 == "sectors") {print $2}')

		if [[ (-n "${disksize[0]}") && (-n "${disksize[1]}") ]]; then
			(( size = disksize[0] * disksize[1] ))
		else
			return 1
		fi
		if (( size <  expected_size )); then
			(( size = expected_size / 1024 / 1024 / 1024 ))
			fail "$disk is too small, need at least ${size}GB"
		fi
	done
	return 0
}

function create_links
{
	typeset dir=$1
	typeset file_list=$2

	[[ -n $PATHDIR ]] || fail "PATHDIR wasn't correctly set"

	for i in $file_list; do
		[[ ! -e $PATHDIR/$i ]] || fail "$i already exists"
		ln -s $dir/$i $PATHDIR/$i || fail "Couldn't link $i"
	done

}

function constrain_path
{
	. $STF_SUITE/include/commands.cfg

	PATHDIR=$(/usr/bin/mktemp -d /var/tmp/constrained_path.XXXX)
	chmod 755 $PATHDIR || fail "Couldn't chmod $PATHDIR"

	create_links "/usr/bin" "$USR_BIN_FILES"
	create_links "/usr/sbin" "$USR_SBIN_FILES"
	create_links "/sbin" "$SBIN_FILES"
	create_links "/opt/zfs-tests/bin" "$ZFSTEST_FILES"

	# Special case links
	ln -s /usr/gnu/bin/dd $PATHDIR/gnu_dd
}

constrain_path
export PATH=$PATHDIR

verify_id
while getopts ac:l:qT: c; do
	case $c in
	'a')
		auto_detect=true
		;;
	'c')
		runfile=$OPTARG
		[[ -f $runfile ]] || fail "Cannot read file: $runfile"
		if [[ -z $runfiles ]]; then
			runfiles=$runfile
		else
			runfiles+=",$runfile"
		fi
		;;
	'l')
		logfile=$OPTARG
		[[ -f $logfile ]] || fail "Cannot read file: $logfile"
		xargs+=" -l $logfile"
		;;
	'q')
		xargs+=" -q"
		;;
	'T')
		xargs+=" -T $OPTARG"
		;;
	esac
done
shift $((OPTIND - 1))

# If the user specified -a, then use free disks, otherwise use those in $DISKS.
if $auto_detect; then
	export DISKS=$(find_disks)
elif [[ -z $DISKS ]]; then
	fail "\$DISKS not set in env, and -a not specified."
else
	verify_disks || fail "Couldn't verify all the disks in \$DISKS"
fi

# Add the root pool to $KEEP according to its contents.
# It's ok to list it twice.
if [[ -z $KEEP ]]; then
	KEEP="$(find_rpool)"
else
	KEEP+=" $(find_rpool)"
fi

export __ZFS_POOL_EXCLUDE="$KEEP"
export KEEP="^$(echo $KEEP | sed 's/ /$|^/g')\$"

[[ -z $runfiles ]] && runfiles=$(find_runfile)
[[ -z $runfiles ]] && fail "Couldn't determine distro"

. $STF_SUITE/include/default.cfg

num_disks=$(echo $DISKS | awk '{print NF}')
(( num_disks < 3 )) && fail "Not enough disks to run ZFS Test Suite"

# Ensure user has only basic privileges.
ppriv -s EIP=basic -e $runner -c $runfiles $xargs
ret=$?

rm -rf $PATHDIR || fail "Couldn't remove $PATHDIR"

exit $ret