summaryrefslogtreecommitdiffstats
path: root/src/VBox/Devices/Audio/HDAStream.cpp
blob: d4e14b6e66fa9c8eee614868d764d5635194a5c3 (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
/* $Id: HDAStream.cpp $ */
/** @file
 * HDAStream.cpp - Stream functions for HD Audio.
 */

/*
 * Copyright (C) 2017-2019 Oracle Corporation
 *
 * 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.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DEV_HDA
#include <VBox/log.h>

#include <iprt/mem.h>
#include <iprt/semaphore.h>

#include <VBox/vmm/pdmdev.h>
#include <VBox/vmm/pdmaudioifs.h>

#include "DrvAudio.h"

#include "DevHDA.h"
#include "HDAStream.h"


#ifdef IN_RING3

/**
 * Creates an HDA stream.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to create.
 * @param   pThis               HDA state to assign the HDA stream to.
 * @param   u8SD                Stream descriptor number to assign.
 */
int hdaR3StreamCreate(PHDASTREAM pStream, PHDASTATE pThis, uint8_t u8SD)
{
    RT_NOREF(pThis);
    AssertPtrReturn(pStream, VERR_INVALID_POINTER);

    pStream->u8SD           = u8SD;
    pStream->pMixSink       = NULL;
    pStream->pHDAState      = pThis;
    pStream->pTimer         = pThis->pTimer[u8SD];
    AssertPtr(pStream->pTimer);

    pStream->State.fInReset = false;
    pStream->State.fRunning = false;
#ifdef HDA_USE_DMA_ACCESS_HANDLER
    RTListInit(&pStream->State.lstDMAHandlers);
#endif

    int rc = RTCritSectInit(&pStream->CritSect);
    AssertRCReturn(rc, rc);

    rc = hdaR3StreamPeriodCreate(&pStream->State.Period);
    AssertRCReturn(rc, rc);

    pStream->State.tsLastUpdateNs = 0;

#ifdef DEBUG
    rc = RTCritSectInit(&pStream->Dbg.CritSect);
    AssertRCReturn(rc, rc);
#endif

    pStream->Dbg.Runtime.fEnabled = pThis->Dbg.fEnabled;

    if (pStream->Dbg.Runtime.fEnabled)
    {
        char szFile[64];

        if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
            RTStrPrintf(szFile, sizeof(szFile), "hdaStreamWriteSD%RU8", pStream->u8SD);
        else
            RTStrPrintf(szFile, sizeof(szFile), "hdaStreamReadSD%RU8", pStream->u8SD);

        char szPath[RTPATH_MAX + 1];
        int rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
                                         0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
        AssertRC(rc2);
        rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileStream);
        AssertRC(rc2);

        if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
            RTStrPrintf(szFile, sizeof(szFile), "hdaDMARawWriteSD%RU8", pStream->u8SD);
        else
            RTStrPrintf(szFile, sizeof(szFile), "hdaDMARawReadSD%RU8", pStream->u8SD);

        rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
                                     0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
        AssertRC(rc2);

        rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileDMARaw);
        AssertRC(rc2);

        if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
            RTStrPrintf(szFile, sizeof(szFile), "hdaDMAWriteMappedSD%RU8", pStream->u8SD);
        else
            RTStrPrintf(szFile, sizeof(szFile), "hdaDMAReadMappedSD%RU8", pStream->u8SD);

        rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
                                     0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
        AssertRC(rc2);

        rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileDMAMapped);
        AssertRC(rc2);

        /* Delete stale debugging files from a former run. */
        DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileStream);
        DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileDMARaw);
        DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileDMAMapped);
    }

    return rc;
}

/**
 * Destroys an HDA stream.
 *
 * @param   pStream             HDA stream to destroy.
 */
void hdaR3StreamDestroy(PHDASTREAM pStream)
{
    AssertPtrReturnVoid(pStream);

    LogFlowFunc(("[SD%RU8] Destroying ...\n", pStream->u8SD));

    hdaR3StreamMapDestroy(&pStream->State.Mapping);

    int rc2;

#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
    rc2 = hdaR3StreamAsyncIODestroy(pStream);
    AssertRC(rc2);
#endif

    if (RTCritSectIsInitialized(&pStream->CritSect))
    {
        rc2 = RTCritSectDelete(&pStream->CritSect);
        AssertRC(rc2);
    }

    if (pStream->State.pCircBuf)
    {
        RTCircBufDestroy(pStream->State.pCircBuf);
        pStream->State.pCircBuf = NULL;
    }

    hdaR3StreamPeriodDestroy(&pStream->State.Period);

#ifdef DEBUG
    if (RTCritSectIsInitialized(&pStream->Dbg.CritSect))
    {
        rc2 = RTCritSectDelete(&pStream->Dbg.CritSect);
        AssertRC(rc2);
    }
#endif

    if (pStream->Dbg.Runtime.fEnabled)
    {
        DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileStream);
        pStream->Dbg.Runtime.pFileStream = NULL;

        DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileDMARaw);
        pStream->Dbg.Runtime.pFileDMARaw = NULL;

        DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileDMAMapped);
        pStream->Dbg.Runtime.pFileDMAMapped = NULL;
    }

    LogFlowFuncLeave();
}

/**
 * Initializes an HDA stream.
 *
 * @returns IPRT status code. VINF_NO_CHANGE if the stream does not need (re-)initialization because the stream's (hardware)
 *          parameters did not change.
 * @param   pStream             HDA stream to initialize.
 * @param   uSD                 SD (stream descriptor) number to assign the HDA stream to.
 */
int hdaR3StreamInit(PHDASTREAM pStream, uint8_t uSD)
{
    AssertPtrReturn(pStream, VERR_INVALID_POINTER);

    PHDASTATE pThis = pStream->pHDAState;
    AssertPtr(pThis);

    const uint64_t u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, uSD),
                                            HDA_STREAM_REG(pThis, BDPU, uSD));
    const uint16_t u16LVI     = HDA_STREAM_REG(pThis, LVI, uSD);
    const uint32_t u32CBL     = HDA_STREAM_REG(pThis, CBL, uSD);
    const uint16_t u16FIFOS   = HDA_STREAM_REG(pThis, FIFOS, uSD) + 1;
    const uint16_t u16FMT     = HDA_STREAM_REG(pThis, FMT, uSD);

    /* Is the bare minimum set of registers configured for the stream?
     * If not, bail out early, as there's nothing to do here for us (yet). */
    if (   !u64BDLBase
        || !u16LVI
        || !u32CBL
        || !u16FIFOS
        || !u16FMT)
    {
        LogFunc(("[SD%RU8] Registers not set up yet, skipping (re-)initialization\n", uSD));
        return VINF_SUCCESS;
    }

    PDMAUDIOPCMPROPS Props;
    int rc = hdaR3SDFMTToPCMProps(u16FMT, &Props);
    if (RT_FAILURE(rc))
    {
        LogRel(("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
        return rc;
    }

    /* Reset (any former) stream map. */
    hdaR3StreamMapReset(&pStream->State.Mapping);

    /*
     * Initialize the stream mapping in any case, regardless if
     * we support surround audio or not. This is needed to handle
     * the supported channels within a single audio stream, e.g. mono/stereo.
     *
     * In other words, the stream mapping *always* knows the real
     * number of channels in a single audio stream.
     */
    rc = hdaR3StreamMapInit(&pStream->State.Mapping, &Props);
    AssertRCReturn(rc, rc);

    /*
     * Set the stream's timer Hz rate, based on the stream channel count.
     * Currently this is just a rough guess and we might want to optimize this further.
     *
     * In any case, more channels per SDI/SDO means that we have to drive data more frequently.
     */
    if (pThis->uTimerHz == HDA_TIMER_HZ_DEFAULT) /* Make sure that we don't have any custom Hz rate set we want to enforce */
    {
        if (Props.cChannels >= 5)
            pStream->State.uTimerHz = 300;
        else if (Props.cChannels == 4)
            pStream->State.uTimerHz = 150;
        else
            pStream->State.uTimerHz = 100;
    }
    else
        pStream->State.uTimerHz = pThis->uTimerHz;

#ifndef VBOX_WITH_AUDIO_HDA_51_SURROUND
    if (Props.cChannels > 2)
    {
        /*
         * When not running with surround support enabled, override the audio channel count
         * with stereo (2) channels so that we at least can properly work with those.
         *
         * Note: This also involves dealing with surround setups the guest might has set up for us.
         */
        LogRel2(("HDA: More than stereo (2) channels are not supported (%RU8 requested), "
                 "falling back to stereo channels for stream #%RU8\n", Props.cChannels, uSD));
        Props.cChannels = 2;
        Props.cShift    = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(Props.cBytes, Props.cChannels);
    }
#endif

    /* Did some of the vital / critical parameters change?
     * If not, we can skip a lot of the (re-)initialization and just (re-)use the existing stuff.
     * Also, tell the caller so that further actions can be taken. */
    if (   uSD        == pStream->u8SD
        && u64BDLBase == pStream->u64BDLBase
        && u16LVI     == pStream->u16LVI
        && u32CBL     == pStream->u32CBL
        && u16FIFOS   == pStream->u16FIFOS
        && u16FMT     == pStream->u16FMT)
    {
        LogFunc(("[SD%RU8] No format change, skipping (re-)initialization\n", uSD));
        return VINF_NO_CHANGE;
    }

    pStream->u8SD       = uSD;

    /* Update all register copies so that we later know that something has changed. */
    pStream->u64BDLBase = u64BDLBase;
    pStream->u16LVI     = u16LVI;
    pStream->u32CBL     = u32CBL;
    pStream->u16FIFOS   = u16FIFOS;
    pStream->u16FMT     = u16FMT;

    PPDMAUDIOSTREAMCFG pCfg = &pStream->State.Cfg;
    pCfg->Props = Props;

    /* (Re-)Allocate the stream's internal DMA buffer, based on the PCM  properties we just got above. */
    if (pStream->State.pCircBuf)
    {
        RTCircBufDestroy(pStream->State.pCircBuf);
        pStream->State.pCircBuf = NULL;
    }

    /* By default we allocate an internal buffer of 100ms. */
    rc = RTCircBufCreate(&pStream->State.pCircBuf,
                         DrvAudioHlpMilliToBytes(100 /* ms */, &pCfg->Props)); /** @todo Make this configurable. */
    AssertRCReturn(rc, rc);

    /* Set the stream's direction. */
    pCfg->enmDir = hdaGetDirFromSD(pStream->u8SD);

    /* The the stream's name, based on the direction. */
    switch (pCfg->enmDir)
    {
        case PDMAUDIODIR_IN:
# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
#  error "Implement me!"
# else
            pCfg->DestSource.Source = PDMAUDIORECSOURCE_LINE;
            pCfg->enmLayout         = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
            RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
# endif
            break;

        case PDMAUDIODIR_OUT:
            /* Destination(s) will be set in hdaAddStreamOut(),
             * based on the channels / stream layout. */
            break;

        default:
            rc = VERR_NOT_SUPPORTED;
            break;
    }

    /* Set scheduling hint (if available). */
    if (pStream->State.uTimerHz)
        pCfg->Device.uSchedulingHintMs = 1000 /* ms */ / pStream->State.uTimerHz;

    LogFunc(("[SD%RU8] DMA @ 0x%x (%RU32 bytes), LVI=%RU16, FIFOS=%RU16\n",
             pStream->u8SD, pStream->u64BDLBase, pStream->u32CBL, pStream->u16LVI, pStream->u16FIFOS));

    /* Make sure that mandatory parameters are set up correctly. */
    AssertStmt(pStream->u32CBL %  pStream->State.Mapping.cbFrameSize == 0, rc = VERR_INVALID_PARAMETER);
    AssertStmt(pStream->u16LVI >= 1,                                       rc = VERR_INVALID_PARAMETER);

    if (RT_SUCCESS(rc))
    {
        /* Make sure that the chosen Hz rate dividable by the stream's rate. */
        if (pStream->State.Cfg.Props.uHz % pStream->State.uTimerHz != 0)
            LogRel(("HDA: Stream timer Hz rate (%RU32) does not fit to stream #%RU8 timing (%RU32)\n",
                    pStream->State.uTimerHz, pStream->u8SD, pStream->State.Cfg.Props.uHz));

        /* Figure out how many transfer fragments we're going to use for this stream. */
        /** @todo Use a more dynamic fragment size? */
        Assert(pStream->u16LVI <= UINT8_MAX - 1);
        uint8_t cFragments = pStream->u16LVI + 1;
        if (cFragments <= 1)
            cFragments = 2; /* At least two fragments (BDLEs) must be present. */

        /*
         * Handle the stream's position adjustment.
         */
        uint32_t cfPosAdjust = 0;

        LogFunc(("[SD%RU8] fPosAdjustEnabled=%RTbool, cPosAdjustFrames=%RU16\n",
                 pStream->u8SD, pThis->fPosAdjustEnabled, pThis->cPosAdjustFrames));

        if (pThis->fPosAdjustEnabled) /* Is the position adjustment enabled at all? */
        {
            HDABDLE BDLE;
            RT_ZERO(BDLE);

            int rc2 = hdaR3BDLEFetch(pThis, &BDLE, pStream->u64BDLBase, 0 /* Entry */);
            AssertRC(rc2);

            /* Note: Do *not* check if this BDLE aligns to the stream's frame size.
             *       It can happen that this isn't the case on some guests, e.g.
             *       on Windows with a 5.1 speaker setup.
             *
             *       The only thing which counts is that the stream's CBL value
             *       properly aligns to the stream's frame size.
             */

            /* If no custom set position adjustment is set, apply some
             * simple heuristics to detect the appropriate position adjustment. */
            if (   !pThis->cPosAdjustFrames
            /* Position adjustmenet buffer *must* have the IOC bit set! */
                && hdaR3BDLENeedsInterrupt(&BDLE))
            {
                /** @todo Implement / use a (dynamic) table once this gets more complicated. */
#ifdef VBOX_WITH_INTEL_HDA
                /* Intel ICH / PCH: 1 frame. */
                if (BDLE.Desc.u32BufSize == (uint32_t)(1 * pStream->State.Mapping.cbFrameSize))
                {
                    cfPosAdjust = 1;
                }
                /* Intel Baytrail / Braswell: 32 frames. */
                else if (BDLE.Desc.u32BufSize == (uint32_t)(32 * pStream->State.Mapping.cbFrameSize))
                {
                    cfPosAdjust = 32;
                }
#endif
            }
            else /* Go with the set default. */
                cfPosAdjust = pThis->cPosAdjustFrames;

            if (cfPosAdjust)
            {
                /* Also adjust the number of fragments, as the position adjustment buffer
                 * does not count as an own fragment as such.
                 *
                 * This e.g. can happen on (newer) Ubuntu guests which use
                 * 4 (IOC) + 4408 (IOC) + 4408 (IOC) + 4408 (IOC) + 4404 (= 17632) bytes,
                 * where the first buffer (4) is used as position adjustment.
                 *
                 * Only skip a fragment if the whole buffer fragment is used for
                 * position adjustment.
                 */
                if (   (cfPosAdjust * pStream->State.Mapping.cbFrameSize) == BDLE.Desc.u32BufSize
                    && cFragments)
                {
                    cFragments--;
                }

                /* Initialize position adjustment counter. */
                pStream->State.cfPosAdjustDefault = cfPosAdjust;
                pStream->State.cfPosAdjustLeft    = pStream->State.cfPosAdjustDefault;

                LogRel2(("HDA: Position adjustment for stream #%RU8 active (%RU32 frames)\n",
                         pStream->u8SD, pStream->State.cfPosAdjustDefault));
            }
        }

        LogFunc(("[SD%RU8] cfPosAdjust=%RU32, cFragments=%RU8\n", pStream->u8SD, cfPosAdjust, cFragments));

        /*
         * Set up data transfer stuff.
         */

        /* Calculate the fragment size the guest OS expects interrupt delivery at. */
        pStream->State.cbTransferSize = pStream->u32CBL / cFragments;
        Assert(pStream->State.cbTransferSize);
        Assert(pStream->State.cbTransferSize % pStream->State.Mapping.cbFrameSize == 0);

        /* Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
         * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects. */
        pStream->State.cbTransferChunk = (pStream->State.Cfg.Props.uHz / pStream->State.uTimerHz) * pStream->State.Mapping.cbFrameSize;
        Assert(pStream->State.cbTransferChunk);
        Assert(pStream->State.cbTransferChunk % pStream->State.Mapping.cbFrameSize == 0);

        /* Make sure that the transfer chunk does not exceed the overall transfer size. */
        if (pStream->State.cbTransferChunk > pStream->State.cbTransferSize)
            pStream->State.cbTransferChunk = pStream->State.cbTransferSize;

        const uint64_t cTicksPerHz = TMTimerGetFreq(pStream->pTimer) / pStream->State.uTimerHz;

        /* Calculate the timer ticks per byte for this stream. */
        pStream->State.cTicksPerByte = cTicksPerHz / pStream->State.cbTransferChunk;
        Assert(pStream->State.cTicksPerByte);

        /* Calculate timer ticks per transfer. */
        pStream->State.cTransferTicks     = pStream->State.cbTransferChunk * pStream->State.cTicksPerByte;
        Assert(pStream->State.cTransferTicks);

        LogFunc(("[SD%RU8] Timer %uHz (%RU64 ticks per Hz), cTicksPerByte=%RU64, cbTransferChunk=%RU32, cTransferTicks=%RU64, " \
                 "cbTransferSize=%RU32\n",
                 pStream->u8SD, pStream->State.uTimerHz, cTicksPerHz, pStream->State.cTicksPerByte,
                 pStream->State.cbTransferChunk, pStream->State.cTransferTicks, pStream->State.cbTransferSize));

        /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
        hdaR3StreamSetPosition(pStream, HDA_STREAM_REG(pThis, LPIB, pStream->u8SD));

#ifdef LOG_ENABLED
        hdaR3BDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
#endif
    }

    if (RT_FAILURE(rc))
        LogRel(("HDA: Initializing stream #%RU8 failed with %Rrc\n", pStream->u8SD, rc));

    return rc;
}

/**
 * Resets an HDA stream.
 *
 * @param   pThis               HDA state.
 * @param   pStream             HDA stream to reset.
 * @param   uSD                 Stream descriptor (SD) number to use for this stream.
 */
void hdaR3StreamReset(PHDASTATE pThis, PHDASTREAM pStream, uint8_t uSD)
{
    AssertPtrReturnVoid(pThis);
    AssertPtrReturnVoid(pStream);
    AssertReturnVoid(uSD < HDA_MAX_STREAMS);

# ifdef VBOX_STRICT
    AssertReleaseMsg(!pStream->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
# endif

    LogFunc(("[SD%RU8] Reset\n", uSD));

    /*
     * Set reset state.
     */
    Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false); /* No nested calls. */
    ASMAtomicXchgBool(&pStream->State.fInReset, true);

    /*
     * Second, initialize the registers.
     */
    HDA_STREAM_REG(pThis, STS,   uSD) = HDA_SDSTS_FIFORDY;
    /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
     * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
    HDA_STREAM_REG(pThis, CTL,   uSD) = 0x40000 | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
    /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
    HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
    /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
    HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
    HDA_STREAM_REG(pThis, LPIB,  uSD) = 0;
    HDA_STREAM_REG(pThis, CBL,   uSD) = 0;
    HDA_STREAM_REG(pThis, LVI,   uSD) = 0;
    HDA_STREAM_REG(pThis, FMT,   uSD) = 0;
    HDA_STREAM_REG(pThis, BDPU,  uSD) = 0;
    HDA_STREAM_REG(pThis, BDPL,  uSD) = 0;

#ifdef HDA_USE_DMA_ACCESS_HANDLER
    hdaR3StreamUnregisterDMAHandlers(pThis, pStream);
#endif

    /* Assign the default mixer sink to the stream. */
    pStream->pMixSink = hdaR3GetDefaultSink(pThis, uSD);

    /* Reset position adjustment counter. */
    pStream->State.cfPosAdjustLeft = pStream->State.cfPosAdjustDefault;

    /* Reset transfer stuff. */
    pStream->State.cbTransferProcessed        = 0;
    pStream->State.cTransferPendingInterrupts = 0;
    pStream->State.tsTransferLast = 0;
    pStream->State.tsTransferNext = 0;

    /* Initialize other timestamps. */
    pStream->State.tsLastUpdateNs = 0;

    RT_ZERO(pStream->State.BDLE);
    pStream->State.uCurBDLE = 0;

    if (pStream->State.pCircBuf)
        RTCircBufReset(pStream->State.pCircBuf);

    /* Reset the stream's period. */
    hdaR3StreamPeriodReset(&pStream->State.Period);

#ifdef DEBUG
    pStream->Dbg.cReadsTotal      = 0;
    pStream->Dbg.cbReadTotal      = 0;
    pStream->Dbg.tsLastReadNs     = 0;
    pStream->Dbg.cWritesTotal     = 0;
    pStream->Dbg.cbWrittenTotal   = 0;
    pStream->Dbg.cWritesHz        = 0;
    pStream->Dbg.cbWrittenHz      = 0;
    pStream->Dbg.tsWriteSlotBegin = 0;
#endif

    /* Report that we're done resetting this stream. */
    HDA_STREAM_REG(pThis, CTL,   uSD) = 0;

    LogFunc(("[SD%RU8] Reset\n", uSD));

    /* Exit reset mode. */
    ASMAtomicXchgBool(&pStream->State.fInReset, false);
}

/**
 * Enables or disables an HDA audio stream.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to enable or disable.
 * @param   fEnable             Whether to enable or disble the stream.
 */
int hdaR3StreamEnable(PHDASTREAM pStream, bool fEnable)
{
    AssertPtrReturn(pStream, VERR_INVALID_POINTER);

    LogFunc(("[SD%RU8] fEnable=%RTbool, pMixSink=%p\n", pStream->u8SD, fEnable, pStream->pMixSink));

    int rc = VINF_SUCCESS;

    AUDMIXSINKCMD enmCmd = fEnable
                         ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;

    /* First, enable or disable the stream and the stream's sink, if any. */
    if (   pStream->pMixSink
        && pStream->pMixSink->pMixSink)
        rc = AudioMixerSinkCtl(pStream->pMixSink->pMixSink, enmCmd);

    if (   RT_SUCCESS(rc)
        && fEnable
        && pStream->Dbg.Runtime.fEnabled)
    {
        Assert(DrvAudioHlpPCMPropsAreValid(&pStream->State.Cfg.Props));

        if (fEnable)
        {
            if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileStream))
            {
                int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileStream, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
                                              &pStream->State.Cfg.Props);
                AssertRC(rc2);
            }

            if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileDMARaw))
            {
                int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileDMARaw, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
                                              &pStream->State.Cfg.Props);
                AssertRC(rc2);
            }

            if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileDMAMapped))
            {
                int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileDMAMapped, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
                                              &pStream->State.Cfg.Props);
                AssertRC(rc2);
            }
        }
    }

    if (RT_SUCCESS(rc))
    {
        pStream->State.fRunning = fEnable;
    }

    LogFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
    return rc;
}

uint32_t hdaR3StreamGetPosition(PHDASTATE pThis, PHDASTREAM pStream)
{
    return HDA_STREAM_REG(pThis, LPIB, pStream->u8SD);
}

/**
 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
 * updating its associated LPIB register and DMA position buffer (if enabled).
 *
 * @param   pStream             HDA stream to update read / write position for.
 * @param   u32LPIB             Absolute position (in bytes) to set current read / write position to.
 */
void hdaR3StreamSetPosition(PHDASTREAM pStream, uint32_t u32LPIB)
{
    AssertPtrReturnVoid(pStream);

    Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
              pStream->u8SD, u32LPIB, pStream->pHDAState->fDMAPosition));

    /* Update LPIB in any case. */
    HDA_STREAM_REG(pStream->pHDAState, LPIB, pStream->u8SD) = u32LPIB;

    /* Do we need to tell the current DMA position? */
    if (pStream->pHDAState->fDMAPosition)
    {
        int rc2 = PDMDevHlpPCIPhysWrite(pStream->pHDAState->CTX_SUFF(pDevIns),
                                        pStream->pHDAState->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
                                        (void *)&u32LPIB, sizeof(uint32_t));
        AssertRC(rc2);
    }
}

/**
 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
 *
 * @returns Available data (in bytes).
 * @param   pStream             HDA stream to retrieve size for.
 */
uint32_t hdaR3StreamGetUsed(PHDASTREAM pStream)
{
    AssertPtrReturn(pStream, 0);

    if (!pStream->State.pCircBuf)
        return 0;

    return (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
}

/**
 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
 *
 * @returns Free data (in bytes).
 * @param   pStream             HDA stream to retrieve size for.
 */
uint32_t hdaR3StreamGetFree(PHDASTREAM pStream)
{
    AssertPtrReturn(pStream, 0);

    if (!pStream->State.pCircBuf)
        return 0;

    return (uint32_t)RTCircBufFree(pStream->State.pCircBuf);
}

/**
 * Returns whether a next transfer for a given stream is scheduled or not.
 * This takes pending stream interrupts into account as well as the next scheduled
 * transfer timestamp.
 *
 * @returns True if a next transfer is scheduled, false if not.
 * @param   pStream             HDA stream to retrieve schedule status for.
 */
bool hdaR3StreamTransferIsScheduled(PHDASTREAM pStream)
{
    if (pStream)
    {
        AssertPtrReturn(pStream->pHDAState, false);

        if (pStream->State.fRunning)
        {
            if (pStream->State.cTransferPendingInterrupts)
            {
                Log3Func(("[SD%RU8] Scheduled (%RU8 IRQs pending)\n", pStream->u8SD, pStream->State.cTransferPendingInterrupts));
                return true;
            }

            const uint64_t tsNow = TMTimerGet(pStream->pTimer);
            if (pStream->State.tsTransferNext > tsNow)
            {
                Log3Func(("[SD%RU8] Scheduled in %RU64\n", pStream->u8SD, pStream->State.tsTransferNext - tsNow));
                return true;
            }
        }
    }
    return false;
}

/**
 * Returns the (virtual) clock timestamp of the next transfer, if any.
 * Will return 0 if no new transfer is scheduled.
 *
 * @returns The (virtual) clock timestamp of the next transfer.
 * @param   pStream             HDA stream to retrieve timestamp for.
 */
uint64_t hdaR3StreamTransferGetNext(PHDASTREAM pStream)
{
    return pStream->State.tsTransferNext;
}

/**
 * Writes audio data from a mixer sink into an HDA stream's DMA buffer.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to write to.
 * @param   pvBuf               Data buffer to write.
 *                              If NULL, silence will be written.
 * @param   cbBuf               Number of bytes of data buffer to write.
 * @param   pcbWritten          Number of bytes written. Optional.
 */
int hdaR3StreamWrite(PHDASTREAM pStream, const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
{
    AssertPtrReturn(pStream, VERR_INVALID_POINTER);
    /* pvBuf is optional. */
    AssertReturn(cbBuf,      VERR_INVALID_PARAMETER);
    /* pcbWritten is optional. */

    PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
    AssertPtr(pCircBuf);

    int rc = VINF_SUCCESS;

    uint32_t cbWrittenTotal = 0;
    uint32_t cbLeft         = RT_MIN(cbBuf, (uint32_t)RTCircBufFree(pCircBuf));

    while (cbLeft)
    {
        void *pvDst;
        size_t cbDst;

        RTCircBufAcquireWriteBlock(pCircBuf, cbLeft, &pvDst, &cbDst);

        if (cbDst)
        {
            if (pvBuf)
            {
                memcpy(pvDst, (uint8_t *)pvBuf + cbWrittenTotal, cbDst);
            }
            else /* Send silence. */
            {
                /** @todo Use a sample spec for "silence" based on the PCM parameters.
                 *        For now we ASSUME that silence equals NULLing the data. */
                RT_BZERO(pvDst, cbDst);
            }

            if (pStream->Dbg.Runtime.fEnabled)
                DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvDst, cbDst, 0 /* fFlags */);
        }

        RTCircBufReleaseWriteBlock(pCircBuf, cbDst);

        if (RT_FAILURE(rc))
            break;

        Assert(cbLeft  >= (uint32_t)cbDst);
        cbLeft         -= (uint32_t)cbDst;

        cbWrittenTotal += (uint32_t)cbDst;
    }

    Log3Func(("cbWrittenTotal=%RU32\n", cbWrittenTotal));

    if (pcbWritten)
        *pcbWritten = cbWrittenTotal;

    return rc;
}


/**
 * Reads audio data from an HDA stream's DMA buffer and writes into a specified mixer sink.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to read audio data from.
 * @param   cbToRead            Number of bytes to read.
 * @param   pcbRead             Number of bytes read. Optional.
 */
int hdaR3StreamRead(PHDASTREAM pStream, uint32_t cbToRead, uint32_t *pcbRead)
{
    AssertPtrReturn(pStream, VERR_INVALID_POINTER);
    AssertReturn(cbToRead,   VERR_INVALID_PARAMETER);
    /* pcbWritten is optional. */

    PHDAMIXERSINK pSink = pStream->pMixSink;
    if (!pSink)
    {
        AssertMsgFailed(("[SD%RU8] Can't read from a stream with no sink attached\n", pStream->u8SD));

        if (pcbRead)
            *pcbRead = 0;
        return VINF_SUCCESS;
    }

    PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
    AssertPtr(pCircBuf);

    int rc = VINF_SUCCESS;

    uint32_t cbReadTotal = 0;
    uint32_t cbLeft      = RT_MIN(cbToRead, (uint32_t)RTCircBufUsed(pCircBuf));

    while (cbLeft)
    {
        void *pvSrc;
        size_t cbSrc;

        uint32_t cbWritten = 0;

        RTCircBufAcquireReadBlock(pCircBuf, cbLeft, &pvSrc, &cbSrc);

        if (cbSrc)
        {
            if (pStream->Dbg.Runtime.fEnabled)
                DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvSrc, cbSrc, 0 /* fFlags */);

            rc = AudioMixerSinkWrite(pSink->pMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
            AssertRC(rc);

            Assert(cbSrc >= cbWritten);
            Log2Func(("[SD%RU8] %RU32/%zu bytes read\n", pStream->u8SD, cbWritten, cbSrc));
        }

        RTCircBufReleaseReadBlock(pCircBuf, cbWritten);

        if (RT_FAILURE(rc))
            break;

        Assert(cbLeft  >= cbWritten);
        cbLeft         -= cbWritten;

        cbReadTotal    += cbWritten;
    }

    if (pcbRead)
        *pcbRead = cbReadTotal;

    return rc;
}

/**
 * Transfers data of an HDA stream according to its usage (input / output).
 *
 * For an SDO (output) stream this means reading DMA data from the device to
 * the HDA stream's internal FIFO buffer.
 *
 * For an SDI (input) stream this is reading audio data from the HDA stream's
 * internal FIFO buffer and writing it as DMA data to the device.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to update.
 * @param   cbToProcessMax      How much data (in bytes) to process as maximum.
 */
int hdaR3StreamTransfer(PHDASTREAM pStream, uint32_t cbToProcessMax)
{
    AssertPtrReturn(pStream, VERR_INVALID_POINTER);

    hdaR3StreamLock(pStream);

    PHDASTATE pThis = pStream->pHDAState;
    AssertPtr(pThis);

    PHDASTREAMPERIOD pPeriod = &pStream->State.Period;
    if (!hdaR3StreamPeriodLock(pPeriod))
        return VERR_ACCESS_DENIED;

    bool fProceed = true;

    /* Stream not running? */
    if (!pStream->State.fRunning)
    {
        Log3Func(("[SD%RU8] Not running\n", pStream->u8SD));
        fProceed = false;
    }
    else if (HDA_STREAM_REG(pThis, STS, pStream->u8SD) & HDA_SDSTS_BCIS)
    {
        Log3Func(("[SD%RU8] BCIS bit set\n", pStream->u8SD));
        fProceed = false;
    }

    if (!fProceed)
    {
        hdaR3StreamPeriodUnlock(pPeriod);
        hdaR3StreamUnlock(pStream);
        return VINF_SUCCESS;
    }

    const uint64_t tsNow = TMTimerGet(pStream->pTimer);

    if (!pStream->State.tsTransferLast)
        pStream->State.tsTransferLast = tsNow;

#ifdef DEBUG
    const int64_t iTimerDelta = tsNow - pStream->State.tsTransferLast;
    Log3Func(("[SD%RU8] Time now=%RU64, last=%RU64 -> %RI64 ticks delta\n",
              pStream->u8SD, tsNow, pStream->State.tsTransferLast, iTimerDelta));
#endif

    pStream->State.tsTransferLast = tsNow;

    /* Sanity checks. */
    Assert(pStream->u8SD < HDA_MAX_STREAMS);
    Assert(pStream->u64BDLBase);
    Assert(pStream->u32CBL);
    Assert(pStream->u16FIFOS);

    /* State sanity checks. */
    Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false);

    int rc = VINF_SUCCESS;

    /* Fetch first / next BDL entry. */
    PHDABDLE pBDLE = &pStream->State.BDLE;
    if (hdaR3BDLEIsComplete(pBDLE))
    {
        rc = hdaR3BDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
        AssertRC(rc);
    }

    uint32_t cbToProcess = RT_MIN(pStream->State.cbTransferSize - pStream->State.cbTransferProcessed,
                                  pStream->State.cbTransferChunk);

    Log3Func(("[SD%RU8] cbToProcess=%RU32, cbToProcessMax=%RU32\n", pStream->u8SD, cbToProcess, cbToProcessMax));

    if (cbToProcess > cbToProcessMax)
    {
        LogFunc(("[SD%RU8] Limiting transfer (cbToProcess=%RU32, cbToProcessMax=%RU32)\n",
                 pStream->u8SD, cbToProcess, cbToProcessMax));

        /* Never process more than a stream currently can handle. */
        cbToProcess = cbToProcessMax;
    }

    uint32_t cbProcessed = 0;
    uint32_t cbLeft      = cbToProcess;

    uint8_t abChunk[HDA_FIFO_MAX + 1];
    while (cbLeft)
    {
        /* Limit the chunk to the stream's FIFO size and what's left to process. */
        uint32_t cbChunk = RT_MIN(cbLeft, pStream->u16FIFOS);

        /* Limit the chunk to the remaining data of the current BDLE. */
        cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);

        /* If there are position adjustment frames left to be processed,
         * make sure that we process them first as a whole. */
        if (pStream->State.cfPosAdjustLeft)
            cbChunk = RT_MIN(cbChunk, uint32_t(pStream->State.cfPosAdjustLeft * pStream->State.Mapping.cbFrameSize));

        Log3Func(("[SD%RU8] cbChunk=%RU32, cPosAdjustFramesLeft=%RU16\n",
                  pStream->u8SD, cbChunk, pStream->State.cfPosAdjustLeft));

        if (!cbChunk)
            break;

        uint32_t   cbDMA    = 0;
        PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;

        if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN) /* Input (SDI). */
        {
            STAM_PROFILE_START(&pThis->StatIn, a);

            uint32_t cbDMAWritten = 0;
            uint32_t cbDMAToWrite = cbChunk;

            /** @todo Do we need interleaving streams support here as well?
             *        Never saw anything else besides mono/stereo mics (yet). */
            while (cbDMAToWrite)
            {
                void *pvBuf; size_t cbBuf;
                RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);

                if (   !cbBuf
                    && !RTCircBufUsed(pCircBuf))
                    break;

                memcpy(abChunk + cbDMAWritten, pvBuf, cbBuf);

                RTCircBufReleaseReadBlock(pCircBuf, cbBuf);

                Assert(cbDMAToWrite >= cbBuf);
                cbDMAToWrite -= (uint32_t)cbBuf;
                cbDMAWritten += (uint32_t)cbBuf;
                Assert(cbDMAWritten <= cbChunk);
            }

            if (cbDMAToWrite)
            {
                LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", pStream->u8SD, cbDMAToWrite));

                Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
                memset((uint8_t *)abChunk + cbDMAWritten, 0, cbDMAToWrite);
                cbDMAWritten = cbChunk;
            }

            rc = hdaR3DMAWrite(pThis, pStream, abChunk, cbDMAWritten, &cbDMA /* pcbWritten */);
            if (RT_FAILURE(rc))
                LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));

            STAM_PROFILE_STOP(&pThis->StatIn, a);
        }
        else if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
        {
            STAM_PROFILE_START(&pThis->StatOut, a);

            rc = hdaR3DMARead(pThis, pStream, abChunk, cbChunk, &cbDMA /* pcbRead */);
            if (RT_SUCCESS(rc))
            {
                const uint32_t cbFree = (uint32_t)RTCircBufFree(pCircBuf);

                /*
                 * Most guests don't use different stream frame sizes than
                 * the default one, so save a bit of CPU time and don't go into
                 * the frame extraction code below.
                 *
                 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
                 */
                if (pStream->State.Mapping.cbFrameSize == HDA_FRAME_SIZE_DEFAULT)
                {
                    uint32_t cbDMARead = 0;
                    uint32_t cbDMALeft = RT_MIN(cbDMA, cbFree);

                    while (cbDMALeft)
                    {
                        void *pvBuf; size_t cbBuf;
                        RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);

                        if (cbBuf)
                        {
                            memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
                            cbDMARead += (uint32_t)cbBuf;
                            cbDMALeft -= (uint32_t)cbBuf;
                        }

                        RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
                    }
                }
                else
                {
                    /*
                     * The following code extracts the required audio stream (channel) data
                     * of non-interleaved *and* interleaved audio streams.
                     *
                     * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
                     * but an HDA audio stream can have interleaved audio data of multiple audio
                     * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
                     *
                     * So take this into account by just handling the first channel in such a stream ("A")
                     * and just discard the other channel's data.
                     *
                     * I know, the following code is horribly slow, but seems to work for now.
                     ** @todo Optimize channel data extraction! Use some SSE(3) / intrinsics?
                     */
                    for (unsigned m = 0; m < pStream->State.Mapping.cMappings; m++)
                    {
                        const uint32_t cbFrame  = pStream->State.Mapping.cbFrameSize;

                        Assert(cbFree >= cbDMA);

                        PPDMAUDIOSTREAMMAP pMap = &pStream->State.Mapping.paMappings[m];
                        AssertPtr(pMap);

                        Log3Func(("Mapping #%u: Start (cbDMA=%RU32, cbFrame=%RU32, cbOff=%RU32)\n",
                                  m, cbDMA, cbFrame, pMap->cbOff));

                        uint8_t *pbSrcBuf = abChunk;
                        size_t cbSrcOff   = pMap->cbOff;
                        Assert(cbChunk >= cbSrcOff);

                        for (unsigned i = 0; i < cbDMA / cbFrame; i++)
                        {
                            void *pvDstBuf; size_t cbDstBuf;
                            RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbSize, &pvDstBuf, &cbDstBuf);

                            Assert(cbDstBuf >= pMap->cbSize);

                            if (cbDstBuf)
                            {
                                Log3Func(("Mapping #%u: Frame #%02u:    cbSize=%zu, cbFirst=%zu, cbOff=%zu, cbDstBuf=%zu, cbSrcOff=%zu\n",
                                          m, i, pMap->cbSize, pMap->cbFirst, pMap->cbOff, cbDstBuf, cbSrcOff));

                                memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);

#if 0 /* Too slow, even for release builds, so disabled it. */
                                if (pStream->Dbg.Runtime.fEnabled)
                                    DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMAMapped, pvDstBuf, cbDstBuf,
                                                         0 /* fFlags */);
#endif
                                Assert(cbSrcOff <= cbDMA);
                                if (cbSrcOff + cbFrame + pMap->cbFirst <= cbDMA)
                                    cbSrcOff += cbFrame + pMap->cbFirst;

                                Log3Func(("Mapping #%u: Frame #%02u:    -> cbSrcOff=%zu\n", m, i, cbSrcOff));
                            }

                            RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
                        }

                        Log3Func(("Mapping #%u: End cbSize=%zu, cbDMA=%RU32, cbSrcOff=%zu\n",
                                  m, pMap->cbSize, cbDMA, cbSrcOff));

                        Assert(cbSrcOff <= cbDMA);

                        const uint32_t cbSrcLeft = cbDMA - (uint32_t)cbSrcOff;
                        if (cbSrcLeft)
                        {
                            Log3Func(("Mapping #%u: cbSrcLeft=%RU32\n", m, cbSrcLeft));

                            if (cbSrcLeft >= pMap->cbSize)
                            {
                                void *pvDstBuf; size_t cbDstBuf;
                                RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbSize, &pvDstBuf, &cbDstBuf);

                                Assert(cbDstBuf >= pMap->cbSize);

                                if (cbDstBuf)
                                {
                                    memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
                                }

                                RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
                            }

                            Assert(pMap->cbFrame >= cbSrcLeft);
                            pMap->cbOff = pMap->cbFrame - cbSrcLeft;
                        }
                        else
                            pMap->cbOff = 0;

                        Log3Func(("Mapping #%u finish (cbSrcOff=%zu, cbOff=%zu)\n", m, cbSrcOff, pMap->cbOff));
                    }
                }
            }
            else
                LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));

            STAM_PROFILE_STOP(&pThis->StatOut, a);
        }

        else /** @todo Handle duplex streams? */
            AssertFailed();

        if (cbDMA)
        {
            /* We always increment the position of DMA buffer counter because we're always reading
             * into an intermediate DMA buffer. */
            pBDLE->State.u32BufOff += (uint32_t)cbDMA;
            Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);

            /* Are we done doing the position adjustment?
             * Only then do the transfer accounting .*/
            if (pStream->State.cfPosAdjustLeft == 0)
            {
                Assert(cbLeft >= cbDMA);
                cbLeft        -= cbDMA;

                cbProcessed   += cbDMA;
            }

            /*
             * Update the stream's current position.
             * Do this as accurate and close to the actual data transfer as possible.
             * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
             */
            uint32_t cbStreamPos = hdaR3StreamGetPosition(pThis, pStream);
            if (cbStreamPos == pStream->u32CBL)
                cbStreamPos = 0;

            hdaR3StreamSetPosition(pStream, cbStreamPos + cbDMA);
        }

        if (hdaR3BDLEIsComplete(pBDLE))
        {
            Log3Func(("[SD%RU8] Complete: %R[bdle]\n", pStream->u8SD, pBDLE));

                /* Does the current BDLE require an interrupt to be sent? */
            if (   hdaR3BDLENeedsInterrupt(pBDLE)
                /* Are we done doing the position adjustment?
                 * It can happen that a BDLE which is handled while doing the
                 * position adjustment requires an interrupt on completion (IOC) being set.
                 *
                 * In such a case we need to skip such an interrupt and just move on. */
                && pStream->State.cfPosAdjustLeft == 0)
            {
                /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
                 * we need to generate an interrupt.
                 */
                if (HDA_STREAM_REG(pThis, CTL, pStream->u8SD) & HDA_SDCTL_IOCE)
                {
                    pStream->State.cTransferPendingInterrupts++;

                    AssertMsg(pStream->State.cTransferPendingInterrupts <= 32,
                              ("Too many pending interrupts (%RU8) for stream #%RU8\n",
                               pStream->State.cTransferPendingInterrupts, pStream->u8SD));
                }
            }

            if (pStream->State.uCurBDLE == pStream->u16LVI)
            {
                pStream->State.uCurBDLE = 0;
            }
            else
                pStream->State.uCurBDLE++;

            /* Fetch the next BDLE entry. */
            hdaR3BDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
        }

        /* Do the position adjustment accounting. */
        pStream->State.cfPosAdjustLeft -=
            RT_MIN(pStream->State.cfPosAdjustLeft, cbDMA / pStream->State.Mapping.cbFrameSize);

        if (RT_FAILURE(rc))
            break;
    }

    Log3Func(("[SD%RU8] cbToProcess=%RU32, cbProcessed=%RU32, cbLeft=%RU32, %R[bdle], rc=%Rrc\n",
              pStream->u8SD, cbToProcess, cbProcessed, cbLeft, pBDLE, rc));

    /* Sanity. */
    Assert(cbProcessed == cbToProcess);
    Assert(cbLeft      == 0);

    /* Only do the data accounting if we don't have to do any position
     * adjustment anymore. */
    if (pStream->State.cfPosAdjustLeft == 0)
    {
        hdaR3StreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStream->State.Mapping.cbFrameSize,
                                             hdaR3StreamPeriodGetRemainingFrames(pPeriod)));

        pStream->State.cbTransferProcessed += cbProcessed;
    }

    /* Make sure that we never report more stuff processed than initially announced. */
    if (pStream->State.cbTransferProcessed > pStream->State.cbTransferSize)
        pStream->State.cbTransferProcessed = pStream->State.cbTransferSize;

    uint32_t cbTransferLeft     = pStream->State.cbTransferSize - pStream->State.cbTransferProcessed;
    bool     fTransferComplete  = !cbTransferLeft;
    uint64_t tsTransferNext     = 0;

    if (fTransferComplete)
    {
        /*
         * Try updating the wall clock.
         *
         * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
         *         in order to determine the correct timing of the sound device. Other guests
         *         like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
         *         ignore this.
         *
         * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
         *         fashion) this *will* upset guest device drivers and will completely fuck up the
         *         sound output. Running VLC on the guest will tell!
         */
        const bool fWalClkSet = hdaR3WalClkSet(pThis,
                                                 hdaWalClkGetCurrent(pThis)
                                               + hdaR3StreamPeriodFramesToWalClk(pPeriod,
                                                                                   pStream->State.cbTransferProcessed
                                                                                 / pStream->State.Mapping.cbFrameSize),
                                               false /* fForce */);
        RT_NOREF(fWalClkSet);
    }

    /* Does the period have any interrupts outstanding? */
    if (pStream->State.cTransferPendingInterrupts)
    {
        Log3Func(("[SD%RU8] Scheduling interrupt\n", pStream->u8SD));

        /*
         * Set the stream's BCIS bit.
         *
         * Note: This only must be done if the whole period is complete, and not if only
         * one specific BDL entry is complete (if it has the IOC bit set).
         *
         * This will otherwise confuses the guest when it 1) deasserts the interrupt,
         * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
         *
         * snd_hda_intel on Linux will tell.
         */
        HDA_STREAM_REG(pThis, STS, pStream->u8SD) |= HDA_SDSTS_BCIS;

        /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
         * ending / beginning a period. */
#ifndef LOG_ENABLED
        hdaProcessInterrupt(pThis);
#else
        hdaProcessInterrupt(pThis, __FUNCTION__);
#endif
    }
    else /* Transfer still in-flight -- schedule the next timing slot. */
    {
        uint32_t cbTransferNext = cbTransferLeft;

        /* No data left to transfer anymore or do we have more data left
         * than we can transfer per timing slot? Clamp. */
        if (   !cbTransferNext
            || cbTransferNext > pStream->State.cbTransferChunk)
        {
            cbTransferNext = pStream->State.cbTransferChunk;
        }

        tsTransferNext = tsNow + (cbTransferNext * pStream->State.cTicksPerByte);

        /*
         * If the current transfer is complete, reset our counter.
         *
         * This can happen for examlpe if the guest OS (like macOS) sets up
         * big BDLEs without IOC bits set (but for the last one) and the
         * transfer is complete before we reach such a BDL entry.
         */
        if (fTransferComplete)
            pStream->State.cbTransferProcessed = 0;
    }

    /* If we need to do another transfer, (re-)arm the device timer.  */
    if (tsTransferNext) /* Can be 0 if no next transfer is needed. */
    {
        Log3Func(("[SD%RU8] Scheduling timer\n", pStream->u8SD));

        TMTimerUnlock(pStream->pTimer);

        LogFunc(("Timer set SD%RU8\n", pStream->u8SD));
        hdaR3TimerSet(pStream->pHDAState, pStream, tsTransferNext, false /* fForce */);

        TMTimerLock(pStream->pTimer, VINF_SUCCESS);

        pStream->State.tsTransferNext = tsTransferNext;
    }

    pStream->State.tsTransferLast = tsNow;

    Log3Func(("[SD%RU8] cbTransferLeft=%RU32 -- %RU32/%RU32\n",
              pStream->u8SD, cbTransferLeft, pStream->State.cbTransferProcessed, pStream->State.cbTransferSize));
    Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
              pStream->u8SD, fTransferComplete, pStream->State.cTransferPendingInterrupts));
    Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
              pStream->u8SD, tsNow, tsTransferNext, tsTransferNext - tsNow));

    hdaR3StreamPeriodUnlock(pPeriod);
    hdaR3StreamUnlock(pStream);

    return VINF_SUCCESS;
}

/**
 * Updates a HDA stream by doing its required data transfers.
 * The host sink(s) set the overall pace.
 *
 * This routine is called by both, the synchronous and the asynchronous, implementations.
 *
 * This routine is called by both, the synchronous and the asynchronous
 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
 *
 * When running synchronously, the device DMA transfers *and* the mixer sink
 * processing is within the device timer.
 *
 * When running asynchronously, only the device DMA transfers are done in the
 * device timer, whereas the mixer sink processing then is done in the stream's
 * own async I/O thread. This thread also will call this function
 * (with fInTimer set to @c false).
 *
 * @param   pStream             HDA stream to update.
 * @param   fInTimer            Whether to this function was called from the timer
 *                              context or an asynchronous I/O stream thread (if supported).
 */
void hdaR3StreamUpdate(PHDASTREAM pStream, bool fInTimer)
{
    if (!pStream)
        return;

    PAUDMIXSINK pSink = NULL;
    if (   pStream->pMixSink
        && pStream->pMixSink->pMixSink)
    {
        pSink = pStream->pMixSink->pMixSink;
    }

    if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
        return;

    int rc2;

    if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
    {
        bool fDoRead = false; /* Whether to read from the HDA stream or not. */

# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
        if (fInTimer)
# endif
        {
            const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
            if (cbStreamFree)
            {
                /* Do the DMA transfer. */
                rc2 = hdaR3StreamTransfer(pStream, cbStreamFree);
                AssertRC(rc2);
            }

            /* Only read from the HDA stream at the given scheduling rate. */
            const uint64_t tsNowNs = RTTimeNanoTS();
            if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
            {
                fDoRead = true;
                pStream->State.tsLastUpdateNs = tsNowNs;
            }
        }

        Log3Func(("[SD%RU8] fInTimer=%RTbool, fDoRead=%RTbool\n", pStream->u8SD, fInTimer, fDoRead));

# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
        if (fDoRead)
        {
            rc2 = hdaR3StreamAsyncIONotify(pStream);
            AssertRC(rc2);
        }
# endif

# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
        if (!fInTimer) /* In async I/O thread */
        {
# else
        if (fDoRead)
        {
# endif
            const uint32_t cbSinkWritable     = AudioMixerSinkGetWritable(pSink);
            const uint32_t cbStreamReadable   = hdaR3StreamGetUsed(pStream);
            const uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);

            Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32\n", pStream->u8SD, cbSinkWritable, cbStreamReadable));

            if (cbToReadFromStream)
            {
                /* Read (guest output) data and write it to the stream's sink. */
                rc2 = hdaR3StreamRead(pStream, cbToReadFromStream, NULL);
                AssertRC(rc2);
            }

            /* When running synchronously, update the associated sink here.
             * Otherwise this will be done in the async I/O thread. */
            rc2 = AudioMixerSinkUpdate(pSink);
            AssertRC(rc2);
        }
    }
    else /* Input (SDI). */
    {
# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
        if (!fInTimer)
        {
# endif
            rc2 = AudioMixerSinkUpdate(pSink);
            AssertRC(rc2);

            /* Is the sink ready to be read (host input data) from? If so, by how much? */
            uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);

            /* How much (guest input) data is available for writing at the moment for the HDA stream? */
            const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);

            Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStream->u8SD, cbSinkReadable, cbStreamFree));

            /* Do not read more than the HDA stream can hold at the moment.
             * The host sets the overall pace. */
            if (cbSinkReadable > cbStreamFree)
                cbSinkReadable = cbStreamFree;

            if (cbSinkReadable)
            {
                uint8_t abFIFO[HDA_FIFO_MAX + 1];
                while (cbSinkReadable)
                {
                    uint32_t cbRead;
                    rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
                                             abFIFO, RT_MIN(cbSinkReadable, (uint32_t)sizeof(abFIFO)), &cbRead);
                    AssertRCBreak(rc2);

                    if (!cbRead)
                    {
                        AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
                        break;
                    }

                    /* Write (guest input) data to the stream which was read from stream's sink before. */
                    uint32_t cbWritten;
                    rc2 = hdaR3StreamWrite(pStream, abFIFO, cbRead, &cbWritten);
                    AssertRCBreak(rc2);

                    if (!cbWritten)
                    {
                        AssertFailed(); /* Should never happen, as we know how much we can write. */
                        break;
                    }

                    Assert(cbSinkReadable >= cbRead);
                    cbSinkReadable -= cbRead;
                }
            }
# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
        }
        else /* fInTimer */
        {
# endif

# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
            const uint64_t tsNowNs = RTTimeNanoTS();
            if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
            {
                rc2 = hdaR3StreamAsyncIONotify(pStream);
                AssertRC(rc2);

                pStream->State.tsLastUpdateNs = tsNowNs;
            }
# endif
            const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStream);
            if (cbStreamUsed)
            {
                rc2 = hdaR3StreamTransfer(pStream, cbStreamUsed);
                AssertRC(rc2);
            }
# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
        }
# endif
    }
}

/**
 * Locks an HDA stream for serialized access.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to lock.
 */
void hdaR3StreamLock(PHDASTREAM pStream)
{
    AssertPtrReturnVoid(pStream);
    int rc2 = RTCritSectEnter(&pStream->CritSect);
    AssertRC(rc2);
}

/**
 * Unlocks a formerly locked HDA stream.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to unlock.
 */
void hdaR3StreamUnlock(PHDASTREAM pStream)
{
    AssertPtrReturnVoid(pStream);
    int rc2 = RTCritSectLeave(&pStream->CritSect);
    AssertRC(rc2);
}

/**
 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
 * updating its associated LPIB register and DMA position buffer (if enabled).
 *
 * @returns Set LPIB value.
 * @param   pStream             HDA stream to update read / write position for.
 * @param   u32LPIB             New LPIB (position) value to set.
 */
uint32_t hdaR3StreamUpdateLPIB(PHDASTREAM pStream, uint32_t u32LPIB)
{
    AssertPtrReturn(pStream, 0);

    AssertMsg(u32LPIB <= pStream->u32CBL,
              ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStream->u8SD, u32LPIB, pStream->u32CBL));

    const PHDASTATE pThis = pStream->pHDAState;

    u32LPIB = RT_MIN(u32LPIB, pStream->u32CBL);

    LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
                 pStream->u8SD, u32LPIB, pThis->fDMAPosition));

    /* Update LPIB in any case. */
    HDA_STREAM_REG(pThis, LPIB, pStream->u8SD) = u32LPIB;

    /* Do we need to tell the current DMA position? */
    if (pThis->fDMAPosition)
    {
        int rc2 = PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns),
                                        pThis->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
                                        (void *)&u32LPIB, sizeof(uint32_t));
        AssertRC(rc2);
    }

    return u32LPIB;
}

# ifdef HDA_USE_DMA_ACCESS_HANDLER
/**
 * Registers access handlers for a stream's BDLE DMA accesses.
 *
 * @returns true if registration was successful, false if not.
 * @param   pStream             HDA stream to register BDLE access handlers for.
 */
bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
{
    /* At least LVI and the BDL base must be set. */
    if (   !pStream->u16LVI
        || !pStream->u64BDLBase)
    {
        return false;
    }

    hdaR3StreamUnregisterDMAHandlers(pStream);

    LogFunc(("Registering ...\n"));

    int rc = VINF_SUCCESS;

    /*
     * Create BDLE ranges.
     */

    struct BDLERANGE
    {
        RTGCPHYS uAddr;
        uint32_t uSize;
    } arrRanges[16]; /** @todo Use a define. */

    size_t cRanges = 0;

    for (uint16_t i = 0; i < pStream->u16LVI + 1; i++)
    {
        HDABDLE BDLE;
        rc = hdaR3BDLEFetch(pThis, &BDLE, pStream->u64BDLBase, i /* Index */);
        if (RT_FAILURE(rc))
            break;

        bool fAddRange = true;
        BDLERANGE *pRange;

        if (cRanges)
        {
            pRange = &arrRanges[cRanges - 1];

            /* Is the current range a direct neighbor of the current BLDE? */
            if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
            {
                /* Expand the current range by the current BDLE's size. */
                pRange->uSize += BDLE.Desc.u32BufSize;

                /* Adding a new range in this case is not needed anymore. */
                fAddRange = false;

                LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
            }
        }

        /* Do we need to add a new range? */
        if (   fAddRange
            && cRanges < RT_ELEMENTS(arrRanges))
        {
            pRange = &arrRanges[cRanges];

            pRange->uAddr = BDLE.Desc.u64BufAddr;
            pRange->uSize = BDLE.Desc.u32BufSize;

            LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));

            cRanges++;
        }
    }

    LogFunc(("%zu ranges total\n", cRanges));

    /*
     * Register all ranges as DMA access handlers.
     */

    for (size_t i = 0; i < cRanges; i++)
    {
        BDLERANGE *pRange = &arrRanges[i];

        PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
        if (!pHandler)
        {
            rc = VERR_NO_MEMORY;
            break;
        }

        RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);

        pHandler->pStream = pStream; /* Save a back reference to the owner. */

        char szDesc[32];
        RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);

        int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
                                                   hdaDMAAccessHandler,
                                                   NULL, NULL, NULL,
                                                   NULL, NULL, NULL,
                                                   szDesc, &pHandler->hAccessHandlerType);
        AssertRCBreak(rc2);

        pHandler->BDLEAddr  = pRange->uAddr;
        pHandler->BDLESize  = pRange->uSize;

        /* Get first and last pages of the BDLE range. */
        RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
        RTGCPHYS pgLast  = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);

        /* Calculate the region size (in pages). */
        RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);

        pHandler->GCPhysFirst = pgFirst;
        pHandler->GCPhysLast  = pHandler->GCPhysFirst + (regionSize - 1);

        LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
                 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
        LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
                 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));

        rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
                                         pHandler->GCPhysFirst, pHandler->GCPhysLast,
                                         pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
                                         szDesc);
        AssertRCBreak(rc2);

        pHandler->fRegistered = true;
    }

    LogFunc(("Registration ended with rc=%Rrc\n", rc));

    return RT_SUCCESS(rc);
}

/**
 * Unregisters access handlers of a stream's BDLEs.
 *
 * @param   pStream             HDA stream to unregister BDLE access handlers for.
 */
void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
{
    LogFunc(("\n"));

    PHDADMAACCESSHANDLER pHandler, pHandlerNext;
    RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
    {
        if (!pHandler->fRegistered) /* Handler not registered? Skip. */
            continue;

        LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
                 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));

        int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
                                               pHandler->GCPhysFirst);
        AssertRC(rc2);

        RTListNodeRemove(&pHandler->Node);

        RTMemFree(pHandler);
        pHandler = NULL;
    }

    Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
}
# endif /* HDA_USE_DMA_ACCESS_HANDLER */

# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
/**
 * Asynchronous I/O thread for a HDA stream.
 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
 *
 * @returns IPRT status code.
 * @param   hThreadSelf         Thread handle.
 * @param   pvUser              User argument. Must be of type PHDASTREAMTHREADCTX.
 */
DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
{
    PHDASTREAMTHREADCTX pCtx = (PHDASTREAMTHREADCTX)pvUser;
    AssertPtr(pCtx);

    PHDASTREAM pStream = pCtx->pStream;
    AssertPtr(pStream);

    PHDASTREAMSTATEAIO pAIO = &pCtx->pStream->State.AIO;

    ASMAtomicXchgBool(&pAIO->fStarted, true);

    RTThreadUserSignal(hThreadSelf);

    LogFunc(("[SD%RU8] Started\n", pStream->u8SD));

    for (;;)
    {
        int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
        if (RT_FAILURE(rc2))
            break;

        if (ASMAtomicReadBool(&pAIO->fShutdown))
            break;

        rc2 = RTCritSectEnter(&pAIO->CritSect);
        if (RT_SUCCESS(rc2))
        {
            if (!pAIO->fEnabled)
            {
                RTCritSectLeave(&pAIO->CritSect);
                continue;
            }

            hdaR3StreamUpdate(pStream, false /* fInTimer */);

            int rc3 = RTCritSectLeave(&pAIO->CritSect);
            AssertRC(rc3);
        }

        AssertRC(rc2);
    }

    LogFunc(("[SD%RU8] Ended\n", pStream->u8SD));

    ASMAtomicXchgBool(&pAIO->fStarted, false);

    return VINF_SUCCESS;
}

/**
 * Creates the async I/O thread for a specific HDA audio stream.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA audio stream to create the async I/O thread for.
 */
int hdaR3StreamAsyncIOCreate(PHDASTREAM pStream)
{
    PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;

    int rc;

    if (!ASMAtomicReadBool(&pAIO->fStarted))
    {
        pAIO->fShutdown = false;
        pAIO->fEnabled  = true; /* Enabled by default. */

        rc = RTSemEventCreate(&pAIO->Event);
        if (RT_SUCCESS(rc))
        {
            rc = RTCritSectInit(&pAIO->CritSect);
            if (RT_SUCCESS(rc))
            {
                HDASTREAMTHREADCTX Ctx = { pStream->pHDAState, pStream };

                char szThreadName[64];
                RTStrPrintf2(szThreadName, sizeof(szThreadName), "hdaAIO%RU8", pStream->u8SD);

                rc = RTThreadCreate(&pAIO->Thread, hdaR3StreamAsyncIOThread, &Ctx,
                                    0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
                if (RT_SUCCESS(rc))
                    rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
            }
        }
    }
    else
        rc = VINF_SUCCESS;

    LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
    return rc;
}

/**
 * Destroys the async I/O thread of a specific HDA audio stream.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA audio stream to destroy the async I/O thread for.
 */
int hdaR3StreamAsyncIODestroy(PHDASTREAM pStream)
{
    PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;

    if (!ASMAtomicReadBool(&pAIO->fStarted))
        return VINF_SUCCESS;

    ASMAtomicWriteBool(&pAIO->fShutdown, true);

    int rc = hdaR3StreamAsyncIONotify(pStream);
    AssertRC(rc);

    int rcThread;
    rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
    LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));

    if (RT_SUCCESS(rc))
    {
        rc = RTCritSectDelete(&pAIO->CritSect);
        AssertRC(rc);

        rc = RTSemEventDestroy(pAIO->Event);
        AssertRC(rc);

        pAIO->fStarted  = false;
        pAIO->fShutdown = false;
        pAIO->fEnabled  = false;
    }

    LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
    return rc;
}

/**
 * Lets the stream's async I/O thread know that there is some data to process.
 *
 * @returns IPRT status code.
 * @param   pStream             HDA stream to notify async I/O thread for.
 */
int hdaR3StreamAsyncIONotify(PHDASTREAM pStream)
{
    return RTSemEventSignal(pStream->State.AIO.Event);
}

/**
 * Locks the async I/O thread of a specific HDA audio stream.
 *
 * @param   pStream             HDA stream to lock async I/O thread for.
 */
void hdaR3StreamAsyncIOLock(PHDASTREAM pStream)
{
    PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;

    if (!ASMAtomicReadBool(&pAIO->fStarted))
        return;

    int rc2 = RTCritSectEnter(&pAIO->CritSect);
    AssertRC(rc2);
}

/**
 * Unlocks the async I/O thread of a specific HDA audio stream.
 *
 * @param   pStream             HDA stream to unlock async I/O thread for.
 */
void hdaR3StreamAsyncIOUnlock(PHDASTREAM pStream)
{
    PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;

    if (!ASMAtomicReadBool(&pAIO->fStarted))
        return;

    int rc2 = RTCritSectLeave(&pAIO->CritSect);
    AssertRC(rc2);
}

/**
 * Enables (resumes) or disables (pauses) the async I/O thread.
 *
 * @param   pStream             HDA stream to enable/disable async I/O thread for.
 * @param   fEnable             Whether to enable or disable the I/O thread.
 *
 * @remarks Does not do locking.
 */
void hdaR3StreamAsyncIOEnable(PHDASTREAM pStream, bool fEnable)
{
    PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
    ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
}
# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */

#endif /* IN_RING3 */