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

/*
 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 * Copyright (c) 2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
 * All rights reserved
 * Copyright (c) 2013 Steven Hartland. All rights reserved.
 * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
 * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
 * Copyright (c) 2019 Datto Inc.
 */

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <libintl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <stddef.h>
#include <fcntl.h>
#include <sys/mount.h>
#include <sys/mntent.h>
#include <sys/mnttab.h>
#include <sys/avl.h>
#include <sys/debug.h>
#include <sys/stat.h>
#include <stddef.h>
#include <pthread.h>
#include <umem.h>
#include <time.h>

#include <libzfs.h>
#include <libzfs_core.h>
#include <libzutil.h>

#include "zfs_namecheck.h"
#include "zfs_prop.h"
#include "zfs_fletcher.h"
#include "libzfs_impl.h"
#include <zlib.h>
#include <sys/zio_checksum.h>
#include <sys/dsl_crypt.h>
#include <sys/ddt.h>
#include <sys/socket.h>
#include <sys/sha2.h>

/* in libzfs_dataset.c */
extern void zfs_setprop_error(libzfs_handle_t *, zfs_prop_t, int, char *);

static int zfs_receive_impl(libzfs_handle_t *, const char *, const char *,
    recvflags_t *, int, const char *, nvlist_t *, avl_tree_t *, char **, int,
    uint64_t *, const char *, nvlist_t *);
static int guid_to_name_redact_snaps(libzfs_handle_t *hdl, const char *parent,
    uint64_t guid, boolean_t bookmark_ok, uint64_t *redact_snap_guids,
    uint64_t num_redact_snaps, char *name);
static int guid_to_name(libzfs_handle_t *, const char *,
    uint64_t, boolean_t, char *);

static const zio_cksum_t zero_cksum = { { 0 } };

typedef struct dedup_arg {
	int	inputfd;
	int	outputfd;
	libzfs_handle_t  *dedup_hdl;
} dedup_arg_t;

typedef struct progress_arg {
	zfs_handle_t *pa_zhp;
	int pa_fd;
	boolean_t pa_parsable;
	boolean_t pa_estimate;
	int pa_verbosity;
} progress_arg_t;

typedef struct dataref {
	uint64_t ref_guid;
	uint64_t ref_object;
	uint64_t ref_offset;
} dataref_t;

typedef struct dedup_entry {
	struct dedup_entry	*dde_next;
	zio_cksum_t dde_chksum;
	uint64_t dde_prop;
	dataref_t dde_ref;
} dedup_entry_t;

#define	MAX_DDT_PHYSMEM_PERCENT		20
#define	SMALLEST_POSSIBLE_MAX_DDT_MB		128

typedef struct dedup_table {
	dedup_entry_t	**dedup_hash_array;
	umem_cache_t	*ddecache;
	uint64_t	max_ddt_size;  /* max dedup table size in bytes */
	uint64_t	cur_ddt_size;  /* current dedup table size in bytes */
	uint64_t	ddt_count;
	int		numhashbits;
	boolean_t	ddt_full;
} dedup_table_t;

static int
high_order_bit(uint64_t n)
{
	int count;

	for (count = 0; n != 0; count++)
		n >>= 1;
	return (count);
}

static size_t
ssread(void *buf, size_t len, FILE *stream)
{
	size_t outlen;

	if ((outlen = fread(buf, len, 1, stream)) == 0)
		return (0);

	return (outlen);
}

static void
ddt_hash_append(libzfs_handle_t *hdl, dedup_table_t *ddt, dedup_entry_t **ddepp,
    zio_cksum_t *cs, uint64_t prop, dataref_t *dr)
{
	dedup_entry_t	*dde;

	if (ddt->cur_ddt_size >= ddt->max_ddt_size) {
		if (ddt->ddt_full == B_FALSE) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "Dedup table full.  Deduplication will continue "
			    "with existing table entries"));
			ddt->ddt_full = B_TRUE;
		}
		return;
	}

	if ((dde = umem_cache_alloc(ddt->ddecache, UMEM_DEFAULT))
	    != NULL) {
		assert(*ddepp == NULL);
		dde->dde_next = NULL;
		dde->dde_chksum = *cs;
		dde->dde_prop = prop;
		dde->dde_ref = *dr;
		*ddepp = dde;
		ddt->cur_ddt_size += sizeof (dedup_entry_t);
		ddt->ddt_count++;
	}
}

/*
 * Using the specified dedup table, do a lookup for an entry with
 * the checksum cs.  If found, return the block's reference info
 * in *dr. Otherwise, insert a new entry in the dedup table, using
 * the reference information specified by *dr.
 *
 * return value:  true - entry was found
 *		  false - entry was not found
 */
static boolean_t
ddt_update(libzfs_handle_t *hdl, dedup_table_t *ddt, zio_cksum_t *cs,
    uint64_t prop, dataref_t *dr)
{
	uint32_t hashcode;
	dedup_entry_t **ddepp;

	hashcode = BF64_GET(cs->zc_word[0], 0, ddt->numhashbits);

	for (ddepp = &(ddt->dedup_hash_array[hashcode]); *ddepp != NULL;
	    ddepp = &((*ddepp)->dde_next)) {
		if (ZIO_CHECKSUM_EQUAL(((*ddepp)->dde_chksum), *cs) &&
		    (*ddepp)->dde_prop == prop) {
			*dr = (*ddepp)->dde_ref;
			return (B_TRUE);
		}
	}
	ddt_hash_append(hdl, ddt, ddepp, cs, prop, dr);
	return (B_FALSE);
}

static int
dump_record(dmu_replay_record_t *drr, void *payload, int payload_len,
    zio_cksum_t *zc, int outfd)
{
	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
	fletcher_4_incremental_native(drr,
	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum), zc);
	if (drr->drr_type != DRR_BEGIN) {
		ASSERT(ZIO_CHECKSUM_IS_ZERO(&drr->drr_u.
		    drr_checksum.drr_checksum));
		drr->drr_u.drr_checksum.drr_checksum = *zc;
	}
	fletcher_4_incremental_native(&drr->drr_u.drr_checksum.drr_checksum,
	    sizeof (zio_cksum_t), zc);
	if (write(outfd, drr, sizeof (*drr)) == -1)
		return (errno);
	if (payload_len != 0) {
		fletcher_4_incremental_native(payload, payload_len, zc);
		if (write(outfd, payload, payload_len) == -1)
			return (errno);
	}
	return (0);
}

/*
 * This function is started in a separate thread when the dedup option
 * has been requested.  The main send thread determines the list of
 * snapshots to be included in the send stream and makes the ioctl calls
 * for each one.  But instead of having the ioctl send the output to the
 * the output fd specified by the caller of zfs_send()), the
 * ioctl is told to direct the output to a pipe, which is read by the
 * alternate thread running THIS function.  This function does the
 * dedup'ing by:
 *  1. building a dedup table (the DDT)
 *  2. doing checksums on each data block and inserting a record in the DDT
 *  3. looking for matching checksums, and
 *  4.  sending a DRR_WRITE_BYREF record instead of a write record whenever
 *      a duplicate block is found.
 * The output of this function then goes to the output fd requested
 * by the caller of zfs_send().
 */
static void *
cksummer(void *arg)
{
	dedup_arg_t *dda = arg;
	char *buf = zfs_alloc(dda->dedup_hdl, SPA_MAXBLOCKSIZE);
	dmu_replay_record_t thedrr = { 0 };
	dmu_replay_record_t *drr = &thedrr;
	FILE *ofp;
	int outfd;
	dedup_table_t ddt;
	zio_cksum_t stream_cksum;
	uint64_t numbuckets;

#ifdef _ILP32
	ddt.max_ddt_size = SMALLEST_POSSIBLE_MAX_DDT_MB << 20;
#else
	uint64_t physmem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);
	ddt.max_ddt_size =
	    MAX((physmem * MAX_DDT_PHYSMEM_PERCENT) / 100,
	    SMALLEST_POSSIBLE_MAX_DDT_MB << 20);
#endif

	numbuckets = ddt.max_ddt_size / (sizeof (dedup_entry_t));

	/*
	 * numbuckets must be a power of 2.  Increase number to
	 * a power of 2 if necessary.
	 */
	if (!ISP2(numbuckets))
		numbuckets = 1ULL << high_order_bit(numbuckets);

	ddt.dedup_hash_array = calloc(numbuckets, sizeof (dedup_entry_t *));
	ddt.ddecache = umem_cache_create("dde", sizeof (dedup_entry_t), 0,
	    NULL, NULL, NULL, NULL, NULL, 0);
	ddt.cur_ddt_size = numbuckets * sizeof (dedup_entry_t *);
	ddt.numhashbits = high_order_bit(numbuckets) - 1;
	ddt.ddt_full = B_FALSE;

	outfd = dda->outputfd;
	ofp = fdopen(dda->inputfd, "r");
	while (ssread(drr, sizeof (*drr), ofp) != 0) {

		/*
		 * kernel filled in checksum, we are going to write same
		 * record, but need to regenerate checksum.
		 */
		if (drr->drr_type != DRR_BEGIN) {
			bzero(&drr->drr_u.drr_checksum.drr_checksum,
			    sizeof (drr->drr_u.drr_checksum.drr_checksum));
		}

		switch (drr->drr_type) {
		case DRR_BEGIN:
		{
			struct drr_begin *drrb = &drr->drr_u.drr_begin;
			int fflags;
			int sz = 0;
			ZIO_SET_CHECKSUM(&stream_cksum, 0, 0, 0, 0);

			ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);

			/* set the DEDUP feature flag for this stream */
			fflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
			fflags |= (DMU_BACKUP_FEATURE_DEDUP |
			    DMU_BACKUP_FEATURE_DEDUPPROPS);
			DMU_SET_FEATUREFLAGS(drrb->drr_versioninfo, fflags);

			if (drr->drr_payloadlen != 0) {
				sz = drr->drr_payloadlen;

				if (sz > SPA_MAXBLOCKSIZE) {
					buf = zfs_realloc(dda->dedup_hdl, buf,
					    SPA_MAXBLOCKSIZE, sz);
				}
				(void) ssread(buf, sz, ofp);
				if (ferror(stdin))
					perror("fread");
			}
			if (dump_record(drr, buf, sz, &stream_cksum,
			    outfd) != 0)
				goto out;
			break;
		}

		case DRR_END:
		{
			struct drr_end *drre = &drr->drr_u.drr_end;
			/* use the recalculated checksum */
			drre->drr_checksum = stream_cksum;
			if (dump_record(drr, NULL, 0, &stream_cksum,
			    outfd) != 0)
				goto out;
			break;
		}

		case DRR_OBJECT:
		{
			struct drr_object *drro = &drr->drr_u.drr_object;
			if (drro->drr_bonuslen > 0) {
				(void) ssread(buf,
				    DRR_OBJECT_PAYLOAD_SIZE(drro), ofp);
			}
			if (dump_record(drr, buf, DRR_OBJECT_PAYLOAD_SIZE(drro),
			    &stream_cksum, outfd) != 0)
				goto out;
			break;
		}

		case DRR_SPILL:
		{
			struct drr_spill *drrs = &drr->drr_u.drr_spill;
			(void) ssread(buf, DRR_SPILL_PAYLOAD_SIZE(drrs), ofp);
			if (dump_record(drr, buf, DRR_SPILL_PAYLOAD_SIZE(drrs),
			    &stream_cksum, outfd) != 0)
				goto out;
			break;
		}

		case DRR_FREEOBJECTS:
		{
			if (dump_record(drr, NULL, 0, &stream_cksum,
			    outfd) != 0)
				goto out;
			break;
		}

		case DRR_WRITE:
		{
			struct drr_write *drrw = &drr->drr_u.drr_write;
			dataref_t	dataref;
			uint64_t	payload_size;

			payload_size = DRR_WRITE_PAYLOAD_SIZE(drrw);
			(void) ssread(buf, payload_size, ofp);

			/*
			 * Use the existing checksum if it's dedup-capable,
			 * else calculate a SHA256 checksum for it.
			 */

			if (ZIO_CHECKSUM_EQUAL(drrw->drr_key.ddk_cksum,
			    zero_cksum) ||
			    !DRR_IS_DEDUP_CAPABLE(drrw->drr_flags)) {
				SHA2_CTX ctx;
				zio_cksum_t tmpsha256;

				SHA2Init(SHA256, &ctx);
				SHA2Update(&ctx, buf, payload_size);
				SHA2Final(&tmpsha256, &ctx);

				drrw->drr_key.ddk_cksum.zc_word[0] =
				    BE_64(tmpsha256.zc_word[0]);
				drrw->drr_key.ddk_cksum.zc_word[1] =
				    BE_64(tmpsha256.zc_word[1]);
				drrw->drr_key.ddk_cksum.zc_word[2] =
				    BE_64(tmpsha256.zc_word[2]);
				drrw->drr_key.ddk_cksum.zc_word[3] =
				    BE_64(tmpsha256.zc_word[3]);
				drrw->drr_checksumtype = ZIO_CHECKSUM_SHA256;
				drrw->drr_flags |= DRR_CHECKSUM_DEDUP;
			}

			dataref.ref_guid = drrw->drr_toguid;
			dataref.ref_object = drrw->drr_object;
			dataref.ref_offset = drrw->drr_offset;

			if (ddt_update(dda->dedup_hdl, &ddt,
			    &drrw->drr_key.ddk_cksum, drrw->drr_key.ddk_prop,
			    &dataref)) {
				dmu_replay_record_t wbr_drr = {0};
				struct drr_write_byref *wbr_drrr =
				    &wbr_drr.drr_u.drr_write_byref;

				/* block already present in stream */
				wbr_drr.drr_type = DRR_WRITE_BYREF;

				wbr_drrr->drr_object = drrw->drr_object;
				wbr_drrr->drr_offset = drrw->drr_offset;
				wbr_drrr->drr_length = drrw->drr_logical_size;
				wbr_drrr->drr_toguid = drrw->drr_toguid;
				wbr_drrr->drr_refguid = dataref.ref_guid;
				wbr_drrr->drr_refobject =
				    dataref.ref_object;
				wbr_drrr->drr_refoffset =
				    dataref.ref_offset;

				wbr_drrr->drr_checksumtype =
				    drrw->drr_checksumtype;
				wbr_drrr->drr_flags = drrw->drr_flags;
				wbr_drrr->drr_key.ddk_cksum =
				    drrw->drr_key.ddk_cksum;
				wbr_drrr->drr_key.ddk_prop =
				    drrw->drr_key.ddk_prop;

				if (dump_record(&wbr_drr, NULL, 0,
				    &stream_cksum, outfd) != 0)
					goto out;
			} else {
				/* block not previously seen */
				if (dump_record(drr, buf, payload_size,
				    &stream_cksum, outfd) != 0)
					goto out;
			}
			break;
		}

		case DRR_WRITE_EMBEDDED:
		{
			struct drr_write_embedded *drrwe =
			    &drr->drr_u.drr_write_embedded;
			(void) ssread(buf,
			    P2ROUNDUP((uint64_t)drrwe->drr_psize, 8), ofp);
			if (dump_record(drr, buf,
			    P2ROUNDUP((uint64_t)drrwe->drr_psize, 8),
			    &stream_cksum, outfd) != 0)
				goto out;
			break;
		}

		case DRR_FREE:
		{
			if (dump_record(drr, NULL, 0, &stream_cksum,
			    outfd) != 0)
				goto out;
			break;
		}

		case DRR_OBJECT_RANGE:
		{
			if (dump_record(drr, NULL, 0, &stream_cksum,
			    outfd) != 0)
				goto out;
			break;
		}

		default:
			(void) fprintf(stderr, "INVALID record type 0x%x\n",
			    drr->drr_type);
			/* should never happen, so assert */
			assert(B_FALSE);
		}
	}
out:
	umem_cache_destroy(ddt.ddecache);
	free(ddt.dedup_hash_array);
	free(buf);
	(void) fclose(ofp);

	return (NULL);
}

/*
 * Routines for dealing with the AVL tree of fs-nvlists
 */
typedef struct fsavl_node {
	avl_node_t fn_node;
	nvlist_t *fn_nvfs;
	char *fn_snapname;
	uint64_t fn_guid;
} fsavl_node_t;

static int
fsavl_compare(const void *arg1, const void *arg2)
{
	const fsavl_node_t *fn1 = (const fsavl_node_t *)arg1;
	const fsavl_node_t *fn2 = (const fsavl_node_t *)arg2;

	return (TREE_CMP(fn1->fn_guid, fn2->fn_guid));
}

/*
 * Given the GUID of a snapshot, find its containing filesystem and
 * (optionally) name.
 */
static nvlist_t *
fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
{
	fsavl_node_t fn_find;
	fsavl_node_t *fn;

	fn_find.fn_guid = snapguid;

	fn = avl_find(avl, &fn_find, NULL);
	if (fn) {
		if (snapname)
			*snapname = fn->fn_snapname;
		return (fn->fn_nvfs);
	}
	return (NULL);
}

static void
fsavl_destroy(avl_tree_t *avl)
{
	fsavl_node_t *fn;
	void *cookie;

	if (avl == NULL)
		return;

	cookie = NULL;
	while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
		free(fn);
	avl_destroy(avl);
	free(avl);
}

/*
 * Given an nvlist, produce an avl tree of snapshots, ordered by guid
 */
static avl_tree_t *
fsavl_create(nvlist_t *fss)
{
	avl_tree_t *fsavl;
	nvpair_t *fselem = NULL;

	if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
		return (NULL);

	avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
	    offsetof(fsavl_node_t, fn_node));

	while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
		nvlist_t *nvfs, *snaps;
		nvpair_t *snapelem = NULL;

		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));

		while ((snapelem =
		    nvlist_next_nvpair(snaps, snapelem)) != NULL) {
			fsavl_node_t *fn;
			uint64_t guid;

			VERIFY(0 == nvpair_value_uint64(snapelem, &guid));
			if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
				fsavl_destroy(fsavl);
				return (NULL);
			}
			fn->fn_nvfs = nvfs;
			fn->fn_snapname = nvpair_name(snapelem);
			fn->fn_guid = guid;

			/*
			 * Note: if there are multiple snaps with the
			 * same GUID, we ignore all but one.
			 */
			if (avl_find(fsavl, fn, NULL) == NULL)
				avl_add(fsavl, fn);
			else
				free(fn);
		}
	}

	return (fsavl);
}

/*
 * Routines for dealing with the giant nvlist of fs-nvlists, etc.
 */
typedef struct send_data {
	/*
	 * assigned inside every recursive call,
	 * restored from *_save on return:
	 *
	 * guid of fromsnap snapshot in parent dataset
	 * txg of fromsnap snapshot in current dataset
	 * txg of tosnap snapshot in current dataset
	 */

	uint64_t parent_fromsnap_guid;
	uint64_t fromsnap_txg;
	uint64_t tosnap_txg;

	/* the nvlists get accumulated during depth-first traversal */
	nvlist_t *parent_snaps;
	nvlist_t *fss;
	nvlist_t *snapprops;
	nvlist_t *snapholds;	/* user holds */

	/* send-receive configuration, does not change during traversal */
	const char *fsname;
	const char *fromsnap;
	const char *tosnap;
	boolean_t recursive;
	boolean_t raw;
	boolean_t doall;
	boolean_t replicate;
	boolean_t verbose;
	boolean_t backup;
	boolean_t seenfrom;
	boolean_t seento;
	boolean_t holds;	/* were holds requested with send -h */
	boolean_t props;

	/*
	 * The header nvlist is of the following format:
	 * {
	 *   "tosnap" -> string
	 *   "fromsnap" -> string (if incremental)
	 *   "fss" -> {
	 *	id -> {
	 *
	 *	 "name" -> string (full name; for debugging)
	 *	 "parentfromsnap" -> number (guid of fromsnap in parent)
	 *
	 *	 "props" -> { name -> value (only if set here) }
	 *	 "snaps" -> { name (lastname) -> number (guid) }
	 *	 "snapprops" -> { name (lastname) -> { name -> value } }
	 *	 "snapholds" -> { name (lastname) -> { holdname -> crtime } }
	 *
	 *	 "origin" -> number (guid) (if clone)
	 *	 "is_encroot" -> boolean
	 *	 "sent" -> boolean (not on-disk)
	 *	}
	 *   }
	 * }
	 *
	 */
} send_data_t;

static void
send_iterate_prop(zfs_handle_t *zhp, boolean_t received_only, nvlist_t *nv);

static int
send_iterate_snap(zfs_handle_t *zhp, void *arg)
{
	send_data_t *sd = arg;
	uint64_t guid = zhp->zfs_dmustats.dds_guid;
	uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
	char *snapname;
	nvlist_t *nv;
	boolean_t isfromsnap, istosnap, istosnapwithnofrom;

	snapname = strrchr(zhp->zfs_name, '@')+1;
	isfromsnap = (sd->fromsnap != NULL &&
	    strcmp(sd->fromsnap, snapname) == 0);
	istosnap = (sd->tosnap != NULL && (strcmp(sd->tosnap, snapname) == 0));
	istosnapwithnofrom = (istosnap && sd->fromsnap == NULL);

	if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
		if (sd->verbose) {
			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
			    "skipping snapshot %s because it was created "
			    "after the destination snapshot (%s)\n"),
			    zhp->zfs_name, sd->tosnap);
		}
		zfs_close(zhp);
		return (0);
	}

	VERIFY(0 == nvlist_add_uint64(sd->parent_snaps, snapname, guid));
	/*
	 * NB: if there is no fromsnap here (it's a newly created fs in
	 * an incremental replication), we will substitute the tosnap.
	 */
	if (isfromsnap || (sd->parent_fromsnap_guid == 0 && istosnap)) {
		sd->parent_fromsnap_guid = guid;
	}

	if (!sd->recursive) {
		if (!sd->seenfrom && isfromsnap) {
			sd->seenfrom = B_TRUE;
			zfs_close(zhp);
			return (0);
		}

		if ((sd->seento || !sd->seenfrom) && !istosnapwithnofrom) {
			zfs_close(zhp);
			return (0);
		}

		if (istosnap)
			sd->seento = B_TRUE;
	}

	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
	send_iterate_prop(zhp, sd->backup, nv);
	VERIFY(0 == nvlist_add_nvlist(sd->snapprops, snapname, nv));
	nvlist_free(nv);
	if (sd->holds) {
		nvlist_t *holds = fnvlist_alloc();
		int err = lzc_get_holds(zhp->zfs_name, &holds);
		if (err == 0) {
			VERIFY(0 == nvlist_add_nvlist(sd->snapholds,
			    snapname, holds));
		}
		fnvlist_free(holds);
	}

	zfs_close(zhp);
	return (0);
}

static void
send_iterate_prop(zfs_handle_t *zhp, boolean_t received_only, nvlist_t *nv)
{
	nvlist_t *props = NULL;
	nvpair_t *elem = NULL;

	if (received_only)
		props = zfs_get_recvd_props(zhp);
	else
		props = zhp->zfs_props;

	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
		char *propname = nvpair_name(elem);
		zfs_prop_t prop = zfs_name_to_prop(propname);
		nvlist_t *propnv;

		if (!zfs_prop_user(propname)) {
			/*
			 * Realistically, this should never happen.  However,
			 * we want the ability to add DSL properties without
			 * needing to make incompatible version changes.  We
			 * need to ignore unknown properties to allow older
			 * software to still send datasets containing these
			 * properties, with the unknown properties elided.
			 */
			if (prop == ZPROP_INVAL)
				continue;

			if (zfs_prop_readonly(prop))
				continue;
		}

		verify(nvpair_value_nvlist(elem, &propnv) == 0);
		if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
		    prop == ZFS_PROP_REFQUOTA ||
		    prop == ZFS_PROP_REFRESERVATION) {
			char *source;
			uint64_t value;
			verify(nvlist_lookup_uint64(propnv,
			    ZPROP_VALUE, &value) == 0);
			if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
				continue;
			/*
			 * May have no source before SPA_VERSION_RECVD_PROPS,
			 * but is still modifiable.
			 */
			if (nvlist_lookup_string(propnv,
			    ZPROP_SOURCE, &source) == 0) {
				if ((strcmp(source, zhp->zfs_name) != 0) &&
				    (strcmp(source,
				    ZPROP_SOURCE_VAL_RECVD) != 0))
					continue;
			}
		} else {
			char *source;
			if (nvlist_lookup_string(propnv,
			    ZPROP_SOURCE, &source) != 0)
				continue;
			if ((strcmp(source, zhp->zfs_name) != 0) &&
			    (strcmp(source, ZPROP_SOURCE_VAL_RECVD) != 0))
				continue;
		}

		if (zfs_prop_user(propname) ||
		    zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
			char *value;
			verify(nvlist_lookup_string(propnv,
			    ZPROP_VALUE, &value) == 0);
			VERIFY(0 == nvlist_add_string(nv, propname, value));
		} else {
			uint64_t value;
			verify(nvlist_lookup_uint64(propnv,
			    ZPROP_VALUE, &value) == 0);
			VERIFY(0 == nvlist_add_uint64(nv, propname, value));
		}
	}
}

/*
 * returns snapshot creation txg
 * and returns 0 if the snapshot does not exist
 */
static uint64_t
get_snap_txg(libzfs_handle_t *hdl, const char *fs, const char *snap)
{
	char name[ZFS_MAX_DATASET_NAME_LEN];
	uint64_t txg = 0;

	if (fs == NULL || fs[0] == '\0' || snap == NULL || snap[0] == '\0')
		return (txg);

	(void) snprintf(name, sizeof (name), "%s@%s", fs, snap);
	if (zfs_dataset_exists(hdl, name, ZFS_TYPE_SNAPSHOT)) {
		zfs_handle_t *zhp = zfs_open(hdl, name, ZFS_TYPE_SNAPSHOT);
		if (zhp != NULL) {
			txg = zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG);
			zfs_close(zhp);
		}
	}

	return (txg);
}

/*
 * recursively generate nvlists describing datasets.  See comment
 * for the data structure send_data_t above for description of contents
 * of the nvlist.
 */
static int
send_iterate_fs(zfs_handle_t *zhp, void *arg)
{
	send_data_t *sd = arg;
	nvlist_t *nvfs = NULL, *nv = NULL;
	int rv = 0;
	uint64_t min_txg = 0, max_txg = 0;
	uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
	uint64_t fromsnap_txg_save = sd->fromsnap_txg;
	uint64_t tosnap_txg_save = sd->tosnap_txg;
	uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
	uint64_t guid = zhp->zfs_dmustats.dds_guid;
	uint64_t fromsnap_txg, tosnap_txg;
	char guidstring[64];

	fromsnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->fromsnap);
	if (fromsnap_txg != 0)
		sd->fromsnap_txg = fromsnap_txg;

	tosnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->tosnap);
	if (tosnap_txg != 0)
		sd->tosnap_txg = tosnap_txg;

	/*
	 * on the send side, if the current dataset does not have tosnap,
	 * perform two additional checks:
	 *
	 * - skip sending the current dataset if it was created later than
	 *   the parent tosnap
	 * - return error if the current dataset was created earlier than
	 *   the parent tosnap
	 */
	if (sd->tosnap != NULL && tosnap_txg == 0) {
		if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
			if (sd->verbose) {
				(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
				    "skipping dataset %s: snapshot %s does "
				    "not exist\n"), zhp->zfs_name, sd->tosnap);
			}
		} else {
			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
			    "cannot send %s@%s%s: snapshot %s@%s does not "
			    "exist\n"), sd->fsname, sd->tosnap, sd->recursive ?
			    dgettext(TEXT_DOMAIN, " recursively") : "",
			    zhp->zfs_name, sd->tosnap);
			rv = EZFS_NOENT;
		}
		goto out;
	}

	nvfs = fnvlist_alloc();
	fnvlist_add_string(nvfs, "name", zhp->zfs_name);
	fnvlist_add_uint64(nvfs, "parentfromsnap",
	    sd->parent_fromsnap_guid);

	if (zhp->zfs_dmustats.dds_origin[0]) {
		zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
		    zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
		if (origin == NULL) {
			rv = -1;
			goto out;
		}
		fnvlist_add_uint64(nvfs, "origin",
		    origin->zfs_dmustats.dds_guid);

		zfs_close(origin);
	}

	/* iterate over props */
	if (sd->props || sd->backup || sd->recursive) {
		nv = fnvlist_alloc();
		send_iterate_prop(zhp, sd->backup, nv);
	}
	if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF) {
		boolean_t encroot;

		/* determine if this dataset is an encryption root */
		if (zfs_crypto_get_encryption_root(zhp, &encroot, NULL) != 0) {
			rv = -1;
			goto out;
		}

		if (encroot)
			fnvlist_add_boolean(nvfs, "is_encroot");

		/*
		 * Encrypted datasets can only be sent with properties if
		 * the raw flag is specified because the receive side doesn't
		 * currently have a mechanism for recursively asking the user
		 * for new encryption parameters.
		 */
		if (!sd->raw) {
			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
			    "cannot send %s@%s: encrypted dataset %s may not "
			    "be sent with properties without the raw flag\n"),
			    sd->fsname, sd->tosnap, zhp->zfs_name);
			rv = -1;
			goto out;
		}

	}

	if (nv != NULL)
		fnvlist_add_nvlist(nvfs, "props", nv);

	/* iterate over snaps, and set sd->parent_fromsnap_guid */
	sd->parent_fromsnap_guid = 0;
	sd->parent_snaps = fnvlist_alloc();
	sd->snapprops = fnvlist_alloc();
	if (sd->holds)
		VERIFY(0 == nvlist_alloc(&sd->snapholds, NV_UNIQUE_NAME, 0));


	/*
	 * If this is a "doall" send, a replicate send or we're just trying
	 * to gather a list of previous snapshots, iterate through all the
	 * snaps in the txg range. Otherwise just look at the one we're
	 * interested in.
	 */
	if (sd->doall || sd->replicate || sd->tosnap == NULL) {
		if (!sd->replicate && fromsnap_txg != 0)
			min_txg = fromsnap_txg;
		if (!sd->replicate && tosnap_txg != 0)
			max_txg = tosnap_txg;
		(void) zfs_iter_snapshots_sorted(zhp, send_iterate_snap, sd,
		    min_txg, max_txg);
	} else {
		char snapname[MAXPATHLEN] = { 0 };
		zfs_handle_t *snap;

		(void) snprintf(snapname, sizeof (snapname), "%s@%s",
		    zhp->zfs_name, sd->tosnap);
		if (sd->fromsnap != NULL)
			sd->seenfrom = B_TRUE;
		snap = zfs_open(zhp->zfs_hdl, snapname,
		    ZFS_TYPE_SNAPSHOT);
		if (snap != NULL)
			(void) send_iterate_snap(snap, sd);
	}

	fnvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps);
	fnvlist_add_nvlist(nvfs, "snapprops", sd->snapprops);
	if (sd->holds)
		fnvlist_add_nvlist(nvfs, "snapholds", sd->snapholds);
	fnvlist_free(sd->parent_snaps);
	fnvlist_free(sd->snapprops);
	fnvlist_free(sd->snapholds);

	/* add this fs to nvlist */
	(void) snprintf(guidstring, sizeof (guidstring),
	    "0x%llx", (longlong_t)guid);
	fnvlist_add_nvlist(sd->fss, guidstring, nvfs);

	/* iterate over children */
	if (sd->recursive)
		rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);

out:
	sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
	sd->fromsnap_txg = fromsnap_txg_save;
	sd->tosnap_txg = tosnap_txg_save;
	fnvlist_free(nv);
	fnvlist_free(nvfs);

	zfs_close(zhp);
	return (rv);
}

static int
gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
    const char *tosnap, boolean_t recursive, boolean_t raw, boolean_t doall,
    boolean_t replicate, boolean_t verbose, boolean_t backup, boolean_t holds,
    boolean_t props, nvlist_t **nvlp, avl_tree_t **avlp)
{
	zfs_handle_t *zhp;
	send_data_t sd = { 0 };
	int error;

	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
	if (zhp == NULL)
		return (EZFS_BADTYPE);

	VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
	sd.fsname = fsname;
	sd.fromsnap = fromsnap;
	sd.tosnap = tosnap;
	sd.recursive = recursive;
	sd.raw = raw;
	sd.doall = doall;
	sd.replicate = replicate;
	sd.verbose = verbose;
	sd.backup = backup;
	sd.holds = holds;
	sd.props = props;

	if ((error = send_iterate_fs(zhp, &sd)) != 0) {
		nvlist_free(sd.fss);
		if (avlp != NULL)
			*avlp = NULL;
		*nvlp = NULL;
		return (error);
	}

	if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
		nvlist_free(sd.fss);
		*nvlp = NULL;
		return (EZFS_NOMEM);
	}

	*nvlp = sd.fss;
	return (0);
}

/*
 * Routines specific to "zfs send"
 */
typedef struct send_dump_data {
	/* these are all just the short snapname (the part after the @) */
	const char *fromsnap;
	const char *tosnap;
	char prevsnap[ZFS_MAX_DATASET_NAME_LEN];
	uint64_t prevsnap_obj;
	boolean_t seenfrom, seento, replicate, doall, fromorigin;
	boolean_t dryrun, parsable, progress, embed_data, std_out;
	boolean_t large_block, compress, raw, holds;
	int outfd;
	boolean_t err;
	nvlist_t *fss;
	nvlist_t *snapholds;
	avl_tree_t *fsavl;
	snapfilter_cb_t *filter_cb;
	void *filter_cb_arg;
	nvlist_t *debugnv;
	char holdtag[ZFS_MAX_DATASET_NAME_LEN];
	int cleanup_fd;
	int verbosity;
	uint64_t size;
} send_dump_data_t;

static int
zfs_send_space(zfs_handle_t *zhp, const char *snapname, const char *from,
    enum lzc_send_flags flags, uint64_t *spacep)
{
	libzfs_handle_t *hdl = zhp->zfs_hdl;
	int error;

	assert(snapname != NULL);
	error = lzc_send_space(snapname, from, flags, spacep);

	if (error != 0) {
		char errbuf[1024];
		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
		    "warning: cannot estimate space for '%s'"), snapname);

		switch (error) {
		case EXDEV:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "not an earlier snapshot from the same fs"));
			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));

		case ENOENT:
			if (zfs_dataset_exists(hdl, snapname,
			    ZFS_TYPE_SNAPSHOT)) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "incremental source (%s) does not exist"),
				    snapname);
			}
			return (zfs_error(hdl, EZFS_NOENT, errbuf));

		case EDQUOT:
		case EFBIG:
		case EIO:
		case ENOLINK:
		case ENOSPC:
		case ENOSTR:
		case ENXIO:
		case EPIPE:
		case ERANGE:
		case EFAULT:
		case EROFS:
		case EINVAL:
			zfs_error_aux(hdl, strerror(error));
			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));

		default:
			return (zfs_standard_error(hdl, error, errbuf));
		}
	}

	return (0);
}

/*
 * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
 * NULL) to the file descriptor specified by outfd.
 */
static int
dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
    boolean_t fromorigin, int outfd, enum lzc_send_flags flags,
    nvlist_t *debugnv)
{
	zfs_cmd_t zc = {"\0"};
	libzfs_handle_t *hdl = zhp->zfs_hdl;
	nvlist_t *thisdbg;

	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
	assert(fromsnap_obj == 0 || !fromorigin);

	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
	zc.zc_cookie = outfd;
	zc.zc_obj = fromorigin;
	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
	zc.zc_fromobj = fromsnap_obj;
	zc.zc_flags = flags;

	VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
	if (fromsnap && fromsnap[0] != '\0') {
		VERIFY(0 == nvlist_add_string(thisdbg,
		    "fromsnap", fromsnap));
	}

	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
		char errbuf[1024];
		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
		    "warning: cannot send '%s'"), zhp->zfs_name);

		VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
		if (debugnv) {
			VERIFY(0 == nvlist_add_nvlist(debugnv,
			    zhp->zfs_name, thisdbg));
		}
		nvlist_free(thisdbg);

		switch (errno) {
		case EXDEV:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "not an earlier snapshot from the same fs"));
			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));

		case EACCES:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "source key must be loaded"));
			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));

		case ENOENT:
			if (zfs_dataset_exists(hdl, zc.zc_name,
			    ZFS_TYPE_SNAPSHOT)) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "incremental source (@%s) does not exist"),
				    zc.zc_value);
			}
			return (zfs_error(hdl, EZFS_NOENT, errbuf));

		case EDQUOT:
		case EFBIG:
		case EIO:
		case ENOLINK:
		case ENOSPC:
		case ENOSTR:
		case ENXIO:
		case EPIPE:
		case ERANGE:
		case EFAULT:
		case EROFS:
			zfs_error_aux(hdl, strerror(errno));
			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));

		default:
			return (zfs_standard_error(hdl, errno, errbuf));
		}
	}

	if (debugnv)
		VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
	nvlist_free(thisdbg);

	return (0);
}

static void
gather_holds(zfs_handle_t *zhp, send_dump_data_t *sdd)
{
	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);

	/*
	 * zfs_send() only sets snapholds for sends that need them,
	 * e.g. replication and doall.
	 */
	if (sdd->snapholds == NULL)
		return;

	fnvlist_add_string(sdd->snapholds, zhp->zfs_name, sdd->holdtag);
}

int
zfs_send_progress(zfs_handle_t *zhp, int fd, uint64_t *bytes_written,
    uint64_t *blocks_visited)
{
	zfs_cmd_t zc = { {0} };
	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
	zc.zc_cookie = fd;
	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
		return (errno);
	if (bytes_written != NULL)
		*bytes_written = zc.zc_cookie;
	if (blocks_visited != NULL)
		*blocks_visited = zc.zc_objset_type;
	return (0);
}

static void *
send_progress_thread(void *arg)
{
	progress_arg_t *pa = arg;
	zfs_handle_t *zhp = pa->pa_zhp;
	uint64_t bytes;
	uint64_t blocks;
	char buf[16];
	time_t t;
	struct tm *tm;
	boolean_t firstloop = B_TRUE;

	/*
	 * Print the progress from ZFS_IOC_SEND_PROGRESS every second.
	 */
	for (;;) {
		int err;
		(void) sleep(1);
		if ((err = zfs_send_progress(zhp, pa->pa_fd, &bytes,
		    &blocks)) != 0) {
			if (err == EINTR || err == ENOENT)
				return ((void *)0);
			return ((void *)(uintptr_t)err);
		}

		if (firstloop && !pa->pa_parsable) {
			(void) fprintf(stderr,
			    "TIME       %s   %sSNAPSHOT %s\n",
			    pa->pa_estimate ? "BYTES" : " SENT",
			    pa->pa_verbosity >= 2 ? "   BLOCKS    " : "",
			    zhp->zfs_name);
			firstloop = B_FALSE;
		}

		(void) time(&t);
		tm = localtime(&t);

		if (pa->pa_verbosity >= 2 && pa->pa_parsable) {
			(void) fprintf(stderr,
			    "%02d:%02d:%02d\t%llu\t%llu\t%s\n",
			    tm->tm_hour, tm->tm_min, tm->tm_sec,
			    (u_longlong_t)bytes, (u_longlong_t)blocks,
			    zhp->zfs_name);
		} else if (pa->pa_verbosity >= 2) {
			zfs_nicenum(bytes, buf, sizeof (buf));
			(void) fprintf(stderr,
			    "%02d:%02d:%02d   %5s    %8llu    %s\n",
			    tm->tm_hour, tm->tm_min, tm->tm_sec,
			    buf, (u_longlong_t)blocks, zhp->zfs_name);
		} else if (pa->pa_parsable) {
			(void) fprintf(stderr, "%02d:%02d:%02d\t%llu\t%s\n",
			    tm->tm_hour, tm->tm_min, tm->tm_sec,
			    (u_longlong_t)bytes, zhp->zfs_name);
		} else {
			zfs_nicebytes(bytes, buf, sizeof (buf));
			(void) fprintf(stderr, "%02d:%02d:%02d   %5s   %s\n",
			    tm->tm_hour, tm->tm_min, tm->tm_sec,
			    buf, zhp->zfs_name);
		}
	}
}

static void
send_print_verbose(FILE *fout, const char *tosnap, const char *fromsnap,
    uint64_t size, boolean_t parsable)
{
	if (parsable) {
		if (fromsnap != NULL) {
			(void) fprintf(fout, "incremental\t%s\t%s",
			    fromsnap, tosnap);
		} else {
			(void) fprintf(fout, "full\t%s",
			    tosnap);
		}
	} else {
		if (fromsnap != NULL) {
			if (strchr(fromsnap, '@') == NULL &&
			    strchr(fromsnap, '#') == NULL) {
				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
				    "send from @%s to %s"),
				    fromsnap, tosnap);
			} else {
				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
				    "send from %s to %s"),
				    fromsnap, tosnap);
			}
		} else {
			(void) fprintf(fout, dgettext(TEXT_DOMAIN,
			    "full send of %s"),
			    tosnap);
		}
	}

	if (parsable) {
		(void) fprintf(fout, "\t%llu",
		    (longlong_t)size);
	} else if (size != 0) {
		char buf[16];
		zfs_nicebytes(size, buf, sizeof (buf));
		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
		    " estimated size is %s"), buf);
	}
	(void) fprintf(fout, "\n");
}

static int
dump_snapshot(zfs_handle_t *zhp, void *arg)
{
	send_dump_data_t *sdd = arg;
	progress_arg_t pa = { 0 };
	pthread_t tid;
	char *thissnap;
	enum lzc_send_flags flags = 0;
	int err;
	boolean_t isfromsnap, istosnap, fromorigin;
	boolean_t exclude = B_FALSE;
	FILE *fout = sdd->std_out ? stdout : stderr;

	err = 0;
	thissnap = strchr(zhp->zfs_name, '@') + 1;
	isfromsnap = (sdd->fromsnap != NULL &&
	    strcmp(sdd->fromsnap, thissnap) == 0);

	if (!sdd->seenfrom && isfromsnap) {
		gather_holds(zhp, sdd);
		sdd->seenfrom = B_TRUE;
		(void) strlcpy(sdd->prevsnap, thissnap,
		    sizeof (sdd->prevsnap));
		sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
		zfs_close(zhp);
		return (0);
	}

	if (sdd->seento || !sdd->seenfrom) {
		zfs_close(zhp);
		return (0);
	}

	istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
	if (istosnap)
		sdd->seento = B_TRUE;

	if (sdd->large_block)
		flags |= LZC_SEND_FLAG_LARGE_BLOCK;
	if (sdd->embed_data)
		flags |= LZC_SEND_FLAG_EMBED_DATA;
	if (sdd->compress)
		flags |= LZC_SEND_FLAG_COMPRESS;
	if (sdd->raw)
		flags |= LZC_SEND_FLAG_RAW;

	if (!sdd->doall && !isfromsnap && !istosnap) {
		if (sdd->replicate) {
			char *snapname;
			nvlist_t *snapprops;
			/*
			 * Filter out all intermediate snapshots except origin
			 * snapshots needed to replicate clones.
			 */
			nvlist_t *nvfs = fsavl_find(sdd->fsavl,
			    zhp->zfs_dmustats.dds_guid, &snapname);

			VERIFY(0 == nvlist_lookup_nvlist(nvfs,
			    "snapprops", &snapprops));
			VERIFY(0 == nvlist_lookup_nvlist(snapprops,
			    thissnap, &snapprops));
			exclude = !nvlist_exists(snapprops, "is_clone_origin");
		} else {
			exclude = B_TRUE;
		}
	}

	/*
	 * If a filter function exists, call it to determine whether
	 * this snapshot will be sent.
	 */
	if (exclude || (sdd->filter_cb != NULL &&
	    sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
		/*
		 * This snapshot is filtered out.  Don't send it, and don't
		 * set prevsnap_obj, so it will be as if this snapshot didn't
		 * exist, and the next accepted snapshot will be sent as
		 * an incremental from the last accepted one, or as the
		 * first (and full) snapshot in the case of a replication,
		 * non-incremental send.
		 */
		zfs_close(zhp);
		return (0);
	}

	gather_holds(zhp, sdd);
	fromorigin = sdd->prevsnap[0] == '\0' &&
	    (sdd->fromorigin || sdd->replicate);

	if (sdd->verbosity != 0) {
		uint64_t size = 0;
		char fromds[ZFS_MAX_DATASET_NAME_LEN];

		if (sdd->prevsnap[0] != '\0') {
			(void) strlcpy(fromds, zhp->zfs_name, sizeof (fromds));
			*(strchr(fromds, '@') + 1) = '\0';
			(void) strlcat(fromds, sdd->prevsnap, sizeof (fromds));
		}
		if (zfs_send_space(zhp, zhp->zfs_name,
		    sdd->prevsnap[0] ? fromds : NULL, flags, &size) != 0) {
			size = 0; /* cannot estimate send space */
		} else {
			send_print_verbose(fout, zhp->zfs_name,
			    sdd->prevsnap[0] ? sdd->prevsnap : NULL,
			    size, sdd->parsable);
		}
		sdd->size += size;
	}

	if (!sdd->dryrun) {
		/*
		 * If progress reporting is requested, spawn a new thread to
		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
		 */
		if (sdd->progress) {
			pa.pa_zhp = zhp;
			pa.pa_fd = sdd->outfd;
			pa.pa_parsable = sdd->parsable;
			pa.pa_estimate = B_FALSE;
			pa.pa_verbosity = sdd->verbosity;

			if ((err = pthread_create(&tid, NULL,
			    send_progress_thread, &pa)) != 0) {
				zfs_close(zhp);
				return (err);
			}
		}

		err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
		    fromorigin, sdd->outfd, flags, sdd->debugnv);

		if (sdd->progress) {
			void *status = NULL;
			(void) pthread_cancel(tid);
			(void) pthread_join(tid, &status);
			int error = (int)(uintptr_t)status;
			if (error != 0 && status != PTHREAD_CANCELED) {
				char errbuf[1024];
				(void) snprintf(errbuf, sizeof (errbuf),
				    dgettext(TEXT_DOMAIN,
				    "progress thread exited nonzero"));
				return (zfs_standard_error(zhp->zfs_hdl, error,
				    errbuf));
			}
		}
	}

	(void) strcpy(sdd->prevsnap, thissnap);
	sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
	zfs_close(zhp);
	return (err);
}

static int
dump_filesystem(zfs_handle_t *zhp, void *arg)
{
	int rv = 0;
	send_dump_data_t *sdd = arg;
	boolean_t missingfrom = B_FALSE;
	zfs_cmd_t zc = {"\0"};
	uint64_t min_txg = 0, max_txg = 0;

	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
	    zhp->zfs_name, sdd->tosnap);
	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
		    "WARNING: could not send %s@%s: does not exist\n"),
		    zhp->zfs_name, sdd->tosnap);
		sdd->err = B_TRUE;
		return (0);
	}

	if (sdd->replicate && sdd->fromsnap) {
		/*
		 * If this fs does not have fromsnap, and we're doing
		 * recursive, we need to send a full stream from the
		 * beginning (or an incremental from the origin if this
		 * is a clone).  If we're doing non-recursive, then let
		 * them get the error.
		 */
		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
		    zhp->zfs_name, sdd->fromsnap);
		if (zfs_ioctl(zhp->zfs_hdl,
		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
			missingfrom = B_TRUE;
		}
	}

	sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
	sdd->prevsnap_obj = 0;
	if (sdd->fromsnap == NULL || missingfrom)
		sdd->seenfrom = B_TRUE;



	/*
	 * Iterate through all snapshots and process the ones we will be
	 * sending. If we only have a "from" and "to" snapshot to deal
	 * with, we can avoid iterating through all the other snapshots.
	 */
	if (sdd->doall || sdd->replicate || sdd->tosnap == NULL) {
		if (!sdd->replicate && sdd->fromsnap != NULL)
			min_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name,
			    sdd->fromsnap);
		if (!sdd->replicate && sdd->tosnap != NULL)
			max_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name,
			    sdd->tosnap);
		rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg,
		    min_txg, max_txg);
	} else {
		char snapname[MAXPATHLEN] = { 0 };
		zfs_handle_t *snap;

		if (!sdd->seenfrom) {
			(void) snprintf(snapname, sizeof (snapname),
			    "%s@%s", zhp->zfs_name, sdd->fromsnap);
			snap = zfs_open(zhp->zfs_hdl, snapname,
			    ZFS_TYPE_SNAPSHOT);
			if (snap != NULL)
				rv = dump_snapshot(snap, sdd);
			else
				rv = -1;
		}

		if (rv == 0) {
			(void) snprintf(snapname, sizeof (snapname),
			    "%s@%s", zhp->zfs_name, sdd->tosnap);
			snap = zfs_open(zhp->zfs_hdl, snapname,
			    ZFS_TYPE_SNAPSHOT);
			if (snap != NULL)
				rv = dump_snapshot(snap, sdd);
			else
				rv = -1;
		}
	}

	if (!sdd->seenfrom) {
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
		    "WARNING: could not send %s@%s:\n"
		    "incremental source (%s@%s) does not exist\n"),
		    zhp->zfs_name, sdd->tosnap,
		    zhp->zfs_name, sdd->fromsnap);
		sdd->err = B_TRUE;
	} else if (!sdd->seento) {
		if (sdd->fromsnap) {
			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
			    "WARNING: could not send %s@%s:\n"
			    "incremental source (%s@%s) "
			    "is not earlier than it\n"),
			    zhp->zfs_name, sdd->tosnap,
			    zhp->zfs_name, sdd->fromsnap);
		} else {
			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
			    "WARNING: "
			    "could not send %s@%s: does not exist\n"),
			    zhp->zfs_name, sdd->tosnap);
		}
		sdd->err = B_TRUE;
	}

	return (rv);
}

static int
dump_filesystems(zfs_handle_t *rzhp, void *arg)
{
	send_dump_data_t *sdd = arg;
	nvpair_t *fspair;
	boolean_t needagain, progress;

	if (!sdd->replicate)
		return (dump_filesystem(rzhp, sdd));

	/* Mark the clone origin snapshots. */
	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
		nvlist_t *nvfs;
		uint64_t origin_guid = 0;

		VERIFY(0 == nvpair_value_nvlist(fspair, &nvfs));
		(void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
		if (origin_guid != 0) {
			char *snapname;
			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
			    origin_guid, &snapname);
			if (origin_nv != NULL) {
				nvlist_t *snapprops;
				VERIFY(0 == nvlist_lookup_nvlist(origin_nv,
				    "snapprops", &snapprops));
				VERIFY(0 == nvlist_lookup_nvlist(snapprops,
				    snapname, &snapprops));
				VERIFY(0 == nvlist_add_boolean(
				    snapprops, "is_clone_origin"));
			}
		}
	}
again:
	needagain = progress = B_FALSE;
	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
		nvlist_t *fslist, *parent_nv;
		char *fsname;
		zfs_handle_t *zhp;
		int err;
		uint64_t origin_guid = 0;
		uint64_t parent_guid = 0;

		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
		if (nvlist_lookup_boolean(fslist, "sent") == 0)
			continue;

		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
		(void) nvlist_lookup_uint64(fslist, "parentfromsnap",
		    &parent_guid);

		if (parent_guid != 0) {
			parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
			if (!nvlist_exists(parent_nv, "sent")) {
				/* parent has not been sent; skip this one */
				needagain = B_TRUE;
				continue;
			}
		}

		if (origin_guid != 0) {
			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
			    origin_guid, NULL);
			if (origin_nv != NULL &&
			    !nvlist_exists(origin_nv, "sent")) {
				/*
				 * origin has not been sent yet;
				 * skip this clone.
				 */
				needagain = B_TRUE;
				continue;
			}
		}

		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
		if (zhp == NULL)
			return (-1);
		err = dump_filesystem(zhp, sdd);
		VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
		progress = B_TRUE;
		zfs_close(zhp);
		if (err)
			return (err);
	}
	if (needagain) {
		assert(progress);
		goto again;
	}

	/* clean out the sent flags in case we reuse this fss */
	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
		nvlist_t *fslist;

		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
		(void) nvlist_remove_all(fslist, "sent");
	}

	return (0);
}

nvlist_t *
zfs_send_resume_token_to_nvlist(libzfs_handle_t *hdl, const char *token)
{
	unsigned int version;
	int nread, i;
	unsigned long long checksum, packed_len;

	/*
	 * Decode token header, which is:
	 *   <token version>-<checksum of payload>-<uncompressed payload length>
	 * Note that the only supported token version is 1.
	 */
	nread = sscanf(token, "%u-%llx-%llx-",
	    &version, &checksum, &packed_len);
	if (nread != 3) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "resume token is corrupt (invalid format)"));
		return (NULL);
	}

	if (version != ZFS_SEND_RESUME_TOKEN_VERSION) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "resume token is corrupt (invalid version %u)"),
		    version);
		return (NULL);
	}

	/* convert hexadecimal representation to binary */
	token = strrchr(token, '-') + 1;
	int len = strlen(token) / 2;
	unsigned char *compressed = zfs_alloc(hdl, len);
	for (i = 0; i < len; i++) {
		nread = sscanf(token + i * 2, "%2hhx", compressed + i);
		if (nread != 1) {
			free(compressed);
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "resume token is corrupt "
			    "(payload is not hex-encoded)"));
			return (NULL);
		}
	}

	/* verify checksum */
	zio_cksum_t cksum;
	fletcher_4_native_varsize(compressed, len, &cksum);
	if (cksum.zc_word[0] != checksum) {
		free(compressed);
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "resume token is corrupt (incorrect checksum)"));
		return (NULL);
	}

	/* uncompress */
	void *packed = zfs_alloc(hdl, packed_len);
	uLongf packed_len_long = packed_len;
	if (uncompress(packed, &packed_len_long, compressed, len) != Z_OK ||
	    packed_len_long != packed_len) {
		free(packed);
		free(compressed);
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "resume token is corrupt (decompression failed)"));
		return (NULL);
	}

	/* unpack nvlist */
	nvlist_t *nv;
	int error = nvlist_unpack(packed, packed_len, &nv, KM_SLEEP);
	free(packed);
	free(compressed);
	if (error != 0) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "resume token is corrupt (nvlist_unpack failed)"));
		return (NULL);
	}
	return (nv);
}
static enum lzc_send_flags
lzc_flags_from_sendflags(const sendflags_t *flags)
{
	enum lzc_send_flags lzc_flags = 0;
	if (flags->largeblock)
		lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
	if (flags->embed_data)
		lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
	if (flags->compress)
		lzc_flags |= LZC_SEND_FLAG_COMPRESS;
	if (flags->raw)
		lzc_flags |= LZC_SEND_FLAG_RAW;
	return (lzc_flags);
}

static int
estimate_size(zfs_handle_t *zhp, const char *from, int fd, sendflags_t *flags,
    uint64_t resumeobj, uint64_t resumeoff, uint64_t bytes,
    const char *redactbook, char *errbuf)
{
	uint64_t size;
	FILE *fout = flags->dryrun ? stdout : stderr;
	progress_arg_t pa = { 0 };
	int err = 0;
	pthread_t ptid;

	if (flags->progress) {
		pa.pa_zhp = zhp;
		pa.pa_fd = fd;
		pa.pa_parsable = flags->parsable;
		pa.pa_estimate = B_TRUE;
		pa.pa_verbosity = flags->verbosity;

		err = pthread_create(&ptid, NULL,
		    send_progress_thread, &pa);
		if (err != 0) {
			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
			return (zfs_error(zhp->zfs_hdl,
			    EZFS_THREADCREATEFAILED, errbuf));
		}
	}

	err = lzc_send_space_resume_redacted(zhp->zfs_name, from,
	    lzc_flags_from_sendflags(flags), resumeobj, resumeoff, bytes,
	    redactbook, fd, &size);

	if (flags->progress) {
		void *status = NULL;
		(void) pthread_cancel(ptid);
		(void) pthread_join(ptid, &status);
		int error = (int)(uintptr_t)status;
		if (error != 0 && status != PTHREAD_CANCELED) {
			char errbuf[1024];
			(void) snprintf(errbuf, sizeof (errbuf),
			    dgettext(TEXT_DOMAIN, "progress thread exited "
			    "nonzero"));
			return (zfs_standard_error(zhp->zfs_hdl, error,
			    errbuf));
		}
	}

	if (err != 0) {
		zfs_error_aux(zhp->zfs_hdl, strerror(err));
		return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
		    errbuf));
	}
	send_print_verbose(fout, zhp->zfs_name, from, size,
	    flags->parsable);

	if (flags->parsable) {
		(void) fprintf(fout, "size\t%llu\n", (longlong_t)size);
	} else {
		char buf[16];
		zfs_nicenum(size, buf, sizeof (buf));
		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
		    "total estimated size is %s\n"), buf);
	}
	return (0);
}

static boolean_t
redact_snaps_contains(const uint64_t *snaps, uint64_t num_snaps, uint64_t guid)
{
	for (int i = 0; i < num_snaps; i++) {
		if (snaps[i] == guid)
			return (B_TRUE);
	}
	return (B_FALSE);
}

static boolean_t
redact_snaps_equal(const uint64_t *snaps1, uint64_t num_snaps1,
    const uint64_t *snaps2, uint64_t num_snaps2)
{
	if (num_snaps1 != num_snaps2)
		return (B_FALSE);
	for (int i = 0; i < num_snaps1; i++) {
		if (!redact_snaps_contains(snaps2, num_snaps2, snaps1[i]))
			return (B_FALSE);
	}
	return (B_TRUE);
}

/*
 * Check that the list of redaction snapshots in the bookmark matches the send
 * we're resuming, and return whether or not it's complete.
 *
 * Note that the caller needs to free the contents of *bookname with free() if
 * this function returns successfully.
 */
static int
find_redact_book(libzfs_handle_t *hdl, const char *path,
    const uint64_t *redact_snap_guids, int num_redact_snaps,
    char **bookname)
{
	char errbuf[1024];
	int error = 0;
	nvlist_t *props = fnvlist_alloc();
	nvlist_t *bmarks;

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot resume send"));

	fnvlist_add_boolean(props, "redact_complete");
	fnvlist_add_boolean(props, zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS));
	error = lzc_get_bookmarks(path, props, &bmarks);
	nvlist_free(props);
	if (error != 0) {
		if (error == ESRCH) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "nonexistent redaction bookmark provided"));
		} else if (error == ENOENT) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "dataset to be sent no longer exists"));
		} else {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "unknown error: %s"), strerror(error));
		}
		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
	}
	nvpair_t *pair;
	for (pair = nvlist_next_nvpair(bmarks, NULL); pair;
	    pair = nvlist_next_nvpair(bmarks, pair)) {

		nvlist_t *bmark = fnvpair_value_nvlist(pair);
		nvlist_t *vallist = fnvlist_lookup_nvlist(bmark,
		    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS));
		uint_t len = 0;
		uint64_t *bmarksnaps = fnvlist_lookup_uint64_array(vallist,
		    ZPROP_VALUE, &len);
		if (redact_snaps_equal(redact_snap_guids,
		    num_redact_snaps, bmarksnaps, len)) {
			break;
		}
	}
	if (pair == NULL)  {
		fnvlist_free(bmarks);
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "no appropriate redaction bookmark exists"));
		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
	}
	char *name = nvpair_name(pair);
	nvlist_t *bmark = fnvpair_value_nvlist(pair);
	nvlist_t *vallist = fnvlist_lookup_nvlist(bmark, "redact_complete");
	boolean_t complete = fnvlist_lookup_boolean_value(vallist,
	    ZPROP_VALUE);
	if (!complete) {
		fnvlist_free(bmarks);
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "incomplete redaction bookmark provided"));
		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
	}
	*bookname = strndup(name, ZFS_MAX_DATASET_NAME_LEN);
	ASSERT3P(*bookname, !=, NULL);
	fnvlist_free(bmarks);
	return (0);
}

int
zfs_send_resume(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
    const char *resume_token)
{
	char errbuf[1024];
	char *toname;
	char *fromname = NULL;
	uint64_t resumeobj, resumeoff, toguid, fromguid, bytes;
	zfs_handle_t *zhp;
	int error = 0;
	char name[ZFS_MAX_DATASET_NAME_LEN];
	enum lzc_send_flags lzc_flags = 0;
	FILE *fout = (flags->verbosity > 0 && flags->dryrun) ? stdout : stderr;
	uint64_t *redact_snap_guids = NULL;
	int num_redact_snaps = 0;
	char *redact_book = NULL;

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot resume send"));

	nvlist_t *resume_nvl =
	    zfs_send_resume_token_to_nvlist(hdl, resume_token);
	if (resume_nvl == NULL) {
		/*
		 * zfs_error_aux has already been set by
		 * zfs_send_resume_token_to_nvlist
		 */
		return (zfs_error(hdl, EZFS_FAULT, errbuf));
	}
	if (flags->verbosity != 0) {
		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
		    "resume token contents:\n"));
		nvlist_print(fout, resume_nvl);
	}

	if (nvlist_lookup_string(resume_nvl, "toname", &toname) != 0 ||
	    nvlist_lookup_uint64(resume_nvl, "object", &resumeobj) != 0 ||
	    nvlist_lookup_uint64(resume_nvl, "offset", &resumeoff) != 0 ||
	    nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
	    nvlist_lookup_uint64(resume_nvl, "toguid", &toguid) != 0) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "resume token is corrupt"));
		return (zfs_error(hdl, EZFS_FAULT, errbuf));
	}
	fromguid = 0;
	(void) nvlist_lookup_uint64(resume_nvl, "fromguid", &fromguid);

	if (flags->largeblock || nvlist_exists(resume_nvl, "largeblockok"))
		lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
	if (flags->embed_data || nvlist_exists(resume_nvl, "embedok"))
		lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
	if (flags->compress || nvlist_exists(resume_nvl, "compressok"))
		lzc_flags |= LZC_SEND_FLAG_COMPRESS;
	if (flags->raw || nvlist_exists(resume_nvl, "rawok"))
		lzc_flags |= LZC_SEND_FLAG_RAW;

	if (guid_to_name(hdl, toname, toguid, B_FALSE, name) != 0) {
		if (zfs_dataset_exists(hdl, toname, ZFS_TYPE_DATASET)) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "'%s' is no longer the same snapshot used in "
			    "the initial send"), toname);
		} else {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "'%s' used in the initial send no longer exists"),
			    toname);
		}
		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
	}
	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
	if (zhp == NULL) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "unable to access '%s'"), name);
		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
	}

	if (nvlist_lookup_uint64_array(resume_nvl, "book_redact_snaps",
	    &redact_snap_guids, (uint_t *)&num_redact_snaps) != 0) {
		num_redact_snaps = -1;
	}

	if (fromguid != 0) {
		if (guid_to_name_redact_snaps(hdl, toname, fromguid, B_TRUE,
		    redact_snap_guids, num_redact_snaps, name) != 0) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "incremental source %#llx no longer exists"),
			    (longlong_t)fromguid);
			return (zfs_error(hdl, EZFS_BADPATH, errbuf));
		}
		fromname = name;
	}

	redact_snap_guids = NULL;

	if (nvlist_lookup_uint64_array(resume_nvl,
	    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS), &redact_snap_guids,
	    (uint_t *)&num_redact_snaps) == 0) {
		char path[ZFS_MAX_DATASET_NAME_LEN];

		(void) strlcpy(path, toname, sizeof (path));
		char *at = strchr(path, '@');
		ASSERT3P(at, !=, NULL);

		*at = '\0';

		if ((error = find_redact_book(hdl, path, redact_snap_guids,
		    num_redact_snaps, &redact_book)) != 0) {
			return (error);
		}
	}

	if (flags->verbosity != 0) {
		/*
		 * Some of these may have come from the resume token, set them
		 * here for size estimate purposes.
		 */
		sendflags_t tmpflags = *flags;
		if (lzc_flags & LZC_SEND_FLAG_LARGE_BLOCK)
			tmpflags.largeblock = B_TRUE;
		if (lzc_flags & LZC_SEND_FLAG_COMPRESS)
			tmpflags.compress = B_TRUE;
		if (lzc_flags & LZC_SEND_FLAG_EMBED_DATA)
			tmpflags.embed_data = B_TRUE;
		error = estimate_size(zhp, fromname, outfd, &tmpflags,
		    resumeobj, resumeoff, bytes, redact_book, errbuf);
	}

	if (!flags->dryrun) {
		progress_arg_t pa = { 0 };
		pthread_t tid;
		/*
		 * If progress reporting is requested, spawn a new thread to
		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
		 */
		if (flags->progress) {
			pa.pa_zhp = zhp;
			pa.pa_fd = outfd;
			pa.pa_parsable = flags->parsable;
			pa.pa_estimate = B_FALSE;
			pa.pa_verbosity = flags->verbosity;

			error = pthread_create(&tid, NULL,
			    send_progress_thread, &pa);
			if (error != 0) {
				if (redact_book != NULL)
					free(redact_book);
				zfs_close(zhp);
				return (error);
			}
		}

		error = lzc_send_resume_redacted(zhp->zfs_name, fromname, outfd,
		    lzc_flags, resumeobj, resumeoff, redact_book);
		if (redact_book != NULL)
			free(redact_book);

		if (flags->progress) {
			void *status = NULL;
			(void) pthread_cancel(tid);
			(void) pthread_join(tid, &status);
			int error = (int)(uintptr_t)status;
			if (error != 0 && status != PTHREAD_CANCELED) {
				char errbuf[1024];
				(void) snprintf(errbuf, sizeof (errbuf),
				    dgettext(TEXT_DOMAIN,
				    "progress thread exited nonzero"));
				return (zfs_standard_error(hdl, error, errbuf));
			}
		}

		char errbuf[1024];
		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
		    "warning: cannot send '%s'"), zhp->zfs_name);

		zfs_close(zhp);

		switch (error) {
		case 0:
			return (0);
		case EACCES:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "source key must be loaded"));
			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
		case ESRCH:
			if (lzc_exists(zhp->zfs_name)) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "incremental source could not be found"));
			}
			return (zfs_error(hdl, EZFS_NOENT, errbuf));

		case EXDEV:
		case ENOENT:
		case EDQUOT:
		case EFBIG:
		case EIO:
		case ENOLINK:
		case ENOSPC:
		case ENOSTR:
		case ENXIO:
		case EPIPE:
		case ERANGE:
		case EFAULT:
		case EROFS:
			zfs_error_aux(hdl, strerror(errno));
			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));

		default:
			return (zfs_standard_error(hdl, errno, errbuf));
		}
	} else {
		if (redact_book != NULL)
			free(redact_book);
	}

	zfs_close(zhp);

	return (error);
}

/*
 * This function informs the target system that the recursive send is complete.
 * The record is also expected in the case of a send -p.
 */
static int
send_conclusion_record(int fd, zio_cksum_t *zc)
{
	dmu_replay_record_t drr = { 0 };
	drr.drr_type = DRR_END;
	if (zc != NULL)
		drr.drr_u.drr_end.drr_checksum = *zc;
	if (write(fd, &drr, sizeof (drr)) == -1) {
		return (errno);
	}
	return (0);
}

/*
 * This function is responsible for sending the records that contain the
 * necessary information for the target system's libzfs to be able to set the
 * properties of the filesystem being received, or to be able to prepare for
 * a recursive receive.
 *
 * The "zhp" argument is the handle of the snapshot we are sending
 * (the "tosnap").  The "from" argument is the short snapshot name (the part
 * after the @) of the incremental source.
 */
static int
send_prelim_records(zfs_handle_t *zhp, const char *from, int fd,
    boolean_t gather_props, boolean_t recursive, boolean_t verbose,
    boolean_t dryrun, boolean_t raw, boolean_t replicate, boolean_t backup,
    boolean_t holds, boolean_t props, boolean_t doall,
    nvlist_t **fssp, avl_tree_t **fsavlp)
{
	int err = 0;
	char *packbuf = NULL;
	size_t buflen = 0;
	zio_cksum_t zc = { {0} };
	int featureflags = 0;
	/* name of filesystem/volume that contains snapshot we are sending */
	char tofs[ZFS_MAX_DATASET_NAME_LEN];
	/* short name of snap we are sending */
	char *tosnap = "";

	char errbuf[1024];
	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "warning: cannot send '%s'"), zhp->zfs_name);
	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM && zfs_prop_get_int(zhp,
	    ZFS_PROP_VERSION) >= ZPL_VERSION_SA) {
		featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
	}

	if (holds)
		featureflags |= DMU_BACKUP_FEATURE_HOLDS;

	(void) strlcpy(tofs, zhp->zfs_name, ZFS_MAX_DATASET_NAME_LEN);
	char *at = strchr(tofs, '@');
	if (at != NULL) {
		*at = '\0';
		tosnap = at + 1;
	}

	if (gather_props) {
		nvlist_t *hdrnv = fnvlist_alloc();
		nvlist_t *fss = NULL;

		if (from != NULL)
			fnvlist_add_string(hdrnv, "fromsnap", from);
		fnvlist_add_string(hdrnv, "tosnap", tosnap);
		if (!recursive)
			fnvlist_add_boolean(hdrnv, "not_recursive");

		if (raw) {
			VERIFY0(nvlist_add_boolean(hdrnv, "raw"));
		}

		if ((err = gather_nvlist(zhp->zfs_hdl, tofs,
		    from, tosnap, recursive, raw, doall, replicate, verbose,
		    backup, holds, props, &fss, fsavlp)) != 0) {
			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
			    errbuf));
		}
		fnvlist_add_nvlist(hdrnv, "fss", fss);
		VERIFY0(nvlist_pack(hdrnv, &packbuf, &buflen, NV_ENCODE_XDR,
		    0));
		if (fssp != NULL) {
			*fssp = fss;
		} else {
			nvlist_free(fss);
		}
		nvlist_free(hdrnv);
	}

	if (!dryrun) {
		dmu_replay_record_t drr = { 0 };
		/* write first begin record */
		drr.drr_type = DRR_BEGIN;
		drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
		DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
		    drr_versioninfo, DMU_COMPOUNDSTREAM);
		DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
		    drr_versioninfo, featureflags);
		if (snprintf(drr.drr_u.drr_begin.drr_toname,
		    sizeof (drr.drr_u.drr_begin.drr_toname), "%s@%s", tofs,
		    tosnap) >= sizeof (drr.drr_u.drr_begin.drr_toname)) {
			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
			    errbuf));
		}
		drr.drr_payloadlen = buflen;

		err = dump_record(&drr, packbuf, buflen, &zc, fd);
		free(packbuf);
		if (err != 0) {
			zfs_error_aux(zhp->zfs_hdl, strerror(err));
			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
			    errbuf));
		}
		err = send_conclusion_record(fd, &zc);
		if (err != 0) {
			zfs_error_aux(zhp->zfs_hdl, strerror(err));
			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
			    errbuf));
		}
	}
	return (0);
}

/*
 * Generate a send stream.  The "zhp" argument is the filesystem/volume
 * that contains the snapshot to send.  The "fromsnap" argument is the
 * short name (the part after the '@') of the snapshot that is the
 * incremental source to send from (if non-NULL).  The "tosnap" argument
 * is the short name of the snapshot to send.
 *
 * The content of the send stream is the snapshot identified by
 * 'tosnap'.  Incremental streams are requested in two ways:
 *     - from the snapshot identified by "fromsnap" (if non-null) or
 *     - from the origin of the dataset identified by zhp, which must
 *	 be a clone.  In this case, "fromsnap" is null and "fromorigin"
 *	 is TRUE.
 *
 * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
 * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
 * if "replicate" is set.  If "doall" is set, dump all the intermediate
 * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
 * case too. If "props" is set, send properties.
 */
int
zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
    sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
    void *cb_arg, nvlist_t **debugnvp)
{
	char errbuf[1024];
	send_dump_data_t sdd = { 0 };
	int err = 0;
	nvlist_t *fss = NULL;
	avl_tree_t *fsavl = NULL;
	static uint64_t holdseq;
	int spa_version;
	pthread_t tid = 0;
	int pipefd[2];
	dedup_arg_t dda = { 0 };
	int featureflags = 0;
	FILE *fout;

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot send '%s'"), zhp->zfs_name);

	if (fromsnap && fromsnap[0] == '\0') {
		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
		    "zero-length incremental source"));
		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
	}

	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM) {
		uint64_t version;
		version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
		if (version >= ZPL_VERSION_SA) {
			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
		}
	}

	if (flags->holds)
		featureflags |= DMU_BACKUP_FEATURE_HOLDS;

	/*
	 * Start the dedup thread if this is a dedup stream. We do not bother
	 * doing this if this a raw send of an encrypted dataset with dedup off
	 * because normal encrypted blocks won't dedup.
	 */
	if (flags->dedup && !flags->dryrun && !(flags->raw &&
	    zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
	    zfs_prop_get_int(zhp, ZFS_PROP_DEDUP) == ZIO_CHECKSUM_OFF)) {
		featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
		    DMU_BACKUP_FEATURE_DEDUPPROPS);
		if ((err = socketpair(AF_UNIX, SOCK_STREAM, 0, pipefd)) != 0) {
			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
			return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
			    errbuf));
		}
		dda.outputfd = outfd;
		dda.inputfd = pipefd[1];
		dda.dedup_hdl = zhp->zfs_hdl;
		if ((err = pthread_create(&tid, NULL, cksummer, &dda)) != 0) {
			(void) close(pipefd[0]);
			(void) close(pipefd[1]);
			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
			return (zfs_error(zhp->zfs_hdl,
			    EZFS_THREADCREATEFAILED, errbuf));
		}
	}

	if (flags->replicate || flags->doall || flags->props ||
	    flags->holds || flags->backup) {
		char full_tosnap_name[ZFS_MAX_DATASET_NAME_LEN];
		if (snprintf(full_tosnap_name, sizeof (full_tosnap_name),
		    "%s@%s", zhp->zfs_name, tosnap) >=
		    sizeof (full_tosnap_name)) {
			err = EINVAL;
			goto stderr_out;
		}
		zfs_handle_t *tosnap = zfs_open(zhp->zfs_hdl,
		    full_tosnap_name, ZFS_TYPE_SNAPSHOT);
		if (tosnap == NULL) {
			err = -1;
			goto err_out;
		}
		err = send_prelim_records(tosnap, fromsnap, outfd,
		    flags->replicate || flags->props || flags->holds,
		    flags->replicate, flags->verbosity > 0, flags->dryrun,
		    flags->raw, flags->replicate, flags->backup, flags->holds,
		    flags->props, flags->doall, &fss, &fsavl);
		zfs_close(tosnap);
		if (err != 0)
			goto err_out;
	}

	/* dump each stream */
	sdd.fromsnap = fromsnap;
	sdd.tosnap = tosnap;
	if (tid != 0)
		sdd.outfd = pipefd[0];
	else
		sdd.outfd = outfd;
	sdd.replicate = flags->replicate;
	sdd.doall = flags->doall;
	sdd.fromorigin = flags->fromorigin;
	sdd.fss = fss;
	sdd.fsavl = fsavl;
	sdd.verbosity = flags->verbosity;
	sdd.parsable = flags->parsable;
	sdd.progress = flags->progress;
	sdd.dryrun = flags->dryrun;
	sdd.large_block = flags->largeblock;
	sdd.embed_data = flags->embed_data;
	sdd.compress = flags->compress;
	sdd.raw = flags->raw;
	sdd.holds = flags->holds;
	sdd.filter_cb = filter_func;
	sdd.filter_cb_arg = cb_arg;
	if (debugnvp)
		sdd.debugnv = *debugnvp;
	if (sdd.verbosity != 0 && sdd.dryrun)
		sdd.std_out = B_TRUE;
	fout = sdd.std_out ? stdout : stderr;

	/*
	 * Some flags require that we place user holds on the datasets that are
	 * being sent so they don't get destroyed during the send. We can skip
	 * this step if the pool is imported read-only since the datasets cannot
	 * be destroyed.
	 */
	if (!flags->dryrun && !zpool_get_prop_int(zfs_get_pool_handle(zhp),
	    ZPOOL_PROP_READONLY, NULL) &&
	    zfs_spa_version(zhp, &spa_version) == 0 &&
	    spa_version >= SPA_VERSION_USERREFS &&
	    (flags->doall || flags->replicate)) {
		++holdseq;
		(void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
		    ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
		sdd.cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
		if (sdd.cleanup_fd < 0) {
			err = errno;
			goto stderr_out;
		}
		sdd.snapholds = fnvlist_alloc();
	} else {
		sdd.cleanup_fd = -1;
		sdd.snapholds = NULL;
	}

	if (flags->verbosity != 0 || sdd.snapholds != NULL) {
		/*
		 * Do a verbose no-op dry run to get all the verbose output
		 * or to gather snapshot hold's before generating any data,
		 * then do a non-verbose real run to generate the streams.
		 */
		sdd.dryrun = B_TRUE;
		err = dump_filesystems(zhp, &sdd);

		if (err != 0)
			goto stderr_out;

		if (flags->verbosity != 0) {
			if (flags->parsable) {
				(void) fprintf(fout, "size\t%llu\n",
				    (longlong_t)sdd.size);
			} else {
				char buf[16];
				zfs_nicebytes(sdd.size, buf, sizeof (buf));
				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
				    "total estimated size is %s\n"), buf);
			}
		}

		/* Ensure no snaps found is treated as an error. */
		if (!sdd.seento) {
			err = ENOENT;
			goto err_out;
		}

		/* Skip the second run if dryrun was requested. */
		if (flags->dryrun)
			goto err_out;

		if (sdd.snapholds != NULL) {
			err = zfs_hold_nvl(zhp, sdd.cleanup_fd, sdd.snapholds);
			if (err != 0)
				goto stderr_out;

			fnvlist_free(sdd.snapholds);
			sdd.snapholds = NULL;
		}

		sdd.dryrun = B_FALSE;
		sdd.verbosity = 0;
	}

	err = dump_filesystems(zhp, &sdd);
	fsavl_destroy(fsavl);
	nvlist_free(fss);

	/* Ensure no snaps found is treated as an error. */
	if (err == 0 && !sdd.seento)
		err = ENOENT;

	if (tid != 0) {
		if (err != 0)
			(void) pthread_cancel(tid);
		(void) close(pipefd[0]);
		(void) pthread_join(tid, NULL);
	}

	if (sdd.cleanup_fd != -1) {
		VERIFY(0 == close(sdd.cleanup_fd));
		sdd.cleanup_fd = -1;
	}

	if (!flags->dryrun && (flags->replicate || flags->doall ||
	    flags->props || flags->backup || flags->holds)) {
		/*
		 * write final end record.  NB: want to do this even if
		 * there was some error, because it might not be totally
		 * failed.
		 */
		err = send_conclusion_record(outfd, NULL);
		if (err != 0)
			return (zfs_standard_error(zhp->zfs_hdl, err, errbuf));
	}

	return (err || sdd.err);

stderr_out:
	err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
err_out:
	fsavl_destroy(fsavl);
	nvlist_free(fss);
	fnvlist_free(sdd.snapholds);

	if (sdd.cleanup_fd != -1)
		VERIFY(0 == close(sdd.cleanup_fd));
	if (tid != 0) {
		(void) pthread_cancel(tid);
		(void) close(pipefd[0]);
		(void) pthread_join(tid, NULL);
	}
	return (err);
}

static int
get_dedup_fd(zfs_handle_t *zhp, dedup_arg_t *dda, int fd, pthread_t *tid,
    int *outfd)
{
	int pipefd[2];
	char errbuf[1024];
	int err;
	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "warning: cannot send '%s'"), zhp->zfs_name);
	if ((err = socketpair(AF_UNIX, SOCK_STREAM, 0, pipefd)) != 0) {
		zfs_error_aux(zhp->zfs_hdl, strerror(errno));
		return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
		    errbuf));
	}
	dda->outputfd = fd;
	dda->inputfd = pipefd[1];
	dda->dedup_hdl = zhp->zfs_hdl;
	if ((err = pthread_create(tid, NULL, cksummer, dda)) != 0) {
		(void) close(pipefd[0]);
		(void) close(pipefd[1]);
		zfs_error_aux(zhp->zfs_hdl, strerror(err));
		return (zfs_error(zhp->zfs_hdl, EZFS_THREADCREATEFAILED,
		    errbuf));
	}
	*outfd = pipefd[0];
	return (0);
}

zfs_handle_t *
name_to_dir_handle(libzfs_handle_t *hdl, const char *snapname)
{
	char dirname[ZFS_MAX_DATASET_NAME_LEN];
	(void) strlcpy(dirname, snapname, ZFS_MAX_DATASET_NAME_LEN);
	char *c = strchr(dirname, '@');
	if (c != NULL)
		*c = '\0';
	return (zfs_open(hdl, dirname, ZFS_TYPE_DATASET));
}

/*
 * Returns B_TRUE if earlier is an earlier snapshot in later's timeline; either
 * an earlier snapshot in the same filesystem, or a snapshot before later's
 * origin, or it's origin's origin, etc.
 */
static boolean_t
snapshot_is_before(zfs_handle_t *earlier, zfs_handle_t *later)
{
	boolean_t ret;
	uint64_t later_txg =
	    (later->zfs_type == ZFS_TYPE_FILESYSTEM ||
	    later->zfs_type == ZFS_TYPE_VOLUME ?
	    UINT64_MAX : zfs_prop_get_int(later, ZFS_PROP_CREATETXG));
	uint64_t earlier_txg = zfs_prop_get_int(earlier, ZFS_PROP_CREATETXG);

	if (earlier_txg >= later_txg)
		return (B_FALSE);

	zfs_handle_t *earlier_dir = name_to_dir_handle(earlier->zfs_hdl,
	    earlier->zfs_name);
	zfs_handle_t *later_dir = name_to_dir_handle(later->zfs_hdl,
	    later->zfs_name);

	if (strcmp(earlier_dir->zfs_name, later_dir->zfs_name) == 0) {
		zfs_close(earlier_dir);
		zfs_close(later_dir);
		return (B_TRUE);
	}

	char clonename[ZFS_MAX_DATASET_NAME_LEN];
	if (zfs_prop_get(later_dir, ZFS_PROP_ORIGIN, clonename,
	    ZFS_MAX_DATASET_NAME_LEN, NULL, NULL, 0, B_TRUE) != 0) {
		zfs_close(earlier_dir);
		zfs_close(later_dir);
		return (B_FALSE);
	}

	zfs_handle_t *origin = zfs_open(earlier->zfs_hdl, clonename,
	    ZFS_TYPE_DATASET);
	uint64_t origin_txg = zfs_prop_get_int(origin, ZFS_PROP_CREATETXG);

	/*
	 * If "earlier" is exactly the origin, then
	 * snapshot_is_before(earlier, origin) will return false (because
	 * they're the same).
	 */
	if (origin_txg == earlier_txg &&
	    strcmp(origin->zfs_name, earlier->zfs_name) == 0) {
		zfs_close(earlier_dir);
		zfs_close(later_dir);
		zfs_close(origin);
		return (B_TRUE);
	}
	zfs_close(earlier_dir);
	zfs_close(later_dir);

	ret = snapshot_is_before(earlier, origin);
	zfs_close(origin);
	return (ret);
}

/*
 * The "zhp" argument is the handle of the dataset to send (typically a
 * snapshot).  The "from" argument is the full name of the snapshot or
 * bookmark that is the incremental source.
 */
int
zfs_send_one(zfs_handle_t *zhp, const char *from, int fd, sendflags_t *flags,
    const char *redactbook)
{
	int err;
	libzfs_handle_t *hdl = zhp->zfs_hdl;
	int orig_fd = fd;
	pthread_t ddtid, ptid;
	progress_arg_t pa = { 0 };
	dedup_arg_t dda = { 0 };

	char errbuf[1024];
	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "warning: cannot send '%s'"), zhp->zfs_name);

	if (from != NULL && strchr(from, '@')) {
		zfs_handle_t *from_zhp = zfs_open(hdl, from,
		    ZFS_TYPE_DATASET);
		if (from_zhp == NULL)
			return (-1);
		if (!snapshot_is_before(from_zhp, zhp)) {
			zfs_close(from_zhp);
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "not an earlier snapshot from the same fs"));
			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
		}
		zfs_close(from_zhp);
	}

	/*
	 * Send fs properties
	 */
	if (flags->props || flags->holds || flags->backup) {
		/*
		 * Note: the header generated by send_prelim_records()
		 * assumes that the incremental source is in the same
		 * filesystem/volume as the target (which is a requirement
		 * when doing "zfs send -R").  But that isn't always the
		 * case here (e.g. send from snap in origin, or send from
		 * bookmark).  We pass from=NULL, which will omit this
		 * information from the prelim records; it isn't used
		 * when receiving this type of stream.
		 */
		err = send_prelim_records(zhp, NULL, fd, B_TRUE, B_FALSE,
		    flags->verbosity > 0, flags->dryrun, flags->raw,
		    flags->replicate, flags->backup, flags->holds,
		    flags->props, flags->doall, NULL, NULL);
		if (err != 0)
			return (err);
	}

	/*
	 * Perform size estimate if verbose was specified.
	 */
	if (flags->verbosity != 0) {
		err = estimate_size(zhp, from, fd, flags, 0, 0, 0, redactbook,
		    errbuf);
		if (err != 0)
			return (err);
	}

	if (flags->dryrun)
		return (0);

	/*
	 * If deduplication is requested, spawn a thread that will deduplicate
	 * the data coming out of the kernel.
	 */
	if (flags->dedup) {
		err = get_dedup_fd(zhp, &dda, fd, &ddtid, &fd);
		if (err != 0)
			return (err);
	}

	/*
	 * If progress reporting is requested, spawn a new thread to poll
	 * ZFS_IOC_SEND_PROGRESS at a regular interval.
	 */
	if (flags->progress) {
		pa.pa_zhp = zhp;
		pa.pa_fd = fd;
		pa.pa_parsable = flags->parsable;
		pa.pa_estimate = B_FALSE;
		pa.pa_verbosity = flags->verbosity;

		err = pthread_create(&ptid, NULL,
		    send_progress_thread, &pa);
		if (err != 0) {
			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
			if (flags->dedup) {
				(void) pthread_cancel(ddtid);
				(void) close(fd);
				(void) pthread_join(ddtid, NULL);
			}
			return (zfs_error(zhp->zfs_hdl,
			    EZFS_THREADCREATEFAILED, errbuf));
		}
	}

	err = lzc_send_redacted(zhp->zfs_name, from, fd,
	    lzc_flags_from_sendflags(flags), redactbook);

	if (flags->progress) {
		void *status = NULL;
		if (err != 0)
			(void) pthread_cancel(ptid);
		(void) pthread_join(ptid, &status);
		int error = (int)(uintptr_t)status;
		if (error != 0 && status != PTHREAD_CANCELED) {
			char errbuf[1024];
			(void) snprintf(errbuf, sizeof (errbuf),
			    dgettext(TEXT_DOMAIN, "progress thread exited "
			    "nonzero"));
			return (zfs_standard_error(hdl, error, errbuf));
		}
	}
	if (flags->dedup) {
		if (err != 0)
			(void) pthread_cancel(ddtid);
		(void) close(fd);
		(void) pthread_join(ddtid, NULL);
	}

	if (flags->props || flags->holds || flags->backup) {
		/* Write the final end record. */
		err = send_conclusion_record(orig_fd, NULL);
		if (err != 0)
			return (zfs_standard_error(hdl, err, errbuf));
	}
	if (err != 0) {
		switch (errno) {
		case EXDEV:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "not an earlier snapshot from the same fs"));
			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));

		case ENOENT:
		case ESRCH:
			if (lzc_exists(zhp->zfs_name)) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "incremental source (%s) does not exist"),
				    from);
			}
			return (zfs_error(hdl, EZFS_NOENT, errbuf));

		case EACCES:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "dataset key must be loaded"));
			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));

		case EBUSY:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "target is busy; if a filesystem, "
			    "it must not be mounted"));
			return (zfs_error(hdl, EZFS_BUSY, errbuf));

		case EDQUOT:
		case EFBIG:
		case EIO:
		case ENOLINK:
		case ENOSPC:
		case ENOSTR:
		case ENXIO:
		case EPIPE:
		case ERANGE:
		case EFAULT:
		case EROFS:
			zfs_error_aux(hdl, strerror(errno));
			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));

		default:
			return (zfs_standard_error(hdl, errno, errbuf));
		}
	}
	return (err != 0);
}

/*
 * Routines specific to "zfs recv"
 */

static int
recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
    boolean_t byteswap, zio_cksum_t *zc)
{
	char *cp = buf;
	int rv;
	int len = ilen;

	assert(ilen <= SPA_MAXBLOCKSIZE);

	do {
		rv = read(fd, cp, len);
		cp += rv;
		len -= rv;
	} while (rv > 0);

	if (rv < 0 || len != 0) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "failed to read from stream"));
		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
		    "cannot receive")));
	}

	if (zc) {
		if (byteswap)
			fletcher_4_incremental_byteswap(buf, ilen, zc);
		else
			fletcher_4_incremental_native(buf, ilen, zc);
	}
	return (0);
}

static int
recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
    boolean_t byteswap, zio_cksum_t *zc)
{
	char *buf;
	int err;

	buf = zfs_alloc(hdl, len);
	if (buf == NULL)
		return (ENOMEM);

	err = recv_read(hdl, fd, buf, len, byteswap, zc);
	if (err != 0) {
		free(buf);
		return (err);
	}

	err = nvlist_unpack(buf, len, nvp, 0);
	free(buf);
	if (err != 0) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
		    "stream (malformed nvlist)"));
		return (EINVAL);
	}
	return (0);
}

/*
 * Returns the grand origin (origin of origin of origin...) of a given handle.
 * If this dataset is not a clone, it simply returns a copy of the original
 * handle.
 */
static zfs_handle_t *
recv_open_grand_origin(zfs_handle_t *zhp)
{
	char origin[ZFS_MAX_DATASET_NAME_LEN];
	zprop_source_t src;
	zfs_handle_t *ozhp = zfs_handle_dup(zhp);

	while (ozhp != NULL) {
		if (zfs_prop_get(ozhp, ZFS_PROP_ORIGIN, origin,
		    sizeof (origin), &src, NULL, 0, B_FALSE) != 0)
			break;

		(void) zfs_close(ozhp);
		ozhp = zfs_open(zhp->zfs_hdl, origin, ZFS_TYPE_FILESYSTEM);
	}

	return (ozhp);
}

static int
recv_rename_impl(zfs_handle_t *zhp, const char *name, const char *newname)
{
	int err;
	zfs_handle_t *ozhp = NULL;

	/*
	 * Attempt to rename the dataset. If it fails with EACCES we have
	 * attempted to rename the dataset outside of its encryption root.
	 * Force the dataset to become an encryption root and try again.
	 */
	err = lzc_rename(name, newname);
	if (err == EACCES) {
		ozhp = recv_open_grand_origin(zhp);
		if (ozhp == NULL) {
			err = ENOENT;
			goto out;
		}

		err = lzc_change_key(ozhp->zfs_name, DCP_CMD_FORCE_NEW_KEY,
		    NULL, NULL, 0);
		if (err != 0)
			goto out;

		err = lzc_rename(name, newname);
	}

out:
	if (ozhp != NULL)
		zfs_close(ozhp);
	return (err);
}

static int
recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
    int baselen, char *newname, recvflags_t *flags)
{
	static int seq;
	int err;
	prop_changelist_t *clp = NULL;
	zfs_handle_t *zhp = NULL;

	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
	if (zhp == NULL) {
		err = -1;
		goto out;
	}
	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
	    flags->force ? MS_FORCE : 0);
	if (clp == NULL) {
		err = -1;
		goto out;
	}
	err = changelist_prefix(clp);
	if (err)
		goto out;

	if (tryname) {
		(void) strcpy(newname, tryname);
		if (flags->verbose) {
			(void) printf("attempting rename %s to %s\n",
			    name, newname);
		}
		err = recv_rename_impl(zhp, name, newname);
		if (err == 0)
			changelist_rename(clp, name, tryname);
	} else {
		err = ENOENT;
	}

	if (err != 0 && strncmp(name + baselen, "recv-", 5) != 0) {
		seq++;

		(void) snprintf(newname, ZFS_MAX_DATASET_NAME_LEN,
		    "%.*srecv-%u-%u", baselen, name, getpid(), seq);

		if (flags->verbose) {
			(void) printf("failed - trying rename %s to %s\n",
			    name, newname);
		}
		err = recv_rename_impl(zhp, name, newname);
		if (err == 0)
			changelist_rename(clp, name, newname);
		if (err && flags->verbose) {
			(void) printf("failed (%u) - "
			    "will try again on next pass\n", errno);
		}
		err = EAGAIN;
	} else if (flags->verbose) {
		if (err == 0)
			(void) printf("success\n");
		else
			(void) printf("failed (%u)\n", errno);
	}

	(void) changelist_postfix(clp);

out:
	if (clp != NULL)
		changelist_free(clp);
	if (zhp != NULL)
		zfs_close(zhp);

	return (err);
}

static int
recv_promote(libzfs_handle_t *hdl, const char *fsname,
    const char *origin_fsname, recvflags_t *flags)
{
	int err;
	zfs_cmd_t zc = {"\0"};
	zfs_handle_t *zhp = NULL, *ozhp = NULL;

	if (flags->verbose)
		(void) printf("promoting %s\n", fsname);

	(void) strlcpy(zc.zc_value, origin_fsname, sizeof (zc.zc_value));
	(void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));

	/*
	 * Attempt to promote the dataset. If it fails with EACCES the
	 * promotion would cause this dataset to leave its encryption root.
	 * Force the origin to become an encryption root and try again.
	 */
	err = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
	if (err == EACCES) {
		zhp = zfs_open(hdl, fsname, ZFS_TYPE_DATASET);
		if (zhp == NULL) {
			err = -1;
			goto out;
		}

		ozhp = recv_open_grand_origin(zhp);
		if (ozhp == NULL) {
			err = -1;
			goto out;
		}

		err = lzc_change_key(ozhp->zfs_name, DCP_CMD_FORCE_NEW_KEY,
		    NULL, NULL, 0);
		if (err != 0)
			goto out;

		err = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
	}

out:
	if (zhp != NULL)
		zfs_close(zhp);
	if (ozhp != NULL)
		zfs_close(ozhp);

	return (err);
}

static int
recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
    char *newname, recvflags_t *flags)
{
	int err = 0;
	prop_changelist_t *clp;
	zfs_handle_t *zhp;
	boolean_t defer = B_FALSE;
	int spa_version;

	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
	if (zhp == NULL)
		return (-1);
	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
	    flags->force ? MS_FORCE : 0);
	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
	    zfs_spa_version(zhp, &spa_version) == 0 &&
	    spa_version >= SPA_VERSION_USERREFS)
		defer = B_TRUE;
	zfs_close(zhp);
	if (clp == NULL)
		return (-1);
	err = changelist_prefix(clp);
	if (err)
		return (err);

	if (flags->verbose)
		(void) printf("attempting destroy %s\n", name);
	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
		nvlist_t *nv = fnvlist_alloc();
		fnvlist_add_boolean(nv, name);
		err = lzc_destroy_snaps(nv, defer, NULL);
		fnvlist_free(nv);
	} else {
		err = lzc_destroy(name);
	}
	if (err == 0) {
		if (flags->verbose)
			(void) printf("success\n");
		changelist_remove(clp, name);
	}

	(void) changelist_postfix(clp);
	changelist_free(clp);

	/*
	 * Deferred destroy might destroy the snapshot or only mark it to be
	 * destroyed later, and it returns success in either case.
	 */
	if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
	    ZFS_TYPE_SNAPSHOT))) {
		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
	}

	return (err);
}

typedef struct guid_to_name_data {
	uint64_t guid;
	boolean_t bookmark_ok;
	char *name;
	char *skip;
	uint64_t *redact_snap_guids;
	uint64_t num_redact_snaps;
} guid_to_name_data_t;

boolean_t
redact_snaps_match(zfs_handle_t *zhp, guid_to_name_data_t *gtnd)
{
	uint64_t *bmark_snaps;
	uint_t bmark_num_snaps;
	nvlist_t *nvl;
	if (zhp->zfs_type != ZFS_TYPE_BOOKMARK)
		return (B_FALSE);

	nvl = fnvlist_lookup_nvlist(zhp->zfs_props,
	    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS));
	bmark_snaps = fnvlist_lookup_uint64_array(nvl, ZPROP_VALUE,
	    &bmark_num_snaps);
	if (bmark_num_snaps != gtnd->num_redact_snaps)
		return (B_FALSE);
	int i = 0;
	for (; i < bmark_num_snaps; i++) {
		int j = 0;
		for (; j < bmark_num_snaps; j++) {
			if (bmark_snaps[i] == gtnd->redact_snap_guids[j])
				break;
		}
		if (j == bmark_num_snaps)
			break;
	}
	return (i == bmark_num_snaps);
}

static int
guid_to_name_cb(zfs_handle_t *zhp, void *arg)
{
	guid_to_name_data_t *gtnd = arg;
	const char *slash;
	int err;

	if (gtnd->skip != NULL &&
	    (slash = strrchr(zhp->zfs_name, '/')) != NULL &&
	    strcmp(slash + 1, gtnd->skip) == 0) {
		zfs_close(zhp);
		return (0);
	}

	if (zfs_prop_get_int(zhp, ZFS_PROP_GUID) == gtnd->guid &&
	    (gtnd->num_redact_snaps == -1 || redact_snaps_match(zhp, gtnd))) {
		(void) strcpy(gtnd->name, zhp->zfs_name);
		zfs_close(zhp);
		return (EEXIST);
	}

	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
	if (err != EEXIST && gtnd->bookmark_ok)
		err = zfs_iter_bookmarks(zhp, guid_to_name_cb, gtnd);
	zfs_close(zhp);
	return (err);
}

/*
 * Attempt to find the local dataset associated with this guid.  In the case of
 * multiple matches, we attempt to find the "best" match by searching
 * progressively larger portions of the hierarchy.  This allows one to send a
 * tree of datasets individually and guarantee that we will find the source
 * guid within that hierarchy, even if there are multiple matches elsewhere.
 *
 * If num_redact_snaps is not -1, we attempt to find a redaction bookmark with
 * the specified number of redaction snapshots.  If num_redact_snaps isn't 0 or
 * -1, then redact_snap_guids will be an array of the guids of the snapshots the
 * redaction bookmark was created with.  If num_redact_snaps is -1, then we will
 * attempt to find a snapshot or bookmark (if bookmark_ok is passed) with the
 * given guid.  Note that a redaction bookmark can be returned if
 * num_redact_snaps == -1.
 */
static int
guid_to_name_redact_snaps(libzfs_handle_t *hdl, const char *parent,
    uint64_t guid, boolean_t bookmark_ok, uint64_t *redact_snap_guids,
    uint64_t num_redact_snaps, char *name)
{
	char pname[ZFS_MAX_DATASET_NAME_LEN];
	guid_to_name_data_t gtnd;

	gtnd.guid = guid;
	gtnd.bookmark_ok = bookmark_ok;
	gtnd.name = name;
	gtnd.skip = NULL;
	gtnd.redact_snap_guids = redact_snap_guids;
	gtnd.num_redact_snaps = num_redact_snaps;

	/*
	 * Search progressively larger portions of the hierarchy, starting
	 * with the filesystem specified by 'parent'.  This will
	 * select the "most local" version of the origin snapshot in the case
	 * that there are multiple matching snapshots in the system.
	 */
	(void) strlcpy(pname, parent, sizeof (pname));
	char *cp = strrchr(pname, '@');
	if (cp == NULL)
		cp = strchr(pname, '\0');
	for (; cp != NULL; cp = strrchr(pname, '/')) {
		/* Chop off the last component and open the parent */
		*cp = '\0';
		zfs_handle_t *zhp = make_dataset_handle(hdl, pname);

		if (zhp == NULL)
			continue;
		int err = guid_to_name_cb(zfs_handle_dup(zhp), &gtnd);
		if (err != EEXIST)
			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
		if (err != EEXIST && bookmark_ok)
			err = zfs_iter_bookmarks(zhp, guid_to_name_cb, &gtnd);
		zfs_close(zhp);
		if (err == EEXIST)
			return (0);

		/*
		 * Remember the last portion of the dataset so we skip it next
		 * time through (as we've already searched that portion of the
		 * hierarchy).
		 */
		gtnd.skip = strrchr(pname, '/') + 1;
	}

	return (ENOENT);
}

static int
guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
    boolean_t bookmark_ok, char *name)
{
	return (guid_to_name_redact_snaps(hdl, parent, guid, bookmark_ok, NULL,
	    -1, name));
}

/*
 * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
 * guid1 is after guid2.
 */
static int
created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
    uint64_t guid1, uint64_t guid2)
{
	nvlist_t *nvfs;
	char *fsname = NULL, *snapname = NULL;
	char buf[ZFS_MAX_DATASET_NAME_LEN];
	int rv;
	zfs_handle_t *guid1hdl, *guid2hdl;
	uint64_t create1, create2;

	if (guid2 == 0)
		return (0);
	if (guid1 == 0)
		return (1);

	nvfs = fsavl_find(avl, guid1, &snapname);
	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
	guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
	if (guid1hdl == NULL)
		return (-1);

	nvfs = fsavl_find(avl, guid2, &snapname);
	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
	guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
	if (guid2hdl == NULL) {
		zfs_close(guid1hdl);
		return (-1);
	}

	create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
	create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);

	if (create1 < create2)
		rv = -1;
	else if (create1 > create2)
		rv = +1;
	else
		rv = 0;

	zfs_close(guid1hdl);
	zfs_close(guid2hdl);

	return (rv);
}

/*
 * This function reestablishes the hierarchy of encryption roots after a
 * recursive incremental receive has completed. This must be done after the
 * second call to recv_incremental_replication() has renamed and promoted all
 * sent datasets to their final locations in the dataset hierarchy.
 */
static int
recv_fix_encryption_hierarchy(libzfs_handle_t *hdl, const char *top_zfs,
    nvlist_t *stream_nv, avl_tree_t *stream_avl)
{
	int err;
	nvpair_t *fselem = NULL;
	nvlist_t *stream_fss;

	VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss", &stream_fss));

	while ((fselem = nvlist_next_nvpair(stream_fss, fselem)) != NULL) {
		zfs_handle_t *zhp = NULL;
		uint64_t crypt;
		nvlist_t *snaps, *props, *stream_nvfs = NULL;
		nvpair_t *snapel = NULL;
		boolean_t is_encroot, is_clone, stream_encroot;
		char *cp;
		char *stream_keylocation = NULL;
		char keylocation[MAXNAMELEN];
		char fsname[ZFS_MAX_DATASET_NAME_LEN];

		keylocation[0] = '\0';
		VERIFY(0 == nvpair_value_nvlist(fselem, &stream_nvfs));
		VERIFY(0 == nvlist_lookup_nvlist(stream_nvfs, "snaps", &snaps));
		VERIFY(0 == nvlist_lookup_nvlist(stream_nvfs, "props", &props));
		stream_encroot = nvlist_exists(stream_nvfs, "is_encroot");

		/* find a snapshot from the stream that exists locally */
		err = ENOENT;
		while ((snapel = nvlist_next_nvpair(snaps, snapel)) != NULL) {
			uint64_t guid;

			VERIFY(0 == nvpair_value_uint64(snapel, &guid));
			err = guid_to_name(hdl, top_zfs, guid, B_FALSE,
			    fsname);
			if (err == 0)
				break;
		}

		if (err != 0)
			continue;

		cp = strchr(fsname, '@');
		if (cp != NULL)
			*cp = '\0';

		zhp = zfs_open(hdl, fsname, ZFS_TYPE_DATASET);
		if (zhp == NULL) {
			err = ENOENT;
			goto error;
		}

		crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
		is_clone = zhp->zfs_dmustats.dds_origin[0] != '\0';
		(void) zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);

		/* we don't need to do anything for unencrypted datasets */
		if (crypt == ZIO_CRYPT_OFF) {
			zfs_close(zhp);
			continue;
		}

		/*
		 * If the dataset is flagged as an encryption root, was not
		 * received as a clone and is not currently an encryption root,
		 * force it to become one. Fixup the keylocation if necessary.
		 */
		if (stream_encroot) {
			if (!is_clone && !is_encroot) {
				err = lzc_change_key(fsname,
				    DCP_CMD_FORCE_NEW_KEY, NULL, NULL, 0);
				if (err != 0) {
					zfs_close(zhp);
					goto error;
				}
			}

			VERIFY(0 == nvlist_lookup_string(props,
			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
			    &stream_keylocation));

			/*
			 * Refresh the properties in case the call to
			 * lzc_change_key() changed the value.
			 */
			zfs_refresh_properties(zhp);
			err = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
			    keylocation, sizeof (keylocation), NULL, NULL,
			    0, B_TRUE);
			if (err != 0) {
				zfs_close(zhp);
				goto error;
			}

			if (strcmp(keylocation, stream_keylocation) != 0) {
				err = zfs_prop_set(zhp,
				    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
				    stream_keylocation);
				if (err != 0) {
					zfs_close(zhp);
					goto error;
				}
			}
		}

		/*
		 * If the dataset is not flagged as an encryption root and is
		 * currently an encryption root, force it to inherit from its
		 * parent. The root of a raw send should never be
		 * force-inherited.
		 */
		if (!stream_encroot && is_encroot &&
		    strcmp(top_zfs, fsname) != 0) {
			err = lzc_change_key(fsname, DCP_CMD_FORCE_INHERIT,
			    NULL, NULL, 0);
			if (err != 0) {
				zfs_close(zhp);
				goto error;
			}
		}

		zfs_close(zhp);
	}

	return (0);

error:
	return (err);
}

static int
recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
    recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
    nvlist_t *renamed)
{
	nvlist_t *local_nv, *deleted = NULL;
	avl_tree_t *local_avl;
	nvpair_t *fselem, *nextfselem;
	char *fromsnap;
	char newname[ZFS_MAX_DATASET_NAME_LEN];
	char guidname[32];
	int error;
	boolean_t needagain, progress, recursive;
	char *s1, *s2;

	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));

	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
	    ENOENT);

	if (flags->dryrun)
		return (0);

again:
	needagain = progress = B_FALSE;

	VERIFY(0 == nvlist_alloc(&deleted, NV_UNIQUE_NAME, 0));

	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
	    recursive, B_TRUE, B_FALSE, recursive, B_FALSE, B_FALSE,
	    B_FALSE, B_TRUE, &local_nv, &local_avl)) != 0)
		return (error);

	/*
	 * Process deletes and renames
	 */
	for (fselem = nvlist_next_nvpair(local_nv, NULL);
	    fselem; fselem = nextfselem) {
		nvlist_t *nvfs, *snaps;
		nvlist_t *stream_nvfs = NULL;
		nvpair_t *snapelem, *nextsnapelem;
		uint64_t fromguid = 0;
		uint64_t originguid = 0;
		uint64_t stream_originguid = 0;
		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
		char *fsname, *stream_fsname;

		nextfselem = nvlist_next_nvpair(local_nv, fselem);

		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
		    &parent_fromsnap_guid));
		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);

		/*
		 * First find the stream's fs, so we can check for
		 * a different origin (due to "zfs promote")
		 */
		for (snapelem = nvlist_next_nvpair(snaps, NULL);
		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
			uint64_t thisguid;

			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);

			if (stream_nvfs != NULL)
				break;
		}

		/* check for promote */
		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
		    &stream_originguid);
		if (stream_nvfs && originguid != stream_originguid) {
			switch (created_before(hdl, local_avl,
			    stream_originguid, originguid)) {
			case 1: {
				/* promote it! */
				nvlist_t *origin_nvfs;
				char *origin_fsname;

				origin_nvfs = fsavl_find(local_avl, originguid,
				    NULL);
				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
				    "name", &origin_fsname));
				error = recv_promote(hdl, fsname, origin_fsname,
				    flags);
				if (error == 0)
					progress = B_TRUE;
				break;
			}
			default:
				break;
			case -1:
				fsavl_destroy(local_avl);
				nvlist_free(local_nv);
				return (-1);
			}
			/*
			 * We had/have the wrong origin, therefore our
			 * list of snapshots is wrong.  Need to handle
			 * them on the next pass.
			 */
			needagain = B_TRUE;
			continue;
		}

		for (snapelem = nvlist_next_nvpair(snaps, NULL);
		    snapelem; snapelem = nextsnapelem) {
			uint64_t thisguid;
			char *stream_snapname;
			nvlist_t *found, *props;

			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);

			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
			found = fsavl_find(stream_avl, thisguid,
			    &stream_snapname);

			/* check for delete */
			if (found == NULL) {
				char name[ZFS_MAX_DATASET_NAME_LEN];

				if (!flags->force)
					continue;

				(void) snprintf(name, sizeof (name), "%s@%s",
				    fsname, nvpair_name(snapelem));

				error = recv_destroy(hdl, name,
				    strlen(fsname)+1, newname, flags);
				if (error)
					needagain = B_TRUE;
				else
					progress = B_TRUE;
				sprintf(guidname, "%llu",
				    (u_longlong_t)thisguid);
				nvlist_add_boolean(deleted, guidname);
				continue;
			}

			stream_nvfs = found;

			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
			    &props) && 0 == nvlist_lookup_nvlist(props,
			    stream_snapname, &props)) {
				zfs_cmd_t zc = {"\0"};

				zc.zc_cookie = B_TRUE; /* received */
				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
				    "%s@%s", fsname, nvpair_name(snapelem));
				if (zcmd_write_src_nvlist(hdl, &zc,
				    props) == 0) {
					(void) zfs_ioctl(hdl,
					    ZFS_IOC_SET_PROP, &zc);
					zcmd_free_nvlists(&zc);
				}
			}

			/* check for different snapname */
			if (strcmp(nvpair_name(snapelem),
			    stream_snapname) != 0) {
				char name[ZFS_MAX_DATASET_NAME_LEN];
				char tryname[ZFS_MAX_DATASET_NAME_LEN];

				(void) snprintf(name, sizeof (name), "%s@%s",
				    fsname, nvpair_name(snapelem));
				(void) snprintf(tryname, sizeof (name), "%s@%s",
				    fsname, stream_snapname);

				error = recv_rename(hdl, name, tryname,
				    strlen(fsname)+1, newname, flags);
				if (error)
					needagain = B_TRUE;
				else
					progress = B_TRUE;
			}

			if (strcmp(stream_snapname, fromsnap) == 0)
				fromguid = thisguid;
		}

		/* check for delete */
		if (stream_nvfs == NULL) {
			if (!flags->force)
				continue;

			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
			    newname, flags);
			if (error)
				needagain = B_TRUE;
			else
				progress = B_TRUE;
			sprintf(guidname, "%llu",
			    (u_longlong_t)parent_fromsnap_guid);
			nvlist_add_boolean(deleted, guidname);
			continue;
		}

		if (fromguid == 0) {
			if (flags->verbose) {
				(void) printf("local fs %s does not have "
				    "fromsnap (%s in stream); must have "
				    "been deleted locally; ignoring\n",
				    fsname, fromsnap);
			}
			continue;
		}

		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
		    "name", &stream_fsname));
		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
		    "parentfromsnap", &stream_parent_fromsnap_guid));

		s1 = strrchr(fsname, '/');
		s2 = strrchr(stream_fsname, '/');

		/*
		 * Check if we're going to rename based on parent guid change
		 * and the current parent guid was also deleted. If it was then
		 * rename will fail and is likely unneeded, so avoid this and
		 * force an early retry to determine the new
		 * parent_fromsnap_guid.
		 */
		if (stream_parent_fromsnap_guid != 0 &&
		    parent_fromsnap_guid != 0 &&
		    stream_parent_fromsnap_guid != parent_fromsnap_guid) {
			sprintf(guidname, "%llu",
			    (u_longlong_t)parent_fromsnap_guid);
			if (nvlist_exists(deleted, guidname)) {
				progress = B_TRUE;
				needagain = B_TRUE;
				goto doagain;
			}
		}

		/*
		 * Check for rename. If the exact receive path is specified, it
		 * does not count as a rename, but we still need to check the
		 * datasets beneath it.
		 */
		if ((stream_parent_fromsnap_guid != 0 &&
		    parent_fromsnap_guid != 0 &&
		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
		    ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
			nvlist_t *parent;
			char tryname[ZFS_MAX_DATASET_NAME_LEN];

			parent = fsavl_find(local_avl,
			    stream_parent_fromsnap_guid, NULL);
			/*
			 * NB: parent might not be found if we used the
			 * tosnap for stream_parent_fromsnap_guid,
			 * because the parent is a newly-created fs;
			 * we'll be able to rename it after we recv the
			 * new fs.
			 */
			if (parent != NULL) {
				char *pname;

				VERIFY(0 == nvlist_lookup_string(parent, "name",
				    &pname));
				(void) snprintf(tryname, sizeof (tryname),
				    "%s%s", pname, strrchr(stream_fsname, '/'));
			} else {
				tryname[0] = '\0';
				if (flags->verbose) {
					(void) printf("local fs %s new parent "
					    "not found\n", fsname);
				}
			}

			newname[0] = '\0';

			error = recv_rename(hdl, fsname, tryname,
			    strlen(tofs)+1, newname, flags);

			if (renamed != NULL && newname[0] != '\0') {
				VERIFY(0 == nvlist_add_boolean(renamed,
				    newname));
			}

			if (error)
				needagain = B_TRUE;
			else
				progress = B_TRUE;
		}
	}

doagain:
	fsavl_destroy(local_avl);
	nvlist_free(local_nv);
	nvlist_free(deleted);

	if (needagain && progress) {
		/* do another pass to fix up temporary names */
		if (flags->verbose)
			(void) printf("another pass:\n");
		goto again;
	}

	return (needagain || error != 0);
}

static int
zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
    recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
    char **top_zfs, int cleanup_fd, uint64_t *action_handlep,
    nvlist_t *cmdprops)
{
	nvlist_t *stream_nv = NULL;
	avl_tree_t *stream_avl = NULL;
	char *fromsnap = NULL;
	char *sendsnap = NULL;
	char *cp;
	char tofs[ZFS_MAX_DATASET_NAME_LEN];
	char sendfs[ZFS_MAX_DATASET_NAME_LEN];
	char errbuf[1024];
	dmu_replay_record_t drre;
	int error;
	boolean_t anyerr = B_FALSE;
	boolean_t softerr = B_FALSE;
	boolean_t recursive, raw;

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot receive"));

	assert(drr->drr_type == DRR_BEGIN);
	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
	assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
	    DMU_COMPOUNDSTREAM);

	/*
	 * Read in the nvlist from the stream.
	 */
	if (drr->drr_payloadlen != 0) {
		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
		    &stream_nv, flags->byteswap, zc);
		if (error) {
			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			goto out;
		}
	}

	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
	    ENOENT);
	raw = (nvlist_lookup_boolean(stream_nv, "raw") == 0);

	if (recursive && strchr(destname, '@')) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "cannot specify snapshot name for multi-snapshot stream"));
		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
		goto out;
	}

	/*
	 * Read in the end record and verify checksum.
	 */
	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
	    flags->byteswap, NULL)))
		goto out;
	if (flags->byteswap) {
		drre.drr_type = BSWAP_32(drre.drr_type);
		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
	}
	if (drre.drr_type != DRR_END) {
		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
		goto out;
	}
	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "incorrect header checksum"));
		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
		goto out;
	}

	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);

	if (drr->drr_payloadlen != 0) {
		nvlist_t *stream_fss;

		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
		    &stream_fss));
		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "couldn't allocate avl tree"));
			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
			goto out;
		}

		if (fromsnap != NULL && recursive) {
			nvlist_t *renamed = NULL;
			nvpair_t *pair = NULL;

			(void) strlcpy(tofs, destname, sizeof (tofs));
			if (flags->isprefix) {
				struct drr_begin *drrb = &drr->drr_u.drr_begin;
				int i;

				if (flags->istail) {
					cp = strrchr(drrb->drr_toname, '/');
					if (cp == NULL) {
						(void) strlcat(tofs, "/",
						    sizeof (tofs));
						i = 0;
					} else {
						i = (cp - drrb->drr_toname);
					}
				} else {
					i = strcspn(drrb->drr_toname, "/@");
				}
				/* zfs_receive_one() will create_parents() */
				(void) strlcat(tofs, &drrb->drr_toname[i],
				    sizeof (tofs));
				*strchr(tofs, '@') = '\0';
			}

			if (!flags->dryrun && !flags->nomount) {
				VERIFY(0 == nvlist_alloc(&renamed,
				    NV_UNIQUE_NAME, 0));
			}

			softerr = recv_incremental_replication(hdl, tofs, flags,
			    stream_nv, stream_avl, renamed);

			/* Unmount renamed filesystems before receiving. */
			while ((pair = nvlist_next_nvpair(renamed,
			    pair)) != NULL) {
				zfs_handle_t *zhp;
				prop_changelist_t *clp = NULL;

				zhp = zfs_open(hdl, nvpair_name(pair),
				    ZFS_TYPE_FILESYSTEM);
				if (zhp != NULL) {
					clp = changelist_gather(zhp,
					    ZFS_PROP_MOUNTPOINT, 0, 0);
					zfs_close(zhp);
					if (clp != NULL) {
						softerr |=
						    changelist_prefix(clp);
						changelist_free(clp);
					}
				}
			}

			nvlist_free(renamed);
		}
	}

	/*
	 * Get the fs specified by the first path in the stream (the top level
	 * specified by 'zfs send') and pass it to each invocation of
	 * zfs_receive_one().
	 */
	(void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
	    sizeof (sendfs));
	if ((cp = strchr(sendfs, '@')) != NULL) {
		*cp = '\0';
		/*
		 * Find the "sendsnap", the final snapshot in a replication
		 * stream.  zfs_receive_one() handles certain errors
		 * differently, depending on if the contained stream is the
		 * last one or not.
		 */
		sendsnap = (cp + 1);
	}

	/* Finally, receive each contained stream */
	do {
		/*
		 * we should figure out if it has a recoverable
		 * error, in which case do a recv_skip() and drive on.
		 * Note, if we fail due to already having this guid,
		 * zfs_receive_one() will take care of it (ie,
		 * recv_skip() and return 0).
		 */
		error = zfs_receive_impl(hdl, destname, NULL, flags, fd,
		    sendfs, stream_nv, stream_avl, top_zfs, cleanup_fd,
		    action_handlep, sendsnap, cmdprops);
		if (error == ENODATA) {
			error = 0;
			break;
		}
		anyerr |= error;
	} while (error == 0);

	if (drr->drr_payloadlen != 0 && recursive && fromsnap != NULL) {
		/*
		 * Now that we have the fs's they sent us, try the
		 * renames again.
		 */
		softerr = recv_incremental_replication(hdl, tofs, flags,
		    stream_nv, stream_avl, NULL);
	}

	if (raw && softerr == 0 && *top_zfs != NULL) {
		softerr = recv_fix_encryption_hierarchy(hdl, *top_zfs,
		    stream_nv, stream_avl);
	}

out:
	fsavl_destroy(stream_avl);
	nvlist_free(stream_nv);
	if (softerr)
		error = -2;
	if (anyerr)
		error = -1;
	return (error);
}

static void
trunc_prop_errs(int truncated)
{
	ASSERT(truncated != 0);

	if (truncated == 1)
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
		    "1 more property could not be set\n"));
	else
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
		    "%d more properties could not be set\n"), truncated);
}

static int
recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
{
	dmu_replay_record_t *drr;
	void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
	uint64_t payload_size;
	char errbuf[1024];

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot receive"));

	/* XXX would be great to use lseek if possible... */
	drr = buf;

	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
	    byteswap, NULL) == 0) {
		if (byteswap)
			drr->drr_type = BSWAP_32(drr->drr_type);

		switch (drr->drr_type) {
		case DRR_BEGIN:
			if (drr->drr_payloadlen != 0) {
				(void) recv_read(hdl, fd, buf,
				    drr->drr_payloadlen, B_FALSE, NULL);
			}
			break;

		case DRR_END:
			free(buf);
			return (0);

		case DRR_OBJECT:
			if (byteswap) {
				drr->drr_u.drr_object.drr_bonuslen =
				    BSWAP_32(drr->drr_u.drr_object.
				    drr_bonuslen);
				drr->drr_u.drr_object.drr_raw_bonuslen =
				    BSWAP_32(drr->drr_u.drr_object.
				    drr_raw_bonuslen);
			}

			payload_size =
			    DRR_OBJECT_PAYLOAD_SIZE(&drr->drr_u.drr_object);
			(void) recv_read(hdl, fd, buf, payload_size,
			    B_FALSE, NULL);
			break;

		case DRR_WRITE:
			if (byteswap) {
				drr->drr_u.drr_write.drr_logical_size =
				    BSWAP_64(
				    drr->drr_u.drr_write.drr_logical_size);
				drr->drr_u.drr_write.drr_compressed_size =
				    BSWAP_64(
				    drr->drr_u.drr_write.drr_compressed_size);
			}
			payload_size =
			    DRR_WRITE_PAYLOAD_SIZE(&drr->drr_u.drr_write);
			(void) recv_read(hdl, fd, buf,
			    payload_size, B_FALSE, NULL);
			break;
		case DRR_SPILL:
			if (byteswap) {
				drr->drr_u.drr_spill.drr_length =
				    BSWAP_64(drr->drr_u.drr_spill.drr_length);
				drr->drr_u.drr_spill.drr_compressed_size =
				    BSWAP_64(drr->drr_u.drr_spill.
				    drr_compressed_size);
			}

			payload_size =
			    DRR_SPILL_PAYLOAD_SIZE(&drr->drr_u.drr_spill);
			(void) recv_read(hdl, fd, buf, payload_size,
			    B_FALSE, NULL);
			break;
		case DRR_WRITE_EMBEDDED:
			if (byteswap) {
				drr->drr_u.drr_write_embedded.drr_psize =
				    BSWAP_32(drr->drr_u.drr_write_embedded.
				    drr_psize);
			}
			(void) recv_read(hdl, fd, buf,
			    P2ROUNDUP(drr->drr_u.drr_write_embedded.drr_psize,
			    8), B_FALSE, NULL);
			break;
		case DRR_OBJECT_RANGE:
		case DRR_WRITE_BYREF:
		case DRR_FREEOBJECTS:
		case DRR_FREE:
			break;

		default:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "invalid record type"));
			free(buf);
			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
		}
	}

	free(buf);
	return (-1);
}

static void
recv_ecksum_set_aux(libzfs_handle_t *hdl, const char *target_snap,
    boolean_t resumable)
{
	char target_fs[ZFS_MAX_DATASET_NAME_LEN];

	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
	    "checksum mismatch or incomplete stream"));

	if (!resumable)
		return;
	(void) strlcpy(target_fs, target_snap, sizeof (target_fs));
	*strchr(target_fs, '@') = '\0';
	zfs_handle_t *zhp = zfs_open(hdl, target_fs,
	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
	if (zhp == NULL)
		return;

	char token_buf[ZFS_MAXPROPLEN];
	int error = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
	    token_buf, sizeof (token_buf),
	    NULL, NULL, 0, B_TRUE);
	if (error == 0) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "checksum mismatch or incomplete stream.\n"
		    "Partially received snapshot is saved.\n"
		    "A resuming stream can be generated on the sending "
		    "system by running:\n"
		    "    zfs send -t %s"),
		    token_buf);
	}
	zfs_close(zhp);
}

/*
 * Prepare a new nvlist of properties that are to override (-o) or be excluded
 * (-x) from the received dataset
 * recvprops: received properties from the send stream
 * cmdprops: raw input properties from command line
 * origprops: properties, both locally-set and received, currently set on the
 *            target dataset if it exists, NULL otherwise.
 * oxprops: valid output override (-o) and excluded (-x) properties
 */
static int
zfs_setup_cmdline_props(libzfs_handle_t *hdl, zfs_type_t type,
    char *fsname, boolean_t zoned, boolean_t recursive, boolean_t newfs,
    boolean_t raw, boolean_t toplevel, nvlist_t *recvprops, nvlist_t *cmdprops,
    nvlist_t *origprops, nvlist_t **oxprops, uint8_t **wkeydata_out,
    uint_t *wkeylen_out, const char *errbuf)
{
	nvpair_t *nvp;
	nvlist_t *oprops, *voprops;
	zfs_handle_t *zhp = NULL;
	zpool_handle_t *zpool_hdl = NULL;
	char *cp;
	int ret = 0;
	char namebuf[ZFS_MAX_DATASET_NAME_LEN];

	if (nvlist_empty(cmdprops))
		return (0); /* No properties to override or exclude */

	*oxprops = fnvlist_alloc();
	oprops = fnvlist_alloc();

	strlcpy(namebuf, fsname, ZFS_MAX_DATASET_NAME_LEN);

	/*
	 * Get our dataset handle. The target dataset may not exist yet.
	 */
	if (zfs_dataset_exists(hdl, namebuf, ZFS_TYPE_DATASET)) {
		zhp = zfs_open(hdl, namebuf, ZFS_TYPE_DATASET);
		if (zhp == NULL) {
			ret = -1;
			goto error;
		}
	}

	/* open the zpool handle */
	cp = strchr(namebuf, '/');
	if (cp != NULL)
		*cp = '\0';
	zpool_hdl = zpool_open(hdl, namebuf);
	if (zpool_hdl == NULL) {
		ret = -1;
		goto error;
	}

	/* restore namebuf to match fsname for later use */
	if (cp != NULL)
		*cp = '/';

	/*
	 * first iteration: process excluded (-x) properties now and gather
	 * added (-o) properties to be later processed by zfs_valid_proplist()
	 */
	nvp = NULL;
	while ((nvp = nvlist_next_nvpair(cmdprops, nvp)) != NULL) {
		const char *name = nvpair_name(nvp);
		zfs_prop_t prop = zfs_name_to_prop(name);

		/* "origin" is processed separately, don't handle it here */
		if (prop == ZFS_PROP_ORIGIN)
			continue;

		/*
		 * we're trying to override or exclude a property that does not
		 * make sense for this type of dataset, but we don't want to
		 * fail if the receive is recursive: this comes in handy when
		 * the send stream contains, for instance, a child ZVOL and
		 * we're trying to receive it with "-o atime=on"
		 */
		if (!zfs_prop_valid_for_type(prop, type, B_FALSE) &&
		    !zfs_prop_user(name)) {
			if (recursive)
				continue;
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "property '%s' does not apply to datasets of this "
			    "type"), name);
			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
			goto error;
		}

		/* raw streams can't override encryption properties */
		if ((zfs_prop_encryption_key_param(prop) ||
		    prop == ZFS_PROP_ENCRYPTION) && (raw || !newfs)) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "encryption property '%s' cannot "
			    "be set or excluded for raw or incremental "
			    "streams."), name);
			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
			goto error;
		}

		switch (nvpair_type(nvp)) {
		case DATA_TYPE_BOOLEAN: /* -x property */
			/*
			 * DATA_TYPE_BOOLEAN is the way we're asked to "exclude"
			 * a property: this is done by forcing an explicit
			 * inherit on the destination so the effective value is
			 * not the one we received from the send stream.
			 * We do this only if the property is not already
			 * locally-set, in which case its value will take
			 * priority over the received anyway.
			 */
			if (nvlist_exists(origprops, name)) {
				nvlist_t *attrs;

				attrs = fnvlist_lookup_nvlist(origprops, name);
				if (strcmp(fnvlist_lookup_string(attrs,
				    ZPROP_SOURCE), ZPROP_SOURCE_VAL_RECVD) != 0)
					continue;
			}
			/*
			 * We can't force an explicit inherit on non-inheritable
			 * properties: if we're asked to exclude this kind of
			 * values we remove them from "recvprops" input nvlist.
			 */
			if (!zfs_prop_inheritable(prop) &&
			    !zfs_prop_user(name) && /* can be inherited too */
			    nvlist_exists(recvprops, name))
				fnvlist_remove(recvprops, name);
			else
				fnvlist_add_nvpair(*oxprops, nvp);
			break;
		case DATA_TYPE_STRING: /* -o property=value */
			fnvlist_add_nvpair(oprops, nvp);
			break;
		default:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "property '%s' must be a string or boolean"), name);
			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
			goto error;
		}
	}

	if (toplevel) {
		/* convert override strings properties to native */
		if ((voprops = zfs_valid_proplist(hdl, ZFS_TYPE_DATASET,
		    oprops, zoned, zhp, zpool_hdl, B_FALSE, errbuf)) == NULL) {
			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
			goto error;
		}

		/*
		 * zfs_crypto_create() requires the parent name. Get it
		 * by truncating the fsname copy stored in namebuf.
		 */
		cp = strrchr(namebuf, '/');
		if (cp != NULL)
			*cp = '\0';

		if (!raw && zfs_crypto_create(hdl, namebuf, voprops, NULL,
		    B_FALSE, wkeydata_out, wkeylen_out) != 0) {
			fnvlist_free(voprops);
			ret = zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
			goto error;
		}

		/* second pass: process "-o" properties */
		fnvlist_merge(*oxprops, voprops);
		fnvlist_free(voprops);
	} else {
		/* override props on child dataset are inherited */
		nvp = NULL;
		while ((nvp = nvlist_next_nvpair(oprops, nvp)) != NULL) {
			const char *name = nvpair_name(nvp);
			fnvlist_add_boolean(*oxprops, name);
		}
	}

error:
	if (zhp != NULL)
		zfs_close(zhp);
	if (zpool_hdl != NULL)
		zpool_close(zpool_hdl);
	fnvlist_free(oprops);
	return (ret);
}

/*
 * Restores a backup of tosnap from the file descriptor specified by infd.
 */
static int
zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
    const char *originsnap, recvflags_t *flags, dmu_replay_record_t *drr,
    dmu_replay_record_t *drr_noswap, const char *sendfs, nvlist_t *stream_nv,
    avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
    uint64_t *action_handlep, const char *finalsnap, nvlist_t *cmdprops)
{
	time_t begin_time;
	int ioctl_err, ioctl_errno, err;
	char *cp;
	struct drr_begin *drrb = &drr->drr_u.drr_begin;
	char errbuf[1024];
	const char *chopprefix;
	boolean_t newfs = B_FALSE;
	boolean_t stream_wantsnewfs;
	boolean_t newprops = B_FALSE;
	uint64_t read_bytes = 0;
	uint64_t errflags = 0;
	uint64_t parent_snapguid = 0;
	prop_changelist_t *clp = NULL;
	nvlist_t *snapprops_nvlist = NULL;
	nvlist_t *snapholds_nvlist = NULL;
	zprop_errflags_t prop_errflags;
	nvlist_t *prop_errors = NULL;
	boolean_t recursive;
	char *snapname = NULL;
	char destsnap[MAXPATHLEN * 2];
	char origin[MAXNAMELEN];
	char name[MAXPATHLEN];
	char tmp_keylocation[MAXNAMELEN];
	nvlist_t *rcvprops = NULL; /* props received from the send stream */
	nvlist_t *oxprops = NULL; /* override (-o) and exclude (-x) props */
	nvlist_t *origprops = NULL; /* original props (if destination exists) */
	zfs_type_t type;
	boolean_t toplevel = B_FALSE;
	boolean_t zoned = B_FALSE;
	boolean_t hastoken = B_FALSE;
	boolean_t redacted;
	uint8_t *wkeydata = NULL;
	uint_t wkeylen = 0;

	begin_time = time(NULL);
	bzero(origin, MAXNAMELEN);
	bzero(tmp_keylocation, MAXNAMELEN);

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot receive"));

	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
	    ENOENT);

	/* Did the user request holds be skipped via zfs recv -k? */
	boolean_t holds = flags->holds && !flags->skipholds;

	if (stream_avl != NULL) {
		char *keylocation = NULL;
		nvlist_t *lookup = NULL;
		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
		    &snapname);

		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
		    &parent_snapguid);
		err = nvlist_lookup_nvlist(fs, "props", &rcvprops);
		if (err) {
			VERIFY(0 == nvlist_alloc(&rcvprops, NV_UNIQUE_NAME, 0));
			newprops = B_TRUE;
		}

		/*
		 * The keylocation property may only be set on encryption roots,
		 * but this dataset might not become an encryption root until
		 * recv_fix_encryption_hierarchy() is called. That function
		 * will fixup the keylocation anyway, so we temporarily unset
		 * the keylocation for now to avoid any errors from the receive
		 * ioctl.
		 */
		err = nvlist_lookup_string(rcvprops,
		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
		if (err == 0) {
			strcpy(tmp_keylocation, keylocation);
			(void) nvlist_remove_all(rcvprops,
			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION));
		}

		if (flags->canmountoff) {
			VERIFY(0 == nvlist_add_uint64(rcvprops,
			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
		} else if (newprops) {	/* nothing in rcvprops, eliminate it */
			nvlist_free(rcvprops);
			rcvprops = NULL;
			newprops = B_FALSE;
		}
		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &lookup)) {
			VERIFY(0 == nvlist_lookup_nvlist(lookup,
			    snapname, &snapprops_nvlist));
		}
		if (holds) {
			if (0 == nvlist_lookup_nvlist(fs, "snapholds",
			    &lookup)) {
				VERIFY(0 == nvlist_lookup_nvlist(lookup,
				    snapname, &snapholds_nvlist));
			}
		}
	}

	cp = NULL;

	/*
	 * Determine how much of the snapshot name stored in the stream
	 * we are going to tack on to the name they specified on the
	 * command line, and how much we are going to chop off.
	 *
	 * If they specified a snapshot, chop the entire name stored in
	 * the stream.
	 */
	if (flags->istail) {
		/*
		 * A filesystem was specified with -e. We want to tack on only
		 * the tail of the sent snapshot path.
		 */
		if (strchr(tosnap, '@')) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
			    "argument - snapshot not allowed with -e"));
			err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
			goto out;
		}

		chopprefix = strrchr(sendfs, '/');

		if (chopprefix == NULL) {
			/*
			 * The tail is the poolname, so we need to
			 * prepend a path separator.
			 */
			int len = strlen(drrb->drr_toname);
			cp = malloc(len + 2);
			cp[0] = '/';
			(void) strcpy(&cp[1], drrb->drr_toname);
			chopprefix = cp;
		} else {
			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
		}
	} else if (flags->isprefix) {
		/*
		 * A filesystem was specified with -d. We want to tack on
		 * everything but the first element of the sent snapshot path
		 * (all but the pool name).
		 */
		if (strchr(tosnap, '@')) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
			    "argument - snapshot not allowed with -d"));
			err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
			goto out;
		}

		chopprefix = strchr(drrb->drr_toname, '/');
		if (chopprefix == NULL)
			chopprefix = strchr(drrb->drr_toname, '@');
	} else if (strchr(tosnap, '@') == NULL) {
		/*
		 * If a filesystem was specified without -d or -e, we want to
		 * tack on everything after the fs specified by 'zfs send'.
		 */
		chopprefix = drrb->drr_toname + strlen(sendfs);
	} else {
		/* A snapshot was specified as an exact path (no -d or -e). */
		if (recursive) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "cannot specify snapshot name for multi-snapshot "
			    "stream"));
			err = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			goto out;
		}
		chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
	}

	ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
	ASSERT(chopprefix > drrb->drr_toname || strchr(sendfs, '/') == NULL);
	ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname) ||
	    strchr(sendfs, '/') == NULL);
	ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
	    chopprefix[0] == '\0');

	/*
	 * Determine name of destination snapshot.
	 */
	(void) strlcpy(destsnap, tosnap, sizeof (destsnap));
	(void) strlcat(destsnap, chopprefix, sizeof (destsnap));
	free(cp);
	if (!zfs_name_valid(destsnap, ZFS_TYPE_SNAPSHOT)) {
		err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
		goto out;
	}

	/*
	 * Determine the name of the origin snapshot.
	 */
	if (originsnap) {
		(void) strlcpy(origin, originsnap, sizeof (origin));
		if (flags->verbose)
			(void) printf("using provided clone origin %s\n",
			    origin);
	} else if (drrb->drr_flags & DRR_FLAG_CLONE) {
		if (guid_to_name(hdl, destsnap,
		    drrb->drr_fromguid, B_FALSE, origin) != 0) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "local origin for clone %s does not exist"),
			    destsnap);
			err = zfs_error(hdl, EZFS_NOENT, errbuf);
			goto out;
		}
		if (flags->verbose)
			(void) printf("found clone origin %s\n", origin);
	}

	boolean_t resuming = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
	    DMU_BACKUP_FEATURE_RESUMING;
	boolean_t raw = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
	    DMU_BACKUP_FEATURE_RAW;
	boolean_t embedded = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
	    DMU_BACKUP_FEATURE_EMBED_DATA;
	stream_wantsnewfs = (drrb->drr_fromguid == 0 ||
	    (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && !resuming;

	if (stream_wantsnewfs) {
		/*
		 * if the parent fs does not exist, look for it based on
		 * the parent snap GUID
		 */
		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
		    "cannot receive new filesystem stream"));

		(void) strcpy(name, destsnap);
		cp = strrchr(name, '/');
		if (cp)
			*cp = '\0';
		if (cp &&
		    !zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
			char suffix[ZFS_MAX_DATASET_NAME_LEN];
			(void) strcpy(suffix, strrchr(destsnap, '/'));
			if (guid_to_name(hdl, name, parent_snapguid,
			    B_FALSE, destsnap) == 0) {
				*strchr(destsnap, '@') = '\0';
				(void) strcat(destsnap, suffix);
			}
		}
	} else {
		/*
		 * If the fs does not exist, look for it based on the
		 * fromsnap GUID.
		 */
		if (resuming) {
			(void) snprintf(errbuf, sizeof (errbuf),
			    dgettext(TEXT_DOMAIN,
			    "cannot receive resume stream"));
		} else {
			(void) snprintf(errbuf, sizeof (errbuf),
			    dgettext(TEXT_DOMAIN,
			    "cannot receive incremental stream"));
		}

		(void) strcpy(name, destsnap);
		*strchr(name, '@') = '\0';

		/*
		 * If the exact receive path was specified and this is the
		 * topmost path in the stream, then if the fs does not exist we
		 * should look no further.
		 */
		if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
		    !zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
			char snap[ZFS_MAX_DATASET_NAME_LEN];
			(void) strcpy(snap, strchr(destsnap, '@'));
			if (guid_to_name(hdl, name, drrb->drr_fromguid,
			    B_FALSE, destsnap) == 0) {
				*strchr(destsnap, '@') = '\0';
				(void) strcat(destsnap, snap);
			}
		}
	}

	(void) strcpy(name, destsnap);
	*strchr(name, '@') = '\0';

	redacted = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
	    DMU_BACKUP_FEATURE_REDACTED;

	if (zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
		zfs_cmd_t zc = {"\0"};
		zfs_handle_t *zhp;
		boolean_t encrypted;

		(void) strcpy(zc.zc_name, name);

		/*
		 * Destination fs exists.  It must be one of these cases:
		 *  - an incremental send stream
		 *  - the stream specifies a new fs (full stream or clone)
		 *    and they want us to blow away the existing fs (and
		 *    have therefore specified -F and removed any snapshots)
		 *  - we are resuming a failed receive.
		 */
		if (stream_wantsnewfs) {
			boolean_t is_volume = drrb->drr_type == DMU_OST_ZVOL;
			if (!flags->force) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "destination '%s' exists\n"
				    "must specify -F to overwrite it"), name);
				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
				goto out;
			}
			if (zfs_ioctl(hdl, ZFS_IOC_SNAPSHOT_LIST_NEXT,
			    &zc) == 0) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "destination has snapshots (eg. %s)\n"
				    "must destroy them to overwrite it"),
				    zc.zc_name);
				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
				goto out;
			}
			if (is_volume && strrchr(name, '/') == NULL) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "destination %s is the root dataset\n"
				    "cannot overwrite with a ZVOL"),
				    name);
				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
				goto out;
			}
			if (is_volume &&
			    zfs_ioctl(hdl, ZFS_IOC_DATASET_LIST_NEXT,
			    &zc) == 0) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "destination has children (eg. %s)\n"
				    "cannot overwrite with a ZVOL"),
				    zc.zc_name);
				err = zfs_error(hdl, EZFS_WRONG_PARENT, errbuf);
				goto out;
			}
		}

		if ((zhp = zfs_open(hdl, name,
		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
			err = -1;
			goto out;
		}

		if (stream_wantsnewfs &&
		    zhp->zfs_dmustats.dds_origin[0]) {
			zfs_close(zhp);
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "destination '%s' is a clone\n"
			    "must destroy it to overwrite it"), name);
			err = zfs_error(hdl, EZFS_EXISTS, errbuf);
			goto out;
		}

		/*
		 * Raw sends can not be performed as an incremental on top
		 * of existing unencrypted datasets. zfs recv -F can't be
		 * used to blow away an existing encrypted filesystem. This
		 * is because it would require the dsl dir to point to the
		 * new key (or lack of a key) and the old key at the same
		 * time. The -F flag may still be used for deleting
		 * intermediate snapshots that would otherwise prevent the
		 * receive from working.
		 */
		encrypted = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) !=
		    ZIO_CRYPT_OFF;
		if (!stream_wantsnewfs && !encrypted && raw) {
			zfs_close(zhp);
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "cannot perform raw receive on top of "
			    "existing unencrypted dataset"));
			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
			goto out;
		}

		if (stream_wantsnewfs && flags->force &&
		    ((raw && !encrypted) || encrypted)) {
			zfs_close(zhp);
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "zfs receive -F cannot be used to destroy an "
			    "encrypted filesystem or overwrite an "
			    "unencrypted one with an encrypted one"));
			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
			goto out;
		}

		if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
		    stream_wantsnewfs) {
			/* We can't do online recv in this case */
			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
			if (clp == NULL) {
				zfs_close(zhp);
				err = -1;
				goto out;
			}
			if (changelist_prefix(clp) != 0) {
				changelist_free(clp);
				zfs_close(zhp);
				err = -1;
				goto out;
			}
		}

		/*
		 * If we are resuming a newfs, set newfs here so that we will
		 * mount it if the recv succeeds this time.  We can tell
		 * that it was a newfs on the first recv because the fs
		 * itself will be inconsistent (if the fs existed when we
		 * did the first recv, we would have received it into
		 * .../%recv).
		 */
		if (resuming && zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT))
			newfs = B_TRUE;

		/* we want to know if we're zoned when validating -o|-x props */
		zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);

		/* may need this info later, get it now we have zhp around */
		if (zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN, NULL, 0,
		    NULL, NULL, 0, B_TRUE) == 0)
			hastoken = B_TRUE;

		/* gather existing properties on destination */
		origprops = fnvlist_alloc();
		fnvlist_merge(origprops, zhp->zfs_props);
		fnvlist_merge(origprops, zhp->zfs_user_props);

		zfs_close(zhp);
	} else {
		zfs_handle_t *zhp;

		/*
		 * Destination filesystem does not exist.  Therefore we better
		 * be creating a new filesystem (either from a full backup, or
		 * a clone).  It would therefore be invalid if the user
		 * specified only the pool name (i.e. if the destination name
		 * contained no slash character).
		 */
		cp = strrchr(name, '/');

		if (!stream_wantsnewfs || cp == NULL) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "destination '%s' does not exist"), name);
			err = zfs_error(hdl, EZFS_NOENT, errbuf);
			goto out;
		}

		/*
		 * Trim off the final dataset component so we perform the
		 * recvbackup ioctl to the filesystems's parent.
		 */
		*cp = '\0';

		if (flags->isprefix && !flags->istail && !flags->dryrun &&
		    create_parents(hdl, destsnap, strlen(tosnap)) != 0) {
			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
			goto out;
		}

		/* validate parent */
		zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
		if (zhp == NULL) {
			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
			goto out;
		}
		if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "parent '%s' is not a filesystem"), name);
			err = zfs_error(hdl, EZFS_WRONG_PARENT, errbuf);
			zfs_close(zhp);
			goto out;
		}

		zfs_close(zhp);

		newfs = B_TRUE;
		*cp = '/';
	}

	if (flags->verbose) {
		(void) printf("%s %s stream of %s into %s\n",
		    flags->dryrun ? "would receive" : "receiving",
		    drrb->drr_fromguid ? "incremental" : "full",
		    drrb->drr_toname, destsnap);
		(void) fflush(stdout);
	}

	if (flags->dryrun) {
		void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);

		/*
		 * We have read the DRR_BEGIN record, but we have
		 * not yet read the payload. For non-dryrun sends
		 * this will be done by the kernel, so we must
		 * emulate that here, before attempting to read
		 * more records.
		 */
		err = recv_read(hdl, infd, buf, drr->drr_payloadlen,
		    flags->byteswap, NULL);
		free(buf);
		if (err != 0)
			goto out;

		err = recv_skip(hdl, infd, flags->byteswap);
		goto out;
	}

	/*
	 * If this is the top-level dataset, record it so we can use it
	 * for recursive operations later.
	 */
	if (top_zfs != NULL &&
	    (*top_zfs == NULL || strcmp(*top_zfs, name) == 0)) {
		toplevel = B_TRUE;
		if (*top_zfs == NULL)
			*top_zfs = zfs_strdup(hdl, name);
	}

	if (drrb->drr_type == DMU_OST_ZVOL) {
		type = ZFS_TYPE_VOLUME;
	} else if (drrb->drr_type == DMU_OST_ZFS) {
		type = ZFS_TYPE_FILESYSTEM;
	} else {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "invalid record type: 0x%d"), drrb->drr_type);
		err = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
		goto out;
	}
	if ((err = zfs_setup_cmdline_props(hdl, type, name, zoned, recursive,
	    stream_wantsnewfs, raw, toplevel, rcvprops, cmdprops, origprops,
	    &oxprops, &wkeydata, &wkeylen, errbuf)) != 0)
		goto out;

	/*
	 * When sending with properties (zfs send -p), the encryption property
	 * is not included because it is a SETONCE property and therefore
	 * treated as read only. However, we are always able to determine its
	 * value because raw sends will include it in the DRR_BDEGIN payload
	 * and non-raw sends with properties are not allowed for encrypted
	 * datasets. Therefore, if this is a non-raw properties stream, we can
	 * infer that the value should be ZIO_CRYPT_OFF and manually add that
	 * to the received properties.
	 */
	if (stream_wantsnewfs && !raw && rcvprops != NULL &&
	    !nvlist_exists(cmdprops, zfs_prop_to_name(ZFS_PROP_ENCRYPTION))) {
		if (oxprops == NULL)
			oxprops = fnvlist_alloc();
		fnvlist_add_uint64(oxprops,
		    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), ZIO_CRYPT_OFF);
	}

	err = ioctl_err = lzc_receive_with_cmdprops(destsnap, rcvprops,
	    oxprops, wkeydata, wkeylen, origin, flags->force, flags->resumable,
	    raw, infd, drr_noswap, cleanup_fd, &read_bytes, &errflags,
	    action_handlep, &prop_errors);
	ioctl_errno = ioctl_err;
	prop_errflags = errflags;

	if (err == 0) {
		nvpair_t *prop_err = NULL;

		while ((prop_err = nvlist_next_nvpair(prop_errors,
		    prop_err)) != NULL) {
			char tbuf[1024];
			zfs_prop_t prop;
			int intval;

			prop = zfs_name_to_prop(nvpair_name(prop_err));
			(void) nvpair_value_int32(prop_err, &intval);
			if (strcmp(nvpair_name(prop_err),
			    ZPROP_N_MORE_ERRORS) == 0) {
				trunc_prop_errs(intval);
				break;
			} else if (snapname == NULL || finalsnap == NULL ||
			    strcmp(finalsnap, snapname) == 0 ||
			    strcmp(nvpair_name(prop_err),
			    zfs_prop_to_name(ZFS_PROP_REFQUOTA)) != 0) {
				/*
				 * Skip the special case of, for example,
				 * "refquota", errors on intermediate
				 * snapshots leading up to a final one.
				 * That's why we have all of the checks above.
				 *
				 * See zfs_ioctl.c's extract_delay_props() for
				 * a list of props which can fail on
				 * intermediate snapshots, but shouldn't
				 * affect the overall receive.
				 */
				(void) snprintf(tbuf, sizeof (tbuf),
				    dgettext(TEXT_DOMAIN,
				    "cannot receive %s property on %s"),
				    nvpair_name(prop_err), name);
				zfs_setprop_error(hdl, prop, intval, tbuf);
			}
		}
	}

	if (err == 0 && snapprops_nvlist) {
		zfs_cmd_t zc = {"\0"};

		(void) strcpy(zc.zc_name, destsnap);
		zc.zc_cookie = B_TRUE; /* received */
		if (zcmd_write_src_nvlist(hdl, &zc, snapprops_nvlist) == 0) {
			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
			zcmd_free_nvlists(&zc);
		}
	}
	if (err == 0 && snapholds_nvlist) {
		nvpair_t *pair;
		nvlist_t *holds, *errors = NULL;
		int cleanup_fd = -1;

		VERIFY(0 == nvlist_alloc(&holds, 0, KM_SLEEP));
		for (pair = nvlist_next_nvpair(snapholds_nvlist, NULL);
		    pair != NULL;
		    pair = nvlist_next_nvpair(snapholds_nvlist, pair)) {
			VERIFY(0 == nvlist_add_string(holds, destsnap,
			    nvpair_name(pair)));
		}
		(void) lzc_hold(holds, cleanup_fd, &errors);
		nvlist_free(snapholds_nvlist);
		nvlist_free(holds);
	}

	if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
		/*
		 * It may be that this snapshot already exists,
		 * in which case we want to consume & ignore it
		 * rather than failing.
		 */
		avl_tree_t *local_avl;
		nvlist_t *local_nv, *fs;
		cp = strchr(destsnap, '@');

		/*
		 * XXX Do this faster by just iterating over snaps in
		 * this fs.  Also if zc_value does not exist, we will
		 * get a strange "does not exist" error message.
		 */
		*cp = '\0';
		if (gather_nvlist(hdl, destsnap, NULL, NULL, B_FALSE, B_TRUE,
		    B_FALSE, B_FALSE, B_FALSE, B_FALSE, B_FALSE, B_TRUE,
		    &local_nv, &local_avl) == 0) {
			*cp = '@';
			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
			fsavl_destroy(local_avl);
			nvlist_free(local_nv);

			if (fs != NULL) {
				if (flags->verbose) {
					(void) printf("snap %s already exists; "
					    "ignoring\n", destsnap);
				}
				err = ioctl_err = recv_skip(hdl, infd,
				    flags->byteswap);
			}
		}
		*cp = '@';
	}

	if (ioctl_err != 0) {
		switch (ioctl_errno) {
		case ENODEV:
			cp = strchr(destsnap, '@');
			*cp = '\0';
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "most recent snapshot of %s does not\n"
			    "match incremental source"), destsnap);
			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
			*cp = '@';
			break;
		case ETXTBSY:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "destination %s has been modified\n"
			    "since most recent snapshot"), name);
			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
			break;
		case EACCES:
			if (raw && stream_wantsnewfs) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "failed to create encryption key"));
			} else if (raw && !stream_wantsnewfs) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "encryption key does not match "
				    "existing key"));
			} else {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "inherited key must be loaded"));
			}
			(void) zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
			break;
		case EEXIST:
			cp = strchr(destsnap, '@');
			if (newfs) {
				/* it's the containing fs that exists */
				*cp = '\0';
			}
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "destination already exists"));
			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
			    destsnap);
			*cp = '@';
			break;
		case EINVAL:
			if (flags->resumable) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "kernel modules must be upgraded to "
				    "receive this stream."));
			} else if (embedded && !raw) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "incompatible embedded data stream "
				    "feature with encrypted receive."));
			}
			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			break;
		case ECKSUM:
			recv_ecksum_set_aux(hdl, destsnap, flags->resumable);
			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			break;
		case ENOTSUP:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "pool must be upgraded to receive this stream."));
			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
			break;
		case EDQUOT:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "destination %s space quota exceeded."), name);
			(void) zfs_error(hdl, EZFS_NOSPC, errbuf);
			break;
		case ZFS_ERR_FROM_IVSET_GUID_MISSING:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "IV set guid missing. See errata %u at "
			    "http://zfsonlinux.org/msg/ZFS-8000-ER."),
			    ZPOOL_ERRATA_ZOL_8308_ENCRYPTION);
			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			break;
		case ZFS_ERR_FROM_IVSET_GUID_MISMATCH:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "IV set guid mismatch. See the 'zfs receive' "
			    "man page section\n discussing the limitations "
			    "of raw encrypted send streams."));
			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			break;
		case ZFS_ERR_SPILL_BLOCK_FLAG_MISSING:
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "Spill block flag missing for raw send.\n"
			    "The zfs software on the sending system must "
			    "be updated."));
			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
			break;
		case EBUSY:
			if (hastoken) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "destination %s contains "
				    "partially-complete state from "
				    "\"zfs receive -s\"."), name);
				(void) zfs_error(hdl, EZFS_BUSY, errbuf);
				break;
			}
			/* fallthru */
		default:
			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
		}
	}

	/*
	 * Mount the target filesystem (if created).  Also mount any
	 * children of the target filesystem if we did a replication
	 * receive (indicated by stream_avl being non-NULL).
	 */
	if (clp) {
		if (!flags->nomount)
			err |= changelist_postfix(clp);
		changelist_free(clp);
	}

	if ((newfs || stream_avl) && type == ZFS_TYPE_FILESYSTEM && !redacted)
		flags->domount = B_TRUE;

	if (prop_errflags & ZPROP_ERR_NOCLEAR) {
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
		    "failed to clear unreceived properties on %s"), name);
		(void) fprintf(stderr, "\n");
	}
	if (prop_errflags & ZPROP_ERR_NORESTORE) {
		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
		    "failed to restore original properties on %s"), name);
		(void) fprintf(stderr, "\n");
	}

	if (err || ioctl_err) {
		err = -1;
		goto out;
	}

	if (flags->verbose) {
		char buf1[64];
		char buf2[64];
		uint64_t bytes = read_bytes;
		time_t delta = time(NULL) - begin_time;
		if (delta == 0)
			delta = 1;
		zfs_nicebytes(bytes, buf1, sizeof (buf1));
		zfs_nicebytes(bytes/delta, buf2, sizeof (buf1));

		(void) printf("received %s stream in %lu seconds (%s/sec)\n",
		    buf1, delta, buf2);
	}

	err = 0;
out:
	if (prop_errors != NULL)
		nvlist_free(prop_errors);

	if (tmp_keylocation[0] != '\0') {
		VERIFY(0 == nvlist_add_string(rcvprops,
		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), tmp_keylocation));
	}

	if (newprops)
		nvlist_free(rcvprops);

	nvlist_free(oxprops);
	nvlist_free(origprops);

	return (err);
}

/*
 * Check properties we were asked to override (both -o|-x)
 */
static boolean_t
zfs_receive_checkprops(libzfs_handle_t *hdl, nvlist_t *props,
    const char *errbuf)
{
	nvpair_t *nvp;
	zfs_prop_t prop;
	const char *name;

	nvp = NULL;
	while ((nvp = nvlist_next_nvpair(props, nvp)) != NULL) {
		name = nvpair_name(nvp);
		prop = zfs_name_to_prop(name);

		if (prop == ZPROP_INVAL) {
			if (!zfs_prop_user(name)) {
				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
				    "invalid property '%s'"), name);
				return (B_FALSE);
			}
			continue;
		}
		/*
		 * "origin" is readonly but is used to receive datasets as
		 * clones so we don't raise an error here
		 */
		if (prop == ZFS_PROP_ORIGIN)
			continue;

		/* encryption params have their own verification later */
		if (prop == ZFS_PROP_ENCRYPTION ||
		    zfs_prop_encryption_key_param(prop))
			continue;

		/*
		 * cannot override readonly, set-once and other specific
		 * settable properties
		 */
		if (zfs_prop_readonly(prop) || prop == ZFS_PROP_VERSION ||
		    prop == ZFS_PROP_VOLSIZE) {
			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
			    "invalid property '%s'"), name);
			return (B_FALSE);
		}
	}

	return (B_TRUE);
}

static int
zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap,
    const char *originsnap, recvflags_t *flags, int infd, const char *sendfs,
    nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
    uint64_t *action_handlep, const char *finalsnap, nvlist_t *cmdprops)
{
	int err;
	dmu_replay_record_t drr, drr_noswap;
	struct drr_begin *drrb = &drr.drr_u.drr_begin;
	char errbuf[1024];
	zio_cksum_t zcksum = { { 0 } };
	uint64_t featureflags;
	int hdrtype;

	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
	    "cannot receive"));

	/* check cmdline props, raise an error if they cannot be received */
	if (!zfs_receive_checkprops(hdl, cmdprops, errbuf)) {
		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
	}

	if (flags->isprefix &&
	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
		    "(%s) does not exist"), tosnap);
		return (zfs_error(hdl, EZFS_NOENT, errbuf));
	}
	if (originsnap &&
	    !zfs_dataset_exists(hdl, originsnap, ZFS_TYPE_DATASET)) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified origin fs "
		    "(%s) does not exist"), originsnap);
		return (zfs_error(hdl, EZFS_NOENT, errbuf));
	}

	/* read in the BEGIN record */
	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
	    &zcksum)))
		return (err);

	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
		/* It's the double end record at the end of a package */
		return (ENODATA);
	}

	/* the kernel needs the non-byteswapped begin record */
	drr_noswap = drr;

	flags->byteswap = B_FALSE;
	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
		/*
		 * We computed the checksum in the wrong byteorder in
		 * recv_read() above; do it again correctly.
		 */
		bzero(&zcksum, sizeof (zio_cksum_t));
		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
		flags->byteswap = B_TRUE;

		drr.drr_type = BSWAP_32(drr.drr_type);
		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
		drrb->drr_type = BSWAP_32(drrb->drr_type);
		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
	}

	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
		    "stream (bad magic number)"));
		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
	}

	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
	hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);

	if (!DMU_STREAM_SUPPORTED(featureflags) ||
	    (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
		    "stream has unsupported feature, feature flags = %lx"),
		    featureflags);
		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
	}

	/* Holds feature is set once in the compound stream header. */
	boolean_t holds = (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
	    DMU_BACKUP_FEATURE_HOLDS);
	if (holds)
		flags->holds = B_TRUE;

	if (strchr(drrb->drr_toname, '@') == NULL) {
		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
		    "stream (bad snapshot name)"));
		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
	}

	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
		char nonpackage_sendfs[ZFS_MAX_DATASET_NAME_LEN];
		if (sendfs == NULL) {
			/*
			 * We were not called from zfs_receive_package(). Get
			 * the fs specified by 'zfs send'.
			 */
			char *cp;
			(void) strlcpy(nonpackage_sendfs,
			    drr.drr_u.drr_begin.drr_toname,
			    sizeof (nonpackage_sendfs));
			if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
				*cp = '\0';
			sendfs = nonpackage_sendfs;
			VERIFY(finalsnap == NULL);
		}
		return (zfs_receive_one(hdl, infd, tosnap, originsnap, flags,
		    &drr, &drr_noswap, sendfs, stream_nv, stream_avl, top_zfs,
		    cleanup_fd, action_handlep, finalsnap, cmdprops));
	} else {
		assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
		    DMU_COMPOUNDSTREAM);
		return (zfs_receive_package(hdl, infd, tosnap, flags, &drr,
		    &zcksum, top_zfs, cleanup_fd, action_handlep, cmdprops));
	}
}

/*
 * Restores a backup of tosnap from the file descriptor specified by infd.
 * Return 0 on total success, -2 if some things couldn't be
 * destroyed/renamed/promoted, -1 if some things couldn't be received.
 * (-1 will override -2, if -1 and the resumable flag was specified the
 * transfer can be resumed if the sending side supports it).
 */
int
zfs_receive(libzfs_handle_t *hdl, const char *tosnap, nvlist_t *props,
    recvflags_t *flags, int infd, avl_tree_t *stream_avl)
{
	char *top_zfs = NULL;
	int err;
	int cleanup_fd;
	uint64_t action_handle = 0;
	struct stat sb;
	char *originsnap = NULL;

	/*
	 * The only way fstat can fail is if we do not have a valid file
	 * descriptor.
	 */
	if (fstat(infd, &sb) == -1) {
		perror("fstat");
		return (-2);
	}

	/*
	 * It is not uncommon for gigabytes to be processed in zfs receive.
	 * Speculatively increase the buffer size if supported by the platform.
	 */
	if (S_ISFIFO(sb.st_mode))
		libzfs_set_pipe_max(infd);

	if (props) {
		err = nvlist_lookup_string(props, "origin", &originsnap);
		if (err && err != ENOENT)
			return (err);
	}

	cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
	VERIFY(cleanup_fd >= 0);

	err = zfs_receive_impl(hdl, tosnap, originsnap, flags, infd, NULL, NULL,
	    stream_avl, &top_zfs, cleanup_fd, &action_handle, NULL, props);

	VERIFY(0 == close(cleanup_fd));

	if (err == 0 && !flags->nomount && flags->domount && top_zfs) {
		zfs_handle_t *zhp = NULL;
		prop_changelist_t *clp = NULL;

		zhp = zfs_open(hdl, top_zfs,
		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
		if (zhp == NULL) {
			err = -1;
			goto out;
		} else {
			if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
				zfs_close(zhp);
				goto out;
			}

			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
			    CL_GATHER_MOUNT_ALWAYS, 0);
			zfs_close(zhp);
			if (clp == NULL) {
				err = -1;
				goto out;
			}

			/* mount and share received datasets */
			err = changelist_postfix(clp);
			changelist_free(clp);
			if (err != 0)
				err = -1;
		}
	}

out:
	if (top_zfs)
		free(top_zfs);

	return (err);
}