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
|
// Copyright © 2024 Institute of Software, CAS. All rights reserved.
//
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use kvm_bindings::*;
use std::fs::File;
use std::os::raw::c_void;
use std::os::raw::{c_int, c_ulong};
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use crate::cap::Cap;
use crate::ioctls::device::new_device;
use crate::ioctls::device::DeviceFd;
use crate::ioctls::vcpu::new_vcpu;
use crate::ioctls::vcpu::VcpuFd;
use crate::ioctls::{KvmRunWrapper, Result};
use crate::kvm_ioctls::*;
use vmm_sys_util::errno;
use vmm_sys_util::eventfd::EventFd;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
use vmm_sys_util::ioctl::ioctl;
#[cfg(target_arch = "x86_64")]
use vmm_sys_util::ioctl::ioctl_with_mut_ptr;
use vmm_sys_util::ioctl::{ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val};
/// An address either in programmable I/O space or in memory mapped I/O space.
///
/// The `IoEventAddress` is used for specifying the type when registering an event
/// in [register_ioevent](struct.VmFd.html#method.register_ioevent).
#[derive(Debug, Clone, Copy)]
pub enum IoEventAddress {
/// Representation of an programmable I/O address.
Pio(u64),
/// Representation of an memory mapped I/O address.
Mmio(u64),
}
/// Helper structure for disabling datamatch.
///
/// The structure can be used as a parameter to
/// [`register_ioevent`](struct.VmFd.html#method.register_ioevent)
/// to disable filtering of events based on the datamatch flag. For details check the
/// [KVM API documentation](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
#[derive(Debug, Clone, Copy)]
pub struct NoDatamatch;
impl From<NoDatamatch> for u64 {
fn from(_: NoDatamatch) -> u64 {
0
}
}
/// Wrapper over KVM VM ioctls.
#[derive(Debug)]
pub struct VmFd {
vm: File,
run_size: usize,
}
impl VmFd {
/// Creates/modifies a guest physical memory slot.
///
/// See the documentation for `KVM_SET_USER_MEMORY_REGION`.
///
/// # Arguments
///
/// * `user_memory_region` - Guest physical memory slot. For details check the
/// `kvm_userspace_memory_region` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Safety
///
/// This function is unsafe because there is no guarantee `userspace_addr` points to a valid
/// memory region, nor the memory region lives as long as the kernel needs it to.
///
/// The caller of this method must make sure that:
/// - the raw pointer (`userspace_addr`) points to valid memory
/// - the regions provided to KVM are not overlapping other memory regions.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
///
/// use kvm_bindings::kvm_userspace_memory_region;
/// use kvm_ioctls::Kvm;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let mem_region = kvm_userspace_memory_region {
/// slot: 0,
/// guest_phys_addr: 0x10000 as u64,
/// memory_size: 0x10000 as u64,
/// userspace_addr: 0x0 as u64,
/// flags: 0,
/// };
/// unsafe {
/// vm.set_user_memory_region(mem_region).unwrap();
/// };
/// ```
pub unsafe fn set_user_memory_region(
&self,
user_memory_region: kvm_userspace_memory_region,
) -> Result<()> {
let ret = ioctl_with_ref(self, KVM_SET_USER_MEMORY_REGION(), &user_memory_region);
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Creates/modifies a guest physical memory slot.
///
/// See the documentation for `KVM_SET_USER_MEMORY_REGION2`.
///
/// # Arguments
///
/// * `user_memory_region2` - Guest physical memory slot. For details check the
/// `kvm_userspace_memory_region2` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Safety
///
/// This function is unsafe because there is no guarantee `userspace_addr` points to a valid
/// memory region, nor the memory region lives as long as the kernel needs it to.
///
/// The caller of this method must make sure that:
/// - the raw pointer (`userspace_addr`) points to valid memory
/// - the regions provided to KVM are not overlapping other memory regions.
/// - the guest_memfd points at a file created via KVM_CREATE_GUEST_MEMFD on
/// the current VM, and the target range must not be bound to any other memory region
///
/// # Example
///
/// On x86, create a `KVM_X86_SW_PROTECTED_VM` with a memslot that has a `guest_memfd` associated.
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
///
/// use kvm_bindings::{
/// kvm_create_guest_memfd, kvm_userspace_memory_region2, KVM_CAP_GUEST_MEMFD,
/// KVM_CAP_USER_MEMORY2, KVM_MEM_GUEST_MEMFD,
/// };
/// use kvm_ioctls::{Cap, Kvm};
/// use std::os::fd::RawFd;
///
/// let kvm = Kvm::new().unwrap();
/// #[cfg(target_arch = "x86_64")]
/// let vm = kvm
/// .create_vm_with_type(kvm_bindings::KVM_X86_SW_PROTECTED_VM as u64)
/// .unwrap();
/// #[cfg(not(target_arch = "x86_64"))]
/// let vm = kvm.create_vm().unwrap(); /* non-x86 does not yet have a vm type that supports gmem */
///
/// let address_space = unsafe { libc::mmap(0 as _, 10000, 3, 34, -1, 0) };
/// let userspace_addr = address_space as *const u8 as u64;
///
/// if !vm.check_extension(Cap::GuestMemfd) || !vm.check_extension(Cap::UserMemory2) {
/// return;
/// }
///
/// let gmem = kvm_create_guest_memfd {
/// size: 0x10000,
/// flags: 0,
/// reserved: [0; 6],
/// };
///
/// let fd: RawFd = unsafe { vm.create_guest_memfd(gmem).unwrap() };
///
/// let mem_region = kvm_userspace_memory_region2 {
/// slot: 0,
/// flags: KVM_MEM_GUEST_MEMFD,
/// guest_phys_addr: 0x10000 as u64,
/// memory_size: 0x10000 as u64,
/// userspace_addr,
/// guest_memfd_offset: 0,
/// guest_memfd: fd as u32,
/// pad1: 0,
/// pad2: [0; 14],
/// };
/// unsafe {
/// vm.set_user_memory_region2(mem_region).unwrap();
/// };
/// ```
pub unsafe fn set_user_memory_region2(
&self,
user_memory_region2: kvm_userspace_memory_region2,
) -> Result<()> {
let ret = ioctl_with_ref(self, KVM_SET_USER_MEMORY_REGION2(), &user_memory_region2);
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Sets the address of the three-page region in the VM's address space.
///
/// See the documentation for `KVM_SET_TSS_ADDR`.
///
/// # Arguments
///
/// * `offset` - Physical address of a three-page region in the guest's physical address space.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// vm.set_tss_address(0xfffb_d000).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn set_tss_address(&self, offset: usize) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd and we verify the return result.
let ret = unsafe { ioctl_with_val(self, KVM_SET_TSS_ADDR(), offset as c_ulong) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Sets the address of the one-page region in the VM's address space.
///
/// See the documentation for `KVM_SET_IDENTITY_MAP_ADDR`.
///
/// # Arguments
///
/// * `address` - Physical address of a one-page region in the guest's physical address space.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// vm.set_identity_map_address(0xfffb_c000).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn set_identity_map_address(&self, address: u64) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_IDENTITY_MAP_ADDR(), &address) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Creates an in-kernel interrupt controller.
///
/// See the documentation for `KVM_CREATE_IRQCHIP`.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// #[cfg(target_arch = "x86_64")]
/// vm.create_irq_chip().unwrap();
/// #[cfg(target_arch = "aarch64")]
/// {
/// use kvm_bindings::{
/// kvm_create_device, kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V2, KVM_CREATE_DEVICE_TEST,
/// };
/// let mut gic_device = kvm_create_device {
/// type_: kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V2,
/// fd: 0,
/// flags: KVM_CREATE_DEVICE_TEST,
/// };
/// if vm.create_device(&mut gic_device).is_ok() {
/// vm.create_irq_chip().unwrap();
/// }
/// }
/// ```
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
pub fn create_irq_chip(&self) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd and we verify the return result.
let ret = unsafe { ioctl(self, KVM_CREATE_IRQCHIP()) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// X86 specific call to retrieve the state of a kernel interrupt controller.
///
/// See the documentation for `KVM_GET_IRQCHIP` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `irqchip` - `kvm_irqchip` (input/output) to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # use kvm_bindings::{kvm_irqchip, KVM_IRQCHIP_PIC_MASTER};
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// vm.create_irq_chip().unwrap();
/// let mut irqchip = kvm_irqchip::default();
/// irqchip.chip_id = KVM_IRQCHIP_PIC_MASTER;
/// vm.get_irqchip(&mut irqchip).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn get_irqchip(&self, irqchip: &mut kvm_irqchip) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_irqchip struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_IRQCHIP(), irqchip) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// X86 specific call to set the state of a kernel interrupt controller.
///
/// See the documentation for `KVM_SET_IRQCHIP` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `irqchip` - `kvm_irqchip` (input/output) to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # use kvm_bindings::{kvm_irqchip, KVM_IRQCHIP_PIC_MASTER};
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// vm.create_irq_chip().unwrap();
/// let mut irqchip = kvm_irqchip::default();
/// irqchip.chip_id = KVM_IRQCHIP_PIC_MASTER;
/// // Your `irqchip` manipulation here.
/// vm.set_irqchip(&mut irqchip).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn set_irqchip(&self, irqchip: &kvm_irqchip) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_irqchip struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_IRQCHIP(), irqchip) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Creates a PIT as per the `KVM_CREATE_PIT2` ioctl.
///
/// # Arguments
///
/// * pit_config - PIT configuration. For details check the `kvm_pit_config` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// use kvm_bindings::kvm_pit_config;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// vm.create_irq_chip().unwrap();
/// let pit_config = kvm_pit_config::default();
/// vm.create_pit2(pit_config).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn create_pit2(&self, pit_config: kvm_pit_config) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_CREATE_PIT2(), &pit_config) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// X86 specific call to retrieve the state of the in-kernel PIT model.
///
/// See the documentation for `KVM_GET_PIT2` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `pitstate` - `kvm_pit_state2` to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # use kvm_bindings::kvm_pit_config;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// vm.create_irq_chip().unwrap();
///
/// let pit_config = kvm_pit_config::default();
/// vm.create_pit2(pit_config).unwrap();
/// let pitstate = vm.get_pit2().unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn get_pit2(&self) -> Result<kvm_pit_state2> {
let mut pitstate = Default::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_pit_state2 struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_PIT2(), &mut pitstate) };
if ret == 0 {
Ok(pitstate)
} else {
Err(errno::Error::last())
}
}
/// X86 specific call to set the state of the in-kernel PIT model.
///
/// See the documentation for `KVM_SET_PIT2` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `pitstate` - `kvm_pit_state2` to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # use kvm_bindings::{kvm_pit_config, kvm_pit_state2};
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// vm.create_irq_chip().unwrap();
///
/// let pit_config = kvm_pit_config::default();
/// vm.create_pit2(pit_config).unwrap();
/// let mut pitstate = kvm_pit_state2::default();
/// // Your `pitstate` manipulation here.
/// vm.set_pit2(&mut pitstate).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn set_pit2(&self, pitstate: &kvm_pit_state2) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_pit_state2 struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_PIT2(), pitstate) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// X86 specific call to retrieve the current timestamp of kvmclock.
///
/// See the documentation for `KVM_GET_CLOCK` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `clock` - `kvm_clock_data` to be read.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let clock = vm.get_clock().unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn get_clock(&self) -> Result<kvm_clock_data> {
let mut clock = Default::default();
// SAFETY: Here we trust the kernel not to read past the end of the kvm_clock_data struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_CLOCK(), &mut clock) };
if ret == 0 {
Ok(clock)
} else {
Err(errno::Error::last())
}
}
/// X86 specific call to set the current timestamp of kvmclock.
///
/// See the documentation for `KVM_SET_CLOCK` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `clock` - `kvm_clock_data` to be written.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # use kvm_bindings::kvm_clock_data;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let mut clock = kvm_clock_data::default();
/// vm.set_clock(&mut clock).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn set_clock(&self, clock: &kvm_clock_data) -> Result<()> {
// SAFETY: Here we trust the kernel not to read past the end of the kvm_clock_data struct.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_CLOCK(), clock) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Directly injects a MSI message as per the `KVM_SIGNAL_MSI` ioctl.
///
/// See the documentation for `KVM_SIGNAL_MSI`.
///
/// This ioctl returns > 0 when the MSI is successfully delivered and 0
/// when the guest blocked the MSI.
///
/// # Arguments
///
/// * kvm_msi - MSI message configuration. For details check the `kvm_msi` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// # Example
///
/// In this example, the important function signal_msi() calling into
/// the actual ioctl is commented out. The reason is that MSI vectors are
/// not chosen from the HW side (VMM). The guest OS (or anything that runs
/// inside the VM) is supposed to allocate the MSI vectors, and usually
/// communicate back through PCI configuration space. Sending a random MSI
/// vector through this signal_msi() function will always result in a
/// failure, which is why it needs to be commented out.
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// use kvm_bindings::kvm_msi;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let msi = kvm_msi::default();
/// #[cfg(target_arch = "x86_64")]
/// vm.create_irq_chip().unwrap();
/// //vm.signal_msi(msi).unwrap();
/// ```
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
pub fn signal_msi(&self, msi: kvm_msi) -> Result<c_int> {
// SAFETY: Safe because we allocated the structure and we know the kernel
// will read exactly the size of the structure.
let ret = unsafe { ioctl_with_ref(self, KVM_SIGNAL_MSI(), &msi) };
if ret >= 0 {
Ok(ret)
} else {
Err(errno::Error::last())
}
}
/// Sets the GSI routing table entries, overwriting any previously set
/// entries, as per the `KVM_SET_GSI_ROUTING` ioctl.
///
/// See the documentation for `KVM_SET_GSI_ROUTING`.
///
/// Returns an io::Error when the table could not be updated.
///
/// # Arguments
///
/// * kvm_irq_routing - IRQ routing configuration. Describe all routes
/// associated with GSI entries. For details check
/// the `kvm_irq_routing` and `kvm_irq_routing_entry`
/// structures in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// use kvm_bindings::kvm_irq_routing;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// #[cfg(target_arch = "x86_64")]
/// vm.create_irq_chip().unwrap();
///
/// #[cfg(target_arch = "riscv64")]
/// vm.create_device(&mut kvm_bindings::kvm_create_device {
/// type_: kvm_bindings::kvm_device_type_KVM_DEV_TYPE_RISCV_AIA,
/// fd: 0,
/// flags: 0,
/// })
/// .expect("Cannot create KVM vAIA device.");
///
/// let irq_routing = kvm_irq_routing::default();
/// vm.set_gsi_routing(&irq_routing).unwrap();
/// ```
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
pub fn set_gsi_routing(&self, irq_routing: &kvm_irq_routing) -> Result<()> {
// SAFETY: Safe because we allocated the structure and we know the kernel
// will read exactly the size of the structure.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_GSI_ROUTING(), irq_routing) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Registers an event to be signaled whenever a certain address is written to.
///
/// See the documentation for `KVM_IOEVENTFD`.
///
/// # Arguments
///
/// * `fd` - `EventFd` which will be signaled. When signaling, the usual `vmexit` to userspace
/// is prevented.
/// * `addr` - Address being written to.
/// * `datamatch` - Limits signaling `fd` to only the cases where the value being written is
/// equal to this parameter. The size of `datamatch` is important and it must
/// match the expected size of the guest's write.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate libc;
/// extern crate vmm_sys_util;
/// # use kvm_ioctls::{IoEventAddress, Kvm, NoDatamatch};
/// use libc::{eventfd, EFD_NONBLOCK};
/// use vmm_sys_util::eventfd::EventFd;
/// let kvm = Kvm::new().unwrap();
/// let vm_fd = kvm.create_vm().unwrap();
/// let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
/// vm_fd
/// .register_ioevent(&evtfd, &IoEventAddress::Pio(0xf4), NoDatamatch)
/// .unwrap();
/// vm_fd
/// .register_ioevent(&evtfd, &IoEventAddress::Mmio(0x1000), NoDatamatch)
/// .unwrap();
/// ```
pub fn register_ioevent<T: Into<u64>>(
&self,
fd: &EventFd,
addr: &IoEventAddress,
datamatch: T,
) -> Result<()> {
let mut flags = 0;
if std::mem::size_of::<T>() > 0 {
flags |= 1 << kvm_ioeventfd_flag_nr_datamatch
}
if let IoEventAddress::Pio(_) = *addr {
flags |= 1 << kvm_ioeventfd_flag_nr_pio
}
let ioeventfd = kvm_ioeventfd {
datamatch: datamatch.into(),
len: std::mem::size_of::<T>() as u32,
addr: match addr {
IoEventAddress::Pio(ref p) => *p,
IoEventAddress::Mmio(ref m) => *m,
},
fd: fd.as_raw_fd(),
flags,
..Default::default()
};
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_IOEVENTFD(), &ioeventfd) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Unregisters an event from a certain address it has been previously registered to.
///
/// See the documentation for `KVM_IOEVENTFD`.
///
/// # Arguments
///
/// * `fd` - FD which will be unregistered.
/// * `addr` - Address being written to.
///
/// # Safety
///
/// This function is unsafe because it relies on RawFd.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate libc;
/// extern crate vmm_sys_util;
/// # use kvm_ioctls::{IoEventAddress, Kvm, NoDatamatch};
/// use libc::EFD_NONBLOCK;
/// use vmm_sys_util::eventfd::EventFd;
///
/// let kvm = Kvm::new().unwrap();
/// let vm_fd = kvm.create_vm().unwrap();
/// let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
/// let pio_addr = IoEventAddress::Pio(0xf4);
/// let mmio_addr = IoEventAddress::Mmio(0x1000);
/// vm_fd
/// .register_ioevent(&evtfd, &pio_addr, NoDatamatch)
/// .unwrap();
/// vm_fd
/// .register_ioevent(&evtfd, &mmio_addr, 0x1234u32)
/// .unwrap();
/// vm_fd
/// .unregister_ioevent(&evtfd, &pio_addr, NoDatamatch)
/// .unwrap();
/// vm_fd
/// .unregister_ioevent(&evtfd, &mmio_addr, 0x1234u32)
/// .unwrap();
/// ```
pub fn unregister_ioevent<T: Into<u64>>(
&self,
fd: &EventFd,
addr: &IoEventAddress,
datamatch: T,
) -> Result<()> {
let mut flags = 1 << kvm_ioeventfd_flag_nr_deassign;
if std::mem::size_of::<T>() > 0 {
flags |= 1 << kvm_ioeventfd_flag_nr_datamatch
}
if let IoEventAddress::Pio(_) = *addr {
flags |= 1 << kvm_ioeventfd_flag_nr_pio
}
let ioeventfd = kvm_ioeventfd {
datamatch: datamatch.into(),
len: std::mem::size_of::<T>() as u32,
addr: match addr {
IoEventAddress::Pio(ref p) => *p,
IoEventAddress::Mmio(ref m) => *m,
},
fd: fd.as_raw_fd(),
flags,
..Default::default()
};
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_IOEVENTFD(), &ioeventfd) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Gets the bitmap of pages dirtied since the last call of this function.
///
/// Leverages the dirty page logging feature in KVM. As a side-effect, this also resets the
/// bitmap inside the kernel. For the dirty log to be available, you have to set the flag
/// `KVM_MEM_LOG_DIRTY_PAGES` when creating guest memory regions.
///
/// Check the documentation for `KVM_GET_DIRTY_LOG`.
///
/// # Arguments
///
/// * `slot` - Guest memory slot identifier.
/// * `memory_size` - Size of the memory region.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use std::io::Write;
/// # use std::ptr::null_mut;
/// # use std::slice;
/// # use kvm_ioctls::{Kvm, VcpuExit};
/// # use kvm_bindings::{kvm_userspace_memory_region, KVM_MEM_LOG_DIRTY_PAGES};
/// # let kvm = Kvm::new().unwrap();
/// # let vm = kvm.create_vm().unwrap();
/// // This example is based on https://lwn.net/Articles/658511/.
/// let mem_size = 0x4000;
/// let guest_addr: u64 = 0x1000;
/// let load_addr: *mut u8 = unsafe {
/// libc::mmap(
/// null_mut(),
/// mem_size,
/// libc::PROT_READ | libc::PROT_WRITE,
/// libc::MAP_ANONYMOUS | libc::MAP_SHARED | libc::MAP_NORESERVE,
/// -1,
/// 0,
/// ) as *mut u8
/// };
///
/// // Initialize a guest memory region using the flag `KVM_MEM_LOG_DIRTY_PAGES`.
/// let mem_region = kvm_userspace_memory_region {
/// slot: 0,
/// guest_phys_addr: guest_addr,
/// memory_size: mem_size as u64,
/// userspace_addr: load_addr as u64,
/// flags: KVM_MEM_LOG_DIRTY_PAGES,
/// };
/// unsafe { vm.set_user_memory_region(mem_region).unwrap() };
///
/// #[cfg(target_arch = "x86_64")]
/// // ASM code that just forces a MMIO Write.
/// let asm_code = [0xc6, 0x06, 0x00, 0x80, 0x00];
/// #[cfg(target_arch = "aarch64")]
/// let asm_code = [
/// 0x01, 0x00, 0x00, 0x10, /* adr x1, <this address> */
/// 0x22, 0x10, 0x00, 0xb9, /* str w2, [x1, #16]; write to this page */
/// 0x02, 0x00, 0x00, 0xb9, /* str w2, [x0]; force MMIO exit */
/// 0x00, 0x00, 0x00,
/// 0x14, /* b <this address>; shouldn't get here, but if so loop forever */
/// ];
/// #[cfg(target_arch = "riscv64")]
/// let asm_code = [
/// 0x17, 0x03, 0x00, 0x00, // auipc t1, 0; <this address> -> t1
/// 0xa3, 0x23, 0x73, 0x00, // sw t2, t1 + 7; dirty current page
/// 0x23, 0x20, 0x75, 0x00, // sw t2, a0; trigger MMIO exit
/// 0x6f, 0x00, 0x00, 0x00, // j .;shouldn't get here, but if so loop forever
/// ];
///
/// // Write the code in the guest memory. This will generate a dirty page.
/// unsafe {
/// let mut slice = slice::from_raw_parts_mut(load_addr, mem_size);
/// slice.write(&asm_code).unwrap();
/// }
///
/// let mut vcpu_fd = vm.create_vcpu(0).unwrap();
///
/// #[cfg(target_arch = "x86_64")]
/// {
/// // x86_64 specific registry setup.
/// let mut vcpu_sregs = vcpu_fd.get_sregs().unwrap();
/// vcpu_sregs.cs.base = 0;
/// vcpu_sregs.cs.selector = 0;
/// vcpu_fd.set_sregs(&vcpu_sregs).unwrap();
///
/// let mut vcpu_regs = vcpu_fd.get_regs().unwrap();
/// // Set the Instruction Pointer to the guest address where we loaded the code.
/// vcpu_regs.rip = guest_addr;
/// vcpu_regs.rax = 2;
/// vcpu_regs.rbx = 3;
/// vcpu_regs.rflags = 2;
/// vcpu_fd.set_regs(&vcpu_regs).unwrap();
/// }
///
/// #[cfg(target_arch = "aarch64")]
/// {
/// // aarch64 specific registry setup.
/// let mut kvi = kvm_bindings::kvm_vcpu_init::default();
/// vm.get_preferred_target(&mut kvi).unwrap();
/// vcpu_fd.vcpu_init(&kvi).unwrap();
///
/// let core_reg_base: u64 = 0x6030_0000_0010_0000;
/// let mmio_addr: u64 = guest_addr + mem_size as u64;
/// vcpu_fd.set_one_reg(core_reg_base + 2 * 32, &guest_addr.to_le_bytes()); // set PC
/// vcpu_fd.set_one_reg(core_reg_base + 2 * 0, &mmio_addr.to_le_bytes()); // set X0
/// }
///
/// #[cfg(target_arch = "riscv64")]
/// {
/// let core_reg_base: u64 = 0x8030_0000_0200_0000;
/// let mmio_addr: u64 = guest_addr + mem_size as u64;
/// vcpu_fd.set_one_reg(core_reg_base, &guest_addr.to_le_bytes()); // set PC
/// vcpu_fd.set_one_reg(core_reg_base + 10, &mmio_addr.to_le_bytes()); // set A0
/// }
///
/// loop {
/// match vcpu_fd.run().expect("run failed") {
/// VcpuExit::MmioWrite(addr, data) => {
/// // On x86_64, the code snippet dirties 1 page when loading the code in memory
/// // while on aarch64 the dirty bit comes from writing to guest_addr (current PC).
/// let dirty_pages_bitmap = vm.get_dirty_log(0, mem_size).unwrap();
/// let dirty_pages = dirty_pages_bitmap
/// .into_iter()
/// .map(|page| page.count_ones())
/// .fold(0, |dirty_page_count, i| dirty_page_count + i);
/// assert_eq!(dirty_pages, 1);
/// break;
/// }
/// exit_reason => panic!("unexpected exit reason: {:?}", exit_reason),
/// }
/// }
/// ```
pub fn get_dirty_log(&self, slot: u32, memory_size: usize) -> Result<Vec<u64>> {
// Compute the length of the bitmap needed for all dirty pages in one memory slot.
// One memory page is `page_size` bytes and `KVM_GET_DIRTY_LOG` returns one dirty bit for
// each page.
// SAFETY: We trust the sysconf libc function and we're calling it with a correct parameter.
let page_size = match unsafe { libc::sysconf(libc::_SC_PAGESIZE) } {
-1 => return Err(errno::Error::last()),
ps => ps as usize,
};
// For ease of access we are saving the bitmap in a u64 vector. We are using ceil to
// make sure we count all dirty pages even when `memory_size` is not a multiple of
// `page_size * 64`.
let bitmap_size = memory_size.div_ceil(page_size * 64);
let mut bitmap = vec![0u64; bitmap_size];
let dirtylog = kvm_dirty_log {
slot,
padding1: 0,
__bindgen_anon_1: kvm_dirty_log__bindgen_ty_1 {
dirty_bitmap: bitmap.as_mut_ptr() as *mut c_void,
},
};
// SAFETY: Safe because we know that our file is a VM fd, and we know that the amount of
// memory we allocated for the bitmap is at least one bit per page.
let ret = unsafe { ioctl_with_ref(self, KVM_GET_DIRTY_LOG(), &dirtylog) };
if ret == 0 {
Ok(bitmap)
} else {
Err(errno::Error::last())
}
}
/// Registers an event that will, when signaled, trigger the `gsi` IRQ.
///
/// # Arguments
///
/// * `fd` - `EventFd` to be signaled.
/// * `gsi` - IRQ to be triggered.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate libc;
/// # extern crate vmm_sys_util;
/// # use kvm_ioctls::Kvm;
/// # use libc::EFD_NONBLOCK;
/// # use vmm_sys_util::eventfd::EventFd;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
/// #[cfg(target_arch = "x86_64")]
/// {
/// vm.create_irq_chip().unwrap();
/// vm.register_irqfd(&evtfd, 0).unwrap();
/// }
/// ```
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
pub fn register_irqfd(&self, fd: &EventFd, gsi: u32) -> Result<()> {
let irqfd = kvm_irqfd {
fd: fd.as_raw_fd() as u32,
gsi,
..Default::default()
};
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_IRQFD(), &irqfd) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Registers an event that will, when signaled, assert the `gsi` IRQ.
/// If the irqchip is resampled by the guest, the IRQ is de-asserted,
/// and `resamplefd` is notified.
///
/// # Arguments
///
/// * `fd` - `EventFd` to be signaled.
/// * `resamplefd` - `EventFd`to be notified on resample.
/// * `gsi` - IRQ to be triggered.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate libc;
/// # extern crate vmm_sys_util;
/// # use kvm_ioctls::Kvm;
/// # use libc::EFD_NONBLOCK;
/// # use vmm_sys_util::eventfd::EventFd;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
/// let resamplefd = EventFd::new(EFD_NONBLOCK).unwrap();
/// #[cfg(target_arch = "x86_64")]
/// {
/// vm.create_irq_chip().unwrap();
/// vm.register_irqfd_with_resample(&evtfd, &resamplefd, 0)
/// .unwrap();
/// }
/// ```
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
pub fn register_irqfd_with_resample(
&self,
fd: &EventFd,
resamplefd: &EventFd,
gsi: u32,
) -> Result<()> {
let irqfd = kvm_irqfd {
fd: fd.as_raw_fd() as u32,
resamplefd: resamplefd.as_raw_fd() as u32,
gsi,
flags: KVM_IRQFD_FLAG_RESAMPLE,
..Default::default()
};
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_IRQFD(), &irqfd) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Unregisters an event that will, when signaled, trigger the `gsi` IRQ.
///
/// # Arguments
///
/// * `fd` - `EventFd` to be signaled.
/// * `gsi` - IRQ to be triggered.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate libc;
/// # extern crate vmm_sys_util;
/// # use kvm_ioctls::Kvm;
/// # use libc::EFD_NONBLOCK;
/// # use vmm_sys_util::eventfd::EventFd;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
/// let resamplefd = EventFd::new(EFD_NONBLOCK).unwrap();
/// #[cfg(target_arch = "x86_64")]
/// {
/// vm.create_irq_chip().unwrap();
/// vm.register_irqfd(&evtfd, 0).unwrap();
/// vm.unregister_irqfd(&evtfd, 0).unwrap();
/// vm.register_irqfd_with_resample(&evtfd, &resamplefd, 0)
/// .unwrap();
/// vm.unregister_irqfd(&evtfd, 0).unwrap();
/// }
/// ```
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
pub fn unregister_irqfd(&self, fd: &EventFd, gsi: u32) -> Result<()> {
let irqfd = kvm_irqfd {
fd: fd.as_raw_fd() as u32,
gsi,
flags: KVM_IRQFD_FLAG_DEASSIGN,
..Default::default()
};
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_IRQFD(), &irqfd) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Sets the level on the given irq to 1 if `active` is true, and 0 otherwise.
///
/// # Arguments
///
/// * `irq` - IRQ to be set.
/// * `active` - Level of the IRQ input.
///
/// # Errors
///
/// Returns an io::Error when the irq field is invalid
///
/// # Examples
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate libc;
/// # extern crate vmm_sys_util;
/// # use kvm_ioctls::{Kvm, VmFd};
/// # use libc::EFD_NONBLOCK;
/// # use vmm_sys_util::eventfd::EventFd;
/// fn arch_setup(vm_fd: &VmFd) {
/// // Arch-specific setup:
/// // For x86 architectures, it simply means calling vm.create_irq_chip().unwrap().
/// # #[cfg(target_arch = "x86_64")]
/// # vm_fd.create_irq_chip().unwrap();
/// // For Arm architectures, the IRQ controllers need to be setup first.
/// // Details please refer to the kernel documentation.
/// // https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt
/// # #[cfg(target_arch = "aarch64")] {
/// # vm_fd.create_vcpu(0).unwrap();
/// # // ... rest of setup for Arm goes here
/// # }
/// }
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// arch_setup(&vm);
/// #[cfg(target_arch = "x86_64")]
/// {
/// vm.set_irq_line(4, true);
/// // ...
/// }
/// #[cfg(target_arch = "aarch64")]
/// {
/// vm.set_irq_line(0x01_00_0020, true);
/// // ....
/// }
/// ```
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
pub fn set_irq_line(&self, irq: u32, active: bool) -> Result<()> {
let mut irq_level = kvm_irq_level::default();
irq_level.__bindgen_anon_1.irq = irq;
irq_level.level = u32::from(active);
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_IRQ_LINE(), &irq_level) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Creates a new KVM vCPU file descriptor and maps the memory corresponding
/// its `kvm_run` structure.
///
/// See the documentation for `KVM_CREATE_VCPU`.
///
/// # Arguments
///
/// * `id` - The vCPU ID.
///
/// # Errors
///
/// Returns an io::Error when the VM fd is invalid or the vCPU memory cannot
/// be mapped correctly.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// // Create one vCPU with the ID=0.
/// let vcpu = vm.create_vcpu(0);
/// ```
pub fn create_vcpu(&self, id: u64) -> Result<VcpuFd> {
#[allow(clippy::cast_lossless)]
// SAFETY: Safe because we know that vm is a VM fd and we verify the return result.
let vcpu_fd = unsafe { ioctl_with_val(&self.vm, KVM_CREATE_VCPU(), id as c_ulong) };
if vcpu_fd < 0 {
return Err(errno::Error::last());
}
// Wrap the vCPU now in case the following ? returns early.
// SAFETY: This is safe because we verified the value of the fd and we own the fd.
let vcpu = unsafe { File::from_raw_fd(vcpu_fd) };
let kvm_run_ptr = KvmRunWrapper::mmap_from_fd(&vcpu, self.run_size)?;
Ok(new_vcpu(vcpu, kvm_run_ptr))
}
/// Creates a VcpuFd object from a vcpu RawFd.
///
/// # Arguments
///
/// * `fd` - the RawFd used for creating the VcpuFd object.
///
/// # Safety
///
/// This function is unsafe as the primitives currently returned have the contract that
/// they are the sole owner of the file descriptor they are wrapping. Usage of this function
/// could accidentally allow violating this contract which can cause memory unsafety in code
/// that relies on it being true.
///
/// The caller of this method must make sure the fd is valid and nothing else uses it.
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # use std::os::unix::io::AsRawFd;
/// # use kvm_ioctls::Kvm;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// // Create one vCPU with the ID=0.
/// let vcpu = vm.create_vcpu(0).unwrap();
/// let rawfd = unsafe { libc::dup(vcpu.as_raw_fd()) };
/// assert!(rawfd >= 0);
/// let vcpu = unsafe { vm.create_vcpu_from_rawfd(rawfd).unwrap() };
/// ```
pub unsafe fn create_vcpu_from_rawfd(&self, fd: RawFd) -> Result<VcpuFd> {
let vcpu = File::from_raw_fd(fd);
let kvm_run_ptr = KvmRunWrapper::mmap_from_fd(&vcpu, self.run_size)?;
Ok(new_vcpu(vcpu, kvm_run_ptr))
}
/// Creates an emulated device in the kernel.
///
/// See the documentation for `KVM_CREATE_DEVICE`.
///
/// # Arguments
///
/// * `device`: device configuration. For details check the `kvm_create_device` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// use kvm_bindings::{
/// kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V2, kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V3,
/// kvm_device_type_KVM_DEV_TYPE_RISCV_AIA, kvm_device_type_KVM_DEV_TYPE_VFIO,
/// KVM_CREATE_DEVICE_TEST,
/// };
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// // Creating a device with the KVM_CREATE_DEVICE_TEST flag to check
/// // whether the device type is supported. This will not create the device.
/// // To create the device the flag needs to be removed.
/// let mut device = kvm_bindings::kvm_create_device {
/// #[cfg(target_arch = "x86_64")]
/// type_: kvm_device_type_KVM_DEV_TYPE_VFIO,
/// #[cfg(target_arch = "aarch64")]
/// type_: kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V3,
/// #[cfg(target_arch = "riscv64")]
/// type_: kvm_device_type_KVM_DEV_TYPE_RISCV_AIA,
/// fd: 0,
/// flags: KVM_CREATE_DEVICE_TEST,
/// };
/// // On ARM, creating VGICv3 may fail due to hardware dependency.
/// // Retry to create VGICv2 in that case.
/// let device_fd = vm.create_device(&mut device).unwrap_or_else(|_| {
/// #[cfg(target_arch = "x86_64")]
/// panic!("Cannot create VFIO device.");
/// #[cfg(target_arch = "aarch64")]
/// {
/// device.type_ = kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V2;
/// vm.create_device(&mut device)
/// .expect("Cannot create vGIC device")
/// }
/// #[cfg(target_arch = "riscv64")]
/// panic!("Cannot create vAIA device.");
/// });
/// ```
pub fn create_device(&self, device: &mut kvm_create_device) -> Result<DeviceFd> {
// SAFETY: Safe because we are calling this with the VM fd and we trust the kernel.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_CREATE_DEVICE(), device) };
if ret == 0 {
// SAFETY: We validated the return of the function creating the fd and we trust the
// kernel.
Ok(new_device(unsafe { File::from_raw_fd(device.fd as i32) }))
} else {
Err(errno::Error::last())
}
}
/// Returns the preferred CPU target type which can be emulated by KVM on underlying host.
///
/// The preferred CPU target is returned in the `kvi` parameter.
/// See documentation for `KVM_ARM_PREFERRED_TARGET`.
///
/// # Arguments
/// * `kvi` - CPU target configuration (out). For details check the `kvm_vcpu_init`
/// structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use kvm_ioctls::Kvm;
/// use kvm_bindings::kvm_vcpu_init;
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let mut kvi = kvm_vcpu_init::default();
/// vm.get_preferred_target(&mut kvi).unwrap();
/// ```
#[cfg(target_arch = "aarch64")]
pub fn get_preferred_target(&self, kvi: &mut kvm_vcpu_init) -> Result<()> {
// SAFETY: The ioctl is safe because we allocated the struct and we know the
// kernel will write exactly the size of the struct.
let ret = unsafe { ioctl_with_mut_ref(self, KVM_ARM_PREFERRED_TARGET(), kvi) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Enable the specified capability as per the `KVM_ENABLE_CAP` ioctl.
///
/// See the documentation for `KVM_ENABLE_CAP`.
///
/// Returns an io::Error when the capability could not be enabled.
///
/// # Arguments
///
/// * kvm_enable_cap - KVM capability structure. For details check the `kvm_enable_cap`
/// structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
///
/// # use kvm_ioctls::Kvm;
/// use kvm_bindings::{kvm_enable_cap, KVM_CAP_SPLIT_IRQCHIP};
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let mut cap: kvm_enable_cap = Default::default();
/// cap.cap = KVM_CAP_SPLIT_IRQCHIP;
/// // As per the KVM documentation, KVM_CAP_SPLIT_IRQCHIP only emulates
/// // the local APIC in kernel, expecting that a userspace IOAPIC will
/// // be implemented by the VMM.
/// // Along with this capability, the user needs to specify the number
/// // of pins reserved for the userspace IOAPIC. This number needs to be
/// // provided through the first argument of the capability structure, as
/// // specified in KVM documentation:
/// // args[0] - number of routes reserved for userspace IOAPICs
/// //
/// // Because an IOAPIC supports 24 pins, that's the reason why this test
/// // picked this number as reference.
/// cap.args[0] = 24;
/// vm.enable_cap(&cap).unwrap();
/// ```
#[cfg(any(target_arch = "x86_64", target_arch = "s390x", target_arch = "powerpc"))]
pub fn enable_cap(&self, cap: &kvm_enable_cap) -> Result<()> {
// SAFETY: The ioctl is safe because we allocated the struct and we know the
// kernel will write exactly the size of the struct.
let ret = unsafe { ioctl_with_ref(self, KVM_ENABLE_CAP(), cap) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Get the `kvm_run` size.
pub fn run_size(&self) -> usize {
self.run_size
}
/// Wrapper over `KVM_CHECK_EXTENSION`.
///
/// Returns 0 if the capability is not available and a positive integer otherwise.
/// See the documentation for `KVM_CHECK_EXTENSION`.
///
/// # Arguments
///
/// * `c` - KVM capability to check.
///
/// # Example
///
/// ```
/// # use kvm_ioctls::Kvm;
/// use kvm_ioctls::Cap;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// assert!(vm.check_extension_int(Cap::MaxVcpus) > 0);
/// ```
pub fn check_extension_int(&self, c: Cap) -> i32 {
self.check_extension_raw(c as c_ulong)
}
/// Wrapper over `KVM_CHECK_EXTENSION`.
///
/// Returns 0 if the capability is not available and a positive integer otherwise.
/// See the documentation for `KVM_CHECK_EXTENSION`.
///
/// # Arguments
///
/// * `c` - KVM capability to check in a form of a raw integer.
///
/// # Example
///
/// ```
/// # use kvm_ioctls::Kvm;
/// # use std::os::raw::c_ulong;
/// use kvm_ioctls::Cap;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// assert!(vm.check_extension_raw(Cap::MaxVcpus as c_ulong) > 0);
/// ```
pub fn check_extension_raw(&self, c: c_ulong) -> i32 {
// SAFETY: Safe because we know that our file is a KVM fd.
// If `c` is not a known kernel extension, kernel will return 0.
unsafe { ioctl_with_val(self, KVM_CHECK_EXTENSION(), c) }
}
/// Checks if a particular `Cap` is available.
///
/// Returns true if the capability is supported and false otherwise.
/// See the documentation for `KVM_CHECK_EXTENSION`.
///
/// # Arguments
///
/// * `c` - VM capability to check.
///
/// # Example
///
/// ```
/// # use kvm_ioctls::Kvm;
/// use kvm_ioctls::Cap;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// // Check if `KVM_CAP_MP_STATE` is supported.
/// assert!(vm.check_extension(Cap::MpState));
/// ```
pub fn check_extension(&self, c: Cap) -> bool {
self.check_extension_int(c) > 0
}
/// Creates an anonymous file and returns a file descriptor that refers to it.
///
/// See the documentation for `KVM_CREATE_GUEST_MEMFD`.
///
/// Returns an io::Error when the file could not be created.
///
/// # Arguments
///
/// * kvm_create_guest_memfd - KVM create guest memfd structure. For details check the
/// `kvm_create_guest_memfd` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
///
/// # use kvm_ioctls::{Cap, Kvm};
/// use kvm_bindings::{kvm_create_guest_memfd, KVM_CAP_GUEST_MEMFD};
/// use std::os::fd::RawFd;
///
/// let kvm = Kvm::new().unwrap();
/// #[cfg(target_arch = "x86_64")]
/// let vm = kvm
/// .create_vm_with_type(kvm_bindings::KVM_X86_SW_PROTECTED_VM as u64)
/// .unwrap();
/// #[cfg(not(target_arch = "x86_64"))]
/// let vm = kvm.create_vm().unwrap(); /* non-x86 does not yet have a vm type that supports gmem */
///
/// if !vm.check_extension(Cap::GuestMemfd) {
/// return;
/// }
///
/// let gmem = kvm_create_guest_memfd {
/// size: 0x1000,
/// flags: 0,
/// reserved: [0; 6],
/// };
///
/// let guest_memfd = vm.create_guest_memfd(gmem).unwrap();
/// ```
pub fn create_guest_memfd(&self, gmem: kvm_create_guest_memfd) -> Result<RawFd> {
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only
// read the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_CREATE_GUEST_MEMFD(), &gmem) };
if ret < 0 {
return Err(errno::Error::last());
}
Ok(ret)
}
/// Allows userspace to set memory attributes for a range of guest physical memory.
///
/// See the documentation for `KVM_SET_MEMORY_ATTRIBUTES`.
///
/// Returns an io::Error when the attributes could not be set.
///
/// # Arguments
///
/// * kvm_memory_attributes - KVM set memory attributes structure. For details check the
/// `kvm_memory_attributes` structure in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Example
///
/// ```rust
/// # extern crate kvm_ioctls;
/// extern crate kvm_bindings;
///
/// # use kvm_ioctls::{Cap, Kvm};
/// use kvm_bindings::{
/// kvm_create_guest_memfd, kvm_memory_attributes, kvm_userspace_memory_region2,
/// KVM_CAP_GUEST_MEMFD, KVM_CAP_MEMORY_ATTRIBUTES, KVM_CAP_USER_MEMORY2,
/// KVM_MEMORY_ATTRIBUTE_PRIVATE, KVM_MEM_GUEST_MEMFD,
/// };
/// use std::os::fd::RawFd;
///
/// let kvm = Kvm::new().unwrap();
/// #[cfg(target_arch = "x86_64")]
/// let vm = kvm
/// .create_vm_with_type(kvm_bindings::KVM_X86_SW_PROTECTED_VM as u64)
/// .unwrap();
/// #[cfg(not(target_arch = "x86_64"))]
/// let vm = kvm.create_vm().unwrap(); /* non-x86 does not yet have a vm type that supports gmem */
/// let gmem = kvm_create_guest_memfd {
/// size: 0x10000,
/// flags: 0,
/// reserved: [0; 6],
/// };
///
/// let address_space = unsafe { libc::mmap(0 as _, 10000, 3, 34, -1, 0) };
/// let userspace_addr = address_space as *const u8 as u64;
///
/// if !vm.check_extension(Cap::GuestMemfd)
/// || !vm.check_extension(Cap::UserMemory2)
/// || !vm.check_extension(Cap::MemoryAttributes)
/// {
/// return;
/// }
///
/// let fd: RawFd = unsafe { vm.create_guest_memfd(gmem).unwrap() };
/// let mem_region = kvm_userspace_memory_region2 {
/// slot: 0,
/// flags: KVM_MEM_GUEST_MEMFD,
/// guest_phys_addr: 0x10000 as u64,
/// memory_size: 0x10000 as u64,
/// userspace_addr,
/// guest_memfd_offset: 0,
/// guest_memfd: fd as u32,
/// pad1: 0,
/// pad2: [0; 14],
/// };
/// unsafe {
/// vm.set_user_memory_region2(mem_region).unwrap();
/// };
///
/// let attr = kvm_memory_attributes {
/// address: 0x10000,
/// size: 0x10000,
/// attributes: KVM_MEMORY_ATTRIBUTE_PRIVATE as u64,
/// flags: 0,
/// };
/// vm.set_memory_attributes(attr).unwrap();
/// ```
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
pub fn set_memory_attributes(&self, attr: kvm_memory_attributes) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_SET_MEMORY_ATTRIBUTES(), &attr) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Issues platform-specific memory encryption commands to manage encrypted VMs if
/// the platform supports creating those encrypted VMs.
///
/// Currently, this ioctl is used for issuing Secure Encrypted Virtualization
/// (SEV) commands on AMD Processors.
///
/// See the documentation for `KVM_MEMORY_ENCRYPT_OP` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// For SEV-specific functionality, prefer safe wrapper:
/// - [`encrypt_op_sev`](Self::encrypt_op_sev)
///
/// # Safety
///
/// This function is unsafe because there is no guarantee `T` is valid in this context, how
/// much data kernel will read from memory and where it will write data on error.
///
/// # Arguments
///
/// * `op` - an opaque platform specific structure.
///
/// # Example
#[cfg_attr(has_sev, doc = "```rust")]
#[cfg_attr(not(has_sev), doc = "```rust,no_run")]
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// use kvm_bindings::bindings::kvm_sev_cmd;
/// # use kvm_ioctls::Kvm;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// // Initialize the SEV platform context.
/// let mut init: kvm_sev_cmd = Default::default();
/// unsafe { vm.encrypt_op(&mut init).unwrap() };
/// ```
#[cfg(target_arch = "x86_64")]
pub unsafe fn encrypt_op<T>(&self, op: *mut T) -> Result<()> {
let ret = ioctl_with_mut_ptr(self, KVM_MEMORY_ENCRYPT_OP(), op);
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Issue common lifecycle events of SEV guests, such as launching, running, snapshotting,
/// migrating and decommissioning via `KVM_MEMORY_ENCRYPT_OP` ioctl.
///
/// Kernel documentation states that this ioctl can be used for testing whether SEV is enabled
/// by sending `NULL`. To do that, pass [`std::ptr::null_mut`](std::ptr::null_mut) to [`encrypt_op`](Self::encrypt_op).
///
/// See the documentation for Secure Encrypted Virtualization (SEV).
///
/// # Arguments
///
/// * `op` - SEV-specific structure. For details check the
/// [Secure Encrypted Virtualization (SEV) doc](https://www.kernel.org/doc/Documentation/virtual/kvm/amd-memory-encryption.rst).
///
/// # Example
#[cfg_attr(has_sev, doc = "```rust")]
#[cfg_attr(not(has_sev), doc = "```rust,no_run")]
/// # extern crate kvm_ioctls;
/// # extern crate kvm_bindings;
/// # use std::{os::raw::c_void, ptr::null_mut};
/// use kvm_bindings::bindings::kvm_sev_cmd;
/// # use kvm_ioctls::Kvm;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
///
/// // Check whether SEV is enabled, optional.
/// unsafe { vm.encrypt_op(null_mut() as *mut c_void) }.unwrap();
///
/// // Initialize the SEV platform context.
/// let mut init: kvm_sev_cmd = Default::default();
/// vm.encrypt_op_sev(&mut init).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn encrypt_op_sev(&self, op: &mut kvm_sev_cmd) -> Result<()> {
// SAFETY: Safe because we know that kernel will only read the correct amount of memory
// from our pointer and we know where it will write it (op.error).
unsafe { self.encrypt_op(op) }
}
/// Register a guest memory region which may contain encrypted data.
///
/// It is used in the SEV-enabled guest.
///
/// See the documentation for `KVM_MEMORY_ENCRYPT_REG_REGION` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `memory_region` - Guest physical memory region.
///
/// # Example
#[cfg_attr(has_sev, doc = "```rust")]
#[cfg_attr(not(has_sev), doc = "```rust,no_run")]
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # extern crate libc;
/// # use std::{fs::OpenOptions, ptr::null_mut};
/// # use std::os::unix::io::AsRawFd;
/// use kvm_bindings::bindings::{kvm_enc_region, kvm_sev_cmd, kvm_sev_launch_start, sev_cmd_id_KVM_SEV_LAUNCH_START};
/// # use kvm_ioctls::Kvm;
/// use libc;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let sev = OpenOptions::new()
/// .read(true)
/// .write(true)
/// .open("/dev/sev")
/// .unwrap();
///
/// // Initialize the SEV platform context.
/// let mut init: kvm_sev_cmd = Default::default();
/// vm.encrypt_op_sev(&mut init).unwrap();
///
/// // Create the memory encryption context.
/// let start_data: kvm_sev_launch_start = Default::default();
/// let mut start = kvm_sev_cmd {
/// id: sev_cmd_id_KVM_SEV_LAUNCH_START,
/// data: &start_data as *const kvm_sev_launch_start as _,
/// sev_fd: sev.as_raw_fd() as _,
/// ..Default::default()
/// };
/// vm.encrypt_op_sev(&mut start).unwrap();
///
/// let addr = unsafe {
/// libc::mmap(
/// null_mut(),
/// 4096,
/// libc::PROT_READ | libc::PROT_WRITE,
/// libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
/// -1,
/// 0,
/// )
/// };
/// assert_ne!(addr, libc::MAP_FAILED);
///
/// let memory_region = kvm_enc_region {
/// addr: addr as _,
/// size: 4096,
/// };
/// vm.register_enc_memory_region(&memory_region).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn register_enc_memory_region(&self, memory_region: &kvm_enc_region) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_MEMORY_ENCRYPT_REG_REGION(), memory_region) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Unregister a guest memory region registered with
/// [`register_enc_memory_region`](Self::register_enc_memory_region).
///
/// It is used in the SEV-enabled guest.
///
/// See the documentation for `KVM_MEMORY_ENCRYPT_UNREG_REGION` in the
/// [KVM API doc](https://www.kernel.org/doc/Documentation/virtual/kvm/api.txt).
///
/// # Arguments
///
/// * `memory_region` - Guest physical memory region.
///
/// # Example
#[cfg_attr(has_sev, doc = "```rust")]
#[cfg_attr(not(has_sev), doc = "```rust,no_run")]
/// # extern crate kvm_bindings;
/// # extern crate kvm_ioctls;
/// # extern crate libc;
/// # use std::{fs::OpenOptions, ptr::null_mut};
/// # use std::os::unix::io::AsRawFd;
/// use kvm_bindings::bindings::{kvm_enc_region, kvm_sev_cmd, kvm_sev_launch_start, sev_cmd_id_KVM_SEV_LAUNCH_START};
/// # use kvm_ioctls::Kvm;
/// use libc;
///
/// let kvm = Kvm::new().unwrap();
/// let vm = kvm.create_vm().unwrap();
/// let sev = OpenOptions::new()
/// .read(true)
/// .write(true)
/// .open("/dev/sev")
/// .unwrap();
///
/// // Initialize the SEV platform context.
/// let mut init: kvm_sev_cmd = Default::default();
/// vm.encrypt_op_sev(&mut init).unwrap();
///
/// // Create the memory encryption context.
/// let start_data: kvm_sev_launch_start = Default::default();
/// let mut start = kvm_sev_cmd {
/// id: sev_cmd_id_KVM_SEV_LAUNCH_START,
/// data: &start_data as *const kvm_sev_launch_start as _,
/// sev_fd: sev.as_raw_fd() as _,
/// ..Default::default()
/// };
/// vm.encrypt_op_sev(&mut start).unwrap();
///
/// let addr = unsafe {
/// libc::mmap(
/// null_mut(),
/// 4096,
/// libc::PROT_READ | libc::PROT_WRITE,
/// libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
/// -1,
/// 0,
/// )
/// };
/// assert_ne!(addr, libc::MAP_FAILED);
///
/// let memory_region = kvm_enc_region {
/// addr: addr as _,
/// size: 4096,
/// };
/// vm.register_enc_memory_region(&memory_region).unwrap();
/// vm.unregister_enc_memory_region(&memory_region).unwrap();
/// ```
#[cfg(target_arch = "x86_64")]
pub fn unregister_enc_memory_region(&self, memory_region: &kvm_enc_region) -> Result<()> {
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_MEMORY_ENCRYPT_UNREG_REGION(), memory_region) };
if ret == 0 {
Ok(())
} else {
Err(errno::Error::last())
}
}
/// Registers an address for coalesced MMIO. Write accesses to the address
/// will not cause a corresponding [`VcpuExit`](crate::VcpuExit), but
/// instead will be appended to the MMIO ring buffer. The [`VcpuFd`] can
/// read entries in the ring buffer via [`VcpuFd::coalesced_mmio_read()`].
/// If entries are not read the buffer will eventually be full,
/// preventing further elements from being appended by the kernel.
///
/// Needs `KVM_CAP_COALESCED_MMIO` ([`Cap::CoalescedMmio`](crate::Cap::CoalescedMmio))
/// and/or `KVM_CAP_COALESCED_PIO` ([`Cap::CoalescedMmio`](crate::Cap::CoalescedPio)).
///
/// See the documentation for `KVM_REGISTER_COALESCED_MMIO`.
///
/// # Arguments
///
/// * `addr` - Address being written to.
/// * `size` - The size of the write for the mechanism to trigger.
pub fn register_coalesced_mmio(&self, addr: IoEventAddress, size: u32) -> Result<()> {
let (addr, pio) = match addr {
IoEventAddress::Pio(addr) => (addr, 1),
IoEventAddress::Mmio(addr) => (addr, 0),
};
let mut zone = kvm_coalesced_mmio_zone {
addr,
size,
..Default::default()
};
zone.__bindgen_anon_1.pio = pio;
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_REGISTER_COALESCED_MMIO(), &zone) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
/// Unregister an address that was previously registered via
/// [`register_coalesced_mmio()`](VmFd::register_coalesced_mmio).
///
/// See the documentation for `KVM_UNREGISTER_COALESCED_MMIO`.
pub fn unregister_coalesced_mmio(&self, addr: IoEventAddress, size: u32) -> Result<()> {
let (addr, pio) = match addr {
IoEventAddress::Pio(addr) => (addr, 1),
IoEventAddress::Mmio(addr) => (addr, 0),
};
let mut zone = kvm_coalesced_mmio_zone {
addr,
size,
..Default::default()
};
zone.__bindgen_anon_1.pio = pio;
// SAFETY: Safe because we know that our file is a VM fd, we know the kernel will only read
// the correct amount of memory from our pointer, and we verify the return result.
let ret = unsafe { ioctl_with_ref(self, KVM_UNREGISTER_COALESCED_MMIO(), &zone) };
if ret != 0 {
return Err(errno::Error::last());
}
Ok(())
}
}
/// Helper function to create a new `VmFd`.
///
/// This should not be exported as a public function because the preferred way is to use
/// `create_vm` from `Kvm`. The function cannot be part of the `VmFd` implementation because
/// then it would be exported with the public `VmFd` interface.
pub fn new_vmfd(vm: File, run_size: usize) -> VmFd {
VmFd { vm, run_size }
}
impl AsRawFd for VmFd {
fn as_raw_fd(&self) -> RawFd {
self.vm.as_raw_fd()
}
}
/// Create a dummy GIC device.
///
/// # Arguments
///
/// * `vm` - The vm file descriptor.
/// * `flags` - Flags to be passed to `KVM_CREATE_DEVICE`.
#[cfg(test)]
#[cfg(target_arch = "aarch64")]
pub(crate) fn create_gic_device(vm: &VmFd, flags: u32) -> DeviceFd {
let mut gic_device = kvm_create_device {
type_: kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V3,
fd: 0,
flags,
};
match vm.create_device(&mut gic_device) {
Ok(fd) => fd,
Err(_) => {
gic_device.type_ = kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V2;
vm.create_device(&mut gic_device)
.expect("Cannot create KVM vGIC device")
}
}
}
/// Set supported number of IRQs for vGIC.
///
/// # Arguments
///
/// * `vgic` - The vGIC file descriptor.
/// * `nr_irqs` - Number of IRQs.
#[cfg(test)]
#[cfg(target_arch = "aarch64")]
pub(crate) fn set_supported_nr_irqs(vgic: &DeviceFd, nr_irqs: u32) {
let vgic_attr = kvm_device_attr {
group: KVM_DEV_ARM_VGIC_GRP_NR_IRQS,
attr: 0,
addr: &nr_irqs as *const u32 as u64,
flags: 0,
};
vgic.has_device_attr(&vgic_attr).unwrap();
vgic.set_device_attr(&vgic_attr).unwrap();
}
/// Request the initialization of the vGIC.
///
/// # Arguments
///
/// * `vgic` - The vGIC file descriptor.
#[cfg(test)]
#[cfg(target_arch = "aarch64")]
pub(crate) fn request_gic_init(vgic: &DeviceFd) {
let vgic_attr = kvm_device_attr {
group: KVM_DEV_ARM_VGIC_GRP_CTRL,
attr: u64::from(KVM_DEV_ARM_VGIC_CTRL_INIT),
addr: 0,
flags: 0,
};
vgic.has_device_attr(&vgic_attr).unwrap();
vgic.set_device_attr(&vgic_attr).unwrap();
}
/// Create a dummy AIA device.
///
/// # Arguments
///
/// * `vm` - The vm file descriptor.
/// * `flags` - Flags to be passed to `KVM_CREATE_DEVICE`.
#[cfg(test)]
#[cfg(target_arch = "riscv64")]
pub(crate) fn create_aia_device(vm: &VmFd, flags: u32) -> DeviceFd {
let mut aia_device = kvm_create_device {
type_: kvm_device_type_KVM_DEV_TYPE_RISCV_AIA,
fd: 0,
flags,
};
vm.create_device(&mut aia_device)
.expect("Cannot create KVM vAIA device")
}
/// Set supported number of IRQs for vAIA.
///
/// # Arguments
///
/// * `vaia` - The vAIA file descriptor.
/// * `nr_irqs` - Number of IRQs.
#[cfg(test)]
#[cfg(target_arch = "riscv64")]
pub(crate) fn set_supported_nr_irqs(vaia: &DeviceFd, nr_irqs: u32) {
let vaia_attr = kvm_device_attr {
group: KVM_DEV_RISCV_AIA_GRP_CONFIG,
attr: u64::from(KVM_DEV_RISCV_AIA_CONFIG_SRCS),
addr: &nr_irqs as *const u32 as u64,
flags: 0,
};
vaia.has_device_attr(&vaia_attr).unwrap();
vaia.set_device_attr(&vaia_attr).unwrap();
}
/// Request the initialization of the vAIA.
///
/// # Arguments
///
/// * `vaia` - The vAIA file descriptor.
#[cfg(test)]
#[cfg(target_arch = "riscv64")]
pub(crate) fn request_aia_init(vaia: &DeviceFd) {
let vaia_attr = kvm_device_attr {
group: KVM_DEV_RISCV_AIA_GRP_CTRL,
attr: u64::from(KVM_DEV_RISCV_AIA_CTRL_INIT),
addr: 0,
flags: 0,
};
vaia.has_device_attr(&vaia_attr).unwrap();
vaia.set_device_attr(&vaia_attr).unwrap();
}
#[cfg(test)]
mod tests {
#![allow(clippy::undocumented_unsafe_blocks)]
use super::*;
use crate::Kvm;
#[cfg(target_arch = "x86_64")]
use std::{fs::OpenOptions, os::fd::IntoRawFd, ptr::null_mut};
use libc::EFD_NONBLOCK;
#[test]
fn test_set_invalid_memory() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let invalid_mem_region = kvm_userspace_memory_region {
slot: 0,
guest_phys_addr: 0,
memory_size: 0,
userspace_addr: 0,
flags: 0,
};
unsafe { vm.set_user_memory_region(invalid_mem_region) }.unwrap_err();
}
#[test]
fn test_set_invalid_memory2() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let invalid_mem_region = kvm_userspace_memory_region2 {
slot: 0,
flags: 0,
guest_phys_addr: 0,
memory_size: 0,
userspace_addr: 0,
guest_memfd_offset: 0,
guest_memfd: 0,
pad1: 0,
pad2: [0; 14],
};
unsafe { vm.set_user_memory_region2(invalid_mem_region) }.unwrap_err();
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_set_tss_address() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
vm.set_tss_address(0xfffb_d000).unwrap();
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_set_identity_map_address() {
let Ok(kvm) = Kvm::new() else { return };
if kvm.check_extension(Cap::SetIdentityMapAddr) {
let vm = kvm.create_vm().unwrap();
vm.set_identity_map_address(0xfffb_c000).unwrap();
vm.create_vcpu(0).unwrap();
// Setting the identity map after creating a vCPU must fail.
vm.set_identity_map_address(0xfffb_c000).unwrap_err();
}
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_irq_chip() {
use Cap;
let Ok(kvm) = Kvm::new() else { return };
assert!(kvm.check_extension(Cap::Irqchip));
let vm = kvm.create_vm().unwrap();
vm.create_irq_chip().unwrap();
let mut irqchip = kvm_irqchip {
chip_id: KVM_IRQCHIP_PIC_MASTER,
..Default::default()
};
// Set the irq_base to a non-default value to check that set & get work.
irqchip.chip.pic.irq_base = 10;
vm.set_irqchip(&irqchip).unwrap();
// We initialize a dummy irq chip (`other_irqchip`) in which the
// function `get_irqchip` returns its result.
let mut other_irqchip = kvm_irqchip {
chip_id: KVM_IRQCHIP_PIC_MASTER,
..Default::default()
};
vm.get_irqchip(&mut other_irqchip).unwrap();
// Safe because we know that the irqchip type is PIC.
unsafe { assert_eq!(irqchip.chip.pic, other_irqchip.chip.pic) };
}
#[test]
#[cfg(target_arch = "aarch64")]
fn test_irq_chip() {
use Cap;
let Ok(kvm) = Kvm::new() else { return };
assert!(kvm.check_extension(Cap::Irqchip));
let vm = kvm.create_vm().unwrap();
// On ARM/arm64, a GICv2 is created. It's better to check ahead whether GICv2
// can be emulated or not.
let mut gic_device = kvm_create_device {
type_: kvm_device_type_KVM_DEV_TYPE_ARM_VGIC_V2,
fd: 0,
flags: KVM_CREATE_DEVICE_TEST,
};
let vgic_v2_supported = vm.create_device(&mut gic_device).is_ok();
assert_eq!(vm.create_irq_chip().is_ok(), vgic_v2_supported);
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_pit2() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
assert!(kvm.check_extension(Cap::Irqchip));
vm.create_irq_chip().unwrap();
vm.create_pit2(kvm_pit_config::default()).unwrap();
let pit2 = vm.get_pit2().unwrap();
vm.set_pit2(&pit2).unwrap();
let mut other_pit2 = vm.get_pit2().unwrap();
// Load time will differ, let's overwrite it so we can test equality.
other_pit2.channels[0].count_load_time = pit2.channels[0].count_load_time;
other_pit2.channels[1].count_load_time = pit2.channels[1].count_load_time;
other_pit2.channels[2].count_load_time = pit2.channels[2].count_load_time;
assert_eq!(pit2, other_pit2);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_clock() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
// Get current time.
let orig = vm.get_clock().unwrap();
// Reset time.
let fudged = kvm_clock_data {
clock: 10,
..Default::default()
};
vm.set_clock(&fudged).unwrap();
// Get new time.
let new = vm.get_clock().unwrap();
// Verify new time has progressed but is smaller than orig time.
assert!(fudged.clock < new.clock);
assert!(new.clock < orig.clock);
}
#[test]
fn test_register_ioevent() {
assert_eq!(std::mem::size_of::<NoDatamatch>(), 0);
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
vm_fd
.register_ioevent(&evtfd, &IoEventAddress::Pio(0xf4), NoDatamatch)
.unwrap();
vm_fd
.register_ioevent(&evtfd, &IoEventAddress::Mmio(0x1000), NoDatamatch)
.unwrap();
vm_fd
.register_ioevent(&evtfd, &IoEventAddress::Pio(0xc1), 0x7fu8)
.unwrap();
vm_fd
.register_ioevent(&evtfd, &IoEventAddress::Pio(0xc2), 0x1337u16)
.unwrap();
vm_fd
.register_ioevent(&evtfd, &IoEventAddress::Pio(0xc4), 0xdead_beefu32)
.unwrap();
vm_fd
.register_ioevent(&evtfd, &IoEventAddress::Pio(0xc8), 0xdead_beef_dead_beefu64)
.unwrap()
}
#[test]
fn test_unregister_ioevent() {
assert_eq!(std::mem::size_of::<NoDatamatch>(), 0);
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
let evtfd = EventFd::new(EFD_NONBLOCK).unwrap();
let pio_addr = IoEventAddress::Pio(0xf4);
let mmio_addr = IoEventAddress::Mmio(0x1000);
// First try to unregister addresses which have not been registered.
vm_fd
.unregister_ioevent(&evtfd, &pio_addr, NoDatamatch)
.unwrap_err();
vm_fd
.unregister_ioevent(&evtfd, &mmio_addr, NoDatamatch)
.unwrap_err();
// Now register the addresses
vm_fd
.register_ioevent(&evtfd, &pio_addr, NoDatamatch)
.unwrap();
vm_fd
.register_ioevent(&evtfd, &mmio_addr, 0x1337u16)
.unwrap();
// Try again unregistering the addresses. This time it should work
// since they have been previously registered.
vm_fd
.unregister_ioevent(&evtfd, &pio_addr, NoDatamatch)
.unwrap();
vm_fd
.unregister_ioevent(&evtfd, &mmio_addr, 0x1337u16)
.unwrap();
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_register_unregister_irqfd() {
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
let evtfd1 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd2 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd3 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd4 = EventFd::new(EFD_NONBLOCK).unwrap();
let resamplefd = EventFd::new(EFD_NONBLOCK).unwrap();
vm_fd.create_irq_chip().unwrap();
vm_fd.register_irqfd(&evtfd1, 4).unwrap();
vm_fd.register_irqfd(&evtfd2, 8).unwrap();
vm_fd.register_irqfd(&evtfd3, 4).unwrap();
vm_fd.unregister_irqfd(&evtfd2, 8).unwrap();
// KVM irqfd doesn't report failure on this case:(
vm_fd.unregister_irqfd(&evtfd2, 8).unwrap();
// Duplicated eventfd registration.
// On x86_64 this fails as the event fd was already matched with a GSI.
vm_fd.register_irqfd(&evtfd3, 4).unwrap_err();
vm_fd.register_irqfd(&evtfd3, 5).unwrap_err();
// KVM irqfd doesn't report failure on this case:(
vm_fd.unregister_irqfd(&evtfd3, 5).unwrap();
if vm_fd.check_extension(Cap::IrqfdResample) {
vm_fd
.register_irqfd_with_resample(&evtfd4, &resamplefd, 6)
.unwrap();
vm_fd.unregister_irqfd(&evtfd4, 6).unwrap();
} else {
vm_fd
.register_irqfd_with_resample(&evtfd4, &resamplefd, 6)
.unwrap_err();
}
}
#[test]
#[cfg(target_arch = "aarch64")]
fn test_register_unregister_irqfd() {
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
let evtfd1 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd2 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd3 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd4 = EventFd::new(EFD_NONBLOCK).unwrap();
let resamplefd = EventFd::new(EFD_NONBLOCK).unwrap();
// Create the vGIC device.
let vgic_fd = create_gic_device(&vm_fd, 0);
// GICv3 on arm/aarch64 requires an online vCPU prior to setting device attributes,
// see: https://www.kernel.org/doc/html/latest/virt/kvm/devices/arm-vgic-v3.html
vm_fd.create_vcpu(0).unwrap();
// Set supported number of IRQs.
set_supported_nr_irqs(&vgic_fd, 128);
// Request the initialization of the vGIC.
request_gic_init(&vgic_fd);
vm_fd.register_irqfd(&evtfd1, 4).unwrap();
vm_fd.register_irqfd(&evtfd2, 8).unwrap();
vm_fd.register_irqfd(&evtfd3, 4).unwrap();
vm_fd.unregister_irqfd(&evtfd2, 8).unwrap();
// KVM irqfd doesn't report failure on this case:(
vm_fd.unregister_irqfd(&evtfd2, 8).unwrap();
// Duplicated eventfd registration.
// On aarch64, this fails because setting up the interrupt controller is mandatory before
// registering any IRQ.
vm_fd.register_irqfd(&evtfd3, 4).unwrap_err();
vm_fd.register_irqfd(&evtfd3, 5).unwrap_err();
// KVM irqfd doesn't report failure on this case:(
vm_fd.unregister_irqfd(&evtfd3, 5).unwrap();
if vm_fd.check_extension(Cap::IrqfdResample) {
vm_fd
.register_irqfd_with_resample(&evtfd4, &resamplefd, 6)
.unwrap();
vm_fd.unregister_irqfd(&evtfd4, 6).unwrap();
} else {
vm_fd
.register_irqfd_with_resample(&evtfd4, &resamplefd, 6)
.unwrap_err();
}
}
#[test]
#[cfg(target_arch = "riscv64")]
fn test_register_unregister_irqfd() {
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
let evtfd1 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd2 = EventFd::new(EFD_NONBLOCK).unwrap();
let evtfd3 = EventFd::new(EFD_NONBLOCK).unwrap();
// Create the vAIA device.
let vaia_fd = create_aia_device(&vm_fd, 0);
// AIA on riscv64 requires at least one online vCPU prior to setting
// device attributes. Otherwise it would fail when trying ot set address
// of IMSIC.
vm_fd.create_vcpu(0).unwrap();
// Set maximum supported number of IRQs of the vAIA device to 128.
set_supported_nr_irqs(&vaia_fd, 128);
// Before request vAIA device to initialize, APLIC and IMSIC must be set
let aplic_addr: u64 = 0x4000;
vaia_fd
.set_device_attr(&kvm_device_attr {
group: KVM_DEV_RISCV_AIA_GRP_ADDR,
attr: u64::from(KVM_DEV_RISCV_AIA_ADDR_APLIC),
addr: &aplic_addr as *const u64 as u64,
flags: 0,
})
.unwrap();
let imsic_addr: u64 = 0x8000;
vaia_fd
.set_device_attr(&kvm_device_attr {
group: KVM_DEV_RISCV_AIA_GRP_ADDR,
attr: 1u64,
addr: &imsic_addr as *const u64 as u64,
flags: 0,
})
.unwrap();
// Initialize valid vAIA device.
request_aia_init(&vaia_fd);
vm_fd.register_irqfd(&evtfd1, 4).unwrap();
vm_fd.register_irqfd(&evtfd2, 8).unwrap();
vm_fd.register_irqfd(&evtfd3, 4).unwrap();
vm_fd.unregister_irqfd(&evtfd2, 8).unwrap();
// KVM irqfd doesn't report failure on this case:(
vm_fd.unregister_irqfd(&evtfd2, 8).unwrap();
// Duplicated eventfd registration.
// On riscv64 this fails as the event fd was already matched with a GSI.
vm_fd.register_irqfd(&evtfd3, 4).unwrap_err();
vm_fd.register_irqfd(&evtfd3, 5).unwrap_err();
// KVM irqfd doesn't report failure on this case:(
vm_fd.unregister_irqfd(&evtfd3, 5).unwrap();
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_set_irq_line() {
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
vm_fd.create_irq_chip().unwrap();
vm_fd.set_irq_line(4, true).unwrap();
vm_fd.set_irq_line(4, false).unwrap();
vm_fd.set_irq_line(4, true).unwrap();
}
#[test]
#[cfg(target_arch = "aarch64")]
#[allow(clippy::unusual_byte_groupings)]
fn test_set_irq_line() {
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
// Create a vcpu for test case 2 of the KVM_IRQ_LINE API on aarch64.
vm_fd.create_vcpu(0).unwrap();
// Create the vGIC device.
let vgic_fd = create_gic_device(&vm_fd, 0);
// Set supported number of IRQs.
set_supported_nr_irqs(&vgic_fd, 128);
// Request the initialization of the vGIC.
request_gic_init(&vgic_fd);
// On arm/aarch64, irq field is interpreted like this:
// bits: | 31 ... 24 | 23 ... 16 | 15 ... 0 |
// field: | irq_type | vcpu_index | irq_id |
// The irq_type field has the following values:
// - irq_type[0]: out-of-kernel GIC: irq_id 0 is IRQ, irq_id 1 is FIQ
// - irq_type[1]: in-kernel GIC: SPI, irq_id between 32 and 1019 (incl.) (the vcpu_index field is ignored)
// - irq_type[2]: in-kernel GIC: PPI, irq_id between 16 and 31 (incl.)
// Hence, using irq_type = 1, irq_id = 32 (decimal), the irq field in hex is: 0x01_00_0020
vm_fd.set_irq_line(0x01_00_0020, true).unwrap();
vm_fd.set_irq_line(0x01_00_0020, false).unwrap();
vm_fd.set_irq_line(0x01_00_0020, true).unwrap();
// Case 2: using irq_type = 2, vcpu_index = 0, irq_id = 16 (decimal), the irq field in hex is: 0x02_00_0010
vm_fd.set_irq_line(0x02_00_0010, true).unwrap();
vm_fd.set_irq_line(0x02_00_0010, false).unwrap();
vm_fd.set_irq_line(0x02_00_0010, true).unwrap();
}
#[test]
#[cfg(target_arch = "riscv64")]
fn test_set_irq_line() {
let Ok(kvm) = Kvm::new() else { return };
let vm_fd = kvm.create_vm().unwrap();
vm_fd.create_vcpu(0).unwrap();
// Create the vAIA device.
let vaia_fd = create_aia_device(&vm_fd, 0);
// Set maximum supported number of IRQs of the vAIA device to 128.
set_supported_nr_irqs(&vaia_fd, 128);
// Before request vAIA device to initialize, APLIC and IMSIC must be set
let aplic_addr: u64 = 0x4000;
vaia_fd
.set_device_attr(&kvm_device_attr {
group: KVM_DEV_RISCV_AIA_GRP_ADDR,
attr: u64::from(KVM_DEV_RISCV_AIA_ADDR_APLIC),
addr: &aplic_addr as *const u64 as u64,
flags: 0,
})
.unwrap();
let imsic_addr: u64 = 0x8000;
vaia_fd
.set_device_attr(&kvm_device_attr {
group: KVM_DEV_RISCV_AIA_GRP_ADDR,
attr: 1u64,
addr: &imsic_addr as *const u64 as u64,
flags: 0,
})
.unwrap();
// Initialize valid vAIA device.
request_aia_init(&vaia_fd);
vm_fd.set_irq_line(7, true).unwrap();
vm_fd.set_irq_line(7, false).unwrap();
vm_fd.set_irq_line(7, true).unwrap();
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_faulty_vm_fd() {
let badf_errno = libc::EBADF;
let faulty_vm_fd = VmFd {
vm: unsafe { File::from_raw_fd(-2) },
run_size: 0,
};
let invalid_mem_region = kvm_userspace_memory_region {
slot: 0,
guest_phys_addr: 0,
memory_size: 0,
userspace_addr: 0,
flags: 0,
};
assert_eq!(
unsafe {
faulty_vm_fd
.set_user_memory_region(invalid_mem_region)
.unwrap_err()
.errno()
},
badf_errno
);
assert_eq!(
faulty_vm_fd.set_tss_address(0).unwrap_err().errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd.create_irq_chip().unwrap_err().errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd
.create_pit2(kvm_pit_config::default())
.unwrap_err()
.errno(),
badf_errno
);
let event_fd = EventFd::new(EFD_NONBLOCK).unwrap();
assert_eq!(
faulty_vm_fd
.register_ioevent(&event_fd, &IoEventAddress::Pio(0), 0u64)
.unwrap_err()
.errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd
.get_irqchip(&mut kvm_irqchip::default())
.unwrap_err()
.errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd
.set_irqchip(&kvm_irqchip::default())
.unwrap_err()
.errno(),
badf_errno
);
assert_eq!(faulty_vm_fd.get_clock().unwrap_err().errno(), badf_errno);
assert_eq!(
faulty_vm_fd
.set_clock(&kvm_clock_data::default())
.unwrap_err()
.errno(),
badf_errno
);
assert_eq!(faulty_vm_fd.get_pit2().unwrap_err().errno(), badf_errno);
assert_eq!(
faulty_vm_fd
.set_pit2(&kvm_pit_state2::default())
.unwrap_err()
.errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd
.register_irqfd(&event_fd, 0)
.unwrap_err()
.errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd.create_vcpu(0).err().unwrap().errno(),
badf_errno
);
assert_eq!(
faulty_vm_fd.get_dirty_log(0, 0).unwrap_err().errno(),
badf_errno
);
// Don't drop the File object, or it'll notice the file it's trying to close is
// invalid and abort the process.
let _ = faulty_vm_fd.vm.into_raw_fd();
}
#[test]
#[cfg(target_arch = "aarch64")]
fn test_get_preferred_target() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let mut kvi = kvm_vcpu_init::default();
vm.get_preferred_target(&mut kvi).unwrap();
}
/// As explained in the example code related to signal_msi(), sending
/// a random MSI vector will always fail because no vector has been
/// previously allocated from the guest itself.
#[test]
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
fn test_signal_msi_failure() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let msi = kvm_msi::default();
vm.signal_msi(msi).unwrap_err();
}
#[test]
#[cfg(not(any(target_arch = "aarch64", target_arch = "riscv64")))]
fn test_enable_cap_failure() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let cap: kvm_enable_cap = Default::default();
// Providing the `kvm_enable_cap` structure filled with default() should
// always result in a failure as it is not a valid capability.
vm.enable_cap(&cap).unwrap_err();
}
#[test]
#[cfg(target_arch = "x86_64")]
fn test_enable_split_irqchip_cap() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let mut cap = kvm_enable_cap {
cap: KVM_CAP_SPLIT_IRQCHIP,
..Default::default()
};
// As per the KVM documentation, KVM_CAP_SPLIT_IRQCHIP only emulates
// the local APIC in kernel, expecting that a userspace IOAPIC will
// be implemented by the VMM.
// Along with this capability, the user needs to specify the number
// of pins reserved for the userspace IOAPIC. This number needs to be
// provided through the first argument of the capability structure, as
// specified in KVM documentation:
// args[0] - number of routes reserved for userspace IOAPICs
//
// Because an IOAPIC supports 24 pins, that's the reason why this test
// picked this number as reference.
cap.args[0] = 24;
vm.enable_cap(&cap).unwrap();
}
#[test]
#[cfg(any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "riscv64"
))]
fn test_set_gsi_routing() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let irq_routing = kvm_irq_routing::default();
// Expect failure for x86 since the irqchip is not created yet.
#[cfg(target_arch = "x86_64")]
vm.set_gsi_routing(&irq_routing).unwrap_err();
#[cfg(target_arch = "x86_64")]
vm.create_irq_chip().unwrap();
// RISC-V 64-bit expect an AIA device to be created in advance of
// committing irq_routing table.
#[cfg(target_arch = "riscv64")]
create_aia_device(&vm, 0);
vm.set_gsi_routing(&irq_routing).unwrap();
}
#[test]
fn test_create_vcpu_different_ids() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
// Fails when an arbitrarily large value
let err = vm.create_vcpu(65537_u64).err();
assert_eq!(err.unwrap().errno(), libc::EINVAL);
// Fails when input `id` = `max_vcpu_id`
let max_vcpu_id = kvm.get_max_vcpu_id();
vm.create_vcpu((max_vcpu_id - 1) as u64).unwrap();
let vcpu_err = vm.create_vcpu(max_vcpu_id as u64).err();
assert_eq!(vcpu_err.unwrap().errno(), libc::EINVAL);
}
#[test]
fn test_check_extension() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
assert!(vm.check_extension(Cap::MpState));
}
#[test]
#[cfg(target_arch = "x86_64")]
#[cfg_attr(not(has_sev), ignore)]
fn test_encrypt_op_sev() {
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
let mut init: kvm_sev_cmd = Default::default();
vm.encrypt_op_sev(&mut init).unwrap();
}
#[test]
#[cfg(target_arch = "x86_64")]
#[cfg_attr(not(has_sev), ignore)]
fn test_register_unregister_enc_memory_region() {
let sev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/sev")
.unwrap();
let Ok(kvm) = Kvm::new() else { return };
let vm = kvm.create_vm().unwrap();
// Perform SEV launch sequence according to
// https://www.kernel.org/doc/Documentation/virtual/kvm/amd-memory-encryption.rst
let mut init: kvm_sev_cmd = Default::default();
vm.encrypt_op_sev(&mut init).unwrap();
let start_data: kvm_sev_launch_start = Default::default();
let mut start = kvm_sev_cmd {
id: sev_cmd_id_KVM_SEV_LAUNCH_START,
data: &start_data as *const kvm_sev_launch_start as _,
sev_fd: sev.as_raw_fd() as _,
..Default::default()
};
vm.encrypt_op_sev(&mut start).unwrap();
let addr = unsafe {
libc::mmap(
null_mut(),
4096,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
-1,
0,
)
};
assert_ne!(addr, libc::MAP_FAILED);
assert_eq!(
vm.register_enc_memory_region(&Default::default())
.unwrap_err()
.errno(),
libc::EINVAL
);
assert_eq!(
vm.unregister_enc_memory_region(&Default::default())
.unwrap_err()
.errno(),
libc::EINVAL
);
let memory_region = kvm_enc_region {
addr: addr as _,
size: 4096,
};
assert_eq!(
vm.unregister_enc_memory_region(&memory_region)
.unwrap_err()
.errno(),
libc::EINVAL
);
vm.register_enc_memory_region(&memory_region).unwrap();
vm.unregister_enc_memory_region(&memory_region).unwrap();
}
}
|