1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
|
/* $Id: VBoxGuest.cpp $ */
/** @file
* VBoxGuest - Guest Additions Driver, Common Code.
*/
/*
* Copyright (C) 2007-2019 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/** @page pg_vbdrv VBoxGuest
*
* VBoxGuest is the device driver for VMMDev.
*
* The device driver is shipped as part of the guest additions. It has roots in
* the host VMM support driver (usually known as VBoxDrv), so fixes in platform
* specific code may apply to both drivers.
*
* The common code lives in VBoxGuest.cpp and is compiled both as C++ and C.
* The VBoxGuest.cpp source file shall not contain platform specific code,
* though it must occationally do a few \#ifdef RT_OS_XXX tests to cater for
* platform differences. Though, in those cases, it is common that more than
* one platform needs special handling.
*
* On most platforms the device driver should create two device nodes, one for
* full (unrestricted) access to the feature set, and one which only provides a
* restrict set of functions. These are generally referred to as 'vboxguest'
* and 'vboxuser' respectively. Currently, this two device approach is only
* implemented on Linux!
*
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DEFAULT
#include "VBoxGuestInternal.h"
#include <VBox/VMMDev.h> /* for VMMDEV_RAM_SIZE */
#include <VBox/err.h>
#include <VBox/log.h>
#include <VBox/HostServices/GuestPropertySvc.h>
#include <iprt/ctype.h>
#include <iprt/mem.h>
#include <iprt/time.h>
#include <iprt/memobj.h>
#include <iprt/asm.h>
#include <iprt/asm-amd64-x86.h>
#include <iprt/string.h>
#include <iprt/process.h>
#include <iprt/assert.h>
#include <iprt/param.h>
#include <iprt/timer.h>
#ifdef VBOX_WITH_HGCM
# include <iprt/thread.h>
#endif
#include "version-generated.h"
#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
# include "revision-generated.h"
#endif
#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
# include <iprt/rand.h>
#endif
/*********************************************************************************************************************************
* Defined Constants And Macros *
*********************************************************************************************************************************/
#define VBOXGUEST_ACQUIRE_STYLE_EVENTS (VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST | VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST)
/*********************************************************************************************************************************
* Internal Functions *
*********************************************************************************************************************************/
#ifdef VBOX_WITH_HGCM
static DECLCALLBACK(int) vgdrvHgcmAsyncWaitCallback(VMMDevHGCMRequestHeader *pHdrNonVolatile, void *pvUser, uint32_t u32User);
#endif
static int vgdrvIoCtl_CancelAllWaitEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession);
static void vgdrvBitUsageTrackerClear(PVBOXGUESTBITUSAGETRACER pTracker);
static uint32_t vgdrvGetAllowedEventMaskForSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession);
static int vgdrvResetEventFilterOnHost(PVBOXGUESTDEVEXT pDevExt, uint32_t fFixedEvents);
static int vgdrvResetMouseStatusOnHost(PVBOXGUESTDEVEXT pDevExt);
static int vgdrvResetCapabilitiesOnHost(PVBOXGUESTDEVEXT pDevExt);
static int vgdrvSetSessionEventFilter(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination);
static int vgdrvSetSessionMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination);
static int vgdrvSetSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNoMask,
uint32_t *pfSessionCaps, uint32_t *pfGlobalCaps, bool fSessionTermination);
static int vgdrvAcquireSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, uint32_t fFlags, bool fSessionTermination);
static int vgdrvDispatchEventsLocked(PVBOXGUESTDEVEXT pDevExt, uint32_t fEvents);
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
static const uint32_t g_cbChangeMemBalloonReq = RT_UOFFSETOF(VMMDevChangeMemBalloon, aPhysPage[VMMDEV_MEMORY_BALLOON_CHUNK_PAGES]);
#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
/**
* Drag in the rest of IRPT since we share it with the
* rest of the kernel modules on Solaris.
*/
PFNRT g_apfnVBoxGuestIPRTDeps[] =
{
/* VirtioNet */
(PFNRT)RTRandBytes,
/* RTSemMutex* */
(PFNRT)RTSemMutexCreate,
(PFNRT)RTSemMutexDestroy,
(PFNRT)RTSemMutexRequest,
(PFNRT)RTSemMutexRequestNoResume,
(PFNRT)RTSemMutexRequestDebug,
(PFNRT)RTSemMutexRequestNoResumeDebug,
(PFNRT)RTSemMutexRelease,
(PFNRT)RTSemMutexIsOwned,
NULL
};
#endif /* RT_OS_DARWIN || RT_OS_SOLARIS */
/**
* Reserves memory in which the VMM can relocate any guest mappings
* that are floating around.
*
* This operation is a little bit tricky since the VMM might not accept
* just any address because of address clashes between the three contexts
* it operates in, so use a small stack to perform this operation.
*
* @returns VBox status code (ignored).
* @param pDevExt The device extension.
*/
static int vgdrvInitFixateGuestMappings(PVBOXGUESTDEVEXT pDevExt)
{
/*
* Query the required space.
*/
VMMDevReqHypervisorInfo *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevReqHypervisorInfo), VMMDevReq_GetHypervisorInfo);
if (RT_FAILURE(rc))
return rc;
pReq->hypervisorStart = 0;
pReq->hypervisorSize = 0;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc)) /* this shouldn't happen! */
{
VbglR0GRFree(&pReq->header);
return rc;
}
/*
* The VMM will report back if there is nothing it wants to map, like for
* instance in VT-x and AMD-V mode.
*/
if (pReq->hypervisorSize == 0)
Log(("vgdrvInitFixateGuestMappings: nothing to do\n"));
else
{
/*
* We have to try several times since the host can be picky
* about certain addresses.
*/
RTR0MEMOBJ hFictive = NIL_RTR0MEMOBJ;
uint32_t cbHypervisor = pReq->hypervisorSize;
RTR0MEMOBJ ahTries[5];
uint32_t iTry;
bool fBitched = false;
Log(("vgdrvInitFixateGuestMappings: cbHypervisor=%#x\n", cbHypervisor));
for (iTry = 0; iTry < RT_ELEMENTS(ahTries); iTry++)
{
/*
* Reserve space, or if that isn't supported, create a object for
* some fictive physical memory and map that in to kernel space.
*
* To make the code a bit uglier, most systems cannot help with
* 4MB alignment, so we have to deal with that in addition to
* having two ways of getting the memory.
*/
uint32_t uAlignment = _4M;
RTR0MEMOBJ hObj;
rc = RTR0MemObjReserveKernel(&hObj, (void *)-1, RT_ALIGN_32(cbHypervisor, _4M), uAlignment);
if (rc == VERR_NOT_SUPPORTED)
{
uAlignment = PAGE_SIZE;
rc = RTR0MemObjReserveKernel(&hObj, (void *)-1, RT_ALIGN_32(cbHypervisor, _4M) + _4M, uAlignment);
}
/*
* If both RTR0MemObjReserveKernel calls above failed because either not supported or
* not implemented at all at the current platform, try to map the memory object into the
* virtual kernel space.
*/
if (rc == VERR_NOT_SUPPORTED)
{
if (hFictive == NIL_RTR0MEMOBJ)
{
rc = RTR0MemObjEnterPhys(&hObj, VBOXGUEST_HYPERVISOR_PHYSICAL_START, cbHypervisor + _4M, RTMEM_CACHE_POLICY_DONT_CARE);
if (RT_FAILURE(rc))
break;
hFictive = hObj;
}
uAlignment = _4M;
rc = RTR0MemObjMapKernel(&hObj, hFictive, (void *)-1, uAlignment, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
if (rc == VERR_NOT_SUPPORTED)
{
uAlignment = PAGE_SIZE;
rc = RTR0MemObjMapKernel(&hObj, hFictive, (void *)-1, uAlignment, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
}
}
if (RT_FAILURE(rc))
{
LogRel(("VBoxGuest: Failed to reserve memory for the hypervisor: rc=%Rrc (cbHypervisor=%#x uAlignment=%#x iTry=%u)\n",
rc, cbHypervisor, uAlignment, iTry));
fBitched = true;
break;
}
/*
* Try set it.
*/
pReq->header.requestType = VMMDevReq_SetHypervisorInfo;
pReq->header.rc = VERR_INTERNAL_ERROR;
pReq->hypervisorSize = cbHypervisor;
pReq->hypervisorStart = (RTGCPTR32)(uintptr_t)RTR0MemObjAddress(hObj);
if ( uAlignment == PAGE_SIZE
&& pReq->hypervisorStart & (_4M - 1))
pReq->hypervisorStart = RT_ALIGN_32(pReq->hypervisorStart, _4M);
AssertMsg(RT_ALIGN_32(pReq->hypervisorStart, _4M) == pReq->hypervisorStart, ("%#x\n", pReq->hypervisorStart));
rc = VbglR0GRPerform(&pReq->header);
if (RT_SUCCESS(rc))
{
pDevExt->hGuestMappings = hFictive != NIL_RTR0MEMOBJ ? hFictive : hObj;
Log(("VBoxGuest: %p LB %#x; uAlignment=%#x iTry=%u hGuestMappings=%p (%s)\n",
RTR0MemObjAddress(pDevExt->hGuestMappings),
RTR0MemObjSize(pDevExt->hGuestMappings),
uAlignment, iTry, pDevExt->hGuestMappings, hFictive != NIL_RTR0PTR ? "fictive" : "reservation"));
break;
}
ahTries[iTry] = hObj;
}
/*
* Cleanup failed attempts.
*/
while (iTry-- > 0)
RTR0MemObjFree(ahTries[iTry], false /* fFreeMappings */);
if ( RT_FAILURE(rc)
&& hFictive != NIL_RTR0PTR)
RTR0MemObjFree(hFictive, false /* fFreeMappings */);
if (RT_FAILURE(rc) && !fBitched)
LogRel(("VBoxGuest: Warning: failed to reserve %#d of memory for guest mappings.\n", cbHypervisor));
}
VbglR0GRFree(&pReq->header);
/*
* We ignore failed attempts for now.
*/
return VINF_SUCCESS;
}
/**
* Undo what vgdrvInitFixateGuestMappings did.
*
* @param pDevExt The device extension.
*/
static void vgdrvTermUnfixGuestMappings(PVBOXGUESTDEVEXT pDevExt)
{
if (pDevExt->hGuestMappings != NIL_RTR0PTR)
{
/*
* Tell the host that we're going to free the memory we reserved for
* it, the free it up. (Leak the memory if anything goes wrong here.)
*/
VMMDevReqHypervisorInfo *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevReqHypervisorInfo), VMMDevReq_SetHypervisorInfo);
if (RT_SUCCESS(rc))
{
pReq->hypervisorStart = 0;
pReq->hypervisorSize = 0;
rc = VbglR0GRPerform(&pReq->header);
VbglR0GRFree(&pReq->header);
}
if (RT_SUCCESS(rc))
{
rc = RTR0MemObjFree(pDevExt->hGuestMappings, true /* fFreeMappings */);
AssertRC(rc);
}
else
LogRel(("vgdrvTermUnfixGuestMappings: Failed to unfix the guest mappings! rc=%Rrc\n", rc));
pDevExt->hGuestMappings = NIL_RTR0MEMOBJ;
}
}
/**
* Report the guest information to the host.
*
* @returns IPRT status code.
* @param enmOSType The OS type to report.
*/
static int vgdrvReportGuestInfo(VBOXOSTYPE enmOSType)
{
/*
* Allocate and fill in the two guest info reports.
*/
VMMDevReportGuestInfo2 *pReqInfo2 = NULL;
VMMDevReportGuestInfo *pReqInfo1 = NULL;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReqInfo2, sizeof (VMMDevReportGuestInfo2), VMMDevReq_ReportGuestInfo2);
Log(("vgdrvReportGuestInfo: VbglR0GRAlloc VMMDevReportGuestInfo2 completed with rc=%Rrc\n", rc));
if (RT_SUCCESS(rc))
{
pReqInfo2->guestInfo.additionsMajor = VBOX_VERSION_MAJOR;
pReqInfo2->guestInfo.additionsMinor = VBOX_VERSION_MINOR;
pReqInfo2->guestInfo.additionsBuild = VBOX_VERSION_BUILD;
pReqInfo2->guestInfo.additionsRevision = VBOX_SVN_REV;
pReqInfo2->guestInfo.additionsFeatures = VBOXGSTINFO2_F_REQUESTOR_INFO;
RTStrCopy(pReqInfo2->guestInfo.szName, sizeof(pReqInfo2->guestInfo.szName), VBOX_VERSION_STRING);
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReqInfo1, sizeof (VMMDevReportGuestInfo), VMMDevReq_ReportGuestInfo);
Log(("vgdrvReportGuestInfo: VbglR0GRAlloc VMMDevReportGuestInfo completed with rc=%Rrc\n", rc));
if (RT_SUCCESS(rc))
{
pReqInfo1->guestInfo.interfaceVersion = VMMDEV_VERSION;
pReqInfo1->guestInfo.osType = enmOSType;
/*
* There are two protocols here:
* 1. Info2 + Info1. Supported by >=3.2.51.
* 2. Info1 and optionally Info2. The old protocol.
*
* We try protocol 1 first. It will fail with VERR_NOT_SUPPORTED
* if not supported by the VMMDev (message ordering requirement).
*/
rc = VbglR0GRPerform(&pReqInfo2->header);
Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo2 completed with rc=%Rrc\n", rc));
if (RT_SUCCESS(rc))
{
rc = VbglR0GRPerform(&pReqInfo1->header);
Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo completed with rc=%Rrc\n", rc));
}
else if ( rc == VERR_NOT_SUPPORTED
|| rc == VERR_NOT_IMPLEMENTED)
{
rc = VbglR0GRPerform(&pReqInfo1->header);
Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo completed with rc=%Rrc\n", rc));
if (RT_SUCCESS(rc))
{
rc = VbglR0GRPerform(&pReqInfo2->header);
Log(("vgdrvReportGuestInfo: VbglR0GRPerform VMMDevReportGuestInfo2 completed with rc=%Rrc\n", rc));
if (rc == VERR_NOT_IMPLEMENTED)
rc = VINF_SUCCESS;
}
}
VbglR0GRFree(&pReqInfo1->header);
}
VbglR0GRFree(&pReqInfo2->header);
}
return rc;
}
/**
* Report the guest driver status to the host.
*
* @returns IPRT status code.
* @param fActive Flag whether the driver is now active or not.
*/
static int vgdrvReportDriverStatus(bool fActive)
{
/*
* Report guest status of the VBox driver to the host.
*/
VMMDevReportGuestStatus *pReq2 = NULL;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq2, sizeof(*pReq2), VMMDevReq_ReportGuestStatus);
Log(("vgdrvReportDriverStatus: VbglR0GRAlloc VMMDevReportGuestStatus completed with rc=%Rrc\n", rc));
if (RT_SUCCESS(rc))
{
pReq2->guestStatus.facility = VBoxGuestFacilityType_VBoxGuestDriver;
pReq2->guestStatus.status = fActive ?
VBoxGuestFacilityStatus_Active
: VBoxGuestFacilityStatus_Inactive;
pReq2->guestStatus.flags = 0;
rc = VbglR0GRPerform(&pReq2->header);
Log(("vgdrvReportDriverStatus: VbglR0GRPerform VMMDevReportGuestStatus completed with fActive=%d, rc=%Rrc\n",
fActive ? 1 : 0, rc));
if (rc == VERR_NOT_IMPLEMENTED) /* Compatibility with older hosts. */
rc = VINF_SUCCESS;
VbglR0GRFree(&pReq2->header);
}
return rc;
}
/** @name Memory Ballooning
* @{
*/
/**
* Inflate the balloon by one chunk represented by an R0 memory object.
*
* The caller owns the balloon mutex.
*
* @returns IPRT status code.
* @param pMemObj Pointer to the R0 memory object.
* @param pReq The pre-allocated request for performing the VMMDev call.
*/
static int vgdrvBalloonInflate(PRTR0MEMOBJ pMemObj, VMMDevChangeMemBalloon *pReq)
{
uint32_t iPage;
int rc;
for (iPage = 0; iPage < VMMDEV_MEMORY_BALLOON_CHUNK_PAGES; iPage++)
{
RTHCPHYS phys = RTR0MemObjGetPagePhysAddr(*pMemObj, iPage);
pReq->aPhysPage[iPage] = phys;
}
pReq->fInflate = true;
pReq->header.size = g_cbChangeMemBalloonReq;
pReq->cPages = VMMDEV_MEMORY_BALLOON_CHUNK_PAGES;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
LogRel(("vgdrvBalloonInflate: VbglR0GRPerform failed. rc=%Rrc\n", rc));
return rc;
}
/**
* Deflate the balloon by one chunk - info the host and free the memory object.
*
* The caller owns the balloon mutex.
*
* @returns IPRT status code.
* @param pMemObj Pointer to the R0 memory object.
* The memory object will be freed afterwards.
* @param pReq The pre-allocated request for performing the VMMDev call.
*/
static int vgdrvBalloonDeflate(PRTR0MEMOBJ pMemObj, VMMDevChangeMemBalloon *pReq)
{
uint32_t iPage;
int rc;
for (iPage = 0; iPage < VMMDEV_MEMORY_BALLOON_CHUNK_PAGES; iPage++)
{
RTHCPHYS phys = RTR0MemObjGetPagePhysAddr(*pMemObj, iPage);
pReq->aPhysPage[iPage] = phys;
}
pReq->fInflate = false;
pReq->header.size = g_cbChangeMemBalloonReq;
pReq->cPages = VMMDEV_MEMORY_BALLOON_CHUNK_PAGES;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
{
LogRel(("vgdrvBalloonDeflate: VbglR0GRPerform failed. rc=%Rrc\n", rc));
return rc;
}
rc = RTR0MemObjFree(*pMemObj, true);
if (RT_FAILURE(rc))
{
LogRel(("vgdrvBalloonDeflate: RTR0MemObjFree(%p,true) -> %Rrc; this is *BAD*!\n", *pMemObj, rc));
return rc;
}
*pMemObj = NIL_RTR0MEMOBJ;
return VINF_SUCCESS;
}
/**
* Inflate/deflate the memory balloon and notify the host.
*
* This is a worker used by vgdrvIoCtl_CheckMemoryBalloon - it takes the mutex.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param cBalloonChunks The new size of the balloon in chunks of 1MB.
* @param pfHandleInR3 Where to return the handle-in-ring3 indicator
* (VINF_SUCCESS if set).
*/
static int vgdrvSetBalloonSizeKernel(PVBOXGUESTDEVEXT pDevExt, uint32_t cBalloonChunks, bool *pfHandleInR3)
{
int rc = VINF_SUCCESS;
if (pDevExt->MemBalloon.fUseKernelAPI)
{
VMMDevChangeMemBalloon *pReq;
uint32_t i;
if (cBalloonChunks > pDevExt->MemBalloon.cMaxChunks)
{
LogRel(("vgdrvSetBalloonSizeKernel: illegal balloon size %u (max=%u)\n",
cBalloonChunks, pDevExt->MemBalloon.cMaxChunks));
return VERR_INVALID_PARAMETER;
}
if (cBalloonChunks == pDevExt->MemBalloon.cMaxChunks)
return VINF_SUCCESS; /* nothing to do */
if ( cBalloonChunks > pDevExt->MemBalloon.cChunks
&& !pDevExt->MemBalloon.paMemObj)
{
pDevExt->MemBalloon.paMemObj = (PRTR0MEMOBJ)RTMemAllocZ(sizeof(RTR0MEMOBJ) * pDevExt->MemBalloon.cMaxChunks);
if (!pDevExt->MemBalloon.paMemObj)
{
LogRel(("vgdrvSetBalloonSizeKernel: no memory for paMemObj!\n"));
return VERR_NO_MEMORY;
}
}
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, g_cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
if (RT_FAILURE(rc))
return rc;
if (cBalloonChunks > pDevExt->MemBalloon.cChunks)
{
/* inflate */
for (i = pDevExt->MemBalloon.cChunks; i < cBalloonChunks; i++)
{
rc = RTR0MemObjAllocPhysNC(&pDevExt->MemBalloon.paMemObj[i],
VMMDEV_MEMORY_BALLOON_CHUNK_SIZE, NIL_RTHCPHYS);
if (RT_FAILURE(rc))
{
if (rc == VERR_NOT_SUPPORTED)
{
/* not supported -- fall back to the R3-allocated memory. */
rc = VINF_SUCCESS;
pDevExt->MemBalloon.fUseKernelAPI = false;
Assert(pDevExt->MemBalloon.cChunks == 0);
Log(("VBoxGuestSetBalloonSizeKernel: PhysNC allocs not supported, falling back to R3 allocs.\n"));
}
/* else if (rc == VERR_NO_MEMORY || rc == VERR_NO_PHYS_MEMORY):
* cannot allocate more memory => don't try further, just stop here */
/* else: XXX what else can fail? VERR_MEMOBJ_INIT_FAILED for instance. just stop. */
break;
}
rc = vgdrvBalloonInflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
if (RT_FAILURE(rc))
{
Log(("vboxGuestSetBalloonSize(inflate): failed, rc=%Rrc!\n", rc));
RTR0MemObjFree(pDevExt->MemBalloon.paMemObj[i], true);
pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
break;
}
pDevExt->MemBalloon.cChunks++;
}
}
else
{
/* deflate */
for (i = pDevExt->MemBalloon.cChunks; i-- > cBalloonChunks;)
{
rc = vgdrvBalloonDeflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
if (RT_FAILURE(rc))
{
Log(("vboxGuestSetBalloonSize(deflate): failed, rc=%Rrc!\n", rc));
break;
}
pDevExt->MemBalloon.cChunks--;
}
}
VbglR0GRFree(&pReq->header);
}
/*
* Set the handle-in-ring3 indicator. When set Ring-3 will have to work
* the balloon changes via the other API.
*/
*pfHandleInR3 = pDevExt->MemBalloon.fUseKernelAPI ? false : true;
return rc;
}
/**
* Inflate/deflate the balloon by one chunk.
*
* Worker for vgdrvIoCtl_ChangeMemoryBalloon - it takes the mutex.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param pvChunk The address of the chunk to add to / remove from the
* balloon. (user space address)
* @param fInflate Inflate if true, deflate if false.
*/
static int vgdrvSetBalloonSizeFromUser(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, RTR3PTR pvChunk, bool fInflate)
{
VMMDevChangeMemBalloon *pReq;
PRTR0MEMOBJ pMemObj = NULL;
int rc = VINF_SUCCESS;
uint32_t i;
RT_NOREF1(pSession);
if (fInflate)
{
if ( pDevExt->MemBalloon.cChunks > pDevExt->MemBalloon.cMaxChunks - 1
|| pDevExt->MemBalloon.cMaxChunks == 0 /* If called without first querying. */)
{
LogRel(("vgdrvSetBalloonSizeFromUser: cannot inflate balloon, already have %u chunks (max=%u)\n",
pDevExt->MemBalloon.cChunks, pDevExt->MemBalloon.cMaxChunks));
return VERR_INVALID_PARAMETER;
}
if (!pDevExt->MemBalloon.paMemObj)
{
pDevExt->MemBalloon.paMemObj = (PRTR0MEMOBJ)RTMemAlloc(sizeof(RTR0MEMOBJ) * pDevExt->MemBalloon.cMaxChunks);
if (!pDevExt->MemBalloon.paMemObj)
{
LogRel(("vgdrvSetBalloonSizeFromUser: no memory for paMemObj!\n"));
return VERR_NO_MEMORY;
}
for (i = 0; i < pDevExt->MemBalloon.cMaxChunks; i++)
pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
}
}
else
{
if (pDevExt->MemBalloon.cChunks == 0)
{
AssertMsgFailed(("vgdrvSetBalloonSizeFromUser: cannot decrease balloon, already at size 0\n"));
return VERR_INVALID_PARAMETER;
}
}
/*
* Enumerate all memory objects and check if the object is already registered.
*/
for (i = 0; i < pDevExt->MemBalloon.cMaxChunks; i++)
{
if ( fInflate
&& !pMemObj
&& pDevExt->MemBalloon.paMemObj[i] == NIL_RTR0MEMOBJ)
pMemObj = &pDevExt->MemBalloon.paMemObj[i]; /* found free object pointer */
if (RTR0MemObjAddressR3(pDevExt->MemBalloon.paMemObj[i]) == pvChunk)
{
if (fInflate)
return VERR_ALREADY_EXISTS; /* don't provide the same memory twice */
pMemObj = &pDevExt->MemBalloon.paMemObj[i];
break;
}
}
if (!pMemObj)
{
if (fInflate)
{
/* no free object pointer found -- should not happen */
return VERR_NO_MEMORY;
}
/* cannot free this memory as it wasn't provided before */
return VERR_NOT_FOUND;
}
/*
* Try inflate / default the balloon as requested.
*/
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, g_cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
if (RT_FAILURE(rc))
return rc;
pReq->header.fRequestor = pSession->fRequestor;
if (fInflate)
{
rc = RTR0MemObjLockUser(pMemObj, pvChunk, VMMDEV_MEMORY_BALLOON_CHUNK_SIZE,
RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
if (RT_SUCCESS(rc))
{
rc = vgdrvBalloonInflate(pMemObj, pReq);
if (RT_SUCCESS(rc))
pDevExt->MemBalloon.cChunks++;
else
{
Log(("vgdrvSetBalloonSizeFromUser(inflate): failed, rc=%Rrc!\n", rc));
RTR0MemObjFree(*pMemObj, true);
*pMemObj = NIL_RTR0MEMOBJ;
}
}
}
else
{
rc = vgdrvBalloonDeflate(pMemObj, pReq);
if (RT_SUCCESS(rc))
pDevExt->MemBalloon.cChunks--;
else
Log(("vgdrvSetBalloonSizeFromUser(deflate): failed, rc=%Rrc!\n", rc));
}
VbglR0GRFree(&pReq->header);
return rc;
}
/**
* Cleanup the memory balloon of a session.
*
* Will request the balloon mutex, so it must be valid and the caller must not
* own it already.
*
* @param pDevExt The device extension.
* @param pSession The session. Can be NULL at unload.
*/
static void vgdrvCloseMemBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
{
RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
if ( pDevExt->MemBalloon.pOwner == pSession
|| pSession == NULL /*unload*/)
{
if (pDevExt->MemBalloon.paMemObj)
{
VMMDevChangeMemBalloon *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, g_cbChangeMemBalloonReq, VMMDevReq_ChangeMemBalloon);
if (RT_SUCCESS(rc))
{
/* fRequestor is kernel here, as we're cleaning up. */
uint32_t i;
for (i = pDevExt->MemBalloon.cChunks; i-- > 0;)
{
rc = vgdrvBalloonDeflate(&pDevExt->MemBalloon.paMemObj[i], pReq);
if (RT_FAILURE(rc))
{
LogRel(("vgdrvCloseMemBalloon: Deflate failed with rc=%Rrc. Will leak %u chunks.\n",
rc, pDevExt->MemBalloon.cChunks));
break;
}
pDevExt->MemBalloon.paMemObj[i] = NIL_RTR0MEMOBJ;
pDevExt->MemBalloon.cChunks--;
}
VbglR0GRFree(&pReq->header);
}
else
LogRel(("vgdrvCloseMemBalloon: Failed to allocate VMMDev request buffer (rc=%Rrc). Will leak %u chunks.\n",
rc, pDevExt->MemBalloon.cChunks));
RTMemFree(pDevExt->MemBalloon.paMemObj);
pDevExt->MemBalloon.paMemObj = NULL;
}
pDevExt->MemBalloon.pOwner = NULL;
}
RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
}
/** @} */
/** @name Heartbeat
* @{
*/
/**
* Sends heartbeat to host.
*
* @returns VBox status code.
*/
static int vgdrvHeartbeatSend(PVBOXGUESTDEVEXT pDevExt)
{
int rc;
if (pDevExt->pReqGuestHeartbeat)
{
rc = VbglR0GRPerform(pDevExt->pReqGuestHeartbeat);
Log3(("vgdrvHeartbeatSend: VbglR0GRPerform vgdrvHeartbeatSend completed with rc=%Rrc\n", rc));
}
else
rc = VERR_INVALID_STATE;
return rc;
}
/**
* Callback for heartbeat timer.
*/
static DECLCALLBACK(void) vgdrvHeartbeatTimerHandler(PRTTIMER hTimer, void *pvUser, uint64_t iTick)
{
PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
int rc;
AssertReturnVoid(pDevExt);
rc = vgdrvHeartbeatSend(pDevExt);
if (RT_FAILURE(rc))
Log(("HB Timer: vgdrvHeartbeatSend failed: rc=%Rrc\n", rc));
NOREF(hTimer); NOREF(iTick);
}
/**
* Configure the host to check guest's heartbeat
* and get heartbeat interval from the host.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param fEnabled Set true to enable guest heartbeat checks on host.
*/
static int vgdrvHeartbeatHostConfigure(PVBOXGUESTDEVEXT pDevExt, bool fEnabled)
{
VMMDevReqHeartbeat *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_HeartbeatConfigure);
Log(("vgdrvHeartbeatHostConfigure: VbglR0GRAlloc vgdrvHeartbeatHostConfigure completed with rc=%Rrc\n", rc));
if (RT_SUCCESS(rc))
{
pReq->fEnabled = fEnabled;
pReq->cNsInterval = 0;
rc = VbglR0GRPerform(&pReq->header);
Log(("vgdrvHeartbeatHostConfigure: VbglR0GRPerform vgdrvHeartbeatHostConfigure completed with rc=%Rrc\n", rc));
pDevExt->cNsHeartbeatInterval = pReq->cNsInterval;
VbglR0GRFree(&pReq->header);
}
return rc;
}
/**
* Initializes the heartbeat timer.
*
* This feature may be disabled by the host.
*
* @returns VBox status (ignored).
* @param pDevExt The device extension.
*/
static int vgdrvHeartbeatInit(PVBOXGUESTDEVEXT pDevExt)
{
/*
* Make sure that heartbeat checking is disabled.
*/
int rc = vgdrvHeartbeatHostConfigure(pDevExt, false);
if (RT_SUCCESS(rc))
{
rc = vgdrvHeartbeatHostConfigure(pDevExt, true);
if (RT_SUCCESS(rc))
{
/*
* Preallocate the request to use it from the timer callback because:
* 1) on Windows VbglR0GRAlloc must be called at IRQL <= APC_LEVEL
* and the timer callback runs at DISPATCH_LEVEL;
* 2) avoid repeated allocations.
*/
rc = VbglR0GRAlloc(&pDevExt->pReqGuestHeartbeat, sizeof(*pDevExt->pReqGuestHeartbeat), VMMDevReq_GuestHeartbeat);
if (RT_SUCCESS(rc))
{
LogRel(("vgdrvHeartbeatInit: Setting up heartbeat to trigger every %RU64 milliseconds\n",
pDevExt->cNsHeartbeatInterval / RT_NS_1MS));
rc = RTTimerCreateEx(&pDevExt->pHeartbeatTimer, pDevExt->cNsHeartbeatInterval, 0 /*fFlags*/,
(PFNRTTIMER)vgdrvHeartbeatTimerHandler, pDevExt);
if (RT_SUCCESS(rc))
{
rc = RTTimerStart(pDevExt->pHeartbeatTimer, 0);
if (RT_SUCCESS(rc))
return VINF_SUCCESS;
LogRel(("vgdrvHeartbeatInit: Heartbeat timer failed to start, rc=%Rrc\n", rc));
}
else
LogRel(("vgdrvHeartbeatInit: Failed to create heartbeat timer: %Rrc\n", rc));
VbglR0GRFree(pDevExt->pReqGuestHeartbeat);
pDevExt->pReqGuestHeartbeat = NULL;
}
else
LogRel(("vgdrvHeartbeatInit: VbglR0GRAlloc(VMMDevReq_GuestHeartbeat): %Rrc\n", rc));
LogRel(("vgdrvHeartbeatInit: Failed to set up the timer, guest heartbeat is disabled\n"));
vgdrvHeartbeatHostConfigure(pDevExt, false);
}
else
LogRel(("vgdrvHeartbeatInit: Failed to configure host for heartbeat checking: rc=%Rrc\n", rc));
}
return rc;
}
/** @} */
/**
* Helper to reinit the VMMDev communication after hibernation.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param enmOSType The OS type.
*
* @todo Call this on all platforms, not just windows.
*/
int VGDrvCommonReinitDevExtAfterHibernation(PVBOXGUESTDEVEXT pDevExt, VBOXOSTYPE enmOSType)
{
int rc = vgdrvReportGuestInfo(enmOSType);
if (RT_SUCCESS(rc))
{
rc = vgdrvReportDriverStatus(true /* Driver is active */);
if (RT_FAILURE(rc))
Log(("VGDrvCommonReinitDevExtAfterHibernation: could not report guest driver status, rc=%Rrc\n", rc));
}
else
Log(("VGDrvCommonReinitDevExtAfterHibernation: could not report guest information to host, rc=%Rrc\n", rc));
LogFlow(("VGDrvCommonReinitDevExtAfterHibernation: returned with rc=%Rrc\n", rc));
RT_NOREF1(pDevExt);
return rc;
}
/**
* Initializes the release logger (debug is implicit), if configured.
*
* @returns IPRT status code.
*/
int VGDrvCommonInitLoggers(void)
{
#ifdef VBOX_GUESTDRV_WITH_RELEASE_LOGGER
/*
* Create the release log.
*/
static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
PRTLOGGER pRelLogger;
int rc = RTLogCreate(&pRelLogger, 0 /*fFlags*/, "all", "VBOXGUEST_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER, NULL);
if (RT_SUCCESS(rc))
RTLogRelSetDefaultInstance(pRelLogger);
/** @todo Add native hook for getting logger config parameters and setting
* them. On linux we should use the module parameter stuff... */
return rc;
#else
return VINF_SUCCESS;
#endif
}
/**
* Destroys the loggers.
*/
void VGDrvCommonDestroyLoggers(void)
{
#ifdef VBOX_GUESTDRV_WITH_RELEASE_LOGGER
RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
RTLogDestroy(RTLogSetDefaultInstance(NULL));
#endif
}
/**
* Initialize the device extension fundament.
*
* There are no device resources at this point, VGDrvCommonInitDevExtResources
* should be called when they are available.
*
* @returns VBox status code.
* @param pDevExt The device extension to init.
*/
int VGDrvCommonInitDevExtFundament(PVBOXGUESTDEVEXT pDevExt)
{
int rc;
AssertMsg( pDevExt->uInitState != VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT
&& pDevExt->uInitState != VBOXGUESTDEVEXT_INIT_STATE_RESOURCES, ("uInitState=%#x\n", pDevExt->uInitState));
/*
* Initialize the data.
*/
pDevExt->IOPortBase = UINT16_MAX;
pDevExt->pVMMDevMemory = NULL;
pDevExt->hGuestMappings = NIL_RTR0MEMOBJ;
pDevExt->EventSpinlock = NIL_RTSPINLOCK;
pDevExt->fHostFeatures = 0;
pDevExt->pIrqAckEvents = NULL;
pDevExt->PhysIrqAckEvents = NIL_RTCCPHYS;
RTListInit(&pDevExt->WaitList);
#ifdef VBOX_WITH_HGCM
RTListInit(&pDevExt->HGCMWaitList);
#endif
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
RTListInit(&pDevExt->WakeUpList);
#endif
RTListInit(&pDevExt->WokenUpList);
RTListInit(&pDevExt->FreeList);
RTListInit(&pDevExt->SessionList);
pDevExt->cSessions = 0;
pDevExt->fLoggingEnabled = false;
pDevExt->f32PendingEvents = 0;
pDevExt->u32MousePosChangedSeq = 0;
pDevExt->SessionSpinlock = NIL_RTSPINLOCK;
pDevExt->MemBalloon.hMtx = NIL_RTSEMFASTMUTEX;
pDevExt->MemBalloon.cChunks = 0;
pDevExt->MemBalloon.cMaxChunks = 0;
pDevExt->MemBalloon.fUseKernelAPI = true;
pDevExt->MemBalloon.paMemObj = NULL;
pDevExt->MemBalloon.pOwner = NULL;
pDevExt->pfnMouseNotifyCallback = NULL;
pDevExt->pvMouseNotifyCallbackArg = NULL;
pDevExt->pReqGuestHeartbeat = NULL;
pDevExt->fFixedEvents = 0;
vgdrvBitUsageTrackerClear(&pDevExt->EventFilterTracker);
pDevExt->fEventFilterHost = UINT32_MAX; /* forces a report */
vgdrvBitUsageTrackerClear(&pDevExt->MouseStatusTracker);
pDevExt->fMouseStatusHost = UINT32_MAX; /* forces a report */
pDevExt->fAcquireModeGuestCaps = 0;
pDevExt->fSetModeGuestCaps = 0;
pDevExt->fAcquiredGuestCaps = 0;
vgdrvBitUsageTrackerClear(&pDevExt->SetGuestCapsTracker);
pDevExt->fGuestCapsHost = UINT32_MAX; /* forces a report */
/*
* Create the wait and session spinlocks as well as the ballooning mutex.
*/
rc = RTSpinlockCreate(&pDevExt->EventSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestEvent");
if (RT_SUCCESS(rc))
{
rc = RTSpinlockCreate(&pDevExt->SessionSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VBoxGuestSession");
if (RT_SUCCESS(rc))
{
rc = RTSemFastMutexCreate(&pDevExt->MemBalloon.hMtx);
if (RT_SUCCESS(rc))
{
pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT;
return VINF_SUCCESS;
}
LogRel(("VGDrvCommonInitDevExt: failed to create mutex, rc=%Rrc!\n", rc));
RTSpinlockDestroy(pDevExt->SessionSpinlock);
}
else
LogRel(("VGDrvCommonInitDevExt: failed to create spinlock, rc=%Rrc!\n", rc));
RTSpinlockDestroy(pDevExt->EventSpinlock);
}
else
LogRel(("VGDrvCommonInitDevExt: failed to create spinlock, rc=%Rrc!\n", rc));
pDevExt->uInitState = 0;
return rc;
}
/**
* Counter to VGDrvCommonInitDevExtFundament.
*
* @param pDevExt The device extension.
*/
void VGDrvCommonDeleteDevExtFundament(PVBOXGUESTDEVEXT pDevExt)
{
int rc2;
AssertMsgReturnVoid(pDevExt->uInitState == VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT, ("uInitState=%#x\n", pDevExt->uInitState));
pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_DELETED;
rc2 = RTSemFastMutexDestroy(pDevExt->MemBalloon.hMtx); AssertRC(rc2);
rc2 = RTSpinlockDestroy(pDevExt->EventSpinlock); AssertRC(rc2);
rc2 = RTSpinlockDestroy(pDevExt->SessionSpinlock); AssertRC(rc2);
}
/**
* Initializes the VBoxGuest device extension resource parts.
*
* The native code locates the VMMDev on the PCI bus and retrieve the MMIO and
* I/O port ranges, this function will take care of mapping the MMIO memory (if
* present). Upon successful return the native code should set up the interrupt
* handler.
*
* @returns VBox status code.
*
* @param pDevExt The device extension. Allocated by the native code.
* @param IOPortBase The base of the I/O port range.
* @param pvMMIOBase The base of the MMIO memory mapping.
* This is optional, pass NULL if not present.
* @param cbMMIO The size of the MMIO memory mapping.
* This is optional, pass 0 if not present.
* @param enmOSType The guest OS type to report to the VMMDev.
* @param fFixedEvents Events that will be enabled upon init and no client
* will ever be allowed to mask.
*/
int VGDrvCommonInitDevExtResources(PVBOXGUESTDEVEXT pDevExt, uint16_t IOPortBase,
void *pvMMIOBase, uint32_t cbMMIO, VBOXOSTYPE enmOSType, uint32_t fFixedEvents)
{
int rc;
AssertMsgReturn(pDevExt->uInitState == VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT, ("uInitState=%#x\n", pDevExt->uInitState),
VERR_INVALID_STATE);
/*
* If there is an MMIO region validate the version and size.
*/
if (pvMMIOBase)
{
VMMDevMemory *pVMMDev = (VMMDevMemory *)pvMMIOBase;
Assert(cbMMIO);
if ( pVMMDev->u32Version == VMMDEV_MEMORY_VERSION
&& pVMMDev->u32Size >= 32
&& pVMMDev->u32Size <= cbMMIO)
{
pDevExt->pVMMDevMemory = pVMMDev;
Log(("VGDrvCommonInitDevExtResources: VMMDevMemory: mapping=%p size=%#RX32 (%#RX32) version=%#RX32\n",
pVMMDev, pVMMDev->u32Size, cbMMIO, pVMMDev->u32Version));
}
else /* try live without it. */
LogRel(("VGDrvCommonInitDevExtResources: Bogus VMMDev memory; u32Version=%RX32 (expected %RX32) u32Size=%RX32 (expected <= %RX32)\n",
pVMMDev->u32Version, VMMDEV_MEMORY_VERSION, pVMMDev->u32Size, cbMMIO));
}
/*
* Initialize the guest library and report the guest info back to VMMDev,
* set the interrupt control filter mask, and fixate the guest mappings
* made by the VMM.
*/
pDevExt->IOPortBase = IOPortBase;
rc = VbglR0InitPrimary(pDevExt->IOPortBase, (VMMDevMemory *)pDevExt->pVMMDevMemory, &pDevExt->fHostFeatures);
if (RT_SUCCESS(rc))
{
VMMDevRequestHeader *pAckReq = NULL;
rc = VbglR0GRAlloc(&pAckReq, sizeof(VMMDevEvents), VMMDevReq_AcknowledgeEvents);
if (RT_SUCCESS(rc))
{
pDevExt->PhysIrqAckEvents = VbglR0PhysHeapGetPhysAddr(pAckReq);
Assert(pDevExt->PhysIrqAckEvents != 0);
ASMCompilerBarrier(); /* linux + solaris already have IRQs hooked up at this point, so take care. */
pDevExt->pIrqAckEvents = (VMMDevEvents *)pAckReq;
rc = vgdrvReportGuestInfo(enmOSType);
if (RT_SUCCESS(rc))
{
/*
* Set the fixed event and make sure the host doesn't have any lingering
* the guest capabilities or mouse status bits set.
*/
#ifdef VBOX_WITH_HGCM
fFixedEvents |= VMMDEV_EVENT_HGCM;
#endif
pDevExt->fFixedEvents = fFixedEvents;
rc = vgdrvResetEventFilterOnHost(pDevExt, fFixedEvents);
if (RT_SUCCESS(rc))
{
rc = vgdrvResetCapabilitiesOnHost(pDevExt);
if (RT_SUCCESS(rc))
{
rc = vgdrvResetMouseStatusOnHost(pDevExt);
if (RT_SUCCESS(rc))
{
/*
* Initialize stuff which may fail without requiring the driver init to fail.
*/
vgdrvInitFixateGuestMappings(pDevExt);
vgdrvHeartbeatInit(pDevExt);
/*
* Done!
*/
rc = vgdrvReportDriverStatus(true /* Driver is active */);
if (RT_FAILURE(rc))
LogRel(("VGDrvCommonInitDevExtResources: VBoxReportGuestDriverStatus failed, rc=%Rrc\n", rc));
pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_RESOURCES;
LogFlowFunc(("VGDrvCommonInitDevExtResources: returns success\n"));
return VINF_SUCCESS;
}
LogRel(("VGDrvCommonInitDevExtResources: failed to clear mouse status: rc=%Rrc\n", rc));
}
else
LogRel(("VGDrvCommonInitDevExtResources: failed to clear guest capabilities: rc=%Rrc\n", rc));
}
else
LogRel(("VGDrvCommonInitDevExtResources: failed to set fixed event filter: rc=%Rrc\n", rc));
pDevExt->fFixedEvents = 0;
}
else
LogRel(("VGDrvCommonInitDevExtResources: vgdrvReportGuestInfo failed: rc=%Rrc\n", rc));
VbglR0GRFree((VMMDevRequestHeader *)pDevExt->pIrqAckEvents);
}
else
LogRel(("VGDrvCommonInitDevExtResources: VbglR0GRAlloc failed: rc=%Rrc\n", rc));
VbglR0TerminatePrimary();
}
else
LogRel(("VGDrvCommonInitDevExtResources: VbglR0InitPrimary failed: rc=%Rrc\n", rc));
pDevExt->IOPortBase = UINT16_MAX;
return rc;
}
/**
* Deletes all the items in a wait chain.
* @param pList The head of the chain.
*/
static void vgdrvDeleteWaitList(PRTLISTNODE pList)
{
while (!RTListIsEmpty(pList))
{
int rc2;
PVBOXGUESTWAIT pWait = RTListGetFirst(pList, VBOXGUESTWAIT, ListNode);
RTListNodeRemove(&pWait->ListNode);
rc2 = RTSemEventMultiDestroy(pWait->Event); AssertRC(rc2);
pWait->Event = NIL_RTSEMEVENTMULTI;
pWait->pSession = NULL;
RTMemFree(pWait);
}
}
/**
* Counter to VGDrvCommonInitDevExtResources.
*
* @param pDevExt The device extension.
*/
void VGDrvCommonDeleteDevExtResources(PVBOXGUESTDEVEXT pDevExt)
{
Log(("VGDrvCommonDeleteDevExtResources:\n"));
AssertMsgReturnVoid(pDevExt->uInitState == VBOXGUESTDEVEXT_INIT_STATE_RESOURCES, ("uInitState=%#x\n", pDevExt->uInitState));
pDevExt->uInitState = VBOXGUESTDEVEXT_INIT_STATE_FUNDAMENT;
/*
* Stop and destroy HB timer and disable host heartbeat checking.
*/
if (pDevExt->pHeartbeatTimer)
{
RTTimerDestroy(pDevExt->pHeartbeatTimer);
vgdrvHeartbeatHostConfigure(pDevExt, false);
}
VbglR0GRFree(pDevExt->pReqGuestHeartbeat);
pDevExt->pReqGuestHeartbeat = NULL;
/*
* Clean up the bits that involves the host first.
*/
vgdrvTermUnfixGuestMappings(pDevExt);
if (!RTListIsEmpty(&pDevExt->SessionList))
{
LogRelFunc(("session list not empty!\n"));
RTListInit(&pDevExt->SessionList);
}
/*
* Update the host flags (mouse status etc) not to reflect this session.
*/
pDevExt->fFixedEvents = 0;
vgdrvResetEventFilterOnHost(pDevExt, 0 /*fFixedEvents*/);
vgdrvResetCapabilitiesOnHost(pDevExt);
vgdrvResetMouseStatusOnHost(pDevExt);
vgdrvCloseMemBalloon(pDevExt, (PVBOXGUESTSESSION)NULL);
/*
* No more IRQs.
*/
pDevExt->pIrqAckEvents = NULL; /* Will be freed by VbglR0TerminatePrimary. */
ASMAtomicWriteU32(&pDevExt->fHostFeatures, 0);
/*
* Cleanup all the other resources.
*/
vgdrvDeleteWaitList(&pDevExt->WaitList);
#ifdef VBOX_WITH_HGCM
vgdrvDeleteWaitList(&pDevExt->HGCMWaitList);
#endif
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
vgdrvDeleteWaitList(&pDevExt->WakeUpList);
#endif
vgdrvDeleteWaitList(&pDevExt->WokenUpList);
vgdrvDeleteWaitList(&pDevExt->FreeList);
VbglR0TerminatePrimary();
pDevExt->pVMMDevMemory = NULL;
pDevExt->IOPortBase = 0;
}
/**
* Initializes the VBoxGuest device extension when the device driver is loaded.
*
* The native code locates the VMMDev on the PCI bus and retrieve the MMIO and
* I/O port ranges, this function will take care of mapping the MMIO memory (if
* present). Upon successful return the native code should set up the interrupt
* handler.
*
* Instead of calling this method, the host specific code choose to perform a
* more granular initialization using:
* 1. VGDrvCommonInitLoggers
* 2. VGDrvCommonInitDevExtFundament
* 3. VGDrvCommonInitDevExtResources
*
* @returns VBox status code.
*
* @param pDevExt The device extension. Allocated by the native code.
* @param IOPortBase The base of the I/O port range.
* @param pvMMIOBase The base of the MMIO memory mapping.
* This is optional, pass NULL if not present.
* @param cbMMIO The size of the MMIO memory mapping.
* This is optional, pass 0 if not present.
* @param enmOSType The guest OS type to report to the VMMDev.
* @param fFixedEvents Events that will be enabled upon init and no client
* will ever be allowed to mask.
*/
int VGDrvCommonInitDevExt(PVBOXGUESTDEVEXT pDevExt, uint16_t IOPortBase,
void *pvMMIOBase, uint32_t cbMMIO, VBOXOSTYPE enmOSType, uint32_t fFixedEvents)
{
int rc;
VGDrvCommonInitLoggers();
rc = VGDrvCommonInitDevExtFundament(pDevExt);
if (RT_SUCCESS(rc))
{
rc = VGDrvCommonInitDevExtResources(pDevExt, IOPortBase, pvMMIOBase, cbMMIO, enmOSType, fFixedEvents);
if (RT_SUCCESS(rc))
return rc;
VGDrvCommonDeleteDevExtFundament(pDevExt);
}
VGDrvCommonDestroyLoggers();
return rc; /* (failed) */
}
/**
* Checks if the given option can be taken to not mean 'false'.
*
* @returns true or false accordingly.
* @param pszValue The value to consider.
*/
bool VBDrvCommonIsOptionValueTrue(const char *pszValue)
{
if (pszValue)
{
char ch;
while ( (ch = *pszValue) != '\0'
&& RT_C_IS_SPACE(ch))
pszValue++;
return ch != '\0'
&& ch != 'n' /* no */
&& ch != 'N' /* NO */
&& ch != 'd' /* disabled */
&& ch != 'f' /* false*/
&& ch != 'F' /* FALSE */
&& ch != 'D' /* DISABLED */
&& ( (ch != 'o' && ch != 'O') /* off, OFF, Off */
|| (pszValue[1] != 'f' && pszValue[1] != 'F') )
&& (ch != '0' || pszValue[1] != '\0') /* '0' */
;
}
return false;
}
/**
* Processes a option.
*
* This will let the OS specific code have a go at it too.
*
* @param pDevExt The device extension.
* @param pszName The option name, sans prefix.
* @param pszValue The option value.
*/
void VGDrvCommonProcessOption(PVBOXGUESTDEVEXT pDevExt, const char *pszName, const char *pszValue)
{
Log(("VGDrvCommonProcessOption: pszName='%s' pszValue='%s'\n", pszName, pszValue));
if ( RTStrICmpAscii(pszName, "r3_log_to_host") == 0
|| RTStrICmpAscii(pszName, "LoggingEnabled") == 0 /*legacy*/ )
pDevExt->fLoggingEnabled = VBDrvCommonIsOptionValueTrue(pszValue);
else if ( RTStrNICmpAscii(pszName, RT_STR_TUPLE("log")) == 0
|| RTStrNICmpAscii(pszName, RT_STR_TUPLE("dbg_log")) == 0)
{
bool const fLogRel = *pszName == 'd' || *pszName == 'D';
const char *pszSubName = &pszName[fLogRel ? 4 + 3 : 3];
if ( !*pszSubName
|| RTStrICmpAscii(pszSubName, "_flags") == 0
|| RTStrICmpAscii(pszSubName, "_dest") == 0)
{
PRTLOGGER pLogger = fLogRel ? RTLogRelGetDefaultInstance() : RTLogDefaultInstance();
if (pLogger)
{
if (!*pszSubName)
RTLogGroupSettings(pLogger, pszValue);
else if (RTStrICmpAscii(pszSubName, "_flags"))
RTLogFlags(pLogger, pszValue);
else
RTLogDestinations(pLogger, pszValue);
}
}
else if (!VGDrvNativeProcessOption(pDevExt, pszName, pszValue))
LogRel(("VBoxGuest: Ignoring unknown option '%s' (value '%s')\n", pszName, pszValue));
}
else if (!VGDrvNativeProcessOption(pDevExt, pszName, pszValue))
LogRel(("VBoxGuest: Ignoring unknown option '%s' (value '%s')\n", pszName, pszValue));
}
/**
* Read driver configuration from the host.
*
* This involves connecting to the guest properties service, which means that
* interrupts needs to work and that the calling thread must be able to block.
*
* @param pDevExt The device extension.
*/
void VGDrvCommonProcessOptionsFromHost(PVBOXGUESTDEVEXT pDevExt)
{
/*
* Create a kernel session without our selves, then connect to the HGCM service.
*/
PVBOXGUESTSESSION pSession;
int rc = VGDrvCommonCreateKernelSession(pDevExt, &pSession);
if (RT_SUCCESS(rc))
{
union
{
VBGLIOCHGCMCONNECT Connect;
VBGLIOCHGCMDISCONNECT Disconnect;
GuestPropMsgEnumProperties EnumMsg;
} uBuf;
RT_ZERO(uBuf.Connect);
VBGLREQHDR_INIT(&uBuf.Connect.Hdr, HGCM_CONNECT);
uBuf.Connect.u.In.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
RTStrCopy(uBuf.Connect.u.In.Loc.u.host.achName, sizeof(uBuf.Connect.u.In.Loc.u.host.achName),
"VBoxGuestPropSvc"); /** @todo Add a define to the header for the name. */
rc = VGDrvCommonIoCtl(VBGL_IOCTL_HGCM_CONNECT, pDevExt, pSession, &uBuf.Connect.Hdr, sizeof(uBuf.Connect));
if (RT_SUCCESS(rc))
{
static const char g_szzPattern[] = "/VirtualBox/GuestAdd/VBoxGuest/*\0";
uint32_t const idClient = uBuf.Connect.u.Out.idClient;
char *pszzStrings = NULL;
uint32_t cbStrings;
/*
* Enumerate all the relevant properties. We try with a 1KB buffer, but
* will double it until we get what we want or go beyond 16KB.
*/
for (cbStrings = _1K; cbStrings <= _16K; cbStrings *= 2)
{
pszzStrings = (char *)RTMemAllocZ(cbStrings);
if (pszzStrings)
{
VBGL_HGCM_HDR_INIT(&uBuf.EnumMsg.hdr, idClient, GUEST_PROP_FN_ENUM_PROPS, 3);
uBuf.EnumMsg.patterns.type = VMMDevHGCMParmType_LinAddr;
uBuf.EnumMsg.patterns.u.Pointer.size = sizeof(g_szzPattern);
uBuf.EnumMsg.patterns.u.Pointer.u.linearAddr = (uintptr_t)g_szzPattern;
uBuf.EnumMsg.strings.type = VMMDevHGCMParmType_LinAddr;
uBuf.EnumMsg.strings.u.Pointer.size = cbStrings;
uBuf.EnumMsg.strings.u.Pointer.u.linearAddr = (uintptr_t)pszzStrings;
uBuf.EnumMsg.size.type = VMMDevHGCMParmType_32bit;
uBuf.EnumMsg.size.u.value32 = 0;
rc = VGDrvCommonIoCtl(VBGL_IOCTL_HGCM_CALL(sizeof(uBuf.EnumMsg)), pDevExt, pSession,
&uBuf.EnumMsg.hdr.Hdr, sizeof(uBuf.EnumMsg));
if (RT_SUCCESS(rc))
{
if ( uBuf.EnumMsg.size.type == VMMDevHGCMParmType_32bit
&& uBuf.EnumMsg.size.u.value32 <= cbStrings
&& uBuf.EnumMsg.size.u.value32 > 0)
cbStrings = uBuf.EnumMsg.size.u.value32;
Log(("VGDrvCommonReadConfigurationFromHost: GUEST_PROP_FN_ENUM_PROPS -> %#x bytes (cbStrings=%#x)\n",
uBuf.EnumMsg.size.u.value32, cbStrings));
break;
}
RTMemFree(pszzStrings);
pszzStrings = NULL;
}
else
{
LogRel(("VGDrvCommonReadConfigurationFromHost: failed to allocate %#x bytes\n", cbStrings));
break;
}
}
/*
* Disconnect and destroy the session.
*/
VBGLREQHDR_INIT(&uBuf.Disconnect.Hdr, HGCM_DISCONNECT);
uBuf.Disconnect.u.In.idClient = idClient;
VGDrvCommonIoCtl(VBGL_IOCTL_HGCM_DISCONNECT, pDevExt, pSession, &uBuf.Disconnect.Hdr, sizeof(uBuf.Disconnect));
VGDrvCommonCloseSession(pDevExt, pSession);
/*
* Process the properties if we got any.
*
* The string buffer contains packed strings in groups of four - name, value,
* timestamp (as a decimal string) and flags. It is terminated by four empty
* strings. Layout:
* Name\0Value\0Timestamp\0Flags\0
*/
if (pszzStrings)
{
uint32_t off;
for (off = 0; off < cbStrings; off++)
{
/*
* Parse the four fields, checking that it's all plain ASCII w/o any control characters.
*/
const char *apszFields[4] = { NULL, NULL, NULL, NULL };
bool fValidFields = true;
unsigned iField;
for (iField = 0; iField < RT_ELEMENTS(apszFields); iField++)
{
apszFields[0] = &pszzStrings[off];
while (off < cbStrings)
{
char ch = pszzStrings[off++];
if ((unsigned)ch < 0x20U || (unsigned)ch > 0x7fU)
{
if (!ch)
break;
if (fValidFields)
Log(("VGDrvCommonReadConfigurationFromHost: Invalid char %#x at %#x (field %u)\n",
ch, off - 1, iField));
fValidFields = false;
}
}
}
if ( off <= cbStrings
&& fValidFields
&& *apszFields[0] != '\0')
{
/*
* Validate and convert the flags to integer, then process the option.
*/
uint32_t fFlags = 0;
rc = GuestPropValidateFlags(apszFields[3], &fFlags);
if (RT_SUCCESS(rc))
{
if (fFlags & GUEST_PROP_F_RDONLYGUEST)
{
apszFields[0] += sizeof(g_szzPattern) - 2;
VGDrvCommonProcessOption(pDevExt, apszFields[0], apszFields[1]);
}
else
LogRel(("VBoxGuest: Ignoring '%s' as it does not have RDONLYGUEST set\n", apszFields[0]));
}
else
LogRel(("VBoxGuest: Invalid flags '%s' for '%s': %Rrc\n", apszFields[2], apszFields[0], rc));
}
else if (off < cbStrings)
{
LogRel(("VBoxGuest: Malformed guest properties enum result!\n"));
Log(("VBoxGuest: off=%#x cbStrings=%#x\n%.*Rhxd\n", off, cbStrings, cbStrings, pszzStrings));
break;
}
else if (!fValidFields)
LogRel(("VBoxGuest: Ignoring %.*Rhxs as it has invalid characters in one or more fields\n",
(int)strlen(apszFields[0]), apszFields[0]));
else
break;
}
RTMemFree(pszzStrings);
}
else
LogRel(("VGDrvCommonReadConfigurationFromHost: failed to enumerate '%s': %Rrc\n", g_szzPattern, rc));
}
else
LogRel(("VGDrvCommonReadConfigurationFromHost: failed to connect: %Rrc\n", rc));
}
else
LogRel(("VGDrvCommonReadConfigurationFromHost: failed to connect: %Rrc\n", rc));
}
/**
* Destroys the VBoxGuest device extension.
*
* The native code should call this before the driver is unloaded,
* but don't call this on shutdown.
*
* @param pDevExt The device extension.
*/
void VGDrvCommonDeleteDevExt(PVBOXGUESTDEVEXT pDevExt)
{
Log(("VGDrvCommonDeleteDevExt:\n"));
Log(("VBoxGuest: The additions driver is terminating.\n"));
VGDrvCommonDeleteDevExtResources(pDevExt);
VGDrvCommonDeleteDevExtFundament(pDevExt);
VGDrvCommonDestroyLoggers();
}
/**
* Creates a VBoxGuest user session.
*
* The native code calls this when a ring-3 client opens the device.
* Use VGDrvCommonCreateKernelSession when a ring-0 client connects.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param fRequestor VMMDEV_REQUESTOR_XXX.
* @param ppSession Where to store the session on success.
*/
int VGDrvCommonCreateUserSession(PVBOXGUESTDEVEXT pDevExt, uint32_t fRequestor, PVBOXGUESTSESSION *ppSession)
{
PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)RTMemAllocZ(sizeof(*pSession));
if (RT_UNLIKELY(!pSession))
{
LogRel(("VGDrvCommonCreateUserSession: no memory!\n"));
return VERR_NO_MEMORY;
}
pSession->Process = RTProcSelf();
pSession->R0Process = RTR0ProcHandleSelf();
pSession->pDevExt = pDevExt;
pSession->fRequestor = fRequestor;
pSession->fUserSession = RT_BOOL(fRequestor & VMMDEV_REQUESTOR_USER_DEVICE);
RTSpinlockAcquire(pDevExt->SessionSpinlock);
RTListAppend(&pDevExt->SessionList, &pSession->ListNode);
pDevExt->cSessions++;
RTSpinlockRelease(pDevExt->SessionSpinlock);
*ppSession = pSession;
LogFlow(("VGDrvCommonCreateUserSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
return VINF_SUCCESS;
}
/**
* Creates a VBoxGuest kernel session.
*
* The native code calls this when a ring-0 client connects to the device.
* Use VGDrvCommonCreateUserSession when a ring-3 client opens the device.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param ppSession Where to store the session on success.
*/
int VGDrvCommonCreateKernelSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION *ppSession)
{
PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)RTMemAllocZ(sizeof(*pSession));
if (RT_UNLIKELY(!pSession))
{
LogRel(("VGDrvCommonCreateKernelSession: no memory!\n"));
return VERR_NO_MEMORY;
}
pSession->Process = NIL_RTPROCESS;
pSession->R0Process = NIL_RTR0PROCESS;
pSession->pDevExt = pDevExt;
pSession->fRequestor = VMMDEV_REQUESTOR_KERNEL | VMMDEV_REQUESTOR_USR_DRV_OTHER
| VMMDEV_REQUESTOR_CON_DONT_KNOW | VMMDEV_REQUESTOR_TRUST_NOT_GIVEN;
RTSpinlockAcquire(pDevExt->SessionSpinlock);
RTListAppend(&pDevExt->SessionList, &pSession->ListNode);
pDevExt->cSessions++;
RTSpinlockRelease(pDevExt->SessionSpinlock);
*ppSession = pSession;
LogFlow(("VGDrvCommonCreateKernelSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
return VINF_SUCCESS;
}
/**
* Closes a VBoxGuest session.
*
* @param pDevExt The device extension.
* @param pSession The session to close (and free).
*/
void VGDrvCommonCloseSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
{
#ifdef VBOX_WITH_HGCM
unsigned i;
#endif
LogFlow(("VGDrvCommonCloseSession: pSession=%p proc=%RTproc (%d) r0proc=%p\n",
pSession, pSession->Process, (int)pSession->Process, (uintptr_t)pSession->R0Process)); /** @todo %RTr0proc */
RTSpinlockAcquire(pDevExt->SessionSpinlock);
RTListNodeRemove(&pSession->ListNode);
pDevExt->cSessions--;
RTSpinlockRelease(pDevExt->SessionSpinlock);
vgdrvAcquireSessionCapabilities(pDevExt, pSession, 0, UINT32_MAX, VBGL_IOC_AGC_FLAGS_DEFAULT, true /*fSessionTermination*/);
vgdrvSetSessionCapabilities(pDevExt, pSession, 0 /*fOrMask*/, UINT32_MAX /*fNotMask*/,
NULL /*pfSessionCaps*/, NULL /*pfGlobalCaps*/, true /*fSessionTermination*/);
vgdrvSetSessionEventFilter(pDevExt, pSession, 0 /*fOrMask*/, UINT32_MAX /*fNotMask*/, true /*fSessionTermination*/);
vgdrvSetSessionMouseStatus(pDevExt, pSession, 0 /*fOrMask*/, UINT32_MAX /*fNotMask*/, true /*fSessionTermination*/);
vgdrvIoCtl_CancelAllWaitEvents(pDevExt, pSession);
#ifdef VBOX_WITH_HGCM
for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
if (pSession->aHGCMClientIds[i])
{
uint32_t idClient = pSession->aHGCMClientIds[i];
pSession->aHGCMClientIds[i] = 0;
Log(("VGDrvCommonCloseSession: disconnecting client id %#RX32\n", idClient));
VbglR0HGCMInternalDisconnect(idClient, VMMDEV_REQUESTOR_KERNEL | VMMDEV_REQUESTOR_USR_DRV,
vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
}
#endif
pSession->pDevExt = NULL;
pSession->Process = NIL_RTPROCESS;
pSession->R0Process = NIL_RTR0PROCESS;
vgdrvCloseMemBalloon(pDevExt, pSession);
RTMemFree(pSession);
}
/**
* Allocates a wait-for-event entry.
*
* @returns The wait-for-event entry.
* @param pDevExt The device extension.
* @param pSession The session that's allocating this. Can be NULL.
*/
static PVBOXGUESTWAIT vgdrvWaitAlloc(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
{
/*
* Allocate it one way or the other.
*/
PVBOXGUESTWAIT pWait = RTListGetFirst(&pDevExt->FreeList, VBOXGUESTWAIT, ListNode);
if (pWait)
{
RTSpinlockAcquire(pDevExt->EventSpinlock);
pWait = RTListGetFirst(&pDevExt->FreeList, VBOXGUESTWAIT, ListNode);
if (pWait)
RTListNodeRemove(&pWait->ListNode);
RTSpinlockRelease(pDevExt->EventSpinlock);
}
if (!pWait)
{
int rc;
pWait = (PVBOXGUESTWAIT)RTMemAlloc(sizeof(*pWait));
if (!pWait)
{
LogRelMax(32, ("vgdrvWaitAlloc: out-of-memory!\n"));
return NULL;
}
rc = RTSemEventMultiCreate(&pWait->Event);
if (RT_FAILURE(rc))
{
LogRelMax(32, ("vgdrvWaitAlloc: RTSemEventMultiCreate failed with rc=%Rrc!\n", rc));
RTMemFree(pWait);
return NULL;
}
pWait->ListNode.pNext = NULL;
pWait->ListNode.pPrev = NULL;
}
/*
* Zero members just as an precaution.
*/
pWait->fReqEvents = 0;
pWait->fResEvents = 0;
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
pWait->fPendingWakeUp = false;
pWait->fFreeMe = false;
#endif
pWait->pSession = pSession;
#ifdef VBOX_WITH_HGCM
pWait->pHGCMReq = NULL;
#endif
RTSemEventMultiReset(pWait->Event);
return pWait;
}
/**
* Frees the wait-for-event entry.
*
* The caller must own the wait spinlock !
* The entry must be in a list!
*
* @param pDevExt The device extension.
* @param pWait The wait-for-event entry to free.
*/
static void vgdrvWaitFreeLocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTWAIT pWait)
{
pWait->fReqEvents = 0;
pWait->fResEvents = 0;
#ifdef VBOX_WITH_HGCM
pWait->pHGCMReq = NULL;
#endif
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
Assert(!pWait->fFreeMe);
if (pWait->fPendingWakeUp)
pWait->fFreeMe = true;
else
#endif
{
RTListNodeRemove(&pWait->ListNode);
RTListAppend(&pDevExt->FreeList, &pWait->ListNode);
}
}
/**
* Frees the wait-for-event entry.
*
* @param pDevExt The device extension.
* @param pWait The wait-for-event entry to free.
*/
static void vgdrvWaitFreeUnlocked(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTWAIT pWait)
{
RTSpinlockAcquire(pDevExt->EventSpinlock);
vgdrvWaitFreeLocked(pDevExt, pWait);
RTSpinlockRelease(pDevExt->EventSpinlock);
}
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
/**
* Processes the wake-up list.
*
* All entries in the wake-up list gets signalled and moved to the woken-up
* list.
* At least on Windows this function can be invoked concurrently from
* different VCPUs. So, be thread-safe.
*
* @param pDevExt The device extension.
*/
void VGDrvCommonWaitDoWakeUps(PVBOXGUESTDEVEXT pDevExt)
{
if (!RTListIsEmpty(&pDevExt->WakeUpList))
{
RTSpinlockAcquire(pDevExt->EventSpinlock);
for (;;)
{
int rc;
PVBOXGUESTWAIT pWait = RTListGetFirst(&pDevExt->WakeUpList, VBOXGUESTWAIT, ListNode);
if (!pWait)
break;
/* Prevent other threads from accessing pWait when spinlock is released. */
RTListNodeRemove(&pWait->ListNode);
pWait->fPendingWakeUp = true;
RTSpinlockRelease(pDevExt->EventSpinlock);
rc = RTSemEventMultiSignal(pWait->Event);
AssertRC(rc);
RTSpinlockAcquire(pDevExt->EventSpinlock);
Assert(pWait->ListNode.pNext == NULL && pWait->ListNode.pPrev == NULL);
RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
pWait->fPendingWakeUp = false;
if (RT_LIKELY(!pWait->fFreeMe))
{ /* likely */ }
else
{
pWait->fFreeMe = false;
vgdrvWaitFreeLocked(pDevExt, pWait);
}
}
RTSpinlockRelease(pDevExt->EventSpinlock);
}
}
#endif /* VBOXGUEST_USE_DEFERRED_WAKE_UP */
/**
* Implements the fast (no input or output) type of IOCtls.
*
* This is currently just a placeholder stub inherited from the support driver code.
*
* @returns VBox status code.
* @param iFunction The IOCtl function number.
* @param pDevExt The device extension.
* @param pSession The session.
*/
int VGDrvCommonIoCtlFast(uintptr_t iFunction, PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
{
LogFlow(("VGDrvCommonIoCtlFast: iFunction=%#x pDevExt=%p pSession=%p\n", iFunction, pDevExt, pSession));
NOREF(iFunction);
NOREF(pDevExt);
NOREF(pSession);
return VERR_NOT_SUPPORTED;
}
/**
* Gets the driver I/O control interface version, maybe adjusting it for
* backwards compatibility.
*
* The adjusting is currently not implemented as we only have one major I/O
* control interface version out there to support. This is something we will
* implement as needed.
*
* returns IPRT status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param pReq The request info.
*/
static int vgdrvIoCtl_DriverVersionInfo(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCDRIVERVERSIONINFO pReq)
{
int rc;
LogFlow(("VBGL_IOCTL_DRIVER_VERSION_INFO: uReqVersion=%#x uMinVersion=%#x uReserved1=%#x uReserved2=%#x\n",
pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, pReq->u.In.uReserved1, pReq->u.In.uReserved2));
RT_NOREF2(pDevExt, pSession);
/*
* Input validation.
*/
if ( pReq->u.In.uMinVersion <= pReq->u.In.uReqVersion
&& RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(pReq->u.In.uReqVersion))
{
/*
* Match the version.
* The current logic is very simple, match the major interface version.
*/
if ( pReq->u.In.uMinVersion <= VBGL_IOC_VERSION
&& RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(VBGL_IOC_VERSION))
rc = VINF_SUCCESS;
else
{
LogRel(("VBGL_IOCTL_DRIVER_VERSION_INFO: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, VBGL_IOC_VERSION));
rc = VERR_VERSION_MISMATCH;
}
}
else
{
LogRel(("VBGL_IOCTL_DRIVER_VERSION_INFO: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
rc = VERR_INVALID_PARAMETER;
}
pReq->u.Out.uSessionVersion = RT_SUCCESS(rc) ? VBGL_IOC_VERSION : UINT32_MAX;
pReq->u.Out.uDriverVersion = VBGL_IOC_VERSION;
pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
pReq->u.Out.uReserved1 = 0;
pReq->u.Out.uReserved2 = 0;
return rc;
}
/**
* Similar to vgdrvIoCtl_DriverVersionInfo, except its for IDC.
*
* returns IPRT status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param pReq The request info.
*/
static int vgdrvIoCtl_IdcConnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCIDCCONNECT pReq)
{
int rc;
LogFlow(("VBGL_IOCTL_IDC_CONNECT: u32MagicCookie=%#x uReqVersion=%#x uMinVersion=%#x uReserved=%#x\n",
pReq->u.In.u32MagicCookie, pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, pReq->u.In.uReserved));
Assert(pSession != NULL);
RT_NOREF(pDevExt);
/*
* Input validation.
*/
if (pReq->u.In.u32MagicCookie == VBGL_IOCTL_IDC_CONNECT_MAGIC_COOKIE)
{
if ( pReq->u.In.uMinVersion <= pReq->u.In.uReqVersion
&& RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(pReq->u.In.uReqVersion))
{
/*
* Match the version.
* The current logic is very simple, match the major interface version.
*/
if ( pReq->u.In.uMinVersion <= VBGL_IOC_VERSION
&& RT_HI_U16(pReq->u.In.uMinVersion) == RT_HI_U16(VBGL_IOC_VERSION))
{
pReq->u.Out.pvSession = pSession;
pReq->u.Out.uSessionVersion = VBGL_IOC_VERSION;
pReq->u.Out.uDriverVersion = VBGL_IOC_VERSION;
pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
pReq->u.Out.uReserved1 = 0;
pReq->u.Out.pvReserved2 = NULL;
return VINF_SUCCESS;
}
LogRel(("VBGL_IOCTL_IDC_CONNECT: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, VBGL_IOC_VERSION));
rc = VERR_VERSION_MISMATCH;
}
else
{
LogRel(("VBGL_IOCTL_IDC_CONNECT: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
rc = VERR_INVALID_PARAMETER;
}
pReq->u.Out.pvSession = NULL;
pReq->u.Out.uSessionVersion = UINT32_MAX;
pReq->u.Out.uDriverVersion = VBGL_IOC_VERSION;
pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
pReq->u.Out.uReserved1 = 0;
pReq->u.Out.pvReserved2 = NULL;
}
else
{
LogRel(("VBGL_IOCTL_IDC_CONNECT: u32MagicCookie=%#x expected %#x!\n",
pReq->u.In.u32MagicCookie, VBGL_IOCTL_IDC_CONNECT_MAGIC_COOKIE));
rc = VERR_INVALID_PARAMETER;
}
return rc;
}
/**
* Counterpart to vgdrvIoCtl_IdcConnect, destroys the session.
*
* returns IPRT status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param pReq The request info.
*/
static int vgdrvIoCtl_IdcDisconnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCIDCDISCONNECT pReq)
{
LogFlow(("VBGL_IOCTL_IDC_DISCONNECT: pvSession=%p vs pSession=%p\n", pReq->u.In.pvSession, pSession));
RT_NOREF(pDevExt);
Assert(pSession != NULL);
if (pReq->u.In.pvSession == pSession)
{
VGDrvCommonCloseSession(pDevExt, pSession);
return VINF_SUCCESS;
}
LogRel(("VBGL_IOCTL_IDC_DISCONNECT: In.pvSession=%p is not equal to pSession=%p!\n", pReq->u.In.pvSession, pSession));
return VERR_INVALID_PARAMETER;
}
/**
* Return the VMM device I/O info.
*
* returns IPRT status code.
* @param pDevExt The device extension.
* @param pInfo The request info.
* @note Ring-0 only, caller checked.
*/
static int vgdrvIoCtl_GetVMMDevIoInfo(PVBOXGUESTDEVEXT pDevExt, PVBGLIOCGETVMMDEVIOINFO pInfo)
{
LogFlow(("VBGL_IOCTL_GET_VMMDEV_IO_INFO\n"));
pInfo->u.Out.IoPort = pDevExt->IOPortBase;
pInfo->u.Out.pvVmmDevMapping = pDevExt->pVMMDevMemory;
pInfo->u.Out.auPadding[0] = 0;
#if HC_ARCH_BITS != 32
pInfo->u.Out.auPadding[1] = 0;
pInfo->u.Out.auPadding[2] = 0;
#endif
return VINF_SUCCESS;
}
/**
* Set the callback for the kernel mouse handler.
*
* returns IPRT status code.
* @param pDevExt The device extension.
* @param pNotify The new callback information.
*/
int vgdrvIoCtl_SetMouseNotifyCallback(PVBOXGUESTDEVEXT pDevExt, PVBGLIOCSETMOUSENOTIFYCALLBACK pNotify)
{
LogFlow(("VBOXGUEST_IOCTL_SET_MOUSE_NOTIFY_CALLBACK: pfnNotify=%p pvUser=%p\n", pNotify->u.In.pfnNotify, pNotify->u.In.pvUser));
#ifdef VBOXGUEST_MOUSE_NOTIFY_CAN_PREEMPT
VGDrvNativeSetMouseNotifyCallback(pDevExt, pNotify);
#else
RTSpinlockAcquire(pDevExt->EventSpinlock);
pDevExt->pfnMouseNotifyCallback = pNotify->u.In.pfnNotify;
pDevExt->pvMouseNotifyCallbackArg = pNotify->u.In.pvUser;
RTSpinlockRelease(pDevExt->EventSpinlock);
#endif
return VINF_SUCCESS;
}
/**
* Worker vgdrvIoCtl_WaitEvent.
*
* The caller enters the spinlock, we leave it.
*
* @returns VINF_SUCCESS if we've left the spinlock and can return immediately.
*/
DECLINLINE(int) vbdgCheckWaitEventCondition(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
PVBGLIOCWAITFOREVENTS pInfo, int iEvent, const uint32_t fReqEvents)
{
uint32_t fMatches = pDevExt->f32PendingEvents & fReqEvents;
if (fMatches & VBOXGUEST_ACQUIRE_STYLE_EVENTS)
fMatches &= vgdrvGetAllowedEventMaskForSession(pDevExt, pSession);
if (fMatches || pSession->fPendingCancelWaitEvents)
{
ASMAtomicAndU32(&pDevExt->f32PendingEvents, ~fMatches);
RTSpinlockRelease(pDevExt->EventSpinlock);
pInfo->u.Out.fEvents = fMatches;
if (fReqEvents & ~((uint32_t)1 << iEvent))
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x\n", pInfo->u.Out.fEvents));
else
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x/%d\n", pInfo->u.Out.fEvents, iEvent));
pSession->fPendingCancelWaitEvents = false;
return VINF_SUCCESS;
}
RTSpinlockRelease(pDevExt->EventSpinlock);
return VERR_TIMEOUT;
}
static int vgdrvIoCtl_WaitForEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
PVBGLIOCWAITFOREVENTS pInfo, bool fInterruptible)
{
uint32_t const cMsTimeout = pInfo->u.In.cMsTimeOut;
const uint32_t fReqEvents = pInfo->u.In.fEvents;
uint32_t fResEvents;
int iEvent;
PVBOXGUESTWAIT pWait;
int rc;
pInfo->u.Out.fEvents = 0; /* Note! This overwrites pInfo->u.In.* fields! */
/*
* Copy and verify the input mask.
*/
iEvent = ASMBitFirstSetU32(fReqEvents) - 1;
if (RT_UNLIKELY(iEvent < 0))
{
LogRel(("VBOXGUEST_IOCTL_WAITEVENT: Invalid input mask %#x!!\n", fReqEvents));
return VERR_INVALID_PARAMETER;
}
/*
* Check the condition up front, before doing the wait-for-event allocations.
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
rc = vbdgCheckWaitEventCondition(pDevExt, pSession, pInfo, iEvent, fReqEvents);
if (rc == VINF_SUCCESS)
return rc;
if (!cMsTimeout)
{
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns VERR_TIMEOUT\n"));
return VERR_TIMEOUT;
}
pWait = vgdrvWaitAlloc(pDevExt, pSession);
if (!pWait)
return VERR_NO_MEMORY;
pWait->fReqEvents = fReqEvents;
/*
* We've got the wait entry now, re-enter the spinlock and check for the condition.
* If the wait condition is met, return.
* Otherwise enter into the list and go to sleep waiting for the ISR to signal us.
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
RTListAppend(&pDevExt->WaitList, &pWait->ListNode);
rc = vbdgCheckWaitEventCondition(pDevExt, pSession, pInfo, iEvent, fReqEvents);
if (rc == VINF_SUCCESS)
{
vgdrvWaitFreeUnlocked(pDevExt, pWait);
return rc;
}
if (fInterruptible)
rc = RTSemEventMultiWaitNoResume(pWait->Event, cMsTimeout == UINT32_MAX ? RT_INDEFINITE_WAIT : cMsTimeout);
else
rc = RTSemEventMultiWait(pWait->Event, cMsTimeout == UINT32_MAX ? RT_INDEFINITE_WAIT : cMsTimeout);
/*
* There is one special case here and that's when the semaphore is
* destroyed upon device driver unload. This shouldn't happen of course,
* but in case it does, just get out of here ASAP.
*/
if (rc == VERR_SEM_DESTROYED)
return rc;
/*
* Unlink the wait item and dispose of it.
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
fResEvents = pWait->fResEvents;
vgdrvWaitFreeLocked(pDevExt, pWait);
RTSpinlockRelease(pDevExt->EventSpinlock);
/*
* Now deal with the return code.
*/
if ( fResEvents
&& fResEvents != UINT32_MAX)
{
pInfo->u.Out.fEvents = fResEvents;
if (fReqEvents & ~((uint32_t)1 << iEvent))
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x\n", pInfo->u.Out.fEvents));
else
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %#x/%d\n", pInfo->u.Out.fEvents, iEvent));
rc = VINF_SUCCESS;
}
else if ( fResEvents == UINT32_MAX
|| rc == VERR_INTERRUPTED)
{
rc = VERR_INTERRUPTED;
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns VERR_INTERRUPTED\n"));
}
else if (rc == VERR_TIMEOUT)
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns VERR_TIMEOUT (2)\n"));
else
{
if (RT_SUCCESS(rc))
{
LogRelMax(32, ("VBOXGUEST_IOCTL_WAITEVENT: returns %Rrc but no events!\n", rc));
rc = VERR_INTERNAL_ERROR;
}
LogFlow(("VBOXGUEST_IOCTL_WAITEVENT: returns %Rrc\n", rc));
}
return rc;
}
/** @todo the semantics of this IoCtl have been tightened, so that no calls to
* VBOXGUEST_IOCTL_WAITEVENT are allowed in a session after it has been
* called. Change the code to make calls to VBOXGUEST_IOCTL_WAITEVENT made
* after that to return VERR_INTERRUPTED or something appropriate. */
static int vgdrvIoCtl_CancelAllWaitEvents(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
{
PVBOXGUESTWAIT pWait;
PVBOXGUESTWAIT pSafe;
int rc = 0;
/* Was as least one WAITEVENT in process for this session? If not we
* set a flag that the next call should be interrupted immediately. This
* is needed so that a user thread can reliably interrupt another one in a
* WAITEVENT loop. */
bool fCancelledOne = false;
LogFlow(("VBOXGUEST_IOCTL_CANCEL_ALL_WAITEVENTS\n"));
/*
* Walk the event list and wake up anyone with a matching session.
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
{
if (pWait->pSession == pSession)
{
fCancelledOne = true;
pWait->fResEvents = UINT32_MAX;
RTListNodeRemove(&pWait->ListNode);
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
#else
rc |= RTSemEventMultiSignal(pWait->Event);
RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
#endif
}
}
if (!fCancelledOne)
pSession->fPendingCancelWaitEvents = true;
RTSpinlockRelease(pDevExt->EventSpinlock);
Assert(rc == 0);
NOREF(rc);
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
VGDrvCommonWaitDoWakeUps(pDevExt);
#endif
return VINF_SUCCESS;
}
/**
* Checks if the VMM request is allowed in the context of the given session.
*
* @returns VINF_SUCCESS or VERR_PERMISSION_DENIED.
* @param pDevExt The device extension.
* @param pSession The calling session.
* @param enmType The request type.
* @param pReqHdr The request.
*/
static int vgdrvCheckIfVmmReqIsAllowed(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, VMMDevRequestType enmType,
VMMDevRequestHeader const *pReqHdr)
{
/*
* Categorize the request being made.
*/
/** @todo This need quite some more work! */
enum
{
kLevel_Invalid, kLevel_NoOne, kLevel_OnlyVBoxGuest, kLevel_OnlyKernel, kLevel_TrustedUsers, kLevel_AllUsers
} enmRequired;
RT_NOREF1(pDevExt);
switch (enmType)
{
/*
* Deny access to anything we don't know or provide specialized I/O controls for.
*/
#ifdef VBOX_WITH_HGCM
case VMMDevReq_HGCMConnect:
case VMMDevReq_HGCMDisconnect:
# ifdef VBOX_WITH_64_BITS_GUESTS
case VMMDevReq_HGCMCall32:
case VMMDevReq_HGCMCall64:
# else
case VMMDevReq_HGCMCall:
# endif /* VBOX_WITH_64_BITS_GUESTS */
case VMMDevReq_HGCMCancel:
case VMMDevReq_HGCMCancel2:
#endif /* VBOX_WITH_HGCM */
case VMMDevReq_SetGuestCapabilities:
default:
enmRequired = kLevel_NoOne;
break;
/*
* There are a few things only this driver can do (and it doesn't use
* the VMMRequst I/O control route anyway, but whatever).
*/
case VMMDevReq_ReportGuestInfo:
case VMMDevReq_ReportGuestInfo2:
case VMMDevReq_GetHypervisorInfo:
case VMMDevReq_SetHypervisorInfo:
case VMMDevReq_RegisterPatchMemory:
case VMMDevReq_DeregisterPatchMemory:
case VMMDevReq_GetMemBalloonChangeRequest:
enmRequired = kLevel_OnlyVBoxGuest;
break;
/*
* Trusted users apps only.
*/
case VMMDevReq_QueryCredentials:
case VMMDevReq_ReportCredentialsJudgement:
case VMMDevReq_RegisterSharedModule:
case VMMDevReq_UnregisterSharedModule:
case VMMDevReq_WriteCoreDump:
case VMMDevReq_GetCpuHotPlugRequest:
case VMMDevReq_SetCpuHotPlugStatus:
case VMMDevReq_CheckSharedModules:
case VMMDevReq_GetPageSharingStatus:
case VMMDevReq_DebugIsPageShared:
case VMMDevReq_ReportGuestStats:
case VMMDevReq_ReportGuestUserState:
case VMMDevReq_GetStatisticsChangeRequest:
case VMMDevReq_ChangeMemBalloon:
enmRequired = kLevel_TrustedUsers;
break;
/*
* Anyone.
*/
case VMMDevReq_GetMouseStatus:
case VMMDevReq_SetMouseStatus:
case VMMDevReq_SetPointerShape:
case VMMDevReq_GetHostVersion:
case VMMDevReq_Idle:
case VMMDevReq_GetHostTime:
case VMMDevReq_SetPowerStatus:
case VMMDevReq_AcknowledgeEvents:
case VMMDevReq_CtlGuestFilterMask:
case VMMDevReq_ReportGuestStatus:
case VMMDevReq_GetDisplayChangeRequest:
case VMMDevReq_VideoModeSupported:
case VMMDevReq_GetHeightReduction:
case VMMDevReq_GetDisplayChangeRequest2:
case VMMDevReq_VideoModeSupported2:
case VMMDevReq_VideoAccelEnable:
case VMMDevReq_VideoAccelFlush:
case VMMDevReq_VideoSetVisibleRegion:
case VMMDevReq_GetDisplayChangeRequestEx:
case VMMDevReq_GetDisplayChangeRequestMulti:
case VMMDevReq_GetSeamlessChangeRequest:
case VMMDevReq_GetVRDPChangeRequest:
case VMMDevReq_LogString:
case VMMDevReq_GetSessionId:
enmRequired = kLevel_AllUsers;
break;
/*
* Depends on the request parameters...
*/
/** @todo this have to be changed into an I/O control and the facilities
* tracked in the session so they can automatically be failed when the
* session terminates without reporting the new status.
*
* The information presented by IGuest is not reliable without this! */
case VMMDevReq_ReportGuestCapabilities:
switch (((VMMDevReportGuestStatus const *)pReqHdr)->guestStatus.facility)
{
case VBoxGuestFacilityType_All:
case VBoxGuestFacilityType_VBoxGuestDriver:
enmRequired = kLevel_OnlyVBoxGuest;
break;
case VBoxGuestFacilityType_VBoxService:
enmRequired = kLevel_TrustedUsers;
break;
case VBoxGuestFacilityType_VBoxTrayClient:
case VBoxGuestFacilityType_Seamless:
case VBoxGuestFacilityType_Graphics:
default:
enmRequired = kLevel_AllUsers;
break;
}
break;
}
/*
* Check against the session.
*/
switch (enmRequired)
{
default:
case kLevel_NoOne:
break;
case kLevel_OnlyVBoxGuest:
case kLevel_OnlyKernel:
if (pSession->R0Process == NIL_RTR0PROCESS)
return VINF_SUCCESS;
break;
case kLevel_TrustedUsers:
if (pSession->fUserSession)
break;
case kLevel_AllUsers:
return VINF_SUCCESS;
}
return VERR_PERMISSION_DENIED;
}
static int vgdrvIoCtl_VMMDevRequest(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
VMMDevRequestHeader *pReqHdr, size_t cbData)
{
int rc;
VMMDevRequestHeader *pReqCopy;
/*
* Validate the header and request size.
*/
const VMMDevRequestType enmType = pReqHdr->requestType;
const uint32_t cbReq = pReqHdr->size;
const uint32_t cbMinSize = (uint32_t)vmmdevGetRequestSize(enmType);
LogFlow(("VBOXGUEST_IOCTL_VMMREQUEST: type %d\n", pReqHdr->requestType));
if (cbReq < cbMinSize)
{
LogRel(("VBOXGUEST_IOCTL_VMMREQUEST: invalid hdr size %#x, expected >= %#x; type=%#x!!\n",
cbReq, cbMinSize, enmType));
return VERR_INVALID_PARAMETER;
}
if (cbReq > cbData)
{
LogRel(("VBOXGUEST_IOCTL_VMMREQUEST: invalid size %#x, expected >= %#x (hdr); type=%#x!!\n",
cbData, cbReq, enmType));
return VERR_INVALID_PARAMETER;
}
rc = VbglGR0Verify(pReqHdr, cbData);
if (RT_FAILURE(rc))
{
Log(("VBOXGUEST_IOCTL_VMMREQUEST: invalid header: size %#x, expected >= %#x (hdr); type=%#x; rc=%Rrc!!\n",
cbData, cbReq, enmType, rc));
return rc;
}
rc = vgdrvCheckIfVmmReqIsAllowed(pDevExt, pSession, enmType, pReqHdr);
if (RT_FAILURE(rc))
{
Log(("VBOXGUEST_IOCTL_VMMREQUEST: Operation not allowed! type=%#x rc=%Rrc\n", enmType, rc));
return rc;
}
/*
* Make a copy of the request in the physical memory heap so
* the VBoxGuestLibrary can more easily deal with the request.
* (This is really a waste of time since the OS or the OS specific
* code has already buffered or locked the input/output buffer, but
* it does makes things a bit simpler wrt to phys address.)
*/
rc = VbglR0GRAlloc(&pReqCopy, cbReq, enmType);
if (RT_FAILURE(rc))
{
Log(("VBOXGUEST_IOCTL_VMMREQUEST: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
cbReq, cbReq, rc));
return rc;
}
memcpy(pReqCopy, pReqHdr, cbReq);
Assert(pReqCopy->reserved1 == cbReq);
pReqCopy->reserved1 = 0; /* VGDrvCommonIoCtl or caller sets cbOut, so clear it. */
pReqCopy->fRequestor = pSession->fRequestor;
if (enmType == VMMDevReq_GetMouseStatus) /* clear poll condition. */
pSession->u32MousePosChangedSeq = ASMAtomicUoReadU32(&pDevExt->u32MousePosChangedSeq);
rc = VbglR0GRPerform(pReqCopy);
if ( RT_SUCCESS(rc)
&& RT_SUCCESS(pReqCopy->rc))
{
Assert(rc != VINF_HGCM_ASYNC_EXECUTE);
Assert(pReqCopy->rc != VINF_HGCM_ASYNC_EXECUTE);
memcpy(pReqHdr, pReqCopy, cbReq);
pReqHdr->reserved1 = cbReq; /* preserve cbOut */
}
else if (RT_FAILURE(rc))
Log(("VBOXGUEST_IOCTL_VMMREQUEST: VbglR0GRPerform - rc=%Rrc!\n", rc));
else
{
Log(("VBOXGUEST_IOCTL_VMMREQUEST: request execution failed; VMMDev rc=%Rrc!\n", pReqCopy->rc));
rc = pReqCopy->rc;
}
VbglR0GRFree(pReqCopy);
return rc;
}
#ifdef VBOX_WITH_HGCM
AssertCompile(RT_INDEFINITE_WAIT == (uint32_t)RT_INDEFINITE_WAIT); /* assumed by code below */
/** Worker for vgdrvHgcmAsyncWaitCallback*. */
static int vgdrvHgcmAsyncWaitCallbackWorker(VMMDevHGCMRequestHeader volatile *pHdr, PVBOXGUESTDEVEXT pDevExt,
bool fInterruptible, uint32_t cMillies)
{
int rc;
/*
* Check to see if the condition was met by the time we got here.
*
* We create a simple poll loop here for dealing with out-of-memory
* conditions since the caller isn't necessarily able to deal with
* us returning too early.
*/
PVBOXGUESTWAIT pWait;
for (;;)
{
RTSpinlockAcquire(pDevExt->EventSpinlock);
if ((pHdr->fu32Flags & VBOX_HGCM_REQ_DONE) != 0)
{
RTSpinlockRelease(pDevExt->EventSpinlock);
return VINF_SUCCESS;
}
RTSpinlockRelease(pDevExt->EventSpinlock);
pWait = vgdrvWaitAlloc(pDevExt, NULL);
if (pWait)
break;
if (fInterruptible)
return VERR_INTERRUPTED;
RTThreadSleep(1);
}
pWait->fReqEvents = VMMDEV_EVENT_HGCM;
pWait->pHGCMReq = pHdr;
/*
* Re-enter the spinlock and re-check for the condition.
* If the condition is met, return.
* Otherwise link us into the HGCM wait list and go to sleep.
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
RTListAppend(&pDevExt->HGCMWaitList, &pWait->ListNode);
if ((pHdr->fu32Flags & VBOX_HGCM_REQ_DONE) != 0)
{
vgdrvWaitFreeLocked(pDevExt, pWait);
RTSpinlockRelease(pDevExt->EventSpinlock);
return VINF_SUCCESS;
}
RTSpinlockRelease(pDevExt->EventSpinlock);
if (fInterruptible)
rc = RTSemEventMultiWaitNoResume(pWait->Event, cMillies);
else
rc = RTSemEventMultiWait(pWait->Event, cMillies);
if (rc == VERR_SEM_DESTROYED)
return rc;
/*
* Unlink, free and return.
*/
if ( RT_FAILURE(rc)
&& rc != VERR_TIMEOUT
&& ( !fInterruptible
|| rc != VERR_INTERRUPTED))
LogRel(("vgdrvHgcmAsyncWaitCallback: wait failed! %Rrc\n", rc));
vgdrvWaitFreeUnlocked(pDevExt, pWait);
return rc;
}
/**
* This is a callback for dealing with async waits.
*
* It operates in a manner similar to vgdrvIoCtl_WaitEvent.
*/
static DECLCALLBACK(int) vgdrvHgcmAsyncWaitCallback(VMMDevHGCMRequestHeader *pHdr, void *pvUser, uint32_t u32User)
{
PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
LogFlow(("vgdrvHgcmAsyncWaitCallback: requestType=%d\n", pHdr->header.requestType));
return vgdrvHgcmAsyncWaitCallbackWorker((VMMDevHGCMRequestHeader volatile *)pHdr, pDevExt,
false /* fInterruptible */, u32User /* cMillies */);
}
/**
* This is a callback for dealing with async waits with a timeout.
*
* It operates in a manner similar to vgdrvIoCtl_WaitEvent.
*/
static DECLCALLBACK(int) vgdrvHgcmAsyncWaitCallbackInterruptible(VMMDevHGCMRequestHeader *pHdr, void *pvUser, uint32_t u32User)
{
PVBOXGUESTDEVEXT pDevExt = (PVBOXGUESTDEVEXT)pvUser;
LogFlow(("vgdrvHgcmAsyncWaitCallbackInterruptible: requestType=%d\n", pHdr->header.requestType));
return vgdrvHgcmAsyncWaitCallbackWorker((VMMDevHGCMRequestHeader volatile *)pHdr, pDevExt,
true /* fInterruptible */, u32User /* cMillies */);
}
static int vgdrvIoCtl_HGCMConnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMCONNECT pInfo)
{
int rc;
HGCMCLIENTID idClient = 0;
/*
* The VbglHGCMConnect call will invoke the callback if the HGCM
* call is performed in an ASYNC fashion. The function is not able
* to deal with cancelled requests.
*/
Log(("VBOXGUEST_IOCTL_HGCM_CONNECT: %.128s\n",
pInfo->u.In.Loc.type == VMMDevHGCMLoc_LocalHost || pInfo->u.In.Loc.type == VMMDevHGCMLoc_LocalHost_Existing
? pInfo->u.In.Loc.u.host.achName : "<not local host>"));
rc = VbglR0HGCMInternalConnect(&pInfo->u.In.Loc, pSession->fRequestor, &idClient,
vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
Log(("VBOXGUEST_IOCTL_HGCM_CONNECT: idClient=%RX32 (rc=%Rrc)\n", idClient, rc));
if (RT_SUCCESS(rc))
{
/*
* Append the client id to the client id table.
* If the table has somehow become filled up, we'll disconnect the session.
*/
unsigned i;
RTSpinlockAcquire(pDevExt->SessionSpinlock);
for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
if (!pSession->aHGCMClientIds[i])
{
pSession->aHGCMClientIds[i] = idClient;
break;
}
RTSpinlockRelease(pDevExt->SessionSpinlock);
if (i >= RT_ELEMENTS(pSession->aHGCMClientIds))
{
LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_CONNECT: too many HGCMConnect calls for one session!\n"));
VbglR0HGCMInternalDisconnect(idClient, pSession->fRequestor, vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
pInfo->u.Out.idClient = 0;
return VERR_TOO_MANY_OPEN_FILES;
}
}
pInfo->u.Out.idClient = idClient;
return rc;
}
static int vgdrvIoCtl_HGCMDisconnect(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMDISCONNECT pInfo)
{
/*
* Validate the client id and invalidate its entry while we're in the call.
*/
int rc;
const uint32_t idClient = pInfo->u.In.idClient;
unsigned i;
RTSpinlockAcquire(pDevExt->SessionSpinlock);
for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
if (pSession->aHGCMClientIds[i] == idClient)
{
pSession->aHGCMClientIds[i] = UINT32_MAX;
break;
}
RTSpinlockRelease(pDevExt->SessionSpinlock);
if (i >= RT_ELEMENTS(pSession->aHGCMClientIds))
{
LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_DISCONNECT: idClient=%RX32\n", idClient));
return VERR_INVALID_HANDLE;
}
/*
* The VbglHGCMConnect call will invoke the callback if the HGCM
* call is performed in an ASYNC fashion. The function is not able
* to deal with cancelled requests.
*/
Log(("VBOXGUEST_IOCTL_HGCM_DISCONNECT: idClient=%RX32\n", idClient));
rc = VbglR0HGCMInternalDisconnect(idClient, pSession->fRequestor, vgdrvHgcmAsyncWaitCallback, pDevExt, RT_INDEFINITE_WAIT);
LogFlow(("VBOXGUEST_IOCTL_HGCM_DISCONNECT: rc=%Rrc\n", rc));
/* Update the client id array according to the result. */
RTSpinlockAcquire(pDevExt->SessionSpinlock);
if (pSession->aHGCMClientIds[i] == UINT32_MAX)
pSession->aHGCMClientIds[i] = RT_SUCCESS(rc) ? 0 : idClient;
RTSpinlockRelease(pDevExt->SessionSpinlock);
return rc;
}
static int vgdrvIoCtl_HGCMCallInner(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMCALL pInfo,
uint32_t cMillies, bool fInterruptible, bool f32bit, bool fUserData,
size_t cbExtra, size_t cbData)
{
const uint32_t u32ClientId = pInfo->u32ClientID;
uint32_t fFlags;
size_t cbActual;
unsigned i;
int rc;
/*
* Some more validations.
*/
if (RT_LIKELY(pInfo->cParms <= VMMDEV_MAX_HGCM_PARMS)) /* (Just make sure it doesn't overflow the next check.) */
{ /* likely */}
else
{
LogRel(("VBOXGUEST_IOCTL_HGCM_CALL: cParm=%RX32 is not sane\n", pInfo->cParms));
return VERR_INVALID_PARAMETER;
}
cbActual = cbExtra + sizeof(*pInfo);
#ifdef RT_ARCH_AMD64
if (f32bit)
cbActual += pInfo->cParms * sizeof(HGCMFunctionParameter32);
else
#endif
cbActual += pInfo->cParms * sizeof(HGCMFunctionParameter);
if (RT_LIKELY(cbData >= cbActual))
{ /* likely */}
else
{
LogRel(("VBOXGUEST_IOCTL_HGCM_CALL: cbData=%#zx (%zu) required size is %#zx (%zu)\n",
cbData, cbData, cbActual, cbActual));
return VERR_INVALID_PARAMETER;
}
pInfo->Hdr.cbOut = (uint32_t)cbActual;
/*
* Validate the client id.
*/
RTSpinlockAcquire(pDevExt->SessionSpinlock);
for (i = 0; i < RT_ELEMENTS(pSession->aHGCMClientIds); i++)
if (pSession->aHGCMClientIds[i] == u32ClientId)
break;
RTSpinlockRelease(pDevExt->SessionSpinlock);
if (RT_LIKELY(i < RT_ELEMENTS(pSession->aHGCMClientIds)))
{ /* likely */}
else
{
LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_CALL: Invalid handle. u32Client=%RX32\n", u32ClientId));
return VERR_INVALID_HANDLE;
}
/*
* The VbglHGCMCall call will invoke the callback if the HGCM
* call is performed in an ASYNC fashion. This function can
* deal with cancelled requests, so we let user more requests
* be interruptible (should add a flag for this later I guess).
*/
LogFlow(("VBOXGUEST_IOCTL_HGCM_CALL: u32Client=%RX32\n", pInfo->u32ClientID));
fFlags = !fUserData && pSession->R0Process == NIL_RTR0PROCESS ? VBGLR0_HGCMCALL_F_KERNEL : VBGLR0_HGCMCALL_F_USER;
uint32_t cbInfo = (uint32_t)(cbData - cbExtra);
#ifdef RT_ARCH_AMD64
if (f32bit)
{
if (fInterruptible)
rc = VbglR0HGCMInternalCall32(pInfo, cbInfo, fFlags, pSession->fRequestor,
vgdrvHgcmAsyncWaitCallbackInterruptible, pDevExt, cMillies);
else
rc = VbglR0HGCMInternalCall32(pInfo, cbInfo, fFlags, pSession->fRequestor,
vgdrvHgcmAsyncWaitCallback, pDevExt, cMillies);
}
else
#endif
{
if (fInterruptible)
rc = VbglR0HGCMInternalCall(pInfo, cbInfo, fFlags, pSession->fRequestor,
vgdrvHgcmAsyncWaitCallbackInterruptible, pDevExt, cMillies);
else
rc = VbglR0HGCMInternalCall(pInfo, cbInfo, fFlags, pSession->fRequestor,
vgdrvHgcmAsyncWaitCallback, pDevExt, cMillies);
}
if (RT_SUCCESS(rc))
{
rc = pInfo->Hdr.rc;
LogFlow(("VBOXGUEST_IOCTL_HGCM_CALL: result=%Rrc\n", rc));
}
else
{
if ( rc != VERR_INTERRUPTED
&& rc != VERR_TIMEOUT)
LogRelMax(32, ("VBOXGUEST_IOCTL_HGCM_CALL: %s Failed. rc=%Rrc (Hdr.rc=%Rrc).\n", f32bit ? "32" : "64", rc, pInfo->Hdr.rc));
else
Log(("VBOXGUEST_IOCTL_HGCM_CALL: %s Failed. rc=%Rrc (Hdr.rc=%Rrc).\n", f32bit ? "32" : "64", rc, pInfo->Hdr.rc));
}
return rc;
}
static int vgdrvIoCtl_HGCMCallWrapper(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCHGCMCALL pInfo,
bool f32bit, bool fUserData, size_t cbData)
{
return vgdrvIoCtl_HGCMCallInner(pDevExt, pSession, pInfo, pInfo->cMsTimeout,
pInfo->fInterruptible || pSession->R0Process != NIL_RTR0PROCESS,
f32bit, fUserData, 0 /*cbExtra*/, cbData);
}
/**
* Handles a fast HGCM call from another driver.
*
* The driver has provided a fully assembled HGCM call request and all we need
* to do is send it to the host and do the wait processing.
*
* @returns VBox status code of the request submission part.
* @param pDevExt The device extension.
* @param pCallReq The call request.
*/
static int vgdrvIoCtl_HGCMFastCall(PVBOXGUESTDEVEXT pDevExt, VBGLIOCIDCHGCMFASTCALL volatile *pCallReq)
{
VMMDevHGCMCall volatile *pHgcmCall = (VMMDevHGCMCall volatile *)(pCallReq + 1);
int rc;
/*
* Check out the physical address.
*/
Assert((pCallReq->GCPhysReq & PAGE_OFFSET_MASK) == ((uintptr_t)pHgcmCall & PAGE_OFFSET_MASK));
AssertReturn(!pCallReq->fInterruptible, VERR_NOT_IMPLEMENTED);
/*
* Submit the request.
*/
Log(("vgdrvIoCtl_HGCMFastCall -> host\n"));
ASMOutU32(pDevExt->IOPortBase + VMMDEV_PORT_OFF_REQUEST, (uint32_t)pCallReq->GCPhysReq);
/* Make the compiler aware that the host has changed memory. */
ASMCompilerBarrier();
pCallReq->Hdr.rc = rc = pHgcmCall->header.header.rc;
Log(("vgdrvIoCtl_HGCMFastCall -> %Rrc (header rc=%Rrc)\n", rc, pHgcmCall->header.result));
/*
* The host is likely to engage in asynchronous execution of HGCM, unless it fails.
*/
if (rc == VINF_HGCM_ASYNC_EXECUTE)
{
rc = vgdrvHgcmAsyncWaitCallbackWorker(&pHgcmCall->header, pDevExt, false /* fInterruptible */, RT_INDEFINITE_WAIT);
if (pHgcmCall->header.fu32Flags & VBOX_HGCM_REQ_DONE)
{
Assert(!(pHgcmCall->header.fu32Flags & VBOX_HGCM_REQ_CANCELLED));
rc = VINF_SUCCESS;
}
else
{
/*
* Timeout and interrupt scenarios are messy and requires
* cancelation, so implement later.
*/
AssertReleaseMsgFailed(("rc=%Rrc\n", rc));
}
}
else
Assert((pHgcmCall->header.fu32Flags & VBOX_HGCM_REQ_DONE) || RT_FAILURE_NP(rc));
Log(("vgdrvIoCtl_HGCMFastCall: rc=%Rrc result=%Rrc fu32Flags=%#x\n", rc, pHgcmCall->header.result, pHgcmCall->header.fu32Flags));
return rc;
}
#endif /* VBOX_WITH_HGCM */
/**
* Handle VBGL_IOCTL_CHECK_BALLOON from R3.
*
* Ask the host for the size of the balloon and try to set it accordingly. If
* this approach fails because it's not supported, return with fHandleInR3 set
* and let the user land supply memory we can lock via the other ioctl.
*
* @returns VBox status code.
*
* @param pDevExt The device extension.
* @param pSession The session.
* @param pInfo The output buffer.
*/
static int vgdrvIoCtl_CheckMemoryBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCCHECKBALLOON pInfo)
{
VMMDevGetMemBalloonChangeRequest *pReq;
int rc;
LogFlow(("VBGL_IOCTL_CHECK_BALLOON:\n"));
rc = RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
AssertRCReturn(rc, rc);
/*
* The first user trying to query/change the balloon becomes the
* owner and owns it until the session is closed (vgdrvCloseMemBalloon).
*/
if ( pDevExt->MemBalloon.pOwner != pSession
&& pDevExt->MemBalloon.pOwner == NULL)
pDevExt->MemBalloon.pOwner = pSession;
if (pDevExt->MemBalloon.pOwner == pSession)
{
/*
* This is a response to that event. Setting this bit means that
* we request the value from the host and change the guest memory
* balloon according to this value.
*/
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(VMMDevGetMemBalloonChangeRequest), VMMDevReq_GetMemBalloonChangeRequest);
if (RT_SUCCESS(rc))
{
pReq->header.fRequestor = pSession->fRequestor;
pReq->eventAck = VMMDEV_EVENT_BALLOON_CHANGE_REQUEST;
rc = VbglR0GRPerform(&pReq->header);
if (RT_SUCCESS(rc))
{
Assert(pDevExt->MemBalloon.cMaxChunks == pReq->cPhysMemChunks || pDevExt->MemBalloon.cMaxChunks == 0);
pDevExt->MemBalloon.cMaxChunks = pReq->cPhysMemChunks;
pInfo->u.Out.cBalloonChunks = pReq->cBalloonChunks;
pInfo->u.Out.fHandleInR3 = false;
pInfo->u.Out.afPadding[0] = false;
pInfo->u.Out.afPadding[1] = false;
pInfo->u.Out.afPadding[2] = false;
rc = vgdrvSetBalloonSizeKernel(pDevExt, pReq->cBalloonChunks, &pInfo->u.Out.fHandleInR3);
/* Ignore various out of memory failures. */
if ( rc == VERR_NO_MEMORY
|| rc == VERR_NO_PHYS_MEMORY
|| rc == VERR_NO_CONT_MEMORY)
rc = VINF_SUCCESS;
}
else
LogRel(("VBGL_IOCTL_CHECK_BALLOON: VbglR0GRPerform failed. rc=%Rrc\n", rc));
VbglR0GRFree(&pReq->header);
}
}
else
rc = VERR_PERMISSION_DENIED;
RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
LogFlow(("VBGL_IOCTL_CHECK_BALLOON returns %Rrc\n", rc));
return rc;
}
/**
* Handle a request for changing the memory balloon.
*
* @returns VBox status code.
*
* @param pDevExt The device extention.
* @param pSession The session.
* @param pInfo The change request structure (input).
*/
static int vgdrvIoCtl_ChangeMemoryBalloon(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCCHANGEBALLOON pInfo)
{
int rc;
LogFlow(("VBGL_IOCTL_CHANGE_BALLOON: fInflate=%RTbool u64ChunkAddr=%p\n", pInfo->u.In.fInflate, pInfo->u.In.pvChunk));
if ( pInfo->u.In.abPadding[0]
|| pInfo->u.In.abPadding[1]
|| pInfo->u.In.abPadding[2]
|| pInfo->u.In.abPadding[3]
|| pInfo->u.In.abPadding[4]
|| pInfo->u.In.abPadding[5]
|| pInfo->u.In.abPadding[6]
#if ARCH_BITS == 32
|| pInfo->u.In.abPadding[7]
|| pInfo->u.In.abPadding[8]
|| pInfo->u.In.abPadding[9]
#endif
)
{
Log(("VBGL_IOCTL_CHANGE_BALLOON: Padding isn't all zero: %.*Rhxs\n", sizeof(pInfo->u.In.abPadding), pInfo->u.In.abPadding));
return VERR_INVALID_PARAMETER;
}
rc = RTSemFastMutexRequest(pDevExt->MemBalloon.hMtx);
AssertRCReturn(rc, rc);
if (!pDevExt->MemBalloon.fUseKernelAPI)
{
/*
* The first user trying to query/change the balloon becomes the
* owner and owns it until the session is closed (vgdrvCloseMemBalloon).
*/
if ( pDevExt->MemBalloon.pOwner != pSession
&& pDevExt->MemBalloon.pOwner == NULL)
pDevExt->MemBalloon.pOwner = pSession;
if (pDevExt->MemBalloon.pOwner == pSession)
rc = vgdrvSetBalloonSizeFromUser(pDevExt, pSession, pInfo->u.In.pvChunk, pInfo->u.In.fInflate != false);
else
rc = VERR_PERMISSION_DENIED;
}
else
rc = VERR_PERMISSION_DENIED;
RTSemFastMutexRelease(pDevExt->MemBalloon.hMtx);
return rc;
}
/**
* Handle a request for writing a core dump of the guest on the host.
*
* @returns VBox status code.
*
* @param pDevExt The device extension.
* @param pSession The session.
* @param pInfo The output buffer.
*/
static int vgdrvIoCtl_WriteCoreDump(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCWRITECOREDUMP pInfo)
{
VMMDevReqWriteCoreDump *pReq = NULL;
int rc;
LogFlow(("VBOXGUEST_IOCTL_WRITE_CORE_DUMP\n"));
RT_NOREF1(pDevExt);
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_WriteCoreDump);
if (RT_SUCCESS(rc))
{
pReq->header.fRequestor = pSession->fRequestor;
pReq->fFlags = pInfo->u.In.fFlags;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
Log(("VBOXGUEST_IOCTL_WRITE_CORE_DUMP: VbglR0GRPerform failed, rc=%Rrc!\n", rc));
VbglR0GRFree(&pReq->header);
}
else
Log(("VBOXGUEST_IOCTL_WRITE_CORE_DUMP: failed to allocate %u (%#x) bytes to cache the request. rc=%Rrc!!\n",
sizeof(*pReq), sizeof(*pReq), rc));
return rc;
}
/**
* Guest backdoor logging.
*
* @returns VBox status code.
*
* @param pDevExt The device extension.
* @param pch The log message (need not be NULL terminated).
* @param cbData Size of the buffer.
* @param fUserSession Copy of VBOXGUESTSESSION::fUserSession for the
* call. True normal user, false root user.
*/
static int vgdrvIoCtl_Log(PVBOXGUESTDEVEXT pDevExt, const char *pch, size_t cbData, bool fUserSession)
{
if (pDevExt->fLoggingEnabled)
RTLogBackdoorPrintf("%.*s", cbData, pch);
else if (!fUserSession)
LogRel(("%.*s", cbData, pch));
else
Log(("%.*s", cbData, pch));
return VINF_SUCCESS;
}
/** @name Guest Capabilities, Mouse Status and Event Filter
* @{
*/
/**
* Clears a bit usage tracker (init time).
*
* @param pTracker The tracker to clear.
*/
static void vgdrvBitUsageTrackerClear(PVBOXGUESTBITUSAGETRACER pTracker)
{
uint32_t iBit;
AssertCompile(sizeof(pTracker->acPerBitUsage) == 32 * sizeof(uint32_t));
for (iBit = 0; iBit < 32; iBit++)
pTracker->acPerBitUsage[iBit] = 0;
pTracker->fMask = 0;
}
#ifdef VBOX_STRICT
/**
* Checks that pTracker->fMask is correct and that the usage values are within
* the valid range.
*
* @param pTracker The tracker.
* @param cMax Max valid usage value.
* @param pszWhat Identifies the tracker in assertions.
*/
static void vgdrvBitUsageTrackerCheckMask(PCVBOXGUESTBITUSAGETRACER pTracker, uint32_t cMax, const char *pszWhat)
{
uint32_t fMask = 0;
uint32_t iBit;
AssertCompile(sizeof(pTracker->acPerBitUsage) == 32 * sizeof(uint32_t));
for (iBit = 0; iBit < 32; iBit++)
if (pTracker->acPerBitUsage[iBit])
{
fMask |= RT_BIT_32(iBit);
AssertMsg(pTracker->acPerBitUsage[iBit] <= cMax,
("%s: acPerBitUsage[%u]=%#x cMax=%#x\n", pszWhat, iBit, pTracker->acPerBitUsage[iBit], cMax));
}
AssertMsg(fMask == pTracker->fMask, ("%s: %#x vs %#x\n", pszWhat, fMask, pTracker->fMask));
}
#endif
/**
* Applies a change to the bit usage tracker.
*
*
* @returns true if the mask changed, false if not.
* @param pTracker The bit usage tracker.
* @param fChanged The bits to change.
* @param fPrevious The previous value of the bits.
* @param cMax The max valid usage value for assertions.
* @param pszWhat Identifies the tracker in assertions.
*/
static bool vgdrvBitUsageTrackerChange(PVBOXGUESTBITUSAGETRACER pTracker, uint32_t fChanged, uint32_t fPrevious,
uint32_t cMax, const char *pszWhat)
{
bool fGlobalChange = false;
AssertCompile(sizeof(pTracker->acPerBitUsage) == 32 * sizeof(uint32_t));
while (fChanged)
{
uint32_t const iBit = ASMBitFirstSetU32(fChanged) - 1;
uint32_t const fBitMask = RT_BIT_32(iBit);
Assert(iBit < 32); Assert(fBitMask & fChanged);
if (fBitMask & fPrevious)
{
pTracker->acPerBitUsage[iBit] -= 1;
AssertMsg(pTracker->acPerBitUsage[iBit] <= cMax,
("%s: acPerBitUsage[%u]=%#x cMax=%#x\n", pszWhat, iBit, pTracker->acPerBitUsage[iBit], cMax));
if (pTracker->acPerBitUsage[iBit] == 0)
{
fGlobalChange = true;
pTracker->fMask &= ~fBitMask;
}
}
else
{
pTracker->acPerBitUsage[iBit] += 1;
AssertMsg(pTracker->acPerBitUsage[iBit] > 0 && pTracker->acPerBitUsage[iBit] <= cMax,
("pTracker->acPerBitUsage[%u]=%#x cMax=%#x\n", pszWhat, iBit, pTracker->acPerBitUsage[iBit], cMax));
if (pTracker->acPerBitUsage[iBit] == 1)
{
fGlobalChange = true;
pTracker->fMask |= fBitMask;
}
}
fChanged &= ~fBitMask;
}
#ifdef VBOX_STRICT
vgdrvBitUsageTrackerCheckMask(pTracker, cMax, pszWhat);
#endif
NOREF(pszWhat); NOREF(cMax);
return fGlobalChange;
}
/**
* Init and termination worker for resetting the (host) event filter on the host
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param fFixedEvents Fixed events (init time).
*/
static int vgdrvResetEventFilterOnHost(PVBOXGUESTDEVEXT pDevExt, uint32_t fFixedEvents)
{
VMMDevCtlGuestFilterMask *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_CtlGuestFilterMask);
if (RT_SUCCESS(rc))
{
pReq->u32NotMask = UINT32_MAX & ~fFixedEvents;
pReq->u32OrMask = fFixedEvents;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
LogRelFunc(("failed with rc=%Rrc\n", rc));
VbglR0GRFree(&pReq->header);
}
RT_NOREF1(pDevExt);
return rc;
}
/**
* Changes the event filter mask for the given session.
*
* This is called in response to VBGL_IOCTL_CHANGE_FILTER_MASK as well as to do
* session cleanup.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param fOrMask The events to add.
* @param fNotMask The events to remove.
* @param fSessionTermination Set if we're called by the session cleanup code.
* This tweaks the error handling so we perform
* proper session cleanup even if the host
* misbehaves.
*
* @remarks Takes the session spinlock.
*/
static int vgdrvSetSessionEventFilter(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination)
{
VMMDevCtlGuestFilterMask *pReq;
uint32_t fChanged;
uint32_t fPrevious;
int rc;
/*
* Preallocate a request buffer so we can do all in one go without leaving the spinlock.
*/
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_CtlGuestFilterMask);
if (RT_SUCCESS(rc))
{ /* nothing */ }
else if (!fSessionTermination)
{
LogRel(("vgdrvSetSessionFilterMask: VbglR0GRAlloc failure: %Rrc\n", rc));
return rc;
}
else
pReq = NULL; /* Ignore failure, we must do session cleanup. */
RTSpinlockAcquire(pDevExt->SessionSpinlock);
/*
* Apply the changes to the session mask.
*/
fPrevious = pSession->fEventFilter;
pSession->fEventFilter |= fOrMask;
pSession->fEventFilter &= ~fNotMask;
/*
* If anything actually changed, update the global usage counters.
*/
fChanged = fPrevious ^ pSession->fEventFilter;
LogFlow(("vgdrvSetSessionEventFilter: Session->fEventFilter: %#x -> %#x (changed %#x)\n",
fPrevious, pSession->fEventFilter, fChanged));
if (fChanged)
{
bool fGlobalChange = vgdrvBitUsageTrackerChange(&pDevExt->EventFilterTracker, fChanged, fPrevious,
pDevExt->cSessions, "EventFilterTracker");
/*
* If there are global changes, update the event filter on the host.
*/
if (fGlobalChange || pDevExt->fEventFilterHost == UINT32_MAX)
{
Assert(pReq || fSessionTermination);
if (pReq)
{
pReq->u32OrMask = pDevExt->fFixedEvents | pDevExt->EventFilterTracker.fMask;
if (pReq->u32OrMask == pDevExt->fEventFilterHost)
rc = VINF_SUCCESS;
else
{
pDevExt->fEventFilterHost = pReq->u32OrMask;
pReq->u32NotMask = ~pReq->u32OrMask;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
{
/*
* Failed, roll back (unless it's session termination time).
*/
pDevExt->fEventFilterHost = UINT32_MAX;
if (!fSessionTermination)
{
vgdrvBitUsageTrackerChange(&pDevExt->EventFilterTracker, fChanged, pSession->fEventFilter,
pDevExt->cSessions, "EventFilterTracker");
pSession->fEventFilter = fPrevious;
}
}
}
}
else
rc = VINF_SUCCESS;
}
}
RTSpinlockRelease(pDevExt->SessionSpinlock);
if (pReq)
VbglR0GRFree(&pReq->header);
return rc;
}
/**
* Handle VBGL_IOCTL_CHANGE_FILTER_MASK.
*
* @returns VBox status code.
*
* @param pDevExt The device extension.
* @param pSession The session.
* @param pInfo The request.
*/
static int vgdrvIoCtl_ChangeFilterMask(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCCHANGEFILTERMASK pInfo)
{
LogFlow(("VBGL_IOCTL_CHANGE_FILTER_MASK: or=%#x not=%#x\n", pInfo->u.In.fOrMask, pInfo->u.In.fNotMask));
if ((pInfo->u.In.fOrMask | pInfo->u.In.fNotMask) & ~VMMDEV_EVENT_VALID_EVENT_MASK)
{
Log(("VBGL_IOCTL_CHANGE_FILTER_MASK: or=%#x not=%#x: Invalid masks!\n", pInfo->u.In.fOrMask, pInfo->u.In.fNotMask));
return VERR_INVALID_PARAMETER;
}
return vgdrvSetSessionEventFilter(pDevExt, pSession, pInfo->u.In.fOrMask, pInfo->u.In.fNotMask, false /*fSessionTermination*/);
}
/**
* Init and termination worker for set mouse feature status to zero on the host.
*
* @returns VBox status code.
* @param pDevExt The device extension.
*/
static int vgdrvResetMouseStatusOnHost(PVBOXGUESTDEVEXT pDevExt)
{
VMMDevReqMouseStatus *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetMouseStatus);
if (RT_SUCCESS(rc))
{
pReq->mouseFeatures = 0;
pReq->pointerXPos = 0;
pReq->pointerYPos = 0;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
LogRelFunc(("failed with rc=%Rrc\n", rc));
VbglR0GRFree(&pReq->header);
}
RT_NOREF1(pDevExt);
return rc;
}
/**
* Changes the mouse status mask for the given session.
*
* This is called in response to VBOXGUEST_IOCTL_SET_MOUSE_STATUS as well as to
* do session cleanup.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param fOrMask The status flags to add.
* @param fNotMask The status flags to remove.
* @param fSessionTermination Set if we're called by the session cleanup code.
* This tweaks the error handling so we perform
* proper session cleanup even if the host
* misbehaves.
*
* @remarks Takes the session spinlock.
*/
static int vgdrvSetSessionMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, bool fSessionTermination)
{
VMMDevReqMouseStatus *pReq;
uint32_t fChanged;
uint32_t fPrevious;
int rc;
/*
* Preallocate a request buffer so we can do all in one go without leaving the spinlock.
*/
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetMouseStatus);
if (RT_SUCCESS(rc))
{
if (!fSessionTermination)
pReq->header.fRequestor = pSession->fRequestor;
}
else if (!fSessionTermination)
{
LogRel(("vgdrvSetSessionMouseStatus: VbglR0GRAlloc failure: %Rrc\n", rc));
return rc;
}
else
pReq = NULL; /* Ignore failure, we must do session cleanup. */
RTSpinlockAcquire(pDevExt->SessionSpinlock);
/*
* Apply the changes to the session mask.
*/
fPrevious = pSession->fMouseStatus;
pSession->fMouseStatus |= fOrMask;
pSession->fMouseStatus &= ~fNotMask;
/*
* If anything actually changed, update the global usage counters.
*/
fChanged = fPrevious ^ pSession->fMouseStatus;
if (fChanged)
{
bool fGlobalChange = vgdrvBitUsageTrackerChange(&pDevExt->MouseStatusTracker, fChanged, fPrevious,
pDevExt->cSessions, "MouseStatusTracker");
/*
* If there are global changes, update the event filter on the host.
*/
if (fGlobalChange || pDevExt->fMouseStatusHost == UINT32_MAX)
{
Assert(pReq || fSessionTermination);
if (pReq)
{
pReq->mouseFeatures = pDevExt->MouseStatusTracker.fMask;
if (pReq->mouseFeatures == pDevExt->fMouseStatusHost)
rc = VINF_SUCCESS;
else
{
pDevExt->fMouseStatusHost = pReq->mouseFeatures;
pReq->pointerXPos = 0;
pReq->pointerYPos = 0;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
{
/*
* Failed, roll back (unless it's session termination time).
*/
pDevExt->fMouseStatusHost = UINT32_MAX;
if (!fSessionTermination)
{
vgdrvBitUsageTrackerChange(&pDevExt->MouseStatusTracker, fChanged, pSession->fMouseStatus,
pDevExt->cSessions, "MouseStatusTracker");
pSession->fMouseStatus = fPrevious;
}
}
}
}
else
rc = VINF_SUCCESS;
}
}
RTSpinlockRelease(pDevExt->SessionSpinlock);
if (pReq)
VbglR0GRFree(&pReq->header);
return rc;
}
/**
* Sets the mouse status features for this session and updates them globally.
*
* @returns VBox status code.
*
* @param pDevExt The device extention.
* @param pSession The session.
* @param fFeatures New bitmap of enabled features.
*/
static int vgdrvIoCtl_SetMouseStatus(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, uint32_t fFeatures)
{
LogFlow(("VBGL_IOCTL_SET_MOUSE_STATUS: features=%#x\n", fFeatures));
if (fFeatures & ~VMMDEV_MOUSE_GUEST_MASK)
return VERR_INVALID_PARAMETER;
return vgdrvSetSessionMouseStatus(pDevExt, pSession, fFeatures, ~fFeatures, false /*fSessionTermination*/);
}
/**
* Return the mask of VMM device events that this session is allowed to see (wrt
* to "acquire" mode guest capabilities).
*
* The events associated with guest capabilities in "acquire" mode will be
* restricted to sessions which has acquired the respective capabilities.
* If someone else tries to wait for acquired events, they won't be woken up
* when the event becomes pending. Should some other thread in the session
* acquire the capability while the corresponding event is pending, the waiting
* thread will woken up.
*
* @returns Mask of events valid for the given session.
* @param pDevExt The device extension.
* @param pSession The session.
*
* @remarks Needs only be called when dispatching events in the
* VBOXGUEST_ACQUIRE_STYLE_EVENTS mask.
*/
static uint32_t vgdrvGetAllowedEventMaskForSession(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession)
{
uint32_t fAcquireModeGuestCaps;
uint32_t fAcquiredGuestCaps;
uint32_t fAllowedEvents;
/*
* Note! Reads pSession->fAcquiredGuestCaps and pDevExt->fAcquireModeGuestCaps
* WITHOUT holding VBOXGUESTDEVEXT::SessionSpinlock.
*/
fAcquireModeGuestCaps = ASMAtomicUoReadU32(&pDevExt->fAcquireModeGuestCaps);
if (fAcquireModeGuestCaps == 0)
return VMMDEV_EVENT_VALID_EVENT_MASK;
fAcquiredGuestCaps = ASMAtomicUoReadU32(&pSession->fAcquiredGuestCaps);
/*
* Calculate which events to allow according to the cap config and caps
* acquired by the session.
*/
fAllowedEvents = VMMDEV_EVENT_VALID_EVENT_MASK;
if ( !(fAcquiredGuestCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS)
&& (fAcquireModeGuestCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS))
fAllowedEvents &= ~VMMDEV_EVENT_DISPLAY_CHANGE_REQUEST;
if ( !(fAcquiredGuestCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS)
&& (fAcquireModeGuestCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS))
fAllowedEvents &= ~VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST;
return fAllowedEvents;
}
/**
* Init and termination worker for set guest capabilities to zero on the host.
*
* @returns VBox status code.
* @param pDevExt The device extension.
*/
static int vgdrvResetCapabilitiesOnHost(PVBOXGUESTDEVEXT pDevExt)
{
VMMDevReqGuestCapabilities2 *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
if (RT_SUCCESS(rc))
{
pReq->u32NotMask = UINT32_MAX;
pReq->u32OrMask = 0;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
LogRelFunc(("failed with rc=%Rrc\n", rc));
VbglR0GRFree(&pReq->header);
}
RT_NOREF1(pDevExt);
return rc;
}
/**
* Sets the guest capabilities to the host while holding the lock.
*
* This will ASSUME that we're the ones in charge of the mask, so
* we'll simply clear all bits we don't set.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param pReq The request.
*/
static int vgdrvUpdateCapabilitiesOnHostWithReqAndLock(PVBOXGUESTDEVEXT pDevExt, VMMDevReqGuestCapabilities2 *pReq)
{
int rc;
pReq->u32OrMask = pDevExt->fAcquiredGuestCaps | pDevExt->SetGuestCapsTracker.fMask;
if (pReq->u32OrMask == pDevExt->fGuestCapsHost)
rc = VINF_SUCCESS;
else
{
pDevExt->fGuestCapsHost = pReq->u32OrMask;
pReq->u32NotMask = ~pReq->u32OrMask;
rc = VbglR0GRPerform(&pReq->header);
if (RT_FAILURE(rc))
pDevExt->fGuestCapsHost = UINT32_MAX;
}
return rc;
}
/**
* Switch a set of capabilities into "acquire" mode and (maybe) acquire them for
* the given session.
*
* This is called in response to VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE as well as
* to do session cleanup.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param fOrMask The capabilities to add .
* @param fNotMask The capabilities to remove. Ignored in
* VBOXGUESTCAPSACQUIRE_FLAGS_CONFIG_ACQUIRE_MODE.
* @param fFlags Confusing operation modifier.
* VBOXGUESTCAPSACQUIRE_FLAGS_NONE means to both
* configure and acquire/release the capabilities.
* VBOXGUESTCAPSACQUIRE_FLAGS_CONFIG_ACQUIRE_MODE
* means only configure capabilities in the
* @a fOrMask capabilities for "acquire" mode.
* @param fSessionTermination Set if we're called by the session cleanup code.
* This tweaks the error handling so we perform
* proper session cleanup even if the host
* misbehaves.
*
* @remarks Takes both the session and event spinlocks.
*/
static int vgdrvAcquireSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, uint32_t fFlags,
bool fSessionTermination)
{
uint32_t fCurrentOwnedCaps;
uint32_t fSessionRemovedCaps;
uint32_t fSessionAddedCaps;
uint32_t fOtherConflictingCaps;
VMMDevReqGuestCapabilities2 *pReq = NULL;
int rc;
/*
* Validate and adjust input.
*/
if (fOrMask & ~( VMMDEV_GUEST_SUPPORTS_SEAMLESS
| VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING
| VMMDEV_GUEST_SUPPORTS_GRAPHICS ) )
{
LogRel(("vgdrvAcquireSessionCapabilities: invalid fOrMask=%#x (pSession=%p fNotMask=%#x fFlags=%#x)\n",
fOrMask, pSession, fNotMask, fFlags));
return VERR_INVALID_PARAMETER;
}
if ((fFlags & ~VBGL_IOC_AGC_FLAGS_VALID_MASK) != 0)
{
LogRel(("vgdrvAcquireSessionCapabilities: invalid fFlags=%#x (pSession=%p fOrMask=%#x fNotMask=%#x)\n",
fFlags, pSession, fOrMask, fNotMask));
return VERR_INVALID_PARAMETER;
}
Assert(!fOrMask || !fSessionTermination);
/* The fNotMask no need to have all values valid, invalid ones will simply be ignored. */
fNotMask &= ~fOrMask;
/*
* Preallocate a update request if we're about to do more than just configure
* the capability mode.
*/
if (!(fFlags & VBGL_IOC_AGC_FLAGS_CONFIG_ACQUIRE_MODE))
{
rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
if (RT_SUCCESS(rc))
{
if (!fSessionTermination)
pReq->header.fRequestor = pSession->fRequestor;
}
else if (!fSessionTermination)
{
LogRel(("vgdrvAcquireSessionCapabilities: pSession=%p fOrMask=%#x fNotMask=%#x fFlags=%#x: VbglR0GRAlloc failure: %Rrc\n",
pSession, fOrMask, fNotMask, fFlags, rc));
return rc;
}
else
pReq = NULL; /* Ignore failure, we must do session cleanup. */
}
/*
* Try switch the capabilities in the OR mask into "acquire" mode.
*
* Note! We currently ignore anyone which may already have "set" the capabilities
* in fOrMask. Perhaps not the best way to handle it, but it's simple...
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
if (!(pDevExt->fSetModeGuestCaps & fOrMask))
pDevExt->fAcquireModeGuestCaps |= fOrMask;
else
{
RTSpinlockRelease(pDevExt->EventSpinlock);
if (pReq)
VbglR0GRFree(&pReq->header);
AssertMsgFailed(("Trying to change caps mode: %#x\n", fOrMask));
LogRel(("vgdrvAcquireSessionCapabilities: pSession=%p fOrMask=%#x fNotMask=%#x fFlags=%#x: calling caps acquire for set caps\n",
pSession, fOrMask, fNotMask, fFlags));
return VERR_INVALID_STATE;
}
/*
* If we only wanted to switch the capabilities into "acquire" mode, we're done now.
*/
if (fFlags & VBGL_IOC_AGC_FLAGS_CONFIG_ACQUIRE_MODE)
{
RTSpinlockRelease(pDevExt->EventSpinlock);
Assert(!pReq);
Log(("vgdrvAcquireSessionCapabilities: pSession=%p fOrMask=%#x fNotMask=%#x fFlags=%#x: configured acquire caps: 0x%x\n",
pSession, fOrMask, fNotMask, fFlags));
return VINF_SUCCESS;
}
Assert(pReq || fSessionTermination);
/*
* Caller wants to acquire/release the capabilities too.
*
* Note! The mode change of the capabilities above won't be reverted on
* failure, this is intentional.
*/
fCurrentOwnedCaps = pSession->fAcquiredGuestCaps;
fSessionRemovedCaps = fCurrentOwnedCaps & fNotMask;
fSessionAddedCaps = fOrMask & ~fCurrentOwnedCaps;
fOtherConflictingCaps = pDevExt->fAcquiredGuestCaps & ~fCurrentOwnedCaps;
fOtherConflictingCaps &= fSessionAddedCaps;
if (!fOtherConflictingCaps)
{
if (fSessionAddedCaps)
{
pSession->fAcquiredGuestCaps |= fSessionAddedCaps;
pDevExt->fAcquiredGuestCaps |= fSessionAddedCaps;
}
if (fSessionRemovedCaps)
{
pSession->fAcquiredGuestCaps &= ~fSessionRemovedCaps;
pDevExt->fAcquiredGuestCaps &= ~fSessionRemovedCaps;
}
/*
* If something changes (which is very likely), tell the host.
*/
if (fSessionAddedCaps || fSessionRemovedCaps || pDevExt->fGuestCapsHost == UINT32_MAX)
{
Assert(pReq || fSessionTermination);
if (pReq)
{
rc = vgdrvUpdateCapabilitiesOnHostWithReqAndLock(pDevExt, pReq);
if (RT_FAILURE(rc) && !fSessionTermination)
{
/* Failed, roll back. */
if (fSessionAddedCaps)
{
pSession->fAcquiredGuestCaps &= ~fSessionAddedCaps;
pDevExt->fAcquiredGuestCaps &= ~fSessionAddedCaps;
}
if (fSessionRemovedCaps)
{
pSession->fAcquiredGuestCaps |= fSessionRemovedCaps;
pDevExt->fAcquiredGuestCaps |= fSessionRemovedCaps;
}
RTSpinlockRelease(pDevExt->EventSpinlock);
LogRel(("vgdrvAcquireSessionCapabilities: vgdrvUpdateCapabilitiesOnHostWithReqAndLock failed: rc=%Rrc\n", rc));
VbglR0GRFree(&pReq->header);
return rc;
}
}
}
}
else
{
RTSpinlockRelease(pDevExt->EventSpinlock);
Log(("vgdrvAcquireSessionCapabilities: Caps %#x were busy\n", fOtherConflictingCaps));
VbglR0GRFree(&pReq->header);
return VERR_RESOURCE_BUSY;
}
RTSpinlockRelease(pDevExt->EventSpinlock);
if (pReq)
VbglR0GRFree(&pReq->header);
/*
* If we added a capability, check if that means some other thread in our
* session should be unblocked because there are events pending.
*
* HACK ALERT! When the seamless support capability is added we generate a
* seamless change event so that the ring-3 client can sync with
* the seamless state. Although this introduces a spurious
* wakeups of the ring-3 client, it solves the problem of client
* state inconsistency in multiuser environment (on Windows).
*/
if (fSessionAddedCaps)
{
uint32_t fGenFakeEvents = 0;
if (fSessionAddedCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS)
fGenFakeEvents |= VMMDEV_EVENT_SEAMLESS_MODE_CHANGE_REQUEST;
RTSpinlockAcquire(pDevExt->EventSpinlock);
if (fGenFakeEvents || pDevExt->f32PendingEvents)
vgdrvDispatchEventsLocked(pDevExt, fGenFakeEvents);
RTSpinlockRelease(pDevExt->EventSpinlock);
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
VGDrvCommonWaitDoWakeUps(pDevExt);
#endif
}
return VINF_SUCCESS;
}
/**
* Handle VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES.
*
* @returns VBox status code.
*
* @param pDevExt The device extension.
* @param pSession The session.
* @param pAcquire The request.
*/
static int vgdrvIoCtl_GuestCapsAcquire(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCACQUIREGUESTCAPS pAcquire)
{
int rc;
LogFlow(("VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES: or=%#x not=%#x flags=%#x\n",
pAcquire->u.In.fOrMask, pAcquire->u.In.fNotMask, pAcquire->u.In.fFlags));
rc = vgdrvAcquireSessionCapabilities(pDevExt, pSession, pAcquire->u.In.fOrMask, pAcquire->u.In.fNotMask,
pAcquire->u.In.fFlags, false /*fSessionTermination*/);
if (RT_FAILURE(rc))
LogRel(("VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES failed rc=%Rrc\n", rc));
return rc;
}
/**
* Sets the guest capabilities for a session.
*
* @returns VBox status code.
* @param pDevExt The device extension.
* @param pSession The session.
* @param fOrMask The capabilities to add.
* @param fNotMask The capabilities to remove.
* @param pfSessionCaps Where to return the guest capabilities reported
* for this session. Optional.
* @param pfGlobalCaps Where to return the guest capabilities reported
* for all the sessions. Optional.
*
* @param fSessionTermination Set if we're called by the session cleanup code.
* This tweaks the error handling so we perform
* proper session cleanup even if the host
* misbehaves.
*
* @remarks Takes the session spinlock.
*/
static int vgdrvSetSessionCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
uint32_t fOrMask, uint32_t fNotMask, uint32_t *pfSessionCaps, uint32_t *pfGlobalCaps,
bool fSessionTermination)
{
/*
* Preallocate a request buffer so we can do all in one go without leaving the spinlock.
*/
VMMDevReqGuestCapabilities2 *pReq;
int rc = VbglR0GRAlloc((VMMDevRequestHeader **)&pReq, sizeof(*pReq), VMMDevReq_SetGuestCapabilities);
if (RT_SUCCESS(rc))
{
if (!fSessionTermination)
pReq->header.fRequestor = pSession->fRequestor;
}
else if (!fSessionTermination)
{
if (pfSessionCaps)
*pfSessionCaps = UINT32_MAX;
if (pfGlobalCaps)
*pfGlobalCaps = UINT32_MAX;
LogRel(("vgdrvSetSessionCapabilities: VbglR0GRAlloc failure: %Rrc\n", rc));
return rc;
}
else
pReq = NULL; /* Ignore failure, we must do session cleanup. */
RTSpinlockAcquire(pDevExt->SessionSpinlock);
#ifndef VBOXGUEST_DISREGARD_ACQUIRE_MODE_GUEST_CAPS
/*
* Capabilities in "acquire" mode cannot be set via this API.
* (Acquire mode is only used on windows at the time of writing.)
*/
if (!(fOrMask & pDevExt->fAcquireModeGuestCaps))
#endif
{
/*
* Apply the changes to the session mask.
*/
uint32_t fChanged;
uint32_t fPrevious = pSession->fCapabilities;
pSession->fCapabilities |= fOrMask;
pSession->fCapabilities &= ~fNotMask;
/*
* If anything actually changed, update the global usage counters.
*/
fChanged = fPrevious ^ pSession->fCapabilities;
if (fChanged)
{
bool fGlobalChange = vgdrvBitUsageTrackerChange(&pDevExt->SetGuestCapsTracker, fChanged, fPrevious,
pDevExt->cSessions, "SetGuestCapsTracker");
/*
* If there are global changes, update the capabilities on the host.
*/
if (fGlobalChange || pDevExt->fGuestCapsHost == UINT32_MAX)
{
Assert(pReq || fSessionTermination);
if (pReq)
{
rc = vgdrvUpdateCapabilitiesOnHostWithReqAndLock(pDevExt, pReq);
/* On failure, roll back (unless it's session termination time). */
if (RT_FAILURE(rc) && !fSessionTermination)
{
vgdrvBitUsageTrackerChange(&pDevExt->SetGuestCapsTracker, fChanged, pSession->fCapabilities,
pDevExt->cSessions, "SetGuestCapsTracker");
pSession->fCapabilities = fPrevious;
}
}
}
}
}
#ifndef VBOXGUEST_DISREGARD_ACQUIRE_MODE_GUEST_CAPS
else
rc = VERR_RESOURCE_BUSY;
#endif
if (pfSessionCaps)
*pfSessionCaps = pSession->fCapabilities;
if (pfGlobalCaps)
*pfGlobalCaps = pDevExt->fAcquiredGuestCaps | pDevExt->SetGuestCapsTracker.fMask;
RTSpinlockRelease(pDevExt->SessionSpinlock);
if (pReq)
VbglR0GRFree(&pReq->header);
return rc;
}
/**
* Handle VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES.
*
* @returns VBox status code.
*
* @param pDevExt The device extension.
* @param pSession The session.
* @param pInfo The request.
*/
static int vgdrvIoCtl_SetCapabilities(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLIOCSETGUESTCAPS pInfo)
{
int rc;
LogFlow(("VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES: or=%#x not=%#x\n", pInfo->u.In.fOrMask, pInfo->u.In.fNotMask));
if (!((pInfo->u.In.fOrMask | pInfo->u.In.fNotMask) & ~VMMDEV_GUEST_CAPABILITIES_MASK))
rc = vgdrvSetSessionCapabilities(pDevExt, pSession, pInfo->u.In.fOrMask, pInfo->u.In.fNotMask,
&pInfo->u.Out.fSessionCaps, &pInfo->u.Out.fGlobalCaps, false /*fSessionTermination*/);
else
rc = VERR_INVALID_PARAMETER;
return rc;
}
/** @} */
/**
* Common IOCtl for user to kernel and kernel to kernel communication.
*
* This function only does the basic validation and then invokes
* worker functions that takes care of each specific function.
*
* @returns VBox status code.
*
* @param iFunction The requested function.
* @param pDevExt The device extension.
* @param pSession The client session.
* @param pReqHdr Pointer to the request. This always starts with
* a request common header.
* @param cbReq The max size of the request buffer.
*/
int VGDrvCommonIoCtl(uintptr_t iFunction, PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PVBGLREQHDR pReqHdr, size_t cbReq)
{
uintptr_t const iFunctionStripped = VBGL_IOCTL_CODE_STRIPPED(iFunction);
int rc;
LogFlow(("VGDrvCommonIoCtl: iFunction=%#x pDevExt=%p pSession=%p pReqHdr=%p cbReq=%zu\n",
iFunction, pDevExt, pSession, pReqHdr, cbReq));
/*
* Define some helper macros to simplify validation.
*/
#define REQ_CHECK_SIZES_EX(Name, cbInExpect, cbOutExpect) \
do { \
if (RT_LIKELY( pReqHdr->cbIn == (cbInExpect) \
&& ( pReqHdr->cbOut == (cbOutExpect) \
|| ((cbInExpect) == (cbOutExpect) && pReqHdr->cbOut == 0) ) )) \
{ /* likely */ } \
else \
{ \
Log(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld. cbOut=%ld expected %ld.\n", \
(long)pReqHdr->cbIn, (long)(cbInExpect), (long)pReqHdr->cbOut, (long)(cbOutExpect))); \
return pReqHdr->rc = VERR_INVALID_PARAMETER; \
} \
} while (0)
#define REQ_CHECK_SIZES(Name) REQ_CHECK_SIZES_EX(Name, Name ## _SIZE_IN, Name ## _SIZE_OUT)
#define REQ_CHECK_SIZE_IN(Name, cbInExpect) \
do { \
if (RT_LIKELY(pReqHdr->cbIn == (cbInExpect))) \
{ /* likely */ } \
else \
{ \
Log(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld.\n", \
(long)pReqHdr->cbIn, (long)(cbInExpect))); \
return pReqHdr->rc = VERR_INVALID_PARAMETER; \
} \
} while (0)
#define REQ_CHECK_SIZE_OUT(Name, cbOutExpect) \
do { \
if (RT_LIKELY( pReqHdr->cbOut == (cbOutExpect) \
|| (pReqHdr->cbOut == 0 && pReqHdr->cbIn == (cbOutExpect)))) \
{ /* likely */ } \
else \
{ \
Log(( #Name ": Invalid input/output sizes. cbOut=%ld (%ld) expected %ld.\n", \
(long)pReqHdr->cbOut, (long)pReqHdr->cbIn, (long)(cbOutExpect))); \
return pReqHdr->rc = VERR_INVALID_PARAMETER; \
} \
} while (0)
#define REQ_CHECK_EXPR(Name, expr) \
do { \
if (RT_LIKELY(!!(expr))) \
{ /* likely */ } \
else \
{ \
Log(( #Name ": %s\n", #expr)); \
return pReqHdr->rc = VERR_INVALID_PARAMETER; \
} \
} while (0)
#define REQ_CHECK_EXPR_FMT(expr, fmt) \
do { \
if (RT_LIKELY(!!(expr))) \
{ /* likely */ } \
else \
{ \
Log( fmt ); \
return pReqHdr->rc = VERR_INVALID_PARAMETER; \
} \
} while (0)
#define REQ_CHECK_RING0(mnemonic) \
do { \
if (pSession->R0Process != NIL_RTR0PROCESS) \
{ \
LogFunc((mnemonic ": Ring-0 only, caller is %RTproc/%p\n", \
pSession->Process, (uintptr_t)pSession->R0Process)); \
return pReqHdr->rc = VERR_PERMISSION_DENIED; \
} \
} while (0)
/*
* Validate the request.
*/
if (RT_LIKELY(cbReq >= sizeof(*pReqHdr)))
{ /* likely */ }
else
{
Log(("VGDrvCommonIoCtl: Bad ioctl request size; cbReq=%#lx\n", (long)cbReq));
return VERR_INVALID_PARAMETER;
}
if (pReqHdr->cbOut == 0)
pReqHdr->cbOut = pReqHdr->cbIn;
if (RT_LIKELY( pReqHdr->uVersion == VBGLREQHDR_VERSION
&& pReqHdr->cbIn >= sizeof(*pReqHdr)
&& pReqHdr->cbIn <= cbReq
&& pReqHdr->cbOut >= sizeof(*pReqHdr)
&& pReqHdr->cbOut <= cbReq))
{ /* likely */ }
else
{
Log(("VGDrvCommonIoCtl: Bad ioctl request header; cbIn=%#lx cbOut=%#lx version=%#lx\n",
(long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->uVersion));
return VERR_INVALID_PARAMETER;
}
if (RT_LIKELY(RT_VALID_PTR(pSession)))
{ /* likely */ }
else
{
Log(("VGDrvCommonIoCtl: Invalid pSession value %p (ioctl=%#x)\n", pSession, iFunction));
return VERR_INVALID_PARAMETER;
}
/*
* Deal with variably sized requests first.
*/
rc = VINF_SUCCESS;
if ( iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_VMMDEV_REQUEST(0))
|| iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_VMMDEV_REQUEST_BIG) )
{
REQ_CHECK_EXPR(VBGL_IOCTL_VMMDEV_REQUEST, pReqHdr->uType != VBGLREQHDR_TYPE_DEFAULT);
REQ_CHECK_EXPR_FMT(pReqHdr->cbIn == pReqHdr->cbOut,
("VBGL_IOCTL_VMMDEV_REQUEST: cbIn=%ld != cbOut=%ld\n", (long)pReqHdr->cbIn, (long)pReqHdr->cbOut));
pReqHdr->rc = vgdrvIoCtl_VMMDevRequest(pDevExt, pSession, (VMMDevRequestHeader *)pReqHdr, cbReq);
}
else if (RT_LIKELY(pReqHdr->uType == VBGLREQHDR_TYPE_DEFAULT))
{
if (iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_LOG(0)))
{
REQ_CHECK_SIZE_OUT(VBGL_IOCTL_LOG, VBGL_IOCTL_LOG_SIZE_OUT);
pReqHdr->rc = vgdrvIoCtl_Log(pDevExt, &((PVBGLIOCLOG)pReqHdr)->u.In.szMsg[0], pReqHdr->cbIn - sizeof(VBGLREQHDR),
pSession->fUserSession);
}
#ifdef VBOX_WITH_HGCM
else if (iFunction == VBGL_IOCTL_IDC_HGCM_FAST_CALL) /* (is variable size, but we don't bother encoding it) */
{
REQ_CHECK_RING0("VBGL_IOCTL_IDC_HGCM_FAST_CALL");
REQ_CHECK_EXPR(VBGL_IOCTL_IDC_HGCM_FAST_CALL, cbReq >= sizeof(VBGLIOCIDCHGCMFASTCALL) + sizeof(VMMDevHGCMCall));
vgdrvIoCtl_HGCMFastCall(pDevExt, (VBGLIOCIDCHGCMFASTCALL volatile *)pReqHdr);
}
else if ( iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL(0))
# if ARCH_BITS == 64
|| iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL_32(0))
# endif
)
{
REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn >= sizeof(VBGLIOCHGCMCALL));
REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn == pReqHdr->cbOut);
pReqHdr->rc = vgdrvIoCtl_HGCMCallWrapper(pDevExt, pSession, (PVBGLIOCHGCMCALL)pReqHdr,
iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL_32(0)),
false /*fUserData*/, cbReq);
}
else if (iFunctionStripped == VBGL_IOCTL_CODE_STRIPPED(VBGL_IOCTL_HGCM_CALL_WITH_USER_DATA(0)))
{
REQ_CHECK_RING0("VBGL_IOCTL_HGCM_CALL_WITH_USER_DATA");
REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn >= sizeof(VBGLIOCHGCMCALL));
REQ_CHECK_EXPR(VBGL_IOCTL_HGCM_CALL, pReqHdr->cbIn == pReqHdr->cbOut);
pReqHdr->rc = vgdrvIoCtl_HGCMCallWrapper(pDevExt, pSession, (PVBGLIOCHGCMCALL)pReqHdr,
ARCH_BITS == 32, true /*fUserData*/, cbReq);
}
#endif /* VBOX_WITH_HGCM */
else
{
switch (iFunction)
{
/*
* Ring-0 only:
*/
case VBGL_IOCTL_IDC_CONNECT:
REQ_CHECK_RING0("VBGL_IOCL_IDC_CONNECT");
REQ_CHECK_SIZES(VBGL_IOCTL_IDC_CONNECT);
pReqHdr->rc = vgdrvIoCtl_IdcConnect(pDevExt, pSession, (PVBGLIOCIDCCONNECT)pReqHdr);
break;
case VBGL_IOCTL_IDC_DISCONNECT:
REQ_CHECK_RING0("VBGL_IOCTL_IDC_DISCONNECT");
REQ_CHECK_SIZES(VBGL_IOCTL_IDC_DISCONNECT);
pReqHdr->rc = vgdrvIoCtl_IdcDisconnect(pDevExt, pSession, (PVBGLIOCIDCDISCONNECT)pReqHdr);
break;
case VBGL_IOCTL_GET_VMMDEV_IO_INFO:
REQ_CHECK_RING0("GET_VMMDEV_IO_INFO");
REQ_CHECK_SIZES(VBGL_IOCTL_GET_VMMDEV_IO_INFO);
pReqHdr->rc = vgdrvIoCtl_GetVMMDevIoInfo(pDevExt, (PVBGLIOCGETVMMDEVIOINFO)pReqHdr);
break;
case VBGL_IOCTL_SET_MOUSE_NOTIFY_CALLBACK:
REQ_CHECK_RING0("SET_MOUSE_NOTIFY_CALLBACK");
REQ_CHECK_SIZES(VBGL_IOCTL_SET_MOUSE_NOTIFY_CALLBACK);
pReqHdr->rc = vgdrvIoCtl_SetMouseNotifyCallback(pDevExt, (PVBGLIOCSETMOUSENOTIFYCALLBACK)pReqHdr);
break;
/*
* Ring-3 only:
*/
case VBGL_IOCTL_DRIVER_VERSION_INFO:
REQ_CHECK_SIZES(VBGL_IOCTL_DRIVER_VERSION_INFO);
pReqHdr->rc = vgdrvIoCtl_DriverVersionInfo(pDevExt, pSession, (PVBGLIOCDRIVERVERSIONINFO)pReqHdr);
break;
/*
* Both ring-3 and ring-0:
*/
case VBGL_IOCTL_WAIT_FOR_EVENTS:
REQ_CHECK_SIZES(VBGL_IOCTL_WAIT_FOR_EVENTS);
pReqHdr->rc = vgdrvIoCtl_WaitForEvents(pDevExt, pSession, (VBGLIOCWAITFOREVENTS *)pReqHdr,
pSession->R0Process != NIL_RTR0PROCESS);
break;
case VBGL_IOCTL_INTERRUPT_ALL_WAIT_FOR_EVENTS:
REQ_CHECK_SIZES(VBGL_IOCTL_INTERRUPT_ALL_WAIT_FOR_EVENTS);
pReqHdr->rc = vgdrvIoCtl_CancelAllWaitEvents(pDevExt, pSession);
break;
case VBGL_IOCTL_CHANGE_FILTER_MASK:
REQ_CHECK_SIZES(VBGL_IOCTL_CHANGE_FILTER_MASK);
pReqHdr->rc = vgdrvIoCtl_ChangeFilterMask(pDevExt, pSession, (PVBGLIOCCHANGEFILTERMASK)pReqHdr);
break;
#ifdef VBOX_WITH_HGCM
case VBGL_IOCTL_HGCM_CONNECT:
REQ_CHECK_SIZES(VBGL_IOCTL_HGCM_CONNECT);
pReqHdr->rc = vgdrvIoCtl_HGCMConnect(pDevExt, pSession, (PVBGLIOCHGCMCONNECT)pReqHdr);
break;
case VBGL_IOCTL_HGCM_DISCONNECT:
REQ_CHECK_SIZES(VBGL_IOCTL_HGCM_DISCONNECT);
pReqHdr->rc = vgdrvIoCtl_HGCMDisconnect(pDevExt, pSession, (PVBGLIOCHGCMDISCONNECT)pReqHdr);
break;
#endif
case VBGL_IOCTL_CHECK_BALLOON:
REQ_CHECK_SIZES(VBGL_IOCTL_CHECK_BALLOON);
pReqHdr->rc = vgdrvIoCtl_CheckMemoryBalloon(pDevExt, pSession, (PVBGLIOCCHECKBALLOON)pReqHdr);
break;
case VBGL_IOCTL_CHANGE_BALLOON:
REQ_CHECK_SIZES(VBGL_IOCTL_CHANGE_BALLOON);
pReqHdr->rc = vgdrvIoCtl_ChangeMemoryBalloon(pDevExt, pSession, (PVBGLIOCCHANGEBALLOON)pReqHdr);
break;
case VBGL_IOCTL_WRITE_CORE_DUMP:
REQ_CHECK_SIZES(VBGL_IOCTL_WRITE_CORE_DUMP);
pReqHdr->rc = vgdrvIoCtl_WriteCoreDump(pDevExt, pSession, (PVBGLIOCWRITECOREDUMP)pReqHdr);
break;
case VBGL_IOCTL_SET_MOUSE_STATUS:
REQ_CHECK_SIZES(VBGL_IOCTL_SET_MOUSE_STATUS);
pReqHdr->rc = vgdrvIoCtl_SetMouseStatus(pDevExt, pSession, ((PVBGLIOCSETMOUSESTATUS)pReqHdr)->u.In.fStatus);
break;
case VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES:
REQ_CHECK_SIZES(VBGL_IOCTL_ACQUIRE_GUEST_CAPABILITIES);
pReqHdr->rc = vgdrvIoCtl_GuestCapsAcquire(pDevExt, pSession, (PVBGLIOCACQUIREGUESTCAPS)pReqHdr);
break;
case VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES:
REQ_CHECK_SIZES(VBGL_IOCTL_CHANGE_GUEST_CAPABILITIES);
pReqHdr->rc = vgdrvIoCtl_SetCapabilities(pDevExt, pSession, (PVBGLIOCSETGUESTCAPS)pReqHdr);
break;
#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
case VBGL_IOCTL_DPC_LATENCY_CHECKER:
REQ_CHECK_SIZES(VBGL_IOCTL_DPC_LATENCY_CHECKER);
pReqHdr->rc = VGDrvNtIOCtl_DpcLatencyChecker();
break;
#endif
default:
{
LogRel(("VGDrvCommonIoCtl: Unknown request iFunction=%#x (stripped %#x) cbReq=%#x\n",
iFunction, iFunctionStripped, cbReq));
pReqHdr->rc = rc = VERR_NOT_SUPPORTED;
break;
}
}
}
}
else
{
Log(("VGDrvCommonIoCtl: uType=%#x, expected default (ioctl=%#x)\n", pReqHdr->uType, iFunction));
return VERR_INVALID_PARAMETER;
}
LogFlow(("VGDrvCommonIoCtl: returns %Rrc (req: rc=%Rrc cbOut=%#x)\n", rc, pReqHdr->rc, pReqHdr->cbOut));
return rc;
}
/**
* Used by VGDrvCommonISR as well as the acquire guest capability code.
*
* @returns VINF_SUCCESS on success. On failure, ORed together
* RTSemEventMultiSignal errors (completes processing despite errors).
* @param pDevExt The VBoxGuest device extension.
* @param fEvents The events to dispatch.
*/
static int vgdrvDispatchEventsLocked(PVBOXGUESTDEVEXT pDevExt, uint32_t fEvents)
{
PVBOXGUESTWAIT pWait;
PVBOXGUESTWAIT pSafe;
int rc = VINF_SUCCESS;
fEvents |= pDevExt->f32PendingEvents;
RTListForEachSafe(&pDevExt->WaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
{
uint32_t fHandledEvents = pWait->fReqEvents & fEvents;
if ( fHandledEvents != 0
&& !pWait->fResEvents)
{
/* Does this one wait on any of the events we're dispatching? We do a quick
check first, then deal with VBOXGUEST_ACQUIRE_STYLE_EVENTS as applicable. */
if (fHandledEvents & VBOXGUEST_ACQUIRE_STYLE_EVENTS)
fHandledEvents &= vgdrvGetAllowedEventMaskForSession(pDevExt, pWait->pSession);
if (fHandledEvents)
{
pWait->fResEvents = pWait->fReqEvents & fEvents & fHandledEvents;
fEvents &= ~pWait->fResEvents;
RTListNodeRemove(&pWait->ListNode);
#ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
#else
RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
rc |= RTSemEventMultiSignal(pWait->Event);
#endif
if (!fEvents)
break;
}
}
}
ASMAtomicWriteU32(&pDevExt->f32PendingEvents, fEvents);
return rc;
}
/**
* Simply checks whether the IRQ is ours or not, does not do any interrupt
* procesing.
*
* @returns true if it was our interrupt, false if it wasn't.
* @param pDevExt The VBoxGuest device extension.
*/
bool VGDrvCommonIsOurIRQ(PVBOXGUESTDEVEXT pDevExt)
{
VMMDevMemory volatile *pVMMDevMemory;
bool fOurIrq;
RTSpinlockAcquire(pDevExt->EventSpinlock);
pVMMDevMemory = pDevExt->pVMMDevMemory;
fOurIrq = pVMMDevMemory ? pVMMDevMemory->V.V1_04.fHaveEvents : false;
RTSpinlockRelease(pDevExt->EventSpinlock);
return fOurIrq;
}
/**
* Common interrupt service routine.
*
* This deals with events and with waking up thread waiting for those events.
*
* @returns true if it was our interrupt, false if it wasn't.
* @param pDevExt The VBoxGuest device extension.
*/
bool VGDrvCommonISR(PVBOXGUESTDEVEXT pDevExt)
{
VMMDevEvents volatile *pReq;
bool fMousePositionChanged = false;
int rc = 0;
VMMDevMemory volatile *pVMMDevMemory;
bool fOurIrq;
/*
* Make sure we've initialized the device extension.
*/
if (RT_LIKELY(pDevExt->fHostFeatures & VMMDEV_HVF_FAST_IRQ_ACK))
pReq = NULL;
else if (RT_LIKELY((pReq = pDevExt->pIrqAckEvents) != NULL))
{ /* likely */ }
else
return false;
/*
* Enter the spinlock and check if it's our IRQ or not.
*/
RTSpinlockAcquire(pDevExt->EventSpinlock);
pVMMDevMemory = pDevExt->pVMMDevMemory;
fOurIrq = pVMMDevMemory ? pVMMDevMemory->V.V1_04.fHaveEvents : false;
if (fOurIrq)
{
/*
* Acknowledge events.
* We don't use VbglR0GRPerform here as it may take another spinlocks.
*/
uint32_t fEvents;
if (!pReq)
{
fEvents = ASMInU32(pDevExt->IOPortBase + VMMDEV_PORT_OFF_REQUEST_FAST);
ASMCompilerBarrier(); /* paranoia */
rc = fEvents != UINT32_MAX ? VINF_SUCCESS : VERR_INTERNAL_ERROR;
}
else
{
pReq->header.rc = VERR_INTERNAL_ERROR;
pReq->events = 0;
ASMCompilerBarrier();
ASMOutU32(pDevExt->IOPortBase + VMMDEV_PORT_OFF_REQUEST, (uint32_t)pDevExt->PhysIrqAckEvents);
ASMCompilerBarrier(); /* paranoia */
fEvents = pReq->events;
rc = pReq->header.rc;
}
if (RT_SUCCESS(rc))
{
Log3(("VGDrvCommonISR: acknowledge events succeeded %#RX32\n", fEvents));
/*
* VMMDEV_EVENT_MOUSE_POSITION_CHANGED can only be polled for.
*/
if (fEvents & VMMDEV_EVENT_MOUSE_POSITION_CHANGED)
{
fMousePositionChanged = true;
fEvents &= ~VMMDEV_EVENT_MOUSE_POSITION_CHANGED;
#if !defined(VBOXGUEST_MOUSE_NOTIFY_CAN_PREEMPT)
if (pDevExt->pfnMouseNotifyCallback)
pDevExt->pfnMouseNotifyCallback(pDevExt->pvMouseNotifyCallbackArg);
#endif
}
#ifdef VBOX_WITH_HGCM
/*
* The HGCM event/list is kind of different in that we evaluate all entries.
*/
if (fEvents & VMMDEV_EVENT_HGCM)
{
PVBOXGUESTWAIT pWait;
PVBOXGUESTWAIT pSafe;
RTListForEachSafe(&pDevExt->HGCMWaitList, pWait, pSafe, VBOXGUESTWAIT, ListNode)
{
if (pWait->pHGCMReq->fu32Flags & VBOX_HGCM_REQ_DONE)
{
pWait->fResEvents = VMMDEV_EVENT_HGCM;
RTListNodeRemove(&pWait->ListNode);
# ifdef VBOXGUEST_USE_DEFERRED_WAKE_UP
RTListAppend(&pDevExt->WakeUpList, &pWait->ListNode);
# else
RTListAppend(&pDevExt->WokenUpList, &pWait->ListNode);
rc |= RTSemEventMultiSignal(pWait->Event);
# endif
}
}
fEvents &= ~VMMDEV_EVENT_HGCM;
}
#endif
/*
* Normal FIFO waiter evaluation.
*/
rc |= vgdrvDispatchEventsLocked(pDevExt, fEvents);
}
else /* something is serious wrong... */
Log(("VGDrvCommonISR: acknowledge events failed rc=%Rrc (events=%#x)!!\n", rc, fEvents));
}
else
Log3(("VGDrvCommonISR: not ours\n"));
RTSpinlockRelease(pDevExt->EventSpinlock);
/*
* Execute the mouse notification callback here if it cannot be executed while
* holding the interrupt safe spinlock, see @bugref{8639}.
*/
#if defined(VBOXGUEST_MOUSE_NOTIFY_CAN_PREEMPT) && !defined(RT_OS_WINDOWS) /* (Windows does this in the Dpc callback) */
if ( fMousePositionChanged
&& pDevExt->pfnMouseNotifyCallback)
pDevExt->pfnMouseNotifyCallback(pDevExt->pvMouseNotifyCallbackArg);
#endif
#if defined(VBOXGUEST_USE_DEFERRED_WAKE_UP) && !defined(RT_OS_WINDOWS)
/*
* Do wake-ups.
* Note. On Windows this isn't possible at this IRQL, so a DPC will take
* care of it. Same on darwin, doing it in the work loop callback.
*/
VGDrvCommonWaitDoWakeUps(pDevExt);
#endif
/*
* Work the poll and async notification queues on OSes that implements that.
* (Do this outside the spinlock to prevent some recursive spinlocking.)
*/
if (fMousePositionChanged)
{
ASMAtomicIncU32(&pDevExt->u32MousePosChangedSeq);
VGDrvNativeISRMousePollEvent(pDevExt);
}
AssertMsg(rc == 0, ("rc=%#x (%d)\n", rc, rc));
return fOurIrq;
}
|