summaryrefslogtreecommitdiff
path: root/open-vm-tools/modules/linux/vmci/linux/driver.c
blob: c9519ca20ed6688afdb9aa0b385a8f05c45f1c94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
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
/*********************************************************
 * Copyright (C) 2011 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
 *
 *********************************************************/

/* Must come before any kernel header file */
#include "driver-config.h"

#define EXPORT_SYMTAB

#include <asm/atomic.h>
#include <asm/io.h>

#include <linux/file.h>
#include <linux/fs.h>
#include <linux/init.h>
#if defined(__x86_64__) && LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 12)
#   include <linux/ioctl32.h>
/* Use weak: not all kernels export sys_ioctl for use by modules */
asmlinkage __attribute__((weak)) long
sys_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg);
#endif
#include <linux/miscdevice.h>
#include <linux/moduleparam.h>
#include <linux/poll.h>
#include <linux/smp.h>

#include "compat_highmem.h"
#include "compat_interrupt.h"
#include "compat_ioport.h"
#include "compat_kernel.h"
#include "compat_mm.h"
#include "compat_module.h"
#include "compat_mutex.h"
#include "compat_page.h"
#include "compat_pci.h"
#include "compat_sched.h"
#include "compat_slab.h"
#include "compat_uaccess.h"
#include "compat_version.h"

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 9)
#  error "Linux kernels before 2.6.9 are not supported."
#endif

#include "vm_basic_types.h"
#include "vm_device_version.h"

#include "vmware.h"
#include "driverLog.h"
#include "pgtbl.h"
#include "vmci_defs.h"
#include "vmci_handle_array.h"
#include "vmci_infrastructure.h"
#include "vmci_iocontrols.h"
#include "vmci_version.h"
#include "vmci_kernel_if.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"
#include "vmciResource.h"

#define LGPFX "VMCI: "

#define VMCI_DEVICE_NAME   "vmci"
#define VMCI_MODULE_NAME   "vmci"


/*
 *----------------------------------------------------------------------
 *
 * PCI Device interface --
 *
 *      Declarations of types and functions related to the VMCI PCI
 *      device personality.
 *
 *
 *----------------------------------------------------------------------
 */

/*
 * VMCI PCI driver state
 */

typedef struct vmci_device {
   compat_mutex_t    lock;

   unsigned int      ioaddr;
   unsigned int      ioaddr_size;
   unsigned int      irq;
   unsigned int      intr_type;
   Bool              exclusive_vectors;
   struct msix_entry msix_entries[VMCI_MAX_INTRS];

   Bool              enabled;
   spinlock_t        dev_spinlock;
   atomic_t          datagrams_allowed;
} vmci_device;

static const struct pci_device_id vmci_ids[] = {
   { PCI_DEVICE(PCI_VENDOR_ID_VMWARE, PCI_DEVICE_ID_VMWARE_VMCI), },
   { 0 },
};

static int vmci_probe_device(struct pci_dev *pdev,
                             const struct pci_device_id *id);
static void vmci_remove_device(struct pci_dev* pdev);

static struct pci_driver vmci_driver = {
   .name     = VMCI_DEVICE_NAME,
   .id_table = vmci_ids,
   .probe = vmci_probe_device,
   .remove = vmci_remove_device,
};

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19)
static compat_irqreturn_t vmci_interrupt(int irq, void *dev_id,
                                           struct pt_regs * regs);
static compat_irqreturn_t vmci_interrupt_bm(int irq, void *dev_id,
                                            struct pt_regs * regs);
#else
static compat_irqreturn_t vmci_interrupt(int irq, void *dev_id);
static compat_irqreturn_t vmci_interrupt_bm(int irq, void *dev_id);
#endif
static void dispatch_datagrams(unsigned long data);
static void process_bitmap(unsigned long data);

/* MSI-X has performance problems in < 2.6.19 */
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 19)
#  define VMCI_DISABLE_MSIX   0
#else
#  define VMCI_DISABLE_MSIX   1
#endif

/*
 * Needed by other components of this module.  It's okay to have one global
 * instance of this because there can only ever be one VMCI device.  Our
 * virtual hardware enforces this.
 */

struct pci_dev *vmci_pdev;

static vmci_device vmci_dev;
static compat_mod_param_bool vmci_disable_host = 0;
static compat_mod_param_bool vmci_disable_guest = 0;
static compat_mod_param_bool vmci_disable_msi;
static compat_mod_param_bool vmci_disable_msix = VMCI_DISABLE_MSIX;

DECLARE_TASKLET(vmci_dg_tasklet, dispatch_datagrams,
                (unsigned long)&vmci_dev);

DECLARE_TASKLET(vmci_bm_tasklet, process_bitmap,
                (unsigned long)&vmci_dev);

/*
 * Allocate a buffer for incoming datagrams globally to avoid repeated
 * allocation in the interrupt handler's atomic context.
 */

static uint8 *data_buffer = NULL;
static uint32 data_buffer_size = VMCI_MAX_DG_SIZE;

/*
 * If the VMCI hardware supports the notification bitmap, we allocate
 * and register a page with the device.
 */

static uint8 *notification_bitmap;
static dma_addr_t notification_base;


/*
 *----------------------------------------------------------------------
 *
 * Host device node interface --
 *
 *      Implements VMCI by implementing open/close/ioctl functions
 *
 *
 *----------------------------------------------------------------------
 */

/*
 * Per-instance host state
 */

typedef struct VMCILinux {
   VMCIContext *context;
   int userVersion;
   VMCIObjType ctType;
#if defined(HAVE_COMPAT_IOCTL) || defined(HAVE_UNLOCKED_IOCTL)
   compat_mutex_t lock;
#endif
} VMCILinux;

/*
 * Static driver state.
 */

#define VM_DEVICE_NAME_SIZE 32
#define LINUXLOG_BUFFER_SIZE  1024

typedef struct VMCILinuxState {
   struct miscdevice misc;
   char buf[LINUXLOG_BUFFER_SIZE];
   atomic_t activeContexts;
} VMCILinuxState;

static int VMCISetupNotify(VMCIContext *context, VA notifyUVA);
static void VMCIUnsetNotifyInt(VMCIContext *context, Bool useLock);

static int LinuxDriver_Open(struct inode *inode, struct file *filp);

static int LinuxDriver_Ioctl(struct inode *inode, struct file *filp,
                             u_int iocmd, unsigned long ioarg);

#if defined(HAVE_COMPAT_IOCTL) || defined(HAVE_UNLOCKED_IOCTL)
static long LinuxDriver_UnlockedIoctl(struct file *filp,
                                      u_int iocmd, unsigned long ioarg);
#endif

static int LinuxDriver_Close(struct inode *inode, struct file *filp);
static unsigned int LinuxDriverPoll(struct file *file, poll_table *wait);


#if defined(HAVE_COMPAT_IOCTL) || defined(HAVE_UNLOCKED_IOCTL)
#define LinuxDriverLockIoctlPerFD(mutex) compat_mutex_lock(mutex)
#define LinuxDriverUnlockIoctlPerFD(mutex) compat_mutex_unlock(mutex)
#else
#define LinuxDriverLockIoctlPerFD(mutex) do {} while (0)
#define LinuxDriverUnlockIoctlPerFD(mutex) do {} while (0)
#endif

/* should be const if not for older kernels support */
static struct file_operations vmuser_fops = {
   .owner            = THIS_MODULE,
   .open             = LinuxDriver_Open,
   .release          = LinuxDriver_Close,
   .poll             = LinuxDriverPoll,
#ifdef HAVE_UNLOCKED_IOCTL
   .unlocked_ioctl   = LinuxDriver_UnlockedIoctl,
#else
   .ioctl            = LinuxDriver_Ioctl,
#endif
#ifdef HAVE_COMPAT_IOCTL
   .compat_ioctl     = LinuxDriver_UnlockedIoctl,
#endif
};

static struct VMCILinuxState linuxState = {
   .misc             = {
      .name          = VMCI_DEVICE_NAME,
      .minor         = MISC_DYNAMIC_MINOR,
      .fops          = &vmuser_fops,
   },
   .activeContexts   = ATOMIC_INIT(0),
};


/*
 *----------------------------------------------------------------------
 *
 * Shared VMCI device definitions --
 *
 *      Types and variables shared by both host and guest personality
 *
 *
 *----------------------------------------------------------------------
 */

static Bool guestDeviceInit;
static atomic_t guestDeviceActive;
static Bool hostDeviceInit;

/*
 *-----------------------------------------------------------------------------
 *
 * Host device support --
 *
 *      The following functions implement the support for the VMCI
 *      host driver.
 *
 *
 *-----------------------------------------------------------------------------
 */


#ifdef VM_X86_64
#ifndef HAVE_COMPAT_IOCTL
static int
LinuxDriver_Ioctl32_Handler(unsigned int fd, unsigned int iocmd,
                            unsigned long ioarg, struct file * filp)
{
   int ret;
   ret = -ENOTTY;
   if (filp && filp->f_op && filp->f_op->ioctl == LinuxDriver_Ioctl) {
      ret = LinuxDriver_Ioctl(filp->f_dentry->d_inode, filp, iocmd, ioarg);
   }
   return ret;
}
#endif /* !HAVE_COMPAT_IOCTL */

static int
register_ioctl32_handlers(void)
{
#ifndef HAVE_COMPAT_IOCTL
   {
      int i;

      for (i = IOCTL_VMCI_FIRST; i < IOCTL_VMCI_LAST; i++) {
         int retval = register_ioctl32_conversion(i,
                                                  LinuxDriver_Ioctl32_Handler);

         if (retval) {
            Warning(LGPFX"Failed to register ioctl32 conversion "
                    "(cmd=%d,err=%d).\n", i, retval);
            return retval;
         }
      }

      for (i = IOCTL_VMCI_FIRST2; i < IOCTL_VMCI_LAST2; i++) {
         int retval = register_ioctl32_conversion(i,
                                                  LinuxDriver_Ioctl32_Handler);

         if (retval) {
            Warning(LGPFX"Failed to register ioctl32 conversion "
                    "(cmd=%d,err=%d).\n", i, retval);
            return retval;
         }
      }
   }
#endif /* !HAVE_COMPAT_IOCTL */
   return 0;
}

static void
unregister_ioctl32_handlers(void)
{
#ifndef HAVE_COMPAT_IOCTL
   {
      int i;

      for (i = IOCTL_VMCI_FIRST; i < IOCTL_VMCI_LAST; i++) {
         int retval = unregister_ioctl32_conversion(i);

         if (retval) {
            Warning(LGPFX"Failed to unregister ioctl32 conversion "
                    "(cmd=%d,err=%d).\n", i, retval);
         }
      }

      for (i = IOCTL_VMCI_FIRST2; i < IOCTL_VMCI_LAST2; i++) {
         int retval = unregister_ioctl32_conversion(i);

         if (retval) {
            Warning(LGPFX"Failed to unregister ioctl32 conversion "
                    "(cmd=%d,err=%d).\n", i, retval);
         }
      }
   }
#endif /* !HAVE_COMPAT_IOCTL */
}
#else /* VM_X86_64 */
#define register_ioctl32_handlers() (0)
#define unregister_ioctl32_handlers() do { } while (0)
#endif /* VM_X86_64 */


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_host_init --
 *
 *      Initializes the VMCI host device driver.
 *
 * Results:
 *      0 on success, other error codes on failure.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
vmci_host_init(void)
{
   int error;

   if (VMCI_HostInit() < VMCI_SUCCESS) {
      return -ENOMEM;
   }

   error = misc_register(&linuxState.misc);
   if (error) {
      Warning(LGPFX "Module registration error "
              "(name=%s, major=%d, minor=%d, err=%d).\n",
              linuxState.misc.name, MISC_MAJOR, linuxState.misc.minor,
              error);
      goto err_host_cleanup;
   }

   error = register_ioctl32_handlers();
   if (error) {
      Warning(LGPFX "Failed to register ioctl32 handlers, err: %d\n", error);
      goto err_misc_unregister;
   }

   Log(LGPFX "Module registered (name=%s, major=%d, minor=%d).\n",
       linuxState.misc.name, MISC_MAJOR, linuxState.misc.minor);

   return 0;

err_misc_unregister:
   misc_deregister(&linuxState.misc);
err_host_cleanup:
   VMCI_HostCleanup();
   return error;
}


/*
 *----------------------------------------------------------------------
 *
 * LinuxDriver_Open  --
 *
 *     Called on open of /dev/vmci.
 *
 * Side effects:
 *     Increment use count used to determine eventual deallocation of
 *     the module
 *
 *----------------------------------------------------------------------
 */

static int
LinuxDriver_Open(struct inode *inode, // IN
                 struct file *filp)   // IN
{
   VMCILinux *vmciLinux;

   vmciLinux = kmalloc(sizeof *vmciLinux, GFP_KERNEL);
   if (vmciLinux == NULL) {
      return -ENOMEM;
   }
   memset(vmciLinux, 0, sizeof *vmciLinux);
   vmciLinux->ctType = VMCIOBJ_NOT_SET;
   vmciLinux->userVersion = 0;
#if defined(HAVE_COMPAT_IOCTL) || defined(HAVE_UNLOCKED_IOCTL)
   compat_mutex_init(&vmciLinux->lock);
#endif

   filp->private_data = vmciLinux;

   return 0;
}


/*
 *----------------------------------------------------------------------
 *
 * LinuxDriver_Close  --
 *
 *      Called on close of /dev/vmci, most often when the process
 *      exits.
 *
 *----------------------------------------------------------------------
 */

static int
LinuxDriver_Close(struct inode *inode, // IN
                  struct file *filp)   // IN
{
   VMCILinux *vmciLinux;

   vmciLinux = (VMCILinux *)filp->private_data;
   ASSERT(vmciLinux);

   if (vmciLinux->ctType == VMCIOBJ_CONTEXT) {
      ASSERT(vmciLinux->context);

      VMCIContext_ReleaseContext(vmciLinux->context);
      vmciLinux->context = NULL;

      /*
       * The number of active contexts is used to track whether any
       * VMX'en are using the host personality. It is incremented when
       * a context is created through the IOCTL_VMCI_INIT_CONTEXT
       * ioctl.
       */

      atomic_dec(&linuxState.activeContexts);
   }
   vmciLinux->ctType = VMCIOBJ_NOT_SET;

   kfree(vmciLinux);
   filp->private_data = NULL;
   return 0;
}


/*
 *----------------------------------------------------------------------
 *
 * LinuxDriverPoll  --
 *
 *      This is used to wake up the VMX when a VMCI call arrives, or
 *      to wake up select() or poll() at the next clock tick.
 *
 *----------------------------------------------------------------------
 */

static unsigned int
LinuxDriverPoll(struct file *filp,
                poll_table *wait)
{
   VMCILockFlags flags;
   VMCILinux *vmciLinux = (VMCILinux *) filp->private_data;
   unsigned int mask = 0;

   if (vmciLinux->ctType == VMCIOBJ_CONTEXT) {
      ASSERT(vmciLinux->context != NULL);
      /*
       * Check for VMCI calls to this VM context.
       */

      if (wait != NULL) {
         poll_wait(filp, &vmciLinux->context->hostContext.waitQueue, wait);
      }

      VMCI_GrabLock(&vmciLinux->context->lock, &flags);
      if (vmciLinux->context->pendingDatagrams > 0 ||
          VMCIHandleArray_GetSize(vmciLinux->context->pendingDoorbellArray) > 0) {
         mask = POLLIN;
      }
      VMCI_ReleaseLock(&vmciLinux->context->lock, flags);
   }
   return mask;
}


/*
 *----------------------------------------------------------------------
 *
 * VMCICopyHandleArrayToUser  --
 *
 *      Copies the handles of a handle array into a user buffer, and
 *      returns the new length in userBufferSize. If the copy to the
 *      user buffer fails, the functions still returns VMCI_SUCCESS,
 *      but retval != 0.
 *
 *----------------------------------------------------------------------
 */

static int
VMCICopyHandleArrayToUser(void *userBufUVA,             // IN
                          uint64 *userBufSize,          // IN/OUT
                          VMCIHandleArray *handleArray, // IN
                          int *retval)                  // IN
{
   uint32 arraySize;
   VMCIHandle *handles;

   if (handleArray) {
      arraySize = VMCIHandleArray_GetSize(handleArray);
   } else {
      arraySize = 0;
   }

   if (arraySize * sizeof *handles > *userBufSize) {
      return VMCI_ERROR_MORE_DATA;
   }

   *userBufSize = arraySize * sizeof *handles;
   if (*userBufSize) {
      *retval = copy_to_user(userBufUVA,
                             VMCIHandleArray_GetHandles(handleArray),
                             *userBufSize);
   }

   return VMCI_SUCCESS;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIDoQPBrokerAlloc --
 *
 *      Helper function for creating queue pair and copying the result
 *      to user memory.
 *
 * Results:
 *      0 if result value was copied to user memory, -EFAULT otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
VMCIDoQPBrokerAlloc(VMCIHandle handle,
                    VMCIId peer,
                    uint32 flags,
                    uint64 produceSize,
                    uint64 consumeSize,
                    QueuePairPageStore *pageStore,
                    VMCIContext *context,
                    Bool vmToVm,
                    void *resultUVA)
{
   VMCIId cid;
   int result;
   int retval;

   cid = VMCIContext_GetId(context);

   result = VMCIQPBroker_Alloc(handle, peer, flags, VMCI_NO_PRIVILEGE_FLAGS,
                               produceSize, consumeSize, pageStore, context);
   if (result == VMCI_SUCCESS && vmToVm) {
      result = VMCI_SUCCESS_QUEUEPAIR_CREATE;
   }
   retval = copy_to_user(resultUVA, &result, sizeof result);
   if (retval) {
      retval = -EFAULT;
      if (result >= VMCI_SUCCESS) {
         result = VMCIQPBroker_Detach(handle, context);
         ASSERT(result >= VMCI_SUCCESS);
      }
   }

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * LinuxDriver_Ioctl --
 *
 *      Main path for UserRPC
 *
 * Results:
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
LinuxDriver_Ioctl(struct inode *inode,
                  struct file *filp,
                  u_int iocmd,
                  unsigned long ioarg)
{
   VMCILinux *vmciLinux = (VMCILinux *) filp->private_data;
   int retval = 0;

   switch (iocmd) {
   case IOCTL_VMCI_VERSION2: {
      int verFromUser;

      if (copy_from_user(&verFromUser, (void *)ioarg, sizeof verFromUser)) {
         retval = -EFAULT;
         break;
      }

      vmciLinux->userVersion = verFromUser;
   }
      /* Fall through. */
   case IOCTL_VMCI_VERSION:
      /*
       * The basic logic here is:
       *
       * If the user sends in a version of 0 tell it our version.
       * If the user didn't send in a version, tell it our version.
       * If the user sent in an old version, tell it -its- version.
       * If the user sent in an newer version, tell it our version.
       *
       * The rationale behind telling the caller its version is that
       * Workstation 6.5 required that VMX and VMCI kernel module were
       * version sync'd.  All new VMX users will be programmed to
       * handle the VMCI kernel module version.
       */

      if (vmciLinux->userVersion > 0 &&
          vmciLinux->userVersion < VMCI_VERSION_HOSTQP) {
         retval = vmciLinux->userVersion;
      } else {
         retval = VMCI_VERSION;
      }
      break;

   case IOCTL_VMCI_INIT_CONTEXT: {
      VMCIInitBlock initBlock;
      VMCIHostUser user;

      retval = copy_from_user(&initBlock, (void *)ioarg, sizeof initBlock);
      if (retval != 0) {
         Log(LGPFX"Error reading init block.\n");
         retval = -EFAULT;
         break;
      }

      LinuxDriverLockIoctlPerFD(&vmciLinux->lock);
      if (vmciLinux->ctType != VMCIOBJ_NOT_SET) {
         Log(LGPFX"Received VMCI init on initialized handle.\n");
         retval = -EINVAL;
         goto init_release;
      }

      if (initBlock.flags & ~VMCI_PRIVILEGE_FLAG_RESTRICTED) {
         Log(LGPFX"Unsupported VMCI restriction flag.\n");
         retval = -EINVAL;
         goto init_release;
      }

      user = current_uid();
      retval = VMCIContext_InitContext(initBlock.cid, initBlock.flags,
                                       0 /* Unused */, vmciLinux->userVersion,
                                       &user, &vmciLinux->context);
      if (retval < VMCI_SUCCESS) {
         Log(LGPFX"Error initializing context.\n");
         retval = retval == VMCI_ERROR_DUPLICATE_ENTRY ? -EEXIST : -EINVAL;
         goto init_release;
      }

      /*
       * Copy cid to userlevel, we do this to allow the VMX to enforce its
       * policy on cid generation.
       */
      initBlock.cid = VMCIContext_GetId(vmciLinux->context);
      retval = copy_to_user((void *)ioarg, &initBlock, sizeof initBlock);
      if (retval != 0) {
         VMCIContext_ReleaseContext(vmciLinux->context);
         vmciLinux->context = NULL;
         Log(LGPFX"Error writing init block.\n");
         retval = -EFAULT;
         goto init_release;
      }
      ASSERT(initBlock.cid != VMCI_INVALID_ID);

      vmciLinux->ctType = VMCIOBJ_CONTEXT;

      atomic_inc(&linuxState.activeContexts);

     init_release:
      LinuxDriverUnlockIoctlPerFD(&vmciLinux->lock);
      break;
   }

   case IOCTL_VMCI_DATAGRAM_SEND: {
      VMCIDatagramSendRecvInfo sendInfo;
      VMCIDatagram *dg = NULL;
      VMCIId cid;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Warning(LGPFX"Ioctl only valid for context handle (iocmd=%d).\n", iocmd);
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&sendInfo, (void *) ioarg, sizeof sendInfo);
      if (retval) {
         Warning(LGPFX"copy_from_user failed.\n");
         retval = -EFAULT;
         break;
      }

      if (sendInfo.len > VMCI_MAX_DG_SIZE) {
         Warning(LGPFX"Datagram too big (size=%d).\n", sendInfo.len);
         retval = -EINVAL;
         break;
      }

      if (sendInfo.len < sizeof *dg) {
         Warning(LGPFX"Datagram too small (size=%d).\n", sendInfo.len);
         retval = -EINVAL;
         break;
      }

      dg = VMCI_AllocKernelMem(sendInfo.len, VMCI_MEMORY_NORMAL);
      if (dg == NULL) {
         Log(LGPFX"Cannot allocate memory to dispatch datagram.\n");
         retval = -ENOMEM;
         break;
      }

      retval = copy_from_user(dg, (char *)(VA)sendInfo.addr, sendInfo.len);
      if (retval != 0) {
         Log(LGPFX"Error getting datagram (err=%d).\n", retval);
         VMCI_FreeKernelMem(dg, sendInfo.len);
         retval = -EFAULT;
         break;
      }

      VMCI_DEBUG_LOG(10, (LGPFX"Datagram dst (handle=0x%x:0x%x) src "
                          "(handle=0x%x:0x%x), payload (size=%"FMT64"u "
                          "bytes).\n", dg->dst.context, dg->dst.resource,
                          dg->src.context, dg->src.resource,
                          dg->payloadSize));

      /* Get source context id. */
      ASSERT(vmciLinux->context);
      cid = VMCIContext_GetId(vmciLinux->context);
      ASSERT(cid != VMCI_INVALID_ID);
      sendInfo.result = VMCIDatagram_Dispatch(cid, dg, TRUE);
      VMCI_FreeKernelMem(dg, sendInfo.len);
      retval = copy_to_user((void *)ioarg, &sendInfo, sizeof sendInfo);
      break;
   }

   case IOCTL_VMCI_DATAGRAM_RECEIVE: {
      VMCIDatagramSendRecvInfo recvInfo;
      VMCIDatagram *dg = NULL;
      size_t size;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Warning(LGPFX"Ioctl only valid for context handle (iocmd=%d).\n",
                 iocmd);
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&recvInfo, (void *) ioarg, sizeof recvInfo);
      if (retval) {
         Warning(LGPFX"copy_from_user failed.\n");
         retval = -EFAULT;
         break;
      }

      ASSERT(vmciLinux->ctType == VMCIOBJ_CONTEXT);

      size = recvInfo.len;
      ASSERT(vmciLinux->context);
      recvInfo.result = VMCIContext_DequeueDatagram(vmciLinux->context,
                                                    &size, &dg);

      if (recvInfo.result >= VMCI_SUCCESS) {
         ASSERT(dg);
         retval = copy_to_user((void *) ((uintptr_t) recvInfo.addr), dg,
                               VMCI_DG_SIZE(dg));
         VMCI_FreeKernelMem(dg, VMCI_DG_SIZE(dg));
         if (retval != 0) {
            break;
         }
      }
      retval = copy_to_user((void *)ioarg, &recvInfo, sizeof recvInfo);
      break;
   }

   case IOCTL_VMCI_QUEUEPAIR_ALLOC: {
      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_QUEUEPAIR_ALLOC only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      if (vmciLinux->userVersion < VMCI_VERSION_NOVMVM) {
         VMCIQueuePairAllocInfo_VMToVM queuePairAllocInfo;
         VMCIQueuePairAllocInfo_VMToVM *info = (VMCIQueuePairAllocInfo_VMToVM *)ioarg;

         retval = copy_from_user(&queuePairAllocInfo, (void *)ioarg,
                                 sizeof queuePairAllocInfo);
         if (retval) {
            retval = -EFAULT;
            break;
         }

         retval = VMCIDoQPBrokerAlloc(queuePairAllocInfo.handle,
                                      queuePairAllocInfo.peer,
                                      queuePairAllocInfo.flags,
                                      queuePairAllocInfo.produceSize,
                                      queuePairAllocInfo.consumeSize,
                                      NULL,
                                      vmciLinux->context,
                                      TRUE, // VM to VM style create
                                      &info->result);
      } else {
         VMCIQueuePairAllocInfo queuePairAllocInfo;
         VMCIQueuePairAllocInfo *info = (VMCIQueuePairAllocInfo *)ioarg;
         QueuePairPageStore pageStore;

         retval = copy_from_user(&queuePairAllocInfo, (void *)ioarg,
                                 sizeof queuePairAllocInfo);
         if (retval) {
            retval = -EFAULT;
            break;
         }

         pageStore.pages = queuePairAllocInfo.ppnVA;
         pageStore.len = queuePairAllocInfo.numPPNs;

         retval = VMCIDoQPBrokerAlloc(queuePairAllocInfo.handle,
                                      queuePairAllocInfo.peer,
                                      queuePairAllocInfo.flags,
                                      queuePairAllocInfo.produceSize,
                                      queuePairAllocInfo.consumeSize,
                                      &pageStore,
                                      vmciLinux->context,
                                      FALSE, // Not VM to VM style create
                                      &info->result);
      }
      break;
   }

   case IOCTL_VMCI_QUEUEPAIR_SETVA: {
      VMCIQueuePairSetVAInfo setVAInfo;
      VMCIQueuePairSetVAInfo *info = (VMCIQueuePairSetVAInfo *)ioarg;
      int32 result;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_QUEUEPAIR_SETVA only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      if (vmciLinux->userVersion < VMCI_VERSION_NOVMVM) {
         Log(LGPFX"IOCTL_VMCI_QUEUEPAIR_SETVA not supported for this VMX version.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&setVAInfo, (void *)ioarg, sizeof setVAInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      if (setVAInfo.va) {
         /*
          * VMX is passing down a new VA for the queue pair mapping.
          */

         result = VMCIQPBroker_Map(setVAInfo.handle, vmciLinux->context, setVAInfo.va);
      } else {
         /*
          * The queue pair is about to be unmapped by the VMX.
          */

         result = VMCIQPBroker_Unmap(setVAInfo.handle, vmciLinux->context, 0);
      }

      retval = copy_to_user(&info->result, &result, sizeof result);
      if (retval) {
         retval = -EFAULT;
      }

      break;
   }

   case IOCTL_VMCI_QUEUEPAIR_SETPAGEFILE: {
      VMCIQueuePairPageFileInfo pageFileInfo;
      VMCIQueuePairPageFileInfo *info = (VMCIQueuePairPageFileInfo *)ioarg;
      int32 result;

      if (vmciLinux->userVersion < VMCI_VERSION_HOSTQP ||
          vmciLinux->userVersion >= VMCI_VERSION_NOVMVM) {
         Log(LGPFX"IOCTL_VMCI_QUEUEPAIR_SETPAGEFILE not supported this VMX "
             "(version=%d).\n", vmciLinux->userVersion);
         retval = -EINVAL;
         break;
      }

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_QUEUEPAIR_SETPAGEFILE only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&pageFileInfo, (void *)ioarg, sizeof *info);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      /*
       * Communicate success pre-emptively to the caller.  Note that
       * the basic premise is that it is incumbent upon the caller not
       * to look at the info.result field until after the ioctl()
       * returns.  And then, only if the ioctl() result indicates no
       * error.  We send up the SUCCESS status before calling
       * SetPageStore() store because failing to copy up the result
       * code means unwinding the SetPageStore().
       *
       * It turns out the logic to unwind a SetPageStore() opens a can
       * of worms.  For example, if a host had created the QueuePair
       * and a guest attaches and SetPageStore() is successful but
       * writing success fails, then ... the host has to be stopped
       * from writing (anymore) data into the QueuePair.  That means
       * an additional test in the VMCI_Enqueue() code path.  Ugh.
       */

      result = VMCI_SUCCESS;
      retval = copy_to_user(&info->result, &result, sizeof result);
      if (retval == 0) {
         result = VMCIQPBroker_SetPageStore(pageFileInfo.handle,
                                            pageFileInfo.produceVA,
                                            pageFileInfo.consumeVA,
                                            vmciLinux->context);
         if (result < VMCI_SUCCESS) {

            retval = copy_to_user(&info->result, &result, sizeof result);
            if (retval != 0) {
               /*
                * Note that in this case the SetPageStore() call
                * failed but we were unable to communicate that to the
                * caller (because the copy_to_user() call failed).
                * So, if we simply return an error (in this case
                * -EFAULT) then the caller will know that the
                * SetPageStore failed even though we couldn't put the
                * result code in the result field and indicate exactly
                * why it failed.
                *
                * That says nothing about the issue where we were once
                * able to write to the caller's info memory and now
                * can't.  Something more serious is probably going on
                * than the fact that SetPageStore() didn't work.
                */
               retval = -EFAULT;
            }
         }

      } else {
         /*
          * In this case, we can't write a result field of the
          * caller's info block.  So, we don't even try to
          * SetPageStore().
          */
         retval = -EFAULT;
      }

      break;
   }

   case IOCTL_VMCI_QUEUEPAIR_DETACH: {
      VMCIQueuePairDetachInfo detachInfo;
      VMCIQueuePairDetachInfo *info = (VMCIQueuePairDetachInfo *)ioarg;
      int32 result;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_QUEUEPAIR_DETACH only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&detachInfo, (void *)ioarg, sizeof detachInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      result = VMCIQPBroker_Detach(detachInfo.handle, vmciLinux->context);
      if (result == VMCI_SUCCESS &&
          vmciLinux->userVersion < VMCI_VERSION_NOVMVM) {
         result = VMCI_SUCCESS_LAST_DETACH;
      }

      retval = copy_to_user(&info->result, &result, sizeof result);
      if (retval) {
         retval = -EFAULT;
      }

      break;
   }

   case IOCTL_VMCI_CTX_ADD_NOTIFICATION: {
      VMCINotifyAddRemoveInfo arInfo;
      VMCINotifyAddRemoveInfo *info = (VMCINotifyAddRemoveInfo *)ioarg;
      int32 result;
      VMCIId cid;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_CTX_ADD_NOTIFICATION only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&arInfo, (void *)ioarg, sizeof arInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      cid = VMCIContext_GetId(vmciLinux->context);
      result = VMCIContext_AddNotification(cid, arInfo.remoteCID);
      retval = copy_to_user(&info->result, &result, sizeof result);
      if (retval) {
         retval = -EFAULT;
         break;
      }
      break;
   }

   case IOCTL_VMCI_CTX_REMOVE_NOTIFICATION: {
      VMCINotifyAddRemoveInfo arInfo;
      VMCINotifyAddRemoveInfo *info = (VMCINotifyAddRemoveInfo *)ioarg;
      int32 result;
      VMCIId cid;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_CTX_REMOVE_NOTIFICATION only valid for "
             "contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&arInfo, (void *)ioarg, sizeof arInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      cid = VMCIContext_GetId(vmciLinux->context);
      result = VMCIContext_RemoveNotification(cid, arInfo.remoteCID);
      retval = copy_to_user(&info->result, &result, sizeof result);
      if (retval) {
         retval = -EFAULT;
         break;
      }
      break;
   }

   case IOCTL_VMCI_CTX_GET_CPT_STATE: {
      VMCICptBufInfo getInfo;
      VMCIId cid;
      char *cptBuf;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_CTX_GET_CPT_STATE only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&getInfo, (void *)ioarg, sizeof getInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      cid = VMCIContext_GetId(vmciLinux->context);
      getInfo.result = VMCIContext_GetCheckpointState(cid, getInfo.cptType,
                                                      &getInfo.bufSize,
                                                      &cptBuf);
      if (getInfo.result == VMCI_SUCCESS && getInfo.bufSize) {
         retval = copy_to_user((void *)(VA)getInfo.cptBuf, cptBuf,
                               getInfo.bufSize);
         VMCI_FreeKernelMem(cptBuf, getInfo.bufSize);
         if (retval) {
            retval = -EFAULT;
            break;
         }
      }
      retval = copy_to_user((void *)ioarg, &getInfo, sizeof getInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }
      break;
   }

   case IOCTL_VMCI_CTX_SET_CPT_STATE: {
      VMCICptBufInfo setInfo;
      VMCIId cid;
      char *cptBuf;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_CTX_SET_CPT_STATE only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&setInfo, (void *)ioarg, sizeof setInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      cptBuf = VMCI_AllocKernelMem(setInfo.bufSize, VMCI_MEMORY_NORMAL);
      if (cptBuf == NULL) {
         Log(LGPFX"Cannot allocate memory to set cpt state (type=%d).\n",
             setInfo.cptType);
         retval = -ENOMEM;
         break;
      }
      retval = copy_from_user(cptBuf, (void *)(VA)setInfo.cptBuf,
                              setInfo.bufSize);
      if (retval) {
         VMCI_FreeKernelMem(cptBuf, setInfo.bufSize);
         retval = -EFAULT;
         break;
      }

      cid = VMCIContext_GetId(vmciLinux->context);
      setInfo.result = VMCIContext_SetCheckpointState(cid, setInfo.cptType,
                                                      setInfo.bufSize, cptBuf);
      VMCI_FreeKernelMem(cptBuf, setInfo.bufSize);
      retval = copy_to_user((void *)ioarg, &setInfo, sizeof setInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }
      break;
   }

   case IOCTL_VMCI_GET_CONTEXT_ID: {
      VMCIId cid = VMCI_HOST_CONTEXT_ID;

      retval = copy_to_user((void *)ioarg, &cid, sizeof cid);
      break;
   }

   case IOCTL_VMCI_SET_NOTIFY: {
      VMCISetNotifyInfo notifyInfo;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_SET_NOTIFY only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&notifyInfo, (void *)ioarg, sizeof notifyInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      if ((VA)notifyInfo.notifyUVA != (VA)NULL) {
         notifyInfo.result = VMCISetupNotify(vmciLinux->context,
                                             (VA)notifyInfo.notifyUVA);
      } else {
         VMCIUnsetNotifyInt(vmciLinux->context, TRUE);
         notifyInfo.result = VMCI_SUCCESS;
      }

      retval = copy_to_user((void *)ioarg, &notifyInfo, sizeof notifyInfo);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      break;
   }

   case IOCTL_VMCI_NOTIFY_RESOURCE: {
      VMCINotifyResourceInfo info;
      VMCIId cid;

      if (vmciLinux->userVersion < VMCI_VERSION_NOTIFY) {
         Log(LGPFX"IOCTL_VMCI_NOTIFY_RESOURCE is invalid for current"
             " VMX versions.\n");
         retval = -EINVAL;
         break;
      }

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_NOTIFY_RESOURCE is only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&info, (void *)ioarg, sizeof info);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      cid = VMCIContext_GetId(vmciLinux->context);
      switch (info.action) {
      case VMCI_NOTIFY_RESOURCE_ACTION_NOTIFY:
         if (info.resource == VMCI_NOTIFY_RESOURCE_DOOR_BELL) {
            info.result = VMCIContext_NotifyDoorbell(cid, info.handle,
                                                     VMCI_NO_PRIVILEGE_FLAGS);
         } else {
            info.result = VMCI_ERROR_UNAVAILABLE;
         }
         break;
      case VMCI_NOTIFY_RESOURCE_ACTION_CREATE:
         info.result = VMCIContext_DoorbellCreate(cid, info.handle);
         break;
      case VMCI_NOTIFY_RESOURCE_ACTION_DESTROY:
         info.result = VMCIContext_DoorbellDestroy(cid, info.handle);
         break;
      default:
         Log(LGPFX"IOCTL_VMCI_NOTIFY_RESOURCE got unknown action (action=%d).\n",
             info.action);
         info.result = VMCI_ERROR_INVALID_ARGS;
      }
      retval = copy_to_user((void *)ioarg, &info,
                            sizeof info);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      break;
   }

   case IOCTL_VMCI_NOTIFICATIONS_RECEIVE: {
      VMCINotificationReceiveInfo info;
      VMCIHandleArray *dbHandleArray;
      VMCIHandleArray *qpHandleArray;
      VMCIId cid;

      if (vmciLinux->ctType != VMCIOBJ_CONTEXT) {
         Log(LGPFX"IOCTL_VMCI_NOTIFICATIONS_RECEIVE is only valid for contexts.\n");
         retval = -EINVAL;
         break;
      }

      if (vmciLinux->userVersion < VMCI_VERSION_NOTIFY) {
         Log(LGPFX"IOCTL_VMCI_NOTIFICATIONS_RECEIVE is not supported for the"
             " current vmx version.\n");
         retval = -EINVAL;
         break;
      }

      retval = copy_from_user(&info, (void *)ioarg, sizeof info);
      if (retval) {
         retval = -EFAULT;
         break;
      }

      if ((info.dbHandleBufSize && !info.dbHandleBufUVA) ||
          (info.qpHandleBufSize && !info.qpHandleBufUVA)) {
         retval = -EINVAL;
         break;
      }

      cid = VMCIContext_GetId(vmciLinux->context);
      info.result = VMCIContext_ReceiveNotificationsGet(cid,
                                                        &dbHandleArray,
                                                        &qpHandleArray);
      if (info.result == VMCI_SUCCESS) {
         info.result =
            VMCICopyHandleArrayToUser((void *)(VA)info.dbHandleBufUVA,
                                      &info.dbHandleBufSize,
                                      dbHandleArray,
                                      &retval);
         if (info.result == VMCI_SUCCESS && !retval) {
            info.result =
               VMCICopyHandleArrayToUser((void *)(VA)info.qpHandleBufUVA,
                                         &info.qpHandleBufSize,
                                         qpHandleArray,
                                         &retval);
         }
         if (!retval) {
            retval = copy_to_user((void *)ioarg, &info, sizeof info);
         }
         VMCIContext_ReceiveNotificationsRelease(cid, dbHandleArray, qpHandleArray,
                                                 info.result == VMCI_SUCCESS && !retval);
      } else {
         retval = copy_to_user((void *)ioarg, &info, sizeof info);
      }
      break;
   }

   default:
      Warning(LGPFX"Unknown ioctl (iocmd=%d).\n", iocmd);
      retval = -EINVAL;
   }

   return retval;
}


#if defined(HAVE_COMPAT_IOCTL) || defined(HAVE_UNLOCKED_IOCTL)
/*
 *-----------------------------------------------------------------------------
 *
 * LinuxDriver_UnlockedIoctl --
 *
 *      Wrapper for LinuxDriver_Ioctl supporting the compat_ioctl and
 *      unlocked_ioctl methods that have signatures different from the
 *      old ioctl. Used as compat_ioctl method for 32bit apps running
 *      on 64bit kernel and for unlocked_ioctl on systems supporting
 *      those.  LinuxDriver_Ioctl may safely be called without holding
 *      the BKL.
 *
 * Results:
 *      Same as LinuxDriver_Ioctl.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static long
LinuxDriver_UnlockedIoctl(struct file *filp,
                          u_int iocmd,
                          unsigned long ioarg)
{
   return LinuxDriver_Ioctl(NULL, filp, iocmd, ioarg);
}
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIUserVAInvalidPointer --
 *
 *      Checks if a given user VA is valid or not.  Copied from
 *      bora/modules/vmnet/linux/hostif.c:VNetUserIfInvalidPointer().  TODO
 *      libify the common code.
 *
 * Results:
 *      TRUE iff invalid.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static INLINE Bool
VMCIUserVAInvalidPointer(VA uva,      // IN:
                         size_t size) // IN:
{
   return !access_ok(VERIFY_WRITE, (void *)uva, size);
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIUserVALockPage --
 *
 *      Lock physical page backing a given user VA.  Copied from
 *      bora/modules/vmnet/linux/userif.c:UserIfLockPage().  TODO libify the
 *      common code.
 *
 * Results:
 *      Pointer to struct page on success, NULL otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static INLINE struct page *
VMCIUserVALockPage(VA addr) // IN:
{
   struct page *page = NULL;
   int retval;

   down_read(&current->mm->mmap_sem);
   retval = get_user_pages(current, current->mm, addr,
                           1, 1, 0, &page, NULL);
   up_read(&current->mm->mmap_sem);

   if (retval != 1) {
      return NULL;
   }

   return page;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIMapBoolPtr --
 *
 *      Lock physical page backing a given user VA and maps it to kernel
 *      address space.  The range of the mapped memory should be within a
 *      single page otherwise an error is returned.  Copied from
 *      bora/modules/vmnet/linux/userif.c:VNetUserIfMapUint32Ptr().  TODO
 *      libify the common code.
 *
 * Results:
 *      0 on success, negative error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static INLINE int
VMCIMapBoolPtr(VA notifyUVA,     // IN:
               struct page **p,  // OUT:
               Bool **notifyPtr) // OUT:
{
   if (VMCIUserVAInvalidPointer(notifyUVA, sizeof **notifyPtr) ||
       (((notifyUVA + sizeof **notifyPtr - 1) & ~(PAGE_SIZE - 1)) !=
        (notifyUVA & ~(PAGE_SIZE - 1)))) {
      return -EINVAL;
   }

   *p = VMCIUserVALockPage(notifyUVA);
   if (*p == NULL) {
      return -EAGAIN;
   }

   *notifyPtr = (Bool *)((uint8 *)kmap(*p) + (notifyUVA & (PAGE_SIZE - 1)));
   return 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCISetupNotify --
 *
 *      Sets up a given context for notify to work.  Calls VMCIMapBoolPtr()
 *      which maps the notify boolean in user VA in kernel space.
 *
 * Results:
 *      VMCI_SUCCESS on success, error code otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
VMCISetupNotify(VMCIContext *context, // IN:
                VA notifyUVA)         // IN:
{
   int retval;

   if (context->notify) {
      Warning(LGPFX"Notify mechanism is already set up.\n");
      return VMCI_ERROR_DUPLICATE_ENTRY;
   }

   retval =
      VMCIMapBoolPtr(notifyUVA, &context->notifyPage, &context->notify) == 0 ?
         VMCI_SUCCESS : VMCI_ERROR_GENERIC;
   if (retval == VMCI_SUCCESS) {
      VMCIContext_CheckAndSignalNotify(context);
   }

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIUnsetNotifyInt --
 *
 *      Internal version of VMCIUnsetNotify, that allows for locking
 *      the context before unsetting the notify pointer. If useLock is
 *      TRUE, the context lock is grabbed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
VMCIUnsetNotifyInt(VMCIContext *context, // IN
                   Bool useLock)         // IN
{
   VMCILockFlags flags;

   if (useLock) {
      VMCI_GrabLock(&context->lock, &flags);
   }

   if (context->notifyPage) {
      struct page *notifyPage = context->notifyPage;

      context->notify = NULL;
      context->notifyPage = NULL;

      if (useLock) {
         VMCI_ReleaseLock(&context->lock, flags);
      }

      kunmap(notifyPage);
      put_page(notifyPage);
   } else {
      if (useLock) {
         VMCI_ReleaseLock(&context->lock, flags);
      }
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCIUnsetNotify --
 *
 *      Reverts actions set up by VMCISetupNotify().  Unmaps and unlocks the
 *      page mapped/locked by VMCISetupNotify().
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
VMCIUnsetNotify(VMCIContext *context) // IN:
{
   VMCIUnsetNotifyInt(context, FALSE);
}


/*
 *-----------------------------------------------------------------------------
 *
 * PCI device support --
 *
 *      The following functions implement the support for the VMCI
 *      guest device. This includes initializing the device and
 *      interrupt handling.
 *
 *-----------------------------------------------------------------------------
 */


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_guest_init --
 *
 *      Initializes the VMCI PCI device. The initialization might fail
 *      if there is no VMCI PCI device.
 *
 * Results:
 *      0 on success, other error codes on failure.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
vmci_guest_init(void)
{
   int retval;

   /* Initialize guest device data. */
   compat_mutex_init(&vmci_dev.lock);
   vmci_dev.intr_type = VMCI_INTR_TYPE_INTX;
   vmci_dev.exclusive_vectors = FALSE;
   spin_lock_init(&vmci_dev.dev_spinlock);
   vmci_dev.enabled = FALSE;
   atomic_set(&vmci_dev.datagrams_allowed, 0);
   atomic_set(&guestDeviceActive, 0);

   data_buffer = vmalloc(data_buffer_size);
   if (!data_buffer) {
      return -ENOMEM;
   }

   /* This should be last to make sure we are done initializing. */
   retval = pci_register_driver(&vmci_driver);
   if (retval < 0) {
      vfree(data_buffer);
      data_buffer = NULL;
      return retval;
   }

   return 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_enable_msix --
 *
 *      Enable MSI-X.  Try exclusive vectors first, then shared vectors.
 *
 * Results:
 *      0 on success, other error codes on failure.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
vmci_enable_msix(struct pci_dev *pdev) // IN
{
   int i;
   int result;

   for (i = 0; i < VMCI_MAX_INTRS; ++i) {
      vmci_dev.msix_entries[i].entry = i;
      vmci_dev.msix_entries[i].vector = i;
   }

   result = pci_enable_msix(pdev, vmci_dev.msix_entries, VMCI_MAX_INTRS);
   if (!result) {
      vmci_dev.exclusive_vectors = TRUE;
   } else if (result > 0) {
      result = pci_enable_msix(pdev, vmci_dev.msix_entries, 1);
   }
   return result;
}


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_probe_device --
 *
 *      Most of the initialization at module load time is done here.
 *
 * Results:
 *      Returns 0 for success, an error otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
vmci_probe_device(struct pci_dev *pdev,           // IN: vmci PCI device
                  const struct pci_device_id *id) // IN: matching device ID
{
   unsigned int ioaddr;
   unsigned int ioaddr_size;
   unsigned int capabilities;
   int result;

   printk(KERN_INFO "Probing for vmci/PCI.\n");

   result = pci_enable_device(pdev);
   if (result) {
      printk(KERN_ERR "Cannot VMCI device %s: error %d\n",
             pci_name(pdev), result);
      return result;
   }
   pci_set_master(pdev); /* To enable QueuePair functionality. */
   ioaddr = pci_resource_start(pdev, 0);
   ioaddr_size = pci_resource_len(pdev, 0);

   /*
    * Request I/O region with adjusted base address and size. The adjusted
    * values are needed and used if we release the region in case of failure.
    */

   if (!compat_request_region(ioaddr, ioaddr_size, "vmci")) {
      printk(KERN_INFO "vmci: Another driver already loaded "
                       "for device in slot %s.\n", pci_name(pdev));
      goto pci_disable;
   }

   printk(KERN_INFO "Found vmci/PCI at %#x, irq %u.\n", ioaddr, pdev->irq);

   /*
    * Verify that the VMCI Device supports the capabilities that
    * we need. If the device is missing capabilities that we would
    * like to use, check for fallback capabilities and use those
    * instead (so we can run a new VM on old hosts). Fail the load if
    * a required capability is missing and there is no fallback.
    *
    * Right now, we need datagrams. There are no fallbacks.
    */
   capabilities = inl(ioaddr + VMCI_CAPS_ADDR);

   if ((capabilities & VMCI_CAPS_DATAGRAM) == 0) {
      printk(KERN_ERR "VMCI device does not support datagrams.\n");
      goto release;
   }

   /*
    * If the hardware supports notifications, we will use that as
    * well.
    */
   if (capabilities & VMCI_CAPS_NOTIFICATIONS) {
      capabilities = VMCI_CAPS_DATAGRAM;
      notification_bitmap = pci_alloc_consistent(pdev, PAGE_SIZE,
                                                 &notification_base);
      if (notification_bitmap == NULL) {
         printk(KERN_ERR "VMCI device unable to allocate notification bitmap.\n");
      } else {
         memset(notification_bitmap, 0, PAGE_SIZE);
         capabilities |= VMCI_CAPS_NOTIFICATIONS;
      }
   } else {
      capabilities = VMCI_CAPS_DATAGRAM;
   }
   printk(KERN_INFO "VMCI: using capabilities 0x%x.\n", capabilities);

   /* Let the host know which capabilities we intend to use. */
   outl(capabilities, ioaddr + VMCI_CAPS_ADDR);

   /* Device struct initialization. */
   compat_mutex_lock(&vmci_dev.lock);
   if (vmci_dev.enabled) {
      printk(KERN_ERR "VMCI device already enabled.\n");
      goto unlock;
   }

   vmci_dev.ioaddr = ioaddr;
   vmci_dev.ioaddr_size = ioaddr_size;
   atomic_set(&vmci_dev.datagrams_allowed, 1);

   /*
    * Register notification bitmap with device if that capability is
    * used
    */
   if (capabilities & VMCI_CAPS_NOTIFICATIONS) {
      unsigned long bitmapPPN = notification_base >> PAGE_SHIFT;
      if (!VMCI_RegisterNotificationBitmap(bitmapPPN)) {
         printk(KERN_ERR "VMCI device unable to register notification bitmap "
                "with PPN 0x%x.\n", (uint32)bitmapPPN);
         goto datagram_disallow;
      }
   }

   /* Check host capabilities. */
   if (!VMCI_CheckHostCapabilities()) {
      goto remove_bitmap;
   }

   /* Enable device. */
   vmci_dev.enabled = TRUE;
   pci_set_drvdata(pdev, &vmci_dev);
   vmci_pdev = pdev;

   /*
    * We do global initialization here because we need datagrams
    * during VMCIUtil_Init, since it registers for VMCI events. If we
    * ever support more than one VMCI device we will have to create
    * seperate LateInit/EarlyExit functions that can be used to do
    * initialization/cleanup that depends on the device being
    * accessible.  We need to initialize VMCI components before
    * requesting an irq - the VMCI interrupt handler uses these
    * components, and it may be invoked once request_irq() has
    * registered the handler (as the irq line may be shared).
    */
   VMCIUtil_Init();

   if (VMCIQPGuestEndpoints_Init() < VMCI_SUCCESS) {
      goto util_exit;
   }

   /*
    * Enable interrupts.  Try MSI-X first, then MSI, and then fallback on
    * legacy interrupts.
    */
   if (!vmci_disable_msix && !vmci_enable_msix(pdev)) {
      vmci_dev.intr_type = VMCI_INTR_TYPE_MSIX;
      vmci_dev.irq = vmci_dev.msix_entries[0].vector;
   } else if (!vmci_disable_msi && !pci_enable_msi(pdev)) {
      vmci_dev.intr_type = VMCI_INTR_TYPE_MSI;
      vmci_dev.irq = pdev->irq;
   } else {
      vmci_dev.intr_type = VMCI_INTR_TYPE_INTX;
      vmci_dev.irq = pdev->irq;
   }

   /* Request IRQ for legacy or MSI interrupts, or for first MSI-X vector. */
   result = request_irq(vmci_dev.irq, vmci_interrupt, COMPAT_IRQF_SHARED,
                        "vmci", &vmci_dev);
   if (result) {
      printk(KERN_ERR "vmci: irq %u in use: %d\n", vmci_dev.irq, result);
      goto components_exit;
   }

   /*
    * For MSI-X with exclusive vectors we need to request an interrupt for each
    * vector so that we get a separate interrupt handler routine.  This allows
    * us to distinguish between the vectors.
    */

   if (vmci_dev.exclusive_vectors) {
      ASSERT(vmci_dev.intr_type == VMCI_INTR_TYPE_MSIX);
      result = request_irq(vmci_dev.msix_entries[1].vector, vmci_interrupt_bm,
                           0, "vmci", &vmci_dev);
      if (result) {
         printk(KERN_ERR "vmci: irq %u in use: %d\n",
                vmci_dev.msix_entries[1].vector, result);
         free_irq(vmci_dev.irq, &vmci_dev);
         goto components_exit;
      }
   }

   printk(KERN_INFO "Registered vmci device.\n");

   atomic_inc(&guestDeviceActive);

   compat_mutex_unlock(&vmci_dev.lock);

   /* Enable specific interrupt bits. */
   if (capabilities & VMCI_CAPS_NOTIFICATIONS) {
      outl(VMCI_IMR_DATAGRAM | VMCI_IMR_NOTIFICATION,
           vmci_dev.ioaddr + VMCI_IMR_ADDR);
   } else {
      outl(VMCI_IMR_DATAGRAM, vmci_dev.ioaddr + VMCI_IMR_ADDR);
   }

   /* Enable interrupts. */
   outl(VMCI_CONTROL_INT_ENABLE, vmci_dev.ioaddr + VMCI_CONTROL_ADDR);

   return 0;

 components_exit:
   VMCIQPGuestEndpoints_Exit();
 util_exit:
   VMCIUtil_Exit();
   vmci_dev.enabled = FALSE;
   if (vmci_dev.intr_type == VMCI_INTR_TYPE_MSIX) {
      pci_disable_msix(pdev);
   } else if (vmci_dev.intr_type == VMCI_INTR_TYPE_MSI) {
      pci_disable_msi(pdev);
   }
 remove_bitmap:
   if (notification_bitmap) {
      outl(VMCI_CONTROL_RESET, vmci_dev.ioaddr + VMCI_CONTROL_ADDR);
   }
 datagram_disallow:
   atomic_set(&vmci_dev.datagrams_allowed, 0);
 unlock:
   compat_mutex_unlock(&vmci_dev.lock);
 release:
   if (notification_bitmap) {
      pci_free_consistent(pdev, PAGE_SIZE, notification_bitmap,
                          notification_base);
      notification_bitmap = NULL;
   }
   release_region(ioaddr, ioaddr_size);
 pci_disable:
   pci_disable_device(pdev);
   return -EBUSY;
}


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_remove_device --
 *
 *      Cleanup, called for each device on unload.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
vmci_remove_device(struct pci_dev* pdev)
{
   struct vmci_device *dev = pci_get_drvdata(pdev);

   printk(KERN_INFO "Removing vmci device\n");

   atomic_dec(&guestDeviceActive);

   VMCIQPGuestEndpoints_Exit();
   VMCIUtil_Exit();
   vmci_pdev = NULL;

   compat_mutex_lock(&dev->lock);

   atomic_set(&vmci_dev.datagrams_allowed, 0);

   printk(KERN_INFO "Resetting vmci device\n");
   outl(VMCI_CONTROL_RESET, vmci_dev.ioaddr + VMCI_CONTROL_ADDR);

   /*
    * Free IRQ and then disable MSI/MSI-X as appropriate.  For MSI-X, we might
    * have multiple vectors, each with their own IRQ, which we must free too.
    */

   free_irq(dev->irq, dev);
   if (dev->intr_type == VMCI_INTR_TYPE_MSIX) {
      if (dev->exclusive_vectors) {
         free_irq(dev->msix_entries[1].vector, dev);
      }
      pci_disable_msix(pdev);
   } else if (dev->intr_type == VMCI_INTR_TYPE_MSI) {
      pci_disable_msi(pdev);
   }
   dev->exclusive_vectors = FALSE;
   dev->intr_type = VMCI_INTR_TYPE_INTX;

   release_region(dev->ioaddr, dev->ioaddr_size);
   dev->enabled = FALSE;
   if (notification_bitmap) {
      /*
       * The device reset above cleared the bitmap state of the
       * device, so we can safely free it here.
       */

      pci_free_consistent(pdev, PAGE_SIZE, notification_bitmap,
                          notification_base);
      notification_bitmap = NULL;
   }

   printk(KERN_INFO "Unregistered vmci device.\n");
   compat_mutex_unlock(&dev->lock);

   pci_disable_device(pdev);
}


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_interrupt --
 *
 *      Interrupt handler for legacy or MSI interrupt, or for first MSI-X
 *      interrupt (vector VMCI_INTR_DATAGRAM).
 *
 * Results:
 *      COMPAT_IRQ_HANDLED if the interrupt is handled, COMPAT_IRQ_NONE if
 *      not an interrupt.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19)
static compat_irqreturn_t
vmci_interrupt(int irq,               // IN
               void *clientdata,      // IN
               struct pt_regs *regs)  // IN
#else
static compat_irqreturn_t
vmci_interrupt(int irq,               // IN
               void *clientdata)      // IN
#endif
{
   vmci_device *dev = clientdata;

   if (dev == NULL) {
      printk(KERN_DEBUG "vmci_interrupt(): irq %d for unknown device.\n", irq);
      return COMPAT_IRQ_NONE;
   }

   /*
    * If we are using MSI-X with exclusive vectors then we simply schedule
    * the datagram tasklet, since we know the interrupt was meant for us.
    * Otherwise we must read the ICR to determine what to do.
    */

   if (dev->intr_type == VMCI_INTR_TYPE_MSIX && dev->exclusive_vectors) {
      tasklet_schedule(&vmci_dg_tasklet);
   } else {
      unsigned int icr;

      ASSERT(dev->intr_type == VMCI_INTR_TYPE_INTX ||
             dev->intr_type == VMCI_INTR_TYPE_MSI);

      /* Acknowledge interrupt and determine what needs doing. */
      icr = inl(dev->ioaddr + VMCI_ICR_ADDR);
      if (icr == 0 || icr == 0xffffffff) {
         return COMPAT_IRQ_NONE;
      }

      if (icr & VMCI_ICR_DATAGRAM) {
         tasklet_schedule(&vmci_dg_tasklet);
         icr &= ~VMCI_ICR_DATAGRAM;
      }
      if (icr & VMCI_ICR_NOTIFICATION) {
         tasklet_schedule(&vmci_bm_tasklet);
         icr &= ~VMCI_ICR_NOTIFICATION;
      }
      if (icr != 0) {
         printk(KERN_INFO LGPFX"Ignoring unknown interrupt cause (%d).\n", icr);
      }
   }

   return COMPAT_IRQ_HANDLED;
}


/*
 *-----------------------------------------------------------------------------
 *
 * vmci_interrupt_bm --
 *
 *      Interrupt handler for MSI-X interrupt vector VMCI_INTR_NOTIFICATION,
 *      which is for the notification bitmap.  Will only get called if we are
 *      using MSI-X with exclusive vectors.
 *
 * Results:
 *      COMPAT_IRQ_HANDLED if the interrupt is handled, COMPAT_IRQ_NONE if
 *      not an interrupt.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19)
static compat_irqreturn_t
vmci_interrupt_bm(int irq,               // IN
                  void *clientdata,      // IN
                  struct pt_regs *regs)  // IN
#else
static compat_irqreturn_t
vmci_interrupt_bm(int irq,               // IN
                  void *clientdata)      // IN
#endif
{
   vmci_device *dev = clientdata;

   if (dev == NULL) {
      printk(KERN_DEBUG "vmci_interrupt_bm(): irq %d for unknown device.\n", irq);
      return COMPAT_IRQ_NONE;
   }

   /* For MSI-X we can just assume it was meant for us. */
   ASSERT(dev->intr_type == VMCI_INTR_TYPE_MSIX && dev->exclusive_vectors);
   tasklet_schedule(&vmci_bm_tasklet);

   return COMPAT_IRQ_HANDLED;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCI_DeviceEnabled --
 *
 *      Checks whether the VMCI device is enabled.
 *
 * Results:
 *      TRUE if device is enabled, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
VMCI_DeviceEnabled(void)
{
   return VMCI_GuestPersonalityActive() || VMCI_HostPersonalityActive();
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCI_SendDatagram --
 *
 *      VM to hypervisor call mechanism. We use the standard VMware naming
 *      convention since shared code is calling this function as well.
 *
 * Results:
 *      The result of the hypercall.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

int
VMCI_SendDatagram(VMCIDatagram *dg)
{
   unsigned long flags;
   int result;

   /* Check args. */
   if (dg == NULL) {
      return VMCI_ERROR_INVALID_ARGS;
   }

   if (atomic_read(&vmci_dev.datagrams_allowed) == 0) {
      return VMCI_ERROR_UNAVAILABLE;
   }

   /*
    * Need to acquire spinlock on the device because
    * the datagram data may be spread over multiple pages and the monitor may
    * interleave device user rpc calls from multiple VCPUs. Acquiring the
    * spinlock precludes that possibility. Disabling interrupts to avoid
    * incoming datagrams during a "rep out" and possibly landing up in this
    * function.
    */
   spin_lock_irqsave(&vmci_dev.dev_spinlock, flags);

   /*
    * Send the datagram and retrieve the return value from the result register.
    */
   __asm__ __volatile__(
      "cld\n\t"
      "rep outsb\n\t"
      : /* No output. */
      : "d"(vmci_dev.ioaddr + VMCI_DATA_OUT_ADDR),
        "c"(VMCI_DG_SIZE(dg)), "S"(dg)
      );

   /*
    * XXX Should read result high port as well when updating handlers to
    * return 64bit.
    */
   result = inl(vmci_dev.ioaddr + VMCI_RESULT_LOW_ADDR);
   spin_unlock_irqrestore(&vmci_dev.dev_spinlock, flags);

   return result;
}


/*
 *-----------------------------------------------------------------------------
 *
 * dispatch_datagrams --
 *
 *      Reads and dispatches incoming datagrams.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Reads data from the device.
 *
 *-----------------------------------------------------------------------------
 */

void
dispatch_datagrams(unsigned long data)
{
   vmci_device *dev = (vmci_device *)data;

   if (dev == NULL) {
      printk(KERN_DEBUG "vmci: dispatch_datagrams(): no vmci device"
             "present.\n");
      return;
   }

   if (data_buffer == NULL) {
      printk(KERN_DEBUG "vmci: dispatch_datagrams(): no buffer present.\n");
      return;
   }


   VMCI_ReadDatagramsFromPort((VMCIIoHandle) 0, dev->ioaddr + VMCI_DATA_IN_ADDR,
                              data_buffer, data_buffer_size);
}


/*
 *-----------------------------------------------------------------------------
 *
 * process_bitmap --
 *
 *      Scans the notification bitmap for raised flags, clears them
 *      and handles the notifications.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
process_bitmap(unsigned long data)
{
   vmci_device *dev = (vmci_device *)data;

   if (dev == NULL) {
      printk(KERN_DEBUG "vmci: process_bitmaps(): no vmci device"
             "present.\n");
      return;
   }

   if (notification_bitmap == NULL) {
      printk(KERN_DEBUG "vmci: process_bitmaps(): no bitmap present.\n");
      return;
   }


   VMCI_ScanNotificationBitmap(notification_bitmap);
}


/*
 *----------------------------------------------------------------------
 *
 * Shared functions --
 *
 *      Functions shared between host and guest personality.
 *
 *----------------------------------------------------------------------
 */


/*
 *-----------------------------------------------------------------------------
 *
 * VMCI_GuestPersonalityActive --
 *
 *      Determines whether the VMCI PCI device has been successfully
 *      initialized.
 *
 * Results:
 *      TRUE, if VMCI guest device is operational, FALSE otherwise.
 *
 * Side effects:
 *      Reads data from the device.
 *
 *-----------------------------------------------------------------------------
 */

Bool
VMCI_GuestPersonalityActive(void)
{
   return guestDeviceInit && atomic_read(&guestDeviceActive) > 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * VMCI_HostPersonalityActive --
 *
 *      Determines whether the VMCI host personality is
 *      available. Since the core functionality of the host driver is
 *      always present, all guests could possibly use the host
 *      personality. However, to minimize the deviation from the
 *      pre-unified driver state of affairs, we only consider the host
 *      device active, if there is no active guest device, or if there
 *      are VMX'en with active VMCI contexts using the host device.
 *
 * Results:
 *      TRUE, if VMCI host driver is operational, FALSE otherwise.
 *
 * Side effects:
 *      Reads data from the device.
 *
 *-----------------------------------------------------------------------------
 */

Bool
VMCI_HostPersonalityActive(void)
{
   return hostDeviceInit &&
      (!VMCI_GuestPersonalityActive() ||
       atomic_read(&linuxState.activeContexts) > 0);
}


/*
 *----------------------------------------------------------------------
 *
 * Module definitions --
 *
 *      Implements support for module load/unload.
 *
 *----------------------------------------------------------------------
 */


/*
 *----------------------------------------------------------------------
 *
 * vmci_init --
 *
 *      linux module entry point. Called by /sbin/insmod command
 *
 * Results:
 *      registers a device driver for a major # that depends
 *      on the uid. Add yourself to that list.  List is now in
 *      private/driver-private.c.
 *
 *----------------------------------------------------------------------
 */

static int __init
vmci_init(void)
{
   int retval;

   retval = VMCI_SharedInit();
   if (retval != VMCI_SUCCESS) {
      Warning(LGPFX"Failed to initialize VMCI common components (err=%d).\n",
              retval);
      return -ENOMEM;
   }

   if (!vmci_disable_guest) {
      retval = vmci_guest_init();
      if (retval != 0) {
         Warning(LGPFX"VMCI PCI device not initialized (err=%d).\n", retval);
      } else {
         guestDeviceInit = TRUE;
         if (VMCI_GuestPersonalityActive()) {
            Log(LGPFX"Using guest personality\n");
         }
      }
   }

   if (!vmci_disable_host) {
      retval = vmci_host_init();
      if (retval != 0) {
         Warning(LGPFX"Unable to initialize host personality (err=%d).\n",
                 retval);
      } else {
         hostDeviceInit = TRUE;
         Log(LGPFX"Using host personality\n");
      }
   }

   if (!guestDeviceInit && !hostDeviceInit) {
      VMCI_SharedCleanup();
      return -ENODEV;
   }

   Log(LGPFX"Module (name=%s) is initialized\n", VMCI_MODULE_NAME);

   return 0;
}


/*
 *----------------------------------------------------------------------
 *
 * vmci_exit --
 *
 *      Called by /sbin/rmmod
 *
 *
 *----------------------------------------------------------------------
 */

static void __exit
vmci_exit(void)
{
   int retval;

   if (guestDeviceInit) {
      pci_unregister_driver(&vmci_driver);
      vfree(data_buffer);
      guestDeviceInit = FALSE;
   }

   if (hostDeviceInit) {
      unregister_ioctl32_handlers();

      VMCI_HostCleanup();

      retval = misc_deregister(&linuxState.misc);
      if (retval) {
         Warning(LGPFX "Module %s: error unregistering\n", VMCI_MODULE_NAME);
      } else {
         Log(LGPFX"Module %s: unloaded\n", VMCI_MODULE_NAME);
      }

      hostDeviceInit = FALSE;
   }

   VMCI_SharedCleanup();
}


module_init(vmci_init);
module_exit(vmci_exit);
MODULE_DEVICE_TABLE(pci, vmci_ids);

module_param_named(disable_host, vmci_disable_host, bool, 0);
MODULE_PARM_DESC(disable_host, "Disable driver host personality - (default=0)");

module_param_named(disable_guest, vmci_disable_guest, bool, 0);
MODULE_PARM_DESC(disable_guest, "Disable driver guest personality - (default=0)");

module_param_named(disable_msi, vmci_disable_msi, bool, 0);
MODULE_PARM_DESC(disable_msi, "Disable MSI use in driver - (default=0)");

module_param_named(disable_msix, vmci_disable_msix, bool, 0);
MODULE_PARM_DESC(disable_msix, "Disable MSI-X use in driver - (default="
                 __stringify(VMCI_DISABLE_MSIX) ")");

MODULE_AUTHOR("VMware, Inc.");
MODULE_DESCRIPTION("VMware Virtual Machine Communication Interface (VMCI).");
MODULE_VERSION(VMCI_DRIVER_VERSION_STRING);
MODULE_LICENSE("GPL v2");
/*
 * Starting with SLE10sp2, Novell requires that IHVs sign a support agreement
 * with them and mark their kernel modules as externally supported via a
 * change to the module header. If this isn't done, the module will not load
 * by default (i.e., neither mkinitrd nor modprobe will accept it).
 */
MODULE_INFO(supported, "external");