1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
|
/* $Id: DevVirtioSCSI.cpp $ */
/** @file
* VBox storage devices - Virtio SCSI Driver
*
* Log-levels used:
* - Level 1: The most important (but usually rare) things to note
* - Level 2: SCSI command logging
* - Level 3: Vector and I/O transfer summary (shows what client sent an expects and fulfillment)
* - Level 6: Device <-> Guest Driver negotation, traffic, notifications and state handling
* - Level 12: Brief formatted hex dumps of I/O data
*/
/*
* Copyright (C) 2006-2023 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>.
*
* SPDX-License-Identifier: GPL-3.0-only
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
//#define LOG_GROUP LOG_GROUP_DRV_SCSI
#define LOG_GROUP LOG_GROUP_DEV_VIRTIO
#include <VBox/vmm/pdmdev.h>
#include <VBox/vmm/pdmstorageifs.h>
#include <VBox/vmm/pdmcritsect.h>
#include <VBox/AssertGuest.h>
#include <VBox/msi.h>
#include <VBox/version.h>
#include <VBox/log.h>
#include <iprt/errcore.h>
#include <iprt/assert.h>
#include <iprt/string.h>
#include <VBox/sup.h>
#include "../build/VBoxDD.h"
#include <VBox/scsi.h>
#ifdef IN_RING3
# include <iprt/alloc.h>
# include <iprt/memcache.h>
# include <iprt/semaphore.h>
# include <iprt/sg.h>
# include <iprt/param.h>
# include <iprt/uuid.h>
#endif
#include "../VirtIO/VirtioCore.h"
#include "VBoxSCSI.h"
#include "VBoxDD.h"
/*********************************************************************************************************************************
* Defined Constants And Macros *
*********************************************************************************************************************************/
/** The current saved state version. */
#define VIRTIOSCSI_SAVED_STATE_VERSION UINT32_C(1)
#define LUN0 0
/** @name VirtIO 1.0 SCSI Host feature bits (See VirtIO 1.0 specification, Section 5.6.3)
* @{ */
#define VIRTIO_SCSI_F_INOUT RT_BIT_64(0) /** Request is device readable AND writeable */
#define VIRTIO_SCSI_F_HOTPLUG RT_BIT_64(1) /** Host allows hotplugging SCSI LUNs & targets */
#define VIRTIO_SCSI_F_CHANGE RT_BIT_64(2) /** Host LUNs chgs via VIRTIOSCSI_T_PARAM_CHANGE evt */
#define VIRTIO_SCSI_F_T10_PI RT_BIT_64(3) /** Add T10 port info (DIF/DIX) in SCSI req hdr */
/** @} */
#define VIRTIOSCSI_HOST_SCSI_FEATURES_ALL \
(VIRTIO_SCSI_F_INOUT | VIRTIO_SCSI_F_HOTPLUG | VIRTIO_SCSI_F_CHANGE | VIRTIO_SCSI_F_T10_PI)
#define VIRTIOSCSI_HOST_SCSI_FEATURES_NONE 0
#define VIRTIOSCSI_HOST_SCSI_FEATURES_OFFERED VIRTIOSCSI_HOST_SCSI_FEATURES_NONE
#define VIRTIOSCSI_REQ_VIRTQ_CNT 4 /**< T.B.D. Consider increasing */
#define VIRTIOSCSI_VIRTQ_CNT (VIRTIOSCSI_REQ_VIRTQ_CNT + 2)
#define VIRTIOSCSI_MAX_TARGETS 256 /**< T.B.D. Figure out a a good value for this. */
#define VIRTIOSCSI_MAX_LUN 1 /**< VirtIO specification, section 5.6.4 */
#define VIRTIOSCSI_MAX_COMMANDS_PER_LUN 128 /**< T.B.D. What is a good value for this? */
#define VIRTIOSCSI_MAX_SEG_COUNT 126 /**< T.B.D. What is a good value for this? */
#define VIRTIOSCSI_MAX_SECTORS_HINT 0x10000 /**< VirtIO specification, section 5.6.4 */
#define VIRTIOSCSI_MAX_CHANNEL_HINT 0 /**< VirtIO specification, section 5.6.4 should be 0 */
#define PCI_DEVICE_ID_VIRTIOSCSI_HOST 0x1048 /**< Informs guest driver of type of VirtIO device */
#define PCI_CLASS_BASE_MASS_STORAGE 0x01 /**< PCI Mass Storage device class */
#define PCI_CLASS_SUB_SCSI_STORAGE_CONTROLLER 0x00 /**< PCI SCSI Controller subclass */
#define PCI_CLASS_PROG_UNSPECIFIED 0x00 /**< Programming interface. N/A. */
#define VIRTIOSCSI_PCI_CLASS 0x01 /**< Base class Mass Storage? */
#define VIRTIOSCSI_SENSE_SIZE_DEFAULT 96 /**< VirtIO 1.0: 96 on reset, guest can change */
#define VIRTIOSCSI_SENSE_SIZE_MAX 4096 /**< Picked out of thin air by bird. */
#define VIRTIOSCSI_CDB_SIZE_DEFAULT 32 /**< VirtIO 1.0: 32 on reset, guest can change */
#define VIRTIOSCSI_CDB_SIZE_MAX 255 /**< Picked out of thin air by bird. */
#define VIRTIOSCSI_PI_BYTES_IN 1 /**< Value TBD (see section 5.6.6.1) */
#define VIRTIOSCSI_PI_BYTES_OUT 1 /**< Value TBD (see section 5.6.6.1) */
#define VIRTIOSCSI_DATA_OUT 512 /**< Value TBD (see section 5.6.6.1) */
/**
* VirtIO SCSI Host Device device-specific queue indicies.
* (Note: # of request queues is determined by virtio_scsi_config.num_queues. VirtIO 1.0, 5.6.4)
*/
#define CONTROLQ_IDX 0 /**< VirtIO Spec-defined Index of control queue */
#define EVENTQ_IDX 1 /**< VirtIO Spec-defined Index of event queue */
#define VIRTQ_REQ_BASE 2 /**< VirtIO Spec-defined base index of req. queues */
#define VIRTQNAME(uVirtqNbr) (pThis->aszVirtqNames[uVirtqNbr]) /**< Macro to get queue name from its index */
#define CBVIRTQNAME(uVirtqNbr) RTStrNLen(VIRTQNAME(uVirtqNbr), sizeof(VIRTQNAME(uVirtqNbr)))
#define IS_REQ_VIRTQ(uVirtqNbr) (uVirtqNbr >= VIRTQ_REQ_BASE && uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT)
#define VIRTIO_IS_IN_DIRECTION(pMediaExTxDirEnumValue) \
((pMediaExTxDirEnumValue) == PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE)
#define VIRTIO_IS_OUT_DIRECTION(pMediaExTxDirEnumValue) \
((pMediaExTxDirEnumValue) == PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE)
#define IS_VIRTQ_EMPTY(pDevIns, pVirtio, uVirtqNbr) \
(virtioCoreVirtqAvailBufCount(pDevIns, pVirtio, uVirtqNbr) == 0)
/*********************************************************************************************************************************
* Structures and Typedefs *
*********************************************************************************************************************************/
/**
* VirtIO SCSI Host Device device-specific configuration (see VirtIO 1.0, section 5.6.4)
* VBox VirtIO core issues callback to this VirtIO device-specific implementation to handle
* MMIO accesses to device-specific configuration parameters.
*/
typedef struct virtio_scsi_config
{
uint32_t uNumVirtqs; /**< num_queues \# of req q's exposed by dev */
uint32_t uSegMax; /**< seg_max Max \# of segs allowed in cmd */
uint32_t uMaxSectors; /**< max_sectors Hint to guest max xfer to use */
uint32_t uCmdPerLun; /**< cmd_per_lun Max \# of link cmd sent per lun */
uint32_t uEventInfoSize; /**< event_info_size Fill max, evtq bufs */
uint32_t uSenseSize; /**< sense_size Max sense data size dev writes */
uint32_t uCdbSize; /**< cdb_size Max CDB size driver writes */
uint16_t uMaxChannel; /**< max_channel Hint to guest driver */
uint16_t uMaxTarget; /**< max_target Hint to guest driver */
uint32_t uMaxLun; /**< max_lun Hint to guest driver */
} VIRTIOSCSI_CONFIG_T, PVIRTIOSCSI_CONFIG_T;
/** @name VirtIO 1.0 SCSI Host Device device specific control types
* @{ */
#define VIRTIOSCSI_T_NO_EVENT 0
#define VIRTIOSCSI_T_TRANSPORT_RESET 1
#define VIRTIOSCSI_T_ASYNC_NOTIFY 2 /**< Asynchronous notification */
#define VIRTIOSCSI_T_PARAM_CHANGE 3
/** @} */
/**
* Device operation: eventq
*/
#define VIRTIOSCSI_T_EVENTS_MISSED UINT32_C(0x80000000)
typedef struct virtio_scsi_event
{
// Device-writable part
uint32_t uEvent; /**< event */
uint8_t abVirtioLun[8]; /**< lun */
uint32_t uReason; /**< reason */
} VIRTIOSCSI_EVENT_T, *PVIRTIOSCSI_EVENT_T;
/** @name VirtIO 1.0 SCSI Host Device device specific event types
* @{ */
#define VIRTIOSCSI_EVT_RESET_HARD 0 /**< */
#define VIRTIOSCSI_EVT_RESET_RESCAN 1 /**< */
#define VIRTIOSCSI_EVT_RESET_REMOVED 2 /**< */
/** @} */
/**
* Device operation: reqestq
*/
#pragma pack(1)
typedef struct REQ_CMD_HDR_T
{
uint8_t abVirtioLun[8]; /**< lun */
uint64_t uId; /**< id */
uint8_t uTaskAttr; /**< task_attr */
uint8_t uPrio; /**< prio */
uint8_t uCrn; /**< crn */
} REQ_CMD_HDR_T;
#pragma pack()
AssertCompileSize(REQ_CMD_HDR_T, 19);
typedef struct REQ_CMD_PI_T
{
uint32_t uPiBytesOut; /**< pi_bytesout */
uint32_t uPiBytesIn; /**< pi_bytesin */
} REQ_CMD_PI_T;
AssertCompileSize(REQ_CMD_PI_T, 8);
typedef struct REQ_RESP_HDR_T
{
uint32_t cbSenseLen; /**< sense_len */
uint32_t uResidual; /**< residual */
uint16_t uStatusQualifier; /**< status_qualifier */
uint8_t uStatus; /**< status SCSI status code */
uint8_t uResponse; /**< response */
} REQ_RESP_HDR_T;
AssertCompileSize(REQ_RESP_HDR_T, 12);
#pragma pack(1)
typedef struct VIRTIOSCSI_REQ_CMD_T
{
/** Device-readable section
* @{ */
REQ_CMD_HDR_T ReqHdr;
uint8_t uCdb[1]; /**< cdb */
REQ_CMD_PI_T piHdr; /**< T10 Pi block integrity (optional feature) */
uint8_t uPiOut[1]; /**< pi_out[] T10 pi block integrity */
uint8_t uDataOut[1]; /**< dataout */
/** @} */
/** @name Device writable section
* @{ */
REQ_RESP_HDR_T respHdr;
uint8_t uSense[1]; /**< sense */
uint8_t uPiIn[1]; /**< pi_in[] T10 Pi block integrity */
uint8_t uDataIn[1]; /**< detain; */
/** @} */
} VIRTIOSCSI_REQ_CMD_T, *PVIRTIOSCSI_REQ_CMD_T;
#pragma pack()
AssertCompileSize(VIRTIOSCSI_REQ_CMD_T, 19+8+12+6);
/** @name VirtIO 1.0 SCSI Host Device Req command-specific response values
* @{ */
#define VIRTIOSCSI_S_OK 0 /**< control, command */
#define VIRTIOSCSI_S_OVERRUN 1 /**< control */
#define VIRTIOSCSI_S_ABORTED 2 /**< control */
#define VIRTIOSCSI_S_BAD_TARGET 3 /**< control, command */
#define VIRTIOSCSI_S_RESET 4 /**< control */
#define VIRTIOSCSI_S_BUSY 5 /**< control, command */
#define VIRTIOSCSI_S_TRANSPORT_FAILURE 6 /**< control, command */
#define VIRTIOSCSI_S_TARGET_FAILURE 7 /**< control, command */
#define VIRTIOSCSI_S_NEXUS_FAILURE 8 /**< control, command */
#define VIRTIOSCSI_S_FAILURE 9 /**< control, command */
#define VIRTIOSCSI_S_INCORRECT_LUN 12 /**< command */
/** @} */
/** @name VirtIO 1.0 SCSI Host Device command-specific task_attr values
* @{ */
#define VIRTIOSCSI_S_SIMPLE 0 /**< */
#define VIRTIOSCSI_S_ORDERED 1 /**< */
#define VIRTIOSCSI_S_HEAD 2 /**< */
#define VIRTIOSCSI_S_ACA 3 /**< */
/** @} */
/**
* VirtIO 1.0 SCSI Host Device Control command before we know type (5.6.6.2)
*/
typedef struct VIRTIOSCSI_CTRL_T
{
uint32_t uType;
} VIRTIOSCSI_CTRL_T, *PVIRTIOSCSI_CTRL_T;
/** @name VirtIO 1.0 SCSI Host Device command-specific TMF values
* @{ */
#define VIRTIOSCSI_T_TMF 0 /**< */
#define VIRTIOSCSI_T_TMF_ABORT_TASK 0 /**< */
#define VIRTIOSCSI_T_TMF_ABORT_TASK_SET 1 /**< */
#define VIRTIOSCSI_T_TMF_CLEAR_ACA 2 /**< */
#define VIRTIOSCSI_T_TMF_CLEAR_TASK_SET 3 /**< */
#define VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET 4 /**< */
#define VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET 5 /**< */
#define VIRTIOSCSI_T_TMF_QUERY_TASK 6 /**< */
#define VIRTIOSCSI_T_TMF_QUERY_TASK_SET 7 /**< */
/** @} */
#pragma pack(1)
typedef struct VIRTIOSCSI_CTRL_TMF_T
{
uint32_t uType; /**< type */
uint32_t uSubtype; /**< subtype */
uint8_t abScsiLun[8]; /**< lun */
uint64_t uId; /**< id */
} VIRTIOSCSI_CTRL_TMF_T, *PVIRTIOSCSI_CTRL_TMF_T;
#pragma pack()
AssertCompileSize(VIRTIOSCSI_CTRL_TMF_T, 24);
/** VirtIO 1.0 section 5.6.6.2, CTRL TMF response is an 8-bit status */
/** @name VirtIO 1.0 SCSI Host Device device specific tmf control response values
* @{ */
#define VIRTIOSCSI_S_FUNCTION_COMPLETE 0 /**< */
#define VIRTIOSCSI_S_FUNCTION_SUCCEEDED 10 /**< */
#define VIRTIOSCSI_S_FUNCTION_REJECTED 11 /**< */
/** @} */
#define VIRTIOSCSI_T_AN_QUERY 1 /**< Asynchronous notification query */
#define VIRTIOSCSI_T_AN_SUBSCRIBE 2 /**< Asynchronous notification subscription */
#pragma pack(1)
typedef struct VIRTIOSCSI_CTRL_AN_T
{
uint32_t uType; /**< type */
uint8_t abScsiLun[8]; /**< lun */
uint32_t fEventsRequested; /**< event_requested */
} VIRTIOSCSI_CTRL_AN_T, *PVIRTIOSCSI_CTRL_AN_T;
#pragma pack()
AssertCompileSize(VIRTIOSCSI_CTRL_AN_T, 16);
/** VirtIO 1.0, Section 5.6.6.2, CTRL AN response is 4-byte evt mask + 8-bit status */
typedef union VIRTIO_SCSI_CTRL_UNION_T
{
VIRTIOSCSI_CTRL_T Type;
VIRTIOSCSI_CTRL_TMF_T Tmf;
VIRTIOSCSI_CTRL_AN_T AsyncNotify;
uint8_t ab[24];
} VIRTIO_SCSI_CTRL_UNION_T, *PVIRTIO_SCSI_CTRL_UNION_T;
AssertCompile(sizeof(VIRTIO_SCSI_CTRL_UNION_T) == 24); /* VIRTIOSCSI_CTRL_T forces 4 byte alignment, the other two are byte packed. */
/** @name VirtIO 1.0 SCSI Host Device device specific tmf control response values
* @{ */
#define VIRTIOSCSI_EVT_ASYNC_OPERATIONAL_CHANGE 2 /**< */
#define VIRTIOSCSI_EVT_ASYNC_POWER_MGMT 4 /**< */
#define VIRTIOSCSI_EVT_ASYNC_EXTERNAL_REQUEST 8 /**< */
#define VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE 16 /**< */
#define VIRTIOSCSI_EVT_ASYNC_MULTI_HOST 32 /**< */
#define VIRTIOSCSI_EVT_ASYNC_DEVICE_BUSY 64 /**< */
/** @} */
#define SUBSCRIBABLE_EVENTS \
( VIRTIOSCSI_EVT_ASYNC_OPERATIONAL_CHANGE \
| VIRTIOSCSI_EVT_ASYNC_POWER_MGMT \
| VIRTIOSCSI_EVT_ASYNC_EXTERNAL_REQUEST \
| VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE \
| VIRTIOSCSI_EVT_ASYNC_MULTI_HOST \
| VIRTIOSCSI_EVT_ASYNC_DEVICE_BUSY )
#define SUPPORTED_EVENTS 0 /* TBD */
/**
* Worker thread context, shared state.
*/
typedef struct VIRTIOSCSIWORKER
{
SUPSEMEVENT hEvtProcess; /**< handle of associated sleep/wake-up semaphore */
bool volatile fSleeping; /**< Flags whether worker thread is sleeping or not */
bool volatile fNotified; /**< Flags whether worker thread notified */
} VIRTIOSCSIWORKER;
/** Pointer to a VirtIO SCSI worker. */
typedef VIRTIOSCSIWORKER *PVIRTIOSCSIWORKER;
/**
* Worker thread context, ring-3 state.
*/
typedef struct VIRTIOSCSIWORKERR3
{
R3PTRTYPE(PPDMTHREAD) pThread; /**< pointer to worker thread's handle */
uint16_t auRedoDescs[VIRTQ_SIZE];/**< List of previously suspended reqs to re-submit */
uint16_t cRedoDescs; /**< Number of redo desc chain head desc idxes in list */
} VIRTIOSCSIWORKERR3;
/** Pointer to a VirtIO SCSI worker. */
typedef VIRTIOSCSIWORKERR3 *PVIRTIOSCSIWORKERR3;
/**
* State of a target attached to the VirtIO SCSI Host
*/
typedef struct VIRTIOSCSITARGET
{
/** The ring-3 device instance so we can easily get our bearings. */
PPDMDEVINSR3 pDevIns;
/** Pointer to attached driver's base interface. */
R3PTRTYPE(PPDMIBASE) pDrvBase;
/** Target number (PDM LUN) */
uint32_t uTarget;
/** Target Description */
R3PTRTYPE(char *) pszTargetName;
/** Target base interface. */
PDMIBASE IBase;
/** Flag whether device is present. */
bool fPresent;
/** Media port interface. */
PDMIMEDIAPORT IMediaPort;
/** Pointer to the attached driver's media interface. */
R3PTRTYPE(PPDMIMEDIA) pDrvMedia;
/** Extended media port interface. */
PDMIMEDIAEXPORT IMediaExPort;
/** Pointer to the attached driver's extended media interface. */
R3PTRTYPE(PPDMIMEDIAEX) pDrvMediaEx;
/** Status LED interface */
PDMILEDPORTS ILed;
/** The status LED state for this device. */
PDMLED led;
} VIRTIOSCSITARGET, *PVIRTIOSCSITARGET;
/**
* VirtIO Host SCSI device state, shared edition.
*
* @extends VIRTIOCORE
*/
typedef struct VIRTIOSCSI
{
/** The core virtio state. */
VIRTIOCORE Virtio;
/** VirtIO Host SCSI device runtime configuration parameters */
VIRTIOSCSI_CONFIG_T virtioScsiConfig;
bool fBootable;
bool afPadding0[3];
/** Number of targets in paTargetInstances. */
uint32_t cTargets;
/** Per device-bound virtq worker-thread contexts (eventq slot unused) */
VIRTIOSCSIWORKER aWorkers[VIRTIOSCSI_VIRTQ_CNT];
/** Instance name */
char szInstance[16];
/** Device-specific spec-based VirtIO VIRTQNAMEs */
char aszVirtqNames[VIRTIOSCSI_VIRTQ_CNT][VIRTIO_MAX_VIRTQ_NAME_SIZE];
/** Track which VirtIO queues we've attached to */
bool afVirtqAttached[VIRTIOSCSI_VIRTQ_CNT];
/** Set if events missed due to lack of bufs avail on eventq */
bool fEventsMissed;
/** Explicit alignment padding. */
bool afPadding1[2];
/** Mask of VirtIO Async Event types this device will deliver */
uint32_t fAsyncEvtsEnabled;
/** Total number of requests active across all targets */
volatile uint32_t cActiveReqs;
/** True if the guest/driver and VirtIO framework are in the ready state */
uint32_t fVirtioReady;
/** True if VIRTIO_SCSI_F_T10_PI was negotiated */
uint32_t fHasT10pi;
/** True if VIRTIO_SCSI_F_HOTPLUG was negotiated */
uint32_t fHasHotplug;
/** True if VIRTIO_SCSI_F_INOUT was negotiated */
uint32_t fHasInOutBufs;
/** True if VIRTIO_SCSI_F_CHANGE was negotiated */
uint32_t fHasLunChange;
/** True if in the process of resetting */
uint32_t fResetting;
} VIRTIOSCSI;
/** Pointer to the shared state of the VirtIO Host SCSI device. */
typedef VIRTIOSCSI *PVIRTIOSCSI;
/**
* VirtIO Host SCSI device state, ring-3 edition.
*
* @extends VIRTIOCORER3
*/
typedef struct VIRTIOSCSIR3
{
/** The core virtio ring-3 state. */
VIRTIOCORER3 Virtio;
/** Array of per-target data. */
R3PTRTYPE(PVIRTIOSCSITARGET) paTargetInstances;
/** Per device-bound virtq worker-thread contexts (eventq slot unused) */
VIRTIOSCSIWORKERR3 aWorkers[VIRTIOSCSI_VIRTQ_CNT];
/** Device base interface. */
PDMIBASE IBase;
/** Pointer to the device instance.
* @note Only used in interface callbacks. */
PPDMDEVINSR3 pDevIns;
/** Status Target: LEDs port interface. */
PDMILEDPORTS ILeds;
/** IMediaExPort: Media ejection notification */
R3PTRTYPE(PPDMIMEDIANOTIFY) pMediaNotify;
/** Virtq to send tasks to R3. - HC ptr */
R3PTRTYPE(PPDMQUEUE) pNotifierVirtqR3;
/** True if in the process of quiescing I/O */
uint32_t fQuiescing;
/** For which purpose we're quiescing. */
VIRTIOVMSTATECHANGED enmQuiescingFor;
} VIRTIOSCSIR3;
/** Pointer to the ring-3 state of the VirtIO Host SCSI device. */
typedef VIRTIOSCSIR3 *PVIRTIOSCSIR3;
/**
* VirtIO Host SCSI device state, ring-0 edition.
*/
typedef struct VIRTIOSCSIR0
{
/** The core virtio ring-0 state. */
VIRTIOCORER0 Virtio;
} VIRTIOSCSIR0;
/** Pointer to the ring-0 state of the VirtIO Host SCSI device. */
typedef VIRTIOSCSIR0 *PVIRTIOSCSIR0;
/**
* VirtIO Host SCSI device state, raw-mode edition.
*/
typedef struct VIRTIOSCSIRC
{
/** The core virtio raw-mode state. */
VIRTIOCORERC Virtio;
} VIRTIOSCSIRC;
/** Pointer to the ring-0 state of the VirtIO Host SCSI device. */
typedef VIRTIOSCSIRC *PVIRTIOSCSIRC;
/** @typedef VIRTIOSCSICC
* The instance data for the current context. */
typedef CTX_SUFF(VIRTIOSCSI) VIRTIOSCSICC;
/** @typedef PVIRTIOSCSICC
* Pointer to the instance data for the current context. */
typedef CTX_SUFF(PVIRTIOSCSI) PVIRTIOSCSICC;
/**
* Request structure for IMediaEx (Associated Interfaces implemented by DrvSCSI)
* @note cbIn, cbOUt, cbDataOut mostly for debugging
*/
typedef struct VIRTIOSCSIREQ
{
PDMMEDIAEXIOREQ hIoReq; /**< Handle of I/O request */
PVIRTIOSCSITARGET pTarget; /**< Target */
uint16_t uVirtqNbr; /**< Index of queue this request arrived on */
PVIRTQBUF pVirtqBuf; /**< Prepared desc chain pulled from virtq avail ring */
size_t cbDataIn; /**< size of datain buffer */
size_t cbDataOut; /**< size of dataout buffer */
uint16_t uDataInOff; /**< Fixed size of respHdr + sense (precede datain) */
uint16_t uDataOutOff; /**< Fixed size of reqhdr + cdb (precede dataout) */
uint32_t cbSenseAlloc; /**< Size of sense buffer */
size_t cbSenseLen; /**< Receives \# bytes written into sense buffer */
uint8_t *pbSense; /**< Pointer to R3 sense buffer */
PDMMEDIAEXIOREQSCSITXDIR enmTxDir; /**< Receives transfer direction of I/O req */
uint8_t uStatus; /**< SCSI status code */
} VIRTIOSCSIREQ;
typedef VIRTIOSCSIREQ *PVIRTIOSCSIREQ;
/**
* callback_method_impl{VIRTIOCORER0,pfnVirtqNotified}
* @todo this causes burn if I prefix with at-sign. This callback is in VIRTIOCORER0 and VIRTIOCORER3
*/
static DECLCALLBACK(void) virtioScsiNotified(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
{
RT_NOREF(pVirtio);
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
AssertReturnVoid(uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT);
PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
#if defined (IN_RING3) && defined (LOG_ENABLED)
RTLogFlush(NULL);
#endif
if (uVirtqNbr == CONTROLQ_IDX || IS_REQ_VIRTQ(uVirtqNbr))
{
Log6Func(("%s has available data\n", VIRTQNAME(uVirtqNbr)));
/* Wake queue's worker thread up if sleeping */
if (!ASMAtomicXchgBool(&pWorker->fNotified, true))
{
if (ASMAtomicReadBool(&pWorker->fSleeping))
{
Log6Func(("waking %s worker.\n", VIRTQNAME(uVirtqNbr)));
int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pWorker->hEvtProcess);
AssertRC(rc);
}
}
}
else if (uVirtqNbr == EVENTQ_IDX)
{
Log3Func(("Driver queued buffer(s) to %s\n", VIRTQNAME(uVirtqNbr)));
// if (ASMAtomicXchgBool(&pThis->fEventsMissed, false))
// virtioScsiR3ReportEventsMissed(pDevIns, pThis, 0);
}
else
LogFunc(("Unexpected queue idx (ignoring): %d\n", uVirtqNbr));
}
#ifdef IN_RING3 /* spans most of the file, at the moment. */
DECLINLINE(void) virtioScsiSetVirtqNames(PVIRTIOSCSI pThis)
{
RTStrCopy(pThis->aszVirtqNames[CONTROLQ_IDX], VIRTIO_MAX_VIRTQ_NAME_SIZE, "controlq");
RTStrCopy(pThis->aszVirtqNames[EVENTQ_IDX], VIRTIO_MAX_VIRTQ_NAME_SIZE, "eventq");
for (uint16_t uVirtqNbr = VIRTQ_REQ_BASE; uVirtqNbr < VIRTQ_REQ_BASE + VIRTIOSCSI_REQ_VIRTQ_CNT; uVirtqNbr++)
RTStrPrintf(pThis->aszVirtqNames[uVirtqNbr], VIRTIO_MAX_VIRTQ_NAME_SIZE,
"requestq<%d>", uVirtqNbr - VIRTQ_REQ_BASE);
}
#ifdef LOG_ENABLED
DECLINLINE(const char *) virtioGetTxDirText(uint32_t enmTxDir)
{
switch (enmTxDir)
{
case PDMMEDIAEXIOREQSCSITXDIR_UNKNOWN: return "<UNKNOWN>";
case PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE: return "<DEV-TO-GUEST>";
case PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE: return "<GUEST-TO-DEV>";
case PDMMEDIAEXIOREQSCSITXDIR_NONE: return "<NONE>";
default: return "<BAD ENUM>";
}
}
DECLINLINE(const char *) virtioGetTMFTypeText(uint32_t uSubType)
{
switch (uSubType)
{
case VIRTIOSCSI_T_TMF_ABORT_TASK: return "ABORT TASK";
case VIRTIOSCSI_T_TMF_ABORT_TASK_SET: return "ABORT TASK SET";
case VIRTIOSCSI_T_TMF_CLEAR_ACA: return "CLEAR ACA";
case VIRTIOSCSI_T_TMF_CLEAR_TASK_SET: return "CLEAR TASK SET";
case VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET: return "I T NEXUS RESET";
case VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET: return "LOGICAL UNIT RESET";
case VIRTIOSCSI_T_TMF_QUERY_TASK: return "QUERY TASK";
case VIRTIOSCSI_T_TMF_QUERY_TASK_SET: return "QUERY TASK SET";
default: return "<unknown>";
}
}
DECLINLINE(const char *) virtioGetReqRespText(uint32_t vboxRc)
{
switch (vboxRc)
{
case VIRTIOSCSI_S_OK: return "OK/COMPLETE";
case VIRTIOSCSI_S_OVERRUN: return "OVERRRUN";
case VIRTIOSCSI_S_ABORTED: return "ABORTED";
case VIRTIOSCSI_S_BAD_TARGET: return "BAD TARGET";
case VIRTIOSCSI_S_RESET: return "RESET";
case VIRTIOSCSI_S_TRANSPORT_FAILURE: return "TRANSPORT FAILURE";
case VIRTIOSCSI_S_TARGET_FAILURE: return "TARGET FAILURE";
case VIRTIOSCSI_S_NEXUS_FAILURE: return "NEXUS FAILURE";
case VIRTIOSCSI_S_BUSY: return "BUSY";
case VIRTIOSCSI_S_FAILURE: return "FAILURE";
case VIRTIOSCSI_S_INCORRECT_LUN: return "INCORRECT LUN";
case VIRTIOSCSI_S_FUNCTION_SUCCEEDED: return "FUNCTION SUCCEEDED";
case VIRTIOSCSI_S_FUNCTION_REJECTED: return "FUNCTION REJECTED";
default: return "<unknown>";
}
}
DECLINLINE(void) virtioGetControlAsyncMaskText(char *pszOutput, uint32_t cbOutput, uint32_t fAsyncTypesMask)
{
RTStrPrintf(pszOutput, cbOutput, "%s%s%s%s%s%s",
fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_OPERATIONAL_CHANGE ? "CHANGE_OPERATION " : "",
fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_POWER_MGMT ? "POWER_MGMT " : "",
fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_EXTERNAL_REQUEST ? "EXTERNAL_REQ " : "",
fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE ? "MEDIA_CHANGE " : "",
fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_MULTI_HOST ? "MULTI_HOST " : "",
fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_DEVICE_BUSY ? "DEVICE_BUSY " : "");
}
static uint8_t virtioScsiEstimateCdbLen(uint8_t uCmd, uint8_t cbMax)
{
if (uCmd < 0x1f)
return RT_MIN(6, cbMax);
if (uCmd >= 0x20 && uCmd < 0x60)
return RT_MIN(10, cbMax);
if (uCmd >= 0x60 && uCmd < 0x80)
return cbMax;
if (uCmd >= 0x80 && uCmd < 0xa0)
return RT_MIN(16, cbMax);
if (uCmd >= 0xa0 && uCmd < 0xc0)
return RT_MIN(12, cbMax);
return cbMax;
}
#endif /* LOG_ENABLED */
/*
* @todo Figure out how to implement this with R0 changes. Not used by current linux driver
*/
#if 0
static int virtioScsiR3SendEvent(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget, uint32_t uEventType, uint32_t uReason)
{
switch (uEventType)
{
case VIRTIOSCSI_T_NO_EVENT:
Log6Func(("(target=%d, LUN=%d): Warning event info guest queued is shorter than configured\n", uTarget, LUN0));
break;
case VIRTIOSCSI_T_NO_EVENT | VIRTIOSCSI_T_EVENTS_MISSED:
Log6Func(("(target=%d, LUN=%d): Warning driver that events were missed\n", uTarget, LUN0));
break;
case VIRTIOSCSI_T_TRANSPORT_RESET:
switch (uReason)
{
case VIRTIOSCSI_EVT_RESET_REMOVED:
Log6Func(("(target=%d, LUN=%d): Target or LUN removed\n", uTarget, LUN0));
break;
case VIRTIOSCSI_EVT_RESET_RESCAN:
Log6Func(("(target=%d, LUN=%d): Target or LUN added\n", uTarget, LUN0));
break;
case VIRTIOSCSI_EVT_RESET_HARD:
Log6Func(("(target=%d, LUN=%d): Target was reset\n", uTarget, LUN0));
break;
}
break;
case VIRTIOSCSI_T_ASYNC_NOTIFY:
{
#ifdef LOG_ENABLED
char szTypeText[128];
virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), uReason);
Log6Func(("(target=%d, LUN=%d): Delivering subscribed async notification %s\n", uTarget, LUN0, szTypeText));
#endif
break;
}
case VIRTIOSCSI_T_PARAM_CHANGE:
LogFunc(("(target=%d, LUN=%d): PARAM_CHANGE sense code: 0x%x sense qualifier: 0x%x\n",
uTarget, LUN0, uReason & 0xff, (uReason >> 8) & 0xff));
break;
default:
Log6Func(("(target=%d, LUN=%d): Unknown event type: %d, ignoring\n", uTarget, LUN0, uEventType));
return VINF_SUCCESS;
}
PVIRTQBUF pVirtqBuf = NULL;
int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, EVENTQ_IDX, &pVirtqBuf, true);
if (rc == VERR_NOT_AVAILABLE)
{
LogFunc(("eventq is empty, events missed (driver didn't preload queue)!\n"));
ASMAtomicWriteBool(&pThis->fEventsMissed, true);
return VINF_SUCCESS;
}
AssertRCReturn(rc, rc);
VIRTIOSCSI_EVENT_T Event;
Event.uEvent = uEventType;
Event.uReason = uReason;
Event.abVirtioLun[0] = 1;
Event.abVirtioLun[1] = uTarget;
Event.abVirtioLun[2] = (LUN0 >> 8) & 0x40;
Event.abVirtioLun[3] = LUN0 & 0xff;
Event.abVirtioLun[4] = 0;
Event.abVirtioLun[5] = 0;
Event.abVirtioLun[6] = 0;
Event.abVirtioLun[7] = 0;
RTSGSEG aReqSegs[1];
aReqSegs[0].pvSeg = &Event;
aReqSegs[0].cbSeg = sizeof(Event);
RTSGBUF ReqSgBuf;
RTSgBufInit(&ReqSgBuf, aReqSegs, RT_ELEMENTS(aReqSegs));
rc = virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, EVENTQ_IDX, &ReqSgBuf, pVirtqBuf, true /*fFence*/);
if (rc == VINF_SUCCESS)
virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, EVENTQ_IDX, false);
else
LogRel(("Error writing control message to guest\n"));
virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
return rc;
}
#endif
/**
* Releases one reference from the given controller instances active request counter.
*
* @param pDevIns The device instance.
* @param pThis VirtIO SCSI shared instance data.
* @param pThisCC VirtIO SCSI ring-3 instance data.
*/
DECLINLINE(void) virtioScsiR3Release(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC)
{
Assert(pThis->cActiveReqs);
if (!ASMAtomicDecU32(&pThis->cActiveReqs) && pThisCC->fQuiescing)
PDMDevHlpAsyncNotificationCompleted(pDevIns);
}
/**
* Retains one reference for the given controller instances active request counter.
*
* @param pThis VirtIO SCSI shared instance data.
*/
DECLINLINE(void) virtioScsiR3Retain(PVIRTIOSCSI pThis)
{
ASMAtomicIncU32(&pThis->cActiveReqs);
}
/** Internal worker. */
static void virtioScsiR3FreeReq(PVIRTIOSCSITARGET pTarget, PVIRTIOSCSIREQ pReq)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pTarget->pDevIns, PVIRTIOSCSI);
RTMemFree(pReq->pbSense);
pReq->pbSense = NULL;
virtioCoreR3VirtqBufRelease(&pThis->Virtio, pReq->pVirtqBuf);
pReq->pVirtqBuf = NULL;
pTarget->pDrvMediaEx->pfnIoReqFree(pTarget->pDrvMediaEx, pReq->hIoReq);
}
/**
* This is called to complete a request immediately
*
* @param pDevIns The device instance.
* @param pThis VirtIO SCSI shared instance data.
* @param uVirtqNbr Virtq index
* @param pVirtqBuf Pointer to pre-processed descriptor chain pulled from virtq
* @param pRespHdr Response header
* @param pbSense Pointer to sense buffer or NULL if none.
* @param cbSenseCfg The configured sense buffer size.
*
* @returns VINF_SUCCESS
*/
static int virtioScsiR3ReqErr(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uVirtqNbr,
PVIRTQBUF pVirtqBuf, REQ_RESP_HDR_T *pRespHdr, uint8_t *pbSense,
size_t cbSenseCfg)
{
Log2Func((" status: %s response: %s\n",
SCSIStatusText(pRespHdr->uStatus), virtioGetReqRespText(pRespHdr->uResponse)));
RTSGSEG aReqSegs[2];
/* Segment #1: Response header*/
aReqSegs[0].pvSeg = pRespHdr;
aReqSegs[0].cbSeg = sizeof(*pRespHdr);
/* Segment #2: Sense data. */
uint8_t abSenseBuf[VIRTIOSCSI_SENSE_SIZE_MAX];
AssertCompile(VIRTIOSCSI_SENSE_SIZE_MAX <= 4096);
Assert(cbSenseCfg <= sizeof(abSenseBuf));
RT_ZERO(abSenseBuf);
if (pbSense && pRespHdr->cbSenseLen)
memcpy(abSenseBuf, pbSense, RT_MIN(pRespHdr->cbSenseLen, sizeof(abSenseBuf)));
else
pRespHdr->cbSenseLen = 0;
aReqSegs[1].pvSeg = abSenseBuf;
aReqSegs[1].cbSeg = cbSenseCfg;
/* Init S/G buffer. */
RTSGBUF ReqSgBuf;
RTSgBufInit(&ReqSgBuf, aReqSegs, RT_ELEMENTS(aReqSegs));
if (pThis->fResetting)
pRespHdr->uResponse = VIRTIOSCSI_S_RESET;
virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, uVirtqNbr, &ReqSgBuf, pVirtqBuf, true /* fFence */);
virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, uVirtqNbr);
Log2(("---------------------------------------------------------------------------------\n"));
return VINF_SUCCESS;
}
/**
* Variant of virtioScsiR3ReqErr that takes four (4) REQ_RESP_HDR_T member
* fields rather than a pointer to an initialized structure.
*
* @param pDevIns The device instance.
* @param pThis VirtIO SCSI shared instance data.
* @param uVirtqNbr Virtq index
* @param pVirtqBuf Pointer to pre-processed descriptor chain pulled from virtq
* @param cbResidual The number of residual bytes or something like that.
* @param bStatus The SCSI status code.
* @param bResponse The virtio SCSI response code.
* @param pbSense Pointer to sense buffer or NULL if none.
* @param cbSense The number of bytes of sense data. Zero if none.
* @param cbSenseCfg The configured sense buffer size.
*
* @returns VINF_SUCCESS
*/
static int virtioScsiR3ReqErr4(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uVirtqNbr,
PVIRTQBUF pVirtqBuf, size_t cbResidual, uint8_t bStatus, uint8_t bResponse,
uint8_t *pbSense, size_t cbSense, size_t cbSenseCfg)
{
REQ_RESP_HDR_T RespHdr;
RespHdr.cbSenseLen = cbSense & UINT32_MAX;
RespHdr.uResidual = cbResidual & UINT32_MAX;
RespHdr.uStatusQualifier = 0;
RespHdr.uStatus = bStatus;
RespHdr.uResponse = bResponse;
return virtioScsiR3ReqErr(pDevIns, pThis, uVirtqNbr, pVirtqBuf, &RespHdr, pbSense, cbSenseCfg);
}
static void virtioScsiR3SenseKeyToVirtioResp(REQ_RESP_HDR_T *respHdr, uint8_t uSenseKey)
{
switch (uSenseKey)
{
case SCSI_SENSE_ABORTED_COMMAND:
respHdr->uResponse = VIRTIOSCSI_S_ABORTED;
break;
case SCSI_SENSE_COPY_ABORTED:
respHdr->uResponse = VIRTIOSCSI_S_ABORTED;
break;
case SCSI_SENSE_UNIT_ATTENTION:
respHdr->uResponse = VIRTIOSCSI_S_TARGET_FAILURE;
break;
case SCSI_SENSE_HARDWARE_ERROR:
respHdr->uResponse = VIRTIOSCSI_S_TARGET_FAILURE;
break;
case SCSI_SENSE_NOT_READY:
/* Not sure what to return for this. See choices at VirtIO 1.0, 5.6.6.1.1 */
respHdr->uResponse = VIRTIOSCSI_S_FAILURE;
/* respHdr->uResponse = VIRTIOSCSI_S_BUSY; */ /* BUSY is VirtIO's 'retryable' response */
break;
default:
respHdr->uResponse = VIRTIOSCSI_S_FAILURE;
break;
}
}
/**
* @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCompleteNotify}
*/
static DECLCALLBACK(int) virtioScsiR3IoReqFinish(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
void *pvIoReqAlloc, int rcReq)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
PPDMDEVINS pDevIns = pTarget->pDevIns;
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
PPDMIMEDIAEX pIMediaEx = pTarget->pDrvMediaEx;
PVIRTIOSCSIREQ pReq = (PVIRTIOSCSIREQ)pvIoReqAlloc;
size_t cbResidual = 0;
int rc = pIMediaEx->pfnIoReqQueryResidual(pIMediaEx, hIoReq, &cbResidual);
AssertRC(rc);
size_t cbXfer = 0;
rc = pIMediaEx->pfnIoReqQueryXferSize(pIMediaEx, hIoReq, &cbXfer);
AssertRC(rc);
/* Masking deals with data type size discrepancies between
* The APIs (virtio and VBox). Windows C-compiler complains otherwise */
Assert(!(cbXfer & 0xffffffff00000000));
uint32_t cbXfer32 = cbXfer & 0xffffffff;
REQ_RESP_HDR_T respHdr = { 0 };
respHdr.cbSenseLen = pReq->pbSense[2] == SCSI_SENSE_NONE ? 0 : (uint32_t)pReq->cbSenseLen;
AssertMsg(!(cbResidual & 0xffffffff00000000),
("WARNING: Residual size larger than sizeof(uint32_t), truncating"));
respHdr.uResidual = (uint32_t)(cbResidual & 0xffffffff);
respHdr.uStatus = pReq->uStatus;
/* VirtIO 1.0 spec 5.6.6.1.1 says device MUST return a VirtIO response byte value.
* Some are returned during the submit phase, and a few are not mapped at all,
* wherein anything that can't map specifically gets mapped to VIRTIOSCSI_S_FAILURE
*/
if (pThis->fResetting)
respHdr.uResponse = VIRTIOSCSI_S_RESET;
else
{
switch (rcReq)
{
case SCSI_STATUS_OK:
{
if (pReq->uStatus != SCSI_STATUS_CHECK_CONDITION)
respHdr.uResponse = VIRTIOSCSI_S_OK;
else
virtioScsiR3SenseKeyToVirtioResp(&respHdr, pReq->pbSense[2]);
break;
}
case SCSI_STATUS_CHECK_CONDITION:
virtioScsiR3SenseKeyToVirtioResp(&respHdr, pReq->pbSense[2]);
break;
default:
respHdr.uResponse = VIRTIOSCSI_S_FAILURE;
break;
}
}
Log2Func(("status: (%d) %s, response: (%d) %s\n", pReq->uStatus, SCSIStatusText(pReq->uStatus),
respHdr.uResponse, virtioGetReqRespText(respHdr.uResponse)));
if (RT_FAILURE(rcReq))
Log2Func(("rcReq: %Rrc\n", rcReq));
if (LogIs3Enabled())
{
LogFunc(("cbDataIn = %u, cbDataOut = %u (cbIn = %u, cbOut = %u)\n",
pReq->cbDataIn, pReq->cbDataOut, pReq->pVirtqBuf->cbPhysReturn, pReq->pVirtqBuf->cbPhysSend));
LogFunc(("xfer = %lu, residual = %u\n", cbXfer, cbResidual));
LogFunc(("xfer direction: %s, sense written = %d, sense size = %d\n",
virtioGetTxDirText(pReq->enmTxDir), respHdr.cbSenseLen, pThis->virtioScsiConfig.uSenseSize));
}
if (respHdr.cbSenseLen && LogIs2Enabled())
{
LogFunc(("Sense: %s\n", SCSISenseText(pReq->pbSense[2])));
LogFunc(("Sense Ext3: %s\n", SCSISenseExtText(pReq->pbSense[12], pReq->pbSense[13])));
}
if ( (VIRTIO_IS_IN_DIRECTION(pReq->enmTxDir) && cbXfer32 > pReq->cbDataIn)
|| (VIRTIO_IS_OUT_DIRECTION(pReq->enmTxDir) && cbXfer32 > pReq->cbDataOut))
{
Log2Func((" * * * * Data overrun, returning sense\n"));
uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
0, SCSI_SENSE_ILLEGAL_REQUEST, 0, 0, 0, 0, 10, 0, 0, 0 };
respHdr.cbSenseLen = sizeof(abSense);
respHdr.uStatus = SCSI_STATUS_CHECK_CONDITION;
respHdr.uResponse = VIRTIOSCSI_S_OVERRUN;
respHdr.uResidual = pReq->cbDataIn & UINT32_MAX;
virtioScsiR3ReqErr(pDevIns, pThis, pReq->uVirtqNbr, pReq->pVirtqBuf, &respHdr, abSense,
RT_MIN(pThis->virtioScsiConfig.uSenseSize, VIRTIOSCSI_SENSE_SIZE_MAX));
}
else
{
Assert(pReq->pbSense != NULL);
/* req datain bytes already in guest phys mem. via virtioScsiIoReqCopyFromBuf() */
RTSGSEG aReqSegs[2];
aReqSegs[0].pvSeg = &respHdr;
aReqSegs[0].cbSeg = sizeof(respHdr);
aReqSegs[1].pvSeg = pReq->pbSense;
aReqSegs[1].cbSeg = pReq->cbSenseAlloc; /* VirtIO 1.0 spec 5.6.4/5.6.6.1 */
RTSGBUF ReqSgBuf;
RTSgBufInit(&ReqSgBuf, aReqSegs, RT_ELEMENTS(aReqSegs));
size_t cbReqSgBuf = RTSgBufCalcTotalLength(&ReqSgBuf);
/** @todo r=bird: Returning here looks a little bogus... */
AssertMsgReturn(cbReqSgBuf <= pReq->pVirtqBuf->cbPhysReturn,
("Guest expected less req data (space needed: %zu, avail: %u)\n",
cbReqSgBuf, pReq->pVirtqBuf->cbPhysReturn),
VERR_BUFFER_OVERFLOW);
virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, pReq->uVirtqNbr, &ReqSgBuf, pReq->pVirtqBuf, true /* fFence TBD */);
virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, pReq->uVirtqNbr);
Log2(("-----------------------------------------------------------------------------------------\n"));
}
virtioScsiR3FreeReq(pTarget, pReq);
virtioScsiR3Release(pDevIns, pThis, pThisCC);
return rc;
}
/**
* @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyFromBuf}
* Copy virtual memory from VSCSI layer to guest physical memory
*/
static DECLCALLBACK(int) virtioScsiR3IoReqCopyFromBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
void *pvIoReqAlloc, uint32_t offDst, PRTSGBUF pSgBuf, size_t cbCopy)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
PPDMDEVINS pDevIns = pTarget->pDevIns;
PVIRTIOSCSIREQ pReq = (PVIRTIOSCSIREQ)pvIoReqAlloc;
RT_NOREF(hIoReq, cbCopy);
if (!pReq->cbDataIn)
return VINF_SUCCESS;
AssertReturn(pReq->pVirtqBuf, VERR_INVALID_PARAMETER);
PVIRTIOSGBUF pSgPhysReturn = pReq->pVirtqBuf->pSgPhysReturn;
virtioCoreGCPhysChainAdvance(pSgPhysReturn, offDst);
size_t cbCopied = 0;
size_t cbRemain = pReq->cbDataIn;
/* Skip past the REQ_RESP_HDR_T and sense code if we're at the start of the buffer. */
if (!pSgPhysReturn->idxSeg && pSgPhysReturn->cbSegLeft == pSgPhysReturn->paSegs[0].cbSeg)
virtioCoreGCPhysChainAdvance(pSgPhysReturn, pReq->uDataInOff);
while (cbRemain)
{
cbCopied = RT_MIN(pSgBuf->cbSegLeft, pSgPhysReturn->cbSegLeft);
Assert(cbCopied > 0);
PDMDevHlpPCIPhysWriteUser(pDevIns, pSgPhysReturn->GCPhysCur, pSgBuf->pvSegCur, cbCopied);
RTSgBufAdvance(pSgBuf, cbCopied);
virtioCoreGCPhysChainAdvance(pSgPhysReturn, cbCopied);
cbRemain -= cbCopied;
}
RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); /* needed? */
Log3Func((".... Copied %lu bytes from %lu byte guest buffer, residual=%lu\n",
cbCopy, pReq->pVirtqBuf->cbPhysReturn, pReq->pVirtqBuf->cbPhysReturn - cbCopy));
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyToBuf}
*
* Copy guest physical memory to VSCSI layer virtual memory
*/
static DECLCALLBACK(int) virtioScsiR3IoReqCopyToBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
void *pvIoReqAlloc, uint32_t offSrc, PRTSGBUF pSgBuf, size_t cbCopy)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
PPDMDEVINS pDevIns = pTarget->pDevIns;
PVIRTIOSCSIREQ pReq = (PVIRTIOSCSIREQ)pvIoReqAlloc;
RT_NOREF(hIoReq, cbCopy);
if (!pReq->cbDataOut)
return VINF_SUCCESS;
PVIRTIOSGBUF pSgPhysSend = pReq->pVirtqBuf->pSgPhysSend;
virtioCoreGCPhysChainAdvance(pSgPhysSend, offSrc);
size_t cbCopied = 0;
size_t cbRemain = pReq->cbDataOut;
while (cbRemain)
{
cbCopied = RT_MIN(pSgBuf->cbSegLeft, pSgPhysSend->cbSegLeft);
Assert(cbCopied > 0);
PDMDevHlpPCIPhysReadUser(pDevIns, pSgPhysSend->GCPhysCur, pSgBuf->pvSegCur, cbCopied);
RTSgBufAdvance(pSgBuf, cbCopied);
virtioCoreGCPhysChainAdvance(pSgPhysSend, cbCopied);
cbRemain -= cbCopied;
}
Log2Func((".... Copied %lu bytes to %lu byte guest buffer, residual=%lu\n",
cbCopy, pReq->pVirtqBuf->cbPhysReturn, pReq->pVirtqBuf->cbPhysReturn - cbCopy));
return VINF_SUCCESS;
}
/**
* Handles request queues for/on a worker thread.
*
* @returns VBox status code (logged by caller).
*/
static int virtioScsiR3ReqSubmit(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC,
uint16_t uVirtqNbr, PVIRTQBUF pVirtqBuf)
{
/*
* Validate configuration values we use here before we start.
*/
uint32_t const cbCdb = pThis->virtioScsiConfig.uCdbSize;
uint32_t const cbSenseCfg = pThis->virtioScsiConfig.uSenseSize;
/** @todo Report these as errors to the guest or does the caller do that? */
ASSERT_GUEST_LOGREL_MSG_RETURN(cbCdb <= VIRTIOSCSI_CDB_SIZE_MAX, ("cbCdb=%#x\n", cbCdb), VERR_OUT_OF_RANGE);
ASSERT_GUEST_LOGREL_MSG_RETURN(cbSenseCfg <= VIRTIOSCSI_SENSE_SIZE_MAX, ("cbSenseCfg=%#x\n", cbSenseCfg), VERR_OUT_OF_RANGE);
/*
* Extract command header and CDB from guest physical memory
* The max size is rather small here (19 + 255 = 274), so put
* it on the stack.
*/
size_t const cbReqHdr = sizeof(REQ_CMD_HDR_T) + cbCdb;
AssertReturn(pVirtqBuf && pVirtqBuf->cbPhysSend >= cbReqHdr, VERR_INVALID_PARAMETER);
AssertCompile(VIRTIOSCSI_CDB_SIZE_MAX < 4096);
union
{
RT_GCC_EXTENSION struct
{
REQ_CMD_HDR_T ReqHdr;
uint8_t abCdb[VIRTIOSCSI_CDB_SIZE_MAX];
} ;
uint8_t ab[sizeof(REQ_CMD_HDR_T) + VIRTIOSCSI_CDB_SIZE_MAX];
uint64_t au64Align[(sizeof(REQ_CMD_HDR_T) + VIRTIOSCSI_CDB_SIZE_MAX) / sizeof(uint64_t)];
} VirtqReq;
RT_ZERO(VirtqReq);
for (size_t offReq = 0; offReq < cbReqHdr; )
{
size_t cbSeg = cbReqHdr - offReq;
RTGCPHYS GCPhys = virtioCoreGCPhysChainGetNextSeg(pVirtqBuf->pSgPhysSend, &cbSeg);
PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhys, &VirtqReq.ab[offReq], cbSeg);
offReq += cbSeg;
}
uint8_t const uType = VirtqReq.ReqHdr.abVirtioLun[0];
uint8_t const uTarget = VirtqReq.ReqHdr.abVirtioLun[1];
uint32_t uScsiLun = RT_MAKE_U16(VirtqReq.ReqHdr.abVirtioLun[3], VirtqReq.ReqHdr.abVirtioLun[2]) & 0x3fff;
bool fBadLUNFormat = false;
if (uType == 0xc1 && uTarget == 0x01)
{
LogRel(("* * * WARNING: REPORT LUNS LU ACCESSED. FEATURE NOT IMPLEMENTED SEE DevVirtioScsi.cpp * * * "));
/* Force rejection. */ /** @todo figure out right way to handle. Note this is a very
* vague and confusing part of the VirtIO spec (which deviates from the SCSI standard).
* I have not been able to determine how to implement this properly. I've checked the
* source code of Guest drivers, and so far none seem to use it. If this message is logged,
* meaning a guest expects this feature, implementing it can be re-visited */
uScsiLun = 0xff;
}
else
if (uType != 1)
fBadLUNFormat = true;
LogFunc(("[%s] (Target: %d LUN: %d) CDB: %.*Rhxs\n",
SCSICmdText(VirtqReq.abCdb[0]), uTarget, uScsiLun,
virtioScsiEstimateCdbLen(VirtqReq.abCdb[0], cbCdb), &VirtqReq.abCdb[0]));
Log3Func(("cmd id: %RX64, attr: %x, prio: %d, crn: %x\n",
VirtqReq.ReqHdr.uId, VirtqReq.ReqHdr.uTaskAttr, VirtqReq.ReqHdr.uPrio, VirtqReq.ReqHdr.uCrn));
/*
* Calculate request offsets and data sizes.
*/
uint32_t const offDataOut = sizeof(REQ_CMD_HDR_T) + cbCdb;
uint32_t const offDataIn = sizeof(REQ_RESP_HDR_T) + cbSenseCfg;
size_t const cbDataOut = pVirtqBuf->cbPhysSend - offDataOut;
/** @todo r=bird: Validate cbPhysReturn properly? I've just RT_MAX'ed it for now. */
size_t const cbDataIn = RT_MAX(pVirtqBuf->cbPhysReturn, offDataIn) - offDataIn;
Assert(offDataOut <= UINT16_MAX);
Assert(offDataIn <= UINT16_MAX);
/*
* Handle submission errors
*/
if (RT_LIKELY(!fBadLUNFormat))
{ /* likely */ }
else
{
Log2Func(("Error submitting request, bad LUN format\n"));
return virtioScsiR3ReqErr4(pDevIns, pThis, uVirtqNbr, pVirtqBuf, cbDataIn + cbDataOut, 0 /*bStatus*/,
VIRTIOSCSI_S_FAILURE, NULL /*pbSense*/, 0 /*cbSense*/, cbSenseCfg);
}
PVIRTIOSCSITARGET const pTarget = &pThisCC->paTargetInstances[uTarget];
if (RT_LIKELY( uTarget < pThis->cTargets
&& pTarget->fPresent
&& pTarget->pDrvMediaEx))
{ /* likely */ }
else
{
Log2Func(("Error submitting request to bad target (%d) or bad LUN (%d)\n", uTarget, uScsiLun));
uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
0, SCSI_SENSE_ILLEGAL_REQUEST,
0, 0, 0, 0, 10, SCSI_ASC_LOGICAL_UNIT_NOT_SUPPORTED, 0, 0 };
return virtioScsiR3ReqErr4(pDevIns, pThis, uVirtqNbr, pVirtqBuf, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
VIRTIOSCSI_S_BAD_TARGET, abSense, sizeof(abSense), cbSenseCfg);
}
if (RT_LIKELY(uScsiLun == 0))
{ /* likely */ }
else
{
Log2Func(("Error submitting request to bad target (%d) or bad LUN (%d)\n", uTarget, uScsiLun));
uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
0, SCSI_SENSE_ILLEGAL_REQUEST,
0, 0, 0, 0, 10, SCSI_ASC_LOGICAL_UNIT_NOT_SUPPORTED, 0, 0 };
return virtioScsiR3ReqErr4(pDevIns, pThis, uVirtqNbr, pVirtqBuf, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
VIRTIOSCSI_S_OK, abSense, sizeof(abSense), cbSenseCfg);
}
if (RT_LIKELY(!pThis->fResetting))
{ /* likely */ }
else
{
Log2Func(("Aborting req submission because reset is in progress\n"));
return virtioScsiR3ReqErr4(pDevIns, pThis, uVirtqNbr, pVirtqBuf, cbDataIn + cbDataOut, SCSI_STATUS_OK,
VIRTIOSCSI_S_RESET, NULL /*pbSense*/, 0 /*cbSense*/, cbSenseCfg);
}
#if 0
if (RT_LIKELY(!cbDataIn || !cbDataOut || pThis->fHasInOutBufs)) /* VirtIO 1.0, 5.6.6.1.1 */
{ /* likely */ }
else
{
Log2Func(("Error submitting request, got datain & dataout bufs w/o INOUT feature negotated\n"));
uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
0, SCSI_SENSE_ILLEGAL_REQUEST, 0, 0, 0, 0, 10, 0, 0, 0 };
return virtioScsiR3ReqErr4(pDevIns, pThis, uVirtqNbr, pVirtqBuf, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
VIRTIOSCSI_S_FAILURE, abSense, sizeof(abSense), cbSenseCfg);
}
#endif
/*
* Have underlying driver allocate a req of size set during initialization of this device.
*/
virtioScsiR3Retain(pThis);
PDMMEDIAEXIOREQ hIoReq = NULL;
PVIRTIOSCSIREQ pReq = NULL;
PPDMIMEDIAEX pIMediaEx = pTarget->pDrvMediaEx;
int rc = pIMediaEx->pfnIoReqAlloc(pIMediaEx, &hIoReq, (void **)&pReq, 0 /* uIoReqId */,
PDMIMEDIAEX_F_SUSPEND_ON_RECOVERABLE_ERR);
if (RT_FAILURE(rc))
{
virtioScsiR3Release(pDevIns, pThis, pThisCC);
return rc;
}
pReq->hIoReq = hIoReq;
pReq->pTarget = pTarget;
pReq->uVirtqNbr = uVirtqNbr;
pReq->cbDataIn = cbDataIn;
pReq->cbDataOut = cbDataOut;
pReq->pVirtqBuf = pVirtqBuf;
virtioCoreR3VirtqBufRetain(pVirtqBuf); /* (For pReq->pVirtqBuf. Released by virtioScsiR3FreeReq.) */
pReq->uDataInOff = offDataIn;
pReq->uDataOutOff = offDataOut;
pReq->cbSenseAlloc = cbSenseCfg;
pReq->pbSense = (uint8_t *)RTMemAllocZ(pReq->cbSenseAlloc);
AssertMsgReturnStmt(pReq->pbSense, ("Out of memory allocating sense buffer"),
virtioScsiR3FreeReq(pTarget, pReq);, VERR_NO_MEMORY);
/* Note: DrvSCSI allocates one virtual memory buffer for input and output phases of the request */
rc = pIMediaEx->pfnIoReqSendScsiCmd(pIMediaEx, pReq->hIoReq, uScsiLun,
&VirtqReq.abCdb[0], cbCdb,
PDMMEDIAEXIOREQSCSITXDIR_UNKNOWN, &pReq->enmTxDir,
RT_MAX(cbDataIn, cbDataOut),
pReq->pbSense, pReq->cbSenseAlloc, &pReq->cbSenseLen,
&pReq->uStatus, RT_MS_30SEC);
if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
{
/*
* Getting here means the request failed in early in the submission to the lower level driver,
* and there will be no callback to the finished/completion function for this request
*/
Assert(RT_FAILURE_NP(rc));
Log2Func(("Request-submission error from lower-level driver\n"));
uint8_t uASC, uASCQ = 0;
switch (rc)
{
case VERR_NO_MEMORY:
uASC = SCSI_ASC_SYSTEM_RESOURCE_FAILURE;
break;
default:
uASC = SCSI_ASC_INTERNAL_TARGET_FAILURE;
break;
}
uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
0, SCSI_SENSE_VENDOR_SPECIFIC,
0, 0, 0, 0, 10, uASC, uASCQ, 0 };
REQ_RESP_HDR_T respHdr = { 0 };
respHdr.cbSenseLen = sizeof(abSense);
respHdr.uStatus = SCSI_STATUS_CHECK_CONDITION;
respHdr.uResponse = VIRTIOSCSI_S_FAILURE;
respHdr.uResidual = (cbDataIn + cbDataOut) & UINT32_MAX;
virtioScsiR3ReqErr(pDevIns, pThis, uVirtqNbr, pVirtqBuf, &respHdr, abSense, cbSenseCfg);
virtioScsiR3FreeReq(pTarget, pReq);
virtioScsiR3Release(pDevIns, pThis, pThisCC);
}
return VINF_SUCCESS;
}
/**
* Handles control transfers for/on a worker thread.
*
* @returns VBox status code (ignored by the caller).
* @param pDevIns The device instance.
* @param pThis VirtIO SCSI shared instance data.
* @param pThisCC VirtIO SCSI ring-3 instance data.
* @param uVirtqNbr CONTROLQ_IDX
* @param pVirtqBuf Descriptor chain to process.
*/
static int virtioScsiR3Ctrl(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC,
uint16_t uVirtqNbr, PVIRTQBUF pVirtqBuf)
{
AssertReturn(pVirtqBuf->cbPhysSend >= RT_MIN(sizeof(VIRTIOSCSI_CTRL_AN_T),
sizeof(VIRTIOSCSI_CTRL_TMF_T)), 0);
/*
* Allocate buffer and read in the control command
*/
VIRTIO_SCSI_CTRL_UNION_T ScsiCtrlUnion;
RT_ZERO(ScsiCtrlUnion);
size_t const cb = RT_MIN(pVirtqBuf->cbPhysSend, sizeof(VIRTIO_SCSI_CTRL_UNION_T));
for (size_t uOffset = 0; uOffset < cb; )
{
size_t cbSeg = cb - uOffset;
RTGCPHYS GCPhys = virtioCoreGCPhysChainGetNextSeg(pVirtqBuf->pSgPhysSend, &cbSeg);
PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhys, &ScsiCtrlUnion.ab[uOffset], cbSeg);
uOffset += cbSeg;
}
AssertReturn( (ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_TMF
&& pVirtqBuf->cbPhysSend >= sizeof(VIRTIOSCSI_CTRL_TMF_T))
|| ( ( ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_AN_QUERY
|| ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_AN_SUBSCRIBE)
&& pVirtqBuf->cbPhysSend >= sizeof(VIRTIOSCSI_CTRL_AN_T)),
0 /** @todo r=bird: what kind of status is '0' here? */);
union
{
uint32_t fSupportedEvents;
} uData;
uint8_t bResponse = VIRTIOSCSI_S_OK;
uint8_t cSegs;
RTSGSEG aReqSegs[2];
switch (ScsiCtrlUnion.Type.uType)
{
case VIRTIOSCSI_T_TMF: /* Task Management Functions */
{
uint8_t uTarget = ScsiCtrlUnion.Tmf.abScsiLun[1];
uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.Tmf.abScsiLun[3], ScsiCtrlUnion.Tmf.abScsiLun[2]) & 0x3fff;
Log2Func(("[%s] (Target: %d LUN: %d) Task Mgt Function: %s\n",
VIRTQNAME(uVirtqNbr), uTarget, uScsiLun, virtioGetTMFTypeText(ScsiCtrlUnion.Tmf.uSubtype)));
if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
bResponse = VIRTIOSCSI_S_BAD_TARGET;
else
if (uScsiLun != 0)
bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
else
switch (ScsiCtrlUnion.Tmf.uSubtype)
{
case VIRTIOSCSI_T_TMF_ABORT_TASK:
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
break;
case VIRTIOSCSI_T_TMF_ABORT_TASK_SET:
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
break;
case VIRTIOSCSI_T_TMF_CLEAR_ACA:
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
break;
case VIRTIOSCSI_T_TMF_CLEAR_TASK_SET:
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
break;
case VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET:
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
break;
case VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET:
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
break;
case VIRTIOSCSI_T_TMF_QUERY_TASK:
bResponse = VIRTIOSCSI_S_FUNCTION_REJECTED;
break;
case VIRTIOSCSI_T_TMF_QUERY_TASK_SET:
bResponse = VIRTIOSCSI_S_FUNCTION_REJECTED;
break;
default:
LogFunc(("Unknown TMF type\n"));
bResponse = VIRTIOSCSI_S_FAILURE;
}
cSegs = 0; /* only bResponse */
break;
}
case VIRTIOSCSI_T_AN_QUERY: /* Guest SCSI driver is querying supported async event notifications */
{
uint8_t uTarget = ScsiCtrlUnion.AsyncNotify.abScsiLun[1];
uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.AsyncNotify.abScsiLun[3],
ScsiCtrlUnion.AsyncNotify.abScsiLun[2]) & 0x3fff;
if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
bResponse = VIRTIOSCSI_S_BAD_TARGET;
else
if (uScsiLun != 0)
bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
else
bResponse = VIRTIOSCSI_S_FUNCTION_COMPLETE;
#ifdef LOG_ENABLED
if (LogIs2Enabled())
{
char szTypeText[128];
virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), ScsiCtrlUnion.AsyncNotify.fEventsRequested);
Log2Func(("[%s] (Target: %d LUN: %d) Async. Notification Query: %s\n",
VIRTQNAME(uVirtqNbr), uTarget, uScsiLun, szTypeText));
}
#endif
uData.fSupportedEvents = SUPPORTED_EVENTS;
aReqSegs[0].pvSeg = &uData.fSupportedEvents;
aReqSegs[0].cbSeg = sizeof(uData.fSupportedEvents);
cSegs = 1;
break;
}
case VIRTIOSCSI_T_AN_SUBSCRIBE: /* Guest SCSI driver is subscribing to async event notification(s) */
{
if (ScsiCtrlUnion.AsyncNotify.fEventsRequested & ~SUBSCRIBABLE_EVENTS)
LogFunc(("Unsupported bits in event subscription event mask: %#x\n",
ScsiCtrlUnion.AsyncNotify.fEventsRequested));
uint8_t uTarget = ScsiCtrlUnion.AsyncNotify.abScsiLun[1];
uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.AsyncNotify.abScsiLun[3],
ScsiCtrlUnion.AsyncNotify.abScsiLun[2]) & 0x3fff;
#ifdef LOG_ENABLED
if (LogIs2Enabled())
{
char szTypeText[128];
virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), ScsiCtrlUnion.AsyncNotify.fEventsRequested);
Log2Func(("[%s] (Target: %d LUN: %d) Async. Notification Subscribe: %s\n",
VIRTQNAME(uVirtqNbr), uTarget, uScsiLun, szTypeText));
}
#endif
if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
bResponse = VIRTIOSCSI_S_BAD_TARGET;
else
if (uScsiLun != 0)
bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
else
{
bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED; /* or VIRTIOSCSI_S_FUNCTION_COMPLETE? */
pThis->fAsyncEvtsEnabled = SUPPORTED_EVENTS & ScsiCtrlUnion.AsyncNotify.fEventsRequested;
}
aReqSegs[0].pvSeg = &pThis->fAsyncEvtsEnabled;
aReqSegs[0].cbSeg = sizeof(pThis->fAsyncEvtsEnabled);
cSegs = 1;
break;
}
default:
{
LogFunc(("Unknown control type extracted from %s: %u\n", VIRTQNAME(uVirtqNbr), ScsiCtrlUnion.Type.uType));
bResponse = VIRTIOSCSI_S_FAILURE;
cSegs = 0; /* only bResponse */
break;
}
}
/* Add the response code: */
aReqSegs[cSegs].pvSeg = &bResponse;
aReqSegs[cSegs].cbSeg = sizeof(bResponse);
cSegs++;
Assert(cSegs <= RT_ELEMENTS(aReqSegs));
LogFunc(("Response code: %s\n", virtioGetReqRespText(bResponse)));
RTSGBUF ReqSgBuf;
RTSgBufInit(&ReqSgBuf, aReqSegs, cSegs);
virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, uVirtqNbr, &ReqSgBuf, pVirtqBuf, true /*fFence*/);
virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, uVirtqNbr);
return VINF_SUCCESS;
}
/**
* @callback_method_impl{FNPDMTHREADWAKEUPDEV}
*/
static DECLCALLBACK(int) virtioScsiR3WorkerWakeUp(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
return PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[(uintptr_t)pThread->pvUser].hEvtProcess);
}
/**
* @callback_method_impl{FNPDMTHREADDEV}
*/
static DECLCALLBACK(int) virtioScsiR3WorkerThread(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
{
uint16_t const uVirtqNbr = (uint16_t)(uintptr_t)pThread->pvUser;
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
return VINF_SUCCESS;
Log6Func(("[Re]starting %s worker\n", VIRTQNAME(uVirtqNbr)));
while (pThread->enmState == PDMTHREADSTATE_RUNNING)
{
if ( !pWorkerR3->cRedoDescs
&& IS_VIRTQ_EMPTY(pDevIns, &pThis->Virtio, uVirtqNbr))
{
/* Atomic interlocks avoid missing alarm while going to sleep & notifier waking the awoken */
ASMAtomicWriteBool(&pWorker->fSleeping, true);
bool fNotificationSent = ASMAtomicXchgBool(&pWorker->fNotified, false);
if (!fNotificationSent)
{
Log6Func(("%s worker sleeping...\n", VIRTQNAME(uVirtqNbr)));
Assert(ASMAtomicReadBool(&pWorker->fSleeping));
int rc = PDMDevHlpSUPSemEventWaitNoResume(pDevIns, pWorker->hEvtProcess, RT_INDEFINITE_WAIT);
AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_INTERRUPTED, ("%Rrc\n", rc), rc);
if (RT_UNLIKELY(pThread->enmState != PDMTHREADSTATE_RUNNING))
{
Log6Func(("%s worker thread not running, exiting\n", VIRTQNAME(uVirtqNbr)));
return VINF_SUCCESS;
}
if (rc == VERR_INTERRUPTED)
{
Log6Func(("%s worker interrupted ... continuing\n", VIRTQNAME(uVirtqNbr)));
continue;
}
Log6Func(("%s worker woken\n", VIRTQNAME(uVirtqNbr)));
ASMAtomicWriteBool(&pWorker->fNotified, false);
}
ASMAtomicWriteBool(&pWorker->fSleeping, false);
}
if (!virtioCoreIsVirtqEnabled(&pThis->Virtio, uVirtqNbr))
{
LogFunc(("%s queue not enabled, worker aborting...\n", VIRTQNAME(uVirtqNbr)));
break;
}
if (!pThis->afVirtqAttached[uVirtqNbr])
{
LogFunc(("%s queue not attached, worker aborting...\n", VIRTQNAME(uVirtqNbr)));
break;
}
if (!pThisCC->fQuiescing)
{
/* Process any reqs that were suspended saved to the redo queue in save exec. */
for (int i = 0; i < pWorkerR3->cRedoDescs; i++)
{
#ifdef VIRTIO_VBUF_ON_STACK
PVIRTQBUF pVirtqBuf = virtioCoreR3VirtqBufAlloc();
if (!pVirtqBuf)
{
LogRel(("Failed to allocate memory for VIRTQBUF\n"));
break; /* No point in trying to allocate memory for other descriptor chains */
}
int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, uVirtqNbr,
pWorkerR3->auRedoDescs[i], pVirtqBuf);
#else /* !VIRTIO_VBUF_ON_STACK */
PVIRTQBUF pVirtqBuf;
int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, uVirtqNbr,
pWorkerR3->auRedoDescs[i], &pVirtqBuf);
#endif /* !VIRTIO_VBUF_ON_STACK */
if (RT_FAILURE(rc))
LogRel(("Error fetching desc chain to redo, %Rrc", rc));
rc = virtioScsiR3ReqSubmit(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf);
if (RT_FAILURE(rc))
LogRel(("Error submitting req packet, resetting %Rrc", rc));
virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
}
pWorkerR3->cRedoDescs = 0;
Log6Func(("fetching next descriptor chain from %s\n", VIRTQNAME(uVirtqNbr)));
#ifdef VIRTIO_VBUF_ON_STACK
PVIRTQBUF pVirtqBuf = virtioCoreR3VirtqBufAlloc();
if (!pVirtqBuf)
LogRel(("Failed to allocate memory for VIRTQBUF\n"));
else
{
int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, uVirtqNbr, pVirtqBuf, true);
#else /* !VIRTIO_VBUF_ON_STACK */
PVIRTQBUF pVirtqBuf = NULL;
int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, uVirtqNbr, &pVirtqBuf, true);
#endif /* !VIRTIO_VBUF_ON_STACK */
if (rc == VERR_NOT_AVAILABLE)
{
Log6Func(("Nothing found in %s\n", VIRTQNAME(uVirtqNbr)));
continue;
}
AssertRC(rc);
if (uVirtqNbr == CONTROLQ_IDX)
virtioScsiR3Ctrl(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf);
else /* request queue index */
{
rc = virtioScsiR3ReqSubmit(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf);
if (RT_FAILURE(rc))
LogRel(("Error submitting req packet, resetting %Rrc", rc));
}
virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
#ifdef VIRTIO_VBUF_ON_STACK
}
#endif /* VIRTIO_VBUF_ON_STACK */
}
}
return VINF_SUCCESS;
}
/*********************************************************************************************************************************
* Sending evnets
*********************************************************************************************************************************/
/*
* @todo Figure out how to implement this with R0 changes. Not used by current linux driver
*/
#if 0
DECLINLINE(void) virtioScsiR3ReportEventsMissed(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
{
virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_NO_EVENT | VIRTIOSCSI_T_EVENTS_MISSED, 0);
}
#endif
#if 0
/* SUBSCRIBABLE EVENT - not sure when to call this or how to detect when media is added or removed
* via the VBox GUI */
DECLINLINE(void) virtioScsiR3ReportMediaChange(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
{
if (pThis->fAsyncEvtsEnabled & VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE)
virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_ASYNC_NOTIFY, VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE);
}
/* ESSENTIAL (NON-SUBSCRIBABLE) EVENT TYPES (most guest virtio-scsi drivers ignore?) */
DECLINLINE(void) virtioScsiR3ReportTransportReset(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
{
virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_HARD);
}
DECLINLINE(void) virtioScsiR3ReportParamChange(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget,
uint32_t uSenseCode, uint32_t uSenseQualifier)
{
uint32_t uReason = uSenseQualifier << 8 | uSenseCode;
virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_PARAM_CHANGE, uReason);
}
DECLINLINE(void) virtioScsiR3ReportTargetRemoved(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
{
if (pThis->fHasHotplug)
virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_REMOVED);
}
DECLINLINE(void) virtioScsiR3ReportTargetAdded(PDMDEVINS pDevInsPVIRTIOSCSI pThis, uint16_t uTarget)
{
if (pThis->fHasHotplug)
virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_RESCAN);
}
#endif
/**
* @callback_method_impl{VIRTIOCORER3,pfnStatusChanged}
*/
static DECLCALLBACK(void) virtioScsiR3StatusChanged(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint32_t fVirtioReady)
{
PVIRTIOSCSI pThis = RT_FROM_MEMBER(pVirtio, VIRTIOSCSI, Virtio);
PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pVirtioCC, VIRTIOSCSICC, Virtio);
pThis->fVirtioReady = fVirtioReady;
if (fVirtioReady)
{
LogFunc(("VirtIO ready\n-----------------------------------------------------------------------------------------\n"));
uint64_t fFeatures = virtioCoreGetNegotiatedFeatures(&pThis->Virtio);
pThis->fHasT10pi = fFeatures & VIRTIO_SCSI_F_T10_PI;
pThis->fHasHotplug = fFeatures & VIRTIO_SCSI_F_HOTPLUG;
pThis->fHasInOutBufs = fFeatures & VIRTIO_SCSI_F_INOUT;
pThis->fHasLunChange = fFeatures & VIRTIO_SCSI_F_CHANGE;
pThis->fResetting = false;
pThisCC->fQuiescing = false;
for (unsigned i = 0; i < VIRTIOSCSI_VIRTQ_CNT; i++)
pThis->afVirtqAttached[i] = true;
}
else
{
LogFunc(("VirtIO is resetting\n"));
for (unsigned i = 0; i < VIRTIOSCSI_VIRTQ_CNT; i++)
pThis->afVirtqAttached[i] = false;
/*
* BIOS may change these values. When the OS comes up, and KVM driver accessed
* through Windows, it assumes they are the default size. So as per the VirtIO 1.0 spec,
* 5.6.4, these device configuration values must be set to default upon device reset.
*/
pThis->virtioScsiConfig.uSenseSize = VIRTIOSCSI_SENSE_SIZE_DEFAULT;
pThis->virtioScsiConfig.uCdbSize = VIRTIOSCSI_CDB_SIZE_DEFAULT;
}
}
/*********************************************************************************************************************************
* LEDs *
*********************************************************************************************************************************/
/**
* @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed, Target level.}
*/
static DECLCALLBACK(int) virtioScsiR3TargetQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, ILed);
if (iLUN == 0)
{
*ppLed = &pTarget->led;
Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
return VINF_SUCCESS;
}
return VERR_PDM_LUN_NOT_FOUND;
}
/**
* @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed, Device level.}
*/
static DECLCALLBACK(int) virtioScsiR3DeviceQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
{
PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIOSCSICC, ILeds);
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVIRTIOSCSI);
if (iLUN < pThis->cTargets)
{
*ppLed = &pThisCC->paTargetInstances[iLUN].led;
Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
return VINF_SUCCESS;
}
return VERR_PDM_LUN_NOT_FOUND;
}
/*********************************************************************************************************************************
* PDMIMEDIAPORT (target) *
*********************************************************************************************************************************/
/**
* @interface_method_impl{PDMIMEDIAPORT,pfnQueryDeviceLocation, Target level.}
*/
static DECLCALLBACK(int) virtioScsiR3QueryDeviceLocation(PPDMIMEDIAPORT pInterface, const char **ppcszController,
uint32_t *piInstance, uint32_t *piLUN)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaPort);
PPDMDEVINS pDevIns = pTarget->pDevIns;
AssertPtrReturn(ppcszController, VERR_INVALID_POINTER);
AssertPtrReturn(piInstance, VERR_INVALID_POINTER);
AssertPtrReturn(piLUN, VERR_INVALID_POINTER);
*ppcszController = pDevIns->pReg->szName;
*piInstance = pDevIns->iInstance;
*piLUN = pTarget->uTarget;
return VINF_SUCCESS;
}
/*********************************************************************************************************************************
* Virtio config. *
*********************************************************************************************************************************/
/**
* Worker for virtioScsiR3DevCapWrite and virtioScsiR3DevCapRead.
*/
static int virtioScsiR3CfgAccessed(PVIRTIOSCSI pThis, uint32_t uOffsetOfAccess, void *pv, uint32_t cb, bool fWrite)
{
AssertReturn(pv && cb <= sizeof(uint32_t), fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00);
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uNumVirtqs, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uNumVirtqs, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uSegMax, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uSegMax, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxSectors, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxSectors, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uCmdPerLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uCmdPerLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uEventInfoSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uEventInfoSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uSenseSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS( uSenseSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uCdbSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS( uCdbSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxChannel, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxChannel, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxTarget, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxTarget, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
else
{
LogFunc(("Bad access by guest to virtio_scsi_config: off=%u (%#x), cb=%u\n", uOffsetOfAccess, uOffsetOfAccess, cb));
return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
}
return VINF_SUCCESS;
}
/**
* @callback_method_impl{VIRTIOCORER3,pfnDevCapRead}
*/
static DECLCALLBACK(int) virtioScsiR3DevCapRead(PPDMDEVINS pDevIns, uint32_t uOffset, void *pv, uint32_t cb)
{
return virtioScsiR3CfgAccessed(PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI), uOffset, pv, cb, false /*fRead*/);
}
/**
* @callback_method_impl{VIRTIOCORER3,pfnDevCapWrite}
*/
static DECLCALLBACK(int) virtioScsiR3DevCapWrite(PPDMDEVINS pDevIns, uint32_t uOffset, const void *pv, uint32_t cb)
{
return virtioScsiR3CfgAccessed(PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI), uOffset, (void *)pv, cb, true /*fWrite*/);
}
/*********************************************************************************************************************************
* IBase for device and targets *
*********************************************************************************************************************************/
/**
* @interface_method_impl{PDMIBASE,pfnQueryInterface, Target level.}
*/
static DECLCALLBACK(void *) virtioScsiR3TargetQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pTarget->IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAPORT, &pTarget->IMediaPort);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEXPORT, &pTarget->IMediaExPort);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pTarget->ILed);
return NULL;
}
/**
* @interface_method_impl{PDMIBASE,pfnQueryInterface, Device level.}
*/
static DECLCALLBACK(void *) virtioScsiR3DeviceQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIOSCSICC, IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThisCC->IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThisCC->ILeds);
return NULL;
}
/*********************************************************************************************************************************
* Misc *
*********************************************************************************************************************************/
/**
* @callback_method_impl{FNDBGFHANDLERDEV, virtio-scsi debugger info callback.}
*/
static DECLCALLBACK(void) virtioScsiR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
/* Parse arguments. */
RT_NOREF(pszArgs); //bool fVerbose = pszArgs && strstr(pszArgs, "verbose") != NULL;
/* Show basic information. */
pHlp->pfnPrintf(pHlp, "%s#%d: virtio-scsci ",
pDevIns->pReg->szName,
pDevIns->iInstance);
pHlp->pfnPrintf(pHlp, "numTargets=%lu", pThis->cTargets);
}
/*********************************************************************************************************************************
* Saved state *
*********************************************************************************************************************************/
/**
* @callback_method_impl{FNSSMDEVLOADEXEC}
*/
static DECLCALLBACK(int) virtioScsiR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
LogFunc(("LOAD EXEC!!\n"));
AssertReturn(uPass == SSM_PASS_FINAL, VERR_SSM_UNEXPECTED_PASS);
AssertLogRelMsgReturn(uVersion == VIRTIOSCSI_SAVED_STATE_VERSION,
("uVersion=%u\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
virtioScsiSetVirtqNames(pThis);
for (int uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
pHlp->pfnSSMGetBool(pSSM, &pThis->afVirtqAttached[uVirtqNbr]);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uNumVirtqs);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uSegMax);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uMaxSectors);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uCmdPerLun);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uEventInfoSize);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uSenseSize);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uCdbSize);
pHlp->pfnSSMGetU16(pSSM, &pThis->virtioScsiConfig.uMaxChannel);
pHlp->pfnSSMGetU16(pSSM, &pThis->virtioScsiConfig.uMaxTarget);
pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uMaxLun);
pHlp->pfnSSMGetU32(pSSM, &pThis->fAsyncEvtsEnabled);
pHlp->pfnSSMGetBool(pSSM, &pThis->fEventsMissed);
pHlp->pfnSSMGetU32(pSSM, &pThis->fVirtioReady);
pHlp->pfnSSMGetU32(pSSM, &pThis->fHasT10pi);
pHlp->pfnSSMGetU32(pSSM, &pThis->fHasHotplug);
pHlp->pfnSSMGetU32(pSSM, &pThis->fHasInOutBufs);
pHlp->pfnSSMGetU32(pSSM, &pThis->fHasLunChange);
pHlp->pfnSSMGetU32(pSSM, &pThis->fResetting);
uint32_t cTargets;
int rc = pHlp->pfnSSMGetU32(pSSM, &cTargets);
AssertRCReturn(rc, rc);
AssertReturn(cTargets == pThis->cTargets,
pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_LOAD_CONFIG_MISMATCH, RT_SRC_POS,
N_("target count has changed: %u saved, %u configured now"),
cTargets, pThis->cTargets));
for (uint16_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
{
uint16_t cReqsRedo;
rc = pHlp->pfnSSMGetU16(pSSM, &cReqsRedo);
AssertRCReturn(rc, rc);
AssertReturn(cReqsRedo < VIRTQ_SIZE,
pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
N_("Bad count of I/O transactions to re-do in saved state (%#x, max %#x - 1)"),
cReqsRedo, VIRTQ_SIZE));
for (uint16_t uVirtqNbr = VIRTQ_REQ_BASE; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
{
PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
pWorkerR3->cRedoDescs = 0;
}
for (int i = 0; i < cReqsRedo; i++)
{
uint16_t uVirtqNbr;
rc = pHlp->pfnSSMGetU16(pSSM, &uVirtqNbr);
AssertRCReturn(rc, rc);
AssertReturn(uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT,
pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
N_("Bad queue index for re-do in saved state (%#x, max %#x)"),
uVirtqNbr, VIRTIOSCSI_VIRTQ_CNT - 1));
uint16_t idxHead;
rc = pHlp->pfnSSMGetU16(pSSM, &idxHead);
AssertRCReturn(rc, rc);
AssertReturn(idxHead < VIRTQ_SIZE,
pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
N_("Bad queue element index for re-do in saved state (%#x, max %#x)"),
idxHead, VIRTQ_SIZE - 1));
PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
pWorkerR3->auRedoDescs[pWorkerR3->cRedoDescs++] = idxHead;
pWorkerR3->cRedoDescs %= VIRTQ_SIZE;
}
}
/*
* Call the virtio core to let it load its state.
*/
rc = virtioCoreR3ModernDeviceLoadExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM,
uVersion, VIRTIOSCSI_SAVED_STATE_VERSION, pThis->virtioScsiConfig.uNumVirtqs);
/*
* Nudge request queue workers
*/
for (int uVirtqNbr = VIRTQ_REQ_BASE; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
{
if (pThis->afVirtqAttached[uVirtqNbr])
{
LogFunc(("Waking %s worker.\n", VIRTQNAME(uVirtqNbr)));
int rc2 = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[uVirtqNbr].hEvtProcess);
AssertRCReturn(rc, rc2);
}
}
return rc;
}
/**
* @callback_method_impl{FNSSMDEVSAVEEXEC}
*/
static DECLCALLBACK(int) virtioScsiR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
LogFunc(("SAVE EXEC!!\n"));
for (int uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
pHlp->pfnSSMPutBool(pSSM, pThis->afVirtqAttached[uVirtqNbr]);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uNumVirtqs);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uSegMax);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uMaxSectors);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uCmdPerLun);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uEventInfoSize);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uSenseSize);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uCdbSize);
pHlp->pfnSSMPutU16(pSSM, pThis->virtioScsiConfig.uMaxChannel);
pHlp->pfnSSMPutU16(pSSM, pThis->virtioScsiConfig.uMaxTarget);
pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uMaxLun);
pHlp->pfnSSMPutU32(pSSM, pThis->fAsyncEvtsEnabled);
pHlp->pfnSSMPutBool(pSSM, pThis->fEventsMissed);
pHlp->pfnSSMPutU32(pSSM, pThis->fVirtioReady);
pHlp->pfnSSMPutU32(pSSM, pThis->fHasT10pi);
pHlp->pfnSSMPutU32(pSSM, pThis->fHasHotplug);
pHlp->pfnSSMPutU32(pSSM, pThis->fHasInOutBufs);
pHlp->pfnSSMPutU32(pSSM, pThis->fHasLunChange);
pHlp->pfnSSMPutU32(pSSM, pThis->fResetting);
AssertMsg(!pThis->cActiveReqs, ("There are still outstanding requests on this device\n"));
pHlp->pfnSSMPutU32(pSSM, pThis->cTargets);
for (uint16_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
{
PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
/* Query all suspended requests and store them in the request queue. */
if (pTarget->pDrvMediaEx)
{
uint32_t cReqsRedo = pTarget->pDrvMediaEx->pfnIoReqGetSuspendedCount(pTarget->pDrvMediaEx);
pHlp->pfnSSMPutU16(pSSM, cReqsRedo);
if (cReqsRedo)
{
PDMMEDIAEXIOREQ hIoReq;
PVIRTIOSCSIREQ pReq;
int rc = pTarget->pDrvMediaEx->pfnIoReqQuerySuspendedStart(pTarget->pDrvMediaEx, &hIoReq,
(void **)&pReq);
AssertRCBreak(rc);
while(--cReqsRedo)
{
pHlp->pfnSSMPutU16(pSSM, pReq->uVirtqNbr);
pHlp->pfnSSMPutU16(pSSM, pReq->pVirtqBuf->uHeadIdx);
rc = pTarget->pDrvMediaEx->pfnIoReqQuerySuspendedNext(pTarget->pDrvMediaEx, hIoReq,
&hIoReq, (void **)&pReq);
AssertRCBreak(rc);
}
}
}
}
/*
* Call the virtio core to let it save its state.
*/
return virtioCoreR3SaveExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM, VIRTIOSCSI_SAVED_STATE_VERSION, VIRTIOSCSI_VIRTQ_CNT);
}
/*********************************************************************************************************************************
* Device interface. *
*********************************************************************************************************************************/
/**
* @interface_method_impl{PDMDEVREGR3,pfnDetach}
*
* One harddisk at one port has been unplugged.
* The VM is suspended at this point.
*/
static DECLCALLBACK(void) virtioScsiR3Detach(PPDMDEVINS pDevIns, unsigned uTarget, uint32_t fFlags)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
AssertReturnVoid(uTarget < pThis->cTargets);
PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
LogFunc((""));
AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
("virtio-scsi: Device does not support hotplugging\n"));
RT_NOREF(fFlags);
/*
* Zero all important members.
*/
pTarget->fPresent = false;
pTarget->pDrvBase = NULL;
pTarget->pDrvMedia = NULL;
pTarget->pDrvMediaEx = NULL;
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnAttach}
*
* This is called when we change block driver.
*/
static DECLCALLBACK(int) virtioScsiR3Attach(PPDMDEVINS pDevIns, unsigned uTarget, uint32_t fFlags)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
AssertReturn(uTarget < pThis->cTargets, VERR_PDM_LUN_NOT_FOUND);
PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
Assert(pTarget->pDevIns == pDevIns);
AssertMsgReturn(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
("virtio-scsi: Device does not support hotplugging\n"),
VERR_INVALID_PARAMETER);
AssertRelease(!pTarget->pDrvBase);
Assert(pTarget->uTarget == uTarget);
/*
* Try attach the SCSI driver and get the interfaces, required as well as optional.
*/
int rc = PDMDevHlpDriverAttach(pDevIns, pTarget->uTarget, &pDevIns->IBase, &pTarget->pDrvBase, pTarget->pszTargetName);
if (RT_SUCCESS(rc))
{
pTarget->fPresent = true;
pTarget->pDrvMedia = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIA);
AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMedia),
("virtio-scsi configuration error: LUN#%d missing basic media interface!\n", uTarget),
VERR_PDM_MISSING_INTERFACE);
/* Get the extended media interface. */
pTarget->pDrvMediaEx = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIAEX);
AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
("virtio-scsi configuration error: LUN#%d missing extended media interface!\n", uTarget),
VERR_PDM_MISSING_INTERFACE);
rc = pTarget->pDrvMediaEx->pfnIoReqAllocSizeSet(pTarget->pDrvMediaEx, sizeof(VIRTIOSCSIREQ));
AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
("virtio-scsi configuration error: LUN#%u: Failed to set I/O request size!\n", uTarget),
rc);
}
else
AssertMsgFailed(("Failed to attach %s. rc=%Rrc\n", pTarget->pszTargetName, rc));
if (RT_FAILURE(rc))
{
pTarget->fPresent = false;
pTarget->pDrvBase = NULL;
pTarget->pDrvMedia = NULL;
pTarget->pDrvMediaEx = NULL;
pThisCC->pMediaNotify = NULL;
}
return rc;
}
/**
* @callback_method_impl{FNPDMDEVASYNCNOTIFY}
*/
static DECLCALLBACK(bool) virtioScsiR3DeviceQuiesced(PPDMDEVINS pDevIns)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
if (ASMAtomicReadU32(&pThis->cActiveReqs))
return false;
LogFunc(("Device I/O activity quiesced: %s\n",
virtioCoreGetStateChangeText(pThisCC->enmQuiescingFor)));
virtioCoreR3VmStateChanged(&pThis->Virtio, pThisCC->enmQuiescingFor);
pThis->fResetting = false;
pThisCC->fQuiescing = false;
return true;
}
/**
* Worker for virtioScsiR3Reset() and virtioScsiR3SuspendOrPowerOff().
*/
static void virtioScsiR3QuiesceDevice(PPDMDEVINS pDevIns, VIRTIOVMSTATECHANGED enmQuiscingFor)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
/* Prevent worker threads from removing/processing elements from virtq's */
pThisCC->fQuiescing = true;
pThisCC->enmQuiescingFor = enmQuiscingFor;
PDMDevHlpSetAsyncNotification(pDevIns, virtioScsiR3DeviceQuiesced);
/* If already quiesced invoke async callback. */
if (!ASMAtomicReadU32(&pThis->cActiveReqs))
PDMDevHlpAsyncNotificationCompleted(pDevIns);
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnReset}
*/
static DECLCALLBACK(void) virtioScsiR3Reset(PPDMDEVINS pDevIns)
{
LogFunc(("\n"));
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
pThis->fResetting = true;
virtioScsiR3QuiesceDevice(pDevIns, kvirtIoVmStateChangedReset);
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnPowerOff}
*/
static DECLCALLBACK(void) virtioScsiR3SuspendOrPowerOff(PPDMDEVINS pDevIns, VIRTIOVMSTATECHANGED enmType)
{
LogFunc(("\n"));
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
/* VM is halted, thus no new I/O being dumped into queues by the guest.
* Workers have been flagged to stop pulling stuff already queued-up by the guest.
* Now tell lower-level to to suspend reqs (for example, DrvVD suspends all reqs
* on its wait queue, and we will get a callback as the state changes to
* suspended (and later, resumed) for each).
*/
for (uint32_t i = 0; i < pThis->cTargets; i++)
{
PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[i];
if (pTarget->pDrvMediaEx)
pTarget->pDrvMediaEx->pfnNotifySuspend(pTarget->pDrvMediaEx);
}
virtioScsiR3QuiesceDevice(pDevIns, enmType);
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnSuspend}
*/
static DECLCALLBACK(void) virtioScsiR3PowerOff(PPDMDEVINS pDevIns)
{
LogFunc(("\n"));
virtioScsiR3SuspendOrPowerOff(pDevIns, kvirtIoVmStateChangedPowerOff);
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnSuspend}
*/
static DECLCALLBACK(void) virtioScsiR3Suspend(PPDMDEVINS pDevIns)
{
LogFunc(("\n"));
virtioScsiR3SuspendOrPowerOff(pDevIns, kvirtIoVmStateChangedSuspend);
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnResume}
*/
static DECLCALLBACK(void) virtioScsiR3Resume(PPDMDEVINS pDevIns)
{
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
LogFunc(("\n"));
pThisCC->fQuiescing = false;
/* Wake worker threads flagged to skip pulling queue entries during quiesce
* to ensure they re-check their queues. Active request queues may already
* be awake due to new reqs coming in.
*/
for (uint16_t uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_REQ_VIRTQ_CNT; uVirtqNbr++)
{
if ( virtioCoreIsVirtqEnabled(&pThis->Virtio, uVirtqNbr)
&& ASMAtomicReadBool(&pThis->aWorkers[uVirtqNbr].fSleeping))
{
Log6Func(("waking %s worker.\n", VIRTQNAME(uVirtqNbr)));
int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[uVirtqNbr].hEvtProcess);
AssertRC(rc);
}
}
/* Ensure guest is working the queues too. */
virtioCoreR3VmStateChanged(&pThis->Virtio, kvirtIoVmStateChangedResume);
}
/**
* @interface_method_impl{PDMIMEDIAEXPORT,pfnMediumEjected}
*/
static DECLCALLBACK(void) virtioScsiR3MediumEjected(PPDMIMEDIAEXPORT pInterface)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
PPDMDEVINS pDevIns = pTarget->pDevIns;
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
#if 0 /* need more info about how to use this event. The VirtIO 1.0 specification
* lists several SCSI related event types but presumes the reader knows
* how to use them without providing references. */
virtioScsiR3ReportMediaChange(pDevIns, pThis, pTarget->uTarget);
#endif
if (pThisCC->pMediaNotify)
{
int rc = PDMDevHlpVMReqCallNoWait(pDevIns, VMCPUID_ANY,
(PFNRT)pThisCC->pMediaNotify->pfnEjected, 2,
pThisCC->pMediaNotify, pTarget->uTarget);
AssertRC(rc);
}
}
/**
* @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqStateChanged}
*/
static DECLCALLBACK(void) virtioScsiR3IoReqStateChanged(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
void *pvIoReqAlloc, PDMMEDIAEXIOREQSTATE enmState)
{
PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
PPDMDEVINS pDevIns = pTarget->pDevIns;
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
RT_NOREF(hIoReq, pvIoReqAlloc);
switch (enmState)
{
case PDMMEDIAEXIOREQSTATE_SUSPENDED:
{
/* Stop considering this request active */
virtioScsiR3Release(pDevIns, pThis, pThisCC);
break;
}
case PDMMEDIAEXIOREQSTATE_ACTIVE:
virtioScsiR3Retain(pThis);
break;
default:
AssertMsgFailed(("Invalid request state given %u\n", enmState));
}
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnDestruct}
*/
static DECLCALLBACK(int) virtioScsiR3Destruct(PPDMDEVINS pDevIns)
{
PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
RTMemFree(pThisCC->paTargetInstances);
pThisCC->paTargetInstances = NULL;
pThisCC->pMediaNotify = NULL;
for (unsigned uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
{
PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
if (pWorker->hEvtProcess != NIL_SUPSEMEVENT)
{
PDMDevHlpSUPSemEventClose(pDevIns, pWorker->hEvtProcess);
pWorker->hEvtProcess = NIL_SUPSEMEVENT;
}
if (pThisCC->aWorkers[uVirtqNbr].pThread)
{
/* Destroy the thread. */
int rcThread;
int rc = PDMDevHlpThreadDestroy(pDevIns, pThisCC->aWorkers[uVirtqNbr].pThread, &rcThread);
if (RT_FAILURE(rc) || RT_FAILURE(rcThread))
AssertMsgFailed(("%s Failed to destroythread rc=%Rrc rcThread=%Rrc\n",
__FUNCTION__, rc, rcThread));
pThisCC->aWorkers[uVirtqNbr].pThread = NULL;
}
}
virtioCoreR3Term(pDevIns, &pThis->Virtio, &pThisCC->Virtio);
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMDEVREGR3,pfnConstruct}
*/
static DECLCALLBACK(int) virtioScsiR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
{
PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
/*
* Quick initialization of the state data, making sure that the destructor always works.
*/
pThisCC->pDevIns = pDevIns;
LogFunc(("PDM device instance: %d\n", iInstance));
RTStrPrintf(pThis->szInstance, sizeof(pThis->szInstance), "VIRTIOSCSI%d", iInstance);
pThisCC->IBase.pfnQueryInterface = virtioScsiR3DeviceQueryInterface;
pThisCC->ILeds.pfnQueryStatusLed = virtioScsiR3DeviceQueryStatusLed;
/*
* Validate and read configuration.
*/
PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "NumTargets|Bootable", "");
int rc = pHlp->pfnCFGMQueryU32Def(pCfg, "NumTargets", &pThis->cTargets, 1);
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi configuration error: failed to read NumTargets as integer"));
if (pThis->cTargets < 1 || pThis->cTargets > VIRTIOSCSI_MAX_TARGETS)
return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
N_("virtio-scsi configuration error: NumTargets=%u is out of range (1..%u)"),
pThis->cTargets, VIRTIOSCSI_MAX_TARGETS);
rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "Bootable", &pThis->fBootable, true);
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi configuration error: failed to read Bootable as boolean"));
LogRel(("%s: Targets=%u Bootable=%RTbool (unimplemented) R0Enabled=%RTbool RCEnabled=%RTbool\n",
pThis->szInstance, pThis->cTargets, pThis->fBootable, pDevIns->fR0Enabled, pDevIns->fRCEnabled));
/*
* Do core virtio initialization.
*/
/* Configure virtio_scsi_config that transacts via VirtIO implementation's Dev. Specific Cap callbacks */
pThis->virtioScsiConfig.uNumVirtqs = VIRTIOSCSI_REQ_VIRTQ_CNT;
pThis->virtioScsiConfig.uSegMax = VIRTIOSCSI_MAX_SEG_COUNT;
pThis->virtioScsiConfig.uMaxSectors = VIRTIOSCSI_MAX_SECTORS_HINT;
pThis->virtioScsiConfig.uCmdPerLun = VIRTIOSCSI_MAX_COMMANDS_PER_LUN;
pThis->virtioScsiConfig.uEventInfoSize = sizeof(VIRTIOSCSI_EVENT_T); /*VirtIO 1.0 Spec says at least this size! */
pThis->virtioScsiConfig.uSenseSize = VIRTIOSCSI_SENSE_SIZE_DEFAULT;
pThis->virtioScsiConfig.uCdbSize = VIRTIOSCSI_CDB_SIZE_DEFAULT;
pThis->virtioScsiConfig.uMaxChannel = VIRTIOSCSI_MAX_CHANNEL_HINT;
pThis->virtioScsiConfig.uMaxTarget = pThis->cTargets;
pThis->virtioScsiConfig.uMaxLun = VIRTIOSCSI_MAX_LUN;
/* Initialize the generic Virtio core: */
pThisCC->Virtio.pfnVirtqNotified = virtioScsiNotified;
pThisCC->Virtio.pfnStatusChanged = virtioScsiR3StatusChanged;
pThisCC->Virtio.pfnDevCapRead = virtioScsiR3DevCapRead;
pThisCC->Virtio.pfnDevCapWrite = virtioScsiR3DevCapWrite;
VIRTIOPCIPARAMS VirtioPciParams;
VirtioPciParams.uDeviceId = PCI_DEVICE_ID_VIRTIOSCSI_HOST;
VirtioPciParams.uClassBase = PCI_CLASS_BASE_MASS_STORAGE;
VirtioPciParams.uClassSub = PCI_CLASS_SUB_SCSI_STORAGE_CONTROLLER;
VirtioPciParams.uClassProg = PCI_CLASS_PROG_UNSPECIFIED;
VirtioPciParams.uSubsystemId = PCI_DEVICE_ID_VIRTIOSCSI_HOST; /* VirtIO 1.0 spec allows PCI Device ID here */
VirtioPciParams.uInterruptLine = 0x00;
VirtioPciParams.uInterruptPin = 0x01;
rc = virtioCoreR3Init(pDevIns, &pThis->Virtio, &pThisCC->Virtio, &VirtioPciParams, pThis->szInstance,
VIRTIOSCSI_HOST_SCSI_FEATURES_OFFERED, 0 /*fOfferLegacy*/,
&pThis->virtioScsiConfig /*pvDevSpecificCap*/, sizeof(pThis->virtioScsiConfig));
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi: failed to initialize VirtIO"));
/*
* Initialize queues.
*/
virtioScsiSetVirtqNames(pThis);
/* Attach the queues and create worker threads for them: */
for (uint16_t uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
{
rc = virtioCoreR3VirtqAttach(&pThis->Virtio, uVirtqNbr, VIRTQNAME(uVirtqNbr));
if (RT_FAILURE(rc))
continue;
if (uVirtqNbr == CONTROLQ_IDX || IS_REQ_VIRTQ(uVirtqNbr))
{
rc = PDMDevHlpThreadCreate(pDevIns, &pThisCC->aWorkers[uVirtqNbr].pThread,
(void *)(uintptr_t)uVirtqNbr, virtioScsiR3WorkerThread,
virtioScsiR3WorkerWakeUp, 0, RTTHREADTYPE_IO, VIRTQNAME(uVirtqNbr));
if (rc != VINF_SUCCESS)
{
LogRel(("Error creating thread for Virtual Virtq %s: %Rrc\n", VIRTQNAME(uVirtqNbr), rc));
return rc;
}
rc = PDMDevHlpSUPSemEventCreate(pDevIns, &pThis->aWorkers[uVirtqNbr].hEvtProcess);
if (RT_FAILURE(rc))
return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
N_("DevVirtioSCSI: Failed to create SUP event semaphore"));
}
pThis->afVirtqAttached[uVirtqNbr] = true;
}
/*
* Initialize per device instances (targets).
*/
Log2Func(("Probing %d targets ...\n", pThis->cTargets));
pThisCC->paTargetInstances = (PVIRTIOSCSITARGET)RTMemAllocZ(sizeof(VIRTIOSCSITARGET) * pThis->cTargets);
if (!pThisCC->paTargetInstances)
return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to allocate memory for target states"));
for (uint32_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
{
PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
if (RTStrAPrintf(&pTarget->pszTargetName, "VSCSI%u", uTarget) < 0)
AssertLogRelFailedReturn(VERR_NO_MEMORY);
/* Initialize static parts of the device. */
pTarget->pDevIns = pDevIns;
pTarget->uTarget = uTarget;
pTarget->IBase.pfnQueryInterface = virtioScsiR3TargetQueryInterface;
/* IMediaPort and IMediaExPort interfaces provide callbacks for VD media and downstream driver access */
pTarget->IMediaPort.pfnQueryDeviceLocation = virtioScsiR3QueryDeviceLocation;
pTarget->IMediaPort.pfnQueryScsiInqStrings = NULL;
pTarget->IMediaExPort.pfnIoReqCompleteNotify = virtioScsiR3IoReqFinish;
pTarget->IMediaExPort.pfnIoReqCopyFromBuf = virtioScsiR3IoReqCopyFromBuf;
pTarget->IMediaExPort.pfnIoReqCopyToBuf = virtioScsiR3IoReqCopyToBuf;
pTarget->IMediaExPort.pfnIoReqStateChanged = virtioScsiR3IoReqStateChanged;
pTarget->IMediaExPort.pfnMediumEjected = virtioScsiR3MediumEjected;
pTarget->IMediaExPort.pfnIoReqQueryBuf = NULL; /* When used avoids copyFromBuf CopyToBuf*/
pTarget->IMediaExPort.pfnIoReqQueryDiscardRanges = NULL;
pTarget->IBase.pfnQueryInterface = virtioScsiR3TargetQueryInterface;
pTarget->ILed.pfnQueryStatusLed = virtioScsiR3TargetQueryStatusLed;
pTarget->led.u32Magic = PDMLED_MAGIC;
LogFunc(("Attaching LUN: %s\n", pTarget->pszTargetName));
AssertReturn(uTarget < pThis->cTargets, VERR_PDM_NO_SUCH_LUN);
rc = PDMDevHlpDriverAttach(pDevIns, uTarget, &pTarget->IBase, &pTarget->pDrvBase, pTarget->pszTargetName);
if (RT_SUCCESS(rc))
{
pTarget->fPresent = true;
pTarget->pDrvMedia = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIA);
AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMedia),
("virtio-scsi configuration error: LUN#%d missing basic media interface!\n", uTarget),
VERR_PDM_MISSING_INTERFACE);
/* Get the extended media interface. */
pTarget->pDrvMediaEx = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIAEX);
AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
("virtio-scsi configuration error: LUN#%d missing extended media interface!\n", uTarget),
VERR_PDM_MISSING_INTERFACE);
rc = pTarget->pDrvMediaEx->pfnIoReqAllocSizeSet(pTarget->pDrvMediaEx, sizeof(VIRTIOSCSIREQ));
AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
("virtio-scsi configuration error: LUN#%u: Failed to set I/O request size!\n", uTarget),
rc);
}
else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
{
pTarget->fPresent = false;
pTarget->pDrvBase = NULL;
Log(("virtio-scsi: no driver attached to device %s\n", pTarget->pszTargetName));
rc = VINF_SUCCESS;
}
else
{
AssertLogRelMsgFailed(("virtio-scsi: Failed to attach %s: %Rrc\n", pTarget->pszTargetName, rc));
return rc;
}
}
/*
* Status driver (optional).
*/
PPDMIBASE pUpBase = NULL;
AssertCompile(PDM_STATUS_LUN >= VIRTIOSCSI_MAX_TARGETS);
rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThisCC->IBase, &pUpBase, "Status Port");
if (RT_FAILURE(rc) && rc != VERR_PDM_NO_ATTACHED_DRIVER)
return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to attach the status LUN"));
if (RT_SUCCESS(rc) && pUpBase)
pThisCC->pMediaNotify = PDMIBASE_QUERY_INTERFACE(pUpBase, PDMIMEDIANOTIFY);
/*
* Register saved state.
*/
rc = PDMDevHlpSSMRegister(pDevIns, VIRTIOSCSI_SAVED_STATE_VERSION, sizeof(*pThis),
virtioScsiR3SaveExec, virtioScsiR3LoadExec);
AssertRCReturn(rc, rc);
/*
* Register the debugger info callback (ignore errors).
*/
char szTmp[128];
RTStrPrintf(szTmp, sizeof(szTmp), "%s%u", pDevIns->pReg->szName, pDevIns->iInstance);
PDMDevHlpDBGFInfoRegister(pDevIns, szTmp, "virtio-scsi info", virtioScsiR3Info);
return rc;
}
#else /* !IN_RING3 */
/**
* @callback_method_impl{PDMDEVREGR0,pfnConstruct}
*/
static DECLCALLBACK(int) virtioScsiRZConstruct(PPDMDEVINS pDevIns)
{
PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
pThisCC->Virtio.pfnVirtqNotified = virtioScsiNotified;
return virtioCoreRZInit(pDevIns, &pThis->Virtio);
}
#endif /* !IN_RING3 */
/**
* The device registration structure.
*/
const PDMDEVREG g_DeviceVirtioSCSI =
{
/* .u32Version = */ PDM_DEVREG_VERSION,
/* .uReserved0 = */ 0,
/* .szName = */ "virtio-scsi",
/* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RZ | PDM_DEVREG_FLAGS_NEW_STYLE
| PDM_DEVREG_FLAGS_FIRST_SUSPEND_NOTIFICATION
| PDM_DEVREG_FLAGS_FIRST_POWEROFF_NOTIFICATION,
/* .fClass = */ PDM_DEVREG_CLASS_STORAGE,
/* .cMaxInstances = */ ~0U,
/* .uSharedVersion = */ 42,
/* .cbInstanceShared = */ sizeof(VIRTIOSCSI),
/* .cbInstanceCC = */ sizeof(VIRTIOSCSICC),
/* .cbInstanceRC = */ sizeof(VIRTIOSCSIRC),
/* .cMaxPciDevices = */ 1,
/* .cMaxMsixVectors = */ VBOX_MSIX_MAX_ENTRIES,
/* .pszDescription = */ "Virtio Host SCSI.\n",
#if defined(IN_RING3)
/* .pszRCMod = */ "VBoxDDRC.rc",
/* .pszR0Mod = */ "VBoxDDR0.r0",
/* .pfnConstruct = */ virtioScsiR3Construct,
/* .pfnDestruct = */ virtioScsiR3Destruct,
/* .pfnRelocate = */ NULL,
/* .pfnMemSetup = */ NULL,
/* .pfnPowerOn = */ NULL,
/* .pfnReset = */ virtioScsiR3Reset,
/* .pfnSuspend = */ virtioScsiR3Suspend,
/* .pfnResume = */ virtioScsiR3Resume,
/* .pfnAttach = */ virtioScsiR3Attach,
/* .pfnDetach = */ virtioScsiR3Detach,
/* .pfnQueryInterface = */ NULL,
/* .pfnInitComplete = */ NULL,
/* .pfnPowerOff = */ virtioScsiR3PowerOff,
/* .pfnSoftReset = */ NULL,
/* .pfnReserved0 = */ NULL,
/* .pfnReserved1 = */ NULL,
/* .pfnReserved2 = */ NULL,
/* .pfnReserved3 = */ NULL,
/* .pfnReserved4 = */ NULL,
/* .pfnReserved5 = */ NULL,
/* .pfnReserved6 = */ NULL,
/* .pfnReserved7 = */ NULL,
#elif defined(IN_RING0)
/* .pfnEarlyConstruct = */ NULL,
/* .pfnConstruct = */ virtioScsiRZConstruct,
/* .pfnDestruct = */ NULL,
/* .pfnFinalDestruct = */ NULL,
/* .pfnRequest = */ NULL,
/* .pfnReserved0 = */ NULL,
/* .pfnReserved1 = */ NULL,
/* .pfnReserved2 = */ NULL,
/* .pfnReserved3 = */ NULL,
/* .pfnReserved4 = */ NULL,
/* .pfnReserved5 = */ NULL,
/* .pfnReserved6 = */ NULL,
/* .pfnReserved7 = */ NULL,
#elif defined(IN_RC)
/* .pfnConstruct = */ virtioScsiRZConstruct,
/* .pfnReserved0 = */ NULL,
/* .pfnReserved1 = */ NULL,
/* .pfnReserved2 = */ NULL,
/* .pfnReserved3 = */ NULL,
/* .pfnReserved4 = */ NULL,
/* .pfnReserved5 = */ NULL,
/* .pfnReserved6 = */ NULL,
/* .pfnReserved7 = */ NULL,
#else
# error "Not in IN_RING3, IN_RING0 or IN_RC!"
#endif
/* .u32VersionEnd = */ PDM_DEVREG_VERSION
};
|