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
|
/*++
Module Name:
compat.cpp
Abstract:
Functions that provide compatibility between the Windows and Linux versions,
and mostly that serve to keep #ifdef's out of the main code in order to
improve readibility.
Authors:
Bill Bolosky, November, 2011
Environment:
User mode service.
Revision History:
--*/
#include "stdafx.h"
#include "Compat.h"
#include "BigAlloc.h"
#ifndef _MSC_VER
#include <fcntl.h>
#include <aio.h>
#include <err.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif
#include "exit.h"
#ifdef PROFILE_WAIT
#include <map>
#endif
#include "DataWriter.h"
#include "Error.h"
using std::min;
using std::max;
#ifdef PROFILE_WAIT
#undef AcquireExclusiveLock
#undef WaitForSingleWaiterObject
#undef WaitForEvent
void AcquireUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock);
bool WaitForSingleWaiterObject(SingleWaiterObject *singleWaiterObject);
void WaitForEvent(EventObject *eventObject);
using std::map;
using std::string;
static map<string,_int64> times;
void addTime(const char* fn, int line, _int64 time)
{
if (time > 0) {
char s[20];
sprintf(s, ":%d", line);
string key = string(fn) + string(s);
times[key] += time;
}
}
void AcquireExclusiveLockProfile(ExclusiveLock *lock, const char* fn, int line)
{
_int64 start = timeInMillis();
AcquireExclusiveLock(lock);
addTime(fn, line, timeInMillis() - start);
}
bool WaitForSingleWaiterObjectProfile(SingleWaiterObject *singleWaiterObject, const char* fn, int line)
{
_int64 start = timeInMillis();
bool result = WaitForSingleWaiterObject(singleWaiterObject);
addTime(fn, line, timeInMillis() - start);
return result;
}
void WaitForEventProfile(EventObject *eventObject, const char* fn, int line)
{
_int64 start = timeInMillis();
WaitForEvent(eventObject);
addTime(fn, line, timeInMillis() - start);
}
#endif
void PrintWaitProfile()
{
#ifdef PROFILE_WAIT
printf("function:line wait_time (s)\n");
for (map<string,_int64>::iterator lt = times.begin(); lt != times.end(); lt++) {
printf("%s %.3f\n", lt->first.data(), lt->second * 0.0001);
}
#endif
}
#ifdef _MSC_VER
const void* memmem(const void* data, const size_t dataLength, const void* pattern, const size_t patternLength)
{
if (dataLength < patternLength) {
return NULL;
}
const void* p = data;
const char first = *(char*)pattern;
size_t count = dataLength - patternLength + 1;
while (count > 0) {
const void* q = memchr(p, first, count);
if (q == NULL) {
return NULL;
}
if (0 == memcmp(q, pattern, patternLength)) {
return q;
}
count -= ((char*)q - (char*)p) + 1;
p = (char*)q + 1;
}
return NULL;
}
_int64 timeInMillis()
/**
* Get the current time in milliseconds since some arbitrary starting point
* (e.g. system boot or epoch)
*/
{
return GetTickCount64();
}
_int64 timeInNanos()
{
static _int64 performanceFrequency = 0;
if (0 == performanceFrequency) {
QueryPerformanceFrequency((PLARGE_INTEGER)&performanceFrequency);
}
LARGE_INTEGER perfCount;
QueryPerformanceCounter(&perfCount);
const _int64 billion = 1000000000; // ns / s
//
// We have to be careful here to avoid _int64 overflow and resulting madness.
//
// If QPC returns t and QPF returns f, then we're trying to compute t * billion / f.
// However, f is typically, say, 10^7. So if we just used that expression then we'd
// wrap every 2^64 / 10^(7+9) seconds, i.e., ~1844s or almost twice/hour. That's not OK.
//
// Conversely, if we used t * (billion/f) then if f doesn't go evenly into a billion
// we'd have a rate error, which is bad and subtle.
//
// Instead, if we define F as floor(billion/f) (the whole part of ticks/ns), and r as billion%f (the remainder)
// then we have (in real math) timeInNanos() = t * floor(billion/f) + t * (r/f).
// The first term wraps every 2^64 ns, which is ~584 years and furthermore is an integer
// since both t and floor(billion/f) are integers, so we don't need to worry about it for either wrapping or loss of precision.
// The second term will wrap less often, since r/f < 1. To do it in integer math, we just reverse the parens and so have as our final
// formula timeInNanos() = t * floor(billion/f) + (t*r)/f.
//
return perfCount.QuadPart * (billion / performanceFrequency) + (perfCount.QuadPart * billion % performanceFrequency) / performanceFrequency;
}
void AcquireUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
EnterCriticalSection(lock);
}
void ReleaseUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
LeaveCriticalSection(lock);
}
bool InitializeUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
InitializeCriticalSection(lock);
return true;
}
bool DestroyUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock) {
DeleteCriticalSection(lock);
return true;
}
bool CreateSingleWaiterObject(SingleWaiterObject *newWaiter)
{
*newWaiter = CreateEvent(NULL,TRUE,FALSE,NULL);
if (NULL == *newWaiter) {
return false;
}
return true;
}
void DestroySingleWaiterObject(SingleWaiterObject *waiter)
{
CloseHandle(*waiter);
}
void SignalSingleWaiterObject(SingleWaiterObject *singleWaiterObject) {
SetEvent(*singleWaiterObject);
}
bool WaitForSingleWaiterObject(SingleWaiterObject *singleWaiterObject) {
DWORD retVal = WaitForSingleObject(*singleWaiterObject,INFINITE);
if (WAIT_OBJECT_0 != retVal) {
return false;
}
return true;
}
void ResetSingleWaiterObject(SingleWaiterObject *singleWaiterObject) {
ResetEvent(*singleWaiterObject);
}
//
// In Windows, the single waiter objects are already implemented using events.
//
void CreateEventObject(EventObject *newEvent) {CreateSingleWaiterObject(newEvent);}
void DestroyEventObject(EventObject *eventObject) {DestroySingleWaiterObject(eventObject);}
void AllowEventWaitersToProceed(EventObject *eventObject) {SignalSingleWaiterObject(eventObject);}
void PreventEventWaitersFromProceeding(EventObject *eventObject) {ResetSingleWaiterObject(eventObject);}
void WaitForEvent(EventObject *eventObject) {WaitForSingleWaiterObject(eventObject);}
bool WaitForEventWithTimeout(EventObject *eventObject, _int64 timeoutInMillis)
{
DWORD retVal = WaitForSingleObjectEx(*eventObject, (unsigned)timeoutInMillis, FALSE);
if (retVal == WAIT_OBJECT_0) {
return true;
} else if (retVal == WAIT_TIMEOUT) {
return false;
}
WriteErrorMessage("WaitForSingleObject returned unexpected result %d (error %d)\n", retVal, GetLastError());
soft_exit(1);
return false; // NOTREACHED: Just to avoid the compiler complaining.
}
void BindThreadToProcessor(unsigned processorNumber) // This hard binds a thread to a processor. You can no-op it at some perf hit.
{
if (!SetThreadAffinityMask(GetCurrentThread(),((unsigned _int64)1) << processorNumber)) {
WriteErrorMessage("Binding thread to processor %d failed, %d\n",processorNumber,GetLastError());
}
}
bool DoesThreadHaveProcessorAffinitySet()
{
return false; // This is harder to do in Windows than you'd think, so we just no-op it.
}
int InterlockedIncrementAndReturnNewValue(volatile int *valueToIncrement)
{
return InterlockedIncrement((volatile long *)valueToIncrement);
}
int InterlockedDecrementAndReturnNewValue(volatile int *valueToDecrement)
{
return InterlockedDecrement((volatile long *)valueToDecrement);
}
_uint32 InterlockedCompareExchange32AndReturnOldValue(volatile _uint32 *valueToUpdate, _uint32 replacementValue, _uint32 desiredPreviousValue)
{
return (_uint32) InterlockedCompareExchange(valueToUpdate, replacementValue, desiredPreviousValue);
}
_uint64 InterlockedCompareExchange64AndReturnOldValue(volatile _uint64 *valueToUpdate, _uint64 replacementValue, _uint64 desiredPreviousValue)
{
return (_uint64) InterlockedCompareExchange(valueToUpdate, replacementValue, desiredPreviousValue);
}
void* InterlockedCompareExchangePointerAndReturnOldValue(void * volatile *valueToUpdate, void* replacementValue, void* desiredPreviousValue)
{
return InterlockedCompareExchangePointer(valueToUpdate, replacementValue, desiredPreviousValue);
}
struct WrapperThreadContext {
ThreadMainFunction mainFunction;
void *mainFunctionParameter;
};
DWORD WINAPI
WrapperThreadMain(PVOID Context)
{
WrapperThreadContext *context = (WrapperThreadContext *)Context;
(*context->mainFunction)(context->mainFunctionParameter);
delete context;
context = NULL;
return 0;
}
bool StartNewThread(ThreadMainFunction threadMainFunction, void *threadMainFunctionParameter)
{
WrapperThreadContext *context = new WrapperThreadContext;
if (NULL == context) {
return false;
}
context->mainFunction = threadMainFunction;
context->mainFunctionParameter = threadMainFunctionParameter;
HANDLE hThread;
DWORD threadId;
hThread = CreateThread(NULL,0,WrapperThreadMain,context,0,&threadId);
if (NULL == hThread) {
WriteErrorMessage("Create thread failed, %d\n",GetLastError());
delete context;
context = NULL;
return false;
}
CloseHandle(hThread);
hThread = NULL;
return true;
}
void SleepForMillis(unsigned millis)
{
Sleep(millis);
}
unsigned GetNumberOfProcessors()
{
SYSTEM_INFO systemInfo[1];
GetSystemInfo(systemInfo);
return systemInfo->dwNumberOfProcessors;
}
_int64 QueryFileSize(const char *fileName) {
HANDLE hFile = CreateFile(fileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (INVALID_HANDLE_VALUE == hFile) {
WriteErrorMessage("Unable to open file '%s' for QueryFileSize, %d\n", fileName, GetLastError());
soft_exit(1);
}
LARGE_INTEGER fileSize;
if (!GetFileSizeEx(hFile,&fileSize)) {
WriteErrorMessage("GetFileSize failed, %d\n",GetLastError());
soft_exit(1);
}
CloseHandle(hFile);
return fileSize.QuadPart;
}
bool
DeleteSingleFile(
const char* filename)
{
return DeleteFile(filename) ? true : false;
}
bool
MoveSingleFile(
const char* oldFileName,
const char* newFileName)
{
return MoveFile(oldFileName, newFileName) ? true : false;
}
class LargeFileHandle
{
public:
HANDLE handle;
};
LargeFileHandle*
OpenLargeFile(
const char* filename,
const char* mode)
{
_ASSERT(strlen(mode) == 1 && (*mode == 'r' || *mode == 'w' || *mode == 'a'));
LargeFileHandle* result = new LargeFileHandle();
result->handle = CreateFile(filename,
*mode == 'r' ? GENERIC_READ :
*mode == 'a' ? FILE_APPEND_DATA
: GENERIC_WRITE,
0 /* exclusive */,
NULL,
*mode == 'w' ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (result->handle == NULL) {
WriteErrorMessage("open large file %s failed with 0x%x\n", filename, GetLastError());
delete (void*) result;
return NULL;
}
return result;
}
size_t
WriteLargeFile(
LargeFileHandle* file,
void* buffer,
size_t bytes)
{
size_t count = bytes;
while (count > 0) {
DWORD step = 0;
if ((! WriteFile(file->handle, buffer, (DWORD) min(count, (size_t) 0x2000000), &step, NULL)) || step == 0) {
WriteErrorMessage("WriteLargeFile failed at %lu of %lu bytes with 0x%x\n", bytes - count, bytes, GetLastError());
return bytes - count;
}
count -= step;
buffer = ((char*) buffer) + step;
}
return bytes;
}
size_t
ReadLargeFile(
LargeFileHandle* file,
void* buffer,
size_t bytes)
{
size_t count = bytes;
while (count > 0) {
DWORD step = 0;
if ((! ReadFile(file->handle, buffer, (DWORD) min(count, (size_t) 0x1000000), &step, NULL)) || step == 0) {
WriteErrorMessage("ReadLargeFile failed at %lu of %lu bytes with 0x%x\n", bytes - count, bytes, GetLastError());
return bytes - count;
}
count -= step;
buffer = ((char*) buffer) + step;
}
return bytes;
}
void
CloseLargeFile(
LargeFileHandle* file)
{
if (CloseHandle(file->handle)) {
delete (void*) file;
}
}
class MemoryMappedFile
{
public:
HANDLE fileHandle;
HANDLE fileMapping;
void* mappedAddress;
};
MemoryMappedFile*
OpenMemoryMappedFile(
const char* filename,
size_t offset,
size_t length,
void** o_contents,
bool write,
bool sequential)
{
MemoryMappedFile* result = new MemoryMappedFile();
result->fileHandle = CreateFile(filename, (write ? GENERIC_WRITE : 0) | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | (sequential ? FILE_FLAG_SEQUENTIAL_SCAN : FILE_FLAG_RANDOM_ACCESS), NULL);
if (result->fileHandle == NULL) {
WriteErrorMessage("unable to open mapped file %s error 0x%x\n", filename, GetLastError());
delete result;
return NULL;
}
result->fileMapping = CreateFileMapping(result->fileHandle, NULL, write ? PAGE_READWRITE : PAGE_READONLY, 0, 0, NULL);
if (result->fileMapping == NULL) {
WriteErrorMessage("unable to create file mapping %s error 0x%x\n", filename, GetLastError());
delete result;
return NULL;
}
*o_contents = result->mappedAddress = MapViewOfFile(result->fileMapping,
write ? FILE_MAP_WRITE : FILE_MAP_READ,
(DWORD) (offset >> (8 * sizeof(DWORD))),
(DWORD) offset,
length);
if (*o_contents == NULL) {
WriteErrorMessage("unable to map file %s error 0x%x\n", filename, GetLastError());
delete result;
return NULL;
}
return result;
}
void
CloseMemoryMappedFile(
MemoryMappedFile* mappedFile)
{
bool ok = UnmapViewOfFile(mappedFile->mappedAddress) &&
CloseHandle(mappedFile->fileMapping) &&
CloseHandle(mappedFile->fileHandle);
if (ok) {
delete (void*) mappedFile;
} else {
WriteErrorMessage("unable to close memory mapped file, error 0x%x\n", GetLastError());
}
}
void AdviseMemoryMappedFilePrefetch(const MemoryMappedFile *mappedFile)
{
// No-op on WIndows.
}
class WindowsAsyncFile : public AsyncFile
{
public:
static WindowsAsyncFile* open(const char* filename, bool write);
WindowsAsyncFile(HANDLE i_hFile);
~WindowsAsyncFile();
virtual bool close();
virtual _int64 getSize();
class Writer : public AsyncFile::Writer
{
public:
Writer(); // ctor for the writeQueueHead element
Writer(WindowsAsyncFile* i_file);
~Writer();
virtual bool close();
virtual bool beginWrite(void* buffer, size_t length, size_t offset, size_t *bytesWritten);
virtual bool waitForCompletion();
void addToQueue();
void removeFromQueue();
Writer* getFirstItemFromWriteQueue();
bool isQueueEmpty(); // Only call on queue head
private:
WindowsAsyncFile* file;
bool writing;
bool queueHead; // Is this the queue head element and not really a Writer?
_int64 nLaps;
int nLapsActive;
OVERLAPPED *laps;
Writer* writeQueueNext;
Writer* writeQueuePrev;
HANDLE hWriteStartedEvent; // This gets set once the write is moved from the queue and sent down to Windows. Once this happens it's safe to wait on the OVERLAPPED for the Windows completion
void* writeBuffer;
size_t writeLength;
size_t writeOffset;
DWORD* bytesWritten; // A place for WriteFile to record what it actually did
size_t* writeBytesWritten; // where we return the total written
size_t writeBytesWrittenBuffer; // if the user passes in null, we just squirrel it away here
int squirrel; // A squirreled-away copy of the first bytes of the buffer at write time. It's used to assert that the buffer hasn't been overwritten when the write completes.
void launchWrite(); //Actually send the write down to Windows
const int maxWriteSize = 128 * 1024 * 1024; // 128MB seems like a big enough write even for very wide array storage
}; // Writer
virtual AsyncFile::Writer* getWriter();
class Reader : public AsyncFile::Reader
{
public:
Reader(WindowsAsyncFile* i_file);
virtual bool close();
virtual bool beginRead(void* buffer, size_t length, size_t offset, size_t *bytesRead);
virtual bool waitForCompletion();
private:
WindowsAsyncFile* file;
bool reading;
OVERLAPPED lap;
size_t* out_bytes_read;
}; // Reader
virtual AsyncFile::Reader* getReader();
private:
HANDLE hFile;
//
// Because Windows "async" cached writes aren't really all that async (they are serialized and wait for the copy-in to cache
// to complete), we make them more async by making a queue of them. When a writer comes in and the queue is empty, it adds itself
// to the queue and issues the async write. When the async write completes (i.e., the Write system call completes, not GetOvelappedResult()
// says it's done) it removes itself from the queue and starts the next item at the head of the queue. If the queue is empty, it returns to
// its caller. When a write call happens and the queue is NOT empty, then the writer just adds the write to the queue.
//
Writer writeQueueHead[1];
CRITICAL_SECTION writeQueueLock[1];
}; // WindowsAsyncFile
WindowsAsyncFile*
WindowsAsyncFile::open(
const char* filename,
bool write)
{
HANDLE hFile = CreateFile(filename,
GENERIC_READ | (write ? GENERIC_WRITE : 0),
write ? 0 : FILE_SHARE_READ,
NULL,
write ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (INVALID_HANDLE_VALUE == hFile) {
WriteErrorMessage("Unable to create SAM file '%s', %d\n",filename,GetLastError());
return NULL;
}
return new WindowsAsyncFile(hFile);
}
_int64
WindowsAsyncFile::getSize()
{
LARGE_INTEGER liSize;
if (!GetFileSizeEx(hFile, &liSize)) {
WriteErrorMessage("WindowsAsyncFile: GetFileSizeEx() failed, %d\n", GetLastError());
soft_exit(1);
}
return liSize.QuadPart;
}
WindowsAsyncFile::WindowsAsyncFile(
HANDLE i_hFile)
: hFile(i_hFile)
{
InitializeCriticalSection(writeQueueLock);
}
WindowsAsyncFile::~WindowsAsyncFile()
{
DeleteCriticalSection(writeQueueLock);
}
WindowsAsyncFile::Writer::~Writer()
{
if (laps != NULL) {
for (int i = 0; i < nLaps; i++) {
if (INVALID_HANDLE_VALUE != laps[i].hEvent) {
CloseHandle(laps[i].hEvent);
}
} // for each lap
delete[] laps;
} // if we have laps
if (INVALID_HANDLE_VALUE != hWriteStartedEvent)
{
CloseHandle(hWriteStartedEvent);
hWriteStartedEvent = INVALID_HANDLE_VALUE;
}
} // WindowsAsyncFile::Writer::~Writer()
void
WindowsAsyncFile::Writer::addToQueue()
{
//
// Caller must hold the write queue lock.
//
_ASSERT(writeQueueNext == NULL);
_ASSERT(writeQueuePrev == NULL);
writeQueueNext = file->writeQueueHead;
writeQueuePrev = file->writeQueueHead->writeQueuePrev;
writeQueueNext->writeQueuePrev = this;
writeQueuePrev->writeQueueNext = this;
} // WindowsAsyncFile::Writer::addToQueue()
void
WindowsAsyncFile::Writer::removeFromQueue()
{
writeQueueNext->writeQueuePrev = writeQueuePrev;
writeQueuePrev->writeQueueNext = writeQueueNext;
writeQueueNext = writeQueuePrev = NULL;
} // WindowsAsyncFile::Writer::removeFromQueue()
WindowsAsyncFile::Writer *
WindowsAsyncFile::Writer::getFirstItemFromWriteQueue()
{
_ASSERT(queueHead);
return writeQueueNext;
}
bool
WindowsAsyncFile::Writer::isQueueEmpty()
{
_ASSERT(queueHead);
return writeQueueNext == this;
}
bool
WindowsAsyncFile::close()
{
return CloseHandle(hFile) ? true : false;
}
// ctor for the queue head
WindowsAsyncFile::Writer::Writer()
{
writeQueueNext = writeQueuePrev = this;
writing = false;
file = NULL;
nLaps = 0;
nLapsActive = 0;
laps = NULL;
queueHead = TRUE;
hWriteStartedEvent = INVALID_HANDLE_VALUE;
writeBuffer = NULL;
writeOffset = 0;
writeLength = 0;
bytesWritten = NULL;
squirrel = 0; // Just to make the compiler not complain about uninitialized stuff
writeBytesWritten = NULL;
}
AsyncFile::Writer*
WindowsAsyncFile::getWriter()
{
return new Writer(this);
}
// ctor for normal (non-queue head) Writers
WindowsAsyncFile::Writer::Writer(WindowsAsyncFile* i_file)
: file(i_file), writing(false), queueHead(FALSE), writeBuffer(NULL), writeOffset(0), writeLength(0), bytesWritten(NULL), squirrel(0), writeBytesWritten(NULL)
{
writeQueueNext = writeQueuePrev = NULL;
nLaps = 0;
nLapsActive = 0;
laps = NULL;
hWriteStartedEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
}
bool
WindowsAsyncFile::Writer::close()
{
waitForCompletion();
for (int i = 0; i < nLaps; i++) {
CloseHandle(laps[i].hEvent);
}
CloseHandle(hWriteStartedEvent);
return true;
}
bool
WindowsAsyncFile::Writer::beginWrite(
void* buffer,
size_t length,
size_t offset,
size_t *bytesWritten)
{
_ASSERT(!writing); // We should never start a write when the previous one is still outstanding. The following waitForCompleteion() is therefore unnecessary (but I'm leaving it for now).
if (! waitForCompletion()) {
return false;
}
writeBuffer = buffer;
writeLength = length;
writeOffset = offset;
if (bytesWritten == NULL) {
writeBytesWritten = &writeBytesWrittenBuffer;
} else {
writeBytesWritten = bytesWritten;
}
if (length < sizeof(int)) {
squirrel = 0;
} else {
squirrel = *((int*)buffer);
}
ResetEvent(hWriteStartedEvent);
writing = true;
EnterCriticalSection(file->writeQueueLock);
bool weAreWriter = file->writeQueueHead->isQueueEmpty();
addToQueue();
LeaveCriticalSection(file->writeQueueLock);
if (!weAreWriter) {
//
// Someone else owns the queue and will start our write.
//
return true;
}
//
// Launch writes to windows until the queue is empty.
//
EnterCriticalSection(file->writeQueueLock);
while (!file->writeQueueHead->isQueueEmpty()) {
Writer* nextToWrite = file->writeQueueHead->getFirstItemFromWriteQueue();
LeaveCriticalSection(file->writeQueueLock);
nextToWrite->launchWrite();
EnterCriticalSection(file->writeQueueLock);
_ASSERT(file->writeQueueHead->getFirstItemFromWriteQueue() == nextToWrite);
nextToWrite->removeFromQueue();
SetEvent(nextToWrite->hWriteStartedEvent);
}
LeaveCriticalSection(file->writeQueueLock);
return true;
} // WindowsAsyncFile::Writer::beginWrite
void
WindowsAsyncFile::Writer::launchWrite()
{
_int64 nNeededLaps = (writeLength + maxWriteSize - 1) / maxWriteSize;
if (nNeededLaps > nLaps) {
//
// Need more laps because we have to break this into more chunks than we ever have before.
//
OVERLAPPED* newLaps = new OVERLAPPED[nNeededLaps];
for (_int64 i = 0; i < nLaps; i++) {
newLaps[i] = laps[i]; // This mostly just copies the event handle
}
for (_int64 i = nLaps; i < nNeededLaps; i++) {
newLaps[i].hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
}
delete[] laps;
laps = newLaps;
nLaps = nNeededLaps;
if (NULL != bytesWritten) {
delete[] bytesWritten;
}
bytesWritten = new DWORD[nLaps];
} // If we need more OVERLAPPEDs.
LARGE_INTEGER liWriteOffset;
liWriteOffset.QuadPart = writeOffset;
size_t amountLeftToWrite = writeLength;
size_t amountWritten = 0;
_ASSERT(nLapsActive == 0);
while (amountLeftToWrite > 0) {
_ASSERT(nLapsActive < nLaps);
DWORD amountToWrite = (DWORD)__min(maxWriteSize, amountLeftToWrite);
laps[nLapsActive].OffsetHigh = liWriteOffset.HighPart;
laps[nLapsActive].Offset = liWriteOffset.LowPart;
if (!WriteFile(file->hFile, (char*)writeBuffer + amountWritten, amountToWrite, &bytesWritten[nLapsActive], &laps[nLapsActive])) {
if (ERROR_IO_PENDING != GetLastError()) {
WriteErrorMessage("WindowsAsyncFile: WriteFile of %d bytes failed, %d\n", amountToWrite, GetLastError());
soft_exit(1);
}
}
liWriteOffset.QuadPart += amountToWrite;
amountWritten += amountToWrite;
amountLeftToWrite -= amountToWrite;
nLapsActive++;
} // while we have something to write
} // WindowsAsyncFile::Writer::launchWrite
bool
WindowsAsyncFile::Writer::waitForCompletion()
{
if (writing) {
if (WAIT_OBJECT_0 != WaitForSingleObject(hWriteStartedEvent, INFINITE)) {
WriteErrorMessage("WaitForSingleObject failed in WindowsAsnycWriter, %d\n", GetLastError());
soft_exit(1);
}
*writeBytesWritten = 0;
for (_int64 i = 0; i < nLapsActive; i++) {
DWORD nBytesTransferred;
if (!GetOverlappedResult(file->hFile, &laps[i], &nBytesTransferred, TRUE)) {
return false;
}
*writeBytesWritten += nBytesTransferred;
}
xassert(writeLength < sizeof(int) || squirrel == *((int*)writeBuffer));
writing = false;
nLapsActive = 0;
ResetEvent(hWriteStartedEvent);
}
return true;
}
AsyncFile::Reader*
WindowsAsyncFile::getReader()
{
return new Reader(this);
}
WindowsAsyncFile::Reader::Reader(
WindowsAsyncFile* i_file)
: file(i_file), reading(false), out_bytes_read(NULL)
{
lap.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
}
bool
WindowsAsyncFile::Reader::close()
{
return CloseHandle(lap.hEvent) ? true : false;
}
bool
WindowsAsyncFile::Reader::beginRead(
void* buffer,
size_t length,
size_t offset,
size_t* bytesRead)
{
if (! waitForCompletion()) {
return false;
}
out_bytes_read = bytesRead;
lap.OffsetHigh = (DWORD) (offset >> (8 * sizeof(DWORD)));
lap.Offset = (DWORD) offset;
DWORD nBytesRead;
if (!ReadFile(file->hFile, buffer,(DWORD) length, &nBytesRead, &lap)) {
if (ERROR_IO_PENDING != GetLastError()) {
WriteErrorMessage("WindowsSAMWriter: WriteFile failed, %d\n",GetLastError());
return false;
}
}
*out_bytes_read = nBytesRead;
reading = true;
return true;
}
bool
WindowsAsyncFile::Reader::waitForCompletion()
{
if (reading) {
DWORD nBytesTransferred;
if (!GetOverlappedResult(file->hFile,&lap,&nBytesTransferred,TRUE)) {
return false;
}
*out_bytes_read = nBytesTransferred;
out_bytes_read = NULL;
reading = false;
}
return true;
}
_int64 InterlockedAdd64AndReturnNewValue(volatile _int64 *valueToWhichToAdd, _int64 amountToAdd)
{
return InterlockedAdd64((volatile LONGLONG *)valueToWhichToAdd,(LONGLONG)amountToAdd);
}
int _fseek64bit(FILE *stream, _int64 offset, int origin)
{
return _fseeki64(stream,offset,origin);
}
int getpagesize()
{
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
return systemInfo.dwAllocationGranularity;
}
FileMapper::FileMapper()
{
hFile = INVALID_HANDLE_VALUE;
hMapping = NULL;
initialized = false;
pagesize = getpagesize();
mapCount = 0;
#if 0
hFilePrefetch = INVALID_HANDLE_VALUE;
lap->hEvent = NULL;
prefetchBuffer = BigAlloc(prefetchBufferSize);
isPrefetchOutstanding = false;
lastPrefetch = 0;
#endif
millisSpentInReadFile = 0;
countOfImmediateCompletions = 0;
countOfDelayedCompletions = 0;
countOfFailures = 0;
}
bool
FileMapper::init(const char *i_fileName)
{
if (initialized) {
if (strcmp(fileName, i_fileName)) {
WriteErrorMessage("FileMapper already initialized with %s, cannot init with %s\n", fileName, i_fileName);
return false;
}
return true;
}
fileName = i_fileName;
hFile = CreateFile(fileName, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
if (INVALID_HANDLE_VALUE == hFile) {
WriteErrorMessage("Failed to open '%s', error %d\n",fileName, GetLastError());
return false;
}
#if 0
hFilePrefetch = CreateFile(fileName, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
if (INVALID_HANDLE_VALUE == hFilePrefetch) {
WriteErrorMessage("Failed to open '%s' for prefetch, error %d\n",fileName, GetLastError());
CloseHandle(hFile);
return false;
}
#endif
BY_HANDLE_FILE_INFORMATION fileInfo;
if (!GetFileInformationByHandle(hFile,&fileInfo)) {
WriteErrorMessage("Unable to get file information for '%s', error %d\n", fileName, GetLastError());
CloseHandle(hFile);
#if 0
CloseHandle(hFilePrefetch);
#endif
return false;
}
LARGE_INTEGER liFileSize;
liFileSize.HighPart = fileInfo.nFileSizeHigh;
liFileSize.LowPart = fileInfo.nFileSizeLow;
fileSize = liFileSize.QuadPart;
hMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL);
if (NULL == hMapping) {
WriteErrorMessage("Unable to create mapping to file '%s', %d\n", fileName, GetLastError());
CloseHandle(hFile);
#if 0
CloseHandle(hFilePrefetch);
#endif
return false;
}
#if 0
lap->hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
#endif
initialized = true;
return true;
}
char *
FileMapper::createMapping(size_t offset, size_t amountToMap, void** o_mappedBase)
{
size_t beginRounding = offset % pagesize;
LARGE_INTEGER liStartingOffset;
liStartingOffset.QuadPart = offset - beginRounding;
size_t endRounding = 0;
if ((amountToMap + beginRounding) % pagesize != 0) {
endRounding = pagesize - (amountToMap + beginRounding) % pagesize;
}
size_t mapRequestSize = beginRounding + amountToMap + endRounding;
_ASSERT(mapRequestSize % pagesize == 0);
if (mapRequestSize + liStartingOffset.QuadPart >= fileSize) {
mapRequestSize = 0; // Says to just map the whole thing.
}
char* mappedBase = (char *)MapViewOfFile(hMapping,FILE_MAP_READ,liStartingOffset.HighPart,liStartingOffset.LowPart, mapRequestSize);
if (NULL == mappedBase) {
WriteErrorMessage("Unable to map file, %d\n", GetLastError());
return NULL;
}
char* mappedRegion = mappedBase + beginRounding;
#if 0
prefetch(0);
#endif
InterlockedIncrementAndReturnNewValue(&mapCount);
*o_mappedBase = mappedBase;
return mappedRegion;
}
void
FileMapper::unmap(void* mappedBase)
{
_ASSERT(mapCount > 0);
if (mapCount > 0) {
int n = InterlockedDecrementAndReturnNewValue(&mapCount);
_ASSERT(n >= 0);
if (!UnmapViewOfFile(mappedBase)) {
WriteErrorMessage("Unmap of file failed, %d\n", GetLastError());
}
}
}
FileMapper::~FileMapper()
{
_ASSERT(mapCount == 0);
#if 0
if (isPrefetchOutstanding) {
DWORD numberOfBytesTransferred;
GetOverlappedResult(hFile,lap,&numberOfBytesTransferred,TRUE);
}
BigDealloc(prefetchBuffer);
prefetchBuffer = NULL;
CloseHandle(hFilePrefetch);
CloseHandle(lap->hEvent);
#endif
CloseHandle(hMapping);
CloseHandle(hFile);
WriteErrorMessage("FileMapper: %lld immediate completions, %lld delayed completions, %lld failures, %lld ms in readfile (%lld ms/call)\n",countOfImmediateCompletions, countOfDelayedCompletions, countOfFailures, millisSpentInReadFile,
millisSpentInReadFile/max(1, countOfImmediateCompletions + countOfDelayedCompletions + countOfFailures));
}
#if 0
void
FileMapper::prefetch(size_t currentRead)
{
if (currentRead + prefetchBufferSize / 2 <= lastPrefetch || lastPrefetch + prefetchBufferSize >= amountMapped) {
//
// Nothing to do; we're either not ready for more prefetching or we're at the end of our region.
//
return;
}
if (isPrefetchOutstanding) {
//
// See if the last prefetch is done.
//
DWORD numberOfBytesTransferred;
if (GetOverlappedResult(hFile,lap,&numberOfBytesTransferred,FALSE)) {
isPrefetchOutstanding = false;
} else {
#if DBG
if (GetLastError() != ERROR_IO_PENDING) {
WriteErrorMessage("mapped file prefetcher: GetOverlappedResult failed, %d\n", GetLastError());
}
#endif // DBG
return; // There's still IO on outstanding, we can't start more.
}
}
DWORD amountToRead = (DWORD)__min(prefetchBufferSize, amountMapped - lastPrefetch);
_ASSERT(amountToRead > 0); // Else we should have failed the initial check and returned
LARGE_INTEGER liReadOffset;
lastPrefetch += prefetchBufferSize;
liReadOffset.QuadPart = lastPrefetch;
lap->OffsetHigh = liReadOffset.HighPart;
lap->Offset = liReadOffset.LowPart;
DWORD nBytesRead;
_int64 start = timeInMillis();
if (!ReadFile(hFilePrefetch,prefetchBuffer,amountToRead,&nBytesRead,lap)) {
if (GetLastError() == ERROR_IO_PENDING) {
InterlockedAdd64AndReturnNewValue(&countOfDelayedCompletions,1);
isPrefetchOutstanding = true;
} else {
InterlockedAdd64AndReturnNewValue(&countOfFailures,1);
#if DBG
if (GetLastError() != ERROR_IO_PENDING) {
WriteErrorMessage("mapped file prefetcher: ReadFile failed, %d\n", GetLastError());
}
#endif // DBG
isPrefetchOutstanding = false; // Just ignore it
}
} else {
InterlockedAdd64AndReturnNewValue(&countOfImmediateCompletions,1);
isPrefetchOutstanding = false;
}
InterlockedAdd64AndReturnNewValue(&millisSpentInReadFile,timeInMillis() - start);
}
#endif
void PreventMachineHibernationWhileThisThreadIsAlive()
{
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
}
void SetToLowSchedulingPriority()
{
if (!SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS)) {
WriteErrorMessage("Unable to set process to background priority class, %d. Ignoring and proceeding at normal priority\n", GetLastError());
}
}
struct NamedPipe {
HANDLE hPipe;
};
NamedPipe *OpenNamedPipe(const char *pipeName, bool serverSide)
{
NamedPipe *pipe = new NamedPipe;
const char *prefix = "\\\\.\\pipe\\";
char *fullyQualifiedPipeName = new char[strlen(prefix) + strlen(pipeName) + 1]; // +1 for null
sprintf(fullyQualifiedPipeName, "%s%s", prefix, pipeName);
if (serverSide) {
pipe->hPipe = CreateNamedPipe(fullyQualifiedPipeName, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, 100000, 100000, 0, NULL);
if (INVALID_HANDLE_VALUE == pipe->hPipe) {
WriteErrorMessage("OpenNamedPipe('%s'): unable to open pipe, %d\n", fullyQualifiedPipeName, GetLastError());
delete pipe;
return NULL;
}
if (!ConnectNamedPipe(pipe->hPipe, NULL) && ERROR_PIPE_CONNECTED != GetLastError()) {
WriteErrorMessage("Unable to connect named pipe, %d\n", GetLastError());
delete pipe;
return NULL;
}
} else {
pipe->hPipe = CreateFile(fullyQualifiedPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
while (INVALID_HANDLE_VALUE == pipe->hPipe && GetLastError() == ERROR_PIPE_BUSY) {
WriteStatusMessage("Server is busy. Waiting.\n");
if (!WaitNamedPipe(fullyQualifiedPipeName, NMPWAIT_WAIT_FOREVER)) {
fprintf(stderr, "Waiting for server connection failed, %d\n", GetLastError());
delete pipe;
return NULL;
}
pipe->hPipe = CreateFile(fullyQualifiedPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
}
if (INVALID_HANDLE_VALUE == pipe->hPipe) {
WriteErrorMessage("Unable to open server connection '%s', %d\n", fullyQualifiedPipeName, GetLastError());
delete pipe;
return NULL;
}
}
return pipe;
}
bool ReadFromNamedPipe(NamedPipe *pipe, char *outputBuffer, size_t outputBufferSize)
{
DWORD bytesRead;
while (!ReadFile(pipe->hPipe, outputBuffer, (DWORD)outputBufferSize, &bytesRead, NULL)) {
if (GetLastError() != ERROR_BROKEN_PIPE && GetLastError() != ERROR_NO_DATA) {
fprintf(stderr, "Read named pipe failed, %d\n", GetLastError()); // Don't use WriteErrorMessage, it will try to send on the pipe
return false;
}
if (GetLastError() == ERROR_BROKEN_PIPE) {
if (!DisconnectNamedPipe(pipe->hPipe)) {
fprintf(stderr, "Disconnect named pipe failed, %d; ignoring\n", GetLastError());
}
if (!ConnectNamedPipe(pipe->hPipe, NULL) && ERROR_PIPE_CONNECTED != GetLastError()) {
fprintf(stderr, "ReadFromNamedPipe: reconnecting to pipe failed, %d\n", GetLastError());
return false;
}
}
}
return true;
}
bool WriteToNamedPipe(NamedPipe *pipe, const char *stringToWrite)
{
DWORD bytesWritten;
if (!WriteFile(pipe->hPipe, stringToWrite, (DWORD)strlen(stringToWrite) + 1, &bytesWritten, NULL)) { // +1 sends terminating NULL
fprintf(stderr, "WriteToNamedPipe: write failed, %d\n", GetLastError());
return false;
}
FlushFileBuffers(pipe->hPipe);
if (bytesWritten != strlen(stringToWrite) + 1) {
fprintf(stderr, "WriteToNamedPipe: expected to write %lld bytes, actually wrote %d\n", strlen(stringToWrite) + 1, bytesWritten);
}
return bytesWritten == strlen(stringToWrite) + 1;
}
void CloseNamedPipe(NamedPipe *pipe)
{
CloseHandle(pipe->hPipe);
delete pipe;
}
const char *DEFAULT_NAMED_PIPE_NAME = "SNAP";
#else // _MSC_VER
#if defined(__MACH__)
#include <mach/clock.h>
#include <mach/mach.h>
#endif
_int64 timeInMillis()
/**
* Get the current time in milliseconds since some arbitrary starting point
* (e.g. system boot or epoch)
*/
{
timeval t;
gettimeofday(&t, NULL);
return ((_int64) t.tv_sec) * 1000 + ((_int64) t.tv_usec) / 1000;
}
_int64 timeInNanos()
{
timespec ts;
#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
#elif defined(__MACH__)
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
#else
#error "Don't know how to get time in nanos on your platform"
#endif
return ((_int64) ts.tv_sec) * 1000000000 + (_int64) ts.tv_nsec;
}
void AcquireUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
pthread_mutex_lock(lock);
}
void ReleaseUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
pthread_mutex_unlock(lock);
}
bool InitializeUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
return pthread_mutex_init(lock, NULL) == 0;
}
bool DestroyUnderlyingExclusiveLock(UnderlyingExclusiveLock *lock)
{
return pthread_mutex_destroy(lock) == 0;
}
class SingleWaiterObjectImpl {
protected:
pthread_mutex_t lock;
pthread_cond_t cond;
bool set;
public:
bool init() {
if (pthread_mutex_init(&lock, NULL) != 0) {
return false;
}
if (pthread_cond_init(&cond, NULL) != 0) {
pthread_mutex_destroy(&lock);
return false;
}
set = false;
return true;
}
void signal() {
pthread_mutex_lock(&lock);
set = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
void wait() {
pthread_mutex_lock(&lock);
while (!set) {
pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);
}
bool waitWithTimeout(_int64 timeoutInMillis) {
struct timespec wakeTime;
#if defined(__linux__)
clock_gettime(CLOCK_REALTIME, &wakeTime);
wakeTime.tv_nsec += timeoutInMillis * 1000000;
#elif defined(__MACH__)
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
wakeTime.tv_nsec = mts.tv_nsec + timeoutInMillis * 1000000;
wakeTime.tv_sec = mts.tv_sec;
#endif
wakeTime.tv_sec += wakeTime.tv_nsec / 1000000000;
wakeTime.tv_nsec = wakeTime.tv_nsec % 1000000000;
bool timedOut = false;
pthread_mutex_lock(&lock);
while (!set) {
int retVal = pthread_cond_timedwait(&cond, &lock, &wakeTime);
if (retVal == ETIMEDOUT) {
timedOut = true;
break;
}
}
pthread_mutex_unlock(&lock);
return !timedOut;
}
bool destroy() {
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&lock);
return true;
}
};
bool CreateSingleWaiterObject(SingleWaiterObject *waiter)
{
SingleWaiterObjectImpl *obj = new SingleWaiterObjectImpl;
if (obj == NULL) {
return false;
}
if (!obj->init()) {
delete obj;
return false;
}
*waiter = obj;
return true;
}
void DestroySingleWaiterObject(SingleWaiterObject *waiter)
{
(*waiter)->destroy();
delete *waiter;
}
void SignalSingleWaiterObject(SingleWaiterObject *waiter)
{
(*waiter)->signal();
}
bool WaitForSingleWaiterObject(SingleWaiterObject *waiter)
{
(*waiter)->wait();
return true;
}
void ResetSingleWaiterObject(SingleWaiterObject *waiter)
{
(*waiter)->init();
}
class EventObjectImpl : public SingleWaiterObjectImpl
{
public:
void signalAll()
{
pthread_mutex_lock(&lock);
set = true;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
}
void blockAll()
{
pthread_mutex_lock(&lock);
set = false;
pthread_mutex_unlock(&lock);
}
};
void CreateEventObject(EventObject *newEvent)
{
EventObjectImpl* obj = new EventObjectImpl();
if (obj == NULL) {
return;
}
if (!obj->init()) {
delete obj;
return;
}
*newEvent = obj;
}
void DestroyEventObject(EventObject *eventObject)
{
(*eventObject)->destroy();
delete *eventObject;
}
void AllowEventWaitersToProceed(EventObject *eventObject)
{
(*eventObject)->signalAll();
}
void PreventEventWaitersFromProceeding(EventObject *eventObject)
{
(*eventObject)->blockAll();
}
void WaitForEvent(EventObject *eventObject)
{
(*eventObject)->wait();
}
bool WaitForEventWithTimeout(EventObject *eventObject, _int64 timeoutInMillis)
{
return (*eventObject)->waitWithTimeout(timeoutInMillis);
}
int InterlockedIncrementAndReturnNewValue(volatile int *valueToDecrement)
{
return (int) __sync_fetch_and_add((volatile int*) valueToDecrement, 1) + 1;
}
int InterlockedDecrementAndReturnNewValue(volatile int *valueToDecrement)
{
return __sync_fetch_and_sub(valueToDecrement, 1) - 1;
}
_int64 InterlockedAdd64AndReturnNewValue(volatile _int64 *valueToWhichToAdd, _int64 amountToAdd)
{
return __sync_fetch_and_add(valueToWhichToAdd, amountToAdd) + amountToAdd;
}
_uint32 InterlockedCompareExchange32AndReturnOldValue(volatile _uint32 *valueToUpdate, _uint32 replacementValue, _uint32 desiredPreviousValue)
{
return __sync_val_compare_and_swap(valueToUpdate, desiredPreviousValue, replacementValue);
}
_uint64 InterlockedCompareExchange64AndReturnOldValue(volatile _uint64 *valueToUpdate, _uint64 replacementValue, _uint64 desiredPreviousValue)
{
return (_uint64) __sync_val_compare_and_swap((volatile _int64 *) valueToUpdate, desiredPreviousValue, replacementValue);
}
void* InterlockedCompareExchangePointerAndReturnOldValue(void * volatile *valueToUpdate, void* replacementValue, void* desiredPreviousValue)
{
return __sync_val_compare_and_swap(valueToUpdate, desiredPreviousValue, replacementValue);
}
namespace {
// POSIX thread functions need to return void*, so we wrap the ThreadMainFunction in our API
struct ThreadInfo {
ThreadMainFunction function;
void *parameter;
ThreadInfo(ThreadMainFunction f, void *p): function(f), parameter(p) {}
};
void* runThread(void* infoVoidPtr) {
ThreadInfo *info = (ThreadInfo*) infoVoidPtr;
info->function(info->parameter);
delete info;
return NULL;
}
}
bool StartNewThread(ThreadMainFunction threadMainFunction, void *threadMainFunctionParameter)
{
ThreadInfo *info = new ThreadInfo(threadMainFunction, threadMainFunctionParameter);
pthread_t thread;
return pthread_create(&thread, NULL, runThread, info) == 0;
}
void BindThreadToProcessor(unsigned processorNumber)
{
#ifdef __linux__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(processorNumber, &cpuset);
if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset) != 0) {
perror("sched_setaffinity");
}
#endif
}
bool DoesThreadHaveProcessorAffinitySet()
{
#ifdef __linux__
cpu_set_t cpuset;
if (sched_getaffinity(0, sizeof(cpu_set_t), &cpuset) != 0) {
perror("sched_getaffinity");
} else {
for (int i = 0; i < GetNumberOfProcessors(); i++) {
if (!CPU_ISSET(i, &cpuset)) {
return true;
} // if this CPU is clear
} // for each CPU
} // if sched_getaffinity worked
#endif
return false; // We didn't find a CPU we can't use, or else we got an error or aren't on Linux, in which case the default is false.
}
unsigned GetNumberOfProcessors()
{
return (unsigned) sysconf(_SC_NPROCESSORS_ONLN);
}
void SleepForMillis(unsigned millis)
{
usleep(millis*1000);
}
_int64 QueryFileSize(const char *fileName)
{
int fd = open(fileName, O_RDONLY);
if (fd < 0) {
WriteErrorMessage("Unable to open file '%s' for query file size, errno %d (%s)\n", fileName, errno, strerror(errno));
soft_exit(1);
}
struct stat sb;
int r = fstat(fd, &sb);
_ASSERT(r != -1);
_int64 fileSize = sb.st_size;
close(fd);
return fileSize;
}
bool
DeleteSingleFile(
const char* filename)
{
return unlink(filename) == 0;
}
bool
MoveSingleFile(
const char* from,
const char* to)
{
return rename(from, to) == 0;
}
class LargeFileHandle
{
public:
FILE* file;
};
LargeFileHandle*
OpenLargeFile(
const char* filename,
const char* mode)
{
_ASSERT(strlen(mode) == 1 && (*mode == 'r' || *mode == 'w' || *mode == 'a'));
char fmode[3];
fmode[0] = mode[0]; fmode[1] = 'b'; fmode[2] = '\0';
FILE* file = fopen(filename, fmode);
if (file == NULL) {
return NULL;
}
LargeFileHandle* result = new LargeFileHandle();
result->file = file;
return result;
}
size_t
WriteLargeFile(
LargeFileHandle* file,
void* buffer,
size_t bytes)
{
return fwrite(buffer, 1, bytes, file->file);
}
size_t
ReadLargeFile(
LargeFileHandle* file,
void* buffer,
size_t bytes)
{
return fread(buffer, 1, bytes, file->file);
}
void
CloseLargeFile(
LargeFileHandle* file)
{
if (0 == fclose(file->file)) {
delete file;
}
}
class MemoryMappedFile
{
public:
int fd;
void* map;
size_t length;
};
MemoryMappedFile*
OpenMemoryMappedFile(
const char* filename,
size_t offset,
size_t length,
void** o_contents,
bool write,
bool sequential)
{
int fd = open(filename, write ? O_CREAT | O_RDWR : O_RDONLY, S_IRUSR | S_IWUSR);
if (fd < 0) {
WriteErrorMessage("OpenMemoryMappedFile %s failed\n", filename);
return NULL;
}
// todo: large page support
size_t page = getpagesize();
size_t extra = offset % page;
void* map = mmap(NULL, length + extra, (write ? PROT_WRITE : 0) | PROT_READ, MAP_PRIVATE, fd, offset - extra);
if (map == NULL || map == MAP_FAILED) {
WriteErrorMessage("OpenMemoryMappedFile %s mmap failed\n", filename);
close(fd);
return NULL;
}
int e = madvise(map, length + extra, sequential ? MADV_SEQUENTIAL : MADV_RANDOM);
if (e < 0) {
WriteErrorMessage("OpenMemoryMappedFile %s madvise failed; this should only affect performance\n", filename);
}
MemoryMappedFile* result = new MemoryMappedFile();
result->fd = fd;
result->map = map;
result->length = length + extra;
*o_contents = (char*)map + extra;
return result;
}
void
CloseMemoryMappedFile(
MemoryMappedFile* mappedFile)
{
int e = munmap(mappedFile->map, mappedFile->length);
int e2 = close(mappedFile->fd);
if (e != 0 || e2 != 0) {
WriteErrorMessage("CloseMemoryMapped file failed\n");
}
}
void AdviseMemoryMappedFilePrefetch(const MemoryMappedFile *mappedFile)
{
if (madvise(mappedFile->map, mappedFile->length, MADV_SEQUENTIAL)) {
WriteErrorMessage("madvise MADV_SEQUENTIAL failed (since it's only an optimization, this is OK). Errno %d (%s)\n", errno, strerror(errno));
}
if (madvise(mappedFile->map, mappedFile->length, MADV_WILLNEED)) {
WriteErrorMessage("madvise MADV_WILLNEED failed (since it's only an optimization, this is OK). Errno %d (%s)\n", errno, strerror(errno));
}
}
#ifdef __linux__
class PosixAsyncFile : public AsyncFile
{
public:
static PosixAsyncFile* open(const char* filename, bool write);
virtual bool close();
_int64 getSize();
class Writer : public AsyncFile::Writer
{
public:
Writer(PosixAsyncFile* i_file);
virtual bool close();
virtual bool beginWrite(void* buffer, size_t length, size_t offset, size_t *bytesWritten);
virtual bool waitForCompletion();
private:
PosixAsyncFile* file;
bool writing;
SingleWaiterObject ready;
struct aiocb aiocb;
size_t* result;
//
// The parameters of a write, which are used by launchWrite(). We need to keep
// them around because writes may not necessarily write all of the data in a single
// call, so we might have to start successive ones for very large IOs.
//
char* writeBuffer;
size_t bytesToWrite;
size_t writeOffset;
size_t bytesAlreadyWritten;
int writeErrno; // used to communicate any error from the completion routine to waitForCompletion()
bool launchWrite();
friend void sigev_ready_write(union sigval val);
void sigev_ready_called();
};
virtual AsyncFile::Writer* getWriter();
class Reader : public AsyncFile::Reader
{
public:
Reader(PosixAsyncFile* i_file);
virtual bool close();
virtual bool beginRead(void* buffer, size_t length, size_t offset, size_t *bytesRead);
virtual bool waitForCompletion();
private:
PosixAsyncFile* file;
bool reading;
SingleWaiterObject ready;
struct aiocb aiocb;
size_t* result;
size_t bytesToRead;
};
virtual AsyncFile::Reader* getReader();
private:
//
// We can open lots of handles to the same file, so in order to avoid exhausting the
// file descriptor space we keep a cache of them with reference counts.
//
static ExclusiveLock* cacheLock; // This starts out as null and then gets initialized using the interlocked swap trick
struct CacheEntry {
char* filename; // NULL indicates that this is an unused entry.
int referenceCount;
int fd;
bool write;
CacheEntry* next;
CacheEntry* prev;
void enqueue() {
prev = cache;
next = cache->next;
prev->next = this;
next->prev = this;
}
void dequeue()
{
prev->next = next;
next->prev = prev;
}
CacheEntry() : filename(NULL), referenceCount(0), fd(-1), write(false) {}
};
//
// We don't expect there to be too many open files, so we use an unordered list here.
//
static CacheEntry *cache; // This is the header of the linked list
struct CacheEntry* cacheEntry; // This is where our fd is
PosixAsyncFile(CacheEntry *i_cacheEntry);
};
PosixAsyncFile::CacheEntry *PosixAsyncFile::cache = NULL;
ExclusiveLock* PosixAsyncFile::cacheLock = NULL;
_int64
PosixAsyncFile::getSize()
{
struct stat statBuffer;
if (-1 == fstat(cacheEntry->fd, &statBuffer)) {
WriteErrorMessage("PosixAsyncFile: fstat failed, %d (%s)\n", errno, strerror(errno));
return -1;
}
return statBuffer.st_size;
}
PosixAsyncFile*
PosixAsyncFile::open(
const char* filename,
bool write)
{
if (cacheLock == NULL) {
ExclusiveLock* newLock = new ExclusiveLock();
InitializeExclusiveLock(newLock);
AcquireExclusiveLock(newLock);
if (NULL != InterlockedCompareExchangePointerAndReturnOldValue((void * volatile*)&cacheLock, newLock, NULL)) {
//
// Someone else beat us to it.
//
ReleaseExclusiveLock(newLock);
DestroyExclusiveLock(newLock);
delete newLock;
AcquireExclusiveLock(cacheLock);
} else {
cache = new CacheEntry;
cache->next = cache->prev = cache;
}
} else {
AcquireExclusiveLock(cacheLock);
}
//
// Scan the cache to see if we already have this. The cache is unsorted linear because we expect
// it to be small.
//
CacheEntry* cacheEntry = cache->next;
while (cacheEntry != cache && (cacheEntry->write != write || strcmp(cacheEntry->filename, filename))) {
cacheEntry = cacheEntry->next;
}
if (cacheEntry != cache) {
//
// Cache hit.
//
cacheEntry->referenceCount++;
ReleaseExclusiveLock(cacheLock);
return new PosixAsyncFile(cacheEntry);
}
//
// It's not in the cache, so make a new entry.
//
int fd = ::open(filename, write ? O_CREAT | O_RDWR | O_TRUNC : O_RDONLY, write ? S_IRWXU | S_IRGRP : 0);
if (fd < 0) {
ReleaseExclusiveLock(cacheLock);
WriteErrorMessage("Unable to open file '%s', %d (%s)\n", filename, errno, strerror(errno));
return NULL;
}
cacheEntry = new CacheEntry;
cacheEntry->fd = fd;
cacheEntry->filename = new char[strlen(filename) + 1];
strcpy(cacheEntry->filename, filename);
cacheEntry->write = write;
cacheEntry->referenceCount = 1;
cacheEntry->enqueue();
ReleaseExclusiveLock(cacheLock);
return new PosixAsyncFile(cacheEntry);
}
PosixAsyncFile::PosixAsyncFile(
CacheEntry *i_cacheEntry)
: cacheEntry(i_cacheEntry)
{
}
bool
PosixAsyncFile::close()
{
bool closeWorked = true;
AcquireExclusiveLock(cacheLock);
cacheEntry->referenceCount--;
if (cacheEntry->referenceCount == 0) {
cacheEntry->dequeue();
delete[] cacheEntry->filename;
closeWorked = ::close(cacheEntry->fd) == 0;
delete cacheEntry;
}
ReleaseExclusiveLock(cacheLock);
return closeWorked;
}
AsyncFile::Writer*
PosixAsyncFile::getWriter()
{
return new Writer(this);
}
PosixAsyncFile::Writer::Writer(PosixAsyncFile* i_file)
: file(i_file), writing(false)
{
memset(&aiocb, 0, sizeof(aiocb));
if (! CreateSingleWaiterObject(&ready)) {
WriteErrorMessage("PosixAsyncFile: cannot create waiter\n");
soft_exit(1);
}
}
bool
PosixAsyncFile::Writer::close()
{
waitForCompletion();
DestroySingleWaiterObject(&ready);
return true;
}
void
sigev_ready_read(union sigval val)
{
SignalSingleWaiterObject((SingleWaiterObject*)val.sival_ptr);
}
void
sigev_ready_write(
union sigval val)
{
PosixAsyncFile::Writer* writer = (PosixAsyncFile::Writer*)(val.sival_ptr);
writer->sigev_ready_called();
}
void
PosixAsyncFile::Writer::sigev_ready_called()
{
_ASSERT(writing);
ssize_t ret = aio_return(&aiocb);
if (ret < 0 && errno != 0) {
WriteErrorMessage("PosixAsyncFile Writer aio_return failed, errno %d (%s)\n", errno, strerror(errno));
writeErrno = errno;
}
bytesAlreadyWritten += ret;
if (bytesAlreadyWritten < bytesToWrite && ret >0) {
//
// We're not done, launch the next chunk of the write.
//
if (!launchWrite()) {
WriteErrorMessage("PosixAsyncFile::Writer::sigev_ready_called: launch of later portion of buffer failed. errno %d (%s)\n", errno, strerror(errno));
soft_exit(1);
}
} else {
SignalSingleWaiterObject(&ready);
}
} // PosixAsyncFile::Writer::sigev_ready_called
void
aio_setup(
struct aiocb* control,
void *sigval_ptr,
void (*callback)(union sigval),
int fd,
void* buffer,
size_t length,
size_t offset)
{
memset(control, 0, sizeof(control));
control->aio_fildes = fd;
control->aio_buf = buffer;
control->aio_nbytes = length;
control->aio_offset = offset;
control->aio_sigevent.sigev_notify = SIGEV_THREAD;
control->aio_sigevent.sigev_value.sival_ptr = sigval_ptr;
control->aio_sigevent.sigev_notify_function = callback;
}
bool
PosixAsyncFile::Writer::beginWrite(
void* buffer,
size_t length,
size_t offset,
size_t *bytesWritten)
{
if (! waitForCompletion()) {
return false;
}
result = bytesWritten;
writeBuffer = (char *)buffer; // We keep writeBuffer as a char * so that we can do math over it in case we get a partially completed write
bytesToWrite = length;
writeOffset = offset;
bytesAlreadyWritten = 0;
writeErrno = 0;
writing = true;
return launchWrite();
}
bool
PosixAsyncFile::Writer::launchWrite()
{
_ASSERT(writing);
aio_setup(&aiocb, this, sigev_ready_write, file->cacheEntry->fd, writeBuffer + bytesAlreadyWritten, bytesToWrite - bytesAlreadyWritten, writeOffset + bytesAlreadyWritten);
if (aio_write(&aiocb) < 0) {
warn("PosixAsyncFile aio_write failed");
return false;
}
return true;
}
bool
PosixAsyncFile::Writer::waitForCompletion()
{
if (writing) {
WaitForSingleWaiterObject(&ready);
ResetSingleWaiterObject(&ready);
writing = false;
if (result != NULL) {
*result = bytesAlreadyWritten;
}
if (writeErrno != 0) {
return false;
}
}
return true;
}
AsyncFile::Reader*
PosixAsyncFile::getReader()
{
return new Reader(this);
}
PosixAsyncFile::Reader::Reader(
PosixAsyncFile* i_file)
: file(i_file), reading(false)
{
memset(&aiocb, 0, sizeof(aiocb));
if (! CreateSingleWaiterObject(&ready)) {
WriteErrorMessage("PosixAsyncFile cannot create waiter\n");
soft_exit(1);
}
}
bool
PosixAsyncFile::Reader::close()
{
DestroySingleWaiterObject(&ready);
return true;
}
bool
PosixAsyncFile::Reader::beginRead(
void* buffer,
size_t length,
size_t offset,
size_t* bytesRead)
{
if (! waitForCompletion()) {
return false;
}
aio_setup(&aiocb, &ready, sigev_ready_read, file->cacheEntry->fd, buffer, length, offset);
result = bytesRead;
bytesToRead = length;
if (aio_read(&aiocb) < 0) {
warn("PosixAsyncFile Reader aio_read failed");
return false;
}
reading = true;
return true;
}
bool
PosixAsyncFile::Reader::waitForCompletion()
{
if (reading) {
WaitForSingleWaiterObject(&ready);
ResetSingleWaiterObject(&ready);
reading = false;
ssize_t ret = aio_return(&aiocb);
if (ret < 0 && errno != 0) {
WriteErrorMessage("PosixAsyncFile::Reader(0x%llx) aio_return returned %lld errno %d (%s) on fd %d, buffer 0x%llx\n", this, ret, errno, strerror(errno), aiocb.aio_fildes, aiocb.aio_buf);
return false;
}
if (result != NULL) {
*result = max((ssize_t)0, ret);
}
if (ret != bytesToRead) {
WriteErrorMessage(
"PosixAsyncFile::beginRead() launched a read that didn't get all of its bytes (it's probably too big). Please create a git issue to get the dev team to write this code. Requested size %lld, completed size %lld\n",
bytesToRead, ret);
soft_exit(1);
}
}
return true;
}
#else
// todo: make this actually async!
class OsxAsyncFile : public AsyncFile
{
public:
static OsxAsyncFile* open(const char* filename, bool write);
OsxAsyncFile(int i_fd);
_int64 getSize();
virtual bool close();
class Writer : public AsyncFile::Writer
{
public:
Writer(OsxAsyncFile* i_file);
virtual bool close();
virtual bool beginWrite(void* buffer, size_t length, size_t offset, size_t *bytesWritten);
virtual bool waitForCompletion();
private:
OsxAsyncFile* file;
bool writing;
SingleWaiterObject ready;
struct aiocb aiocb;
size_t* result;
};
virtual AsyncFile::Writer* getWriter();
class Reader : public AsyncFile::Reader
{
public:
Reader(OsxAsyncFile* i_file);
virtual bool close();
virtual bool beginRead(void* buffer, size_t length, size_t offset, size_t *bytesRead);
virtual bool waitForCompletion();
private:
OsxAsyncFile* file;
bool reading;
size_t* result;
};
virtual AsyncFile::Reader* getReader();
private:
int fd;
ExclusiveLock lock;
};
_int64
OsxAsyncFile::getSize()
{
struct stat statBuffer;
if (-1 == ::fstat(fd, &statBuffer)) {
WriteErrorMessage("OsxAsyncFile: fstat failed, %d\n", errno);
return -1;
}
return statBuffer.st_size;
}
OsxAsyncFile*
OsxAsyncFile::open(
const char* filename,
bool write)
{
int fd = ::open(filename, write ? O_CREAT | O_RDWR | O_TRUNC : O_RDONLY, write ? S_IRWXU | S_IRGRP : 0);
if (fd < 0) {
WriteErrorMessage("Unable to create SAM file '%s', %d\n",filename,errno);
return NULL;
}
return new OsxAsyncFile(fd);
}
OsxAsyncFile::OsxAsyncFile(
int i_fd)
: fd(i_fd)
{
InitializeExclusiveLock(&lock);
}
bool
OsxAsyncFile::close()
{
DestroyExclusiveLock(&lock);
return ::close(fd) == 0;
}
AsyncFile::Writer*
OsxAsyncFile::getWriter()
{
return new Writer(this);
}
OsxAsyncFile::Writer::Writer(OsxAsyncFile* i_file)
: file(i_file), writing(false)
{
}
bool
OsxAsyncFile::Writer::close()
{
return true;
}
bool
OsxAsyncFile::Writer::beginWrite(
void* buffer,
size_t length,
size_t offset,
size_t *bytesWritten)
{
AcquireExclusiveLock(&file->lock);
size_t m = ::lseek(file->fd, offset, SEEK_SET);
if (m == -1) {
return false;
}
size_t n = ::write(file->fd, buffer, length);
if (bytesWritten) {
*bytesWritten = n;
}
ReleaseExclusiveLock(&file->lock);
return n != -1;
}
bool
OsxAsyncFile::Writer::waitForCompletion()
{
return true;
}
AsyncFile::Reader*
OsxAsyncFile::getReader()
{
return new Reader(this);
}
OsxAsyncFile::Reader::Reader(
OsxAsyncFile* i_file)
: file(i_file), reading(false)
{
}
bool
OsxAsyncFile::Reader::close()
{
return true;
}
bool
OsxAsyncFile::Reader::beginRead(
void* buffer,
size_t length,
size_t offset,
size_t* bytesRead)
{
AcquireExclusiveLock(&file->lock);
size_t m = ::lseek(file->fd, offset, SEEK_SET);
if (m == -1) {
return false;
}
size_t n = ::read(file->fd, buffer, length);
if (bytesRead) {
*bytesRead = n;
}
ReleaseExclusiveLock(&file->lock);
return n != -1;
}
bool
OsxAsyncFile::Reader::waitForCompletion()
{
return true;
}
#endif
int _fseek64bit(FILE *stream, _int64 offset, int origin)
{
#ifdef __APPLE__
// Apple's file pointers are already 64-bit so just use fseeko.
fseeko(stream, offset, origin);
#else
return fseeko64(stream, offset, origin);
#endif
}
FileMapper::FileMapper()
{
fd = -1;
initialized = false;
mapCount = 0;
pagesize = getpagesize();
}
bool
FileMapper::init(const char *i_fileName)
{
if (initialized) {
if (strcmp(fileName, i_fileName)) {
WriteErrorMessage("FileMapper already initialized with %s, cannot init with %s\n", fileName, i_fileName);
return false;
}
return true;
}
fileName = i_fileName;
fd = open(fileName, O_RDONLY);
if (fd == -1) {
WriteErrorMessage("Failed to open %s\n", fileName);
return false;
}
struct stat sb;
int r = fstat(fd, &sb);
if (r == -1) {
WriteErrorMessage("Failed to stat %s\n", fileName);
return false;
}
fileSize = sb.st_size;
initialized = true;
return true;
}
char *
FileMapper::createMapping(size_t offset, size_t amountToMap, void** o_token)
{
size_t beginRounding = offset % pagesize;
size_t mapRequestSize = beginRounding + amountToMap;
//_ASSERT(mapRequestSize % pagesize == 0);
if (mapRequestSize + offset >= fileSize) {
mapRequestSize = 0; // Says to just map the whole thing.
}
char* mappedBase = (char *) mmap(NULL, amountToMap + beginRounding, PROT_READ, MAP_SHARED, fd, offset - beginRounding);
if (mappedBase == MAP_FAILED) {
WriteErrorMessage("mmap failed.\n");
return NULL;
}
int r = madvise(mappedBase, min((size_t) madviseSize, amountToMap + beginRounding), MADV_WILLNEED | MADV_SEQUENTIAL);
_ASSERT(r == 0);
lastPosMadvised = 0;
InterlockedIncrementAndReturnNewValue(&mapCount);
*o_token = new UnmapToken(mappedBase, amountToMap);
return mappedBase + beginRounding;
}
void
FileMapper::unmap(void* i_token)
{
_ASSERT(mapCount > 0);
if (mapCount > 0) {
int n = InterlockedDecrementAndReturnNewValue(&mapCount);
_ASSERT(n >= 0);
UnmapToken* token = (UnmapToken*) i_token;
munmap(token->first, token->second);
delete token;
}
}
FileMapper::~FileMapper()
{
_ASSERT(mapCount == 0);
close(fd);
}
#if 0
void
FileMapper::prefetch(size_t currentRead)
{
if (currentRead > lastPosMadvised + madviseSize / 2) {
_uint64 offset = lastPosMadvised + madviseSize;
_uint64 len = (offset > amountMapped ? 0 : min(amountMapped - offset, (_uint64) madviseSize));
if (len > 0) {
// Start reading new range
int r = madvise(mappedBase + offset, len, MADV_WILLNEED);
_ASSERT(r == 0);
}
if (lastPosMadvised > 0) {
// Unload the range we had before our current one
int r = madvise(mappedBase + lastPosMadvised - madviseSize, madviseSize, MADV_DONTNEED);
_ASSERT(r == 0);
}
lastPosMadvised = offset;
}
}
#endif
void PreventMachineHibernationWhileThisThreadIsAlive()
{
// Only implemented for Windows
}
void SetToLowSchedulingPriority()
{
// Only implemented for Windows (the Linux version is per-thread, and I'm too lazy to do it now).
WriteErrorMessage("The Linux code for running at low priority is not implemented, so SNAP will run at normal priority\n");
}
//
// Linux named pipes are unidirectional, so we need two of them.
//
struct NamedPipe {
bool serverSide;
char * pipeName;
FILE * input;
FILE * output;
};
bool createPipe(const char *fullyQualifiedPipeName)
{
if (mkfifo(fullyQualifiedPipeName, S_IRUSR | S_IWUSR)) {
if (errno != EEXIST) {
if (errno == ENOENT) {
WriteErrorMessage("OpenNamedPipe: unable to create named pipe at path '%s' because a directory in the path doesn't exist. Please create it or use a different pipe name\n", fullyQualifiedPipeName);
return false;
}
if (errno == EACCES) {
WriteErrorMessage("OpenNamedPipe: unable to create named pipe at path '%s' because you do not have sufficient permissions.\n", fullyQualifiedPipeName);
return false;
}
if (errno == ENOTDIR) {
WriteErrorMessage("OpenNamedPipe: a component of your pipe path isn't a directory. '%s'\n", fullyQualifiedPipeName);
return false;
}
WriteErrorMessage("OpenNamedPipe: unexpectedly failed to create named pipe '%s', errno %d (%s)\n", fullyQualifiedPipeName, errno, strerror(errno));
return false;
}
}
return true;
}
FILE *connectPipe(char *fullyQualifiedPipeName, bool forInput)
{
FILE *pipeFile = fopen(fullyQualifiedPipeName, forInput ? "r" : "w");
if (NULL == pipeFile) {
WriteErrorMessage("OpenNamedPipe: unable to open pipe file '%s', errno %d (%s)\n", fullyQualifiedPipeName, errno, strerror(errno));
}
return pipeFile;
}
char *createFullyQualifiedPipeName(const char *pipeName, bool serverSide, bool forInput)
{
char *fullyQualifiedPipeName;
const char *defaultPipeDirectory = "/tmp/";
const char *pipeDirectory;
const char *toServer = "-toServer";
const char *toClient = "-toClient";
if (pipeName[0] != '/') {
pipeDirectory = defaultPipeDirectory;
} else {
pipeDirectory = "";
}
fullyQualifiedPipeName = new char[strlen(pipeDirectory) + strlen(pipeName) + __max(strlen(toServer), strlen(toClient)) + 1]; // +1 for trailing null
sprintf(fullyQualifiedPipeName, "%s%s%s", pipeDirectory, pipeName, (serverSide == forInput) ? toServer : toClient);
return fullyQualifiedPipeName;
}
bool connectNamedPipes(NamedPipe *pipe)
{
char *inputPipeName = createFullyQualifiedPipeName(pipe->pipeName, pipe->serverSide, true);
char *outputPipeName = createFullyQualifiedPipeName(pipe->pipeName, pipe->serverSide, false);
if (pipe->input != NULL) {
fclose(pipe->input);
pipe->input = NULL;
}
if (pipe->output != NULL) {
fclose(pipe->output);
pipe->output = NULL;
}
//
// Connecting pipes is synchronous, so the server and client need to connect
// in opposite order.
//
if (pipe->serverSide) {
signal(SIGPIPE, SIG_IGN);// If the client hits ^C, we'll get this. Ignore it, let the fwrite fail, and continue
pipe->input = connectPipe(inputPipeName, true);
pipe->output = connectPipe(outputPipeName, false);
//
// Release any exclusive lock on the toServer pipe that may have been left by a now-dead client
//
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 1;
lock.l_pid = 0;
if (fcntl(fileno(pipe->output), F_SETLKW, &lock) < 0) {
fprintf(stderr,"Unable to clear named pipe lock, errno %d (%s)\n", errno, strerror(errno));
delete pipe;
return NULL;
}
} else {
pipe->output = connectPipe(outputPipeName, false);
pipe->input = connectPipe(inputPipeName, true);
}
delete [] inputPipeName;
delete [] outputPipeName;
return pipe->input != NULL && pipe->output != NULL;
}
NamedPipe *OpenNamedPipe(const char *pipeName, bool serverSide)
{
char *inputPipeName = createFullyQualifiedPipeName(pipeName, serverSide, true);
char *outputPipeName = createFullyQualifiedPipeName(pipeName, serverSide, false);
NamedPipe *pipe = new NamedPipe;
pipe->pipeName = new char[strlen(pipeName) + 1];
strcpy(pipe->pipeName, pipeName);
pipe->input = pipe->output = NULL;
pipe->serverSide = serverSide;
if (serverSide) {
if (!createPipe(inputPipeName)) {
delete pipe;
return NULL;
}
if (!createPipe(outputPipeName)) {
delete pipe;
return NULL;
}
}
delete [] inputPipeName;
delete [] outputPipeName;
if (!connectNamedPipes(pipe)) {
delete pipe;
return NULL;
}
if (!serverSide) {
//
// Take an exclusive lock on the toServer pipe so that only one client is sending at a time.
//
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 1;
lock.l_pid = 0;
if (fcntl(fileno(pipe->output), F_SETLKW, &lock) < 0) {
fprintf(stderr,"OpenNamedPipe: F_SETLKW failed, errno %d (%s)\n", errno, strerror(errno));
delete pipe;
return NULL;
}
}
return pipe;
}
//
// Our Linux version of named pipe IO sends strings with 4 byte byte counts first.
//
bool ReadFromNamedPipe(NamedPipe *pipe, char *outputBuffer, size_t outputBufferSize)
{
unsigned int size;
for (;;) {
if (1 != fread(&size, sizeof(size), 1, pipe->input)) {
if (!pipe->serverSide) {
return false;
}
if (!connectNamedPipes(pipe)) {
return false;
}
continue;
}
if (size >= outputBufferSize) {
WriteErrorMessage("Trying to read too big a chunk from named pipe, %d >= %lld\n", size, outputBufferSize);
return false;
}
if (1 != fread(outputBuffer, size, 1, pipe->input)) {
if (!pipe->serverSide) {
return false;
}
if (!connectNamedPipes(pipe)) {
return false;
}
continue;
}
break;
}
outputBuffer[size] = '\0';
return true;
}
bool WriteToNamedPipe(NamedPipe *pipe, const char *stringToWrite)
{
unsigned int size = (unsigned int)strlen(stringToWrite);
if (1 != fwrite(&size, sizeof(size), 1, pipe->output)) {
return false;
}
if (1 != fwrite(stringToWrite, size, 1, pipe->output)) {
return false;
}
fflush(pipe->output);
return true;
}
void CloseNamedPipe(NamedPipe *pipe)
{
fclose(pipe->input);
fclose(pipe->output);
delete pipe;
}
const char *DEFAULT_NAMED_PIPE_NAME = "SNAP";
#endif // _MSC_VER
AsyncFile* AsyncFile::open(const char* filename, bool write)
{
if (!strcmp("-", filename) && write) {
return StdoutAsyncFile::open("-", true);
}
#ifdef _MSC_VER
return WindowsAsyncFile::open(filename, write);
#else
#ifdef __linux__
return PosixAsyncFile::open(filename, write);
#else
return OsxAsyncFile::open(filename, write);
#endif
#endif
}
|