File: content.c

package info (click to toggle)
xfsdump 3.1.9%2B0
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 3,932 kB
  • sloc: ansic: 45,863; sh: 3,227; makefile: 545
file content (9758 lines) | stat: -rw-r--r-- 236,020 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
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
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
/*
 * Copyright (c) 2000-2001 Silicon Graphics, Inc.
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it would be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write the Free Software Foundation,
 * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <attr/attributes.h>
#include <xfs/handle.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <utime.h>
#include <malloc.h>
#include <pthread.h>
#include <assert.h>
#include <string.h>
#include <uuid/uuid.h>
#include <xfs/xfs.h>
#include <xfs/jdm.h>	/* only for util.h */

#include "config.h"

#include "types.h"
#include "timeutil.h"
#include "util.h"	/* only for r/w routines, ALIGN_PTR */
#include "cldmgr.h"
#include "qlock.h"
#include "lock.h"
#include "path.h"
#include "openutil.h"
#include "exit.h"
#include "getopt.h"
#include "mlog.h"
#include "dlog.h"
#include "bag.h"
#include "node.h"
#include "namreg.h"
#include "stream.h"
#include "global.h"
#include "drive.h"
#include "media.h"
#include "content.h"
#include "content_inode.h"
#include "inomap.h"
#include "dirattr.h"
#include "tree.h"
#include "inventory.h"
#include "mmap.h"
#include "arch_xlate.h"
#include "win.h"
#include "hsmapi.h"

/* content.c - manages restore content
 */

/* structure definitions used locally ****************************************/

#define HOUSEKEEPING_MAGIC	0x686b6d61
	/* "hkma" - see the housekeeping_magic field of pers_t below.
	 */
#define HOUSEKEEPING_VERSION	2
	/* see the housekeeping_version field of pers_t below.
	 * version 2 changed the size of a gen_t, which caused node_t
	 * to change in size. also p_truncategenpr was added to treepers_t.
	 */

#define WRITE_TRIES_MAX	3
	/* retry loop tuning for write(2) workaround
	 */
typedef enum { SYNC_INIT, SYNC_BUSY, SYNC_DONE } sync_t;
	/* for lock-step synchronization
	 */
typedef struct { xfs_ino_t eg_ino; off64_t eg_off; } egrp_t;
	/* extent group descriptor
	 */
typedef char label_t[GLOBAL_HDR_STRING_SZ];
	/* dump or mobj label
	 */
typedef enum { PURP_SEARCH, PURP_DIR, PURP_NONDIR } purp_t;
	/* to describe purpose for a media file request. may be for
	 * searching for a dump to restore, for dir restore, or non-dir
	 */
typedef off_t dh_t;
	/* handles for descriptors in persistent state inventory
	 * encoded as byte offset plus one of descriptor into descriptor
	 * portion of persistent state. plus one so DH_NULL can be zero.
	 */
#define DH_NULL		((dh_t)0)
	/* NULL inv. descriptor handles, to terminate linked descriptor lists.
	 * must be zero-valued, so memset of pers.s sets freeh to DH_NULL.
	 */
#define DH2F(h)	((pers_file_t *)((char *)descp + (h - 1)))
#define DH2O(h)	((pers_obj_t *)((char *)descp + (h - 1)))
#define DH2S(h)	((pers_strm_t *)((char *)descp + (h - 1)))
#define DH2D(h)	((pers_desc_t *)((char *)descp + (h - 1)))
	/* convert file, object, and stream inv. descriptor handle into
	 * descriptor pointers
	 */
#define DAU		1
	/* number of descriptor pages to allocate when free list exhausted
	 */
#define IBPGINCR	32
	/* session inv. restore retry buffer increment
	 */

/* Media state abstraction
 */
struct Media {
	drive_t *M_drivep;
	global_hdr_t *M_grhdrp;
	drive_hdr_t *M_drhdrp;
	media_hdr_t *M_mrhdrp;
	content_hdr_t *M_crhdrp;
	content_inode_hdr_t *M_scrhdrp;

	enum { POS_UNKN,	/* whenever media file not open */
	       POS_ATHDR,	/* at beginning of media file */
	       POS_INDIR,	/* at beginning of inomap/dirdump */
	       POS_ATNONDIR,	/* at first non-dir file */
	       POS_END,		/* EOM/EOD */
	       POS_USELESS,	/* current object contains nothing useful */
	       POS_BLANK	/* like useless */
	} M_pos;
		/* media positioning info. initially UNKN, set back to
		 * unkn whenever end_read op called.
		 */
	ix_t M_fmfix;
	ix_t M_lmfix;
	ix_t M_pmfix;
	bool_t M_pmfixvalpr;
	purp_t M_mfixpurp;
	bool_t M_flmfixvalpr;
		/* the indices within the current media object of the first
		 * and last media files seen, as well as previous last.
		 * invalidated whenever purpose changes or media is changed.
		 * previous (pmfix) not valid until second media file seen.
		 */
	ix_t M_fsfix;
	ix_t M_fsoix;
	ix_t M_fssix;
	bool_t M_fsfixvalpr;
		/* index within the current media object of the first
		 * media file that is part of dump being restored,
		 * and indices of the obj and stream containing that mfile.
		 * invalidated on media change.
		 */
};

typedef struct Media Media_t;


/* persistent state - mmapped, has linked lists of dump streams, media
 * objects, and media files. descriptors for each fit into PERS_DESCSZ
 * bytes, and are allocated from a common free pool.
 */

/* persistent media file descriptor
 */
struct pers_file {
	dh_t f_nexth;
		/* singly-linked list of files withing object
		 */
	dh_t f_parh;
		/* parent object
		 */
	bool_t f_szvalpr;
	off64_t f_sz;
		/* if this info came from an inventory (on-line or on-media),
		 * we know the media file size
		 */
	bool_t f_dirtriedpr;
		/* set if attempted to restore dirs from this media file.
		 * says nothing about success or failure. prevents us from
		 * trying to restore dirs from this media file again.
		 */
	bool_t f_valpr;
		/* following three fields are valid
		 */
	egrp_t f_firstegrp;
		/* first extent group in this media file
		 */
	egrp_t f_curegrp;
		/* next extent group to be restored from this media file.
		 * initially equals f_firstegrp.
		 */
	drive_mark_t f_curmark;
		/* drive manager mark for seeking to current extent group
		 */
	bool_t f_nondirdonepr;
		/* TRUE when non-dirs from this media file completely restored,
		 * or as restored as they can be (some or all lost due to
		 * media corruption).
		 */
	bool_t f_nondirskippr;
		/* no non-dirs are needed from this nmedia file (due to
		 * subtree or interactive selections)
		 */
	int f_flags;
		/* mark terminators and inventories
		 */
	bool_t f_underheadpr;
		/* the drive is currently positioned at or in this media file
		 */
};

/* f_flags
 */
#define PF_INV	(1 << 0)
#define PF_TERM	(1 << 1)

typedef struct pers_file pers_file_t;

/* persistent media object descriptor
 */
struct pers_obj {
	dh_t o_nexth;
		/* singly-linked list of objects in stream
		 */
	dh_t o_parh;
		/* parent dump stream descriptor
		 */
	dh_t o_cldh;
		/* head of list of pertinent media files contained in
		 * this media object
		 */
	bool_t o_idlabvalpr;
		/* id and label fields are valid
		 */
	uuid_t o_id;
		/* uuid of media object
		 */
	label_t o_lab;
		/* label of media object
		 */
	ix_t o_fmfmix;
	bool_t o_fmfmixvalpr;
		/* 0-based index into this mobj's mfiles of first
		 * mfile in the mobj that is part of the dump stream.
		 */
	ix_t o_fmfsix;
	bool_t o_fmfsixvalpr;
		/* 0-based index into this dump stream's mfiles of first
		 * mfile in the mobj that is part of the dump stream.
		 */
	bool_t o_lmfknwnpr;
		/* TRUE if last media file on object is represented in
		 * children list.
		 */
	bool_t o_indrivepr;
	ix_t o_indriveix;
		/* TRUE if this object is in a drive, and which drive it is
		 * in.
		 */
};

typedef struct pers_obj pers_obj_t;

/* media dump stream descriptor
 */
struct pers_strm {
	dh_t s_nexth;
		/* singly-linked list of streams generated by dump
		 */
	dh_t s_cldh;
		/* head of list of mobjs containing this dstrm's mfiles
		 */
	bool_t s_lastobjknwnpr;
		/* TRUE if if last object in the stream is represented in
		 * children list.
		 */
};

typedef struct pers_strm pers_strm_t;

/* media descriptor allocation object (for free list)
 */
union pers_desc {
	dh_t d_nexth;
		/* singly-linked free list of descriptors
		 */
	pers_file_t d_file;
		/* media file descriptor overlay;
		 */
	pers_obj_t d_obj;
		/* media object descriptor overlay;
		 */
	pers_strm_t d_strm;
		/* media stream descriptor overlay;
		 */
};

typedef union pers_desc pers_desc_t;

#define PERS_DESCSZ	512
	/* size of media object, media file, and media stream descriptors.
	 * need to fit integral number into a page, single allocator
	 * used allocate and free all types .
	 */

/* subtree descriptor - the subtree command line arguments are transcribed
 * into variable-length descriptors and placed in an integral number of
 * pages after the persistent header, and before the media descriptor free list.
 */
#define STDESCALIGN	8

struct stdesc {
	bool_t std_sensepr;
		/* TRUE if this is a subtree to INCLUDE, FALSE if EXCLUDE
		 */
	off_t std_nextoff;
		/* offset to next descriptor, in bytes relative to this
		 */
	char std_path[1];
		/* first character of a NULL-terminated string containing the
		 * the relative subtree pathname
		 */
};

typedef struct stdesc stdesc_t;

/* byte span descriptor - registers a span of a file restored.
 */
struct bytespan {
	off64_t	offset;
	off64_t	endoffset;
};

typedef struct bytespan bytespan_t;

/* partial restore descriptor - Keeps track of different byte spans restored
 * for a specific inode.  Used to sync operations between restore streams.
 */
struct partial_rest {
	xfs_ino_t	is_ino;
		/* inode number */
	bytespan_t is_bs[STREAM_SIMMAX];
		/* each stream could conceivably be writing to a single
		 * file simultaneously if one file spans all device streams.
		 * Need a record for each possible place in the file.
		 */
};

typedef struct partial_rest partial_rest_t;

struct stream_context {
	bstat_t    sc_bstat;
	char       sc_path[2 * MAXPATHLEN];
	int   sc_fd;
	int   sc_hsmflags;

	/*
	 * we have to set the owner before we set extended attributes otherwise
	 * capabilities will not be restored correctly as setting the owner with
	 * fchmod will strip the capability attribute from the file. Hence we
	 * need to do this before restoring xattrs and record it so we don't do
	 * it again on completion of file restoration.
	 */
	bool_t	   sc_ownerset;
};

typedef struct stream_context stream_context_t;

/* persistent state file header - on-disk format information plus
 * accumulation state (which spans several sessions) and session state.
 * the latter two have a valid bit, and their fields are not valid until
 * the valid bit is set. all elements defined such that a bzero results
 * in a valid initial state.
 */
struct pers {
	/* on-disk format information used to verify that xfsrestore
	 * can make sense of the data in xfsrestorehousekeepingdir
	 * when running in cumulative mode or when resuming a restore.
	 *
	 * for backwards/forwards compatibility, this struct must be
	 * the first field! also any changes to the struct must address
	 * compatibility with other xfsrestore versions.
	 */
	struct {
		size32_t housekeeping_magic;
			/* used to determine if this struct has been
			 * initialized, and whether the machine's
			 * endianness is the same as the previous
			 * invocation. (data written to xfsrestore's
			 * state directory is not converted to an
			 * endian-neutral format since it only persists
			 * for the life of one or more restore sessions.)
			 */
		size32_t housekeeping_version;
			/* version of the data structures used in the
			 * state files in housekeepingdir. this must be
			 * bumped whenever the on-disk format changes.
			 */
		size64_t pagesize;
			/* headers in the persistent state files
			 * are aligned on page size boundaries, so
			 * this cannot change betweeen invocations.
			 */
	} v;

	/* command line arguments from first session, and session
	 * history.
	 */
	struct {
		bool_t valpr;
			/* not set until a BASE dump has been identified
			 * and validated for restoral, and an attempt has
			 * been made to load the dump inventory into persistent
			 * state, and the namreg and tree abstractions
			 * have been initialized, and the session history
			 * has been initialized and validated.
			 */
		char dstdir[MAXPATHLEN];
			/* absolute pathname of the destination directory
			 */
		bool_t dstdirisxfspr;
			/* destination directory is an xfs filesystem; xfs-specific
			 * calls can be made when needed.
			 */
		ix_t dumpcnt;
			/* how many dumps have been applied completedly (A1)
			 */
		uuid_t lastdumpid;
			/* uuid of the last dump completely restored (A1)
			 */
		label_t lastdumplab;
			/* label of the last dump completely restored (A1)
			 */
		bool_t cumpr;
			/* is a cumulative restore (-r)
			 */
		bool_t interpr;
			/* interactive mode specified on command line (-i)
			 */
		bool_t existpr;
			/* existing files may not be overwritten (-e)
			 */
		bool_t changepr;
			/* only missing or old files may be overwritten (-E)
			 */
		bool_t newerpr;
		time32_t newertime;
			/* only files older than example may be overwritten (-n)
			 */
		bool_t ownerpr;
			/* attempt to restore owner/group (-o)
			 */
		ix_t stcnt;
			/* how many subtree args (both inclusive and exclusive)
			 * are recorded in the subtree pages (-s)
			 */
		bool_t firststsensepr;
		bool_t firststsenseprvalpr;
			/* sense of first subtree arg
			 */
		ix_t stpgcnt;
			/* how many pages following the header page are reserved
			 * for the subtree descriptors
			 */
		bool_t restoredmpr;
			/* restore DMAPI event settings
			 */
		bool_t restoreextattrpr;
			/* restore extended attributes
			 */

		ix_t parrestcnt;
			/* Count of partialy restored files.  Used to speed
			 * up searches in parrest.
			 */

		partial_rest_t parrest[STREAM_SIMMAX * 2 - 2];
			/* record of bytes restored to partially restored files.
			 * Max possible is two per stream except the first
			 * drive will never finish another drives file and the
			 * last drive will never leave a file for another to
			 * complete.
			 */
	} a;

	/* session state.
	 */
	struct {
		bool_t valpr;
			/* until this is true, a resume will ignore (and bzero)
			 * this structure. validate just prior to applying
			 * the directory dump, and after all fields marked (A2)
			 * are correct. invalidate as soon as the session is
			 * complete, and atomically update all fields marked
			 * (A1) at the same time. dirattr abstraction must be
			 * initialized prior to setting this.
			 */
		time32_t accumtime;
			/* for measuring elapsed time of restore
			 */
		uuid_t dumpid;
			/* id of dump currently being applied
			 */
		label_t dumplab;
			/* label of the dump being applied (A2)
			 */
		time32_t begintime;
			/* set when session begun and each time resumed
			 */
		bool_t stat_valpr;
			/* the following stats are not valid until the
			 * first media file header has been read.
			 */
		uint64_t stat_inocnt;
			/* number of non-dir inos to restore during session
			 */
		uint64_t stat_inodone;
			/* number of non-dir inos restored so far
			 */
		off64_t stat_datacnt;
			/* bytes of ordinary files to restore during session
			 */
		off64_t stat_datadone;
			/* bytes of ordinary files restored so far
			 */
		ix_t descpgcnt;
			/* number of pages mapped for pers. media descriptors
			 */
		dh_t descfreeh;
			/* linked list of free media descriptor alloc objs (A2)
			 */
		dh_t strmheadh;
			/* head of singly-linked list of stream descriptors (A2)
			 */
		bool_t fullinvpr;
			/* have discovered and incorporated a full inventory
			 * description into pers. may come from online or a
			 * inventory media file.
			 */
		bool_t marknorefdonepr;
			/* have marked tree nodes as unreferenced by directory
			 * entries, and nulled  dirattr handles.
			 */
		bool_t dirdonepr;
			/* have applied all directories from a dirdump.
			 */
		bool_t adjrefdonepr;
			/* have adjusted marking of nodes no longer referenced
			 * by directory entries.
			 */
		bool_t inomapsanitizedonepr;
			/* the inomap needs to b sanitized prior to subtree
			 * or interactive selections
			 */
		bool_t stdonepr;
			/* have applied subtree selections
			 */
		bool_t interdonepr;
			/* have completed interactive subtree dialog
			 */
		bool_t treepostdonepr;
			/* all of the above treep ost-processing steps have
			 * been completed.
			 */
			/*
			 * nondir restore done here
			 */
		bool_t dirattrdonepr;
			/* directory attributes have been restored and
			 * directory attributes registry has been deleted
			 */
		bool_t orphdeltriedpr;
			/* removed (or tried to remove) orphanage
			 */
		bool_t inomapdelpr;
			/* deleted session ino map
			 */
	} s;
};

typedef struct pers pers_t;

/* transient state. re-generated during each restore session
 */

struct tran {
	time32_t t_starttime;
		/* for measuring elapsed time of restore session
		 */
	size64_t t_dircnt;
	size64_t t_dirdonecnt;
	size64_t t_direntcnt;
		/* for displaying stats on directory reconstruction
		 */
	size64_t t_vmsz;
		/* how much vm may be used. recorded here from main,
		 * passed to tree_init() once we have a valid media
		 * file header
		 */
	bool_t t_toconlypr;
		/* just display table of contents; don't restore files
		 */
	bool_t t_noinvupdatepr;
		/* true if inventory is NOT to be updated when on-media
		 * inventory encountered.
		 */
	bool_t t_dumpidknwnpr;
		/* determined during initialization; if false, set during
		 * per-stream init
		 */
	bool_t t_dirattrinitdonepr;
	bool_t t_namreginitdonepr;
	bool_t t_treeinitdonepr;
		/* determinied during initialization, used during
		 * per-stream restore
		 */
	uuid_t t_reqdumpid;
	bool_t t_reqdumpidvalpr;
		/* uuid of the dump as requested on cmd line
		 */
	char * t_reqdumplab;
	bool_t t_reqdumplabvalpr;
		/* label of the dump as requested on cmd line
		 */
	char *t_hkdir;
		/* absolute pathname of housekeeping directory
		 */
	int t_persfd;
		/* file descriptor of the persistent state file
		 */
	size64_t t_dirdumps;
		/* bitset of streams which contain a directory dump
		 */
	bool_t t_truncategenpr;
		/* force use of truncated generation numbers
		 */
	sync_t t_sync1;
		/* to single-thread attempt to validate command line
		 * selection of dump with online inventory
		 */
	sync_t t_sync2;
		/* to single-thread dump selection by media scan
		 */
	sync_t t_sync3;
		/* to single-thread attempt to apply dirdump to tree
		 */
	sync_t t_sync4;
		/* to single-thread attempt to do tree post-processing
		 * prior to non-directory restore
		 */
	sync_t t_sync5;
		/* to single-thread cleanup after applying non-dir restore
		 */
	qlockh_t t_pilockh;
		/* to establish critical regions while updating pers
		 * inventory
		 */
};

typedef struct tran tran_t;


/* declarations of externally defined global symbols *************************/

extern void usage(void);
extern bool_t preemptchk(void);
extern char *homedir;
extern bool_t pipeline;
extern bool_t stdoutpiped;
extern char *sistr;
extern size_t pgsz;
extern size_t pgmask;


/* forward declarations of locally defined static functions ******************/

static void toconly_cleanup(void);

static Media_t *Media_create(ix_t thrdix);
static void Media_indir(Media_t *Mediap);
static void Media_indir(Media_t *Mediap);
static void Media_atnondir(Media_t *Mediap);
static rv_t Media_mfile_next(Media_t *Mediap,
			      purp_t purp,
			      sync_t *donesyncp,
			      dh_t  *filehp,
			      global_hdr_t **grhdrpp,
			      drive_hdr_t **drhdrpp,
			      media_hdr_t **mrhdrpp,
			      content_hdr_t **crhdrpp,
			      content_inode_hdr_t **scrhdrpp,
			      drive_t **drivepp,
			      filehdr_t *fhdr);
static void Media_end(Media_t *Mediap);
static bool_t Media_prompt_change(drive_t *drivep,
				   purp_t purp,
				   bag_t *bagp,
				   bool_t knownholespr,
				   bool_t maybeholespr);

static bool_t Inv_validate_cmdline(void);
static bool_t dumpcompat(bool_t resumepr,
			  ix_t level,
			  uuid_t baseid,
			  bool_t logpr);
static bool_t promptdumpmatch(ix_t thrdix,
			       global_hdr_t *grhdrp,
			       media_hdr_t *mrhdrp,
			       content_hdr_t *crhdrp,
			       content_inode_hdr_t *scrhdrp);

static void pi_checkpoint(dh_t fileh,
			   drive_mark_t *drivemarkp,
			   xfs_ino_t ino,
			   off64_t off);
static bool_t pi_transcribe(inv_session_t *sessp);
static dh_t pi_addfile(Media_t *Mediap,
			global_hdr_t *grhdrp,
			drive_hdr_t *drhdrp,
			media_hdr_t *mrhdrp,
			content_inode_hdr_t *scrhdrp,
			drive_t * drivep);
static void pi_seestrmend(ix_t strmix);
static void pi_seeobjstrmend(ix_t strmix, ix_t mediaix);
static xfs_ino_t pi_scanfileendino(dh_t fileh);
static bool_t pi_alldone(void);
static bag_t * pi_neededobjs_dir_alloc(bool_t *knownholesprp,
				        bool_t *maybeholesprp);
static bag_t * pi_neededobjs_nondir_alloc(bool_t *knownholesprp,
					   bool_t *maybeholesprp,
					   bool_t showobjindrivepr,
					   bool_t markskippr);
static void pi_neededobjs_free(bag_t *bagp);
static void pi_bracketneededegrps(dh_t thisfileh,
				   egrp_t *first_egrp,
				   egrp_t *next_egrp);
static void pi_update_stats(off64_t sz);
static void pi_hiteod(ix_t strmix, ix_t objix);
static void pi_hiteom(ix_t strmix, ix_t objix);
static void pi_hitnextdump(ix_t strmix, ix_t objix, ix_t lastfileix);
static bool_t pi_know_no_more_on_object(purp_t purp, ix_t strmix, ix_t objix);
static bool_t pi_know_no_more_beyond_on_object(purp_t purp,
					        ix_t strmix,
					        ix_t objix,
					        ix_t fileix);
static void pi_preclean(void);
static void pi_driveempty(ix_t driveix);
static void pi_note_indrive(ix_t driveix, uuid_t mediaid);
static void pi_note_underhead(dh_t thisobjh, dh_t thisfileh);
static void pi_lock(void);
static void pi_unlock(void);

static rv_t applydirdump(drive_t *drivep,
			  dh_t fileh,
			  content_inode_hdr_t *scrhdrp,
			  filehdr_t *fhdrp);
static rv_t treepost(char *path1, char *path2);
static rv_t applynondirdump(drive_t *drivep,
			     dh_t fileh,
			     content_inode_hdr_t *scrhdrp,
			     char *path1,
			     char *path2,
			     filehdr_t *fhdrp);
static rv_t finalize(char *path1, char *path2);
static void wipepersstate(void);

static rv_t read_filehdr(drive_t *drivep, filehdr_t *fhdrp, bool_t fhcs);
static rv_t restore_file(drive_t *drivep,
			  filehdr_t *fhdrp,
			  bool_t ehcs,
			  bool_t ahcs,
			  char *path1,
			  char *path2);
static bool_t restore_reg(drive_t *drivep,
			   filehdr_t *fhdrp,
			   rv_t *rvp,
			   char *path);
static bool_t restore_extent_group(drive_t *drivep,
				    filehdr_t *fhdrp,
				    char *path,
				    int fd,
				    bool_t ehcs,
				    rv_t *rvp);
static bool_t restore_complete_reg(stream_context_t*);
static bool_t restore_spec(filehdr_t *fhdrp, rv_t *rvp, char *path);
static bool_t restore_symlink(drive_t *drivep,
			       filehdr_t *fhdrp,
			       rv_t *rvp,
			       char *path,
			       char *scratchpath,
			       bool_t ehcs);
static rv_t read_extenthdr(drive_t *drivep, extenthdr_t *ehdrp, bool_t ehcs);
static rv_t read_dirent(drive_t *drivep,
			 direnthdr_t *dhdrp,
			 size_t direntbufsz,
			 bool_t dhcs);
static rv_t discard_padding(size_t sz, drive_t *drivep);
static rv_t restore_extent(filehdr_t *fhdrp,
			    extenthdr_t *ehdrp,
			    int fd,
			    char *path,
			    drive_t *drivep,
			    off64_t *bytesreadp);
static bool_t askinvforbaseof(uuid_t baseid, inv_session_t *sessp);
static void addobj(bag_t *bagp,
		    uuid_t *objidp,
		    label_t objlabel,
		    bool_t indrivepr,
		    ix_t indriveix);
static size_t cntobj(bag_t *bagp);
static bool_t gapneeded(egrp_t *firstegrpp, egrp_t *lastegrpp);
static char * ehdr_typestr(int32_t type);
static int egrpcmp(egrp_t *egrpap, egrp_t *egrpbp);
static void display_dump_label(bool_t lockpr,
				int mllevel,
				char *introstr,
				global_hdr_t *grhdrp,
				media_hdr_t *mrhdrp,
				content_hdr_t *crhdrp,
				content_inode_hdr_t *scrhdrp);
static void display_needed_objects(purp_t purp,
				    bag_t *bagp,
				    bool_t knownholespr,
				    bool_t maybeholespr);
static void set_mcflag(ix_t thrdix);
static void clr_mcflag(ix_t thrdix);
static void pi_show(char *introstring);
static void pi_show_nomloglock(void);

static bool_t extattr_init(size_t drivecnt);
static char * get_extattrbuf(ix_t which);
static rv_t restore_extattr(drive_t *drivep,
			     filehdr_t *fhdrp,
			     char *path,
			     bool_t ahcs,
			     bool_t isdirpr,
			     bool_t onlydoreadpr,
			     dah_t dah);
static bool_t restore_dir_extattr_cb(char *path, dah_t dah);
static bool_t restore_dir_extattr_cb_cb(extattrhdr_t *ahdrp, void *ctxp);
static void setextattr(char *path, extattrhdr_t *ahdrp);
static void partial_reg(ix_t d_index, xfs_ino_t ino, off64_t fsize,
                        off64_t offset, off64_t sz);
static bool_t partial_check (xfs_ino_t ino, off64_t fsize);
static bool_t partial_check2 (partial_rest_t *isptr, off64_t fsize);
static int do_fssetdm_by_handle(char *path, fsdmidata_t *fdmp);
static int quotafilecheck(char *type, char *dstdir, char *quotafile);

/* definition of locally defined global variables ****************************/

bool_t content_media_change_needed;
bool_t restore_rootdir_permissions;
char *media_change_alert_program = NULL;
size_t perssz;


/* definition of locally defined static variables *****************************/

static pers_t *persp;		/* mapped at init, ok to use */
static tran_t *tranp;		/* allocated at init, ok to use */
static pers_desc_t *descp = 0;	/* mapped on the fly; don't use! (see macros) */
static char *hkdirname = "xfsrestorehousekeepingdir";
static char *persname = "state";
static char *perspath = 0;
static bool_t mcflag[STREAM_SIMMAX]; /* media change flag */


/* definition of locally defined global functions ****************************/

bool_t
content_init(int argc, char *argv[], size64_t vmsz)
{
	char *dstdir;	/* abs. path to destination dir */
	bool_t cumpr;	/* cmd line cumulative restore specification */
	bool_t resumepr;/* cmd line resumed restore specification */
	bool_t existpr;	/* cmd line overwrite inhibit specification */
	bool_t newerpr;	/* cmd line overwrite inhibit specification */
	time32_t newertime = 0;
	bool_t changepr;/* cmd line overwrite inhibit specification */
	bool_t interpr;	/* cmd line interactive mode requested */
	bool_t ownerpr;	/* cmd line chown/chmod requested */
	bool_t restoredmpr; /* cmd line restore dm api attrs specification */
	bool_t restoreextattrpr; /* cmd line restore extended attr spec */
	bool_t sesscpltpr; /* force completion of prev interrupted session */
	ix_t stcnt;	/* cmd line number of subtrees requested */
	bool_t firststsensepr;
	bool_t firststsenseprvalpr;
	ix_t stsz;	/* bytes required to record subtree selections */
	ix_t stpgcnt;	/* pages required to hold subtree selections */
	ix_t newstpgcnt;/* pages required to hold subtree selections */
	ix_t descpgcnt; /* pages allocated for persistent descriptors */
	struct stat statbuf;
	pid_t pid;
	int c;
	bool_t ok;
	int rval;
	bool_t fullpr;

	/* Calculate the size needed for the persistent inventory
	 */
	for (perssz = pgsz; perssz < sizeof(pers_t); perssz += pgsz)
		;

	/* sanity checks
	 */
	assert(sizeof(pers_desc_t) <= PERS_DESCSZ);
	assert(PERS_DESCSZ <= pgsz);
	assert(!(pgsz % PERS_DESCSZ));
	assert(sizeof(extattrhdr_t) == EXTATTRHDR_SZ);

	assert(!(perssz % pgsz));

	assert(SYNC_INIT == 0);

	mlog(MLOG_NITTY,
	      "sizeof( pers_desc_t ) == %d, pgsz == %d, perssz == %d \n",
	      sizeof(pers_desc_t), pgsz, perssz);

	/* allocate transient state
	 */
	tranp = (tran_t *)calloc(1, sizeof(tran_t));
	assert(tranp);

	/* allocate a qlock for establishing pi critical regions
	 */
	tranp->t_pilockh = qlock_alloc(QLOCK_ORD_PI);

	/* record vmsz; will be used later to init tree abstraction
	 */
	tranp->t_vmsz = vmsz;

	/* record the start time for stats display
	 */
	tranp->t_starttime = time(0);

	/* get command line options
	 */
	cumpr = BOOL_FALSE;
	resumepr = BOOL_FALSE;
	existpr = BOOL_FALSE;
	newerpr = BOOL_FALSE;
	changepr = BOOL_FALSE;
	ownerpr = BOOL_FALSE;
	restoredmpr = BOOL_FALSE;
	restoreextattrpr = BOOL_TRUE;
	sesscpltpr = BOOL_FALSE;
	stcnt = 0;
	firststsensepr = firststsenseprvalpr = BOOL_FALSE;
	stsz = 0;
	interpr = BOOL_FALSE;
	restore_rootdir_permissions = BOOL_FALSE;
	optind = 1;
	opterr = 0;
	while ((c = getopt(argc, argv, GETOPT_CMDSTRING)) != EOF) {
		switch (c) {
		case GETOPT_TOC:
			tranp->t_toconlypr = BOOL_TRUE;
			break;
		case GETOPT_CUMULATIVE:
			cumpr = BOOL_TRUE;
			break;
		case GETOPT_RESUME:
			resumepr = BOOL_TRUE;
			break;
		case GETOPT_EXISTING:
			existpr = BOOL_TRUE;
			break;
		case GETOPT_NEWER:
			if (!optarg || optarg[0] == '-') {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument missing\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			if (stat(optarg, &statbuf)) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "unable to get status of -%c argument %s:"
				      " %s\n"),
				      c,
				      optarg,
				      strerror(errno));
				return BOOL_FALSE;
			}
			newerpr = BOOL_TRUE;
			newertime = statbuf.st_mtime;
			break;
		case GETOPT_CHANGED:
			changepr = BOOL_TRUE;
			break;
		case GETOPT_OWNER:
			ownerpr = BOOL_TRUE;
			break;
		case GETOPT_WORKSPACE:
			if (!optarg || optarg[0] == '-') {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument missing\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			if (optarg[0] != '/') {
				tranp->t_hkdir = path_reltoabs(optarg,
								homedir);
				if (!tranp->t_hkdir) {
					mlog(MLOG_NORMAL | MLOG_ERROR, _(
					      "-%c argument %s is an "
					      "invalid pathname\n"),
					      c,
					      optarg);
					usage();
					return BOOL_FALSE;
				}
				mlog(MLOG_DEBUG,
				      "alternate workspace path converted "
				      "from %s to %s\n",
				      optarg,
				      tranp->t_hkdir);
			} else {
				tranp->t_hkdir = optarg;
			}
			rval = stat(tranp->t_hkdir, &statbuf);
			if (rval) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "cannot stat -%c argument %s (%s): %s\n"),
				      c,
				      optarg,
				      tranp->t_hkdir,
				      strerror(errno));
				usage();
				return BOOL_FALSE;
			}
			if ((statbuf.st_mode & S_IFMT) != S_IFDIR) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument %s (%s) "
				      "is not a directory\n"),
				      c,
				      optarg,
				      tranp->t_hkdir);
				usage();
				return BOOL_FALSE;
			}

			break;
		case GETOPT_DUMPLABEL:
			if (tranp->t_reqdumplabvalpr) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "too many -%c arguments: "
				      "\"-%c %s\" already given\n"),
				      c,
				      c,
				      tranp->t_reqdumplab);
				usage();
				return BOOL_FALSE;
			}
			if (!optarg || optarg[0] == '-') {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument missing\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			if (strlen(optarg)
			     >
			     sizeofmember(pers_t, s.dumplab)) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument %s too long: max is %d\n"),
				      c,
				      optarg,
				      sizeofmember(pers_t, s.dumplab));
				usage();
				return BOOL_FALSE;
			}
			tranp->t_reqdumplab = optarg;
			tranp->t_reqdumplabvalpr = BOOL_TRUE;
			break;
		case GETOPT_SESSIONID:
			if (tranp->t_reqdumpidvalpr) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "too many -%c arguments\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			if (!optarg || optarg[0] == '-') {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument missing\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			if (uuid_parse(optarg, tranp->t_reqdumpid) < 0) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "-%c argument not a valid uuid\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			tranp->t_reqdumpidvalpr = BOOL_TRUE;
			break;
		case GETOPT_SUBTREE:
		case GETOPT_NOSUBTREE:
			if (!optarg
			     ||
			     optarg[0] == 0
			     ||
			     optarg[0] == '-') {
				mlog(MLOG_NORMAL, _(
				      "-%c argument missing\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			if (optarg[0] == '/') {
				mlog(MLOG_NORMAL, _(
				      "-%c argument must be relative\n"),
				      c);
				usage();
				return BOOL_FALSE;
			}
			stcnt++;
			if (!firststsenseprvalpr) {
				if (c == GETOPT_SUBTREE) {
					firststsensepr = BOOL_TRUE;
				} else {
					firststsensepr = BOOL_FALSE;
				}
				firststsenseprvalpr = BOOL_TRUE;
			}
			stsz += sizeof(stdesc_t)
				+
				strlen(optarg)
				+
				(STDESCALIGN - 1);
			stsz &= ~(STDESCALIGN - 1);
			break;
		case GETOPT_INTERACTIVE:
			if (!dlog_allowed()) {
				mlog(MLOG_NORMAL, _(
				      "-%c unavailable: no /dev/tty\n"),
				      GETOPT_INTERACTIVE);
				return BOOL_FALSE;
			}
			interpr = BOOL_TRUE;
			break;
		case GETOPT_NOINVUPDATE:
			tranp->t_noinvupdatepr = BOOL_TRUE;
			break;
		case GETOPT_SETDM:
			restoredmpr = BOOL_TRUE;
			break;
		case GETOPT_ALERTPROG:
			if (!optarg || optarg[0] == '-') {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
					"-%c argument missing\n"),
					c);
				usage();
				return BOOL_FALSE;
			}
			media_change_alert_program = optarg;
			break;
		case GETOPT_NOEXTATTR:
			restoreextattrpr = BOOL_FALSE;
			break;
		case GETOPT_SESSCPLT:
			sesscpltpr = BOOL_TRUE;
			break;
		case GETOPT_SMALLWINDOW:
			/* obsolete */
			break;
		case GETOPT_ROOTPERM:
			restore_rootdir_permissions = BOOL_TRUE;
			break;
		case GETOPT_FMT2COMPAT:
			tranp->t_truncategenpr = BOOL_TRUE;
			break;
		}
	}

	/* command line option error checking
	 */
	if (cumpr && tranp->t_toconlypr) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "-%c and -%c option cannot be used together\n"),
		      GETOPT_TOC,
		      GETOPT_CUMULATIVE);
		usage();
		return BOOL_FALSE;
	}
	if (resumepr && tranp->t_toconlypr) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "-%c and -%c option cannot be used together\n"),
		      GETOPT_TOC,
		      GETOPT_RESUME);
		usage();
		return BOOL_FALSE;
	}

	/* assume all streams contain a directory dump. streams will remove
	 * themselves from this bitset if they do not contain a directory dump.
	 */
	assert(drivecnt <= sizeof(tranp->t_dirdumps) * NBBY);
	tranp->t_dirdumps = (1ULL << drivecnt) - 1;

	/* the user may specify stdin as the restore source stream,
	 * by a single dash ('-') with no option letter. This must
	 * appear between the last lettered argument and the destination
	 * directory pathname.
	 */
	if (optind < argc && !strcmp(argv[optind ], "-")) {
		optind++;
	}

	/* the last argument must be the destination directory. not
	 * required if table-of-contents display, or if a resumed restore
	 * or a delta restore.
	 */
	if (!tranp->t_toconlypr) {
		if (optind >= argc) {
			dstdir = 0;
		} else {
			if (argv[optind][0] != '/') {
				dstdir = path_reltoabs(argv[optind],
							homedir);
				if (!dstdir) {
					mlog(MLOG_NORMAL | MLOG_ERROR, _(
					      "destination directory %s "
					      "invalid pathname\n"),
					      argv[optind]);
					usage();
					return BOOL_FALSE;
				}
				mlog(MLOG_DEBUG,
				      "restore destination path converted "
				      "from %s to %s\n",
				      argv[optind],
				      dstdir);
			} else {
				dstdir = argv[optind];
			}
			rval = stat(dstdir, &statbuf);
			if (rval) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "cannot stat destination directory %s: "
				      "%s\n"),
				      dstdir,
				      strerror(errno));
				usage();
				return BOOL_FALSE;
			}
			if ((statbuf.st_mode & S_IFMT) != S_IFDIR) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "specified destination %s "
				      "is not a directory\n"),
				      dstdir);
				usage();
				return BOOL_FALSE;
			}
		}
	} else {
		if (optind < argc) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "do not specify destination directory if "
			      "contents only restore invoked (-%c option)\n"),
			      GETOPT_TOC);
			usage();
			return BOOL_FALSE;
		}
		dstdir = ".";
	}

	/* generate a full pathname for the housekeeping dir.
	 * the housekeeping dir will by default be placed in the
	 * destination directory, unless this is a toc, in which case
	 * it will be placed in the current directory. in either case, an
	 * alternate directory may be specified on the command line.
	 * if this is toconly, modify the housekeeping dir's name with
	 * the pid.
	 */
	if (!tranp->t_hkdir) {
		if (tranp->t_toconlypr) {
			tranp->t_hkdir = homedir;
		} else {
			if (!dstdir) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "destination directory "
				      "not specified\n"));
				usage();
				return BOOL_FALSE;
			} else {
				tranp->t_hkdir = dstdir;
			}
		}
	}
	if (tranp->t_toconlypr) {
		pid = getpid();
	} else {
		pid = 0;
	}
	tranp->t_hkdir = open_pathalloc(tranp->t_hkdir, hkdirname, pid);

	/* if this is a table-of-contents only restore, register an
	 * exit handler to get rid of the housekeeping directory and
	 * its contents. NOTE: needs several tran fields initialized!
	 */
	if (tranp->t_toconlypr) {
		atexit(toconly_cleanup);
	}

	/* create housekeeping dir if not present
	 */
	rval = mkdir(tranp->t_hkdir, S_IRWXU);
	if (rval && errno != EEXIST) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "unable to create %s: %s\n"),
		      tranp->t_hkdir,
		      strerror(errno));
		return BOOL_FALSE;
	}

	/* build a full pathname to pers. state file
	 */
	assert(!perspath);
	perspath = open_pathalloc(tranp->t_hkdir, persname, 0);

	/* open, creating if non-existent
	 */
	tranp->t_persfd = open(perspath,
				O_CREAT | O_RDWR,
				S_IRUSR | S_IWUSR);
	if (tranp->t_persfd < 0) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "could not open/create persistent state file %s: %s\n"),
		      perspath,
		      strerror(errno));
		return BOOL_FALSE;
	}

	/* temporarily mmap just the header, and validate the command line
	 * arguments. three cases: no dumps applied so far, or one or more
	 * dumps applied completely, or restore session was interrupted
	 */
	persp = (pers_t *) mmap_autogrow(perssz, tranp->t_persfd, 0);

	if (persp == (pers_t *)-1) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "could not map persistent state file hdr %s: %s\n"),
		      perspath,
		      strerror(errno));
		return BOOL_FALSE;
	}

	/* but first setup or verify the on-disk format information
	 */
	if (!persp->a.valpr) {
		/* this is the first restore session
		 */
		persp->v.housekeeping_magic = HOUSEKEEPING_MAGIC;
		persp->v.housekeeping_version = HOUSEKEEPING_VERSION;
		persp->v.pagesize = pgsz;

	} else {
		/* cumulative or resuming a restore, verify the header
		 */
		if (persp->v.housekeeping_magic != HOUSEKEEPING_MAGIC) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "%s format corrupt or wrong endianness "
			      "(0x%x, expected 0x%x)\n"),
			      hkdirname,
			      persp->v.housekeeping_magic,
			      HOUSEKEEPING_MAGIC);
			return BOOL_FALSE;
		}
		if (persp->v.housekeeping_version != HOUSEKEEPING_VERSION) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "%s format version differs from previous "
			      "restore (%u, expected %u)\n"),
			      hkdirname,
			      persp->v.housekeeping_version,
			      HOUSEKEEPING_VERSION);
			return BOOL_FALSE;
		}
		if (persp->v.pagesize != pgsz) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "%s format differs from previous "
			      "restore due to page size change "
			      "(was %lu, now %lu)\n"),
			      hkdirname,
			      persp->v.pagesize,
			      pgsz);
			return BOOL_FALSE;
		}
	}

	if (!persp->a.valpr) {
		if (!dstdir) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "destination directory not specified\n"));
			usage();
			return BOOL_FALSE;
		}
		if (strlen(dstdir) >= sizeofmember(pers_t, a.dstdir)) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "destination directory pathname too long: "
			      "max is %d characters\n"),
			      sizeofmember(pers_t, a.dstdir) - 1);
			usage();
			return BOOL_FALSE;
		}
		if (resumepr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c option invalid: there is no "
			      "interrupted restore to resume\n"),
			      GETOPT_RESUME);
			usage();
			return BOOL_FALSE;
		}
		if (sesscpltpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c option invalid: there is no "
			      "interrupted restore to force completion of\n"),
			      GETOPT_SESSCPLT);
			usage();
			return BOOL_FALSE;
		}
	} else if (!persp->s.valpr) {
		if (!cumpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "must rm -rf %s prior to noncumulative restore\n"),
			      tranp->t_hkdir);
			return BOOL_FALSE;
		}
		if (resumepr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c option invalid: there is no "
			      "interrupted restore to resume\n"),
			      GETOPT_RESUME);
			usage();
			return BOOL_FALSE;
		}
		if (sesscpltpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c option invalid: there is no "
			      "interrupted restore to force completion of\n"),
			      GETOPT_SESSCPLT);
			usage();
			return BOOL_FALSE;
		}
		if (existpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating "
			      "cumulative restore\n"),
			      GETOPT_EXISTING);
			return BOOL_FALSE;
		}
		if (newerpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating "
			      "cumulative restore\n"),
			      GETOPT_NEWER);
			return BOOL_FALSE;
		}
		if (changepr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating "
			      "cumulative restore\n"),
			      GETOPT_CHANGED);
			return BOOL_FALSE;
		}
		if (ownerpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating "
			      "cumulative restore\n"),
			      GETOPT_OWNER);
			return BOOL_FALSE;
		}
		if (stcnt) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c and -%c valid only when initiating "
			      "cumulative restore\n"),
			      GETOPT_SUBTREE,
			      GETOPT_NOSUBTREE);
			return BOOL_FALSE;
		}
		if (tranp->t_truncategenpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating "
			      "cumulative restore\n"),
			      GETOPT_FMT2COMPAT);
			return BOOL_FALSE;
		}
	} else {
		if (!resumepr && !sesscpltpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c option required to resume "
			      "or "
			      "-%c option required to force completion of "
			      "previously "
			      "interrupted restore session\n"),
			      GETOPT_RESUME,
			      GETOPT_SESSCPLT);
			return BOOL_FALSE;
		}
		if (tranp->t_reqdumplabvalpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_DUMPLABEL);
			return BOOL_FALSE;
		}
		if (tranp->t_reqdumpidvalpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_SESSIONID);
			return BOOL_FALSE;
		}
		if (existpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_EXISTING);
			return BOOL_FALSE;
		}
		if (newerpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_NEWER);
			return BOOL_FALSE;
		}
		if (changepr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_CHANGED);
			return BOOL_FALSE;
		}
		if (ownerpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_OWNER);
			return BOOL_FALSE;
		}
		if (interpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_INTERACTIVE);
			return BOOL_FALSE;
		}
		if (stcnt) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			     "-%c and -%c valid only when initiating restore\n"),
			      GETOPT_SUBTREE,
			      GETOPT_NOSUBTREE);
			return BOOL_FALSE;
		}
		if (tranp->t_truncategenpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "-%c valid only when initiating restore\n"),
			      GETOPT_FMT2COMPAT);
			return BOOL_FALSE;
		}
	}

	if (persp->a.valpr) {
		if (restoredmpr && persp->a.restoredmpr != restoredmpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			     "-%c cannot reset flag from previous restore\n"),
			      GETOPT_SETDM);
			return BOOL_FALSE;
		}
		if (!restoreextattrpr &&
		       persp->a.restoreextattrpr != restoreextattrpr) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			     "-%c cannot reset flag from previous restore\n"),
			      GETOPT_NOEXTATTR);
			return BOOL_FALSE;
		}
	}

	/* force owner option if root
	 */
	ownerpr = (geteuid() == 0) ? BOOL_TRUE : ownerpr;

	/* force completion of interrupted restore if asked to do so
	 */
	if (sesscpltpr) {
		char *path1;
		char *path2;
		rv_t rv;
		int rval;

		path1 = (char *)calloc(1, 2 * MAXPATHLEN);
		assert(path1);
		path2 = (char *)calloc(1, 2 * MAXPATHLEN);
		assert(path2);
		assert(persp->a.valpr);
		assert(persp->s.valpr);
		rval = chdir(persp->a.dstdir);
		if (rval) {
			mlog(MLOG_NORMAL, _(
			      "chdir %s failed: %s\n"),
			      persp->a.dstdir,
			      strerror(errno));
			return BOOL_FALSE;
		}
		ok = dirattr_init(tranp->t_hkdir, BOOL_TRUE, (uint64_t)0);
		if (!ok) {
			return BOOL_FALSE;
		}
		ok = namreg_init(tranp->t_hkdir, BOOL_TRUE, (uint64_t)0);
		if (!ok) {
			return BOOL_FALSE;
		}
		ok = inomap_sync_pers(tranp->t_hkdir);
		if (!ok) {
			return BOOL_FALSE;
		}

		/* This is only a full restore if we're doing a level
		 * 0 restore.
		 */
		if (persp->a.dumpcnt == 0) {
			fullpr = BOOL_TRUE;
		} else {
			fullpr = BOOL_FALSE;
		}

		ok = tree_sync(tranp->t_hkdir,
				persp->a.dstdir,
				tranp->t_toconlypr,
				fullpr,
				persp->a.dstdirisxfspr);
		if (!ok) {
			return BOOL_FALSE;
		}
		rv = finalize(path1, path2);
		free((void *)path1);
		free((void *)path2);
		switch (rv) {
		case RV_OK:
			break;
		case RV_ERROR:
			return EXIT_ERROR;
		case RV_INTR:
			return EXIT_NORMAL;
		case RV_CORE:
		default:
			return EXIT_FAULT;
		}
	}

	/* for the three cases, calculate old and new mapping params
	 * and wipe partial state
	 */
	if (!persp->a.valpr) {
		stpgcnt = 0;
		newstpgcnt = (stsz + pgmask) / pgsz;
		descpgcnt = 0;
		memset((void *)&persp->a, 0,
			sizeof(pers_t) - offsetofmember(pers_t, a));
	} else if (!persp->s.valpr) {
		stpgcnt = persp->a.stpgcnt;
		newstpgcnt = stpgcnt;
		descpgcnt = 0;
		memset((void *)&persp->s, 0, sizeofmember(pers_t, s));
	} else {
		stpgcnt = persp->a.stpgcnt;
		newstpgcnt = stpgcnt;
		descpgcnt = persp->s.descpgcnt;
		assert(resumepr);
		mlog(MLOG_VERBOSE, _(
		      "resuming restore previously begun %s\n"),
		      ctimennl(&persp->s.begintime));
		persp->s.begintime = time(0);
	}

	/* unmap temp mapping of hdr, truncate, and remap hdr/subtrees
	 */
	rval = munmap((void *)persp, perssz);
	assert(!rval);
	rval = ftruncate(tranp->t_persfd, (off_t)perssz
					   +
					   (off_t)(stpgcnt + descpgcnt)
					   *
					   (off_t)pgsz);
	assert(!rval);
	stpgcnt = newstpgcnt;
	persp = (pers_t *) mmap_autogrow(perssz + stpgcnt * pgsz,
				   tranp->t_persfd, 0);
	if (persp == (pers_t *)-1) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "could not map persistent state file %s: %s\n"),
		      perspath,
		      strerror(errno));
		return BOOL_FALSE;
	}

	/* if first restore session, record cmd line args and subtrees
	 * and start time.
	 */
	if (!persp->a.valpr) {
		stdesc_t *stdescp;

		strcpy(persp->a.dstdir, dstdir);
		persp->a.dstdirisxfspr = platform_test_xfs_path(dstdir);
		if (cumpr) {
			persp->a.cumpr = cumpr;
		}
		if (interpr) {
			persp->a.interpr = interpr;
		}
		if (existpr) {
			persp->a.existpr = existpr;
		}
		if (changepr) {
			persp->a.changepr = changepr;
		}
		if (ownerpr) {
			persp->a.ownerpr = ownerpr;
		}
		if (newerpr) {
			persp->a.newerpr = newerpr;
			persp->a.newertime = newertime;
		}
		persp->a.restoredmpr = restoredmpr;
		if (!persp->a.dstdirisxfspr) {
			restoreextattrpr = BOOL_FALSE;
		}
		persp->a.restoreextattrpr = restoreextattrpr;
		persp->a.stcnt = stcnt;
		persp->a.firststsensepr = firststsensepr;
		persp->a.firststsenseprvalpr = firststsenseprvalpr;
		persp->a.stpgcnt = stpgcnt;
		optind = 1;
		opterr = 0;
		stdescp = (stdesc_t *)((char *)persp + perssz);
		while ((c = getopt(argc, argv, GETOPT_CMDSTRING)) != EOF) {
			size_t stdsz;
			switch (c) {
			case GETOPT_SUBTREE:
			case GETOPT_NOSUBTREE:
				stdescp->std_sensepr = (c == GETOPT_SUBTREE)
						       ?
						       BOOL_TRUE
						       :
						       BOOL_FALSE;
				stdsz = sizeof(stdesc_t)
					+
					strlen(optarg)
					+
					(STDESCALIGN - 1);
				stdsz &= ~(STDESCALIGN - 1);
				assert(stdsz <= (size_t)OFFMAX);
				stdescp->std_nextoff = (off_t)stdsz;
				strcpy(stdescp->std_path, optarg);
				stdescp = (stdesc_t *)
					  ((char *)stdescp + stdsz);
				stcnt--;
				break;
			}
		}
		assert(stcnt == 0);
	}

	/* initialize the local extattr abstraction. must be done even if
	 * we don't intend to restore extended attributes
	 */
	ok = extattr_init(drivecnt);
	if (!ok) {
		return BOOL_FALSE;
	}

	/* effectively initialize libhandle on this filesystem by
	 * allocating a file system handle. this needs to be done
	 * before any open_by_handle() calls (and possibly other
	 * libhandle calls).
	 */
	if (persp->a.dstdirisxfspr) {
		void	*fshanp;
		size_t	fshlen=0;

		if(path_to_fshandle(persp->a.dstdir, &fshanp, &fshlen)) {
			mlog(MLOG_NORMAL,
				_("unable to construct a file "
				  "system handle for %s: %s\n"),
				persp->a.dstdir,
				strerror(errno));
			return BOOL_FALSE;
		}
		/* libhandle has it cached, release this copy */
		free_handle(fshanp, fshlen);
	}

	/* map in pers. inv. descriptors, if any. NOTE: this ptr is to be
	 * referenced ONLY via the macros provided; the descriptors will be
	 * occasionally remapped, causing the ptr to change.
	 */
	assert(!descp);
	if (descpgcnt) {
		descp = (pers_desc_t *) mmap_autogrow(descpgcnt * pgsz,
						tranp->t_persfd,
						(off_t)perssz
						+
						(off_t)(stpgcnt * pgsz));
		if (descp == (pers_desc_t *)-1) {
			mlog(MLOG_NORMAL | MLOG_ERROR, _(
			      "could not map persistent state file inv %s: "
			      "%s (%d)\n"),
			      perspath,
			      strerror(errno),
			      errno);
			descp = 0;
			return BOOL_FALSE;
		}
		pi_preclean();
	}

	/* if resuming an interrupted restore, indicate we know the id
	 * of the dump session being restored. otherwise, it will be determined
	 * during coordination of per-drive threads.
	 */
	if (persp->a.valpr && persp->s.valpr) {
		persp->s.begintime = time(0);
		tranp->t_dumpidknwnpr = BOOL_TRUE;
	}

	/* sync up with the directory attributes registry.
	 * starts fresh with each dump session restored.
	 * determine if full init needed instead.
	 */
	if (persp->a.valpr && persp->s.valpr) {
		ok = dirattr_init(tranp->t_hkdir, BOOL_TRUE, (uint64_t)0);
		if (!ok) {
			return BOOL_FALSE;
		}
		tranp->t_dirattrinitdonepr = BOOL_TRUE;
	}

	/* sync up with the name registry. created by the
	 * first session, retained by subsequent sessions.
	 * determine if full init needed instead.
	 */
	if (persp->a.valpr) {
		ok = namreg_init(tranp->t_hkdir, BOOL_TRUE, (uint64_t)0);
		if (!ok) {
			return BOOL_FALSE;
		}
		tranp->t_namreginitdonepr = BOOL_TRUE;
	}

	/* sync up with the inomap abstraction. created anew with each fresh
	 * restore session, but persistent after tree updated with dirdump.
	 * determine if full init needed instead.
	 */
	ok = inomap_sync_pers(tranp->t_hkdir);
	if (!ok) {
		return BOOL_FALSE;
	}

	/* sync up with the tree abstraction. created by the
	 * first session, retained by subsequent sessions.
	 * don't call tree_init() from here; can only be called
	 * when a valid media file header is at hand.
	 */
	if (persp->a.valpr) {
		/* This is only a full restore if we're doing a level
		 * 0 restore.
		 */
		if (persp->a.dumpcnt == 0) {
			fullpr = BOOL_TRUE;
		} else {
			fullpr = BOOL_FALSE;
		}

		ok = tree_sync(tranp->t_hkdir,
				persp->a.dstdir,
				tranp->t_toconlypr,
				fullpr,
				persp->a.dstdirisxfspr);
		if (!ok) {
			return BOOL_FALSE;
		}
		tranp->t_treeinitdonepr = BOOL_TRUE;
	}

	/* set media change flags to FALSE;
	 */
	{
		ix_t ix;
		ix_t endix = sizeof(mcflag)
			     /
			     sizeof(mcflag[0]);
		for (ix = 0; ix < endix; ix++) {
			mcflag[ix] = BOOL_FALSE;
		}
	}
	content_media_change_needed = BOOL_FALSE;

	pi_show(" at initialization");
	return BOOL_TRUE;
}

/* stream thread entry point - returns exit code
 */
int
content_stream_restore(ix_t thrdix)
{
	dh_t fileh;
	Media_t *Mediap; /* local media abstraction */
	char *path1;
	char *path2;
	drive_t *drivep;
	int dcaps;
	global_hdr_t *grhdrp;
	drive_hdr_t *drhdrp;
	media_hdr_t *mrhdrp;
	content_hdr_t *crhdrp;
	content_inode_hdr_t *scrhdrp;
	stream_context_t *strctxp;
	filehdr_t fhdr; /* save hdr terminating dir restore */
	uuid_t lastdumprejectedid;
	rv_t rv;
	bool_t ok;
	int rval;

	/* allocate two path buffers
	 */
	path1 = (char *)calloc(1, 2 * MAXPATHLEN);
	assert(path1);
	path2 = (char *)calloc(1, 2 * MAXPATHLEN);
	assert(path2);

	/* set the current directory to dstdir. the tree abstraction
	 * depends on the current directory being the root of the
	 * destination file system.
	 */
	rval = chdir(persp->a.dstdir);
	if (rval) {
		mlog(MLOG_NORMAL, _(
		      "chdir %s failed: %s\n"),
		      persp->a.dstdir,
		      strerror(errno));
		return mlog_exit(EXIT_ERROR, RV_ERROR);
	}

	/* set my file creation mask to zero, to avoid modifying the
	 * dumped mode bits
	 */
	(void)umask(0);

	/* initialize the Media abstraction
	 */
	Mediap = Media_create(thrdix);

	/*
	 * initialize the stream context
	 */
	strctxp = (stream_context_t *)calloc(1, sizeof(stream_context_t));
	if (!strctxp) {
		mlog(MLOG_NORMAL | MLOG_ERROR,
		      _("malloc of stream context failed (%d bytes): %s\n"),
		      sizeof(stream_context_t),
		      strerror(errno));
		return mlog_exit(EXIT_ERROR, RV_ERROR);
	}
	strctxp->sc_fd = -1;
	Mediap->M_drivep->d_strmcontextp = (void *)strctxp;

	/* if we don't know the dump session id to restore,
	 * first see if command line options can be validated
	 * against the online inventory to identify it. only
	 * one stream needs to do this; the others just wait.
	 * side-effect of validation is to incorporate the online
	 * inventory into the persistent state.
	 */
	if (tranp->t_dumpidknwnpr) {
		tranp->t_sync1 = SYNC_DONE;
	}
	while (tranp->t_sync1 != SYNC_DONE) {
		lock();
		if (tranp->t_sync1 == SYNC_BUSY) {
			unlock();
			sleep(1);
			if (cldmgr_stop_requested()) {
				return mlog_exit(EXIT_NORMAL, RV_INTR);
			}
			continue;
		}
		if (tranp->t_sync1 == SYNC_DONE) {
			unlock();
			continue;
		}
		tranp->t_sync1 = SYNC_BUSY;
		unlock();
		mlog(MLOG_DEBUG,
		      "checking and validating command line dump id/label\n");
		ok = Inv_validate_cmdline();
		    /* side-effect - searches for and incorporates online inv
		     * into pi, and makes persp->s.dumpid valid.
		     */
		if (ok == BOOL_ERROR) {
			return mlog_exit(EXIT_ERROR, RV_OPT);
		}
		tranp->t_dumpidknwnpr = ok;
		tranp->t_sync1 = SYNC_DONE;
	}

	/* if we still don't know the session to restore, search the
	 * media for a match either to the command line arguments or
	 * until the operator selects a media file from the desired
	 * dump.
	 */
	if (tranp->t_dumpidknwnpr) {
		tranp->t_sync2 = SYNC_DONE;
	}
	uuid_clear(lastdumprejectedid);
	if (tranp->t_sync2 != SYNC_DONE) {
		mlog(MLOG_VERBOSE, _(
		      "searching media for dump\n"));
	}
	while (tranp->t_sync2 != SYNC_DONE) {
		bool_t matchpr;
		inv_session_t *sessp;
		bool_t resumepr;
		ix_t level;
		uuid_t *baseidp;

		rv = Media_mfile_next(Mediap,
				       PURP_SEARCH,
				       &tranp->t_sync2,
				       0,
				       &grhdrp,
				       &drhdrp,
				       &mrhdrp,
				       &crhdrp,
				       &scrhdrp,
				       &drivep,
				       &fhdr);
		switch (rv) {
		case RV_OK:
			break;
		case RV_DONE:
		case RV_NOMORE:
			continue;
		case RV_INTR:
		case RV_QUIT:
		case RV_DRIVE:
			Media_end(Mediap);
			return mlog_exit(EXIT_NORMAL, rv);
		case RV_CORE:
		default:
			Media_end(Mediap);
			return mlog_exit(EXIT_FAULT, rv);
		}
		dcaps = drivep->d_capabilities;

		lock();
		while (tranp->t_sync2 == SYNC_BUSY) {
			unlock();
			sleep(1);
			if (cldmgr_stop_requested()) {
				Media_end(Mediap);
				return mlog_exit(EXIT_NORMAL, RV_INTR);
			}
			lock();
		}
		if (tranp->t_sync2 == SYNC_DONE) {
			unlock();
			continue;
		}
		tranp->t_sync2 = SYNC_BUSY;

		unlock();
		mlog(MLOG_DEBUG,
		      "dump found: checking\n");
		matchpr = BOOL_FALSE;
		resumepr = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_RESUME);
		assert(scrhdrp->cih_level >= 0);
		level = (ix_t)scrhdrp->cih_level;
		baseidp = resumepr
			  ?
			  &scrhdrp->cih_resume_id
			  :
			  &scrhdrp->cih_last_id;
		if (tranp->t_reqdumpidvalpr) {
			if (uuid_compare(tranp->t_reqdumpid,
					 grhdrp->gh_dumpid) == 0) {
				matchpr = BOOL_TRUE;
				display_dump_label(BOOL_TRUE, /* lock */
						    MLOG_VERBOSE, _(
						    "found dump matching "
						    "specified id:\n"),
						    grhdrp,
						    mrhdrp,
						    crhdrp,
						    scrhdrp);
			}
		} else if (tranp->t_reqdumplabvalpr) {
			if (!strncmp(tranp->t_reqdumplab,
					grhdrp->gh_dumplabel,
					sizeof(grhdrp->gh_dumplabel))) {
				matchpr = BOOL_TRUE;
				display_dump_label(BOOL_TRUE, /* lock */
						    MLOG_VERBOSE,  _(
						    "found dump matching "
						    "specified label:\n"),
						    grhdrp,
						    mrhdrp,
						    crhdrp,
						    scrhdrp);
			}
		} else if (dumpcompat(resumepr,
					level,
					*baseidp,
					BOOL_FALSE)) {
			if (uuid_compare(lastdumprejectedid,
					 grhdrp->gh_dumpid) == 0) {
				matchpr = BOOL_FALSE;
			} else {
				if (dlog_allowed()
				     &&
				     ((dcaps & DRIVE_CAP_FILES)
				       ||
				       (dcaps & DRIVE_CAP_REMOVABLE)
				       ||
				       drivecnt > 1)) {
					matchpr = promptdumpmatch(thrdix,
								   grhdrp,
								   mrhdrp,
								   crhdrp,
								   scrhdrp);
				} else {
					matchpr = BOOL_TRUE;
					display_dump_label(BOOL_TRUE,/* lock */
							    MLOG_VERBOSE, _(
							    "dump "
							    "description: \n"),
							    grhdrp,
							    mrhdrp,
							    crhdrp,
							    scrhdrp);
				}
			}
		}
		if (cldmgr_stop_requested()) {
			Media_end(Mediap);
			return mlog_exit(EXIT_NORMAL, RV_INTR);
		}
		if (!matchpr) {
			Media_end(Mediap);
			uuid_copy(lastdumprejectedid, grhdrp->gh_dumpid);
			tranp->t_sync2 = SYNC_INIT;
			if (!dlog_allowed()
			     ||
			     (!(dcaps & DRIVE_CAP_FILES)
			       &&
			       !(dcaps & DRIVE_CAP_REMOVABLE))) {
				return mlog_exit(EXIT_NORMAL, RV_QUIT);
			}
			continue;
		}
		if (!dumpcompat(resumepr, level, *baseidp, BOOL_TRUE)) {
			Media_end(Mediap);
			return mlog_exit(EXIT_ERROR, RV_COMPAT);
		}
		strncpyterm(persp->s.dumplab,
			     grhdrp->gh_dumplabel,
			     sizeof(persp->s.dumplab));
		sessp = 0;

		/* don't look at the online inventory if the input is piped
		 */
		if (!drivep->d_isnamedpipepr
		     &&
		     !drivep->d_isunnamedpipepr) {
			ok = inv_get_session_byuuid(NULL,
						    &grhdrp->gh_dumpid,
						    &sessp);
			if (ok && sessp) {
				mlog(MLOG_VERBOSE, _(
				      "using online session inventory\n"));
				persp->s.fullinvpr = pi_transcribe(sessp);
				inv_free_session(&sessp);
			}
		}
		fileh = pi_addfile(Mediap,
				    grhdrp,
				    drhdrp,
				    mrhdrp,
				    scrhdrp,
				    drivep);
			/* done here because Media_mfile_next doesn't know
			 * if this is a match
			 */
		if (fileh == DH_NULL) {
			return mlog_exit(EXIT_FAULT, RV_ERROR);
		}
		uuid_copy(persp->s.dumpid, grhdrp->gh_dumpid);
		persp->s.begintime = time(0);
		tranp->t_dumpidknwnpr = BOOL_TRUE;
		tranp->t_sync2 = SYNC_DONE;
	}

	/* all drives coordinate in attempt to apply session dir dump.
	 * only one actually completes.
	 */
	if (persp->s.dirdonepr) {
		tranp->t_sync3 = SYNC_DONE;
	}
	if (tranp->t_sync3 != SYNC_DONE) {
		mlog(MLOG_VERBOSE, _(
		      "searching media for directory dump\n"));
	}
	while (tranp->t_sync3 != SYNC_DONE) {
		rv = Media_mfile_next(Mediap,
				       PURP_DIR,
				       &tranp->t_sync3,
				       &fileh,
				       &grhdrp,
				       &drhdrp,
				       &mrhdrp,
				       &crhdrp,
				       &scrhdrp,
				       &drivep,
				       &fhdr);
		switch (rv) {
		case RV_OK:
			break;
		case RV_DONE:
		case RV_NOMORE:
			continue;
		case RV_INTR:
		case RV_QUIT:
		case RV_DRIVE:
			Media_end(Mediap);
			return mlog_exit(EXIT_NORMAL, rv);
		case RV_CORE:
		default:
			Media_end(Mediap);
			return mlog_exit(EXIT_FAULT, rv);
		}
		dcaps = drivep->d_capabilities;
		assert(fileh != DH_NULL);
		lock();
		if (tranp->t_sync3 == SYNC_BUSY) {
			unlock();
			mlog(MLOG_TRACE,
			      "waiting for directories to be restored\n");
			lock();
		}
		while (tranp->t_sync3 == SYNC_BUSY) {
			unlock();
#if DEBUG_DUMPSTREAMS
			{
			    static int count[STREAM_MAX] = {0};
			    int streamix = stream_getix(pthread_self());
			    if (++(count[streamix]) == 30) {
				mlog(MLOG_TRACE,
					"still waiting for dirs to be restored\n");
				count[streamix] = 0;
			    }
			}
#endif
			sleep(1);
			if (cldmgr_stop_requested()) {
				Media_end(Mediap);
				return mlog_exit(EXIT_NORMAL, RV_INTR);
			}
			lock();
		}
		if (tranp->t_sync3 == SYNC_DONE) {
			unlock();
			continue;
		}
		if (!(scrhdrp->cih_dumpattr & CIH_DUMPATTR_DIRDUMP)) {
			/* if no streams have a directory dump, issue a
			 * message and exit. first set SYNC_BUSY to prevent
			 * other threads from coming through here and issuing
			 * the same message.
			 */
			tranp->t_dirdumps &= ~(1ULL << thrdix);
			if (!tranp->t_dirdumps) {
				tranp->t_sync3 = SYNC_BUSY;
			}
			unlock();
			if (!tranp->t_dirdumps) {
				mlog(MLOG_VERBOSE | MLOG_ERROR, _(
					"no directory dump found\n"));
				Media_end(Mediap);
				return mlog_exit(EXIT_NORMAL, RV_ERROR);
			}
			sleep(1);
			if (cldmgr_stop_requested()) {
				Media_end(Mediap);
				return mlog_exit(EXIT_NORMAL, RV_INTR);
			}
			continue;
		}
		tranp->t_sync3 = SYNC_BUSY;
		unlock();
		if (!tranp->t_dirattrinitdonepr) {
			mlog(MLOG_TRACE,
			      "initializing directory attributes registry\n");
			mlog(MLOG_NITTY,
			      "content_stream_restore: dircnt %llu\n",
			      scrhdrp->cih_inomap_dircnt);
			ok = dirattr_init(tranp->t_hkdir,
					   BOOL_FALSE,
					   scrhdrp->cih_inomap_dircnt);
			if (!ok) {
				Media_end(Mediap);
				return mlog_exit(EXIT_ERROR, RV_ERROR);
			}
			tranp->t_dirattrinitdonepr = BOOL_TRUE;
		}

		if (!tranp->t_namreginitdonepr) {
			mlog(MLOG_TRACE,
			      "initializing directory entry name registry\n");
			ok = namreg_init(tranp->t_hkdir,
					  BOOL_FALSE,
					  scrhdrp->cih_inomap_dircnt
					  +
					  scrhdrp->cih_inomap_nondircnt);
			if (!ok) {
				Media_end(Mediap);
				return mlog_exit(EXIT_ERROR, RV_ERROR);
			}
			tranp->t_namreginitdonepr = BOOL_TRUE;
		}

		if (!tranp->t_treeinitdonepr) {
			bool_t fullpr;

			fullpr = (scrhdrp->cih_level
				   ==
				   0)
				 &&
				 !(scrhdrp->cih_dumpattr
				    &
				    CIH_DUMPATTR_RESUME);

			mlog(MLOG_TRACE,
			      "initializing directory hierarchy image\n");
			ok = tree_init(tranp->t_hkdir,
					persp->a.dstdir,
					tranp->t_toconlypr,
					persp->a.ownerpr,
					scrhdrp->cih_rootino,
					scrhdrp->cih_inomap_firstino,
					scrhdrp->cih_inomap_lastino,
					scrhdrp->cih_inomap_dircnt,
					scrhdrp->cih_inomap_nondircnt,
					tranp->t_vmsz,
					fullpr,
					persp->a.restoredmpr,
					persp->a.dstdirisxfspr,
					grhdrp->gh_version,
					tranp->t_truncategenpr);
			if (!ok) {
				Media_end(Mediap);
				return mlog_exit(EXIT_ERROR, RV_ERROR);
			}
			tranp->t_treeinitdonepr = BOOL_TRUE;

		} else {
			ok = tree_check_dump_format(grhdrp->gh_version);
			if (!ok) {
				Media_end(Mediap);
				return mlog_exit(EXIT_ERROR, RV_ERROR);
			}
		}

		/* commit the session and accumulative state
		 */
		persp->s.valpr = BOOL_TRUE;
		persp->a.valpr = BOOL_TRUE;

		mlog(MLOG_VERBOSE, _(
		      "reading directories\n"));
		win_locks_off(); /* we are single threaded here */
		rv = applydirdump(drivep, fileh, scrhdrp, &fhdr);
		win_locks_on();
		mlog(MLOG_TRACE,
		      "number of mmap calls for windows = %lu\n", win_getnum_mmaps());
		switch (rv) {
		case RV_OK:
			DH2F(fileh)->f_dirtriedpr = BOOL_TRUE;
			Media_atnondir(Mediap);
			tranp->t_sync3 = SYNC_DONE;
			break;
		case RV_CORRUPT:
			Media_indir(Mediap);
			DH2F(fileh)->f_dirtriedpr = BOOL_TRUE;
			tranp->t_sync3 = SYNC_INIT;
			break;
		case RV_INTR:
		case RV_DRIVE:
			Media_end(Mediap);
			return mlog_exit(EXIT_NORMAL, rv);
		case RV_CORE:
		default:
			Media_end(Mediap);
			return mlog_exit(EXIT_FAULT, rv);
		}
	}

	/* now let one thread do all tree post-processing prior to
	 * non-dir restore
	 */
	if (persp->s.treepostdonepr) {
		tranp->t_sync4 = SYNC_DONE;
	}
	while (tranp->t_sync4 != SYNC_DONE) {
		lock();
		if (tranp->t_sync4 == SYNC_BUSY) {
			unlock();
			mlog(MLOG_TRACE,
			      "waiting for directory post-processing "
			      "to complete\n");
			lock();
		}
		while (tranp->t_sync4 == SYNC_BUSY) {
			unlock();
#if DEBUG_DUMPSTREAMS
			{
			static int count[STREAM_MAX] = {0};
			int streamix = stream_getix(pthread_self());
			    if (++(count[streamix]) == 30) {
				mlog(MLOG_NORMAL,
				      "still waiting for dirs post-processing\n");
				count[streamix] = 0;
			    }
			}
#endif
			sleep(1);
			if (cldmgr_stop_requested()) {
				Media_end(Mediap);
				return mlog_exit(EXIT_NORMAL, RV_INTR);
			}
			lock();
		}
		if (tranp->t_sync4 == SYNC_DONE) {
			unlock();
			continue;
		}
		tranp->t_sync4 = SYNC_BUSY;
		unlock();
		mlog(MLOG_VERBOSE, _(
		      "directory post-processing\n"));
		win_locks_off(); /* we are single threaded here */
		rv = treepost(path1, path2);
		win_locks_on();
		switch (rv) {
		case RV_OK:
			break;
		case RV_ERROR:
			Media_end(Mediap);
			return mlog_exit(EXIT_ERROR, RV_ERROR);
		case RV_INTR:
			Media_end(Mediap);
			return mlog_exit(EXIT_INTERRUPT, RV_INTR);
		case RV_CORE:
		default:
			Media_end(Mediap);
			return mlog_exit(EXIT_FAULT, rv);
		}

		/* now that we have a tree and inomap, scan the
		 * pi to see what media files can be skipped.
		 * this func has cancer: too many flags and
		 * side-effects!
		 */
		{
		bool_t dummyknownholespr;
		bool_t dummymaybeholespr;
		bag_t *bagp = pi_neededobjs_nondir_alloc(&dummyknownholespr,
							  &dummymaybeholespr,
							  BOOL_FALSE,
							  BOOL_TRUE);
		if (bagp) {
			pi_neededobjs_free(bagp);
			bagp = 0;
		}
		}

		/* release exclusion
		 */
		tranp->t_sync4 = SYNC_DONE;
	}

	/* now all are free to do concurrent non-dir restore!
	 * apply media files until there are no more, or we are interrupted
	 */
	for (;;) {
		mlog(MLOG_DEBUG,
		      "getting next media file for non-dir restore\n");
		rv = Media_mfile_next(Mediap,
				       PURP_NONDIR,
				       0,
				       &fileh,
				       &grhdrp,
				       &drhdrp,
				       &mrhdrp,
				       &crhdrp,
				       &scrhdrp,
				       &drivep,
				       &fhdr);
		if (rv == RV_NOMORE) {
			break;
		}
		switch (rv) {
		case RV_OK:
			break;
		case RV_INTR:
		case RV_QUIT:
		case RV_DRIVE:
			Media_end(Mediap);
			return mlog_exit(EXIT_NORMAL, rv);
		case RV_CORE:
		default:
			Media_end(Mediap);
			return mlog_exit(EXIT_FAULT, rv);
		}
		dcaps = drivep->d_capabilities;
		assert(fileh > DH_NULL);
		if (tranp->t_toconlypr) {
			mlog(MLOG_VERBOSE, _(
			      "reading non-directory files\n"));
		} else {
			mlog(MLOG_VERBOSE, _(
			      "restoring non-directory files\n"));
		}
		mlog(MLOG_TRACE,
		      "media file %u in "
		      "object %u "
		      "of stream %u\n",
		      mrhdrp->mh_mediafileix,
		      mrhdrp->mh_mediaix,
		      drhdrp->dh_driveix);
		mlog(MLOG_DEBUG,
		      "file %u in stream, "
		      "file %u in dump %u on object\n",
		      mrhdrp->mh_dumpfileix,
		      mrhdrp->mh_dumpmediafileix,
		      mrhdrp->mh_dumpmediaix);
		rv = applynondirdump(drivep,
				      fileh,
				      scrhdrp,
				      path1,
				      path2,
				      &fhdr);
		switch (rv) {
		case RV_OK:
			DH2F(fileh)->f_nondirdonepr = BOOL_TRUE;
			Media_end(Mediap);
			break;
		case RV_INTR:
		case RV_DRIVE:
		case RV_INCOMPLETE:
			Media_end(Mediap);
			return mlog_exit(EXIT_NORMAL, rv);
		case RV_CORE:
		default:
			Media_end(Mediap);
			return mlog_exit(EXIT_FAULT, rv);
		}
	}

	/* finally, choose one thread to do final processing
	 * and cleanup. the winner waits, the losers all exit.
	 * once the losers exit, the winner can perform cleanup.
	 */
	lock();
	if (tranp->t_sync5 == SYNC_BUSY) {
		unlock();
		return mlog_exit(EXIT_NORMAL, RV_DONE);
	}
	tranp->t_sync5 = SYNC_BUSY;
	unlock();
	if (drivecnt > 1) {
		mlog(MLOG_TRACE,
		      "waiting for other streams to exit\n");
	}
	while (cldmgr_otherstreamsremain(thrdix)) {
		sleep(1);
	}

	mlog(MLOG_DEBUG,
	      "tree finalize\n");
	rv = finalize(path1, path2);
	if (rv == RV_OK || rv == RV_INTR) {
		rval = EXIT_NORMAL;
	} else if (rv == RV_ERROR) {
		rval = EXIT_ERROR;
	} else {
		rval = EXIT_FAULT;
	}

	return mlog_exit(rval, rv);
}

/* called after all threads have exited. scans state to decide
 * if interrupted or not.
 */
bool_t
content_complete(void)
{
	bool_t completepr;
	time_t elapsed;

	if (!persp) {
		completepr = BOOL_TRUE;
	} else if (!persp->a.valpr) {
		completepr =  BOOL_TRUE;
	} else if (!persp->s.valpr) {
		completepr =  BOOL_TRUE;
	} else {
		completepr = BOOL_FALSE;
	}

	elapsed = time(0) - tranp->t_starttime;
	if (persp) {
		elapsed += persp->s.accumtime;
	}

	if (completepr) {
		if (tranp->t_toconlypr) {
			mlog(MLOG_VERBOSE, _(
			      "table of contents display complete"
			      ": %ld seconds elapsed"
			      "\n"),
			      elapsed);
		} else {
			int found;

			found = quotafilecheck("user",
					       persp->a.dstdir,
					       CONTENT_QUOTAFILE);
			found += quotafilecheck("project",
						persp->a.dstdir,
						CONTENT_PQUOTAFILE);
			found += quotafilecheck("group",
						persp->a.dstdir,
						CONTENT_GQUOTAFILE);

			if (found)
				mlog(MLOG_NORMAL,
				      _("use \'xfs_quota\' to restore quotas\n"));

			mlog(MLOG_VERBOSE, _(
			      "restore complete"
			      ": %ld seconds elapsed"
			      "\n"),
			      elapsed);
		}
	} else if (tranp->t_toconlypr) {
		mlog(MLOG_VERBOSE | MLOG_NOTE, _(
		      "table of contents display interrupted"
		      ": %ld seconds elapsed"
		      "\n"),
		      elapsed);
	} else {
		mlog(MLOG_VERBOSE | MLOG_NOTE, _(
		      "restore interrupted"
		      ": %ld seconds elapsed"
		      ": may resume later using -%c option"
		      "\n"),
		      elapsed,
		      GETOPT_RESUME);
	}

	/* accumulate total elapsed time
	 */
	if (persp) {
		persp->s.accumtime = elapsed;
	}

	if (!persp->a.valpr) {
		wipepersstate();
		persp = 0;
	}

	return completepr;
}

#define STATLINESZ	160

size_t
content_statline(char **linespp[])
{
	static char statlinebuf[1][STATLINESZ];
	static char *statline[1];
	size64_t inodone;
	off64_t datadone;
	size64_t inocnt;
	off64_t datacnt;
	double percent;
	time_t elapsed;
	time_t now;
	struct tm *tmp;
	ix_t i;

	/* build and supply the line array
	 */
	for (i = 0; i < 1; i++) {
		statline[i] = &statlinebuf[i][0];
	}
	*linespp = statline;

	if (!persp->s.stat_valpr) {
		return 0;
	}

	/* calculate the elapsed time
	 */
	elapsed = persp->s.accumtime
		  +
		  (time(0) - tranp->t_starttime);

	/* get local time
	 */
	now = time(0);
	tmp = localtime(&now);

	if (!persp->s.dirdonepr) {
		if (!tranp->t_dircnt) {
			return 0;
		}

		percent = (double)tranp->t_dirdonecnt
			  /
			  (double)tranp->t_dircnt;
		percent *= 100.0;
		sprintf(statline[0], _(
			 "status at %02d:%02d:%02d: "
			 "%llu/%llu directories reconstructed, "
			 "%.1f%%%% complete, "
			 "%llu directory entries processed, "
			 "%ld seconds elapsed\n"),
			 tmp->tm_hour,
			 tmp->tm_min,
			 tmp->tm_sec,
			 (unsigned long long)tranp->t_dirdonecnt,
			 (unsigned long long)tranp->t_dircnt,
			 percent,
			 (unsigned long long)tranp->t_direntcnt,
			 elapsed);
		assert(strlen(statline[0]) < STATLINESZ);

		return 1;
	}

	/* get the accumulated totals for non-dir inos and data bytes dumped.
	 * not under lock!
	 */
	inodone = persp->s.stat_inodone;
	datadone = persp->s.stat_datadone;
	inocnt = persp->s.stat_inocnt;
	datacnt = persp->s.stat_datacnt;

	/* calculate percentage of data dumped
	 */
	if (datacnt) {
		percent = (double)datadone
			  /
			  (double)datacnt;
		percent *= 100.0;
	} else {
		percent = 100.0;
	}
	if (percent > 100.0) {
		percent = 100.0;
	}

	/* format the status line in a local static buffer (non-re-entrant!)
	 */
	sprintf(statline[0], _(
		 "status at %02d:%02d:%02d: %llu/%llu files restored, "
		 "%.1f%%%% complete, "
		 "%ld seconds elapsed\n"),
		 tmp->tm_hour,
		 tmp->tm_min,
		 tmp->tm_sec,
		 (unsigned long long)inodone,
		 (unsigned long long)inocnt,
		 percent,
		 elapsed);
	assert(strlen(statline[0]) < STATLINESZ);

	/* return buffer to caller
	 */
	return 1;
}

void
content_showinv(void)
{
	pi_show_nomloglock();
}

void
content_showremainingobjects(void)
{
	bool_t knownholespr = BOOL_FALSE;
	bool_t maybeholespr = BOOL_FALSE;
	bag_t *bagp;

	bagp = pi_neededobjs_nondir_alloc(&knownholespr,
					   &maybeholespr,
					   BOOL_TRUE,
					   BOOL_FALSE);
	display_needed_objects(PURP_NONDIR,
				bagp,
				knownholespr,
				maybeholespr);
	if (bagp) {
		pi_neededobjs_free(bagp);
		bagp = 0;
	}
}

/* dlog_begin already called; this is a second-level dialog.
 * prompt for each thread currently waiting for confirmation,
 * as well as an info prompt.
 */
#define PREAMBLEMAX	3
#define QUERYMAX	36
#define CHOICEMAX	30
#define ACKMAX		3
#define POSTAMBLEMAX	3
#define DLOG_TIMEOUT	300
#define DLOG_TIMEOUT_MEDIA	3600

#define CHOICESTRSZ	10
typedef struct { ix_t thrdix; char choicestr[CHOICESTRSZ]; } cttm_t;

char *
content_mediachange_query(void)
{
	cttm_t choicetothrdmap[STREAM_SIMMAX];
	char *querystr[QUERYMAX];
	size_t querycnt;
	char *choicestr[CHOICEMAX];
	size_t choicecnt;
	char *ackstr[ACKMAX];
	size_t ackcnt;
	size_t maxdrvchoiceix;
	size_t infoix;
	size_t nochangeix;
	size_t responseix;
	ix_t thrdix;

	infoix = querycnt = 0;
	querystr[querycnt++] =
		_("select a drive to acknowledge media change\n");
	choicecnt = 0;
	maxdrvchoiceix = 0;
	for (thrdix = 0; thrdix < STREAM_SIMMAX; thrdix++) {
		if (mcflag[thrdix]) {
			choicetothrdmap[choicecnt].thrdix = thrdix;
			sprintf(choicetothrdmap[choicecnt].choicestr,
				 _("drive %u"),
				 (unsigned int)thrdix);
			choicestr[choicecnt] =
					choicetothrdmap[choicecnt].choicestr;
			maxdrvchoiceix = choicecnt;
			choicecnt++;
		}
	}
	if (persp->s.valpr) {
		infoix = choicecnt;
		choicestr[choicecnt++ ] = _("display needed media objects");
	}
	nochangeix = choicecnt;
	choicestr[choicecnt++ ] = _("continue");
	assert(choicecnt <= CHOICEMAX);
	responseix = dlog_multi_query(querystr,
				       querycnt,
				       choicestr,
				       choicecnt,
				       0,           /* hilitestr */
				       IXMAX,       /* hiliteix */
				       0,           /* defaultstr */
				       nochangeix,  /* defaultix */
				       DLOG_TIMEOUT,
				       nochangeix, /* timeout ix */
				       nochangeix, /* sigint ix */
				       nochangeix, /* sighup ix */
				       nochangeix);/* sigquit ix */
	if (responseix <= maxdrvchoiceix) {
		clr_mcflag(choicetothrdmap[responseix].thrdix);
		return _("media change acknowledged\n");
	}
	if (responseix == infoix) {
		bool_t knownholespr = BOOL_FALSE;
		bool_t maybeholespr = BOOL_FALSE;
		bag_t *bagp = pi_neededobjs_nondir_alloc(&knownholespr,
							  &maybeholespr,
							  BOOL_FALSE,
							  BOOL_FALSE);
		display_needed_objects(PURP_NONDIR,
					bagp,
					knownholespr,
					maybeholespr);
		if (bagp) {
			pi_neededobjs_free(bagp);
			bagp = 0;
		}
		ackcnt = 0;
		dlog_multi_ack(ackstr,
				ackcnt);
		querycnt = 0;
		choicecnt = 0;
		nochangeix = choicecnt;
		choicestr[choicecnt++ ] = _("continue");
		assert(choicecnt <= CHOICEMAX);
		responseix = dlog_multi_query(querystr,
					       querycnt,
					       choicestr,
					       choicecnt,
					       0,           /* hilitestr */
					       IXMAX,       /* hiliteix */
					       0,           /* defaultstr */
					       nochangeix,  /* defaultix */
					       DLOG_TIMEOUT,
					       nochangeix, /* timeout ix */
					       nochangeix, /* sigint ix */
					       nochangeix, /* sighup ix */
					       nochangeix);/* sigquit ix */
		return _("continuing\n");
	}
	assert(responseix == nochangeix);
	return _("continuing\n");
}

/* definition of locally defined static functions ****************************/

/* does all pre-processing leading up to applying the dirdump,
 * then applies the dirdump. updates pers progress flags along the way.
 * does NOT do any post-processing!
 */
/* ARGSUSED */
static rv_t
applydirdump(drive_t *drivep,
	      dh_t fileh,
	      content_inode_hdr_t *scrhdrp,
	      filehdr_t *fhdrp)
{
	bool_t fhcs;
	bool_t dhcs;
	bool_t ahcs;

	fhcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_FILEHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;
	dhcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_DIRENTHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;
	ahcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_EXTATTRHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;

	if (!persp->s.marknorefdonepr) {
		tree_marknoref();
		persp->s.marknorefdonepr = BOOL_TRUE;
	}

	if (scrhdrp->cih_dumpattr & CIH_DUMPATTR_NOTSELFCONTAINED) {
		mlog(MLOG_NORMAL | MLOG_NOTE, _(
		      "dump is not self-contained, "
		      "orphaned files expected if base dump(s) "
		      "was not applied\n"));
	}

	if (!persp->s.dirdonepr) {
		rv_t rv;
		dah_t dah;

		char _direntbuf[sizeof(direnthdr_t)
				+
				NAME_MAX + 1
				+
				DIRENTHDR_ALIGN];
		char *direntbuf = ALIGN_PTR(_direntbuf, DIRENTHDR_ALIGN);
		size_t direntbufsz =
			sizeof(_direntbuf) - (direntbuf - _direntbuf);

		mlog(MLOG_TRACE,
		      "reading the ino map\n");
		rv = inomap_restore_pers(drivep, scrhdrp, tranp->t_hkdir);
		if (rv != RV_OK) {
			return rv;
		}

		tranp->t_dircnt = scrhdrp->cih_inomap_dircnt;
		tranp->t_dirdonecnt = 0;
		tranp->t_direntcnt = 0;

		mlog(MLOG_TRACE,
		      "reading the directories \n");

		dah = DAH_NULL;
		for (;;) {
			nh_t dirh;

			/* read the file header
			 */
			rv = read_filehdr(drivep, fhdrp, fhcs);
			if (rv) {
				return rv;
			}

			/* if this is a null file hdr, we're done
			 * reading dirs, and there are no nondirs.
			 * done.
			 */
			if (fhdrp->fh_flags & FILEHDR_FLAGS_NULL) {
				break;
			}

			/* if its not a directory, must be the
			 * first non-dir file. done.
			 */
			if ((fhdrp->fh_stat.bs_mode & S_IFMT) != S_IFDIR) {
				break;
			}

			/* if stop requested bail out gracefully
			 */
			if (cldmgr_stop_requested()) {
				return RV_INTR;
			}

			/* if in a pipeline, call preemptchk() to
			 * print status reports
			 */
			if (pipeline)
			{
				mlog(MLOG_DEBUG,
					"preemptchk( )\n");
				preemptchk();
			}

			/* may be an extended attributes file hdr
			 */
			if (fhdrp->fh_flags & FILEHDR_FLAGS_EXTATTR) {
				rv = restore_extattr(drivep,
						      fhdrp,
						      0,
						      ahcs,
						      BOOL_TRUE, /* isdirpr */
						      BOOL_FALSE, /* onlydoreadpr */
						      dah);
				if (rv != RV_OK) {
					return rv;
				}
				continue;
			}

			/* add the directory to the tree. save the
			 * returned tree node id, to associate with
			 * the directory entries. get the dirattr handle,
			 * so that any extattr following will be associated
			 * with that dir.
			 */
			dah = DAH_NULL;
			dirh = tree_begindir(fhdrp, &dah);
			if (dirh == NH_NULL)
			    return RV_ERROR;

			/* read the directory entries, and populate the
			 * tree with them. we can tell when we are done
			 * by looking for a null dirent.
			 */
			for (;;) {
				register direnthdr_t *dhdrp =
						    (direnthdr_t *)direntbuf;
				register size_t namelen;

				rv = read_dirent(drivep,
						  dhdrp,
						  direntbufsz,
						  dhcs);
				if (rv != RV_OK) {
					return rv;
				}

				/* if null, we're done with this dir.
				 * break out of this inner loop and
				 * move on th the next dir.
				 */
				if (dhdrp->dh_ino == 0) {
					break;
				}
				namelen = strlen(dhdrp->dh_name);
				assert(namelen <= NAME_MAX);

				/* add this dirent to the tree.
				 */
				rv = tree_addent(dirh,
					     dhdrp->dh_ino,
					     dhdrp->dh_gen,
					     dhdrp->dh_name,
					     namelen);
				if (rv != RV_OK) {
					return rv;
				}
				tranp->t_direntcnt++;
			}

			tree_enddir(dirh);

			tranp->t_dirdonecnt++;
		}

		if ((rv = dirattr_flush()) != RV_OK) {
			return rv;
		}

		if ((rv = namreg_map()) != RV_OK) {
			return rv;
		}

		persp->s.dirdonepr = BOOL_TRUE;
	}

	mlog(MLOG_VERBOSE, _("%llu directories and %llu entries processed\n"),
		tranp->t_dirdonecnt, tranp->t_direntcnt);

	return RV_OK;
}

/* like applydirdump, but just eats up the inomap/dirdump portion of the
 * dump, doesn't use it. the first non-dir filehdr_t is copied into supplied
 * buffer. returns integer error code from drive ops used.
 */
/* ARGSUSED */
rv_t
eatdirdump(drive_t *drivep,
	    dh_t fileh,
	    content_inode_hdr_t *scrhdrp,
	    filehdr_t *fhdrp)
{
	bool_t fhcs;
	bool_t dhcs;
	bool_t ahcs;

	char _direntbuf[sizeof(direnthdr_t)
			+
			NAME_MAX + 1
			+
			DIRENTHDR_ALIGN];
	char *direntbuf = ALIGN_PTR(_direntbuf, DIRENTHDR_ALIGN);
	size_t direntbufsz = sizeof(_direntbuf) - (direntbuf - _direntbuf);
	rv_t rv;

	fhcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_FILEHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;
	dhcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_DIRENTHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;
	ahcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_EXTATTRHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;

	mlog(MLOG_DEBUG,
	      "discarding ino map\n");
	rv = inomap_discard(drivep, scrhdrp);
	if (rv != RV_OK) {
		return rv;
	}

	mlog(MLOG_DEBUG,
	      "discarding directories \n");
	for (;;) {
		/* read the file header
		 */
		rv = read_filehdr(drivep, fhdrp, fhcs);
		if (rv) {
			return rv;
		}

		/* if this is a null file hdr, we're done
		 * reading dirs, and there are no nondirs.
		 * done.
		 */
		if (fhdrp->fh_flags & FILEHDR_FLAGS_NULL) {
			break;
		}

		/* if its not a directory, must be the
		 * first non-dir file. done.
		 */
		if ((fhdrp->fh_stat.bs_mode & S_IFMT) != S_IFDIR) {
			break;
		}

		/* if stop requested bail out gracefully
		 */
		if (cldmgr_stop_requested()) {
			return RV_INTR;
		}

		/* may be an extended attributes file hdr
		 */
		if (fhdrp->fh_flags & FILEHDR_FLAGS_EXTATTR) {
			rv = restore_extattr(drivep,
					      fhdrp,
					      0,
					      ahcs,
					      BOOL_TRUE, /* isdirpr */
					      BOOL_TRUE, /* onlydoreadpr */
					      DAH_NULL);
			if (rv != RV_OK) {
				return rv;
			}
			continue;
		}

		/* read the directory entries.
		 * we can tell when we are done
		 * by looking for a null dirent.
		 */
		for (;;) {
			register direnthdr_t *dhdrp =
					    (direnthdr_t *)direntbuf;
			/* REFERENCED */
			register size_t namelen;

			rv = read_dirent(drivep,
					  dhdrp,
					  direntbufsz,
					  dhcs);
			if (rv) {
				return rv;
			}

			/* if null, we're done with this dir.
			 * break out of this inner loop and
			 * move on th the next dir.
			 */
			if (dhdrp->dh_ino == 0) {
				break;
			}
			namelen = strlen(dhdrp->dh_name);
			assert(namelen <= NAME_MAX);
		}
	}

	return RV_OK;
}

/* does all post-processing of the tree required prior to restoral of
 * the non-directory portion of the dump. only one thread at a time,
 * so no locking needed. since the steps are interdependent, loops
 * until no point in doing so.
 */
static rv_t
treepost(char *path1, char *path2)
{
	bool_t ok;

#ifdef TREE_CHK
	/* first scan the tree for corruption
	 */
	mlog(MLOG_DEBUG | MLOG_TREE,
	      "checking tree for consistency\n");
	if (!tree_chk()) {
		return RV_CORE;
	}
#endif /* TREE_CHK */

	/* adjust ref flags based on what dirs were dumped
	 */
	if (!persp->s.adjrefdonepr) {
		mlog(MLOG_DEBUG | MLOG_TREE,
		      "adjusting dirent ref flags\n");
		ok = tree_adjref();
		if (!ok) {
			return RV_INTR;
		}
		persp->s.adjrefdonepr = BOOL_TRUE;
	}

	/* if a subtree or interactive restore, sanitize the inomap
	 * so only inos selected by subtree or interactive cmds will
	 * be present in inomap.
	 */
	if (!persp->s.inomapsanitizedonepr) {
		if (persp->a.interpr
		     ||
		     (persp->a.firststsenseprvalpr
		       &&
		       persp->a.firststsensepr)) {
			inomap_sanitize();
		}
		persp->s.inomapsanitizedonepr = BOOL_TRUE;
	}

	/* apply subtree selections
	 */
	if (!persp->s.stdonepr) {
		ix_t stix;
		stdesc_t *stdescp;

		mlog(MLOG_DEBUG | MLOG_TREE,
		      "applying subtree selections\n");

		/* if first subtree selection is inclusive in sense,
		 * first mark the entire tree as unselected. otherwise,
		 * select all (no subtree selections or first was excluding).
		 */
		if ((persp->a.interpr
		       &&
		       (!persp->a.firststsenseprvalpr
		         ||
		         persp->a.firststsensepr))
		     ||
		     (persp->a.firststsenseprvalpr
		       &&
		       persp->a.firststsensepr)) {
			tree_markallsubtree(BOOL_FALSE);
		} else {
			tree_markallsubtree(BOOL_TRUE);
		}

		/* now apply all subtree commands from command line
		 */
		for (stix = 0,
		      stdescp = (stdesc_t *)((char *)persp + perssz)
		      ;
		      stix < persp->a.stcnt
		      ;
		      stix++,
		      stdescp = (stdesc_t *)((char *)stdescp
						+
						stdescp->std_nextoff)) {
			ok = tree_subtree_parse(stdescp->std_sensepr,
						 stdescp->std_path);
			if (!ok) {
				mlog(MLOG_NORMAL | MLOG_ERROR, _(
				      "subtree argument %s invalid\n"),
				      stdescp->std_path);
				return RV_ERROR;
			}
		}
		persp->s.stdonepr = BOOL_TRUE;
	}

	/* next engage interactive subtree selection
	 */
	if (!persp->s.interdonepr) {
		if (persp->a.interpr) {
			ok = tree_subtree_inter();
			if (!ok) {
				return RV_INTR;
			}
		}
		persp->s.interdonepr = BOOL_TRUE;
	}

	ok = tree_post(path1, path2);

	if (!ok) {
		return RV_INTR;
	}

	ok = tree_extattr(restore_dir_extattr_cb, path1);
	if (!ok) {
		return RV_INTR;
	}

	persp->s.treepostdonepr = BOOL_TRUE;

	return RV_OK;
}

static rv_t
applynondirdump(drive_t *drivep,
		 dh_t fileh,
		 content_inode_hdr_t *scrhdrp,
		 char *path1,
		 char *path2,
		 filehdr_t *fhdrp)
{
	rv_t rv = RV_UNKNOWN;
	bool_t fhcs;
	bool_t ehcs;
	bool_t ahcs;
	egrp_t first_egrp;
	egrp_t next_egrp;
	stream_context_t *strctxp = (stream_context_t *)drivep->d_strmcontextp;

	/* determine if file header and/or extent heade checksums present
	 */
	fhcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_FILEHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;
	ehcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_EXTENTHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;
	ahcs = (scrhdrp->cih_dumpattr & CIH_DUMPATTR_EXTATTRHDR_CHECKSUM)
	       ?
	       BOOL_TRUE
	       :
	       BOOL_FALSE;

	/* determine the first and next egrps needed from this media file.
	 * used to decide if stats should be updated
	 */
	pi_bracketneededegrps(fileh, &first_egrp, &next_egrp);

	/* initialize the stream context
	 */
	memset(&strctxp->sc_bstat, 0, sizeof(bstat_t));
	strctxp->sc_path[0] = '\0';
	strctxp->sc_fd = -1;
	strctxp->sc_ownerset = BOOL_FALSE;


	for (;;) {
		drive_ops_t *dop = drivep->d_opsp;
		drive_mark_t drivemark;
		bstat_t *bstatp = &fhdrp->fh_stat;
		bool_t resyncpr = BOOL_FALSE;
		int rval;

		/* if a null file header, break
		 */
		if (fhdrp->fh_flags & FILEHDR_FLAGS_NULL) {
			rv = RV_OK;
			goto applynondirdump_out;
		}

		/* if working on a different file than we were previously,
		 * complete the old one and begin the new one.
		 */
		if (bstatp->bs_ino != strctxp->sc_bstat.bs_ino) {

			restore_complete_reg(strctxp);

			/* start new ino */
			memcpy(&strctxp->sc_bstat, bstatp, sizeof(bstat_t));
			strctxp->sc_path[0] = '\0';
			strctxp->sc_fd = -1;
			strctxp->sc_ownerset = BOOL_FALSE;

			rv = restore_file(drivep, fhdrp, ehcs, ahcs, path1, path2);

		} else if (fhdrp->fh_flags & FILEHDR_FLAGS_EXTATTR) {
			rv = restore_extattr(drivep,
					      fhdrp,
					      strctxp->sc_path,
					      ahcs,
					      BOOL_FALSE, /* isdirpr */
					      BOOL_FALSE, /* onlydoreadpr */
					      DAH_NULL);
		} else {
			/* Must be another extent group for the current file */
			restore_extent_group(drivep,
					      fhdrp,
					      strctxp->sc_path,
					      strctxp->sc_fd,
					      ehcs,
					      &rv);
		}

		switch(rv) {
		case RV_OK:
			break;
		case RV_EOD:
			rv = RV_OK;
			goto applynondirdump_out;
		case RV_CORRUPT:
			rval = (*dop->do_next_mark)(drivep);
			if (rval) {
				mlog(MLOG_NORMAL | MLOG_WARNING, _(
				      "unable to resync media file: "
				      "some portion of dump will NOT "
				      "be restored\n"));
				rv = RV_OK;  /* treat as EOD */
				goto applynondirdump_out;
			}
			resyncpr = BOOL_TRUE;
			break;
		default:
			goto applynondirdump_out;
		}

		/* update stats if appropriate
		 */
		if (((bstatp->bs_mode & S_IFMT) == S_IFREG)
		     &&
		     !(fhdrp->fh_flags & FILEHDR_FLAGS_EXTATTR)
		     &&
		     fhdrp->fh_offset == 0) {
			egrp_t cur_egrp;
			cur_egrp.eg_ino = fhdrp->fh_stat.bs_ino;
			cur_egrp.eg_off = fhdrp->fh_offset;
			if (cur_egrp.eg_ino > first_egrp.eg_ino) {
				if (cur_egrp.eg_ino < next_egrp.eg_ino
				     ||
				     next_egrp.eg_off > 0) {
					assert(cur_egrp.eg_ino
						<=
						next_egrp.eg_ino);
					pi_update_stats(bstatp->bs_blocks
							 *
							 (off64_t)
							 bstatp->bs_blksize);
				}
			}
		}

		do {
			/* get a mark for the next read, in case we restart here
			 */
			(*dop->do_get_mark)(drivep, &drivemark);

			/* read the file header.
			 */
			rv = read_filehdr(drivep, fhdrp, fhcs);
			switch(rv) {
			case RV_OK:
				break;
			case RV_EOD:
				rv = RV_OK;
				goto applynondirdump_out;
			case RV_CORRUPT:
				rval = (*dop->do_next_mark)(drivep);
				if (rval) {
					mlog(MLOG_NORMAL | MLOG_WARNING, _(
					      "unable to resync media file: "
					      "some portion of dump will NOT "
					      "be restored\n"));
					rv = RV_OK;  /* treat as EOD */
					goto applynondirdump_out;
				}
				resyncpr = BOOL_TRUE;
			default:
				goto applynondirdump_out;
			}

			if (resyncpr && rv == RV_OK) {
				mlog(MLOG_NORMAL | MLOG_WARNING, _(
				      "resynchronization achieved at "
				      "ino %llu offset %lld\n"),
				      fhdrp->fh_stat.bs_ino,
				      fhdrp->fh_offset);
				resyncpr = BOOL_FALSE;
			}
		} while (resyncpr);

		/* checkpoint into persistent state if not a null file hdr
		 */
		if (!(fhdrp->fh_flags & FILEHDR_FLAGS_NULL)) {
			pi_checkpoint(fileh,
				       &drivemark,
				       fhdrp->fh_stat.bs_ino,
				       fhdrp->fh_offset);
		}

		/* if in a pipeline, call preemptchk() to
		 * print status reports
		 */
		if (pipeline)
		{
			mlog(MLOG_DEBUG,
				"preemptchk( )\n");
			preemptchk();
		}
	}

applynondirdump_out:

	/* We've hit the end of this media file or encountered corruption.
	 * In either case, we may not be back to complete the metadata for
	 * this file, so attempt to complete it now.
	 */
	restore_complete_reg(strctxp);

	return rv;
}

/* ARGSUSED */
static rv_t
finalize(char *path1, char *path2)
{
	bool_t ok;

	if (!tranp->t_toconlypr) {

		/* restore directory attributes
		 */
		if (!persp->s.dirattrdonepr) {;
			ok = tree_setattr(path1);
			if (!ok) {
				return RV_INTR;
			}
			persp->s.dirattrdonepr = BOOL_TRUE;
		}

		/* remove orphanage if empty
		 */
		if (!persp->s.orphdeltriedpr) {;
			ok = tree_delorph();
			if (!ok) {
				return RV_INTR;
			}
			persp->s.orphdeltriedpr = BOOL_TRUE;
		}

		/* delete the persistent ino map
		 */
		if (!persp->s.inomapdelpr) {
			inomap_del_pers(tranp->t_hkdir);
			persp->s.inomapdelpr = BOOL_TRUE;
		}
	}

	/* at this point, all session-only persistent state has been deleted.
	 * if this is a cumulative restore, just update the pers cum state and
	 * invalidate the pers session state. otherwise, invalidate the
	 * persistent state. content_complete will remove housekeeping dir.
	 */
	if (persp->a.cumpr) {
		/* following must be atomic!
		 */
		persp->a.dumpcnt++;
		uuid_copy(persp->a.lastdumpid, persp->s.dumpid);
		strcpy(persp->a.lastdumplab, persp->s.dumplab);
		persp->s.valpr = BOOL_FALSE;
	} else {
		persp->a.valpr = BOOL_FALSE;
	}
	return RV_OK;
}

static void
toconly_cleanup(void)
{
	if (!tranp) {
		return;
	}

	if (!tranp->t_toconlypr) {
		return;
	}

	if (!tranp->t_hkdir) {
		return;
	}

	if (!strlen(tranp->t_hkdir)) {
		return;
	}

	wipepersstate();
}

static void
wipepersstate(void)
{
	DIR *dirp;
	struct dirent64 *direntp;
	char pathname[MAXPATHLEN];
	dirp = opendir(tranp->t_hkdir);
	if (!dirp) {
		return;
	}

	while ((direntp = readdir64(dirp)) != 0) {
		/* REFERENCED */
		int len;
		if (!strcmp(direntp->d_name, ".")) {
			continue;
		}
		if (!strcmp(direntp->d_name, "..")) {
			continue;
		}
		len = sprintf(pathname,
			       "%s/%s",
			       tranp->t_hkdir,
			       direntp->d_name);
		assert(len > 0);
		assert(len < MAXPATHLEN);
		(void)unlink(pathname);
		closedir(dirp);
		dirp = opendir(tranp->t_hkdir);
		if (!dirp) {
			return;
		}
	}
	closedir(dirp);

	rmdir(tranp->t_hkdir);
}

/* Inv abstraction ***********************************************************/

/* attempt to validate id or label against online inventory.
 * sets pers id/label and pers idvalpr etc as side-effect (does NOT set valpr!)
 */
static bool_t
Inv_validate_cmdline(void)
{
	inv_session_t *sessp;
	bool_t ok;
	bool_t rok;

	assert(!persp->s.valpr);

	ok = BOOL_FALSE;
	sessp = 0;
	if (tranp->t_reqdumpidvalpr) {
		ok = inv_get_session_byuuid(NULL, &tranp->t_reqdumpid, &sessp);
	} else if (tranp->t_reqdumplabvalpr) {
		ok = inv_get_session_bylabel(NULL, tranp->t_reqdumplab, &sessp);
	}
	rok = BOOL_FALSE;
	if (ok && sessp) {
		uuid_t baseid;

		uuid_clear(baseid);
                askinvforbaseof(baseid, sessp);
		if (!dumpcompat(sessp->s_isresumed,
				   (ix_t)(sessp->s_level),
				   baseid,
				   BOOL_TRUE)) {
			inv_free_session(&sessp);
			return BOOL_ERROR;
		}

		mlog(MLOG_VERBOSE, _(
		      "using online session inventory\n"));
		persp->s.fullinvpr = pi_transcribe(sessp);
		if (persp->s.fullinvpr) {
			strncpyterm(persp->s.dumplab,
				     sessp->s_label,
				     sizeof(persp->s.dumplab));
			uuid_copy(persp->s.dumpid, sessp->s_sesid);
			rok = BOOL_TRUE;
		}
		inv_free_session(&sessp);
	}
	return rok;
}


/* Media abstraction *********************************************************/


static Media_t *
Media_create(ix_t thrdix)
{
	drive_t *drivep = drivepp[thrdix];
	global_hdr_t *grhdrp = drivep->d_greadhdrp;
	drive_hdr_t *drhdrp = drivep->d_readhdrp;
	media_hdr_t *mrhdrp = (media_hdr_t *)drhdrp->dh_upper;
	content_hdr_t *crhdrp = (content_hdr_t *)mrhdrp->mh_upper;
	content_inode_hdr_t *scrhdrp =
				(content_inode_hdr_t *)crhdrp->ch_specific;
	Media_t *Mediap;


	mlog(MLOG_DEBUG,
	      "Media_create\n");

	Mediap = (Media_t *)calloc(1, sizeof(Media_t));
	Mediap->M_drivep = drivep;
	Mediap->M_grhdrp = grhdrp;
	Mediap->M_drhdrp = drhdrp;
	Mediap->M_mrhdrp = mrhdrp;
	Mediap->M_crhdrp = crhdrp;
	Mediap->M_scrhdrp = scrhdrp;
	assert(POS_UNKN == 0);

	return Mediap;
}

/* these calls allow the Media users to clue Media in to fine position changes
 * within the current media file
 */
static void
Media_indir(Media_t *Mediap)
{
	mlog(MLOG_DEBUG,
	      "Media_indir\n");

	Mediap->M_pos = POS_INDIR;
}

static void
Media_atnondir(Media_t *Mediap)
{
	mlog(MLOG_DEBUG,
	      "Media_atnondir\n");

	Mediap->M_pos = POS_ATNONDIR;
}

/* supplies pertinent media files to the caller. if purpose is search,
 * returns all media files. otherwise, returns only media files with the
 * dump ID. smart enough to know that if purpose was search but is now dir,
 * current media file can be returned again. same for other transitions.
 * always traverses the media object in a forward direction, beginning with
 * current media file, wrapping around to beginning of media if necessary.
 * also supplies fresh hdr pointers and drive manager. in current
 * implementation these do not change, but will when we use new TLM. does
 * fine positioning within media file according to purpose of request.
 *
 * Note:
 * The difference between rval and rv.
 * rval is used for the drive_* functions (e.g. do_begin_read)
 * and will take on values such as DRIVE_ERROR_*.
 * However, it also set to 0 for no error and 1 for error.
 * It is defaulted to 0 for no error.
 * rv, however, is of type rv_t and is used for functions returning
 * rv_t and for the result of this function.
 * It takes on values like RV_OK, RV_EOF.
 */
static rv_t
Media_mfile_next(Media_t *Mediap,
		  purp_t purp,
		  sync_t *donesyncp,
		  dh_t  *filehp,
		  global_hdr_t **grhdrpp,
		  drive_hdr_t **drhdrpp,
		  media_hdr_t **mrhdrpp,
		  content_hdr_t **crhdrpp,
		  content_inode_hdr_t **scrhdrpp,
		  drive_t **drivepp,
		  filehdr_t *fhdrp) /*caller-supplied buf if NONDIR purp*/
{
	drive_t *drivep = Mediap->M_drivep;
	drive_ops_t *dop = drivep->d_opsp;
	global_hdr_t *grhdrp = Mediap->M_grhdrp;
	drive_hdr_t *drhdrp = Mediap->M_drhdrp;
	media_hdr_t *mrhdrp = Mediap->M_mrhdrp;
	content_hdr_t *crhdrp = Mediap->M_crhdrp;
	content_inode_hdr_t *scrhdrp = Mediap->M_scrhdrp;
	dh_t fileh;
	int rval = 0; /* no error by default */
	rv_t rv;
	bool_t ok;
	uuid_t prevmfiledumpid;

	mlog(MLOG_DEBUG | MLOG_MEDIA,
	      "Media_mfile_next: purp==%d pos==%d\n",
	      purp,
	      Mediap->M_pos);

	/* pass back hdr and drive ptrs
	 */
	*grhdrpp =  grhdrp;
	*drhdrpp =  drhdrp;
	*mrhdrpp =  mrhdrp;
	*crhdrpp =  crhdrp;
	*scrhdrpp =  scrhdrp;
	*drivepp = drivep;

	/* if ref return for pers mfile desc supplied, pre-zero
	 */
	if (filehp) {
		*filehp = DH_NULL;
	}

	/* keep a close eye on the validity of fileh
	 */
	fileh = DH_NULL;

	/* if purpose has changed, invalidate first, last, and previous indices
	 */
	if (Mediap->M_flmfixvalpr) {
		if (purp != Mediap->M_mfixpurp) {
			Mediap->M_flmfixvalpr = BOOL_FALSE;
			Mediap->M_pmfixvalpr = BOOL_FALSE;
		}
	}

	/* use a local variable to keep track of dump sessions seen on
	 * media. if not in search mode, each time we see a different
	 * dump session, log a message to keep the user informed.
	 * invalidated each time we change media or rewind.
	 */
	uuid_clear(prevmfiledumpid);

	/* if restore is complete, return indication. be sure to end read
	 * if active.
	 */
	if (purp == PURP_NONDIR
	     &&
	     pi_alldone()) {
		if (Mediap->M_pos == POS_ATHDR
		     ||
		     Mediap->M_pos == POS_INDIR
		     ||
		     Mediap->M_pos == POS_ATNONDIR) {
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			fileh = DH_NULL;
		}
		return RV_NOMORE;
	}

	/* loop searching for an acceptable media file.
	 * change media as necessary.
	 */
	for (;;) {
		bool_t emptypr; /* begin_read says drive empty */
		bool_t partofdumppr;
		bool_t hassomepr;
		bool_t resumepr;
		bool_t canseeknextpr;
		drive_mark_t chkpnt;
		bool_t fhcs;
		bag_t *bagp = NULL;
		bool_t knownholespr;
		bool_t maybeholespr;
		xfs_ino_t begino;
		xfs_ino_t endino;
		int dcaps = drivep->d_capabilities;
		dh_t objh = DH_NULL;

		emptypr = BOOL_FALSE;

		/* check if no point in going on
		 */
		if (cldmgr_stop_requested()) {
			return RV_INTR;
		}
		if (donesyncp && *donesyncp == SYNC_DONE) {
			return RV_DONE;
		}
		if (purp == PURP_NONDIR
		     &&
		     pi_alldone()) {
			return RV_NOMORE;
		}

		/* if we have a useless media object, get another one
		 */
		if (Mediap->M_pos == POS_USELESS
		     ||
		     Mediap->M_pos == POS_BLANK) {
			goto newmedia;
		}

		/* if the purpose if to search, and we already have
		 * a media file, that media file has already been
		 * searched, so set pos to cause another begin read
		 */
		if (purp == PURP_SEARCH) {
			if (Mediap->M_pos == POS_ATHDR
			     ||
			     Mediap->M_pos == POS_INDIR
			     ||
			     Mediap->M_pos == POS_ATNONDIR) {
				Mediap->M_pos = POS_UNKN;
			}
		}

		/* if already have a media file, skip the begin_read
		 */
		if (Mediap->M_pos == POS_ATHDR
		     ||
		     Mediap->M_pos == POS_INDIR
		     ||
		     Mediap->M_pos == POS_ATNONDIR) {
			goto validate;
		}

		/* see if the indices say we've seen all there is to see
		 */
		if (Mediap->M_flmfixvalpr) {
			if (Mediap->M_pos == POS_UNKN) {
				if (Mediap->M_lmfix + 1 == Mediap->M_fmfix) {
					goto newmedia;
				}
			}
			if (Mediap->M_pos == POS_END) {
				if (Mediap->M_fmfix == 0) {
					goto newmedia;
				}
				if (Mediap->M_fsfixvalpr
				     &&
				     Mediap->M_fmfix <= Mediap->M_fsfix) {
					goto newmedia;
				}
			}
		}

		/* if we are at the end, do a rewind, or get new media
		 * if rewinds not possible. this may take a while, so
		 * afterwards check for interrupt or if someone else
		 * has finished the job.
		 */
		if (Mediap->M_pos == POS_END) {
			if (!(dcaps & DRIVE_CAP_REWIND)) {
				goto newmedia;
			}
			mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
			      "rewinding\n"));
			(*drivep->d_opsp->do_rewind)(drivep);
			Mediap->M_pos = POS_UNKN;
			if (cldmgr_stop_requested()) {
				return RV_INTR;
			}
			if (donesyncp && *donesyncp == SYNC_DONE) {
				return RV_DONE;
			}
			if (purp == PURP_NONDIR
			     &&
			     pi_alldone()) {
				return RV_NOMORE;
			}
		}

		/* begin a new media file, and determine new position.
		 * bail if catastrophic. also, tell pi about EOD/EOM
		 * if appropriate.
		 */
		rval = (*drivep->d_opsp->do_begin_read)(drivep);
		switch (rval) {
		case 0:
			mlog_lock();
			mlog(MLOG_VERBOSE | MLOG_NOLOCK | MLOG_MEDIA, _(
			      "examining media file %u\n"),
			      mrhdrp->mh_mediafileix);
			mlog(MLOG_TRACE | MLOG_NOLOCK | MLOG_MEDIA,
			      "file %u in "
			      "object %u "
			      "of stream %u\n",
			      mrhdrp->mh_mediafileix,
			      mrhdrp->mh_mediaix,
			      drhdrp->dh_driveix);
			mlog(MLOG_TRACE | MLOG_NOLOCK | MLOG_MEDIA,
			      "file %u in stream, "
			      "file %u of dump %u on object\n",
			      mrhdrp->mh_dumpfileix,
			      mrhdrp->mh_dumpmediafileix,
			      mrhdrp->mh_dumpmediaix);
			mlog_unlock();

			Mediap->M_pos = POS_ATHDR;
			if (Mediap->M_flmfixvalpr) {
				Mediap->M_pmfix = Mediap->M_lmfix;
				Mediap->M_pmfixvalpr = BOOL_TRUE;
			}

			pi_note_indrive(drhdrp->dh_driveix,
					 mrhdrp->mh_mediaid);

			break;
		case DRIVE_ERROR_EOD:
			Mediap->M_pos = POS_END;
			if (Mediap->M_fsfixvalpr) {
				assert(purp != PURP_SEARCH);
				pi_hiteod(Mediap->M_fssix,
					   Mediap->M_fsoix);
			}
			break;
		case DRIVE_ERROR_EOM:
			Mediap->M_pos = POS_END;
			if (Mediap->M_fsfixvalpr) {
				assert(purp != PURP_SEARCH);
				pi_hiteom(Mediap->M_fssix,
					   Mediap->M_fsoix);
			}
			break;
		case DRIVE_ERROR_MEDIA:
/*
 * pv: 766024; tes@engr
 * The setting of emptypr, in my opinion, should only happen
 * in the case that the drive does not have a tape online.
 * This corresponds to a couple of cases in prepare_drive().
 * Otherwise, when we go to a newmedia we won't be able to eject
 * the tape when we want/need to.
 * This may need to be reviewed in the future.
 */
			emptypr = BOOL_TRUE; /* so don't try to eject */
			/* fall through */
		case DRIVE_ERROR_FOREIGN:
		case DRIVE_ERROR_FORMAT:
		case DRIVE_ERROR_VERSION:
		case DRIVE_ERROR_EOF:
			Mediap->M_pos = POS_USELESS;
			break;
		case DRIVE_ERROR_BLANK:
			Mediap->M_pos = POS_BLANK;
			break;
		case DRIVE_ERROR_CORRUPTION:
			Mediap->M_pos = POS_UNKN;
			continue;
		case DRIVE_ERROR_STOP:
			return RV_INTR;
		case DRIVE_ERROR_DEVICE:
			return RV_DRIVE;
		default:
			return RV_CORE;
		}

validate:
		/* update the positional indices
		 */
		if (Mediap->M_pos == POS_ATHDR
		     ||
		     Mediap->M_pos == POS_INDIR
		     ||
		     Mediap->M_pos == POS_ATNONDIR) {
			if (!Mediap->M_flmfixvalpr) {
				Mediap->M_fmfix = mrhdrp->mh_mediafileix;
				Mediap->M_mfixpurp = purp;
				Mediap->M_flmfixvalpr = BOOL_TRUE;
			}
			Mediap->M_lmfix = mrhdrp->mh_mediafileix;
		}

		/* check for interrupt. be sure to end_read if necessary
		 */
		if (cldmgr_stop_requested()) {
			if (Mediap->M_pos == POS_ATHDR
			     ||
			     Mediap->M_pos == POS_INDIR
			     ||
			     Mediap->M_pos == POS_ATNONDIR) {
				(*dop->do_end_read)(drivep);
				Mediap->M_pos = POS_UNKN;
				fileh = DH_NULL;
			}
			return RV_INTR;
		}

		/* check if another thread has finished job (for this purpose).
		 * don't end_read, we will be back.
		 */
		if (donesyncp && *donesyncp == SYNC_DONE) {
			return RV_DONE;
		}

		/* we may be done due to the actions of other threads.
		 * if so, return indicating so
		 */
		if (purp == PURP_NONDIR
		     &&
		     pi_alldone()) {
			return RV_NOMORE;
		}

		/* if the media object is useless, go get more
		 */
		if (Mediap->M_pos == POS_USELESS
		     ||
		     Mediap->M_pos == POS_BLANK) {
			goto newmedia;
		}

		/* if we hit the end, this is not a search, and we've
		 * seen at least one media file pertaining to the dump,
		 * ask the inventory if there is any point in examining
		 * the beginning of the object.
		 */
		if (Mediap->M_pos == POS_END
		     &&
		     purp != PURP_SEARCH
		     &&
		     Mediap->M_fsfixvalpr
		     &&
		     pi_know_no_more_on_object(purp,
						Mediap->M_fssix,
						Mediap->M_fsoix)) {
			goto newmedia;
		}

		/* if we hit the end, go back to the top, where
		 * we will decide if we should rewind or get new media.
		 */
		if (Mediap->M_pos == POS_END) {
			continue;
		}

		/* if the purpose is to search, return this media file
		 */
		if (purp == PURP_SEARCH) {
			assert(Mediap->M_pos == POS_ATHDR);
			return RV_OK;
		}

		/* see if this media file is part of the desired dump session
		 */
		partofdumppr = (bool_t)(uuid_compare(persp->s.dumpid,
						     grhdrp->gh_dumpid) == 0);
		if (!partofdumppr) {
		    char gh_string_uuid[UUID_STR_LEN + 1];
		    char inv_string_uuid[UUID_STR_LEN + 1];

		    uuid_unparse(grhdrp->gh_dumpid, gh_string_uuid);
		    uuid_unparse(persp->s.dumpid, inv_string_uuid);
		    mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
		          "inventory session uuid (%s) does not match "
		          "the media header's session uuid (%s)\n"),
			  inv_string_uuid, gh_string_uuid);
		}

		/* if media file dump id is different from the preceeding
		 * media file, print something useful at TRACE verbosity.
		 */
		if (uuid_compare(prevmfiledumpid,
				   grhdrp->gh_dumpid) != 0) {

			char string_uuid[UUID_STR_LEN + 1];

			mlog_lock();
			mlog(MLOG_TRACE | MLOG_NOLOCK | MLOG_MEDIA,
			      "dump session label: \"%s\"\n",
			      grhdrp->gh_dumplabel);

			uuid_unparse(grhdrp->gh_dumpid, string_uuid);
			mlog(MLOG_TRACE | MLOG_NOLOCK | MLOG_MEDIA,
			      "dump session id: %s\n",
			      string_uuid);
			mlog(MLOG_TRACE | MLOG_NOLOCK | MLOG_MEDIA,
			      "stream %u, object %u, file %u\n",
			      drhdrp->dh_driveix,
			      mrhdrp->mh_mediaix,
			      mrhdrp->mh_dumpmediafileix);
			mlog_unlock();
			uuid_copy(prevmfiledumpid, grhdrp->gh_dumpid);
		}

		/* if this media file is not part of the desired dump session,
		 * and a preceeding media file on this object was part of the
		 * dump, we know we have hit the end of the stream. tell the
		 * persistent inventory.
		 */
		 if (!partofdumppr
		      &&
		      Mediap->M_fsfixvalpr
		      &&
		      Mediap->M_lmfix > Mediap->M_fsfix) {
			pi_hitnextdump(Mediap->M_fssix,
					Mediap->M_fsoix,
					Mediap->M_lmfix);
		}

		/* if this media file is not part of the desired dump session,
		 * we are doing non-dir, and the preceeding media file on this
		 * object was part of the dump, we know we have hit the end of
		 * the stream. check if we are done.
		 */
		 if (!partofdumppr
		      &&
		      purp == PURP_NONDIR
		      &&
		      Mediap->M_fsfixvalpr
		      &&
		      Mediap->M_lmfix > Mediap->M_fsfix) {
			if (pi_alldone()) {
				(*dop->do_end_read)(drivep);
				Mediap->M_pos = POS_UNKN;
				fileh = DH_NULL;
				return RV_NOMORE;
			}
		}

		/* if this media file is not part of the desired dump session,
		 * and preceeding media files on this object were, decide if
		 * we need to rewind and look at the beginning of the object.
		 */
		if (!partofdumppr
		     &&
		     Mediap->M_fsfixvalpr
		     &&
		     Mediap->M_fmfix <= Mediap->M_fsfix) {
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			fileh = DH_NULL;
			if (dcaps & DRIVE_CAP_REWIND) {
				mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
				  "rewinding\n"));
				(*drivep->d_opsp->do_rewind)(drivep);
				continue;
			} else {
				goto newmedia;
			}
		}

		/* if this media file is not part of the desired dump session,
		 * and the above conditions were not met, then keep looking
		 */
		if (!partofdumppr) {
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			fileh = DH_NULL;
			continue;
		}

		/* record the index within this media object of the first
		 * media file in the dump stream
		 */
		if (!Mediap->M_fsfixvalpr) {
			Mediap->M_fsfix =
				     mrhdrp->mh_mediafileix
				     -
				     mrhdrp->mh_dumpmediafileix;
			Mediap->M_fsoix = mrhdrp->mh_mediaix;
			Mediap->M_fssix = drhdrp->dh_driveix;
			Mediap->M_fsfixvalpr = BOOL_TRUE;
		}

		/* this media file is part of the dump. add it to the
		 * persistent inventory and get a file handle.
		 */
		fileh = pi_addfile(Mediap,
				    grhdrp,
				    drhdrp,
				    mrhdrp,
				    scrhdrp,
				    drivep);

		if (fileh == DH_NULL) {
			return RV_CORE;
		}

		pi_lock();
		objh = DH2F(fileh)->f_parh;
		DH2O(objh)->o_indriveix = drivep->d_index;
		DH2O(objh)->o_indrivepr = BOOL_TRUE;
		pi_unlock();

		pi_note_underhead(objh, fileh);

		/* if purp is nondir, we may be done.
		 */
		if (purp == PURP_NONDIR && pi_alldone()) {
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			return RV_NOMORE;
		}

		/* check for a wraparound
		 */
		if (Mediap->M_flmfixvalpr) {
			if (Mediap->M_fsfixvalpr
			     &&
			     Mediap->M_fmfix <= Mediap->M_fsfix
			     &&
			     Mediap->M_lmfix < Mediap->M_fmfix) {
				(*dop->do_end_read)(drivep);
				Mediap->M_pos = POS_UNKN;
				fileh = DH_NULL;
				goto newmedia;
			}
			if (Mediap->M_pmfixvalpr
			     &&
			     Mediap->M_pmfix < Mediap->M_fmfix
			     &&
			     Mediap->M_lmfix > Mediap->M_fmfix) {
				(*dop->do_end_read)(drivep);
				Mediap->M_pos = POS_UNKN;
				fileh = DH_NULL;
				goto newmedia;
			}
		}

		/* if this media file is an inventory or a terminator,
		 * we have hit the end of the stream. don't tell the persistent
		 * inventory; it already knows because of a pi_addfile.
		 * decide if any preceeding media files are useful and if so
		 * go get them. otherwise get another media object.
		 */
		if (MEDIA_TERMINATOR_CHK(mrhdrp)
		     ||
		     scrhdrp->cih_mediafiletype
		     ==
		     CIH_MEDIAFILETYPE_INVENTORY) {
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			fileh = DH_NULL;
			if (pi_know_no_more_on_object(purp,
							Mediap->M_fssix,
							Mediap->M_fsoix)) {
				goto newmedia;
			}
			if (Mediap->M_fmfix > Mediap->M_fsfix
			     &&
			     (dcaps & DRIVE_CAP_REWIND)) {
				pi_note_underhead(objh, DH_NULL);
				mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
					"rewinding\n"));
				(*drivep->d_opsp->do_rewind)(drivep);
				continue;
			}
			goto newmedia;
		}

		/* if the purpose is dir, but this media file is not positioned
		 * at the hdr or has already been tried, get another one.
		 * use the persistent inventory to do this intelligently.
		 */
		if (purp == PURP_DIR
		     &&
		     (Mediap->M_pos != POS_ATHDR
		       ||
		       DH2F(fileh)->f_dirtriedpr)) {
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			fileh = DH_NULL;
			if (pi_know_no_more_beyond_on_object(purp,
							       Mediap->M_fssix,
							       Mediap->M_fsoix,
						mrhdrp->mh_dumpmediafileix)) {
				if (pi_know_no_more_on_object(purp,
								Mediap->M_fssix,
							    Mediap->M_fsoix)) {
					goto newmedia;
				}
				if (Mediap->M_fmfix > Mediap->M_fsfix
				     &&
				     (dcaps & DRIVE_CAP_REWIND)) {
					pi_note_underhead(objh, DH_NULL);
					mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
						"rewinding\n"));
					(*drivep->d_opsp->do_rewind)(drivep);
					continue;
				}
				goto newmedia;
			} else {
				continue;
			}
		}

		/* if the purpose is dir, give it to the caller
		 */
		if (purp == PURP_DIR) {
			assert(Mediap->M_pos == POS_ATHDR);
			if (filehp) {
				assert(fileh != DH_NULL);
				*filehp = fileh;
			}
			return RV_OK;
		}

		/* if we made it this far, the purpose is NONDIR and this
		 * is a valid media file from the desired dump session.
		 */

		/* see if this media file contains any inodes not yet restored
		 */
		assert(fileh != DH_NULL);
		pi_lock();
		assert(DH2F(fileh)->f_valpr);
		begino = DH2F(fileh)->f_curegrp.eg_ino;
		endino = pi_scanfileendino(fileh);
		hassomepr = inomap_rst_needed(begino, endino);

		/* if we have already given up on this media file or
		 * it doesn't contains anything not yet restored,
		 * or it can be skipped, move on. force the done flag on,
		 * so we don't check it again.
		 */
		if (DH2F(fileh)->f_nondirdonepr
		     ||
		     DH2F(fileh)->f_nondirskippr
		     ||
		     !hassomepr) {
			if (!DH2F(fileh)->f_nondirskippr) {
				DH2F(fileh)->f_nondirdonepr = BOOL_TRUE;
			}
			pi_unlock();
			(*dop->do_end_read)(drivep);
			Mediap->M_pos = POS_UNKN;
			fileh = DH_NULL;
			if (pi_know_no_more_beyond_on_object(purp,
							       Mediap->M_fssix,
							       Mediap->M_fsoix,
						mrhdrp->mh_dumpmediafileix)) {
				if (pi_know_no_more_on_object(purp,
								Mediap->M_fssix,
							    Mediap->M_fsoix)) {
					goto newmedia;
				}
				if (Mediap->M_fmfix > Mediap->M_fsfix
				     &&
				     (dcaps & DRIVE_CAP_REWIND)) {
					pi_note_underhead(objh, DH_NULL);
					mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
						"rewinding\n"));
					(*drivep->d_opsp->do_rewind)(drivep);
					continue;
				}
				goto newmedia;
			} else {
				continue;
			}
		}

		/* so the purpose is NONDIR and we like this media file.
		 * be sure we are positioned at the beginning of the
		 * non-dir filehdr not yet restored, and supply to caller.
		 */

		/* need to position just after the first
		 * non-dir filehdr_t not yet restored.
		 * may be a problem if we are currently positioned
		 * in the middle of the dir dump and have no
		 * checkpoint to seek to. if at beginning
		 * and no check point, can still get there
		 * by doing dummy read of dirdump.
		 */
		assert(fileh != DH_NULL);
		assert(DH2F(fileh)->f_valpr);
		resumepr = ((DH2F(fileh)->f_firstegrp.eg_ino
			       !=
			       DH2F(fileh)->f_curegrp.eg_ino)
			     ||
			     (DH2F(fileh)->f_firstegrp.eg_off
			       !=
			       DH2F(fileh)->f_curegrp.eg_off));
		chkpnt = DH2F(fileh)->f_curmark;
		pi_unlock();
		fhcs = (scrhdrp->cih_dumpattr
			 &
			 CIH_DUMPATTR_FILEHDR_CHECKSUM)
		       ?
		       BOOL_TRUE
		       :
		       BOOL_FALSE;
		canseeknextpr = dcaps & DRIVE_CAP_NEXTMARK;
		switch(Mediap->M_pos) {
		case POS_ATHDR:
		case POS_INDIR:
			if (resumepr) {
			    mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
				  "seeking past portion of media file "
				  "already restored\n"));
			    rval = (*dop->do_seek_mark)(drivep,
							    &chkpnt);
			    if (!rval) {
				    rv_t rv;
				    rv = read_filehdr(drivep,
						       fhdrp,
						       fhcs);
				    if (rv != RV_OK) {
					    rval = 1;
				    } else {
					    mlog(MLOG_TRACE | MLOG_MEDIA,
						  "positioned at unrestored "
						  "portion of media file\n");
				    }
			    }
			} else if (canseeknextpr) {
			    mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
				  "seeking past media file "
				  "directory dump\n"));
			    rval = (*dop->do_next_mark)(drivep);
			    if (!rval) {
				    rv_t rv;
				    rv = read_filehdr(drivep,
						       fhdrp,
						       fhcs);
				    if (rv != RV_OK) {
					    rval = 1;
				    } else {
					    mlog(MLOG_TRACE | MLOG_MEDIA,
						  "positioned at "
						  "media file "
						  "non-directory dump\n");
				    }
			    }
			} else if (Mediap->M_pos == POS_ATHDR) {
			    mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
				  "seeking past media file "
				  "directory dump\n"));
			    rv = eatdirdump(drivep,
					     fileh,
					     scrhdrp,
					     fhdrp);
			    if (rv != RV_OK) {
				    rval = 1;
			    } else {
				    mlog(MLOG_TRACE | MLOG_MEDIA,
					  "positioned at "
					  "media file "
					  "non-directory dump\n");
			    }
			} else {
			    rval = 1;
			}
			break;
		case POS_ATNONDIR:
			rval = 0;
			break;
		default:
		    assert(0);
		    rval = 1;
		    break;
		}

		/* if error encountered during fine positioning,
		 * mark file so we won't try it again
		 */
		if (rval) {
			DH2F(fileh)->f_nondirdonepr = BOOL_TRUE;
		} else {
			Mediap->M_pos = POS_ATNONDIR;
		}

		/* if no error during fine positioning, return.
		 */
		if (!rval) {
			if (filehp) {
				assert(fileh != DH_NULL);
				*filehp = fileh;
			}
			return RV_OK;
		}

		/* an error occurred during fine positioning. any other useful
		 * media files on this object? if so, continue; if not, get
		 * more media.
		 */
		(*dop->do_end_read)(drivep);
		Mediap->M_pos = POS_UNKN;
		fileh = DH_NULL;
		assert(purp == PURP_NONDIR);
		if (pi_know_no_more_beyond_on_object(purp,
						       Mediap->M_fssix,
						       Mediap->M_fsoix,
					mrhdrp->mh_dumpmediafileix)) {
			if (pi_know_no_more_on_object(purp,
							Mediap->M_fssix,
							Mediap->M_fsoix)) {
				goto newmedia;
			}
			if (Mediap->M_fmfix > Mediap->M_fsfix
			     &&
			     (dcaps & DRIVE_CAP_REWIND)) {
				pi_note_underhead(objh, DH_NULL);
				mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
					"rewinding\n"));
				(*drivep->d_opsp->do_rewind)(drivep);
				continue;
			}
			goto newmedia;
		} else {
			continue;
		}
		/* fall through */

newmedia:
		/* invalidate prev id, so we log a TRACE msg for first
		 * media file seen on new media
		 */
		uuid_clear(prevmfiledumpid);

		/* if we are searching and some other thread completed
		 * the search, don't pop the media unless it is useless
		 */
		if (purp == PURP_SEARCH
		     &&
		     Mediap->M_pos != POS_USELESS
		     &&
		     Mediap->M_pos != POS_BLANK
		     &&
		     donesyncp
		     &&
		     *donesyncp == SYNC_DONE) {
			return RV_DONE;
		}

		/* if media not removable, just return
		 */
		if ((*dop->do_get_device_class)(drivep)
		     ==
		     DEVICE_NONREMOVABLE)
		{
		    /* if no error has already been detected then don't log
		       a failure */
		    if (mlog_get_hint() == RV_NONE)
			mlog_exit_hint(RV_OK);
		    return RV_QUIT;
		}

		/* check for an interrupt
		 */
		if (cldmgr_stop_requested()) {
			return RV_INTR;
		}

		/* check if we are done.
		 */
		switch(purp) {
		case PURP_SEARCH:
			knownholespr = BOOL_TRUE;
			maybeholespr = BOOL_FALSE;
			bagp = 0;
			break;
		case PURP_DIR:
			knownholespr = BOOL_FALSE;
			maybeholespr = BOOL_FALSE;
			bagp = pi_neededobjs_dir_alloc(&knownholespr,
							&maybeholespr);
			break;
		case PURP_NONDIR:
			knownholespr = BOOL_FALSE;
			maybeholespr = BOOL_FALSE;
			bagp = pi_neededobjs_nondir_alloc(&knownholespr,
							   &maybeholespr,
							   BOOL_FALSE,
							   BOOL_FALSE);
			break;
		default:
			assert(0);
		}

		if (!bagp && !knownholespr && !maybeholespr) {
			/* if PURP_DIR, this may be a problem
			 */
			if (purp == PURP_NONDIR) {
				return RV_NOMORE;
			}
		}

		/* eject media if drive not already empty
		 */
		if (!emptypr) {
			int dcaps = drivep->d_capabilities;
			if (purp == PURP_SEARCH) {
				if (Mediap->M_pos == POS_USELESS) {
					mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
					      "media object not useful\n"));
				} else if (Mediap->M_pos == POS_BLANK) {
					mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
					      "media object empty\n"));
				} else {
					mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
					      "all media files examined, "
					      "none selected for restoral\n"));
				}
			}
			if (dcaps & DRIVE_CAP_EJECT) {
				(*dop->do_eject_media)(drivep);
			}
		}

		/* tell the persistent inventory this drive is now empty
		 */
		pi_driveempty(drivep->d_index);

		/* invalidate all positional descriptors
		 */
		Mediap->M_pos = POS_UNKN;
		Mediap->M_flmfixvalpr = BOOL_FALSE;
		Mediap->M_pmfixvalpr = BOOL_FALSE;
		Mediap->M_fsfixvalpr = BOOL_FALSE;
		fileh = DH_NULL;


		/* ask for a media change: supply a list of media objects
		 * which may contain useful media files
		 */
		if (dlog_allowed()) {
			/* If an alert program has been specified, run it.
			 */
			if (media_change_alert_program != NULL)
				system(media_change_alert_program);

			if (drivecnt > 1 && !stdoutpiped) {
				ix_t thrdix = drivep->d_index;
				if (bagp) {
					pi_neededobjs_free(bagp);
					bagp = 0;
				}
				assert(sistr);
				mlog(MLOG_NORMAL | MLOG_NOTE | MLOG_MEDIA, _(
				      "please change media: "
				      "type %s to confirm media change\n"),
				      sistr);
				set_mcflag(thrdix);
				while (mcflag[thrdix]) {
					sleep(2);
					if (cldmgr_stop_requested()) {
						clr_mcflag(thrdix);
						return RV_INTR;
					}
					if (purp == PURP_NONDIR
					     &&
					     pi_alldone()) {
						clr_mcflag(thrdix);
						return RV_NOMORE;
					}
				}
				ok = BOOL_TRUE;
			} else {
				ok = Media_prompt_change(drivep,
							  purp,
							  bagp,
							  knownholespr,
							  maybeholespr);
			}
		} else {
			ok = BOOL_FALSE;
		}
		if (bagp) {
			pi_neededobjs_free(bagp);
			bagp = 0;
		}
		if (cldmgr_stop_requested()) {
			return RV_INTR;
		}
		if (!ok) {
			return RV_QUIT;
		}
	}
	/* NOTREACHED */
}

/* figures out and calls if needed do_end_read().
 */
static void
Media_end(Media_t *Mediap)
{
	drive_t *drivep = Mediap->M_drivep;
	drive_ops_t *dop = drivep->d_opsp;

	mlog(MLOG_DEBUG | MLOG_MEDIA,
	      "Media_end: pos==%d\n",
	      Mediap->M_pos);

	if (Mediap->M_pos == POS_ATHDR
	     ||
	     Mediap->M_pos == POS_INDIR
	     ||
	     Mediap->M_pos == POS_ATNONDIR) {
		(*dop->do_end_read)(drivep);
		Mediap->M_pos = POS_UNKN;
	}
}

/* Persistent inventory operators *******************************************/

/* the persistent inventory is an mmap()ed file containing a hierarchical
 * representation of all the media files generated by a dump session. it
 * is useful for asking questions about how much of the dump remains to
 * be restored.
 *
 * the top of the hierarchy is a linked list of streams. each of these contains
 * a linked list of objects, which in turn each contain a linked list of files.
 * each stream descriptor also has a flag indicating the last object in the
 * stream is represented. each file descriptor contains a flag indicating the
 * last file in that object is represented. the object descriptor also contains
 * two indices; one indicating where in the dump stream the first media file
 * in that object lies, and where in the object the first media file pertaining
 * to the dump stream lies. each file descriptor describes the first extent
 * group in that media file, and the next extent group in the media file to be
 * restored. the file descriptor also contains flags indicating if an attempt
 * (successful or unsuccessful) to use the file for a directory dump, and
 * a similar flag for non-dir.
 *
 * all media files generated during the dump are represented, including
 * terminators and inventories.
 */
static void
pi_lock(void)
{
	qlock_lock(tranp->t_pilockh);
}

static void
pi_unlock(void)
{
	qlock_unlock(tranp->t_pilockh);
}

/* sets check point in media file descriptor
 */
static void
pi_checkpoint(dh_t fileh, drive_mark_t *drivemarkp, xfs_ino_t ino, off64_t off)
{
	pi_lock();
	DH2F(fileh)->f_curmark = *drivemarkp;
	DH2F(fileh)->f_curegrp.eg_ino = ino;
	DH2F(fileh)->f_curegrp.eg_off = off;
	pi_unlock();
}

/* lock must be held by caller
 */
static bool_t
pi_allocdesc(dh_t *deschp)
{
	dh_t desch;

	if (persp->s.descfreeh == DH_NULL) {
		ix_t stpgcnt = persp->a.stpgcnt;
		ix_t olddescpgcnt = persp->s.descpgcnt;
		ix_t newdescpgcnt = olddescpgcnt + DAU;
		ix_t descppg = pgsz / PERS_DESCSZ;
		ix_t descix;
		/* REFERENCED */
		int rval;

		/* first unmap if any existing descriptors
		 */
		if (descp) {
			assert(olddescpgcnt > 0);
			rval = munmap((void *)descp,
				       olddescpgcnt * pgsz);
			assert(!rval);
			descp = 0;
		} else {
			assert(olddescpgcnt == 0);
		}

		/* remap with DAU more pages of descriptors
		 */
		assert(stpgcnt <= (ix_t)INTGENMAX);
		assert(newdescpgcnt > 0);
		descp = (pers_desc_t *) mmap_autogrow(newdescpgcnt * pgsz,
						tranp->t_persfd,
						(off_t)perssz
						+
						(off_t)(stpgcnt * pgsz));
		if (descp == (pers_desc_t *)(-1)) {
			pi_unlock();
			mlog(MLOG_NORMAL | MLOG_ERROR | MLOG_MEDIA, _(
			      "could not remap persistent state file "
			      "inv %s: %d (%s)\n"),
			      perspath,
			      errno,
			      strerror(errno));
			pi_lock();
			descp = 0;
			return BOOL_FALSE;
		}
		persp->s.descfreeh = (dh_t)(olddescpgcnt * pgsz + 1);
		for (descix = 0, desch = persp->s.descfreeh
		      ;
		      descix < (DAU * descppg) - 1
		      ;
		      descix++, desch += PERS_DESCSZ) {
			DH2D(desch)->d_nexth = desch + PERS_DESCSZ;
		}
		DH2D(desch)->d_nexth = DH_NULL;
		persp->s.descpgcnt = newdescpgcnt;
	}

	desch = persp->s.descfreeh;
	persp->s.descfreeh = DH2D(desch)->d_nexth;
	memset((void *)DH2D(desch), 0, sizeof(pers_desc_t));
	assert(desch != DH_NULL);
	*deschp = desch;
	return BOOL_TRUE;
}

/* inserts the indexed file into the given stream. ensures that all
 * previous files are represented as well. if dmfix is not valid, only
 * adds objects.
 */
static dh_t
pi_insertfile(ix_t drivecnt,
	       ix_t driveix,
	       ix_t mediaix,
	       bool_t idlabvalpr,
	       uuid_t *mediaidp,
	       label_t medialabel,
	       bool_t previdlabvalpr,
	       uuid_t *prevmediaidp,
	       label_t prevmedialabel,
	       bool_t mfixvalpr,
	       ix_t mediafileix,
	       bool_t dmfixvalpr,
	       ix_t dumpmediafileix,
	       bool_t dfixvalpr,
	       ix_t dumpfileix,
	       bool_t egrpvalpr,
	       xfs_ino_t startino,
	       off64_t startoffset,
	       int flags,
	       bool_t fileszvalpr,
	       off64_t filesz)
{
	ix_t strmix;
	dh_t strmh;
	ix_t objix;
	dh_t objh;
	dh_t prevobjh;
	ix_t fileix;
	dh_t fileh;
	dh_t prevfileh;
	bool_t ok;

	pi_lock();

	/* first alloc stream descriptors if needed
	 */
	if (persp->s.strmheadh == DH_NULL) {
		for (strmix = 0; strmix < drivecnt; strmix++) {
			ok = pi_allocdesc(&strmh);
			if (!ok) {
				pi_unlock();
				return DH_NULL;
			}
			DH2S(strmh)->s_nexth = persp->s.strmheadh;
			persp->s.strmheadh = strmh;
		}
	}

	/* get handle to this stream
	 */
	for (strmix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmix < driveix
	      ;
	      strmix++,
	      strmh = DH2S(strmh)->s_nexth)
		;
	assert(strmh != DH_NULL);

	/* get handle to this object by walking/constructing this stream's
	 * object list, up to the desired object
	 */
	objh = prevobjh = DH_NULL;
	for (objix = 0; objix <= mediaix; objix++) {
		prevobjh = objh;
		if (objix == 0) {
			objh = DH2S(strmh)->s_cldh;
		} else {
			objh = DH2O(prevobjh)->o_nexth;
		}
		if (objh == DH_NULL) {
			ok = pi_allocdesc(&objh);
			if (!ok) {
				pi_unlock();
				return DH_NULL;
			}
			DH2O(objh)->o_parh = strmh;
			if (objix == 0) {
				DH2S(strmh)->s_cldh = objh;
			} else {
				DH2O(prevobjh)->o_nexth = objh;
			}
		}
	}

	/* update the object fields if not yet valid
	 */
	if (idlabvalpr
	     &&
	     ! DH2O(objh)->o_idlabvalpr) {
		uuid_copy(DH2O(objh)->o_id, *mediaidp);
		strncpy(DH2O(objh)->o_lab,
			 medialabel,
			 sizeof(DH2O(objh)->o_lab));
		DH2O(objh)->o_idlabvalpr = BOOL_TRUE;
	}
	if (mfixvalpr
	     &&
	     dmfixvalpr
	     &&
	     ! DH2O(objh)->o_fmfmixvalpr) {
		DH2O(objh)->o_fmfmix = mediafileix - dumpmediafileix;
		DH2O(objh)->o_fmfmixvalpr = BOOL_TRUE;
	}
	if (dfixvalpr
	     &&
	     dmfixvalpr
	     &&
	     ! DH2O(objh)->o_fmfsixvalpr) {
		DH2O(objh)->o_fmfsix = dumpfileix - dumpmediafileix;
		DH2O(objh)->o_fmfsixvalpr = BOOL_TRUE;
	}

	/* record the previous object's id and label if not yet valid
	 */
	if (prevobjh != DH_NULL
	     &&
	     previdlabvalpr
	     &&
	     ! DH2O(prevobjh)->o_idlabvalpr) {
		uuid_copy(DH2O(prevobjh)->o_id, *prevmediaidp);
		strncpy(DH2O(prevobjh)->o_lab,
			       prevmedialabel,
			       sizeof(DH2O(prevobjh)->o_lab));
		DH2O(prevobjh)->o_idlabvalpr = BOOL_TRUE;
	}

	/* if the dump file and dump media file indices are valid,
	 * and the previous object has at least one media file with its
	 * dump file index valid, can infer the index of the last media
	 * file on the previous dump object.
	 */
	if (DH2O(objh)->o_fmfsixvalpr
	     &&
	     prevobjh != DH_NULL
	     &&
	     DH2O(prevobjh)->o_fmfsixvalpr
	     &&
	     ! DH2O(prevobjh)->o_lmfknwnpr) {
		size_t prevmfcnt;
		assert(DH2O(objh)->o_fmfsix > DH2O(prevobjh)->o_fmfsix);
		prevmfcnt = DH2O(objh)->o_fmfsix - DH2O(prevobjh)->o_fmfsix;
		pi_unlock();
		assert(mediaix > 0);
		(void)pi_insertfile(drivecnt,
				       driveix,
				       mediaix - 1,
				       BOOL_FALSE,
				       0,
				       0,
				       BOOL_FALSE,
				       0,
				       0,
				       BOOL_FALSE,
				       0,
				       BOOL_TRUE,
				       prevmfcnt - 1,
				       BOOL_TRUE,
				       DH2O(objh)->o_fmfsix - 1,
				       0,
				       0,
				       0,
				       0,
				       BOOL_FALSE,
				       (off64_t)0);
		pi_seeobjstrmend(strmix, mediaix - 1);
		pi_lock();
	}

	/* if don't know dump stream media file index, can't add any media files
	 */
	if (!dmfixvalpr) {
		pi_unlock();
		pi_show(" after pi_insertfile no media file ix");
		return DH_NULL;
	}

	/* get handle to this file by walking/constructing this object's
	 * file list, up to the desired file
	 */
	fileh = DH_NULL;
	for (fileix = 0; fileix <= dumpmediafileix; fileix++) {
		prevfileh = fileh;
		if (fileix == 0) {
			fileh = DH2O(objh)->o_cldh;
		} else {
			fileh = DH2F(prevfileh)->f_nexth;
		}
		if (fileh == DH_NULL) {
			ok = pi_allocdesc(&fileh);
			if (!ok) {
				pi_unlock();
				return DH_NULL;
			}
			DH2F(fileh)->f_parh = objh;
			if (fileix == 0) {
				DH2O(objh)->o_cldh = fileh;
			} else {
				DH2F(prevfileh)->f_nexth = fileh;
			}
		}
	}

	/* update the media file fields not yet valid
	 */
	if (egrpvalpr && !DH2F(fileh)->f_valpr) {
		assert(!(DH2F(fileh)->f_flags & PF_INV));
		assert(!(DH2F(fileh)->f_flags & PF_TERM));
		DH2F(fileh)->f_firstegrp.eg_ino = startino;
		DH2F(fileh)->f_firstegrp.eg_off = startoffset;
		DH2F(fileh)->f_curegrp = DH2F(fileh)->f_firstegrp;
		DH2F(fileh)->f_valpr = BOOL_TRUE;
	}

	/* set flags
	 */
	DH2F(fileh)->f_flags = flags;

	/* if we know the file size,
	 * update it
	 */
	if (fileszvalpr) {
		DH2F(fileh)->f_sz = filesz;
		DH2F(fileh)->f_szvalpr = BOOL_TRUE;
	}

	pi_unlock();
	pi_show(" after pi_insertfile");
	return fileh;
}

/* add pers file desc if not already present. will automatically
 * update/alloc pers obj and strm descriptors. If given a session inventory,
 * attempt to incorporate into pi. also, initializes completion stats.
 */
/* ARGSUSED */
static dh_t
pi_addfile(Media_t *Mediap,
	    global_hdr_t *grhdrp,
	    drive_hdr_t *drhdrp,
	    media_hdr_t *mrhdrp,
	    content_inode_hdr_t *scrhdrp,
	    drive_t * drivep)
{
	dh_t fileh;

	if (!persp->s.stat_valpr) {
		persp->s.stat_inocnt = scrhdrp->cih_inomap_nondircnt;
		persp->s.stat_inodone = 0;
		assert(scrhdrp->cih_inomap_datasz <= OFF64MAX);
		persp->s.stat_datacnt = (off64_t)scrhdrp->cih_inomap_datasz;
		persp->s.stat_datadone = 0;
		persp->s.stat_valpr = BOOL_TRUE;
	}

	/* if we see a terminator, we know we have seen the end of
	 * a stream.
	 */
	if (MEDIA_TERMINATOR_CHK(mrhdrp)) {
		fileh = pi_insertfile(drhdrp->dh_drivecnt,
				       drhdrp->dh_driveix,
				       mrhdrp->mh_mediaix,
				       BOOL_TRUE,
				       &mrhdrp->mh_mediaid,
				       mrhdrp->mh_medialabel,
				       BOOL_TRUE,
				       &mrhdrp->mh_prevmediaid,
				       mrhdrp->mh_prevmedialabel,
				       BOOL_TRUE,
				       mrhdrp->mh_mediafileix,
				       BOOL_TRUE,
				       mrhdrp->mh_dumpmediafileix,
				       BOOL_TRUE,
				       mrhdrp->mh_dumpfileix,
				       BOOL_FALSE,
				       (xfs_ino_t)0,
				       (off64_t)0,
				       PF_TERM,
				       BOOL_FALSE,
				       (off64_t)0);
		if (fileh == DH_NULL) {
			return DH_NULL;
		}
		pi_seestrmend(drhdrp->dh_driveix);
		pi_seeobjstrmend(drhdrp->dh_driveix, mrhdrp->mh_mediaix);
		return fileh;
	}

	/* data file
	 */
	if (scrhdrp->cih_mediafiletype == CIH_MEDIAFILETYPE_DATA) {
		/* tell the inventory about this media file
		 */
		fileh = pi_insertfile(drhdrp->dh_drivecnt,
				       drhdrp->dh_driveix,
				       mrhdrp->mh_mediaix,
				       BOOL_TRUE,
				       &mrhdrp->mh_mediaid,
				       mrhdrp->mh_medialabel,
				       BOOL_TRUE,
				       &mrhdrp->mh_prevmediaid,
				       mrhdrp->mh_prevmedialabel,
				       BOOL_TRUE,
				       mrhdrp->mh_mediafileix,
				       BOOL_TRUE,
				       mrhdrp->mh_dumpmediafileix,
				       BOOL_TRUE,
				       mrhdrp->mh_dumpfileix,
				       BOOL_TRUE,
				       scrhdrp->cih_startpt.sp_ino,
				       scrhdrp->cih_startpt.sp_offset,
				       0,
				       BOOL_FALSE,
				       (off64_t)0);
		if (fileh == DH_NULL) {
			return DH_NULL;
		}
		assert(drhdrp->dh_drivecnt > 0);
		if (drhdrp->dh_driveix < drhdrp->dh_drivecnt - 1) {
			/* if this is not in the last stream, we know
			 * there is at least one other media file in
			 * the following stream, and we know its start pt
			 */
			(void)pi_insertfile(drhdrp->dh_drivecnt,
					       drhdrp->dh_driveix + 1,
					       0,
					       BOOL_FALSE,
					       0,
					       0,
					       BOOL_FALSE,
					       0,
					       0,
					       BOOL_FALSE,
					       0,
					       BOOL_TRUE,
					       0,
					       BOOL_FALSE,
					       0,
					       BOOL_TRUE,
					       scrhdrp->cih_endpt.sp_ino,
					       scrhdrp->cih_endpt.sp_offset,
					       0,
					       BOOL_FALSE,
					       (off64_t)0);
		}
		if (!(drivep->d_capabilities & DRIVE_CAP_FILES)) {
			/* if drive does not support multiple files,
			 * we know this is end of object and stream
			 */
			pi_seestrmend(drhdrp->dh_driveix);
			pi_seeobjstrmend(drhdrp->dh_driveix, mrhdrp->mh_mediaix);
		}

		return fileh;
	}

	/* inventory file
	 */
	if (scrhdrp->cih_mediafiletype == CIH_MEDIAFILETYPE_INVENTORY) {
		fileh = pi_insertfile(drhdrp->dh_drivecnt,
				       drhdrp->dh_driveix,
				       mrhdrp->mh_mediaix,
				       BOOL_TRUE,
				       &mrhdrp->mh_mediaid,
				       mrhdrp->mh_medialabel,
				       BOOL_TRUE,
				       &mrhdrp->mh_prevmediaid,
				       mrhdrp->mh_prevmedialabel,
				       BOOL_TRUE,
				       mrhdrp->mh_mediafileix,
				       BOOL_TRUE,
				       mrhdrp->mh_dumpmediafileix,
				       BOOL_TRUE,
				       mrhdrp->mh_dumpfileix,
				       BOOL_FALSE,
				       (xfs_ino_t)0,
				       (off64_t)0,
					PF_INV,
					BOOL_FALSE,
					(off64_t)0);
		if (fileh == DH_NULL) {
			return DH_NULL;
		}
		pi_seestrmend(drhdrp->dh_driveix);
		pi_seeobjstrmend(drhdrp->dh_driveix,
				  mrhdrp->mh_mediaix);
		if (drhdrp->dh_driveix < drhdrp->dh_drivecnt - 1) {
			(void)pi_insertfile(drhdrp->dh_drivecnt,
					       drhdrp->dh_driveix + 1,
					       0,
					       BOOL_FALSE,
					       0,
					       0,
					       BOOL_FALSE,
					       0,
					       0,
					       BOOL_FALSE,
					       0,
					       BOOL_TRUE,
					       0,
					       BOOL_FALSE,
					       0,
					       BOOL_TRUE,
					       scrhdrp->cih_endpt.sp_ino,
					       scrhdrp->cih_endpt.sp_offset,
					       0,
					       BOOL_FALSE,
					       (off64_t)0);
		}
		if (!persp->s.fullinvpr
		     &&
		     Mediap->M_pos == POS_ATHDR) {
			size_t bufszincr;
			size_t bufsz;
			size_t buflen;
			char *bufp;
			inv_session_t *sessp;
			invt_sessinfo_t   sessinfo;
			bool_t ok;
			bool_t donepr;

			/* read inventory into buffer
			 */
			bufszincr = IBPGINCR * PGSZ;
				/* use 4096, no need to be correlated
				 * with system page size
				 */
			bufsz = bufszincr;
			buflen = 0;
			bufp = (char *)malloc(bufsz);

			/* need to read until we hit EOF/EOD. that's the only
			 * way to know how big the inventory is. mark the Media
			 * current media file as no longer at hdr.
			 */
			Mediap->M_pos = POS_ATNONDIR;
			donepr = BOOL_FALSE;
			while (!donepr) {
				int nread;
				drive_ops_t *dop = drivep->d_opsp;
				int rval = 0;
				nread = read_buf(bufp + buflen,
						  bufszincr,
						  (void *)drivep,
						  (rfp_t)dop->do_read,
					    (rrbfp_t)dop->do_return_read_buf,
						  &rval);
				switch(rval) {
				case 0:
					assert(nread == (int)bufszincr);
					buflen += (size_t)nread;
					bufsz += bufszincr;
					bufp = (char *)realloc((void *)bufp,
								 bufsz);
					assert(bufp);
					continue;
				case DRIVE_ERROR_EOD:
				case DRIVE_ERROR_EOF:
					buflen += (size_t)nread;
					donepr = BOOL_TRUE;
					break;
				default:
					free((void *)bufp);
					return fileh;
				}
			}

			/* ask inventory to convert buffer into session
			 * desc.
			 */
			sessp = 0;
			if (!buflen) {
				ok = BOOL_FALSE;
			} else {
			    /* extract the session information from the buffer */
			    if (stobj_unpack_sessinfo(bufp, buflen, &sessinfo)<0) {
				ok = BOOL_FALSE;
			    } else {
				stobj_convert_sessinfo(&sessp, &sessinfo);
				ok = BOOL_TRUE;
			    }
			}
			if (!ok || !sessp) {
				mlog(MLOG_DEBUG | MLOG_WARNING | MLOG_MEDIA, _(
				      "on-media session "
				      "inventory corrupt\n"));
			} else {
				/* if root, update online inventory.
				 */
				if (!geteuid()
				     &&
				     !tranp->t_noinvupdatepr) {
					mlog(MLOG_VERBOSE | MLOG_MEDIA, _(
					      "incorporating on-media session "
					      "inventory into online "
					      "inventory\n"));
					inv_put_sessioninfo(&sessinfo);
				}

				/* convert into pi format
				 */
				mlog(MLOG_VERBOSE | MLOG_MEDIA,
				      "using on-media session inventory\n");
				persp->s.fullinvpr = pi_transcribe(sessp);
				inv_free_session(&sessp);
			}
			free((void *)bufp);
		}
		return fileh;
	}

	assert(0);
	return DH_NULL;
}

/* translate a session inventory into a pi
 */
static bool_t
pi_transcribe(inv_session_t *sessp)
{
	ix_t strmcnt;
	ix_t strmix;

	/* traverse inventory, transcribing into pers inv.
	 */
	strmcnt =  (size_t)sessp->s_nstreams;
	for (strmix = 0; strmix < strmcnt; strmix++) {
		inv_stream_t *strmp;
		size_t fileix;
		size_t filecnt;
		uuid_t lastobjid;
		label_t lastobjlabel;
		ix_t mediaix;
		size_t dumpmediafileix;

		strmp = &sessp->s_streams[strmix];
		filecnt = strmp->st_nmediafiles;
                uuid_clear(lastobjid);
		lastobjlabel[0] = 0;
		mediaix = 0;
		dumpmediafileix = 0;

		/* insert all media files from this stream. note that
		 * the media object representation is inverted
		 */
		for (fileix = 0; fileix < filecnt; fileix++) {
			inv_mediafile_t *filep;
			bool_t fileszvalpr;

			filep = &strmp->st_mediafiles[fileix];
			if (uuid_compare(filep->m_moid,
					   lastobjid) != 0) {
				dumpmediafileix = 0;
				if (fileix != 0) {
					pi_seeobjstrmend(strmix, mediaix);
					mediaix++;
				}
			}

			fileszvalpr = BOOL_TRUE;

			(void)pi_insertfile(strmcnt,
					       strmix,
					       mediaix,
					       BOOL_TRUE,
					       &filep->m_moid,
					       filep->m_label,
					       BOOL_TRUE,
					       &lastobjid,
					       lastobjlabel,
					       BOOL_TRUE,
					       filep->m_mfile_index,
					       BOOL_TRUE,
					       dumpmediafileix,
					       BOOL_TRUE,
					       fileix,
					       filep->m_isinvdump
					       ?
					       BOOL_FALSE
					       :
					       BOOL_TRUE,
					       filep->m_startino,
					       filep->m_startino_off,
					       filep->m_isinvdump
					       ?
					       PF_INV
					       :
					       0,
					       fileszvalpr,
					       filep->m_size);
			uuid_copy(lastobjid, filep->m_moid);
			strncpy(lastobjlabel,
				 filep->m_label,
				 sizeof(lastobjlabel));
			dumpmediafileix++;
		}
		pi_seestrmend(strmix);
		pi_seeobjstrmend(strmix, mediaix);
	}

	return BOOL_TRUE;
}

/* clean up pers. inv: initially no media objects in drives. flags may
 * be set from previously interrupted invocation.
 */
static void
pi_preclean(void)
{
	dh_t strmh;
	dh_t objh;
	dh_t fileh;

	for (strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL
	      ;
	      strmh = DH2S(strmh)->s_nexth) {
		for (objh = DH2S(strmh)->s_cldh
		      ;
		      objh != DH_NULL
		      ;
		      objh = DH2O(objh)->o_nexth) {
			DH2O(objh)->o_indrivepr = BOOL_FALSE;
			for (fileh = DH2O(objh)->o_cldh
			      ;
			      fileh != DH_NULL
			      ;
			      fileh = DH2F(fileh)->f_nexth) {
				DH2F(fileh)->f_underheadpr = BOOL_FALSE;
			}
		}
	}
}

/* tell pi no media objects are in this drive
 */
static void
pi_driveempty(ix_t driveix)
{
	dh_t strmh;
	dh_t objh;
	dh_t fileh;

	pi_lock();

	for (strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL
	      ;
	      strmh = DH2S(strmh)->s_nexth) {
		for (objh = DH2S(strmh)->s_cldh
		      ;
		      objh != DH_NULL
		      ;
		      objh = DH2O(objh)->o_nexth) {
			if (DH2O(objh)->o_indrivepr
			     &&
			     DH2O(objh)->o_indriveix == driveix) {
				DH2O(objh)->o_indrivepr = BOOL_FALSE;
				for (fileh = DH2O(objh)->o_cldh
				      ;
				      fileh != DH_NULL
				      ;
				      fileh = DH2F(fileh)->f_nexth) {
					DH2F(fileh)->f_underheadpr =
								    BOOL_FALSE;
				}
			}
		}
	}

	pi_unlock();
}

/* tell pi this media object is in the drive
 */
static void
pi_note_indrive(ix_t driveix, uuid_t media_id)
{
	dh_t strmh;
	dh_t objh;

	pi_lock();

	for (strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL
	      ;
	      strmh = DH2S(strmh)->s_nexth) {
		for (objh = DH2S(strmh)->s_cldh
		      ;
		      objh != DH_NULL
		      ;
		      objh = DH2O(objh)->o_nexth) {
			if (DH2O(objh)->o_idlabvalpr
			     &&
			     uuid_compare(DH2O(objh)->o_id, media_id) == 0) {
				DH2O(objh)->o_indrivepr = BOOL_TRUE;
				DH2O(objh)->o_indriveix = driveix;
				goto done;
			}
		}
	}

done:
	pi_unlock();
}

/* tell pi this media file is under the head of the drive containing the object
 */
static void
pi_note_underhead(dh_t thisobjh, dh_t thisfileh)
{
	dh_t fileh;

	if (thisobjh == DH_NULL) {
		return;
	}

	pi_lock();

	if (thisfileh != DH_NULL) {
		DH2F(thisfileh)->f_underheadpr = BOOL_TRUE;
	}

	for (fileh = DH2O(thisobjh)->o_cldh
	      ;
	      fileh != DH_NULL
	      ;
	      fileh = DH2F(fileh)->f_nexth) {
		if (fileh != thisfileh) {
			DH2F(fileh)->f_underheadpr = BOOL_FALSE;
		}
	}

	pi_unlock();
}

/* mark the pi stream indicating all objects in that stream are known.
 */
static void
pi_seestrmend(ix_t strmix)
{
	ix_t ix;
	dh_t strmh;

	pi_lock();

	/* get handle to the indexed stream
	 */
	for (ix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL && ix < strmix
	      ;
	      ix++,
	      strmh = DH2S(strmh)->s_nexth)
		;

	/* if an empty stream (can happen when dump interrupted),
	 * nothing need be done, so return
	 */
	if (strmh == DH_NULL) {
		pi_unlock();
		return;
	}

	/* set stream flag and object and file counts
	 */
	DH2S(strmh)->s_lastobjknwnpr = BOOL_TRUE;

	pi_unlock();
	pi_show(" after pi_seestrmend");
}

/* mark pi indicating all media files in object are known
 */
static void
pi_seeobjstrmend(ix_t strmix, ix_t mediaix)
{
	ix_t ix;
	dh_t strmh;
	dh_t objh;

	pi_lock();

	/* get handle to the indexed stream
	 */
	for (ix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL && ix < strmix
	      ;
	      ix++,
	      strmh = DH2S(strmh)->s_nexth)
		;

	/* if an empty stream (can happen when dump interrupted),
	 * nothing need be done, so return
	 */
	if (strmh == DH_NULL) {
		pi_unlock();
		return;
	}


	/* get handle to indexed object in stream
	 */
	for (ix = 0,
	      objh = DH2S(strmh)->s_cldh
	      ;
	      objh != DH_NULL && ix < mediaix
	      ;
	      ix++,
	      objh = DH2O(objh)->o_nexth)
		;

	/* if an empty object (can happen when dump interrupted),
	 * nothing need be done, so return
	 */
	if (objh == DH_NULL) {
		pi_unlock();
		return;
	}


	/* set object flag
	 */
	DH2O(objh)->o_lmfknwnpr = BOOL_TRUE;

	pi_unlock();
	pi_show(" after pi_seeobjstrmend");
}

/* scans pi to determine ino of last file wholly or partially contained on
 * this mfile. must err on the high side if partial info.
 * NOTE: assumes caller locks pi!
 */
static xfs_ino_t
pi_scanfileendino(dh_t fileh)
{
	dh_t strmh;
	ix_t mode = 0;

	assert(fileh != DH_NULL);

	/* traverse the pi tree, looking for the next media file after
	 */
	for (strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL
	      ;
	      strmh = DH2S(strmh)->s_nexth) {
	    dh_t objh;

	    for (objh = DH2S(strmh)->s_cldh
		  ;
		  objh != DH_NULL
		  ;
		  objh = DH2O(objh)->o_nexth) {
		dh_t nexth;

		for (nexth = DH2O(objh)->o_cldh
		      ;
		      nexth != DH_NULL
		      ;
		      nexth = DH2F(nexth)->f_nexth) {

		    switch(mode) {
		    case 0:
			if (nexth == fileh) {
				mode = 1;
			}
			break;
		    default:
			if (DH2F(nexth)->f_valpr) {
			    xfs_ino_t ino;

			    assert(!(DH2F(nexth)->f_flags & PF_INV));
			    assert(!(DH2F(nexth)->f_flags & PF_TERM));
			    if (DH2F(nexth)->f_firstegrp.eg_off) {
				ino =  DH2F(nexth)->f_firstegrp.eg_ino;
				return ino;
			    } else {
				assert(DH2F(nexth)->f_firstegrp.eg_ino > 0);
				ino =  DH2F(nexth)->f_firstegrp.eg_ino - 1;
				return ino;
			    }
			}
			break;
		    }
		}
	    }
	}
	return INO64MAX;
}

/* used to detemine range of extent groups still to be restored
 * from media file. *--o
 */
static void
pi_bracketneededegrps(dh_t thisfileh, egrp_t *first_egrp, egrp_t *next_egrp)
{
	dh_t strmh;
	bool_t thisfoundpr = BOOL_FALSE;
	dh_t prech = DH_NULL;
	dh_t follh = DH_NULL;


	assert(thisfileh != DH_NULL);

	/* traverse the pi tree, looking for fileh
	 */
	pi_lock();
	assert(DH2F(thisfileh)->f_valpr);

	for (strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL
	      ;
	      strmh = DH2S(strmh)->s_nexth) {
	    dh_t objh;

	    for (objh = DH2S(strmh)->s_cldh
		  ;
		  objh != DH_NULL
		  ;
		  objh = DH2O(objh)->o_nexth) {
		dh_t fileh;

		for (fileh = DH2O(objh)->o_cldh
		      ;
		      fileh != DH_NULL
		      ;
		      fileh = DH2F(fileh)->f_nexth) {
		    if (!thisfoundpr) {
			if (fileh == thisfileh) {
			    thisfoundpr = BOOL_TRUE;
			} else if (DH2F(fileh)->f_valpr) {
			    assert(!(DH2F(fileh)->f_flags & PF_INV));
			    assert(!(DH2F(fileh)->f_flags & PF_TERM));
			    prech = fileh;
			}
		    } else if (DH2F(fileh)->f_valpr) {
			assert(!(DH2F(fileh)->f_flags & PF_INV));
			assert(!(DH2F(fileh)->f_flags & PF_TERM));
			assert(follh == DH_NULL);
			follh = fileh;
			goto done;
		    }
		}
	    }
	}
done:

	assert(thisfoundpr);

	/* initially the lower bracket is this file descriptor's
	 * current egrp. this catches the case where a previous restore
	 * session was interrupted while restoring this media file.
	 */
	*first_egrp = DH2F(thisfileh)->f_curegrp;

	/* if the closest valid preceeding media file's current egrp is
	 * greater, use it as the lower bracket
	 */
	if (prech != DH_NULL
	     &&
	     egrpcmp(&DH2F(prech)->f_curegrp, first_egrp) > 0) {
		*first_egrp = DH2F(prech)->f_curegrp;
	}

	/* the upper bracket is initially the end of the world.
	 * if we found a valid following file descriptor describing a
	 * media file which has already been at least restored, use
	 * its first egrp as an upper bracket.
	 */
	next_egrp->eg_ino = INO64MAX;
	next_egrp->eg_off = OFF64MAX;
	if (follh != DH_NULL
	     &&
	     egrpcmp(&DH2F(follh)->f_curegrp, &DH2F(follh)->f_firstegrp)
	     >
	     0) {
		*next_egrp = DH2F(follh)->f_firstegrp;
	}

	pi_unlock();
}

static void
pi_update_stats(off64_t sz)
{
	pi_lock();
	assert(persp->s.stat_valpr);
	persp->s.stat_inodone++;
	persp->s.stat_datadone += sz;
	pi_unlock();
}

/* pi_iterator - each invocation of the iterator advances to the next media file
 * in the dump session, walking the media file hierarchy depth-wise. if
 * an object's file list is exhausted and the first media file in the next
 * object is returned and the exhausted object's last media file has not yet
 * been identified, the return-by-ref flag filemissingpr is set. similarly for
 * streams, objmissingpr.
 * NOTE: does not preset missingpr's to FALSE.
 * NOTE: caller must lock pi.
 */

struct pi_iter {
	bool_t initializedpr;
	dh_t strmh;
	dh_t objh;
	dh_t fileh;
	bool_t donepr;
};

typedef struct pi_iter pi_iter_t;

static pi_iter_t *
pi_iter_alloc(void)
{
	pi_iter_t *iterp;

	iterp = (pi_iter_t *)calloc(1, sizeof(pi_iter_t));
	assert(iterp);
	return iterp;
}

static void
pi_iter_free(pi_iter_t *iterp)
{
	free((void *)iterp);
}

static dh_t
pi_iter_nextfileh(pi_iter_t *iterp,
		   bool_t *objmissingprp,
		   bool_t *filemissingprp)
{
	assert(!iterp->donepr);

	if (persp->s.strmheadh == DH_NULL) {
		iterp->donepr = BOOL_TRUE;
		return DH_NULL;
	}

	if (!iterp->initializedpr) {
		assert(persp->s.strmheadh != DH_NULL);
		iterp->strmh = persp->s.strmheadh;
		iterp->objh = DH2S(iterp->strmh)->s_cldh;
		if (iterp->objh == DH_NULL) {
			if (!DH2S(iterp->strmh)->s_lastobjknwnpr) {
				*objmissingprp = BOOL_TRUE;
			}
		} else {
			iterp->fileh = DH2O(iterp->objh)->o_cldh;
			if (iterp->fileh == DH_NULL) {
				if (!DH2O(iterp->objh)->o_lmfknwnpr) {
					*filemissingprp = BOOL_TRUE;
				}
			}
		}

		while (iterp->fileh == DH_NULL) {
			while (iterp->objh == DH_NULL) {
				if (!DH2S(iterp->strmh)->s_lastobjknwnpr) {
					*objmissingprp = BOOL_TRUE;
				}
				iterp->strmh = DH2S(iterp->strmh)->s_nexth;
				if (iterp->strmh == DH_NULL) {
					iterp->donepr = BOOL_TRUE;
					return DH_NULL;
				}
				iterp->objh = DH2S(iterp->strmh)->s_cldh;
			}
			iterp->fileh = DH2O(iterp->objh)->o_cldh;
			if (iterp->fileh == DH_NULL) {
				if (!DH2O(iterp->objh)->o_lmfknwnpr) {
					*filemissingprp = BOOL_TRUE;
				}
				iterp->objh = DH2O(iterp->objh)->o_nexth;
			}
		}
		iterp->initializedpr = BOOL_TRUE;
		return iterp->fileh;
	}

	iterp->fileh = DH2F(iterp->fileh)->f_nexth;
	while (iterp->fileh == DH_NULL) {
		if (!DH2O(iterp->objh)->o_lmfknwnpr) {
			*filemissingprp = BOOL_TRUE;
		}
		iterp->objh = DH2O(iterp->objh)->o_nexth;
		while (iterp->objh == DH_NULL) {
			if (!DH2S(iterp->strmh)->s_lastobjknwnpr) {
				*objmissingprp = BOOL_TRUE;
			}
			iterp->strmh = DH2S(iterp->strmh)->s_nexth;
			if (iterp->strmh == DH_NULL) {
				iterp->donepr = BOOL_TRUE;
				return DH_NULL;
			}
			iterp->objh = DH2S(iterp->strmh)->s_cldh;
		}
		iterp->fileh = DH2O(iterp->objh)->o_cldh;
	}

	return iterp->fileh;
}

/* produces a list of media objects needed. also indicates if we know
 * some unidentified media objects are needed, and if it is possible
 * that we need some unidentifed objects, but don't know for sure.
 * if markskippr is set, set the f_nondirskipr flag if the media file
 * does not contain any nondirs of interest.
 */

struct bagobj {
	bagelem_t bagelem;
	uuid_t id;
	label_t label;
	bool_t indrivepr;
	ix_t indriveix;
};

typedef struct bagobj bagobj_t;

static bag_t *
pi_neededobjs_nondir_alloc(bool_t *knownholesprp,
			    bool_t *maybeholesprp,
			    bool_t showobjindrivepr,
			    bool_t markskippr)
{
	bag_t *bagp;
	pi_iter_t *headiterp;
	pi_iter_t *tailiterp;
	dh_t headh;
	dh_t tailh;
	egrp_t tailegrp;
	bool_t knownobjmissingpr;
	bool_t maybeobjmissingpr;
	bool_t maybefilemissingpr;
	dh_t lastobjaddedh;
	int objlistlen;

	/* no point in proceeding if pi not begun
	 */
	if (persp->s.strmheadh == DH_NULL) {
		*knownholesprp = BOOL_TRUE;
		*maybeholesprp = BOOL_FALSE;
		return 0;
	}

	/* to hold a list of media object handles: caller must free
	 * using pi_neededobjs_free().
	 */
	bagp = bag_alloc();

	/* allocate two iterators to scan pi
	 */
	tailiterp = pi_iter_alloc();
	headiterp = pi_iter_alloc();

	/* set the handle to the last file added to the list to NULL.
	 * this will be updated each time we add an object to the list,
	 * preventing the same object from being added more than once.
	 * this works because the media files for a given object will
	 * always appear contiguous and just once in a pi iteration.
	 */
	lastobjaddedh = DH_NULL;
	objlistlen = 0;

	/* these will be set TRUE if the tail iterator ever indicates
	 * we crossed an object or stream boundary and did not see a
	 * valid last file  or last object respectively. can accumulate
	 * the booleans, since iterator never sets FALSE, just TRUE.
	 */
	maybeobjmissingpr = BOOL_FALSE;
	maybefilemissingpr = BOOL_FALSE;

	/* this will be set TRUE if we see a needed media file but the
	 * object containing the media file has not been IDed.
	 */
	knownobjmissingpr = BOOL_FALSE;

	tailegrp.eg_ino = 0;
	tailegrp.eg_off = 0;

	tailh = DH_NULL;

	/* lock up the inventory during the scan
	 */
	pi_lock();

	do {
		egrp_t headegrp;
		bool_t foundgappr;

		/* advance the head until we see the next media file which has
		 * a valid egrp, or until we run out of media files.
		 */
		do {
			bool_t dummyobjmissingpr;
			bool_t dummyfilemissingpr;
			headh = pi_iter_nextfileh(headiterp,
						   &dummyobjmissingpr,
						   &dummyfilemissingpr);
		} while (headh != DH_NULL && !DH2F(headh)->f_valpr);
		if (headh == DH_NULL) {
			headegrp.eg_ino = INO64MAX;
			headegrp.eg_off = OFF64MAX;
		} else {
			assert(!(DH2F(headh)->f_flags & PF_INV));
			assert(!(DH2F(headh)->f_flags & PF_TERM));
			headegrp = DH2F(headh)->f_firstegrp;
		}

		/* see if the range of egrps from head up to but not including
		 * tail needed according to ino map
		 */
		if (gapneeded(&tailegrp, &headegrp)) {
			foundgappr = BOOL_TRUE;
		} else {
			foundgappr = BOOL_FALSE;
		}

		/* now bring tail up to head, adding objects and setting flags
		 * along the way. note special handling of NULL tailh. possible
		 * only first time through: ignore. also, ignore inv and term.
		 */
		do {
		    /* if requested, mark media files not needed
		     */
		    if (markskippr
			 &&
			 !foundgappr
			 &&
			 tailh != DH_NULL
			 &&
			 !(DH2F(tailh)->f_flags & PF_INV)
			 &&
			 !(DH2F(tailh)->f_flags & PF_TERM)
			 &&
			 !DH2F(tailh)->f_nondirskippr) {
			    DH2F(tailh)->f_nondirskippr = BOOL_TRUE;
		    }

		    /* build up list of needed objects
		     */
		    if (foundgappr
			 &&
			 tailh != DH_NULL
			 &&
			 !(DH2F(tailh)->f_flags & PF_INV)
			 &&
			 !(DH2F(tailh)->f_flags & PF_TERM)
			 &&
			 !DH2F(tailh)->f_nondirdonepr
			 &&
			 !DH2F(tailh)->f_nondirskippr) {

			    dh_t objh = DH2F(tailh)->f_parh;

			    if (!DH2O(objh)->o_indrivepr
				 ||
				 showobjindrivepr) {
				if (DH2O(objh)->o_idlabvalpr) {
					if (objh != lastobjaddedh) {
					    addobj(bagp,
						    &DH2O(objh)->o_id,
						    DH2O(objh)->o_lab,
						    DH2O(objh)->o_indrivepr,
						    DH2O(objh)->o_indriveix);
					    lastobjaddedh = objh;
					    objlistlen++;
					}
				} else {
					knownobjmissingpr = BOOL_TRUE;
				}
			    }
		    }

		    /* pull the tail up to the next media file
		     */
		    tailh = pi_iter_nextfileh(tailiterp,
					       &maybeobjmissingpr,
					       &maybefilemissingpr);
		} while (tailh != headh);

		tailegrp = headegrp;

	} while (headh != DH_NULL);

	pi_unlock();

	/* free the iterators
	 */
	pi_iter_free(tailiterp);
	pi_iter_free(headiterp);

	/* free the bag and return NULL if object list empty
	 */
	if (objlistlen == 0) {
		bag_free(bagp);
		bagp = 0;
	}

	*maybeholesprp = (maybeobjmissingpr || maybefilemissingpr);
	*knownholesprp = knownobjmissingpr;
	return bagp;
}

static bag_t *
pi_neededobjs_dir_alloc(bool_t *knownholesprp, bool_t *maybeholesprp)
{
	bag_t *bagp;
	dh_t fileh;
	pi_iter_t *iterp;
	bool_t knownobjmissingpr;
	bool_t maybeobjmissingpr;
	bool_t maybefilemissingpr;
	dh_t lastobjaddedh;
	int objlistlen;

	bagp = bag_alloc();
	iterp = pi_iter_alloc();

	knownobjmissingpr = BOOL_FALSE;
	maybeobjmissingpr = BOOL_FALSE;
	maybefilemissingpr = BOOL_FALSE;
	lastobjaddedh = DH_NULL;
	objlistlen = 0;

	pi_lock();

	while ((fileh = pi_iter_nextfileh(iterp,
					     &maybeobjmissingpr,
					     &maybefilemissingpr))
		!= DH_NULL) {
		if (!DH2F(fileh)->f_dirtriedpr) {
			dh_t objh = DH2F(fileh)->f_parh;
			if (!DH2O(objh)->o_indrivepr) {
				if (DH2O(objh)->o_idlabvalpr) {
					if (objh != lastobjaddedh) {
						addobj(bagp,
							&DH2O(objh)->o_id,
							DH2O(objh)->o_lab,
						    DH2O(objh)->o_indrivepr,
						    DH2O(objh)->o_indriveix);
						lastobjaddedh = objh;
						objlistlen++;
					}
				} else {
					knownobjmissingpr = BOOL_TRUE;
				}
			}
		}
	}

	pi_unlock();

	pi_iter_free(iterp);

	if (objlistlen == 0) {
		bag_free(bagp);
		bagp = 0;
	}

	*maybeholesprp = (maybeobjmissingpr || maybefilemissingpr);
	*knownholesprp = knownobjmissingpr;
	return bagp;
}

static void
pi_neededobjs_free(bag_t *bagp)
{
	bagiter_t bagiter;
	bagobj_t *bagobjp;
	bagelem_t *bagelemp;
	size64_t dummykey;
	void *dummypayloadp;

	assert(bagp);

	bagiter_init(bagp, &bagiter);

	bagobjp = 0;
	while ((bagelemp = bagiter_next(&bagiter, (void **)&bagobjp))) {
		bag_remove(bagp, bagelemp, &dummykey, &dummypayloadp);
		assert(bagobjp);
		assert(bagobjp == (bagobj_t *)dummypayloadp);
		free((void *)bagobjp);
		bagobjp = 0;
	}

	bag_free(bagp);
}

/* a macro predicate to indicate if we know we are done. if we are not
 * done or don't know, returns FALSE.
 */
static bool_t
pi_alldone(void)
{
	bag_t *bagp;
	bool_t knownholespr;
	bool_t maybeholespr;
	size_t cnt;

	knownholespr = BOOL_FALSE;
	maybeholespr = BOOL_FALSE;
	bagp = pi_neededobjs_nondir_alloc(&knownholespr,
					   &maybeholespr,
					   BOOL_TRUE,
					   BOOL_FALSE);
	if (bagp) {
		cnt = cntobj(bagp);
		pi_neededobjs_free(bagp);
	} else {
		cnt = 0;
	}

	if (cnt || knownholespr || maybeholespr) {
		return BOOL_FALSE;
	} else {
		return BOOL_TRUE;
	}
}

/* tells the persistent inventory we hit end-of-data while examining the
 * object specified by the index param. this tells us we've seen the end
 * of the stream as well as the end of the object.
 */
static void
pi_hiteod(ix_t strmix, ix_t objix)
{
	ix_t ix;
	dh_t strmh;
	dh_t objh;
	size_t objcnt;
	ix_t lastobjix;

	pi_lock();

	/* get handle to the indexed stream
	 */
	for (ix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL && ix < strmix
	      ;
	      ix++,
	      strmh = DH2S(strmh)->s_nexth)
		;
	assert(strmh != DH_NULL);

	/* get index to last object in stream
	 */
	for (objcnt = 0, objh = DH2S(strmh)->s_cldh
	      ;
	      objh != DH_NULL
	      ;
	      objh = DH2O(objh)->o_nexth, objcnt++)
		;
	assert(objcnt != 0);
	lastobjix = objcnt - 1;

	pi_unlock();

	/* can't possibly happen, but check for case where pi indicates
	 * other media objects beyond this one.
	 */
	if (objix != lastobjix) {
		mlog(MLOG_NORMAL | MLOG_WARNING | MLOG_MEDIA, _(
		      "hit EOD at stream %u object %u, "
		      "yet inventory indicates last object index is %u\n"),
		      strmix,
		      objix,
		      lastobjix);
	} else {
		pi_seestrmend(strmix);
	}

	pi_seeobjstrmend(strmix, lastobjix);
}

/* tells the persistent inventory we hit end-of-media while examining the
 * object specified by the index param. this tells us we've seen the end
 * of the object.
 */
static void
pi_hiteom(ix_t strmix, ix_t objix)
{
	pi_seeobjstrmend(strmix, objix);
}

static void
pi_hitnextdump(ix_t strmix, ix_t objix, ix_t lastfileix)
{
	ix_t ix;
	dh_t strmh;
	dh_t objh;
	size_t objcnt;
	ix_t lastobjix;

	pi_lock();

	/* get handle to the indexed stream
	 */
	for (ix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL && ix < strmix
	      ;
	      ix++,
	      strmh = DH2S(strmh)->s_nexth)
		;
	assert(strmh != DH_NULL);

	/* get index to last object in stream
	 */
	for (objcnt = 0, objh = DH2S(strmh)->s_cldh
	      ;
	      objh != DH_NULL
	      ;
	      objh = DH2O(objh)->o_nexth, objcnt++)
		;
	assert(objcnt != 0);
	lastobjix = objcnt - 1;

	pi_unlock();

	/* can't possibly happen, but check for case where pi indicates
	 * other media objects beyond this one.
	 */
	if (objix != lastobjix) {
		mlog(MLOG_NORMAL | MLOG_WARNING | MLOG_MEDIA, _(
		      "hit next dump at stream %u object %u file %u, "
		      "yet inventory indicates last object index is %u\n"),
		      strmix,
		      objix,
		      lastfileix,
		      lastobjix);
	} else {
		pi_seestrmend(strmix);
	}

	pi_seeobjstrmend(strmix, lastobjix);
}

/* returns TRUE if pi is certain no more useful media files remaining
 * on object. if any doubt, such as not knowing the last media file on
 * the object, returns FALSE.
 */
static bool_t
pi_know_no_more_on_object(purp_t purp, ix_t strmix, ix_t objix)
{
	ix_t ix;
	dh_t strmh;
	dh_t objh;
	dh_t fileh;

	assert(purp == PURP_DIR || purp == PURP_NONDIR);

	pi_lock();

	/* get handle to the indexed stream
	 */
	for (ix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL && ix < strmix
	      ;
	      ix++,
	      strmh = DH2S(strmh)->s_nexth)
		;
	assert(strmh != DH_NULL);

	/* get handle to indexed object
	 */
	for (ix = 0, objh = DH2S(strmh)->s_cldh
	      ;
	      objh != DH_NULL && ix < objix
	      ;
	      ix++,
	      objh = DH2O(objh)->o_nexth)
		;
	assert(objh != DH_NULL);

	/* if don't know last media file on object, return FALSE
	 */
	if (!DH2O(objh)->o_lmfknwnpr) {
		pi_unlock();
		return BOOL_FALSE;
	}

	/* check all media files on object. if any are not marked done,
	 * return FALSE.
	 */
	for (fileh = DH2O(objh)->o_cldh
	      ;
	      fileh != DH_NULL
	      ;
	      fileh = DH2F(fileh)->f_nexth) {
		if (DH2F(fileh)->f_flags & PF_INV) {
			continue;
		}
		if (DH2F(fileh)->f_flags & PF_TERM) {
			continue;
		}
		if (purp == PURP_DIR) {
			if (!DH2F(fileh)->f_dirtriedpr) {
				pi_unlock();
				return BOOL_FALSE;
			}
		} else {
			if (!DH2F(fileh)->f_nondirskippr
			     &&
			     !DH2F(fileh)->f_nondirdonepr) {
				pi_unlock();
				return BOOL_FALSE;
			}
		}
	}

	pi_unlock();
	return BOOL_TRUE;
}

static bool_t
pi_know_no_more_beyond_on_object(purp_t purp,
				  ix_t strmix,
				  ix_t objix,
				  ix_t fileix)
{
	ix_t ix;
	dh_t strmh;
	dh_t objh;
	dh_t fileh;

	assert(purp == PURP_DIR || purp == PURP_NONDIR);

	pi_lock();

	/* get handle to the indexed stream
	 */
	for (ix = 0,
	      strmh = persp->s.strmheadh
	      ;
	      strmh != DH_NULL && ix < strmix
	      ;
	      ix++,
	      strmh = DH2S(strmh)->s_nexth)
		;
	assert(strmh != DH_NULL);

	/* get handle to indexed object
	 */
	for (ix = 0,
	      objh = DH2S(strmh)->s_cldh
	      ;
	      objh != DH_NULL && ix < objix
	      ;
	      ix++,
	      objh = DH2O(objh)->o_nexth)
		;
	assert(objh != DH_NULL);

	/* if don't know last media file on object, return FALSE
	 */
	if (!DH2O(objh)->o_lmfknwnpr) {
		pi_unlock();
		return BOOL_FALSE;
	}

	/* check all files on object after indexed file. if any are not marked
	 * done, return FALSE. skip inventory and terminator files.
	 */
	for (ix = 0,
	      fileh = DH2O(objh)->o_cldh
	      ;
	      fileh != DH_NULL
	      ;
	      ix++,
	      fileh = DH2F(fileh)->f_nexth) {
		if (ix <= fileix) {
			continue;
		}
		if (DH2F(fileh)->f_flags & PF_INV) {
			continue;
		}
		if (DH2F(fileh)->f_flags & PF_TERM) {
			continue;
		}
		if (purp == PURP_DIR) {
			if (!DH2F(fileh)->f_dirtriedpr) {
				pi_unlock();
				return BOOL_FALSE;
			}
		} else {
			if (!DH2F(fileh)->f_nondirdonepr
			     &&
			     !DH2F(fileh)->f_nondirskippr) {
				pi_unlock();
				return BOOL_FALSE;
			}
		}
	}

	pi_unlock();
	return BOOL_TRUE;
}

/* indicates if the given extent group range is called for by the
 * ino map. *---o (endpoint not inclusive)
 */
static bool_t
gapneeded(egrp_t *firstegrpp, egrp_t *lastegrpp)
{
	xfs_ino_t endino;

	if (firstegrpp->eg_ino > lastegrpp->eg_ino) {
		return BOOL_FALSE;
	}

	if (firstegrpp->eg_ino == lastegrpp->eg_ino
	     &&
	     firstegrpp->eg_off > lastegrpp->eg_off) {
		return BOOL_FALSE;
	}

	if (lastegrpp->eg_off > 0 || lastegrpp->eg_ino == 0) {
		endino = lastegrpp->eg_ino;
	} else {
		endino = lastegrpp->eg_ino - 1;
	}

	if (!inomap_rst_needed(firstegrpp->eg_ino, endino)) {
		return BOOL_FALSE;
	}

	return BOOL_TRUE;
}

static void
addobj(bag_t *bagp,
	uuid_t *idp,
	label_t label,
	bool_t indrivepr,
	ix_t indriveix)
{
	bagobj_t *bagobjp;

	bagobjp = (bagobj_t *)calloc(1, sizeof(bagobj_t));
	assert(bagobjp);
	uuid_copy(bagobjp->id, *idp);
	strncpy(bagobjp->label,
		 label,
		 sizeof(bagobjp->label));
	bagobjp->indrivepr = indrivepr;
	bagobjp->indriveix = indriveix;
	bag_insert(bagp,
		    &bagobjp->bagelem,
		    (size64_t)0,
		    (void *)bagobjp);
}

static size_t
cntobj(bag_t *bagp)
{
	bagiter_t bagiter;
	bagobj_t *bagobjp;
	size_t cnt;

	assert(bagp);

	bagiter_init(bagp, &bagiter);
	cnt = 0;
	bagobjp = 0; /* keep lint happy */
	while (bagiter_next(&bagiter, (void **)&bagobjp)) {
		cnt++;
		bagobjp = 0; /* keep lint happy */
	}

	return cnt;
}


/* misc. static functions ***************************************************/

/* queries inventory for the base of the given session. if the given session
 * was a resumed dump, then must be last dump of same level. otherwise,
 * must be last dump of a lesser level
 */
static bool_t
askinvforbaseof(uuid_t baseid, inv_session_t *sessp)
{
	ix_t level;
	bool_t resumedpr;
	inv_idbtoken_t invtok;
	inv_session_t *basesessp;
	bool_t ok;

	level = (ix_t)sessp->s_level;
	resumedpr = sessp->s_isresumed;

	/* don't look for base if level 0 and not resumed
	 */
	if (level == 0 && !resumedpr) {
		return BOOL_TRUE;
	}

	/* open the inventory for this file system
	 */
	invtok = inv_open(INV_BY_UUID,
			   INV_SEARCH_ONLY,
			   (void *)&sessp->s_fsid);
	if (invtok == INV_TOKEN_NULL) {
		mlog(MLOG_NORMAL | MLOG_WARNING | MLOG_MEDIA, _(
		      "unable to open inventory to validate dump\n"));
		return BOOL_FALSE;
	}

	/* get the base session
	 */
	if (resumedpr) {
		ok = inv_lastsession_level_equalto(&sessp->s_fsid,
						    invtok,
						    (u_char_t)level,
						    &basesessp);
	} else {
		ok = inv_lastsession_level_lessthan(&sessp->s_fsid,
						     invtok,
						     (u_char_t)level,
						     &basesessp);
	}
	if (!ok) {
		mlog(MLOG_NORMAL | MLOG_WARNING | MLOG_MEDIA, _(
		      "unable to find base dump in inventory "
		      "to validate dump\n"));
		return BOOL_FALSE;
	}

	/* close the inventory
	 */
	ok = inv_close(invtok);
	assert(ok);

	/* return id of base session
	 */
        uuid_copy(baseid, basesessp->s_sesid);

	/* free the base session descriptor
	 */
	inv_free_session(&basesessp);

	return BOOL_TRUE;
}

static bool_t
dumpcompat(bool_t resumepr, ix_t level, uuid_t baseid, bool_t logpr)
{
	if (persp->a.cumpr) {
		if (persp->a.dumpcnt == 0) {
			if (resumepr) {
				if (logpr) {
				    mlog(MLOG_NORMAL | MLOG_ERROR, _(
					  "cumulative restores must begin with "
					  "an initial (not resumed) "
					  "level 0 dump\n"));
				}
				return BOOL_FALSE;
			}
			if (level > 0) {
				if (logpr) {
				    mlog(MLOG_NORMAL | MLOG_ERROR, _(
					  "cumulative restores must begin with "
					  "a level 0 dump\n"));
				}
				return BOOL_FALSE;
			}
		} else {
			if (resumepr) {
				if (uuid_compare(persp->a.lastdumpid,
						   baseid) != 0) {
					if (logpr) {
					    mlog(MLOG_NORMAL | MLOG_ERROR, _(
						  "selected resumed dump "
						  "not a resumption of "
						  "previously applied dump\n"));
					}
					return BOOL_FALSE;
				}
			} else {
				if (uuid_compare(persp->a.lastdumpid,
						   baseid) != 0) {
					if (logpr) {
					    mlog(MLOG_NORMAL | MLOG_ERROR, _(
						  "selected dump not based on "
						  "previously applied dump\n"));
					}
					return BOOL_FALSE;
				}
			}
		}
	}

	return BOOL_TRUE;
}

/* prompts for a new media object. supplies list of media objects still
 * needed, and indicates if there are or may be unidentified media objects
 * still needed/available
 */
static bool_t
Media_prompt_change(drive_t *drivep,
		     purp_t purp,
		     bag_t *bagp,
		     bool_t knownholespr,
		     bool_t maybeholespr)
{
	fold_t fold;
	char question[100];
	char *preamblestr[PREAMBLEMAX];
	size_t preamblecnt;
	char *querystr[QUERYMAX];
	size_t querycnt;
	char *choicestr[CHOICEMAX];
	size_t choicecnt;
	char *ackstr[ACKMAX];
	size_t ackcnt;
	char *postamblestr[POSTAMBLEMAX];
	size_t postamblecnt;
	ix_t doix;
	ix_t dontix;
	ix_t invstatix;
	ix_t neededix;
	ix_t responseix;
	ix_t sigintix;

retry:
	fold_init(fold, _("change media dialog"), '=');
	preamblecnt = 0;
	preamblestr[preamblecnt++ ] = "\n";
	preamblestr[preamblecnt++] = fold;
	preamblestr[preamblecnt++ ] = "\n\n";
	assert(preamblecnt <= PREAMBLEMAX);
	dlog_begin(preamblestr, preamblecnt);

	/* query: ask if media changed or declined
	 */
	if (drivecnt > 1) {
		sprintf(question, _(
			 "please change media in "
			 "drive %u\n"),
			 (unsigned int)drivep->d_index);
	} else {
		sprintf(question, _(
			 "please change media in "
			 "drive\n"));
	}
	querycnt = 0;
	querystr[querycnt++] = question;
	assert(querycnt <= QUERYMAX);
	choicecnt = 0;
	dontix = choicecnt;
	choicestr[choicecnt++ ] = _("media change declined");
	if (purp != PURP_SEARCH) {
		invstatix = choicecnt;
		choicestr[choicecnt++ ] = _("display media inventory status");
		neededix = choicecnt;
		choicestr[choicecnt++ ] = _("list needed media objects");
	} else {
		invstatix = IXMAX;
		neededix = IXMAX;
	}
	doix = choicecnt;
	choicestr[choicecnt++ ] = _("media changed");
	assert(choicecnt <= CHOICEMAX);
	sigintix = IXMAX - 1;

	responseix = dlog_multi_query(querystr,
				       querycnt,
				       choicestr,
				       choicecnt,
				       0,           /* hilitestr */
				       IXMAX,       /* hiliteix */
				       0,           /* defaultstr */
				       doix,        /* defaultix */
				       DLOG_TIMEOUT_MEDIA,
				       dontix,		/* timeout ix */
				       sigintix,	/* sigint ix */
				       dontix,		/* sighup ix */
				       dontix);	/* sigquit ix */
	ackcnt = 0;
	if (responseix == doix) {
		ackstr[ackcnt++ ] = _("examining new media\n");
	} else if (responseix == dontix) {
		ackstr[ackcnt++ ] = _("media change aborted\n");
	} else if (responseix == invstatix) {
		ackstr[ackcnt++ ] = "\n";
		assert(ackcnt <= ACKMAX);
		dlog_multi_ack(ackstr,
				ackcnt);
		pi_show_nomloglock();
		postamblecnt = 0;
		fold_init(fold, _("end dialog"), '-');
		postamblestr[postamblecnt++ ] = "\n";
		postamblestr[postamblecnt++] = fold;
		postamblestr[postamblecnt++ ] = "\n\n";
		assert(postamblecnt <= POSTAMBLEMAX);
		dlog_end(postamblestr,
			  postamblecnt);
		goto retry;
	} else if (responseix == neededix) {
		ackstr[ackcnt++ ] = "\n";
		assert(ackcnt <= ACKMAX);
		dlog_multi_ack(ackstr,
				ackcnt);
		display_needed_objects(purp,
					bagp,
					knownholespr,
					maybeholespr);
		postamblecnt = 0;
		fold_init(fold, "end dialog", '-');
		postamblestr[postamblecnt++ ] = "\n";
		postamblestr[postamblecnt++] = fold;
		postamblestr[postamblecnt++ ] = "\n\n";
		assert(postamblecnt <= POSTAMBLEMAX);
		dlog_end(postamblestr,
			  postamblecnt);
		goto retry;
	} else {
		assert(responseix == sigintix);
		ackstr[ackcnt++ ] = _("keyboard interrupt\n");
	}

	assert(ackcnt <= ACKMAX);
	dlog_multi_ack(ackstr,
			ackcnt);

	postamblecnt = 0;
	fold_init(fold, _("end dialog"), '-');
	postamblestr[postamblecnt++ ] = "\n";
	postamblestr[postamblecnt++] = fold;
	postamblestr[postamblecnt++ ] = "\n\n";
	assert(postamblecnt <= POSTAMBLEMAX);
	dlog_end(postamblestr,
		  postamblecnt);

	if (responseix == sigintix) {
		if (cldmgr_stop_requested()) {
			return BOOL_FALSE;
		}
		sleep(1); /* to allow main thread to begin dialog */
		mlog(MLOG_NORMAL | MLOG_BARE,
		      ""); /* to block until main thread dialog complete */
		sleep(1); /* to allow main thread to request children die */
		if (cldmgr_stop_requested()) {
			return BOOL_FALSE;
		}
		mlog(MLOG_DEBUG,
		      "retrying media change dialog\n");
		goto retry;
	}

	return responseix == doix;
}

/* prompts the operator, asking if the current media file header describes
 * the dump to be restored
 */
static bool_t
promptdumpmatch(ix_t thrdix,
		 global_hdr_t *grhdrp,
		 media_hdr_t *mrhdrp,
		 content_hdr_t *crhdrp,
		 content_inode_hdr_t *scrhdrp)
{
	fold_t fold;
	char introstring[80];
	char *preamblestr[PREAMBLEMAX];
	size_t preamblecnt;
	char *querystr[QUERYMAX];
	size_t querycnt;
	char *choicestr[CHOICEMAX];
	size_t choicecnt;
	char *ackstr[ACKMAX];
	size_t ackcnt;
	char *postamblestr[POSTAMBLEMAX];
	size_t postamblecnt;
	ix_t doix;
	ix_t dontix;
	ix_t responseix;
	ix_t sigintix;

retry:
	preamblecnt = 0;
	fold_init(fold, _("dump selection dialog"), '=');
	preamblestr[preamblecnt++ ] = "\n";
	preamblestr[preamblecnt++] = fold;
	preamblestr[preamblecnt++ ] = "\n\n";
	assert(preamblecnt <= PREAMBLEMAX);
	dlog_begin(preamblestr, preamblecnt);

	/* display vital stats and ask if this one should be restored
	 */
	if (drivecnt > 0) {
		sprintf(introstring, _(
			 "the following dump has been found"
			 " on drive %u"
			 "\n\n"),
			 (unsigned int)thrdix);
	} else {
		sprintf(introstring, _(
			 "the following dump has been found"
			 "\n\n"));
	}
	assert(strlen(introstring) < sizeof(introstring));
	display_dump_label(BOOL_FALSE,
			    MLOG_NORMAL | MLOG_BARE,
			    introstring,
			    grhdrp,
			    mrhdrp,
			    crhdrp,
			    scrhdrp);

	querycnt = 0;
	if (tranp->t_toconlypr) {
		querystr[querycnt++ ] = _("\nexamine this dump?\n");
	} else {
		querystr[querycnt++] = (persp->a.interpr) ?
			_("\ninteractively restore from this dump?\n")
				: _("\nrestore this dump?\n");
	}
	assert(querycnt <= QUERYMAX);
	choicecnt = 0;
	dontix = choicecnt;
	choicestr[choicecnt++ ] = _("skip");
	doix = choicecnt;
	choicestr[choicecnt++] = (persp->a.interpr) ?
				_("interactively restore\n") : _("restore\n");
	assert(choicecnt <= CHOICEMAX);
	sigintix = IXMAX - 1;

	responseix = dlog_multi_query(querystr,
				       querycnt,
				       choicestr,
				       choicecnt,
				       0,           /* hilitestr */
				       IXMAX,       /* hiliteix */
				       0,           /* defaultstr */
				       doix,        /* defaultix */
				       0,
				       IXMAX,		/* timeout ix */
				       sigintix,	/* sigint ix */
				       dontix,		/* sighup ix */
				       dontix);	/* sigquit ix */
	ackcnt = 0;
	if (responseix == doix) {
		ackstr[ackcnt++] = (persp->a.interpr) ?
			_("this dump selected for interactive restoral\n")
			      : _("this dump selected for restoral\n");
	} else if (responseix == dontix) {
		ackstr[ackcnt++ ] = _("dump skipped\n");
	} else {
		assert(responseix == sigintix);
		ackstr[ackcnt++ ] = _("keyboard interrupt\n");
	}

	assert(ackcnt <= ACKMAX);
	dlog_multi_ack(ackstr,
			ackcnt);

	postamblecnt = 0;
	fold_init(fold, "end dialog", '-');
	postamblestr[postamblecnt++ ] = "\n";
	postamblestr[postamblecnt++] = fold;
	postamblestr[postamblecnt++ ] = "\n\n";
	assert(postamblecnt <= POSTAMBLEMAX);
	dlog_end(postamblestr,
		  postamblecnt);

	if (responseix == sigintix) {
		if (cldmgr_stop_requested()) {
			return BOOL_FALSE;
		}
		sleep(1); /* to allow main thread to begin dialog */
		mlog(MLOG_NORMAL | MLOG_BARE,
		      ""); /* to block until main thread dialog complete */
		sleep(1); /* to allow main thread to request children die */
		if (cldmgr_stop_requested()) {
			return BOOL_FALSE;
		}
		mlog(MLOG_DEBUG,
		      "retrying dump selection dialog\n");
		goto retry;
	}

	return responseix == doix;
}

/* restore_file - knows how to restore non-directory files
 *
 * uses the tree's callback iterator, which will call me for each
 * link to the specified inode.
 */
struct cb_context {
	drive_t *cb_drivep;
	filehdr_t *cb_fhdrp;
	rv_t cb_rv;
	bool_t cb_ehcs;
	bool_t cb_ahcs;
	char *cb_path1;
	char *cb_path2;
};

typedef struct cb_context cb_context_t;

static bool_t restore_file_cb(void *, bool_t, char *, char *);

static rv_t
restore_file(drive_t *drivep,
	      filehdr_t *fhdrp,
	      bool_t ehcs,
	      bool_t ahcs,
	      char *path1,
	      char *path2)
{
	rv_t rv;
	bstat_t *bstatp = &fhdrp->fh_stat;
	cb_context_t context;

	/* ask the tree to call me back for each link to this inode.
	 * my callback will restore the file the first time it is
	 * invoked, and create a hard link in subsequent calls.
	 */
	context.cb_drivep = drivep;
	context.cb_fhdrp = fhdrp;
	context.cb_rv = RV_OK;
	context.cb_ehcs = ehcs;
	context.cb_ahcs = ahcs;
	context.cb_path1 = path1;
	context.cb_path2 = path2;
	rv = tree_cb_links(bstatp->bs_ino,
		       bstatp->bs_gen,
		       bstatp->bs_ctime.tv_sec,
		       bstatp->bs_mtime.tv_sec,
		       restore_file_cb,
		       &context,
		       path1,
		       path2);
	if (context.cb_rv) /* context error result has precedence */
	    return context.cb_rv; /* this would be set by callback */
	else
	    return rv;
}

/* called for each link to the file described by fhdr. the first
 * call is detected by noting linkpr is FALSE, and is used to create/
 * update the first link to the file, using path1. subsequent calls have
 * linkpr set false, and should link path1 to path2. if path1 is ever null,
 * just pull from media: don't create.
 * if this func returns FALSE, will cause tree_cb_links to abort
 */
static bool_t
restore_file_cb(void *cp, bool_t linkpr, char *path1, char *path2)
{
	cb_context_t *contextp = (cb_context_t *)cp;
	drive_t *drivep = contextp->cb_drivep;
	filehdr_t *fhdrp = contextp->cb_fhdrp;
	bstat_t *bstatp = &fhdrp->fh_stat;
	rv_t *rvp = &contextp->cb_rv;
	bool_t ehcs = contextp->cb_ehcs;
	bool_t ahcs = contextp->cb_ahcs;
	stream_context_t *strctxp = (stream_context_t *)drivep->d_strmcontextp;

	int rval;
	bool_t ok;

	if (cldmgr_stop_requested()) {
		*rvp = RV_INTR;
		return BOOL_FALSE;
	}

	if (!linkpr) {
		if (path1) {
			/* cache the path for use in restoring attributes
			 * and extended attributes
			 */
			strcpy(strctxp->sc_path, path1);
		}

		/* call type-specific function to create the file
		 */
		switch(bstatp->bs_mode & S_IFMT) {
		case S_IFREG:
			ok = restore_reg(drivep, fhdrp, rvp, path1);
			if (!ok)
				return ok;
			if (fhdrp->fh_flags & FILEHDR_FLAGS_EXTATTR) {
				*rvp = restore_extattr(drivep,
							fhdrp,
							path1,
							ahcs,
							BOOL_FALSE, /* isdirpr */
							BOOL_FALSE, /* onlydoreadpr */
							DAH_NULL);
			} else {
				ok = restore_extent_group(drivep,
							   fhdrp,
							   path1,
							   strctxp->sc_fd,
							   ehcs,
							   rvp);
			}
			return ok;
		case S_IFBLK:
		case S_IFCHR:
		case S_IFIFO:
#ifdef S_IFNAM
		case S_IFNAM:
#endif
		case S_IFSOCK:
			ok = restore_spec(fhdrp, rvp, path1);
			return ok;
		case S_IFLNK:
			ok = restore_symlink(drivep,
					      fhdrp,
					      rvp,
					      path1,
					      path2,
					      ehcs);
			return ok;
		default:
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "ino %llu: unknown file type: %08x\n"),
			      bstatp->bs_ino,
			      bstatp->bs_mode);
			return BOOL_FALSE;
		}
	} else if (!tranp->t_toconlypr) {
		assert(path1);
		assert(path2);
		mlog(MLOG_TRACE,
		      "linking %s to %s\n",
		      path1,
		      path2);
		rval = unlink(path2);
		if (rval && errno != ENOENT) {
			mlog(MLOG_VERBOSE | MLOG_WARNING, _(
			      "unable to unlink "
			      "current file prior to linking "
			      "%s to %s:"
			      " %s\n"),
			      path1,
			      path2,
			      strerror(errno));
		} else {
			rval = link(path1, path2);
			if (rval) {
				mlog(MLOG_NORMAL | MLOG_WARNING, _(
				      "attempt to "
				      "link %s to %s failed:"
				      " %s\n"),
				      path1,
				      path2,
				      strerror(errno));
			}
		}
		return BOOL_TRUE;
	} else {
		mlog(MLOG_NORMAL | MLOG_BARE,
		      "%s\n",
		      path2);
		return BOOL_TRUE;
	}
}

/*
 * Set the file owner and strip suid/sgid if necessary. On failure, it will
 * close the file descriptor, unlink the file and return -1. On success,
 * it will mark the stream contexts as having set the owner and return 0.
 */
static int
set_file_owner(
	char		 *path,
	int	 *fdp,
	stream_context_t *strcxtp)
{
	bstat_t		*bstatp = &strcxtp->sc_bstat;
	mode_t		mode = (mode_t)bstatp->bs_mode;
	int		rval;

	rval = fchown(*fdp, (uid_t)bstatp->bs_uid, (gid_t)bstatp->bs_gid);
	if (!rval)
		goto done;

	mlog(MLOG_VERBOSE | MLOG_WARNING,
	     _("chown (uid=%u, gid=%u) %s failed: %s\n"),
	     bstatp->bs_uid, bstatp->bs_gid, path, strerror(errno));

	if (mode & S_ISUID) {
		mlog(MLOG_VERBOSE | MLOG_WARNING,
		     _("stripping setuid bit on %s since chown failed\n"),
		     path);
		mode &= ~S_ISUID;
	}

	if ((mode & (S_ISGID|S_IXGRP)) == (S_ISGID|S_IXGRP)) {
		mlog(MLOG_VERBOSE | MLOG_WARNING,
		     _("stripping setgid bit on %s since chown failed\n"),
		     path);
		mode &= ~S_ISGID;
	}

	if (mode == (mode_t)bstatp->bs_mode)
		goto done;

	rval = fchmod(*fdp, mode);
	if (rval) {
		mlog(MLOG_VERBOSE | MLOG_ERROR,
		     _("unable to strip setuid/setgid on %s, unlinking file.\n"),
		     path);
		unlink(path);
		close(*fdp);
		*fdp = -1;
		return -1;
	}
done:
	strcxtp->sc_ownerset = BOOL_TRUE;
	return 0;
}

/* called to begin a regular file. if no path given, or if just toc,
 * don't actually write, just read. also get into that situation if
 * cannot prepare destination. fd == -1 signifies no write. *statp
 * is set to indicate drive errors. returns FALSE if should abort
 * this iteration.
 */
static bool_t
restore_reg(drive_t *drivep,
	     filehdr_t *fhdrp,
	     rv_t *rvp,
	     char *path)
{
	bstat_t *bstatp = &fhdrp->fh_stat;
	stream_context_t *strctxp = (stream_context_t *)drivep->d_strmcontextp;
	int *fdp = &strctxp->sc_fd;
	int rval;
	struct fsxattr fsxattr;
	struct stat64 stat;
	int oflags;

	if (!path)
		return BOOL_TRUE;

	if (fhdrp->fh_offset) {
		if (!tranp->t_toconlypr) {
			mlog(MLOG_TRACE,
			      "restoring regular file ino %llu %s"
			      " (offset %lld)\n",
			      bstatp->bs_ino,
			      path,
			      fhdrp->fh_offset);
		} else {
			mlog(MLOG_NORMAL | MLOG_BARE,
			      _("%s (offset %lld)\n"),
			      path,
			      fhdrp->fh_offset);
		}
	} else {
		if (!tranp->t_toconlypr) {
			mlog(MLOG_TRACE,
			      "restoring regular file ino %llu %s\n",
			      bstatp->bs_ino,
			      path);
		} else {
			mlog(MLOG_NORMAL | MLOG_BARE,
			      "%s\n",
			      path);
		}
	}

	if (tranp->t_toconlypr)
		return BOOL_TRUE;

	oflags = O_CREAT | O_RDWR;
	if (persp->a.dstdirisxfspr && bstatp->bs_xflags & XFS_XFLAG_REALTIME)
		oflags |= O_DIRECT;

	*fdp = open(path, oflags, S_IRUSR | S_IWUSR);
	if (*fdp < 0) {
		mlog(MLOG_NORMAL | MLOG_WARNING,
		      _("open of %s failed: %s: discarding ino %llu\n"),
		      path,
		      strerror(errno),
		      bstatp->bs_ino);
		return BOOL_TRUE;
	}

	rval = fstat64(*fdp, &stat);
	if (rval != 0) {
		mlog(MLOG_VERBOSE | MLOG_WARNING,
		      _("attempt to stat %s failed: %s\n"),
		      path,
		      strerror(errno));
	} else {
		if (stat.st_size != bstatp->bs_size) {
			mlog(MLOG_TRACE,
			      "truncating %s from %lld to %lld\n",
			      path,
			      stat.st_size,
			      bstatp->bs_size);

			rval = ftruncate64(*fdp, bstatp->bs_size);
			if (rval != 0) {
				mlog(MLOG_VERBOSE | MLOG_WARNING,
				      _("attempt to truncate %s failed: %s\n"),
				      path,
				      strerror(errno));
			}
		}
	}

	if (strctxp->sc_ownerset == BOOL_FALSE && persp->a.ownerpr) {
		rval = set_file_owner(path, fdp, strctxp);
		if (rval)
			return BOOL_TRUE;
	}

	if (persp->a.dstdirisxfspr) {

		/* set the extended inode flags, except those which must
		 * be set only after all data has been restored.
		 */
		assert(bstatp->bs_extsize >= 0);
		memset((void *)&fsxattr, 0, sizeof(fsxattr));
		fsxattr.fsx_xflags = bstatp->bs_xflags & ~POST_DATA_XFLAGS;
		fsxattr.fsx_extsize = (uint32_t) bstatp->bs_extsize;
		fsxattr.fsx_projid = bstat_projid(bstatp);

		rval = ioctl(*fdp, XFS_IOC_FSSETXATTR, (void *)&fsxattr);
		if (rval < 0) {
			mlog(MLOG_NORMAL | MLOG_WARNING,
			      _("attempt to set extended attributes "
				"(xflags 0x%x, extsize = 0x%x, projid = 0x%x) "
				"of %s failed: %s\n"),
			      fsxattr.fsx_xflags,
			      fsxattr.fsx_extsize,
			      fsxattr.fsx_projid,
			      path,
			      strerror(errno));
		}
	}

	if (persp->a.dstdirisxfspr && persp->a.restoredmpr) {
		HsmBeginRestoreFile(bstatp,
				     *fdp,
				     &strctxp->sc_hsmflags);
	}

	return BOOL_TRUE;
}

/* called to peel a regular file's extent groups from the media.
 * if no path given, or if just toc, don't actually write, just
 * read. fd == -1 signifies no write. *rvp is set to indicate
 * drive errors. returns FALSE if should abort this iteration.
 */
static bool_t
restore_extent_group(drive_t *drivep,
		      filehdr_t *fhdrp,
		      char *path,
		      int fd,
		      bool_t ehcs,
		      rv_t *rvp)
{
	bstat_t *bstatp = &fhdrp->fh_stat;
	off64_t restoredsz = 0;
	extenthdr_t ehdr;
	off64_t bytesread;
	rv_t rv;

	/* copy data extents from media to the file
	 */
	for (;;) {
		/* read the extent header
		 */
		rv = read_extenthdr(drivep, &ehdr, ehcs);
		if (rv != RV_OK) {
			*rvp = rv;
			return BOOL_FALSE;
		}
		mlog(MLOG_NITTY,
		      "read extent hdr type %s offset %lld sz %lld flags %x\n",
		      ehdr_typestr(ehdr.eh_type),
		      ehdr.eh_offset,
		      ehdr.eh_sz,
		      ehdr.eh_flags);

		/* if we see the specially marked last extent hdr,
		 * we are done.
		 */
		if (ehdr.eh_type == EXTENTHDR_TYPE_LAST) {
			/* For a wholly sparse file, there is no HOLE
			 * record; advance restoredsz to EOF.
			 */
			if (!restoredsz)
				restoredsz = bstatp->bs_size;
			break;
		}

		/* if its an ALIGNment extent, discard the extent.
		 */
		if (ehdr.eh_type == EXTENTHDR_TYPE_ALIGN) {
			size_t sz;
			assert(ehdr.eh_sz <= INTGENMAX);
			sz = (size_t)ehdr.eh_sz;
			rv = discard_padding(sz, drivep);
			if (rv != RV_OK) {
				*rvp = rv;
				return BOOL_FALSE;
			}
			continue;
		}

		/* Add up extents restored to later check if the file
		 * is done.
		 */
		restoredsz += ehdr.eh_sz;  /* Increments of block size (usually 512) */

		/* Holes do not need to be restored since we now
		 * unlink the file at the start of the restore.
		 */
		if (ehdr.eh_type == EXTENTHDR_TYPE_HOLE) {
			continue;
		}

		/* real data
		 */
		assert(ehdr.eh_type == EXTENTHDR_TYPE_DATA);
		bytesread = 0;
		rv = restore_extent(fhdrp,
				     &ehdr,
				     fd,
				     path,
				     drivep,
				     &bytesread);
		if (rv != RV_OK) {
			*rvp = rv;
			return BOOL_FALSE;
		}

		if (cldmgr_stop_requested()) {
			*rvp = RV_INTR;
			return BOOL_FALSE;
		}
	}

	/* The extent group has been restored.  If the file is not
	 * complete, we may need to co-ordinate with other restore
	 * streams to time the restoration of extended attributes
	 * and certain extended inode flags. Register the portion
	 * of the file completed here in the persistent state.
	 */
	if (bstatp->bs_size > restoredsz) {
		partial_reg(drivep->d_index,
			    bstatp->bs_ino,
			    bstatp->bs_size,
			    fhdrp->fh_offset,
			    restoredsz);
	}

	return BOOL_TRUE;
}

/* apply the attributes that can only go on now that all data
 * and extended attributes have been applied. fd == -1 signifies
 * no write, due to unknown path or toc only.
 */
static bool_t
restore_complete_reg(stream_context_t *strcxtp)
{
	bstat_t *bstatp = &strcxtp->sc_bstat;
	char *path = strcxtp->sc_path;
	int fd = strcxtp->sc_fd;
	struct utimbuf utimbuf;
	int rval;

	// only applies to regular files
	if (!S_ISREG((strcxtp->sc_bstat.bs_mode)))
		return BOOL_TRUE;

	if (fd < 0)
		return BOOL_TRUE;

	if (!partial_check(bstatp->bs_ino, bstatp->bs_size)) {
		close(fd);
		return BOOL_TRUE;
	}

	/* set the access and modification times
	 */
	utimbuf.actime = (time32_t)bstatp->bs_atime.tv_sec;
	utimbuf.modtime = (time32_t)bstatp->bs_mtime.tv_sec;
	rval = utime(path, &utimbuf);
	if (rval) {
		mlog(MLOG_VERBOSE | MLOG_WARNING, _(
		      "unable to set access and modification "
		      "times of %s: %s\n"),
		      path,
		      strerror(errno));
	}

	/* set the owner and group (if enabled)
	 */
	if (strcxtp->sc_ownerset == BOOL_FALSE && persp->a.ownerpr) {
		rval = set_file_owner(path, &fd, strcxtp);
		if (rval)
			return BOOL_TRUE;
	}

	/* set the permissions/mode
	 */
	rval = fchmod(fd, (mode_t)bstatp->bs_mode);
	if (rval) {
		mlog(MLOG_VERBOSE | MLOG_WARNING, _(
		      "unable to set mode of %s: %s\n"),
		      path,
		      strerror(errno));
	}

	if (persp->a.dstdirisxfspr && persp->a.restoredmpr) {
		fsdmidata_t fssetdm;

		/* Set the DMAPI Fields. */
		fssetdm.fsd_dmevmask = bstatp->bs_dmevmask;
		fssetdm.fsd_padding = 0;
		fssetdm.fsd_dmstate = bstatp->bs_dmstate;

		rval = ioctl(fd, XFS_IOC_FSSETDM, (void *)&fssetdm);
		if (rval) {
			mlog(MLOG_NORMAL | MLOG_WARNING,
			      _("attempt to set DMI attributes of %s "
			      "failed: %s\n"),
			      path,
			      strerror(errno));
		}

		HsmEndRestoreFile(path, fd, &strcxtp->sc_hsmflags);
	}

	/* set any extended inode flags that couldn't be set
	 * prior to restoring the data.
	 */
	if (persp->a.dstdirisxfspr && bstatp->bs_xflags & POST_DATA_XFLAGS) {
		struct fsxattr fsxattr;
		memset((void *)&fsxattr, 0, sizeof(fsxattr));
		fsxattr.fsx_xflags = bstatp->bs_xflags;
		fsxattr.fsx_extsize = (uint32_t)bstatp->bs_extsize;
		fsxattr.fsx_projid = bstat_projid(bstatp);

		rval = ioctl(fd, XFS_IOC_FSSETXATTR, (void *)&fsxattr);
		if (rval < 0) {
			mlog(MLOG_NORMAL | MLOG_WARNING,
			     _("attempt to set extended attributes "
			     "(xflags 0x%x, extsize = 0x%x, projid = 0x%x) "
			     "of %s failed: %s\n"),
			     fsxattr.fsx_xflags,
			     fsxattr.fsx_extsize,
			     fsxattr.fsx_projid,
			     path,
			     strerror(errno));
		}
	}

	close(fd);
	return BOOL_TRUE;
}

/* ARGSUSED */
static bool_t
restore_spec(filehdr_t *fhdrp, rv_t *rvp, char *path)
{
	bstat_t *bstatp = &fhdrp->fh_stat;
	struct utimbuf utimbuf;
	char *printstr;
	int rval;

	if (!path) {
		return BOOL_TRUE;
	}

	switch (bstatp->bs_mode & S_IFMT) {
	case S_IFBLK:
		printstr = _("block special file");
		break;
	case S_IFCHR:
		printstr = _("char special file");
		break;
	case S_IFIFO:
		printstr = _("named pipe");
		break;
#ifdef S_IFNAM
	case S_IFNAM:
		printstr = _("XENIX named pipe");
		break;
#endif
	case S_IFSOCK:
		printstr = _("UNIX domain socket");
		break;
	default:
		mlog(MLOG_NORMAL | MLOG_WARNING, _(
		      "%s: unknown file type: mode 0x%x ino %llu\n"),
		      path,
		      bstatp->bs_mode,
		      fhdrp->fh_stat.bs_ino);
		return BOOL_TRUE;
	}

	if (!tranp->t_toconlypr) {
		mlog(MLOG_TRACE,
		      "restoring %s ino %llu %s\n",
		      printstr,
		      fhdrp->fh_stat.bs_ino,
		      path);
	} else {
		mlog(MLOG_NORMAL | MLOG_BARE,
		      "%s\n",
		      path);
	}

	if (!tranp->t_toconlypr) {
		if ((bstatp->bs_mode & S_IFMT) == S_IFSOCK) {
			int sockfd;
			struct sockaddr_un addr;
			size_t addrlen;

			sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
			if (sockfd < 0) {
				mlog(MLOG_VERBOSE | MLOG_WARNING, _(
				      "unable to create "
				      "%s ino %llu %s: %s: discarding\n"),
				      printstr,
				      fhdrp->fh_stat.bs_ino,
				      path,
				      strerror(errno));
				return BOOL_TRUE;
			}
			memset((void *)&addr, 0, sizeof(addr));
			addr.sun_family = AF_UNIX;
			if (strlen(path) >= sizeof(addr.sun_path)) {
				mlog(MLOG_VERBOSE | MLOG_WARNING, _(
				      "pathname too long for bind of "
				      "%s ino %llu %s: discarding\n"),
				      printstr,
				      fhdrp->fh_stat.bs_ino,
				      path);
				(void)close(sockfd);
				return BOOL_TRUE;
			}
			strcpy(addr.sun_path, path);
			addrlen = strlen(addr.sun_path)
				  +
				  sizeof(addr.sun_family);
			rval = bind(sockfd,
				     (struct sockaddr *)&addr,
				     (int)addrlen);
			if (rval < 0) {
				mlog(MLOG_VERBOSE | MLOG_WARNING, _(
				      "unable to bind "
				      "%s ino %llu %s: %s: discarding\n"),
				      printstr,
				      fhdrp->fh_stat.bs_ino,
				      path,
				      strerror(errno));
				(void)close(sockfd);
				return BOOL_TRUE;
			}
			(void)close(sockfd);

		} else {
			/* create the node
			*/
			rval = mknod(path,
				      (mode_t)bstatp->bs_mode,
				      (dev_t)IRIX_DEV_TO_KDEVT(bstatp->bs_rdev));
			if (rval && rval != EEXIST) {
				mlog(MLOG_VERBOSE | MLOG_WARNING, _(
				      "unable to create %s "
				      "ino %llu %s: %s: discarding\n"),
				      printstr,
				      fhdrp->fh_stat.bs_ino,
				      path,
				      strerror(errno));
				return BOOL_TRUE;
			}
		}

		/* set the owner and group (if enabled)
		 */
		if (persp->a.ownerpr) {
			rval = chown(path,
				      (uid_t)bstatp->bs_uid,
				      (gid_t)bstatp->bs_gid);
			if (rval) {
				mlog(MLOG_VERBOSE | MLOG_WARNING,
				      _("chown (uid=%u, gid=%u) %s "
				      "failed: %s\n"),
				      bstatp->bs_uid,
				      bstatp->bs_gid,
				      path,
				      strerror(errno));
			}
		}

		/* set the permissions/mode
		 */
		rval = chmod(path, (mode_t)fhdrp->fh_stat.bs_mode);
		if (rval) {
			mlog(MLOG_VERBOSE | MLOG_WARNING, _(
			      "unable to set mode of %s: %s\n"),
			      path,
			      strerror(errno));
		}

		/* set the access and modification times
		 */
		utimbuf.actime = (time32_t)bstatp->bs_atime.tv_sec;
		utimbuf.modtime = (time32_t)bstatp->bs_mtime.tv_sec;
		rval = utime(path, &utimbuf);
		if (rval) {
			mlog(MLOG_VERBOSE | MLOG_WARNING, _(
			      "unable to set access and modification "
			      "times of %s: %s\n"),
			      path,
			      strerror(errno));
		}
	}

	return BOOL_TRUE;
}

static bool_t
restore_symlink(drive_t *drivep,
		 filehdr_t *fhdrp,
		 rv_t *rvp,
		 char *path,
		 char *scratchpath,
		 bool_t ehcs)
{
	bstat_t *bstatp = &fhdrp->fh_stat;
	drive_ops_t *dop = drivep->d_opsp;
	extenthdr_t ehdr;
	char *scratch;
	int nread;
	int rval;
	rv_t rv;
	mode_t oldumask;

	if (path) {
		if (!tranp->t_toconlypr) {
			mlog(MLOG_TRACE,
			      "restoring symbolic link ino %llu %s\n",
			      bstatp->bs_ino,
			      path);
		} else {
			mlog(MLOG_NORMAL | MLOG_BARE,
			      "%s\n",
			      path);
		}
	}

	/* read the extent header
	 */
	rv = read_extenthdr(drivep, &ehdr, ehcs);
	if (rv != RV_OK) {
		*rvp = rv;
		return BOOL_FALSE;
	}

	/* symlinks always have one extent
	 */
	assert(ehdr.eh_type == EXTENTHDR_TYPE_DATA);

	/* read the link path extent
	 */
	if (ehdr.eh_sz < (off64_t)(2 * MAXPATHLEN)) {
		scratch = scratchpath;
	} else {
		scratch = 0;
	}
	nread = read_buf(scratch,
			  (size_t)ehdr.eh_sz,
			  (void *)drivep,
			  (rfp_t)dop->do_read,
			  (rrbfp_t)dop->do_return_read_buf,
			  &rval);
	if (rval) {
		switch(rval) {
		case DRIVE_ERROR_EOF:
		case DRIVE_ERROR_EOD:
		case DRIVE_ERROR_EOM:
		case DRIVE_ERROR_MEDIA:
			*rvp = RV_EOD;
			break;
		case DRIVE_ERROR_CORRUPTION:
			*rvp = RV_CORRUPT;
			break;
		case DRIVE_ERROR_DEVICE:
			*rvp = RV_DRIVE;
			break;
		case DRIVE_ERROR_CORE:
		default:
			*rvp = RV_CORE;
		}
		return BOOL_FALSE;
	}
	assert((off64_t)nread == ehdr.eh_sz);
	if (!scratch) {
		if (path) {
			mlog(MLOG_VERBOSE | MLOG_WARNING, _(
			      "unable to create symlink ino %llu "
			      "%s: src too long: discarding\n"),
			      bstatp->bs_ino,
			      path);
		}
		return BOOL_TRUE;
	}
	scratchpath[nread] = 0;
	if (!tranp->t_toconlypr && path) {
		/* create the symbolic link
		 */
		/* NOTE: There is no direct way to set mode for
		 * sym links. Do it using umask.
		 * No way of setting times for sym links.
		 */

		oldumask = umask(((mode_t)(~bstatp->bs_mode)) & 0777);

		rval = symlink(scratchpath, path);

		umask(oldumask);

		if (rval) {
			mlog(MLOG_VERBOSE | MLOG_WARNING, _(
			      "unable to create "
			      "symlink ino %llu %s: %s: discarding\n"),
			      bstatp->bs_ino,
			      path,
			      strerror(errno));
			return BOOL_TRUE;
		}

		/* set the owner and group (if enabled)
		 */
		if (persp->a.ownerpr) {
			rval = lchown(path,
				       (uid_t)bstatp->bs_uid,
				       (gid_t)bstatp->bs_gid);
			if (rval) {
				mlog(MLOG_VERBOSE | MLOG_WARNING,
				      _("chown (uid=%u, gid=%u) %s "
				      "failed: %s\n"),
				      bstatp->bs_uid,
				      bstatp->bs_gid,
				      path,
				      strerror(errno));
			}
		}

		if (persp->a.restoredmpr) {
		fsdmidata_t fssetdm;

		/*	Restore DMAPI fields. */

		fssetdm.fsd_dmevmask = bstatp->bs_dmevmask;
		fssetdm.fsd_padding = 0;
		fssetdm.fsd_dmstate = bstatp->bs_dmstate;
		rval = do_fssetdm_by_handle(path, &fssetdm);
		}
	}

	return BOOL_TRUE;
}

/* ARGSUSED */
static rv_t
read_filehdr(drive_t *drivep, filehdr_t *fhdrp, bool_t fhcs)
{
	bstat_t *bstatp = &fhdrp->fh_stat;
	drive_ops_t *dop = drivep->d_opsp;
	/* REFERENCED */
	int nread;
	int rval;
	filehdr_t tmpfh;

	nread = read_buf((char *)&tmpfh,
			  sizeof(*fhdrp),
			  (void *)drivep,
			  (rfp_t)dop->do_read,
			  (rrbfp_t)dop->do_return_read_buf,
			  &rval);
	xlate_filehdr(&tmpfh, fhdrp, 1);

	switch(rval) {
	case 0:
		break;
	case DRIVE_ERROR_EOD:
	case DRIVE_ERROR_EOF:
	case DRIVE_ERROR_EOM:
	case DRIVE_ERROR_MEDIA:
		return RV_EOD;
	case DRIVE_ERROR_CORRUPTION:
		return RV_CORRUPT;
	case DRIVE_ERROR_DEVICE:
		return RV_DRIVE;
	case DRIVE_ERROR_CORE:
	default:
		return RV_CORE;
	}
	assert((size_t)nread == sizeof(*fhdrp));

	mlog(MLOG_NITTY,
	      "read file hdr off %lld flags 0x%x ino %llu mode 0x%08x\n",
	      fhdrp->fh_offset,
	      fhdrp->fh_flags,
	      bstatp->bs_ino,
	      bstatp->bs_mode);

	if (fhcs) {
		if (!(fhdrp->fh_flags & FILEHDR_FLAGS_CHECKSUM)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "corrupt file header\n"));
			return RV_CORRUPT;
		}
		if (!is_checksum_valid(fhdrp, FILEHDR_SZ)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "bad file header checksum\n"));
			return RV_CORRUPT;
		}
	}

	return RV_OK;
}

/* ARGSUSED */
static rv_t
read_extenthdr(drive_t *drivep, extenthdr_t *ehdrp, bool_t ehcs)
{
	drive_ops_t *dop = drivep->d_opsp;
	/* REFERENCED */
	int nread;
	int rval;
	extenthdr_t tmpeh;

	nread = read_buf((char *)&tmpeh,
			  sizeof(*ehdrp),
			  (void *)drivep,
			  (rfp_t)dop->do_read,
			  (rrbfp_t)dop->do_return_read_buf,
			  &rval);
	xlate_extenthdr(&tmpeh, ehdrp, 1);

	switch(rval) {
	case 0:
		break;
	case DRIVE_ERROR_EOD:
	case DRIVE_ERROR_EOF:
	case DRIVE_ERROR_EOM:
	case DRIVE_ERROR_MEDIA:
		return RV_EOD;
	case DRIVE_ERROR_CORRUPTION:
		return RV_CORRUPT;
	case DRIVE_ERROR_DEVICE:
		return RV_DRIVE;
	case DRIVE_ERROR_CORE:
	default:
		return RV_CORE;
	}
	assert((size_t)nread == sizeof(*ehdrp));

	mlog(MLOG_NITTY,
	      "read extent hdr size %lld offset %lld type %d flags %08x\n",
	      ehdrp->eh_sz,
	      ehdrp->eh_offset,
	      ehdrp->eh_type,
	      ehdrp->eh_flags);

	if (ehcs) {
		if (!(ehdrp->eh_flags & EXTENTHDR_FLAGS_CHECKSUM)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "corrupt extent header\n"));
			return RV_CORRUPT;
		}
		if (!is_checksum_valid(ehdrp, EXTENTHDR_SZ)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "bad extent header checksum\n"));
			return RV_CORRUPT;
		}
	}

	return RV_OK;
}

/* ARGSUSED */
static rv_t
read_dirent(drive_t *drivep,
	     direnthdr_t *dhdrp,
	     size_t direntbufsz,
	     bool_t dhcs)
{
	global_hdr_t *grhdrp = drivep->d_greadhdrp;
	drive_ops_t *dop = drivep->d_opsp;
	/* REFERENCED */
	int nread;
	int rval;
	direnthdr_t tmpdh;
	char *namep;    // beginning of name following the direnthdr_t

	assert(sizeof(direnthdr_t) == DIRENTHDR_SZ);
	assert(sizeof(direnthdr_v1_t) == DIRENTHDR_SZ);

	/* read the head of the dirent
	 */
	nread = read_buf((char *)&tmpdh,
			  DIRENTHDR_SZ,
			  (void *)drivep,
			  (rfp_t)dop->do_read,
			  (rrbfp_t)
			  dop->do_return_read_buf,
			  &rval);
	switch(rval) {
	case 0:
		break;
	case DRIVE_ERROR_EOD:
	case DRIVE_ERROR_EOF:
	case DRIVE_ERROR_EOM:
	case DRIVE_ERROR_MEDIA:
		return RV_EOD;
	case DRIVE_ERROR_CORRUPTION:
		return RV_CORRUPT;
	case DRIVE_ERROR_DEVICE:
		return RV_DRIVE;
	case DRIVE_ERROR_CORE:
	default:
		return RV_CORE;
	}
	assert((size_t)nread == DIRENTHDR_SZ);

	if (grhdrp->gh_version >= GLOBAL_HDR_VERSION_3) {
		xlate_direnthdr(&tmpdh, dhdrp, 1);
		namep = dhdrp->dh_name + sizeof(dhdrp->dh_name);

		if (dhcs && !is_checksum_valid(dhdrp, DIRENTHDR_SZ)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
				"bad directory entry header checksum\n"));
			return RV_CORRUPT;
		}
	} else {
		direnthdr_v1_t dhdr_v1;
		xlate_direnthdr_v1((direnthdr_v1_t *)&tmpdh, &dhdr_v1, 1);
		dhdrp->dh_ino = dhdr_v1.dh_ino;
		dhdrp->dh_gen = BIGGEN2GEN(dhdr_v1.dh_gen);
		dhdrp->dh_checksum = dhdr_v1.dh_checksum;
		dhdrp->dh_sz = dhdr_v1.dh_sz;
		memcpy(dhdrp->dh_name, dhdr_v1.dh_name, sizeof(dhdr_v1.dh_name));
		namep = dhdrp->dh_name + sizeof(dhdr_v1.dh_name);

		if (dhcs && !is_checksum_valid(&dhdr_v1, DIRENTHDR_SZ)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
				"bad directory entry header checksum\n"));
			return RV_CORRUPT;
		}
	}

	mlog(MLOG_NITTY,
	      "read dirent hdr ino %llu gen %u size %u\n",
	      dhdrp->dh_ino,
	      (size_t)dhdrp->dh_gen,
	      (size_t)dhdrp->dh_sz);

	if (dhdrp->dh_sz == 0) {
		mlog(MLOG_NORMAL | MLOG_WARNING, _(
			"corrupt directory entry header\n"));
		return RV_CORRUPT;
	}

	/* if null, return
	 */
	if (dhdrp->dh_ino == 0) {
		assert((size_t)dhdrp->dh_sz == sizeof(direnthdr_t));
		return RV_OK;
	}

	/* read the remainder of the dirent.
	 */
	assert((size_t)dhdrp->dh_sz <= direntbufsz);
	assert((size_t)dhdrp->dh_sz >= sizeof(direnthdr_t));
	assert(!((size_t)dhdrp->dh_sz & (DIRENTHDR_ALIGN - 1)));
	if ((size_t)dhdrp->dh_sz > sizeof(direnthdr_t)) {
		size_t remsz = (size_t)dhdrp->dh_sz - sizeof(direnthdr_t);
		nread = read_buf(namep,
				  remsz,
				  (void *)drivep,
				  (rfp_t)dop->do_read,
				  (rrbfp_t)
				  dop->do_return_read_buf,
				  &rval);
		switch(rval) {
		case 0:
			break;
		case DRIVE_ERROR_EOD:
		case DRIVE_ERROR_EOF:
		case DRIVE_ERROR_EOM:
		case DRIVE_ERROR_MEDIA:
			return RV_EOD;
		case DRIVE_ERROR_CORRUPTION:
			return RV_CORRUPT;
		case DRIVE_ERROR_DEVICE:
			return RV_DRIVE;
		case DRIVE_ERROR_CORE:
		default:
			return RV_CORE;
		}
		assert((size_t) nread == remsz);
	}

	return RV_OK;
}

/* ARGSUSED */
static rv_t
read_extattrhdr(drive_t *drivep, extattrhdr_t *ahdrp, bool_t ahcs)
{
	drive_ops_t *dop = drivep->d_opsp;
	/* REFERENCED */
	int nread;
	int rval;
	extattrhdr_t tmpah;

	nread = read_buf((char *)&tmpah,
			  sizeof(*ahdrp),
			  (void *)drivep,
			  (rfp_t)dop->do_read,
			  (rrbfp_t)dop->do_return_read_buf,
			  &rval);
	xlate_extattrhdr(&tmpah, ahdrp, 1);

	switch(rval) {
	case 0:
		break;
	case DRIVE_ERROR_EOD:
	case DRIVE_ERROR_EOF:
	case DRIVE_ERROR_EOM:
	case DRIVE_ERROR_MEDIA:
		return RV_EOD;
	case DRIVE_ERROR_CORRUPTION:
		return RV_CORRUPT;
	case DRIVE_ERROR_DEVICE:
		return RV_DRIVE;
	case DRIVE_ERROR_CORE:
	default:
		return RV_CORE;
	}
	assert((size_t)nread == sizeof(*ahdrp));

	mlog(MLOG_NITTY,
	      "read extattr hdr sz %u valoff %u flags 0x%x valsz %u cs 0x%x\n",
	      ahdrp->ah_sz,
	      (uint)ahdrp->ah_valoff,
	      (uint)ahdrp->ah_flags,
	      ahdrp->ah_valsz,
	      ahdrp->ah_checksum);

	if (ahcs) {
		if (ahdrp->ah_flags & EXTATTRHDR_FLAGS_CHECKSUM) {
			if (!is_checksum_valid(ahdrp, EXTATTRHDR_SZ)) {
				mlog(MLOG_NORMAL | MLOG_WARNING, _(
					"bad extattr header checksum\n"));
				return RV_CORRUPT;
			}
		} else if (ahdrp->ah_flags & EXTATTRHDR_FLAGS_OLD_CHECKSUM) {
			/* possibly a corrupt header, but most likely an old
			 * header, which cannot be verified due to a bug in how
			 * its checksum was calculated.
			 */
			static bool_t warned = BOOL_FALSE;
			if (!warned) {
				mlog(MLOG_NORMAL | MLOG_WARNING, _(
					"ignoring old-style extattr "
					"header checksums\n"));
				warned = BOOL_TRUE;
			}
		} else {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "corrupt extattr header\n"));
			return RV_CORRUPT;
		}
	}

	return RV_OK;
}

static rv_t
discard_padding(size_t sz, drive_t *drivep)
{
	drive_ops_t *dop = drivep->d_opsp;
	/* REFERENCED */
	int nread;
	int rval;

	nread = read_buf(0,
			  sz,
			  (void *)drivep,
			  (rfp_t)dop->do_read,
			  (rrbfp_t)dop->do_return_read_buf,
			  &rval);
	switch(rval) {
	case 0:
		assert((size_t)nread == sz);
		return RV_OK;
	case DRIVE_ERROR_EOF:
	case DRIVE_ERROR_EOD:
	case DRIVE_ERROR_EOM:
	case DRIVE_ERROR_MEDIA:
		return RV_EOD;
	case DRIVE_ERROR_CORRUPTION:
		return RV_CORRUPT;
	case DRIVE_ERROR_DEVICE:
		return RV_DRIVE;
	case DRIVE_ERROR_CORE:
	default:
		return RV_CORE;
	}
}

static rv_t
restore_extent(filehdr_t *fhdrp,
		extenthdr_t *ehdrp,
		int fd,
		char *path,
		drive_t *drivep,
		off64_t *bytesreadp)
{
	bstat_t *bstatp = &fhdrp->fh_stat;
	drive_ops_t *dop = drivep->d_opsp;
	off64_t off = ehdrp->eh_offset;
	off64_t sz = ehdrp->eh_sz;
	off64_t new_off;
	struct dioattr da;
	bool_t isrealtime = BOOL_FALSE;

	*bytesreadp = 0;

	if (fd != -1) {
		assert(path);
		/* seek to the beginning of the extent.
		 * must be on a basic fs blksz boundary.
		 */
		assert((off & (off64_t)(BBSIZE - 1)) == 0);
		new_off = lseek64(fd, off, SEEK_SET);
		if (new_off < 0) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "attempt to seek %s to %lld failed: %s: "
			      "not restoring extent off %lld sz %lld\n"),
			      path,
			      off,
			      strerror(errno),
			      off,
			      sz);
			fd = -1;
			new_off = off;
		}
		assert(new_off == off);
	}
	if ((fd != -1) && (bstatp->bs_xflags & XFS_XFLAG_REALTIME)) {
		if ((ioctl(fd, XFS_IOC_DIOINFO, &da) < 0)) {
			mlog(MLOG_NORMAL | MLOG_WARNING, _(
			      "dioinfo %s failed: "
			      "%s: discarding ino %llu\n"),
			      path,
			      strerror(errno),
			      fhdrp->fh_stat.bs_ino);
			fd = -1;
		} else
			isrealtime = BOOL_TRUE;
	}

	/* move from media to fs.
	 */
	while (sz) {
		char *bufp;
		size_t req_bufsz;	/* requested bufsz */
		size_t sup_bufsz;	/* supplied bufsz */
		int nwritten;
		int rval;
		size_t ntowrite;

		req_bufsz = (size_t)min((off64_t)INTGENMAX, sz);
		bufp = (*dop->do_read)(drivep, req_bufsz, &sup_bufsz, &rval);
		if (rval) {
			rv_t rv;
			char *reasonstr;
			switch(rval) {
			case DRIVE_ERROR_EOF:
				rv = RV_EOD;
				reasonstr = _("end of media file");
				break;
			case DRIVE_ERROR_EOD:
				rv = RV_EOD;
				reasonstr = _("end of recorded data");
				break;
			case DRIVE_ERROR_EOM:
				rv = RV_EOD;
				reasonstr = _("end of media");
				break;
			case DRIVE_ERROR_MEDIA:
				rv = RV_EOD;
				reasonstr = _("media error or no media");
				break;
			case DRIVE_ERROR_CORRUPTION:
				rv = RV_CORRUPT;
				reasonstr = _("end of media file");
				break;
			case DRIVE_ERROR_DEVICE:
				rv = RV_DRIVE;
				reasonstr = _("end of media file");
				break;
			case DRIVE_ERROR_CORE:
			default:
				rv = RV_CORE;
				reasonstr = _("dumping core");
				break;
			}
			mlog(MLOG_NORMAL, _(
			      "attempt to read %u bytes failed: %s\n"),
			      req_bufsz,
			      reasonstr);
			return rv;
		}
		if (off >= bstatp->bs_size) {
			assert(off == bstatp->bs_size);
			ntowrite = 0;
		} else if ((off64_t)sup_bufsz > bstatp->bs_size - off) {
			ntowrite = (size_t)(bstatp->bs_size - off);
		} else {
			ntowrite = sup_bufsz;
		}
		assert(ntowrite <= (size_t)INTGENMAX);
		if (ntowrite > 0) {
			*bytesreadp += (off64_t)ntowrite;
			if (fd != -1) {
				size_t tries;
				size_t remaining;
				int rval;
				off64_t tmp_off;

				rval = 0; /* for lint */
				for (nwritten = 0,
				      tries = 0,
				      remaining = ntowrite,
				      tmp_off = off
				      ;
				      nwritten < (int)ntowrite
				      &&
				      tries < WRITE_TRIES_MAX
				      ;
				      nwritten += rval,
				      tries++,
				      remaining -= (size_t)rval,
				      tmp_off += (off64_t)rval) {
					int rttrunc = 0;
					int trycnt = 0;
					assert(remaining
						<=
						(size_t)INTGENMAX);
					/*
					 * Realtime files must be written
					 * to the end of the block even if
					 * it has been truncated back.
					 */
					if (isrealtime &&
					    (remaining % da.d_miniosz != 0 ||
					     remaining < da.d_miniosz)) {
						/*
						 * Since the ring and static
						 * buffers from the different
						 * drives are always large, we
						 * just need to write to the
						 * end of the next block
						 * boundry and truncate.
						 */
						rttrunc = remaining;
						remaining += da.d_miniosz -
						   (remaining % da.d_miniosz);
					}
					/*
					 * Do the write. Due to delayed allocation
					 * it's possible to receive false ENOSPC
					 * errors when the filesystem is nearly
					 * full. XFS kernel code tries to avoid
					 * this, but cannot always do so. Catch
					 * ENOSPC and mimic the kernel behavior
					 * by trying to flush the current file
					 * first, then trying a system wide sync
					 * if ENOSPC still occurs.
					 */
					for (trycnt = 0; trycnt < 3; trycnt++) {
						rval = write(fd, bufp, remaining);
						if (rval >= 0 || errno != ENOSPC)
							break;

						(trycnt == 0) ?
							fdatasync(fd) : sync();
					}
					if (rval < 0) {
						nwritten = rval;
						break;
					}
					assert((size_t)rval <= remaining);
					if (rval < remaining) {
						mlog(MLOG_NORMAL | MLOG_WARNING,
						      _("attempt to "
						      "write %u bytes to %s at "
						      "offset %lld failed: "
						      "only %d bytes written\n"),
						      remaining,
						      path,
						      tmp_off,
						      rval);
					}
					if (rttrunc) {
						/* truncate and re-set rval */
						if (rval == remaining)
							rval = rttrunc;
						ftruncate(fd, bstatp->bs_size);
					}
				}
			} else {
				nwritten = (int)ntowrite;
			}
		} else {
			nwritten = 0;
		}
		(*dop->do_return_read_buf)(drivep, bufp, sup_bufsz);
		if ((size_t)nwritten != ntowrite) {
			if (nwritten < 0) {
				mlog(MLOG_NORMAL, _(
				      "attempt to write %u bytes to %s "
				      "at offset %lld failed: %s\n"),
				      ntowrite,
				      path,
				      off,
				      strerror(errno));
			} else {
				assert((size_t)nwritten < ntowrite);
				mlog(MLOG_NORMAL, _(
				      "attempt to write %u bytes to %s at "
				      "offset %lld failed: only %d bytes "
				      "written\n"),
				      ntowrite,
				      path,
				      off,
				      nwritten);
			}
			/* stop attempting to write, but complete reads
			 */
			fd = -1;
			assert(ntowrite <= (size_t)INTGENMAX);
			nwritten = (int)ntowrite;
		}
		sz -= (off64_t)sup_bufsz;
		off += (off64_t)nwritten;
	}

	return RV_OK;
}

static char *extattrbufp = 0; /* ptr to start of all the extattr buffers */
static size_t extattrbufsz = 0; /* size of each extattr buffer */

static bool_t
extattr_init(size_t drivecnt)
{
	assert(!extattrbufp);
	extattrbufsz = EXTATTRHDR_SZ		/* dump hdr */
		       +
		       NAME_MAX			/* attribute name */
		       +
		       1			/* NULL term. of name */
		       +
		       ATTR_MAX_VALUELEN;	/* attribute value */
	extattrbufsz = roundup(extattrbufsz, EXTATTRHDR_ALIGN);

	extattrbufp = memalign(EXTATTRHDR_ALIGN, extattrbufsz * drivecnt);
	if (extattrbufp == NULL) {
		mlog(MLOG_NORMAL | MLOG_ERROR, _(
		      "Failed to allocate extended attribute buffer\n"));
		return BOOL_FALSE;
	}

	return BOOL_TRUE;
}

static char *
get_extattrbuf(ix_t which)
{
        return extattrbufp + (extattrbufsz * which);
}


struct extattr_cb_ctx {
	extattrhdr_t *ecb_ahdrp;
};

typedef struct extattr_cb_ctx extattr_cb_ctx_t;

static rv_t
restore_extattr(drive_t *drivep,
		 filehdr_t *fhdrp,
		 char *path,
		 bool_t ahcs,
		 bool_t isdirpr,
		 bool_t onlydoreadpr,
		 dah_t dah)
{
	drive_ops_t *dop = drivep->d_opsp;
	extattrhdr_t *ahdrp = (extattrhdr_t *)get_extattrbuf(drivep->d_index);
	stream_context_t *strctxp = (stream_context_t *)drivep->d_strmcontextp;
	bstat_t *bstatp = &fhdrp->fh_stat;
	bool_t isfilerestored = BOOL_FALSE;

	assert(extattrbufp);

	if (!isdirpr)
		isfilerestored = partial_check(bstatp->bs_ino,  bstatp->bs_size);

	/* peel off extattrs until null hdr hit
	 */
	for (;;) {
		size_t recsz;
		/* REFERENCED */
		int nread;
		int rval;
		rv_t rv;

		rv = read_extattrhdr(drivep, ahdrp, ahcs);
		if (rv != RV_OK) {
			return rv;
		}

		if (ahdrp->ah_flags & EXTATTRHDR_FLAGS_NULL) {
			return RV_OK;
		}

		recsz = (size_t)ahdrp->ah_sz;
		assert(recsz <= extattrbufsz);
		assert(recsz >= EXTATTRHDR_SZ);
		nread = read_buf((char *)&ahdrp[1],
				  recsz - EXTATTRHDR_SZ,
				  (void *)drivep,
				  (rfp_t)dop->do_read,
				  (rrbfp_t)dop->do_return_read_buf,
				  &rval);
		switch(rval) {
		case 0:
			break;
		case DRIVE_ERROR_EOD:
		case DRIVE_ERROR_EOF:
		case DRIVE_ERROR_EOM:
		case DRIVE_ERROR_MEDIA:
			return RV_EOD;
		case DRIVE_ERROR_CORRUPTION:
			return RV_CORRUPT;
		case DRIVE_ERROR_DEVICE:
			return RV_DRIVE;
		case DRIVE_ERROR_CORE:
		default:
			return RV_CORE;
		}
		assert(nread == (int)(recsz - EXTATTRHDR_SZ));

		if (!persp->a.restoreextattrpr && !persp->a.restoredmpr) {
			continue;
		}

		if (onlydoreadpr || tranp->t_toconlypr)
			continue;

		/* NOTE: In the cases below, if we get errors then we issue warnings
		 * but we do not stop the restoration.
		 * We can still restore the file possibly without the
		 * extended attributes.
		 */
		if (isdirpr) {
			assert(!path);
			if (dah != DAH_NULL) {
				dirattr_addextattr(dah, ahdrp);
			}
		} else if (isfilerestored && path[0] != '\0') {
			setextattr(path, ahdrp);

			if (persp->a.dstdirisxfspr && persp->a.restoredmpr) {
				int flag = 0;
				char *attrname = (char *)&ahdrp[1];
				if (ahdrp->ah_flags & EXTATTRHDR_FLAGS_ROOT)
					flag = ATTR_ROOT;
				else if (ahdrp->ah_flags & EXTATTRHDR_FLAGS_SECURE)
					flag = ATTR_SECURE;

				HsmRestoreAttribute(flag,
						     attrname,
						     &strctxp->sc_hsmflags);
			}
		}
	}
	/* NOTREACHED */
}

static bool_t
restore_dir_extattr_cb(char *path, dah_t dah)
{
        /*
         * directory extattr's are built during the directory phase
         * by 1 thread so we only need one extattr buffer
         * -> we pick the 0th one
         */
	extattrhdr_t *ahdrp = (extattrhdr_t *)get_extattrbuf(0);
	bool_t ok;

	/* ask the dirattr abstraction to call me back for each
	 * extended dirattr associated with this dah.
	 */
	ok = dirattr_cb_extattr(dah,
				 restore_dir_extattr_cb_cb,
				 ahdrp,
				 (void *)path);
	return ok;
}

static bool_t
restore_dir_extattr_cb_cb(extattrhdr_t *ahdrp, void *ctxp)
{
	char *path = (char *)ctxp;

	setextattr(path, ahdrp);

	return BOOL_TRUE;
}

static void
setextattr(char *path, extattrhdr_t *ahdrp)
{
	static	char dmiattr[] = "SGI_DMI_";
	bool_t isrootpr = ahdrp->ah_flags & EXTATTRHDR_FLAGS_ROOT;
	bool_t issecurepr = ahdrp->ah_flags & EXTATTRHDR_FLAGS_SECURE;
	bool_t isdmpr;
	int attr_namespace;
	int rval;

	isdmpr = (isrootpr &&
		   !strncmp((char *)(&ahdrp[1]), dmiattr, sizeof(dmiattr)-1));

	/* If restoreextattrpr not set, then we are here because -D was
	 * specified. So return unless it looks like a root DMAPI attribute.
	 */
	if (!persp->a.restoreextattrpr && !isdmpr)
		return;

	if (isrootpr) {
		attr_namespace = ATTR_ROOT;
	} else if (issecurepr) {
		attr_namespace = ATTR_SECURE;
	} else {
		attr_namespace = 0;
	}

	rval = attr_set(path,
			 (char *)(&ahdrp[1]),
			 ((char *)ahdrp) + (u_long_t)ahdrp->ah_valoff,
			 (int)ahdrp->ah_valsz,
			 attr_namespace | ATTR_DONTFOLLOW);
	if (rval) {
		char *namespace;
		if (isrootpr) {
			namespace = _("root");
		} else if (issecurepr) {
			namespace = _("secure");
		} else {
			namespace = _("non-root");
		}

		mlog(MLOG_VERBOSE | MLOG_WARNING, _(
		      "unable to set %s extended attribute for %s: "
		      "%s (%d)\n"),
		      namespace,
		      path,
		      strerror(errno),
		      errno);
	}
}

#ifdef DEBUGPARTIALS
/*
 * Debug code to view the partials in the partial register
 */
void
dump_partials(void)
{
	partial_rest_t *isptr = NULL;
	bytespan_t *bsptr = NULL;
	int i;

	pi_lock();
	printf("\npartial_reg: count=%d\n", (int)persp->a.parrestcnt);
	if (persp->a.parrestcnt > 0) {
		for (i=0; i < partialmax; i++) {
			if (persp->a.parrest[i].is_ino > 0) {
				int j;

				isptr = &persp->a.parrest[i];
				printf("\tino=%llu ",
				       (unsigned long long)isptr->is_ino);
				for (j=0, bsptr=isptr->is_bs;
				     j < drivecnt;
				     j++, bsptr++)
				{
					if (bsptr->endoffset > 0) {
						printf("%d:%lld-%lld ",
						   j, (long long)bsptr->offset,
						   (long long)bsptr->endoffset);
					}
				}
				printf("\n");
			}
		}
	}
	printf("\n");
	pi_unlock();
}


/* There can only be at most 2 partials for a given stream.
 * An unfinished one from a split and the current one from
 * a multiple group extent or another split.
 * If there are more than 2, then there is an internal error.
 */
void
check_valid_partials(void)
{
	int *num_partials; /* array for sum of partials for a given drive */
	partial_rest_t *isptr = NULL;
	bytespan_t *bsptr = NULL;
	int i;

	/* zero the sums for each stream */
	num_partials = calloc(drivecnt, sizeof(int));
	if (!num_partials) {
		perror("num_partials array allocation");
		return;
	}

	pi_lock();
	if (persp->a.parrestcnt > 0) {
		for (i=0; i < partialmax; i++) {
			if (persp->a.parrest[i].is_ino > 0) {
				int j;

				isptr = &persp->a.parrest[i];
				for (j=0, bsptr=isptr->is_bs;
				     j < drivecnt;
				     j++, bsptr++)
				{
					if (bsptr->endoffset > 0) {
					    num_partials[j]++;
					    if (num_partials[j] > 2) {
						pi_unlock();
						mlog(MLOG_NORMAL | MLOG_WARNING,
		  "partial_reg: Too many partials (>2) for drive: %d\n", j);
						dump_partials();
						exit(EXIT_ERROR);
					    }
					}
				}
			}
		}
	}
	pi_unlock();
	free(num_partials);
}
#endif

/* partial_reg - Registers files that are only partially restored by
 * a dump stream into the persistent state.
 *
 * This is done because DMAPI extended attributes must not be set until
 * the entire file has been restored in order to co-ordinate with the
 * Data Migration Facility (DMF) daemons.  Since extended attributes are
 * recorded with each extent group in the dump, this registry is used to
 * make sure only the final dump stream applies the extended attributes.
 *
 * Likewise, certain extended inode flags (e.g. XFS_XFLAG_IMMUTABLE)
 * should only be set after all data for a file has been restored.
 */
static void
partial_reg(ix_t d_index,
	     xfs_ino_t ino,
	     off64_t fsize,
	     off64_t offset,
	     off64_t sz)
{
	off64_t	endoffset;
	partial_rest_t *isptr = NULL;
	bytespan_t *bsptr = NULL;
	int i;

	mlog(MLOG_NITTY, "partial_reg: d_index = %d, ino = %llu, "
                           "fsize = %lld, offset = %lld, sz = %lld\n",
                           d_index, ino, fsize, offset, sz);

	endoffset = offset + sz;

	if (partialmax == 0)
		return;

	pi_lock();

	/* Search for a matching inode.  Gaps can exist so we must search
	 * all entries.
	 */
	for (i=0; i < partialmax; i++) {
		if (persp->a.parrest[i].is_ino == ino) {
			isptr = &persp->a.parrest[i];
			break;
		}
	}

	/* If not found, find a free one, fill it in and return */
	if (!isptr) {
		mlog(MLOG_NITTY | MLOG_NOLOCK,
			"partial_reg: no entry found for %llu\n", ino);
		/* find a free one */
		for (i=0; i < partialmax; i++) {
			if (persp->a.parrest[i].is_ino == 0) {
				int j;

				isptr = &persp->a.parrest[i];
				isptr->is_ino = ino;
				persp->a.parrestcnt++;

				/* Clear all endoffsets (this value is
				 * used to decide if an entry is used or
				 * not
				 */
				for (j=0, bsptr=isptr->is_bs;
				     j < drivecnt; j++, bsptr++) {
				     bsptr->endoffset = 0;
				}

				goto found;
			}
		}

		/* Should never get here. */
		pi_unlock();
		mlog(MLOG_NORMAL | MLOG_WARNING, _(
		  "partial_reg: Out of records. Extend attrs applied early.\n"));
#ifdef DEBUGPARTIALS
		dump_partials();
#endif
		return;
	}

found:
	/* Update this drive's entry */
	bsptr = &isptr->is_bs[d_index];
	if (bsptr->endoffset == 0) {
		/* no existing entry for this drive, fill in the values */
		bsptr->offset = offset;
		bsptr->endoffset = endoffset;
		mlog(MLOG_NITTY | MLOG_NOLOCK,
			"partial_reg: update entry [%d]: "
			"<off = %lld, end = %lld>\n",
			d_index, offset, endoffset);
	} else {
		bool_t ret;

		/* entry exists for this drive, just extend the endoffset, the
		 * records will be sequential for any given drive.
		 */
		bsptr->endoffset = endoffset;
		ret = partial_check2(isptr, fsize);
		mlog(MLOG_NITTY | MLOG_NOLOCK,
			"partial_reg: extend entry [%d]: <end = %lld>\n",
			d_index, endoffset);
		mlog(MLOG_NITTY | MLOG_NOLOCK,
			"partial_reg: partial_check returns: %d\n", ret);
	}

	pi_unlock();

#ifdef DEBUGPARTIALS
	check_valid_partials();
	dump_partials();
#endif
}


/* Checks the registry of files that are only partially restored by
 * any given dump stream to see if the remainder of the file has
 * been restored by another dump stream.
 */
static bool_t
partial_check (xfs_ino_t ino, off64_t fsize)
{
	partial_rest_t *isptr = NULL;
	bool_t ret;
	int i;

	if (partialmax == 0)
		return BOOL_TRUE;

	pi_lock();

	/* Check if no files are listed in the sync area */
	if (persp->a.parrestcnt == 0) {
		pi_unlock();
		return BOOL_TRUE;
	}

	/* Search for the inode.  Gaps can exist so we must search
	 * all entries.
	 */
	for (i=0; i < partialmax; i++) {
		if (persp->a.parrest[i].is_ino == ino) {
			isptr = &persp->a.parrest[i];
			break;
		}
	}

	/* If not found, return okay */
	if (!isptr) {
		pi_unlock();
		return BOOL_TRUE;
	}

	ret = partial_check2(isptr, fsize);

	pi_unlock();

#ifdef DEBUGPARTIALS
	check_valid_partials();
	dump_partials();
#endif

	return ret;
}

/*
 * Checks the given parrest entry to see if the file has
 * been completely restored.
 * Always invoked with the persistent inventory locked (pi_lock)
 */
static bool_t
partial_check2(partial_rest_t *isptr, off64_t fsize)
{
	bytespan_t *bsptr = NULL;
	off64_t curoffset = 0;
	int i;

gapsearch:
	/* Search the entire set of bytespan records to see if the next
	 * span has been restored.  Bytespans are not necessarily in order
	 * so the search is repeated from the start each time.
	 */
	for (i=0, bsptr=isptr->is_bs; i < drivecnt; i++, bsptr++) {
		if (bsptr->endoffset > 0 &&
		    bsptr->offset <= curoffset &&
		    bsptr->endoffset > curoffset)
		{
			curoffset = bsptr->endoffset;
			goto gapsearch;
		}
	}

	/* Check if all bytes are accounted for.  */
	if (curoffset >= fsize) {
		isptr->is_ino = 0;  /* clear the entry */
		persp->a.parrestcnt--;
		return BOOL_TRUE;
	} else {
		return BOOL_FALSE;
	}
}

static char *
ehdr_typestr(int32_t type)
{
	switch (type) {
	case EXTENTHDR_TYPE_LAST:
		return "LAST";
	case EXTENTHDR_TYPE_ALIGN:
		return "ALIGN";
	case EXTENTHDR_TYPE_DATA:
		return "DATA";
	case EXTENTHDR_TYPE_HOLE:
		return "HOLE";
	default:
		return "?";
	}
}

/* ARGSUSED */
bool_t
content_overwrite_ok(char *path,
		      int32_t ctime,
		      int32_t mtime,
		      char **reasonstrp,
		      bool_t *exists)
{
	struct stat statbuf;

	*exists = BOOL_TRUE;

	/* if file doesn't exist, allow
	 */

	if (lstat(path, &statbuf)) {
		*reasonstrp = 0;
		if (errno == ENOENT) {
			*exists = BOOL_FALSE;
		}
		return BOOL_TRUE;
	}

	/* if overwrites absolutely inhibited, disallow
	 */
	if (persp->a.existpr) {
		*reasonstrp = _("overwrites inhibited");
		return BOOL_FALSE;
	}

	/* if newer time specified, compare
	 */
	if (persp->a.newerpr) {
		if ((time32_t)ctime < persp->a.newertime) {
			*reasonstrp = _("too old");
			return BOOL_FALSE;
		}
	}

	/* don't overwrite changed files
	 */
	if (persp->a.changepr) {
		if (statbuf.st_ctime >= (time32_t)ctime) {
			*reasonstrp = _("existing version is newer");
			return BOOL_FALSE;
		}
	}

	*reasonstrp = 0;
	return BOOL_TRUE;
}


static void
set_mcflag(ix_t thrdix)
{
	lock();
	mcflag[thrdix] = BOOL_TRUE;
	content_media_change_needed = BOOL_TRUE;
	unlock();
}

static void
clr_mcflag(ix_t thrdix)
{
	lock();
	mcflag[thrdix] = BOOL_FALSE;
	for (thrdix = 0; thrdix < drivecnt; thrdix++) {
		if (mcflag[thrdix]) {
			unlock();
			return;
		}
	}
	content_media_change_needed = BOOL_FALSE;
	unlock();
}

/* debug functions ***********************************************************/

static void
pi_show(char *introstring)
{
	char strbuf[100];
	/* REFERENCED */
	int strbuflen;
	fold_t fold;

	if (mlog_level_ss[MLOG_SS_MEDIA] < MLOG_NITTY + 1) {
		return;
	}

	mlog_lock();

	strbuflen = sprintf(strbuf,
			     "persistent inventory media file tree%s",
			     introstring);
	assert((size_t)strbuflen < sizeof(strbuf));
	fold_init(fold, strbuf, ':');
	mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
	      "\n%s\n\n",
	      fold);

	pi_show_nomloglock();

	fold_init(fold, "end persistent inventory display", '.');
	mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
	      "\n%s\n\n",
	      fold);

	mlog_unlock();
}

static void
pi_show_nomloglock(void)
{
	dh_t strmh;
	int strmix;


	/* no point in proceeding if pi not begun
	 */
	if (persp->s.strmheadh == DH_NULL) {
		mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA, _(
		      "session inventory unknown\n"));
		return;
	}

	mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA, _(
	      "session inventory display\n"));

	/* iterate over all streams
	 */
	for (strmh = persp->s.strmheadh, strmix = 0
	      ;
	      strmh != DH_NULL
	      ;
	      strmh = DH2S(strmh)->s_nexth, strmix++) {
		dh_t objh;
		int objix;

		mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
		      _("\nmedia stream %u:\n"),
		      strmix);
		if (DH2S(strmh)->s_cldh == DH_NULL) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
			      _("\n    media objects not yet identified\n"));
			continue;
		}
		/* iterate over all objects
		 */
		for (objh = DH2S(strmh)->s_cldh, objix = 0
		      ;
		      objh != DH_NULL
		      ;
		      objh = DH2O(objh)->o_nexth, objix++) {
			dh_t fileh;
			ix_t fileix;

			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
			      _("\n    media object %u:\n\n"),
			      objix);
			if (DH2O(objh)->o_idlabvalpr) {
				if (strlen(DH2O(objh)->o_lab)) {
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("    label: "));
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					"\"%s\"\n",
				      DH2O(objh)->o_lab);
				} else {
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("    label is blank\n"));
				}
				if (!uuid_is_null(DH2O(objh)->o_id)) {
				    char media_string_uuid[UUID_STR_LEN + 1];
				    uuid_unparse(DH2O(objh)->o_id,
						    media_string_uuid);
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("    id: %s\n"),
					  media_string_uuid);
				}
			} else {
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("    label not identified\n"));
			}
			if (DH2O(objh)->o_fmfmixvalpr) {
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("    index within object "
				      "of first media file: %u\n"),
				      DH2O(objh)->o_fmfmix);
			}
			if (DH2O(objh)->o_fmfsixvalpr) {
				mlog(MLOG_DEBUG | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("    index within stream "
				      "of first media file: %u\n"),
				      DH2O(objh)->o_fmfsix);
			}

			if (DH2O(objh)->o_indrivepr) {
				if (drivecnt > 1) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("    now in drive %u\n"),
					  DH2O(objh)->o_indriveix);
				} else {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("    now in drive\n"));
				}
			}

			if (DH2O(objh)->o_cldh == DH_NULL) {
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("        media files not yet "
				      "identified\n"));
				continue;
			}

			/* iterate over all files
			 */
			for (fileh = DH2O(objh)->o_cldh, fileix = 0
			      ;
			      fileh != DH_NULL
			      ;
			      fileh = DH2F(fileh)->f_nexth, fileix++) {
			    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				  _("\n        media file %u"),
				  fileix);
			    if (DH2O(objh)->o_fmfmixvalpr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  " (%u):\n",
					  DH2O(objh)->o_fmfmix + fileix);
			    } else {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  ":\n");
			    }
			    if (DH2F(fileh)->f_szvalpr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					 _("        size: "
					 "%lld bytes\n"),
					 DH2F(fileh)->f_sz);
			    }
			    if (DH2F(fileh)->f_dirtriedpr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					 _("        used for directory "
					 "restoral\n"));
			    }
			    if (DH2F(fileh)->f_valpr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					 _("        first extent contained: "
					 "ino %llu off %lld\n"),
					 DH2F(fileh)->f_firstegrp.eg_ino,
					 DH2F(fileh)->f_firstegrp.eg_off);
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					 _("        next extent to restore: "
					 "ino %llu off %lld\n"),
					 DH2F(fileh)->f_curegrp.eg_ino,
					 DH2F(fileh)->f_curegrp.eg_off);
				    mlog(MLOG_DEBUG | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					 _("        rollback mark %lld\n"),
					 DH2F(fileh)->f_curmark);
			    }
			    if (DH2F(fileh)->f_nondirskippr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("        contains no selected "
					  "non-directories\n"));
			    }
			    if (DH2F(fileh)->f_nondirdonepr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("        non-directories done\n"));
			    }
			    if (DH2F(fileh)->f_flags & PF_INV) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("        contains session "
					  "inventory\n"));
			    }
			    if (DH2F(fileh)->f_flags & PF_TERM) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("        is stream terminator\n"));
			    }
			    if (DH2F(fileh)->f_underheadpr) {
				    mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
					  _("        now reading\n"));
			    }
			}
			if (!DH2O(objh)->o_lmfknwnpr) {
				mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
				      _("\n        may be additional "
				      "unidentified media files\n"));
			}
		}
		if (!DH2S(strmh)->s_lastobjknwnpr) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK | MLOG_MEDIA,
			      _("\n    may be "
			      "additional unidentified media objects\n\n"));
		}
	}
}

static int
egrpcmp(egrp_t *egrpap, egrp_t *egrpbp)
{
	if (egrpap->eg_ino < egrpbp->eg_ino) {
		return -1;
	} else if (egrpap->eg_ino > egrpbp->eg_ino) {
		return 1;
	} else if (egrpap->eg_off < egrpbp->eg_off) {
		return -1;
	} else if (egrpap->eg_off > egrpbp->eg_off) {
		return 1;
	} else {
		return 0;
	}
}

static void
display_dump_label(bool_t lockpr,
		    int mllevel,
		    char *introstr,
		    global_hdr_t *grhdrp,
		    media_hdr_t *mrhdrp,
		    content_hdr_t *crhdrp,
		    content_inode_hdr_t *scrhdrp)
{
	char dateline[28];
	char level_string[2];
	char dump_string_uuid[UUID_STR_LEN + 1];
	char media_string_uuid[UUID_STR_LEN + 1];
	char fs_string_uuid[UUID_STR_LEN + 1];

	assert(scrhdrp->cih_level >= 0);
	assert(scrhdrp->cih_level < 10);
	level_string[0] = (char)('0' + (u_char_t)scrhdrp->cih_level);
	level_string[1] = 0;

	uuid_unparse(grhdrp->gh_dumpid, dump_string_uuid);
	uuid_unparse(mrhdrp->mh_mediaid, media_string_uuid);
	uuid_unparse(crhdrp->ch_fsid, fs_string_uuid);

	if (lockpr) {
		mlog_lock();
	}

	mlog(mllevel | MLOG_NOLOCK,
	      "%s",
	      introstr);
	mlog(mllevel | MLOG_NOLOCK,
	      _("hostname: %s\n"),
	      grhdrp->gh_hostname);
	mlog(mllevel | MLOG_NOLOCK,
	      _("mount point: %s\n"),
	      crhdrp->ch_mntpnt);
	mlog(mllevel | MLOG_NOLOCK,
	      _("volume: %s\n"),
	      crhdrp->ch_fsdevice);
	mlog(mllevel | MLOG_NOLOCK,
	      _("session time: %s"),
	      ctime32_r(&grhdrp->gh_timestamp, dateline));
	mlog(mllevel | MLOG_NOLOCK,
	      _("level: %s%s\n"),
	      level_string,
	      (scrhdrp->cih_dumpattr & CIH_DUMPATTR_RESUME)
	      ?
	      _(" resumed")
	      :
	      "");
	mlog(mllevel | MLOG_NOLOCK,
	      _("session label: "));
	mlog(mllevel | MLOG_NOLOCK | MLOG_BARE,
	      "\"%s\"\n",
	      grhdrp->gh_dumplabel);
	mlog(mllevel | MLOG_NOLOCK,
	      _("media label: "));
	mlog(mllevel | MLOG_NOLOCK | MLOG_BARE,
	      "\"%s\"\n",
	      mrhdrp->mh_medialabel);
	mlog(mllevel | MLOG_NOLOCK,
	      _("file system id: %s\n"),
	      fs_string_uuid);
	mlog(mllevel | MLOG_NOLOCK,
	      _("session id: %s\n"),
	      dump_string_uuid);
	mlog(mllevel | MLOG_NOLOCK,
	      _("media id: %s\n"),
	      media_string_uuid);

	if (lockpr) {
		mlog_unlock();
	}
}

static void
display_needed_objects(purp_t purp,
			bag_t *bagp,
			bool_t knownholespr,
			bool_t maybeholespr)
{
	if (bagp) {
		ix_t ix;
		bagiter_t iter;
		bagobj_t *bagobjp;
		if (purp == PURP_DIR) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK, _(
			      "the following media objects "
			      "contain media files not yet tried "
			      "for directory hierarchy restoral:\n"));
		}
		if (purp == PURP_NONDIR) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK, _(
			      "the following media objects "
			      "are needed:\n"));
		}
		bagiter_init(bagp, &iter);
		bagobjp = 0; /* keep lint happy */
		ix = 0;
		while (bagiter_next(&iter,
				      (void **)&bagobjp)) {
			char uuidstr[UUID_STR_LEN + 1];
			uuid_unparse(bagobjp->id, uuidstr);
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      "\n");
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      _("%2u. label: "),
			      ix);
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      "\"%s\"\n",
			      bagobjp->label);
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      _("    id: "));
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      "\"%s\"\n",
			      uuidstr);
			if (bagobjp->indrivepr) {
				if (drivecnt > 1) {
					mlog(MLOG_NORMAL
					      |
					      MLOG_BARE
					      |
					      MLOG_NOLOCK,
					      _("    now in drive %u\n"),
					      bagobjp->indriveix);
				} else {
					mlog(MLOG_NORMAL
					      |
					      MLOG_BARE
					      |
					      MLOG_NOLOCK,
					      _("    now in drive\n"));
				}
			}
			ix++;
			bagobjp = 0; /* keep lint happy */
		}
	}
	if (knownholespr) {
		if (purp == PURP_DIR) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      bagp ?
			      _("\nthere are additional unidentified media "
			      "objects containing media files not yet tried "
			      "for directory hierarchy restoral:\n")
				:
			      _("\nthere are unidentified media "
			      "objects containing media files not yet tried "
			      "for directory hierarchy restoral:\n"));
		}
		if (purp == PURP_NONDIR) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      bagp ?
			      _("\nthere are additional unidentified media "
			      "objects not yet fully restored\n")
				:
			      _("\nthere are unidentified media objects "
			      "not yet fully restored\n"));
		}
	} else if (maybeholespr) {
		if (purp == PURP_DIR) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      bagp ?
			      _("\nthere may be additional unidentified media "
			      "objects containing media files not yet tried "
			      "for directory hierarchy restoral:\n")
				:
			      _("\nthere may be unidentified media "
			      "objects containing media files not yet tried "
			      "for directory hierarchy restoral:\n"));

		}
		if (purp == PURP_NONDIR) {
			mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
			      bagp ?
			      _("\nthere may be additional unidentified media "
			      "objects not yet fully restored\n")
				:
			      _("\there may be unidentified media "
			      "objects not yet fully restored\n"));
		}
	}

	if (!bagp && !knownholespr && !maybeholespr) {
		mlog(MLOG_NORMAL | MLOG_BARE | MLOG_NOLOCK,
		      _("no additional media objects needed\n"));
	}
}

static int
do_fssetdm_by_handle(
	char		*path,
	fsdmidata_t	*fdmp)
{
	void		*hanp;
	size_t		hlen=0;
	int		rc;

	if (path_to_handle(path, &hanp, &hlen)) {
		mlog(MLOG_NORMAL | MLOG_WARNING, _(
			"path_to_handle of %s failed:%s\n"),
			path, strerror(errno));
		return -1;
	}

	rc = fssetdm_by_handle(hanp, hlen, fdmp);
	free_handle(hanp, hlen);
	if (rc) {
		mlog(MLOG_NORMAL | MLOG_WARNING, _(
			"fssetdm_by_handle of %s failed %s\n"),
			path, strerror(errno));
	}
	return rc;
}

static int
quotafilecheck(char *type, char *dstdir, char *quotafile)
{
	struct stat s;
	char buf[MAXPATHLEN];

	sprintf(buf,
		 "%s/%s",
		 dstdir,
		 quotafile);

	if (stat (buf, &s) >= 0 && S_ISREG(s.st_mode)) {
		mlog(MLOG_NORMAL, _(
		      "%s quota information written to '%s'\n"),
		      type,
		      buf);
		return 1;
	}

	return 0;
}