summaryrefslogtreecommitdiff
path: root/src/VBox/VMM/SSM.cpp
blob: 9a89fd6c6b6edcd0c8dc26daba49c621c7203f46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
/* $Id: SSM.cpp $ */
/** @file
 * SSM - Saved State Manager.
 */

/*
 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 USA or visit http://www.sun.com if you need
 * additional information or have any questions.
 */


/** @page pg_ssm        SSM - The Saved State Manager
 *
 * The Saved State Manager (SSM) implements facilities for saving and loading a
 * VM state in a structural manner using callbacks for each collection of data
 * which needs saving.
 *
 * At init time each of the VMM components, Devices, Drivers and one or two
 * other things will register data entities which they need to save and restore.
 * Each entity have a unique name (ascii), instance number, and a set of
 * callbacks associated with it.  The name will be used to identify the entity
 * during restore.  The callbacks are for the two operations, save and restore.
 * There are three callbacks for each of the two - a prepare, a execute and a
 * complete - giving each component ample opportunity to perform actions both
 * before and afterwards.
 *
 * The SSM provides a number of APIs for encoding and decoding the data.
 *
 * @see grp_ssm
 *
 *
 * @section sec_ssm_future  Future Changes
 *
 * There are plans to extend SSM to make it easier to be both backwards and
 * (somewhat) forwards compatible.  One of the new features will be being able
 * to classify units and data items as unimportant.  Another potentail feature
 * is naming data items, perhaps by extending the SSMR3PutStruct API.
 *
 */


/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_SSM
#include <VBox/ssm.h>
#include <VBox/dbgf.h>
#include <VBox/mm.h>
#include "SSMInternal.h"
#include <VBox/vm.h>
#include <VBox/err.h>
#include <VBox/log.h>
#include <VBox/version.h>

#include <iprt/assert.h>
#include <iprt/file.h>
#include <iprt/alloc.h>
#include <iprt/uuid.h>
#include <iprt/zip.h>
#include <iprt/crc32.h>
#include <iprt/thread.h>
#include <iprt/string.h>


/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/
/** Saved state file magic base string. */
#define SSMFILEHDR_MAGIC_BASE   "\177VirtualBox SavedState "
/** Saved state file v1.0 magic. */
#define SSMFILEHDR_MAGIC_V1_0   "\177VirtualBox SavedState V1.0\n"
/** Saved state file v1.1 magic. */
#define SSMFILEHDR_MAGIC_V1_1   "\177VirtualBox SavedState V1.1\n"
/** Saved state file v1.2 magic. */
#define SSMFILEHDR_MAGIC_V1_2   "\177VirtualBox SavedState V1.2\n\0\0\0"

/** Data unit magic. */
#define SSMFILEUNITHDR_MAGIC    "\nUnit\n"
/** Data end marker magic. */
#define SSMFILEUNITHDR_END      "\nTheEnd"

/** Start structure magic. (Isacc Asimov) */
#define SSMR3STRUCT_BEGIN       0x19200102
/** End structure magic. (Isacc Asimov) */
#define SSMR3STRUCT_END         0x19920406


/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/** SSM state. */
typedef enum SSMSTATE
{
    SSMSTATE_INVALID = 0,
    SSMSTATE_SAVE_PREP,
    SSMSTATE_SAVE_EXEC,
    SSMSTATE_SAVE_DONE,
    SSMSTATE_LOAD_PREP,
    SSMSTATE_LOAD_EXEC,
    SSMSTATE_LOAD_DONE,
    SSMSTATE_OPEN_READ
} SSMSTATE;


/**
 * Handle structure.
 */
typedef struct SSMHANDLE
{
    /** The file handle. */
    RTFILE          File;
    /** The VM handle. */
    PVM             pVM;
    /** The size of the file header.
     * Because the file header was incorrectly aligned there we've ended up with
     * differences between the 64-bit and 32-bit file header. */
    size_t          cbFileHdr;
    /** The current operation. */
    SSMSTATE        enmOp;
    /** What to do after save completes. (move the enum) */
    SSMAFTER        enmAfter;
    /** The current rc of the save operation. */
    int             rc;
    /** The compressor of the current data unit. */
    PRTZIPCOMP      pZipComp;
    /** The decompressor of the current data unit. */
    PRTZIPDECOMP    pZipDecomp;
    /** Number of compressed bytes left in the current data unit. */
    uint64_t        cbUnitLeft;
    /** The current uncompressed offset into the data unit. */
    uint64_t        offUnit;

    /** Pointer to the progress callback function. */
    PFNVMPROGRESS   pfnProgress;
    /** User specified arguemnt to the callback function. */
    void           *pvUser;
    /** Next completion percentage. (corresponds to offEstProgress) */
    unsigned        uPercent;
    /** The position of the next progress callback in the estimated file. */
    uint64_t        offEstProgress;
    /** The estimated total byte count.
     * (Only valid after the prep.) */
    uint64_t        cbEstTotal;
    /** Current position in the estimated file. */
    uint64_t        offEst;
    /** End of current unit in the estimated file. */
    uint64_t        offEstUnitEnd;
    /** the amount of % we reserve for the 'prepare' phase */
    unsigned        uPercentPrepare;
    /** the amount of % we reserve for the 'done' stage */
    unsigned        uPercentDone;

    /** RTGCPHYS size in bytes. (Only applicable when loading/reading.) */
    unsigned        cbGCPhys;
    /** RTGCPTR size in bytes. (Only applicable when loading/reading.) */
    unsigned        cbGCPtr;
    /** Whether cbGCPtr is fixed or settable. */
    bool            fFixedGCPtrSize;
} SSMHANDLE;


/**
 * Header of the saved state file.
 *
 * @remarks This is a superset of SSMFILEHDRV11.
 */
typedef struct SSMFILEHDR
{
    /** Magic string which identifies this file as a version of VBox saved state
     *  file format (SSMFILEHDR_MAGIC_V1_2). */
    char            achMagic[32];
    /** The size of this file. Used to check
     * whether the save completed and that things are fine otherwise. */
    uint64_t        cbFile;
    /** File checksum. The actual calculation skips past the u32CRC field. */
    uint32_t        u32CRC;
    /** Padding. */
    uint32_t        u32Reserved;
    /** The machine UUID. (Ignored if NIL.) */
    RTUUID          MachineUuid;

    /** The major version number. */
    uint16_t        u16VerMajor;
    /** The minor version number. */
    uint16_t        u16VerMinor;
    /** The build number. */
    uint32_t        u32VerBuild;
    /** The SVN revision. */
    uint32_t        u32SvnRev;

    /** 32 or 64 depending on the host. */
    uint8_t         cHostBits;
    /** The size of RTGCPHYS. */
    uint8_t         cbGCPhys;
    /** The size of RTGCPTR. */
    uint8_t         cbGCPtr;
    /** Padding. */
    uint8_t         au8Reserved;
} SSMFILEHDR;
AssertCompileSize(SSMFILEHDR, 64+16);
AssertCompileMemberSize(SSMFILEHDR, achMagic, sizeof(SSMFILEHDR_MAGIC_V1_2));
/** Pointer to a saved state file header. */
typedef SSMFILEHDR *PSSMFILEHDR;


/**
 * Header of the saved state file, version 1.1.
 */
typedef struct SSMFILEHDRV11
{
    /** Magic string which identifies this file as a version of VBox saved state
     *  file format (SSMFILEHDR_MAGIC_V1_1). */
    char            achMagic[32];
    /** The size of this file. Used to check
     * whether the save completed and that things are fine otherwise. */
    uint64_t        cbFile;
    /** File checksum. The actual calculation skips past the u32CRC field. */
    uint32_t        u32CRC;
    /** Padding. */
    uint32_t        u32Reserved;
    /** The machine UUID. (Ignored if NIL.) */
    RTUUID          MachineUuid;
} SSMFILEHDRV11;
AssertCompileSize(SSMFILEHDRV11, 64);
/** Pointer to a saved state file header. */
typedef SSMFILEHDRV11 *PSSMFILEHDRV11;


/**
 * The x86 edition of the 1.0 header.
 */
#pragma pack(1) /* darn, MachineUuid got missaligned! */
typedef struct SSMFILEHDRV10X86
{
    /** Magic string which identifies this file as a version of VBox saved state
     * file format (SSMFILEHDR_MAGIC_V1_0). */
    char            achMagic[32];
    /** The size of this file. Used to check
     * whether the save completed and that things are fine otherwise. */
    uint64_t        cbFile;
    /** File checksum. The actual calculation skips past the u32CRC field. */
    uint32_t        u32CRC;
    /** The machine UUID. (Ignored if NIL.) */
    RTUUID          MachineUuid;
} SSMFILEHDRV10X86;
#pragma pack()
/** Pointer to a SSMFILEHDRV10X86. */
typedef SSMFILEHDRV10X86 *PSSMFILEHDRV10X86;

/**
 * The amd64 edition of the 1.0 header.
 */
typedef SSMFILEHDR SSMFILEHDRV10AMD64;
/** Pointer to SSMFILEHDRV10AMD64. */
typedef SSMFILEHDRV10AMD64 *PSSMFILEHDRV10AMD64;


/**
 * Data unit header.
 */
typedef struct SSMFILEUNITHDR
{
    /** Magic (SSMFILEUNITHDR_MAGIC or SSMFILEUNITHDR_END). */
    char            achMagic[8];
    /** Number of bytes in this data unit including the header. */
    uint64_t        cbUnit;
    /** @todo Add uncompressed byte count as well. */
    /** Data version. */
    uint32_t        u32Version;
    /** Instance number. */
    uint32_t        u32Instance;
    /** Size of the data unit name including the terminator. (bytes) */
    uint32_t        cchName;
    /** Data unit name. */
    char            szName[1];
} SSMFILEUNITHDR;
/** Pointer to SSMFILEUNITHDR.  */
typedef SSMFILEUNITHDR *PSSMFILEUNITHDR;


/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static int                  ssmR3LazyInit(PVM pVM);
static DECLCALLBACK(int)    ssmR3SelfSaveExec(PVM pVM, PSSMHANDLE pSSM);
static DECLCALLBACK(int)    ssmR3SelfLoadExec(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
static int                  ssmR3Register(PVM pVM, const char *pszName, uint32_t u32Instance, uint32_t u32Version, size_t cbGuess, const char *pszBefore, PSSMUNIT *ppUnit);
static int                  ssmR3CalcChecksum(RTFILE File, uint64_t cbFile, uint32_t *pu32CRC);
static void                 ssmR3Progress(PSSMHANDLE pSSM, uint64_t cbAdvance);
static int                  ssmR3Validate(RTFILE File, PSSMFILEHDR pHdr, size_t *pcbFileHdr);
static PSSMUNIT             ssmR3Find(PVM pVM, const char *pszName, uint32_t u32Instance);
static int                  ssmR3WriteFinish(PSSMHANDLE pSSM);
static int                  ssmR3Write(PSSMHANDLE pSSM, const void *pvBuf, size_t cbBuf);
static DECLCALLBACK(int)    ssmR3WriteOut(void *pvSSM, const void *pvBuf, size_t cbBuf);
static void                 ssmR3ReadFinish(PSSMHANDLE pSSM);
static int                  ssmR3Read(PSSMHANDLE pSSM, void *pvBuf, size_t cbBuf);
static DECLCALLBACK(int)    ssmR3ReadIn(void *pvSSM, void *pvBuf, size_t cbBuf, size_t *pcbRead);


/**
 * Performs lazy initialization of the SSM.
 *
 * @returns VBox status code.
 * @param   pVM         The VM.
 */
static int ssmR3LazyInit(PVM pVM)
{
    /*
     * Register a saved state unit which we use to put the VirtualBox version,
     * revision and similar stuff in.
     */
    pVM->ssm.s.fInitialized = true;
    int rc = SSMR3RegisterInternal(pVM, "SSM", 0 /*u32Instance*/, 1/*u32Version*/, 64 /*cbGuess*/,
                                   NULL /*pfnSavePrep*/, ssmR3SelfSaveExec, NULL /*pfnSaveDone*/,
                                   NULL /*pfnSavePrep*/, ssmR3SelfLoadExec, NULL /*pfnSaveDone*/);
    pVM->ssm.s.fInitialized = RT_SUCCESS(rc);
    return rc;
}


/**
 * For saving usful things without having to go thru the tedious process of
 * adding it to the header.
 *
 * @returns VBox status code.
 * @param   pVM             Pointer to the shared VM structure.
 * @param   pSSM            The SSM handle.
 */
static DECLCALLBACK(int) ssmR3SelfSaveExec(PVM pVM, PSSMHANDLE pSSM)
{
    /*
     * String table containg pairs of variable and value string.
     * Terminated by two empty strings.
     */
#ifdef VBOX_OSE
    SSMR3PutStrZ(pSSM, "OSE");
    SSMR3PutStrZ(pSSM, "true");
#endif

    /* terminator */
    SSMR3PutStrZ(pSSM, "");
    return SSMR3PutStrZ(pSSM, "");
}


/**
 * For load the version + revision and stuff.
 *
 * @returns VBox status code.
 * @param   pVM             Pointer to the shared VM structure.
 * @param   pSSM            The SSM handle.
 * @param   u32Version      The version (1).
 */
static DECLCALLBACK(int) ssmR3SelfLoadExec(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
{
    AssertLogRelMsgReturn(u32Version == 1, ("%d", u32Version), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);

    /*
     * String table containg pairs of variable and value string.
     * Terminated by two empty strings.
     */
    for (unsigned i = 0; ; i++)
    {
        char szVar[128];
        char szValue[1024];
        int rc = SSMR3GetStrZ(pSSM, szVar, sizeof(szVar));
        AssertRCReturn(rc, rc);
        rc = SSMR3GetStrZ(pSSM, szValue, sizeof(szValue));
        AssertRCReturn(rc, rc);
        if (!szVar[0] && !szValue[0])
            break;
        if (i == 0)
            LogRel(("SSM: Saved state info:\n"));
        LogRel(("SSM:   %s: %s\n", szVar, szValue));
    }
    return VINF_SUCCESS;
}


/**
 * Internal registration worker.
 *
 * @returns VBox status code.
 * @param   pVM             The VM handle.
 * @param   pszName         Data unit name.
 * @param   u32Instance     The instance id.
 * @param   u32Version      The data unit version.
 * @param   cbGuess         The guessed data unit size.
 * @param   pszBefore       Name of data unit to be placed in front of.
 *                          Optional.
 * @param   ppUnit          Where to store the insterted unit node.
 *                          Caller must fill in the missing details.
 */
static int ssmR3Register(PVM pVM, const char *pszName, uint32_t u32Instance,
                         uint32_t u32Version, size_t cbGuess, const char *pszBefore, PSSMUNIT *ppUnit)
{
    AssertPtrReturn(pszName, VERR_INVALID_POINTER);
    AssertReturn(*pszName, VERR_INVALID_PARAMETER);
    AssertReturn(!pszBefore || *pszBefore, VERR_INVALID_PARAMETER);

    /*
     * Lazy init.
     */
    if (!pVM->ssm.s.fInitialized)
    {
        int rc = ssmR3LazyInit(pVM);
        AssertRCReturn(rc, rc);
    }

    /*
     * Walk to the end of the list checking for duplicates as we go.
     */
    size_t      cchBefore       = pszBefore ? strlen(pszBefore) : 0;
    PSSMUNIT    pUnitBeforePrev = NULL;
    PSSMUNIT    pUnitBefore     = NULL;
    size_t      cchName         = strlen(pszName);
    PSSMUNIT    pUnitPrev       = NULL;
    PSSMUNIT    pUnit           = pVM->ssm.s.pHead;
    while (pUnit)
    {
        if (    pUnit->u32Instance == u32Instance
            &&  pUnit->cchName == cchName
            &&  !memcmp(pUnit->szName, pszName, cchName))
        {
            AssertMsgFailed(("Duplicate registration %s\n", pszName));
            return VERR_SSM_UNIT_EXISTS;
        }
        if (    pUnit->cchName == cchBefore
            &&  !pUnitBefore
            &&  !memcmp(pUnit->szName, pszBefore, cchBefore))
        {
            pUnitBeforePrev = pUnitPrev;
            pUnitBefore     = pUnit;
        }

        /* next */
        pUnitPrev = pUnit;
        pUnit = pUnit->pNext;
    }

    /*
     * Allocate new node.
     */
    pUnit = (PSSMUNIT)MMR3HeapAllocZ(pVM, MM_TAG_SSM, RT_OFFSETOF(SSMUNIT, szName[cchName + 1]));
    if (!pUnit)
        return VERR_NO_MEMORY;

    /*
     * Fill in (some) data. (Stuff is zero'ed.)
     */
    pUnit->u32Version   = u32Version;
    pUnit->u32Instance  = u32Instance;
    pUnit->cbGuess      = cbGuess;
    pUnit->cchName      = cchName;
    memcpy(pUnit->szName, pszName, cchName);

    /*
     * Insert
     */
    if (pUnitBefore)
    {
        pUnit->pNext = pUnitBefore;
        if (pUnitBeforePrev)
            pUnitBeforePrev->pNext = pUnit;
        else
            pVM->ssm.s.pHead       = pUnit;
    }
    else if (pUnitPrev)
        pUnitPrev->pNext = pUnit;
    else
        pVM->ssm.s.pHead = pUnit;

    *ppUnit = pUnit;
    return VINF_SUCCESS;
}


/**
 * Register a PDM Devices data unit.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pDevIns         Device instance.
 * @param   pszName         Data unit name.
 * @param   u32Instance     The instance identifier of the data unit.
 *                          This must together with the name be unique.
 * @param   u32Version      Data layout version number.
 * @param   cbGuess         The approximate amount of data in the unit.
 *                          Only for progress indicators.
 * @param   pszBefore       Name of data unit which we should be put in front
 *                          of. Optional (NULL).
 * @param   pfnSavePrep     Prepare save callback, optional.
 * @param   pfnSaveExec     Execute save callback, optional.
 * @param   pfnSaveDone     Done save callback, optional.
 * @param   pfnLoadPrep     Prepare load callback, optional.
 * @param   pfnLoadExec     Execute load callback, optional.
 * @param   pfnLoadDone     Done load callback, optional.
 */
VMMR3DECL(int) SSMR3RegisterDevice(PVM pVM, PPDMDEVINS pDevIns, const char *pszName, uint32_t u32Instance, uint32_t u32Version, size_t cbGuess, const char *pszBefore,
    PFNSSMDEVSAVEPREP pfnSavePrep, PFNSSMDEVSAVEEXEC pfnSaveExec, PFNSSMDEVSAVEDONE pfnSaveDone,
    PFNSSMDEVLOADPREP pfnLoadPrep, PFNSSMDEVLOADEXEC pfnLoadExec, PFNSSMDEVLOADDONE pfnLoadDone)
{
    PSSMUNIT pUnit;
    int rc = ssmR3Register(pVM, pszName, u32Instance, u32Version, cbGuess, pszBefore, &pUnit);
    if (RT_SUCCESS(rc))
    {
        pUnit->enmType = SSMUNITTYPE_DEV;
        pUnit->u.Dev.pfnSavePrep = pfnSavePrep;
        pUnit->u.Dev.pfnSaveExec = pfnSaveExec;
        pUnit->u.Dev.pfnSaveDone = pfnSaveDone;
        pUnit->u.Dev.pfnLoadPrep = pfnLoadPrep;
        pUnit->u.Dev.pfnLoadExec = pfnLoadExec;
        pUnit->u.Dev.pfnLoadDone = pfnLoadDone;
        pUnit->u.Dev.pDevIns = pDevIns;
    }
    return rc;
}


/**
 * Register a PDM driver data unit.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pDrvIns         Driver instance.
 * @param   pszName         Data unit name.
 * @param   u32Instance     The instance identifier of the data unit.
 *                          This must together with the name be unique.
 * @param   u32Version      Data layout version number.
 * @param   cbGuess         The approximate amount of data in the unit.
 *                          Only for progress indicators.
 * @param   pfnSavePrep     Prepare save callback, optional.
 * @param   pfnSaveExec     Execute save callback, optional.
 * @param   pfnSaveDone     Done save callback, optional.
 * @param   pfnLoadPrep     Prepare load callback, optional.
 * @param   pfnLoadExec     Execute load callback, optional.
 * @param   pfnLoadDone     Done load callback, optional.
 */
VMMR3DECL(int) SSMR3RegisterDriver(PVM pVM, PPDMDRVINS pDrvIns, const char *pszName, uint32_t u32Instance, uint32_t u32Version, size_t cbGuess,
    PFNSSMDRVSAVEPREP pfnSavePrep, PFNSSMDRVSAVEEXEC pfnSaveExec, PFNSSMDRVSAVEDONE pfnSaveDone,
    PFNSSMDRVLOADPREP pfnLoadPrep, PFNSSMDRVLOADEXEC pfnLoadExec, PFNSSMDRVLOADDONE pfnLoadDone)
{
    PSSMUNIT pUnit;
    int rc = ssmR3Register(pVM, pszName, u32Instance, u32Version, cbGuess, NULL, &pUnit);
    if (RT_SUCCESS(rc))
    {
        pUnit->enmType = SSMUNITTYPE_DRV;
        pUnit->u.Drv.pfnSavePrep = pfnSavePrep;
        pUnit->u.Drv.pfnSaveExec = pfnSaveExec;
        pUnit->u.Drv.pfnSaveDone = pfnSaveDone;
        pUnit->u.Drv.pfnLoadPrep = pfnLoadPrep;
        pUnit->u.Drv.pfnLoadExec = pfnLoadExec;
        pUnit->u.Drv.pfnLoadDone = pfnLoadDone;
        pUnit->u.Drv.pDrvIns = pDrvIns;
    }
    return rc;
}


/**
 * Register a internal data unit.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pszName         Data unit name.
 * @param   u32Instance     The instance identifier of the data unit.
 *                          This must together with the name be unique.
 * @param   u32Version      Data layout version number.
 * @param   cbGuess         The approximate amount of data in the unit.
 *                          Only for progress indicators.
 * @param   pfnSavePrep     Prepare save callback, optional.
 * @param   pfnSaveExec     Execute save callback, optional.
 * @param   pfnSaveDone     Done save callback, optional.
 * @param   pfnLoadPrep     Prepare load callback, optional.
 * @param   pfnLoadExec     Execute load callback, optional.
 * @param   pfnLoadDone     Done load callback, optional.
 */
VMMR3DECL(int) SSMR3RegisterInternal(PVM pVM, const char *pszName, uint32_t u32Instance, uint32_t u32Version, size_t cbGuess,
    PFNSSMINTSAVEPREP pfnSavePrep, PFNSSMINTSAVEEXEC pfnSaveExec, PFNSSMINTSAVEDONE pfnSaveDone,
    PFNSSMINTLOADPREP pfnLoadPrep, PFNSSMINTLOADEXEC pfnLoadExec, PFNSSMINTLOADDONE pfnLoadDone)
{
    PSSMUNIT pUnit;
    int rc = ssmR3Register(pVM, pszName, u32Instance, u32Version, cbGuess, NULL, &pUnit);
    if (RT_SUCCESS(rc))
    {
        pUnit->enmType = SSMUNITTYPE_INTERNAL;
        pUnit->u.Internal.pfnSavePrep = pfnSavePrep;
        pUnit->u.Internal.pfnSaveExec = pfnSaveExec;
        pUnit->u.Internal.pfnSaveDone = pfnSaveDone;
        pUnit->u.Internal.pfnLoadPrep = pfnLoadPrep;
        pUnit->u.Internal.pfnLoadExec = pfnLoadExec;
        pUnit->u.Internal.pfnLoadDone = pfnLoadDone;
    }
    return rc;
}


/**
 * Register an external data unit.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pszName         Data unit name.
 * @param   u32Instance     The instance identifier of the data unit.
 *                          This must together with the name be unique.
 * @param   u32Version      Data layout version number.
 * @param   cbGuess         The approximate amount of data in the unit.
 *                          Only for progress indicators.
 * @param   pfnSavePrep     Prepare save callback, optional.
 * @param   pfnSaveExec     Execute save callback, optional.
 * @param   pfnSaveDone     Done save callback, optional.
 * @param   pfnLoadPrep     Prepare load callback, optional.
 * @param   pfnLoadExec     Execute load callback, optional.
 * @param   pfnLoadDone     Done load callback, optional.
 * @param   pvUser          User argument.
 */
VMMR3DECL(int) SSMR3RegisterExternal(PVM pVM, const char *pszName, uint32_t u32Instance, uint32_t u32Version, size_t cbGuess,
    PFNSSMEXTSAVEPREP pfnSavePrep, PFNSSMEXTSAVEEXEC pfnSaveExec, PFNSSMEXTSAVEDONE pfnSaveDone,
    PFNSSMEXTLOADPREP pfnLoadPrep, PFNSSMEXTLOADEXEC pfnLoadExec, PFNSSMEXTLOADDONE pfnLoadDone, void *pvUser)
{
    PSSMUNIT pUnit;
    int rc = ssmR3Register(pVM, pszName, u32Instance, u32Version, cbGuess, NULL, &pUnit);
    if (RT_SUCCESS(rc))
    {
        pUnit->enmType = SSMUNITTYPE_EXTERNAL;
        pUnit->u.External.pfnSavePrep = pfnSavePrep;
        pUnit->u.External.pfnSaveExec = pfnSaveExec;
        pUnit->u.External.pfnSaveDone = pfnSaveDone;
        pUnit->u.External.pfnLoadPrep = pfnLoadPrep;
        pUnit->u.External.pfnLoadExec = pfnLoadExec;
        pUnit->u.External.pfnLoadDone = pfnLoadDone;
        pUnit->u.External.pvUser      = pvUser;
    }
    return rc;
}


/**
 * Deregister one or more PDM Device data units.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pDevIns         Device instance.
 * @param   pszName         Data unit name.
 *                          Use NULL to deregister all data units for that device instance.
 * @param   u32Instance     The instance identifier of the data unit.
 *                          This must together with the name be unique.
 * @remark  Only for dynmaic data units and dynamic unloaded modules.
 */
VMMR3DECL(int) SSMR3DeregisterDevice(PVM pVM, PPDMDEVINS pDevIns, const char *pszName, uint32_t u32Instance)
{
    /*
     * Validate input.
     */
    if (!pDevIns)
    {
        AssertMsgFailed(("pDevIns is NULL!\n"));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Search the list.
     */
    size_t      cchName = pszName ? strlen(pszName) : 0;
    int         rc = pszName ? VERR_SSM_UNIT_NOT_FOUND : VINF_SUCCESS;
    PSSMUNIT    pUnitPrev = NULL;
    PSSMUNIT    pUnit = pVM->ssm.s.pHead;
    while (pUnit)
    {
        if (    pUnit->enmType == SSMUNITTYPE_DEV
            &&  (   !pszName
                 || (   pUnit->cchName == cchName
                     && !memcmp(pUnit->szName, pszName, cchName)))
            &&  pUnit->u32Instance == u32Instance
            )
        {
            if (pUnit->u.Dev.pDevIns == pDevIns)
            {
                /*
                 * Unlink it, advance pointer, and free the node.
                 */
                PSSMUNIT pFree = pUnit;
                pUnit = pUnit->pNext;
                if (pUnitPrev)
                    pUnitPrev->pNext = pUnit;
                else
                    pVM->ssm.s.pHead = pUnit;
                Log(("SSM: Removed data unit '%s' (pdm dev).\n", pFree->szName));
                MMR3HeapFree(pFree);
                if (pszName)
                    return VINF_SUCCESS;
                rc = VINF_SUCCESS;
                continue;
            }
            else if (pszName)
            {
                AssertMsgFailed(("Caller is not owner! Owner=%p Caller=%p %s\n",
                                 pUnit->u.Dev.pDevIns, pDevIns, pszName));
                return VERR_SSM_UNIT_NOT_OWNER;
            }
        }

        /* next */
        pUnitPrev = pUnit;
        pUnit = pUnit->pNext;
    }

    return rc;
}


/**
 * Deregister one ore more PDM Driver data units.
 *
 * @returns VBox status.
 * @param   pVM             The VM handle.
 * @param   pDrvIns         Driver instance.
 * @param   pszName         Data unit name.
 *                          Use NULL to deregister all data units for that driver instance.
 * @param   u32Instance     The instance identifier of the data unit.
 *                          This must together with the name be unique. Ignored if pszName is NULL.
 * @remark  Only for dynmaic data units and dynamic unloaded modules.
 */
VMMR3DECL(int) SSMR3DeregisterDriver(PVM pVM, PPDMDRVINS pDrvIns, const char *pszName, uint32_t u32Instance)
{
    /*
     * Validate input.
     */
    if (!pDrvIns)
    {
        AssertMsgFailed(("pDrvIns is NULL!\n"));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Search the list.
     */
    size_t      cchName = pszName ? strlen(pszName) : 0;
    int         rc = pszName ? VERR_SSM_UNIT_NOT_FOUND : VINF_SUCCESS;
    PSSMUNIT    pUnitPrev = NULL;
    PSSMUNIT    pUnit = pVM->ssm.s.pHead;
    while (pUnit)
    {
        if (    pUnit->enmType == SSMUNITTYPE_DRV
            &&  (   !pszName
                 || (   pUnit->cchName == cchName
                     && !memcmp(pUnit->szName, pszName, cchName)
                     && pUnit->u32Instance == u32Instance))
            )
        {
            if (pUnit->u.Drv.pDrvIns == pDrvIns)
            {
                /*
                 * Unlink it, advance pointer, and free the node.
                 */
                PSSMUNIT pFree = pUnit;
                pUnit = pUnit->pNext;
                if (pUnitPrev)
                    pUnitPrev->pNext = pUnit;
                else
                    pVM->ssm.s.pHead = pUnit;
                Log(("SSM: Removed data unit '%s' (pdm drv).\n", pFree->szName));
                MMR3HeapFree(pFree);
                if (pszName)
                    return VINF_SUCCESS;
                rc = VINF_SUCCESS;
                continue;
            }
            else if (pszName)
            {
                AssertMsgFailed(("Caller is not owner! Owner=%p Caller=%p %s\n",
                                 pUnit->u.Drv.pDrvIns, pDrvIns, pszName));
                return VERR_SSM_UNIT_NOT_OWNER;
            }
        }

        /* next */
        pUnitPrev = pUnit;
        pUnit = pUnit->pNext;
    }

    return rc;
}


/**
 * Deregister a data unit.
 *
 * @returns VBox status.
 * @param   pVM             The VM handle.
 * @param   enmType         Unit type
 * @param   pszName         Data unit name.
 * @remark  Only for dynmaic data units.
 */
static int ssmR3DeregisterByNameAndType(PVM pVM, const char *pszName, SSMUNITTYPE enmType)
{
    /*
     * Validate input.
     */
    if (!pszName)
    {
        AssertMsgFailed(("pszName is NULL!\n"));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Search the list.
     */
    size_t      cchName = strlen(pszName);
    int         rc = VERR_SSM_UNIT_NOT_FOUND;
    PSSMUNIT    pUnitPrev = NULL;
    PSSMUNIT    pUnit = pVM->ssm.s.pHead;
    while (pUnit)
    {
        if (    pUnit->enmType == enmType
            &&  pUnit->cchName == cchName
            &&  !memcmp(pUnit->szName, pszName, cchName))
        {
            /*
             * Unlink it, advance pointer, and free the node.
             */
            PSSMUNIT pFree = pUnit;
            pUnit = pUnit->pNext;
            if (pUnitPrev)
                pUnitPrev->pNext = pUnit;
            else
                pVM->ssm.s.pHead = pUnit;
            Log(("SSM: Removed data unit '%s' (type=%d).\n", pFree->szName, enmType));
            MMR3HeapFree(pFree);
            return VINF_SUCCESS;
        }

        /* next */
        pUnitPrev = pUnit;
        pUnit = pUnit->pNext;
    }

    return rc;
}


/**
 * Deregister an internal data unit.
 *
 * @returns VBox status.
 * @param   pVM             The VM handle.
 * @param   pszName         Data unit name.
 * @remark  Only for dynmaic data units.
 */
VMMR3DECL(int) SSMR3DeregisterInternal(PVM pVM, const char *pszName)
{
    return ssmR3DeregisterByNameAndType(pVM, pszName, SSMUNITTYPE_INTERNAL);
}


/**
 * Deregister an external data unit.
 *
 * @returns VBox status.
 * @param   pVM             The VM handle.
 * @param   pszName         Data unit name.
 * @remark  Only for dynmaic data units.
 */
VMMR3DECL(int) SSMR3DeregisterExternal(PVM pVM, const char *pszName)
{
    return ssmR3DeregisterByNameAndType(pVM, pszName, SSMUNITTYPE_EXTERNAL);
}


/**
 * Calculate the checksum of a file portion.
 *
 * The current implementation is a cut&past of the libkern/crc32.c file from FreeBSD.
 *
 * @returns VBox status.
 * @param   File        Handle to the file.
 * @param   cbFile      Size of the file.
 * @param   pu32CRC     Where to store the calculated checksum.
 */
static int ssmR3CalcChecksum(RTFILE File, uint64_t cbFile, uint32_t *pu32CRC)
{
    /*
     * Allocate a buffer.
     */
    void *pvBuf = RTMemTmpAlloc(32*1024);
    if (!pvBuf)
        return VERR_NO_TMP_MEMORY;

    /*
     * Loop reading and calculating CRC32.
     */
    int         rc = VINF_SUCCESS;
    uint32_t    u32CRC = RTCrc32Start();
    while (cbFile)
    {
        /* read chunk */
        register unsigned cbToRead = 32*1024;
        if (cbFile < 32*1024)
            cbToRead = (unsigned)cbFile;
        rc = RTFileRead(File, pvBuf, cbToRead, NULL);
        if (RT_FAILURE(rc))
        {
            AssertMsgFailed(("Failed with rc=%Rrc while calculating crc.\n", rc));
            RTMemTmpFree(pvBuf);
            return rc;
        }

        /* update total */
        cbFile -= cbToRead;

        /* calc crc32. */
        u32CRC = RTCrc32Process(u32CRC, pvBuf,  cbToRead);
    }
    RTMemTmpFree(pvBuf);

    /* store the calculated crc */
    u32CRC = RTCrc32Finish(u32CRC);
    Log(("SSM: u32CRC=0x%08x\n", u32CRC));
    *pu32CRC = u32CRC;

    return VINF_SUCCESS;
}


/**
 * Works the progress calculation.
 *
 * @param   pSSM        The SSM handle.
 * @param   cbAdvance   Number of bytes to advance
 */
static void ssmR3Progress(PSSMHANDLE pSSM, uint64_t cbAdvance)
{
    /* Can't advance it beyond the estimated end of the unit. */
    uint64_t cbLeft = pSSM->offEstUnitEnd - pSSM->offEst;
    if (cbAdvance > cbLeft)
        cbAdvance = cbLeft;
    pSSM->offEst += cbAdvance;

    /* uPercentPrepare% prepare, xx% exec, uPercentDone% done+crc */
    while (pSSM->offEst >= pSSM->offEstProgress && pSSM->uPercent <= 100-pSSM->uPercentDone)
    {
        if (pSSM->pfnProgress)
            pSSM->pfnProgress(pSSM->pVM, pSSM->uPercent, pSSM->pvUser);
        pSSM->uPercent++;
        pSSM->offEstProgress = (pSSM->uPercent - pSSM->uPercentPrepare) * pSSM->cbEstTotal
                             / (100 - pSSM->uPercentDone - pSSM->uPercentPrepare);
    }
}


/**
 * Start VM save operation.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pszFilename     Name of the file to save the state in.
 * @param   enmAfter        What is planned after a successful save operation.
 * @param   pfnProgress     Progress callback. Optional.
 * @param   pvUser          User argument for the progress callback.
 *
 * @thread  EMT
 */
VMMR3DECL(int) SSMR3Save(PVM pVM, const char *pszFilename, SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvUser)
{
    LogFlow(("SSMR3Save: pszFilename=%p:{%s} enmAfter=%d pfnProgress=%p pvUser=%p\n", pszFilename, pszFilename, enmAfter, pfnProgress, pvUser));
    VM_ASSERT_EMT(pVM);

    /*
     * Validate input.
     */
    if (    enmAfter != SSMAFTER_DESTROY
        &&  enmAfter != SSMAFTER_CONTINUE)
    {
        AssertMsgFailed(("Invalid enmAfter=%d!\n", enmAfter));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Create the handle and try open the file.
     *
     * Note that there might be quite some work to do after executing the saving,
     * so we reserve 20% for the 'Done' period.  The checksumming and closing of
     * the saved state file might take a long time.
     */
    SSMHANDLE Handle       = {0};
    Handle.File             = NIL_RTFILE;
    Handle.pVM              = pVM;
    Handle.cbFileHdr        = sizeof(SSMFILEHDR);
    Handle.enmOp            = SSMSTATE_INVALID;
    Handle.enmAfter         = enmAfter;
    Handle.rc               = VINF_SUCCESS;
    Handle.pZipComp         = NULL;
    Handle.pZipDecomp       = NULL;
    Handle.cbUnitLeft       = 0;
    Handle.offUnit          = UINT64_MAX;
    Handle.pfnProgress      = pfnProgress;
    Handle.pvUser           = pvUser;
    Handle.uPercent         = 0;
    Handle.offEstProgress   = 0;
    Handle.cbEstTotal       = 0;
    Handle.offEst           = 0;
    Handle.offEstUnitEnd    = 0;
    Handle.uPercentPrepare  = 20;
    Handle.uPercentDone     = 2;
    Handle.cbGCPhys         = sizeof(RTGCPHYS);
    Handle.cbGCPtr          = sizeof(RTGCPTR);
    Handle.fFixedGCPtrSize  = true;

    int rc = RTFileOpen(&Handle.File, pszFilename, RTFILE_O_READWRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_WRITE);
    if (RT_FAILURE(rc))
    {
        LogRel(("SSM: Failed to create save state file '%s', rc=%Rrc.\n",  pszFilename, rc));
        return rc;
    }

    Log(("SSM: Starting state save to file '%s'...\n", pszFilename));

    /*
     * Write header.
     */
    SSMFILEHDR Hdr =
    {
        /* .achMagic[32] = */ SSMFILEHDR_MAGIC_V1_2,
        /* .cbFile       = */ 0,
        /* .u32CRC       = */ 0,
        /* .u32Reserved  = */ 0,
        /* .MachineUuid  = */ {{0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}},
        /* .u16VerMajor  = */ VBOX_VERSION_MAJOR,
        /* .u16VerMinor  = */ VBOX_VERSION_MINOR,
        /* .u32VerBuild  = */ VBOX_VERSION_BUILD,
        /* .u32SvnRev    = */ VMMGetSvnRev(),
        /* .cHostBits    = */ HC_ARCH_BITS,
        /* .cbGCPhys     = */ sizeof(RTGCPHYS),
        /* .cbGCPtr      = */ sizeof(RTGCPTR),
        /* .au8Reserved  = */ 0
    };
    rc = RTFileWrite(Handle.File, &Hdr, sizeof(Hdr), NULL);
    if (RT_SUCCESS(rc))
    {
        /*
         * Clear the per unit flags.
         */
        PSSMUNIT pUnit;
        for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
            pUnit->fCalled = false;

        /*
         * Do the prepare run.
         */
        Handle.rc = VINF_SUCCESS;
        Handle.enmOp = SSMSTATE_SAVE_PREP;
        for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
        {
            switch (pUnit->enmType)
            {
                case SSMUNITTYPE_DEV:
                    if (pUnit->u.Dev.pfnSavePrep)
                    {
                        rc = pUnit->u.Dev.pfnSavePrep(pUnit->u.Dev.pDevIns, &Handle);
                        pUnit->fCalled = true;
                    }
                    break;
                case SSMUNITTYPE_DRV:
                    if (pUnit->u.Drv.pfnSavePrep)
                    {
                        rc = pUnit->u.Drv.pfnSavePrep(pUnit->u.Drv.pDrvIns, &Handle);
                        pUnit->fCalled = true;
                    }
                    break;
                case SSMUNITTYPE_INTERNAL:
                    if (pUnit->u.Internal.pfnSavePrep)
                    {
                        rc = pUnit->u.Internal.pfnSavePrep(pVM, &Handle);
                        pUnit->fCalled = true;
                    }
                    break;
                case SSMUNITTYPE_EXTERNAL:
                    if (pUnit->u.External.pfnSavePrep)
                    {
                        rc = pUnit->u.External.pfnSavePrep(&Handle, pUnit->u.External.pvUser);
                        pUnit->fCalled = true;
                    }
                    break;
            }
            if (RT_FAILURE(rc))
            {
                LogRel(("SSM: Prepare save failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
                break;
            }

            Handle.cbEstTotal += pUnit->cbGuess;
        }

        /* Progress. */
        if (pfnProgress)
            pfnProgress(pVM, Handle.uPercentPrepare-1, pvUser);
        Handle.uPercent = Handle.uPercentPrepare;

        /*
         * Do the execute run.
         */
        if (RT_SUCCESS(rc))
        {
            Handle.enmOp = SSMSTATE_SAVE_EXEC;
            for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
            {
                /*
                 * Estimate.
                 */
                ssmR3Progress(&Handle, Handle.offEstUnitEnd - Handle.offEst);
                Handle.offEstUnitEnd += pUnit->cbGuess;

                /*
                 * Does this unit have a callback? If, not skip it.
                 */
                bool fSkip;
                switch (pUnit->enmType)
                {
                    case SSMUNITTYPE_DEV:       fSkip = pUnit->u.Dev.pfnSaveExec      == NULL; break;
                    case SSMUNITTYPE_DRV:       fSkip = pUnit->u.Drv.pfnSaveExec      == NULL; break;
                    case SSMUNITTYPE_INTERNAL:  fSkip = pUnit->u.Internal.pfnSaveExec == NULL; break;
                    case SSMUNITTYPE_EXTERNAL:  fSkip = pUnit->u.External.pfnSaveExec == NULL; break;
                    default:                    fSkip = true; break;
                }
                if (fSkip)
                {
                    pUnit->fCalled = true;
                    continue;
                }

                /*
                 * Write data unit header
                 */
                uint64_t        offHdr = RTFileTell(Handle.File);
                SSMFILEUNITHDR  UnitHdr = { SSMFILEUNITHDR_MAGIC, 0, pUnit->u32Version, pUnit->u32Instance, (uint32_t)pUnit->cchName + 1, { '\0' } };
                rc = RTFileWrite(Handle.File, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDR, szName[0]), NULL);
                if (RT_SUCCESS(rc))
                {
                    rc = RTFileWrite(Handle.File, &pUnit->szName[0], pUnit->cchName + 1, NULL);
                    if (RT_SUCCESS(rc))
                    {
                        /*
                         * Call the execute handler.
                         */
                        Handle.offUnit = 0;
                        switch (pUnit->enmType)
                        {
                            case SSMUNITTYPE_DEV:
                                rc = pUnit->u.Dev.pfnSaveExec(pUnit->u.Dev.pDevIns, &Handle);
                                break;
                            case SSMUNITTYPE_DRV:
                                rc = pUnit->u.Drv.pfnSaveExec(pUnit->u.Drv.pDrvIns, &Handle);
                                break;
                            case SSMUNITTYPE_INTERNAL:
                                rc = pUnit->u.Internal.pfnSaveExec(pVM, &Handle);
                                break;
                            case SSMUNITTYPE_EXTERNAL:
                                pUnit->u.External.pfnSaveExec(&Handle, pUnit->u.External.pvUser);
                                rc = Handle.rc;
                                break;
                        }
                        pUnit->fCalled = true;
                        if (RT_FAILURE(Handle.rc) && RT_SUCCESS(rc))
                            rc = Handle.rc;
                        if (RT_SUCCESS(rc))
                        {
                            /*
                             * Flush buffer / end compression stream.
                             */
                            if (Handle.pZipComp)
                                rc = ssmR3WriteFinish(&Handle);
                            if (RT_SUCCESS(rc))
                            {
                                /*
                                 * Update header with correct length.
                                 */
                                uint64_t    offEnd = RTFileTell(Handle.File);
                                rc = RTFileSeek(Handle.File, offHdr, RTFILE_SEEK_BEGIN, NULL);
                                if (RT_SUCCESS(rc))
                                {
                                    UnitHdr.cbUnit = offEnd - offHdr;
                                    ///@todo UnitHdr.cbUnitUncompressed = Handle.offUnit;
                                    rc = RTFileWrite(Handle.File, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDR, szName[0]), NULL);
                                    if (RT_SUCCESS(rc))
                                    {
                                        rc = RTFileSeek(Handle.File, offEnd, RTFILE_SEEK_BEGIN, NULL);
                                        if (RT_SUCCESS(rc))
                                            Log(("SSM: Data unit: offset %#9llx size %9lld / %9lld '%s'\n", offHdr, UnitHdr.cbUnit, Handle.offUnit, pUnit->szName));
                                    }
                                }
                                Handle.offUnit = UINT64_MAX;
                            }
                            else
                            {
                                LogRel(("SSM: Failed ending compression stream. rc=%Rrc\n", rc));
                                break;
                            }
                        }
                        else
                        {
                            LogRel(("SSM: Execute save failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
                            break;
                        }
                    }
                }
                if (RT_FAILURE(rc))
                {
                    LogRel(("SSM: Failed to write unit header. rc=%Rrc\n", rc));
                    break;
                }
            } /* for each unit */

            /* finish the progress. */
            if (RT_SUCCESS(rc))
                ssmR3Progress(&Handle, Handle.offEstUnitEnd - Handle.offEst);
        }
        /* (progress should be pending 99% now) */
        AssertMsg(RT_FAILURE(rc) || Handle.uPercent == (101-Handle.uPercentDone), ("%d\n", Handle.uPercent));

        /*
         * Do the done run.
         */
        Handle.rc = rc;
        Handle.enmOp = SSMSTATE_SAVE_DONE;
        for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
        {
            switch (pUnit->enmType)
            {
                case SSMUNITTYPE_DEV:
                    if (    pUnit->u.Dev.pfnSaveDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Dev.pfnSavePrep && !pUnit->u.Dev.pfnSaveExec)))
                        rc = pUnit->u.Dev.pfnSaveDone(pUnit->u.Dev.pDevIns, &Handle);
                    break;
                case SSMUNITTYPE_DRV:
                    if (    pUnit->u.Drv.pfnSaveDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Drv.pfnSavePrep && !pUnit->u.Drv.pfnSaveExec)))
                        rc = pUnit->u.Drv.pfnSaveDone(pUnit->u.Drv.pDrvIns, &Handle);
                    break;
                case SSMUNITTYPE_INTERNAL:
                    if (    pUnit->u.Internal.pfnSaveDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Internal.pfnSavePrep && !pUnit->u.Internal.pfnSaveExec)))
                        rc = pUnit->u.Internal.pfnSaveDone(pVM, &Handle);
                    break;
                case SSMUNITTYPE_EXTERNAL:
                    if (    pUnit->u.External.pfnSaveDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.External.pfnSavePrep && !pUnit->u.External.pfnSaveExec)))
                        rc = pUnit->u.External.pfnSaveDone(&Handle, pUnit->u.External.pvUser);
                    break;
            }
            if (RT_FAILURE(rc))
            {
                LogRel(("SSM: Done save failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
                if (RT_SUCCESS(Handle.rc))
                    Handle.rc = rc;
            }
        }
        rc = Handle.rc;

        /*
         * Finalize the file if successfully saved.
         */
        if (RT_SUCCESS(rc))
        {
            /* end record */
            SSMFILEUNITHDR  UnitHdr = { SSMFILEUNITHDR_END, RT_OFFSETOF(SSMFILEUNITHDR, szName[0]), 0, '\0'};
            rc = RTFileWrite(Handle.File, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDR, szName[0]), NULL);
            if (RT_SUCCESS(rc))
            {
                /* get size */
                Hdr.cbFile = RTFileTell(Handle.File);
                /* calc checksum */
                rc = RTFileSeek(Handle.File, RT_OFFSETOF(SSMFILEHDR, u32CRC) + sizeof(Hdr.u32CRC), RTFILE_SEEK_BEGIN, NULL);
                if (RT_SUCCESS(rc))
                    rc = ssmR3CalcChecksum(Handle.File, Hdr.cbFile - sizeof(Hdr), &Hdr.u32CRC);
                if (RT_SUCCESS(rc))
                {
                    if (pfnProgress)
                        pfnProgress(pVM, 90, pvUser);

                    /*
                     * Write the update the header to the file.
                     */
                    rc = RTFileSeek(Handle.File, 0, RTFILE_SEEK_BEGIN, NULL);
                    if (RT_SUCCESS(rc))
                        rc = RTFileWrite(Handle.File, &Hdr, sizeof(Hdr), NULL);
                    if (RT_SUCCESS(rc))
                    {
                        rc = RTFileClose(Handle.File);
                        AssertRC(rc);
                        if (pfnProgress)
                            pfnProgress(pVM, 100, pvUser);
                        Log(("SSM: Successfully saved the vm state to '%s'.\n", pszFilename));
                        Log(("\n\n\n"));
                        DBGFR3InfoLog(pVM, "cpum", "verbose");
                        DBGFR3InfoLog(pVM, "timers", NULL);
                        DBGFR3InfoLog(pVM, "activetimers", NULL);
                        DBGFR3InfoLog(pVM, "ioport", NULL);
                        DBGFR3InfoLog(pVM, "mmio", NULL);
                        DBGFR3InfoLog(pVM, "phys", NULL);
                        Log(("\n\n\n"));
                        return VINF_SUCCESS;
                    }

                }
            }
            LogRel(("SSM: Failed to finalize state file! rc=%Rrc\n", pszFilename));
        }
    }

    /*
     * Delete the file on failure and destroy any compressors.
     */
    int rc2 = RTFileClose(Handle.File);
    AssertRC(rc2);
    rc2 = RTFileDelete(pszFilename);
    AssertRC(rc2);
    if (Handle.pZipComp)
        RTZipCompDestroy(Handle.pZipComp);

    return rc;
}


/**
 * Validates the integrity of a saved state file.
 *
 * @returns VBox status.
 * @param   File        File to validate.
 *                      The file position is undefined on return.
 * @param   pHdr        Where to store the file header.
 * @param   pcbFileHdr  Where to store the file header size.
 */
static int ssmR3Validate(RTFILE File, PSSMFILEHDR pHdr, size_t *pcbFileHdr)
{
    /*
     * Read the header.
     */
    int rc = RTFileRead(File, pHdr, sizeof(*pHdr), NULL);
    if (RT_FAILURE(rc))
    {
        Log(("SSM: Failed to read file header. rc=%Rrc\n", rc));
        return rc;
    }

    /*
     * Verify the magic and make adjustments for versions differences.
     */
    if (memcmp(pHdr->achMagic, SSMFILEHDR_MAGIC_BASE, sizeof(SSMFILEHDR_MAGIC_BASE) - 1))
    {
        Log(("SSM: Not a saved state file. magic=%.*s\n", sizeof(pHdr->achMagic) - 1, pHdr->achMagic));
        return VERR_SSM_INTEGRITY_MAGIC;
    }

    size_t offCrc32 = RT_OFFSETOF(SSMFILEHDR, u32CRC) + sizeof(pHdr->u32CRC);
    *pcbFileHdr = sizeof(*pHdr);
    if (!memcmp(pHdr->achMagic, SSMFILEHDR_MAGIC_V1_0, sizeof(SSMFILEHDR_MAGIC_V1_0)))
    {
        if (pHdr->MachineUuid.au32[3])
        {
            SSMFILEHDRV10X86 OldHdr;
            memcpy(&OldHdr, pHdr, sizeof(OldHdr));
            pHdr->cbFile = OldHdr.cbFile;
            pHdr->u32CRC = OldHdr.u32CRC;
            pHdr->u32Reserved = 0;
            pHdr->MachineUuid = OldHdr.MachineUuid;
            pHdr->cHostBits   = 32;

            offCrc32 = RT_OFFSETOF(SSMFILEHDRV10X86, u32CRC) + sizeof(pHdr->u32CRC);
            *pcbFileHdr = sizeof(OldHdr);
        }
        else
        {
            SSMFILEHDRV10AMD64 OldHdr;
            memcpy(&OldHdr, pHdr, sizeof(OldHdr));
            pHdr->cbFile = OldHdr.cbFile;
            pHdr->u32CRC = OldHdr.u32CRC;
            pHdr->u32Reserved = 0;
            pHdr->MachineUuid = OldHdr.MachineUuid;
            pHdr->cHostBits   = 64;

            offCrc32 = RT_OFFSETOF(SSMFILEHDRV10AMD64, u32CRC) + sizeof(pHdr->u32CRC);
            *pcbFileHdr = sizeof(OldHdr);
        }
        pHdr->u16VerMajor = 0;
        pHdr->u16VerMinor = 0;
        pHdr->u32VerBuild = 0;
        pHdr->u32SvnRev   = 0;
        pHdr->cbGCPhys    = sizeof(uint32_t);
        pHdr->cbGCPtr     = sizeof(uint32_t);
        pHdr->au8Reserved = 0;
    }
    else if (!memcmp(pHdr->achMagic, SSMFILEHDR_MAGIC_V1_1, sizeof(SSMFILEHDR_MAGIC_V1_1)))
    {
        *pcbFileHdr = sizeof(SSMFILEHDRV11);
        pHdr->u16VerMajor = 0;
        pHdr->u16VerMinor = 0;
        pHdr->u32VerBuild = 0;
        pHdr->u32SvnRev   = 0;
        pHdr->cHostBits   = 0; /* unknown */
        pHdr->cbGCPhys    = sizeof(RTGCPHYS);
        pHdr->cbGCPtr     = 0; /* settable. */
        pHdr->au8Reserved = 0;
    }
    else if (!memcmp(pHdr->achMagic, SSMFILEHDR_MAGIC_V1_2, sizeof(pHdr->achMagic)))
    {
        if (    pHdr->u16VerMajor == 0
            ||  pHdr->u16VerMajor > 1000
            ||  pHdr->u32SvnRev == 0
            ||  pHdr->u32SvnRev > 10000000 /*100M*/)
        {
            LogRel(("SSM: Incorrect version values: %d.%d.%d.r%d\n",
                    pHdr->u16VerMajor, pHdr->u16VerMinor, pHdr->u32VerBuild, pHdr->u32SvnRev));
            return VERR_SSM_INTEGRITY_VBOX_VERSION;
        }
        if (    pHdr->cHostBits != 32
            &&  pHdr->cHostBits != 64)
        {
            LogRel(("SSM: Incorrect cHostBits value: %d\n", pHdr->cHostBits));
            return VERR_SSM_INTEGRITY_SIZES;
        }
        if (    pHdr->cbGCPhys != sizeof(uint32_t)
            &&  pHdr->cbGCPhys != sizeof(uint64_t))
        {
            LogRel(("SSM: Incorrect cbGCPhys value: %d\n", pHdr->cbGCPhys));
            return VERR_SSM_INTEGRITY_SIZES;
        }
        if (    pHdr->cbGCPtr != sizeof(uint32_t)
            &&  pHdr->cbGCPtr != sizeof(uint64_t))
        {
            LogRel(("SSM: Incorrect cbGCPtr value: %d\n", pHdr->cbGCPtr));
            return VERR_SSM_INTEGRITY_SIZES;
        }
    }
    else
    {
        Log(("SSM: Unknown file format version. magic=%.*s\n", sizeof(pHdr->achMagic) - 1, pHdr->achMagic));
        return VERR_SSM_INTEGRITY_VERSION;
    }

    /*
     * Verify the file size.
     */
    uint64_t cbFile;
    rc = RTFileGetSize(File, &cbFile);
    if (RT_FAILURE(rc))
    {
        Log(("SSM: Failed to get file size. rc=%Rrc\n", rc));
        return rc;
    }
    if (cbFile != pHdr->cbFile)
    {
        Log(("SSM: File size mismatch. hdr.cbFile=%lld actual %lld\n", pHdr->cbFile, cbFile));
        return VERR_SSM_INTEGRITY_SIZE;
    }

    /*
     * Verify the checksum.
     */
    rc = RTFileSeek(File, offCrc32, RTFILE_SEEK_BEGIN, NULL);
    if (RT_FAILURE(rc))
    {
        Log(("SSM: Failed to seek to crc start. rc=%Rrc\n", rc));
        return rc;
    }
    uint32_t u32CRC;
    rc = ssmR3CalcChecksum(File, pHdr->cbFile - *pcbFileHdr, &u32CRC);
    if (RT_FAILURE(rc))
        return rc;
    if (u32CRC != pHdr->u32CRC)
    {
        Log(("SSM: Invalid CRC! Calculated %#08x, in header %#08x\n", u32CRC, pHdr->u32CRC));
        return VERR_SSM_INTEGRITY_CRC;
    }

    /*
     * Verify Virtual Machine UUID.
     */
    RTUUID  Uuid;
    memset(&Uuid, 0, sizeof(Uuid));
/** @todo get machine uuids  CFGGetUuid(, &Uuid); */
    if (    RTUuidCompare(&pHdr->MachineUuid, &Uuid)
        &&  !RTUuidIsNull(&pHdr->MachineUuid)) /* temporary hack, allowing NULL uuids. */
    {
        Log(("SSM: The UUID of the saved state doesn't match the running VM.\n"));
        return VERR_SMM_INTEGRITY_MACHINE;
    }

    return VINF_SUCCESS;
}


/**
 * Find a data unit by name.
 *
 * @returns Pointer to the unit.
 * @returns NULL if not found.
 *
 * @param   pVM             VM handle.
 * @param   pszName         Data unit name.
 * @param   u32Instance     The data unit instance id.
 */
static PSSMUNIT ssmR3Find(PVM pVM, const char *pszName, uint32_t u32Instance)
{
    size_t   cchName = strlen(pszName);
    PSSMUNIT pUnit = pVM->ssm.s.pHead;
    while (     pUnit
           &&   (   pUnit->u32Instance != u32Instance
                 || pUnit->cchName != cchName
                 || memcmp(pUnit->szName, pszName, cchName)))
        pUnit = pUnit->pNext;
    return pUnit;
}


/**
 * Load VM save operation.
 *
 * @returns VBox status.
 *
 * @param   pVM             The VM handle.
 * @param   pszFilename     Name of the file to save the state in.
 * @param   enmAfter        What is planned after a successful load operation.
 *                          Only acceptable values are SSMAFTER_RESUME and SSMAFTER_DEBUG_IT.
 * @param   pfnProgress     Progress callback. Optional.
 * @param   pvUser          User argument for the progress callback.
 *
 * @thread  EMT
 */
VMMR3DECL(int) SSMR3Load(PVM pVM, const char *pszFilename, SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvUser)
{
    LogFlow(("SSMR3Load: pszFilename=%p:{%s} enmAfter=%d pfnProgress=%p pvUser=%p\n", pszFilename, pszFilename, enmAfter, pfnProgress, pvUser));
    VM_ASSERT_EMT(pVM);

    /*
     * Validate input.
     */
    if (    enmAfter != SSMAFTER_RESUME
        &&  enmAfter != SSMAFTER_DEBUG_IT)
    {
        AssertMsgFailed(("Invalid enmAfter=%d!\n", enmAfter));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Create the handle and open the file.
     * Note that we reserve 20% of the time on validating the image since this might
     * take a long time.
     */
    SSMHANDLE Handle = {0};
    Handle.File             = NIL_RTFILE;
    Handle.pVM              = pVM;
    Handle.cbFileHdr        = sizeof(SSMFILEHDR);
    Handle.enmOp            = SSMSTATE_INVALID;
    Handle.enmAfter         = enmAfter;
    Handle.rc               = VINF_SUCCESS;
    Handle.pZipComp         = NULL;
    Handle.pZipDecomp       = NULL;
    Handle.cbUnitLeft       = 0;
    Handle.offUnit          = UINT64_MAX;
    Handle.pfnProgress      = pfnProgress;
    Handle.pvUser           = pvUser;
    Handle.uPercent         = 0;
    Handle.offEstProgress   = 0;
    Handle.cbEstTotal       = 0;
    Handle.offEst           = 0;
    Handle.offEstUnitEnd    = 0;
    Handle.uPercentPrepare  = 20;
    Handle.uPercentDone     = 2;
    Handle.cbGCPhys         = sizeof(RTGCPHYS);
    Handle.cbGCPtr          = sizeof(RTGCPTR);
    Handle.fFixedGCPtrSize  = false;

    int rc = RTFileOpen(&Handle.File, pszFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
    if (RT_FAILURE(rc))
    {
        Log(("SSM: Failed to open save state file '%s', rc=%Rrc.\n",  pszFilename, rc));
        return rc;
    }

    /*
     * Read file header and validate it.
     */
    SSMFILEHDR Hdr;
    rc = ssmR3Validate(Handle.File, &Hdr, &Handle.cbFileHdr);
    if (RT_SUCCESS(rc))
    {
        if (Hdr.cbGCPhys)
            Handle.cbGCPhys = Hdr.cbGCPhys;
        if (Hdr.cbGCPtr)
        {
            Handle.cbGCPtr = Hdr.cbGCPtr;
            Handle.fFixedGCPtrSize = true;
        }

        if (Handle.cbFileHdr == sizeof(Hdr))
            LogRel(("SSM: File header: Format %.4s, VirtualBox Version %u.%u.%u r%u, %u-bit host, cbGCPhys=%u, cbGCPtr=%u\n",
                    &Hdr.achMagic[sizeof(SSMFILEHDR_MAGIC_BASE) - 1],
                    Hdr.u16VerMajor, Hdr.u16VerMinor, Hdr.u32VerBuild, Hdr.u32SvnRev,
                    Hdr.cHostBits, Hdr.cbGCPhys, Hdr.cbGCPtr));
        else
            LogRel(("SSM: File header: Format %.4s, %u-bit host, cbGCPhys=%u, cbGCPtr=%u\n" ,
                    &Hdr.achMagic[sizeof(SSMFILEHDR_MAGIC_BASE)-1], Hdr.cHostBits, Hdr.cbGCPhys, Hdr.cbGCPtr));


        /*
         * Clear the per unit flags.
         */
        PSSMUNIT pUnit;
        for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
            pUnit->fCalled = false;

        /*
         * Do the prepare run.
         */
        Handle.rc = VINF_SUCCESS;
        Handle.enmOp = SSMSTATE_LOAD_PREP;
        for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
        {
            switch (pUnit->enmType)
            {
                case SSMUNITTYPE_DEV:
                    if (pUnit->u.Dev.pfnLoadPrep)
                    {
                        rc = pUnit->u.Dev.pfnLoadPrep(pUnit->u.Dev.pDevIns, &Handle);
                        pUnit->fCalled = true;
                    }
                    break;
                case SSMUNITTYPE_DRV:
                    if (pUnit->u.Drv.pfnLoadPrep)
                    {
                        rc = pUnit->u.Drv.pfnLoadPrep(pUnit->u.Drv.pDrvIns, &Handle);
                        pUnit->fCalled = true;
                    }
                    break;
                case SSMUNITTYPE_INTERNAL:
                    if (pUnit->u.Internal.pfnLoadPrep)
                    {
                        rc = pUnit->u.Internal.pfnLoadPrep(pVM, &Handle);
                        pUnit->fCalled = true;
                    }
                    break;
                case SSMUNITTYPE_EXTERNAL:
                    if (pUnit->u.External.pfnLoadPrep)
                    {
                        rc = pUnit->u.External.pfnLoadPrep(&Handle, pUnit->u.External.pvUser);
                        pUnit->fCalled = true;
                    }
                    break;
            }
            if (RT_FAILURE(rc))
            {
                LogRel(("SSM: Prepare load failed with rc=%Rrc for data unit '%s.\n", rc, pUnit->szName));
                break;
            }
        }

        /* pending 2% */
        if (pfnProgress)
            pfnProgress(pVM, Handle.uPercentPrepare-1, pvUser);
        Handle.uPercent   = Handle.uPercentPrepare;
        Handle.cbEstTotal = Hdr.cbFile;

        /*
         * Do the execute run.
         */
        if (RT_SUCCESS(rc))
            rc = RTFileSeek(Handle.File, Handle.cbFileHdr, RTFILE_SEEK_BEGIN, NULL);
        if (RT_SUCCESS(rc))
        {
            char   *pszName = NULL;
            size_t  cchName = 0;
            Handle.enmOp = SSMSTATE_LOAD_EXEC;
            for (;;)
            {
                /*
                 * Save the current file position and read the data unit header.
                 */
                uint64_t        offUnit = RTFileTell(Handle.File);
                SSMFILEUNITHDR  UnitHdr;
                rc = RTFileRead(Handle.File, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDR, szName), NULL);
                if (RT_SUCCESS(rc))
                {
                    /*
                     * Check the magic and see if it's valid and whether it is a end header or not.
                     */
                    if (memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(SSMFILEUNITHDR_MAGIC)))
                    {
                        if (!memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_END, sizeof(SSMFILEUNITHDR_END)))
                        {
                            Log(("SSM: EndOfFile: offset %#9llx size %9d\n", offUnit, UnitHdr.cbUnit));
                            /* Complete the progress bar (pending 99% afterwards). */
                            Handle.offEstUnitEnd = Handle.cbEstTotal;
                            ssmR3Progress(&Handle, Handle.cbEstTotal - Handle.offEst);
                            break;
                        }
                        LogRel(("SSM: Invalid unit magic at offset %#llx (%lld), '%.*s'!\n",
                                offUnit, offUnit, sizeof(UnitHdr.achMagic) - 1, &UnitHdr.achMagic[0]));
                        rc = VERR_SSM_INTEGRITY_UNIT_MAGIC;
                        break;
                    }

                    /*
                     * Read the name.
                     * Adjust the name buffer first.
                     */
                    if (cchName < UnitHdr.cchName)
                    {
                        if (pszName)
                            RTMemTmpFree(pszName);
                        cchName = RT_ALIGN_Z(UnitHdr.cchName, 64);
                        pszName = (char *)RTMemTmpAlloc(cchName);
                    }
                    if (pszName)
                    {
                        rc = RTFileRead(Handle.File, pszName, UnitHdr.cchName, NULL);
                        if (RT_SUCCESS(rc))
                        {
                            if (!pszName[UnitHdr.cchName - 1])
                            {
                                Log(("SSM: Data unit: offset %#9llx size %9lld '%s'\n", offUnit, UnitHdr.cbUnit, pszName));

                                /*
                                 * Progress
                                 */
                                Handle.offEstUnitEnd += UnitHdr.cbUnit;

                                /*
                                 * Find the data unit in our internal table.
                                 */
                                pUnit = ssmR3Find(pVM, pszName, UnitHdr.u32Instance);
                                if (pUnit)
                                {
                                    /*
                                     * Call the execute handler.
                                     */
                                    Handle.cbUnitLeft = UnitHdr.cbUnit - RT_OFFSETOF(SSMFILEUNITHDR, szName[UnitHdr.cchName]);
                                    Handle.offUnit = 0;
                                    switch (pUnit->enmType)
                                    {
                                        case SSMUNITTYPE_DEV:
                                            if (pUnit->u.Dev.pfnLoadExec)
                                            {
                                                rc = pUnit->u.Dev.pfnLoadExec(pUnit->u.Dev.pDevIns, &Handle, UnitHdr.u32Version);
                                                AssertRC(rc);
                                            }
                                            else
                                                rc = VERR_SSM_NO_LOAD_EXEC;
                                            break;
                                        case SSMUNITTYPE_DRV:
                                            if (pUnit->u.Drv.pfnLoadExec)
                                            {
                                                rc = pUnit->u.Drv.pfnLoadExec(pUnit->u.Drv.pDrvIns, &Handle, UnitHdr.u32Version);
                                                AssertRC(rc);
                                            }
                                            else
                                                rc = VERR_SSM_NO_LOAD_EXEC;
                                            break;
                                        case SSMUNITTYPE_INTERNAL:
                                            if (pUnit->u.Internal.pfnLoadExec)
                                            {
                                                rc = pUnit->u.Internal.pfnLoadExec(pVM, &Handle, UnitHdr.u32Version);
                                                AssertRC(rc);
                                            }
                                            else
                                                rc = VERR_SSM_NO_LOAD_EXEC;
                                            break;
                                        case SSMUNITTYPE_EXTERNAL:
                                            if (pUnit->u.External.pfnLoadExec)
                                            {
                                                rc = pUnit->u.External.pfnLoadExec(&Handle, pUnit->u.External.pvUser, UnitHdr.u32Version);
                                                if (!rc)
                                                    rc = Handle.rc;
                                            }
                                            else
                                                rc = VERR_SSM_NO_LOAD_EXEC;
                                            break;
                                    }
                                    if (rc != VERR_SSM_NO_LOAD_EXEC)
                                    {
                                        /*
                                         * Close the reader stream.
                                         */
                                        if (Handle.pZipDecomp)
                                            ssmR3ReadFinish(&Handle);

                                        pUnit->fCalled = true;
                                        if (RT_SUCCESS(rc))
                                            rc = Handle.rc;
                                        if (RT_SUCCESS(rc))
                                        {
                                            /*
                                             * Now, we'll check the current position to see if all, or
                                             * more than all, the data was read.
                                             *
                                             * Note! Because of buffering / compression we'll only see the
                                             * really bad ones here.
                                             */
                                            uint64_t off = RTFileTell(Handle.File);
                                            int64_t i64Diff = off - (offUnit + UnitHdr.cbUnit);
                                            if (i64Diff < 0)
                                            {
                                                Log(("SSM: Unit '%s' left %lld bytes unread!\n", pszName, -i64Diff));
                                                rc = RTFileSeek(Handle.File, offUnit + UnitHdr.cbUnit, RTFILE_SEEK_BEGIN, NULL);
                                            }
                                            else if (i64Diff > 0)
                                            {
                                                LogRel(("SSM: Unit '%s' read %lld bytes too much!\n", pszName, i64Diff));
                                                rc = VERR_SSM_INTEGRITY;
                                                break;
                                            }

                                            /* Advance the progress bar to the end of the block. */
                                            ssmR3Progress(&Handle, Handle.offEstUnitEnd - Handle.offEst);
                                        }
                                        else
                                        {
                                            /*
                                             * We failed, but if loading for the debugger ignore certain failures
                                             * just to get it all loaded (big hack).
                                             */
                                            LogRel(("SSM: LoadExec failed with rc=%Rrc for unit '%s'!\n", rc, pszName));
                                            if (    Handle.enmAfter != SSMAFTER_DEBUG_IT
                                                ||  rc != VERR_SSM_LOADED_TOO_MUCH)
                                                break;
                                            Handle.rc = rc = VINF_SUCCESS;
                                            ssmR3Progress(&Handle, Handle.offEstUnitEnd - Handle.offEst);
                                        }
                                        Handle.offUnit = UINT64_MAX;
                                    }
                                    else
                                    {
                                        LogRel(("SSM: No load exec callback for unit '%s'!\n", pszName));
                                        rc = VERR_SSM_INTEGRITY;
                                        break;
                                    }
                                }
                                else
                                {
                                    /*
                                     * SSM unit wasn't found - ignore this when loading for the debugger.
                                     */
                                    LogRel(("SSM: Found no handler for unit '%s'!\n", pszName));
                                    rc = VERR_SSM_INTEGRITY_UNIT_NOT_FOUND;
                                    if (Handle.enmAfter != SSMAFTER_DEBUG_IT)
                                        break;
                                    rc = RTFileSeek(Handle.File, offUnit + UnitHdr.cbUnit, RTFILE_SEEK_BEGIN, NULL);
                                }
                            }
                            else
                            {
                                LogRel(("SSM: Unit name '%.*s' was not properly terminated.\n", UnitHdr.cchName, pszName));
                                rc = VERR_SSM_INTEGRITY;
                                break;
                            }
                        }
                    }
                    else
                        rc = VERR_NO_TMP_MEMORY;
                }

                /*
                 * I/O errors ends up here (yea, I know, very nice programming).
                 */
                if (RT_FAILURE(rc))
                {
                    LogRel(("SSM: I/O error. rc=%Rrc\n", rc));
                    break;
                }
            }
        }
        /* (progress should be pending 99% now) */
        AssertMsg(RT_FAILURE(rc) || Handle.uPercent == (101-Handle.uPercentDone), ("%d\n", Handle.uPercent));

        /*
         * Do the done run.
         */
        Handle.rc = rc;
        Handle.enmOp = SSMSTATE_LOAD_DONE;
        for (pUnit = pVM->ssm.s.pHead; pUnit; pUnit = pUnit->pNext)
        {
            rc = VINF_SUCCESS;
            switch (pUnit->enmType)
            {
                case SSMUNITTYPE_DEV:
                    if (    pUnit->u.Dev.pfnLoadDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Dev.pfnLoadPrep && !pUnit->u.Dev.pfnLoadExec)))
                        rc = pUnit->u.Dev.pfnLoadDone(pUnit->u.Dev.pDevIns, &Handle);
                    break;
                case SSMUNITTYPE_DRV:
                    if (    pUnit->u.Drv.pfnLoadDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Drv.pfnLoadPrep && !pUnit->u.Drv.pfnLoadExec)))
                        rc = pUnit->u.Drv.pfnLoadDone(pUnit->u.Drv.pDrvIns, &Handle);
                    break;
                case SSMUNITTYPE_INTERNAL:
                    if (pUnit->u.Internal.pfnLoadDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Internal.pfnLoadPrep && !pUnit->u.Internal.pfnLoadExec)))
                        rc = pUnit->u.Internal.pfnLoadDone(pVM, &Handle);
                    break;
                case SSMUNITTYPE_EXTERNAL:
                    if (pUnit->u.External.pfnLoadDone
                        &&  (   pUnit->fCalled
                             || (!pUnit->u.Internal.pfnLoadPrep && !pUnit->u.Internal.pfnLoadExec)))
                        rc = pUnit->u.External.pfnLoadDone(&Handle, pUnit->u.External.pvUser);
                    break;
            }
            if (RT_FAILURE(rc))
            {
                LogRel(("SSM: Done load failed with rc=%Rrc for data unit '%s'.\n", rc, pUnit->szName));
                if (RT_SUCCESS(Handle.rc))
                    Handle.rc = rc;
            }
        }
        rc = Handle.rc;

        /* progress */
        if (pfnProgress)
            pfnProgress(pVM, 99, pvUser);
    }

    /*
     * Done
     */
    int rc2 = RTFileClose(Handle.File);
    AssertRC(rc2);
    if (RT_SUCCESS(rc))
    {
        /* progress */
        if (pfnProgress)
            pfnProgress(pVM, 100, pvUser);
        Log(("SSM: Load of '%s' completed!\n", pszFilename));
        Log(("\n\n\n"));
        DBGFR3InfoLog(pVM, "cpum", "verbose");
        DBGFR3InfoLog(pVM, "timers", NULL);
        DBGFR3InfoLog(pVM, "activetimers", NULL);
        DBGFR3InfoLog(pVM, "ioport", NULL);
        DBGFR3InfoLog(pVM, "mmio", NULL);
        DBGFR3InfoLog(pVM, "phys", NULL);
        Log(("\n\n\n"));
    }
    return rc;
}


/**
 * Validates a file as a validate SSM saved state.
 *
 * This will only verify the file format, the format and content of individual
 * data units are not inspected.
 *
 * @returns VINF_SUCCESS if valid.
 * @returns VBox status code on other failures.
 *
 * @param   pszFilename     The path to the file to validate.
 *
 * @thread  Any.
 */
VMMR3DECL(int) SSMR3ValidateFile(const char *pszFilename)
{
    LogFlow(("SSMR3ValidateFile: pszFilename=%p:{%s}\n", pszFilename, pszFilename));

    /*
     * Try open the file and validate it.
     */
    RTFILE File;
    int rc = RTFileOpen(&File, pszFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
    if (RT_SUCCESS(rc))
    {
        size_t cbFileHdr;
        SSMFILEHDR Hdr;
        rc = ssmR3Validate(File, &Hdr, &cbFileHdr);
        RTFileClose(File);
    }
    else
        Log(("SSM: Failed to open saved state file '%s', rc=%Rrc.\n",  pszFilename, rc));
    return rc;
}


/**
 * Opens a saved state file for reading.
 *
 * @returns VBox status code.
 *
 * @param   pszFilename     The path to the saved state file.
 * @param   fFlags          Open flags. Reserved, must be 0.
 * @param   ppSSM           Where to store the SSM handle.
 *
 * @thread  Any.
 */
VMMR3DECL(int) SSMR3Open(const char *pszFilename, unsigned fFlags, PSSMHANDLE *ppSSM)
{
    LogFlow(("SSMR3Open: pszFilename=%p:{%s} fFlags=%#x ppSSM=%p\n", pszFilename, pszFilename, fFlags, ppSSM));

    /*
     * Validate input.
     */
    AssertMsgReturn(VALID_PTR(pszFilename), ("%p\n", pszFilename), VERR_INVALID_PARAMETER);
    AssertMsgReturn(!fFlags, ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
    AssertMsgReturn(VALID_PTR(ppSSM), ("%p\n", ppSSM), VERR_INVALID_PARAMETER);

    /*
     * Allocate a handle.
     */
    PSSMHANDLE pSSM = (PSSMHANDLE)RTMemAllocZ(sizeof(*pSSM));
    AssertReturn(pSSM, VERR_NO_MEMORY);

    /*
     * Try open the file and validate it.
     */
    int rc = RTFileOpen(&pSSM->File, pszFilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
    if (RT_SUCCESS(rc))
    {
        SSMFILEHDR Hdr;
        size_t cbFileHdr;
        rc = ssmR3Validate(pSSM->File, &Hdr, &cbFileHdr);
        if (RT_SUCCESS(rc))
        {
            //pSSM->pVM           = NULL;
            pSSM->cbFileHdr       = cbFileHdr;
            pSSM->enmOp           = SSMSTATE_OPEN_READ;
            pSSM->enmAfter        = SSMAFTER_OPENED;
            //pSSM->rc            = VINF_SUCCESS;
            //pSSM->pZipComp      = NULL;
            //pSSM->pZipDecomp    = NULL;
            //pSSM->cbUnitLeft    = 0;
            pSSM->offUnit         = UINT64_MAX;
            //pSSM->pfnProgress   = NULL;
            //pSSM->pvUser        = NULL;
            //pSSM->uPercent      = 0;
            //pSSM->offEstProgress= 0;
            //pSSM->cbEstTotal    = 0;
            //pSSM->offEst        = 0;
            //pSSM->offEstUnitEnd = 0;
            pSSM->uPercentPrepare = 20;
            pSSM->uPercentDone    = 2;
            pSSM->cbGCPhys        = Hdr.cbGCPhys ? Hdr.cbGCPhys : sizeof(RTGCPHYS);
            pSSM->cbGCPtr         = sizeof(RTGCPTR);
            pSSM->fFixedGCPtrSize = false;
            if (Hdr.cbGCPtr)
            {
                pSSM->cbGCPtr         = Hdr.cbGCPtr;
                pSSM->fFixedGCPtrSize = true;
            }

            *ppSSM = pSSM;
            LogFlow(("SSMR3Open: returns VINF_SUCCESS *ppSSM=%p\n", *ppSSM));
            return VINF_SUCCESS;
        }

        Log(("SSMR3Open: Validation of '%s' failed, rc=%Rrc.\n",  pszFilename, rc));
        RTFileClose(pSSM->File);
    }
    else
        Log(("SSMR3Open: Failed to open saved state file '%s', rc=%Rrc.\n",  pszFilename, rc));
    RTMemFree(pSSM);
    return rc;

}


/**
 * Closes a saved state file opened by SSMR3Open().
 *
 * @returns VBox status code.
 *
 * @param   pSSM            The SSM handle returned by SSMR3Open().
 *
 * @thread  Any, but the caller is responsible for serializing calls per handle.
 */
VMMR3DECL(int) SSMR3Close(PSSMHANDLE pSSM)
{
    LogFlow(("SSMR3Close: pSSM=%p\n", pSSM));

    /*
     * Validate input.
     */
    AssertMsgReturn(VALID_PTR(pSSM), ("%p\n", pSSM), VERR_INVALID_PARAMETER);
    AssertMsgReturn(pSSM->enmAfter == SSMAFTER_OPENED, ("%d\n", pSSM->enmAfter),VERR_INVALID_PARAMETER);
    AssertMsgReturn(pSSM->enmOp == SSMSTATE_OPEN_READ, ("%d\n", pSSM->enmOp), VERR_INVALID_PARAMETER);

    /*
     * Close the file and free the handle.
     */
    int rc = RTFileClose(pSSM->File);
    AssertRC(rc);
    RTMemFree(pSSM);
    return rc;
}


/**
 * Seeks to a specific data unit.
 *
 * After seeking it's possible to use the getters to on
 * that data unit.
 *
 * @returns VBox status code.
 * @returns VERR_SSM_UNIT_NOT_FOUND if the unit+instance wasn't found.
 *
 * @param   pSSM            The SSM handle returned by SSMR3Open().
 * @param   pszUnit         The name of the data unit.
 * @param   iInstance       The instance number.
 * @param   piVersion       Where to store the version number. (Optional)
 *
 * @thread  Any, but the caller is responsible for serializing calls per handle.
 */
VMMR3DECL(int) SSMR3Seek(PSSMHANDLE pSSM, const char *pszUnit, uint32_t iInstance, uint32_t *piVersion)
{
    LogFlow(("SSMR3Seek: pSSM=%p pszUnit=%p:{%s} iInstance=%RU32 piVersion=%p\n",
             pSSM, pszUnit, pszUnit, iInstance, piVersion));

    /*
     * Validate input.
     */
    AssertMsgReturn(VALID_PTR(pSSM), ("%p\n", pSSM), VERR_INVALID_PARAMETER);
    AssertMsgReturn(pSSM->enmAfter == SSMAFTER_OPENED, ("%d\n", pSSM->enmAfter),VERR_INVALID_PARAMETER);
    AssertMsgReturn(pSSM->enmOp == SSMSTATE_OPEN_READ, ("%d\n", pSSM->enmOp), VERR_INVALID_PARAMETER);
    AssertMsgReturn(VALID_PTR(pszUnit), ("%p\n", pszUnit), VERR_INVALID_POINTER);
    AssertMsgReturn(!piVersion || VALID_PTR(piVersion), ("%p\n", piVersion), VERR_INVALID_POINTER);

    /*
     * Reset the state.
     */
    if (pSSM->pZipDecomp)
    {
        RTZipDecompDestroy(pSSM->pZipDecomp);
        pSSM->pZipDecomp = NULL;
    }
    pSSM->rc            = VERR_SSM_UNIT_NOT_FOUND;
    pSSM->cbUnitLeft    = 0;
    pSSM->offUnit       = UINT64_MAX;

    /*
     * Walk the data units until we find EOF or a match.
     */
    size_t  cchUnit = strlen(pszUnit) + 1;
    int     rc = VINF_SUCCESS;
    char   *pszName = NULL;
    size_t  cchName = 0;
    SSMFILEUNITHDR  UnitHdr;
    for (RTFOFF off = pSSM->cbFileHdr; ; off += UnitHdr.cbUnit)
    {
        /*
         * Read the unit header and verify it.
         */
        rc = RTFileReadAt(pSSM->File, off, &UnitHdr, RT_OFFSETOF(SSMFILEUNITHDR, szName), NULL);
        AssertRC(rc);
        if (RT_SUCCESS(rc))
        {
            if (!memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_MAGIC, sizeof(SSMFILEUNITHDR_MAGIC)))
            {
                /*
                 * Does it match thus far or should we just skip along?
                 */
                if (    UnitHdr.u32Instance != iInstance
                    &&  UnitHdr.cchName != cchUnit)
                    continue;

                /*
                 * Read the name.
                 * Adjust the name buffer first.
                 */
                if (cchName < UnitHdr.cchName)
                {
                    if (pszName)
                        RTMemTmpFree(pszName);
                    cchName = RT_ALIGN_Z(UnitHdr.cchName, 64);
                    pszName = (char *)RTMemTmpAlloc(cchName);
                }
                rc = VERR_NO_MEMORY;
                if (pszName)
                {
                    rc = RTFileRead(pSSM->File, pszName, UnitHdr.cchName, NULL);
                    AssertRC(rc);
                    if (RT_SUCCESS(rc))
                    {
                        if (!pszName[UnitHdr.cchName - 1])
                        {
                            /*
                             * Does the name match? If not continue with the next item.
                             */
                            if (memcmp(pszName, pszUnit, cchUnit))
                                continue;

                            pSSM->rc = rc = VINF_SUCCESS;
                            pSSM->cbUnitLeft = UnitHdr.cbUnit - RT_OFFSETOF(SSMFILEUNITHDR, szName[UnitHdr.cchName]);
                            pSSM->offUnit = 0;
                            if (piVersion)
                                *piVersion = UnitHdr.u32Version;
                        }
                        else
                        {
                            AssertMsgFailed((" Unit name '%.*s' was not properly terminated.\n", UnitHdr.cchName, pszName));
                            rc = VERR_SSM_INTEGRITY;
                        }
                    }
                }
            }
            else
            {
                if (!memcmp(&UnitHdr.achMagic[0], SSMFILEUNITHDR_END, sizeof(SSMFILEUNITHDR_END)))
                    rc = VERR_SSM_UNIT_NOT_FOUND;
                else
                {
                    AssertMsgFailed(("Invalid unit magic at offset %RTfoff, '%.*s'!\n",
                                     off, sizeof(UnitHdr.achMagic) - 1, &UnitHdr.achMagic[0]));
                    rc = VERR_SSM_INTEGRITY_UNIT_MAGIC;
                }
            }
        }

        /* error or success, two continue statements cover the iterating */
        break;
    }

    RTMemFree(pszName);
    return rc;
}


/**
 * Finishes a data unit.
 * All buffers and compressor instances are flushed and destroyed.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 */
static int ssmR3WriteFinish(PSSMHANDLE pSSM)
{
    //Log2(("ssmR3WriteFinish: %#010llx start\n", RTFileTell(pSSM->File)));
    if (!pSSM->pZipComp)
        return VINF_SUCCESS;

    int rc = RTZipCompFinish(pSSM->pZipComp);
    if (RT_SUCCESS(rc))
    {
        rc = RTZipCompDestroy(pSSM->pZipComp);
        if (RT_SUCCESS(rc))
        {
            pSSM->pZipComp = NULL;
            //Log2(("ssmR3WriteFinish: %#010llx done\n", RTFileTell(pSSM->File)));
            return VINF_SUCCESS;
        }
    }
    if (RT_SUCCESS(pSSM->rc))
        pSSM->rc = rc;
    Log2(("ssmR3WriteFinish: failure rc=%Rrc\n", rc));
    return rc;
}


/**
 * Writes something to the current data item in the saved state file.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pvBuf           The bits to write.
 * @param   cbBuf           The number of bytes to write.
 */
static int ssmR3Write(PSSMHANDLE pSSM, const void *pvBuf, size_t cbBuf)
{
    Log2(("ssmR3Write: pvBuf=%p cbBuf=%#x %.*Rhxs%s\n", pvBuf, cbBuf, RT_MIN(cbBuf, 128), pvBuf, cbBuf > 128 ? "..." : ""));

    /*
     * Check that everything is fine.
     */
    if (RT_SUCCESS(pSSM->rc))
    {
        /*
         * First call starts the compression.
         */
        if (!pSSM->pZipComp)
        {
            //int rc = RTZipCompCreate(&pSSM->pZipComp, pSSM, ssmR3WriteOut, RTZIPTYPE_ZLIB, RTZIPLEVEL_FAST);
            int rc = RTZipCompCreate(&pSSM->pZipComp, pSSM, ssmR3WriteOut, RTZIPTYPE_LZF, RTZIPLEVEL_FAST);
            //int rc = RTZipCompCreate(&pSSM->pZipComp, pSSM, ssmR3WriteOut, RTZIPTYPE_STORE, RTZIPLEVEL_FAST);
            if (RT_FAILURE(rc))
                return rc;
        }

        /*
         * Write the data item in 128kb chunks for progress indicator reasons.
         */
        while (cbBuf > 0)
        {
            size_t cbChunk = RT_MIN(cbBuf, 128*1024);
            pSSM->rc = RTZipCompress(pSSM->pZipComp, pvBuf, cbChunk);
            if (RT_FAILURE(pSSM->rc))
                break;
            ssmR3Progress(pSSM, cbChunk);
            pSSM->offUnit += cbChunk;
            cbBuf -= cbChunk;
            pvBuf = (char *)pvBuf + cbChunk;
        }
    }

    return pSSM->rc;
}


/**
 * Callback for flusing the output buffer of a compression stream.
 *
 * @returns VBox status.
 * @param   pvSSM           SSM operation handle.
 * @param   pvBuf           Compressed data.
 * @param   cbBuf           Size of the compressed data.
 */
static DECLCALLBACK(int) ssmR3WriteOut(void *pvSSM, const void *pvBuf, size_t cbBuf)
{
    //Log2(("ssmR3WriteOut: %#010llx cbBuf=%#x\n", RTFileTell(((PSSMHANDLE)pvSSM)->File), cbBuf));
    int rc = RTFileWrite(((PSSMHANDLE)pvSSM)->File, pvBuf, cbBuf, NULL);
    if (RT_SUCCESS(rc))
        return rc;
    Log(("ssmR3WriteOut: RTFileWrite(,,%d) -> %d\n", cbBuf, rc));
    return rc;
}


/**
 * Puts a structure.
 *
 * @returns VBox status code.
 * @param   pSSM            The saved state handle.
 * @param   pvStruct        The structure address.
 * @param   paFields        The array of structure fields descriptions.
 *                          The array must be terminated by a SSMFIELD_ENTRY_TERM().
 */
VMMR3DECL(int) SSMR3PutStruct(PSSMHANDLE pSSM, const void *pvStruct, PCSSMFIELD paFields)
{
    /* begin marker. */
    int rc = SSMR3PutU32(pSSM, SSMR3STRUCT_BEGIN);
    if (RT_FAILURE(rc))
        return rc;

    /* put the fields */
    for (PCSSMFIELD pCur = paFields;
         pCur->cb != UINT32_MAX && pCur->off != UINT32_MAX;
         pCur++)
    {
        rc = ssmR3Write(pSSM, (uint8_t *)pvStruct + pCur->off, pCur->cb);
        if (RT_FAILURE(rc))
            return rc;
    }

    /* end marker */
    return SSMR3PutU32(pSSM, SSMR3STRUCT_END);
}


/**
 * Saves a boolean item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   fBool           Item to save.
 */
VMMR3DECL(int) SSMR3PutBool(PSSMHANDLE pSSM, bool fBool)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
    {
        uint8_t u8 = fBool; /* enforce 1 byte size */
        return ssmR3Write(pSSM, &u8, sizeof(u8));
    }
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 8-bit unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u8              Item to save.
 */
VMMR3DECL(int) SSMR3PutU8(PSSMHANDLE pSSM, uint8_t u8)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u8, sizeof(u8));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 8-bit signed integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   i8              Item to save.
 */
VMMR3DECL(int) SSMR3PutS8(PSSMHANDLE pSSM, int8_t i8)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &i8, sizeof(i8));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 16-bit unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u16             Item to save.
 */
VMMR3DECL(int) SSMR3PutU16(PSSMHANDLE pSSM, uint16_t u16)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u16, sizeof(u16));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 16-bit signed integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   i16             Item to save.
 */
VMMR3DECL(int) SSMR3PutS16(PSSMHANDLE pSSM, int16_t i16)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &i16, sizeof(i16));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 32-bit unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u32             Item to save.
 */
VMMR3DECL(int) SSMR3PutU32(PSSMHANDLE pSSM, uint32_t u32)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u32, sizeof(u32));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 32-bit signed integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   i32             Item to save.
 */
VMMR3DECL(int) SSMR3PutS32(PSSMHANDLE pSSM, int32_t i32)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &i32, sizeof(i32));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 64-bit unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u64             Item to save.
 */
VMMR3DECL(int) SSMR3PutU64(PSSMHANDLE pSSM, uint64_t u64)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u64, sizeof(u64));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 64-bit signed integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   i64             Item to save.
 */
VMMR3DECL(int) SSMR3PutS64(PSSMHANDLE pSSM, int64_t i64)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &i64, sizeof(i64));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 128-bit unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u128            Item to save.
 */
VMMR3DECL(int) SSMR3PutU128(PSSMHANDLE pSSM, uint128_t u128)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u128, sizeof(u128));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 128-bit signed integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   i128            Item to save.
 */
VMMR3DECL(int) SSMR3PutS128(PSSMHANDLE pSSM, int128_t i128)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &i128, sizeof(i128));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a VBox unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u               Item to save.
 */
VMMR3DECL(int) SSMR3PutUInt(PSSMHANDLE pSSM, RTUINT u)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u, sizeof(u));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a VBox signed integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   i               Item to save.
 */
VMMR3DECL(int) SSMR3PutSInt(PSSMHANDLE pSSM, RTINT i)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &i, sizeof(i));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a GC natural unsigned integer item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u               Item to save.
 *
 * @deprecated Silly type, don't use it.
 */
VMMR3DECL(int) SSMR3PutGCUInt(PSSMHANDLE pSSM, RTGCUINT u)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u, sizeof(u));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a GC unsigned integer register item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   u               Item to save.
 */
VMMR3DECL(int) SSMR3PutGCUIntReg(PSSMHANDLE pSSM, RTGCUINTREG u)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &u, sizeof(u));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 32 bits GC physical address item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   GCPhys          The item to save
 */
VMMR3DECL(int) SSMR3PutGCPhys32(PSSMHANDLE pSSM, RTGCPHYS32 GCPhys)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &GCPhys, sizeof(GCPhys));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a 64 bits GC physical address item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   GCPhys          The item to save
 */
VMMR3DECL(int) SSMR3PutGCPhys64(PSSMHANDLE pSSM, RTGCPHYS64 GCPhys)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &GCPhys, sizeof(GCPhys));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a GC physical address item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   GCPhys          The item to save
 */
VMMR3DECL(int) SSMR3PutGCPhys(PSSMHANDLE pSSM, RTGCPHYS GCPhys)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &GCPhys, sizeof(GCPhys));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a GC virtual address item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   GCPtr           The item to save.
 */
VMMR3DECL(int) SSMR3PutGCPtr(PSSMHANDLE pSSM, RTGCPTR GCPtr)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &GCPtr, sizeof(GCPtr));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves an RC virtual address item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   RCPtr           The item to save.
 */
VMMR3DECL(int) SSMR3PutRCPtr(PSSMHANDLE pSSM, RTRCPTR RCPtr)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &RCPtr, sizeof(RCPtr));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a GC virtual address (represented as an unsigned integer) item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   GCPtr           The item to save.
 */
VMMR3DECL(int) SSMR3PutGCUIntPtr(PSSMHANDLE pSSM, RTGCUINTPTR GCPtr)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &GCPtr, sizeof(GCPtr));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a I/O port address item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   IOPort          The item to save.
 */
VMMR3DECL(int) SSMR3PutIOPort(PSSMHANDLE pSSM, RTIOPORT IOPort)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &IOPort, sizeof(IOPort));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a selector item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   Sel             The item to save.
 */
VMMR3DECL(int) SSMR3PutSel(PSSMHANDLE pSSM, RTSEL Sel)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, &Sel, sizeof(Sel));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a memory item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pv              Item to save.
 * @param   cb              Size of the item.
 */
VMMR3DECL(int) SSMR3PutMem(PSSMHANDLE pSSM, const void *pv, size_t cb)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
        return ssmR3Write(pSSM, pv, cb);
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Saves a zero terminated string item to the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   psz             Item to save.
 */
VMMR3DECL(int) SSMR3PutStrZ(PSSMHANDLE pSSM, const char *psz)
{
    if (pSSM->enmOp == SSMSTATE_SAVE_EXEC)
    {
        size_t cch = strlen(psz);
        if (cch > 1024*1024)
        {
            AssertMsgFailed(("a %d byte long string, what's this!?!\n"));
            return VERR_TOO_MUCH_DATA;
        }
        uint32_t u32 = (uint32_t)cch;
        int rc = ssmR3Write(pSSM, &u32, sizeof(u32));
        if (rc)
            return rc;
        return ssmR3Write(pSSM, psz, cch);
    }
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}





/**
 * Closes the decompressor of a data unit.
 *
 * @param   pSSM            SSM operation handle.
 */
static void ssmR3ReadFinish(PSSMHANDLE pSSM)
{
    int rc = RTZipDecompDestroy(pSSM->pZipDecomp);
    AssertRC(rc);
    pSSM->pZipDecomp = NULL;
}


/**
 * Internal read worker.
 *
 * @param   pSSM            SSM operation handle.
 * @param   pvBuf           Where to store the read data.
 * @param   cbBuf           Number of bytes to read.
 */
static int ssmR3Read(PSSMHANDLE pSSM, void *pvBuf, size_t cbBuf)
{
    /*
     * Check that everything is fine.
     */
    if (RT_SUCCESS(pSSM->rc))
    {
        /*
         * Open the decompressor on the first read.
         */
        if (!pSSM->pZipDecomp)
        {
            pSSM->rc = RTZipDecompCreate(&pSSM->pZipDecomp, pSSM, ssmR3ReadIn);
            if (RT_FAILURE(pSSM->rc))
                return pSSM->rc;
        }

        /*
         * Do the requested read.
         * Use 32kb chunks to work the progress indicator.
         */
        pSSM->rc = RTZipDecompress(pSSM->pZipDecomp, pvBuf, cbBuf, NULL);
        if (RT_SUCCESS(pSSM->rc))
        {
            Log2(("ssmR3Read: pvBuf=%p cbBuf=%#x %.*Rhxs%s\n", pvBuf, cbBuf, RT_MIN(cbBuf, 128), pvBuf, cbBuf > 128 ? "..." : ""));
            pSSM->offUnit += cbBuf;
        }
        else
            AssertMsgFailed(("rc=%Rrc cbBuf=%#x\n", pSSM->rc, cbBuf));
    }

    return pSSM->rc;
}


/**
 * Callback for reading compressed data into the input buffer of the
 * decompressor.
 *
 * @returns VBox status code.
 * @param   pvSSM       The SSM handle.
 * @param   pvBuf       Where to store the compressed data.
 * @param   cbBuf       Size of the buffer.
 * @param   pcbRead     Number of bytes actually stored in the buffer.
 */
static DECLCALLBACK(int) ssmR3ReadIn(void *pvSSM, void *pvBuf, size_t cbBuf, size_t *pcbRead)
{
    PSSMHANDLE pSSM = (PSSMHANDLE)pvSSM;
    size_t cbRead = cbBuf;
    if (pSSM->cbUnitLeft < cbBuf)
        cbRead = (size_t)pSSM->cbUnitLeft;
    if (cbRead)
    {
        //Log2(("ssmR3ReadIn: %#010llx cbBug=%#x cbRead=%#x\n", RTFileTell(pSSM->File), cbBuf, cbRead));
        int rc = RTFileRead(pSSM->File, pvBuf, cbRead, NULL);
        if (RT_SUCCESS(rc))
        {
            pSSM->cbUnitLeft -= cbRead;
            if (pcbRead)
                *pcbRead = cbRead;
            ssmR3Progress(pSSM, cbRead);
            return VINF_SUCCESS;
        }
        Log(("ssmR3ReadIn: RTFileRead(,,%d) -> %d\n", cbRead, rc));
        return rc;
    }

    /** @todo weed out lazy saving */
    if (pSSM->enmAfter != SSMAFTER_DEBUG_IT)
        AssertMsgFailed(("SSM: attempted reading more than the unit!\n"));
    return VERR_SSM_LOADED_TOO_MUCH;
}


/**
 * Gets a structure.
 *
 * @returns VBox status code.
 * @param   pSSM            The saved state handle.
 * @param   pvStruct        The structure address.
 * @param   paFields        The array of structure fields descriptions.
 *                          The array must be terminated by a SSMFIELD_ENTRY_TERM().
 */
VMMR3DECL(int) SSMR3GetStruct(PSSMHANDLE pSSM, void *pvStruct, PCSSMFIELD paFields)
{
    /* begin marker. */
    uint32_t u32Magic;
    int rc = SSMR3GetU32(pSSM, &u32Magic);
    if (RT_FAILURE(rc))
        return rc;
    if (u32Magic != SSMR3STRUCT_BEGIN)
        AssertMsgFailedReturn(("u32Magic=%#RX32\n", u32Magic), VERR_SSM_STRUCTURE_MAGIC);

    /* put the fields */
    for (PCSSMFIELD pCur = paFields;
         pCur->cb != UINT32_MAX && pCur->off != UINT32_MAX;
         pCur++)
    {
        rc = ssmR3Read(pSSM, (uint8_t *)pvStruct + pCur->off, pCur->cb);
        if (RT_FAILURE(rc))
            return rc;
    }

    /* end marker */
    rc = SSMR3GetU32(pSSM, &u32Magic);
    if (RT_FAILURE(rc))
        return rc;
    if (u32Magic != SSMR3STRUCT_END)
        AssertMsgFailedReturn(("u32Magic=%#RX32\n", u32Magic), VERR_SSM_STRUCTURE_MAGIC);
    return rc;
}


/**
 * Loads a boolean item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pfBool          Where to store the item.
 */
VMMR3DECL(int) SSMR3GetBool(PSSMHANDLE pSSM, bool *pfBool)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
    {
        uint8_t u8; /* see SSMR3PutBool */
        int rc = ssmR3Read(pSSM, &u8, sizeof(u8));
        if (RT_SUCCESS(rc))
        {
            Assert(u8 <= 1);
            *pfBool = !!u8;
        }
        return rc;
    }
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 8-bit unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu8             Where to store the item.
 */
VMMR3DECL(int) SSMR3GetU8(PSSMHANDLE pSSM, uint8_t *pu8)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pu8, sizeof(*pu8));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 8-bit signed integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pi8             Where to store the item.
 */
VMMR3DECL(int) SSMR3GetS8(PSSMHANDLE pSSM, int8_t *pi8)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pi8, sizeof(*pi8));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 16-bit unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu16            Where to store the item.
 */
VMMR3DECL(int) SSMR3GetU16(PSSMHANDLE pSSM, uint16_t *pu16)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pu16, sizeof(*pu16));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 16-bit signed integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pi16            Where to store the item.
 */
VMMR3DECL(int) SSMR3GetS16(PSSMHANDLE pSSM, int16_t *pi16)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pi16, sizeof(*pi16));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 32-bit unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu32            Where to store the item.
 */
VMMR3DECL(int) SSMR3GetU32(PSSMHANDLE pSSM, uint32_t *pu32)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pu32, sizeof(*pu32));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 32-bit signed integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pi32            Where to store the item.
 */
VMMR3DECL(int) SSMR3GetS32(PSSMHANDLE pSSM, int32_t *pi32)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pi32, sizeof(*pi32));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 64-bit unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu64            Where to store the item.
 */
VMMR3DECL(int) SSMR3GetU64(PSSMHANDLE pSSM, uint64_t *pu64)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pu64, sizeof(*pu64));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 64-bit signed integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pi64            Where to store the item.
 */
VMMR3DECL(int) SSMR3GetS64(PSSMHANDLE pSSM, int64_t *pi64)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pi64, sizeof(*pi64));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 128-bit unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu128           Where to store the item.
 */
VMMR3DECL(int) SSMR3GetU128(PSSMHANDLE pSSM, uint128_t *pu128)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pu128, sizeof(*pu128));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 128-bit signed integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pi128           Where to store the item.
 */
VMMR3DECL(int) SSMR3GetS128(PSSMHANDLE pSSM, int128_t *pi128)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pi128, sizeof(*pi128));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a VBox unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu              Where to store the integer.
 */
VMMR3DECL(int) SSMR3GetUInt(PSSMHANDLE pSSM, PRTUINT pu)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pu, sizeof(*pu));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a VBox signed integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pi              Where to store the integer.
 */
VMMR3DECL(int) SSMR3GetSInt(PSSMHANDLE pSSM, PRTINT pi)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pi, sizeof(*pi));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a GC natural unsigned integer item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu              Where to store the integer.
 *
 * @deprecated Silly type with an incorrect size, don't use it.
 */
VMMR3DECL(int) SSMR3GetGCUInt(PSSMHANDLE pSSM, PRTGCUINT pu)
{
    AssertCompile(sizeof(RTGCPTR) == sizeof(*pu));
    return SSMR3GetGCPtr(pSSM, (PRTGCPTR)pu);
}


/**
 * Loads a GC unsigned integer register item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pu              Where to store the integer.
 */
VMMR3DECL(int) SSMR3GetGCUIntReg(PSSMHANDLE pSSM, PRTGCUINTREG pu)
{
    AssertCompile(sizeof(RTGCPTR) == sizeof(*pu));
    return SSMR3GetGCPtr(pSSM, (PRTGCPTR)pu);
}


/**
 * Loads a 32 bits GC physical address item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pGCPhys         Where to store the GC physical address.
 */
VMMR3DECL(int) SSMR3GetGCPhys32(PSSMHANDLE pSSM, PRTGCPHYS32 pGCPhys)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pGCPhys, sizeof(*pGCPhys));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a 64 bits GC physical address item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pGCPhys         Where to store the GC physical address.
 */
VMMR3DECL(int) SSMR3GetGCPhys64(PSSMHANDLE pSSM, PRTGCPHYS64 pGCPhys)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pGCPhys, sizeof(*pGCPhys));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a GC physical address item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pGCPhys         Where to store the GC physical address.
 */
VMMR3DECL(int) SSMR3GetGCPhys(PSSMHANDLE pSSM, PRTGCPHYS pGCPhys)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
    {
        if (sizeof(*pGCPhys) != pSSM->cbGCPhys)
        {
            Assert(sizeof(*pGCPhys) == sizeof(uint64_t) || sizeof(*pGCPhys) == sizeof(uint32_t));
            Assert(pSSM->cbGCPhys   == sizeof(uint64_t) || pSSM->cbGCPhys   == sizeof(uint32_t));
            if (pSSM->cbGCPhys == sizeof(uint64_t))
            {
                /* 64-bit saved, 32-bit load: try truncate it. */
                uint64_t u64;
                int rc = ssmR3Read(pSSM, &u64, pSSM->cbGCPhys);
                if (RT_FAILURE(rc))
                    return rc;
                if (u64 >= _4G)
                    return VERR_SSM_GCPHYS_OVERFLOW;
                *pGCPhys = (RTGCPHYS)u64;
                return rc;
            }
            /* 32-bit saved, 64-bit load: clear the high part. */
            *pGCPhys = 0;
        }
        return ssmR3Read(pSSM, pGCPhys, pSSM->cbGCPhys);
    }
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a GC virtual address item from the current data unit.
 *
 * Only applies to in the 1.1 format:
 *  - SSMR3GetGCPtr
 *  - SSMR3GetGCUIntPtr
 *  - SSMR3GetGCUInt
 *  - SSMR3GetGCUIntReg
 *
 * Put functions are not affected.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   cbGCPtr         Size of RTGCPTR
 *
 * @remarks This interface only works with saved state version 1.1, if the
 *          format isn't 1.1 the call will be ignored.
 */
VMMR3DECL(int) SSMR3SetGCPtrSize(PSSMHANDLE pSSM, unsigned cbGCPtr)
{
    Assert(cbGCPtr == sizeof(RTGCPTR32) || cbGCPtr == sizeof(RTGCPTR64));
    if (!pSSM->fFixedGCPtrSize)
    {
        Log(("SSMR3SetGCPtrSize: %d -> %d bytes\n", pSSM->cbGCPtr, cbGCPtr));
        pSSM->cbGCPtr = cbGCPtr;
        pSSM->fFixedGCPtrSize = true;
    }
    else if (   pSSM->cbGCPtr != cbGCPtr
             && pSSM->cbFileHdr == sizeof(SSMFILEHDRV11))
        AssertMsgFailed(("SSMR3SetGCPtrSize: already fixed at %d bytes; requested %d bytes\n", pSSM->cbGCPtr, cbGCPtr));

    return VINF_SUCCESS;
}


/**
 * Loads a GC virtual address item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pGCPtr          Where to store the GC virtual address.
 */
VMMR3DECL(int) SSMR3GetGCPtr(PSSMHANDLE pSSM, PRTGCPTR pGCPtr)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
    {
        if (sizeof(*pGCPtr) != pSSM->cbGCPtr)
        {
            Assert(sizeof(*pGCPtr) == sizeof(uint64_t) || sizeof(*pGCPtr) == sizeof(uint32_t));
            Assert(pSSM->cbGCPtr   == sizeof(uint64_t) || pSSM->cbGCPtr   == sizeof(uint32_t));
            if (pSSM->cbGCPtr == sizeof(uint64_t))
            {
                /* 64-bit saved, 32-bit load: try truncate it. */
                uint64_t u64;
                int rc = ssmR3Read(pSSM, &u64, pSSM->cbGCPhys);
                if (RT_FAILURE(rc))
                    return rc;
                if (u64 >= _4G)
                    return VERR_SSM_GCPTR_OVERFLOW;
                *pGCPtr = (RTGCPTR)u64;
                return rc;
            }
            /* 32-bit saved, 64-bit load: clear the high part. */
            *pGCPtr = 0;
        }
        return ssmR3Read(pSSM, pGCPtr, pSSM->cbGCPtr);
    }
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a GC virtual address (represented as unsigned integer) item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pGCPtr          Where to store the GC virtual address.
 */
VMMR3DECL(int) SSMR3GetGCUIntPtr(PSSMHANDLE pSSM, PRTGCUINTPTR pGCPtr)
{
    AssertCompile(sizeof(RTGCPTR) == sizeof(*pGCPtr));
    return SSMR3GetGCPtr(pSSM, (PRTGCPTR)pGCPtr);
}


/**
 * Loads an RC virtual address item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pRCPtr          Where to store the RC virtual address.
 */
VMMR3DECL(int) SSMR3GetRCPtr(PSSMHANDLE pSSM, PRTRCPTR pRCPtr)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pRCPtr, sizeof(*pRCPtr));

    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a I/O port address item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pIOPort         Where to store the I/O port address.
 */
VMMR3DECL(int) SSMR3GetIOPort(PSSMHANDLE pSSM, PRTIOPORT pIOPort)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pIOPort, sizeof(*pIOPort));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a selector item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pSel            Where to store the selector.
 */
VMMR3DECL(int) SSMR3GetSel(PSSMHANDLE pSSM, PRTSEL pSel)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pSel, sizeof(*pSel));
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a memory item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   pv              Where to store the item.
 * @param   cb              Size of the item.
 */
VMMR3DECL(int) SSMR3GetMem(PSSMHANDLE pSSM, void *pv, size_t cb)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
        return ssmR3Read(pSSM, pv, cb);
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Loads a string item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   psz             Where to store the item.
 * @param   cbMax           Max size of the item (including '\\0').
 */
VMMR3DECL(int) SSMR3GetStrZ(PSSMHANDLE pSSM, char *psz, size_t cbMax)
{
    return SSMR3GetStrZEx(pSSM, psz, cbMax, NULL);
}


/**
 * Loads a string item from the current data unit.
 *
 * @returns VBox status.
 * @param   pSSM            SSM operation handle.
 * @param   psz             Where to store the item.
 * @param   cbMax           Max size of the item (including '\\0').
 * @param   pcbStr          The length of the loaded string excluding the '\\0'. (optional)
 */
VMMR3DECL(int) SSMR3GetStrZEx(PSSMHANDLE pSSM, char *psz, size_t cbMax, size_t *pcbStr)
{
    if (pSSM->enmOp == SSMSTATE_LOAD_EXEC || pSSM->enmOp == SSMSTATE_OPEN_READ)
    {
        /* read size prefix. */
        uint32_t u32;
        int rc = SSMR3GetU32(pSSM, &u32);
        if (RT_SUCCESS(rc))
        {
            if (pcbStr)
                *pcbStr = u32;
            if (u32 < cbMax)
            {
                /* terminate and read string content. */
                psz[u32] = '\0';
                return ssmR3Read(pSSM, psz, u32);
            }
            return VERR_TOO_MUCH_DATA;
        }
        return rc;
    }
    AssertMsgFailed(("Invalid state %d\n", pSSM->enmOp));
    return VERR_SSM_INVALID_STATE;
}


/**
 * Skips a number of bytes in the current data unit.
 *
 * @returns VBox status code.
 * @param   pSSM                The SSM handle.
 * @param   cb                  The number of bytes to skip.
 */
VMMR3DECL(int) SSMR3Skip(PSSMHANDLE pSSM, size_t cb)
{
    AssertMsgReturn(   pSSM->enmOp == SSMSTATE_LOAD_EXEC
                    || pSSM->enmOp == SSMSTATE_OPEN_READ,
                    ("Invalid state %d\n", pSSM->enmOp),
                    VERR_SSM_INVALID_STATE);
    while (cb > 0)
    {
        uint8_t abBuf[8192];
        size_t  cbCur = RT_MIN(sizeof(abBuf), cb);
        cb -= cbCur;
        int rc = ssmR3Read(pSSM, abBuf, cbCur);
        if (RT_FAILURE(rc))
            return rc;
    }

    return VINF_SUCCESS;
}


/**
 * Query what the VBox status code of the operation is.
 *
 * This can be used for putting and getting a batch of values
 * without bother checking the result till all the calls have
 * been made.
 *
 * @returns SSMAFTER enum value.
 * @param   pSSM            SSM operation handle.
 */
VMMR3DECL(int) SSMR3HandleGetStatus(PSSMHANDLE pSSM)
{
    return pSSM->rc;
}


/**
 * Fail the load operation.
 *
 * This is mainly intended for sub item loaders (like timers) which
 * return code isn't necessarily heeded by the caller but is important
 * to SSM.
 *
 * @returns SSMAFTER enum value.
 * @param   pSSM            SSM operation handle.
 * @param   iStatus         Failure status code. This MUST be a VERR_*.
 */
VMMR3DECL(int) SSMR3HandleSetStatus(PSSMHANDLE pSSM, int iStatus)
{
    if (RT_FAILURE(iStatus))
    {
        if (RT_SUCCESS(pSSM->rc))
            pSSM->rc = iStatus;
        return pSSM->rc = iStatus;
    }
    AssertMsgFailed(("iStatus=%d %Rrc\n", iStatus, iStatus));
    return VERR_INVALID_PARAMETER;
}


/**
 * Get what to do after this operation.
 *
 * @returns SSMAFTER enum value.
 * @param   pSSM            SSM operation handle.
 */
VMMR3DECL(SSMAFTER) SSMR3HandleGetAfter(PSSMHANDLE pSSM)
{
    return pSSM->enmAfter;
}


/**
 * Get the current unit byte offset (uncompressed).
 *
 * @returns The offset. UINT64_MAX if called at a wrong time.
 * @param   pSSM            SSM operation handle.
 */
VMMR3DECL(uint64_t) SSMR3HandleGetUnitOffset(PSSMHANDLE pSSM)
{
    return pSSM->offUnit;
}