Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 6250 lines (5659 sloc) 216.185 kb
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 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249
// -*- mode: C; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
// vim: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:

/*************************************************************************
* Copyright 2009-2012 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
************************************************************************/

//!
//! @file storage/blobstore.c
//! Implements blobstore storage
//!

/*----------------------------------------------------------------------------*\
| |
| INCLUDES |
| |
\*----------------------------------------------------------------------------*/

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h> // close
#include <time.h> // time
#include <sys/time.h> // gettimeofday
#include <sys/stat.h> // mkdir
#include <errno.h> // errno
#include <sys/types.h> // *dir, etc, wait
#include <sys/file.h> // flock
#include <dirent.h>
#include <sys/wait.h> // wait
#include <pthread.h>
#include <sys/types.h> // gettid
#include <regex.h>
#include <libgen.h> // basename

#include <eucalyptus.h> // euca user
#include <misc.h> // ensure_...
#include <ipc.h>
#include <euca_string.h>

#include "blobstore.h"
#include "diskutil.h"

#ifdef _EUCA_BLOBS
#include "map.h"
#endif /* _EUCA_BLOBS */

/*----------------------------------------------------------------------------*\
| |
| DEFINES |
| |
\*----------------------------------------------------------------------------*/

#define BLOBSTORE_METADATA_FILE ".blobstore"
#define BLOBSTORE_METADATA_TIMEOUT_USEC (1000000LL * 60 * 2) //!< it may take dozens of seconds to open blobstore when others are LRU-purging it
#define BLOBSTORE_LOCK_TIMEOUT_USEC 500000LL
#define BLOBSTORE_FIND_TIMEOUT_USEC 50000LL
#define BLOBSTORE_DELETE_TIMEOUT_USEC 50000LL
#define BLOBSTORE_SLEEP_INTERVAL_USEC 99999LL
#define BLOBSTORE_DMSETUP_TIMEOUT_SEC 60
#define BLOBSTORE_MAX_CONCURRENT 99
#define BLOBSTORE_NO_TIMEOUT -1L
#define BLOBSTORE_SIG_MAX 262144
#define DM_PATH "/dev/mapper/"
#define DM_FORMAT DM_PATH "%s" //!< @TODO do not hardcode?
#define MIN_BLOCKS_SNAPSHOT 32 //!< otherwise dmsetup fails with device-mapper: reload ioctl failed: Cannot allocate memory OR device-mapper: reload ioctl failed: Input/output error
#define EUCA_ZERO "euca-zero"
#define EUCA_ZERO_SIZE "2199023255552" //!< is one petabyte enough?

#define __INLINE__ __inline__

#ifdef _UNIT_TEST
#define F1 "/tmp/blobstore_test_1"
#define F2 "/tmp/blobstore_test_2"
#define F3 "/tmp/blobstore_test_3"

#define _R BLOBSTORE_FLAG_RDONLY
#define _W BLOBSTORE_FLAG_RDWR
#define _C (BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_EXCL | BLOBSTORE_FLAG_RDWR)
#define _CBB (BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_EXCL)

#define B1 "BLOCKBLOB-01"
#define B2 "BLOCKBLOB-02"
#define B3 "BLOCKBLOB-03"
#define B4 "BLOCKBLOB-04"
#define B5 "BLOCKBLOB-05"
#define B6 "BLOCKBLOB-06"

#define BS_SIZE 30
#define BB_SIZE 10
#define CBB_SIZE 32
#define STRESS_BS_SIZE 100000
#define STRESS_MIN_BB 64
#define STRESS_BLOBS 10

#define LOCK_CYCLES 3
#define COMPETITIVE_PARTICIPANTS 3
#define COMPETITIVE_ITERATIONS 30
#define COMPETITIVE_PAUSE_USEC 5
#define COMPETITIVE_TIMEOUT_USEC 3000000L
#endif /* _UNIT_TEST */

#ifdef _EUCA_BLOBS
#define USAGE "Usage: euca-blobs [cache=... work=...] command [param1] [param2]...\n"
#define HELP "\n" \
"\thelp\t\t- print this help message\n" \
"\tlist\t\t- list blobs in work and cache\n" \
"\tdelete [id]\t- delete blob with\n"
#define MAX_ARGS 5
#endif /* _EUCA_BLOBS */

/*----------------------------------------------------------------------------*\
| |
| TYPEDEFS |
| |
\*----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*\
| |
| ENUMERATIONS |
| |
\*----------------------------------------------------------------------------*/

// if changing, change the array below and set_blockblob_metadata_path()
typedef enum { //!< paths to files containing...
    BLOCKBLOB_PATH_NONE = 0, //!< sentinel for identifying files that are not blockblob related
    BLOCKBLOB_PATH_BLOCKS, //!< ...blocks, either in flat format or as a snapshot backing
    BLOCKBLOB_PATH_LOCK, //!< ...nothing, but needed for safe locking of access to the blob
    BLOCKBLOB_PATH_DM, //!< ...device mapper devices created for this clone, if any
    BLOCKBLOB_PATH_DEPS, //!< ...names of blockblobs that this blockblob depends on, if any
    BLOCKBLOB_PATH_LOOPBACK, //!< ...name of the loopback device for this blob, when attached
    BLOCKBLOB_PATH_SIG, //!< ...signature of the blob, if provided from outside
    BLOCKBLOB_PATH_REFS, //!< ...names of blockblobs that depend on this blockblob, if any
    BLOCKBLOB_PATH_HOLLOW, //!< ...nothing, but the file acts as a marker of 'hollow' blobs
    BLOCKBLOB_PATH_TOTAL,
} blockblob_path_t;

enum {
    DMSETUP,
    ROOTWRAP,
    LASTHELPER,
};

/*----------------------------------------------------------------------------*\
| |
| STRUCTURES |
| |
\*----------------------------------------------------------------------------*/

typedef struct _blobstore_filelock {
    char path[PATH_MAX]; //!< path that the file was open with @TODO canonicalize?
    int refs; //!< number of open file descriptors (some holding the lock, some waiting) for this path in this process
    int next_fd; //!< next available file descriptor in the table below:
    int fd[BLOBSTORE_MAX_CONCURRENT];
    int fd_status[BLOBSTORE_MAX_CONCURRENT]; //!< 0 = unused, 1 = open
#ifdef _TEST_FILELOCK
    unsigned int thread_id[BLOBSTORE_MAX_CONCURRENT];
#endif /* _TEST_FILELOCK */
    pthread_rwlock_t lock; //!< reader/writer lock for controlling intra-process access
    pthread_mutex_t mutex; //!< for locking this specific struct during manipulations
    sem *sem; //!< semaphore for debugging
    struct _blobstore_filelock *next; //!< pointer for constructing a LL
} blobstore_filelock;

/*----------------------------------------------------------------------------*\
| |
| EXTERNAL VARIABLES |
| |
\*----------------------------------------------------------------------------*/

/* Should preferably be handled in header file */

/*----------------------------------------------------------------------------*\
| |
| GLOBAL VARIABLES |
| |
\*----------------------------------------------------------------------------*/

//! Blobstore errors matching strings. Make sure these match up with blobstore_error_t enums above
const char *_blobstore_error_strings[] = {
    "success",
    "general error",

    // system errno equivalents
    "no such entity",
    "bad file descriptor",
    "out of memory",
    "permission denied",
    "already exists",
    "invalid parameters",
    "no space left",
    "timeout",
    "too many files open",

    // blobstore-specific errors
    "wrong signature",
    "unknown error",
};

const char *blobstore_relation_type_name[] = {
    "copy",
    "map",
    "snapshot",
};

__thread blobstore_error_t _blobstore_errno = BLOBSTORE_ERROR_OK; //!< thread-local errno

/*----------------------------------------------------------------------------*\
| |
| STATIC VARIABLES |
| |
\*----------------------------------------------------------------------------*/

// entries must match the ones in enum above
static const char *blobstore_metadata_suffixes[] = {
    "none", // sentinel entry so that all actual entries have indeces > 0
    "blocks", // MUST be second so loop in check_metadata_name() works
    "lock",
    "dm",
    "deps",
    "loopback",
    "sig",
    "refs",
    "hollow",
};

static void (*err_fn) (const char *msg) = NULL;
static unsigned char _do_print_errors = 1;
static unsigned char _do_print_trace = 1;
static pthread_mutex_t _blobstore_mutex = PTHREAD_MUTEX_INITIALIZER; //!< process-global mutex
static blobstore_filelock *locks_list = NULL; //!< process-global LL head @TODO replace this with a hash table

//! @{
//! @name debugging counters
//! @TODO remove these
static long _locks_list_add_ctr = 0L;
static long _locks_list_rem_ctr = 0L;
static long _open_success_ctr = 0L;
static long _close_success_ctr = 0L;
static long _open_error_ctr = 0L;
static long _open_timeout_ctr = 0L;
static long _close_error_ctr = 0L;
static char zero_buf[1] = "\0";
//! @}

static __thread char _blobstore_last_msg[512] = "";
static __thread char _blobstore_last_trace[8172] = "";

static char *helpers[LASTHELPER] = {
    "dmsetup",
    "euca_rootwrap",
};

static char *helpers_path[LASTHELPER];
static int initialized = 0;

#ifdef _UNIT_TEST
static char *_farray[] = { F1, F2, F3 };
#endif /* _UNIT_TEST */

#ifdef _EUCA_BLOBS
static char show_debug = FALSE;
static char show_extras = FALSE;
static char show_children = FALSE;
static char show_parents = FALSE;
static char *euca_home = NULL;
static char *work_path = NULL;
static char *cache_path = NULL;
static blobstore *work_bs = NULL;
static blobstore *cache_bs = NULL;
static map *blob_map;
#endif /* _EUCA_BLOBS */

/*----------------------------------------------------------------------------*\
| |
| STATIC PROTOTYPES |
| |
\*----------------------------------------------------------------------------*/

static void myprintf(int loglevel, const char *format, ...);
static __INLINE__ void _err_on(void);
static __INLINE__ void _err_off(void);
static void err(blobstore_error_t error, const char *custom_msg, const int src_line_no, const char *src_file_name);
static __INLINE__ void propagate_system_errno(blobstore_error_t default_errno, const int src_line_no, const char *src_file_name);
static void gen_id(char *str, unsigned int size);
static void close_filelock(blobstore_filelock * l);
static void free_filelock(blobstore_filelock * l);
static int close_and_unlock(int fd);
#ifdef _TEST_LOCKS
static char *path_to_sem_name(const char *path, char *name, int name_size);
#endif /* _TEST_LOCKS */
static int open_and_lock(const char *path, int flags, long long timeout_usec, mode_t mode);
static char *get_val(const char *buf, const char *key);
static int fd_to_buf(int fd, char *buf, int size_buf);
static int buf_to_fd(int fd, const char *buf, int size_buf);
static int read_store_metadata(blobstore * bs);
static int write_store_metadata(blobstore * bs);
static int set_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char *path, size_t path_size);
static int write_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, const char *str);
static int read_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char *str, int str_size);
static int write_array_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char **array, int array_size);
static int read_array_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char ***array, int *array_size);
static int update_entry_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, const char *entry, int removing);
static int typeof_blockblob_metadata_path(const blobstore * bs, const char *path, char *bb_id, unsigned int bb_id_size);
static int delete_blockblob_files(const blobstore * bs, const char *bb_id);
static int ensure_blockblob_metadata_path(const blobstore * bs, const char *bb_id);
static void free_bbs(blockblob * bbs);
static unsigned int check_in_use(blobstore * bs, const char *bb_id, long long timeout_usec);
static void set_device_path(blockblob * bb);
static blockblob **walk_bs(blobstore * bs, const char *dir_path, blockblob ** tail_bb, const blockblob * bb_to_avoid);
static blockblob *scan_blobstore(blobstore * bs, const blockblob * bb_to_avoid);
static int compare_bbs(const void *bb1, const void *bb2);
static long long purge_blockblobs_lru(blobstore * bs, blockblob * bb_list, long long need_blocks);
static int get_stale_refs(const blockblob * bb, char ***refs);
static int loop_remove(blobstore * bs, const char *bb_id);
static int dm_suspend_resume(const char *dev_name);
static int dm_check_device(const char *dev_name);
static int dm_delete_device(const char *dev_name);
static int dm_delete_devices(char *dev_names[], int size);
static int dm_create_devices(char *dev_names[], char *dm_tables[], int size);
static char *dm_get_zero(void);
static int blockblob_check(const blockblob * bb);
static int delete_blob_state(blockblob * bb, long long timeout_usec, char do_force);
static int verify_bb(const blockblob * bb, unsigned long long min_size_bytes);

#ifdef _UNIT_TEST
static void _fill_blob(blockblob * bb, char c, int use_file);
static blobstore *create_teststore(int size_blocks, const char *base, const char *name, blobstore_format_t format, blobstore_revocation_t revocation,
                                   blobstore_snapshot_t snapshot);
static int write_byte(blockblob * bb, int seek, char c);
static char read_byte(blockblob * bb, int seek);
static int do_clone_stresstest(const char *base, const char *name, blobstore_format_t format, blobstore_revocation_t revocation, blobstore_snapshot_t snapshot);
static int check_destination(blockblob * bb4, char *op);
static int do_copy_test(const char *base, const char *name);
static int do_clone_test(const char *base, const char *name, blobstore_format_t format, blobstore_revocation_t revocation, blobstore_snapshot_t snapshot, int copy_or_snapshot);
static int do_metadata_test(const char *base, const char *name);
static int do_blobstore_test(const char *base, const char *name, blobstore_format_t format, blobstore_revocation_t revocation);
static void *competitor_function(void *ptr);
static void *thread_function(void *ptr);
static void dummy_err_fn(const char *msg);
#endif /* _UNIT_TEST */

#ifdef _EUCA_BLOBS
static void bs_errors(const char *msg);
static int open_blobstore(const char *path, blobstore ** bs, const char *name);
static int open_blobstores();
static void close_blobstores();
static int do_list_bs(blobstore * bs, const char *regex);
static void print_tree(const char *prefix, blockblob_meta * bm, blockblob_path_t type);
static int do_list(const char *regex);
static int do_delete(const char *id);
static void usage(const char *msg);
static void set_global_parameter(char *key, char *val);
#endif /* _EUCA_BLOBS */

/*----------------------------------------------------------------------------*\
| |
| MACROS |
| |
\*----------------------------------------------------------------------------*/

#define ERR(_ERRNO,_MSG) err(_ERRNO, _MSG, __LINE__, __FILE__)

#define PROPAGATE_ERR(_ERRNO) propagate_system_errno(_ERRNO, __LINE__, __FILE__)

#ifdef _UNIT_TEST
#define _UNEXPECTED() printf ("======================> UNEXPECTED RESULT (errors=%d)!!!\n", ++errors);

#define _CHKMETA(_ST, _RE) \
{ \
snprintf(entry_path, sizeof(entry_path), "%s/%s", bs->path, _ST); \
if (_RE != typeof_blockblob_metadata_path(bs, entry_path, blob_id, sizeof(blob_id))) \
_UNEXPECTED(); \
}

#define _OPEN(_FD, _FI, _FL, _TI, _RE) \
{ \
_blobstore_errno = 0; \
printf("%d: open (" _FI " flags=%d timeout=%d)", getpid(), _FL, _TI); \
_FD = open_and_lock(_FI, _FL, _TI, BLOBSTORE_FILE_PERM); \
printf("=%d errno=%d '%s'\n", _FD, _blobstore_errno, blobstore_get_error_str(_blobstore_errno)); \
if ((_FD == -1) && (_blobstore_errno == 0)) \
printf("======================> UNSET errno ON ERROR (errors=%d)!!!\n", ++errors); \
else if (((_RE == -1) && (_FD != -1)) || ((_RE == 0) && (_FD < 0))) \
_UNEXPECTED(); \
}

#define _CLOS(_FD, _FI) \
{ \
ret = close_and_unlock(_FD); \
printf("%d: close (%d " _FI ")=%d\n", getpid(), _FD, ret); \
}

#define _PARENT_WAITS() \
{ \
int status = 0; \
int ret = 0; \
printf("waiting for child pid=%d\n", pid); \
ret = wait(&status); \
printf("waited for child pid=%d ret=%d\n", ret, WEXITSTATUS(status)); \
errors += WEXITSTATUS(status); \
}

#define _OPENBB(_BB, _ID, _SI, _SG, _FL, _TI, _RE) \
{ \
_blobstore_errno = 0; \
printf("%d: bb_open (%s size=%d flags=%d timeout=%d)", getpid(), SP(_ID), _SI, _FL, _TI); \
_BB = blockblob_open(bs, _ID, (_SI) * 512, _FL, _SG, _TI); \
printf("=%s errno=%d '%s'\n", ((_BB == NULL) ? ("NULL") : ("OK")), _blobstore_errno, blobstore_get_error_str(_blobstore_errno)); \
if ((_BB == NULL) && (_blobstore_errno == 0)) \
printf("======================> UNSET errno ON ERROR (errors=%d)!!!\n", ++errors); \
else if (((_RE == -1) && (_BB != NULL)) || ((_RE == 0) && (_BB == NULL))) \
_UNEXPECTED(); \
}

// same as _OPENBB but accepts bytes rather than blocks
#define _OPENBBb(_BB, _ID, _SI, _SG, _FL, _TI, _RE) \
{ \
_blobstore_errno = 0; \
printf("%d: bb_open (%s size=%d flags=%d timeout=%d)", getpid(), SP(_ID), _SI, _FL, _TI); \
_BB = blockblob_open(bs, _ID, _SI, _FL, _SG, _TI); \
printf("=%s errno=%d '%s'\n", ((_BB == NULL) ? ("NULL") : ("OK")), _blobstore_errno, blobstore_get_error_str(_blobstore_errno)); \
if ((_BB == NULL) && (_blobstore_errno == 0)) \
printf("======================> UNSET errno ON ERROR (errors=%d)!!!\n", ++errors); \
else if (((_RE == -1) && (_BB != NULL)) || ((_RE == 0) && (_BB == NULL))) \
_UNEXPECTED(); \
}

#define _SEARCH(_PATTERN, _RE) \
{ \
results = NULL; \
printf("%d: bs_search (pattern=%s)", getpid(), _PATTERN); \
nresults = blobstore_search (bs, _PATTERN, &results); \
printf("=%d (expected %d) errno=%d '%s'\n", nresults, _RE, _blobstore_errno, blobstore_get_error_str(_blobstore_errno)); \
if ((nresults < 0) && (_blobstore_errno == 0)) \
printf("======================> UNSET errno ON ERROR (errors=%d)!!!\n", ++errors); \
else if (_RE != nresults) \
_UNEXPECTED(); \
for (blockblob_meta * bm = results; bm;) { \
blockblob_meta * next = bm->next; \
EUCA_FREE(bm); \
bm = next; \
} \
}

#define _CLOSBB(_BB, _ID) \
{ \
ret = blockblob_close(_BB); \
printf("%d: bb_close (%lu %s)=%d errno=%d '%s'\n", \
getpid(), ((unsigned long) _BB), SP(_ID), ret, _blobstore_errno, \
blobstore_get_error_str(_blobstore_errno)); \
}

#define _DELEBB(_BB, _ID, _RE) \
{ \
ret = blockblob_delete(_BB, 3000, 0); \
printf("%d: bb_delete (%lu %s)=%d errno=%d '%s'\n", \
getpid(), ((unsigned long) _BB), SP(_ID), ret, _blobstore_errno, \
blobstore_get_error_str(_blobstore_errno)); \
if (ret != _RE) \
_UNEXPECTED(); \
}

#define _CLONBB(_BB, _ID, _MP, _RE) \
{ \
_blobstore_errno = 0; \
printf("%d: bb_clone (%s map=%lu)", getpid(), SP(_ID), ((unsigned long) _MP)); \
ret = blockblob_clone(_BB, _MP, (sizeof(_MP) / sizeof(blockmap))); \
printf("=%d errno=%d '%s'\n", ret, _blobstore_errno, blobstore_get_error_str(_blobstore_errno)); \
if ((ret == -1) && (_blobstore_errno == 0)) \
printf("======================> UNSET errno ON ERROR (errors=%d)!!!\n", ++errors); \
else if (_RE != ret) \
_UNEXPECTED(); \
}

#define _COPYBB(_SBB, _SO, _DBB, _DO, _LEN, _RE) \
{ \
_blobstore_errno = 0; \
printf("%d: bb_copy (%s to %s)", getpid(), (_SBB)->id, (_DBB)->id); \
ret = blockblob_copy(_SBB, _SO, _DBB, _DO, _LEN); \
printf("=%d errno=%d '%s'\n", ret, _blobstore_errno, blobstore_get_error_str(_blobstore_errno)); \
if ((ret == -1) && (_blobstore_errno == 0)) \
printf("======================> UNSET errno ON ERROR (errors=%d)!!!\n", ++errors); \
else if (_RE != ret) \
_UNEXPECTED(); \
}
#endif /* _UNIT_TEST */

/*----------------------------------------------------------------------------*\
| |
| IMPLEMENTATION |
| |
\*----------------------------------------------------------------------------*/

//!
//!
//!
//! @param[in] loglevel
//! @param[in] format
//!
//! @pre
//!
//! @note
//!
static void myprintf(int loglevel, const char *format, ...)
{
    char buf[1024];

    va_list ap;
    va_start(ap, format);
    vsnprintf(buf, sizeof(buf), format, ap);
    va_end(ap);

    if (err_fn)
        err_fn(buf);
    else
        puts(buf);
}

//!
//!
//!
//! @param[in] error
//!
//! @return
//!
//! @pre
//!
//! @note
//!
const char *blobstore_get_error_str(blobstore_error_t error)
{
    return _blobstore_error_strings[error];
}

//!
//!
//!
//! @return
//!
//! @pre
//!
//! @note
//!
const char *blobstore_get_last_msg(void)
{
    return _blobstore_last_msg;
}

//!
//!
//!
//! @return
//!
//! @pre
//!
//! @note
//!
const char *blobstore_get_last_trace(void)
{
    return _blobstore_last_trace;
}

//!
//!
//!
//! @note
//!
static __INLINE__ void _err_on(void)
{
    _do_print_errors = 1;
}

//!
//!
//!
//! @note
//!
static __INLINE__ void _err_off(void)
{
    _do_print_errors = 0;
}

//!
//!
//!
//! @param[in] error
//! @param[in] custom_msg
//! @param[in] src_line_no
//! @param[in] src_file_name
//!
//! @pre
//!
//! @note
//!
static void err(blobstore_error_t error, const char *custom_msg, const int src_line_no, const char *src_file_name)
{
    const char *msg = custom_msg;
    if (msg == NULL) {
        msg = blobstore_get_error_str(error);
    }
    snprintf(_blobstore_last_msg, sizeof(_blobstore_last_msg), "%s:%d %s", src_file_name, src_line_no, msg);
    log_dump_trace(_blobstore_last_trace, sizeof(_blobstore_last_trace));

    if (_do_print_errors) {
        myprintf(EUCA_LOG_ERROR, "error: %s\n", _blobstore_last_msg);
        if (_do_print_trace)
            myprintf(EUCA_LOG_ERROR, "%s", _blobstore_last_trace);
    }
    _blobstore_errno = error;
}

//!
//!
//!
//! @param[in] default_errno
//! @param[in] src_line_no
//! @param[in] src_file_name
//!
//! @pre
//!
//! @note
//!
static __INLINE__ void propagate_system_errno(blobstore_error_t default_errno, const int src_line_no, const char *src_file_name)
{
    switch (errno) {
    case ENOENT:
        _blobstore_errno = BLOBSTORE_ERROR_NOENT;
        break;
    case ENOMEM:
        _blobstore_errno = BLOBSTORE_ERROR_NOMEM;
        break;
    case EACCES:
        _blobstore_errno = BLOBSTORE_ERROR_ACCES;
        break;
    case EEXIST:
        _blobstore_errno = BLOBSTORE_ERROR_EXIST;
        break;
    case EINVAL:
        _blobstore_errno = BLOBSTORE_ERROR_INVAL;
        break;
    case ENOSPC:
        _blobstore_errno = BLOBSTORE_ERROR_NOSPC;
        break;
    case EAGAIN:
        _blobstore_errno = BLOBSTORE_ERROR_AGAIN;
        break;
    default:
        perror("blobstore");
        _blobstore_errno = default_errno;
    }
    err(_blobstore_errno, NULL, src_line_no, src_file_name);
}

//!
//!
//!
//! @param[in] fn
//!
//! @pre
//!
//! @note
//!
void blobstore_set_error_function(void (*fn) (const char *msg))
{
    err_fn = fn;
}

//!
//!
//!
//! @param[in] str
//! @param[in] size
//!
//! @pre
//!
//! @note
//!
static void gen_id(char *str, unsigned int size)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    srandom((unsigned int)((unsigned long long)str * (unsigned long long)tv.tv_usec));
    snprintf(str, size, "%08lx%08lx%08lx", (unsigned long)random(), (unsigned long)random(), (unsigned long)random());
}

//!
//!
//!
//! @param[in] l
//! @param[in] type
//!
//! @return
//!
//! @pre
//!
//! @note
//!
struct flock *flock_whole_file(struct flock *l, short type)
{
    l->l_type = type;
    l->l_pid = 0;

    // set params so as to lock the whole file
    l->l_start = 0;
    l->l_whence = SEEK_SET;
    l->l_len = 0;

    return l;
}

//!
//!
//!
//! @param[in] l
//!
//! @pre \li MUST be called with _blobstore_mutex held.
//! \li The l parameter must not be NULL
//!
//! @note
//!
static void close_filelock(blobstore_filelock * l)
{
    // close all file descriptors at once (we do this because
    // closing any one removes the lock for all descriptors
    // held by a process)
    for (int i = 0; i < l->next_fd; i++) {
        if (l->fd[i] > -1) {
            close(l->fd[i]);
            l->fd[i] = -1;
        }
    }
    l->next_fd = 0; // knock the open fd counter back to 0
}

//!
//!
//!
//! @param[in] l
//!
//! @pre \li MUST be called with _blobstore_mutex held
//! \li The l parameter must not be NULL.
//!
//! @note
//!
static void free_filelock(blobstore_filelock * l)
{
    pthread_rwlock_destroy(&(l->lock));
    pthread_mutex_destroy(&(l->mutex));
    EUCA_FREE(l);
}

//!
//! This function must be used to close files opened with open_and_lock(). (Simply doing close() will
//! leave the file locked via pthreads and future open_and_lock() requests from the same process may
//! fail.) Also, closing the file descriptor releases the OS file lock for the process, so any other
//! read-only descriptors held by the process are no longer guarded since other processes may open the
//! file for writing.
//!
//! @param[in] fd
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int close_and_unlock(int fd)
{
    if (fd < 0) {
        ERR(BLOBSTORE_ERROR_BADF, NULL);
        return -1;
    }
    int ret = 0;
    { // critical section
        pthread_mutex_lock(&_blobstore_mutex); // grab global lock (we will not block below and we may be deallocating)
        LOGTRACE("{%u} close_and_unlock: obtained global lock for closing of fd=%d\n", (unsigned int)pthread_self(), fd);

        blobstore_filelock *path_lock = NULL; // lock struct to which this fd belongs
        int index = -1; // index of this fd entry in the lock struct

        // traverse all locks, looking for one with fd,
        // when found, compute index and open_fds
        blobstore_filelock **next_ptr = &locks_list;
        for (blobstore_filelock * l = locks_list; l; l = l->next) { // look for the fd
            assert(l->next_fd >= 0 && l->next_fd <= BLOBSTORE_MAX_CONCURRENT);
            for (int i = 0; i < l->next_fd; i++) {
                if (l->fd_status[i] && l->fd[i] == fd) {
                    path_lock = l; // found it!
                    index = i;
                    break;
                }
            }
            if (index != -1)
                break;
            next_ptr = &(l->next); // list head or prev element
        }

        if (path_lock) {
            assert(*next_ptr == path_lock);
            assert(index >= 0 && index < BLOBSTORE_MAX_CONCURRENT);

            boolean did_close = FALSE;
            boolean do_free = FALSE;
            { // inner critical section to protect changes to 'path_lock', if any
                pthread_mutex_lock(&(path_lock->mutex)); // grab path-specific mutex
                if (path_lock->fd_status[index] == 1) { // has not been closed yet
                    path_lock->fd_status[index] = 0; // set status to 'unused'
                    did_close = TRUE;
                    path_lock->refs--;

                    int open_fds = 0;
                    for (int i = 0; i < path_lock->next_fd; i++) {
                        if (path_lock->fd_status[i]) {
                            assert(path_lock->fd[i] != fd);
                            open_fds++;
                        }
                    }

                    if (open_fds == 0 && path_lock->refs == 0) { // no open blockblob file descriptors in this process
                        close_filelock(path_lock);
                        *next_ptr = path_lock->next; // remove from LL
                        do_free = TRUE;
                        _locks_list_rem_ctr++;
                        LOGTRACE("{%u} close_and_unlock: unlocked and freed fd=%d path=%s\n", (unsigned int)pthread_self(), fd, path_lock->path);

                    } else {
                        LOGTRACE("{%u} close_and_unlock: kept fd=%d path=%s open/refs=%d/%d\n", (unsigned int)pthread_self(), fd, path_lock->path, open_fds, path_lock->refs);
                    }
                    pthread_rwlock_unlock(&(path_lock->lock)); // give up the Posix lock
                    /* lock testing code
if (path_lock->sem) {
sem_v (path_lock->sem);
sem_free (path_lock->sem);
path_lock->sem = NULL;
}
*/
                }
                pthread_mutex_unlock(&(path_lock->mutex));
            } // end of inner critical section

            if (do_free)
                free_filelock(path_lock);

            if (!did_close) {
                ERR(BLOBSTORE_ERROR_BADF, "file descriptor already closed");
                ret = -1;
            }
        } else { // no match
            ERR(BLOBSTORE_ERROR_BADF, "not an open file descriptor");
            ret = -1;
        }

        if (ret == 0)
            _close_success_ctr++;
        else
            _close_error_ctr++;

        LOGTRACE("{%u} close_and_unlock: releasing global lock for closing of fd=%d ret=%d\n", (unsigned int)pthread_self(), fd, ret);
        pthread_mutex_unlock(&_blobstore_mutex);
    } // end of critical section

    return ret;
}

#ifdef _TEST_LOCKS
//!
//!
//!
//! @param[in] path
//! @param[in] name
//! @param[in] name_size
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static char *path_to_sem_name(const char *path, char *name, int name_size)
{
    snprintf(name, name_size, "euca%s", path);
    for (int i = 0; i < name_size && name[i]; i++)
        if (name[i] == '/')
            name[i] = '-';
    return name;
}
#endif /* _TEST_LOCKS */

//!
//! This function creates or opens a file and locks it. The lock is:
//!
//! \li exclusive if the file is being created or written to, or a
//! \li non-exclusive readers' lock if the file was opened RDONLY.
//!
//! The lock works both across threads and processes. File descriptors obtained from
//! this function should be released with close_and_unlock(). All locks held by a process
//! are released upon termination, whether normal or abnormal.
//!
//! @param[in] path
//! @param[in] flags \li BLOBSTORE_FLAG_RDONLY - open with O_RDONLY, reader lock
//! \li BLOBSTORE_FLAG_RDWR - open with O_RDWR, writer lock
//! \li BLOBSTORE_FLAG_CREAT - open with O_RDWR | O_CREAT, writer lock
//! \li BLOBSTORE_FLAG_EXCL - can be added to _CREAT, as with open()
//! @param[in] timeout_usec \li timeout in microseconds for waiting on a lock
//! \li BLOBSTORE_NO_TIMEOUT / -1 - wait forever
//! \li BLOBSTORE_NO_WAIT / 0 - do not wait at all
//! @param[in] mode gets passed to open() directly
//!
//! @return
//!
//! @see close_and_unlock()
//!
//! @pre
//!
//! @note
//!
static int open_and_lock(const char *path, int flags, long long timeout_usec, mode_t mode)
{
    short l_type;
    int o_flags = 0;
    long long started = time_usec();
    long long deadline = started + timeout_usec;

    // verify the flags and, based on them,
    // decide what type of lock to use
    if (flags & BLOBSTORE_FLAG_RDONLY) {
        l_type = F_RDLCK; // use shared (read) lock
        o_flags |= O_RDONLY; // required when using F_RDLCK

    } else if ((flags & BLOBSTORE_FLAG_RDWR) || (flags & BLOBSTORE_FLAG_CREAT)) {
        l_type = F_WRLCK; // use exclusive (write) lock
        o_flags |= O_RDWR; // required when using F_WRLCK
        if (flags & BLOBSTORE_FLAG_CREAT) {
            o_flags |= O_CREAT;
            // intentionally ignore _EXCL supplied without _CREAT
            if (flags & BLOBSTORE_FLAG_EXCL)
                o_flags |= O_EXCL;
        }

        if (flags & BLOBSTORE_FLAG_CREAT)
            o_flags |= O_TRUNC;
    } else {
        ERR(BLOBSTORE_ERROR_INVAL, "flags to open_and_lock must include either _RDONLY or _RDWR or _CREAT");
        return -1;
    }

    // handle intra-process locking, with a pthreads read-write lock
    // either find in a global linked list 'locks_list' or
    // allocate and append to it a 'blobstore_filelock' struct
    blobstore_filelock *path_lock = NULL;
    { // critical section
        pthread_mutex_lock(&_blobstore_mutex); // grab the global mutex
        blobstore_filelock **next_ptr = &locks_list;
        for (blobstore_filelock * l = locks_list; l; l = l->next) { // look through existing locks
            if (strcmp(path, l->path) == 0) {
                path_lock = l;
                break;
            }
            next_ptr = &(l->next);
        }
        // next_ptr now points either to LL head or
        // to the last non-matching element's next pointer

        if (path_lock == NULL) { // this path is not locked by any thread
            path_lock = EUCA_ZALLOC(1, sizeof(blobstore_filelock));
            if (path_lock == NULL) {
                pthread_mutex_unlock(&_blobstore_mutex);
                ERR(BLOBSTORE_ERROR_NOMEM, NULL);
                return -1;
            }
            euca_strncpy(path_lock->path, path, sizeof(path_lock->path));
            pthread_rwlock_init(&(path_lock->lock), NULL);
            pthread_mutex_init(&(path_lock->mutex), NULL);
            *next_ptr = path_lock; // add at the end of LL
            _locks_list_add_ctr++;
        } else {
            assert(*next_ptr == path_lock);
            if (path_lock->next_fd == BLOBSTORE_MAX_CONCURRENT) {
                pthread_mutex_unlock(&_blobstore_mutex);
                ERR(BLOBSTORE_ERROR_MFILE, "too many open file descriptors"); // to be precise, this means too many file descriptors with overlapping lifetimes
                return -1;
            }
        }
        pthread_mutex_lock(&(path_lock->mutex)); // grab path-specific mutex
        {
            path_lock->refs++; // increase the reference count while still under lock
        }
        pthread_mutex_unlock(&(path_lock->mutex)); // release path-specific mutex
        pthread_mutex_unlock(&_blobstore_mutex); // release global mutex
    } // end of critical section

    // open/create the file, using Posix file locks for inter-process locking
    int fd = open(path, o_flags, mode);
    LOGTRACE("{%u} open_and_lock: open fd=%d flags=%0x path=%s\n", (unsigned int)pthread_self(), fd, o_flags, path);
    if (fd == -1) {
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        goto error;
    }

    { // critical section
        pthread_mutex_lock(&_blobstore_mutex); // grab the global mutex

        // ensure we do not have this file descriptor already in some other list
        for (blobstore_filelock * l = locks_list; l; l = l->next) {
            { // inner critical section
                pthread_mutex_lock(&(l->mutex)); // grab path-specific mutex for atomic update to the table of descriptors
                for (int i = 0; i < l->next_fd; i++) {
                    if (l->fd[i] == fd) {
                        LOGWARN("WARNING: blobstore lock closed outside close_and_unlock [fd=%d, index=%d, refs=%d]\n", fd, i, l->refs);
                        l->fd[i] = -1; // set to invalid so no one else closes our valid descriptor
                        l->fd_status[i] = 0; // definitely unused.
                        l->refs--;
                    }
                }
                pthread_mutex_unlock(&(l->mutex)); // release path-specific mutex
            } // end of inner critical section
        }

        { // inner critical section
            pthread_mutex_lock(&(path_lock->mutex)); // grab path-specific mutex for atomic update to the table of descriptors

            // record the file descriptor in the array regardless of whether
            // we ultimately succeed in obtaining the lock or not -- we must
            // ensure we do not close this file descriptor until all users
            // of the lock are through
            path_lock->fd[path_lock->next_fd] = fd; // record file descriptor to enable future lookups
            path_lock->fd_status[path_lock->next_fd] = 1; // mark the slot as in-use
#ifdef _TEST_FILELOCK
            path_lock->thread_id[path_lock->next_fd] = (unsigned int)pthread_self();
#endif
            path_lock->next_fd++; // move the index up (it only goes up because we close all file descriptors together)

            pthread_mutex_unlock(&(path_lock->mutex)); // release path-specific mutex
        } // end of inner critical section

        pthread_mutex_unlock(&_blobstore_mutex); // release global mutex
    } // end of critical section

    for (;;) {
        // first try getting the Posix rwlock
        int ret;
        if (l_type == F_WRLCK)
            ret = pthread_rwlock_trywrlock(&(path_lock->lock));
        else
            ret = pthread_rwlock_tryrdlock(&(path_lock->lock));
        if (ret == 0) {
            // Posix rwlock succeeded, try the file lock
            errno = 0;
            struct flock l;
            if (fcntl(fd, F_SETLK, flock_whole_file(&l, l_type)) != -1)
                break; // success!
            pthread_rwlock_unlock(&(path_lock->lock)); // give up the Posix lock
            if (errno != EAGAIN) { // any error other than inability to get the lock
                PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
                goto error;
            }
        }
        long long now = time_usec();
        if (timeout_usec != BLOBSTORE_NO_TIMEOUT && now >= deadline) { // we timed out waiting for the lock
            ERR(BLOBSTORE_ERROR_AGAIN, NULL);
            pthread_mutex_lock(&_blobstore_mutex);
            _open_timeout_ctr++;
            pthread_mutex_unlock(&_blobstore_mutex);
            goto error;
        }
        LOGTRACE("{%u} open_and_lock: could not acquire %s lock, sleeping on %s\n", (unsigned int)pthread_self(), (ret == 0) ? ("file") : ("posix"), path);

        usleep(BLOBSTORE_SLEEP_INTERVAL_USEC);
    }

    // successully acquired both file and Posix locks

#ifdef _TEST_LOCKS
    if (l_type == F_WRLCK) {
        char sem_name[512];
        path_lock->sem = sem_alloc(1, path_to_sem_name(path, sem_name, sizeof(sem_name)));
        sem_p(path_lock->sem);
    }
#endif // _TEST_LOCKS

    pthread_mutex_lock(&_blobstore_mutex);
    _open_success_ctr++;
    pthread_mutex_unlock(&_blobstore_mutex);
    { // print out information about the newly acquired lock
        struct stat s;
        fstat(fd, &s);

        struct flock l;
        fcntl(fd, F_GETLK, flock_whole_file(&l, l_type));

        LOGTRACE("{%u} open_and_lock: locked fd=%d path=%s flags=%d ino=%ld mode=%0o [lock type=%d whence=%d start=%ld length=%ld]\n",
                 (unsigned int)pthread_self(), fd, path, o_flags, s.st_ino, s.st_mode, l.l_type, l.l_whence, l.l_start, l.l_len);
    }
    return fd;

error:
    // due to aproblem above (inability to open the file or
    // to acquire Posix locks within the deadline), the
    // 'blobstore_filelock' struct will be removed from the
    // global linked list 'locks_list', its files closed,
    // and its memory freed -- but only if this is the last
    // thread using it

    { // critical section
        pthread_mutex_lock(&_blobstore_mutex); // grab the global lock to protect locks_list traversal

        // we must recalculate next_ptr since the element that it points to
        // may have been removed from the LL and freed while we were outside
        // the critical section
        blobstore_filelock **next_ptr = &locks_list;
        for (blobstore_filelock * l = locks_list; l; l = l->next) { // look through existing locks
            if (path_lock == l)
                break;
            next_ptr = &(l->next);
        }
        // next_ptr must point at the struct we are looking for,
        // which must be in the list
        assert(*next_ptr == path_lock);

        boolean do_free = FALSE;
        { // inner critical section
            pthread_mutex_lock(&(path_lock->mutex)); // grab path-specific mutex for atomic update to the table of descriptors
            path_lock->refs--;

            int open_fds = 0;
            for (int i = 0; i < path_lock->next_fd; i++) {
                if (path_lock->fd_status[i]) {
                    if (path_lock->fd[i] == fd) {
                        path_lock->fd_status[i] = 0; // mark as 'unused'
                    } else {
                        open_fds++;
                    }
                }
            }

            if (open_fds == 0 && path_lock->refs == 0) { // no open blockblob file descriptors in this process
                close_filelock(path_lock);
                *next_ptr = path_lock->next; // remove from LL
                do_free = TRUE;
                _locks_list_rem_ctr++;
                LOGTRACE("{%u} open_and_lock: freed fd=%d path=%s\n", (unsigned int)pthread_self(), fd, path_lock->path);

            } else {
                LOGTRACE("{%u} open_and_lock: kept fd=%d path=%s open/refs=%d/%d\n", (unsigned int)pthread_self(), fd, path_lock->path, open_fds, path_lock->refs);
            }

            pthread_mutex_unlock(&(path_lock->mutex));
        } // end of inner critical section

        if (do_free)
            free_filelock(path_lock);

        _open_error_ctr++;
        pthread_mutex_unlock(&_blobstore_mutex);
    } // end of critical section

    return -1;
}

//!
//!
//!
//! @param[in] buf
//! @param[in] key
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static char *get_val(const char *buf, const char *key)
{
    char *val = NULL;
    char full_key[512];
    snprintf(full_key, sizeof(full_key), "%s: ", key);
    char *val_begin = strstr(buf, full_key);
    if (val_begin) {
        val_begin += strlen(full_key);
        char *val_end = val_begin;
        while (*val_end != '\n' && *val_end != '\0')
            val_end++;
        val = EUCA_ZALLOC(val_end - val_begin + 1, sizeof(char)); // +1 for the \0
        if (val == NULL) {
            ERR(BLOBSTORE_ERROR_NOMEM, NULL);
            return NULL;
        }
        strncpy(val, val_begin, val_end - val_begin);
    }

    return val;
}

//!
//! Helper for reading a file into a buffer
//!
//! @param[in] fd
//! @param[in] buf
//! @param[in] size_buf
//!
//! @return The number of bytes read or -1 if error
//!
//! @pre
//!
//! @note
//!
static int fd_to_buf(int fd, char *buf, int size_buf)
{
    if (lseek(fd, 0, SEEK_SET) == -1) {
        ERR(BLOBSTORE_ERROR_ACCES, "failed to seek in metadata file");
        return -1;
    }

    struct stat sb;
    if (fstat(fd, &sb) == -1) {
        ERR(BLOBSTORE_ERROR_ACCES, "failed to stat metadata file");
        return -1;
    }

    if (read(fd, buf, size_buf) != sb.st_size) //! @TODO do this in a loop?
    {
        ERR(BLOBSTORE_ERROR_NOENT, "failed to read metadata file");
        return -1;
    }

    return sb.st_size;
}

//!
//! Helper for write buffer into a file at descriptor
//!
//! @param[in] fd
//! @param[in] buf
//! @param[in] size_buf
//!
//! @return The number of bytes written or -1 if error
//!
//! @pre
//!
//! @note
//!
static int buf_to_fd(int fd, const char *buf, int size_buf)
{
    if (lseek(fd, 0, SEEK_SET) == -1) {
        ERR(BLOBSTORE_ERROR_ACCES, "failed to seek in metadata file");
        return -1;
    }

    ssize_t size_wrote = write(fd, buf, size_buf); //! @TODO do this in a loop?
    if (size_wrote < size_buf) {
        ERR(BLOBSTORE_ERROR_NOENT, "failed to write metadata file");
        return -1;
    }
    // as a sanity check, stat the file and verify its size
    struct stat sb;
    if (fstat(fd, &sb) == -1) {
        ERR(BLOBSTORE_ERROR_ACCES, "failed to stat metadata file");
        return -1;
    }

    if (sb.st_size != size_buf) {
        ERR(BLOBSTORE_ERROR_NOENT, "failed to read back metadata file");
        return -1;
    }

    return sb.st_size;
}

//!
//!
//!
//! @param[in] bs
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int read_store_metadata(blobstore * bs)
{
    char *val = NULL;
    char buf[1024] = "";
    int size = fd_to_buf(bs->fd, buf, (sizeof(buf) - 1));

    if (size == -1)
        return -1;
    if (size < 30) {
        ERR(BLOBSTORE_ERROR_NOENT, "metadata size is too small");
        return -1;
    }

    buf[size] = '\0';
    if ((val = get_val(buf, "id")) == NULL)
        return -1;
    euca_strncpy(bs->id, val, sizeof(bs->id));
    EUCA_FREE(val);

    if ((val = get_val(buf, "limit")) == NULL)
        return -1;
    errno = 0;
    bs->limit_blocks = strtoll(val, NULL, 10);
    EUCA_FREE(val);
    if (errno != 0) {
        ERR(BLOBSTORE_ERROR_NOENT, "invalid metadata file (limit is missing)");
        return -1;
    }

    if ((val = get_val(buf, "revocation")) == NULL)
        return -1;
    errno = 0;
    bs->revocation_policy = strtoll(val, NULL, 10);
    EUCA_FREE(val);
    if (errno != 0) {
        ERR(BLOBSTORE_ERROR_NOENT, "invalid metadata file (revocation is missing)");
        return -1;
    }

    if ((val = get_val(buf, "snapshot")) == NULL)
        return -1;
    errno = 0;
    bs->snapshot_policy = strtoll(val, NULL, 10);
    EUCA_FREE(val);
    if (errno != 0) {
        ERR(BLOBSTORE_ERROR_NOENT, "invalid metadata file (snapshot is missing)");
        return -1;
    }

    if ((val = get_val(buf, "format")) == NULL)
        return -1;
    errno = 0;
    bs->format = strtoll(val, NULL, 10);
    EUCA_FREE(val);
    if (errno != 0) {
        ERR(BLOBSTORE_ERROR_NOENT, "invalid metadata file (format is missing)");
        return -1;
    }
    return 0;
}

//!
//!
//!
//! @param[in] bs
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int write_store_metadata(blobstore * bs)
{
    if (ftruncate(bs->fd, 0) == -1) {
        ERR(BLOBSTORE_ERROR_NOENT, "failed to truncate the metadata file");
        return -1;
    }
    if (lseek(bs->fd, 0, SEEK_SET) == -1) {
        ERR(BLOBSTORE_ERROR_ACCES, "failed to seek in metadata file");
        return -1;
    }
    char buf[1024];
    snprintf(buf, sizeof(buf), "id: %s\n" "limit: %lld\n" "revocation: %d\n" "snapshot: %d\n" "format: %d\n", bs->id, bs->limit_blocks,
             bs->revocation_policy, bs->snapshot_policy, bs->format);
    int slen = strlen(buf);
    int len = write(bs->fd, buf, slen);
    if (len != slen) {
        ERR(BLOBSTORE_ERROR_NOENT, "failed to write to the metadata file");
        return -1;
    }

    return 0;
}

//!
//!
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_init(void)
{
    int ret = 0;

    if (!initialized) {
        ret = diskutil_init(FALSE); // blobstore does not invoke GRUB-related functions
        if (ret) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to initialize diskutil library");
        } else {
            ret = verify_helpers(helpers, helpers_path, LASTHELPER);
            if (ret) {
                for (int i = 0; i < LASTHELPER; i++) {
                    if (helpers_path[i] == NULL)
                        LOGERROR("ERROR: missing a required handler: %s\n", helpers[i]);
                }
                ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to initialize blobstore library");
            } else {
                initialized = 1;
            }
        }
    }

    return ret;
}

//!
//!
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_cleanup(void)
{
    diskutil_cleanup();
    return 0;
}

//!
//!
//!
//! @param[in] path
//! @param[in] limit_blocks
//! @param[in] flags
//! @param[in] format
//! @param[in] revocation_policy
//! @param[in] snapshot_policy
//!
//! @return
//!
//! @pre
//!
//! @note
//!
blobstore *blobstore_open(const char *path, unsigned long long limit_blocks, unsigned int flags, // BLOBSTORE_FLAG_CREAT - same semantcs as for open() flags
                          blobstore_format_t format, blobstore_revocation_t revocation_policy, blobstore_snapshot_t snapshot_policy)
{
    int saved_errno;

    if (blobstore_init())
        return NULL;

    blobstore *bs = EUCA_ZALLOC(1, sizeof(blobstore));
    if (bs == NULL) {
        ERR(BLOBSTORE_ERROR_NOMEM, NULL);
        goto out;
    }
    euca_strncpy(bs->path, path, sizeof(bs->path)); //! @TODO canonicalize path
    char meta_path[PATH_MAX];
    snprintf(meta_path, sizeof(meta_path), "%s/%s", bs->path, BLOBSTORE_METADATA_FILE);

    int write_flags = 0;
    if (flags & BLOBSTORE_FLAG_CREAT) {
        write_flags = BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_EXCL;
    };

write_metadata:

    if (write_flags) {
        _blobstore_errno = BLOBSTORE_ERROR_OK;
        _err_off();
        bs->fd = open_and_lock(meta_path, write_flags, 0, BLOBSTORE_FILE_PERM);
        _err_on();
        if (bs->fd != -1) { // managed to create or open blobstore metadata file and got exclusive lock

            // the intention is to create the blobstore for the first time
            if (write_flags & BLOBSTORE_FLAG_CREAT) {
                gen_id(bs->id, sizeof(bs->id));
                bs->limit_blocks = limit_blocks;
                bs->revocation_policy = (revocation_policy == BLOBSTORE_REVOCATION_ANY) ? BLOBSTORE_REVOCATION_NONE : revocation_policy;
                bs->snapshot_policy = (snapshot_policy == BLOBSTORE_SNAPSHOT_ANY) ? BLOBSTORE_SNAPSHOT_DM : snapshot_policy; //! @TODO verify that DM is available?
                bs->format = (format == BLOBSTORE_FORMAT_ANY) ? BLOBSTORE_FORMAT_FILES : format;

                // write metadata to disk
                write_store_metadata(bs);

            } else if (write_flags & BLOBSTORE_FLAG_RDWR) { // the intention is to adjust metadata
                if (read_store_metadata(bs))
                    goto free;
                assert(bs->id);
                if (limit_blocks)
                    bs->limit_blocks = limit_blocks;
                if (revocation_policy != BLOBSTORE_REVOCATION_ANY)
                    bs->revocation_policy = revocation_policy;
                write_store_metadata(bs);
            }
            close_and_unlock(bs->fd); // try to close, thus giving up the exclusive lock
        }
        if (_blobstore_errno != BLOBSTORE_ERROR_OK && // either open or write failed
            _blobstore_errno != BLOBSTORE_ERROR_EXIST && // it is OK if file already exists
            _blobstore_errno != BLOBSTORE_ERROR_AGAIN) { // it is OK if we lost the race for the write lock
            ERR(_blobstore_errno, "failed to open or create blobstore");
            goto free;
        }
    }
    // now (re)open, with a shared read lock
    bs->fd = open_and_lock(meta_path, BLOBSTORE_FLAG_RDONLY, BLOBSTORE_METADATA_TIMEOUT_USEC, BLOBSTORE_FILE_PERM);
    if (bs->fd == -1) {
        goto free;
    }
    if (read_store_metadata(bs)) { // try reading metadata
        goto free;
    }
    // verify that parameters are not being changed
    if (limit_blocks && limit_blocks != bs->limit_blocks) {
        if (flags & BLOBSTORE_FLAG_STRICT) {
            ERR(BLOBSTORE_ERROR_INVAL, "'limit_blocks' does not match existing blobstore");
            goto free;
        } else {
            LOGINFO("adjusting blobstore limit from %lld to %lld\n", bs->limit_blocks, limit_blocks);
            write_flags = BLOBSTORE_FLAG_RDWR;
            close_and_unlock(bs->fd);
            goto write_metadata;
        }
    }
    if (snapshot_policy != BLOBSTORE_SNAPSHOT_ANY && snapshot_policy != bs->snapshot_policy) {
        ERR(BLOBSTORE_ERROR_INVAL, "'snapshot_policy' does not match existing blobstore");
        goto free;
    }
    if (format != BLOBSTORE_FORMAT_ANY && format != bs->format) {
        ERR(BLOBSTORE_ERROR_INVAL, "'format' does not match existing blobstore");
        goto free;
    }
    if (revocation_policy != BLOBSTORE_REVOCATION_ANY && revocation_policy != bs->revocation_policy) {
        if (flags & BLOBSTORE_FLAG_STRICT) {
            ERR(BLOBSTORE_ERROR_INVAL, "'revocation_policy' does not match existing blobstore"); //! @TODO maybe make revocation_policy changeable after creation
            goto free;
        } else {
            write_flags = BLOBSTORE_FLAG_RDWR;
            close_and_unlock(bs->fd);
            goto write_metadata;
        }
    }
    int fd = bs->fd;
    bs->fd = -1;
    close_and_unlock(fd);
    goto out;

free:
    saved_errno = _blobstore_errno;
    close_and_unlock(bs->fd);
    EUCA_FREE(bs);
    _blobstore_errno = saved_errno;

out:
    return bs;
}

//!
//! Frees the blobstore handle
//!
//! @param[in] bs
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_close(blobstore * bs)
{
    EUCA_FREE(bs);
    return 0;
}

//!
//! Locks the blobstore
//!
//! @param[in] bs
//! @param[in] timeout_usec
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_lock(blobstore * bs, long long timeout_usec)
{
    char meta_path[PATH_MAX];
    snprintf(meta_path, sizeof(meta_path), "%s/%s", bs->path, BLOBSTORE_METADATA_FILE);

    LOGTRACE("{%u} blobstore_lock: called for %s\n", (unsigned int)pthread_self(), bs->path);
    int fd = open_and_lock(meta_path, BLOBSTORE_FLAG_RDWR, timeout_usec, BLOBSTORE_FILE_PERM);
    if (fd != -1)
        bs->fd = fd;
    return fd;
}

//!
//! Unlocks the blobstore
//!
//! @param[in] bs
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_unlock(blobstore * bs)
{
    int fd = bs->fd;
    bs->fd = -1;
    LOGTRACE("{%u} blobstore_unlock: called for %s\n", (unsigned int)pthread_self(), bs->path);
    return close_and_unlock(fd);
}

//!
//! If no outside references to store or blobs exist, and
//! no blobs are protected, deletes the blobs, the store metadata,
//! and frees the blobstore handle
//!
//! @param[in] bs
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_delete(blobstore * bs)
{
    LOGINFO("creating the baloon blob\n");
    blockblob *bb = blockblob_open(bs, "__baloon_blob__",
                                   bs->limit_blocks * 512, // biggest possible blob
                                   (BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_EXCL),
                                   NULL, // do not care for signature
                                   BLOBSTORE_METADATA_TIMEOUT_USEC); // give a generous timeout
    if (bb == NULL) {
        LOGINFO("failed to purge blobstore: %s: %s\n", blobstore_get_error_str(blobstore_get_error()), blobstore_get_last_msg());
        ERR(BLOBSTORE_ERROR_INVAL, "failed to purge blobstore with a baloon blob");
        return EUCA_ERROR;
    }
    blockblob_delete(bb, BLOBSTORE_DELETE_TIMEOUT_USEC, TRUE); // get rid of the last blob

    char meta_path[PATH_MAX];
    snprintf(meta_path, sizeof(meta_path), "%s/%s", bs->path, BLOBSTORE_METADATA_FILE);
    LOGINFO("removing blobstore metadata '%s'\n", meta_path);
    unlink(meta_path);
    EUCA_FREE(bs);

    return EUCA_OK;
}

//!
//!
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_get_error(void)
{
    return _blobstore_errno;
}

//!
//! Helper for setting paths, depending on blockblob_path_t given BLOCKBLOB_PATH_X: x = tolower(X)
//!
//! for BLOBSTORE_FORMAT_FILES: BS/BB.x
//! for BLOBSTORE_FORMAT_DIRECTORY: BS/BB/x
//!
//! where BS is blobstore path and BB is a blockblob id.
//! BB may have '/' in it, thus placing all blob-related
//! files in a deeper dir hierarchy
//!
//! @param[in] path_t
//! @param[in] bs
//! @param[in] bb_id
//! @param[out] path
//! @param[in] path_size
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int set_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char *path, size_t path_size)
{
    char base[PATH_MAX];
    snprintf(base, sizeof(base), "%s/%s", bs->path, bb_id);

    char name[32];
    switch (path_t) {
    case BLOCKBLOB_PATH_BLOCKS:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_BLOCKS], sizeof(name));
        break;
    case BLOCKBLOB_PATH_LOCK:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_LOCK], sizeof(name));
        break;
    case BLOCKBLOB_PATH_DM:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_DM], sizeof(name));
        break;
    case BLOCKBLOB_PATH_DEPS:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_DEPS], sizeof(name));
        break;
    case BLOCKBLOB_PATH_LOOPBACK:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_LOOPBACK], sizeof(name));
        break;
    case BLOCKBLOB_PATH_SIG:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_SIG], sizeof(name));
        break;
    case BLOCKBLOB_PATH_REFS:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_REFS], sizeof(name));
        break;
    case BLOCKBLOB_PATH_HOLLOW:
        euca_strncpy(name, blobstore_metadata_suffixes[BLOCKBLOB_PATH_HOLLOW], sizeof(name));
        break;
    default:
        ERR(BLOBSTORE_ERROR_INVAL, "invalid path_t");
        return -1;
    }

    switch (bs->format) {
    case BLOBSTORE_FORMAT_FILES:
        snprintf(path, path_size, "%s.%s", base, name);
        break;
    case BLOBSTORE_FORMAT_DIRECTORY:
        snprintf(path, path_size, "%s/%s", base, name);
        break;
    default:
        ERR(BLOBSTORE_ERROR_INVAL, "invalid bs->format");
        return -1;
    }

    return 0;
}

//!
//! Write string 'str' into a specific metadata file (based on 'path_t') of blob 'bb_id'
//!
//! @param[in] path_t
//! @param[in] bs
//! @param[in] bb_id
//! @param[in] str
//!
//! @return 0 for success or -1 for error
//!
//! @pre
//!
//! @note
//!
static int write_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, const char *str)
{
    int ret = 0;
    char path[PATH_MAX];
    set_blockblob_metadata_path(path_t, bs, bb_id, path, sizeof(path));

    int fd = open_and_lock(path,
                           BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_RDWR,
                           BLOBSTORE_METADATA_TIMEOUT_USEC,
                           BLOBSTORE_FILE_PERM);
    if (fd == -1)
        return -1;
    int size = buf_to_fd(fd, str, strlen(str));
    int ret_close = close_and_unlock(fd);
    if (size != strlen(str)) {
        // set the error code, possibly overriding one set by close_and_unlock
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to write desired number of characters to metadata file");
        ret = -1;
    } else if (ret_close != 0) {
        ret = -1; // close_and_unlock should have set the error code
    }

    return ret;
}

//!
//! Reads contents of a specific metadata file (based on 'path_t') of blob 'bb_id' into string 'str' up to 'str_size'
//!
//! @param[in] path_t
//! @param[in] bs
//! @param[in] bb_id
//! @param[out] str
//! @param[in] str_size
//!
//! @return The number of bytes read or -1 in case of error
//!
//! @pre
//!
//! @note
//!
static int read_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char *str, int str_size)
{
    char path[PATH_MAX];
    set_blockblob_metadata_path(path_t, bs, bb_id, path, sizeof(path));

    int fd = open_and_lock(path,
                           BLOBSTORE_FLAG_RDONLY,
                           BLOBSTORE_METADATA_TIMEOUT_USEC,
                           BLOBSTORE_FILE_PERM);
    if (fd == -1)
        return -1;
    int size = fd_to_buf(fd, str, str_size);
    int ret_close = close_and_unlock(fd);
    if (size < 1) {
        // set the error code, possibly overriding one set by close_and_unlock
        ERR(BLOBSTORE_ERROR_NOENT, "blockblob metadata size is too small");
        size = -1;
    } else if (ret_close != 0) {
        size = -1; // close_and_unlock should have set the error code
    }

    return size;
}

//!
//! Writes strings from 'array' of size 'array_size' (which can be 0) line-by-line
//! into a specific metadata file (based on 'path_t') of blob 'bb_id'
//!
//! @param[in] path_t
//! @param[in] bs
//! @param[in] bb_id
//! @param[out] array
//! @param[out] array_size
//!
//! @return 0 for success and -1 for error
//!
//! @pre
//!
//! @note
//!
static int write_array_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char **array, int array_size)
{
    int i = 0;
    int fd = 0;
    int ret = 0;
    int dataLen = 0;
    unsigned int openFlags = (BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_TRUNC | BLOBSTORE_FLAG_RDWR);
    char path[EUCA_MAX_PATH] = "";

    set_blockblob_metadata_path(path_t, bs, bb_id, path, sizeof(path));
    if ((fd = open_and_lock(path, openFlags, BLOBSTORE_METADATA_TIMEOUT_USEC, BLOBSTORE_FILE_PERM)) == -1) {
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        return (-1);
    }

    for (i = 0; i < array_size; i++) {
        dataLen = strlen(array[i]);
        if (write(fd, array[i], dataLen) != dataLen) {
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            ret = -1;
            break;
        }

        if (write(fd, "\n", 1) != 1) {
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            ret = -1;
            break;
        }
    }

    if (close_and_unlock(fd) != 0) {
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        ret = -1;
    }

    return (ret);
}

//!
//! The equivalent of getline for file descriptor.
//!
//! @param[in,out] ppLine pointer to the character array to read into
//! @param[in,out] n amount of memory currently allocated for (*ppLine), if any
//! @param[in] fd file descriptor to read from
//!
//! @return On success, number of characters read excluding the '\n' character is returned. A
//! value or 0 indicates we reached the end of the file. A returned value of -1 indicates
//! an error and the errno is set appropriately. On error, the original allocated memory
//! is left untouched.
//!
//! @pre
//!
//! @note
//!
ssize_t get_line_desc(char **ppLine, size_t * n, int fd)
{
    char c = '\0';
    size_t length = 0;
    size_t newSize = (*n);
    ssize_t error = 0;
    char *pLine = *ppLine;
    char *pNewBlock = *ppLine;

    do {
        // Read one character.. If 0, then EOF, if less then error!
        if ((error = read(fd, &c, 1)) <= 0)
            break;

        // If we're going over, re-allocate memory
        if ((length + 1) >= newSize) {
            newSize += 64;

            if ((pNewBlock = EUCA_REALLOC(pLine, newSize, sizeof(char))) == NULL) {
                error = -1;
                break;
            }

            pLine = pNewBlock;
        }

        pLine[length++] = c;
    } while (c != '\n');

    // Did we have an error?
    if (error < 0) {
        // If (*n) was originally 0 we should free pLine since we allocated that memory.
        if (((*n) == 0) && (pLine != NULL)) {
            EUCA_FREE(pLine);
        }
        return (-1);
    }
    // Now strip the '\n' character
    if (pLine != NULL) {
        (*ppLine) = pLine;
        pLine[length] = '\0'; // Safety

        // Now strip '\n' if present. We could have reached EOF and no '\n' was present
        if (pLine[length - 1] == '\n')
            pLine[--length] = '\0';

        // Update the (*n) value
        (*n) = newSize;
    }

    return (length);
}

//!
//! Reads lines from a specific metadata file (based on 'path_t') of blob 'bb_id',
//! places each line into a newly allocated string, arranges pointers to these
//! strings into a newly allocated array of pointers, and places the size into 'array_size'
//!
//! @param[in] path_t
//! @param[in] bs
//! @param[in] bb_id
//! @param[out] array
//! @param[out] array_size
//!
//! @return 0 for success and -1 for error
//!
//! @pre
//!
//! @note Caller must deallocate the array and the strings pointed to by the array
//!
static int read_array_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, char ***array, int *array_size)
{
    int fd = -1;
    int ret = 0;
    int i = 0;
    int j = 0;
    size_t n = 0;
    ssize_t rdLen = 1;
    char **lines = NULL;
    char *line = NULL;
    char **bigger_lines = NULL;
    char path[EUCA_MAX_PATH] = "";

    set_blockblob_metadata_path(path_t, bs, bb_id, path, sizeof(path));

    // Acquire the metadata file descriptor
    if ((fd = open_and_lock(path, BLOBSTORE_FLAG_RDONLY, BLOBSTORE_METADATA_TIMEOUT_USEC, BLOBSTORE_FILE_PERM)) == -1) {
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        *array = NULL;
        *array_size = 0;
        return 0;
    }
    // Read each line and fill our array
    for (i = 0, rdLen = 1; rdLen > 0; i++) {
        n = 0;
        line = NULL;

        // Read the file. 0 means EOF, < 0 means error...
        if ((rdLen = get_line_desc(&line, &n, fd)) < 0) {
            EUCA_FREE(line);
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            ret = -1;
            break;
        } else if (rdLen == 0) {
            // EOF, no more data
            break;
        }

        LOGEXTREME("%s => [%d] READ LINE %s rdLen %lu, n %ld\n", __func__, fd, line, rdLen, n);

        // Add one more entry to our metadata array
        if ((bigger_lines = EUCA_REALLOC(lines, (i + 1), sizeof(char *))) == NULL) {
            ERR(BLOBSTORE_ERROR_NOMEM, NULL);
            EUCA_FREE(line);
            ret = -1;
            break;
        }

        lines = bigger_lines;
        lines[i] = line;
    }

    // Release the metadata file descriptor
    if (close_and_unlock(fd) != 0) {
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        ret = -1;
    }
    // if something failed, lets do some house cleanup before we bail
    if (ret == -1) {
        if (lines != NULL) {
            for (j = 0; j < i; j++)
                EUCA_FREE(lines[j]);
            EUCA_FREE(lines);
        }
        return (ret);
    }

    *array = lines;
    *array_size = i;
    return (0);
}

//!
//!
//!
//! @param[in] path_t
//! @param[in] bs
//! @param[in] bb_id
//! @param[in] entry
//! @param[in] removing
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int update_entry_blockblob_metadata_path(blockblob_path_t path_t, const blobstore * bs, const char *bb_id, const char *entry, int removing)
{
    int ret = 0;

    // read in current entries from a metadata file
    char **entries;
    int entries_size;
    if (read_array_blockblob_metadata_path(path_t, bs, bb_id, &entries, &entries_size) == -1) {
        return -1;
    }
    // see if this entry is already in the metadata file
    int found = -1;
    for (int j = 0; j < entries_size; j++) {
        if (!strcmp(entry, entries[j])) {
            found = j;
            break;
        }
    }

    if (found == -1 && !removing) { // not in the file and adding
        entries_size++;
        char **bigger_entries = EUCA_ZALLOC(entries_size, sizeof(char *));
        if (bigger_entries == NULL) {
            ret = -1;
            goto cleanup;
        }
        for (int i = 0; i < entries_size - 1; i++) { // we do not trust realloc
            bigger_entries[i] = entries[i];
        }
        EUCA_FREE(entries);
        entries = bigger_entries;
        entries[entries_size - 1] = strdup(entry);

    } else if (found != -1 && removing) { // in the file and deleting
        EUCA_FREE(entries[found]);
        entries_size--;
        if (entries_size && found != entries_size) { // still entries left and not deleting last one
            entries[found] = entries[entries_size]; // move the last one over the one we're deleting
        }

    } else { // nothing to do
        goto cleanup;
    }

    // save new entries into the metadata file
    if (write_array_blockblob_metadata_path(path_t, bs, bb_id, entries, entries_size) == -1) {
        ret = -1;
    }

cleanup:
    if (entries != NULL) {
        for (int j = 0; j < entries_size; j++) {
            EUCA_FREE(entries[j]);
        }
        EUCA_FREE(entries);
    }
    return ret;
}

//!
//! Retrieves the type of the blockblob metadata path we have.
//!
//! @param[in] bs
//! @param[in] path
//! @param[in] bb_id
//! @param[in] bb_id_size
//!
//! @return If 'path' looks like a blockblob metadata file (based on the suffix), return the type of the file and
//! set bb_id appropriately, else return 0 if it is an unrecognized file, else return -1 for error
//!
//! @pre
//!
//! @note
//!
static int typeof_blockblob_metadata_path(const blobstore * bs, const char *path, char *bb_id, unsigned int bb_id_size)
{
    assert(path);
    assert(bs->path);
    assert(strstr(path, bs->path) == path);

    const char *rel_path = path + strlen(bs->path) + 1; // +1 for '/'
    int p_len = strlen(rel_path);

    for (int i = 1; i < BLOCKBLOB_PATH_TOTAL; i++) { // start at 1 to avoid BLOCKBLOB_PATH_NONE
        char suffix[1024];
        if (bs->format == BLOBSTORE_FORMAT_DIRECTORY) {
            snprintf(suffix, sizeof(suffix), "/%s", blobstore_metadata_suffixes[i]);
        } else {
            snprintf(suffix, sizeof(suffix), ".%s", blobstore_metadata_suffixes[i]);
        }
        unsigned int s_len = strlen(suffix);
        const char *sp = suffix + s_len - 1; // last char of suffix
        const char *pp = rel_path + p_len - 1; // last char of (relative) path
        unsigned int matched;
        for (matched = 0; *sp == *pp; sp--, pp--) {
            matched++;
            if (sp == suffix)
                break;
            if (pp == rel_path)
                break;
        }
        if (matched == s_len // whole suffix matched
            && matched < p_len) { // there is more than the suffix
            if ((bb_id_size - 1) < (p_len - s_len)) // not enough room in bb_id
                return -1;
            strncpy(bb_id, rel_path, p_len - s_len); // extract the name, without the suffix
            bb_id[p_len - s_len] = '\0'; // terminate the string
            return i;
        }
    }
    return 0;
}

//!
//!
//!
//! @param[in] bs
//! @param[in] bb_id
//!
//! @return the number of files and directories deleted as part of removing the
//! blob (thus, 0 means there was nothing to delete)
//!
//! @pre
//!
//! @note
//!
static int delete_blockblob_files(const blobstore * bs, const char *bb_id)
{
    int count = 0;

    for (int path_t = 1; path_t < BLOCKBLOB_PATH_TOTAL; path_t++) { // go through all types of blob-related files...
        char path[PATH_MAX];
        set_blockblob_metadata_path((blockblob_path_t) path_t, bs, bb_id, path, sizeof(path));
        if (unlink(path) == 0) // ...and try deleting them
            count++;
    }

    // delete blob's subdirectories if there are any
    char path[PATH_MAX];
    snprintf(path, sizeof(path), "%s/%s%s", bs->path, bb_id, bs->format == BLOBSTORE_FORMAT_DIRECTORY ? "/" : "");
    for (int i = strlen(path) - 1; i > 0; i--) {
        if (path[i] == '/') {
            path[i] = '\0';
            if (rmdir(path) == 0) {
                count++;
            } else {
                break;
            }
        }
    }

    return count;
}

//!
//! Helper for ensuring a directory required by blob exists
//!
//! @param[in] bs
//! @param[in] bb_id
//!
//! @return 0 = already existed, 1 = created OK, -1 = error
//!
//! @pre
//!
//! @note
//!
static int ensure_blockblob_metadata_path(const blobstore * bs, const char *bb_id)
{
    char base[PATH_MAX];
    snprintf(base, sizeof(base), "%s/%s", bs->path, bb_id);
    return ensure_directories_exist(base, !(bs->format == BLOBSTORE_FORMAT_DIRECTORY), NULL, NULL, BLOBSTORE_DIRECTORY_PERM);
}

//!
//!
//!
//! @param[in] bbs
//!
//! @pre
//!
//! @note
//!
static void free_bbs(blockblob * bbs)
{
    while (bbs) {
        blockblob *next_bb = bbs->next;
        EUCA_FREE(bbs);
        bbs = next_bb;
    }
}

//!
//!
//!
//! @param[in] bs
//! @param[in] bb_id
//! @param[in] timeout_usec
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static unsigned int check_in_use(blobstore * bs, const char *bb_id, long long timeout_usec)
{
    unsigned int in_use = 0;
    char path[PATH_MAX];

    // determine the path of the .lock file for this blob
    set_blockblob_metadata_path(BLOCKBLOB_PATH_LOCK, bs, bb_id, path, sizeof(path));

    _err_off(); // do not complain if metadata files do not exist
    int fd = open_and_lock(path, BLOBSTORE_FLAG_RDWR, timeout_usec, BLOBSTORE_FILE_PERM); // try opening to see what happens
    if (fd != -1) {
        struct stat s;
        if (fstat(fd, &s) == 0) {
            if (s.st_size > 0) { // lock file was not truncated before being released => file not properly closed
                in_use |= BLOCKBLOB_STATUS_ABANDONED;
            }
        }
        close_and_unlock(fd);
    } else {
        in_use |= BLOCKBLOB_STATUS_OPENED; //! @TODO check if open failed for other reason?
    }

    if (read_blockblob_metadata_path(BLOCKBLOB_PATH_REFS, bs, bb_id, path, sizeof(path)) > 0) {
        in_use |= BLOCKBLOB_STATUS_MAPPED;
    }

    if (read_blockblob_metadata_path(BLOCKBLOB_PATH_DEPS, bs, bb_id, path, sizeof(path)) > 0) {
        in_use |= BLOCKBLOB_STATUS_BACKED;
    }
    _err_on();

    return in_use;
}

//!
//!
//!
//! @param[in] bb
//!
//! @pre
//!
//! @note
//!
static void set_device_path(blockblob * bb)
{
    char **dm_devs = NULL;
    int dm_devs_size = 0;

    _err_off(); // do not care if .dm file does not exist
    read_array_blockblob_metadata_path(BLOCKBLOB_PATH_DM, bb->store, bb->id, &dm_devs, &dm_devs_size);
    _err_on();

    if (dm_devs_size > 0) { // .dm is there => set device_path to the device-mapper path
        snprintf(bb->device_path, sizeof(bb->device_path), DM_FORMAT, dm_devs[dm_devs_size - 1]); // main device is the last one
        euca_strncpy(bb->dm_name, dm_devs[dm_devs_size - 1], sizeof(bb->dm_name));
        for (int i = 0; i < dm_devs_size; i++) {
            EUCA_FREE(dm_devs[i]);
        }
        EUCA_FREE(dm_devs);
    } else { // .dm is not there => set device_path to loopback
        char lo_dev[PATH_MAX] = "";
        _err_off(); // do not care if loopback file does not exist
        read_blockblob_metadata_path(BLOCKBLOB_PATH_LOOPBACK, bb->store, bb->id, lo_dev, sizeof(lo_dev));
        _err_on();
        euca_strncpy(bb->device_path, lo_dev, sizeof(bb->device_path));
    }
}

//!
//! Given a directory that may contain both blobstore files and
//! non-blobstore files (e.g., instance metadata and soft-links),
//! this deletes all files not managed by the blobstore.
//!
//! @param[in] bs blobstore that may contains blobs under dir_path
//! @param[in] dir_path directory in which to delete non-blob files
//!
//! @return count of files that the function tried to delete or -1 on error
//!
//!
int blobstore_delete_nonblobs(blobstore * bs, const char *dir_path)
{
    int ndeleted = 0;

    DIR *dir;
    if ((dir = opendir(dir_path)) == NULL) {
        return -1;
    }

    struct dirent *dir_entry;
    while ((dir_entry = readdir(dir)) != NULL) {
        char *entry_name = dir_entry->d_name;

        if (!strcmp(".", entry_name) || !strcmp("..", entry_name) || !strcmp(BLOBSTORE_METADATA_FILE, entry_name))
            continue; // ignore known unrelated files

        // get the path of the directory item
        char entry_path[BLOBSTORE_MAX_PATH];
        snprintf(entry_path, sizeof(entry_path), "%s/%s", dir_path, entry_name);

        char blob_id[BLOBSTORE_MAX_PATH];
        if (typeof_blockblob_metadata_path(bs, entry_path, blob_id, sizeof(blob_id)) > 0)
            continue; // ignore all blobstore files

        char *base_name = strdup(dir_path);
        LOGDEBUG("[%s] removing %s\n", basename(base_name), entry_name);
        free(base_name);
        unlink(entry_path);
        ndeleted++;
    }

    closedir(dir);
    return ndeleted;
}

//!
//!
//!
//! @param[in] bs
//! @param[in] dir_path
//! @param[in] tail_bb
//! @param[in] bb_to_avoid
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static blockblob **walk_bs(blobstore * bs, const char *dir_path, blockblob ** tail_bb, const blockblob * bb_to_avoid)
{
    DIR *dir;
    if ((dir = opendir(dir_path)) == NULL) {
        return tail_bb; // ignore access errors in blobstore directory
    }

    struct dirent *dir_entry;
    while ((dir_entry = readdir(dir)) != NULL) {
        char *entry_name = dir_entry->d_name;

        if (!strcmp(".", entry_name) || !strcmp("..", entry_name) || !strcmp(BLOBSTORE_METADATA_FILE, entry_name))
            continue; // ignore known unrelated files

        // get the path of the directory item
        char entry_path[BLOBSTORE_MAX_PATH];
        snprintf(entry_path, sizeof(entry_path), "%s/%s", dir_path, entry_name);
        struct stat sb;
        if (stat(entry_path, &sb) == -1) {
            // ignore access errors in the blobstore directory
            //! @TODO is this wise?
            continue;
        }
        // recurse if this is a directory
        if (S_ISDIR(sb.st_mode)) {
            tail_bb = walk_bs(bs, entry_path, tail_bb, bb_to_avoid);
            if (tail_bb == NULL) {
                closedir(dir);
                return NULL;
            }
            continue;
        }

        char blob_id[BLOBSTORE_MAX_PATH];
        if (typeof_blockblob_metadata_path(bs, entry_path, blob_id, sizeof(blob_id)) != BLOCKBLOB_PATH_BLOCKS)
            continue; // ignore all files except .blocks file

        if (bb_to_avoid != NULL && strncmp(blob_id, bb_to_avoid->id, sizeof(blob_id)) == 0)
            continue; // avoid that particular blockblob

        blockblob *bb = EUCA_ZALLOC(1, sizeof(blockblob));
        if (bb == NULL) {
            goto free;
        }
        *tail_bb = bb; // add to LL
        tail_bb = &(bb->next);

        // fill out the struct
        bb->store = bs;
        euca_strncpy(bb->id, blob_id, sizeof(bb->id));
        euca_strncpy(bb->blocks_path, entry_path, sizeof(bb->blocks_path));
        set_device_path(bb); // read .dm and .loopback and set bb->device_path accordingly
        bb->size_bytes = sb.st_size;
        bb->blocks_allocated = sb.st_blocks;
        bb->last_accessed = sb.st_atime;
        bb->last_modified = sb.st_mtime;
        bb->snapshot_type = BLOBSTORE_FORMAT_ANY; // it is not necessary to know whether this is a snapshot
        bb->in_use = check_in_use(bs, bb->id, 0);

        // see if it's hollow
        char buf[64];
        if (read_blockblob_metadata_path(BLOCKBLOB_PATH_HOLLOW, bb->store, bb->id, buf, sizeof(buf)) != -1) {
            bb->is_hollow = TRUE;
        }
        // if there is a .refs file, subtract the mapped blocks, if any, from the size
        char **array = NULL;
        int array_size = 0;
        if (read_array_blockblob_metadata_path(BLOCKBLOB_PATH_DEPS, bb->store, bb->id, &array, &array_size) != -1) {
            for (int i = 0; i < array_size; i++) {
                char *store_path = NULL;
                char *blob_id = NULL;
                char *rel_type = NULL;
                char *start_block = NULL;
                char *len_blocks = NULL;

                store_path = strtok(array[i], " ");
                blob_id = strtok(NULL, " ");
                rel_type = strtok(NULL, " ");
                start_block = strtok(NULL, " ");
                len_blocks = strtok(NULL, " ");
                if (rel_type && len_blocks && strcmp(rel_type, blobstore_relation_type_name[BLOBSTORE_MAP]) == 0) {
                    bb->size_bytes -= strtoull(len_blocks, NULL, 0) * 512LL;
                }
            }
        }

        if (array) {
            for (int i = 0; i < array_size; i++)
                EUCA_FREE(array[i]);
            EUCA_FREE(array);
        }
    }

free:
    closedir(dir);
    return tail_bb;
}

//!
//! Runs through the blobstore and puts all found blockblobs into a linked list, returning its head
//!
//! @param[in] bs
//! @param[in] bb_to_avoid
//!
//! @return A pointer to the head of a linked list containing all found blockblobs
//!
//! @pre
//!
//! @note
//!
static blockblob *scan_blobstore(blobstore * bs, const blockblob * bb_to_avoid)
{
    blockblob *bbs = NULL;
    if (walk_bs(bs, bs->path, &bbs, bb_to_avoid) == NULL) {
        if (bbs)
            free_bbs(bbs);
        bbs = NULL;
    }

    return bbs;
}

//!
//!
//!
//! @param[in] bb1
//! @param[in] bb2
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int compare_bbs(const void *bb1, const void *bb2)
{
    return (int)((*(blockblob **) bb1)->last_modified - (*(blockblob **) bb2)->last_modified);
}

//!
//!
//!
//! @param[in] bs
//! @param[in] bb_list
//! @param[in] need_blocks
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static long long purge_blockblobs_lru(blobstore * bs, blockblob * bb_list, long long need_blocks)
{
    int list_length = 0;
    long long purged = 0;

    for (blockblob * bb = bb_list; bb; bb = bb->next) {
        list_length++;
    }

    if (list_length) {
        blockblob *bb;
        int i;

        blockblob **bb_array = (blockblob **) EUCA_ZALLOC(list_length, sizeof(blockblob *));
        if (!bb_array)
            return purged;

        for (i = 0, bb = bb_list; bb; bb = bb->next, i++) {
            bb_array[i] = bb;
        }

        qsort(bb_array, list_length, sizeof(blockblob *), compare_bbs);

        int iteration = 0;
        int deleted;
        do {
            // iterate multiple times in case there are dependencies
            //! @TODO unify with _fsck's iteration code?
            deleted = 0; // deleted in this round
            for (i = 0; i < list_length; i++) {
                bb = bb_array[i];
                if (bb == NULL) // was either deleted or deemed undeletable on previous iteration
                    continue;
                bb->in_use = check_in_use(bs, bb->id, 0); // record in-use status

                char code = '?';
                if (bb->in_use & BLOCKBLOB_STATUS_MAPPED) {
                    // mapped blobs have children, thus cannot be deleted at this iteration
                    code = 'C';

                } else if (bb->in_use & BLOCKBLOB_STATUS_OPENED) {
                    bb_array[i] = NULL; // mark it to skip in the future
                    code = 'O';

                } else if (delete_blob_state(bb, BLOBSTORE_DELETE_TIMEOUT_USEC, 1) == -1) {
                    bb_array[i] = NULL; // mark it to skip in the future
                    code = '!';

                } else {
                    purged += round_up_sec(bb->size_bytes) / 512;
                    bb_array[i] = NULL; // mark it to skip in the future
                    code = 'D';
                    deleted++;
                }
                LOGDEBUG("LRU %d %08lld: %29s %c%c%c%c %c %9llu %s", iteration, purged, bb->id, (bb->in_use & BLOCKBLOB_STATUS_OPENED) ? ('o') : ('-'), // o = open
                         (bb->in_use & BLOCKBLOB_STATUS_BACKED) ? ('p') : ('-'), // p = has parents
                         (bb->in_use & BLOCKBLOB_STATUS_MAPPED) ? ('c') : ('-'), // c = has children
                         (bb->in_use & BLOCKBLOB_STATUS_ABANDONED) ? ('a') : ('-'), // a = was abandoned
                         code, // outcome codes: D=deleted, else C=children, !=undeletable, O=open
                         bb->size_bytes / 512L, // size is in sectors
                         ctime(&(bb->last_modified))); // ctime adds a newline
                if (purged >= need_blocks)
                    break;
            }
            iteration++;
        } while (deleted && (purged < need_blocks));
        EUCA_FREE(bb_array);
    }

    return purged;
}

//!
//!
//!
//! @param[in] bs
//! @param[in] meta
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_stat(blobstore * bs, blobstore_meta * meta)
{
    int ret = 0;

    if (blobstore_lock(bs, BLOBSTORE_LOCK_TIMEOUT_USEC) == -1) { // lock it so we can traverse blobstore safely
        return EUCA_ERROR;
    }
    // put existing items in the blobstore into a LL
    _blobstore_errno = BLOBSTORE_ERROR_OK;
    blockblob *bbs = scan_blobstore(bs, NULL);
    if (bbs == NULL) {
        if (_blobstore_errno != BLOBSTORE_ERROR_OK) {
            goto unlock;
        }
    }
    // analyze the LL, calculating sizes
    meta->blocks_allocated = 0;
    meta->blocks_unlocked = 0;
    meta->blocks_locked = 0;
    meta->num_blobs = 0;
    for (blockblob * abb = bbs; abb;) {
        //! @TODO unify this with locked/unlocked calculation in open()
        long long abb_size_blocks = round_up_sec(abb->size_bytes) / 512;
        if (abb->in_use & BLOCKBLOB_STATUS_OPENED) {
            // these can't be purged if we need space
            //! @TODO look into recursive purging of unused references?
            meta->blocks_locked += abb_size_blocks;
        } else {
            // these potentially can be purged, unless they are depended on by locked ones
            meta->blocks_unlocked += abb_size_blocks;
        }
        meta->blocks_allocated += abb->blocks_allocated;
        meta->num_blobs++;

        // free this node and move the pointer
        blockblob *old_bb = abb;
        abb = abb->next;
        EUCA_FREE(old_bb);
    }

unlock:

    if (blobstore_unlock(bs) == -1) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to unlock the blobstore");
    }

    euca_strncpy(meta->id, bs->id, sizeof(meta->id));
    meta->revocation_policy = bs->revocation_policy;
    meta->snapshot_policy = bs->snapshot_policy;
    meta->format = bs->format;
    meta->blocks_limit = bs->limit_blocks;
    if (realpath(bs->path, meta->path) == NULL) {
        LOGERROR("failed to resolve the blobstore path %s\n", bs->path);
        ret = EUCA_ERROR;
    }

    return ret;
}

//!
//! Read .refs file content and return any entries that point to blobs that no longer exist
//!
//! @param[in] bb
//! @param[out] refs
//!
//! @return size of the array placed into *refs, which caller must free, or -1 on error
//!
//! @pre
//!
//! @note
//!
static int get_stale_refs(const blockblob * bb, char ***refs)
{
    blobstore *bs = bb->store;
    char **array = NULL;
    int array_size = 0;
    int stale_refs = 0;

    if (read_array_blockblob_metadata_path(BLOCKBLOB_PATH_REFS, bb->store, bb->id, &array, &array_size) != -1) {
        for (int i = 0; i < array_size; i++) {
            char ref[BLOBSTORE_MAX_PATH + MAX_DM_NAME + 1];
            euca_strncpy(ref, array[i], sizeof(ref));

            char *store_path = strtok(array[i], " ");
            char *blob_id = strtok(NULL, " "); // the remaining entries in array[i] are ignored
            char ref_exists = 0;

            if (strlen(store_path) < 1 || strlen(blob_id) < 1)
                goto stale_ref;

            blobstore *ref_bs = bs;
            if (strcmp(bs->path, store_path)) { // if deleting reference in a different blobstore
                // need to open it
                ref_bs = blobstore_open(store_path, 0, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_ANY, BLOBSTORE_REVOCATION_ANY, BLOBSTORE_SNAPSHOT_ANY);
                if (ref_bs == NULL) // blobstore with a child blob does not exist
                    goto stale_ref;
            }

            blockblob *ref_bb = blockblob_open(ref_bs, blob_id, 0, 0, NULL, BLOBSTORE_FIND_TIMEOUT_USEC);
            if (ref_bb) {
                blockblob_close(ref_bb);
                ref_exists = 1;
            } else {
                if (_blobstore_errno != BLOBSTORE_ERROR_NOENT) // conservatively assume that unless the error says otherwise, the blob exists
                    ref_exists = 1;
            }
            if (ref_bs != bs) {
                blobstore_close(ref_bs);
            }

stale_ref:

            if (ref_exists) {
                EUCA_FREE(array[i]); // free names of refs that exist
            } else {
                strcpy(array[i], ref); // since strtok() clobbered the original value
                stale_refs++;
            }
        }
    }

    if (stale_refs > 0) {
        if (refs) {
            *refs = EUCA_ZALLOC(stale_refs, sizeof(char *));
            if (*refs == NULL) {
                stale_refs = -1; // OOM error
            }
        }
        for (int i = 0, j = 0; i < array_size; i++) {
            if (array[i]) { // ref does not exist
                if (refs && *refs) {
                    (*refs)[j++] = array[i];
                    assert(j <= stale_refs);
                } else {
                    EUCA_FREE(array[i]);
                }
            }
        }
    }

    if (array_size > 0)
        EUCA_FREE(array);

    return stale_refs;
}

//!
//! Checks the integrity check of the blobstore. With a non-NULL examiner(), each found
//! blob is passed to it for examination and the blob is deleted if function returns non-zero
//!
//! @param[in] bs
//! @param[in] examiner
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_fsck(blobstore * bs, int (*examiner) (const blockblob * bb))
{
    int ret = 0;

    if (blobstore_lock(bs, BLOBSTORE_LOCK_TIMEOUT_USEC) == -1) { // lock it so we can traverse blobstore safely
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to lock the blobstore");
        return -1;
    }
    // put existing items in the blobstore into a LL
    _blobstore_errno = BLOBSTORE_ERROR_OK;
    blockblob *bbs = scan_blobstore(bs, NULL);

    if (blobstore_unlock(bs) == -1) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to unlock the blobstore");
        ret = -1;
        goto free;
    }

    if (bbs == NULL) {
        if (_blobstore_errno != BLOBSTORE_ERROR_OK) {
            ret = -1;
        }
        goto free;
    }

    { // check objects in the blobstore

        unsigned int num_blobs = 0;
        unsigned int blobs_deleted = 0;
        unsigned int blobs_undeletable = 0;
        unsigned int blobs_unopenable = 0;
        unsigned int to_delete_prev = 0;
        unsigned int iterations = 1;
        for (; iterations < 10; iterations++) { // outer loop for multiple iterations over the list
            unsigned int to_delete = 0;

            // run through LL, examining each blockblob
            for (blockblob * abb = bbs; abb; abb = abb->next) {
                if (iterations == 1)
                    num_blobs++; // count all blobs on the first iteration

                if (abb->store == NULL) // these were cleared or condemned on a previous iteration
                    continue;

                // examiner(), if specified, tell us whether to delete the blob
                if (blockblob_check(abb) || // blob state is inconsistent
                    (examiner && examiner(abb))) { // blobstore user condemned the blob

                    blockblob *bb = blockblob_open(bs, abb->id, 0, 0, NULL, BLOBSTORE_FIND_TIMEOUT_USEC);
                    if (bb != NULL) {
                        if (bb->in_use & BLOCKBLOB_STATUS_MAPPED) {

                            // Since we are checking integrity, do not trust .refs file blindly,
                            // but ensure that the entries -- blobs depending on this one -- exist

                            char **stale_refs;
                            int num_stale_refs = get_stale_refs(bb, &stale_refs);
                            if (num_stale_refs > 0) {
                                for (int i = 0; i < num_stale_refs; i++) {
                                    // update the .refs file to remove this entry
                                    LOGINFO("removing stale/corrupted reference in blob %s to %s\n", bb->id, stale_refs[i]);
                                    update_entry_blockblob_metadata_path(BLOCKBLOB_PATH_REFS, bb->store, bb->id, stale_refs[i], 1);
                                    EUCA_FREE(stale_refs[i]);
                                }
                                EUCA_FREE(stale_refs);
                            }
                            // mapped blobs have children, thus cannot be deleted at this iteration
                            blockblob_close(bb);
                            to_delete++;

                        } else if (blockblob_delete(bb, BLOBSTORE_DELETE_TIMEOUT_USEC, 1) == -1) {
                            LOGWARN("WARNING: failed to delete blockblob %s\n", abb->id);
                            blockblob_close(bb);
                            abb->store = NULL; // so it will get skipped on next iteration
                            blobs_undeletable++;

                        } else {
                            LOGINFO("deleted stale/corrupted blob %s\n", abb->id);
                            abb->store = NULL; // so it will get skipped on next iteration
                            blobs_deleted++;
                        }
                    } else {
                        LOGWARN("could not open blockblob %s (it may be in use)\n", abb->id);
                        abb->store = NULL; // so it will get skipped on next iteration
                        blobs_unopenable++;
                    }
                }
            }
            assert(iterations < 11);

            if (to_delete == to_delete_prev) // could not delete anything new this iteration
                break;
            to_delete_prev = to_delete;
            if (to_delete == 0)
                break;
        }

        if (num_blobs > 0)
            LOGINFO("%s: examined %d blob(s) in %d iteration(s): "
                    "deleted %d, failed on %d + %d, failed to open %d\n", bs->path, num_blobs, iterations, blobs_deleted, to_delete_prev, blobs_undeletable, blobs_unopenable);
    }
free:
    if (bbs) {
        free_bbs(bbs);
    }

    return ret;
}

//!
//!
//!
//! @param[in] bs
//! @param[in] regex
//! @param[out] results
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_search(blobstore * bs, const char *regex, blockblob_meta ** results)
{
    blockblob_meta *head = NULL;
    blockblob *bbs = NULL;
    int ret = 0;
    regex_t re;

    if (regcomp(&re, regex, REG_NOSUB) != 0) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to parse search regular expression");
        return -1;
    }

    if (blobstore_lock(bs, BLOBSTORE_LOCK_TIMEOUT_USEC) == -1) { // lock it so we can traverse blobstore safely
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to lock the blobstore");
        ret = -1;
        goto free;
    }
    // put existing items in the blobstore into a LL
    _blobstore_errno = BLOBSTORE_ERROR_OK;
    bbs = scan_blobstore(bs, NULL);
    if (bbs == NULL) {
        if (_blobstore_errno != BLOBSTORE_ERROR_OK) {
            ret = -1;
            goto free;
        }
    }
    // run through LL, looking for matches
    unsigned int num_blobs = 0;
    unsigned int blobs_matched = 0;
    blockblob_meta *prev = NULL;
    for (blockblob * abb = bbs; abb; abb = abb->next) {
        num_blobs++;
        if (regexec(&re, abb->id, 0, NULL, 0) != 0)
            continue;
        blobs_matched++;

        blockblob_meta *bm = EUCA_ZALLOC(1, sizeof(blockblob_meta));
        if (bm == NULL) {
            ERR(BLOBSTORE_ERROR_NOMEM, NULL);
            ret = -1;
            goto free;
        }

        euca_strncpy(bm->id, abb->id, sizeof(bm->id));
        bm->bs = bs;
        bm->size_bytes = abb->size_bytes;
        bm->in_use = abb->in_use;
        bm->is_hollow = abb->is_hollow;
        bm->last_accessed = abb->last_accessed;
        bm->last_modified = abb->last_modified;
        if (head == NULL) {
            head = bm;
        } else {
            prev->next = bm;
            bm->prev = prev;
        }
        prev = bm;
    }

    *results = head;
    ret = blobs_matched;

free:
    regfree(&re); // free the regular expression
    if (bbs)
        free_bbs(bbs); // free the blockblobs LL returned by the search function

    if (blobstore_unlock(bs) == -1) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to unlock the blobstore");
        ret = -1;
    }

    if (ret < 0) { // there were problems, so free the partial linked list, if any
        for (blockblob_meta * bm = head; bm;) {
            blockblob_meta *next = bm->next;
            EUCA_FREE(bm);
            bm = next;
        }
    }

    return ret;
}

//!
//!
//!
//! @param[in] bs
//! @param[in] regex
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blobstore_delete_regex(blobstore * bs, const char *regex)
{
    blockblob_meta *matches = NULL;
    int found = blobstore_search(bs, regex, &matches);
    int left_to_delete = found;
    int deleted;
    do {
        // iterate multiple times in case there are dependencies
        //! @TODO unify with _fsck's iteration code?
        deleted = 0; // deleted in this round
        for (blockblob_meta * bm = matches; bm; bm = bm->next) {
            blockblob *bb = blockblob_open(bs, bm->id, 0, 0, NULL, BLOBSTORE_FIND_TIMEOUT_USEC);
            if (bb != NULL) {
                if (bb->in_use & BLOCKBLOB_STATUS_MAPPED) {
                    // mapped blobs have children, thus cannot be deleted at this iteration
                    blockblob_close(bb);
                    continue;
                }
                if (blockblob_delete(bb, BLOBSTORE_DELETE_TIMEOUT_USEC, 0) == -1) {
                    blockblob_close(bb);
                } else {
                    deleted++;
                }
            }
        }
    } while (deleted && (left_to_delete -= deleted));

    // free the search results
    for (blockblob_meta * bm = matches; bm;) {
        blockblob_meta *next = bm->next;
        EUCA_FREE(bm);
        bm = next;
    }

    return (left_to_delete == 0) ? (found) : (-1);
}

//!
//!
//!
//! @param[in] bs
//! @param[in] id can be NULL if creating, in which case blobstore will pick a random ID
//! @param[in] size_bytes on create: reserve this size; on open: verify the size, unless set to 0
//! @param[in] flags BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_EXCL - same semantcs as for open() flags, BLOBSTORE_FLAG_HOLLOW - when creating
//! @param[in] sig if non-NULL, on create sig is recorded, on open it is verified
//! @param[in] timeout_usec maximum wait, in microseconds
//!
//! @return
//!
//! @pre
//!
//! @note
//!
blockblob *blockblob_open(blobstore * bs, const char *id, unsigned long long size_bytes, unsigned int flags, const char *sig, unsigned long long timeout_usec)
{
    long long size_blocks = round_up_sec(size_bytes) / 512;
    if (flags & ~(BLOBSTORE_FLAG_CREAT | BLOBSTORE_FLAG_EXCL | BLOBSTORE_FLAG_HOLLOW)) {
        ERR(BLOBSTORE_ERROR_INVAL, "only _CREAT, _EXCL, & _HOLLOW flags are allowed");
        return NULL;
    }
    if (id == NULL && !(flags & BLOBSTORE_FLAG_CREAT)) {
        ERR(BLOBSTORE_ERROR_INVAL, "NULL id is only allowed with _CREAT");
        return NULL;
    }
    if (size_blocks == 0 && (flags & BLOBSTORE_FLAG_CREAT)) {
        ERR(BLOBSTORE_ERROR_INVAL, "size_blocks can be 0 only without _CREAT");
        return NULL;
    }
    if (size_blocks != 0 && (flags & BLOBSTORE_FLAG_CREAT) && (size_blocks > bs->limit_blocks) && !(flags && BLOBSTORE_FLAG_HOLLOW)) {
        ERR(BLOBSTORE_ERROR_NOSPC, NULL);
        return NULL;
    }

    LOGTRACE("{%u} blockblob_open: opening blob id=%s flags=%d timeout=%lld\n", (unsigned int)pthread_self(), id, flags, timeout_usec);

    blockblob *bbs = NULL; // a temp LL of blockblobs, used for computing free space and for purging
    blockblob *bb = EUCA_ZALLOC(1, sizeof(blockblob));
    if (bb == NULL) {
        ERR(BLOBSTORE_ERROR_NOMEM, NULL);
        goto out;
    }

    bb->store = bs;
    if (id) {
        euca_strncpy(bb->id, id, sizeof(bb->id));
    } else {
        gen_id(bb->id, sizeof(bb->id));
    }
    bb->fd_lock = -1;
    bb->fd_blocks = -1;
    bb->size_bytes = size_bytes;
    set_blockblob_metadata_path(BLOCKBLOB_PATH_BLOCKS, bs, bb->id, bb->blocks_path, sizeof(bb->blocks_path));

    int blobstore_locked = 0;
    if (blobstore_lock(bs, timeout_usec) == -1) { // lock it so we can create blob's file atomically
        goto free; // failed to obtain a lock on the blobstore
    } else {
        blobstore_locked = 1;
    }

    //! @TODO maybe don't create directories needlessly if flags==0?
    int created_directory = ensure_blockblob_metadata_path(bs, bb->id);
    if (created_directory == -1) {
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        goto unlock;
    }
    if (blobstore_unlock(bs) == -1) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to unlock the blobstore");
        goto free;
    }
    blobstore_locked = 0;

    int created_blob = 0;
    char lpath[PATH_MAX];
    set_blockblob_metadata_path(BLOCKBLOB_PATH_LOCK, bs, bb->id, lpath, sizeof(lpath));
    bb->fd_lock = open_and_lock(lpath, flags | BLOBSTORE_FLAG_RDWR, timeout_usec, BLOBSTORE_FILE_PERM); // blobs are always opened with exclusive write access
    if (bb->fd_lock == -1) {
        // failed to open/create and lock the blockblob
        goto clean;
    }
    char thread_id[512];
    int thread_id_len = 0;
    snprintf(thread_id, sizeof(thread_id), "%d/%u", getpid(), (unsigned int)pthread_self());
    thread_id_len = strlen(thread_id);
    if (write(bb->fd_lock, thread_id, thread_id_len) != thread_id_len) {
        // Fail to write our thread indentifier in the lock file.
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to write to the blobstore");
        goto clean;
    }
    // convert BLOBSTORE_* flags into standard Posix open() flags and open/create the blocks file
    int o_flags = 0;
    if (flags & BLOBSTORE_FLAG_RDONLY) {
        o_flags |= O_RDONLY;
    } else if ((flags & BLOBSTORE_FLAG_RDWR) || (flags & BLOBSTORE_FLAG_CREAT)) {
        o_flags |= O_RDWR;
        if (flags & BLOBSTORE_FLAG_CREAT) {
            o_flags |= O_CREAT;
            // intentionally ignore _EXCL supplied without _CREAT
            if (flags & BLOBSTORE_FLAG_EXCL)
                o_flags |= O_EXCL;
        }
    }
    bb->fd_blocks = open(bb->blocks_path, o_flags, BLOBSTORE_FILE_PERM);
    if (bb->fd_blocks == -1) { // failed to open/create the content file
        PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
        goto clean;
    }

    struct stat sb;
    if (fstat(bb->fd_blocks, &sb) == -1) {
        goto clean;
    }

    if (sb.st_size == 0) { // new blob
        created_blob = 1;

        if (blobstore_lock(bs, timeout_usec) == -1) { // lock it so we can traverse blobstore safely
            goto clean; // failed to obtain a lock on the blobstore
        } else {
            blobstore_locked = 1;
        }

        // put existing items in the blobstore into a LL
        _blobstore_errno = BLOBSTORE_ERROR_OK;
        bbs = scan_blobstore(bs, bb);
        if (bbs == NULL) {
            if (_blobstore_errno != BLOBSTORE_ERROR_OK) {
                goto clean;
            }
        }
        // a bit of a hack: HOLLOW blobs skip the blobstore limit check upon creation
        if (flags & BLOBSTORE_FLAG_HOLLOW) {
            bb->is_hollow = TRUE;
            if (write_blockblob_metadata_path(BLOCKBLOB_PATH_HOLLOW, bs, bb->id, "this blob is hollow\n"))
                goto clean;

        } else { // enforce blobstore limits

            // analyze the LL, calculating sizes
            long long blocks_unlocked = 0;
            long long blocks_locked = 0;
            unsigned int num_blobs = 0;
            for (blockblob * abb = bbs; abb; abb = abb->next) {
                long long abb_size_blocks = round_up_sec(abb->size_bytes) / 512;
                if (abb->is_hollow)
                    abb_size_blocks = 0;
                if (abb->in_use & BLOCKBLOB_STATUS_OPENED) {
                    // these can't be purged if we need space
                    //! @TODO look into recursive purging of unused references?
                    blocks_locked += abb_size_blocks;
                } else {
                    blocks_unlocked += abb_size_blocks; // these potentially can be purged, unless they are depended on by locked ones
                }
                num_blobs++;
            }

            long long blocks_free = bs->limit_blocks - (blocks_unlocked + blocks_locked);
            if (blocks_free < size_blocks) {
                if (!(bs->revocation_policy == BLOBSTORE_REVOCATION_LRU) // not allowed to purge
                    || (blocks_free + blocks_unlocked) < size_blocks) { // not enough purgeable material
                    ERR(BLOBSTORE_ERROR_NOSPC, NULL);
                    goto clean;
                }
                long long blocks_needed = size_blocks - blocks_free;
                _err_off(); // do not care about errors duing purging
                long long blocks_freed = purge_blockblobs_lru(bs, bbs, blocks_needed);
                _err_on();
                if (blocks_freed < blocks_needed) {
                    ERR(BLOBSTORE_ERROR_NOSPC, "could not purge enough from cache");
                    goto clean;
                }
            }
        }

        if (lseek(bb->fd_blocks, size_bytes - 1, SEEK_CUR) == (off_t) - 1) { // create a file with a hole
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            goto clean;
        }
        if (write(bb->fd_blocks, zero_buf, 1) != (ssize_t) 1) {
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            goto clean;
        }
        if (sig)
            if (write_blockblob_metadata_path(BLOCKBLOB_PATH_SIG, bs, bb->id, sig)) {
                goto clean;
            }
        bb->snapshot_type = BLOBSTORE_SNAPSHOT_NONE; // just created, so not a snapshot

        if (blobstore_unlock(bs) == -1) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to unlock the blobstore");
        }
        blobstore_locked = 0;

    } else { // blob existed

        char buf[BLOBSTORE_SIG_MAX];

        if (bb->size_bytes == 0) { // find out the size from the file size
            bb->size_bytes = sb.st_size;
        } else if (bb->size_bytes != sb.st_size) { // verify the size specified by the user
            LOGERROR("{%u} encountered a size mismatch when opening a blob (requested %lld, found %ld)\n", (unsigned int)pthread_self(), bb->size_bytes, sb.st_size);
            ERR(BLOBSTORE_ERROR_SIGNATURE, "size of the existing blockblob does not match");
            goto clean;
        }
        // determine whether this blob is a map of another,
        // in which case the blocks are backing and should
        // not be accessed directly
        if (read_blockblob_metadata_path(BLOCKBLOB_PATH_DM, bs, bb->id, buf, sizeof(buf)) > 0) {
            bb->snapshot_type = BLOBSTORE_SNAPSHOT_DM;
        } else {
            bb->snapshot_type = BLOBSTORE_SNAPSHOT_NONE;
        }

        // check if its hollow
        if (read_blockblob_metadata_path(BLOCKBLOB_PATH_HOLLOW, bs, bb->id, buf, sizeof(buf)) != -1) {
            bb->is_hollow = TRUE;
        }

        if (sig && (strlen(sig) > 0)) { // check the signature, if there
            int sig_size;
            if ((sig_size = read_blockblob_metadata_path(BLOCKBLOB_PATH_SIG, bs, bb->id, buf, sizeof(buf))) != strlen(sig)
                || (strncmp(sig, buf, sig_size) != 0)) {
                LOGERROR("{%u} encountered signature mismatch when opening a blob (requested size [%ld], found [%d])\n", (unsigned int)pthread_self(), strlen(sig), sig_size);
                ERR(BLOBSTORE_ERROR_SIGNATURE, NULL);
                goto clean;
            }
        }
        // check its in-use status
        bb->in_use = check_in_use(bs, bb->id, 0);
    }

    { // create a loopback device, if there isn't a valid one already (this may happen whether the blob is new or old)
        char lo_dev[PATH_MAX] = "";
        struct stat sb;

        _err_off(); // do not care if loopback file does not exist
        read_blockblob_metadata_path(BLOCKBLOB_PATH_LOOPBACK, bs, bb->id, lo_dev, sizeof(lo_dev));
        _err_on();
        if ((strlen(lo_dev) < 1) // nothing in .loopback file
            || (stat(lo_dev, &sb) == -1) // something in .loopback that does not exist
            || (!S_ISBLK(sb.st_mode))) { // something in .loopback that is not block device

            if (diskutil_loop(bb->blocks_path, 0, lo_dev, sizeof(lo_dev))) {
                ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to obtain a loopback device for a blockblob");
                goto clean;
            }
            write_blockblob_metadata_path(BLOCKBLOB_PATH_LOOPBACK, bs, bb->id, lo_dev);
        }
    }

    set_device_path(bb); // read .dm and .loopback and set bb->device_path accordingly

    goto out; // all is well

clean:
    {
        int saved_errno = _blobstore_errno; // save it because close_and_unlock() or delete_blockblob_files() may reset it
        if (bb->fd_lock != -1) {
            if (ftruncate(bb->fd_lock, 0) != 0) {
                ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to truncate the blobstore lock file.");
            }
            close_and_unlock(bb->fd_lock);
        }
        if (bb->fd_blocks != -1) {
            close(bb->fd_blocks);
        }
        if (created_directory || created_blob) { // only delete disk state if we created it
            delete_blockblob_files(bs, bb->id);
        }
        if (saved_errno) {
            _blobstore_errno = saved_errno;
        }
    }

unlock:
    {
        int saved_errno = _blobstore_errno;
        if (blobstore_locked && blobstore_unlock(bs) == -1) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to unlock the blobstore");
            if (saved_errno) {
                _blobstore_errno = saved_errno;
            }
        }
    }

free:
    EUCA_FREE(bb);

out:
    LOGTRACE("{%u} blockblob_open: done with blob id=%s ret=%p\n", (unsigned int)pthread_self(), id, bb);
    if (bb == NULL) {
        LOGTRACE("{%u} blockblob_open: errno=%d msg=%s\n", (unsigned int)pthread_self(), _blobstore_errno, blobstore_get_last_msg());
    }

    free_bbs(bbs);
    return bb;
}

//!
//!
//!
//! @param[in] bs
//! @param[in] bb_id
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int loop_remove(blobstore * bs, const char *bb_id)
{
    char path[PATH_MAX] = "";
    int ret = 0;

    _err_off(); // do not care if loopback file does not exist
    read_blockblob_metadata_path(BLOCKBLOB_PATH_LOOPBACK, bs, bb_id, path, sizeof(path)); // loads path of /dev/loop?
    _err_on();

    if (strlen(path)) {
        if (diskutil_unloop(path)) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to remove loopback device for blockblob");
            ret = -1;
        } else {
            set_blockblob_metadata_path(BLOCKBLOB_PATH_LOOPBACK, bs, bb_id, path, sizeof(path)); // load path of .../loopback file itself
            unlink(path);
        }
    }

    return ret;
}

//!
//! releases the blob locks, allowing others to open() it, and frees the blockblob handle
//!
//! @param[in] bb
//!
//! @return
//!
//! @pre
//!
//! @note
//!
int blockblob_close(blockblob * bb)
{
    if (bb == NULL) {
        ERR(BLOBSTORE_ERROR_INVAL, NULL);
        return -1;
    }
    int ret = 0;
    LOGTRACE("{%u} blockblob_close: closing blob id=%s\n", (unsigned int)pthread_self(), bb->id);

    // do not remove /dev/loop* if it is used by device mapper
    // (we do not care about BLOCKBLOB_STATUS_OPENED because
    // it should be only this thread that has the blob open)
    int in_use = check_in_use(bb->store, bb->id, 0);
    if (!(in_use & (BLOCKBLOB_STATUS_MAPPED | BLOCKBLOB_STATUS_BACKED))) {
        ret = loop_remove(bb->store, bb->id);
    }
    ret |= close(bb->fd_blocks);
    if (ftruncate(bb->fd_lock, 0) != 0) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to truncate the blobstore lock file.");
    }
    ret |= close_and_unlock(bb->fd_lock);
    EUCA_FREE(bb); // we free the blob regardless of whether closing succeeds or not
    return ret;
}

//!
//!
//!
//! @param[in] dev_name
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int dm_suspend_resume(const char *dev_name)
{
    int ret = EUCA_OK;

    if ((ret = euca_execlp(NULL, helpers_path[ROOTWRAP], helpers_path[DMSETUP], "suspend", dev_name, NULL)) != EUCA_OK) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to suspend device with 'dmsetup'");
        return (-1);
    }

    if ((ret = euca_execlp(NULL, helpers_path[ROOTWRAP], helpers_path[DMSETUP], "resume", dev_name, NULL)) != EUCA_OK) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to resume device with 'dmsetup'");
        return (-1);
    }

    return (0);
}

//!
//!
//!
//! @param[in] dev_name
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int dm_check_device(const char *dev_name)
{
    // see if the device exists
    char dm_path[MAX_DM_PATH];
    snprintf(dm_path, sizeof(dm_path), DM_PATH "%s", dev_name);
    return check_path(dm_path); // we do not use check_block() because /dev/mapper/... entries can be sym links
}

//!
//!
//!
//! @param[in] dev_name
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int dm_delete_device(const char *dev_name)
{
    int ret = 0;
    int retries = 1;
    char dm_path[MAX_DM_PATH] = "";

    // see if the device to delete exists
    snprintf(dm_path, sizeof(dm_path), DM_PATH "%s", dev_name);
    errno = 0;
    if (check_path(dm_path) && (errno == ENOENT)) // we do not use check_block() because /dev/mapper/... entries can be sym links
        return (0);

try_again:
    myprintf(EUCA_LOG_INFO, "removing device %s (retries=%d)\n", dev_name, retries);
    if ((euca_execlp(NULL, helpers_path[ROOTWRAP], helpers_path[DMSETUP], "remove", dev_name, NULL)) != EUCA_OK) {
        if (retries--) {
            usleep(100);
            goto try_again;
        }
        ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to remove device mapper device with 'dmsetup'");
        ret = -1;
    }
    return (ret);
}

//!
//!
//!
//! @param[in] dev_names
//! @param[in] size
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int dm_delete_devices(char *dev_names[], int size)
{
    if (size < 1)
        return 0;
    int ret = 0;

    // construct list of device names in the order that they should be removed
    int devices = 0;
    char **dev_names_removable = EUCA_ZALLOC(size, sizeof(char *));
    if (dev_names_removable == NULL) {
        ERR(BLOBSTORE_ERROR_NOMEM, NULL);
        return -1;
    }
    for (int i = size - 1; i >= 0; i--) {
        char *name = dev_names[i];
        int seen = 0;
        for (int j = i + 1; j < size; j++) {
            if (!strcmp(name, dev_names[j])) {
                seen = 1;
                break;
            }
        }
        if (!seen) {
            dev_names_removable[devices++] = name;
        }
    }

    // run through devices and remove them
    for (int i = 0; i < devices; i++) {

        // some of these devices may have children devices that were created
        // by GNU parted for each of the partitions inside; here we look for
        // those devices and remove them so the main device is not 'busy'.
        for (int j = 1; j < 10; j++) {
            char name_p[1024]; // device mapper name of a potential partition entry
            char path_p[1024]; // path to the device mapper file
            // just append 'pN' to the name, e.g., sda -> sdap1
            snprintf(name_p, sizeof(name_p), "%sp%d", dev_names_removable[i], j);
            snprintf(path_p, sizeof(path_p), DM_FORMAT, name_p);
            if (check_path(path_p) == 0) {
                dm_delete_device(name_p);
            }
            // also try appending just 'N', since that may be the name format, too
            snprintf(name_p, sizeof(name_p), "%s%d", dev_names_removable[i], j);
            snprintf(path_p, sizeof(path_p), DM_FORMAT, name_p);
            if (check_path(path_p) == 0) {
                dm_delete_device(name_p);
            }
        }
        ret = dm_delete_device(dev_names_removable[i]);
    }
    EUCA_FREE(dev_names_removable);

    return ret;
}

//!
//!
//!
//! @param[in] dev_names
//! @param[in] dm_tables
//! @param[in] size
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int dm_create_devices(char *dev_names[], char *dm_tables[], int size)
{
    int i = 0;
    int fd = 0;
    int status = 0;
    int rc = EUCA_OK;
    int rbytes = 0;
    pid_t cpid = 0;
    char tmpfile[EUCA_MAX_PATH] = "";
    char dm_path[MAX_DM_PATH] = "";

    for (i = 0; i < size; i++) {
        // create devices one by one
        myprintf(EUCA_LOG_INFO, "creating device %s\n", dev_names[i]);

        if ((cpid = fork()) < 0) {
            // fork error
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            goto cleanup;
        } else if (cpid == 0) {
            // child process - runs `dmsetup` using system()
            bzero(tmpfile, sizeof(tmpfile));
            snprintf(tmpfile, sizeof(tmpfile) - 1, "/tmp/dmsetup.XXXXXX");
            if ((fd = safe_mkstemp(tmpfile)) >= 0) {
                if ((rbytes = write(fd, dm_tables[i], strlen(dm_tables[i]))) != strlen(dm_tables[i])) {
                    // if write error
                    LOGERROR("{%u} error: dm_create_devices: write returned number of bytes != write buffer: %d/%ld\n", (unsigned int)pthread_self(), rbytes, strlen(dm_tables[i]));
                    unlink(tmpfile);
                    exit(1);
                }
                close(fd);
            } else {
                // couldn't get fd
                LOGERROR("{%u} error: dm_create_devices: couldn't open temporary file %s: %s\n", (unsigned int)pthread_self(), tmpfile, strerror(errno));
                unlink(tmpfile);
                exit(1);
            }

            // invoke `dmsetup create ...`
            rc = euca_execlp(&status, helpers_path[ROOTWRAP], helpers_path[DMSETUP], "create", dev_names[i], tmpfile, NULL);

            // free out temp file
            unlink(tmpfile);

            // pass back dmsetup's return code
            exit(WEXITSTATUS(status));
        }
        // parent - waits for child, reacts to status
        if ((rc = timewait(cpid, &status, BLOBSTORE_DMSETUP_TIMEOUT_SEC)) <= 0) {
            LOGERROR("{%u} error: dm_create_devices: bad exit from dmsetup child: %d\n", (unsigned int)pthread_self(), rc);
            PROPAGATE_ERR(BLOBSTORE_ERROR_UNKNOWN);
            goto cleanup;
        }

        if (WEXITSTATUS(status) != 0) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to set up device mapper table with 'dmsetup'");
            myprintf(EUCA_LOG_INFO, "{%u} command: %s %s create %s\n", (unsigned int)pthread_self(), helpers_path[ROOTWRAP], helpers_path[DMSETUP], dev_names[i]);
            myprintf(EUCA_LOG_INFO, "{%u} input: %s", (unsigned int)pthread_self(), dm_tables[i]);
            goto cleanup;
        }

        snprintf(dm_path, sizeof(dm_path), DM_PATH "%s", dev_names[i]);
        if (diskutil_ch(dm_path, EUCALYPTUS_ADMIN, NULL, BLOBSTORE_FILE_PERM) != EUCA_OK) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to change permissions on the device mapper file\n");
            goto cleanup;
        }
    }

    return (0);
cleanup:
    _err_off();
    dm_delete_devices(dev_names, i + 1);
    _err_on();
    return (-1);
}

//!
//!
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static char *dm_get_zero(void)
{
    static char dev_zero[] = DM_PATH EUCA_ZERO;

    struct stat sb;
    int tried = 0;
    while (stat(dev_zero, &sb) == -1) {
        if (tried) {
            ERR(BLOBSTORE_ERROR_UNKNOWN, "failed to create blockblob zero block device");
            return NULL;
        }

        char *dm_tables[1] = { "0 " EUCA_ZERO_SIZE " zero" };
        char *dm_names[1] = { EUCA_ZERO };
        dm_create_devices(dm_names, dm_tables, 1);

        tried = 1;
    }

    if (!S_ISBLK(sb.st_mode)) {
        ERR(BLOBSTORE_ERROR_UNKNOWN, "blockblob zero is not a block device");
        return NULL;
    }

    return dev_zero;
}

//!
//!
//!
//! @param[in] bb
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int blockblob_check(const blockblob * bb)
{
    char **array = NULL;
    int array_size = 0;
    int err = 0;
    _err_off(); // do not care if metadata files do not exist

    // check on dm devices listed in .dm of this blob, if any
    if (read_array_blockblob_metadata_path(BLOCKBLOB_PATH_DM, bb->store, bb->id, &array, &array_size) != -1) {
        for (int i = 0; i < array_size; i++) {
            if (dm_check_device(array[i]))
                err++;
            EUCA_FREE(array[i]);
        }
        EUCA_FREE(array);
    }
    // check on the loop device listed in .loopback of the blob, if any
    char lo_dev[PATH_MAX] = "";
    read_blockblob_metadata_path(BLOCKBLOB_PATH_LOOPBACK, bb->store, bb->id, lo_dev, sizeof(lo_dev));
    if (strlen(lo_dev) > 0) {
        struct stat sb;
        if (stat(lo_dev, &sb) == -1) {
            err++;
        } else if (!S_ISBLK(sb.st_mode)) {
            err++;
        } else if (diskutil_loop_check(bb->blocks_path, lo_dev)) {
            err++;
        }
    }
    // check on .refs that point to blobs that no longer exist
    if (get_stale_refs(bb, NULL) > 0)
        err++;

    // check on .lock files that are non-zero => blobs that were not closed properly
    if (bb->in_use & BLOCKBLOB_STATUS_ABANDONED)
        err++;

    _err_on();
    return err;
}

//!
//!
//!
//! @param[in] bb
//! @param[in] timeout_usec
//! @param[in] do_force
//!
//! @return
//!
//! @pre
//!
//! @note
//!
static int delete_blob_state(blockblob * bb, long long timeout_usec, char do_force)
{
    blobstore *bs = bb->store;
    char **array = NULL;
    int array_size = 0;
    int ret = 0;

    // delete dm devices listed in .dm of this blob
    if (read_array_blockblob_metadata_path(BLOCKBLOB_PATH_DM, bb->store, bb->id, &array, &array_size) == -1 || dm_delete_devices(array, array_size) == -1) {
        if (!do_force) {
            ret = -1;
            goto free;
        }
    }
    for (int i = 0; i < array_size; i++) {
        EUCA_FREE(array[i]);
    }
    EUCA_FREE(array);
    array_size = 0;
    array = NULL;

    // Read in .deps (blobs that this blob depends on),
    // so as to update their .refs (blobs depending on them).
    if (read_array_blockblob_metadata_path(BLOCKBLOB_PATH_DEPS, bb->store, bb->id, &array, &array_size) == -1) {
        ret = -1;
        if (!do_force) {
            ret = -1;
            goto free;
        }
    }
    char my_ref[BLOBSTORE_MAX_PATH + MAX_DM_NAME + 1];
    snprintf(my_ref, sizeof(my_ref), "%s %s", bb->store->path, bb->id);
    for (int i = 0; i < array_size; i++) {
        char *store_path = strtok(array[i], " ");
        char *blob_id = strtok(NULL, " "); // the remaining entries in array[i] are ignored

        if (strlen(store_path) < 1 || strlen(blob_id) < 1) {
            continue; //! @TODO print a warning about store/blob corruption?
        }

        blobstore *dep_bs = bs;
        if (strcmp(bs->path, store_path)) { // if deleting reference in a different blobstore
            // need to open it
            dep_bs = blobstore_open(store_path, 0, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_ANY, BLOBSTORE_REVOCATION_ANY, BLOBSTORE_SNAPSHOT_ANY);
            if (dep_bs == NULL)
                continue; //! @TODO print a warning about store/blob corruption?
            if (blobstore_lock(dep_bs, timeout_usec) == -1) { // lock this (different) blobstore, too, so .refs are updated atomically
                blobstore_close(dep_bs);
                continue; //! @TODO print a warning about store/blob corruption?
            }
        }
        // update .refs file on each of the dependencies
        if (update_entry_blockblob_metadata_path(BLOCKBLOB_PATH_REFS, dep_bs, blob_id, my_ref, 1) == -1) {
            //! @TODO print a warning about store/blob corruption?
        }

        if (!(check_in_use(dep_bs, blob_id, 0) & ~(BLOCKBLOB_STATUS_ABANDONED))) { // in use except abandoned
            loop_remove(dep_bs, blob_id); //! @TODO do we care about errors?
        }
        if (dep_bs != bs) {
            blobstore_unlock(dep_bs);
            blobstore_close(dep_bs);
        }
    }

    // remove the loopback entry for this blob
    if (loop_remove(bs, bb->id) == -1) {
        ret = -1;
    }
    // remove the files, data and metadata, for of this blob
    if (delete_blockblob_files(bs, bb->id) < 1) {
        ret = -1;
    }

free:
    for (int i = 0; i < array_size; i++) {
        EUCA_FREE(array[i]);
    }
    EUCA_FREE(array);

    return ret;
}

//!
//! If no outside references to the blob exist, and blob is not protected,
//! deletes the blob and its metadata
//!
//! @param[in] bb
//! @param[in] timeout_usec
//! @param[in] do_force
//!
//! @return 0 if cleanup was successful and frees the blockblob handle, -1 otherwise,
//! and DOES NOT free the