This file is indexed.

/usr/src/open-vm-tools-10.0.7/vmci/common/vmciContext.c is in open-vm-tools-dkms 2:10.0.7-3227872-2ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
/*********************************************************
 * Copyright (C) 2006-2012,2014-2015 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation version 2 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 *********************************************************/

/*
 * vmciContext.c --
 *
 *     Platform independent routines for VMCI calls.
 */

#include "vmci_kernel_if.h"
#include "vm_assert.h"
#include "vmci_defs.h"
#include "vmci_infrastructure.h"
#include "vmciCommonInt.h"
#include "vmciContext.h"
#include "vmciDatagram.h"
#include "vmciDoorbell.h"
#include "vmciDriver.h"
#include "vmciEvent.h"
#include "vmciKernelAPI.h"
#include "vmciQueuePair.h"
#if defined(VMKERNEL)
#  include "vmciVmkInt.h"
#  include "vm_libc.h"
#  include "helper_ext.h"
#endif

#define LGPFX "VMCIContext: "

static void VMCIContextFreeContext(VMCIContext *context);
static Bool VMCIContextExists(VMCIId cid);
static int VMCIContextFireNotification(VMCIId contextID,
                                       VMCIPrivilegeFlags privFlags);
#if defined(VMKERNEL)
static void VMCIContextReleaseGuestMemLocked(VMCIContext *context,
                                             VMCIGuestMemID gid,
                                             Bool powerOff);
static void VMCIContextInFilterCleanup(VMCIContext *context);
#endif

/*
 * List of current VMCI contexts.
 */

static struct {
   VMCIList head;
   VMCILock lock;
   VMCILock firingLock;
} contextList;


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextSignalNotify --
 *
 *      Sets the notify flag to TRUE.  Assumes that the context lock is
 *      held.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static INLINE void
VMCIContextSignalNotify(VMCIContext *context) // IN:
{
#ifndef VMX86_SERVER
   if (context->notify) {
      *context->notify = TRUE;
   }
#endif
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextClearNotify --
 *
 *      Sets the notify flag to FALSE.  Assumes that the context lock is
 *      held.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static INLINE void
VMCIContextClearNotify(VMCIContext *context) // IN:
{
#ifndef VMX86_SERVER
   if (context->notify) {
      *context->notify = FALSE;
   }
#endif
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextClearNotifyAndCall --
 *
 *      If nothing requires the attention of the guest, clears both
 *      notify flag and call.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static INLINE void
VMCIContextClearNotifyAndCall(VMCIContext *context) // IN:
{
   if (context->pendingDatagrams == 0 &&
       VMCIHandleArray_GetSize(context->pendingDoorbellArray) == 0) {
      VMCIHost_ClearCall(&context->hostContext);
      VMCIContextClearNotify(context);
   }
}


#ifndef VMX86_SERVER
/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_CheckAndSignalNotify --
 *
 *      Sets the context's notify flag iff datagrams are pending for this
 *      context.  Called from VMCISetupNotify().
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_CheckAndSignalNotify(VMCIContext *context) // IN:
{
   VMCILockFlags flags;

   ASSERT(context);
   VMCI_GrabLock(&context->lock, &flags);
   if (context->pendingDatagrams) {
      VMCIContextSignalNotify(context);
   }
   VMCI_ReleaseLock(&context->lock, flags);
}
#endif


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_Init --
 *
 *      Initializes the VMCI context module.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_Init(void)
{
   int err;

   VMCIList_Init(&contextList.head);

   err = VMCI_InitLock(&contextList.lock, "VMCIContextListLock",
                       VMCI_LOCK_RANK_CONTEXTLIST);
   if (err < VMCI_SUCCESS) {
      return err;
   }

   err = VMCI_InitLock(&contextList.firingLock, "VMCIContextFiringLock",
                       VMCI_LOCK_RANK_CONTEXTFIRE);
   if (err < VMCI_SUCCESS) {
      VMCI_CleanupLock(&contextList.lock);
   }

   return err;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_Exit --
 *
 *      Cleans up the contexts module.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_Exit(void)
{
   VMCI_CleanupLock(&contextList.firingLock);
   VMCI_CleanupLock(&contextList.lock);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_InitContext --
 *
 *      Allocates and initializes a VMCI context.
 *
 * Results:
 *      Returns 0 on success, appropriate error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_InitContext(VMCIId cid,                   // IN
                        VMCIPrivilegeFlags privFlags, // IN
                        uintptr_t eventHnd,           // IN
                        int userVersion,              // IN: User's vers no.
                        VMCIHostUser *user,           // IN
                        VMCIContext **outContext)     // OUT
{
   VMCILockFlags flags;
   VMCIContext *context;
   int result;

   if (privFlags & ~VMCI_PRIVILEGE_ALL_FLAGS) {
      VMCI_DEBUG_LOG(4, (LGPFX"Invalid flag (flags=0x%x) for VMCI context.\n",
                         privFlags));
      return VMCI_ERROR_INVALID_ARGS;
   }

   if (userVersion == 0) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   context = VMCI_AllocKernelMem(sizeof *context, VMCI_MEMORY_NONPAGED);
   if (context == NULL) {
      VMCI_WARNING((LGPFX"Failed to allocate memory for VMCI context.\n"));
      return VMCI_ERROR_NO_MEM;
   }
   memset(context, 0, sizeof *context);

   VMCIList_InitEntry(&context->listItem);
   VMCIList_Init(&context->datagramQueue);

   context->userVersion = userVersion;

   context->queuePairArray = VMCIHandleArray_Create(0);
   if (!context->queuePairArray) {
      result = VMCI_ERROR_NO_MEM;
      goto error;
   }

   context->doorbellArray = VMCIHandleArray_Create(0);
   if (!context->doorbellArray) {
      result = VMCI_ERROR_NO_MEM;
      goto error;
   }

   context->pendingDoorbellArray = VMCIHandleArray_Create(0);
   if (!context->pendingDoorbellArray) {
      result = VMCI_ERROR_NO_MEM;
      goto error;
   }

   context->notifierArray = VMCIHandleArray_Create(0);
   if (context->notifierArray == NULL) {
      result = VMCI_ERROR_NO_MEM;
      goto error;
   }

   result = VMCI_InitLock(&context->lock, "VMCIContextLock",
                          VMCI_LOCK_RANK_CONTEXT);
   if (result < VMCI_SUCCESS) {
      goto error;
   }
   Atomic_Write(&context->refCount, 1);

#if defined(VMKERNEL)
   result = VMCIMutex_Init(&context->guestMemMutex, "VMCIGuestMem",
                           VMCI_SEMA_RANK_GUESTMEM);
   if (result < VMCI_SUCCESS) {
      VMCI_CleanupLock(&context->lock);
      goto error;
   }
   context->curGuestMemID = INVALID_VMCI_GUEST_MEM_ID;

   context->inFilters = NULL;
#endif

   /* Inititialize host-specific VMCI context. */
   VMCIHost_InitContext(&context->hostContext, eventHnd);

   context->privFlags = privFlags;

   /*
    * If we collide with an existing context we generate a new and use it
    * instead. The VMX will determine if regeneration is okay. Since there
    * isn't 4B - 16 VMs running on a given host, the below loop will terminate.
    */
   VMCI_GrabLock(&contextList.lock, &flags);
   ASSERT(cid != VMCI_INVALID_ID);
   while (VMCIContextExists(cid)) {

      /*
       * If the cid is below our limit and we collide we are creating duplicate
       * contexts internally so we want to assert fail in that case.
       */
      ASSERT(cid >= VMCI_RESERVED_CID_LIMIT);

      /* We reserve the lowest 16 ids for fixed contexts. */
      cid = MAX(cid, VMCI_RESERVED_CID_LIMIT-1) + 1;
      if (cid == VMCI_INVALID_ID) {
         cid = VMCI_RESERVED_CID_LIMIT;
      }
   }
   ASSERT(!VMCIContextExists(cid));
   context->cid = cid;
   context->validUser = user != NULL;
   if (context->validUser) {
      context->user = *user;
   }
   VMCIList_Insert(&context->listItem, &contextList.head);
   VMCI_ReleaseLock(&contextList.lock, flags);

#ifdef VMKERNEL
   VMCIContext_SetFSRState(context, FALSE, VMCI_INVALID_ID, eventHnd, FALSE);
#endif

#ifndef VMX86_SERVER
   context->notify = NULL;
#  ifdef __linux__
   context->notifyPage = NULL;
#  endif
#endif

   *outContext = context;
   return VMCI_SUCCESS;

error:
   if (context->notifierArray) {
      VMCIHandleArray_Destroy(context->notifierArray);
   }
   if (context->queuePairArray) {
      VMCIHandleArray_Destroy(context->queuePairArray);
   }
   if (context->doorbellArray) {
      VMCIHandleArray_Destroy(context->doorbellArray);
   }
   if (context->pendingDoorbellArray) {
      VMCIHandleArray_Destroy(context->pendingDoorbellArray);
   }
   VMCI_FreeKernelMem(context, sizeof *context);
   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_ReleaseContext --
 *
 *      Cleans up a VMCI context.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_ReleaseContext(VMCIContext *context)   // IN
{
   VMCILockFlags flags;

   /* Dequeue VMCI context. */

   VMCI_GrabLock(&contextList.lock, &flags);
   VMCIList_Remove(&context->listItem);
   VMCI_ReleaseLock(&contextList.lock, flags);

   VMCIContext_Release(context);
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIContextFreeContext --
 *
 *      Deallocates all parts of a context datastructure. This
 *      functions doesn't lock the context, because it assumes that
 *      the caller is holding the last reference to context. As paged
 *      memory may be freed as part of the call, the function must be
 *      called without holding any spinlocks as this is not allowed on
 *      Windows.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Paged memory is freed.
 *
 *-----------------------------------------------------------------------------
 */

static void
VMCIContextFreeContext(VMCIContext *context)  // IN
{
   VMCIListItem *curr;
   VMCIListItem *next;
   DatagramQueueEntry *dqEntry;
   VMCIHandle tempHandle;

   /* Fire event to all contexts interested in knowing this context is dying. */
   VMCIContextFireNotification(context->cid, context->privFlags);

   /*
    * Cleanup all queue pair resources attached to context.  If the VM dies
    * without cleaning up, this code will make sure that no resources are
    * leaked.
    */

   tempHandle = VMCIHandleArray_GetEntry(context->queuePairArray, 0);
   while (!VMCI_HANDLE_EQUAL(tempHandle, VMCI_INVALID_HANDLE)) {
      if (VMCIQPBroker_Detach(tempHandle, context) < VMCI_SUCCESS) {
         /*
          * When VMCIQPBroker_Detach() succeeds it removes the handle from the
          * array.  If detach fails, we must remove the handle ourselves.
          */
         VMCIHandleArray_RemoveEntry(context->queuePairArray, tempHandle);
      }
      tempHandle = VMCIHandleArray_GetEntry(context->queuePairArray, 0);
   }

   /*
    * It is fine to destroy this without locking the datagramQueue, as
    * this is the only thread having a reference to the context.
    */

   VMCIList_ScanSafe(curr, next, &context->datagramQueue) {
      dqEntry = VMCIList_Entry(curr, DatagramQueueEntry, listItem);
      VMCIList_Remove(curr);
      ASSERT(dqEntry && dqEntry->dg);
      ASSERT(dqEntry->dgSize == VMCI_DG_SIZE(dqEntry->dg));
      VMCI_FreeKernelMem(dqEntry->dg, dqEntry->dgSize);
      VMCI_FreeKernelMem(dqEntry, sizeof *dqEntry);
   }

   VMCIHandleArray_Destroy(context->notifierArray);
   VMCIHandleArray_Destroy(context->queuePairArray);
   VMCIHandleArray_Destroy(context->doorbellArray);
   VMCIHandleArray_Destroy(context->pendingDoorbellArray);
   VMCI_CleanupLock(&context->lock);
#if defined(VMKERNEL)
   VMCIContextInFilterCleanup(context);
   VMCIMutex_Destroy(&context->guestMemMutex);
#endif
   VMCIHost_ReleaseContext(&context->hostContext);
#ifndef VMX86_SERVER
#  ifdef __linux__
   /* TODO Windows and Mac OS. */
   VMCIUnsetNotify(context);
#  endif
#endif
   VMCI_FreeKernelMem(context, sizeof *context);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_PendingDatagrams --
 *
 *      Returns the current number of pending datagrams. The call may
 *      also serve as a synchronization point for the datagram queue,
 *      as no enqueue operations can occur concurrently.
 *
 * Results:
 *      Length of datagram queue for the given context.
 *
 * Side effects:
 *      Locks datagram queue.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_PendingDatagrams(VMCIId cid,      // IN
                             uint32 *pending) // OUT
{
   VMCIContext *context;
   VMCILockFlags flags;

   context = VMCIContext_Get(cid);
   if (context == NULL) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   VMCI_GrabLock(&context->lock, &flags);
   if (pending) {
      *pending = context->pendingDatagrams;
   }
   VMCI_ReleaseLock(&context->lock, flags);
   VMCIContext_Release(context);

   return VMCI_SUCCESS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_EnqueueDatagram --
 *
 *      Queues a VMCI datagram for the appropriate target VM
 *      context.
 *
 * Results:
 *      Size of enqueued data on success, appropriate error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_EnqueueDatagram(VMCIId cid,         // IN: Target VM
                            VMCIDatagram *dg,   // IN:
                            Bool notify)        // IN:
{
   DatagramQueueEntry *dqEntry;
   VMCIContext *context;
   VMCILockFlags flags;
   VMCIHandle dgSrc;
   size_t vmciDgSize;

   ASSERT(dg);
   vmciDgSize = VMCI_DG_SIZE(dg);
   ASSERT(vmciDgSize <= VMCI_MAX_DG_SIZE);

   /* Get the target VM's VMCI context. */
   context = VMCIContext_Get(cid);
   if (context == NULL) {
      VMCI_DEBUG_LOG(4, (LGPFX"Invalid context (ID=0x%x).\n", cid));
      return VMCI_ERROR_INVALID_ARGS;
   }

   /* Allocate guest call entry and add it to the target VM's queue. */
   dqEntry = VMCI_AllocKernelMem(sizeof *dqEntry, VMCI_MEMORY_NONPAGED);
   if (dqEntry == NULL) {
      VMCI_WARNING((LGPFX"Failed to allocate memory for datagram.\n"));
      VMCIContext_Release(context);
      return VMCI_ERROR_NO_MEM;
   }
   dqEntry->dg = dg;
   dqEntry->dgSize = vmciDgSize;
   dgSrc = dg->src;
   VMCIList_InitEntry(&dqEntry->listItem);

   VMCI_GrabLock(&context->lock, &flags);

#if defined(VMKERNEL)
   if (context->inFilters != NULL) {
      if (VMCIFilterDenyDgIn(context->inFilters->filters, dg)) {
         VMCI_ReleaseLock(&context->lock, flags);
         VMCIContext_Release(context);
         VMCI_FreeKernelMem(dqEntry, sizeof *dqEntry);
         return VMCI_ERROR_NO_ACCESS;
      }
   }
#endif

   /*
    * We put a higher limit on datagrams from the hypervisor.  If the pending
    * datagram is not from hypervisor, then we check if enqueueing it would
    * exceed the VMCI_MAX_DATAGRAM_QUEUE_SIZE limit on the destination.  If the
    * pending datagram is from hypervisor, we allow it to be queued at the
    * destination side provided we don't reach the
    * VMCI_MAX_DATAGRAM_AND_EVENT_QUEUE_SIZE limit.
    */
   if (context->datagramQueueSize + vmciDgSize >=
         VMCI_MAX_DATAGRAM_QUEUE_SIZE &&
       (!VMCI_HANDLE_EQUAL(dgSrc,
                           VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID,
                                            VMCI_CONTEXT_RESOURCE_ID)) ||
        context->datagramQueueSize + vmciDgSize >=
         VMCI_MAX_DATAGRAM_AND_EVENT_QUEUE_SIZE)) {
      VMCI_ReleaseLock(&context->lock, flags);
      VMCIContext_Release(context);
      VMCI_FreeKernelMem(dqEntry, sizeof *dqEntry);
      VMCI_DEBUG_LOG(10, (LGPFX"Context (ID=0x%x) receive queue is full.\n",
                          cid));
      return VMCI_ERROR_NO_RESOURCES;
   }

   VMCIList_Insert(&dqEntry->listItem, &context->datagramQueue);
   context->pendingDatagrams++;
   context->datagramQueueSize += vmciDgSize;

   if (notify) {
      VMCIContextSignalNotify(context);
      VMCIHost_SignalCall(&context->hostContext);
   }

   VMCI_ReleaseLock(&context->lock, flags);
   VMCIContext_Release(context);

   return vmciDgSize;
}

#undef VMCI_MAX_DATAGRAM_AND_EVENT_QUEUE_SIZE


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextExists --
 *
 *      Internal helper to check if a context with the specified context
 *      ID exists. Assumes the contextList.lock is held.
 *
 * Results:
 *      TRUE if a context exists with the given cid.
 *      FALSE otherwise
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static Bool
VMCIContextExists(VMCIId cid)    // IN
{
   VMCIContext *context;
   VMCIListItem *next;
   Bool rv = FALSE;

   VMCIList_Scan(next, &contextList.head) {
      context = VMCIList_Entry(next, VMCIContext, listItem);
      if (context->cid == cid) {
         rv = TRUE;
         break;
      }
   }
   return rv;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_Exists --
 *
 *      Verifies whether a context with the specified context ID exists.
 *
 * Results:
 *      TRUE if a context exists with the given cid.
 *      FALSE otherwise
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

Bool
VMCIContext_Exists(VMCIId cid)    // IN
{
   VMCILockFlags flags;
   Bool rv;

   VMCI_GrabLock(&contextList.lock, &flags);
   rv = VMCIContextExists(cid);
   VMCI_ReleaseLock(&contextList.lock, flags);
   return rv;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_Get --
 *
 *      Retrieves VMCI context corresponding to the given cid.
 *
 * Results:
 *      VMCI context on success, NULL otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

VMCIContext *
VMCIContext_Get(VMCIId cid)  // IN
{
   VMCIContext *context = NULL;
   VMCIListItem *next;
   VMCILockFlags flags;

   if (cid == VMCI_INVALID_ID) {
      return NULL;
   }

   VMCI_GrabLock(&contextList.lock, &flags);
   if (VMCIList_Empty(&contextList.head)) {
      goto out;
   }

   VMCIList_Scan(next, &contextList.head) {
      context = VMCIList_Entry(next, VMCIContext, listItem);
      if (context->cid == cid) {
         /*
          * At this point, we are sure that the reference count is
          * larger already than zero. When starting the destruction of
          * a context, we always remove it from the context list
          * before decreasing the reference count. As we found the
          * context here, it hasn't been destroyed yet. This means
          * that we are not about to increase the reference count of
          * something that is in the process of being destroyed.
          */

         Atomic_Inc(&context->refCount);
         break;
      }
   }

out:
   VMCI_ReleaseLock(&contextList.lock, flags);
   return (context && context->cid == cid) ? context : NULL;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_Release --
 *
 *      Releases the VMCI context. If this is the last reference to
 *      the context it will be deallocated. A context is created with
 *      a reference count of one, and on destroy, it is removed from
 *      the context list before its reference count is
 *      decremented. Thus, if we reach zero, we are sure that nobody
 *      else are about to increment it (they need the entry in the
 *      context list for that). This function musn't be called with a
 *      lock held.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Paged memory may be deallocated.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_Release(VMCIContext *context)  // IN
{
   uint32 refCount;
   ASSERT(context);
   refCount = Atomic_ReadDec32(&context->refCount);
   if (refCount == 1) {
      VMCIContextFreeContext(context);
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_DequeueDatagram --
 *
 *      Dequeues the next datagram and returns it to caller.
 *      The caller passes in a pointer to the max size datagram
 *      it can handle and the datagram is only unqueued if the
 *      size is less than maxSize. If larger maxSize is set to
 *      the size of the datagram to give the caller a chance to
 *      set up a larger buffer for the guestcall.
 *
 * Results:
 *      On success:  0 if no more pending datagrams, otherwise the size of
 *                   the next pending datagram.
 *      On failure:  appropriate error code.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_DequeueDatagram(VMCIContext *context, // IN
                            size_t *maxSize,      // IN/OUT: max size of datagram caller can handle.
                            VMCIDatagram **dg)    // OUT:
{
   DatagramQueueEntry *dqEntry;
   VMCIListItem *listItem;
   VMCILockFlags flags;
   int rv;

   ASSERT(context && dg);

   /* Dequeue the next datagram entry. */
   VMCI_GrabLock(&context->lock, &flags);
   if (context->pendingDatagrams == 0) {
      VMCIContextClearNotifyAndCall(context);
      VMCI_ReleaseLock(&context->lock, flags);
      VMCI_DEBUG_LOG(4, (LGPFX"No datagrams pending.\n"));
      return VMCI_ERROR_NO_MORE_DATAGRAMS;
   }

   listItem = VMCIList_First(&context->datagramQueue);
   ASSERT (listItem != NULL);

   dqEntry = VMCIList_Entry(listItem, DatagramQueueEntry, listItem);
   ASSERT(dqEntry->dg);

   /* Check size of caller's buffer. */
   if (*maxSize < dqEntry->dgSize) {
      *maxSize = dqEntry->dgSize;
      VMCI_ReleaseLock(&context->lock, flags);
      VMCI_DEBUG_LOG(4, (LGPFX"Caller's buffer should be at least "
                         "(size=%u bytes).\n", (uint32)*maxSize));
      return VMCI_ERROR_NO_MEM;
   }

   VMCIList_Remove(listItem);
   context->pendingDatagrams--;
   context->datagramQueueSize -= dqEntry->dgSize;
   if (context->pendingDatagrams == 0) {
      VMCIContextClearNotifyAndCall(context);
      rv = VMCI_SUCCESS;
   } else {
      /*
       * Return the size of the next datagram.
       */
      DatagramQueueEntry *nextEntry;

      listItem = VMCIList_First(&context->datagramQueue);
      ASSERT(listItem);
      nextEntry = VMCIList_Entry(listItem, DatagramQueueEntry, listItem);
      ASSERT(nextEntry && nextEntry->dg);
      /*
       * The following size_t -> int truncation is fine as the maximum size of
       * a (routable) datagram is 68KB.
       */
      rv = (int)nextEntry->dgSize;
   }
   VMCI_ReleaseLock(&context->lock, flags);

   /* Caller must free datagram. */
   ASSERT(dqEntry->dgSize == VMCI_DG_SIZE(dqEntry->dg));
   *dg = dqEntry->dg;
   dqEntry->dg = NULL;
   VMCI_FreeKernelMem(dqEntry, sizeof *dqEntry);

   return rv;
}


#ifdef VMKERNEL
/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SetFSRState --
 *
 *      Set the states related to FSR (quiesced state, migrateCid,
 *      active event handle).
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_SetFSRState(VMCIContext *context, // IN
                        Bool isQuiesced,      // IN
                        VMCIId migrateCid,    // IN
                        uintptr_t eventHnd,   // IN
                        Bool isLocked)        // IN
{
   VMCILockFlags flags;
   if (!context) {
      return;
   }
   if (!isLocked) {
      VMCI_GrabLock(&context->lock, &flags);
   }
   context->isQuiesced = isQuiesced;
   context->migrateCid = migrateCid;
   VMCIHost_SetActiveHnd(&context->hostContext, eventHnd);
   if (!isLocked) {
      VMCI_ReleaseLock(&context->lock, flags);
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_FindAndUpdateSrcFSR --
 *
 *      Find the source context for fast-suspend-resume. If found, the
 *      source context's FSR state is changed to reflect the new active
 *      event handle.
 *
 * Results:
 *      If found, source context for fast-suspend-resume, NULL otherwise.
 *
 * Side effects:
 *      The source context reference count increased and the caller is
 *      supposed to release the context once it is done using it.
 *
 *----------------------------------------------------------------------
 */

VMCIContext *
VMCIContext_FindAndUpdateSrcFSR(VMCIId migrateCid,      // IN
                                uintptr_t eventHnd,     // IN
                                uintptr_t *srcEventHnd) // IN/OUT
{
   VMCIContext *contextSrc = VMCIContext_Get(migrateCid);

   if (contextSrc) {
      VMCILockFlags flags;

      VMCI_GrabLock(&contextSrc->lock, &flags);
      if (contextSrc->isQuiesced && contextSrc->migrateCid == migrateCid) {
         if (srcEventHnd) {
            *srcEventHnd = VMCIHost_GetActiveHnd(&contextSrc->hostContext);
            ASSERT(*srcEventHnd != VMCI_INVALID_ID);
         }
         VMCIContext_SetFSRState(contextSrc, FALSE, VMCI_INVALID_ID,
                                 eventHnd, TRUE);
         VMCI_ReleaseLock(&contextSrc->lock, flags);
         return contextSrc;
      }
      VMCI_ReleaseLock(&contextSrc->lock, flags);
      VMCIContext_Release(contextSrc);
   }
   return NULL;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_IsActiveHnd --
 *
 *      Whether the curent event handle is the active handle.
 *
 * Results:
 *      TRUE if the event handle is active, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

Bool
VMCIContext_IsActiveHnd(VMCIContext *context, // IN
                        uintptr_t eventHnd)   // IN
{
   VMCILockFlags flags;
   Bool isActive;

   ASSERT(context);
   VMCI_GrabLock(&context->lock, &flags);
   isActive = VMCIHost_IsActiveHnd(&context->hostContext, eventHnd);
   VMCI_ReleaseLock(&context->lock, flags);
   return isActive;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_GetActiveHnd --
 *
 *      Returns the curent event handle.
 *
 * Results:
 *      The current active handle.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

uintptr_t
VMCIContext_GetActiveHnd(VMCIContext *context) // IN
{
   VMCILockFlags flags;
   uintptr_t activeHnd;

   ASSERT(context);
   VMCI_GrabLock(&context->lock, &flags);
   activeHnd = VMCIHost_GetActiveHnd(&context->hostContext);
   VMCI_ReleaseLock(&context->lock, flags);
   return activeHnd;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SetInactiveHnd --
 *
 *      Set the handle to be the inactive one.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_SetInactiveHnd(VMCIContext *context, // IN
                           uintptr_t eventHnd)   // IN
{
   VMCILockFlags flags;

   ASSERT(context);
   VMCI_GrabLock(&context->lock, &flags);
   VMCIHost_SetInactiveHnd(&context->hostContext, eventHnd);
   VMCI_ReleaseLock(&context->lock, flags);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_RemoveHnd --
 *
 *      Remove the event handle from host context.
 *
 * Results:
 *      Whether the handle exists and removed, also number of handles
 *      before removal and number of handles after removal.
 *
 * Side effects:
 *      If this is active handle, the inactive handle becomes active.
 *
 *----------------------------------------------------------------------
 */

Bool
VMCIContext_RemoveHnd(VMCIContext *context, // IN
                      uintptr_t eventHnd,   // IN
                      uint32 *numOld,       // OUT
                      uint32 *numNew)       // OUT
{
   VMCILockFlags flags;
   uint32 numHandleOld, numHandleNew;
   Bool ret;

   ASSERT(context);
   VMCI_GrabLock(&context->lock, &flags);
   numHandleOld = VMCIHost_NumHnds(&context->hostContext);
   ret = VMCIHost_RemoveHnd(&context->hostContext, eventHnd);
   numHandleNew = VMCIHost_NumHnds(&context->hostContext);
   /*
    * This is needed to prevent FSR to share this
    * context while this context is being destroyed.
    */
   if (ret && numHandleOld == 1 && numHandleNew == 1) {
      context->migrateCid = VMCI_INVALID_ID;
   }
   VMCI_ReleaseLock(&context->lock, flags);

   if (numOld) {
      *numOld = numHandleOld;
   }
   if (numNew) {
      *numNew = numHandleNew;
   }
   return ret;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIContext_ClearDatagrams --
 *
 *      Clear pending datagrams.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
VMCIContext_ClearDatagrams(VMCIContext *context) // IN
{
   int retval;
   VMCIDatagram *dg = NULL;
   size_t size = VMCI_MAX_DG_SIZE;
   uint32 pending;

   /* Drop all datagrams that are currently pending for given context. */
   if (context == NULL) {
      return;
   }
   retval = VMCIContext_PendingDatagrams(context->cid, &pending);
   if (retval != VMCI_SUCCESS) {
      /*
       * This shouldn't happen as we already verified that the context
       * exists.
       */

      ASSERT(FALSE);
      return;
   }

   /*
    * We drain the queue for any datagrams pending at the beginning of
    * the loop. As datagrams may arrive at any point in time, we
    * cannot guarantee that the queue is empty after this point. Only
    * removing a fixed number of pending datagrams prevents us from
    * looping forever.
    */

   while (pending > 0 &&
          VMCIContext_DequeueDatagram(context, &size, &dg) >= 0) {
      ASSERT(dg);
      VMCI_FreeKernelMem(dg, VMCI_DG_SIZE(dg));
      --pending;
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SetId --
 *
 *      Set the cid of given VMCI context.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_SetId(VMCIContext *context,         // IN
                  VMCIId cid)                   // IN:
{
   VMCILockFlags flags;

   if (!context) {
      return;
   }
   VMCI_GrabLock(&context->lock, &flags);
   context->cid = cid;
   VMCI_ReleaseLock(&context->lock, flags);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextGenerateEvent --
 *
 *      Generates a VMCI event that only takes context ID as event data.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static void
VMCIContextGenerateEvent(VMCIId cid,       // IN
                         VMCI_Event event) // IN
{
   VMCIEventMsg *eMsg;
   VMCIEventPayload_Context *ePayload;
   /* buf is only 48 bytes. */
   char buf[sizeof *eMsg + sizeof *ePayload];

   eMsg = (VMCIEventMsg *)buf;
   ePayload = VMCIEventMsgPayload(eMsg);

   eMsg->hdr.dst = VMCI_MAKE_HANDLE(VMCI_HOST_CONTEXT_ID, VMCI_EVENT_HANDLER);
   eMsg->hdr.src = VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID,
                                    VMCI_CONTEXT_RESOURCE_ID);
   eMsg->hdr.payloadSize = sizeof *eMsg + sizeof *ePayload - sizeof eMsg->hdr;
   eMsg->eventData.event = event;
   ePayload->contextID = cid;

   (void)VMCIEvent_Dispatch((VMCIDatagram *)eMsg);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_NotifyGuestPaused --
 *
 *      Notify subscribers of a execution state change of the VM
 *      with the given context ID. This will happen when a VM is
 *      quiesced/unquiesced.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_NotifyGuestPaused(VMCIId cid,  // IN
                              Bool paused) // IN
{
   VMCIContextGenerateEvent(cid, paused ? VMCI_EVENT_GUEST_PAUSED :
                                          VMCI_EVENT_GUEST_UNPAUSED);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_NotifyMemoryAccess --
 *
 *      Notify subscribers of a memory access change to the device.
 *      This can occur when the device is enabled/disabled/reset.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_NotifyMemoryAccess(VMCIId cid, // IN
                               Bool on)    // IN
{
   VMCIContextGenerateEvent(cid, on ? VMCI_EVENT_MEM_ACCESS_ON :
                                      VMCI_EVENT_MEM_ACCESS_OFF);
}
#endif


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_GetId --
 *
 *      Retrieves cid of given VMCI context.
 *
 * Results:
 *      VMCIId of context on success, VMCI_INVALID_ID otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

VMCIId
VMCIContext_GetId(VMCIContext *context) // IN:
{
   if (!context) {
      return VMCI_INVALID_ID;
   }
   ASSERT(context->cid != VMCI_INVALID_ID);
   return context->cid;
}


/*
 *----------------------------------------------------------------------
 *
 * vmci_context_get_priv_flags --
 *
 *      Retrieves the privilege flags of the given VMCI context ID.
 *
 * Results:
 *     Context's privilege flags.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(vmci_context_get_priv_flags)
VMCIPrivilegeFlags
vmci_context_get_priv_flags(VMCIId contextID)  // IN
{
   if (VMCI_HostPersonalityActive()) {
      VMCIPrivilegeFlags flags;
      VMCIContext *context;

      context = VMCIContext_Get(contextID);
      if (!context) {
         return VMCI_LEAST_PRIVILEGE_FLAGS;
      }
      flags = context->privFlags;
      VMCIContext_Release(context);
      return flags;
   }
   return VMCI_NO_PRIVILEGE_FLAGS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_AddNotification --
 *
 *      Add remoteCID to list of contexts current contexts wants
 *      notifications from/about.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      As in VMCIHandleArray_AppendEntry().
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_AddNotification(VMCIId contextID,  // IN:
                            VMCIId remoteCID)  // IN:
{
   int result = VMCI_ERROR_ALREADY_EXISTS;
   VMCILockFlags flags;
   VMCILockFlags firingFlags;
   VMCIHandle notifierHandle;
   VMCIContext *context = VMCIContext_Get(contextID);
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }

   if (VMCI_CONTEXT_IS_VM(contextID) && VMCI_CONTEXT_IS_VM(remoteCID)) {
      VMCI_DEBUG_LOG(4, (LGPFX"Context removed notifications for other VMs not "
                         "supported (src=0x%x, remote=0x%x).\n",
                         contextID, remoteCID));
      result = VMCI_ERROR_DST_UNREACHABLE;
      goto out;
   }

   if (context->privFlags & VMCI_PRIVILEGE_FLAG_RESTRICTED) {
      result = VMCI_ERROR_NO_ACCESS;
      goto out;
   }

   notifierHandle = VMCI_MAKE_HANDLE(remoteCID, VMCI_EVENT_HANDLER);
   VMCI_GrabLock(&contextList.firingLock, &firingFlags);
   VMCI_GrabLock(&context->lock, &flags);
   if (!VMCIHandleArray_HasEntry(context->notifierArray, notifierHandle)) {
      VMCIHandleArray_AppendEntry(&context->notifierArray, notifierHandle);
      result = VMCI_SUCCESS;
   }
   VMCI_ReleaseLock(&context->lock, flags);
   VMCI_ReleaseLock(&contextList.firingLock, firingFlags);
out:
   VMCIContext_Release(context);
   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_RemoveNotification --
 *
 *      Remove remoteCID from current context's list of contexts it is
 *      interested in getting notifications from/about.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_RemoveNotification(VMCIId contextID,  // IN:
                               VMCIId remoteCID)  // IN:
{
   VMCILockFlags flags;
   VMCILockFlags firingFlags;
   VMCIContext *context = VMCIContext_Get(contextID);
   VMCIHandle tmpHandle;
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }
   VMCI_GrabLock(&contextList.firingLock, &firingFlags);
   VMCI_GrabLock(&context->lock, &flags);
   tmpHandle =
      VMCIHandleArray_RemoveEntry(context->notifierArray,
                                  VMCI_MAKE_HANDLE(remoteCID,
                                                   VMCI_EVENT_HANDLER));
   VMCI_ReleaseLock(&context->lock, flags);
   VMCI_ReleaseLock(&contextList.firingLock, firingFlags);
   VMCIContext_Release(context);

   if (VMCI_HANDLE_EQUAL(tmpHandle, VMCI_INVALID_HANDLE)) {
      return VMCI_ERROR_NOT_FOUND;
   }
   return VMCI_SUCCESS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextFireNotification --
 *
 *      Fire notification for all contexts interested in given cid.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static int
VMCIContextFireNotification(VMCIId contextID,             // IN
                            VMCIPrivilegeFlags privFlags) // IN
{
   uint32 i, arraySize;
   VMCIListItem *next;
   VMCILockFlags flags;
   VMCILockFlags firingFlags;
   VMCIHandleArray *subscriberArray;
   VMCIHandle contextHandle = VMCI_MAKE_HANDLE(contextID, VMCI_EVENT_HANDLER);

   /*
    * We create an array to hold the subscribers we find when scanning through
    * all contexts.
    */
   subscriberArray = VMCIHandleArray_Create(0);
   if (subscriberArray == NULL) {
      return VMCI_ERROR_NO_MEM;
   }

   /*
    * Scan all contexts to find who is interested in being notified about
    * given contextID. We have a special firingLock that we use to synchronize
    * across all notification operations. This avoids us having to take the
    * context lock for each HasEntry call and it solves a lock ranking issue.
    */
   VMCI_GrabLock(&contextList.firingLock, &firingFlags);
   VMCI_GrabLock(&contextList.lock, &flags);
   VMCIList_Scan(next, &contextList.head) {
      VMCIContext *subCtx = VMCIList_Entry(next, VMCIContext, listItem);

      /*
       * We only deliver notifications of the removal of contexts, if
       * the two contexts are allowed to interact.
       */

      if (VMCIHandleArray_HasEntry(subCtx->notifierArray, contextHandle) &&
          !VMCIDenyInteraction(privFlags, subCtx->privFlags)) {
         VMCIHandleArray_AppendEntry(&subscriberArray,
                                     VMCI_MAKE_HANDLE(subCtx->cid,
                                                      VMCI_EVENT_HANDLER));
      }
   }
   VMCI_ReleaseLock(&contextList.lock, flags);
   VMCI_ReleaseLock(&contextList.firingLock, firingFlags);

   /* Fire event to all subscribers. */
   arraySize = VMCIHandleArray_GetSize(subscriberArray);
   for (i = 0; i < arraySize; i++) {
      int result;
      VMCIEventMsg *eMsg;
      VMCIEventPayload_Context *evPayload;
      char buf[sizeof *eMsg + sizeof *evPayload];

      eMsg = (VMCIEventMsg *)buf;

      /* Clear out any garbage. */
      memset(eMsg, 0, sizeof *eMsg + sizeof *evPayload);
      eMsg->hdr.dst = VMCIHandleArray_GetEntry(subscriberArray, i);
      eMsg->hdr.src = VMCI_MAKE_HANDLE(VMCI_HYPERVISOR_CONTEXT_ID,
                                       VMCI_CONTEXT_RESOURCE_ID);
      eMsg->hdr.payloadSize = sizeof *eMsg + sizeof *evPayload -
                              sizeof eMsg->hdr;
      eMsg->eventData.event = VMCI_EVENT_CTX_REMOVED;
      evPayload = VMCIEventMsgPayload(eMsg);
      evPayload->contextID = contextID;

      result = VMCIDatagram_Dispatch(VMCI_HYPERVISOR_CONTEXT_ID,
                                     (VMCIDatagram *)eMsg, FALSE);
      if (result < VMCI_SUCCESS) {
         VMCI_DEBUG_LOG(4, (LGPFX"Failed to enqueue event datagram "
                            "(type=%d) for context (ID=0x%x).\n",
                            eMsg->eventData.event, eMsg->hdr.dst.context));
         /* We continue to enqueue on next subscriber. */
      }
   }
   VMCIHandleArray_Destroy(subscriberArray);

   return VMCI_SUCCESS;
}

/*
 *----------------------------------------------------------------------
 *
 * VMCIContextDgHypervisorSaveStateSize --
 *
 *      Calculate the size for the hypervisor datagram checkpoint
 *      save data.
 *
 *      The format is as follows:
 *
 *      uint32 count - number of entries
 *      uint32 size  - size of first entry
 *      char bytes[] - contents of first entry
 *      uint32 size  - size of second entry
 *      char bytes[] - contents of second entry
 *      ...
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static int
VMCIContextDgHypervisorSaveStateSize(VMCIContext *context,  // IN
                                     uint32 *bufSize,       // IN/OUT
                                     char **cptBufPtr)      // UNUSED
{
   uint32 total;
   VMCIListItem *iter;

   *bufSize = total = 0;

   VMCIList_Scan(iter, &context->datagramQueue) {
      DatagramQueueEntry *dqEntry =
         VMCIList_Entry(iter, DatagramQueueEntry, listItem);

      if (dqEntry->dg->src.context == VMCI_HYPERVISOR_CONTEXT_ID) {
         /* Size of the datagram followed by the contents of the datagram. */
         total += sizeof(uint32) + dqEntry->dgSize;
      }
   }

   if (total > 0) {
      /* Don't forget the datagram count. */
      *bufSize = total + sizeof(uint32);
   }

   return VMCI_SUCCESS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextDgHypervisorSaveState --
 *
 *      Get the hypervisor datagram checkpoint save data.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static int
VMCIContextDgHypervisorSaveState(VMCIContext *context,   // IN
                                 uint32 *bufSize,        // IN/OUT
                                 char **cptBufPtr)       // OUT
{
   uint8 *p;
   uint32 total;
   uint32 count;
   VMCIListItem *iter;

   /* Need at least the count field and the size of one entry. */
   if (*bufSize < sizeof(uint32) * 2) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   p = VMCI_AllocKernelMem(*bufSize, VMCI_MEMORY_NORMAL);
   if (p == NULL) {
      return VMCI_ERROR_NO_MEM;
   }

   *cptBufPtr = p;

   /* Leave space for the datagram count at the start. */
   total  = sizeof(uint32);
   p     += sizeof(uint32);

   count = 0;
   VMCIList_Scan(iter, &context->datagramQueue) {
      DatagramQueueEntry *dqEntry =
         VMCIList_Entry(iter, DatagramQueueEntry, listItem);

      if (dqEntry->dg->src.context == VMCI_HYPERVISOR_CONTEXT_ID) {

         /*
          * VMX might have capped the amount of space we can use to checkpoint
          * hypervisor datagrams. Respect that here. Those that are not written
          * to the buffer will get dropped.
          */

         if (total + sizeof(uint32) + dqEntry->dgSize > *bufSize) {
            break;
         }

         total += sizeof(uint32) + dqEntry->dgSize;

         /*
          * Write in the size of the datagram followed by the contents of the
          * datagram itself.
          */

         *(uint32 *)p = dqEntry->dgSize;
         p += sizeof(uint32);

         memcpy(p, dqEntry->dg, dqEntry->dgSize);
         p += dqEntry->dgSize;

         count++;
      }
   }

   /* Now rollback and write the count at the start of the block. */
   *(uint32 *)(*cptBufPtr) = count;

   return VMCI_SUCCESS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_GetCheckpointState --
 *
 *      Get current context's checkpoint state of given type.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_GetCheckpointState(VMCIId contextID,    // IN:
                               uint32 cptType,      // IN:
                               uint32 *bufSize,     // IN/OUT:
                               char   **cptBufPtr)  // OUT:
{
   int i, result;
   VMCILockFlags flags;
   uint32 arraySize, cptDataSize;
   VMCIHandleArray *array;
   VMCIContext *context;
   char *cptBuf;
   Bool getContextID;

   ASSERT(bufSize && cptBufPtr);

   context = VMCIContext_Get(contextID);
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }

   VMCI_GrabLock(&context->lock, &flags);
   if (cptType == VMCI_NOTIFICATION_CPT_STATE) {
      ASSERT(context->notifierArray);
      array = context->notifierArray;
      getContextID = TRUE;
   } else if (cptType == VMCI_WELLKNOWN_CPT_STATE) {
      /*
       * For compatibility with VMX'en with VM to VM communication, we
       * always return zero wellknown handles.
       */

      *bufSize = 0;
      *cptBufPtr = NULL;
      result = VMCI_SUCCESS;
      goto release;
   } else if (cptType == VMCI_DOORBELL_CPT_STATE) {
      ASSERT(context->doorbellArray);
      array = context->doorbellArray;
      getContextID = FALSE;
   } else if (cptType == VMCI_DG_HYPERVISOR_SAVE_STATE_SIZE) {
      result = VMCIContextDgHypervisorSaveStateSize(context, bufSize, cptBufPtr);
      goto release;
   } else if (cptType == VMCI_DG_HYPERVISOR_SAVE_STATE) {
      result = VMCIContextDgHypervisorSaveState(context, bufSize, cptBufPtr);
      goto release;
   } else {
      VMCI_DEBUG_LOG(4, (LGPFX"Invalid cpt state (type=%d).\n", cptType));
      result = VMCI_ERROR_INVALID_ARGS;
      goto release;
   }

   arraySize = VMCIHandleArray_GetSize(array);
   if (arraySize > 0) {
      if (cptType == VMCI_DOORBELL_CPT_STATE) {
         cptDataSize = arraySize * sizeof(VMCIDoorbellCptState);
      } else {
         cptDataSize = arraySize * sizeof(VMCIId);
      }
      if (*bufSize < cptDataSize) {
         *bufSize = cptDataSize;
         result = VMCI_ERROR_MORE_DATA;
         goto release;
      }

      cptBuf = VMCI_AllocKernelMem(cptDataSize,
                                   VMCI_MEMORY_NONPAGED | VMCI_MEMORY_ATOMIC);
      if (cptBuf == NULL) {
         result = VMCI_ERROR_NO_MEM;
         goto release;
      }

      for (i = 0; i < arraySize; i++) {
         VMCIHandle tmpHandle = VMCIHandleArray_GetEntry(array, i);
         if (cptType == VMCI_DOORBELL_CPT_STATE) {
            ((VMCIDoorbellCptState *)cptBuf)[i].handle = tmpHandle;
         } else {
            ((VMCIId *)cptBuf)[i] =
               getContextID ? tmpHandle.context : tmpHandle.resource;
         }
      }
      *bufSize = cptDataSize;
      *cptBufPtr = cptBuf;
   } else {
      *bufSize = 0;
      *cptBufPtr = NULL;
   }
   result = VMCI_SUCCESS;

release:
   VMCI_ReleaseLock(&context->lock, flags);
   VMCIContext_Release(context);
   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SetCheckpointState --
 *
 *      Set current context's checkpoint state of given type.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_SetCheckpointState(VMCIId contextID, // IN:
                               uint32 cptType,   // IN:
                               uint32 bufSize,   // IN:
                               char   *cptBuf)   // IN:
{
   uint32 i;
   VMCIId currentID;
   int result = VMCI_SUCCESS;
   uint32 numIDs = bufSize / sizeof(VMCIId);
   ASSERT(cptBuf);

   if (cptType == VMCI_WELLKNOWN_CPT_STATE && numIDs > 0) {
      /*
       * We would end up here if VMX with VM to VM communication
       * attempts to restore a checkpoint with wellknown handles.
       */

      VMCI_WARNING((LGPFX"Attempt to restore checkpoint with obsolete "
                    "wellknown handles.\n"));
      return VMCI_ERROR_OBSOLETE;
   }

   if (cptType != VMCI_NOTIFICATION_CPT_STATE) {
      VMCI_DEBUG_LOG(4, (LGPFX"Invalid cpt state (type=%d).\n", cptType));
      return VMCI_ERROR_INVALID_ARGS;
   }

   for (i = 0; i < numIDs && result == VMCI_SUCCESS; i++) {
      currentID = ((VMCIId *)cptBuf)[i];
      result = VMCIContext_AddNotification(contextID, currentID);
      if (result != VMCI_SUCCESS) {
         break;
      }
   }
   if (result != VMCI_SUCCESS) {
      VMCI_DEBUG_LOG(4, (LGPFX"Failed to set cpt state (type=%d) (error=%d).\n",
                         cptType, result));
   }
   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_ReceiveNotificationsGet --
 *
 *      Retrieves the specified context's pending notifications in the
 *      form of a handle array. The handle arrays returned are the
 *      actual data - not a copy and should not be modified by the
 *      caller. They must be released using
 *      VMCIContext_ReceiveNotificationsRelease.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_ReceiveNotificationsGet(VMCIId contextID,                // IN
                                    VMCIHandleArray **dbHandleArray, // OUT
                                    VMCIHandleArray **qpHandleArray) // OUT
{
   VMCIContext *context;
   VMCILockFlags flags;
   int result = VMCI_SUCCESS;

   ASSERT(dbHandleArray && qpHandleArray);

   context = VMCIContext_Get(contextID);
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }
   VMCI_GrabLock(&context->lock, &flags);

   *dbHandleArray = context->pendingDoorbellArray;
   context->pendingDoorbellArray =  VMCIHandleArray_Create(0);
   if (!context->pendingDoorbellArray) {
      context->pendingDoorbellArray = *dbHandleArray;
      *dbHandleArray = NULL;
      result = VMCI_ERROR_NO_MEM;
   }
   *qpHandleArray = NULL;

   VMCI_ReleaseLock(&context->lock, flags);
   VMCIContext_Release(context);

   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_ReceiveNotificationsRelease --
 *
 *      Releases handle arrays with pending notifications previously
 *      retrieved using VMCIContext_ReceiveNotificationsGet. If the
 *      notifications were not successfully handed over to the guest,
 *      success must be false.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_ReceiveNotificationsRelease(VMCIId contextID,               // IN
                                        VMCIHandleArray *dbHandleArray, // IN
                                        VMCIHandleArray *qpHandleArray, // IN
                                        Bool success)                   // IN
{
   VMCIContext *context = VMCIContext_Get(contextID);

   if (context) {
      VMCILockFlags flags;

      VMCI_GrabLock(&context->lock, &flags);
      if (!success) {
         VMCIHandle handle;

         /*
          * New notifications may have been added while we were not
          * holding the context lock, so we transfer any new pending
          * doorbell notifications to the old array, and reinstate the
          * old array.
          */

         handle = VMCIHandleArray_RemoveTail(context->pendingDoorbellArray);
         while (!VMCI_HANDLE_INVALID(handle)) {
            ASSERT(VMCIHandleArray_HasEntry(context->doorbellArray, handle));
            if (!VMCIHandleArray_HasEntry(dbHandleArray, handle)) {
               VMCIHandleArray_AppendEntry(&dbHandleArray, handle);
            }
            handle = VMCIHandleArray_RemoveTail(context->pendingDoorbellArray);
         }
         VMCIHandleArray_Destroy(context->pendingDoorbellArray);
         context->pendingDoorbellArray = dbHandleArray;
         dbHandleArray = NULL;
      } else {
         VMCIContextClearNotifyAndCall(context);
      }
      VMCI_ReleaseLock(&context->lock, flags);
      VMCIContext_Release(context);
   } else {
         /*
          * The OS driver part is holding on to the context for the
          * duration of the receive notification ioctl, so it should
          * still be here.
          */

         ASSERT(FALSE);
   }

   if (dbHandleArray) {
      VMCIHandleArray_Destroy(dbHandleArray);
   }
   if (qpHandleArray) {
      VMCIHandleArray_Destroy(qpHandleArray);
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_DoorbellCreate --
 *
 *      Registers that a new doorbell handle has been allocated by the
 *      context. Only doorbell handles registered can be notified.
 *
 * Results:
 *      VMCI_SUCCESS on success, appropriate error code otherewise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_DoorbellCreate(VMCIId contextID,   // IN
                           VMCIHandle handle)  // IN
{
   VMCIContext *context;
   VMCILockFlags flags;
   int result;

   if (contextID == VMCI_INVALID_ID || VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   context = VMCIContext_Get(contextID);
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }

   VMCI_GrabLock(&context->lock, &flags);
   if (!VMCIHandleArray_HasEntry(context->doorbellArray, handle)) {
      VMCIHandleArray_AppendEntry(&context->doorbellArray, handle);
      result = VMCI_SUCCESS;
   } else {
      result = VMCI_ERROR_DUPLICATE_ENTRY;
   }
   VMCI_ReleaseLock(&context->lock, flags);

   VMCIContext_Release(context);

   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_DoorbellDestroy --
 *
 *      Unregisters a doorbell handle that was previously registered
 *      with VMCIContext_DoorbellCreate.
 *
 * Results:
 *      VMCI_SUCCESS on success, appropriate error code otherewise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_DoorbellDestroy(VMCIId contextID,   // IN
                            VMCIHandle handle)  // IN
{
   VMCIContext *context;
   VMCILockFlags flags;
   VMCIHandle removedHandle;

   if (contextID == VMCI_INVALID_ID || VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   context = VMCIContext_Get(contextID);
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }

   VMCI_GrabLock(&context->lock, &flags);
   removedHandle = VMCIHandleArray_RemoveEntry(context->doorbellArray, handle);
   VMCIHandleArray_RemoveEntry(context->pendingDoorbellArray, handle);
   VMCI_ReleaseLock(&context->lock, flags);

   VMCIContext_Release(context);

   if (VMCI_HANDLE_INVALID(removedHandle)) {
      return VMCI_ERROR_NOT_FOUND;
   } else {
      return VMCI_SUCCESS;
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_DoorbellDestroyAll --
 *
 *      Unregisters all doorbell handles that were previously
 *      registered with VMCIContext_DoorbellCreate.
 *
 * Results:
 *      VMCI_SUCCESS on success, appropriate error code otherewise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_DoorbellDestroyAll(VMCIId contextID) // IN
{
   VMCIContext *context;
   VMCILockFlags flags;
   VMCIHandle removedHandle;

   if (contextID == VMCI_INVALID_ID) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   context = VMCIContext_Get(contextID);
   if (context == NULL) {
      return VMCI_ERROR_NOT_FOUND;
   }

   VMCI_GrabLock(&context->lock, &flags);
   do {
      removedHandle = VMCIHandleArray_RemoveTail(context->doorbellArray);
   } while(!VMCI_HANDLE_INVALID(removedHandle));
   do {
      removedHandle = VMCIHandleArray_RemoveTail(context->pendingDoorbellArray);
   } while(!VMCI_HANDLE_INVALID(removedHandle));
   VMCI_ReleaseLock(&context->lock, flags);

   VMCIContext_Release(context);

   return VMCI_SUCCESS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_NotifyDoorbell --
 *
 *      Registers a notification of a doorbell handle initiated by the
 *      specified source context. The notification of doorbells are
 *      subject to the same isolation rules as datagram delivery. To
 *      allow host side senders of notifications a finer granularity
 *      of sender rights than those assigned to the sending context
 *      itself, the host context is required to specify a different
 *      set of privilege flags that will override the privileges of
 *      the source context.
 *
 * Results:
 *      VMCI_SUCCESS on success, appropriate error code otherewise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_NotifyDoorbell(VMCIId srcCID,                   // IN
                           VMCIHandle handle,               // IN
                           VMCIPrivilegeFlags srcPrivFlags) // IN
{
   VMCIContext *dstContext;
   VMCILockFlags flags;
   int result;

   if (VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   /* Get the target VM's VMCI context. */
   dstContext = VMCIContext_Get(handle.context);
   if (dstContext == NULL) {
      VMCI_DEBUG_LOG(4, (LGPFX"Invalid context (ID=0x%x).\n", handle.context));
      return VMCI_ERROR_NOT_FOUND;
   }

   if (srcCID != handle.context) {
      VMCIPrivilegeFlags dstPrivFlags;

      if (VMCI_CONTEXT_IS_VM(srcCID) && VMCI_CONTEXT_IS_VM(handle.context)) {
         VMCI_DEBUG_LOG(4, (LGPFX"Doorbell notification from VM to VM not "
                            "supported (src=0x%x, dst=0x%x).\n",
                            srcCID, handle.context));
         result = VMCI_ERROR_DST_UNREACHABLE;
         goto out;
      }

      result = VMCIDoorbellGetPrivFlags(handle, &dstPrivFlags);
      if (result < VMCI_SUCCESS) {
         VMCI_WARNING((LGPFX"Failed to get privilege flags for destination "
                       "(handle=0x%x:0x%x).\n", handle.context,
                       handle.resource));
         goto out;
      }

      if (srcCID != VMCI_HOST_CONTEXT_ID ||
          srcPrivFlags == VMCI_NO_PRIVILEGE_FLAGS) {
         srcPrivFlags = vmci_context_get_priv_flags(srcCID);
      }

      if (VMCIDenyInteraction(srcPrivFlags, dstPrivFlags)) {
         result = VMCI_ERROR_NO_ACCESS;
         goto out;
      }
   }

   if (handle.context == VMCI_HOST_CONTEXT_ID) {
      result = VMCIDoorbellHostContextNotify(srcCID, handle);
   } else {
      VMCI_GrabLock(&dstContext->lock, &flags);

#if defined(VMKERNEL)
      if (dstContext->inFilters != NULL &&
          VMCIFilterProtoDeny(dstContext->inFilters->filters, handle.resource,
                              VMCI_FP_DOORBELL)) {
         result = VMCI_ERROR_NO_ACCESS;
      } else
#endif // VMKERNEL
      if (!VMCIHandleArray_HasEntry(dstContext->doorbellArray, handle)) {
         result = VMCI_ERROR_NOT_FOUND;
      } else {
         if (!VMCIHandleArray_HasEntry(dstContext->pendingDoorbellArray, handle)) {
            VMCIHandleArray_AppendEntry(&dstContext->pendingDoorbellArray, handle);

            VMCIContextSignalNotify(dstContext);
#if defined(VMKERNEL)
            VMCIHost_SignalBitmap(&dstContext->hostContext);
#else
            VMCIHost_SignalCall(&dstContext->hostContext);
#endif
         }
         result = VMCI_SUCCESS;
      }
      VMCI_ReleaseLock(&dstContext->lock, flags);
   }

out:
   VMCIContext_Release(dstContext);

   return result;
}


#ifdef VMKERNEL

/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SignalPendingDoorbells --
 *
 *      Signals the guest if any doorbell notifications are
 *      pending. This is used after the VMCI device is unquiesced to
 *      ensure that no pending notifications go unnoticed, since
 *      signals may not be fully processed while the device is
 *      quiesced.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_SignalPendingDoorbells(VMCIId contextID)
{
   VMCIContext *context;
   VMCILockFlags flags;
   Bool pending;

   context = VMCIContext_Get(contextID);
   if (!context) {
      ASSERT(FALSE);
      return;
   }

   VMCI_GrabLock(&context->lock, &flags);
   pending = VMCIHandleArray_GetSize(context->pendingDoorbellArray) > 0;
   VMCI_ReleaseLock(&context->lock, flags);

   if (pending) {
      VMCIHost_SignalBitmapAlways(&context->hostContext);
   }

   VMCIContext_Release(context);
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SignalPendingDatagrams --
 *
 *      Signals the guest if any datagrams are pending. This is used
 *      after the VMCI device is unquiesced to ensure that no pending
 *      datagrams go unnoticed, since signals may not be fully
 *      processed while the device is quiesced.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_SignalPendingDatagrams(VMCIId contextID)
{
   Bool pending;
   VMCIContext *context;
   VMCILockFlags flags;

   context = VMCIContext_Get(contextID);
   if (!context) {
      ASSERT(FALSE);
      return;
   }

   VMCI_GrabLock(&context->lock, &flags);
   pending = context->pendingDatagrams;
   VMCI_ReleaseLock(&context->lock, flags);

   if (pending) {
      VMCIHost_SignalCallAlways(&context->hostContext);
   }

   VMCIContext_Release(context);
}

#endif // defined(VMKERNEL)


/*
 *----------------------------------------------------------------------
 *
 * vmci_cid_2_host_vm_id --
 *
 *      Maps a context ID to the host specific (process/world) ID
 *      of the VM/VMX.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(vmci_cid_2_host_vm_id)
int
vmci_cid_2_host_vm_id(VMCIId contextID,    // IN
                      void *hostVmID,      // OUT
                      size_t hostVmIDLen)  // IN
{
#if defined(VMKERNEL)
   VMCIContext *context;
   VMCIHostVmID vmID;
   int result;

   context = VMCIContext_Get(contextID);
   if (!context) {
      return VMCI_ERROR_NOT_FOUND;
   }

   result = VMCIHost_ContextToHostVmID(&context->hostContext, &vmID);
   if (result == VMCI_SUCCESS) {
      if (sizeof vmID == hostVmIDLen) {
         memcpy(hostVmID, &vmID, hostVmIDLen);
      } else {
         result = VMCI_ERROR_INVALID_ARGS;
      }
   }

   VMCIContext_Release(context);

   return result;
#else // !defined(VMKERNEL)
   return VMCI_ERROR_UNAVAILABLE;
#endif
}


/*
 *----------------------------------------------------------------------
 *
 * vmci_is_context_owner --
 *
 *      Determines whether a given host OS specific representation of
 *      user is the owner of the VM/VMX.
 *
 * Results:
 *      Linux: 1 (true) if hostUser is owner, 0 (false) otherwise.
 *      Other: VMCI_SUCCESS if the hostUser is owner, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

VMCI_EXPORT_SYMBOL(vmci_is_context_owner)
#if defined(linux) && !defined(VMKERNEL)
int
vmci_is_context_owner(VMCIId contextID,   // IN
                      VMCIHostUser uid)          // IN
{
   int isOwner = 0;

   if (VMCI_HostPersonalityActive()) {
      VMCIContext *context = VMCIContext_Get(contextID);
      if (context) {
         if (context->validUser) {
            if (VMCIHost_CompareUser(&uid,
                                     &context->user) == VMCI_SUCCESS) {
               isOwner = 1;
            }
         }
         VMCIContext_Release(context);
      }
   }

   return isOwner;
}
#else // !linux || VMKERNEL
int
vmci_is_context_owner(VMCIId contextID,   // IN
                      void *hostUser)     // IN
{
   if (VMCI_HostPersonalityActive()) {
      VMCIContext *context;
      VMCIHostUser *user = (VMCIHostUser *)hostUser;
      int retval;

      if (vmkernel) {
         return VMCI_ERROR_UNAVAILABLE;
      }

      if (!hostUser) {
         return VMCI_ERROR_INVALID_ARGS;
      }

      context = VMCIContext_Get(contextID);
      if (!context) {
         return VMCI_ERROR_NOT_FOUND;
      }

      if (context->validUser) {
         retval = VMCIHost_CompareUser(user, &context->user);
      } else {
         retval = VMCI_ERROR_UNAVAILABLE;
      }
      VMCIContext_Release(context);

      return retval;
   }
   return VMCI_ERROR_UNAVAILABLE;
}
#endif // !linux || VMKERNEL


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_SupportsHostQP --
 *
 *      Can host QPs be connected to this user process.  The answer is
 *      FALSE unless a sufficient version number has previously been set
 *      by this caller.
 *
 * Results:
 *      TRUE if context supports host queue pairs, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

Bool
VMCIContext_SupportsHostQP(VMCIContext *context)    // IN: Context structure
{
#ifdef VMKERNEL
   return TRUE;
#else
   if (!context || context->userVersion < VMCI_VERSION_HOSTQP) {
      return FALSE;
   }
   return TRUE;
#endif
}




/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_QueuePairCreate --
 *
 *      Registers that a new queue pair handle has been allocated by
 *      the context.
 *
 * Results:
 *      VMCI_SUCCESS on success, appropriate error code otherewise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_QueuePairCreate(VMCIContext *context, // IN: Context structure
                            VMCIHandle handle)    // IN
{
   int result;

   if (context == NULL || VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   if (!VMCIHandleArray_HasEntry(context->queuePairArray, handle)) {
      VMCIHandleArray_AppendEntry(&context->queuePairArray, handle);
      result = VMCI_SUCCESS;
   } else {
      result = VMCI_ERROR_DUPLICATE_ENTRY;
   }

   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_QueuePairDestroy --
 *
 *      Unregisters a queue pair handle that was previously registered
 *      with VMCIContext_QueuePairCreate.
 *
 * Results:
 *      VMCI_SUCCESS on success, appropriate error code otherewise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_QueuePairDestroy(VMCIContext *context, // IN: Context structure
                             VMCIHandle handle)    // IN
{
   VMCIHandle removedHandle;

   if (context == NULL || VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   removedHandle = VMCIHandleArray_RemoveEntry(context->queuePairArray, handle);

   if (VMCI_HANDLE_INVALID(removedHandle)) {
      return VMCI_ERROR_NOT_FOUND;
   } else {
      return VMCI_SUCCESS;
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_QueuePairExists --
 *
 *      Determines whether a given queue pair handle is registered
 *      with the given context.
 *
 * Results:
 *      TRUE, if queue pair is registered with context. FALSE, otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

Bool
VMCIContext_QueuePairExists(VMCIContext *context, // IN: Context structure
                            VMCIHandle handle)    // IN
{
   Bool result;

   if (context == NULL || VMCI_HANDLE_INVALID(handle)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   result = VMCIHandleArray_HasEntry(context->queuePairArray, handle);

   return result;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_RegisterGuestMem --
 *
 *      Tells the context that guest memory is available for
 *      access. This should only be used when unquiescing the VMCI
 *      device of a guest.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notifies host side endpoints of queue pairs that the queue pairs
 *      can be accessed.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_RegisterGuestMem(VMCIContext *context, // IN: Context structure
                             VMCIGuestMemID gid)   // IN: Reference to guest
{
#ifdef VMKERNEL
   uint32 numQueuePairs;
   uint32 cur;

   VMCIMutex_Acquire(&context->guestMemMutex);

   if (context->curGuestMemID != INVALID_VMCI_GUEST_MEM_ID) {
      if (context->curGuestMemID != gid) {
         /*
          * The guest memory has been registered with a different guest
          * memory ID. This is possible if we attempt to continue the
          * execution of the source VMX following a failed FSR.
          */

         VMCIContextReleaseGuestMemLocked(context, context->curGuestMemID,
                                          FALSE);
      } else {
         /*
          * When unquiescing the device during a restore sync not part
          * of an FSR, we will already have registered the guest
          * memory when creating the device, so we don't need to do it
          * again. Also, there are no active queue pairs at this
          * point, so nothing to do.
          */

         ASSERT(VMCIHandleArray_GetSize(context->queuePairArray) == 0);
         goto out;
      }
   }
   context->curGuestMemID = gid;

   /*
    * It is safe to access the queue pair array here, since no changes
    * to the queuePairArray can take place until after the unquiescing
    * is complete.
    */

   numQueuePairs = VMCIHandleArray_GetSize(context->queuePairArray);
   for (cur = 0; cur < numQueuePairs; cur++) {
      VMCIHandle handle;
      handle = VMCIHandleArray_GetEntry(context->queuePairArray, cur);
      if (!VMCI_HANDLE_EQUAL(handle, VMCI_INVALID_HANDLE)) {
         int res;

         res = VMCIQPBroker_Map(handle, context, NULL);
         if (res < VMCI_SUCCESS) {
            VMCI_WARNING(("Failed to map guest memory for queue pair "
                          "(handle=0x%x:0x%x, res=%d).\n",
                          handle.context, handle.resource, res));
         }
      }
   }

out:
   VMCIMutex_Release(&context->guestMemMutex);
#endif
}


#ifdef VMKERNEL
/*
 *----------------------------------------------------------------------
 *
 * VMCIContextReleaseGuestMemLocked --
 *
 *      A version of VMCIContext_ReleaseGuestMem that assumes that the
 *      guest mem lock is already held.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static void
VMCIContextReleaseGuestMemLocked(VMCIContext *context, // IN: Context structure
                                 VMCIGuestMemID gid,   // IN: Reference to guest
                                 Bool powerOff)        // IN: Device going away
{
   uint32 numQueuePairs;
   uint32 cur;

   if (powerOff) {
      VMCIContext_NotifyMemoryAccess(context->cid, FALSE);
   }

   /*
    * It is safe to access the queue pair array here, since no changes
    * to the queuePairArray can take place when the the quiescing
    * has been initiated, or when the device is being cleaned up.
    */

   numQueuePairs = VMCIHandleArray_GetSize(context->queuePairArray);
   for (cur = 0; cur < numQueuePairs; cur++) {
      VMCIHandle handle;
      handle = VMCIHandleArray_GetEntry(context->queuePairArray, cur);
      if (!VMCI_HANDLE_EQUAL(handle, VMCI_INVALID_HANDLE)) {
         int res;

         res = VMCIQPBroker_Unmap(handle, context, gid);
         if (res < VMCI_SUCCESS) {
            VMCI_WARNING(("Failed to unmap guest memory for queue pair "
                          "(handle=0x%x:0x%x, res=%d).\n",
                          handle.context, handle.resource, res));
         }
      }
   }
}
#endif


/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_ReleaseGuestMem --
 *
 *      Releases all the contexts references to guest memory, if the
 *      caller identified by the gid was the last one to register the
 *      guest memory. This should only be used when quiescing or
 *      cleaning up the VMCI device of a guest.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

void
VMCIContext_ReleaseGuestMem(VMCIContext *context, // IN: Context structure
                            VMCIGuestMemID gid,   // IN: Reference to guest
                            Bool powerOff)        // IN: Device is going away
{
#ifdef VMKERNEL
   VMCIMutex_Acquire(&context->guestMemMutex);

   if (context->curGuestMemID == gid) {
      /*
       * In the case of an FSR, we may have multiple VMX'en
       * registering and releasing guest memory concurrently. The
       * common case is that the source will clean up its device state
       * after a successful FSR, where the destination may already
       * have registered guest memory. So we only release guest
       * memory, if this is the same gid, that registered the memory.
       */

      VMCIContextReleaseGuestMemLocked(context, gid, powerOff);
      context->curGuestMemID = INVALID_VMCI_GUEST_MEM_ID;
   }

   VMCIMutex_Release(&context->guestMemMutex);
#endif
}

#if defined(VMKERNEL)
/*
 *----------------------------------------------------------------------
 *
 * VMCIContext_FilterSet --
 *
 *      Sets an ingoing (host to guest) filter for the VMCI firewall of the
 *      given context. If a filter list already exists for the given filter
 *      entry, the old entry will be deleted. It is assumed that the list
 *      can be used as is, and that the memory backing it will be freed by the
 *      VMCI Context module once the filter is deleted.
 *
 * Results:
 *      VMCI_SUCCESS on success,
 *      VMCI_ERROR_NOT_FOUND if there is no active context linked to the cid,
 *      VMCI_ERROR_INVALID_ARGS if a non-VM cid is specified.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCIContext_FilterSet(VMCIId cid,                // IN
                      VMCIFilterState *filters)  // IN
{
   VMCIContext *context;
   VMCILockFlags flags;
   VMCIFilterState *oldState;

   if (!VMCI_CONTEXT_IS_VM(cid)) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   context = VMCIContext_Get(cid);
   if (!context) {
      return VMCI_ERROR_NOT_FOUND;
   }

   VMCI_GrabLock(&context->lock, &flags);

   oldState = context->inFilters;
   context->inFilters = filters;

   VMCI_ReleaseLock(&context->lock, flags);
   if (oldState) {
      VMCIVMKDevFreeFilterState(oldState);
   }
   VMCIContext_Release(context);

   return VMCI_SUCCESS;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCIContextInFilterCleanup --
 *
 *      When a context is destroyed, all filters will be deleted.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

static void
VMCIContextInFilterCleanup(VMCIContext *context)
{
   if (context->inFilters != NULL) {
      VMCIVMKDevFreeFilterState(context->inFilters);
      context->inFilters = NULL;
   }
}


/*
 *----------------------------------------------------------------------
 *
 * VMCI_Uuid2ContextId --
 *
 *      Given a running VM's UUID, retrieve the VM's VMCI context ID.
 *      The given UUID is local to the host; it is _not_ the UUID
 *      handed out by VC.  It comes from the "bios.uuid" field in the
 *      VMX file.  We walk the context list and try to match the given
 *      UUID against each context.  If we get a match, we return the
 *      contexts's VMCI ID.
 *
 * Results:
 *      VMCI_SUCCESS if found and *contextID contains the CID.
 *      VMCI_ERROR_INVALID_ARGS for bad parameters.
 *      VMCI_ERROR_NOT_FOUND if no match.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
VMCI_Uuid2ContextId(const char *uuidString, // IN
                    VMCIId *contextID)      // OUT
{
   int err;
   VMCIListItem *next;
   VMCILockFlags flags;

   if (!uuidString || *uuidString == '\0' || !contextID) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   err = VMCI_ERROR_NOT_FOUND;

   VMCI_GrabLock(&contextList.lock, &flags);
   VMCIList_Scan(next, &contextList.head) {
      VMCIContext *context = VMCIList_Entry(next, VMCIContext, listItem);
      if (VMCIHost_ContextHasUuid(&context->hostContext, uuidString) ==
          VMCI_SUCCESS) {
         *contextID = context->cid;
         err = VMCI_SUCCESS;
         break;
      }
   }
   VMCI_ReleaseLock(&contextList.lock, flags);

   return err;
}
#endif // VMKERNEL