File: libzfs.pyx

package info (click to toggle)
py-libzfs 0.0%2Bgit20240510.5ae7d5e-1
  • links: PTS, VCS
  • area: contrib
  • in suites: sid
  • size: 876 kB
  • sloc: python: 38; makefile: 27; sh: 7
file content (4619 lines) | stat: -rw-r--r-- 157,729 bytes parent folder | download
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
# encoding: utf-8
# cython: language_level=3, c_string_type=unicode, c_string_encoding=default

import os
import stat
import enum
import errno
import itertools
import tempfile
import logging
import time
import threading
cimport libzfs
cimport zfs
cimport nvpair
from datetime import datetime
from libc.errno cimport errno
from libc.string cimport memset, strncpy
from libc.stdlib cimport realloc

import errno as py_errno
import urllib.parse

GLOBAL_CONTEXT_LOCK = threading.Lock()
logger = logging.getLogger(__name__)


include "config.pxi"
include "nvpair.pxi"
include "converter.pxi"


class DatasetType(enum.IntEnum):
    FILESYSTEM = zfs.ZFS_TYPE_FILESYSTEM
    VOLUME = zfs.ZFS_TYPE_VOLUME
    SNAPSHOT = zfs.ZFS_TYPE_SNAPSHOT
    BOOKMARK = zfs.ZFS_TYPE_BOOKMARK


class UserquotaProp(enum.IntEnum):
    USERUSED = zfs.ZFS_PROP_USERUSED
    USERQUOTA = zfs.ZFS_PROP_USERQUOTA
    GROUPUSED = zfs.ZFS_PROP_GROUPUSED
    GROUPQUOTA = zfs.ZFS_PROP_GROUPQUOTA
    IF HAVE_SPA_FEATURE_USEROBJ_ACCOUNTING:
        USEROBJUSED = zfs.ZFS_PROP_USEROBJUSED
        USEROBJQUOTA = zfs.ZFS_PROP_USEROBJQUOTA
        GROUPOBJUSED = zfs.ZFS_PROP_GROUPOBJUSED
        GROUPOBJQUOTA = zfs.ZFS_PROP_GROUPOBJQUOTA
    IF HAVE_SPA_FEATURE_PROJECT_QUOTA:
        PROJECTUSED = zfs.ZFS_PROP_PROJECTUSED
        PROJECTQUOTA = zfs.ZFS_PROP_PROJECTQUOTA
        PROJECTOBJUSED = zfs.ZFS_PROP_PROJECTOBJUSED
        PROJECTOBJQUOTA = zfs.ZFS_PROP_PROJECTOBJQUOTA


class Error(enum.IntEnum):
    SUCCESS = libzfs.EZFS_SUCCESS
    NOMEM = libzfs.EZFS_NOMEM
    BADPROP = libzfs.EZFS_BADPROP
    PROPREADONLY = libzfs.EZFS_PROPREADONLY
    PROPTYPE = libzfs.EZFS_PROPTYPE
    PROPNONINHERIT = libzfs.EZFS_PROPNONINHERIT
    PROPSPACE = libzfs.EZFS_PROPSPACE
    BADTYPE = libzfs.EZFS_BADTYPE
    BUSY = libzfs.EZFS_BUSY
    EXISTS = libzfs.EZFS_EXISTS
    NOENT = libzfs.EZFS_NOENT
    BADSTREAM = libzfs.EZFS_BADSTREAM
    DSREADONLY = libzfs.EZFS_DSREADONLY
    VOLTOOBIG = libzfs.EZFS_VOLTOOBIG
    INVALIDNAME = libzfs.EZFS_INVALIDNAME
    BADRESTORE = libzfs.EZFS_BADRESTORE
    BADBACKUP = libzfs.EZFS_BADBACKUP
    BADTARGET = libzfs.EZFS_BADTARGET
    NODEVICE = libzfs.EZFS_NODEVICE
    BADDEV = libzfs.EZFS_BADDEV
    NOREPLICAS = libzfs.EZFS_NOREPLICAS
    RESILVERING = libzfs.EZFS_RESILVERING
    BADVERSION = libzfs.EZFS_BADVERSION
    POOLUNAVAIL = libzfs.EZFS_POOLUNAVAIL
    DEVOVERFLOW = libzfs.EZFS_DEVOVERFLOW
    BADPATH = libzfs.EZFS_BADPATH
    CROSSTARGET = libzfs.EZFS_CROSSTARGET
    ZONED = libzfs.EZFS_ZONED
    MOUNTFAILED = libzfs.EZFS_MOUNTFAILED
    UMOUNTFAILED = libzfs.EZFS_UMOUNTFAILED
    UNSHARENFSFAILED = libzfs.EZFS_UNSHARENFSFAILED
    SHARENFSFAILED = libzfs.EZFS_SHARENFSFAILED
    PERM = libzfs.EZFS_PERM
    NOSPC = libzfs.EZFS_NOSPC
    FAULT = libzfs.EZFS_FAULT
    IO = libzfs.EZFS_IO
    INTR = libzfs.EZFS_INTR
    ISSPARE = libzfs.EZFS_ISSPARE
    INVALCONFIG = libzfs.EZFS_INVALCONFIG
    RECURSIVE = libzfs.EZFS_RECURSIVE
    NOHISTORY = libzfs.EZFS_NOHISTORY
    POOLPROPS = libzfs.EZFS_POOLPROPS
    POOL_NOTSUP = libzfs.EZFS_POOL_NOTSUP
    INVALARG = libzfs.EZFS_POOL_INVALARG
    NAMETOOLONG = libzfs.EZFS_NAMETOOLONG
    OPENFAILED = libzfs.EZFS_OPENFAILED
    NOCAP = libzfs.EZFS_NOCAP
    LABELFAILED = libzfs.EZFS_LABELFAILED
    BADWHO = libzfs.EZFS_BADWHO
    BADPERM = libzfs.EZFS_BADPERM
    BADPERMSET = libzfs.EZFS_BADPERMSET
    NODELEGATION = libzfs.EZFS_NODELEGATION
    UNSHARESMBFAILED = libzfs.EZFS_UNSHARESMBFAILED
    SHARESMBFAILED = libzfs.EZFS_SHARESMBFAILED
    BADCACHE = libzfs.EZFS_BADCACHE
    ISL2CACHE = libzfs.EZFS_ISL2CACHE
    VDEVNOTSUP = libzfs.EZFS_VDEVNOTSUP
    NOTSUP = libzfs.EZFS_NOTSUP
    SPARE = libzfs.EZFS_ACTIVE_SPARE
    LOGS = libzfs.EZFS_UNPLAYED_LOGS
    RELE = libzfs.EZFS_REFTAG_RELE
    HOLD = libzfs.EZFS_REFTAG_HOLD
    TAGTOOLONG = libzfs.EZFS_TAGTOOLONG
    PIPEFAILED = libzfs.EZFS_PIPEFAILED
    THREADCREATEFAILED = libzfs.EZFS_THREADCREATEFAILED
    ONLINE = libzfs.EZFS_POSTSPLIT_ONLINE
    SCRUBBING = libzfs.EZFS_SCRUBBING
    SCRUB = libzfs.EZFS_NO_SCRUB
    DIFF = libzfs.EZFS_DIFF
    DIFFDATA = libzfs.EZFS_DIFFDATA
    POOLREADONLY = libzfs.EZFS_POOLREADONLY
    UNKNOWN = libzfs.EZFS_UNKNOWN
    IF HAVE_ZFS_ENCRYPTION:
        CRYPTO_FAILED = libzfs.EZFS_CRYPTOFAILED


class LpcError(enum.IntEnum):
    IF HAVE_ZPOOL_SEARCH_IMPORT_LIBZUTIL and HAVE_ZPOOL_SEARCH_IMPORT_PARAMS == 2:
        SUCCESS = libzfs.LPC_SUCCESS
        BADCACHE = libzfs.LPC_BADCACHE
        BADPATH = libzfs.LPC_BADPATH
        NOMEM = libzfs.LPC_NOMEM
        EACCESS = libzfs.LPC_EACCESS
        UNKNOWN = libzfs.LPC_UNKNOWN


class PropertySource(enum.IntEnum):
    NONE = zfs.ZPROP_SRC_NONE
    DEFAULT = zfs.ZPROP_SRC_DEFAULT
    TEMPORARY = zfs.ZPROP_SRC_TEMPORARY
    LOCAL = zfs.ZPROP_SRC_LOCAL
    INHERITED = zfs.ZPROP_SRC_INHERITED
    RECEIVED = zfs.ZPROP_SRC_RECEIVED


class VDevState(enum.IntEnum):
    UNKNOWN = zfs.VDEV_STATE_UNKNOWN
    CLOSED = zfs.VDEV_STATE_CLOSED
    OFFLINE = zfs.VDEV_STATE_OFFLINE
    REMOVED = zfs.VDEV_STATE_REMOVED
    CANT_OPEN = zfs.VDEV_STATE_CANT_OPEN
    FAULTED = zfs.VDEV_STATE_FAULTED
    DEGRADED = zfs.VDEV_STATE_DEGRADED
    HEALTHY = zfs.VDEV_STATE_HEALTHY


class VDevAuxState(enum.IntEnum):
    NONE = zfs.VDEV_AUX_NONE
    OPEN_FAILED = zfs.VDEV_AUX_OPEN_FAILED
    CORRUPT_DATA = zfs.VDEV_AUX_CORRUPT_DATA
    NO_REPLICAS = zfs.VDEV_AUX_NO_REPLICAS
    BAD_GUID_SUM = zfs.VDEV_AUX_BAD_GUID_SUM
    TOO_SMALL = zfs.VDEV_AUX_TOO_SMALL
    BAD_LABEL = zfs.VDEV_AUX_BAD_LABEL
    VERSION_NEWER = zfs.VDEV_AUX_VERSION_NEWER
    VERSION_OLDER = zfs.VDEV_AUX_VERSION_OLDER
    UNSUP_FEAT = zfs.VDEV_AUX_UNSUP_FEAT
    SPARED = zfs.VDEV_AUX_SPARED
    ERR_EXCEEDED = zfs.VDEV_AUX_ERR_EXCEEDED
    IO_FAILURE = zfs.VDEV_AUX_IO_FAILURE
    BAD_LOG = zfs.VDEV_AUX_BAD_LOG
    EXTERNAL = zfs.VDEV_AUX_EXTERNAL
    SPLIT_POOL = zfs.VDEV_AUX_SPLIT_POOL
    IF HAVE_VDEV_AUX_ASHIFT_TOO_BIG:
        ASHIFT_TOO_BIG = zfs.VDEV_AUX_ASHIFT_TOO_BIG


class PoolState(enum.IntEnum):
    ACTIVE = zfs.POOL_STATE_ACTIVE
    EXPORTED = zfs.POOL_STATE_EXPORTED
    DESTROYED = zfs.POOL_STATE_DESTROYED
    SPARE = zfs.POOL_STATE_SPARE
    L2CACHE = zfs.POOL_STATE_L2CACHE
    UNINITIALIZED = zfs.POOL_STATE_UNINITIALIZED
    UNAVAIL = zfs.POOL_STATE_UNAVAIL
    POTENTIALLY_ACTIVE = zfs.POOL_STATE_POTENTIALLY_ACTIVE


class ScanFunction(enum.IntEnum):
    NONE = zfs.POOL_SCAN_NONE
    SCRUB = zfs.POOL_SCAN_SCRUB
    RESILVER = zfs.POOL_SCAN_RESILVER


class PoolStatus(enum.IntEnum):
    CORRUPT_CACHE = libzfs.ZPOOL_STATUS_CORRUPT_CACHE
    MISSING_DEV_R = libzfs.ZPOOL_STATUS_MISSING_DEV_R
    MISSING_DEV_NR = libzfs.ZPOOL_STATUS_MISSING_DEV_NR
    CORRUPT_LABEL_R = libzfs.ZPOOL_STATUS_CORRUPT_LABEL_R
    CORRUPT_LABEL_NR = libzfs.ZPOOL_STATUS_CORRUPT_LABEL_NR
    BAD_GUID_SUM = libzfs.ZPOOL_STATUS_BAD_GUID_SUM
    CORRUPT_POOL = libzfs.ZPOOL_STATUS_CORRUPT_POOL
    CORRUPT_DATA = libzfs.ZPOOL_STATUS_CORRUPT_DATA
    FAILING_DEV = libzfs.ZPOOL_STATUS_FAILING_DEV
    VERSION_NEWER = libzfs.ZPOOL_STATUS_VERSION_NEWER
    HOSTID_MISMATCH = libzfs.ZPOOL_STATUS_HOSTID_MISMATCH
    HOSTID_ACTIVE = libzfs.ZPOOL_STATUS_HOSTID_ACTIVE
    HOSTID_REQUIRED = libzfs.ZPOOL_STATUS_HOSTID_REQUIRED
    IO_FAILURE_WAIT = libzfs.ZPOOL_STATUS_IO_FAILURE_WAIT
    IO_FAILURE_CONTINUE = libzfs.ZPOOL_STATUS_IO_FAILURE_CONTINUE
    IO_FAILURE_MMP = libzfs.ZPOOL_STATUS_IO_FAILURE_MMP
    BAD_LOG = libzfs.ZPOOL_STATUS_BAD_LOG
    IF HAVE_ZPOOL_STATUS_ERRATA:
        ERRATA = libzfs.ZPOOL_STATUS_ERRATA
    UNSUP_FEAT_READ = libzfs.ZPOOL_STATUS_UNSUP_FEAT_READ
    UNSUP_FEAT_WRITE = libzfs.ZPOOL_STATUS_UNSUP_FEAT_WRITE
    FAULTED_DEV_R = libzfs.ZPOOL_STATUS_FAULTED_DEV_R
    FAULTED_DEV_NR = libzfs.ZPOOL_STATUS_FAULTED_DEV_NR
    VERSION_OLDER = libzfs.ZPOOL_STATUS_VERSION_OLDER
    FEAT_DISABLED = libzfs.ZPOOL_STATUS_FEAT_DISABLED
    RESILVERING = libzfs.ZPOOL_STATUS_RESILVERING
    OFFLINE_DEV = libzfs.ZPOOL_STATUS_OFFLINE_DEV
    REMOVED_DEV = libzfs.ZPOOL_STATUS_REMOVED_DEV
    IF HAVE_ZPOOL_STATUS_REBUILDING:
        REBUILDING = libzfs.ZPOOL_STATUS_REBUILDING
    IF HAVE_ZPOOL_STATUS_REBUILD_SCRUB:
        REBUILD_SCRUB = libzfs.ZPOOL_STATUS_REBUILD_SCRUB
    NON_NATIVE_ASHIFT = libzfs.ZPOOL_STATUS_NON_NATIVE_ASHIFT
    IF HAVE_ZPOOL_STATUS_COMPATIBILITY_ERR:
        COMPATIBILITY_ERR = libzfs.ZPOOL_STATUS_COMPATIBILITY_ERR
    IF HAVE_ZPOOL_STATUS_INCOMPATIBLE_FEAT:
        INCOMPATIBLE_FEAT = libzfs.ZPOOL_STATUS_INCOMPATIBLE_FEAT
    OK = libzfs.ZPOOL_STATUS_OK


class ScanState(enum.IntEnum):
    NONE = zfs.DSS_NONE
    SCANNING = zfs.DSS_SCANNING
    FINISHED = zfs.DSS_FINISHED
    CANCELED = zfs.DSS_CANCELED


class ZIOType(enum.IntEnum):
    NONE = zfs.ZIO_TYPE_NULL
    READ = zfs.ZIO_TYPE_READ
    WRITE = zfs.ZIO_TYPE_WRITE
    FREE = zfs.ZIO_TYPE_FREE
    CLAIM = zfs.ZIO_TYPE_CLAIM
    IOCTL = zfs.ZIO_TYPE_IOCTL


IF HAVE_LZC_WAIT:
    class ZpoolWaitActivity(enum.IntEnum):
        DISCARD = zfs.ZPOOL_WAIT_CKPT_DISCARD
        FREE = zfs.ZPOOL_WAIT_FREE
        INITIALIZE = zfs.ZPOOL_WAIT_INITIALIZE
        REPLACE = zfs.ZPOOL_WAIT_REPLACE
        REMOVE = zfs.ZPOOL_WAIT_REMOVE
        RESILVER = zfs.ZPOOL_WAIT_RESILVER
        SCRUB = zfs.ZPOOL_WAIT_SCRUB
        TRIM = zfs.ZPOOL_WAIT_TRIM
        NUM_ACTIVITIES = zfs.ZPOOL_WAIT_NUM_ACTIVITIES


class FeatureState(enum.Enum):
    DISABLED = 0
    ENABLED = 1
    ACTIVE = 2


class SendFlag(enum.Enum):
    IF HAVE_SENDFLAGS_T_VERBOSITY:
        VERBOSITY = 0
    ELSE:
        VERBOSE = 0
    REPLICATE = 1
    DOALL = 2
    FROMORIGIN = 3
    PROPS = 4
    DRYRUN = 5
    PARSABLE = 6
    PROGRESS = 7
    LARGEBLOCK = 8
    EMBED_DATA = 9
    IF HAVE_SENDFLAGS_T_COMPRESS:
        COMPRESS = 10
    IF HAVE_SENDFLAGS_T_RAW:
        RAW = 11
    IF HAVE_SENDFLAGS_T_BACKUP:
        BACKUP = 12
    IF HAVE_SENDFLAGS_T_HOLDS:
        HOLDS = 13
    IF HAVE_SENDFLAGS_T_SAVED:
        SAVED = 14
    IF HAVE_SENDFLAGS_T_PROGRESSASTITLE:
        PROGRESSASTITLE = 15
    IF HAVE_SENDFLAGS_T_DEDUP:
        DEDUP = 16


class DiffRecordType(enum.Enum):
    ADD = '+'
    REMOVE = '-'
    MODIFY = 'M'
    RENAME = 'R'


class DiffFileType(enum.Enum):
    BLOCK = 'B'
    CHAR = 'C'
    FILE = 'F'
    DIRECTORY = '/'
    SYMLINK = '@'
    SOCKET = '='


IF HAVE_ZFS_MAX_DATASET_NAME_LEN:
    cdef enum:
        MAX_DATASET_NAME_LEN = zfs.ZFS_MAX_DATASET_NAME_LEN
ELSE:
    cdef enum:
        MAX_DATASET_NAME_LEN = libzfs.ZFS_MAXNAMELEN


cdef struct iter_state:
    uintptr_t *array
    size_t length
    size_t alloc


cdef struct prop_iter_state:
    zfs.zfs_type_t type
    void *props


def validate_dataset_name(name):
    return validate_zfs_resource_name(name, zfs.ZFS_TYPE_FILESYSTEM | zfs.ZFS_TYPE_VOLUME)


def validate_snapshot_name(name):
    return validate_zfs_resource_name(name, zfs.ZFS_TYPE_SNAPSHOT)


def validate_pool_name(name):
    return validate_zfs_resource_name(name, zfs.ZFS_TYPE_POOL)


cdef validate_zfs_resource_name(str name, int r_type):
    cdef const char *c_name = name
    cdef int ret
    with nogil:
        ret = libzfs.zfs_name_valid(c_name, <zfs.zfs_type_t>r_type)
    return bool(ret)


def validate_draid_configuration(children, draid_parity, draid_spare_disks, draid_data_disks):
    draid_data_disks = zfs.VDEV_DRAID_MAX_CHILDREN if draid_data_disks is None else draid_data_disks
    # Validation added from
    # https://github.com/truenas/zfs/blob/2bb9ef45772886bffcc93b59cfd62594f478cc83/cmd/zpool/zpool_vdev.c#L1369

    if draid_data_disks == zfs.VDEV_DRAID_MAX_CHILDREN:
        if children > draid_spare_disks + draid_parity:
            draid_data_disks = min(children - draid_spare_disks - draid_parity, 8)
        else:
            raise ZFSException(
                py_errno.EINVAL,
                f'Request number of distributed spares {draid_spare_disks} and parity level {draid_parity}\n'
                'leaves no disks available for data'
            )

    if draid_data_disks == 0 or (draid_data_disks + draid_parity) > (children - draid_spare_disks):
        raise ZFSException(
            py_errno.EINVAL,
            f'Requested number of dRAID data disks per group {draid_data_disks} is too high, at'
            f' most {children - draid_spare_disks - draid_parity} disks are available for data'
        )

    if draid_parity == 0 or draid_parity > zfs.VDEV_DRAID_MAXPARITY:
        raise ZFSException(
            py_errno.EINVAL,
            f'Invalid dRAID parity level {draid_parity}; must be between 1 and {zfs.VDEV_DRAID_MAXPARITY}'
        )

    if draid_spare_disks > 100 or draid_spare_disks > (children - (draid_data_disks + draid_parity)):
        raise ZFSException(
            py_errno.EINVAL,
            f'Invalid number of dRAID spares {draid_spare_disks}. Additional disks would be required'
        )

    if children < (draid_data_disks + draid_parity + draid_spare_disks):
        raise ZFSException(
            py_errno.EINVAL,
            f'{children} disks were provided, but at least '
            f'{draid_data_disks + draid_parity + draid_spare_disks} disks are required for this config'
        )

    if children > zfs.VDEV_DRAID_MAX_CHILDREN:
        raise ZFSException(
            py_errno.EINVAL,
            f'{children} disks were provided, but dRAID only supports up to {zfs.VDEV_DRAID_MAX_CHILDREN} disks'
        )
    return draid_data_disks

def update_draid_config(nvlist, children, draid_parity=1, draid_spare_disks=0, draid_data_disks=None):
    draid_data_disks = validate_draid_configuration(children, draid_parity, draid_spare_disks, draid_data_disks)

    ngroups = 1
    while (ngroups * (draid_data_disks + draid_parity)) % (children - draid_spare_disks) != 0:
        ngroups += 1

    # Store the basic dRAID configuration.
    nvlist[zfs.ZPOOL_CONFIG_NPARITY] = draid_parity
    nvlist[zfs.ZPOOL_CONFIG_DRAID_NDATA] = draid_data_disks
    nvlist[zfs.ZPOOL_CONFIG_DRAID_NSPARES] = draid_spare_disks
    nvlist[zfs.ZPOOL_CONFIG_DRAID_NGROUPS] = ngroups


class DiffRecord(object):
    def __init__(self, raw):
        timestamp, cmd, typ, rest = raw.split(maxsplit=3)
        paths = rest.split('->', maxsplit=2)
        self.raw = raw
        self.timestamp = datetime.utcfromtimestamp(float(timestamp))
        self.cmd = DiffRecordType(cmd)
        self.type = DiffFileType(typ)
        self.path = paths[0].strip()

        if self.cmd == DiffRecordType.RENAME:
            self.oldpath = paths[1].strip()

    def __str__(self):
        return self.raw

    def __repr__(self):
        return str(self)

    def asdict(self):
        return {
            'timestamp': self.timestamp,
            'cmd': self.cmd.name,
            'type': self.type.name,
            'path': self.path,
            'oldpath': getattr(self, 'oldpath', None)
        }



IF HAVE_LZC_SEND_FLAG_EMBED_DATA:
    class SendFlags(enum.IntEnum):
        EMBED_DATA = libzfs.LZC_SEND_FLAG_EMBED_DATA


class ZFSInvalidCachefileException(OSError):
    pass


class ZFSException(RuntimeError):
    def __init__(self, code, message):
        super(ZFSException, self).__init__(message)
        self.code = code

    def __reduce__(self):
        return (self.__class__, (self.code, *self.args))


class ZFSVdevStatsException(ZFSException):
    def __init__(self, code):
        super(ZFSVdevStatsException, self).__init__(code, 'Failed to fetch ZFS Vdev Stats')


class ZFSPoolScanStatsException(ZFSException):
    def __init__(self, code):
        super(ZFSPoolScanStatsException, self).__init__(code, 'Failed to retrieve ZFS pool scan stats')


cdef class ZFS(object):
    cdef libzfs.libzfs_handle_t* handle
    cdef boolean_t mnttab_cache_enable
    cdef int history
    cdef char *history_prefix
    proptypes = {}

    def __cinit__(self, history=True, history_prefix='py-libzfs:', mnttab_cache=True):
        cdef zfs.zfs_type_t c_type
        cdef prop_iter_state iter
        self.mnttab_cache_enable=mnttab_cache

        with nogil:
            self.handle = libzfs.libzfs_init()

        if isinstance(history, bool):
            self.history = history
        else:
            raise ZFSException(Error.BADTYPE, 'history is a boolean parameter')

        if self.history:
            if isinstance(history_prefix, str):
                self.history_prefix = history_prefix
            else:
                raise ZFSException(Error.BADTYPE, 'history_prefix is a string parameter')

        for t in DatasetType.__members__.values():
            proptypes = []
            c_type = <zfs.zfs_type_t>t
            iter.type = c_type
            iter.props = <void *>proptypes
            with nogil:
                libzfs.zprop_iter(self.__iterate_props, <void*>&iter, True, True, c_type)

            props = self.proptypes.setdefault(t, [])
            if set(proptypes) != set(props):
                self.proptypes[t] = proptypes

    def __enter__(self):
        GLOBAL_CONTEXT_LOCK.acquire()
        return self

    def __exit__(self, exc_type, value, traceback):
        self.__libzfs_fini()
        GLOBAL_CONTEXT_LOCK.release()
        if exc_type is not None:
            raise

    def __libzfs_fini(self):
        if self.handle:
            with nogil:
                libzfs.libzfs_fini(self.handle)

            self.handle = NULL

    def __dealloc__(self):
        ZFS.__libzfs_fini(self)

    def asdict(self):
        return [p.asdict() for p in self.pools]

    IF HAVE_ZPOOL_EVENTS_NEXT:
        def zpool_events(self, blocking=True, skip_existing_events=False):
            if skip_existing_events:
                existing_events = len(list(self.zpool_events(blocking=False, skip_existing_events=False)))

            event_count = -1
            zevent_fd = os.open(zfs.ZFS_DEV, os.O_RDWR)
            try:
                event = True
                while event:
                    event = self.zpool_events_single(zevent_fd, blocking)
                    event_count += 1
                    if skip_existing_events and event_count < existing_events:
                        continue
                    if event:
                        yield event
            finally:
                os.close(zevent_fd)

        def zpool_events_single(self, zfs_dev_fd, blocking=True):
            cdef nvpair.nvlist_t *nvl
            cdef NVList py_nvl
            cdef int zevent_fd, ret, dropped
            cdef int block_flag = 0 if blocking else 1
            zevent_fd = zfs_dev_fd
            with nogil:
                ret = libzfs.zpool_events_next(self.handle, &nvl, &dropped, block_flag, zevent_fd)
                if ret != 0 or (nvl == NULL and block_flag == 0):
                    raise self.get_error()
            if nvl == NULL:
                # This is okay when non blocking behavior is desired
                return None
            else:
                retval = {'dropped': dropped, **dict(NVList(<uintptr_t>nvl))}
                with nogil:
                    nvpair.nvlist_free(nvl)
                return retval

    @staticmethod
    cdef int __iterate_props(int proptype, void *arg) nogil:
        cdef prop_iter_state *iter
        cdef boolean_t ret = False

        iter = <prop_iter_state *>arg

        IF HAVE_ZFS_PROP_VALID_FOR_TYPE == 3:
            ret = zfs.zfs_prop_valid_for_type(proptype, iter.type, ret)
        ELSE:
            ret = zfs.zfs_prop_valid_for_type(proptype, iter.type)

        if not ret:
            return zfs.ZPROP_CONT

        with gil:
            proptypes = <object>iter.props
            proptypes.append(proptype)
            return zfs.ZPROP_CONT

    @staticmethod
    cdef int __iterate_pools(libzfs.zpool_handle_t *handle, void *arg) nogil:
        cdef iter_state *iter
        cdef iter_state new

        iter = <iter_state *>arg
        if iter.length == iter.alloc:
            new.alloc = iter.alloc + 32
            new.array = <uintptr_t *>realloc(iter.array, new.alloc * sizeof(uintptr_t))
            if not new.array:
                free(iter.array)
                raise MemoryError()

            iter.alloc = new.alloc
            iter.array = new.array

        iter.array[iter.length] = <uintptr_t>handle
        iter.length += 1

    @staticmethod
    cdef int __iterate_filesystems(libzfs.zfs_handle_t *zhp, int flags, libzfs.zfs_iter_f func, void *data) nogil:
        IF HAVE_ZFS_ITER_FILESYSTEMS == 4:
            return libzfs.zfs_iter_filesystems(zhp, flags, func, data)
        ELSE:
            # flags are ignored on older zfs
            return libzfs.zfs_iter_filesystems(zhp, func, data)

    @staticmethod
    cdef int __iterate_snapspec(libzfs.zfs_handle_t *zhp, int flags, const char *spec_orig, libzfs.zfs_iter_f func, void *arg) nogil:
        IF HAVE_ZFS_ITER_SNAPSPEC == 5:
            return libzfs.zfs_iter_snapspec(zhp, flags, spec_orig, func, arg)
        ELSE:
            # flags are ignored on older zfs
            return libzfs.zfs_iter_snapspec(zhp, spec_orig, func, arg)

    @staticmethod
    cdef int __iterate_dependents(libzfs.zfs_handle_t *zhp, int flags, boolean_t allowrecursion, libzfs.zfs_iter_f func, void *data) nogil:
        IF HAVE_ZFS_ITER_DEPENDENTS == 5:
            return libzfs.zfs_iter_dependents(zhp, flags, allowrecursion, func, data)
        ELSE:
            # flags are ignored on older zfs
            return libzfs.zfs_iter_dependents(zhp, allowrecursion, func, data)

    @staticmethod
    cdef int __iterate_bookmarks(libzfs.zfs_handle_t *zhp, int flags, libzfs.zfs_iter_f func, void *data) nogil:
        IF HAVE_ZFS_ITER_BOOKMARKS == 4:
            return libzfs.zfs_iter_bookmarks(zhp, flags, func, data)
        ELSE:
            # flags are ignored on older zfs
            return libzfs.zfs_iter_bookmarks(zhp, func, data)

    cdef object get_error(self):
        description = (<bytes>libzfs.libzfs_error_description(self.handle)).decode('utf-8', 'backslashreplace')
        error_action = (<bytes>libzfs.libzfs_error_action(self.handle)).decode('utf-8', 'backslashreplace')
        if error_action:
            description = f'{error_action}: {description}'
        return ZFSException(Error(libzfs.libzfs_errno(self.handle)), description)

    cdef ZFSVdev make_vdev_tree(self, topology, props=None):
        cdef ZFSVdev root
        root = ZFSVdev(self, zfs.VDEV_TYPE_ROOT)
        root.children = topology.get('data', [])
        ashift_value = (props or {}).get(zfs.ZPOOL_CONFIG_ASHIFT)
        if ashift_value and not isinstance(ashift_value, int):
            ashift_value = None

        def add_properties_to_vdev(vdev):
            cdef char vpath[zfs.MAXPATHLEN + 1]
            cdef boolean_t whole_disk
            IF IS_OPENZFS:
                # Each leaf vdev is supposed to have the wholedisk
                # and ashift properties in its nvlist
                if vdev.type != 'disk':
                    for child in vdev.children:
                        add_properties_to_vdev(child)
                else:
                    strncpy(vpath, vdev.path, zfs.MAXPATHLEN)
                    with nogil:
                        whole_disk = zfs_dev_is_whole_disk(vpath)
                    (<ZFSVdev>vdev).set_whole_disk(whole_disk)
                    if ashift_value:
                        (<ZFSVdev>vdev).set_ashift(ashift_value)
            return vdev

        root = <ZFSVdev>add_properties_to_vdev(root)

        if 'cache' in topology:
            root.nvlist[zfs.ZPOOL_CONFIG_L2CACHE] = [
                (<ZFSVdev>add_properties_to_vdev(<ZFSVdev>i)).nvlist for i in topology['cache']
            ]

        if 'spare' in topology:
            root.nvlist[zfs.ZPOOL_CONFIG_SPARES] = [
                (<ZFSVdev>add_properties_to_vdev(<ZFSVdev>i)).nvlist for i in topology['spare']
            ]

        if 'log' in topology:
            for i in topology['log']:
                vdev = <ZFSVdev>i
                vdev.nvlist[zfs.ZPOOL_CONFIG_IS_LOG] = 1L
                IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
                    vdev.nvlist[zfs.ZPOOL_CONFIG_ALLOCATION_BIAS] = zfs.VDEV_ALLOC_BIAS_LOG
                root.add_child_vdev((<ZFSVdev>add_properties_to_vdev(vdev)))

        if 'draid' in topology:
            children = len(topology['draid'])
            for draid in topology['draid']:
                vdev = <ZFSVdev>draid['disk']
                update_draid_config(vdev.nvlist, **draid['parameters'])
                root.add_child_vdev((<ZFSVdev>add_properties_to_vdev(vdev)))


        IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
            if 'special' in topology:
                for i in topology['special']:
                    vdev = <ZFSVdev>i
                    vdev.nvlist[zfs.ZPOOL_CONFIG_IS_LOG] = False
                    vdev.nvlist[zfs.ZPOOL_CONFIG_ALLOCATION_BIAS] = zfs.VDEV_ALLOC_BIAS_SPECIAL
                    root.add_child_vdev((<ZFSVdev>add_properties_to_vdev(vdev)))

            if 'dedup' in topology:
                for i in topology['dedup']:
                    vdev = <ZFSVdev>i
                    vdev.nvlist[zfs.ZPOOL_CONFIG_IS_LOG] = False
                    vdev.nvlist[zfs.ZPOOL_CONFIG_ALLOCATION_BIAS] = zfs.VDEV_ALLOC_BIAS_DEDUP
                    root.add_child_vdev((<ZFSVdev>add_properties_to_vdev(vdev)))
        return root

    @staticmethod
    cdef int __dataset_handles(libzfs.zfs_handle_t* handle, void *arg) nogil:
        cdef int prop_id
        cdef char csrcstr[MAX_DATASET_NAME_LEN + 1]
        cdef char crawvalue[libzfs.ZFS_MAXPROPLEN + 1]
        cdef char cvalue[libzfs.ZFS_MAXPROPLEN + 1]
        cdef zfs.zprop_source_t csource
        cdef const char *name
        cdef zfs.zfs_type_t typ
        cdef boolean_t retrieve_children

        cdef nvpair.nvlist_t *nvlist

        name = libzfs.zfs_get_name(handle)
        typ = libzfs.zfs_get_type(handle)
        nvlist = libzfs.zfs_get_user_props(handle)

        with gil:
            dataset_type = DatasetType(typ)
            data_list = <object> arg
            configuration_data = data_list[0]
            retrieve_children = configuration_data['retrieve_children']
            data = data_list[1]
            children = []
            child_data = [configuration_data, {}]
            properties = {}

            for key, value in NVList(<uintptr_t>nvlist).items() if configuration_data['user_props'] else []:
                src = 'NONE'
                if value.get('source'):
                    src = value.pop('source')
                    if src == name:
                        src = PropertySource.LOCAL.name
                    elif src == '$recvd':
                        src = PropertySource.RECEIVED.name
                    else:
                        src = PropertySource.INHERITED.name

                properties[key] = {
                    'value': value.get('value'),
                    'rawvalue': value.get('value'),
                    'source': src,
                    'parsed': value.get('value')
                }

            for prop_name, prop_id in configuration_data['props'].get(dataset_type, {}).items():
                csource = zfs.ZPROP_SRC_NONE
                with nogil:
                    strncpy(cvalue, '', libzfs.ZFS_MAXPROPLEN + 1)
                    strncpy(crawvalue, '', libzfs.ZFS_MAXPROPLEN + 1)
                    strncpy(csrcstr, '', MAX_DATASET_NAME_LEN + 1)

                    if libzfs.zfs_prop_get(
                        handle, prop_id, cvalue, libzfs.ZFS_MAXPROPLEN,
                        &csource, csrcstr, MAX_DATASET_NAME_LEN, False
                    ) != 0:
                        csource = zfs.ZPROP_SRC_NONE

                    libzfs.zfs_prop_get(
                        handle, prop_id, crawvalue, libzfs.ZFS_MAXPROPLEN,
                        NULL, NULL, 0, True
                    )

                properties[prop_name] = {
                    'parsed': parse_zfs_prop(prop_name, crawvalue),
                    'rawvalue': crawvalue,
                    'value': cvalue,
                    'source': PropertySource(<int>csource).name,
                    'source_info': str(csrcstr) if csource == zfs.ZPROP_SRC_INHERITED else None
                }

        if retrieve_children:
            ZFS.__iterate_filesystems(handle, 0, ZFS.__dataset_handles, <void*>child_data)

        with gil:
            data[name] = {}
            child_data = child_data[1]
            encryption_dict = {}

            IF HAVE_ZFS_ENCRYPTION:
                if 'encryption' in properties:
                    encryption_dict['encrypted'] = properties['encryption']['value'] != 'off'
                if 'encryptionroot' in properties:
                    encryption_dict['encryption_root'] = properties['encryptionroot']['value'] or None
                if 'keystatus' in properties:
                    encryption_dict['key_loaded'] = properties['keystatus']['value'] == 'available'

            data[name].update({
                'properties': properties,
                'id': name,
                'type': dataset_type.name,
                'name': name,
                'pool': configuration_data['pool'],
                **encryption_dict,
            })
            if retrieve_children:
                data[name]['children'] = list(child_data.values())

            if configuration_data['snapshots'] or configuration_data['snapshots_recursive']:
                snap_props = ['name']
                if configuration_data['snapshot_props'] is None:
                    # We will retrieve all properties of snapshot in this case
                    snap_props = None
                else:
                    snap_props.extend(configuration_data['snapshot_props'])
                snap_list = ZFS._snapshots_snaplist_arg(
                    snap_props, False, False, configuration_data['snapshots_recursive'], False, 0, 0
                )
                snap_list[0]['pool'] = configuration_data['pool']
                ZFS.__datasets_snapshots(handle, <void*>snap_list)
                data[name]['snapshots'] = snap_list[1:]

        libzfs.zfs_close(handle)

    def datasets_serialized(
        self, props=None, user_props=True, datasets=None, snapshots=False, retrieve_children=True,
        snapshots_recursive=False, snapshot_props=None,
    ):
        cdef libzfs.zfs_handle_t* handle
        cdef const char *c_name
        cdef int prop_id

        prop_mapping = {}
        datasets = datasets or [p.name for p in self.pools]

        # If props is None, we include all properties, if it's an empty list, no property is retrieved
        for dataset_type in [DatasetType.FILESYSTEM, DatasetType.VOLUME] if props is None or len(props) else []:
            prop_mapping[dataset_type] = {}
            for prop_id in ZFS.proptypes[dataset_type]:
                with nogil:
                    prop_name = libzfs.zfs_prop_to_name(prop_id)

                if props is None or prop_name in props:
                    prop_mapping[dataset_type][prop_name] = prop_id

        for ds_name in datasets:
            c_name = handle = NULL
            c_name = ds_name

            dataset = [
                {
                    'pool': ds_name.split('/', 1)[0],
                    'props': prop_mapping,
                    'user_props': user_props,
                    'snapshots': snapshots,
                    'snapshots_recursive': bool(snapshots_recursive),
                    'retrieve_children': retrieve_children,
                    'snapshot_props': snapshot_props,
                },
                {}
            ]

            with nogil:
                handle = libzfs.zfs_open(self.handle, c_name, zfs.ZFS_TYPE_FILESYSTEM | zfs.ZFS_TYPE_VOLUME)
                if handle == NULL:
                    # It just means that the dataset in question does not exist
                    # and it's okay to continue checking the next one
                    continue
                else:
                    ZFS.__dataset_handles(handle, <void*>dataset)

            if len(dataset) > 1:
                yield dataset[1][ds_name]

    @staticmethod
    cdef int __retrieve_mountable_datasets_handles(libzfs.zfs_handle_t* handle, void *arg) nogil:
        cdef libzfs.get_all_cb_t *cb = <libzfs.get_all_cb_t*>arg
        if libzfs.zfs_get_type(handle) != zfs.ZFS_TYPE_FILESYSTEM:
            libzfs.zfs_close(handle)
            return 0

        if libzfs.zfs_prop_get_int(handle, zfs.ZFS_PROP_CANMOUNT) == zfs.ZFS_CANMOUNT_NOAUTO:
            libzfs.zfs_close(handle)
            return 0

        IF HAVE_ZFS_ENCRYPTION:
            if libzfs.zfs_prop_get_int(handle, zfs.ZFS_PROP_KEYSTATUS) == zfs.ZFS_KEYSTATUS_UNAVAILABLE:
                libzfs.zfs_close(handle)
                return 0

        IF HAVE_ZFS_SEND_RESUME_TOKEN_TO_NVLIST:
            if (
                libzfs.zfs_prop_get_int(handle, zfs.ZFS_PROP_INCONSISTENT) and libzfs.zfs_prop_get(
                    handle, zfs.ZFS_PROP_RECEIVE_RESUME_TOKEN, NULL, 0, NULL, NULL, 0, True
                ) == 0
            ):
                libzfs.zfs_close(handle)
                return 0

        libzfs.libzfs_add_handle(cb, handle)
        ZFS.__iterate_filesystems(handle, 0, ZFS.__retrieve_mountable_datasets_handles, cb)

    @staticmethod
    cdef int mount_dataset(libzfs.zfs_handle_t *zhp, void *arg) nogil:
        cdef int ret
        cdef nvpair.nvlist_t* mount_data = <nvpair.nvlist_t*>arg
        IF HAVE_ZFS_ENCRYPTION:
            if libzfs.zfs_prop_get_int(zhp, zfs.ZFS_PROP_KEYSTATUS) == zfs.ZFS_KEYSTATUS_UNAVAILABLE:
                return 0

        ret = libzfs.zfs_mount(zhp, NULL, 0)
        if ret != 0:
            nvpair.nvlist_add_boolean(mount_data, libzfs.zfs_get_name(zhp))
        return ret

    @staticmethod
    cdef int share_one_dataset(libzfs.zfs_handle_t *zhp, void *arg) nogil:
        cdef int ret
        IF HAVE_ZFS_SHARE == 1:
            ret = libzfs.zfs_share(zhp)
        ELSE:
            ret = libzfs.zfs_share(zhp, NULL)
        if ret != 0:
            with gil:
                mount_results = <object> arg
                mount_results['failed_share'].append(libzfs.zfs_get_name(zhp))
        return ret

    def run(self):
        self.zpool_enable_datasets('pool', False)


    IF HAVE_ZFS_FOREACH_MOUNTPOINT:
        cdef int zpool_enable_datasets(self, str name, int enable_shares) nogil:
            cdef libzfs.zfs_handle_t* handle
            cdef const char *c_name
            cdef libzfs.get_all_cb_t cb

            with gil:
                mount_data = NVList(otherdict={})
                mount_results = {'failed_mount': [], 'failed_share': []}
                c_name = name
                cb = libzfs.get_all_cb_t(cb_alloc=0, cb_used=0, cb_handles=NULL)

            handle = libzfs.zfs_open(self.handle, c_name, zfs.ZFS_TYPE_FILESYSTEM)
            if handle == NULL:
                free(cb.cb_handles)
                raise self.get_error()

            # Gathering all handles first
            ZFS.__retrieve_mountable_datasets_handles(handle, &cb)

            # Mount all datasets
            libzfs.zfs_foreach_mountpoint(
                self.handle, cb.cb_handles, cb.cb_used, ZFS.mount_dataset, <void*>mount_data.handle, True
            )

            # Share all datasets
            if enable_shares:
                libzfs.zfs_foreach_mountpoint(
                    self.handle, cb.cb_handles, cb.cb_used, ZFS.share_one_dataset, <void*>mount_results, False
                )
                IF HAVE_ZFS_SHARE == 2:
                    with gil:
                        if not mount_results['failed_share']:
                            with nogil:
                                libzfs.zfs_commit_shares(NULL)

            # Free all handles
            for i in range(cb.cb_used):
                libzfs.zfs_close(cb.cb_handles[i])
            free(cb.cb_handles)

            with gil:
                mount_results['failed_mount'] = mount_data.keys()
                if mount_results['failed_mount'] or mount_results['failed_share']:
                    error_str = ''
                    if mount_results['failed_mount']:
                        error_str += f'Failed to mount "{",".join(mount_results["failed_mount"])}" dataset(s)'
                    if mount_results['failed_share']:
                        error_str += (
                            '\n' if error_str else ''
                        ) + f'Failed to share "{",".join(mount_results["failed_share"])}" dataset(s)'
                    raise ZFSException(Error.MOUNTFAILED, error_str)

    @staticmethod
    cdef int __snapshot_details(libzfs.zfs_handle_t *handle, void *arg) nogil:
        cdef int prop_id, ret, simple_handle, holds, mounted
        cdef char csrcstr[MAX_DATASET_NAME_LEN + 1]
        cdef char crawvalue[libzfs.ZFS_MAXPROPLEN + 1]
        cdef char cvalue[libzfs.ZFS_MAXPROPLEN + 1]
        cdef zfs.zprop_source_t csource
        cdef const char *name
        cdef char *mntpt
        cdef nvpair.nvlist_t *ptr
        cdef nvpair.nvlist_t *nvlist
        cdef uint64_t min_txg
        cdef uint64_t max_txg
        cdef uint64_t create_txg

        with gil:
            snap_list = <object> arg
            configuration_data = snap_list[0]
            pool = configuration_data['pool']
            props = configuration_data['props']
            holds = configuration_data['holds']
            mounted = configuration_data['mounted']
            min_txg = configuration_data['min_txg']
            max_txg = configuration_data['max_txg']
            properties = {}
            simple_handle = set(props).issubset({'name', 'createtxg'})
            snap_data = {}

        libzfs.zfs_iter_snapshots(handle, simple_handle, ZFS.__snapshot_details, <void*>snap_list, min_txg, max_txg)

        if libzfs.zfs_get_type(handle) != zfs.ZFS_TYPE_SNAPSHOT:
            return 0

        nvlist = libzfs.zfs_get_user_props(handle)
        name = libzfs.zfs_get_name(handle)
        create_txg = libzfs.zfs_prop_get_int(handle, zfs.ZFS_PROP_CREATETXG)

        with gil:

            # Gathering user props
            nvl = NVList(<uintptr_t>nvlist)

            for key, value in nvl.items():
                src = 'NONE'
                if value.get('source'):
                    src = value.pop('source')
                    if src == name:
                        src = PropertySource.LOCAL.name
                    elif src == '$recvd':
                        src = PropertySource.RECEIVED.name
                    else:
                        src = PropertySource.INHERITED.name

                properties[key] = {
                    'value': value.get('value'),
                    'rawvalue': value.get('value'),
                    'source': src,
                    'parsed': value.get('value')
                }

            for prop_name, prop_id in (props if not simple_handle else {}).items():
                csource = zfs.ZPROP_SRC_NONE
                with nogil:
                    strncpy(cvalue, '', libzfs.ZFS_MAXPROPLEN + 1)
                    strncpy(crawvalue, '', libzfs.ZFS_MAXPROPLEN + 1)
                    strncpy(csrcstr, '', MAX_DATASET_NAME_LEN + 1)

                    if libzfs.zfs_prop_get(
                        handle, prop_id, cvalue, libzfs.ZFS_MAXPROPLEN,
                        &csource, csrcstr, MAX_DATASET_NAME_LEN, False
                    ) != 0:
                        csource = zfs.ZPROP_SRC_NONE

                    libzfs.zfs_prop_get(
                        handle, prop_id, crawvalue, libzfs.ZFS_MAXPROPLEN,
                        NULL, NULL, 0, True
                    )

                properties[prop_name] = {
                    'parsed': parse_zfs_prop(prop_name, crawvalue),
                    'rawvalue': crawvalue,
                    'value': cvalue,
                    'source': PropertySource(<int>csource).name
                }

        if holds:
            ret = libzfs.zfs_get_holds(handle, &ptr)

            with gil:
                if ret != 0:
                    snap_data['holds'] = {}
                else:
                    snap_data['holds'] = dict(NVList(<uintptr_t> ptr))

            if ret == 0:
                nvpair.nvlist_free(ptr)

        if mounted:
            ret = libzfs.zfs_is_mounted(handle, &mntpt)

            with gil:
                if ret == 0:
                    snap_data['mountpoint'] = None
                else:
                    try:
                        snap_data['mountpoint'] = str(mntpt)
                    finally:
                        free(mntpt)

        with gil:
            if not simple_handle:
                snap_data['properties'] = properties

            snap_data.update({
                'pool': pool,
                'name': name,
                'type': DatasetType.SNAPSHOT.name,
                'snapshot_name': name.split('@')[-1],
                'dataset': name.split('@')[0],
                'id': name,
                'createtxg': str(create_txg)
            })

            snap_list.append(snap_data)

        libzfs.zfs_close(handle)

    @staticmethod
    cdef int __datasets_snapshots(libzfs.zfs_handle_t *handle, void *arg) nogil:
        cdef boolean_t close_handle, recursive, is_dataset

        is_dataset = libzfs.zfs_get_type(handle) != zfs.ZFS_TYPE_SNAPSHOT
        ZFS.__snapshot_details(handle, arg)
        with gil:
            snap_list = <object> arg
            close_handle = snap_list[0]['close_handle']
            recursive = snap_list[0]['recursive']

        if is_dataset:
            if recursive:
                ZFS.__iterate_filesystems(handle, 0, ZFS.__datasets_snapshots, arg)
            if close_handle:
                libzfs.zfs_close(handle)

    @staticmethod
    cdef object _snapshots_snaplist_arg(
        object props, object holds, object mounted, object recursive, object close_handle, int min_txg, int max_txg
    ):
        cdef int prop_id

        prop_mapping = {}
        props = props or []

        for prop_id in ZFS.proptypes[DatasetType.SNAPSHOT]:
            with nogil:
                prop_name = libzfs.zfs_prop_to_name(prop_id)

            if not props or prop_name in props:
                prop_mapping[prop_name] = prop_id

        return [{
            'props': prop_mapping,
            'holds': holds,
            'mounted': mounted,
            'recursive': recursive,
            'close_handle': close_handle,
            'min_txg': min_txg,
            'max_txg': max_txg,
        }]

    @staticmethod
    cdef object _snapshots_serialized_impl(
        libzfs.libzfs_handle_t *global_handle, object datasets, object props, object holds,
        object mounted, object recursive, int min_txg, int max_txg
    ):
        cdef libzfs.zfs_handle_t* handle
        cdef const char *c_name

        snap_list = ZFS._snapshots_snaplist_arg(props, holds, mounted, recursive, True, min_txg, max_txg)
        for dataset in datasets:
            c_name = handle = NULL
            c_name = dataset

            snap_list[0]['pool'] = dataset.split('/', 1)[0]

            with nogil:
                handle = libzfs.zfs_open(global_handle, c_name,
                                         zfs.ZFS_TYPE_FILESYSTEM | zfs.ZFS_TYPE_VOLUME | zfs.ZFS_TYPE_SNAPSHOT)
                if handle == NULL:
                    continue
                ZFS.__datasets_snapshots(handle, <void*>snap_list)

        return snap_list[1:]

    def snapshots_serialized(
        self, props=None, holds=False, mounted=False, datasets=None, recursive=True, min_txg=0, max_txg=0
    ):
        datasets = datasets or [p.name for p in self.pools]
        return ZFS._snapshots_serialized_impl(self.handle, datasets, props, holds, mounted, recursive, min_txg, max_txg)

    property errno:
        def __get__(self):
            return Error(libzfs.libzfs_errno(self.handle))

    property errstr:
        def __get__(self):
            return libzfs.libzfs_error_description(self.handle)

    property pools:
        def __get__(self):
            if self.mnttab_cache_enable:
                with nogil:
                    libzfs.libzfs_mnttab_cache(self.handle, self.mnttab_cache_enable)

            cdef ZFSPool pool
            cdef iter_state iter
            cdef libzfs.zpool_handle_t *handle

            try:
                with nogil:
                    iter.length = 0
                    iter.array = <uintptr_t *>malloc(32 * sizeof(uintptr_t))
                    if not iter.array:
                        raise MemoryError()

                    iter.alloc = 32

                    libzfs.zpool_iter(self.handle, self.__iterate_pools, <void*>&iter)

                for h in range(0, iter.length):
                    handle = <libzfs.zpool_handle_t*>iter.array[h]
                    pool = ZFSPool.__new__(ZFSPool)
                    pool.root = self
                    pool.handle = handle
                    iter.array[h] = 0
                    if pool.name == '$import':
                        continue

                    yield pool

            finally:
                with nogil:
                    for h in range(0, iter.length):
                        if iter.array[h] != 0:
                            handle = <libzfs.zpool_handle_t *>iter.array[h]
                            libzfs.zpool_close(handle)

                    free(iter.array)

            if self.mnttab_cache_enable:
                with nogil:
                    libzfs.libzfs_mnttab_cache(self.handle, False)

    property datasets:
        def __get__(self):
            for p in self.pools:
                try:
                    yield p.root_dataset
                    for c in p.root_dataset.children_recursive:
                        yield c
                except ZFSException:
                    continue

    property snapshots:
        def __get__(self):
            for p in self.pools:
                try:
                    for c in p.root_dataset.snapshots_recursive:
                        yield c
                except ZFSException:
                    continue

    def get(self, name):
        cdef const char *c_name = name
        cdef libzfs.zpool_handle_t* handle = NULL
        cdef ZFSPool pool

        with nogil:
            handle = libzfs.zpool_open_canfail(self.handle, c_name)

        if handle == NULL:
            raise ZFSException(Error.NOENT, 'Pool {0} not found'.format(name))

        pool = ZFSPool.__new__(ZFSPool)
        pool.root = self
        pool.handle = handle
        return pool

    def find_import(self, cachefile=None, name=None, destroyed=False, search_paths=None):
        cdef ZFSImportablePool pool
        cdef libzfs.importargs_t iargs
        cdef char* c_name
        cdef nvpair.nvlist_t* result

        iargs.path = NULL
        iargs.paths = 0
        iargs.poolname = NULL
        iargs.guid = 0
        iargs.cachefile = NULL

        if name:
            encoded = name.encode('utf-8')
            c_name = encoded
            iargs.poolname = c_name

        if search_paths:
            iargs.path = <char **>malloc(len(search_paths) * sizeof(char *))
            if not iargs.path:
                raise MemoryError()

            iargs.paths = len(search_paths)
            for i, p in enumerate(search_paths):
                iargs.path[i] = <char *>p

        if cachefile:
            iargs.cachefile = cachefile

        IF HAVE_ZPOOL_SEARCH_IMPORT_LIBZUTIL and HAVE_ZPOOL_SEARCH_IMPORT_PARAMS == 2:
            cdef libzfs.libpc_handle_t lpch
            lpch.lpc_lib_handle = self.handle
            lpch.lpc_ops = &libzfs.libzfs_config_ops
            lpch.lpc_printerr = True

        with nogil:
            IF HAVE_THREAD_INIT_FINI:
                thread_init()
            IF HAVE_ZPOOL_SEARCH_IMPORT_LIBZUTIL and HAVE_ZPOOL_SEARCH_IMPORT_PARAMS == 3:
                result = libzfs.zpool_search_import(self.handle, &iargs, &libzfs.libzfs_config_ops)
            ELIF HAVE_ZPOOL_SEARCH_IMPORT_LIBZUTIL and HAVE_ZPOOL_SEARCH_IMPORT_PARAMS == 2:
                result = libzfs.zpool_search_import(&lpch, &iargs)
            ELSE:
                result = libzfs.zpool_search_import(self.handle, &iargs)
            IF HAVE_THREAD_INIT_FINI:
                thread_fini()

        if iargs.path != NULL:
            free(iargs.path)

        if result is NULL:
            IF HAVE_ZPOOL_SEARCH_IMPORT_LIBZUTIL and HAVE_ZPOOL_SEARCH_IMPORT_PARAMS == 2:
                if cachefile:
                    raise ZFSInvalidCachefileException(LpcError(lpch.lpc_error), lpch.lpc_desc)
                else:
                    raise ZFSException(LpcError(lpch.lpc_error), lpch.lpc_desc)
            ELSE:
                return

        nv = NVList(nvlist=<uintptr_t>result)
        for name, config in nv.items(raw=True):
            pool = ZFSImportablePool.__new__(ZFSImportablePool)
            pool.name = name
            pool.free = False
            pool.nvlist = config

            # Skip destroyed pools
            if config['state'] == PoolState.DESTROYED and not destroyed:
                continue

            yield pool

    IF HAVE_ZFS_ENCRYPTION:
        def import_pool(
            self, ZFSImportablePool pool, newname, opts, missing_log=False, any_host=False, load_keys=False, enable_shares=False
        ):
            return self.__import_pool(pool, newname, opts, missing_log, any_host, load_keys, enable_shares)
    ELSE:
        def import_pool(self, ZFSImportablePool pool, newname, opts, missing_log=False, any_host=False, enable_shares=False):
            return self.__import_pool(pool, newname, opts, missing_log, any_host, enable_shares)

    def __import_pool(self, ZFSImportablePool pool, newname, opts, missing_log=False, any_host=False, load_keys=False, enable_shares=False):
        cdef const char *c_newname = newname
        cdef NVList copts = NVList(otherdict=opts)
        cdef int ret
        cdef int flags = 0
        cdef ZFSPool newpool

        if missing_log:
            flags |= zfs.ZFS_IMPORT_MISSING_LOG

        if any_host:
            flags |= zfs.ZFS_IMPORT_ANY_HOST

        with nogil:
            ret = libzfs.zpool_import_props(
                self.handle,
                pool.nvlist.handle,
                c_newname,
                copts.handle,
                flags
            )

        if ret != 0:
            raise self.get_error()

        newpool = self.get(newname)

        IF HAVE_ZFS_ENCRYPTION:
            failed_loading_keys = []
            if load_keys:
                root_ds = newpool.root_dataset
                for ds in itertools.chain([root_ds], root_ds.children_recursive):
                    if ds.encryption_root and not ds.key_loaded:
                        try:
                            ds.load_key()
                        except ZFSException:
                            failed_loading_keys.append(ds.name)

        IF HAVE_ZFS_FOREACH_MOUNTPOINT:
            self.zpool_enable_datasets(newname, enable_shares)
        ELSE:
            with nogil:
                ret = libzfs.zpool_enable_datasets(newpool.handle, NULL, 0)

        self.write_history(
            'zpool import', str(pool.guid), '-l' if load_keys else '', newpool.name
        )

        if ret != 0:
                raise self.get_error()

        IF HAVE_ZFS_ENCRYPTION:
            if failed_loading_keys:
                raise ZFSException(1, f'Failed loading keys for {",".join(failed_loading_keys)}')

        return newpool

    def export_pool(self, ZFSPool pool):
        cdef int ret

        with nogil:
            ret = libzfs.zpool_disable_datasets(pool.handle, True)

        if ret != 0:
            raise self.get_error()

        with nogil:
            ret = libzfs.zpool_export(pool.handle, True, "export")

        if ret != 0:
            raise self.get_error()

        self.write_history('zpool export', str(pool.name))

    def get_dataset(self, name):
        cdef const char *c_name = name
        cdef libzfs.zfs_handle_t* handle = NULL
        cdef ZFSPool pool
        cdef ZFSDataset dataset

        with nogil:
            handle = libzfs.zfs_open(self.handle, c_name, zfs.ZFS_TYPE_FILESYSTEM | zfs.ZFS_TYPE_VOLUME)

        if handle == NULL:
            raise ZFSException(Error.NOENT, 'Dataset {0} not found'.format(name))

        pool = ZFSPool.__new__(ZFSPool)
        pool.root = self
        pool.free = False

        with nogil:
            pool.handle = libzfs.zfs_get_pool_handle(handle)

        dataset = ZFSDataset.__new__(ZFSDataset)
        dataset.root = self
        dataset.pool = pool
        dataset.handle = handle
        return dataset

    def get_snapshot(self, name):
        cdef libzfs.zfs_handle_t* handle = NULL
        cdef ZFSPool pool
        cdef ZFSSnapshot snap
        cdef const char *c_name = name

        with nogil:
            handle = libzfs.zfs_open(self.handle, c_name, zfs.ZFS_TYPE_SNAPSHOT)

        if handle == NULL:
            raise ZFSException(Error.NOENT, 'Snapshot {0} not found'.format(name))

        pool = ZFSPool.__new__(ZFSPool)
        pool.root = self
        pool.free = False

        with nogil:
            pool.handle = libzfs.zfs_get_pool_handle(handle)

        snap = ZFSSnapshot.__new__(ZFSSnapshot)
        snap.root = self
        snap.pool = pool
        snap.handle = handle
        return snap

    def get_object(self, name):
        return self.get_snapshot(name) if "@" in name else self.get_dataset(name)

    def get_dataset_by_path(self, path):
        cdef libzfs.zfs_handle_t* handle
        cdef char *c_path = path
        cdef zfs.zfs_type_t dataset_type = DatasetType.FILESYSTEM.value

        with nogil:
            handle = libzfs.zfs_path_to_zhandle(self.handle, c_path, dataset_type)

        cdef ZFSPool pool
        cdef ZFSDataset dataset
        if handle == NULL:
            raise ZFSException(Error.NOENT, 'Dataset with path {0} not found'.format(path))

        pool = ZFSPool.__new__(ZFSPool)
        pool.root = self
        pool.free = False

        with nogil:
            pool.handle = libzfs.zfs_get_pool_handle(handle)

        dataset = ZFSDataset.__new__(ZFSDataset)
        dataset.root = self
        dataset.pool = pool
        dataset.handle = handle
        return dataset

    def create(self, name, topology, opts, fsopts, enable_all_feat=True):
        cdef NVList root = self.make_vdev_tree(topology, opts).nvlist
        cdef NVList cfsopts
        cdef NVList copts
        cdef const char *c_name = name
        cdef int ret

        if enable_all_feat:
            opts = opts.copy()
            for i in range(0, zfs.SPA_FEATURES):
                feat = &zfs.spa_feature_table[i]
                opts['feature@{}'.format(feat.fi_uname)] = 'enabled'

        copts = NVList(otherdict=opts)

        temp_file = None
        IF HAVE_ZFS_ENCRYPTION:
            temp_file, fsopts = ZFSPool._encryption_common(fsopts)

        try:
            cfsopts = NVList(otherdict=fsopts)

            with nogil:
                ret = libzfs.zpool_create(
                    self.handle,
                    c_name,
                    root.handle,
                    copts.handle,
                    cfsopts.handle
                )
        finally:
            if os.path.exists(temp_file or ''):
                os.unlink(temp_file)

        if ret != 0:
            raise ZFSException(self.errno, self.errstr)

        IF HAVE_ZFS_ENCRYPTION:
            if temp_file:
                ds = self.get_dataset(name)
                ds.properties['keylocation'].value = 'prompt'

        if self.history:
            hopts = self.generate_history_opts(opts, '-o')
            hfsopts = self.generate_history_opts(fsopts, '-O')
            self.write_history(
                'zpool create',
                hopts,
                hfsopts,
                name,
                self.history_vdevs_list(topology)
            )

        return self.get(name)

    def destroy(self, name, force=False):
        cdef libzfs.zpool_handle_t* handle
        cdef const char *c_name = name
        cdef int rv
        cdef boolean_t c_force = force

        with nogil:
            handle = libzfs.zpool_open(self.handle, c_name)

        if handle == NULL:
            raise ZFSException(Error.NOENT, 'Pool {0} not found'.format(name))

        with nogil:
            rv = libzfs.zpool_disable_datasets(handle, c_force)

        if rv != 0:
            raise self.get_error()

        with nogil:
            rv = libzfs.zpool_destroy(handle, "destroy")

        if rv != 0:
            raise ZFSException(self.errno, self.errstr)

    def receive(self, name, fd, force=False, nomount=False, resumable=False, props=None, limitds=None):
        cdef libzfs.libzfs_handle_t *handle = self.handle
        cdef libzfs.recvflags_t flags
        cdef NVList props_nvl = None
        cdef NVList limitds_nvl = None
        cdef nvpair.nvlist_t *c_props_nvl = NULL
        cdef nvpair.nvlist_t *c_limitds_nvl = NULL
        cdef const char *c_name = name
        cdef int c_fd = fd
        cdef int ret

        memset(&flags, 0, sizeof(libzfs.recvflags_t))

        if force:
            flags.force = True

        if nomount:
            flags.nomount = True

        IF HAVE_RECVFLAGS_T_RESUMABLE:
            if resumable:
                flags.resumable = True

        IF HAVE_ZFS_RECEIVE == 7:
            if props:
                props_nvl = NVList(otherdict=props)
                c_props_nvl = props_nvl.handle

            if limitds:
                limitds_nvl = NVList(otherdict=limitds)
                c_limitds_nvl = limitds_nvl.handle

            with nogil:
                ret = libzfs.zfs_receive(
                    handle,
                    c_name,
                    &flags,
                    c_fd,
                    c_props_nvl,
                    c_limitds_nvl,
                    NULL
                )
        ELSE:
            if props:
                props_nvl = NVList(otherdict=props)
                c_props_nvl = props_nvl.handle

            with nogil:
                IF HAVE_ZFS_RECEIVE == 6:
                    ret = libzfs.zfs_receive(handle, c_name, c_props_nvl, &flags, c_fd, NULL)
                ELSE:
                    ret = libzfs.zfs_receive(handle, c_name, c_props_nvl, &flags, c_fd)

        if ret not in (0, -2):
            raise self.get_error()

    def write_history(self, *args):
        cdef const char *c_message

        history_message = ""

        def eval_arg(argument):
            if isinstance(argument, str):
                return eval_str(argument)
            if isinstance(argument, dict):
                return eval_dict(argument)
            if isinstance(argument, tuple):
                return eval_tuple(argument)
            if isinstance(argument, list):
                return eval_list(argument)
            if isinstance(argument, ZFSVdev):
                return eval_zfsvdev(argument)

            return str(argument)

        def eval_str(argument):
            return " " + argument

        def eval_dict(argument):
            out = ""
            for tup in arg.items():
                out += eval_arg(tup)
            return out

        def eval_tuple(argument):
            if len(argument) == 2:
                if isinstance(argument[1], str):
                    return " " + str(argument[0]) + '=' + str(argument[1])

            out = ""
            for i in argument:
                out += eval_arg(i)
            return out

        def eval_list(argument):
            out = ""
            for i in argument:
                out += eval_arg(i)
            return out

        def eval_zfsvdev(argument):
            disks = argument.disks
            if len(disks):
                out = " " + str(argument.type)
                for disk in disks:
                    out += " " + disk
                return  out
            else:
                return ""

        if self.history:
            history_message = self.history_prefix
            for arg in args:
                history_message += eval_arg(arg)

            c_message = history_message

            with nogil:
                libzfs.zpool_log_history(self.handle, c_message)

    def generate_history_opts(self, opt_dict, prefix):
        keys = []
        out_dict = {}
        if isinstance(opt_dict, dict):
            for key in opt_dict.keys():
                keys.append(key)

            for key in keys:
                out_dict[prefix + ' ' + key] = opt_dict[key]

        return out_dict

    def history_vdevs_list(self, topology):
        out = []
        if self.history:
            for vdev_type in filter(lambda v: v in topology, ('data', 'cache', 'log', 'dedup', 'special')):
                vdevs = topology[vdev_type]
                if vdev_type != 'data':
                    out.append(vdev_type)
                striped = []
                other = []
                for vdev in vdevs:
                    if vdev.type == 'disk':
                        # this is stripe
                        striped.append(vdev)
                        continue
                    other.append(vdev.type)
                    for child in vdev.children:
                        other.append(child.path)
                for vdev in striped:
                    out.append(vdev.path)
                out.extend(other)
        return out

    IF HAVE_SENDFLAGS_T_TYPEDEF and HAVE_ZFS_SEND_RESUME:
        def send_resume(self, fd, token, flags=None):
            cdef libzfs.sendflags_t cflags
            cdef int ret, c_fd
            cdef char *c_token = token

            memset(&cflags, 0, cython.sizeof(libzfs.sendflags_t))

            if flags:
                convert_sendflags(flags, &cflags)

            c_fd = fd
            with nogil:
                ret = libzfs.zfs_send_resume(self.handle, &cflags, c_fd, c_token)

            if ret != 0:
                raise ZFSException(self.errno, self.errstr)

    IF HAVE_ZFS_SEND_RESUME_TOKEN_TO_NVLIST:
        def describe_resume_token(self, token):
            cdef nvpair.nvlist_t *nvl
            cdef char *c_token = token

            with nogil:
                nvl = libzfs.zfs_send_resume_token_to_nvlist(self.handle, c_token)

            if nvl == NULL:
                raise ZFSException(self.errno, self.errstr)

            retval = dict(NVList(<uintptr_t>nvl))
            with nogil:
                nvpair.nvlist_free(nvl)
            return retval


cdef class ZPoolProperty(object):
    cdef int propid
    cdef readonly ZFSPool pool

    def __init__(self):
        raise RuntimeError('ZPoolProperty cannot be instantiated by the user')

    def asdict(self):
        return {
            'value': self.value,
            'rawvalue': self.rawvalue,
            'parsed': self.parsed,
            'source': self.source.name
        }

    def __str__(self):
        return "<libzfs.ZPoolProperty name '{0}' value '{1}'>".format(self.name, self.value)

    def __repr__(self):
        return str(self)

    property name:
        def __get__(self):
            return libzfs.zpool_prop_to_name(self.propid)

    property value:
        def __get__(self):
            cdef char cstr[libzfs.ZPOOL_MAXPROPLEN]
            cdef int ret

            with nogil:
                ret = libzfs.zpool_get_prop(self.pool.handle, self.propid, cstr, sizeof(cstr), NULL, False)

            if ret != 0:
                return '-'

            return cstr

        def __set__(self, value):
            cdef const char *c_name
            cdef const char *c_value = value
            cdef int ret

            name = self.name
            c_name = name

            with nogil:
                ret = libzfs.zpool_set_prop(self.pool.handle, c_name, c_value)

            if ret != 0:
                raise self.pool.root.get_error()

            self.pool.root.write_history('zpool set', (self.name, str(value)), self.pool.name)

    property rawvalue:
        def __get__(self):
            cdef char cstr[libzfs.ZPOOL_MAXPROPLEN]
            cdef int ret

            with nogil:
                ret = libzfs.zpool_get_prop(self.pool.handle, self.propid, cstr, sizeof(cstr), NULL, True)

            if ret != 0:
                return '-'

            return cstr

    property source:
        def __get__(self):
            cdef zfs.zprop_source_t src

            with nogil:
                if libzfs.zpool_get_prop(self.pool.handle, self.propid, NULL, 0, &src, True) != 0:
                    src = zfs.ZPROP_SRC_NONE

            return PropertySource(src)

    property parsed:
        def __get__(self):
            return parse_zpool_prop(self.name, self.rawvalue)

        def __set__(self, value):
            self.value = serialize_zpool_prop(self.name, value)

    property allowed_values:
        def __get__(self):
            return libzfs.zfs_prop_values(self.propid)

    def reset(self):
        pass


cdef class ZPoolFeature(object):
    cdef readonly ZFSPool pool
    cdef NVList nvlist
    cdef zfs.zfeature_info_t *feature

    def asdict(self):
        return {
            'name': self.name,
            'guid': self.guid,
            'description': self.description,
            'state': self.state.name
        }

    property name:
        def __get__(self):
            return self.feature.fi_uname

    property guid:
        def __get__(self):
            return self.feature.fi_guid

    property description:
        def __get__(self):
            return self.feature.fi_desc

    property state:
        def __get__(self):
            if self.guid not in self.nvlist:
                return FeatureState.DISABLED

            if self.nvlist[self.guid] == 0:
                return FeatureState.ENABLED

            if self.nvlist[self.guid] > 0:
                return FeatureState.ACTIVE

    def enable(self):
        cdef const char *c_name
        cdef int ret

        name = "feature@{0}".format(self.name)
        c_name = name

        with nogil:
            ret = libzfs.zpool_set_prop(self.pool.handle, c_name, "enabled")

        if ret != 0:
            raise self.pool.root.get_error()

        self.pool.root.write_history('zpool set', (name, 'enabled'), self.pool.name)


cdef class ZFSProperty(object):
    cdef readonly ZFSObject dataset
    cdef int propid
    cdef const char *cname
    cdef char cvalue[libzfs.ZFS_MAXPROPLEN + 1]
    cdef char crawvalue[libzfs.ZFS_MAXPROPLEN + 1]
    cdef char csrcstr[MAX_DATASET_NAME_LEN + 1]
    cdef zfs.zprop_source_t csource

    def __init__(self):
        raise RuntimeError('ZFSProperty cannot be instantiated by the user')

    def asdict(self):
        return {
            'value': self.value,
            'rawvalue': self.rawvalue,
            'parsed': self.parsed,
            'source': self.source.name if self.source else None
        }

    def __str__(self):
        return "<libzfs.ZFSProperty name '{0}' value '{1}'>".format(self.name, self.value)

    def __repr__(self):
        return str(self)

    def refresh(self):
        self.csource = zfs.ZPROP_SRC_NONE
        with nogil:
            self.cname = libzfs.zfs_prop_to_name(self.propid)
            if libzfs.zfs_prop_get(
                self.dataset.handle, self.propid, self.cvalue, libzfs.ZFS_MAXPROPLEN,
                &self.csource, self.csrcstr, MAX_DATASET_NAME_LEN,
                False
            ) != 0:
                self.csource = zfs.ZPROP_SRC_NONE

            libzfs.zfs_prop_get(
                self.dataset.handle, self.propid, self.crawvalue, libzfs.ZFS_MAXPROPLEN,
                NULL, NULL, 0,
                True
            )

    property name:
        def __get__(self):
            return self.cname

    property value:
        def __get__(self):
            return self.cvalue

        def __set__(self, value):
            cdef const char *c_value
            cdef int ret

            str_value = str(value).encode('utf-8')
            c_value = str_value

            with nogil:
                ret = libzfs.zfs_prop_set(self.dataset.handle, self.cname, c_value)

            if ret != 0:
                raise self.dataset.root.get_error()

            self.dataset.root.write_history('zfs set', (self.name, str(value)), self.dataset.name)

    property rawvalue:
        def __get__(self):
            return self.crawvalue

    property source:
        def __get__(self):
            return PropertySource(<int>self.csource)

    property source_info:
        def __get__(self):
            return str(self.csrcstr)

    property parsed:
        def __get__(self):
            return parse_zfs_prop(self.name, self.rawvalue)

        def __set__(self, value):
            self.value = serialize_zfs_prop(self.name, value)

    property allowed_values:
        def __get__(self):
            return libzfs.zfs_prop_values(self.propid)

    def inherit(self, recursive=False, bint received=False):
        cdef ZFSObject dset
        cdef int ret
        cdef int c_recursive = recursive
        cdef zfs.zfs_prop_t prop

        self.refresh()

        dsets = [self.dataset]
        if recursive:
            dsets.extend(list(self.dataset.children_recursive))
            prop = <zfs.zfs_prop_t>zfs.zfs_name_to_prop(self.cname)

        for d in dsets:
            dset = <ZFSObject>d
            with nogil:
                if c_recursive and prop != zfs.ZPROP_INVAL:
                    IF HAVE_ZFS_PROP_VALID_FOR_TYPE == 3:
                        ret = <int>zfs.zfs_prop_valid_for_type(prop, libzfs.zfs_get_type(dset.handle), 0)
                    ELSE:
                        ret = <int>zfs.zfs_prop_valid_for_type(prop, libzfs.zfs_get_type(dset.handle))
                    if ret != 1:
                        continue
                ret = libzfs.zfs_prop_inherit(dset.handle, self.cname, received)

            if ret != 0:
                error =  self.dataset.root.get_error()
                if error.args:
                    error.args = (f'Failed to inherit {self.name} for {d.name}: {error.args[0]}',)
                raise error

        self.dataset.root.write_history('zfs inherit', '-r' if recursive else '', self.dataset.name)


cdef class ZFSUserProperty(ZFSProperty):
    cdef dict values
    cdef readonly name

    def __init__(self, value):
        self.values = {"value": value}

    def __str__(self):
        return "<libzfs.ZFSUserProperty name '{0}' value '{1}'>".format(self.name, self.value)

    def __repr__(self):
        return str(self)

    property value:
        def __get__(self):
            return self.values.get('value')

        def __set__(self, value):
            cdef const char *c_name
            cdef const char *c_value
            cdef int ret

            str_value = str(value).encode('utf-8')
            c_name = self.name
            c_value = str_value

            if self.dataset:
                with nogil:
                    ret = libzfs.zfs_prop_set(self.dataset.handle, c_name, c_value)

                if ret != 0:
                    raise self.dataset.root.get_error()

                self.values['value'] = value

    property rawvalue:
        def __get__(self):
            return self.value

    property source:
        def __get__(self):
            src = self.values.get('source')
            if not src:
                return None

            if src == self.dataset.name:
                return PropertySource.LOCAL

            if src == '$recvd':
                return PropertySource.RECEIVED

            return PropertySource.INHERITED

    def refresh(self):
        cdef ZFSUserProperty userprop
        cdef nvpair.nvlist_t *nvlist

        self.cname = self.name

        with nogil:
            nvlist = libzfs.zfs_get_user_props(self.dataset.handle)

        nvl = NVList(<uintptr_t>nvlist)

        for k, v in nvl.items():
            if k == self.name:
                self.values.update(v)
                break
        else:
            self.values['value'] = None


cdef class ZFSVdevStats(object):
    cdef readonly ZFSVdev vdev
    cdef NVList _nvlist
    cdef zfs.vdev_stat_t *vs;
    cdef uint_t total

    def asdict(self):
        state = {
            'timestamp': self.timestamp,
            'read_errors': self.read_errors,
            'write_errors': self.write_errors,
            'checksum_errors': self.checksum_errors,
            'ops': self.ops,
            'bytes': self.bytes,
            'size': self.size,
            'allocated': self.allocated,
            'fragmentation': self.fragmentation,
            'self_healed': self.self_healed
        }
        IF HAVE_ZFS_VDEV_STAT_ASHIFT:
            state.update({
                'configured_ashift': self.configured_ashift,
                'logical_ashift': self.logical_ashift,
                'physical_ashift': self.physical_ashift,
            })
        return state

    property nvlist:
        def __get__(self):
            return self._nvlist

        def __set__(self, value):
            self._nvlist = value
            ret = self._nvlist.nvlist_lookup_uint64_array(
                <nvpair.nvlist_t*>self._nvlist.handle, zfs.ZPOOL_CONFIG_VDEV_STATS, <uint64_t **>&self.vs, &self.total
            )
            if ret != 0:
                raise ZFSVdevStatsException(ret)

    property timestamp:
        def __get__(self):
            return self.vs.vs_timestamp

    property size:
        def __get__(self):
            return self.vs.vs_space

    property allocated:
        def __get__(self):
            return self.vs.vs_alloc

    property read_errors:
        def __get__(self):
            return self.vs.vs_read_errors

    property write_errors:
        def __get__(self):
            return self.vs.vs_write_errors

    property checksum_errors:
        def __get__(self):
            return self.vs.vs_checksum_errors

    property ops:
        def __get__(self):
            return self.vs.vs_ops

    property bytes:
        def __get__(self):
            return self.vs.vs_bytes

    IF HAVE_ZFS_VDEV_STAT_ASHIFT:
        property configured_ashift:
            def __get__(self):
                return self.vs.vs_configured_ashift

        property logical_ashift:
            def __get__(self):
                return self.vs.vs_logical_ashift

        property physical_ashift:
            def __get__(self):
                return self.vs.vs_physical_ashift

    property fragmentation:
        def __get__(self):
            return self.vs.vs_fragmentation

    property self_healed:
        def __get__(self):
            # This is in bytes
            return self.vs.vs_self_healed


cdef class ZFSVdev(object):
    cdef readonly ZFSPool zpool
    cdef readonly ZFS root
    cdef readonly ZFSVdev parent
    cdef readonly object group
    cdef NVList nvlist

    def __init__(self, ZFS root, typ, ZFSPool pool=None):
        self.root = root
        self.zpool = pool
        self.nvlist = NVList()
        self.type = typ

    def __str__(self):
        if self.path:
            return "<libzfs.ZFSVdev type '{0}', path '{1}'>".format(self.type, self.path)

        return "<libzfs.ZFSVdev type '{0}'>".format(self.type)

    def __repr__(self):
        return str(self)

    def asdict(self, recursive=True):
        ret = {
            'name': self.name,
            'type': self.type,
            'path': self.path,
            'guid': str(self.guid),
            'status': self.status,
            'stats': self.stats.asdict()
        }

        if recursive:
            ret['children'] = [i.asdict() for i in self.children]

        return ret

    def add_child_vdev(self, ZFSVdev vdev):
        if zfs.ZPOOL_CONFIG_CHILDREN not in self.nvlist:
            self.nvlist.set(zfs.ZPOOL_CONFIG_CHILDREN, [], nvpair.DATA_TYPE_NVLIST_ARRAY)

        self.nvlist[zfs.ZPOOL_CONFIG_CHILDREN] = self.nvlist.get_raw(zfs.ZPOOL_CONFIG_CHILDREN) + [vdev.nvlist]

    def set_ashift(self, int value):
        self.nvlist[zfs.ZPOOL_CONFIG_ASHIFT] = value

    def set_whole_disk(self, boolean_t value):
        self.nvlist[zfs.ZPOOL_CONFIG_WHOLE_DISK] = value

    def attach(self, ZFSVdev vdev):
        cdef const char *command = 'zpool attach'
        cdef ZFSVdev root
        cdef int rv
        cdef boolean_t rebuild = False

        if self.type not in (zfs.VDEV_TYPE_MIRROR, zfs.VDEV_TYPE_DISK, zfs.VDEV_TYPE_FILE):
            raise ZFSException(Error.NOTSUP, "Can attach disks to mirrors and stripes only")

        if self.type == zfs.VDEV_TYPE_MIRROR:
            first_child = next(self.children)
        else:
            first_child = self

        root = self.root.make_vdev_tree({
            'data': [vdev]
        }, {'ashift': self.zpool.properties['ashift'].parsed})

        first_child_path = first_child.path
        new_vdev_path = vdev.path

        cdef const char* c_first_child_path = first_child_path
        cdef const char* c_new_vdev_path = new_vdev_path

        with nogil:
            IF HAVE_ZPOOL_VDEV_ATTACH == 5:
                rv = libzfs.zpool_vdev_attach(
                    self.zpool.handle, c_first_child_path, c_new_vdev_path, root.nvlist.handle, 0
                )
            ELSE:
                rv = libzfs.zpool_vdev_attach(
                    self.zpool.handle, c_first_child_path, c_new_vdev_path, root.nvlist.handle, 0, rebuild
                )

        if rv != 0:
            raise self.root.get_error()

        self.root.write_history(command, self.zpool.name, first_child.path, vdev.path)

    def replace(self, ZFSVdev vdev):
        cdef const char *command = 'zpool replace'
        cdef ZFSVdev root
        cdef int rv
        cdef boolean_t rebuild = False

        if self.type == zfs.VDEV_TYPE_FILE:
            raise ZFSException(Error.NOTSUP, "Can replace disks only")

        root = self.root.make_vdev_tree({
            'data': [vdev]
        }, {'ashift': self.zpool.properties['ashift'].parsed})

        self_path = self.path
        vdev_path = vdev.path

        cdef const char *c_path = self_path
        cdef const char *c_vdev_path = vdev_path

        with nogil:
            IF HAVE_ZPOOL_VDEV_ATTACH == 5:
                rv = libzfs.zpool_vdev_attach(self.zpool.handle, c_path, c_vdev_path, root.nvlist.handle, 1)
            ELSE:
                rv = libzfs.zpool_vdev_attach(self.zpool.handle, c_path, c_vdev_path, root.nvlist.handle, 1, rebuild)

        if rv != 0:
            raise self.root.get_error()

        self.root.write_history(command, self.zpool.name, self.path, vdev.path)

    def detach(self):
        cdef const char *command = 'zpool detach'
        cdef int rv
        if self.type not in (zfs.VDEV_TYPE_FILE, zfs.VDEV_TYPE_DISK):
            raise ZFSException(Error.NOTSUP, "Cannot detach virtual vdevs")

        if self.parent is None:
            raise ZFSException(Error.NOTSUP, "Cannot detach root-level vdevs")

        if self.parent.type not in (zfs.VDEV_TYPE_REPLACING, zfs.VDEV_TYPE_MIRROR, zfs.VDEV_TYPE_SPARE):
            raise ZFSException(Error.NOTSUP, "Can detach disks from mirrors, replacing and spares only")

        path = self.path

        cdef const char *c_path = path

        with nogil:
            rv = libzfs.zpool_vdev_detach(self.zpool.handle, c_path)

        if rv != 0:
            raise self.root.get_error()

        self.root.write_history(command, self.zpool.name, self.path)

    def remove(self):
        cdef const char *command = 'zpool remove'
        path_guid = self.path or str(self.guid)
        cdef const char *c_path_guid = path_guid
        cdef int rv

        with nogil:
            rv = libzfs.zpool_vdev_remove(self.zpool.handle, c_path_guid)

        if rv != 0:
            raise self.root.get_error()

        self.root.write_history(command, self.zpool.name, self.path)

    def offline(self, temporary=False):
        cdef const char *command = 'zpool offline'
        if self.type not in (zfs.VDEV_TYPE_DISK, zfs.VDEV_TYPE_FILE):
            raise ZFSException(Error.NOTSUP, "Can make disks offline only")

        path = self.path
        cdef const char *c_path = path
        cdef int c_temporary = int(temporary)
        cdef int rv

        with nogil:
            rv = libzfs.zpool_vdev_offline(self.zpool.handle, c_path, c_temporary)

        if rv != 0:
            raise self.root.get_error()

        self.root.write_history(command, '-t' if temporary else '',self.zpool.name, self.path)

    def online(self, expand=False):
        cdef const char *command = 'zpool online'
        cdef int flags = 0
        cdef zfs.vdev_state_t newstate

        if self.type not in (zfs.VDEV_TYPE_DISK, zfs.VDEV_TYPE_FILE):
            raise ZFSException(Error.NOTSUP, "Can make disks online only")

        if expand:
            flags |= zfs.ZFS_ONLINE_EXPAND

        path = self.path
        cdef const char *c_path = path
        cdef int rv

        with nogil:
            rv = libzfs.zpool_vdev_online(self.zpool.handle, c_path, flags, &newstate)

        if rv != 0:
            raise self.root.get_error()

        self.root.write_history(command, '-e' if expand else '', self.zpool.name, self.path)

    def degrade(self, aux):
        cdef zfs.vdev_aux_t c_aux = VDevAuxState(int(aux))
        cdef uint64_t c_guid = self.guid
        cdef int rv

        with nogil:
            rv = libzfs.zpool_vdev_degrade(self.zpool.handle, c_guid, c_aux)

        if rv != 0:
            raise self.root.get_error()

    def fault(self, aux):
        cdef zfs.vdev_aux_t c_aux = VDevAuxState(int(aux))
        cdef uint64_t c_guid = self.guid
        cdef int rv

        with nogil:
            rv = libzfs.zpool_vdev_fault(self.zpool.handle, c_guid, c_aux)

        if rv != 0:
            raise self.root.get_error()

    property type:
        def __get__(self):
            value = self.nvlist.get('type')
            if value == zfs.VDEV_TYPE_RAIDZ:
                return value + str(self.nvlist.get('nparity'))

            return value

        def __set__(self, value):
            if value not in (
                zfs.VDEV_TYPE_ROOT,
                zfs.VDEV_TYPE_DISK,
                zfs.VDEV_TYPE_FILE,
                'raidz1',
                'raidz2',
                'raidz3',
                zfs.VDEV_TYPE_MIRROR,
                zfs.VDEV_TYPE_DRAID,
            ):
                raise ValueError('Invalid vdev type')

            self.nvlist['type'] = value

            if value.startswith(zfs.VDEV_TYPE_RAIDZ):
                self.nvlist['type'] = zfs.VDEV_TYPE_RAIDZ
                self.nvlist['nparity'] = long(value[-1])

    property guid:
        def __get__(self):
            return self.nvlist.get(zfs.ZPOOL_CONFIG_GUID)

    property name:
        def __get__(self):
            cdef char *mntpt
            mntpt = libzfs.zpool_vdev_name(
                <libzfs.libzfs_handle_t *>self.root,
                <libzfs.zpool_handle_t *>self.zpool.handle,
                self.nvlist.handle,
                libzfs.VDEV_NAME_TYPE_ID)
            try:
                return str(mntpt)
            finally:
                free(mntpt)

    property path:
        def __get__(self):
            return self.nvlist.get(zfs.ZPOOL_CONFIG_PATH)

        def __set__(self, value):
            self.nvlist[zfs.ZPOOL_CONFIG_PATH] = value

    property status:
        def __get__(self):
            stats = self.nvlist[zfs.ZPOOL_CONFIG_VDEV_STATS]
            return libzfs.zpool_state_to_name(stats[1], stats[2])

    property size:
        def __get__(self):
            return self.nvlist[zfs.ZPOOL_CONFIG_ASIZE] << self.nvlist[zfs.ZPOOL_CONFIG_ASHIFT]

    property stats:
        def __get__(self):
            cdef ZFSVdevStats ret

            ret = ZFSVdevStats.__new__(ZFSVdevStats)
            ret.vdev = self
            ret.nvlist = self.nvlist
            return ret

    property children:
        def __get__(self):
            cdef ZFSVdev vdev

            if zfs.ZPOOL_CONFIG_CHILDREN not in self.nvlist:
                return

            for i in self.nvlist.get_raw(zfs.ZPOOL_CONFIG_CHILDREN):
                vdev = ZFSVdev.__new__(ZFSVdev)
                vdev.nvlist = i
                vdev.zpool = self.zpool
                vdev.root = self.root
                vdev.parent = self
                vdev.group = self.group
                yield vdev

        def __set__(self, value):
            self.nvlist[zfs.ZPOOL_CONFIG_CHILDREN] = [(<ZFSVdev>i).nvlist for i in value]

    property disks:
        def __get__(self):
            try:
                if self.status in ('UNAVAIL', 'OFFLINE'):
                    return []
            except ValueError:
                # status may not be available in user defined ZFSVdev
                pass
            if self.type == zfs.VDEV_TYPE_DISK:
                return [self.path]
            elif self.type == zfs.VDEV_TYPE_FILE:
                return []
            else:
                result = []
                for i in self.children:
                    result += i.disks

                return result


cdef class ZPoolScrub(object):
    cdef readonly ZFS root
    cdef readonly ZFSPool pool
    cdef zfs.pool_scan_stat_t *stats

    def __init__(self, ZFS root, ZFSPool pool):
        self.root = root
        self.pool = pool
        self.stats = NULL
        cdef NVList config
        cdef NVList nvroot = pool.get_raw_config().get_raw(zfs.ZPOOL_CONFIG_VDEV_TREE)
        cdef int ret
        cdef uint_t total
        if zfs.ZPOOL_CONFIG_SCAN_STATS not in nvroot:
            return

        ret = nvroot.nvlist_lookup_uint64_array(
            <nvpair.nvlist_t*>nvroot.handle, zfs.ZPOOL_CONFIG_SCAN_STATS, <uint64_t **>&self.stats, &total
        )
        if ret != 0:
            raise ZFSPoolScanStatsException(ret)

    property state:
        def __get__(self):
            if self.stats != NULL:
                return ScanState(self.stats.pss_state)

    property function:
        def __get__(self):
            if self.stats != NULL:
                return ScanFunction(self.stats.pss_func)

    property start_time:
        def __get__(self):
            if self.stats != NULL:
                return datetime.utcfromtimestamp(self.stats.pss_start_time)

    property end_time:
        def __get__(self):
            if self.stats != NULL and self.state != ScanState.SCANNING:
                return datetime.utcfromtimestamp(self.stats.pss_end_time)

    property bytes_to_scan:
        def __get__(self):
            if self.stats != NULL:
                return self.stats.pss_to_examine

    property bytes_scanned:
        def __get__(self):
            if self.stats != NULL:
                return self.stats.pss_examined

    property total_secs_left:
        def __get__(self):
            if self.state != ScanState.SCANNING:
                return

            total = self.bytes_to_scan
            issued = self.bytes_issued
            elapsed = ((int(time.time()) - self.stats.pss_pass_start) - self.stats.pss_pass_scrub_spent_paused) or 1
            pass_issued = self.stats.pss_pass_issued or 1
            issue_rate = pass_issued / elapsed
            return int((total - issued) / issue_rate)

    property bytes_issued:
        def __get__(self):
            if self.stats != NULL:
                return self.stats.pss_issued

    property bytes_issued_per_pass:
        def __get__(self):
            if self.stats != NULL:
                return self.stats.pss_pass_issued

    property bytes_skipped:
        def __get__(self):
            if self.stats != NULL:
                return self.stats.pss_skipped

    property pause:
        def __get__(self):
            if self.state == ScanState.SCANNING and self.stats.pss_pass_scrub_pause != 0:
                return datetime.utcfromtimestamp(self.stats.pss_pass_scrub_pause)

    property errors:
        def __get__(self):
            if self.stats != NULL:
                return self.stats.pss_errors

    property percentage:
        def __get__(self):
            if self.stats == NULL:
                return

            if not self.bytes_to_scan:
                return 0

            bytes_total = self.bytes_to_scan - self.bytes_skipped
            if bytes_total == 0:
                return 0

            return (<float>self.bytes_issued / <float>bytes_total) * 100

    def asdict(self):
        return {
            'function': self.function.name if self.function else None,
            'state': self.state.name if self.stats != NULL else None,
            'start_time': self.start_time,
            'end_time': self.end_time,
            'percentage': self.percentage,
            'bytes_to_process': self.bytes_scanned,
            'bytes_processed': self.bytes_to_scan,
            'bytes_issued': self.bytes_issued,
            'pause': self.pause,
            'errors': self.errors,
            'total_secs_left': self.total_secs_left
        }


cdef class ZFSPool(object):
    cdef libzfs.zpool_handle_t* handle
    cdef bint free
    cdef readonly ZFS root

    def __cinit__(self):
        self.free = True

    def __init__(self):
        raise RuntimeError('ZFSPool cannot be instantiated by the user')

    def __dealloc__(self):
        if self.free and self.handle != NULL:
            with nogil:
                libzfs.zpool_close(self.handle)

            self.handle = NULL

    def __str__(self):
        return "<libzfs.ZFSPool name '{0}' guid '{1}'>".format(self.name, self.guid)

    def __repr__(self):
        return str(self)

    def asdict(self, datasets_recursive=True):
        try:
            root_ds = self.root_dataset.asdict(datasets_recursive)
        except (ZFSException, AttributeError):
            root_ds = None

        filter_vdevs = [zfs.VDEV_TYPE_HOLE, zfs.VDEV_TYPE_INDIRECT]

        state = {
            'name': self.name,
            'id': self.name,
            'guid': str(self.guid),
            'hostname': self.hostname,
            'status': self.status,
            'healthy': self.healthy,
            'warning': self.warning,
            'error_count': self.error_count,
            'root_dataset': root_ds,
            'properties': {k: p.asdict() for k, p in self.properties.items()} if self.properties else None,
            'features': [i.asdict() for i in self.features] if self.features else None,
            'scan': self.scrub.asdict(),
            'root_vdev': self.root_vdev.asdict(False),
            'groups': {
                'data': [i.asdict() for i in self.data_vdevs if i.type not in filter_vdevs],
                'log': [i.asdict() for i in self.log_vdevs if i.type not in filter_vdevs],
                'cache': [i.asdict() for i in self.cache_vdevs if i.type not in filter_vdevs],
                'spare': [i.asdict() for i in self.spare_vdevs if i.type not in filter_vdevs],
            },
        }
        IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
            state['groups'].update({
                'special': [i.asdict() for i in self.special_vdevs if i.type not in filter_vdevs],
                'dedup': [i.asdict() for i in self.dedup_vdevs if i.type not in filter_vdevs],
            })

        if self.handle != NULL:
            state.update({
                'status_code': self.status_code.name,
                'status_detail': self.status_detail
            })

        return state

    @staticmethod
    cdef int __iterate_props(int proptype, void* arg) nogil:
        with gil:
            proptypes = <object>arg
            proptypes.append(proptype)
            return zfs.ZPROP_CONT

    property root_dataset:
        def __get__(self):
            cdef const char *c_name;
            cdef libzfs.zfs_handle_t* handle = NULL
            cdef ZFSDataset dataset

            name = self.name
            c_name = name

            with nogil:
                handle = libzfs.zfs_open(self.root.handle, c_name, zfs.ZFS_TYPE_FILESYSTEM)

            if handle == NULL:
                raise self.root.get_error()

            dataset = ZFSDataset.__new__(ZFSDataset)
            dataset.root = self.root
            dataset.pool = self
            dataset.handle = handle
            return dataset

    property root_vdev:
        def __get__(self):
            cdef ZFSVdev vdev
            cdef NVList vdev_tree = self.get_raw_config().get_raw(zfs.ZPOOL_CONFIG_VDEV_TREE)

            vdev = ZFSVdev.__new__(ZFSVdev)
            vdev.root = self.root
            vdev.zpool = self
            vdev.nvlist = <NVList>vdev_tree
            return vdev

    def __retrieve_vdevs(self, vdev_type):
        IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
            valid_vdev_types = ('data', 'log', 'spare', 'cache', 'special', 'dedup')
        ELSE:
            valid_vdev_types = ('data', 'log', 'spare', 'cache')
        assert vdev_type in valid_vdev_types

        cdef ZFSVdev vdev
        cdef NVList vdev_tree = self.get_raw_config().get_raw(zfs.ZPOOL_CONFIG_VDEV_TREE)
        raw_value = None

        IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
            if vdev_type == 'special':
                raw_value = zfs.ZPOOL_CONFIG_CHILDREN
                valid_f = lambda c: c.get(zfs.ZPOOL_CONFIG_ALLOCATION_BIAS) == zfs.VDEV_ALLOC_BIAS_SPECIAL
            elif vdev_type == 'dedup':
                raw_value = zfs.ZPOOL_CONFIG_CHILDREN
                valid_f = lambda c: c.get(zfs.ZPOOL_CONFIG_ALLOCATION_BIAS) == zfs.VDEV_ALLOC_BIAS_DEDUP

        if vdev_type == 'data':
            raw_value = zfs.ZPOOL_CONFIG_CHILDREN
            IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
                valid_f = lambda c: zfs.ZPOOL_CONFIG_ALLOCATION_BIAS not in c
            ELSE:
                valid_f = lambda c: not c[zfs.ZPOOL_CONFIG_IS_LOG]
        elif vdev_type == 'log':
            raw_value = zfs.ZPOOL_CONFIG_CHILDREN
            IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
                valid_f = lambda c: (
                    c.get(zfs.ZPOOL_CONFIG_ALLOCATION_BIAS) == zfs.VDEV_ALLOC_BIAS_LOG or c[zfs.ZPOOL_CONFIG_IS_LOG]
                )
            ELSE:
                valid_f = lambda c: c[zfs.ZPOOL_CONFIG_IS_LOG]
        elif vdev_type == 'spare':
            raw_value = zfs.ZPOOL_CONFIG_SPARES
            valid_f = lambda c: c
        elif vdev_type == 'cache':
            raw_value = zfs.ZPOOL_CONFIG_L2CACHE
            valid_f = lambda c: c

        if raw_value not in vdev_tree:
            return

        for child in vdev_tree.get_raw(raw_value):
            if valid_f(child):
                vdev = ZFSVdev.__new__(ZFSVdev)
                vdev.root = self.root
                vdev.zpool = self
                vdev.nvlist = <NVList>child
                vdev.group = vdev_type
                yield vdev

    property data_vdevs:
        def __get__(self):
            return self.__retrieve_vdevs('data')

    property log_vdevs:
        def __get__(self):
            return self.__retrieve_vdevs('log')

    property cache_vdevs:
        def __get__(self):
            return self.__retrieve_vdevs('cache')

    property spare_vdevs:
        def __get__(self):
            return self.__retrieve_vdevs('spare')

    IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
        property special_vdevs:
            def __get__(self):
                return self.__retrieve_vdevs('special')

        property dedup_vdevs:
            def __get__(self):
                return self.__retrieve_vdevs('dedup')

    property groups:
        def __get__(self):
            groups = {
                'data': list(self.data_vdevs),
                'log': list(self.log_vdevs),
                'cache': list(self.cache_vdevs),
                'spare': list(self.spare_vdevs),
            }
            IF HAVE_ZPOOL_CONFIG_ALLOCATION_BIAS:
                groups.update({
                    'special': list(self.special_vdevs),
                    'dedup': list(self.dedup_vdevs),
                })
            return groups

    property name:
        def __get__(self):
            return libzfs.zpool_get_name(self.handle)

    property guid:
        def __get__(self):
            return self.config[zfs.ZPOOL_CONFIG_POOL_GUID]

    property hostname:
        def __get__(self):
            return self.config.get(zfs.ZPOOL_CONFIG_HOSTNAME)

    property state:
        def __get__(self):
            return PoolState(self.config[zfs.ZPOOL_CONFIG_POOL_STATE])

    property status:
        def __get__(self):
            stats = self.config[zfs.ZPOOL_CONFIG_VDEV_TREE][zfs.ZPOOL_CONFIG_VDEV_STATS]
            return libzfs.zpool_state_to_name(stats[1], stats[2])

    property status_code:
        def __get__(self):
            cdef char* msg_id
            if self.handle != NULL:
                IF HAVE_ZPOOL_GET_STATUS == 3:
                    return PoolStatus(libzfs.zpool_get_status(self.handle, <const char**>&msg_id, NULL))
                ELSE:
                    return PoolStatus(libzfs.zpool_get_status(self.handle, <const char**>&msg_id))

    def __warning_statuses(self):
        return [
            PoolStatus.RESILVERING,
            PoolStatus.VERSION_OLDER,
            PoolStatus.FEAT_DISABLED,
            PoolStatus.NON_NATIVE_ASHIFT,
        ]

    property healthy:
        def __get__(self):
            return self.status_code in [PoolStatus.OK, PoolStatus.INCOMPATIBLE_FEAT] + self.__warning_statuses()

    property warning:
        def __get__(self):
            return self.status_code in self.__warning_statuses()

    def __unsup_features(self):
        try:
            nvinfo = self.get_raw_config()[zfs.ZPOOL_CONFIG_LOAD_INFO]
            return dict(nvinfo[zfs.ZPOOL_CONFIG_UNSUP_FEAT])
        except (KeyError, ValueError) as e:
            return str(e)

    property status_detail:
        def __get__(self):
            code = self.status_code
            if code is None:
                return None

            # https://github.com/openzfs/zfs/blob/master/cmd/zpool/zpool_main.c, `switch (reason)`
            status_mapping = {
                PoolStatus.MISSING_DEV_R: 'One or more devices could not be opened. Sufficient replicas exist for '
                                          'the pool to continue functioning in a degraded state.',
                PoolStatus.MISSING_DEV_NR: 'One or more devices could not be opened. There are insufficient '
                                           'replicas for the pool to continue functioning.',
                PoolStatus.CORRUPT_LABEL_R: 'One or more devices could not be used because the label is missing or '
                                            'invalid. Sufficient replicas exist for the pool to continue functioning '
                                            'in a degraded state.',
                PoolStatus.CORRUPT_LABEL_NR: 'One or more devices could not be used because the label is missing '
                                             'or invalid. There are insufficient replicas for the pool to continue '
                                             'functioning.',
                PoolStatus.FAILING_DEV: 'One or more devices has experienced an unrecoverable error. An attempt was '
                                        'made to correct the error. Applications are unaffected.',
                PoolStatus.OFFLINE_DEV: 'One or more devices has been taken offline by the administrator. Sufficient '
                                        'replicas exist for the pool to continue functioning in a degraded state.',
                PoolStatus.REMOVED_DEV: 'One or more devices has been removed by the administrator. Sufficient '
                                        'replicas exist for the pool to continue functioning in a degraded state.',
                PoolStatus.RESILVERING: 'One or more devices is currently being resilvered. The pool will continue '
                                        'to function, possibly in a degraded state.',
                PoolStatus.CORRUPT_DATA: 'One or more devices has experienced an error resulting in data '
                                         'corruption. Applications may be affected.',
                PoolStatus.CORRUPT_POOL: 'The pool metadata is corrupted and the pool cannot be opened.',
                PoolStatus.VERSION_OLDER: 'The pool is formatted using a legacy on-disk format. The pool can still '
                                          'be used, but some features are unavailable.',
                PoolStatus.VERSION_NEWER: 'The pool has been upgraded to a newer, incompatible on-disk version. '
                                          'The pool cannot be accessed on this system.',
                PoolStatus.FEAT_DISABLED: 'Some supported features are not enabled on the pool. The pool can still '
                                          'be used, but some features are unavailable.',
                PoolStatus.UNSUP_FEAT_READ: 'The pool cannot be accessed on this system because it uses the following '
                                            f'feature(s) not supported on this system: {self.__unsup_features()}',
                PoolStatus.UNSUP_FEAT_WRITE: 'The pool can only be accessed in read-only mode on this system. It '
                                             'cannot be accessed in read-write mode because it uses the following '
                                             f'feature(s) not supported on this system: {self.__unsup_features()}',
                PoolStatus.FAULTED_DEV_R: 'One or more devices are faulted in response to persistent errors. '
                                          'Sufficient replicas exist for the pool to continue functioning in a '
                                          'degraded state.',
                PoolStatus.FAULTED_DEV_NR: 'One or more devices are faulted in response to persistent errors. '
                                           'There are insufficient replicas for the pool to continue functioning.',
                PoolStatus.IO_FAILURE_MMP: 'The pool is suspended because multihost writes failed or were delayed; '
		                                'another system could import the pool undetected.',
                PoolStatus.IO_FAILURE_WAIT: 'One or more devices are faulted in response to IO failures.',
                PoolStatus.IO_FAILURE_CONTINUE: 'One or more devices are faulted in response to IO failures.',
                PoolStatus.BAD_LOG: 'An intent log record could not be read. Waiting for administrator intervention '
                                    'to fix the faulted pool.',
                PoolStatus.NON_NATIVE_ASHIFT: 'One or more devices are configured to use a non-native block size. '
                                              'Expect reduced performance.',
                PoolStatus.HOSTID_MISMATCH: 'Mismatch between pool hostid and system hostid on imported pool. This '
                                            'pool was previously imported into a system with a different hostid, and '
                                            'then was verbatim imported into this system.',
            }
            IF HAVE_ZPOOL_STATUS_ERRATA:
                status_mapping[PoolStatus.ERRATA] = 'Errata detected.'
            IF HAVE_ZPOOL_STATUS_REBUILDING:
                status_mapping[PoolStatus.REBUILDING] = 'One or more devices is currently being resilvered. The pool '\
                                                        'will continue to function, possibly in a degraded state.'
            IF HAVE_ZPOOL_STATUS_REBUILD_SCRUB:
                status_mapping[PoolStatus.REBUILD_SCRUB] = 'One or more devices have been sequentially resilvered, '\
                                                           'scrubbing the pool is recommended.'
            IF HAVE_ZPOOL_STATUS_COMPATIBILITY_ERR:
                status_mapping[PoolStatus.COMPATIBILITY_ERR] = 'This pool has a compatibility list specified, but it '\
                                                               'could not be read/parsed at this time. The pool can '\
                                                               'still be used, but this should be investigated.'
            IF HAVE_ZPOOL_STATUS_INCOMPATIBLE_FEAT:
                status_mapping[PoolStatus.INCOMPATIBLE_FEAT] = 'One or more features are enabled on the pool despite '\
                                                               'not being requested by the \'compatibility\' property.'
            return status_mapping.get(code.value)

    property error_count:
        def __get__(self):
            return self.config.get(zfs.ZPOOL_CONFIG_ERRCOUNT)

    property config:
        def __get__(self):
            return dict(self.get_raw_config())

    property properties:
        def __get__(self):
            cdef ZPoolProperty prop
            proptypes = []
            result = {}

            with nogil:
                libzfs.zprop_iter(self.__iterate_props, <void*>proptypes, True, True, zfs.ZFS_TYPE_POOL)

            for x in proptypes:
                prop = ZPoolProperty.__new__(ZPoolProperty)
                prop.pool = self
                prop.propid = x
                result[prop.name] = prop

            return result

    property features:
        def __get__(self):
            cdef ZPoolFeature f
            cdef NVList features_nv
            cdef zfs.zfeature_info_t* feat
            cdef uintptr_t nvl

            if self.status == 'UNAVAIL':
                return

            with nogil:
                nvl = <uintptr_t>libzfs.zpool_get_features(self.handle)

            features_nv = NVList(nvl)

            for i in range(0, zfs.SPA_FEATURES):
                feat = &zfs.spa_feature_table[i]
                f = ZPoolFeature.__new__(ZPoolFeature)
                f.feature = feat
                f.pool = self
                f.nvlist = features_nv
                yield f

    property disks:
        def __get__(self):
            result = []
            for g in self.groups.values():
                for v in g:
                    result += v.disks

            return result

    property scrub:
        def __get__(self):
            return ZPoolScrub(self.root, self)

    IF HAVE_LZC_WAIT:
        def wait(self, operation_type):
            if operation_type not in ZpoolWaitActivity.__members__:
                raise ZFSException(py_errno.EINVAL, 'Specify valid operation type for wait')
            return self._wait_impl(getattr(ZpoolWaitActivity, operation_type).value)

        def _wait_impl(self, operation_type):
            cdef int ret
            cdef zfs.zpool_wait_activity_t c_activity_type = ZpoolWaitActivity(int(operation_type))
            cdef const char * pool_name = self.name

            with nogil:
                ret = libzfs.lzc_wait(pool_name, c_activity_type, NULL)
            if ret != 0:
                raise OSError(ret, os.strerror(ret))

    IF HAVE_LZC_SYNC:
        def sync(self, force=False):
            cdef int ret
            cdef const char *c_name = self.name
            cdef NVList innvl = NVList()

            innvl["force"] = force
            with nogil:
                ret = libzfs.lzc_sync(c_name, innvl.handle, NULL)
            if ret != 0:
                raise OSError(ret, os.strerror(ret))

    cdef NVList get_raw_config(self):
        cdef uintptr_t nvl = <uintptr_t>libzfs.zpool_get_config(self.handle, NULL)
        return NVList(nvl)

    IF HAVE_ZFS_ENCRYPTION:
        @staticmethod
        def _encryption_common(fsopts):
            temp_file = None
            if fsopts.get('encryption', 'off') != 'off' and fsopts.get('keylocation', 'prompt') == 'prompt':
                if 'key' not in fsopts:
                    raise ZFSException(py_errno.EINVAL, 'Key must be supplied when key location is "prompt"')
                key = fsopts.pop('key')
                temp_file = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
                temp_file.write(key.encode() if isinstance(key, str) else key)
                temp_file.close()
                fsopts['keylocation'] = f'file://{temp_file.name}'
            return temp_file.name if temp_file else '', fsopts

    def create(self, name, fsopts, fstype=DatasetType.FILESYSTEM, sparse_vol=False, create_ancestors=False):
        cdef NVList cfsopts
        cdef uint64_t vol_reservation, vol_size
        cdef const char *c_name = name
        cdef zfs.zfs_type_t c_fstype = <zfs.zfs_type_t>fstype
        cdef int ret
        #cdef char[1024] msg
        #cdef nvpair.nvlist_t *nvlist

        # FIXME: for some reason it complains volsize is not valid property for VOLUME
        #nvlist = libzfs.zfs_valid_proplist(self.root.handle, 4, cfsopts.handle, 0, NULL, self.handle, msg)
        #if nvlist == NULL:
        #    raise self.root.get_error()

        # refreservation will not be set correctly if volblocksize is not an integer
        # making change of volsize not work afterwards
        for i in ('volsize', 'volblocksize'):
            if i not in fsopts:
                continue
            value = fsopts[i]
            if isinstance(value, str):
                fsopts[i] = nicestrtonum(self.root, value)

        temp_file = None
        IF HAVE_ZFS_ENCRYPTION:
            temp_file, fsopts = self._encryption_common(fsopts)

        try:
            cfsopts = NVList(otherdict=fsopts)

            if fstype == DatasetType.VOLUME and not sparse_vol:
                vol_size = cfsopts['volsize']
                with nogil:
                    IF HAVE_ZVOLSIZE_TO_RESERVATION_PARAMS == 3:
                        vol_reservation = libzfs.zvol_volsize_to_reservation(self.handle, vol_size, cfsopts.handle)
                    ELSE:
                        vol_reservation = libzfs.zvol_volsize_to_reservation(vol_size, cfsopts.handle)

                cfsopts['refreservation'] = vol_reservation

            if create_ancestors:
                with nogil:
                    ret = libzfs.zfs_create_ancestors(
                        self.root.handle,
                        c_name
                    )
                if ret != 0:
                    raise self.root.get_error()

            with nogil:
                ret = libzfs.zfs_create(
                    self.root.handle,
                    c_name,
                    c_fstype,
                    cfsopts.handle
                )
        finally:
            if os.path.exists(temp_file or ''):
                os.unlink(temp_file)

        if ret != 0:
            raise self.root.get_error()

        IF HAVE_ZFS_ENCRYPTION:
            if temp_file:
                ds = self.root.get_dataset(name)
                ds.properties['keylocation'].value = 'prompt'

        if self.root.history:
            hopts = self.root.generate_history_opts(fsopts, '-o')
            self.root.write_history('zfs create', hopts, name)

    def attach_vdevs(self, vdevs_tree, check_ashift=0):
        cdef const char *command = 'zpool add'
        cdef ZFSVdev vd = self.root.make_vdev_tree(vdevs_tree, {'ashift': self.properties['ashift'].parsed})
        cdef int ret
        cdef boolean_t ashift = check_ashift

        with nogil:
            ret = libzfs.zpool_add(self.handle, vd.nvlist.handle, ashift)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history(command, self.name, self.root.history_vdevs_list(vdevs_tree))

    def vdev_by_guid(self, guid):
        def search_vdev(vdev, g):
            if vdev.guid == g:
                return vdev

            for i in vdev.children:
                ret = search_vdev(i, g)
                if ret:
                    return ret

            return None

        if guid == self.root_vdev.guid:
            return self.root_vdev

        for g in (self.data_vdevs, self.cache_vdevs, self.log_vdevs, self.spare_vdevs):
            for i in g:
                ret = search_vdev(i, guid)
                if ret:
                    return ret

    def delete(self):
        cdef int ret

        with nogil:
            ret = libzfs.zpool_destroy(self.handle, "destroy")

        if ret != 0:
            raise self.root.get_error()

    def start_scrub(self):
        cdef int ret

        with nogil:
            IF HAVE_ZPOOL_SCAN == 3:
                ret = libzfs.zpool_scan(self.handle, zfs.POOL_SCAN_SCRUB, zfs.POOL_SCRUB_NORMAL)
            ELSE:
                ret = libzfs.zpool_scan(self.handle, zfs.POOL_SCAN_SCRUB)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zpool scrub', self.name)

    def stop_scrub(self):
        cdef int ret

        with nogil:
            IF HAVE_ZPOOL_SCAN == 3:
                ret = libzfs.zpool_scan(self.handle, zfs.POOL_SCAN_NONE, zfs.POOL_SCRUB_NORMAL)
            ELSE:
                ret = libzfs.zpool_scan(self.handle, zfs.POOL_SCAN_NONE)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zpool scrub -s', self.name)

    def clear(self):
        cdef NVList policy = NVList()
        cdef int ret
        IF HAVE_ZPOOL_LOAD_POLICY_T:
            policy[zfs.ZPOOL_LOAD_REWIND_POLICY] = zfs.ZPOOL_NO_REWIND
        ELIF HAVE_ZPOOL_REWIND_POLICY_T:
            policy[zfs.ZPOOL_REWIND_REQUEST] = zfs.ZPOOL_NO_REWIND

        with nogil:
            ret = libzfs.zpool_clear(self.handle, NULL, policy.handle)

        self.root.write_history('zpool clear', self.name)
        return ret == 0

    def upgrade(self):
        cdef int ret

        with nogil:
            ret = libzfs.zpool_upgrade(self.handle, zfs.SPA_VERSION)

        if ret != 0:
            raise self.root.get_error()

        for i in self.features:
            if i.state == FeatureState.DISABLED:
                i.enable()

        self.root.write_history('zpool upgrade', self.name)


cdef class ZFSImportablePool(ZFSPool):
    cdef NVList nvlist
    cdef public object name

    def __str__(self):
        return "<libzfs.ZFSImportablePool name '{0}' guid '{1}'>".format(self.name, self.guid)

    def __repr__(self):
        return str(self)

    property config:
        def __get__(self):
            return dict(self.nvlist)

    property properties:
        def __get__(self):
            return None

    property root_dataset:
        def __get__(self):
            return None

    property error_count:
        def __get__(self):
            return 0

    property features:
        def __get__(self):
            return None

    cdef NVList get_raw_config(self):
        return self.nvlist

    def create(self, *args, **kwargs):
        raise NotImplementedError()

    def destroy(self, name):
        raise NotImplementedError()

    def attach_vdev(self, vdev):
        raise NotImplementedError()


cdef class ZFSPropertyDict(dict):
    cdef ZFSObject parent
    cdef object props

    def __repr__(self):
        return '{' + ', '.join(["'{0}': {1}".format(k, repr(v)) for k, v in self.items()]) + '}'

    def refresh(self):
        cdef ZFSProperty prop
        cdef ZFSUserProperty userprop
        cdef nvpair.nvlist_t *nvlist

        proptypes = self.parent.root.proptypes[self.parent.type]
        self.props = {}

        with nogil:
            nvlist = libzfs.zfs_get_user_props(self.parent.handle)

        nvl = NVList(<uintptr_t>nvlist)

        for x in proptypes:
            prop = ZFSProperty.__new__(ZFSProperty)
            prop.dataset = self.parent
            prop.propid = x
            prop.refresh()
            self.props[prop.name] = prop

        for k, v in nvl.items():
            userprop = ZFSUserProperty.__new__(ZFSUserProperty)
            userprop.dataset = self.parent
            userprop.name = k
            userprop.values = v
            self.props[userprop.name] = userprop

    def __delitem__(self, key):
        if key not in self.props:
            raise KeyError(key)

        self.props[key].inherit(recursive=True)

    def __getitem__(self, item):
        return self.props[item]

    def __setitem__(self, key, value):
        cdef ZFSUserProperty userprop
        cdef int ret
        cdef const char *c_key
        cdef const char *c_value

        if type(value) is not ZFSUserProperty:
            raise ValueError('Value should be of type ZFSUserProperty')

        userprop = <ZFSUserProperty>value
        if userprop.dataset is None:
            # detached user property
            userprop.dataset = self.parent
            str_value = str(userprop.value).encode('utf-8')
            c_value = str_value
            c_key = key

            with nogil:
                ret = libzfs.zfs_prop_set(self.parent.handle, c_key, c_value)

            if ret != 0:
                raise self.parent.root.get_error()

        self.props[key] = userprop
        self.parent.root.write_history('zfs set', (str(key), str(userprop.value)), self.parent.name)

    def __iter__(self):
        for i in self.props:
            yield  i

    def get(self, k, d=None):
        return self.props.get(k, d)

    def setdefault(self, k, d=None):
        pass

    def keys(self):
        return self.props.keys()

    def values(self):
        return self.props.values()

    def iterkeys(self):
        return self.props.iterkeys()

    def itervalues(self):
        return self.props.itervalues()

    def has_key(self, key):
        return key in self.props

    def items(self):
        return self.props.items()

    def update(self, E=None, **F):
        raise NotImplementedError()

    def __contains__(self, key):
        return key in self.props


cdef class ZFSObject(object):
    cdef libzfs.zfs_handle_t* handle
    cdef readonly ZFS root
    cdef readonly ZFSPool pool

    def __init__(self):
        raise RuntimeError('ZFSObject cannot be instantiated by the user')

    def __dealloc__(self):
        if self.handle != NULL:
            with nogil:
                libzfs.zfs_close(self.handle)

    def __str__(self):
        return "<libzfs.{0} name '{1}' type '{2}'>".format(self.__class__.__name__, self.name, self.type.name)

    def __repr__(self):
        return str(self)

    def asdict(self):
        return {
            'id': self.name,
            'name': self.name,
            'pool': self.pool.name,
            'type': self.type.name,
            'properties': {k: p.asdict() for k, p in self.properties.items()},
        }

    property name:
        def __get__(self):
            return libzfs.zfs_get_name(self.handle)

    property type:
        def __get__(self):
            cdef zfs.zfs_type_t typ

            with nogil:
                typ = libzfs.zfs_get_type(self.handle)

            return DatasetType(typ)

    property properties:
        def __get__(self):
            cdef ZFSPropertyDict d

            d = ZFSPropertyDict.__new__(ZFSPropertyDict)
            d.parent = self
            d.refresh()
            return d

    def rename(self, new_name, nounmount=False, forceunmount=False, recursive=False):
        cdef const char *c_new_name = new_name
        cdef int ret

        IF HAVE_RENAMEFLAGS_T:
            cdef libzfs.renameflags_t flags
            IF HAVE_RENAMEFLAGS_T_RECURSE:
                flags.recurse = recursive
            ELSE:
                flags.recursive = recursive
            flags.nounmount = nounmount
            flags.forceunmount = forceunmount

            with nogil:
                IF HAVE_ZFS_RENAME == 4:
                    ret = libzfs.zfs_rename(self.handle, NULL, c_new_name, flags)
                ELSE:
                    ret = libzfs.zfs_rename(self.handle, c_new_name, flags)

            history = ['zfs rename', '-f' if forceunmount else '', '-u' if nounmount else '', self.name]

        ELSE:
            if nounmount:
                raise RuntimeError('nounmount option is not supported on this system')

            cdef boolean_t recursive_f = recursive
            cdef boolean_t force_unmount_f = forceunmount

            with nogil:
                ret = libzfs.zfs_rename(self.handle, c_new_name, recursive_f, force_unmount_f)

            history = ['zfs rename', '-f' if forceunmount else '', self.name]

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history(*history)

    def delete(self, bint defer=False):
        cdef int ret

        with nogil:
            ret = libzfs.zfs_destroy(self.handle, defer)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs destroy', self.name)

    def get_send_space(self, fromname=None):
        cdef const char *cfromname = fromname
        cdef const char *c_name = self.name
        cdef uint64_t space
        cdef int ret

        with nogil:
            IF HAVE_LZC_SEND_SPACE == 4:
                ret = libzfs.lzc_send_space(c_name, cfromname, 0, &space)
            ELSE:
                ret = libzfs.lzc_send_space(c_name, cfromname, &space)

        if ret != 0:
            raise ZFSException(Error.FAULT, "Cannot obtain space estimate: ")

        return space


cdef class ZFSResource(ZFSObject):

    @staticmethod
    cdef int __iterate(libzfs.zfs_handle_t* handle, void *arg) nogil:
        cdef iter_state *iter
        cdef iter_state new

        iter = <iter_state *>arg
        if iter.length == iter.alloc:
            new.alloc = iter.alloc + 128
            new.array = <uintptr_t *>realloc(iter.array, new.alloc * sizeof(uintptr_t))
            if not new.array:
                free(iter.array)
                raise MemoryError()

            iter.alloc = new.alloc
            iter.array = new.array

        iter.array[iter.length] = <uintptr_t>handle
        iter.length += 1

    def get_dependents(self, allow_recursion=False):
        cdef ZFSDataset dataset
        cdef ZFSSnapshot snapshot
        cdef zfs.zfs_type_t type
        cdef iter_state iter
        cdef int recursion = allow_recursion

        with nogil:
            iter.length = 0
            iter.array = <uintptr_t *>malloc(128 * sizeof(uintptr_t))
            if not iter.array:
                raise MemoryError()

            iter.alloc = 128
            ZFS.__iterate_dependents(self.handle, 0, recursion, self.__iterate, <void*>&iter)

        try:
            for h in range(0, iter.length):
                type = libzfs.zfs_get_type(<libzfs.zfs_handle_t*>iter.array[h])

                if type == zfs.ZFS_TYPE_FILESYSTEM or type == zfs.ZFS_TYPE_VOLUME:
                    dataset = ZFSDataset.__new__(ZFSDataset)
                    dataset.handle = <libzfs.zfs_handle_t*>iter.array[h]
                    iter.array[h] = 0
                    dataset.root = self.root
                    dataset.pool = self.pool
                    yield dataset

                if type == zfs.ZFS_TYPE_SNAPSHOT:
                    snapshot = ZFSSnapshot.__new__(ZFSSnapshot)
                    snapshot.handle = <libzfs.zfs_handle_t*>iter.array[h]
                    iter.array[h] = 0
                    snapshot.root = self.root
                    snapshot.pool = self.pool
                    yield snapshot
        finally:
            with nogil:
                for h in range(0, iter.length):
                    if iter.array[h]:
                        libzfs.zfs_close(<libzfs.zfs_handle_t*>iter.array[h])

                free(iter.array)

    def update_properties(self, all_properties):
        cdef NVList props = NVList()
        cdef int ret
        invalid_values = []
        for prop_name, prop_details in all_properties.items():
            cur_prop = self.properties.get(prop_name)
            if prop_details.get('source') == 'INHERIT' and cur_prop:
                cur_prop.inherit(recursive=prop_details.get('recursive', False))
            else:
                if 'value' in prop_details:
                    props[prop_name] = prop_details['value']
                elif 'parsed' in prop_details:
                    props[prop_name] = serialize_zfs_prop(prop_name, prop_details['parsed'])
                else:
                    invalid_values.append(prop_name)

        if invalid_values:
            raise ZFSException(Error.BADPROP, f'Malformed values provided for {", ".join(invalid_values)!r}')

        # we capture what the current self.root.errno is set to
        # because `self.root` is a readonly property defined in
        # the parent ZFS class. This means we can't overwrite it
        # by simply doing "self.root.errno = 0". It's important
        # that we capture the previous errno BEFORE calling
        # zfs_prop_set_list(). The reason why we do this is
        # because this python module allows users to instantiate
        # a "long-lived" handle on a zfs resource. If we don't
        # keep track of this errno, someone might fat-finger
        # updating a property of a zvol (for example). When that
        # happens, self.root.errno is set. However, if they try
        # to set the proper value after correcting the typo, they
        # will be presented with the errno that was set previously.
        # Here is an interactive python example showing the issue
        # >>> import libzfs
        # >>> zzzvol = libzfs.ZFS().get_object('dozer/zzzvol')
        # >>> zzzvol.update_properties({'volthreading': {'value': 'on'}})
        # >>> zzzvol.update_properties({'volthreading': {'value': 'o'}})
        # Traceback (most recent call last):
        #   File "<stdin>", line 1, in <module>
        #   File "libzfs.pyx", line 3743, in libzfs.ZFSResource.update_properties
        # libzfs.ZFSException: cannot set property for 'dozer/zzzvol': 'volthreading' must be one of 'on | off'
        # >>> zzzvol.update_properties({'volthreading': {'value': 'on'}})
        # Traceback (most recent call last):
        #   File "<stdin>", line 1, in <module>
        #   File "libzfs.pyx", line 3743, in libzfs.ZFSResource.update_properties
        # libzfs.ZFSException: cannot set property for 'dozer/zzzvol': 'volthreading' must be one of 'on | off'
        prev_errno = self.root.errno
        with nogil:
            ret = libzfs.zfs_prop_set_list(self.handle, props.handle)

        if ret != 0 or (prev_errno != self.root.errno and self.root.errno != 0):
            # setting the propert(y/ies) failed or
            # the propert(y/ies) was/were changed successfully
            # but the extended behavior that comes after failed
            # (i.e. sharenfs=on will update files in exports/conf.d
            #   which can fail for a myriad of reasons)
            raise self.root.get_error()

    @staticmethod
    cdef int _userspace_cb(void *data, const char *domain, uint32_t rid, uint64_t space) nogil:
        with gil:
            result = <list>data
            result.append({'domain': domain, 'rid': rid, 'space': space})

    def userspace(self, quota_props):
        results = {}
        for quota_prop in quota_props:
            prop: zfs.zfs_userquota_prop_t = quota_prop.value
            result = []
            with nogil:
                ret = libzfs.zfs_userspace(self.handle, prop, ZFSResource._userspace_cb, <void*>result)
            if ret:
                raise self.root.get_error()
            results[quota_prop] = result
        return results


cdef class ZFSDataset(ZFSResource):
    def asdict(self, recursive=True, snapshots=False, snapshots_recursive=False):
        ret = super(ZFSDataset, self).asdict()
        ret['mountpoint'] = self.mountpoint

        if recursive:
            ret['children'] = [i.asdict() for i in self.children]

        if snapshots:
            ret['snapshots'] = [s.asdict() for s in self.snapshots]

        if snapshots_recursive:
            ret['snapshots_recursive'] = [s.asdict() for s in self.snapshots_recursive]

        IF HAVE_ZFS_ENCRYPTION:
            root = self.encryption_root
            ret.update({
                'encrypted': self.encrypted,
                'encryption_root': root.name if root else None,
                'key_loaded': self.key_loaded
            })

        return ret

    @staticmethod
    cdef int __snapshots_callback(libzfs.zfs_handle_t * handle, void *arg) nogil:
        cdef const char *name = libzfs.zfs_get_name(handle)
        with gil:
            snap_config = <object> arg
            snap_config['snapshots'].append(name)
        libzfs.zfs_close(handle)

    @staticmethod
    cdef int __gather_snapshots(libzfs.zfs_handle_t * handle, void *arg) nogil:
        cdef char *spec_orig
        cdef int err

        with gil:
            snap_config = <object> arg
            spec_orig = snap_config['snapshot_specification']

        err = ZFS.__iterate_snapspec(handle, 0, spec_orig, ZFSDataset.__snapshots_callback, arg)

        with gil:
            if err not in (0, py_errno.ENOENT):
                snap_config['failure'] = True
            else:
                if snap_config['recursive']:
                    with nogil:
                        err = ZFS.__iterate_filesystems(handle, 0, ZFSDataset.__gather_snapshots, arg)
                    if err:
                        snap_config['failure'] = True

        libzfs.zfs_close(handle)


    def delete_snapshots(self, snapshots_spec):
        # We expect snapshots_spec to be a dict conforming to following valid formats
        # {"all": false, "snapshots": [snapname1, {"start": snap1, "end": snap2}]}
        cdef const char *c_name
        cdef libzfs.zfs_handle_t * handle
        cdef NVList snap_names

        snap_filter = '%' if snapshots_spec['all'] else ''
        invalid_snaps = []
        for snap_spec in filter(
            lambda v: any(k in v for k in ('start', 'end')) if isinstance(v, dict) else v, snapshots_spec['snapshots']
        ):
            if isinstance(snap_spec, str):
                cur_filter = snap_spec
            else:
                cur_filter = ''
                if snap_spec.get('start'):
                    cur_filter = snap_spec['start']
                    if not self.root.snapshots_serialized(['name'], datasets=[f'{self.name}@{snap_spec["start"]}']):
                        invalid_snaps.append(snap_spec['start'])
                cur_filter += '%'
                if snap_spec.get('end'):
                    cur_filter += snap_spec['end']
                    if not self.root.snapshots_serialized(['name'], datasets=[f'{self.name}@{snap_spec["end"]}']):
                        invalid_snaps.append(snap_spec['end'])

            snap_filter += f'{"," if snap_filter else ""}{cur_filter}'

        if invalid_snaps:
            raise ZFSException(py_errno.ENOENT, f'{", ".join(invalid_snaps)} snapshot(s) could not be located')

        name = self.name
        c_name = name
        snap_config = {
            'recursive': snapshots_spec.get('recursive', False),
            'failure': False,
            'snapshots': [],
            'snapshot_specification': snap_filter,
        }
        with nogil:
            handle = libzfs.zfs_open(self.root.handle, c_name, zfs.ZFS_TYPE_FILESYSTEM | zfs.ZFS_TYPE_VOLUME)

        if handle == NULL:
            raise ZFSException(py_errno.EFAULT, f'Unable to open zfs handle for {name!r} dataset')

        with nogil:
            ZFSDataset.__gather_snapshots(handle, <void*>snap_config)

        if snap_config['failure']:
            raise self.root.get_error()

        snap_names = NVList(otherdict={k: True for k in snap_config['snapshots']})
        with nogil:
            err = libzfs.zfs_destroy_snaps_nvl(self.root.handle, snap_names.handle, False)

        if err != 0:
            raise self.root.get_error()

        return snap_config['snapshots']

    property children:
        def __get__(self):
            cdef ZFSDataset dataset
            cdef iter_state iter

            datasets = []
            with nogil:
                iter.length = 0
                iter.array = <uintptr_t *>malloc(128 * sizeof(uintptr_t))
                if not iter.array:
                    raise MemoryError()

                iter.alloc = 128
                ZFS.__iterate_filesystems(self.handle, 0, self.__iterate, <void*>&iter)

            try:
                for h in range(0, iter.length):
                    dataset = ZFSDataset.__new__(ZFSDataset)
                    dataset.handle = <libzfs.zfs_handle_t*>iter.array[h]
                    iter.array[h] = 0
                    dataset.root = self.root
                    dataset.pool = self.pool
                    yield dataset
            finally:
                with nogil:
                    for h in range(0, iter.length):
                        if iter.array[h]:
                            libzfs.zfs_close(<libzfs.zfs_handle_t*>iter.array[h])

                    free(iter.array)

    property children_recursive:
        def __get__(self):
            for c in self.children:
                yield c
                for i in c.children_recursive:
                    yield i

    property snapshots:
        def __get__(self):
            cdef ZFSSnapshot snapshot
            cdef iter_state iter

            with nogil:
                iter.length = 0
                iter.array = <uintptr_t *>malloc(128 * sizeof(uintptr_t))
                if not iter.array:
                    raise MemoryError()

                iter.alloc = 128
                libzfs.zfs_iter_snapshots(self.handle, False, self.__iterate, <void*>&iter, 0, 0)

            try:
                for h in range(0, iter.length):
                    snapshot = ZFSSnapshot.__new__(ZFSSnapshot)
                    snapshot.handle = <libzfs.zfs_handle_t*>iter.array[h]
                    iter.array[h] = 0
                    snapshot.root = self.root
                    snapshot.pool = self.pool
                    if snapshot.snapshot_name == '$ORIGIN':
                        continue

                    yield snapshot
            finally:
                with nogil:
                    for h in range(0, iter.length):
                        if iter.array[h]:
                            libzfs.zfs_close(<libzfs.zfs_handle_t*>iter.array[h])

                    free(iter.array)

    property bookmarks:
        def __get__(self):
            cdef ZFSBookmark bookmark
            cdef iter_state iter

            with nogil:
                iter.length = 0
                iter.array = <uintptr_t *>malloc(128 * sizeof(uintptr_t))
                if not iter.array:
                    raise MemoryError()

                iter.alloc = 128
                ZFS.__iterate_bookmarks(self.handle, 0, self.__iterate, <void *>&iter)

            try:
                for b in range(0, iter.length):
                    bookmark = ZFSBookmark.__new__(ZFSBookmark)
                    bookmark.handle = <libzfs.zfs_handle_t*>iter.array[b]
                    iter.array[b] = 0
                    bookmark.root = self.root
                    bookmark.pool = self.pool
                    yield bookmark
            finally:
                with nogil:
                    for h in range(0, iter.length):
                        if iter.array[h]:
                            libzfs.zfs_close(<libzfs.zfs_handle_t*>iter.array[h])

                    free(iter.array)

    property snapshots_recursive:
        def __get__(self):
            for s in self.snapshots:
                yield s

            for c in self.children:
                for s in c.snapshots:
                    yield s
                for i in c.children_recursive:
                    for s in i.snapshots:
                        yield s

    property dependents:
        def __get__(self):
            return iter(self.get_dependents(False))

    property mountpoint:
        def __get__(self):
            cdef char *mntpt
            cdef int ret

            with nogil:
                ret = libzfs.zfs_is_mounted(self.handle, &mntpt)

            if ret == 0:
                return None

            result = str(mntpt)
            free(mntpt)
            return result

    IF HAVE_ZFS_ENCRYPTION:
        property encrypted:
            def __get__(self):
                return self.properties['encryption'].value != 'off'

        property key_location:
            def __get__(self):
                return self.properties['keylocation'].value

        property encryption_root:
            def __get__(self):
                root = self.properties['encryptionroot'].value
                if root == self.name:
                    return self
                else:
                    return self.root.get_dataset(root) if root else None

        property key_loaded:
            def __get__(self):
                return self.properties['keystatus'].value == 'available'

        cdef load_key_common(self, recursive=False, key_location=None, key=None, no_op=False):
            if recursive and (key_location or key):
                raise ZFSException(py_errno.EINVAL, 'Key location or key cannot be provided with recursive option')

            if key and key_location:
                raise ZFSException(py_errno.EINVAL, 'Key cannot be provided with key location')

            if not recursive and not key and not key_location and self.key_location == 'prompt':
                raise ZFSException(
                    py_errno.EINVAL, 'Key or key location must be provided as default key location is prompt'
                )

            cdef ZFSDataset dataset
            temp_file = None
            if key:
                temp_file = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
                temp_file.write(key.encode() if isinstance(key, str) else key)
                temp_file.close()
                key_location = temp_file.name

            cdef boolean_t noop = no_op
            cdef char *alt_keylocation = NULL
            try:
                if key_location:
                    if not urllib.parse.urlparse(key_location).scheme and os.path.exists(key_location):
                        key_location = f'file://{key_location}'
                    alt_keylocation = key_location

                failed = []
                tried = 0
                for child in itertools.chain([self], self.children_recursive if recursive else []):
                    if (
                        (
                            (child.encryption_root == child and not child.key_loaded) or (
                                child == self and not recursive
                            ) or no_op
                        )
                        and (child.key_location != 'prompt' or key_location)
                    ):
                        dataset = child
                        with nogil:
                            ret = libzfs.zfs_crypto_load_key(dataset.handle, noop, alt_keylocation)
                        if ret != 0:
                            failed.append(self.root.get_error())
                        tried += 1
            finally:
                if temp_file and os.path.exists(temp_file.name):
                    os.unlink(temp_file.name)

            self.root.write_history(
                'zfs load-key', '-r' if recursive else '', f'-L {key_location}' if key_location else '',
                '-n' if noop else '', self.name
            )

            if failed:
                message = '\n'.join(f'{e.code}{f": {e.args[0]}" if e.args else ""}' for e in failed)
                if recursive:
                    message += f'\n{tried - len(failed)}/{tried} key(s) successfully loaded'
                raise ZFSException(Error.CRYPTO_FAILED, message)

        def load_key(self, recursive=False, key=None, key_location=None):
            self.load_key_common(recursive, key_location, key, no_op=False)

        def check_key(self, key=None, key_location=None):
            try:
                self.load_key_common(False, key_location, key, no_op=True)
            except ZFSException:
                return False
            else:
                return True

        def unload_key(self, recursive=False):
            cdef ZFSDataset dataset
            failed = []
            tried = 0
            for child in itertools.chain([self], self.children_recursive if recursive else []):
                if (child.encryption_root == child and child.key_loaded) or (child == self and not recursive):
                    dataset = child
                    with nogil:
                        ret = libzfs.zfs_crypto_unload_key(dataset.handle)
                    if ret != 0:
                        failed.append(self.root.get_error())
                    tried += 1

            self.root.write_history('zfs unload-key', '-r' if recursive else '', self.name)

            if failed:
                message = '\n'.join(f'{e.code}{f": {e.args[0]}" if e.args else ""}' for e in failed)
                if recursive:
                    message += f'\n{tried - len(failed)}/{tried} key(s) successfully unloaded'
                raise ZFSException(Error.CRYPTO_FAILED, message)

        def change_key(self, props=None, load_key=False, inherit=False, key=None):
            if not self.encrypted:
                raise ZFSException(py_errno.EINVAL, f'{self.name} is not encrypted')

            props = props or {}
            if props and inherit:
                raise ZFSException(py_errno.EINVAL, 'Properties not allowed for inheriting')
            elif inherit:
                if self.encryption_root != self:
                    raise ZFSException(py_errno.EINVAL, f'{self.name} must be an encryption root to inherit')

            for k in props:
                if k not in ('keyformat', 'keylocation', 'pbkdf2iters'):
                    raise ZFSException(py_errno.EINVAL, f'{k} property not valid when changing key')
                elif k == 'keylocation' and not urllib.parse.urlparse(props[k]).scheme and os.path.exists(props[k]):
                    props[k] = f'file://{props[k]}'

            if key and props.get('keylocation') != 'prompt':
                raise ZFSException(py_errno.EINVAL, 'Key should not be provided if key location is not prompt.')
            elif props.get('keylocation') == 'prompt' and not key:
                raise ZFSException(py_errno.EINVAL, 'Key is required when keylocation is set to prompt')

            if load_key and not self.key_loaded:
                self.load_key()
                with nogil:
                    libzfs.zfs_refresh_properties(self.handle)

            key_file = None
            if key:
                key_file, props = ZFSPool._encryption_common({'encryption': 'on', 'key': key, **props})
                props.pop('encryption')

            cdef NVList c_props
            cdef boolean_t inherit_root
            try:
                c_props = NVList(otherdict=props)
                inherit_root = inherit

                with nogil:
                    ret = libzfs.zfs_crypto_rewrap(self.handle, c_props.handle, inherit_root)
            finally:
                if os.path.exists(key_file or ''):
                    os.unlink(key_file)

            self.root.write_history(
                'zfs change-key', '-i' if inherit else '', ' '.join(f'-o {k}={v}' for k, v in props.items()),
                '-l' if load_key else '', self.name
            )

            if ret != 0:
                raise self.root.get_error()
            elif key_file:
                self.properties['keylocation'].value = 'prompt'

    def destroy_snapshot(self, name, defer=True):
        cdef const char *c_name = name
        cdef int ret
        cdef int defer_deletion = defer

        with nogil:
            ret = libzfs.zfs_destroy_snaps(self.handle, c_name, defer_deletion)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs destroy', name)

    def mount(self):
        cdef int ret

        try:
            mounted = self.properties['mounted']
        except KeyError:
            # zvols don't have a mounted property
            return
        else:
            if mounted.value == 'no':
                with nogil:
                    ret = libzfs.zfs_mount(self.handle, NULL, 0)

                if ret != 0:
                    raise self.root.get_error()

                self.root.write_history('zfs mount', self.name)

    IF HAVE_ZFS_ENCRYPTION:
        def mount_recursive(self, ignore_errors=False, skip_unloaded_keys=True):
            return self._mount_recursive(ignore_errors, skip_unloaded_keys)
    ELSE:
        def mount_recursive(self, ignore_errors=False):
            return self._mount_recursive(ignore_errors, False)

    def _mount_recursive(self, ignore_errors, skip_unloaded_keys):
        if self.type != DatasetType.FILESYSTEM:
            return

        IF HAVE_ZFS_ENCRYPTION:
            if self.encrypted and not self.key_loaded and skip_unloaded_keys:
                return

        if self.properties['canmount'].value == 'on':
            try:
                self.mount()
            except:
                if not ignore_errors:
                    raise

        for i in self.children:
            i._mount_recursive(ignore_errors, skip_unloaded_keys)

    def umount(self, force=False):
        cdef int flags = 0
        cdef int ret

        if force:
            flags = zfs.MS_FORCE

        with nogil:
            ret = libzfs.zfs_unmountall(self.handle, flags)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs umount', '-f' if force else '', self.name)

    def umount_recursive(self, force=False):
        if self.type != DatasetType.FILESYSTEM:
            return

        self.umount(force)

        for i in self.children:
            i.umount_recursive(force)

    def send(self, fd, fromname=None, toname=None, flags=None):
        cdef int cfd = fd
        cdef int err
        cdef char *ctoname
        cdef char *cfromname = NULL
        cdef libzfs.sendflags_t cflags

        if isinstance(flags, set) is False:
            flags = set()

        memset(&cflags, 0, cython.sizeof(libzfs.sendflags_t))

        if isinstance(toname, str) is False:
            raise ValueError('toname argument is required')

        ctoname = toname

        if fromname:
            cfromname = fromname

        if flags:
            convert_sendflags(flags, &cflags)

        with nogil:
            err = libzfs.zfs_send(self.handle, cfromname, ctoname, &cflags, cfd, NULL, NULL, NULL)

        if err != 0:
            raise self.root.get_error()

    def promote(self):
        cdef int ret

        with nogil:
            ret = libzfs.zfs_promote(self.handle)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs promote', self.name)

    def snapshot(self, name, fsopts=None, recursive=False):
        cdef NVList cfsopts = NVList(otherdict=fsopts or {})
        cdef const char *c_name = name
        cdef int c_recursive = recursive
        cdef int ret

        with nogil:
            ret = libzfs.zfs_snapshot(
                self.root.handle,
                c_name,
                c_recursive,
                cfsopts.handle
            )

        if ret != 0:
            raise self.root.get_error()

        if self.root.history:
            hfsopts = self.root.generate_history_opts(fsopts, '-o')
            self.root.write_history('zfs snapshot', '-r' if recursive else '', hfsopts, name)

    def receive(self, fd, force=False, nomount=False, resumable=False, props=None, limitds=None):
        self.root.receive(
            self.name,
            fd,
            force=force,
            nomount=nomount,
            resumable=resumable,
            props=props,
            limitds=limitds
        )

    def diff(self, fromsnap, tosnap):
        cdef char *c_fromsnap = fromsnap
        cdef char *c_tosnap = tosnap
        cdef int c_flags = libzfs.ZFS_DIFF_PARSEABLE | libzfs.ZFS_DIFF_TIMESTAMP | libzfs.ZFS_DIFF_CLASSIFY
        ret = None

        def worker(fd):
            cdef int c_fd = fd
            cdef int c_ret
            nonlocal ret

            with nogil:
                c_ret = libzfs.zfs_show_diffs(self.handle, c_fd, c_fromsnap, c_tosnap, c_flags)

            ret = c_ret

        rfd, wfd = os.pipe()
        thr = threading.Thread(target=worker, args=(wfd,), daemon=True)
        thr.start()

        with os.fdopen(rfd, 'r') as f:
            for line in f:
                yield DiffRecord(raw=line)

        thr.join()

        if ret != 0:
            raise self.root.get_error()


cdef class ZFSSnapshot(ZFSResource):
    def asdict(self):
        ret = super(ZFSSnapshot, self).asdict()
        ret.update({
            'holds': self.holds,
            'dataset': self.parent.name,
            'snapshot_name': self.snapshot_name,
            'mountpoint': self.mountpoint
        })
        return ret

    property dependents:
        def __get__(self):
            return iter(self.get_dependents(True))

    def rollback(self, force=False):
        cdef ZFSDataset parent
        cdef int c_force = force
        cdef int ret

        parent = <ZFSDataset>self.parent

        with nogil:
            ret = libzfs.zfs_rollback(parent.handle, self.handle, c_force)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs rollback', '-f' if force else '', self.name)

    IF HAVE_LZC_BOOKMARK:
        def bookmark(self, name):
            cdef NVList bookmarks
            cdef nvpair.nvlist_t *c_bookmarks
            cdef int ret

            bookmarks = NVList()
            bookmarks['{0}#{1}'.format(self.parent.name, name)] = self.name
            c_bookmarks = bookmarks.handle

            with nogil:
                ret = libzfs.lzc_bookmark(c_bookmarks, NULL)

            if ret != 0:
                raise OSError(ret, os.strerror(ret))

    def clone(self, name, opts=None):
        cdef NVList copts = None
        cdef nvpair.nvlist_t *copts_handle = NULL
        cdef const char *c_name = name
        cdef int ret

        if opts:
            copts = NVList(otherdict=opts)
            copts_handle = copts.handle

        with nogil:
            ret = libzfs.zfs_clone(
                self.handle,
                c_name,
                copts_handle
            )

        if ret != 0:
            raise self.root.get_error()

        if self.root.history:
            hopts = self.root.generate_history_opts(opts, '-o')
            self.root.write_history('zfs clone', hopts, self.name)

    def hold(self, tag, recursive=False):
        cdef ZFSDataset parent
        cdef const char *c_snapshot_name
        cdef const char *c_tag = tag
        cdef int c_recursive = recursive
        cdef int ret

        snapshot_name = self.snapshot_name
        c_snapshot_name = snapshot_name
        parent = <ZFSDataset>self.parent

        with nogil:
            ret = libzfs.zfs_hold(parent.handle, c_snapshot_name, c_tag, c_recursive, -1)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs hold', '-r' if recursive else '', tag, self.name)

    def release(self, tag, recursive=False):
        cdef ZFSDataset parent
        cdef const char *c_snapshot_name
        cdef const char *c_tag = tag
        cdef int c_recursive = recursive
        cdef int ret

        snapshot_name = self.snapshot_name
        c_snapshot_name = snapshot_name
        parent = <ZFSDataset>self.parent

        with nogil:
            ret = libzfs.zfs_release(parent.handle, c_snapshot_name, c_tag, c_recursive)

        if ret != 0:
            raise self.root.get_error()

        self.root.write_history('zfs release', '-r' if recursive else '', tag, self.name)

    def delete(self, recursive=False, defer=False, recursive_children=False):
        dependents = list(self.dependents)
        if not recursive and not recursive_children:
            if dependents and not defer:
                raise ZFSException(1, f'Cannot destroy {self.name}: snapshot has dependent clones')
            super(ZFSSnapshot, self).delete(defer=defer)
        elif recursive_children:
            for dep in dependents:
                if isinstance(dep, ZFSDataset) and dep.mountpoint:
                    dep.umount(True)
                dep.delete()
            self.delete()
        else:
            self.parent.destroy_snapshot(self.snapshot_name, defer)

        cmd = 'zfs destroy'
        if recursive_children:
            cmd += ' -R'
        elif recursive:
            cmd += ' -r'

        self.root.write_history(cmd, '-d' if defer and not recursive_children else '', self.name)

    def send(self, fd, fromname=None, flags=None):
        if isinstance(flags, set) is False:
            flags = set()
        return self.parent.send(fd, toname=self.snapshot_name, fromname=fromname, flags=flags)

    property snapshot_name:
        def __get__(self):
            return self.name.partition('@')[-1]

    property parent:
        def __get__(self):
            return self.root.get_dataset(self.name.partition('@')[0])

    property holds:
        def __get__(self):
            cdef nvpair.nvlist_t* ptr
            cdef NVList nvl
            cdef int ret

            with nogil:
                ret = libzfs.zfs_get_holds(self.handle, &ptr)

            if ret != 0:
                raise self.root.get_error()

            retval = dict(NVList(<uintptr_t>ptr))
            with nogil:
                nvpair.nvlist_free(ptr)
            return retval

    property mountpoint:
        def __get__(self):
            cdef char *mntpt
            cdef int ret

            with nogil:
                ret = libzfs.zfs_is_mounted(self.handle, &mntpt)

            if ret == 0:
                return None

            result = str(mntpt)
            free(mntpt)
            return result

    def get_send_progress(self, fd):
        IF HAVE_ZFS_IOCTL_HEADER:
            cdef zfs.zfs_cmd_t cmd
            memset(&cmd, 0, cython.sizeof(zfs.zfs_cmd_t))

            cdef int ret

            cmd.zc_cookie = fd
            strncpy(cmd.zc_name, self.name, zfs.MAXPATHLEN)

            with nogil:
                ret = libzfs.zfs_ioctl(self.root.handle, zfs.ZFS_IOC_SEND_PROGRESS, &cmd)

            if ret != 0:
                raise ZFSException(Error.FAULT, "Cannot obtain send progress")

            return cmd.zc_cookie
        ELSE:
            raise NotImplementedError()

cdef class ZFSBookmark(ZFSObject):
    def asdict(self):
        ret = super(ZFSBookmark, self).asdict()
        ret.update({
            'dataset': self.parent.name,
            'bookmark_name': self.bookmark_name
        })
        return ret

    property parent:
        def __get__(self):
            return self.root.get_dataset(self.name.partition('#')[0])

    property bookmark_name:
        def __get__(self):
            return self.name.partition('#')[-1]


cdef convert_sendflags(flags, libzfs.sendflags_t *cflags):
    if not isinstance(flags, set):
        raise ValueError('flags must be passed as a set')

    IF HAVE_SENDFLAGS_T_VERBOSITY:
         if SendFlag.VERBOSITY in flags:
            cflags.verbosity = 1
    ELSE:
        if SendFlag.VERBOSE in flags:
            cflags.verbose = 1

    if SendFlag.REPLICATE in flags:
        cflags.replicate = 1

    if SendFlag.DOALL in flags:
        cflags.doall = 1

    if SendFlag.FROMORIGIN in flags:
        cflags.fromorigin = 1

    IF HAVE_SENDFLAGS_T_DEDUP:
        if SendFlag.DEDUP in flags:
            cflags.dedup = 1

    if SendFlag.PROPS in flags:
        cflags.props = 1

    if SendFlag.DRYRUN in flags:
        cflags.dryrun = 1

    if SendFlag.PARSABLE in flags:
        cflags.parsable = 1

    if SendFlag.PROGRESS in flags:
        cflags.progress = 1

    if SendFlag.LARGEBLOCK in flags:
        cflags.largeblock = 1

    if SendFlag.EMBED_DATA in flags:
        cflags.embed_data = 1

    IF HAVE_SENDFLAGS_T_COMPRESS:
        if SendFlag.COMPRESS in flags:
            cflags.compress = 1

    IF HAVE_SENDFLAGS_T_RAW:
        if SendFlag.RAW in flags:
            cflags.raw = 1

    IF HAVE_SENDFLAGS_T_BACKUP:
        if SendFlag.BACKUP in flags:
            cflags.backup = 1

    IF HAVE_SENDFLAGS_T_HOLDS:
        if SendFlag.HOLDS in flags:
            cflags.holds = 1

    IF HAVE_SENDFLAGS_T_SAVED:
        if SendFlag.SAVED in flags:
            cflags.saved = 1

    IF HAVE_SENDFLAGS_T_PROGRESSASTITLE:
        if SendFlag.PROGRESSASTITLE in flags:
            cflags.progressastitle = 1


def nicestrtonum(ZFS zfs, value):
    cdef uint64_t result

    if libzfs.zfs_nicestrtonum(zfs.handle, value, &result) != 0:
        raise ValueError('Cannot convert {0} to integer'.format(value))

    return result


def read_label(device):
    cdef nvpair.nvlist_t *handle
    cdef NVList nvlist
    cdef char *buf
    cdef char *read
    cdef int ret

    fd = os.open(device, os.O_RDONLY)
    if fd < 0:
        raise OSError(errno, os.strerror(errno))

    st = os.fstat(fd)
    if not stat.S_ISCHR(st.st_mode):
        os.close(fd)
        raise OSError(errno.EINVAL, 'Not a character device')

    IF HAVE_ZPOOL_READ_LABEL_PARAMS == 3:
        ret = libzfs.zpool_read_label(fd, &handle, NULL)
    ELSE:
        ret = libzfs.zpool_read_label(fd, &handle)

    if ret != 0:
        os.close(fd)
        raise OSError(errno.EINVAL, 'Cannot read label')

    os.close(fd)
    retval = dict(NVList(<uintptr_t>handle))
    with nogil:
        nvpair.nvlist_free(handle)
    return retval


def clear_label(device):
    cdef int fd
    cdef int err

    fd = os.open(device, os.O_RDWR)
    if fd < 0:
        raise OSError(errno, f'Unable to open {device} for clearing label: {os.strerror(errno)}')

    with nogil:
        err = libzfs.zpool_clear_label(fd)

    if err != 0:
        os.close(fd)
        raise OSError(errno, f'Failed to clear zpool label for {device}: {os.strerror(errno)}')

    os.close(fd)