summaryrefslogtreecommitdiffstats
path: root/include/VBox/vd-ifs.h
blob: 87dec3f3a69823084c82c0a9f60823198bd8fc8e (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
/** @file
 * VD Container API - interfaces.
 */

/*
 * Copyright (C) 2011-2022 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */

#ifndef VBOX_INCLUDED_vd_ifs_h
#define VBOX_INCLUDED_vd_ifs_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif

#include <iprt/assert.h>
#include <iprt/string.h>
#include <iprt/mem.h>
#include <iprt/file.h>
#include <iprt/net.h>
#include <iprt/sg.h>
#include <VBox/cdefs.h>
#include <VBox/types.h>
#include <VBox/err.h>

RT_C_DECLS_BEGIN

/** @addtogroup grp_vd
 * @{ */

/** Interface header magic. */
#define VDINTERFACE_MAGIC UINT32_C(0x19701015)

/**
 * Supported interface types.
 */
typedef enum VDINTERFACETYPE
{
    /** First valid interface. */
    VDINTERFACETYPE_FIRST = 0,
    /** Interface to pass error message to upper layers. Per-disk. */
    VDINTERFACETYPE_ERROR = VDINTERFACETYPE_FIRST,
    /** Interface for I/O operations. Per-image. */
    VDINTERFACETYPE_IO,
    /** Interface for progress notification. Per-operation. */
    VDINTERFACETYPE_PROGRESS,
    /** Interface for configuration information. Per-image. */
    VDINTERFACETYPE_CONFIG,
    /** Interface for TCP network stack. Per-image. */
    VDINTERFACETYPE_TCPNET,
    /** Interface for getting parent image state. Per-operation. */
    VDINTERFACETYPE_PARENTSTATE,
    /** Interface for synchronizing accesses from several threads. Per-disk. */
    VDINTERFACETYPE_THREADSYNC,
    /** Interface for I/O between the generic VBoxHDD code and the backend. Per-image (internal).
     * This interface is completely internal and must not be used elsewhere. */
    VDINTERFACETYPE_IOINT,
    /** Interface to query the use of block ranges on the disk. Per-operation. */
    VDINTERFACETYPE_QUERYRANGEUSE,
    /** Interface for the metadata traverse callback. Per-operation. */
    VDINTERFACETYPE_TRAVERSEMETADATA,
    /** Interface for crypto operations. Per-filter. */
    VDINTERFACETYPE_CRYPTO,
    /** invalid interface. */
    VDINTERFACETYPE_INVALID
} VDINTERFACETYPE;

/**
 * Common structure for all interfaces and at the beginning of all types.
 */
typedef struct VDINTERFACE
{
    uint32_t            u32Magic;
    /** Human readable interface name. */
    const char         *pszInterfaceName;
    /** Pointer to the next common interface structure. */
    struct VDINTERFACE *pNext;
    /** Interface type. */
    VDINTERFACETYPE     enmInterface;
    /** Size of the interface. */
    size_t              cbSize;
    /** Opaque user data which is passed on every call. */
    void               *pvUser;
} VDINTERFACE;
/** Pointer to a VDINTERFACE. */
typedef VDINTERFACE *PVDINTERFACE;
/** Pointer to a const VDINTERFACE. */
typedef const VDINTERFACE *PCVDINTERFACE;

/**
 * Helper functions to handle interface lists.
 *
 * @note These interface lists are used consistently to pass per-disk,
 * per-image and/or per-operation callbacks. Those three purposes are strictly
 * separate. See the individual interface declarations for what context they
 * apply to. The caller is responsible for ensuring that the lifetime of the
 * interface descriptors is appropriate for the category of interface.
 */

/**
 * Get a specific interface from a list of interfaces specified by the type.
 *
 * @return  Pointer to the matching interface or NULL if none was found.
 * @param   pVDIfs          Pointer to the VD interface list.
 * @param   enmInterface    Interface to search for.
 */
DECLINLINE(PVDINTERFACE) VDInterfaceGet(PVDINTERFACE pVDIfs, VDINTERFACETYPE enmInterface)
{
    AssertMsgReturn(   enmInterface >= VDINTERFACETYPE_FIRST
                    && enmInterface < VDINTERFACETYPE_INVALID,
                    ("enmInterface=%u", enmInterface), NULL);

    while (pVDIfs)
    {
        AssertMsgBreak(pVDIfs->u32Magic == VDINTERFACE_MAGIC,
                       ("u32Magic=%#x\n", pVDIfs->u32Magic));

        if (pVDIfs->enmInterface == enmInterface)
            return pVDIfs;
        pVDIfs = pVDIfs->pNext;
    }

    /* No matching interface was found. */
    return NULL;
}

/**
 * Add an interface to a list of interfaces.
 *
 * @return VBox status code.
 * @param  pInterface   Pointer to an unitialized common interface structure.
 * @param  pszName      Name of the interface.
 * @param  enmInterface Type of the interface.
 * @param  pvUser       Opaque user data passed on every function call.
 * @param  cbInterface  The interface size.
 * @param  ppVDIfs      Pointer to the VD interface list.
 */
DECLINLINE(int) VDInterfaceAdd(PVDINTERFACE pInterface, const char *pszName, VDINTERFACETYPE enmInterface, void *pvUser,
                               size_t cbInterface, PVDINTERFACE *ppVDIfs)
{
    /* Argument checks. */
    AssertMsgReturn(   enmInterface >= VDINTERFACETYPE_FIRST
                    && enmInterface < VDINTERFACETYPE_INVALID,
                    ("enmInterface=%u", enmInterface), VERR_INVALID_PARAMETER);

    AssertPtrReturn(ppVDIfs, VERR_INVALID_PARAMETER);

    /* Fill out interface descriptor. */
    pInterface->u32Magic         = VDINTERFACE_MAGIC;
    pInterface->cbSize           = cbInterface;
    pInterface->pszInterfaceName = pszName;
    pInterface->enmInterface     = enmInterface;
    pInterface->pvUser           = pvUser;
    pInterface->pNext            = *ppVDIfs;

    /* Remember the new start of the list. */
    *ppVDIfs = pInterface;

    return VINF_SUCCESS;
}

/**
 * Removes an interface from a list of interfaces.
 *
 * @return VBox status code
 * @param  pInterface   Pointer to an initialized common interface structure to remove.
 * @param  ppVDIfs      Pointer to the VD interface list to remove from.
 */
DECLINLINE(int) VDInterfaceRemove(PVDINTERFACE pInterface, PVDINTERFACE *ppVDIfs)
{
    int rc = VERR_NOT_FOUND;

    /* Argument checks. */
    AssertPtrReturn(pInterface, VERR_INVALID_PARAMETER);
    AssertPtrReturn(ppVDIfs, VERR_INVALID_PARAMETER);

    if (*ppVDIfs)
    {
        PVDINTERFACE pPrev = NULL;
        PVDINTERFACE pCurr = *ppVDIfs;

        while (   pCurr
               && (pCurr != pInterface))
        {
            pPrev = pCurr;
            pCurr = pCurr->pNext;
        }

        /* First interface */
        if (!pPrev)
        {
            *ppVDIfs = pCurr->pNext;
            rc = VINF_SUCCESS;
        }
        else if (pCurr)
        {
            Assert(pPrev->pNext == pCurr);
            pPrev->pNext = pCurr->pNext;
            rc = VINF_SUCCESS;
        }
    }

    return rc;
}

/**
 * Interface to deliver error messages (and also informational messages)
 * to upper layers.
 *
 * Per-disk interface. Optional, but think twice if you want to miss the
 * opportunity of reporting better human-readable error messages.
 */
typedef struct VDINTERFACEERROR
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Error message callback. Must be able to accept special IPRT format
     * strings.
     *
     * @param   pvUser          The opaque data passed on container creation.
     * @param   rc              The VBox error code.
     * @param   SRC_POS         Use RT_SRC_POS.
     * @param   pszFormat       Error message format string.
     * @param   va              Error message arguments.
     */
    DECLR3CALLBACKMEMBER(void, pfnError, (void *pvUser, int rc, RT_SRC_POS_DECL,
                                          const char *pszFormat, va_list va) RT_IPRT_FORMAT_ATTR(6, 0));

    /**
     * Informational message callback. May be NULL. Used e.g. in
     * VDDumpImages(). Must be able to accept special IPRT format strings.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pszFormat       Message format string.
     * @param   va              Message arguments.
     */
    DECLR3CALLBACKMEMBER(int, pfnMessage, (void *pvUser, const char *pszFormat, va_list va) RT_IPRT_FORMAT_ATTR(2, 0));

} VDINTERFACEERROR, *PVDINTERFACEERROR;

/**
 * Get error interface from interface list.
 *
 * @return Pointer to the first error interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACEERROR) VDIfErrorGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_ERROR);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_ERROR)
                        && (pIf->cbSize == sizeof(VDINTERFACEERROR))),
                    ("Not an error interface\n"), NULL);

    return (PVDINTERFACEERROR)pIf;
}

/**
 * Signal an error to the frontend.
 *
 * @returns VBox status code.
 * @param   pIfError           The error interface.
 * @param   rc                 The status code.
 * @param   SRC_POS            The position in the source code.
 * @param   pszFormat          The format string to pass.
 * @param   ...                Arguments to the format string.
 */
DECLINLINE(int) RT_IPRT_FORMAT_ATTR(6, 7) vdIfError(PVDINTERFACEERROR pIfError, int rc, RT_SRC_POS_DECL,
                                                    const char *pszFormat, ...)
{
    va_list va;
    va_start(va, pszFormat);
    if (pIfError)
        pIfError->pfnError(pIfError->Core.pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
    va_end(va);

#if defined(LOG_ENABLED) && defined(Log)
    va_start(va, pszFormat);
    Log(("vdIfError: %N\n", pszFormat, &va));
    va_end(va);
#endif
    return rc;
}

/**
 * Signal an informational message to the frontend.
 *
 * @returns VBox status code.
 * @param   pIfError           The error interface.
 * @param   pszFormat          The format string to pass.
 * @param   ...                Arguments to the format string.
 */
DECLINLINE(int) RT_IPRT_FORMAT_ATTR(2, 3) vdIfErrorMessage(PVDINTERFACEERROR pIfError, const char *pszFormat, ...)
{
    int rc = VINF_SUCCESS;
    va_list va;
    va_start(va, pszFormat);
    if (pIfError && pIfError->pfnMessage)
        rc = pIfError->pfnMessage(pIfError->Core.pvUser, pszFormat, va);
    va_end(va);

#if defined(LOG_ENABLED) && defined(Log)
    va_start(va, pszFormat);
    Log(("vdIfErrorMessage: %N\n", pszFormat, &va));
    va_end(va);
#endif
    return rc;
}

/**
 * Completion callback which is called by the interface owner
 * to inform the backend that a task finished.
 *
 * @return  VBox status code.
 * @param   pvUser          Opaque user data which is passed on request submission.
 * @param   rcReq           Status code of the completed request.
 */
typedef DECLCALLBACKTYPE(int, FNVDCOMPLETED,(void *pvUser, int rcReq));
/** Pointer to FNVDCOMPLETED() */
typedef FNVDCOMPLETED *PFNVDCOMPLETED;

/**
 * Support interface for I/O
 *
 * Per-image. Optional as input.
 */
typedef struct VDINTERFACEIO
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Open callback
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pszLocation     Name of the location to open.
     * @param   fOpen           Flags for opening the backend.
     *                          See RTFILE_O_* \#defines, inventing another set
     *                          of open flags is not worth the mapping effort.
     * @param   pfnCompleted    The callback which is called whenever a task
     *                          completed. The backend has to pass the user data
     *                          of the request initiator (ie the one who calls
     *                          VDAsyncRead or VDAsyncWrite) in pvCompletion
     *                          if this is NULL.
     * @param   ppvStorage      Where to store the opaque storage handle.
     */
    DECLR3CALLBACKMEMBER(int, pfnOpen, (void *pvUser, const char *pszLocation,
                                        uint32_t fOpen,
                                        PFNVDCOMPLETED pfnCompleted,
                                        void **ppvStorage));

    /**
     * Close callback.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The opaque storage handle to close.
     */
    DECLR3CALLBACKMEMBER(int, pfnClose, (void *pvUser, void *pvStorage));

    /**
     * Delete callback.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pcszFilename    Name of the file to delete.
     */
    DECLR3CALLBACKMEMBER(int, pfnDelete, (void *pvUser, const char *pcszFilename));

    /**
     * Move callback.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pcszSrc         The path to the source file.
     * @param   pcszDst         The path to the destination file.
     *                          This file will be created.
     * @param   fMove           A combination of the RTFILEMOVE_* flags.
     */
    DECLR3CALLBACKMEMBER(int, pfnMove, (void *pvUser, const char *pcszSrc, const char *pcszDst, unsigned fMove));

    /**
     * Returns the free space on a disk.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pcszFilename    Name of a file to identify the disk.
     * @param   pcbFreeSpace    Where to store the free space of the disk.
     */
    DECLR3CALLBACKMEMBER(int, pfnGetFreeSpace, (void *pvUser, const char *pcszFilename, int64_t *pcbFreeSpace));

    /**
     * Returns the last modification timestamp of a file.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pcszFilename    Name of a file to identify the disk.
     * @param   pModificationTime   Where to store the timestamp of the file.
     */
    DECLR3CALLBACKMEMBER(int, pfnGetModificationTime, (void *pvUser, const char *pcszFilename, PRTTIMESPEC pModificationTime));

    /**
     * Returns the size of the opened storage backend.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The opaque storage handle to get the size from.
     * @param   pcb             Where to store the size of the storage backend.
     */
    DECLR3CALLBACKMEMBER(int, pfnGetSize, (void *pvUser, void *pvStorage, uint64_t *pcb));

    /**
     * Sets the size of the opened storage backend if possible.
     *
     * @return  VBox status code.
     * @retval  VERR_NOT_SUPPORTED if the backend does not support this operation.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The opaque storage handle to set the size for.
     * @param   cb              The new size of the image.
     *
     * @note Depending on the host the underlying storage (backing file, etc.)
     *       might not have all required storage allocated (sparse file) which
     *       can delay writes or fail with a not enough free space error if there
     *       is not enough space on the storage medium when writing to the range for
     *       the first time.
     *       Use VDINTERFACEIO::pfnSetAllocationSize to make sure the storage is
     *       really alloacted.
     */
    DECLR3CALLBACKMEMBER(int, pfnSetSize, (void *pvUser, void *pvStorage, uint64_t cb));

    /**
     * Sets the size of the opened storage backend making sure the given size
     * is really allocated.
     *
     * @return VBox status code.
     * @retval VERR_NOT_SUPPORTED if the implementer of the interface doesn't support
     *         this method.
     * @param  pvUser          The opaque data passed on container creation.
     * @param  pvStorage       The storage handle.
     * @param  cbSize          The new size of the image.
     * @param  fFlags          Flags for controlling the allocation strategy.
     *                         Reserved for future use, MBZ.
     */
    DECLR3CALLBACKMEMBER(int, pfnSetAllocationSize, (void *pvUser, void *pvStorage,
                                                     uint64_t cbSize, uint32_t fFlags));

    /**
     * Synchronous write callback.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The storage handle to use.
     * @param   off             The offset to start from.
     * @param   pvBuf           Pointer to the bits need to be written.
     * @param   cbToWrite       How many bytes to write.
     * @param   pcbWritten      Where to store how many bytes were actually written.
     */
    DECLR3CALLBACKMEMBER(int, pfnWriteSync, (void *pvUser, void *pvStorage, uint64_t off,
                                             const void *pvBuf, size_t cbToWrite, size_t *pcbWritten));

    /**
     * Synchronous read callback.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The storage handle to use.
     * @param   off             The offset to start from.
     * @param   pvBuf           Where to store the read bits.
     * @param   cbToRead        How many bytes to read.
     * @param   pcbRead         Where to store how many bytes were actually read.
     */
    DECLR3CALLBACKMEMBER(int, pfnReadSync, (void *pvUser, void *pvStorage, uint64_t off,
                                            void *pvBuf, size_t cbToRead, size_t *pcbRead));

    /**
     * Flush data to the storage backend.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The storage handle to flush.
     */
    DECLR3CALLBACKMEMBER(int, pfnFlushSync, (void *pvUser, void *pvStorage));

    /**
     * Initiate an asynchronous read request.
     *
     * @return  VBox status code.
     * @param   pvUser         The opaque user data passed on container creation.
     * @param   pvStorage      The storage handle.
     * @param   uOffset        The offset to start reading from.
     * @param   paSegments     Scatter gather list to store the data in.
     * @param   cSegments      Number of segments in the list.
     * @param   cbRead         How many bytes to read.
     * @param   pvCompletion   The opaque user data which is returned upon completion.
     * @param   ppTask         Where to store the opaque task handle.
     */
    DECLR3CALLBACKMEMBER(int, pfnReadAsync, (void *pvUser, void *pvStorage, uint64_t uOffset,
                                             PCRTSGSEG paSegments, size_t cSegments,
                                             size_t cbRead, void *pvCompletion,
                                             void **ppTask));

    /**
     * Initiate an asynchronous write request.
     *
     * @return  VBox status code.
     * @param   pvUser         The opaque user data passed on conatiner creation.
     * @param   pvStorage      The storage handle.
     * @param   uOffset        The offset to start writing to.
     * @param   paSegments     Scatter gather list of the data to write
     * @param   cSegments      Number of segments in the list.
     * @param   cbWrite        How many bytes to write.
     * @param   pvCompletion   The opaque user data which is returned upon completion.
     * @param   ppTask         Where to store the opaque task handle.
     */
    DECLR3CALLBACKMEMBER(int, pfnWriteAsync, (void *pvUser, void *pvStorage, uint64_t uOffset,
                                              PCRTSGSEG paSegments, size_t cSegments,
                                              size_t cbWrite, void *pvCompletion,
                                              void **ppTask));

    /**
     * Initiates an async flush request.
     *
     * @return  VBox status code.
     * @param   pvUser          The opaque data passed on container creation.
     * @param   pvStorage       The storage handle to flush.
     * @param   pvCompletion    The opaque user data which is returned upon completion.
     * @param   ppTask          Where to store the opaque task handle.
     */
    DECLR3CALLBACKMEMBER(int, pfnFlushAsync, (void *pvUser, void *pvStorage,
                                              void *pvCompletion, void **ppTask));

} VDINTERFACEIO, *PVDINTERFACEIO;

/**
 * Get I/O interface from interface list.
 *
 * @return Pointer to the first I/O interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACEIO) VDIfIoGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_IO);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_IO)
                        && (pIf->cbSize == sizeof(VDINTERFACEIO))),
                    ("Not a I/O interface"), NULL);

    return (PVDINTERFACEIO)pIf;
}

DECLINLINE(int) vdIfIoFileOpen(PVDINTERFACEIO pIfIo, const char *pszFilename,
                               uint32_t fOpen, PFNVDCOMPLETED pfnCompleted,
                               void **ppStorage)
{
    return pIfIo->pfnOpen(pIfIo->Core.pvUser, pszFilename, fOpen, pfnCompleted, ppStorage);
}

DECLINLINE(int) vdIfIoFileClose(PVDINTERFACEIO pIfIo, void *pStorage)
{
    return pIfIo->pfnClose(pIfIo->Core.pvUser, pStorage);
}

DECLINLINE(int) vdIfIoFileDelete(PVDINTERFACEIO pIfIo, const char *pszFilename)
{
    return pIfIo->pfnDelete(pIfIo->Core.pvUser, pszFilename);
}

DECLINLINE(int) vdIfIoFileMove(PVDINTERFACEIO pIfIo, const char *pszSrc,
                               const char *pszDst, unsigned fMove)
{
    return pIfIo->pfnMove(pIfIo->Core.pvUser, pszSrc, pszDst, fMove);
}

DECLINLINE(int) vdIfIoFileGetFreeSpace(PVDINTERFACEIO pIfIo, const char *pszFilename,
                                       int64_t *pcbFree)
{
    return pIfIo->pfnGetFreeSpace(pIfIo->Core.pvUser, pszFilename, pcbFree);
}

DECLINLINE(int) vdIfIoFileGetModificationTime(PVDINTERFACEIO pIfIo, const char *pcszFilename,
                                              PRTTIMESPEC pModificationTime)
{
    return pIfIo->pfnGetModificationTime(pIfIo->Core.pvUser, pcszFilename,
                                         pModificationTime);
}

DECLINLINE(int) vdIfIoFileGetSize(PVDINTERFACEIO pIfIo, void *pStorage,
                                  uint64_t *pcbSize)
{
    return pIfIo->pfnGetSize(pIfIo->Core.pvUser, pStorage, pcbSize);
}

DECLINLINE(int) vdIfIoFileSetSize(PVDINTERFACEIO pIfIo, void *pStorage,
                                  uint64_t cbSize)
{
    return pIfIo->pfnSetSize(pIfIo->Core.pvUser, pStorage, cbSize);
}

DECLINLINE(int) vdIfIoFileWriteSync(PVDINTERFACEIO pIfIo, void *pStorage,
                                    uint64_t uOffset, const void *pvBuffer, size_t cbBuffer,
                                    size_t *pcbWritten)
{
    return pIfIo->pfnWriteSync(pIfIo->Core.pvUser, pStorage, uOffset,
                               pvBuffer, cbBuffer, pcbWritten);
}

DECLINLINE(int) vdIfIoFileReadSync(PVDINTERFACEIO pIfIo, void *pStorage,
                                   uint64_t uOffset, void *pvBuffer, size_t cbBuffer,
                                   size_t *pcbRead)
{
    return pIfIo->pfnReadSync(pIfIo->Core.pvUser, pStorage, uOffset,
                              pvBuffer, cbBuffer, pcbRead);
}

DECLINLINE(int) vdIfIoFileFlushSync(PVDINTERFACEIO pIfIo, void *pStorage)
{
    return pIfIo->pfnFlushSync(pIfIo->Core.pvUser, pStorage);
}

/**
 * Create a VFS stream handle around a VD I/O interface.
 *
 * The I/O interface will not be closed or free by the stream, the caller will
 * do so after it is done with the stream and has released the instances of the
 * I/O stream object returned by this API.
 *
 * @return  VBox status code.
 * @param   pVDIfsIo        Pointer to the VD I/O interface.
 * @param   pvStorage       The storage argument to pass to the interface
 *                          methods.
 * @param   fFlags          RTFILE_O_XXX, access mask requied.
 * @param   phVfsIos        Where to return the VFS I/O stream handle on
 *                          success.
 */
VBOXDDU_DECL(int) VDIfCreateVfsStream(PVDINTERFACEIO pVDIfsIo, void *pvStorage, uint32_t fFlags, PRTVFSIOSTREAM phVfsIos);

struct VDINTERFACEIOINT;

/**
 * Create a VFS file handle around a VD I/O interface.
 *
 * The I/O interface will not be closed or free by the VFS file, the caller will
 * do so after it is done with the VFS file and has released the instances of
 * the VFS object returned by this API.
 *
 * @return  VBox status code.
 * @param   pVDIfs          Pointer to the VD I/O interface.  If NULL, then @a
 *                          pVDIfsInt must be specified.
 * @param   pVDIfsInt       Pointer to the internal VD I/O interface.  If NULL,
 *                          then @ pVDIfs must be specified.
 * @param   pvStorage       The storage argument to pass to the interface
 *                          methods.
 * @param   fFlags          RTFILE_O_XXX, access mask requied.
 * @param   phVfsFile       Where to return the VFS file handle on success.
 */
VBOXDDU_DECL(int) VDIfCreateVfsFile(PVDINTERFACEIO pVDIfs, struct VDINTERFACEIOINT *pVDIfsInt, void *pvStorage,
                                    uint32_t fFlags, PRTVFSFILE phVfsFile);

/**
 * Creates an VD I/O interface wrapper around an IPRT VFS I/O stream.
 *
 * @return  VBox status code.
 * @param   hVfsIos         The IPRT VFS I/O stream handle. The handle will be
 *                          retained by the returned I/O interface (released on
 *                          close or destruction).
 * @param   fAccessMode     The access mode (RTFILE_O_ACCESS_MASK) to accept.
 * @param   ppIoIf          Where to return the pointer to the VD I/O interface.
 *                          This must be passed to VDIfDestroyFromVfsStream().
 */
VBOXDDU_DECL(int) VDIfCreateFromVfsStream(RTVFSIOSTREAM hVfsIos, uint32_t fAccessMode, PVDINTERFACEIO *ppIoIf);

/**
 * Destroys the VD I/O interface returned by VDIfCreateFromVfsStream.
 *
 * @returns VBox status code.
 * @param   pIoIf           The I/O interface pointer returned by
 *                          VDIfCreateFromVfsStream.  NULL will be quietly
 *                          ignored.
 */
VBOXDDU_DECL(int) VDIfDestroyFromVfsStream(PVDINTERFACEIO pIoIf);


/**
 * Callback which provides progress information about a currently running
 * lengthy operation.
 *
 * @return  VBox status code.
 * @param   pvUser          The opaque user data associated with this interface.
 * @param   uPercentage     Completion percentage.
 */
typedef DECLCALLBACKTYPE(int, FNVDPROGRESS,(void *pvUser, unsigned uPercentage));
/** Pointer to FNVDPROGRESS() */
typedef FNVDPROGRESS *PFNVDPROGRESS;

/**
 * Progress notification interface
 *
 * Per-operation. Optional.
 */
typedef struct VDINTERFACEPROGRESS
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Progress notification callbacks.
     */
    PFNVDPROGRESS pfnProgress;

} VDINTERFACEPROGRESS, *PVDINTERFACEPROGRESS;

/** Initializer for VDINTERFACEPROGRESS.  */
#define VDINTERFACEPROGRESS_INITALIZER(a_pfnProgress) { { 0, NULL, NULL, VDINTERFACETYPE_INVALID, 0, NULL }, a_pfnProgress }

/**
 * Get progress interface from interface list.
 *
 * @return Pointer to the first progress interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACEPROGRESS) VDIfProgressGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_PROGRESS);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_PROGRESS)
                        && (pIf->cbSize == sizeof(VDINTERFACEPROGRESS))),
                    ("Not a progress interface"), NULL);

    return (PVDINTERFACEPROGRESS)pIf;
}

/**
 * Signal new progress information to the frontend.
 *
 * @returns VBox status code.
 * @param   pIfProgress        The progress interface.
 * @param   uPercentage        Completion percentage.
 */
DECLINLINE(int) vdIfProgress(PVDINTERFACEPROGRESS pIfProgress, unsigned uPercentage)
{
    if (pIfProgress)
        return pIfProgress->pfnProgress(pIfProgress->Core.pvUser, uPercentage);
    return VINF_SUCCESS;
}

/**
 * Configuration information interface
 *
 * Per-image. Optional for most backends, but mandatory for images which do
 * not operate on files (including standard block or character devices).
 */
typedef struct VDINTERFACECONFIG
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Validates that the keys are within a set of valid names.
     *
     * @return  true if all key names are found in pszzAllowed.
     * @return  false if not.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszzValid       List of valid key names separated by '\\0' and ending with
     *                          a double '\\0'.
     */
    DECLR3CALLBACKMEMBER(bool, pfnAreKeysValid, (void *pvUser, const char *pszzValid));

    /**
     * Retrieves the length of the string value associated with a key (including
     * the terminator, for compatibility with CFGMR3QuerySize).
     *
     * @return  VBox status code.
     *          VERR_CFGM_VALUE_NOT_FOUND means that the key is not known.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszName         Name of the key to query.
     * @param   pcbValue        Where to store the value length. Non-NULL.
     */
    DECLR3CALLBACKMEMBER(int, pfnQuerySize, (void *pvUser, const char *pszName, size_t *pcbValue));

    /**
     * Query the string value associated with a key.
     *
     * @return  VBox status code.
     *          VERR_CFGM_VALUE_NOT_FOUND means that the key is not known.
     *          VERR_CFGM_NOT_ENOUGH_SPACE means that the buffer is not big enough.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszName         Name of the key to query.
     * @param   pszValue        Pointer to buffer where to store value.
     * @param   cchValue        Length of value buffer.
     */
    DECLR3CALLBACKMEMBER(int, pfnQuery, (void *pvUser, const char *pszName, char *pszValue, size_t cchValue));

    /**
     * Query the bytes value associated with a key.
     *
     * @return  VBox status code.
     *          VERR_CFGM_VALUE_NOT_FOUND means that the key is not known.
     *          VERR_CFGM_NOT_ENOUGH_SPACE means that the buffer is not big enough.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszName         Name of the key to query.
     * @param   ppvData         Pointer to buffer where to store the data.
     * @param   cbData          Length of data buffer.
     */
    DECLR3CALLBACKMEMBER(int, pfnQueryBytes, (void *pvUser, const char *pszName, void *ppvData, size_t cbData));

    /**
     * Set a named property to a specified string value, optionally creating if it doesn't exist.
     *
     * @return  VBox status code.
     *          VERR_CFGM_VALUE_NOT_FOUND means that the key is not known and fCreate flag was not set.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   fCreate         Create property if it doesn't exist (if property exists, it is not an error)
     * @param   pszName         Name of the key to query.
     * @param   pszValue        String value to set the name property to.
     */
    DECLR3CALLBACKMEMBER(int, pfnUpdate, (void *pvUser, bool fCreate,
            const char *pszName, const char *pszValue));

} VDINTERFACECONFIG, *PVDINTERFACECONFIG;

/**
 * Get configuration information interface from interface list.
 *
 * @return Pointer to the first configuration information interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACECONFIG) VDIfConfigGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_CONFIG);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_CONFIG)
                        && (pIf->cbSize == sizeof(VDINTERFACECONFIG))),
                    ("Not a config interface"), NULL);

    return (PVDINTERFACECONFIG)pIf;
}

/**
 * Query configuration, validates that the keys are within a set of valid names.
 *
 * @return  true if all key names are found in pszzAllowed.
 * @return  false if not.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszzValid   List of valid names separated by '\\0' and ending with
 *                      a double '\\0'.
 */
DECLINLINE(bool) VDCFGAreKeysValid(PVDINTERFACECONFIG pCfgIf, const char *pszzValid)
{
    return pCfgIf->pfnAreKeysValid(pCfgIf->Core.pvUser, pszzValid);
}

/**
 * Checks whether a given key is existing.
 *
 * @return  true if the key exists.
 * @return  false if the key does not exist.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of the key.
 */
DECLINLINE(bool) VDCFGIsKeyExisting(PVDINTERFACECONFIG pCfgIf, const char *pszName)
{
    size_t cb = 0;
    int rc = pCfgIf->pfnQuerySize(pCfgIf->Core.pvUser, pszName, &cb);
    return rc == VERR_CFGM_VALUE_NOT_FOUND ? false : true;
}

/**
 * Query configuration, unsigned 64-bit integer value with default.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an integer value
 * @param   pu64        Where to store the value. Set to default on failure.
 * @param   u64Def      The default value.
 */
DECLINLINE(int) VDCFGQueryU64Def(PVDINTERFACECONFIG pCfgIf,
                                 const char *pszName, uint64_t *pu64,
                                 uint64_t u64Def)
{
    char aszBuf[32];
    int rc = pCfgIf->pfnQuery(pCfgIf->Core.pvUser, pszName, aszBuf, sizeof(aszBuf));
    if (RT_SUCCESS(rc))
    {
        rc = RTStrToUInt64Full(aszBuf, 0, pu64);
    }
    else if (rc == VERR_CFGM_VALUE_NOT_FOUND)
    {
        rc = VINF_SUCCESS;
        *pu64 = u64Def;
    }
    return rc;
}

/**
 * Query configuration, unsigned 64-bit integer value.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an integer value
 * @param   pu64        Where to store the value.
 */
DECLINLINE(int) VDCFGQueryU64(PVDINTERFACECONFIG pCfgIf, const char *pszName,
                              uint64_t *pu64)
{
    char aszBuf[32];
    int rc = pCfgIf->pfnQuery(pCfgIf->Core.pvUser, pszName, aszBuf, sizeof(aszBuf));
    if (RT_SUCCESS(rc))
    {
        rc = RTStrToUInt64Full(aszBuf, 0, pu64);
    }

    return rc;
}

/**
 * Query configuration, unsigned 32-bit integer value with default.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an integer value
 * @param   pu32        Where to store the value. Set to default on failure.
 * @param   u32Def      The default value.
 */
DECLINLINE(int) VDCFGQueryU32Def(PVDINTERFACECONFIG pCfgIf,
                                 const char *pszName, uint32_t *pu32,
                                 uint32_t u32Def)
{
    uint64_t u64;
    int rc = VDCFGQueryU64Def(pCfgIf, pszName, &u64, u32Def);
    if (RT_SUCCESS(rc))
    {
        if (!(u64 & UINT64_C(0xffffffff00000000)))
            *pu32 = (uint32_t)u64;
        else
            rc = VERR_CFGM_INTEGER_TOO_BIG;
    }
    return rc;
}

/**
 * Query configuration, bool value with default.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an integer value
 * @param   pf          Where to store the value. Set to default on failure.
 * @param   fDef        The default value.
 */
DECLINLINE(int) VDCFGQueryBoolDef(PVDINTERFACECONFIG pCfgIf,
                                  const char *pszName, bool *pf,
                                  bool fDef)
{
    uint64_t u64;
    int rc = VDCFGQueryU64Def(pCfgIf, pszName, &u64, fDef);
    if (RT_SUCCESS(rc))
        *pf = u64 ? true : false;
    return rc;
}

/**
 * Query configuration, bool value.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an integer value
 * @param   pf          Where to store the value.
 */
DECLINLINE(int) VDCFGQueryBool(PVDINTERFACECONFIG pCfgIf, const char *pszName,
                               bool *pf)
{
    uint64_t u64;
    int rc = VDCFGQueryU64(pCfgIf, pszName, &u64);
    if (RT_SUCCESS(rc))
        *pf = u64 ? true : false;
    return rc;
}

/**
 * Query configuration, dynamically allocated (RTMemAlloc) zero terminated
 * character value.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an zero terminated character value
 * @param   ppszString  Where to store the string pointer. Not set on failure.
 *                      Free this using RTMemFree().
 */
DECLINLINE(int) VDCFGQueryStringAlloc(PVDINTERFACECONFIG pCfgIf,
                                      const char *pszName, char **ppszString)
{
    size_t cb;
    int rc = pCfgIf->pfnQuerySize(pCfgIf->Core.pvUser, pszName, &cb);
    if (RT_SUCCESS(rc))
    {
        char *pszString = (char *)RTMemAlloc(cb);
        if (pszString)
        {
            rc = pCfgIf->pfnQuery(pCfgIf->Core.pvUser, pszName, pszString, cb);
            if (RT_SUCCESS(rc))
                *ppszString = pszString;
            else
                RTMemFree(pszString);
        }
        else
            rc = VERR_NO_MEMORY;
    }
    return rc;
}

/**
 * Query configuration, dynamically allocated (RTMemAlloc) zero terminated
 * character value with default.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an zero terminated character value
 * @param   ppszString  Where to store the string pointer. Not set on failure.
 *                      Free this using RTMemFree().
 * @param   pszDef      The default value.
 */
DECLINLINE(int) VDCFGQueryStringAllocDef(PVDINTERFACECONFIG pCfgIf,
                                         const char *pszName,
                                         char **ppszString,
                                         const char *pszDef)
{
    size_t cb;
    int rc = pCfgIf->pfnQuerySize(pCfgIf->Core.pvUser, pszName, &cb);
    if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
    {
        cb = strlen(pszDef) + 1;
        rc = VINF_SUCCESS;
    }
    if (RT_SUCCESS(rc))
    {
        char *pszString = (char *)RTMemAlloc(cb);
        if (pszString)
        {
            rc = pCfgIf->pfnQuery(pCfgIf->Core.pvUser, pszName, pszString, cb);
            if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
            {
                memcpy(pszString, pszDef, cb);
                rc = VINF_SUCCESS;
            }
            if (RT_SUCCESS(rc))
                *ppszString = pszString;
            else
                RTMemFree(pszString);
        }
        else
            rc = VERR_NO_MEMORY;
    }
    return rc;
}

/**
 * Query configuration, dynamically allocated (RTMemAlloc) byte string value.
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   pszName     Name of an zero terminated character value
 * @param   ppvData     Where to store the byte string pointer. Not set on failure.
 *                      Free this using RTMemFree().
 * @param   pcbData     Where to store the byte string length.
 */
DECLINLINE(int) VDCFGQueryBytesAlloc(PVDINTERFACECONFIG pCfgIf,
                                     const char *pszName, void **ppvData, size_t *pcbData)
{
    size_t cb;
    int rc = pCfgIf->pfnQuerySize(pCfgIf->Core.pvUser, pszName, &cb);
    if (RT_SUCCESS(rc))
    {
        char *pbData;
        Assert(cb);

        pbData = (char *)RTMemAlloc(cb);
        if (pbData)
        {
            if(pCfgIf->pfnQueryBytes)
                rc = pCfgIf->pfnQueryBytes(pCfgIf->Core.pvUser, pszName, pbData, cb);
            else
                rc = pCfgIf->pfnQuery(pCfgIf->Core.pvUser, pszName, pbData, cb);

            if (RT_SUCCESS(rc))
            {
                *ppvData = pbData;
                /* Exclude terminator if the byte data was obtained using the string query callback. */
                *pcbData = cb;
                if (!pCfgIf->pfnQueryBytes)
                    (*pcbData)--;
            }
            else
                RTMemFree(pbData);
        }
        else
            rc = VERR_NO_MEMORY;
    }
    return rc;
}

/**
 * Set property value to string (optionally create if non-existent).
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   fCreate     Create the property if it doesn't exist
 * @param   pszName     Name of property
 * @param   pszValue    String value to assign to property
 */
DECLINLINE(int) VDCFGUpdate(PVDINTERFACECONFIG pCfgIf, bool fCreate, const char *pszName, const char *pszValue)
{
    int rc = pCfgIf->pfnUpdate(pCfgIf->Core.pvUser, fCreate, pszName, pszValue);
    return rc;
}

/**
 * Set property value to Unsigned Int 64-bit (optionally create if non-existent).
 *
 * @return  VBox status code.
 * @param   pCfgIf      Pointer to configuration callback table.
 * @param   fCreate     Create the property if it doesn't exist
 * @param   pszName     Name of property
 * @param   u64Value    64-bit unsigned value to save with property.
 */

DECLINLINE(int) VDCFGUpdateU64(PVDINTERFACECONFIG pCfgIf, bool fCreate, const char *pszName, uint64_t u64Value)
{
     int rc = 0;
     char pszValue[21];
     (void) RTStrPrintf(pszValue, sizeof(pszValue), "%RU64", u64Value);
     rc = VDCFGUpdate(pCfgIf, fCreate, pszName, pszValue);
     return rc;
}



/** Forward declaration of a VD socket. */
typedef struct VDSOCKETINT *VDSOCKET;
/** Pointer to a VD socket. */
typedef VDSOCKET *PVDSOCKET;
/** Nil socket handle. */
#define NIL_VDSOCKET ((VDSOCKET)0)

/** Connect flag to indicate that the backend wants to use the extended
 * socket I/O multiplexing call. This might not be supported on all configurations
 * (internal networking and iSCSI)
 * and the backend needs to take appropriate action.
 */
#define VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT RT_BIT_32(0)

/** @name Select events
 * @{ */
/** Readable without blocking. */
#define VD_INTERFACETCPNET_EVT_READ         RT_BIT_32(0)
/** Writable without blocking. */
#define VD_INTERFACETCPNET_EVT_WRITE        RT_BIT_32(1)
/** Error condition, hangup, exception or similar. */
#define VD_INTERFACETCPNET_EVT_ERROR        RT_BIT_32(2)
/** Hint for the select that getting interrupted while waiting is more likely.
 * The interface implementation can optimize the waiting strategy based on this.
 * It is assumed that it is more likely to get one of the above socket events
 * instead of being interrupted if the flag is not set. */
#define VD_INTERFACETCPNET_HINT_INTERRUPT   RT_BIT_32(3)
/** Mask of the valid bits. */
#define VD_INTERFACETCPNET_EVT_VALID_MASK   UINT32_C(0x0000000f)
/** @} */

/**
 * TCP network stack interface
 *
 * Per-image. Mandatory for backends which have the VD_CAP_TCPNET bit set.
 */
typedef struct VDINTERFACETCPNET
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Creates a socket. The socket is not connected if this succeeds.
     *
     * @return  iprt status code.
     * @retval  VERR_NOT_SUPPORTED if the combination of flags is not supported.
     * @param   fFlags    Combination of the VD_INTERFACETCPNET_CONNECT_* \#defines.
     * @param   phVdSock  Where to store the handle.
     */
    DECLR3CALLBACKMEMBER(int, pfnSocketCreate, (uint32_t fFlags, PVDSOCKET phVdSock));

    /**
     * Destroys the socket.
     *
     * @return iprt status code.
     * @param  hVdSock    Socket handle (/ pointer).
     */
    DECLR3CALLBACKMEMBER(int, pfnSocketDestroy, (VDSOCKET hVdSock));

    /**
     * Connect as a client to a TCP port.
     *
     * @return  iprt status code.
     * @param   hVdSock         Socket handle (/ pointer)..
     * @param   pszAddress      The address to connect to.
     * @param   uPort           The port to connect to.
     * @param   cMillies        Number of milliseconds to wait for the connect attempt to complete.
     *                          Use RT_INDEFINITE_WAIT to wait for ever.
     *                          Use RT_SOCKETCONNECT_DEFAULT_WAIT to wait for the default time
     *                          configured on the running system.
     */
    DECLR3CALLBACKMEMBER(int, pfnClientConnect, (VDSOCKET hVdSock, const char *pszAddress, uint32_t uPort,
                                                 RTMSINTERVAL cMillies));

    /**
     * Close a TCP connection.
     *
     * @return  iprt status code.
     * @param   hVdSock         Socket handle (/ pointer).
     */
    DECLR3CALLBACKMEMBER(int, pfnClientClose, (VDSOCKET hVdSock));

    /**
     * Returns whether the socket is currently connected to the client.
     *
     * @returns true if the socket is connected.
     *          false otherwise.
     * @param   hVdSock     Socket handle (/ pointer).
     */
    DECLR3CALLBACKMEMBER(bool, pfnIsClientConnected, (VDSOCKET hVdSock));

    /**
     * Socket I/O multiplexing.
     * Checks if the socket is ready for reading.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   cMillies    Number of milliseconds to wait for the socket.
     *                      Use RT_INDEFINITE_WAIT to wait for ever.
     */
    DECLR3CALLBACKMEMBER(int, pfnSelectOne, (VDSOCKET hVdSock, RTMSINTERVAL cMillies));

    /**
     * Receive data from a socket.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pvBuffer    Where to put the data we read.
     * @param   cbBuffer    Read buffer size.
     * @param   pcbRead     Number of bytes read.
     *                      If NULL the entire buffer will be filled upon successful return.
     *                      If not NULL a partial read can be done successfully.
     */
    DECLR3CALLBACKMEMBER(int, pfnRead, (VDSOCKET hVdSock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead));

    /**
     * Send data to a socket.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pvBuffer    Buffer to write data to socket.
     * @param   cbBuffer    How much to write.
     */
    DECLR3CALLBACKMEMBER(int, pfnWrite, (VDSOCKET hVdSock, const void *pvBuffer, size_t cbBuffer));

    /**
     * Send data from scatter/gather buffer to a socket.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pSgBuf      Scatter/gather buffer to write data to socket.
     */
    DECLR3CALLBACKMEMBER(int, pfnSgWrite, (VDSOCKET hVdSock, PCRTSGBUF pSgBuf));

    /**
     * Receive data from a socket - not blocking.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pvBuffer    Where to put the data we read.
     * @param   cbBuffer    Read buffer size.
     * @param   pcbRead     Number of bytes read.
     */
    DECLR3CALLBACKMEMBER(int, pfnReadNB, (VDSOCKET hVdSock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead));

    /**
     * Send data to a socket - not blocking.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pvBuffer    Buffer to write data to socket.
     * @param   cbBuffer    How much to write.
     * @param   pcbWritten  Number of bytes written.
     */
    DECLR3CALLBACKMEMBER(int, pfnWriteNB, (VDSOCKET hVdSock, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten));

    /**
     * Send data from scatter/gather buffer to a socket - not blocking.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pSgBuf      Scatter/gather buffer to write data to socket.
     * @param   pcbWritten  Number of bytes written.
     */
    DECLR3CALLBACKMEMBER(int, pfnSgWriteNB, (VDSOCKET hVdSock, PRTSGBUF pSgBuf, size_t *pcbWritten));

    /**
     * Flush socket write buffers.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     */
    DECLR3CALLBACKMEMBER(int, pfnFlush, (VDSOCKET hVdSock));

    /**
     * Enables or disables delaying sends to coalesce packets.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   fEnable     When set to true enables coalescing.
     */
    DECLR3CALLBACKMEMBER(int, pfnSetSendCoalescing, (VDSOCKET hVdSock, bool fEnable));

    /**
     * Gets the address of the local side.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pAddr       Where to store the local address on success.
     */
    DECLR3CALLBACKMEMBER(int, pfnGetLocalAddress, (VDSOCKET hVdSock, PRTNETADDR pAddr));

    /**
     * Gets the address of the other party.
     *
     * @return  iprt status code.
     * @param   hVdSock     Socket handle (/ pointer).
     * @param   pAddr       Where to store the peer address on success.
     */
    DECLR3CALLBACKMEMBER(int, pfnGetPeerAddress, (VDSOCKET hVdSock, PRTNETADDR pAddr));

    /**
     * Socket I/O multiplexing - extended version which can be woken up.
     * Checks if the socket is ready for reading or writing.
     *
     * @return  iprt status code.
     * @retval  VERR_INTERRUPTED if the thread was woken up by a pfnPoke call.
     * @param   hVdSock     VD Socket handle(/pointer).
     * @param   fEvents     Mask of events to wait for.
     * @param   pfEvents    Where to store the received events.
     * @param   cMillies    Number of milliseconds to wait for the socket.
     *                      Use RT_INDEFINITE_WAIT to wait for ever.
     */
    DECLR3CALLBACKMEMBER(int, pfnSelectOneEx, (VDSOCKET hVdSock, uint32_t fEvents,
                                               uint32_t *pfEvents, RTMSINTERVAL cMillies));

    /**
     * Wakes up the thread waiting in pfnSelectOneEx.
     *
     * @return iprt status code.
     * @param  hVdSock      VD Socket handle(/pointer).
     */
    DECLR3CALLBACKMEMBER(int, pfnPoke, (VDSOCKET hVdSock));

} VDINTERFACETCPNET, *PVDINTERFACETCPNET;

/**
 * Get TCP network stack interface from interface list.
 *
 * @return Pointer to the first TCP network stack interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACETCPNET) VDIfTcpNetGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_TCPNET);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_TCPNET)
                        && (pIf->cbSize == sizeof(VDINTERFACETCPNET))),
                    ("Not a TCP net interface"), NULL);

    return (PVDINTERFACETCPNET)pIf;
}


/**
 * Interface to synchronize concurrent accesses by several threads.
 *
 * @note The scope of this interface is to manage concurrent accesses after
 * the HDD container has been created, and they must stop before destroying the
 * container. Opening or closing images is covered by the synchronization, but
 * that does not mean it is safe to close images while a thread executes
 * #VDMerge or #VDCopy operating on these images. Making them safe would require
 * the lock to be held during the entire operation, which prevents other
 * concurrent acitivities.
 *
 * @note Right now this is kept as simple as possible, and does not even
 * attempt to provide enough information to allow e.g. concurrent write
 * accesses to different areas of the disk. The reason is that it is very
 * difficult to predict which area of a disk is affected by a write,
 * especially when different image formats are mixed. Maybe later a more
 * sophisticated interface will be provided which has the necessary information
 * about worst case affected areas.
 *
 * Per-disk interface. Optional, needed if the disk is accessed concurrently
 * by several threads, e.g. when merging diff images while a VM is running.
 */
typedef struct VDINTERFACETHREADSYNC
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Start a read operation.
     */
    DECLR3CALLBACKMEMBER(int, pfnStartRead, (void *pvUser));

    /**
     * Finish a read operation.
     */
    DECLR3CALLBACKMEMBER(int, pfnFinishRead, (void *pvUser));

    /**
     * Start a write operation.
     */
    DECLR3CALLBACKMEMBER(int, pfnStartWrite, (void *pvUser));

    /**
     * Finish a write operation.
     */
    DECLR3CALLBACKMEMBER(int, pfnFinishWrite, (void *pvUser));

} VDINTERFACETHREADSYNC, *PVDINTERFACETHREADSYNC;

/**
 * Get thread synchronization interface from interface list.
 *
 * @return Pointer to the first thread synchronization interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACETHREADSYNC) VDIfThreadSyncGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_THREADSYNC);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_THREADSYNC)
                        && (pIf->cbSize == sizeof(VDINTERFACETHREADSYNC))),
                    ("Not a thread synchronization interface"), NULL);

    return (PVDINTERFACETHREADSYNC)pIf;
}

/**
 * Interface to query usage of disk ranges.
 *
 * Per-operation interface. Optional.
 */
typedef struct VDINTERFACEQUERYRANGEUSE
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Query use of a disk range.
     */
    DECLR3CALLBACKMEMBER(int, pfnQueryRangeUse, (void *pvUser, uint64_t off, uint64_t cb,
                                                 bool *pfUsed));

} VDINTERFACEQUERYRANGEUSE, *PVDINTERFACEQUERYRANGEUSE;

/**
 * Get query range use interface from interface list.
 *
 * @return Pointer to the first thread synchronization interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACEQUERYRANGEUSE) VDIfQueryRangeUseGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_QUERYRANGEUSE);

    /* Check that the interface descriptor is a progress interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_QUERYRANGEUSE)
                        && (pIf->cbSize == sizeof(VDINTERFACEQUERYRANGEUSE))),
                    ("Not a query range use interface"), NULL);

    return (PVDINTERFACEQUERYRANGEUSE)pIf;
}

DECLINLINE(int) vdIfQueryRangeUse(PVDINTERFACEQUERYRANGEUSE pIfQueryRangeUse, uint64_t off, uint64_t cb,
                                  bool *pfUsed)
{
    return pIfQueryRangeUse->pfnQueryRangeUse(pIfQueryRangeUse->Core.pvUser, off, cb, pfUsed);
}


/**
 * Interface used to retrieve keys for cryptographic operations.
 *
 * Per-module interface. Optional but cryptographic modules might fail and
 * return an error if this is not present.
 */
typedef struct VDINTERFACECRYPTO
{
    /**
     * Common interface header.
     */
    VDINTERFACE    Core;

    /**
     * Retains a key identified by the ID. The caller will only hold a reference
     * to the key and must not modify the key buffer in any way.
     *
     * @returns VBox status code.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszId           The alias/id for the key to retrieve.
     * @param   ppbKey          Where to store the pointer to the key buffer on success.
     * @param   pcbKey          Where to store the size of the key in bytes on success.
     */
    DECLR3CALLBACKMEMBER(int, pfnKeyRetain, (void *pvUser, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey));

    /**
     * Releases one reference of the key identified by the given identifier.
     * The caller must not access the key buffer after calling this operation.
     *
     * @returns VBox status code.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszId           The alias/id for the key to release.
     *
     * @note  It is advised to release the key whenever it is not used anymore so
     *        the entity storing the key can do anything to make retrieving the key
     *        from memory more difficult like scrambling the memory buffer for
     *        instance.
     */
    DECLR3CALLBACKMEMBER(int, pfnKeyRelease, (void *pvUser, const char *pszId));

    /**
     * Gets a reference to the password identified by the given ID to open a key store supplied through the config interface.
     *
     * @returns VBox status code.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszId           The alias/id for the password to retain.
     * @param   ppszPassword    Where to store the password to unlock the key store on success.
     */
    DECLR3CALLBACKMEMBER(int, pfnKeyStorePasswordRetain, (void *pvUser, const char *pszId, const char **ppszPassword));

    /**
     * Releases a reference of the password previously acquired with VDINTERFACECRYPTO::pfnKeyStorePasswordRetain()
     * identified by the given ID.
     *
     * @returns VBox status code.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszId           The alias/id for the password to release.
     */
    DECLR3CALLBACKMEMBER(int, pfnKeyStorePasswordRelease, (void *pvUser, const char *pszId));

    /**
     * Saves a key store.
     *
     * @returns VBox status code.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pvKeyStore      The key store to save.
     * @param   cbKeyStore      Size of the key store in bytes.
     *
     * @note The format is filter specific and should be treated as binary data.
     */
    DECLR3CALLBACKMEMBER(int, pfnKeyStoreSave, (void *pvUser, const void *pvKeyStore, size_t cbKeyStore));

    /**
     * Returns the parameters after the key store was loaded successfully.
     *
     * @returns VBox status code.
     * @param   pvUser          The opaque user data associated with this interface.
     * @param   pszCipher       The cipher identifier the DEK is used for.
     * @param   pbDek           The raw DEK which was contained in the key store loaded by
     *                          VDINTERFACECRYPTO::pfnKeyStoreLoad().
     * @param   cbDek           The size of the DEK.
     *
     * @note The provided pointer to the DEK is only valid until this call returns.
     *       The content might change afterwards with out notice (when scrambling the key
     *       for further protection for example) or might be even freed.
     *
     * @note This method is optional and can be NULL if the caller does not require the
     *       parameters.
     */
    DECLR3CALLBACKMEMBER(int, pfnKeyStoreReturnParameters, (void *pvUser, const char *pszCipher,
                                                            const uint8_t *pbDek, size_t cbDek));

} VDINTERFACECRYPTO, *PVDINTERFACECRYPTO;


/**
 * Get error interface from interface list.
 *
 * @return Pointer to the first error interface in the list.
 * @param  pVDIfs    Pointer to the interface list.
 */
DECLINLINE(PVDINTERFACECRYPTO) VDIfCryptoGet(PVDINTERFACE pVDIfs)
{
    PVDINTERFACE pIf = VDInterfaceGet(pVDIfs, VDINTERFACETYPE_CRYPTO);

    /* Check that the interface descriptor is a crypto interface. */
    AssertMsgReturn(   !pIf
                    || (   (pIf->enmInterface == VDINTERFACETYPE_CRYPTO)
                        && (pIf->cbSize == sizeof(VDINTERFACECRYPTO))),
                    ("Not an crypto interface\n"), NULL);

    return (PVDINTERFACECRYPTO)pIf;
}

/**
 * Retains a key identified by the ID. The caller will only hold a reference
 * to the key and must not modify the key buffer in any way.
 *
 * @returns VBox status code.
 * @param   pIfCrypto       Pointer to the crypto interface.
 * @param   pszId           The alias/id for the key to retrieve.
 * @param   ppbKey          Where to store the pointer to the key buffer on success.
 * @param   pcbKey          Where to store the size of the key in bytes on success.
 */
DECLINLINE(int) vdIfCryptoKeyRetain(PVDINTERFACECRYPTO pIfCrypto, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey)
{
    return pIfCrypto->pfnKeyRetain(pIfCrypto->Core.pvUser, pszId, ppbKey, pcbKey);
}

/**
 * Releases one reference of the key identified by the given identifier.
 * The caller must not access the key buffer after calling this operation.
 *
 * @returns VBox status code.
 * @param   pIfCrypto       Pointer to the crypto interface.
 * @param   pszId           The alias/id for the key to release.
 *
 * @note  It is advised to release the key whenever it is not used anymore so
 *        the entity storing the key can do anything to make retrieving the key
 *        from memory more difficult like scrambling the memory buffer for
 *        instance.
 */
DECLINLINE(int) vdIfCryptoKeyRelease(PVDINTERFACECRYPTO pIfCrypto, const char *pszId)
{
    return pIfCrypto->pfnKeyRelease(pIfCrypto->Core.pvUser, pszId);
}

/**
 * Gets a reference to the password identified by the given ID to open a key store supplied through the config interface.
 *
 * @returns VBox status code.
 * @param   pIfCrypto       Pointer to the crypto interface.
 * @param   pszId           The alias/id for the password to retain.
 * @param   ppszPassword    Where to store the password to unlock the key store on success.
 */
DECLINLINE(int) vdIfCryptoKeyStorePasswordRetain(PVDINTERFACECRYPTO pIfCrypto, const char *pszId, const char **ppszPassword)
{
    return pIfCrypto->pfnKeyStorePasswordRetain(pIfCrypto->Core.pvUser, pszId, ppszPassword);
}

/**
 * Releases a reference of the password previously acquired with VDINTERFACECRYPTO::pfnKeyStorePasswordRetain()
 * identified by the given ID.
 *
 * @returns VBox status code.
 * @param   pIfCrypto       Pointer to the crypto interface.
 * @param   pszId           The alias/id for the password to release.
 */
DECLINLINE(int) vdIfCryptoKeyStorePasswordRelease(PVDINTERFACECRYPTO pIfCrypto, const char *pszId)
{
    return pIfCrypto->pfnKeyStorePasswordRelease(pIfCrypto->Core.pvUser, pszId);
}

/**
 * Saves a key store.
 *
 * @returns VBox status code.
 * @param   pIfCrypto       Pointer to the crypto interface.
 * @param   pvKeyStore      The key store to save.
 * @param   cbKeyStore      Size of the key store in bytes.
 *
 * @note The format is filter specific and should be treated as binary data.
 */
DECLINLINE(int) vdIfCryptoKeyStoreSave(PVDINTERFACECRYPTO pIfCrypto, const void *pvKeyStore, size_t cbKeyStore)
{
    return pIfCrypto->pfnKeyStoreSave(pIfCrypto->Core.pvUser, pvKeyStore, cbKeyStore);
}

/**
 * Returns the parameters after the key store was loaded successfully.
 *
 * @returns VBox status code.
 * @param   pIfCrypto       Pointer to the crypto interface.
 * @param   pszCipher       The cipher identifier the DEK is used for.
 * @param   pbDek           The raw DEK which was contained in the key store loaded by
 *                          VDINTERFACECRYPTO::pfnKeyStoreLoad().
 * @param   cbDek           The size of the DEK.
 *
 * @note The provided pointer to the DEK is only valid until this call returns.
 *       The content might change afterwards with out notice (when scrambling the key
 *       for further protection for example) or might be even freed.
 *
 * @note This method is optional and can be NULL if the caller does not require the
 *       parameters.
 */
DECLINLINE(int) vdIfCryptoKeyStoreReturnParameters(PVDINTERFACECRYPTO pIfCrypto, const char *pszCipher,
                                                   const uint8_t *pbDek, size_t cbDek)
{
    if (pIfCrypto->pfnKeyStoreReturnParameters)
        return pIfCrypto->pfnKeyStoreReturnParameters(pIfCrypto->Core.pvUser, pszCipher, pbDek, cbDek);

    return VINF_SUCCESS;
}


RT_C_DECLS_END

/** @} */

#endif /* !VBOX_INCLUDED_vd_ifs_h */