1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
//! RDMA high-level abstraction, providing several useful APIs.
//!
//! Async-rdma is a framework for writing asynchronous rdma applications with the Rust
//! programing language. At a high level, it provides a few major components:
//!
//! * Tools for establishing connections with rdma endpoints such as `RdmaBuilder`.
//!
//! * High-level APIs for data transmission between endpoints including `read`,
//! `write`, `send`, `receive`.
//!
//! * High-level APIs for rdma memory region management including `alloc_local_mr`,
//! `request_remote_mr`, `send_mr`, `receive_local_mr`, `receive_remote_mr`.
//!
//! * A framework including `agent` and `event_listener` working behind APIs for memory
//! region management and executing rdma requests such as `post_send` and `poll`.
//!
//! #### Example
//! A simple example: client request a remote memory region and put data into this remote
//! memory region by rdma `write`.
//! And finally client `send_mr` to make server aware of this memory region.
//! Server `receive_local_mr`, and then get data from this mr.
//!
//! ```
//! use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
//! use portpicker::pick_unused_port;
//! use std::{
//! alloc::Layout,
//! io::{self, Write},
//! net::{Ipv4Addr, SocketAddrV4},
//! time::Duration,
//! };
//!
//! async fn client(addr: SocketAddrV4) -> io::Result<()> {
//! let layout = Layout::new::<[u8; 8]>();
//! let rdma = RdmaBuilder::default().connect(addr).await?;
//! // alloc 8 bytes remote memory
//! let mut rmr = rdma.request_remote_mr(layout).await?;
//! // alloc 8 bytes local memory
//! let mut lmr = rdma.alloc_local_mr(layout)?;
//! // write data into lmr
//! let _num = lmr.as_mut_slice().write(&[1_u8; 8])?;
//! // write the second half of the data in lmr to the rmr
//! rdma.write(&lmr.get(4..8).unwrap(), &mut rmr.get_mut(4..8).unwrap())
//! .await?;
//! // send rmr's meta data to the remote end
//! rdma.send_remote_mr(rmr).await?;
//! Ok(())
//! }
//!
//! #[tokio::main]
//! async fn server(addr: SocketAddrV4) -> io::Result<()> {
//! let rdma = RdmaBuilder::default().listen(addr).await?;
//! // receive mr's meta data from client
//! let lmr = rdma.receive_local_mr().await?;
//! let data = *lmr.as_slice();
//! println!("Data written by the client using RDMA WRITE: {:?}", data);
//! assert_eq!(data, [[0_u8; 4], [1_u8; 4]].concat());
//! Ok(())
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
//! std::thread::spawn(move || server(addr));
//! tokio::time::sleep(Duration::new(1, 0)).await;
//! client(addr)
//! .await
//! .map_err(|err| println!("{}", err))
//! .unwrap();
//! }
//! ```
//!
//!
#![deny(
// The following are allowed by default lints according to
// https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html
anonymous_parameters,
bare_trait_objects,
// box_pointers, // use box pointer to allocate on heap
// elided_lifetimes_in_paths, // allow anonymous lifetime
missing_copy_implementations,
missing_debug_implementations,
missing_docs, // TODO: add documents
single_use_lifetimes, // TODO: fix lifetime names only used once
trivial_casts, // TODO: remove trivial casts in code
trivial_numeric_casts,
// unreachable_pub, allow clippy::redundant_pub_crate lint instead
// unsafe_code,
unstable_features,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results,
variant_size_differences,
warnings, // treat all wanings as errors
clippy::all,
clippy::restriction,
clippy::pedantic,
// clippy::nursery, // It's still under development
clippy::cargo,
unreachable_pub,
)]
#![allow(
// Some explicitly allowed Clippy lints, must have clear reason to allow
clippy::blanket_clippy_restriction_lints, // allow clippy::restriction
clippy::implicit_return, // actually omitting the return keyword is idiomatic Rust code
clippy::module_name_repetitions, // repeation of module name in a struct name is not big deal
clippy::multiple_crate_versions, // multi-version dependency crates is not able to fix
clippy::missing_errors_doc, // TODO: add error docs
clippy::missing_panics_doc, // TODO: add panic docs
clippy::panic_in_result_fn,
clippy::shadow_same, // Not too much bad
clippy::shadow_reuse, // Not too much bad
clippy::exhaustive_enums,
clippy::exhaustive_structs,
clippy::indexing_slicing,
clippy::separated_literal_suffix, // conflicts with clippy::unseparated_literal_suffix
clippy::single_char_lifetime_names, // TODO: change lifetime names
)]
/// The agent that handles async events in the background
mod agent;
/// The completion queue that handles the completion event
mod completion_queue;
/// The rmda device context
mod context;
/// The rmda device
pub mod device;
/// Access of `QP` and `MR`
mod access;
/// The event channel that notifies the completion or error of a request
mod cq_event_channel;
/// The driver to poll the completion queue
mod cq_event_listener;
/// Error handling utilities
mod error_utilities;
/// Gid for device
mod gid;
/// `HashMap` extension
mod hashmap_extension;
/// Ibv async event listener
mod ibv_event_listener;
/// id utils
mod id;
/// Lock utilities
mod lock_utilities;
/// Macro utilities
mod macro_utilities;
/// Memory region abstraction
mod memory_region;
/// Memory window abstraction
mod memory_window;
/// Memory Region allocator
mod mr_allocator;
/// Protection Domain
mod protection_domain;
/// Queue Pair
mod queue_pair;
/// Remote memory region manager
mod rmr_manager;
/// Work Request wrapper
mod work_request;
use access::flags_into_ibv_access;
pub use access::AccessFlag;
use agent::{Agent, MAX_MSG_LEN};
use clippy_utilities::Cast;
use completion_queue::{DEFAULT_CQ_SIZE, DEFAULT_MAX_CQE};
use context::Context;
use cq_event_listener::{CQEventListener, PollingTriggerInput, DEFAULT_CC_EVENT_TIMEOUT};
pub use cq_event_listener::{ManualTrigger, PollingTriggerType};
use derive_builder::Builder;
use enumflags2::BitFlags;
pub use ibv_event_listener::IbvEventType;
pub use memory_region::{
local::{LocalMr, LocalMrReadAccess, LocalMrWriteAccess},
remote::{RemoteMr, RemoteMrReadAccess, RemoteMrWriteAccess},
MrAccess, MrToken, MrTokenBuilder, MrTokenBuilderError,
};
pub use mr_allocator::MRManageStrategy;
use mr_allocator::MrAllocator;
use protection_domain::ProtectionDomain;
use queue_pair::{
QueuePair, QueuePairInitAttrBuilder, RQAttr, RQAttrBuilder, SQAttr, SQAttrBuilder,
};
use rdma_sys::ibv_access_flags;
#[cfg(feature = "cm")]
use rdma_sys::{
rdma_addrinfo, rdma_cm_id, rdma_connect, rdma_create_ep, rdma_disconnect, rdma_freeaddrinfo,
rdma_getaddrinfo, rdma_port_space,
};
use rmr_manager::DEFAULT_RMR_TIMEOUT;
#[cfg(feature = "cm")]
use std::ptr::null_mut;
use std::{alloc::Layout, fmt::Debug, io, sync::Arc, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream, ToSocketAddrs},
sync::{mpsc, Mutex},
};
use tracing::debug;
use crate::queue_pair::builders_into_attrs;
use getset::{CopyGetters, Getters, MutGetters, Setters};
pub use gid::Gid;
pub use queue_pair::{QueuePairEndpoint, QueuePairEndpointBuilder, QueuePairState, MTU};
#[macro_use]
extern crate lazy_static;
/// initial device attributes
#[derive(Debug, Default)]
pub(crate) struct DeviceInitAttr {
/// Rdma device name
dev_name: Option<String>,
}
/// initial CQ attributes
#[derive(Debug, Clone, Copy)]
pub(crate) struct CQInitAttr {
/// Complete queue size
cq_size: u32,
/// Maximum number of completion queue entries (CQE) to poll at a time.
/// The higher the concurrency, the bigger this value should be and more memory allocated at a time.
max_cqe: i32,
}
impl Default for CQInitAttr {
#[inline]
fn default() -> Self {
Self {
cq_size: DEFAULT_CQ_SIZE,
max_cqe: DEFAULT_MAX_CQE,
}
}
}
/// initial QP attributes
#[derive(Debug, Clone, Copy)]
pub(crate) struct QPInitAttr {
/// Connection type
conn_type: ConnectionType,
/// If send/recv raw data
raw: bool,
/// Attributes for init QP
init_attr: QueuePairInitAttrBuilder,
/// Attributes for QP's send queue to receive messages
sq_attr: SQAttrBuilder,
/// Attributes for QP's receive queue to receive messages
rq_attr: RQAttrBuilder,
}
lazy_static! {
/// Default `ibv_access_flags`
static ref DEFAULT_ACCESS:ibv_access_flags = ibv_access_flags::IBV_ACCESS_LOCAL_WRITE
| ibv_access_flags::IBV_ACCESS_REMOTE_WRITE
| ibv_access_flags::IBV_ACCESS_REMOTE_READ
| ibv_access_flags::IBV_ACCESS_REMOTE_ATOMIC;
}
impl Default for QPInitAttr {
#[inline]
fn default() -> Self {
Self {
conn_type: ConnectionType::RCSocket,
raw: false,
init_attr: QueuePairInitAttrBuilder::default(),
sq_attr: SQAttrBuilder::default(),
rq_attr: RQAttrBuilder::default(),
}
}
}
/// Initial `MR` attributes
#[derive(Debug, Clone, Copy)]
pub(crate) struct MRInitAttr {
/// Access flag
access: ibv_access_flags,
/// Strategy to manage `MR`s
strategy: MRManageStrategy,
}
impl Default for MRInitAttr {
#[inline]
fn default() -> Self {
Self {
access: *DEFAULT_ACCESS,
strategy: MRManageStrategy::Jemalloc,
}
}
}
/// Initial Agent attributes
#[derive(Debug, Clone, Copy, Getters, Setters)]
#[getset(set, get)]
pub(crate) struct AgentInitAttr {
/// Max length of message send/recv by Agent
max_message_length: usize,
/// Max access permission for remote mr requests
max_rmr_access: ibv_access_flags,
/// The timeout value for event listener to wait for the CC's notification.
///
/// The listener will wait for the CC's notification to poll the related CQ until timeout.
/// After timeout, listener will poll the CQ to make sure no cqe there, and wait again.
///
/// For the devices or drivers not support notification mechanism, this value will be the polling
/// period, and as a protective measure in other cases.
cc_event_timeout: Duration,
/// The type of the `PollingTrigger`
pt_type: PollingTriggerType,
}
impl Default for AgentInitAttr {
#[inline]
fn default() -> Self {
Self {
max_message_length: MAX_MSG_LEN,
max_rmr_access: *DEFAULT_ACCESS,
cc_event_timeout: DEFAULT_CC_EVENT_TIMEOUT,
pt_type: PollingTriggerType::default(),
}
}
}
/// The builder for the `Rdma`, it follows the builder pattern.
#[derive(Default)]
pub struct RdmaBuilder {
/// Rdma device name
dev_attr: DeviceInitAttr,
/// initial CQ attributes
cq_attr: CQInitAttr,
/// initial QP attributes
qp_attr: QPInitAttr,
/// initial MR attributes
mr_attr: MRInitAttr,
/// initial Agent attributes
agent_attr: AgentInitAttr,
}
impl RdmaBuilder {
/// Create a default builder
/// The default settings are:
/// dev name: None
/// access right: `LocalWrite` | `RemoteRead` | `RemoteWrite` | `RemoteAtomic`
/// complete queue size: 16
/// port number: 1
/// gid index: 1
///
/// Note: We highly recommend setting the port number and the gid index.
#[must_use]
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Create a `Rdma` from this builder
#[inline]
pub fn build(&self) -> io::Result<Rdma> {
Rdma::new(
&self.dev_attr,
self.cq_attr,
self.qp_attr,
self.mr_attr,
self.agent_attr,
)
}
/// Establish connection with RDMA server
///
/// Used with `listen`
///
/// # Examples
///
/// ```
/// use async_rdma::RdmaBuilder;
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = RdmaBuilder::default().connect(addr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = RdmaBuilder::default().listen(addr).await?;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn connect<A: ToSocketAddrs>(self, addr: A) -> io::Result<Rdma> {
match self.qp_attr.conn_type {
ConnectionType::RCSocket => {
let mut rdma = self.build()?;
let remote = tcp_connect_helper(addr, &rdma.endpoint()).await?;
let (recv_attr, send_attr) =
builders_into_attrs(self.qp_attr.rq_attr, self.qp_attr.sq_attr, &remote)?;
rdma.qp_handshake(recv_attr, send_attr)?;
rdma.init_agent(
self.agent_attr.max_message_length,
self.agent_attr.max_rmr_access,
)
.await?;
Ok(rdma)
}
ConnectionType::RCCM | ConnectionType::RCIBV => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXSocket",
)),
}
}
/// Connect to remote end by raw ibv information.
///
/// You can get the destination qp information in any way and use this interface to establish connection.
///
/// The example is the same as `Rdma::ibv_connect`.
#[inline]
pub async fn ibv_connect(self, remote: QueuePairEndpoint) -> io::Result<Rdma> {
match self.qp_attr.conn_type {
ConnectionType::RCIBV => {
let mut rdma = self.build()?;
let (recv_attr, send_attr) =
builders_into_attrs(self.qp_attr.rq_attr, self.qp_attr.sq_attr, &remote)?;
rdma.qp_handshake(recv_attr, send_attr)?;
rdma.init_agent(
self.agent_attr.max_message_length,
self.agent_attr.max_rmr_access,
)
.await?;
Ok(rdma)
}
ConnectionType::RCCM | ConnectionType::RCSocket => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXIBV",
)),
}
}
/// Establish connection with RDMA CM server
///
/// Application scenario can be seen in `[/example/cm_client.rs]`
///
/// # Examples
///
/// ```
/// use async_rdma::{ConnectionType, RdmaBuilder};
/// use local_ip_address::local_ip;
/// use portpicker::pick_unused_port;
/// use rdma_sys::*;
/// use std::{io, ptr::null_mut, time::Duration};
///
/// static SERVER_NODE: &str = "0.0.0.0\0";
///
/// async fn client(node: &str, service: &str) -> io::Result<()> {
/// let _rdma = RdmaBuilder::default()
/// .set_conn_type(ConnectionType::RCCM)
/// .set_raw(true)
/// .cm_connect(node, service)
/// .await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(node: &str, service: &str) -> io::Result<()> {
/// let mut hints = unsafe { std::mem::zeroed::<rdma_addrinfo>() };
/// let mut res: *mut rdma_addrinfo = null_mut();
/// hints.ai_flags = RAI_PASSIVE.try_into().unwrap();
/// hints.ai_port_space = rdma_port_space::RDMA_PS_TCP.try_into().unwrap();
/// let mut ret = unsafe {
/// rdma_getaddrinfo(
/// node.as_ptr().cast(),
/// service.as_ptr().cast(),
/// &hints,
/// &mut res,
/// )
/// };
/// if ret != 0 {
/// println!("rdma_getaddrinfo");
/// return Err(io::Error::last_os_error());
/// }
///
/// let mut listen_id = null_mut();
/// let mut id = null_mut();
/// let mut init_attr = unsafe { std::mem::zeroed::<ibv_qp_init_attr>() };
/// init_attr.cap.max_send_wr = 1;
/// init_attr.cap.max_recv_wr = 1;
/// ret = unsafe { rdma_create_ep(&mut listen_id, res, null_mut(), &mut init_attr) };
/// if ret != 0 {
/// println!("rdma_create_ep");
/// return Err(io::Error::last_os_error());
/// }
///
/// ret = unsafe { rdma_listen(listen_id, 0) };
/// if ret != 0 {
/// println!("rdma_listen");
/// return Err(io::Error::last_os_error());
/// }
///
/// ret = unsafe { rdma_get_request(listen_id, &mut id) };
/// if ret != 0 {
/// println!("rdma_get_request");
/// return Err(io::Error::last_os_error());
/// }
///
/// ret = unsafe { rdma_accept(id, null_mut()) };
/// if ret != 0 {
/// println!("rdma_get_request");
/// return Err(io::Error::last_os_error());
/// }
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let port = pick_unused_port().unwrap();
/// let server_service = port.to_string() + "\0";
/// let client_service = server_service.clone();
/// std::thread::spawn(move || server(SERVER_NODE, &server_service));
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// let node = local_ip().unwrap().to_string() + "\0";
/// client(&node, &client_service)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[cfg(feature = "cm")]
pub async fn cm_connect(self, node: &str, service: &str) -> io::Result<Rdma> {
match self.qp_attr.conn_type {
ConnectionType::RCSocket | ConnectionType::RCIBV => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXCM",
)),
ConnectionType::RCCM => {
let max_message_length = self.agent_attr.max_message_length;
let max_rmr_access = self.agent_attr.max_rmr_access;
let mut rdma = self.build()?;
cm_connect_helper(&mut rdma, node, service)?;
rdma.init_agent(max_message_length, max_rmr_access).await?;
Ok(rdma)
}
}
}
/// Listen to the address to wait for a connection to be established
///
/// Used with `connect`
///
/// # Examples
///
/// ```
/// use async_rdma::RdmaBuilder;
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = RdmaBuilder::default().connect(addr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = RdmaBuilder::default().listen(addr).await?;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn listen<A: ToSocketAddrs>(self, addr: A) -> io::Result<Rdma> {
match self.qp_attr.conn_type {
ConnectionType::RCSocket => {
let recv_attr_builder = self.qp_attr.rq_attr;
let send_attr_builder = self.qp_attr.sq_attr;
let mut rdma = self.build()?;
let tcp_listener = TcpListener::bind(addr).await?;
let remote = tcp_listen(&tcp_listener, &rdma.endpoint()).await?;
let (recv_attr, send_attr) =
builders_into_attrs(recv_attr_builder, send_attr_builder, &remote)?;
rdma.qp_handshake(recv_attr, send_attr)?;
debug!("handshake done");
rdma.init_agent(
self.agent_attr.max_message_length,
self.agent_attr.max_rmr_access,
)
.await?;
let _ = rdma
.clone_attr
.set_tcp_listener(Some(Arc::new(Mutex::new(tcp_listener))));
Ok(rdma)
}
ConnectionType::RCCM | ConnectionType::RCIBV => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXSocket",
)),
}
}
/// Set device name
#[inline]
#[must_use]
pub fn set_dev(mut self, dev: &str) -> Self {
self.dev_attr.dev_name = Some(dev.to_owned());
self
}
/// Set the complete queue size
#[inline]
#[must_use]
pub fn set_cq_size(mut self, cq_size: u32) -> Self {
self.cq_attr.cq_size = cq_size;
self
}
/// Set the max number of CQE in a polling.
#[inline]
#[must_use]
pub fn set_max_cqe(mut self, max_ceq: i32) -> Self {
self.cq_attr.max_cqe = max_ceq;
self
}
/// Set the gid index
#[inline]
#[must_use]
pub fn set_gid_index(mut self, gid_index: usize) -> Self {
// TODO: check gid_index scope(ibv_port_attr.gid_tbl_len)
let _ = self
.qp_attr
.rq_attr
.address_handler()
.grh()
.sgid_index(gid_index.cast());
self
}
/// Set the port number
#[inline]
#[must_use]
pub fn set_port_num(mut self, port_num: u8) -> Self {
let _ = self.qp_attr.rq_attr.address_handler().port_num(port_num);
self
}
/// Set the connection type
#[inline]
#[must_use]
pub fn set_conn_type(mut self, conn_type: ConnectionType) -> Self {
self.qp_attr.conn_type = conn_type;
self
}
/// Set if send/recv raw data
#[inline]
#[must_use]
pub fn set_raw(mut self, raw: bool) -> Self {
self.qp_attr.raw = raw;
self
}
/// Set maximum number of outstanding send requests in the send queue
#[inline]
#[must_use]
pub fn set_qp_max_send_wr(mut self, max_send_wr: u32) -> Self {
let _ = self.qp_attr.init_attr.qp_cap().max_send_wr(max_send_wr);
self
}
/// Set maximum number of outstanding receive requests in the receive queue
#[inline]
#[must_use]
pub fn set_qp_max_recv_wr(mut self, max_recv_wr: u32) -> Self {
let _ = self.qp_attr.init_attr.qp_cap().max_recv_wr(max_recv_wr);
self
}
/// Set maximum number of scatter/gather elements (SGE) in a WR on the send queue
#[inline]
#[must_use]
pub fn set_qp_max_send_sge(mut self, max_send_sge: u32) -> Self {
let _ = self.qp_attr.init_attr.qp_cap().max_send_sge(max_send_sge);
self
}
/// Set maximum number of scatter/gather elements (SGE) in a WR on the receive queue
#[inline]
#[must_use]
pub fn set_qp_max_recv_sge(mut self, max_recv_sge: u32) -> Self {
let _ = self.qp_attr.init_attr.qp_cap().max_recv_sge(max_recv_sge);
self
}
/// Set default `QP` access
#[inline]
#[must_use]
pub fn set_qp_access(mut self, flags: BitFlags<AccessFlag>) -> Self {
let _ = self.qp_attr.init_attr.access(flags_into_ibv_access(flags));
self
}
/// Set default `MR` access
#[inline]
#[must_use]
pub fn set_mr_access(mut self, flags: BitFlags<AccessFlag>) -> Self {
self.mr_attr.access = flags_into_ibv_access(flags);
self
}
/// Set the stragety to manage `MR`s
#[inline]
#[must_use]
pub fn set_mr_strategy(mut self, strategy: MRManageStrategy) -> Self {
self.mr_attr.strategy = strategy;
self
}
/// Set max length of message send/recv by Agent
#[inline]
#[must_use]
pub fn set_max_message_length(mut self, max_msg_len: usize) -> Self {
self.agent_attr.max_message_length = max_msg_len;
self
}
/// Set max access permission for remote mr requests
#[inline]
#[must_use]
pub fn set_max_rmr_access(mut self, flags: BitFlags<AccessFlag>) -> Self {
self.agent_attr.max_rmr_access = flags_into_ibv_access(flags);
self
}
// TODO: check values of rq/sq_attr
/// Set the number of RDMA Reads & atomic operations outstanding at any time that can be
/// handled by this QP as a destination. Relevant only for RC QPs.
#[inline]
#[must_use]
pub fn set_max_dest_rd_atomic(mut self, max_dest_rd_atomic: u8) -> Self {
let _ = self.qp_attr.rq_attr.max_dest_rd_atomic(max_dest_rd_atomic);
self
}
/// Set the minimum RNR NAK Timer Field Value. When an incoming message to this QP should consume a Work
/// Request from the Receive Queue, but not Work Request is outstanding on that Queue, the QP will
/// send an RNR NAK packet to the initiator. It does not affect RNR NAKs sent for other reasons.
///
/// The value can be one of the following numeric values since those values aren’t enumerated:
///
/// 0 - 655.36 milliseconds delay
///
/// 1 - 0.01 milliseconds delay
///
/// 2 - 0.02 milliseconds delay
///
/// 3 - 0.03 milliseconds delay
///
/// 4 - 0.04 milliseconds delay
///
/// 5 - 0.06 milliseconds delay
///
/// 6 - 0.08 milliseconds delay
///
/// 7 - 0.12 milliseconds delay
///
/// 8 - 0.16 milliseconds delay
///
/// 9 - 0.24 milliseconds delay
///
/// 10 - 0.32 milliseconds delay
///
/// 11 - 0.48 milliseconds delay
///
/// 12 - 0.64 milliseconds delay
///
/// 13 - 0.96 milliseconds delay
///
/// 14 - 1.28 milliseconds delay
///
/// 15 - 1.92 milliseconds delay
///
/// 16 - 2.56 milliseconds delay
///
/// 17 - 3.84 milliseconds delay
///
/// 18 - 5.12 milliseconds delay
///
/// 19 - 7.68 milliseconds delay
///
/// 20 - 10.24 milliseconds delay
///
/// 21 - 15.36 milliseconds delay
///
/// 22 - 20.48 milliseconds delay
///
/// 23 - 30.72 milliseconds delay
///
/// 24 - 40.96 milliseconds delay
///
/// 25 - 61.44 milliseconds delay
///
/// 26 - 81.92 milliseconds delay
///
/// 27 - 122.88 milliseconds delay
///
/// 28 - 163.84 milliseconds delay
///
/// 29 - 245.76 milliseconds delay
///
/// 30 - 327.68 milliseconds delay
///
/// 31 - 491.52 milliseconds delay
///
/// Relevant only for RC QPs
#[inline]
#[must_use]
pub fn set_min_rnr_timer(mut self, min_rnr_timer: u8) -> Self {
let _ = self.qp_attr.rq_attr.min_rnr_timer(min_rnr_timer);
self
}
/// Set a 24 bits value of the Packet Sequence Number of the received packets for RC and UC QPs
#[inline]
#[must_use]
pub fn set_rq_psn(mut self, rq_psn: u32) -> Self {
let _ = self.qp_attr.rq_attr.rq_psn(rq_psn);
self
}
/// Set the number of RDMA Reads & atomic operations outstanding at any time that can be handled by
/// this QP as an initiator. Relevant only for RC QPs.
#[inline]
#[must_use]
pub fn set_max_rd_atomic(mut self, max_rd_atomic: u8) -> Self {
let _ = self.qp_attr.sq_attr.max_rd_atomic(max_rd_atomic);
self
}
/// Set a 3 bits value of the total number of times that the QP will try to resend the packets before
/// reporting an error because the remote side doesn't answer in the primary path
#[inline]
#[must_use]
pub fn set_retry_cnt(mut self, retry_cnt: u8) -> Self {
let _ = self.qp_attr.sq_attr.retry_cnt(retry_cnt);
self
}
/// Set a 3 bits value of the total number of times that the QP will try to resend the packets when an
/// RNR NACK was sent by the remote QP before reporting an error. The value 7 is special and specify
/// to retry infinite times in case of RNR.
#[inline]
#[must_use]
pub fn set_rnr_retry(mut self, rnr_retry: u8) -> Self {
let _ = self.qp_attr.sq_attr.rnr_retry(rnr_retry);
self
}
/// Set a 24 bits value of the Packet Sequence Number of the sent packets for any QP.
#[inline]
#[must_use]
pub fn set_sq_psn(mut self, sq_psn: u32) -> Self {
let _ = self.qp_attr.sq_attr.sq_psn(sq_psn);
self
}
/// Set the minimum timeout that a QP waits for ACK/NACK from remote QP before retransmitting the packet.
/// The value zero is special value which means wait an infinite time for the ACK/NACK (useful for
/// debugging). For any other value of timeout, the time calculation is: `4.09*2^timeout`.
/// Relevant only to RC QPs.
#[inline]
#[must_use]
pub fn set_timeout(mut self, timeout: u8) -> Self {
let _ = self.qp_attr.sq_attr.timeout(timeout);
self
}
/// Set the Service Level to be used. 4 bits.
#[inline]
#[must_use]
pub fn set_service_level(mut self, sl: u8) -> Self {
let _ = self.qp_attr.rq_attr.address_handler().service_level(sl);
self
}
/// Set the used Source Path Bits. This is useful when LMC is used in the port, i.e. each port
/// covers a range of LIDs. The packets are being sent with the port's base LID, bitwised `ORed`
/// with the value of the source path bits. The value 0 indicates the port's base LID is used.
#[inline]
#[must_use]
pub fn set_src_path_bits(mut self, src_path_bits: u8) -> Self {
let _ = self
.qp_attr
.rq_attr
.address_handler()
.src_path_bits(src_path_bits);
self
}
/// Set the value which limits the rate of packets that being sent to the subnet. This can be
/// useful if the rate of the packet origin is higher than the rate of the destination.
#[inline]
#[must_use]
pub fn set_static_rate(mut self, static_rate: u8) -> Self {
let _ = self
.qp_attr
.rq_attr
.address_handler()
.static_rate(static_rate);
self
}
/// If this value is set to a non-zero value, it gives a hint for switches and routers
/// with multiple outbound paths that these sequence of packets must be delivered in order,
/// those staying on the same path, so that they won't be reordered. 20 bits.
#[inline]
#[must_use]
pub fn set_flow_label(mut self, flow_label: u32) -> Self {
let _ = self
.qp_attr
.rq_attr
.address_handler()
.grh()
.flow_label(flow_label);
self
}
/// Set the number of hops (i.e. the number of routers) that the packet is permitted to take before
/// being discarded. This ensures that a packet will not loop indefinitely between routers if a
/// routing loop occur. Each router decrement by one this value at the packet and when this value
/// reaches 0, this packet is discarded. Setting the value to 0 or 1 will ensure that the packet
/// won't leave the local subnet.
#[inline]
#[must_use]
pub fn set_hop_limit(mut self, hop_limit: u8) -> Self {
let _ = self
.qp_attr
.rq_attr
.address_handler()
.grh()
.hop_limit(hop_limit);
self
}
/// Using this value, the originator of the packets specifies the required delivery priority for
/// handling them by the routers.
#[inline]
#[must_use]
pub fn set_traffic_class(mut self, traffic_class: u8) -> Self {
let _ = self
.qp_attr
.rq_attr
.address_handler()
.grh()
.traffic_class(traffic_class);
self
}
/// Set Primary key index. The value of the entry in the pkey table that outgoing
/// packets from this QP will be sent with and incoming packets to this QP will be
/// verified within the Primary path.
#[inline]
#[must_use]
pub fn set_pkey_index(mut self, pkey_index: u16) -> Self {
let _ = self.qp_attr.init_attr.pkey_index(pkey_index);
self
}
/// Set the path MTU (Maximum Transfer Unit) i.e. the maximum payload size of a packet that
/// can be transferred in the path. For UC and RC QPs, when needed, the RDMA device will
/// automatically fragment the messages to packet of this size.
#[inline]
#[must_use]
pub fn set_mtu(mut self, mtu: MTU) -> Self {
let _ = self.qp_attr.rq_attr.mtu(mtu);
self
}
/// Set the immediate data flag in `ibv_wc` of rdma device.
///
/// This value is `3` as default for `Soft-RoCE`, and may be `2` for other devices.
#[inline]
pub fn set_imm_flag_in_wc(self, imm_flag: u32) -> io::Result<Self> {
use completion_queue::{IBV_WC_WITH_IMM, INIT_IMM_FLAG};
let mut guard = INIT_IMM_FLAG.lock();
if *guard {
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"IBV_WC_WITH_IMM is initialized or being initialized but has not yet completed",
))
} else {
// SAFETY: only init once before using it
unsafe {
IBV_WC_WITH_IMM = imm_flag;
}
*guard = true;
Ok(self)
}
}
/// Set the timeout value for event listener to wait for the notification of completion channel.
///
/// When a completion queue entry (CQE) is placed on the CQ, a completion event will be sent to
/// the completion channel (CC) associated with the CQ.
///
/// The listener will wait for the CC's notification to poll the related CQ until timeout.
/// After timeout, listener will poll the CQ to make sure no cqe there, and wait again.
///
/// For the devices or drivers not support notification mechanism, this value will be the polling
/// period, and as a protective measure in other cases.
#[inline]
#[must_use]
pub fn set_cc_evnet_timeout(mut self, timeout: Duration) -> Self {
self.agent_attr.cc_event_timeout = timeout;
self
}
/// Set the polling trigger type of cq. Used with `Rdma.poll()` and `Rmda.get_manual_trigger()`.
///
/// When a completion queue entry (CQE) is placed on the CQ, a completion event will be sent to
/// the completion channel (CC) associated with the CQ.
///
/// As default(`PollingTriggerType::AsyncFd`), the listener will wait for the CC's notification to
/// poll the related CQ. If you want to ignore the notification and poll by yourself, you can input
/// `pt_type` as `PollingTriggerType::Channel` and call `Rdma.poll()` to poll the CQ.
#[inline]
#[must_use]
pub fn set_polling_trigger(mut self, pt_type: PollingTriggerType) -> Self {
self.agent_attr.pt_type = pt_type;
self
}
}
impl Debug for RdmaBuilder {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RdmaBuilder")
.field("dev_name", &self.dev_attr.dev_name)
.field("cq_size", &self.cq_attr.cq_size)
.finish()
}
}
/// Exchange metadata through tcp
async fn tcp_connect_helper<A: ToSocketAddrs>(
addr: A,
ep: &QueuePairEndpoint,
) -> io::Result<QueuePairEndpoint> {
let mut stream = TcpStream::connect(addr).await?;
let mut endpoint = bincode::serialize(ep).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("failed to serailize the endpoint, {:?}", e),
)
})?;
stream.write_all(&endpoint).await?;
// the byte number is not important, as read_exact will fill the buffer
let _ = stream.read_exact(endpoint.as_mut()).await?;
bincode::deserialize(&endpoint).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("failed to deserailize the endpoint, {:?}", e),
)
})
}
/// Listen for exchanging metadata through tcp
async fn tcp_listen(
tcp_listener: &TcpListener,
ep: &QueuePairEndpoint,
) -> io::Result<QueuePairEndpoint> {
let (mut stream, _) = tcp_listener.accept().await?;
let endpoint_size = bincode::serialized_size(ep).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("Endpoint serialization failed, {:?}", e),
)
})?;
let mut remote = vec![0_u8; endpoint_size.cast()];
// the byte number is not important, as read_exact will fill the buffer
let _ = stream.read_exact(remote.as_mut()).await?;
let remote: QueuePairEndpoint = bincode::deserialize(&remote).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("failed to deserialize remote endpoint, {:?}", e),
)
})?;
let local = bincode::serialize(ep).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("failed to deserialize remote endpoint, {:?}", e),
)
})?;
stream.write_all(&local).await?;
Ok(remote)
}
/// Exchange metadata and setup connection through cm
#[inline]
#[cfg(feature = "cm")]
fn cm_connect_helper(rdma: &mut Rdma, node: &str, service: &str) -> io::Result<()> {
// SAFETY: POD FFI type
use error_utilities::log_ret_last_os_err;
let mut hints = unsafe { std::mem::zeroed::<rdma_addrinfo>() };
let mut info: *mut rdma_addrinfo = null_mut();
hints.ai_port_space = rdma_port_space::RDMA_PS_TCP.cast();
// Safety: ffi
let mut ret = unsafe {
rdma_getaddrinfo(
node.as_ptr().cast(),
service.as_ptr().cast(),
&hints,
&mut info,
)
};
if ret != 0_i32 {
return Err(log_ret_last_os_err());
}
let mut id: *mut rdma_cm_id = null_mut();
// Safety: ffi
ret = unsafe { rdma_create_ep(&mut id, info, rdma.pd.as_ptr(), null_mut()) };
if ret != 0_i32 {
// Safety: ffi
unsafe {
rdma_freeaddrinfo(info);
}
return Err(log_ret_last_os_err());
}
// Safety: id was initialized by `rdma_create_ep`
unsafe {
debug!(
"cm_id: {:?},{:?},{:?},{:?},{:?},{:?},{:?}",
(*id).qp,
(*id).pd,
(*id).verbs,
(*id).recv_cq_channel,
(*id).send_cq_channel,
(*id).recv_cq,
(*id).send_cq
);
(*id).qp = rdma.qp.as_ptr();
(*id).pd = rdma.pd.as_ptr();
(*id).verbs = rdma.ctx.as_ptr();
(*id).recv_cq_channel = rdma.qp.cq_event_listener().cq.event_channel().as_ptr();
(*id).recv_cq_channel = rdma.qp.cq_event_listener().cq.event_channel().as_ptr();
(*id).recv_cq = rdma.qp.cq_event_listener().cq.as_ptr();
(*id).send_cq = rdma.qp.cq_event_listener().cq.as_ptr();
debug!(
"cm_id: {:?},{:?},{:?},{:?},{:?},{:?},{:?}",
(*id).qp,
(*id).pd,
(*id).verbs,
(*id).recv_cq_channel,
(*id).send_cq_channel,
(*id).recv_cq,
(*id).send_cq
);
}
// Safety: ffi
ret = unsafe { rdma_connect(id, null_mut()) };
if ret != 0_i32 {
// Safety: ffi
unsafe {
let _ = rdma_disconnect(id);
}
return Err(log_ret_last_os_err());
}
Ok(())
}
/// Method of establishing a connection
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionType {
/// Establish reliable connection through `Socket` APIs.
RCSocket,
/// Establish reliable connection through `CM` APIs.
RCCM,
/// Establish reliable connection through `IBV` APIs.
RCIBV,
}
/// Attributes for creating new `Rdma`s through `clone`
#[derive(Debug, Clone, Builder, Getters, MutGetters, Setters, CopyGetters)]
#[getset(set, get, get_mut)]
pub(crate) struct CloneAttr {
/// Tcp listener used for new connections
#[builder(default = "None")]
tcp_listener: Option<Arc<Mutex<TcpListener>>>,
/// Clone `Rdma` with new `ProtectionDomain`
pd: Arc<ProtectionDomain>,
/// Clone `Rdma` with new agent attributes
#[builder(default = "AgentInitAttr::default()")]
agent_attr: AgentInitAttr,
/// Attributes for init QP
qp_init_attr: QueuePairInitAttrBuilder,
/// Attributes for QP's send queue to receive messages
sq_attr: SQAttrBuilder,
/// Attributes for QP's receive queue to receive messages
rq_attr: RQAttrBuilder,
}
impl_into_io_error!(CloneAttrBuilderError);
/// Rdma handler, the only interface that the users deal with rdma
#[derive(Debug)]
pub struct Rdma {
/// device context
ctx: Arc<Context>,
/// protection domain
pd: Arc<ProtectionDomain>,
/// Memory region allocator
allocator: Arc<MrAllocator>,
/// Queue pair
qp: Arc<QueuePair>,
/// Background agent
agent: Option<Arc<Agent>>,
/// Connection type
conn_type: ConnectionType,
/// If send/recv raw data
raw: bool,
/// Attributes for creating new `Rdma`s through `clone`
clone_attr: CloneAttr,
/// The tx end of polling trigger
trigger_tx: Option<mpsc::Sender<()>>,
}
impl Rdma {
/// create a new `Rdma` instance
fn new(
dev_attr: &DeviceInitAttr,
cq_attr: CQInitAttr,
mut qp_attr: QPInitAttr,
mr_attr: MRInitAttr,
agent_attr: AgentInitAttr,
) -> io::Result<Self> {
let ctx = Arc::new(Context::open(
dev_attr.dev_name.as_deref(),
qp_attr.rq_attr.get_port_num(),
qp_attr.rq_attr.get_sgid_index().cast(),
)?);
let ec = ctx.create_event_channel()?;
let cq = Arc::new(ctx.create_completion_queue(cq_attr.cq_size, ec, cq_attr.max_cqe)?);
let (pt_input, trigger_tx) = match agent_attr.pt_type {
PollingTriggerType::Automatic => (PollingTriggerInput::AsyncFd(Arc::clone(&cq)), None),
PollingTriggerType::Manual => {
let (tx, rx) = mpsc::channel(2);
(PollingTriggerInput::Channel(rx), Some(tx))
}
};
let cq_event_listener = Arc::new(CQEventListener::new(
Arc::clone(&cq),
agent_attr.cc_event_timeout,
pt_input,
));
let pd = Arc::new(ctx.create_protection_domain()?);
let allocator = Arc::new(MrAllocator::new(
Arc::<ProtectionDomain>::clone(&pd),
mr_attr,
));
let _ = qp_attr.init_attr.send_cq(cq.as_ptr()).recv_cq(cq.as_ptr());
let clone_attr = CloneAttrBuilder::default()
.pd(Arc::clone(&pd))
.qp_init_attr(qp_attr.init_attr)
.sq_attr(qp_attr.sq_attr)
.rq_attr(qp_attr.rq_attr)
.agent_attr(agent_attr)
.build()?;
let qp = Arc::new(pd.create_qp(
cq_event_listener,
qp_attr.init_attr,
qp_attr.rq_attr.get_port_num(),
true,
)?);
Ok(Self {
ctx,
pd,
qp,
agent: None,
allocator,
conn_type: qp_attr.conn_type,
raw: qp_attr.raw,
clone_attr,
trigger_tx,
})
}
/// Connect to remote end by raw ibv information.
///
/// You can get the destination qp information in any way and use this interface to establish connection.
///
/// # Examples
///
/// ```
/// use async_rdma::{
/// ConnectionType, LocalMrReadAccess, LocalMrWriteAccess, QueuePairEndpoint, Rdma, RdmaBuilder,
/// };
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// time::Duration,
/// };
///
/// async fn client(mut client_rdma: Rdma, server_info: QueuePairEndpoint) -> io::Result<()> {
/// client_rdma.ibv_connect(server_info).await?;
/// // alloc 8 bytes local memory
/// let mut lmr = client_rdma.alloc_local_mr(Layout::new::<[u8; 8]>())?;
/// // write data into lmr
/// let _num = lmr.as_mut_slice().write(&[1_u8; 8])?;
/// // send data in mr to the remote end
/// client_rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(mut server_rdma: Rdma, client_info: QueuePairEndpoint) -> io::Result<()> {
/// server_rdma.ibv_connect(client_info).await?;
/// // receive data
/// let lmr = server_rdma.receive().await?;
/// let data = *lmr.as_slice();
/// assert_eq!(data, [1_u8; 8]);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let server_rdma = RdmaBuilder::default()
/// .set_conn_type(ConnectionType::RCIBV)
/// .build()
/// .unwrap();
/// let server_info = server_rdma.get_qp_endpoint();
/// let client_rdma = RdmaBuilder::default()
/// .set_conn_type(ConnectionType::RCIBV)
/// .build()
/// .unwrap();
/// let client_info = client_rdma.get_qp_endpoint();
/// std::thread::spawn(move || server(server_rdma, client_info));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(client_rdma, server_info)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn ibv_connect(&mut self, remote: QueuePairEndpoint) -> io::Result<()> {
match self.conn_type {
ConnectionType::RCIBV => {
let (recv_attr, send_attr) =
builders_into_attrs(self.clone_attr.rq_attr, self.clone_attr.sq_attr, &remote)?;
self.qp_handshake(recv_attr, send_attr)?;
self.init_agent(
self.clone_attr.agent_attr.max_message_length,
self.clone_attr.agent_attr.max_rmr_access,
)
.await?;
Ok(())
}
ConnectionType::RCCM | ConnectionType::RCSocket => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXIBV",
)),
}
}
/// Create a new `Rdma` that has the same `mr_allocator` and `cq_event_listener` as parent.
fn clone(&self) -> io::Result<Self> {
let qp = Arc::new(self.clone_attr.pd.create_qp(
Arc::clone(self.qp.cq_event_listener()),
self.clone_attr.qp_init_attr,
self.clone_attr.rq_attr.get_port_num(),
true,
)?);
Ok(Self {
ctx: Arc::clone(&self.ctx),
pd: Arc::clone(self.clone_attr.pd()),
qp,
agent: None,
allocator: Arc::clone(&self.allocator),
conn_type: self.conn_type,
raw: self.raw,
clone_attr: self.clone_attr.clone(),
trigger_tx: self.trigger_tx.clone(),
})
}
/// get the queue pair endpoint information
fn endpoint(&self) -> QueuePairEndpoint {
self.qp.endpoint()
}
/// to hand shake the qp so that it works
fn qp_handshake(&mut self, recv_attr: RQAttr, send_attr: SQAttr) -> io::Result<()> {
self.qp.modify_to_rtr(recv_attr)?;
self.qp.modify_to_rts(send_attr)?;
debug!("rts");
Ok(())
}
/// Agent init helper
async fn init_agent(
&mut self,
max_message_length: usize,
max_rmr_access: ibv_access_flags,
) -> io::Result<()> {
if !self.raw {
let agent = Arc::new(Agent::new(
Arc::<QueuePair>::clone(&self.qp),
Arc::<MrAllocator>::clone(&self.allocator),
max_message_length,
max_rmr_access,
Arc::clone(&self.ctx),
)?);
self.agent = Some(agent);
// wait for the remote agent to prepare
tokio::time::sleep(Duration::from_secs(1)).await;
}
Ok(())
}
/// Listen for new connections using the same `mr_allocator` and `event_listener` as parent `Rdma`
///
/// Used with `connect` and `new_connect`
///
/// # Examples
///
/// ```
/// use async_rdma::RdmaBuilder;
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().connect(addr).await?;
/// for _ in 0..3 {
/// let _new_rdma = rdma.new_connect(addr).await?;
/// }
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().listen(addr).await?;
/// for _ in 0..3 {
/// let _new_rdma = rdma.listen().await?;
/// }
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn listen(&mut self) -> io::Result<Self> {
match self.conn_type {
ConnectionType::RCSocket => {
let mut rdma = self.clone()?;
let remote = self
.clone_attr
.tcp_listener
.as_ref()
.map_or_else(
|| Err(io::Error::new(io::ErrorKind::Other, "tcp_listener is None")),
|tcp_listener| {
Ok(async {
let tcp_listener = tcp_listener.lock().await;
tcp_listen(&tcp_listener, &rdma.endpoint()).await
})
},
)?
.await?;
self.clone_attr.rq_attr_mut().reset_remote_info(&remote);
let (recv_attr, send_attr) = self.get_rq_sq_attr()?;
rdma.qp_handshake(recv_attr, send_attr)?;
debug!("handshake done");
rdma.init_agent(
self.clone_attr.agent_attr.max_message_length,
self.clone_attr.agent_attr.max_rmr_access,
)
.await?;
Ok(rdma)
}
ConnectionType::RCCM | ConnectionType::RCIBV => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXSocket",
)),
}
}
/// Establish new connections with RDMA server using the same `mr_allocator` and `event_listener` as parent `Rdma`
///
/// Used with `listen`
///
/// # Examples
///
/// ```
/// use async_rdma::RdmaBuilder;
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().connect(addr).await?;
/// for _ in 0..3 {
/// let _new_rdma = rdma.new_connect(addr).await?;
/// }
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().listen(addr).await?;
/// for _ in 0..3 {
/// let _new_rdma = rdma.listen().await?;
/// }
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn new_connect<A: ToSocketAddrs>(&mut self, addr: A) -> io::Result<Self> {
match self.conn_type {
ConnectionType::RCSocket => {
let mut rdma = self.clone()?;
let remote = tcp_connect_helper(addr, &rdma.endpoint()).await?;
self.clone_attr.rq_attr_mut().reset_remote_info(&remote);
let (recv_attr, send_attr) = self.get_rq_sq_attr()?;
rdma.qp_handshake(recv_attr, send_attr)?;
rdma.init_agent(
self.clone_attr.agent_attr.max_message_length,
self.clone_attr.agent_attr.max_rmr_access,
)
.await?;
Ok(rdma)
}
ConnectionType::RCCM | ConnectionType::RCIBV => Err(io::Error::new(
io::ErrorKind::Other,
"ConnectionType should be XXSocket",
)),
}
}
/// Send the content in the `lm`
///
/// Used with `receive`.
/// Application scenario such as: client put data into a local mr and `send` to server.
/// Server `receive` the mr sent by client and process data in it.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // send the content of lmr to server
/// rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma.receive().await?;
/// // read data from mr
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn send(&self, lm: &LocalMr) -> io::Result<()> {
self.agent
.as_ref()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Agent is not ready"))?
.send_data(lm, None)
.await
}
/// A 64 bits value in a remote mr being read, compared with `old_value` and if they are equal,
/// the `new_value` is being written to the remote mr in an atomic way.
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().connect(addr).await?;
/// // alloc 8 bytes remote memory
/// let mut rmr = rdma.request_remote_mr(Layout::new::<[u8; 8]>()).await?;
/// let new_value = u64::from_le_bytes([1_u8; 8]);
/// // read, compare with rmr and swap `old_value` with `new_value`
/// rdma.atomic_cas(0, new_value, &mut rmr).await?;
/// // send rmr's meta data to the remote end
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().listen(addr).await?;
/// // receive mr's meta data from client
/// let lmr = rdma.receive_local_mr().await?;
/// // assert the content of lmr, which was write by cas
/// let data = *lmr.as_slice();
/// assert_eq!(data, [1_u8; 8]);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn atomic_cas<RW>(
&self,
old_value: u64,
new_value: u64,
rm: &mut RW,
) -> io::Result<()>
where
RW: RemoteMrWriteAccess,
{
if rm.length() != 8 {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"The length of remote mr should be 8",
))
} else if rm.addr() & 7 != 0 {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Atomic operations are legal only when the remote address is on a naturally-aligned 8-byte boundary",
))
} else {
let buf = self.alloc_local_mr(std::alloc::Layout::new::<[u8; 8]>())?;
self.qp.atomic_cas(old_value, new_value, &buf, rm).await
}
}
/// Send raw data in the lm
///
/// Used with `receive_raw`.
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// const RAW_DATA: [u8; 8] = [1_u8; 8];
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).connect(addr).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::for_value(&RAW_DATA))?;
/// // put data into lmr
/// let _num = lmr.as_mut_slice().write(&RAW_DATA)?;
/// // wait for serer to receive first
/// tokio::time::sleep(Duration::from_millis(100)).await;
/// // send the content of lmr to server
/// rdma.send_raw(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).listen(addr).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma.receive_raw(Layout::for_value(&RAW_DATA)).await?;
/// // read data from mr
/// assert_eq!(*lmr.as_slice(), RAW_DATA);
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[cfg(feature = "raw")]
pub async fn send_raw<LR>(&self, lm: &LR) -> io::Result<()>
where
LR: LocalMrReadAccess,
{
self.qp.send_sge_raw(&[lm], None).await
}
/// Send raw data in the lm with imm
///
/// Used with `receive_raw_with_imm`
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// const RAW_DATA: [u8; 8] = [1_u8; 8];
/// const IMM: u32 = 1_u32;
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).connect(addr).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::for_value(&RAW_DATA))?;
/// // put data into lmr
/// let _num = lmr.as_mut_slice().write(&RAW_DATA)?;
/// // wait for serer to receive first
/// tokio::time::sleep(Duration::from_millis(100)).await;
/// // send the content of lmr to server
/// rdma.send_raw_with_imm(&lmr, IMM).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).listen(addr).await?;
/// // receive the data sent by client and put it into an mr
/// let (lmr, imm) = rdma
/// .receive_raw_with_imm(Layout::for_value(&RAW_DATA))
/// .await?;
/// // read data from mr
/// assert_eq!(*lmr.as_slice(), RAW_DATA);
/// assert_eq!(imm, Some(IMM));
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[cfg(feature = "raw")]
pub async fn send_raw_with_imm<LR>(&self, lm: &LR, imm: u32) -> io::Result<()>
where
LR: LocalMrReadAccess,
{
self.qp.send_sge_raw(&[lm], Some(imm)).await
}
/// Send the content in the `lm` with immediate date.
///
/// Used with `receive_with_imm`.
///
/// # Examples
/// ```rust
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
/// static IMM_NUM: u32 = 123;
/// static MSG: &str = "hello world";
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // put data into lmr
/// unsafe { std::ptr::write(*lmr.as_mut_ptr() as *mut Data, Data(MSG.to_string())) };
/// // send the content of lmr and imm data to server
/// rdma.send_with_imm(&lmr, IMM_NUM).await?;
/// rdma.send_with_imm(&lmr, IMM_NUM).await?;
/// rdma.send(&lmr).await?;
/// rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the data and imm sent by the client
/// let (lmr, imm) = rdma.receive_with_imm().await?;
/// assert_eq!(imm, Some(IMM_NUM));
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // receive the data in mr while avoiding the immediate data is ok.
/// let lmr = rdma.receive().await?;
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // `receive_with_imm` works well even if the client didn't send any immediate data.
/// // the imm received will be a `None`.
/// let (lmr, imm) = rdma.receive_with_imm().await?;
/// assert_eq!(imm, None);
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // compared to the above, using `receive` is a better choice.
/// let lmr = rdma.receive().await?;
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// let server_handle = std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// server_handle.join().unwrap().unwrap();
/// }
/// ```
#[inline]
pub async fn send_with_imm(&self, lm: &LocalMr, imm: u32) -> io::Result<()> {
self.agent
.as_ref()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Agent is not ready"))?
.send_data(lm, Some(imm))
.await
}
/// Receive the content and stored in the returned memory region
///
/// Used with `send`.
/// Application scenario such as: client put data into a local mr and `send` to server.
/// Server `receive` the mr sent by client and process data in it.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // send the content of lmr to server
/// rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma.receive().await?;
/// // read data from mr
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn receive(&self) -> io::Result<LocalMr> {
let (lmr, _) = self.receive_with_imm().await?;
Ok(lmr)
}
/// Receive raw data
///
/// Used with `send_raw`.
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// const RAW_DATA: [u8; 8] = [1_u8; 8];
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).connect(addr).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::for_value(&RAW_DATA))?;
/// // put data into lmr
/// let _num = lmr.as_mut_slice().write(&RAW_DATA)?;
/// // wait for serer to receive first
/// tokio::time::sleep(Duration::from_millis(100)).await;
/// // send the content of lmr to server
/// rdma.send_raw(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).listen(addr).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma.receive_raw(Layout::for_value(&RAW_DATA)).await?;
/// // read data from mr
/// assert_eq!(*lmr.as_slice(), RAW_DATA);
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[cfg(feature = "raw")]
pub async fn receive_raw(&self, layout: Layout) -> io::Result<LocalMr> {
let mut lmr = self.alloc_local_mr(layout)?;
let _imm = self.qp.receive_sge_raw(&[&mut lmr]).await?;
Ok(lmr)
}
/// Receive raw data with imm
///
/// Used with `send_raw_with_imm`
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// const RAW_DATA: [u8; 8] = [1_u8; 8];
/// const IMM: u32 = 1_u32;
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).connect(addr).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::for_value(&RAW_DATA))?;
/// // put data into lmr
/// let _num = lmr.as_mut_slice().write(&RAW_DATA)?;
/// // wait for serer to receive first
/// tokio::time::sleep(Duration::from_millis(100)).await;
/// // send the content of lmr to server
/// rdma.send_raw_with_imm(&lmr, IMM).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).listen(addr).await?;
/// // receive the data sent by client and put it into an mr
/// let (lmr, imm) = rdma
/// .receive_raw_with_imm(Layout::for_value(&RAW_DATA))
/// .await?;
/// // read data from mr
/// assert_eq!(*lmr.as_slice(), RAW_DATA);
/// assert_eq!(imm, Some(IMM));
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[cfg(feature = "raw")]
pub async fn receive_raw_with_imm(&self, layout: Layout) -> io::Result<(LocalMr, Option<u32>)> {
let mut lmr = self.alloc_local_mr(layout)?;
let imm = self.qp.receive_sge_raw(&[&mut lmr]).await?;
Ok((lmr, imm))
}
/// Receive raw data and excute an fn after `submit_receive` and before `poll`
///
/// **This is an experimental API**
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
/// use tokio::sync::oneshot;
///
/// const RAW_DATA: [u8; 8] = [1_u8; 8];
///
/// async fn client(addr: SocketAddrV4, rx: oneshot::Receiver<()>) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).connect(addr).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::for_value(&RAW_DATA))?;
/// // put data into lmr
/// let _num = lmr.as_mut_slice().write(&RAW_DATA)?;
/// // wait for serer to receive first
/// rx.await.unwrap();
/// // send the content of lmr to server
/// rdma.send_raw(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4, tx: oneshot::Sender<()>) -> io::Result<()> {
/// let func = || {
/// println!("after post_recv and before poll");
/// tx.send(()).unwrap();
/// };
/// let rdma = RdmaBuilder::default().set_raw(true).listen(addr).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma
/// .receive_raw_fn(Layout::for_value(&RAW_DATA), func)
/// .await?;
/// // read data from mr
/// assert_eq!(*lmr.as_slice(), RAW_DATA);
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, rx) = tokio::sync::oneshot::channel::<()>();
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr, tx));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr, rx)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
///
/// ```
#[inline]
#[cfg(feature = "exp")]
pub async fn receive_raw_fn<F>(&self, layout: Layout, func: F) -> io::Result<LocalMr>
where
F: FnOnce(),
{
let mut lmr = self.alloc_local_mr(layout)?;
let _imm = self.qp.receive_sge_fn(&[&mut lmr], func).await?;
Ok(lmr)
}
/// Receive raw data with imm and excute an fn after `submit_receive` and before `poll`
///
/// **This is an experimental API**
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
/// use tokio::sync::oneshot;
///
/// const RAW_DATA: [u8; 8] = [1_u8; 8];
/// const IMM: u32 = 1_u32;
///
/// async fn client(addr: SocketAddrV4, rx: oneshot::Receiver<()>) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().set_raw(true).connect(addr).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::for_value(&RAW_DATA))?;
/// // put data into lmr
/// let _num = lmr.as_mut_slice().write(&RAW_DATA)?;
/// // wait for serer to receive first
/// rx.await.unwrap();
/// // send the content of lmr to server
/// rdma.send_raw_with_imm(&lmr, IMM).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4, tx: oneshot::Sender<()>) -> io::Result<()> {
/// let func = || {
/// println!("after post_recv and before poll");
/// tx.send(()).unwrap();
/// };
/// let rdma = RdmaBuilder::default().set_raw(true).listen(addr).await?;
/// // receive the data sent by client and put it into an mr
/// let (lmr, imm) = rdma
/// .receive_raw_with_imm_fn(Layout::for_value(&RAW_DATA), func)
/// .await?;
/// // read data from mr
/// assert_eq!(*lmr.as_slice(), RAW_DATA);
/// assert_eq!(imm, Some(IMM));
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, rx) = tokio::sync::oneshot::channel::<()>();
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr, tx));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr, rx)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
///
/// ```
#[inline]
#[cfg(feature = "exp")]
pub async fn receive_raw_with_imm_fn<F>(
&self,
layout: Layout,
func: F,
) -> io::Result<(LocalMr, Option<u32>)>
where
F: FnOnce(),
{
let mut lmr = self.alloc_local_mr(layout)?;
let imm = self.qp.receive_sge_fn(&[&mut lmr], func).await?;
Ok((lmr, imm))
}
/// Receive the content and stored in the returned memory region.
///
/// Used with `send_with_imm`.
///
/// # Examples
/// ```rust
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
/// static IMM_NUM: u32 = 123;
/// static MSG: &str = "hello world";
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // put data into lmr
/// unsafe { std::ptr::write(*lmr.as_mut_ptr() as *mut Data, Data(MSG.to_string())) };
/// // send the content of lmr and imm data to server
/// rdma.send_with_imm(&lmr, IMM_NUM).await?;
/// rdma.send_with_imm(&lmr, IMM_NUM).await?;
/// rdma.send(&lmr).await?;
/// rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the data and imm sent by the client
/// let (lmr, imm) = rdma.receive_with_imm().await?;
/// assert_eq!(imm, Some(IMM_NUM));
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // receive the data in mr while avoiding the immediate data is ok.
/// let lmr = rdma.receive().await?;
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // `receive_with_imm` works well even if the client didn't send any immediate data.
/// // the imm received will be a `None`.
/// let (lmr, imm) = rdma.receive_with_imm().await?;
/// assert_eq!(imm, None);
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // compared to the above, using `receive` is a better choice.
/// let lmr = rdma.receive().await?;
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// let server_handle = std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// server_handle.join().unwrap().unwrap();
/// }
/// ```
#[inline]
pub async fn receive_with_imm(&self) -> io::Result<(LocalMr, Option<u32>)> {
self.agent
.as_ref()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Agent is not ready"))?
.receive_data()
.await
}
/// Receive the immediate data sent by `write_with_imm`.
///
/// Used with `write_with_imm`.
///
/// # Examples
/// ```rust
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// static IMM_NUM: u32 = 123;
/// struct Data(String);
///
/// static MSG: &str = "hello world";
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// let mut rmr = rdma.request_remote_mr(Layout::new::<Data>()).await?;
/// let data = Data(MSG.to_string());
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = data };
/// // write the content of lmr to remote mr with immediate data.
/// rdma.write_with_imm(&lmr, &mut rmr, IMM_NUM).await?;
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the immediate data sent by `write_with_imm`
/// let imm = rdma.receive_write_imm().await?;
/// assert_eq!(imm, IMM_NUM);
/// // receive the metadata of the lmr that had been requested by client
/// let lmr = rdma.receive_local_mr().await?;
/// // assert the content of lmr, which was `write` by client
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// let server_handle = std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// server_handle.join().unwrap().unwrap();
/// }
/// ```
#[inline]
pub async fn receive_write_imm(&self) -> io::Result<u32> {
self.agent
.as_ref()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Agent is not ready"))?
.receive_imm()
.await
}
/// Read content in the `rm` and store the content in the `lm`
///
/// Application scenario such as: client put data into a local mr and `send_mr` to server.
/// Server get a remote mr by `receive_remote_mr`, and then get data from this rmr by rdma `read`.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // then send the metadata of this lmr to server to make server aware of this mr.
/// rdma.send_local_mr(lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // receive the metadata of rmr sent by client
/// let rmr = rdma.receive_remote_mr().await?;
/// // `read` data from rmr to lmr
/// rdma.read(&mut lmr, &rmr).await?;
/// // assert the content of lmr, which was get from rmr by rdma `read`
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn read<LW, RR>(&self, lm: &mut LW, rm: &RR) -> io::Result<()>
where
LW: LocalMrWriteAccess,
RR: RemoteMrReadAccess,
{
self.qp.read(lm, rm).await
}
/// Write content in the `lm` to `rm`
///
/// Application scenario such as: client request a remote mr through `request_remote_mr`,
/// and then put data into this rmr by rdma `write`. After all client `send_mr` to make
/// server aware of this mr.
/// After client `send_mr`, server `receive_local_mr`, and then get data from this mr.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// let mut rmr = rdma.request_remote_mr(Layout::new::<Data>()).await?;
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // write the content of local mr into remote mr
/// rdma.write(&lmr, &mut rmr).await?;
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of the lmr that had been requested by client
/// let lmr = rdma.receive_local_mr().await?;
/// // assert the content of lmr, which was `write` by client
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn write<LR, RW>(&self, lm: &LR, rm: &mut RW) -> io::Result<()>
where
LR: LocalMrReadAccess,
RW: RemoteMrWriteAccess,
{
self.qp.write(lm, rm, None).await
}
/// Write content in the `lm` to `rm` and send a immediate data which
/// will consume a `rdma receive work request` in the receiver's `receive queue`.
/// The receiver can receive this immediate data by using `receive_write_imm`.
///
/// Used with `receive_write_imm`.
///
/// # Examples
/// ```rust
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// static IMM_NUM: u32 = 123;
/// struct Data(String);
///
/// static MSG: &str = "hello world";
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// let mut rmr = rdma.request_remote_mr(Layout::new::<Data>()).await?;
/// let data = Data(MSG.to_string());
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = data };
/// // write the content of lmr to server with immediate data.
/// rdma.write_with_imm(&lmr, &mut rmr, IMM_NUM).await?;
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the immediate data sent by `write_with_imm`
/// let imm = rdma.receive_write_imm().await?;
/// assert_eq!(imm, IMM_NUM);
/// // receive the metadata of the lmr that had been requested by client
/// let lmr = rdma.receive_local_mr().await?;
/// // assert the content of lmr, which was `write` by client
/// unsafe { assert_eq!(MSG.to_string(), *(*(*lmr.as_ptr() as *const Data)).0) };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// let server_handle = std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// server_handle.join().unwrap().unwrap();
/// }
/// ```
#[inline]
pub async fn write_with_imm<LR, RW>(&self, lm: &LR, rm: &mut RW, imm: u32) -> io::Result<()>
where
LR: LocalMrReadAccess,
RW: RemoteMrWriteAccess,
{
self.qp.write(lm, rm, Some(imm)).await
}
/// Connect the remote endpoint and build rmda queue pair by TCP connection
///
/// `gid_index`: 0:ipv6, 1:ipv4
/// `max_message_length`: max length of msg used in `send`&`receive`.
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let _rdma = rdma_listener.accept(1, 1, 512).await?;
/// // run here after client connect
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn connect<A: ToSocketAddrs>(
addr: A,
port_num: u8,
gid_index: usize,
max_message_length: usize,
) -> io::Result<Self> {
let mut rdma = RdmaBuilder::default()
.set_port_num(port_num)
.set_gid_index(gid_index.cast())
.build()?;
assert!(
rdma.conn_type == ConnectionType::RCSocket,
"should set connection type to RCSocket"
);
let remote = tcp_connect_helper(addr, &rdma.endpoint()).await?;
let recv_attr_builder = RQAttrBuilder::default();
let send_attr_builder = SQAttrBuilder::default();
let (recv_attr, send_attr) =
builders_into_attrs(recv_attr_builder, send_attr_builder, &remote)?;
rdma.qp_handshake(recv_attr, send_attr)?;
rdma.init_agent(max_message_length, *DEFAULT_ACCESS).await?;
// wait for server to initialize
tokio::time::sleep(Duration::from_secs(1)).await;
Ok(rdma)
}
/// Establish connection with RDMA CM server
///
/// Application scenario can be seen in `[/example/cm_client.rs]`
///
/// # Examples
///
/// ```
/// use async_rdma::Rdma;
/// use local_ip_address::local_ip;
/// use portpicker::pick_unused_port;
/// use rdma_sys::*;
/// use std::{io, ptr::null_mut, time::Duration};
///
/// static SERVER_NODE: &str = "0.0.0.0\0";
///
/// async fn client(node: &str, service: &str) -> io::Result<()> {
/// let _rdma = Rdma::cm_connect(node, service, 1, 1, 0).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(node: &str, service: &str) -> io::Result<()> {
/// let mut hints = unsafe { std::mem::zeroed::<rdma_addrinfo>() };
/// let mut res: *mut rdma_addrinfo = null_mut();
/// hints.ai_flags = RAI_PASSIVE.try_into().unwrap();
/// hints.ai_port_space = rdma_port_space::RDMA_PS_TCP.try_into().unwrap();
/// let mut ret = unsafe {
/// rdma_getaddrinfo(
/// node.as_ptr().cast(),
/// service.as_ptr().cast(),
/// &hints,
/// &mut res,
/// )
/// };
/// if ret != 0 {
/// println!("rdma_getaddrinfo");
/// return Err(io::Error::last_os_error());
/// }
///
/// let mut listen_id = null_mut();
/// let mut id = null_mut();
/// let mut init_attr = unsafe { std::mem::zeroed::<ibv_qp_init_attr>() };
/// init_attr.cap.max_send_wr = 1;
/// init_attr.cap.max_recv_wr = 1;
/// ret = unsafe { rdma_create_ep(&mut listen_id, res, null_mut(), &mut init_attr) };
/// if ret != 0 {
/// println!("rdma_create_ep");
/// return Err(io::Error::last_os_error());
/// }
///
/// ret = unsafe { rdma_listen(listen_id, 0) };
/// if ret != 0 {
/// println!("rdma_listen");
/// return Err(io::Error::last_os_error());
/// }
///
/// ret = unsafe { rdma_get_request(listen_id, &mut id) };
/// if ret != 0 {
/// println!("rdma_get_request");
/// return Err(io::Error::last_os_error());
/// }
///
/// ret = unsafe { rdma_accept(id, null_mut()) };
/// if ret != 0 {
/// println!("rdma_get_request");
/// return Err(io::Error::last_os_error());
/// }
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let port = pick_unused_port().unwrap();
/// let server_service = port.to_string() + "\0";
/// let client_service = server_service.clone();
/// std::thread::spawn(move || server(SERVER_NODE, &server_service));
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// let node = local_ip().unwrap().to_string() + "\0";
/// client(&node, &client_service)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[cfg(feature = "cm")]
pub async fn cm_connect(
node: &str,
service: &str,
port_num: u8,
gid_index: usize,
max_message_length: usize,
) -> io::Result<Self> {
let mut rdma = RdmaBuilder::default()
.set_port_num(port_num)
.set_gid_index(gid_index)
.set_raw(true)
.set_conn_type(ConnectionType::RCCM)
.build()?;
assert!(
rdma.conn_type == ConnectionType::RCCM,
"should set connection type to RCSocket"
);
cm_connect_helper(&mut rdma, node, service)?;
rdma.init_agent(max_message_length, *DEFAULT_ACCESS).await?;
// wait for server to initialize
tokio::time::sleep(Duration::from_secs(1)).await;
Ok(rdma)
}
/// Allocate a local memory region
///
/// You can use local mr to `send`&`receive` or `read`&`write` with a remote mr.
/// The parameter `layout` can be obtained by `Layout::new::<Data>()`.
/// You can learn the way to write or read data in mr in the following example.
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // send the content of lmr to server
/// rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma.receive().await?;
/// // assert data in the lmr
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub fn alloc_local_mr(&self, layout: Layout) -> io::Result<LocalMr> {
self.allocator
.alloc_zeroed_default_access(&layout, &self.pd)
}
/// Allocate a local memory region that has not been initialized
///
/// You can use local mr to `send`&`receive` or `read`&`write` with a remote mr.
/// The parameter `layout` can be obtained by `Layout::new::<Data>()`.
/// You can learn the way to write or read data in mr in the following example.
///
/// # Safety
///
/// The newly allocated memory in this `LocalMr` is uninitialized.
/// Initialize it before using to make it safe.
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = unsafe { rdma.alloc_local_mr_uninit(Layout::new::<Data>())? };
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // send the content of lmr to server
/// rdma.send(&lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the data sent by client and put it into an mr
/// let lmr = rdma.receive().await?;
/// // assert data in the lmr
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub unsafe fn alloc_local_mr_uninit(&self, layout: Layout) -> io::Result<LocalMr> {
self.allocator.alloc_default_access(&layout, &self.pd)
}
/// Allocate a local memory region with specified access
///
/// Use `alloc_local_mr` if you want to alloc memory region with default access.
///
/// If you want more information, please check the documentation and examples
/// of `alloc_local_mr`.
///
/// # Example
///
/// ```
/// use async_rdma::{AccessFlag, MrAccess, RdmaBuilder};
/// use std::alloc::Layout;
///
/// #[tokio::main]
/// async fn main() {
/// let rdma = RdmaBuilder::default().build().unwrap();
/// let layout = Layout::new::<[u8; 4096]>();
/// let access = AccessFlag::LocalWrite | AccessFlag::RemoteRead;
/// let mr = rdma.alloc_local_mr_with_access(layout, access).unwrap();
/// assert_eq!(mr.access(), access);
/// }
///
/// ```
#[inline]
pub fn alloc_local_mr_with_access(
&self,
layout: Layout,
access: BitFlags<AccessFlag>,
) -> io::Result<LocalMr> {
self.allocator
.alloc_zeroed(&layout, flags_into_ibv_access(access), &self.pd)
}
/// Allocate a local memory region with specified access that has not been initialized
///
/// Use `alloc_local_mr_uninit` if you want to alloc memory region with default access.
///
/// If you want more information, please check the documentation and examples
/// of `alloc_local_mr_uninit`.
///
/// # Safety
///
/// The newly allocated memory in this `LocalMr` is uninitialized.
/// Initialize it before using to make it safe.
///
/// # Example
///
/// ```
/// use async_rdma::{AccessFlag, MrAccess, RdmaBuilder};
/// use std::alloc::Layout;
///
/// #[tokio::main]
/// async fn main() {
/// let rdma = RdmaBuilder::default().build().unwrap();
/// let layout = Layout::new::<[u8; 4096]>();
/// let access = AccessFlag::LocalWrite | AccessFlag::RemoteRead;
/// let mr = unsafe {
/// rdma.alloc_local_mr_uninit_with_access(layout, access)
/// .unwrap()
/// };
/// assert_eq!(mr.access(), access);
/// }
///
/// ```
#[inline]
pub unsafe fn alloc_local_mr_uninit_with_access(
&self,
layout: Layout,
access: BitFlags<AccessFlag>,
) -> io::Result<LocalMr> {
self.allocator
.alloc(&layout, flags_into_ibv_access(access), &self.pd)
}
/// Request a remote memory region with default timeout value.
///
/// **Note**: The operation of this memory region will fail after timeout.
///
/// Used with `send_mr`, `receive_local_mr`, `read` and `write`.
/// Application scenario such as: client uses `request_remote_mr` to apply for
/// a remote mr from server, and makes server aware of this mr by `send_mr` to server.
/// For server, this mr is a local mr, which can be received through `receive_local_mr`.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// // request a mr located in server.
/// let rmr = rdma.request_remote_mr(Layout::new::<Data>()).await?;
/// // do something with rmr like `write` data into it.
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of the lmr that had been requested by client
/// let _lmr = rdma.receive_local_mr().await?;
/// // do something with lmr like getting data from it.
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn request_remote_mr(&self, layout: Layout) -> io::Result<RemoteMr> {
self.request_remote_mr_with_timeout(layout, DEFAULT_RMR_TIMEOUT)
.await
}
/// Request a remote memory region with customized timeout value.
/// The rest is consistent with `request_remote_mr`.
///
/// **Note**: The operation of this memory region will fail after timeout.
///
/// Used with `send_mr`, `receive_local_mr`, `read` and `write`.
/// Application scenario such as: client uses `request_remote_mr` to apply for
/// a remote mr from server, and makes server aware of this mr by `send_mr` to server.
/// For server, this mr is a local mr, which can be received through `receive_local_mr`.
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener, RemoteMrReadAccess};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// // request a mr located in server.
/// let rmr = rdma
/// .request_remote_mr_with_timeout(Layout::new::<Data>(), Duration::from_secs(10))
/// .await?;
/// assert!(!rmr.timeout_check());
/// // do something with rmr like `write` data into it.
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of the lmr that had been requested by client
/// let _lmr = rdma.receive_local_mr().await?;
/// // do something with lmr like getting data from it.
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn request_remote_mr_with_timeout(
&self,
layout: Layout,
timeout: Duration,
) -> io::Result<RemoteMr> {
if let Some(ref agent) = self.agent {
agent.request_remote_mr_with_timeout(layout, timeout).await
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Agent is not ready, please wait a while",
))
}
}
/// Send a local memory region metadata to remote with default timeout value
///
/// **Note**: The operation of this memory region will fail after timeout.
///
/// Used with `receive_remote_mr`
///
/// Application scenario such as: client uses `alloc_local_mr` to alloc a local mr, and
/// makes server aware of this mr by `send_local_mr` to server.
/// For server, this mr is a remote mr, which can be received through `receive_remote_mr`.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// // request a mr located in server.
/// let lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // do something with rmr like `write` data into it.
/// // then send the metadata of this lmr to server to make server aware of this mr.
/// rdma.send_local_mr(lmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of rmr sent by client
/// let _rmr = rdma.receive_remote_mr().await?;
/// // do something with lmr like getting data from it.
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn send_local_mr(&self, mr: LocalMr) -> io::Result<()> {
self.send_local_mr_with_timeout(mr, DEFAULT_RMR_TIMEOUT)
.await
}
/// Send a local memory region metadata with timeout to remote with customized timeout value.
///
/// **Note**: The operation of this memory region will fail after timeout.
///
/// Used with `receive_remote_mr`
///
/// Application scenario such as: client uses `alloc_local_mr` to alloc a local mr, and
/// makes server aware of this mr by `send_local_mr` to server.
/// For server, this mr is a remote mr, which can be received through `receive_remote_mr`.
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener, RemoteMrReadAccess};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// // request a mr located in server.
/// let lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // do something with rmr like `write` data into it.
/// // then send the metadata of this lmr to server to make server aware of this mr.
/// rdma.send_local_mr_with_timeout(lmr, Duration::from_secs(1))
/// .await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of rmr sent by client
/// let rmr = rdma.receive_remote_mr().await?;
/// assert!(!rmr.timeout_check());
/// // do something with lmr like getting data from it.
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn send_local_mr_with_timeout(
&self,
mr: LocalMr,
timeout: Duration,
) -> io::Result<()> {
if let Some(ref agent) = self.agent {
agent.send_local_mr_with_timeout(mr, timeout).await
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Agent is not ready, please wait a while",
))
}
}
/// Send a remote memory region metadata to remote
///
/// Used with `receive_local_mr`.
///
/// Application scenario such as: client uses `request_remote_mr` to apply for
/// a remote mr from server, and makes server aware of this mr by `send_remote_mr` to server.
/// For server, this mr is a local mr, which can be received through `receive_local_mr`.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// // request a mr located in server.
/// let rmr = rdma.request_remote_mr(Layout::new::<Data>()).await?;
/// // do something with rmr like `write` data into it.
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of the lmr that had been requested by client
/// let _lmr = rdma.receive_local_mr().await?;
/// // do something with lmr like getting data from it.
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn send_remote_mr(&self, mr: RemoteMr) -> io::Result<()> {
if let Some(ref agent) = self.agent {
agent.send_remote_mr(mr).await
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Agent is not ready, please wait a while",
))
}
}
/// Receive a local memory region
///
/// Used with `send_mr`.
/// Application scenario such as: client uses `request_remote_mr` to apply for
/// a remote mr from server, and makes server aware of this mr by `send_mr` to server.
/// For server, this mr is a local mr, which can be received through `receive_local_mr`.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// Application scenario such as: client request a remote mr through `request_remote_mr`,
/// and then put data into this rmr by rdma `write`. After all client `send_mr` to make
/// server aware of this mr.
/// After client `send_mr`, server `receive_local_mr`, and then get data from this mr.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// let mut rmr = rdma.request_remote_mr(Layout::new::<Data>()).await?;
/// // put data into lmr
/// unsafe { *(*lmr.as_mut_ptr() as *mut Data) = Data("hello world".to_string()) };
/// // write the content of local mr into remote mr
/// rdma.write(&lmr, &mut rmr).await?;
/// // then send the metadata of rmr to server to make server aware of this mr.
/// rdma.send_remote_mr(rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// // receive the metadata of the lmr that had been requested by client
/// let lmr = rdma.receive_local_mr().await?;
/// // assert the content of lmr, which was `write` by client
/// unsafe {
/// assert_eq!(
/// "hello world".to_string(),
/// *(*(*lmr.as_ptr() as *const Data)).0
/// )
/// };
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn receive_local_mr(&self) -> io::Result<LocalMr> {
if let Some(ref agent) = self.agent {
agent.receive_local_mr().await
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Agent is not ready, please wait a while",
))
}
}
/// Receive a remote memory region
///
/// Used with `send_mr`.
/// Application scenario such as: server alloc a local mr and put data into it and let
/// client know about this mr through `send_mr`. For client, this is a remote mr located
/// in server.Client receive the metadata of this mr by `receive_remote_mr`.
///
/// Application scenario can be seen in `[/example/rpc.rs]`
///
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// struct Data(String);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// // receive the metadata of rmr sent by client
/// let _rmr = rdma.receive_remote_mr().await?;
/// // do something with rmr like `read` data from it.
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let rdma = rdma_listener.accept(1, 1, 512).await?;
/// let lmr = rdma.alloc_local_mr(Layout::new::<Data>())?;
/// // do something with lmr like put data into it.
/// // then send the metadata of this lmr to server to make server aware of this mr.
/// rdma.send_local_mr(lmr).await?;
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn receive_remote_mr(&self) -> io::Result<RemoteMr> {
if let Some(ref agent) = self.agent {
agent.receive_remote_mr().await
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Agent is not ready, please wait a while",
))
}
}
/// Set qp access for new `Rdma` that created by `clone`
///
/// Used with `listen`, `new_connect`
///
/// # Examples
///
/// ```
/// use async_rdma::{AccessFlag, RdmaBuilder};
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().connect(addr).await?;
/// let access = AccessFlag::LocalWrite | AccessFlag::RemoteRead;
/// let mut rdma = rdma.set_new_qp_access(access);
/// let _new_rdma = rdma.new_connect(addr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().listen(addr).await?;
/// let _new_rdma = rdma.listen().await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[must_use]
pub fn set_new_qp_access(mut self, qp_access: BitFlags<AccessFlag>) -> Self {
let _ = self
.clone_attr
.qp_init_attr
.access(flags_into_ibv_access(qp_access));
self
}
/// Set max access permission for remote mr requests for new `Rdma` that created by `clone`
///
/// Used with `listen`, `new_connect`
///
/// # Examples
///
/// ```
/// use async_rdma::{AccessFlag, RdmaBuilder, MrAccess};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().connect(addr).await?;
/// let rmr = rdma.request_remote_mr(Layout::new::<char>()).await?;
/// let new_rdma = rdma.new_connect(addr).await?;
/// let new_rmr = new_rdma.request_remote_mr(Layout::new::<char>()).await?;
/// let access = AccessFlag::LocalWrite | AccessFlag::RemoteRead;
/// assert_eq!(new_rmr.access(), access);
/// assert_ne!(rmr.access(), new_rmr.access());
/// new_rdma.send_remote_mr(new_rmr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().listen(addr).await?;
/// let access = AccessFlag::LocalWrite | AccessFlag::RemoteRead;
/// let mut rdma = rdma.set_new_max_rmr_access(access);
/// let new_rdma = rdma.listen().await?;
/// // receive the metadata of the lmr that had been requested by client
/// let _lmr = new_rdma.receive_local_mr().await?;
/// // wait for the agent thread to send all reponses to the remote.
/// tokio::time::sleep(Duration::from_secs(1)).await;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[must_use]
pub fn set_new_max_rmr_access(mut self, max_rmr_access: BitFlags<AccessFlag>) -> Self {
let _ = self
.clone_attr
.agent_attr
.set_max_rmr_access(flags_into_ibv_access(max_rmr_access));
self
}
/// Set qp access for new `Rdma` that created by `clone`
///
/// Used with `listen`, `new_connect`
///
/// # Examples
///
/// ```
/// use async_rdma::RdmaBuilder;
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().connect(addr).await?;
/// let mut rdma = rdma.set_new_port_num(1_u8);
/// let _new_rdma = rdma.new_connect(addr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().listen(addr).await?;
/// let _new_rdma = rdma.listen().await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[must_use]
pub fn set_new_port_num(mut self, port_num: u8) -> Self {
let _ = self.clone_attr.rq_attr.address_handler().port_num(port_num);
self
}
/// Set new `ProtectionDomain` for new `Rdma` that created by `clone` to provide isolation.
///
/// Used with `listen`, `new_connect`
///
/// # Examples
///
/// ```
/// use async_rdma::RdmaBuilder;
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().connect(addr).await?;
/// let mut rdma = rdma.set_new_pd()?;
/// // then the `Rdma`s created by `new_connect` will have a new `ProtectionDomain`
/// let _new_rdma = rdma.new_connect(addr).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let mut rdma = RdmaBuilder::default().listen(addr).await?;
/// let _new_rdma = rdma.listen().await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub fn set_new_pd(mut self) -> io::Result<Self> {
let _ = self
.clone_attr
.set_pd(Arc::new(self.ctx.create_protection_domain()?));
Ok(self)
}
/// Get the real state of qp by quering
///
/// # Examples
///
/// ```
/// use async_rdma::{RdmaBuilder, QueuePairState};
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_init = RdmaBuilder::default().build()?;
/// assert_eq!(rdma_init.get_cur_qp_state(), QueuePairState::Init);
/// let rdma_send = RdmaBuilder::default().connect(addr).await?;
/// assert_eq!(rdma_send.get_cur_qp_state(), QueuePairState::ReadyToSend);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().listen(addr).await?;
/// assert_eq!(rdma.get_cur_qp_state(), QueuePairState::ReadyToSend);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
#[must_use]
pub fn get_cur_qp_state(&self) -> QueuePairState {
self.qp.cur_state().read().to_owned()
}
/// Get the real state of qp by quering
///
/// # Examples
///
/// ```
/// use async_rdma::{RdmaBuilder, QueuePairState};
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_init = RdmaBuilder::default().build()?;
/// assert_eq!(rdma_init.query_qp_state()?, QueuePairState::Init);
/// let rdma_send = RdmaBuilder::default().connect(addr).await?;
/// assert_eq!(rdma_send.query_qp_state()?, QueuePairState::ReadyToSend);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().listen(addr).await?;
/// assert_eq!(rdma.query_qp_state()?, QueuePairState::ReadyToSend);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub fn query_qp_state(&self) -> io::Result<QueuePairState> {
self.qp.query_state()
}
/// Get information of this qp for establishing a connection.
///
///
#[inline]
#[must_use]
pub fn get_qp_endpoint(&self) -> QueuePairEndpoint {
self.qp.endpoint()
}
/// Get the attrs of send queue and recv queue or create and return a pair of default attrs if
/// they are none.
#[inline]
pub(crate) fn get_rq_sq_attr(&self) -> io::Result<(RQAttr, SQAttr)> {
let recv_attr = self.clone_attr.rq_attr.build()?;
let send_attr = self.clone_attr.sq_attr.build()?;
Ok((recv_attr, send_attr))
}
/// Get the tx end of polling trigger
fn get_poll_trigger_tx(&self) -> io::Result<&mpsc::Sender<()>> {
self.trigger_tx
.as_ref()
.ok_or_else(|| match *self.qp.cq_event_listener().pt_type() {
PollingTriggerType::Automatic => io::Error::new(
io::ErrorKind::Other,
"this method can only used with PollingTriggerType::Manual",
),
PollingTriggerType::Manual => io::Error::new(
io::ErrorKind::Other,
"this is a bug, trigger_tx is not initialized",
),
})
}
/// User driven poll. Used with `RdmaBuilder.set_polling_trigger()`.
/// See also `Rdma.get_manual_trigger()`.
///
/// If you want to control CQ polling by yourself manually, you can set `PollingTriggerType::Manual`
/// using `RdmaBuilder.set_polling_trigger()`. Then all async RDMA operations will not complete
/// until you poll.
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use minstant::Instant;
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// sync::Arc,
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// const POLLING_INTERVAL: Duration = Duration::from_millis(100);
/// let rdma = Arc::new(RdmaBuilder::default()
/// .set_polling_trigger(async_rdma::PollingTriggerType::Manual)
/// .set_cc_evnet_timeout(Duration::from_secs(10))
/// .connect(addr)
/// .await
/// .unwrap());
///
/// let rdma_trigger = rdma.clone();
/// // polling task
/// let _trigger_handle = tokio::spawn(async move {
/// loop {
/// tokio::time::sleep(POLLING_INTERVAL).await;
/// rdma_trigger.poll().await.unwrap();
/// }
/// });
///
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<[u8; 8]>())?;
/// let _num = lmr.as_mut_slice().write(&[1_u8; 8])?;
/// let instant = Instant::now();
/// rdma.send(&lmr).await?;
/// assert!(instant.elapsed() >= POLLING_INTERVAL);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().listen(addr).await?;
/// let lmr = rdma.receive().await?;
/// let data = *lmr.as_slice();
/// assert_eq!(data, [1_u8; 8]);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
///
/// ```
#[inline]
pub async fn poll(&self) -> io::Result<()> {
self.get_poll_trigger_tx()?.send(()).await.map_err(|_e| {
io::Error::new(
io::ErrorKind::BrokenPipe,
"this is a bug, receiver is closed",
)
})
}
/// Get tx end of channel polling trigger.
///
/// You can send a `()` message through tx like to trigger a polling like `Rdma.poll()`.
/// This API is more convenient and flexible than `Rdma.poll()`, becasue you can clone more than
/// one tx and send them to other threads or tasks.
///
/// # Examples
///
/// ```
/// use async_rdma::{LocalMrReadAccess, LocalMrWriteAccess, RdmaBuilder};
/// use minstant::Instant;
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// io::{self, Write},
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// const POLLING_INTERVAL: Duration = Duration::from_millis(100);
/// let rdma = RdmaBuilder::default()
/// .set_polling_trigger(async_rdma::PollingTriggerType::Manual)
/// .set_cc_evnet_timeout(Duration::from_secs(10))
/// .connect(addr)
/// .await
/// .unwrap();
///
/// let trigger = rdma.get_manual_trigger().unwrap();
/// // polling task
/// let _trigger_handle = tokio::spawn(async move {
/// loop {
/// tokio::time::sleep(POLLING_INTERVAL).await;
/// trigger.pull().await.unwrap();
/// }
/// });
///
/// let mut lmr = rdma.alloc_local_mr(Layout::new::<[u8; 8]>())?;
/// let _num = lmr.as_mut_slice().write(&[1_u8; 8])?;
/// let instant = Instant::now();
/// rdma.send(&lmr).await?;
/// assert!(instant.elapsed() >= POLLING_INTERVAL);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = RdmaBuilder::default().listen(addr).await?;
/// let lmr = rdma.receive().await?;
/// let data = *lmr.as_slice();
/// assert_eq!(data, [1_u8; 8]);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
///
/// ```
#[inline]
pub fn get_manual_trigger(&self) -> io::Result<ManualTrigger> {
Ok(ManualTrigger(self.get_poll_trigger_tx()?.clone()))
}
/// Get the last ibv async event type.
///
/// # Examples
///
/// ```
///
/// use async_rdma::{RdmaBuilder, IbvEventType};
/// use portpicker::pick_unused_port;
/// use std::{
/// alloc::Layout,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration, sync::Arc, io,
/// };
/// const POLLING_INTERVAL: Duration = Duration::from_secs(2);
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Arc::new(RdmaBuilder::default()
/// .set_polling_trigger(async_rdma::PollingTriggerType::Manual)
/// .set_cc_evnet_timeout(POLLING_INTERVAL)
/// .set_cq_size(1)
/// .set_max_cqe(1)
/// .connect(addr)
/// .await
/// .unwrap());
///
/// // waiting for rdma send requests
/// tokio::time::sleep(POLLING_INTERVAL).await;
/// // cq is full
/// assert_eq!(rdma.get_last_ibv_event_type().unwrap().unwrap(),IbvEventType::IBV_EVENT_CQ_ERR);
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma = Arc::new(RdmaBuilder::default().listen(addr).await?);
/// let layout = Layout::new::<[u8; 8]>();
/// let mut handles = vec![];
///
/// for _ in 0..10{
/// let rdma_move = rdma.clone();
/// let lmr = rdma_move.alloc_local_mr(layout)?;
/// handles.push(tokio::spawn(async move {let _ = rdma_move.send(&lmr).await;}));
/// }
/// tokio::time::sleep(POLLING_INTERVAL).await;
/// for handle in handles{
/// handle.abort();
/// }
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
///
/// ```
#[inline]
pub fn get_last_ibv_event_type(&self) -> io::Result<Option<IbvEventType>> {
Ok(*self
.agent
.as_ref()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Agent is not ready"))?
.ibv_event_listener()
.last_event_type()
.lock())
}
}
/// Rdma Listener is the wrapper of a `TcpListener`, which is used to
/// build the rdma queue pair.
#[derive(Debug)]
pub struct RdmaListener {
/// Tcp listener to establish the queue pair
tcp_listener: TcpListener,
}
impl RdmaListener {
/// Bind the address and wait for a connection
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let _rdma = rdma_listener.accept(1, 1, 512).await?;
/// // run here after client connect
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
let tcp_listener = TcpListener::bind(addr).await?;
Ok(Self { tcp_listener })
}
/// Wait for a connection from a remote host
/// # Examples
/// ```
/// use async_rdma::{Rdma, RdmaListener};
/// use portpicker::pick_unused_port;
/// use std::{
/// io,
/// net::{Ipv4Addr, SocketAddrV4},
/// time::Duration,
/// };
///
/// async fn client(addr: SocketAddrV4) -> io::Result<()> {
/// let _rdma = Rdma::connect(addr, 1, 1, 512).await?;
/// Ok(())
/// }
///
/// #[tokio::main]
/// async fn server(addr: SocketAddrV4) -> io::Result<()> {
/// let rdma_listener = RdmaListener::bind(addr).await?;
/// let _rdma = rdma_listener.accept(1, 1, 512).await?;
/// // run here after client connect
/// Ok(())
/// }
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), pick_unused_port().unwrap());
/// std::thread::spawn(move || server(addr));
/// tokio::time::sleep(Duration::from_secs(3)).await;
/// client(addr)
/// .await
/// .map_err(|err| println!("{}", err))
/// .unwrap();
/// }
/// ```
#[inline]
pub async fn accept(
&self,
port_num: u8,
gid_index: usize,
max_message_length: usize,
) -> io::Result<Rdma> {
let (mut stream, _) = self.tcp_listener.accept().await?;
let mut rdma = RdmaBuilder::default()
.set_port_num(port_num)
.set_gid_index(gid_index.cast())
.build()?;
assert!(
rdma.conn_type == ConnectionType::RCSocket,
"should set connection type to RCSocket"
);
let endpoint_size = bincode::serialized_size(&rdma.endpoint()).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("Endpoint serialization failed, {:?}", e),
)
})?;
let mut remote = vec![0_u8; endpoint_size.cast()];
// the byte number is not important, as read_exact will fill the buffer
let _ = stream.read_exact(remote.as_mut()).await?;
let remote: QueuePairEndpoint = bincode::deserialize(&remote).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("failed to deserialize remote endpoint, {:?}", e),
)
})?;
let local = bincode::serialize(&rdma.endpoint()).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("failed to deserialize remote endpoint, {:?}", e),
)
})?;
stream.write_all(&local).await?;
let mut recv_attr = RQAttrBuilder::default();
let send_attr = SQAttrBuilder::default();
let _ = recv_attr
.address_handler()
.port_num(port_num)
.grh()
.sgid_index(gid_index.cast());
let (recv_attr, send_attr) = builders_into_attrs(recv_attr, send_attr, &remote)?;
rdma.qp_handshake(recv_attr, send_attr)?;
debug!("handshake done");
rdma.init_agent(max_message_length, *DEFAULT_ACCESS).await?;
Ok(rdma)
}
}