diff --git a/BUILD.bazel b/BUILD.bazel index 0114b89a9..91cc1a5fb 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -243,6 +243,202 @@ cc_library( # === End of rpc definitions === +# === Begin of plasma definitions === + +# TODO(mehrdadn): (How to) support dynamic linking? +PROPAGATED_WINDOWS_DEFINES = ["ARROW_STATIC"] + +PLASMA_COPTS = COPTS + select({ + "@bazel_tools//src/conditions:windows": [ + "-D" + "WIN32_REPLACE_FD_APIS", + "/FI" + "win32fd.h", + ] + ["-D" + define for define in PROPAGATED_WINDOWS_DEFINES], + "//conditions:default": [ + "-DARROW_USE_GLOG", + ], +}) + +PLASMA_LINKOPTS = [] + select({ + "@bazel_tools//src/conditions:windows": [ + "-DefaultLib:" + "ws2_32.lib", + ], + "//conditions:default": [ + ], +}) + +cc_library( + name = "plasma_client", + srcs = [ + "src/ray/plasma/client.cc", + "src/ray/plasma/common.cc", + "src/ray/plasma/fling.cc", + "src/ray/plasma/io.cc", + "src/ray/plasma/malloc.cc", + "src/ray/plasma/plasma.cc", + "src/ray/plasma/protocol.cc", + ], + hdrs = [ + "src/ray/plasma/client.h", + "src/ray/plasma/common.h", + "src/ray/plasma/common_generated.h", + "src/ray/plasma/compat.h", + "src/ray/plasma/external_store.h", + "src/ray/plasma/fling.h", + "src/ray/plasma/io.h", + "src/ray/plasma/malloc.h", + "src/ray/plasma/plasma.h", + "src/ray/plasma/plasma_generated.h", + "src/ray/plasma/protocol.h", + ], + copts = PLASMA_COPTS, + defines = select({ + "@bazel_tools//src/conditions:windows": PROPAGATED_WINDOWS_DEFINES, + "//conditions:default": [], + }), + linkopts = PLASMA_LINKOPTS, + strip_include_prefix = "src/ray", + deps = [ + ":common_fbs", + ":plasma_fbs", + ":platform_shims", + "@arrow", + "@com_github_google_glog//:glog", + ], +) + +cc_binary( + name = "libplasma_java.so", + srcs = [ + "src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.cc", + "src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.h", + ":jni.h", + ":jni_md.h", + ], + copts = PLASMA_COPTS, + includes = [ + "src/ray", + ], + linkshared = 1, + linkstatic = 1, + deps = [":plasma_client"], +) + +genrule( + name = "copy_jni_h", + srcs = ["@bazel_tools//tools/jdk:jni_header"], + outs = ["jni.h"], + cmd = "cp -f $< $@", +) + +genrule( + name = "copy_jni_md_h", + srcs = select({ + "@bazel_tools//src/conditions:windows": ["@bazel_tools//tools/jdk:jni_md_header-windows"], + "@bazel_tools//src/conditions:darwin": ["@bazel_tools//tools/jdk:jni_md_header-darwin"], + "//conditions:default": ["@bazel_tools//tools/jdk:jni_md_header-linux"], + }), + outs = ["jni_md.h"], + cmd = "cp -f $< $@", +) + +genrule( + name = "plasma-jni-darwin-compat", + srcs = [":libplasma_java.so"], + outs = ["libplasma_java.dylib"], + cmd = "cp $< $@", + output_to_bindir = 1, +) + +cc_library( + name = "ae", + srcs = [ + "src/ray/plasma/thirdparty/ae/ae.c", + ], + hdrs = [ + "src/ray/plasma/thirdparty/ae/ae.h", + "src/ray/plasma/thirdparty/ae/ae_epoll.c", + "src/ray/plasma/thirdparty/ae/ae_evport.c", + "src/ray/plasma/thirdparty/ae/ae_kqueue.c", + "src/ray/plasma/thirdparty/ae/ae_select.c", + "src/ray/plasma/thirdparty/ae/config.h", + "src/ray/plasma/thirdparty/ae/zmalloc.h", + ], + copts = PLASMA_COPTS, + includes = [ + "src/ray/plasma/thirdparty/ae", + ], + strip_include_prefix = "src/ray", + deps = [ + ":platform_shims", + ], +) + +cc_library( + name = "plasma_lib", + srcs = [ + "src/ray/plasma/dlmalloc.cc", + "src/ray/plasma/events.cc", + "src/ray/plasma/eviction_policy.cc", + "src/ray/plasma/external_store.cc", + "src/ray/plasma/plasma_allocator.cc", + "src/ray/plasma/quota_aware_policy.cc", + ], + hdrs = [ + "src/ray/plasma/events.h", + "src/ray/plasma/eviction_policy.h", + "src/ray/plasma/external_store.h", + "src/ray/plasma/plasma_allocator.h", + "src/ray/plasma/quota_aware_policy.h", + "src/ray/plasma/store.h", + "src/ray/plasma/thirdparty/dlmalloc.c", + ], + copts = PLASMA_COPTS, + linkopts = PLASMA_LINKOPTS, + strip_include_prefix = "src/ray", + deps = [ + ":ae", + ":plasma_client", + ":platform_shims", + "@com_github_google_glog//:glog", + ], +) + +cc_binary( + name = "plasma_store_server", + srcs = [ + "src/ray/plasma/store.cc", + ], + copts = PLASMA_COPTS, + visibility = ["//visibility:public"], + deps = [ + ":plasma_lib", + ":platform_shims", + ], +) + +FLATC_ARGS = [ + "--gen-object-api", + "--gen-mutable", + "--scoped-enums", +] + +flatbuffer_cc_library( + name = "common_fbs", + srcs = ["src/ray/plasma/common.fbs"], + flatc_args = FLATC_ARGS, + out_prefix = "src/ray/plasma/", +) + +flatbuffer_cc_library( + name = "plasma_fbs", + srcs = ["src/ray/plasma/plasma.fbs"], + flatc_args = FLATC_ARGS, + includes = ["src/ray/plasma/common.fbs"], + out_prefix = "src/ray/plasma/", +) + +# === End of plasma definitions === + cc_library( name = "ray_common", srcs = glob( @@ -267,6 +463,7 @@ cc_library( ":common_cc_proto", ":gcs_cc_proto", ":node_manager_fbs", + ":plasma_client", ":ray_util", "@boost//:asio", "@com_github_grpc_grpc//:grpc++", @@ -275,7 +472,6 @@ cc_library( "@com_google_absl//absl/memory", "@com_google_googletest//:gtest", "@msgpack", - "@plasma//:plasma_client", ], ) @@ -453,6 +649,7 @@ cc_library( ":node_manager_fbs", ":node_manager_rpc", ":object_manager", + ":plasma_client", ":ray_common", ":ray_util", ":service_based_gcs_client_lib", @@ -468,7 +665,6 @@ cc_library( "@io_opencensus_cpp//opencensus/exporters/stats/prometheus:prometheus_exporter", "@io_opencensus_cpp//opencensus/stats", "@io_opencensus_cpp//opencensus/tags", - "@plasma//:plasma_client", ], ) @@ -533,17 +729,17 @@ cc_binary( cc_test( name = "core_worker_test", srcs = ["src/ray/core_worker/test/core_worker_test.cc"], - args = ["$(location @plasma//:plasma_store_server) $(location raylet) $(location raylet_monitor) $(location mock_worker) $(location gcs_server) $(location redis-cli) $(location redis-server) $(location libray_redis_module.so)"], + args = ["$(location //:plasma_store_server) $(location raylet) $(location raylet_monitor) $(location mock_worker) $(location gcs_server) $(location redis-cli) $(location redis-server) $(location libray_redis_module.so)"], copts = COPTS, data = [ "//:gcs_server", "//:libray_redis_module.so", "//:mock_worker", + "//:plasma_store_server", "//:raylet", "//:raylet_monitor", "//:redis-cli", "//:redis-server", - "@plasma//:plasma_store_server", ], deps = [ ":core_worker_lib", @@ -1002,10 +1198,10 @@ cc_library( ":gcs", ":object_manager_fbs", ":object_manager_rpc", + ":plasma_client", ":ray_common", ":ray_util", "@boost//:asio", - "@plasma//:plasma_client", ], ) @@ -1076,13 +1272,13 @@ cc_library( ], visibility = ["//visibility:public"], deps = [ + ":plasma_client", ":sha256", "@boost//:asio", "@com_github_google_glog//:glog", "@com_google_absl//absl/synchronization", "@com_google_absl//absl/time", "@com_google_googletest//:gtest_main", - "@plasma//:plasma_client", ], ) @@ -1375,19 +1571,6 @@ cc_test( ], ) -FLATC_ARGS = [ - "--gen-object-api", - "--gen-mutable", - "--scoped-enums", -] - -flatbuffer_cc_library( - name = "common_fbs", - srcs = ["@plasma//:cpp/src/plasma/common.fbs"], - flatc_args = FLATC_ARGS, - out_prefix = "src/ray/common/", -) - flatbuffer_cc_library( name = "node_manager_fbs", srcs = ["src/ray/raylet/format/node_manager.fbs"], @@ -1471,7 +1654,10 @@ cc_binary( "@bazel_tools//src/conditions:windows": ["@bazel_tools//tools/jdk:jni_md_header-windows"], "@bazel_tools//src/conditions:darwin": ["@bazel_tools//tools/jdk:jni_md_header-darwin"], "//conditions:default": ["@bazel_tools//tools/jdk:jni_md_header-linux"], - }), + }) + [ + ":jni.h", + ":jni_md.h", + ], copts = COPTS, includes = [ "src", @@ -1639,7 +1825,7 @@ genrule( "//:raylet", "//:raylet_monitor", "//:gcs_server", - "@plasma//:plasma_store_server", + "//:plasma_store_server", "//streaming:copy_streaming_py_proto", ], outs = ["ray_pkg.out"], @@ -1664,7 +1850,7 @@ genrule( mkdir -p "$$WORK_DIR/python/ray/core/src/ray/gcs/redis_module/" && cp -f $(locations //:libray_redis_module.so) "$$WORK_DIR/python/ray/core/src/ray/gcs/redis_module/" && cp -f $(location //:raylet_monitor) "$$WORK_DIR/python/ray/core/src/ray/raylet/" && - cp -f $(location @plasma//:plasma_store_server) "$$WORK_DIR/python/ray/core/src/plasma/" && + cp -f $(location //:plasma_store_server) "$$WORK_DIR/python/ray/core/src/plasma/" && cp -f $(location //:raylet) "$$WORK_DIR/python/ray/core/src/ray/raylet/" && cp -f $(location //:gcs_server) "$$WORK_DIR/python/ray/core/src/ray/gcs/" && mkdir -p "$$WORK_DIR/python/ray/core/generated/ray/protocol/" && diff --git a/bazel/BUILD.arrow b/bazel/BUILD.arrow new file mode 100644 index 000000000..715e48d6e --- /dev/null +++ b/bazel/BUILD.arrow @@ -0,0 +1,98 @@ +load("@com_github_google_flatbuffers//:build_defs.bzl", "flatbuffer_cc_library") + +# TODO(mehrdadn): (How to) support dynamic linking? +PROPAGATED_WINDOWS_DEFINES = ["ARROW_STATIC"] + +COPTS = [] + select({ + "@bazel_tools//src/conditions:windows": [ + "-D" + "WIN32_REPLACE_FD_APIS", + "/FI" + "win32fd.h", + ] + ["-D" + define for define in PROPAGATED_WINDOWS_DEFINES], + "//conditions:default": [ + "-DARROW_USE_GLOG", + ], +}) + +LINKOPTS = [] + select({ + "@bazel_tools//src/conditions:windows": [ + "-DefaultLib:" + "ws2_32.lib", + ], + "//conditions:default": [ + ], +}) + +cc_library( + name = "arrow", + srcs = [ + "cpp/src/arrow/buffer.cc", + "cpp/src/arrow/device.cc", + "cpp/src/arrow/io/interfaces.cc", + "cpp/src/arrow/io/memory.cc", + "cpp/src/arrow/memory_pool.cc", + "cpp/src/arrow/result.cc", + "cpp/src/arrow/status.cc", + "cpp/src/arrow/util/future.cc", + "cpp/src/arrow/util/io_util.cc", + "cpp/src/arrow/util/logging.cc", + "cpp/src/arrow/util/memory.cc", + "cpp/src/arrow/util/string.cc", + "cpp/src/arrow/util/string_builder.cc", + "cpp/src/arrow/util/thread_pool.cc", + "cpp/src/arrow/util/utf8.cc", + ], + hdrs = [ + "cpp/src/arrow/buffer.h", + "cpp/src/arrow/device.h", + "cpp/src/arrow/io/concurrency.h", + "cpp/src/arrow/io/interfaces.h", + "cpp/src/arrow/io/memory.h", + "cpp/src/arrow/io/mman.h", + "cpp/src/arrow/io/type_fwd.h", + "cpp/src/arrow/io/util_internal.h", + "cpp/src/arrow/memory_pool.h", + "cpp/src/arrow/result.h", + "cpp/src/arrow/status.h", + "cpp/src/arrow/type_fwd.h", + "cpp/src/arrow/util/bit_util.h", + "cpp/src/arrow/util/checked_cast.h", + "cpp/src/arrow/util/compare.h", + "cpp/src/arrow/util/functional.h", + "cpp/src/arrow/util/future.h", + "cpp/src/arrow/util/io_util.h", + "cpp/src/arrow/util/iterator.h", + "cpp/src/arrow/util/logging.h", + "cpp/src/arrow/util/macros.h", + "cpp/src/arrow/util/make_unique.h", + "cpp/src/arrow/util/memory.h", + "cpp/src/arrow/util/optional.h", + "cpp/src/arrow/util/string.h", + "cpp/src/arrow/util/string_builder.h", + "cpp/src/arrow/util/string_view.h", + "cpp/src/arrow/util/thread_pool.h", + "cpp/src/arrow/util/type_traits.h", + "cpp/src/arrow/util/ubsan.h", + "cpp/src/arrow/util/utf8.h", + "cpp/src/arrow/util/variant.h", + "cpp/src/arrow/util/visibility.h", + "cpp/src/arrow/util/windows_compatibility.h", + "cpp/src/arrow/util/windows_fixup.h", + "cpp/src/arrow/vendored/optional.hpp", + "cpp/src/arrow/vendored/string_view.hpp", + "cpp/src/arrow/vendored/utf8cpp/checked.h", + "cpp/src/arrow/vendored/utf8cpp/core.h", + "cpp/src/arrow/vendored/variant.hpp", + "cpp/src/arrow/vendored/xxhash.h", + "cpp/src/arrow/vendored/xxhash/xxh3.h", + "cpp/src/arrow/vendored/xxhash/xxhash.c", + "cpp/src/arrow/vendored/xxhash/xxhash.h", + ], + copts = COPTS, + linkopts = LINKOPTS, + strip_include_prefix = "cpp/src", + visibility = ["//visibility:public"], + deps = [ + "@//:platform_shims", + "@boost//:filesystem", + "@com_github_google_glog//:glog", + ], +) diff --git a/bazel/BUILD.plasma b/bazel/BUILD.plasma deleted file mode 100644 index b97be9439..000000000 --- a/bazel/BUILD.plasma +++ /dev/null @@ -1,272 +0,0 @@ -load("@com_github_google_flatbuffers//:build_defs.bzl", "flatbuffer_cc_library") - -# TODO(mehrdadn): (How to) support dynamic linking? -PROPAGATED_WINDOWS_DEFINES = ["ARROW_STATIC"] - -COPTS = [] + select({ - "@bazel_tools//src/conditions:windows": [ - "-D" + "WIN32_REPLACE_FD_APIS", - "/FI" + "win32fd.h", - ] + ["-D" + define for define in PROPAGATED_WINDOWS_DEFINES], - "//conditions:default": [ - "-DARROW_USE_GLOG", - ], -}) - -LINKOPTS = [] + select({ - "@bazel_tools//src/conditions:windows": [ - "-DefaultLib:" + "ws2_32.lib", - ], - "//conditions:default": [ - ], -}) - -cc_library( - name = "arrow", - srcs = [ - "cpp/src/arrow/buffer.cc", - "cpp/src/arrow/device.cc", - "cpp/src/arrow/io/interfaces.cc", - "cpp/src/arrow/io/memory.cc", - "cpp/src/arrow/memory_pool.cc", - "cpp/src/arrow/result.cc", - "cpp/src/arrow/status.cc", - "cpp/src/arrow/util/future.cc", - "cpp/src/arrow/util/io_util.cc", - "cpp/src/arrow/util/logging.cc", - "cpp/src/arrow/util/memory.cc", - "cpp/src/arrow/util/string.cc", - "cpp/src/arrow/util/string_builder.cc", - "cpp/src/arrow/util/thread_pool.cc", - "cpp/src/arrow/util/utf8.cc", - ], - hdrs = [ - "cpp/src/arrow/buffer.h", - "cpp/src/arrow/device.h", - "cpp/src/arrow/io/concurrency.h", - "cpp/src/arrow/io/interfaces.h", - "cpp/src/arrow/io/memory.h", - "cpp/src/arrow/io/mman.h", - "cpp/src/arrow/io/type_fwd.h", - "cpp/src/arrow/io/util_internal.h", - "cpp/src/arrow/memory_pool.h", - "cpp/src/arrow/result.h", - "cpp/src/arrow/status.h", - "cpp/src/arrow/type_fwd.h", - "cpp/src/arrow/util/bit_util.h", - "cpp/src/arrow/util/checked_cast.h", - "cpp/src/arrow/util/compare.h", - "cpp/src/arrow/util/functional.h", - "cpp/src/arrow/util/future.h", - "cpp/src/arrow/util/io_util.h", - "cpp/src/arrow/util/iterator.h", - "cpp/src/arrow/util/logging.h", - "cpp/src/arrow/util/macros.h", - "cpp/src/arrow/util/make_unique.h", - "cpp/src/arrow/util/memory.h", - "cpp/src/arrow/util/optional.h", - "cpp/src/arrow/util/string.h", - "cpp/src/arrow/util/string_builder.h", - "cpp/src/arrow/util/string_view.h", - "cpp/src/arrow/util/thread_pool.h", - "cpp/src/arrow/util/type_traits.h", - "cpp/src/arrow/util/ubsan.h", - "cpp/src/arrow/util/utf8.h", - "cpp/src/arrow/util/variant.h", - "cpp/src/arrow/util/visibility.h", - "cpp/src/arrow/util/windows_compatibility.h", - "cpp/src/arrow/util/windows_fixup.h", - "cpp/src/arrow/vendored/optional.hpp", - "cpp/src/arrow/vendored/string_view.hpp", - "cpp/src/arrow/vendored/utf8cpp/checked.h", - "cpp/src/arrow/vendored/utf8cpp/core.h", - "cpp/src/arrow/vendored/variant.hpp", - "cpp/src/arrow/vendored/xxhash.h", - "cpp/src/arrow/vendored/xxhash/xxh3.h", - "cpp/src/arrow/vendored/xxhash/xxhash.c", - "cpp/src/arrow/vendored/xxhash/xxhash.h", - ], - copts = COPTS, - linkopts = LINKOPTS, - strip_include_prefix = "cpp/src", - deps = [ - "@//:platform_shims", - "@boost//:filesystem", - "@com_github_google_glog//:glog", - ], -) - -cc_library( - name = "plasma_client", - srcs = [ - "cpp/src/plasma/client.cc", - "cpp/src/plasma/common.cc", - "cpp/src/plasma/fling.cc", - "cpp/src/plasma/io.cc", - "cpp/src/plasma/malloc.cc", - "cpp/src/plasma/plasma.cc", - "cpp/src/plasma/protocol.cc", - ], - hdrs = [ - "cpp/src/plasma/client.h", - "cpp/src/plasma/common.h", - "cpp/src/plasma/common_generated.h", - "cpp/src/plasma/compat.h", - "cpp/src/plasma/external_store.h", - "cpp/src/plasma/fling.h", - "cpp/src/plasma/io.h", - "cpp/src/plasma/malloc.h", - "cpp/src/plasma/plasma.h", - "cpp/src/plasma/plasma_generated.h", - "cpp/src/plasma/protocol.h", - ], - copts = COPTS, - defines = select({ - "@bazel_tools//src/conditions:windows": PROPAGATED_WINDOWS_DEFINES, - "//conditions:default": [], - }), - linkopts = LINKOPTS, - strip_include_prefix = "cpp/src", - visibility = ["//visibility:public"], - deps = [ - ":arrow", - ":common_fbs", - ":plasma_fbs", - "@//:platform_shims", - "@com_github_google_glog//:glog", - ], -) - -cc_binary( - name = "libplasma_java.so", - srcs = [ - "cpp/src/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.cc", - "cpp/src/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.h", - ":jni.h", - ":jni_md.h", - ], - includes = [ - ".", - "cpp/src", - ], - linkshared = 1, - linkstatic = 1, - deps = [":plasma_client"], -) - -genrule( - name = "copy_jni_h", - srcs = ["@bazel_tools//tools/jdk:jni_header"], - outs = ["jni.h"], - cmd = "cp -f $< $@", -) - -genrule( - name = "copy_jni_md_h", - srcs = select({ - "@bazel_tools//src/conditions:windows": ["@bazel_tools//tools/jdk:jni_md_header-windows"], - "@bazel_tools//src/conditions:darwin": ["@bazel_tools//tools/jdk:jni_md_header-darwin"], - "//conditions:default": ["@bazel_tools//tools/jdk:jni_md_header-linux"], - }), - outs = ["jni_md.h"], - cmd = "cp -f $< $@", -) - -genrule( - name = "plasma-jni-darwin-compat", - srcs = [":libplasma_java.so"], - outs = ["libplasma_java.dylib"], - cmd = "cp $< $@", - output_to_bindir = 1, -) - -cc_library( - name = "ae", - srcs = [ - "cpp/src/plasma/thirdparty/ae/ae.c", - ], - hdrs = [ - "cpp/src/plasma/thirdparty/ae/ae.h", - "cpp/src/plasma/thirdparty/ae/ae_epoll.c", - "cpp/src/plasma/thirdparty/ae/ae_evport.c", - "cpp/src/plasma/thirdparty/ae/ae_kqueue.c", - "cpp/src/plasma/thirdparty/ae/ae_select.c", - "cpp/src/plasma/thirdparty/ae/config.h", - "cpp/src/plasma/thirdparty/ae/zmalloc.h", - ], - copts = COPTS, - includes = [ - "cpp/src/plasma/thirdparty/ae", - ], - strip_include_prefix = "cpp/src", - visibility = ["//visibility:public"], - deps = [ - "@//:platform_shims", - ], -) - -cc_library( - name = "plasma_lib", - srcs = [ - "cpp/src/plasma/dlmalloc.cc", - "cpp/src/plasma/events.cc", - "cpp/src/plasma/eviction_policy.cc", - "cpp/src/plasma/external_store.cc", - "cpp/src/plasma/plasma_allocator.cc", - "cpp/src/plasma/quota_aware_policy.cc", - ], - hdrs = [ - "cpp/src/plasma/events.h", - "cpp/src/plasma/eviction_policy.h", - "cpp/src/plasma/external_store.h", - "cpp/src/plasma/plasma_allocator.h", - "cpp/src/plasma/quota_aware_policy.h", - "cpp/src/plasma/store.h", - "cpp/src/plasma/thirdparty/dlmalloc.c", - ], - copts = COPTS, - linkopts = LINKOPTS, - strip_include_prefix = "cpp/src", - deps = [ - ":ae", - ":plasma_client", - "@//:platform_shims", - "@com_github_google_glog//:glog", - ], -) - -cc_binary( - name = "plasma_store_server", - srcs = [ - "cpp/src/plasma/store.cc", - ], - copts = COPTS, - visibility = ["//visibility:public"], - deps = [ - ":plasma_lib", - "@//:platform_shims", - ], -) - -FLATC_ARGS = [ - "--gen-object-api", - "--gen-mutable", - "--scoped-enums", -] - -flatbuffer_cc_library( - name = "common_fbs", - srcs = ["cpp/src/plasma/common.fbs"], - flatc_args = FLATC_ARGS, - out_prefix = "cpp/src/plasma/", -) - -flatbuffer_cc_library( - name = "plasma_fbs", - srcs = ["cpp/src/plasma/plasma.fbs"], - flatc_args = FLATC_ARGS, - includes = ["cpp/src/plasma/common.fbs"], - out_prefix = "cpp/src/plasma/", -) - -exports_files(["cpp/src/plasma/common.fbs"]) diff --git a/bazel/ray_deps_setup.bzl b/bazel/ray_deps_setup.bzl index 6c0302a46..b77233072 100644 --- a/bazel/ray_deps_setup.bzl +++ b/bazel/ray_deps_setup.bzl @@ -162,18 +162,13 @@ def ray_deps_setup(): ) auto_http_archive( - name = "plasma", + name = "arrow", build_file = True, url = "https://github.com/apache/arrow/archive/af45b9212156980f55c399e2e88b4e19b4bb8ec1.tar.gz", sha256 = "2f0aaa50053792aa274b402f2530e63c1542085021cfef83beee9281412c12f6", patches = [ - "//thirdparty/patches:arrow-headers-unused.patch", "//thirdparty/patches:arrow-windows-export.patch", "//thirdparty/patches:arrow-windows-nonstdc.patch", - "//thirdparty/patches:arrow-windows-sigpipe.patch", - "//thirdparty/patches:arrow-windows-socket.patch", - "//thirdparty/patches:arrow-windows-dlmalloc.patch", - "//thirdparty/patches:arrow-windows-tcp.patch", ], ) diff --git a/ci/travis/bazel-format.sh b/ci/travis/bazel-format.sh index 7a11cafb2..c31b1daf6 100755 --- a/ci/travis/bazel-format.sh +++ b/ci/travis/bazel-format.sh @@ -44,7 +44,7 @@ while [[ $# > 0 ]]; do done pushd $ROOT_DIR/../.. -BAZEL_FILES="bazel/BUILD bazel/BUILD.plasma bazel/ray.bzl BUILD.bazel java/BUILD.bazel +BAZEL_FILES="bazel/BUILD bazel/BUILD.arrow bazel/ray.bzl BUILD.bazel java/BUILD.bazel cpp/BUILD.bazel streaming/BUILD.bazel streaming/java/BUILD.bazel WORKSPACE" buildifier -mode=$RUN_TYPE -diff_command="diff -u" $BAZEL_FILES popd diff --git a/java/BUILD.bazel b/java/BUILD.bazel index fb638c6f8..9169ef232 100644 --- a/java/BUILD.bazel +++ b/java/BUILD.bazel @@ -146,11 +146,11 @@ filegroup( genrule( name = "cp_plasma_store_server", srcs = [ - "@plasma//:plasma_store_server", + "//:plasma_store_server", ], outs = ["plasma_store_server"], cmd = """ - cp -f $(location @plasma//:plasma_store_server) $@ + cp -f $(location //:plasma_store_server) $@ """, ) diff --git a/src/ray/plasma/.clang-format b/src/ray/plasma/.clang-format new file mode 100644 index 000000000..37f3d5766 --- /dev/null +++ b/src/ray/plasma/.clang-format @@ -0,0 +1 @@ +DisableFormat: true \ No newline at end of file diff --git a/src/ray/plasma/.gitignore b/src/ray/plasma/.gitignore new file mode 100644 index 000000000..163b5c56e --- /dev/null +++ b/src/ray/plasma/.gitignore @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +*_generated.h diff --git a/src/ray/plasma/client.cc b/src/ray/plasma/client.cc new file mode 100644 index 000000000..76c80783a --- /dev/null +++ b/src/ray/plasma/client.cc @@ -0,0 +1,1253 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// PLASMA CLIENT: Client library for using the plasma store and manager + +#include "plasma/client.h" + +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include +#include +#include +#include +#ifndef _WIN32 +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/util/thread_pool.h" + +#include "plasma/common.h" +#include "plasma/fling.h" +#include "plasma/io.h" +#include "plasma/malloc.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" + +#ifdef PLASMA_CUDA +#include "arrow/gpu/cuda_api.h" + +using arrow::cuda::CudaBuffer; +using arrow::cuda::CudaBufferWriter; +using arrow::cuda::CudaContext; +using arrow::cuda::CudaDeviceManager; +#endif + +#define XXH_INLINE_ALL 1 +#define XXH_NAMESPACE plasma_client_ +#include "arrow/vendored/xxhash.h" + +#define XXH64_DEFAULT_SEED 0 + +namespace fb = plasma::flatbuf; + +namespace plasma { + +using fb::MessageType; +using fb::PlasmaError; + +using arrow::MutableBuffer; + +typedef struct XXH64_state_s XXH64_state_t; + +// Number of threads used for hash computations. +constexpr int64_t kHashingConcurrency = 8; +constexpr int64_t kBytesInMB = 1 << 20; + +// ---------------------------------------------------------------------- +// GPU support + +#ifdef PLASMA_CUDA + +namespace { + +struct GpuProcessHandle { + /// Pointer to CUDA buffer that is backing this GPU object. + std::shared_ptr ptr; + /// Number of client using this GPU object. + int client_count; +}; + +// This is necessary as IPC handles can only be mapped once per process. +// Thus if multiple clients in the same process get the same gpu object, +// they need to access the same mapped CudaBuffer. +std::unordered_map gpu_object_map; +std::mutex gpu_mutex; + +// Return a new CudaBuffer pointing to the same data as the GpuProcessHandle, +// but able to persist after the original IPC-backed buffer is closed +// (ARROW-5924). +std::shared_ptr MakeBufferFromGpuProcessHandle(GpuProcessHandle* handle) { + return std::make_shared(handle->ptr->address(), handle->ptr->size(), + handle->ptr->context()); +} + +} // namespace + +#endif + +// ---------------------------------------------------------------------- +// PlasmaBuffer + +/// A Buffer class that automatically releases the backing plasma object +/// when it goes out of scope. This is returned by Get. +class ARROW_NO_EXPORT PlasmaBuffer : public Buffer { + public: + ~PlasmaBuffer(); + + PlasmaBuffer(std::shared_ptr client, const ObjectID& object_id, + const std::shared_ptr& buffer) + : Buffer(buffer, 0, buffer->size()), client_(client), object_id_(object_id) { + if (buffer->is_mutable()) { + is_mutable_ = true; + } + } + + private: + std::shared_ptr client_; + ObjectID object_id_; +}; + +/// A mutable Buffer class that keeps the backing data alive by keeping a +/// PlasmaClient shared pointer. This is returned by Create. Release will +/// be called in the associated Seal call. +class ARROW_NO_EXPORT PlasmaMutableBuffer : public MutableBuffer { + public: + PlasmaMutableBuffer(std::shared_ptr client, uint8_t* mutable_data, + int64_t data_size) + : MutableBuffer(mutable_data, data_size), client_(client) {} + + private: + std::shared_ptr client_; +}; + +// ---------------------------------------------------------------------- +// PlasmaClient::Impl + +struct ObjectInUseEntry { + /// A count of the number of times this client has called PlasmaClient::Create + /// or + /// PlasmaClient::Get on this object ID minus the number of calls to + /// PlasmaClient::Release. + /// When this count reaches zero, we remove the entry from the ObjectsInUse + /// and decrement a count in the relevant ClientMmapTableEntry. + int count; + /// Cached information to read the object. + PlasmaObject object; + /// A flag representing whether the object has been sealed. + bool is_sealed; +}; + +class ClientMmapTableEntry { + public: + ClientMmapTableEntry(int fd, int64_t map_size) + : fd_(fd), pointer_(nullptr), length_(0) { + // We subtract kMmapRegionsGap from the length that was added + // in fake_mmap in malloc.h, to make map_size page-aligned again. + length_ = map_size - kMmapRegionsGap; +#ifdef _WIN32 + pointer_ = reinterpret_cast(MapViewOfFile(reinterpret_cast(fh_get(fd)), FILE_MAP_ALL_ACCESS, 0, 0, length_)); + // TODO(pcm): Don't fail here, instead return a Status. + if (pointer_ == NULL) { + ARROW_LOG(FATAL) << "mmap failed"; + } +#else + pointer_ = reinterpret_cast( + mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); + // TODO(pcm): Don't fail here, instead return a Status. + if (pointer_ == MAP_FAILED) { + ARROW_LOG(FATAL) << "mmap failed"; + } +#endif + close(fd); // Closing this fd has an effect on performance. + } + + ~ClientMmapTableEntry() { + // At this point it is safe to unmap the memory, as the PlasmaBuffer + // keeps the PlasmaClient (and therefore the ClientMmapTableEntry) + // alive until it is destroyed. + // We don't need to close the associated file, since it has + // already been closed in the constructor. + int r; +#ifdef _WIN32 + r = UnmapViewOfFile(pointer_) ? 0 : -1; +#else + r = munmap(pointer_, length_); +#endif + if (r != 0) { + ARROW_LOG(ERROR) << "munmap returned " << r << ", errno = " << errno; + } + } + + uint8_t* pointer() { return pointer_; } + + int fd() { return fd_; } + + private: + /// The associated file descriptor on the client. + int fd_; + /// The result of mmap for this file descriptor. + uint8_t* pointer_; + /// The length of the memory-mapped file. + size_t length_; + + ARROW_DISALLOW_COPY_AND_ASSIGN(ClientMmapTableEntry); +}; + +class PlasmaClient::Impl : public std::enable_shared_from_this { + public: + Impl(); + ~Impl(); + + // PlasmaClient method implementations + + Status Connect(const std::string& store_socket_name, + const std::string& manager_socket_name, int release_delay = 0, + int num_retries = -1); + + Status SetClientOptions(const std::string& client_name, int64_t output_memory_quota); + + Status Create(const ObjectID& object_id, int64_t data_size, const uint8_t* metadata, + int64_t metadata_size, std::shared_ptr* data, int device_num = 0, + bool evict_if_full = true); + + Status CreateAndSeal(const ObjectID& object_id, const std::string& data, + const std::string& metadata, bool evict_if_full = true); + + Status CreateAndSealBatch(const std::vector& object_ids, + const std::vector& data, + const std::vector& metadata, + bool evict_if_full = true); + + Status Get(const std::vector& object_ids, int64_t timeout_ms, + std::vector* object_buffers); + + Status Get(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, + ObjectBuffer* object_buffers); + + Status Release(const ObjectID& object_id); + + Status Contains(const ObjectID& object_id, bool* has_object); + + Status List(ObjectTable* objects); + + Status Abort(const ObjectID& object_id); + + Status Seal(const ObjectID& object_id); + + Status Delete(const std::vector& object_ids); + + Status Evict(int64_t num_bytes, int64_t& num_bytes_evicted); + + Status Refresh(const std::vector& object_ids); + + Status Hash(const ObjectID& object_id, uint8_t* digest); + + Status Subscribe(int* fd); + + Status GetNotification(int fd, ObjectID* object_id, int64_t* data_size, + int64_t* metadata_size); + + Status DecodeNotifications(const uint8_t* buffer, std::vector* object_ids, + std::vector* data_sizes, + std::vector* metadata_sizes); + + Status Disconnect(); + + std::string DebugString(); + + bool IsInUse(const ObjectID& object_id); + + int64_t store_capacity() { return store_capacity_; } + + private: + /// Check if store_fd has already been received from the store. If yes, + /// return it. Otherwise, receive it from the store (see analogous logic + /// in store.cc). + /// + /// \param store_fd File descriptor to fetch from the store. + /// \return Client file descriptor corresponding to store_fd. + int GetStoreFd(int store_fd); + + /// This is a helper method for marking an object as unused by this client. + /// + /// \param object_id The object ID we mark unused. + /// \return The return status. + Status MarkObjectUnused(const ObjectID& object_id); + + /// Common helper for Get() variants + Status GetBuffers(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, + const std::function( + const ObjectID&, const std::shared_ptr&)>& wrap_buffer, + ObjectBuffer* object_buffers); + + uint8_t* LookupOrMmap(int fd, int store_fd_val, int64_t map_size); + + uint8_t* LookupMmappedFile(int store_fd_val); + + void IncrementObjectCount(const ObjectID& object_id, PlasmaObject* object, + bool is_sealed); + + bool ComputeObjectHashParallel(XXH64_state_t* hash_state, const unsigned char* data, + int64_t nbytes); + + uint64_t ComputeObjectHash(const ObjectBuffer& obj_buffer); + + uint64_t ComputeObjectHashCPU(const uint8_t* data, int64_t data_size, + const uint8_t* metadata, int64_t metadata_size); + + /// File descriptor of the Unix domain socket that connects to the store. + int store_conn_; + /// Table of dlmalloc buffer files that have been memory mapped so far. This + /// is a hash table mapping a file descriptor to a struct containing the + /// address of the corresponding memory-mapped file. + std::unordered_map> mmap_table_; + /// A hash table of the object IDs that are currently being used by this + /// client. + std::unordered_map> objects_in_use_; + /// The amount of memory available to the Plasma store. The client needs this + /// information to make sure that it does not delay in releasing so much + /// memory that the store is unable to evict enough objects to free up space. + int64_t store_capacity_; + /// A hash set to record the ids that users want to delete but still in use. + std::unordered_set deletion_cache_; + /// A queue of notification + std::deque> pending_notification_; + /// A mutex which protects this class. + std::recursive_mutex client_mutex_; + +#ifdef PLASMA_CUDA + /// Cuda Device Manager. + arrow::cuda::CudaDeviceManager* manager_; +#endif +}; + +PlasmaBuffer::~PlasmaBuffer() { ARROW_UNUSED(client_->Release(object_id_)); } + +PlasmaClient::Impl::Impl() : store_conn_(0), store_capacity_(0) { +#ifdef PLASMA_CUDA + auto maybe_manager = CudaDeviceManager::Instance(); + DCHECK_OK(maybe_manager.status()); + manager_ = *maybe_manager; +#endif +} + +PlasmaClient::Impl::~Impl() {} + +// If the file descriptor fd has been mmapped in this client process before, +// return the pointer that was returned by mmap, otherwise mmap it and store the +// pointer in a hash table. +uint8_t* PlasmaClient::Impl::LookupOrMmap(int fd, int store_fd_val, int64_t map_size) { + auto entry = mmap_table_.find(store_fd_val); + if (entry != mmap_table_.end()) { + return entry->second->pointer(); + } else { + mmap_table_[store_fd_val] = + std::unique_ptr(new ClientMmapTableEntry(fd, map_size)); + return mmap_table_[store_fd_val]->pointer(); + } +} + +// Get a pointer to a file that we know has been memory mapped in this client +// process before. +uint8_t* PlasmaClient::Impl::LookupMmappedFile(int store_fd_val) { + auto entry = mmap_table_.find(store_fd_val); + ARROW_CHECK(entry != mmap_table_.end()); + return entry->second->pointer(); +} + +bool PlasmaClient::Impl::IsInUse(const ObjectID& object_id) { + std::lock_guard guard(client_mutex_); + + const auto elem = objects_in_use_.find(object_id); + return (elem != objects_in_use_.end()); +} + +int PlasmaClient::Impl::GetStoreFd(int store_fd) { + auto entry = mmap_table_.find(store_fd); + if (entry == mmap_table_.end()) { + int fd = recv_fd(store_conn_); + ARROW_CHECK(fd >= 0) << "recv not successful"; + return fd; + } else { + return entry->second->fd(); + } +} + +void PlasmaClient::Impl::IncrementObjectCount(const ObjectID& object_id, + PlasmaObject* object, bool is_sealed) { + // Increment the count of the object to track the fact that it is being used. + // The corresponding decrement should happen in PlasmaClient::Release. + auto elem = objects_in_use_.find(object_id); + ObjectInUseEntry* object_entry; + if (elem == objects_in_use_.end()) { + // Add this object ID to the hash table of object IDs in use. The + // corresponding call to free happens in PlasmaClient::Release. + objects_in_use_[object_id] = + std::unique_ptr(new ObjectInUseEntry()); + objects_in_use_[object_id]->object = *object; + objects_in_use_[object_id]->count = 0; + objects_in_use_[object_id]->is_sealed = is_sealed; + object_entry = objects_in_use_[object_id].get(); + } else { + object_entry = elem->second.get(); + ARROW_CHECK(object_entry->count > 0); + } + // Increment the count of the number of instances of this object that are + // being used by this client. The corresponding decrement should happen in + // PlasmaClient::Release. + object_entry->count += 1; +} + +Status PlasmaClient::Impl::Create(const ObjectID& object_id, int64_t data_size, + const uint8_t* metadata, int64_t metadata_size, + std::shared_ptr* data, int device_num, + bool evict_if_full) { + std::lock_guard guard(client_mutex_); + + ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn_ << " with size " + << data_size << " and metadata size " << metadata_size; + RETURN_NOT_OK(SendCreateRequest(store_conn_, object_id, evict_if_full, data_size, + metadata_size, device_num)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaCreateReply, &buffer)); + ObjectID id; + PlasmaObject object; + int store_fd; + int64_t mmap_size; + RETURN_NOT_OK( + ReadCreateReply(buffer.data(), buffer.size(), &id, &object, &store_fd, &mmap_size)); + // If the CreateReply included an error, then the store will not send a file + // descriptor. + if (device_num == 0) { + int fd = GetStoreFd(store_fd); + ARROW_CHECK(object.data_size == data_size); + ARROW_CHECK(object.metadata_size == metadata_size); + // The metadata should come right after the data. + ARROW_CHECK(object.metadata_offset == object.data_offset + data_size); + *data = std::make_shared( + shared_from_this(), LookupOrMmap(fd, store_fd, mmap_size) + object.data_offset, + data_size); + // If plasma_create is being called from a transfer, then we will not copy the + // metadata here. The metadata will be written along with the data streamed + // from the transfer. + if (metadata != NULL) { + // Copy the metadata to the buffer. + memcpy((*data)->mutable_data() + object.data_size, metadata, metadata_size); + } + } else { +#ifdef PLASMA_CUDA + std::shared_ptr context; + ARROW_ASSIGN_OR_RAISE(context, manager_->GetContext(device_num - 1)); + GpuProcessHandle* handle = new GpuProcessHandle(); + handle->client_count = 2; + ARROW_ASSIGN_OR_RAISE(handle->ptr, context->OpenIpcBuffer(*object.ipc_handle)); + { + std::lock_guard lock(gpu_mutex); + gpu_object_map[object_id] = handle; + } + if (metadata != NULL) { + // Copy the metadata to the buffer. + CudaBufferWriter writer(handle->ptr); + RETURN_NOT_OK(writer.WriteAt(object.data_size, metadata, metadata_size)); + } + *data = MakeBufferFromGpuProcessHandle(handle); +#else + ARROW_LOG(FATAL) << "Arrow GPU library is not enabled."; +#endif + } + + // Increment the count of the number of instances of this object that this + // client is using. A call to PlasmaClient::Release is required to decrement + // this count. Cache the reference to the object. + IncrementObjectCount(object_id, &object, false); + // We increment the count a second time (and the corresponding decrement will + // happen in a PlasmaClient::Release call in plasma_seal) so even if the + // buffer returned by PlasmaClient::Create goes out of scope, the object does + // not get released before the call to PlasmaClient::Seal happens. + IncrementObjectCount(object_id, &object, false); + return Status::OK(); +} + +Status PlasmaClient::Impl::CreateAndSeal(const ObjectID& object_id, + const std::string& data, + const std::string& metadata, + bool evict_if_full) { + std::lock_guard guard(client_mutex_); + + ARROW_LOG(DEBUG) << "called CreateAndSeal on conn " << store_conn_; + // Compute the object hash. + static unsigned char digest[kDigestSize]; + uint64_t hash = ComputeObjectHashCPU( + reinterpret_cast(data.data()), data.size(), + reinterpret_cast(metadata.data()), metadata.size()); + memcpy(&digest[0], &hash, sizeof(hash)); + + RETURN_NOT_OK(SendCreateAndSealRequest(store_conn_, object_id, evict_if_full, data, + metadata, digest)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(store_conn_, MessageType::PlasmaCreateAndSealReply, &buffer)); + RETURN_NOT_OK(ReadCreateAndSealReply(buffer.data(), buffer.size())); + return Status::OK(); +} + +Status PlasmaClient::Impl::CreateAndSealBatch(const std::vector& object_ids, + const std::vector& data, + const std::vector& metadata, + bool evict_if_full) { + std::lock_guard guard(client_mutex_); + + ARROW_LOG(DEBUG) << "called CreateAndSealBatch on conn " << store_conn_; + + std::vector digests; + for (size_t i = 0; i < object_ids.size(); i++) { + // Compute the object hash. + std::string digest; + uint64_t hash = ComputeObjectHashCPU( + reinterpret_cast(data.data()), data.size(), + reinterpret_cast(metadata.data()), metadata.size()); + digest.assign(reinterpret_cast(&hash), sizeof(hash)); + digests.push_back(digest); + } + + RETURN_NOT_OK(SendCreateAndSealBatchRequest(store_conn_, object_ids, evict_if_full, + data, metadata, digests)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(store_conn_, MessageType::PlasmaCreateAndSealBatchReply, &buffer)); + RETURN_NOT_OK(ReadCreateAndSealBatchReply(buffer.data(), buffer.size())); + + return Status::OK(); +} + +Status PlasmaClient::Impl::GetBuffers( + const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, + const std::function( + const ObjectID&, const std::shared_ptr&)>& wrap_buffer, + ObjectBuffer* object_buffers) { + // Fill out the info for the objects that are already in use locally. + bool all_present = true; + for (int64_t i = 0; i < num_objects; ++i) { + auto object_entry = objects_in_use_.find(object_ids[i]); + if (object_entry == objects_in_use_.end()) { + // This object is not currently in use by this client, so we need to send + // a request to the store. + all_present = false; + } else if (!object_entry->second->is_sealed) { + // This client created the object but hasn't sealed it. If we call Get + // with no timeout, we will deadlock, because this client won't be able to + // call Seal. + ARROW_CHECK(timeout_ms != -1) + << "Plasma client called get on an unsealed object that it created"; + ARROW_LOG(WARNING) + << "Attempting to get an object that this client created but hasn't sealed."; + all_present = false; + } else { + PlasmaObject* object = &object_entry->second->object; + std::shared_ptr physical_buf; + + if (object->device_num == 0) { + uint8_t* data = LookupMmappedFile(object->store_fd); + physical_buf = std::make_shared( + data + object->data_offset, object->data_size + object->metadata_size); + } else { +#ifdef PLASMA_CUDA + std::lock_guard lock(gpu_mutex); + auto iter = gpu_object_map.find(object_ids[i]); + ARROW_CHECK(iter != gpu_object_map.end()); + iter->second->client_count++; + physical_buf = MakeBufferFromGpuProcessHandle(iter->second); +#else + ARROW_LOG(FATAL) << "Arrow GPU library is not enabled."; +#endif + } + physical_buf = wrap_buffer(object_ids[i], physical_buf); + object_buffers[i].data = SliceBuffer(physical_buf, 0, object->data_size); + object_buffers[i].metadata = + SliceBuffer(physical_buf, object->data_size, object->metadata_size); + object_buffers[i].device_num = object->device_num; + // Increment the count of the number of instances of this object that this + // client is using. Cache the reference to the object. + IncrementObjectCount(object_ids[i], object, true); + } + } + + if (all_present) { + return Status::OK(); + } + + // If we get here, then the objects aren't all currently in use by this + // client, so we need to send a request to the plasma store. + RETURN_NOT_OK(SendGetRequest(store_conn_, &object_ids[0], num_objects, timeout_ms)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaGetReply, &buffer)); + std::vector received_object_ids(num_objects); + std::vector object_data(num_objects); + PlasmaObject* object; + std::vector store_fds; + std::vector mmap_sizes; + RETURN_NOT_OK(ReadGetReply(buffer.data(), buffer.size(), received_object_ids.data(), + object_data.data(), num_objects, store_fds, mmap_sizes)); + + // We mmap all of the file descriptors here so that we can avoid look them up + // in the subsequent loop based on just the store file descriptor and without + // having to know the relevant file descriptor received from recv_fd. + for (size_t i = 0; i < store_fds.size(); i++) { + int fd = GetStoreFd(store_fds[i]); + LookupOrMmap(fd, store_fds[i], mmap_sizes[i]); + } + + for (int64_t i = 0; i < num_objects; ++i) { + DCHECK(received_object_ids[i] == object_ids[i]); + object = &object_data[i]; + if (object_buffers[i].data) { + // If the object was already in use by the client, then the store should + // have returned it. + DCHECK_NE(object->data_size, -1); + // We've already filled out the information for this object, so we can + // just continue. + continue; + } + // If we are here, the object was not currently in use, so we need to + // process the reply from the object store. + if (object->data_size != -1) { + std::shared_ptr physical_buf; + if (object->device_num == 0) { + uint8_t* data = LookupMmappedFile(object->store_fd); + physical_buf = std::make_shared( + data + object->data_offset, object->data_size + object->metadata_size); + } else { +#ifdef PLASMA_CUDA + std::lock_guard lock(gpu_mutex); + auto iter = gpu_object_map.find(object_ids[i]); + if (iter == gpu_object_map.end()) { + std::shared_ptr context; + ARROW_ASSIGN_OR_RAISE(context, manager_->GetContext(object->device_num - 1)); + GpuProcessHandle* obj_handle = new GpuProcessHandle(); + obj_handle->client_count = 1; + ARROW_ASSIGN_OR_RAISE(obj_handle->ptr, + context->OpenIpcBuffer(*object->ipc_handle)); + gpu_object_map[object_ids[i]] = obj_handle; + physical_buf = MakeBufferFromGpuProcessHandle(obj_handle); + } else { + iter->second->client_count++; + physical_buf = MakeBufferFromGpuProcessHandle(iter->second); + } +#else + ARROW_LOG(FATAL) << "Arrow GPU library is not enabled."; +#endif + } + // Finish filling out the return values. + physical_buf = wrap_buffer(object_ids[i], physical_buf); + object_buffers[i].data = SliceBuffer(physical_buf, 0, object->data_size); + object_buffers[i].metadata = + SliceBuffer(physical_buf, object->data_size, object->metadata_size); + object_buffers[i].device_num = object->device_num; + // Increment the count of the number of instances of this object that this + // client is using. Cache the reference to the object. + IncrementObjectCount(received_object_ids[i], object, true); + } else { + // The object was not retrieved. The caller can detect this condition + // by checking the boolean value of the metadata/data buffers. + DCHECK(!object_buffers[i].metadata); + DCHECK(!object_buffers[i].data); + } + } + return Status::OK(); +} + +Status PlasmaClient::Impl::Get(const std::vector& object_ids, + int64_t timeout_ms, std::vector* out) { + std::lock_guard guard(client_mutex_); + + const auto wrap_buffer = [=](const ObjectID& object_id, + const std::shared_ptr& buffer) { + return std::make_shared(shared_from_this(), object_id, buffer); + }; + const size_t num_objects = object_ids.size(); + *out = std::vector(num_objects); + return GetBuffers(&object_ids[0], num_objects, timeout_ms, wrap_buffer, &(*out)[0]); +} + +Status PlasmaClient::Impl::Get(const ObjectID* object_ids, int64_t num_objects, + int64_t timeout_ms, ObjectBuffer* out) { + std::lock_guard guard(client_mutex_); + + const auto wrap_buffer = [](const ObjectID& object_id, + const std::shared_ptr& buffer) { return buffer; }; + return GetBuffers(object_ids, num_objects, timeout_ms, wrap_buffer, out); +} + +Status PlasmaClient::Impl::MarkObjectUnused(const ObjectID& object_id) { + auto object_entry = objects_in_use_.find(object_id); + ARROW_CHECK(object_entry != objects_in_use_.end()); + ARROW_CHECK(object_entry->second->count == 0); + + // Remove the entry from the hash table of objects currently in use. + objects_in_use_.erase(object_id); + return Status::OK(); +} + +Status PlasmaClient::Impl::Release(const ObjectID& object_id) { + std::lock_guard guard(client_mutex_); + + // If the client is already disconnected, ignore release requests. + if (store_conn_ < 0) { + return Status::OK(); + } + auto object_entry = objects_in_use_.find(object_id); + ARROW_CHECK(object_entry != objects_in_use_.end()); + +#ifdef PLASMA_CUDA + if (object_entry->second->object.device_num != 0) { + std::lock_guard lock(gpu_mutex); + auto iter = gpu_object_map.find(object_id); + ARROW_CHECK(iter != gpu_object_map.end()); + if (--iter->second->client_count == 0) { + delete iter->second; + gpu_object_map.erase(iter); + } + } +#endif + + object_entry->second->count -= 1; + ARROW_CHECK(object_entry->second->count >= 0); + // Check if the client is no longer using this object. + if (object_entry->second->count == 0) { + // Tell the store that the client no longer needs the object. + RETURN_NOT_OK(MarkObjectUnused(object_id)); + RETURN_NOT_OK(SendReleaseRequest(store_conn_, object_id)); + auto iter = deletion_cache_.find(object_id); + if (iter != deletion_cache_.end()) { + deletion_cache_.erase(object_id); + RETURN_NOT_OK(Delete({object_id})); + } + } + return Status::OK(); +} + +// This method is used to query whether the plasma store contains an object. +Status PlasmaClient::Impl::Contains(const ObjectID& object_id, bool* has_object) { + std::lock_guard guard(client_mutex_); + + // Check if we already have a reference to the object. + if (objects_in_use_.count(object_id) > 0) { + *has_object = 1; + } else { + // If we don't already have a reference to the object, check with the store + // to see if we have the object. + RETURN_NOT_OK(SendContainsRequest(store_conn_, object_id)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaContainsReply, &buffer)); + ObjectID object_id2; + DCHECK_GT(buffer.size(), 0); + RETURN_NOT_OK( + ReadContainsReply(buffer.data(), buffer.size(), &object_id2, has_object)); + } + return Status::OK(); +} + +Status PlasmaClient::Impl::List(ObjectTable* objects) { + std::lock_guard guard(client_mutex_); + RETURN_NOT_OK(SendListRequest(store_conn_)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaListReply, &buffer)); + return ReadListReply(buffer.data(), buffer.size(), objects); +} + +static void ComputeBlockHash(const unsigned char* data, int64_t nbytes, uint64_t* hash) { + XXH64_state_t hash_state; + XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); + XXH64_update(&hash_state, data, nbytes); + *hash = XXH64_digest(&hash_state); +} + +bool PlasmaClient::Impl::ComputeObjectHashParallel(XXH64_state_t* hash_state, + const unsigned char* data, + int64_t nbytes) { + // Note that this function will likely be faster if the address of data is + // aligned on a 64-byte boundary. + auto pool = arrow::internal::GetCpuThreadPool(); + + const int num_threads = kHashingConcurrency; + uint64_t threadhash[num_threads + 1]; + const uint64_t data_address = reinterpret_cast(data); + const uint64_t num_blocks = nbytes / kBlockSize; + const uint64_t chunk_size = (num_blocks / num_threads) * kBlockSize; + const uint64_t right_address = data_address + chunk_size * num_threads; + const uint64_t suffix = (data_address + nbytes) - right_address; + // Now the data layout is | k * num_threads * block_size | suffix | == + // | num_threads * chunk_size | suffix |, where chunk_size = k * block_size. + // Each thread gets a "chunk" of k blocks, except the suffix thread. + + std::vector> futures; + for (int i = 0; i < num_threads; i++) { + futures.push_back(*pool->Submit( + ComputeBlockHash, reinterpret_cast(data_address) + i * chunk_size, + chunk_size, &threadhash[i])); + } + ComputeBlockHash(reinterpret_cast(right_address), suffix, + &threadhash[num_threads]); + + for (auto& fut : futures) { + ARROW_CHECK_OK(fut.status()); + } + + XXH64_update(hash_state, reinterpret_cast(threadhash), + sizeof(threadhash)); + return true; +} + +uint64_t PlasmaClient::Impl::ComputeObjectHash(const ObjectBuffer& obj_buffer) { + if (obj_buffer.device_num != 0) { + // TODO(wap): Create cuda program to hash data on gpu. + return 0; + } + return ComputeObjectHashCPU(obj_buffer.data->data(), obj_buffer.data->size(), + obj_buffer.metadata->data(), obj_buffer.metadata->size()); +} + +uint64_t PlasmaClient::Impl::ComputeObjectHashCPU(const uint8_t* data, int64_t data_size, + const uint8_t* metadata, + int64_t metadata_size) { + DCHECK(metadata); + DCHECK(data); + XXH64_state_t hash_state; + XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); + if (data_size >= kBytesInMB) { + ComputeObjectHashParallel(&hash_state, reinterpret_cast(data), + data_size); + } else { + XXH64_update(&hash_state, reinterpret_cast(data), data_size); + } + XXH64_update(&hash_state, reinterpret_cast(metadata), + metadata_size); + return XXH64_digest(&hash_state); +} + +Status PlasmaClient::Impl::Seal(const ObjectID& object_id) { + std::lock_guard guard(client_mutex_); + + // Make sure this client has a reference to the object before sending the + // request to Plasma. + auto object_entry = objects_in_use_.find(object_id); + + if (object_entry == objects_in_use_.end()) { + return MakePlasmaError(PlasmaErrorCode::PlasmaObjectNonexistent, + "Seal() called on an object without a reference to it"); + } + if (object_entry->second->is_sealed) { + return MakePlasmaError(PlasmaErrorCode::PlasmaObjectAlreadySealed, + "Seal() called on an already sealed object"); + } + + object_entry->second->is_sealed = true; + /// Send the seal request to Plasma. + std::vector digest(kDigestSize); + RETURN_NOT_OK(Hash(object_id, &digest[0])); + RETURN_NOT_OK( + SendSealRequest(store_conn_, object_id, std::string(digest.begin(), digest.end()))); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaSealReply, &buffer)); + ObjectID sealed_id; + RETURN_NOT_OK(ReadSealReply(buffer.data(), buffer.size(), &sealed_id)); + ARROW_CHECK(sealed_id == object_id); + // We call PlasmaClient::Release to decrement the number of instances of this + // object + // that are currently being used by this client. The corresponding increment + // happened in plasma_create and was used to ensure that the object was not + // released before the call to PlasmaClient::Seal. + return Release(object_id); +} + +Status PlasmaClient::Impl::Abort(const ObjectID& object_id) { + std::lock_guard guard(client_mutex_); + auto object_entry = objects_in_use_.find(object_id); + ARROW_CHECK(object_entry != objects_in_use_.end()) + << "Plasma client called abort on an object without a reference to it"; + ARROW_CHECK(!object_entry->second->is_sealed) + << "Plasma client called abort on a sealed object"; + + // Make sure that the Plasma client only has one reference to the object. If + // it has more, then the client needs to release the buffer before calling + // abort. + if (object_entry->second->count > 1) { + return Status::Invalid("Plasma client cannot have a reference to the buffer."); + } + +#ifdef PLASMA_CUDA + if (object_entry->second->object.device_num != 0) { + std::lock_guard lock(gpu_mutex); + auto iter = gpu_object_map.find(object_id); + ARROW_CHECK(iter != gpu_object_map.end()); + ARROW_CHECK(iter->second->client_count == 1); + delete iter->second; + gpu_object_map.erase(iter); + } +#endif + + // Send the abort request. + RETURN_NOT_OK(SendAbortRequest(store_conn_, object_id)); + // Decrease the reference count to zero, then remove the object. + object_entry->second->count--; + RETURN_NOT_OK(MarkObjectUnused(object_id)); + + std::vector buffer; + ObjectID id; + MessageType type; + RETURN_NOT_OK(ReadMessage(store_conn_, &type, &buffer)); + return ReadAbortReply(buffer.data(), buffer.size(), &id); +} + +Status PlasmaClient::Impl::Delete(const std::vector& object_ids) { + std::lock_guard guard(client_mutex_); + + std::vector not_in_use_ids; + for (auto& object_id : object_ids) { + // If the object is in used, skip it. + if (objects_in_use_.count(object_id) == 0) { + not_in_use_ids.push_back(object_id); + } else { + deletion_cache_.emplace(object_id); + } + } + if (not_in_use_ids.size() > 0) { + RETURN_NOT_OK(SendDeleteRequest(store_conn_, not_in_use_ids)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaDeleteReply, &buffer)); + DCHECK_GT(buffer.size(), 0); + std::vector error_codes; + not_in_use_ids.clear(); + RETURN_NOT_OK( + ReadDeleteReply(buffer.data(), buffer.size(), ¬_in_use_ids, &error_codes)); + } + return Status::OK(); +} + +Status PlasmaClient::Impl::Evict(int64_t num_bytes, int64_t& num_bytes_evicted) { + std::lock_guard guard(client_mutex_); + + // Send a request to the store to evict objects. + RETURN_NOT_OK(SendEvictRequest(store_conn_, num_bytes)); + // Wait for a response with the number of bytes actually evicted. + std::vector buffer; + MessageType type; + RETURN_NOT_OK(ReadMessage(store_conn_, &type, &buffer)); + return ReadEvictReply(buffer.data(), buffer.size(), num_bytes_evicted); +} + +Status PlasmaClient::Impl::Refresh(const std::vector& object_ids) { + std::lock_guard guard(client_mutex_); + + RETURN_NOT_OK(SendRefreshLRURequest(store_conn_, object_ids)); + std::vector buffer; + MessageType type; + RETURN_NOT_OK(ReadMessage(store_conn_, &type, &buffer)); + return ReadRefreshLRUReply(buffer.data(), buffer.size()); +} + +Status PlasmaClient::Impl::Hash(const ObjectID& object_id, uint8_t* digest) { + std::lock_guard guard(client_mutex_); + + // Get the plasma object data. We pass in a timeout of 0 to indicate that + // the operation should timeout immediately. + std::vector object_buffers; + RETURN_NOT_OK(Get({object_id}, 0, &object_buffers)); + // If the object was not retrieved, return false. + if (!object_buffers[0].data) { + return MakePlasmaError(PlasmaErrorCode::PlasmaObjectNonexistent, "Object not found"); + } + // Compute the hash. + uint64_t hash = ComputeObjectHash(object_buffers[0]); + memcpy(digest, &hash, sizeof(hash)); + return Status::OK(); +} + +Status PlasmaClient::Impl::Subscribe(int* fd) { + std::lock_guard guard(client_mutex_); + + int sock[2]; + // Create a non-blocking socket pair. This will only be used to send + // notifications from the Plasma store to the client. +#ifdef _WINSOCKAPI_ + SOCKET sockets[2] = { INVALID_SOCKET, INVALID_SOCKET }; + socketpair(AF_INET, SOCK_STREAM, 0, sockets); + sock[0] = fh_open(sockets[0], -1); + sock[1] = fh_open(sockets[1], -1); +#else + socketpair(AF_UNIX, SOCK_STREAM, 0, sock); +#endif + // Make the socket non-blocking. +#ifdef _WINSOCKAPI_ + unsigned long value = 1; + ARROW_CHECK(ioctlsocket(sock[1], FIONBIO, &value) == 0); +#else + int flags = fcntl(sock[1], F_GETFL, 0); + ARROW_CHECK(fcntl(sock[1], F_SETFL, flags | O_NONBLOCK) == 0); +#endif + // Tell the Plasma store about the subscription. + RETURN_NOT_OK(SendSubscribeRequest(store_conn_)); + // Send the file descriptor that the Plasma store should use to push + // notifications about sealed objects to this client. + ARROW_CHECK(send_fd(store_conn_, sock[1]) >= 0); + close(sock[1]); + // Return the file descriptor that the client should use to read notifications + // about sealed objects. + *fd = sock[0]; + return Status::OK(); +} + +Status PlasmaClient::Impl::GetNotification(int fd, ObjectID* object_id, + int64_t* data_size, int64_t* metadata_size) { + std::lock_guard guard(client_mutex_); + + if (pending_notification_.empty()) { + auto message = ReadMessageAsync(fd); + if (message == NULL) { + return Status::IOError("Failed to read object notification from Plasma socket"); + } + + std::vector object_ids; + std::vector data_sizes; + std::vector metadata_sizes; + RETURN_NOT_OK( + DecodeNotifications(message.get(), &object_ids, &data_sizes, &metadata_sizes)); + for (size_t i = 0; i < object_ids.size(); ++i) { + pending_notification_.emplace_back(object_ids[i], data_sizes[i], metadata_sizes[i]); + } + } + + auto notification = pending_notification_.front(); + *object_id = std::get<0>(notification); + *data_size = std::get<1>(notification); + *metadata_size = std::get<2>(notification); + + pending_notification_.pop_front(); + + return Status::OK(); +} + +Status PlasmaClient::Impl::DecodeNotifications(const uint8_t* buffer, + std::vector* object_ids, + std::vector* data_sizes, + std::vector* metadata_sizes) { + std::lock_guard guard(client_mutex_); + auto object_info = flatbuffers::GetRoot(buffer); + + for (size_t i = 0; i < object_info->object_info()->size(); ++i) { + auto info = object_info->object_info()->Get(i); + ObjectID id = ObjectID::from_binary(info->object_id()->str()); + object_ids->push_back(id); + if (info->is_deletion()) { + data_sizes->push_back(-1); + metadata_sizes->push_back(-1); + } else { + data_sizes->push_back(info->data_size()); + metadata_sizes->push_back(info->metadata_size()); + } + } + + return Status::OK(); +} + +Status PlasmaClient::Impl::Connect(const std::string& store_socket_name, + const std::string& manager_socket_name, + int release_delay, int num_retries) { + std::lock_guard guard(client_mutex_); + + RETURN_NOT_OK(ConnectIpcSocketRetry(store_socket_name, num_retries, -1, &store_conn_)); + if (manager_socket_name != "") { + return Status::NotImplemented("plasma manager is no longer supported"); + } + if (release_delay != 0) { + ARROW_LOG(WARNING) << "The release_delay parameter in PlasmaClient::Connect " + << "is deprecated"; + } + // Send a ConnectRequest to the store to get its memory capacity. + RETURN_NOT_OK(SendConnectRequest(store_conn_)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaConnectReply, &buffer)); + RETURN_NOT_OK(ReadConnectReply(buffer.data(), buffer.size(), &store_capacity_)); + return Status::OK(); +} + +Status PlasmaClient::Impl::SetClientOptions(const std::string& client_name, + int64_t output_memory_quota) { + std::lock_guard guard(client_mutex_); + RETURN_NOT_OK(SendSetOptionsRequest(store_conn_, client_name, output_memory_quota)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType::PlasmaSetOptionsReply, &buffer)); + return ReadSetOptionsReply(buffer.data(), buffer.size()); +} + +Status PlasmaClient::Impl::Disconnect() { + std::lock_guard guard(client_mutex_); + + // NOTE: We purposefully do not finish sending release calls for objects in + // use, so that we don't duplicate PlasmaClient::Release calls (when handling + // a SIGTERM, for example). + + // Close the connections to Plasma. The Plasma store will release the objects + // that were in use by us when handling the SIGPIPE. + close(store_conn_); + store_conn_ = -1; + return Status::OK(); +} + +std::string PlasmaClient::Impl::DebugString() { + std::lock_guard guard(client_mutex_); + if (!SendGetDebugStringRequest(store_conn_).ok()) { + return "error sending request"; + } + std::vector buffer; + if (!PlasmaReceive(store_conn_, MessageType::PlasmaGetDebugStringReply, &buffer).ok()) { + return "error receiving reply"; + } + std::string debug_string; + if (!ReadGetDebugStringReply(buffer.data(), buffer.size(), &debug_string).ok()) { + return "error parsing reply"; + } + return debug_string; +} + +// ---------------------------------------------------------------------- +// PlasmaClient + +PlasmaClient::PlasmaClient() : impl_(std::make_shared()) {} + +PlasmaClient::~PlasmaClient() {} + +Status PlasmaClient::Connect(const std::string& store_socket_name, + const std::string& manager_socket_name, int release_delay, + int num_retries) { + return impl_->Connect(store_socket_name, manager_socket_name, release_delay, + num_retries); +} + +Status PlasmaClient::SetClientOptions(const std::string& client_name, + int64_t output_memory_quota) { + return impl_->SetClientOptions(client_name, output_memory_quota); +} + +Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, + const uint8_t* metadata, int64_t metadata_size, + std::shared_ptr* data, int device_num, + bool evict_if_full) { + return impl_->Create(object_id, data_size, metadata, metadata_size, data, device_num, + evict_if_full); +} + +Status PlasmaClient::CreateAndSeal(const ObjectID& object_id, const std::string& data, + const std::string& metadata, bool evict_if_full) { + return impl_->CreateAndSeal(object_id, data, metadata, evict_if_full); +} + +Status PlasmaClient::CreateAndSealBatch(const std::vector& object_ids, + const std::vector& data, + const std::vector& metadata, + bool evict_if_full) { + return impl_->CreateAndSealBatch(object_ids, data, metadata, evict_if_full); +} + +Status PlasmaClient::Get(const std::vector& object_ids, int64_t timeout_ms, + std::vector* object_buffers) { + return impl_->Get(object_ids, timeout_ms, object_buffers); +} + +Status PlasmaClient::Get(const ObjectID* object_ids, int64_t num_objects, + int64_t timeout_ms, ObjectBuffer* object_buffers) { + return impl_->Get(object_ids, num_objects, timeout_ms, object_buffers); +} + +Status PlasmaClient::Release(const ObjectID& object_id) { + return impl_->Release(object_id); +} + +Status PlasmaClient::Contains(const ObjectID& object_id, bool* has_object) { + return impl_->Contains(object_id, has_object); +} + +Status PlasmaClient::List(ObjectTable* objects) { return impl_->List(objects); } + +Status PlasmaClient::Abort(const ObjectID& object_id) { return impl_->Abort(object_id); } + +Status PlasmaClient::Seal(const ObjectID& object_id) { return impl_->Seal(object_id); } + +Status PlasmaClient::Delete(const ObjectID& object_id) { + return impl_->Delete(std::vector{object_id}); +} + +Status PlasmaClient::Delete(const std::vector& object_ids) { + return impl_->Delete(object_ids); +} + +Status PlasmaClient::Evict(int64_t num_bytes, int64_t& num_bytes_evicted) { + return impl_->Evict(num_bytes, num_bytes_evicted); +} + +Status PlasmaClient::Refresh(const std::vector& object_ids) { + return impl_->Refresh(object_ids); +} + +Status PlasmaClient::Hash(const ObjectID& object_id, uint8_t* digest) { + return impl_->Hash(object_id, digest); +} + +Status PlasmaClient::Subscribe(int* fd) { return impl_->Subscribe(fd); } + +Status PlasmaClient::GetNotification(int fd, ObjectID* object_id, int64_t* data_size, + int64_t* metadata_size) { + return impl_->GetNotification(fd, object_id, data_size, metadata_size); +} + +Status PlasmaClient::DecodeNotifications(const uint8_t* buffer, + std::vector* object_ids, + std::vector* data_sizes, + std::vector* metadata_sizes) { + return impl_->DecodeNotifications(buffer, object_ids, data_sizes, metadata_sizes); +} + +Status PlasmaClient::Disconnect() { return impl_->Disconnect(); } + +std::string PlasmaClient::DebugString() { return impl_->DebugString(); } + +bool PlasmaClient::IsInUse(const ObjectID& object_id) { + return impl_->IsInUse(object_id); +} + +int64_t PlasmaClient::store_capacity() { return impl_->store_capacity(); } + +} // namespace plasma diff --git a/src/ray/plasma/client.h b/src/ray/plasma/client.h new file mode 100644 index 000000000..76d04a801 --- /dev/null +++ b/src/ray/plasma/client.h @@ -0,0 +1,312 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_CLIENT_H +#define PLASMA_CLIENT_H + +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/status.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" +#include "plasma/common.h" + +using arrow::Buffer; +using arrow::Status; + +namespace plasma { + +/// Object buffer data structure. +struct ObjectBuffer { + /// The data buffer. + std::shared_ptr data; + /// The metadata buffer. + std::shared_ptr metadata; + /// The device number. + int device_num; +}; + +class ARROW_EXPORT PlasmaClient { + public: + PlasmaClient(); + ~PlasmaClient(); + + /// Connect to the local plasma store. Return the resulting connection. + /// + /// \param store_socket_name The name of the UNIX domain socket to use to + /// connect to the Plasma store. + /// \param manager_socket_name The name of the UNIX domain socket to use to + /// connect to the local Plasma manager. If this is "", then this + /// function will not connect to a manager. + /// Note that plasma manager is no longer supported, this function + /// will return failure if this is not "". + /// \param release_delay Deprecated (not used). + /// \param num_retries number of attempts to connect to IPC socket, default 50 + /// \return The return status. + Status Connect(const std::string& store_socket_name, + const std::string& manager_socket_name = "", int release_delay = 0, + int num_retries = -1); + + /// Set runtime options for this client. + /// + /// \param client_name The name of the client, used in debug messages. + /// \param output_memory_quota The memory quota in bytes for objects created by + /// this client. + Status SetClientOptions(const std::string& client_name, int64_t output_memory_quota); + + /// Create an object in the Plasma Store. Any metadata for this object must be + /// be passed in when the object is created. + /// + /// \param object_id The ID to use for the newly created object. + /// \param data_size The size in bytes of the space to be allocated for this + /// object's + /// data (this does not include space used for metadata). + /// \param metadata The object's metadata. If there is no metadata, this + /// pointer + /// should be NULL. + /// \param metadata_size The size in bytes of the metadata. If there is no + /// metadata, this should be 0. + /// \param data The address of the newly created object will be written here. + /// \param device_num The number of the device where the object is being + /// created. + /// device_num = 0 corresponds to the host, + /// device_num = 1 corresponds to GPU0, + /// device_num = 2 corresponds to GPU1, etc. + /// \param evict_if_full Whether to evict other objects to make space for + /// this object. + /// \return The return status. + /// + /// The returned object must be released once it is done with. It must also + /// be either sealed or aborted. + Status Create(const ObjectID& object_id, int64_t data_size, const uint8_t* metadata, + int64_t metadata_size, std::shared_ptr* data, int device_num = 0, + bool evict_if_full = true); + + /// Create and seal an object in the object store. This is an optimization + /// which allows small objects to be created quickly with fewer messages to + /// the store. + /// + /// \param object_id The ID of the object to create. + /// \param data The data for the object to create. + /// \param metadata The metadata for the object to create. + /// \param evict_if_full Whether to evict other objects to make space for + /// this object. + /// \return The return status. + Status CreateAndSeal(const ObjectID& object_id, const std::string& data, + const std::string& metadata, bool evict_if_full = true); + + /// Create and seal multiple objects in the object store. This is an optimization + /// of CreateAndSeal to eliminate the cost of IPC per object. + /// + /// \param object_ids The vector of IDs of the objects to create. + /// \param data The vector of data for the objects to create. + /// \param metadata The vector of metadata for the objects to create. + /// \param evict_if_full Whether to evict other objects to make space for + /// these objects. + /// \return The return status. + Status CreateAndSealBatch(const std::vector& object_ids, + const std::vector& data, + const std::vector& metadata, + bool evict_if_full = true); + + /// Get some objects from the Plasma Store. This function will block until the + /// objects have all been created and sealed in the Plasma Store or the + /// timeout expires. + /// + /// If an object was not retrieved, the corresponding metadata and data + /// fields in the ObjectBuffer structure will evaluate to false. + /// Objects are automatically released by the client when their buffers + /// get out of scope. + /// + /// \param object_ids The IDs of the objects to get. + /// \param timeout_ms The amount of time in milliseconds to wait before this + /// request times out. If this value is -1, then no timeout is set. + /// \param[out] object_buffers The object results. + /// \return The return status. + Status Get(const std::vector& object_ids, int64_t timeout_ms, + std::vector* object_buffers); + + /// Deprecated variant of Get() that doesn't automatically release buffers + /// when they get out of scope. + /// + /// \param object_ids The IDs of the objects to get. + /// \param num_objects The number of object IDs to get. + /// \param timeout_ms The amount of time in milliseconds to wait before this + /// request times out. If this value is -1, then no timeout is set. + /// \param object_buffers An array where the results will be stored. + /// \return The return status. + /// + /// The caller is responsible for releasing any retrieved objects, but it + /// should not release objects that were not retrieved. + Status Get(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, + ObjectBuffer* object_buffers); + + /// Tell Plasma that the client no longer needs the object. This should be + /// called after Get() or Create() when the client is done with the object. + /// After this call, the buffer returned by Get() is no longer valid. + /// + /// \param object_id The ID of the object that is no longer needed. + /// \return The return status. + Status Release(const ObjectID& object_id); + + /// Check if the object store contains a particular object and the object has + /// been sealed. The result will be stored in has_object. + /// + /// @todo: We may want to indicate if the object has been created but not + /// sealed. + /// + /// \param object_id The ID of the object whose presence we are checking. + /// \param has_object The function will write true at this address if + /// the object is present and false if it is not present. + /// \return The return status. + Status Contains(const ObjectID& object_id, bool* has_object); + + /// List all the objects in the object store. + /// + /// This API is experimental and might change in the future. + /// + /// \param[out] objects ObjectTable of objects in the store. For each entry + /// in the map, the following fields are available: + /// - metadata_size: Size of the object metadata in bytes + /// - data_size: Size of the object data in bytes + /// - ref_count: Number of clients referencing the object buffer + /// - create_time: Unix timestamp of the object creation + /// - construct_duration: Object creation time in seconds + /// - state: Is the object still being created or already sealed? + /// \return The return status. + Status List(ObjectTable* objects); + + /// Abort an unsealed object in the object store. If the abort succeeds, then + /// it will be as if the object was never created at all. The unsealed object + /// must have only a single reference (the one that would have been removed by + /// calling Seal). + /// + /// \param object_id The ID of the object to abort. + /// \return The return status. + Status Abort(const ObjectID& object_id); + + /// Seal an object in the object store. The object will be immutable after + /// this + /// call. + /// + /// \param object_id The ID of the object to seal. + /// \return The return status. + Status Seal(const ObjectID& object_id); + + /// Delete an object from the object store. This currently assumes that the + /// object is present, has been sealed and not used by another client. Otherwise, + /// it is a no operation. + /// + /// \todo We may want to allow the deletion of objects that are not present or + /// haven't been sealed. + /// + /// \param object_id The ID of the object to delete. + /// \return The return status. + Status Delete(const ObjectID& object_id); + + /// Delete a list of objects from the object store. This currently assumes that the + /// object is present, has been sealed and not used by another client. Otherwise, + /// it is a no operation. + /// + /// \param object_ids The list of IDs of the objects to delete. + /// \return The return status. If all the objects are non-existent, return OK. + Status Delete(const std::vector& object_ids); + + /// Delete objects until we have freed up num_bytes bytes or there are no more + /// released objects that can be deleted. + /// + /// \param num_bytes The number of bytes to try to free up. + /// \param num_bytes_evicted Out parameter for total number of bytes of space + /// retrieved. + /// \return The return status. + Status Evict(int64_t num_bytes, int64_t& num_bytes_evicted); + + /// Bump objects up in the LRU cache, i.e. treat them as recently accessed. + /// Objects that do not exist in the store will be ignored. + /// + /// \param object_ids The IDs of the objects to bump. + /// \return The return status. + Status Refresh(const std::vector& object_ids); + + /// Compute the hash of an object in the object store. + /// + /// \param object_id The ID of the object we want to hash. + /// \param digest A pointer at which to return the hash digest of the object. + /// The pointer must have at least kDigestSize bytes allocated. + /// \return The return status. + Status Hash(const ObjectID& object_id, uint8_t* digest); + + /// Subscribe to notifications when objects are sealed in the object store. + /// Whenever an object is sealed, a message will be written to the client + /// socket that is returned by this method. + /// + /// \param fd Out parameter for the file descriptor the client should use to + /// read notifications + /// from the object store about sealed objects. + /// \return The return status. + Status Subscribe(int* fd); + + /// Receive next object notification for this client if Subscribe has been called. + /// + /// \param fd The file descriptor we are reading the notification from. + /// \param object_id Out parameter, the object_id of the object that was sealed. + /// \param data_size Out parameter, the data size of the object that was sealed. + /// \param metadata_size Out parameter, the metadata size of the object that was sealed. + /// \return The return status. + Status GetNotification(int fd, ObjectID* object_id, int64_t* data_size, + int64_t* metadata_size); + + Status DecodeNotifications(const uint8_t* buffer, std::vector* object_ids, + std::vector* data_sizes, + std::vector* metadata_sizes); + + /// Disconnect from the local plasma instance, including the local store and + /// manager. + /// + /// \return The return status. + Status Disconnect(); + + /// Get the current debug string from the plasma store server. + /// + /// \return The debug string. + std::string DebugString(); + + /// Get the memory capacity of the store. + /// + /// \return Memory capacity of the store in bytes. + int64_t store_capacity(); + + private: + friend class PlasmaBuffer; + friend class PlasmaMutableBuffer; + FRIEND_TEST(TestPlasmaStore, GetTest); + FRIEND_TEST(TestPlasmaStore, LegacyGetTest); + FRIEND_TEST(TestPlasmaStore, AbortTest); + + bool IsInUse(const ObjectID& object_id); + + class ARROW_NO_EXPORT Impl; + std::shared_ptr impl_; +}; + +} // namespace plasma + +#endif // PLASMA_CLIENT_H diff --git a/src/ray/plasma/common.cc b/src/ray/plasma/common.cc new file mode 100644 index 000000000..bbcd2c9c3 --- /dev/null +++ b/src/ray/plasma/common.cc @@ -0,0 +1,195 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/common.h" + +#include +#include + +#include "arrow/util/ubsan.h" + +#include "plasma/plasma_generated.h" + +namespace fb = plasma::flatbuf; + +namespace plasma { + +namespace { + +const char kErrorDetailTypeId[] = "plasma::PlasmaStatusDetail"; + +class PlasmaStatusDetail : public arrow::StatusDetail { + public: + explicit PlasmaStatusDetail(PlasmaErrorCode code) : code_(code) {} + const char* type_id() const override { return kErrorDetailTypeId; } + std::string ToString() const override { + const char* type; + switch (code()) { + case PlasmaErrorCode::PlasmaObjectExists: + type = "Plasma object exists"; + break; + case PlasmaErrorCode::PlasmaObjectNonexistent: + type = "Plasma object is nonexistent"; + break; + case PlasmaErrorCode::PlasmaStoreFull: + type = "Plasma store is full"; + break; + case PlasmaErrorCode::PlasmaObjectAlreadySealed: + type = "Plasma object is already sealed"; + break; + default: + type = "Unknown plasma error"; + break; + } + return std::string(type); + } + PlasmaErrorCode code() const { return code_; } + + private: + PlasmaErrorCode code_; +}; + +bool IsPlasmaStatus(const arrow::Status& status, PlasmaErrorCode code) { + if (status.ok()) { + return false; + } + auto* detail = status.detail().get(); + return detail != nullptr && detail->type_id() == kErrorDetailTypeId && + static_cast(detail)->code() == code; +} + +} // namespace + +using arrow::Status; + +arrow::Status MakePlasmaError(PlasmaErrorCode code, std::string message) { + arrow::StatusCode arrow_code = arrow::StatusCode::UnknownError; + switch (code) { + case PlasmaErrorCode::PlasmaObjectExists: + arrow_code = arrow::StatusCode::AlreadyExists; + break; + case PlasmaErrorCode::PlasmaObjectNonexistent: + arrow_code = arrow::StatusCode::KeyError; + break; + case PlasmaErrorCode::PlasmaStoreFull: + arrow_code = arrow::StatusCode::CapacityError; + break; + case PlasmaErrorCode::PlasmaObjectAlreadySealed: + // Maybe a stretch? + arrow_code = arrow::StatusCode::TypeError; + break; + } + return arrow::Status(arrow_code, std::move(message), + std::make_shared(code)); +} + +bool IsPlasmaObjectExists(const arrow::Status& status) { + return IsPlasmaStatus(status, PlasmaErrorCode::PlasmaObjectExists); +} +bool IsPlasmaObjectNonexistent(const arrow::Status& status) { + return IsPlasmaStatus(status, PlasmaErrorCode::PlasmaObjectNonexistent); +} +bool IsPlasmaObjectAlreadySealed(const arrow::Status& status) { + return IsPlasmaStatus(status, PlasmaErrorCode::PlasmaObjectAlreadySealed); +} +bool IsPlasmaStoreFull(const arrow::Status& status) { + return IsPlasmaStatus(status, PlasmaErrorCode::PlasmaStoreFull); +} + +UniqueID UniqueID::from_binary(const std::string& binary) { + UniqueID id; + std::memcpy(&id, binary.data(), sizeof(id)); + return id; +} + +const uint8_t* UniqueID::data() const { return id_; } + +uint8_t* UniqueID::mutable_data() { return id_; } + +std::string UniqueID::binary() const { + return std::string(reinterpret_cast(id_), kUniqueIDSize); +} + +std::string UniqueID::hex() const { + constexpr char hex[] = "0123456789abcdef"; + std::string result; + for (int i = 0; i < kUniqueIDSize; i++) { + unsigned int val = id_[i]; + result.push_back(hex[val >> 4]); + result.push_back(hex[val & 0xf]); + } + return result; +} + +// This code is from https://sites.google.com/site/murmurhash/ +// and is public domain. +uint64_t MurmurHash64A(const void* key, int len, unsigned int seed) { + const uint64_t m = 0xc6a4a7935bd1e995; + const int r = 47; + + uint64_t h = seed ^ (len * m); + + const uint64_t* data = reinterpret_cast(key); + const uint64_t* end = data + (len / 8); + + while (data != end) { + uint64_t k = arrow::util::SafeLoad(data++); + + k *= m; + k ^= k >> r; + k *= m; + + h ^= k; + h *= m; + } + + const unsigned char* data2 = reinterpret_cast(data); + + switch (len & 7) { + case 7: + h ^= uint64_t(data2[6]) << 48; // fall through + case 6: + h ^= uint64_t(data2[5]) << 40; // fall through + case 5: + h ^= uint64_t(data2[4]) << 32; // fall through + case 4: + h ^= uint64_t(data2[3]) << 24; // fall through + case 3: + h ^= uint64_t(data2[2]) << 16; // fall through + case 2: + h ^= uint64_t(data2[1]) << 8; // fall through + case 1: + h ^= uint64_t(data2[0]); + h *= m; + } + + h ^= h >> r; + h *= m; + h ^= h >> r; + + return h; +} + +size_t UniqueID::hash() const { return MurmurHash64A(&id_[0], kUniqueIDSize, 0); } + +bool UniqueID::operator==(const UniqueID& rhs) const { + return std::memcmp(data(), rhs.data(), kUniqueIDSize) == 0; +} + +const PlasmaStoreInfo* plasma_config; + +} // namespace plasma diff --git a/src/ray/plasma/common.fbs b/src/ray/plasma/common.fbs new file mode 100644 index 000000000..818827a7e --- /dev/null +++ b/src/ray/plasma/common.fbs @@ -0,0 +1,39 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace plasma.flatbuf; + +// Object information data structure. +table ObjectInfo { + // Object ID of this object. + object_id: string; + // Number of bytes the content of this object occupies in memory. + data_size: long; + // Number of bytes the metadata of this object occupies in memory. + metadata_size: long; + // Number of clients using the objects. + ref_count: int; + // Unix epoch of when this object was created. + create_time: long; + // How long creation of this object took. + construct_duration: long; + // Hash of the object content. If the object is not sealed yet this is + // an empty string. + digest: string; + // Specifies if this object was deleted or added. + is_deletion: bool; +} diff --git a/src/ray/plasma/common.h b/src/ray/plasma/common.h new file mode 100644 index 000000000..d42840cfb --- /dev/null +++ b/src/ray/plasma/common.h @@ -0,0 +1,158 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_COMMON_H +#define PLASMA_COMMON_H + +#include + +#include +#include +#include +// TODO(pcm): Convert getopt and sscanf in the store to use more idiomatic C++ +// and get rid of the next three lines: +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#include + +#include "plasma/compat.h" + +#include "arrow/status.h" +#ifdef PLASMA_CUDA +#include "arrow/gpu/cuda_api.h" +#endif + +namespace plasma { + +enum class ObjectLocation : int32_t { Local, Remote, Nonexistent }; + +enum class PlasmaErrorCode : int8_t { + PlasmaObjectExists = 1, + PlasmaObjectNonexistent = 2, + PlasmaStoreFull = 3, + PlasmaObjectAlreadySealed = 4, +}; + +ARROW_EXPORT arrow::Status MakePlasmaError(PlasmaErrorCode code, std::string message); +/// Return true iff the status indicates an already existing Plasma object. +ARROW_EXPORT bool IsPlasmaObjectExists(const arrow::Status& status); +/// Return true iff the status indicates a non-existent Plasma object. +ARROW_EXPORT bool IsPlasmaObjectNonexistent(const arrow::Status& status); +/// Return true iff the status indicates an already sealed Plasma object. +ARROW_EXPORT bool IsPlasmaObjectAlreadySealed(const arrow::Status& status); +/// Return true iff the status indicates the Plasma store reached its capacity limit. +ARROW_EXPORT bool IsPlasmaStoreFull(const arrow::Status& status); + +constexpr int64_t kUniqueIDSize = 20; + +class ARROW_EXPORT UniqueID { + public: + static UniqueID from_binary(const std::string& binary); + bool operator==(const UniqueID& rhs) const; + const uint8_t* data() const; + uint8_t* mutable_data(); + std::string binary() const; + std::string hex() const; + size_t hash() const; + static int64_t size() { return kUniqueIDSize; } + + private: + uint8_t id_[kUniqueIDSize]; +}; + +static_assert(std::is_pod::value, "UniqueID must be plain old data"); + +typedef UniqueID ObjectID; + +/// Size of object hash digests. +constexpr int64_t kDigestSize = sizeof(uint64_t); + +enum class ObjectState : int { + /// Object was created but not sealed in the local Plasma Store. + PLASMA_CREATED = 1, + /// Object is sealed and stored in the local Plasma Store. + PLASMA_SEALED = 2, + /// Object is evicted to external store. + PLASMA_EVICTED = 3, +}; + +namespace internal { + +struct CudaIpcPlaceholder {}; + +} // namespace internal + +/// This type is used by the Plasma store. It is here because it is exposed to +/// the eviction policy. +struct ObjectTableEntry { + ObjectTableEntry(); + + ~ObjectTableEntry(); + + /// Memory mapped file containing the object. + int fd; + /// Device number. + int device_num; + /// Size of the underlying map. + int64_t map_size; + /// Offset from the base of the mmap. + ptrdiff_t offset; + /// Pointer to the object data. Needed to free the object. + uint8_t* pointer; + /// Size of the object in bytes. + int64_t data_size; + /// Size of the object metadata in bytes. + int64_t metadata_size; + /// Number of clients currently using this object. + int ref_count; + /// Unix epoch of when this object was created. + int64_t create_time; + /// How long creation of this object took. + int64_t construct_duration; + + /// The state of the object, e.g., whether it is open or sealed. + ObjectState state; + /// The digest of the object. Used to see if two objects are the same. + unsigned char digest[kDigestSize]; + +#ifdef PLASMA_CUDA + /// IPC GPU handle to share with clients. + std::shared_ptr<::arrow::cuda::CudaIpcMemHandle> ipc_handle; +#else + std::shared_ptr ipc_handle; +#endif +}; + +/// Mapping from ObjectIDs to information about the object. +typedef std::unordered_map> ObjectTable; + +/// Globally accessible reference to plasma store configuration. +/// TODO(pcm): This can be avoided with some refactoring of existing code +/// by making it possible to pass a context object through dlmalloc. +struct PlasmaStoreInfo; +extern const PlasmaStoreInfo* plasma_config; +} // namespace plasma + +namespace std { +template <> +struct hash<::plasma::UniqueID> { + size_t operator()(const ::plasma::UniqueID& id) const { return id.hash(); } +}; +} // namespace std + +#endif // PLASMA_COMMON_H diff --git a/src/ray/plasma/compat.h b/src/ray/plasma/compat.h new file mode 100644 index 000000000..ce751da1d --- /dev/null +++ b/src/ray/plasma/compat.h @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_COMPAT_H +#define PLASMA_COMPAT_H + +// Workaround for multithreading on XCode 9, see +// https://issues.apache.org/jira/browse/ARROW-1622 and +// https://github.com/tensorflow/tensorflow/issues/13220#issuecomment-331579775 +// This should be a short-term fix until the problem is fixed upstream. +#ifdef __APPLE__ +#ifndef _MACH_PORT_T +#define _MACH_PORT_T +#include /* __darwin_mach_port_t */ +typedef __darwin_mach_port_t mach_port_t; +#include +mach_port_t pthread_mach_thread_np(pthread_t); +#endif /* _MACH_PORT_T */ +#endif /* __APPLE__ */ + +#endif // PLASMA_COMPAT_H diff --git a/src/ray/plasma/dlmalloc.cc b/src/ray/plasma/dlmalloc.cc new file mode 100644 index 000000000..eb37df827 --- /dev/null +++ b/src/ray/plasma/dlmalloc.cc @@ -0,0 +1,186 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/malloc.h" + +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#include +#endif +#include +#include +#include + +#include "plasma/common.h" +#include "plasma/plasma.h" + +namespace plasma { + +void* fake_mmap(size_t); +int fake_munmap(void*, int64_t); + +#define MMAP(s) fake_mmap(s) +#define MUNMAP(a, s) fake_munmap(a, s) +#define DIRECT_MMAP(s) fake_mmap(s) +#define DIRECT_MUNMAP(a, s) fake_munmap(a, s) +#define USE_DL_PREFIX +#define HAVE_MORECORE 0 +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#define DEFAULT_GRANULARITY ((size_t)128U * 1024U) + +#include "plasma/thirdparty/dlmalloc.c" // NOLINT + +#undef MMAP +#undef MUNMAP +#undef DIRECT_MMAP +#undef DIRECT_MUNMAP +#undef USE_DL_PREFIX +#undef HAVE_MORECORE +#undef DEFAULT_GRANULARITY + +// dlmalloc.c defined DEBUG which will conflict with ARROW_LOG(DEBUG). +#ifdef DEBUG +#undef DEBUG +#endif + +constexpr int GRANULARITY_MULTIPLIER = 2; + +static void* pointer_advance(void* p, ptrdiff_t n) { return (unsigned char*)p + n; } + +static void* pointer_retreat(void* p, ptrdiff_t n) { return (unsigned char*)p - n; } + +// Create a buffer. This is creating a temporary file and then +// immediately unlinking it so we do not leave traces in the system. +int create_buffer(int64_t size) { + int fd; + std::string file_template = plasma_config->directory; +#ifdef _WIN32 + HANDLE h = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, + (DWORD)((uint64_t)size >> (CHAR_BIT * sizeof(DWORD))), + (DWORD)(uint64_t)size, NULL); + if (h) { + fd = fh_open(reinterpret_cast(h), -1); + } else { + fd = -1; + } +#else + file_template += "/plasmaXXXXXX"; + std::vector file_name(file_template.begin(), file_template.end()); + file_name.push_back('\0'); + fd = mkstemp(&file_name[0]); + if (fd < 0) { + ARROW_LOG(FATAL) << "create_buffer failed to open file " << &file_name[0]; + return -1; + } + // Immediately unlink the file so we do not leave traces in the system. + if (unlink(&file_name[0]) != 0) { + ARROW_LOG(FATAL) << "failed to unlink file " << &file_name[0]; + return -1; + } + if (!plasma_config->hugepages_enabled) { + // Increase the size of the file to the desired size. This seems not to be + // needed for files that are backed by the huge page fs, see also + // http://www.mail-archive.com/kvm-devel@lists.sourceforge.net/msg14737.html + if (ftruncate(fd, (off_t)size) != 0) { + ARROW_LOG(FATAL) << "failed to ftruncate file " << &file_name[0]; + return -1; + } + } +#endif + return fd; +} + +void* fake_mmap(size_t size) { + // Add kMmapRegionsGap so that the returned pointer is deliberately not + // page-aligned. This ensures that the segments of memory returned by + // fake_mmap are never contiguous. + size += kMmapRegionsGap; + + int fd = create_buffer(size); + ARROW_CHECK(fd >= 0) << "Failed to create buffer during mmap"; + // MAP_POPULATE can be used to pre-populate the page tables for this memory region + // which avoids work when accessing the pages later. However it causes long pauses + // when mmapping the files. Only supported on Linux. + void* pointer; +#ifdef _WIN32 + pointer = MapViewOfFile(reinterpret_cast(fh_get(fd)), FILE_MAP_ALL_ACCESS, 0, 0, size); + if (pointer == NULL) { + ARROW_LOG(ERROR) << "MapViewOfFile failed with error: " << GetLastError(); + return reinterpret_cast(-1); + } +#else + pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (pointer == MAP_FAILED) { + ARROW_LOG(ERROR) << "mmap failed with error: " << std::strerror(errno); + if (errno == ENOMEM && plasma_config->hugepages_enabled) { + ARROW_LOG(ERROR) + << " (this probably means you have to increase /proc/sys/vm/nr_hugepages)"; + } + return pointer; + } +#endif + + // Increase dlmalloc's allocation granularity directly. + mparams.granularity *= GRANULARITY_MULTIPLIER; + + MmapRecord& record = mmap_records[pointer]; + record.fd = fd; + record.size = size; + + // We lie to dlmalloc about where mapped memory actually lives. + pointer = pointer_advance(pointer, kMmapRegionsGap); + ARROW_LOG(DEBUG) << pointer << " = fake_mmap(" << size << ")"; + return pointer; +} + +int fake_munmap(void* addr, int64_t size) { + ARROW_LOG(DEBUG) << "fake_munmap(" << addr << ", " << size << ")"; + addr = pointer_retreat(addr, kMmapRegionsGap); + size += kMmapRegionsGap; + + auto entry = mmap_records.find(addr); + + if (entry == mmap_records.end() || entry->second.size != size) { + // Reject requests to munmap that don't directly match previous + // calls to mmap, to prevent dlmalloc from trimming. + return -1; + } + + int r; +#ifdef _WIN32 + r = UnmapViewOfFile(addr) ? 0 : -1; +#else + r = munmap(addr, size); +#endif + if (r == 0) { + close(entry->second.fd); + } + + mmap_records.erase(entry); + return r; +} + +void SetMallocGranularity(int value) { change_mparam(M_GRANULARITY, value); } + +} // namespace plasma diff --git a/src/ray/plasma/events.cc b/src/ray/plasma/events.cc new file mode 100644 index 000000000..28ff12675 --- /dev/null +++ b/src/ray/plasma/events.cc @@ -0,0 +1,107 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/events.h" + +#include + +#include + +extern "C" { +#include "plasma/thirdparty/ae/ae.h" +} + +namespace plasma { + +// Verify that the constants defined in events.h are defined correctly. +static_assert(kEventLoopTimerDone == AE_NOMORE, "constant defined incorrectly"); +static_assert(kEventLoopOk == AE_OK, "constant defined incorrectly"); +static_assert(kEventLoopRead == AE_READABLE, "constant defined incorrectly"); +static_assert(kEventLoopWrite == AE_WRITABLE, "constant defined incorrectly"); + +void EventLoop::FileEventCallback(aeEventLoop* loop, int fd, void* context, int events) { + FileCallback* callback = reinterpret_cast(context); + (*callback)(events); +} + +int EventLoop::TimerEventCallback(aeEventLoop* loop, TimerID timer_id, void* context) { + TimerCallback* callback = reinterpret_cast(context); + return (*callback)(timer_id); +} + +constexpr int kInitialEventLoopSize = 1024; + +EventLoop::EventLoop() { loop_ = aeCreateEventLoop(kInitialEventLoopSize); } + +bool EventLoop::AddFileEvent(int fd, int events, const FileCallback& callback) { + if (file_callbacks_.find(fd) != file_callbacks_.end()) { + return false; + } + auto data = std::unique_ptr(new FileCallback(callback)); + void* context = reinterpret_cast(data.get()); + // Try to add the file descriptor. + int err = aeCreateFileEvent(loop_, fd, events, EventLoop::FileEventCallback, context); + // If it cannot be added, increase the size of the event loop. + if (err == AE_ERR && errno == ERANGE) { + err = aeResizeSetSize(loop_, 3 * aeGetSetSize(loop_) / 2); + if (err != AE_OK) { + return false; + } + err = aeCreateFileEvent(loop_, fd, events, EventLoop::FileEventCallback, context); + } + // In any case, test if there were errors. + if (err == AE_OK) { + file_callbacks_.emplace(fd, std::move(data)); + return true; + } + return false; +} + +void EventLoop::RemoveFileEvent(int fd) { + aeDeleteFileEvent(loop_, fd, AE_READABLE | AE_WRITABLE); + file_callbacks_.erase(fd); +} + +void EventLoop::Start() { aeMain(loop_); } + +void EventLoop::Stop() { aeStop(loop_); } + +void EventLoop::Shutdown() { + if (loop_ != nullptr) { + aeDeleteEventLoop(loop_); + loop_ = nullptr; + } +} + +EventLoop::~EventLoop() { Shutdown(); } + +int64_t EventLoop::AddTimer(int64_t timeout, const TimerCallback& callback) { + auto data = std::unique_ptr(new TimerCallback(callback)); + void* context = reinterpret_cast(data.get()); + int64_t timer_id = + aeCreateTimeEvent(loop_, timeout, EventLoop::TimerEventCallback, context, NULL); + timer_callbacks_.emplace(timer_id, std::move(data)); + return timer_id; +} + +int EventLoop::RemoveTimer(int64_t timer_id) { + int err = aeDeleteTimeEvent(loop_, timer_id); + timer_callbacks_.erase(timer_id); + return err; +} + +} // namespace plasma diff --git a/src/ray/plasma/events.h b/src/ray/plasma/events.h new file mode 100644 index 000000000..765be9c01 --- /dev/null +++ b/src/ray/plasma/events.h @@ -0,0 +1,111 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_EVENTS +#define PLASMA_EVENTS + +#include +#include +#include + +struct aeEventLoop; + +namespace plasma { + +// The constants below are defined using hardcoded values taken from ae.h so +// that ae.h does not need to be included in this file. + +/// Constant specifying that the timer is done and it will be removed. +constexpr int kEventLoopTimerDone = -1; // AE_NOMORE + +/// A successful status. +constexpr int kEventLoopOk = 0; // AE_OK + +/// Read event on the file descriptor. +constexpr int kEventLoopRead = 1; // AE_READABLE + +/// Write event on the file descriptor. +constexpr int kEventLoopWrite = 2; // AE_WRITABLE + +typedef long long TimerID; // NOLINT + +class EventLoop { + public: + // Signature of the handler that will be called when there is a new event + // on the file descriptor that this handler has been registered for. + // + // The arguments are the event flags (read or write). + using FileCallback = std::function; + + // This handler will be called when a timer times out. The timer id is + // passed as an argument. The return is the number of milliseconds the timer + // shall be reset to or kEventLoopTimerDone if the timer shall not be + // triggered again. + using TimerCallback = std::function; + + EventLoop(); + + ~EventLoop(); + + /// Add a new file event handler to the event loop. + /// + /// \param fd The file descriptor we are listening to. + /// \param events The flags for events we are listening to (read or write). + /// \param callback The callback that will be called when the event happens. + /// \return Returns true if the event handler was added successfully. + bool AddFileEvent(int fd, int events, const FileCallback& callback); + + /// Remove a file event handler from the event loop. + /// + /// \param fd The file descriptor of the event handler. + void RemoveFileEvent(int fd); + + /// Register a handler that will be called after a time slice of + /// "timeout" milliseconds. + /// + /// \param timeout The timeout in milliseconds. + /// \param callback The callback for the timeout. + /// \return The ID of the newly created timer. + int64_t AddTimer(int64_t timeout, const TimerCallback& callback); + + /// Remove a timer handler from the event loop. + /// + /// \param timer_id The ID of the timer that is to be removed. + /// \return The ae.c error code. TODO(pcm): needs to be standardized + int RemoveTimer(int64_t timer_id); + + /// \brief Run the event loop. + void Start(); + + /// \brief Stop the event loop + void Stop(); + + void Shutdown(); + + private: + static void FileEventCallback(aeEventLoop* loop, int fd, void* context, int events); + + static int TimerEventCallback(aeEventLoop* loop, TimerID timer_id, void* context); + + aeEventLoop* loop_; + std::unordered_map> file_callbacks_; + std::unordered_map> timer_callbacks_; +}; + +} // namespace plasma + +#endif // PLASMA_EVENTS diff --git a/src/ray/plasma/eviction_policy.cc b/src/ray/plasma/eviction_policy.cc new file mode 100644 index 000000000..c3b786785 --- /dev/null +++ b/src/ray/plasma/eviction_policy.cc @@ -0,0 +1,175 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/eviction_policy.h" +#include "plasma/plasma_allocator.h" + +#include +#include + +namespace plasma { + +void LRUCache::Add(const ObjectID& key, int64_t size) { + auto it = item_map_.find(key); + ARROW_CHECK(it == item_map_.end()); + // Note that it is important to use a list so the iterators stay valid. + item_list_.emplace_front(key, size); + item_map_.emplace(key, item_list_.begin()); + used_capacity_ += size; +} + +int64_t LRUCache::Remove(const ObjectID& key) { + auto it = item_map_.find(key); + if (it == item_map_.end()) { + return -1; + } + int64_t size = it->second->second; + used_capacity_ -= size; + item_list_.erase(it->second); + item_map_.erase(it); + ARROW_CHECK(used_capacity_ >= 0) << DebugString(); + return size; +} + +void LRUCache::AdjustCapacity(int64_t delta) { + ARROW_LOG(INFO) << "adjusting global lru capacity from " << Capacity() << " to " + << (Capacity() + delta) << " (max " << OriginalCapacity() << ")"; + capacity_ += delta; + ARROW_CHECK(used_capacity_ >= 0) << DebugString(); +} + +int64_t LRUCache::Capacity() const { return capacity_; } + +int64_t LRUCache::OriginalCapacity() const { return original_capacity_; } + +int64_t LRUCache::RemainingCapacity() const { return capacity_ - used_capacity_; } + +void LRUCache::Foreach(std::function f) { + for (auto& pair : item_list_) { + f(pair.first); + } +} + +std::string LRUCache::DebugString() const { + std::stringstream result; + result << "\n(" << name_ << ") capacity: " << Capacity(); + result << "\n(" << name_ + << ") used: " << 100. * (1. - (RemainingCapacity() / (double)OriginalCapacity())) + << "%"; + result << "\n(" << name_ << ") num objects: " << item_map_.size(); + result << "\n(" << name_ << ") num evictions: " << num_evictions_total_; + result << "\n(" << name_ << ") bytes evicted: " << bytes_evicted_total_; + return result.str(); +} + +int64_t LRUCache::ChooseObjectsToEvict(int64_t num_bytes_required, + std::vector* objects_to_evict) { + int64_t bytes_evicted = 0; + auto it = item_list_.end(); + while (bytes_evicted < num_bytes_required && it != item_list_.begin()) { + it--; + objects_to_evict->push_back(it->first); + bytes_evicted += it->second; + bytes_evicted_total_ += it->second; + num_evictions_total_ += 1; + } + return bytes_evicted; +} + +EvictionPolicy::EvictionPolicy(PlasmaStoreInfo* store_info, int64_t max_size) + : pinned_memory_bytes_(0), store_info_(store_info), cache_("global lru", max_size) {} + +int64_t EvictionPolicy::ChooseObjectsToEvict(int64_t num_bytes_required, + std::vector* objects_to_evict) { + int64_t bytes_evicted = + cache_.ChooseObjectsToEvict(num_bytes_required, objects_to_evict); + // Update the LRU cache. + for (auto& object_id : *objects_to_evict) { + cache_.Remove(object_id); + } + return bytes_evicted; +} + +void EvictionPolicy::ObjectCreated(const ObjectID& object_id, Client* client, + bool is_create) { + cache_.Add(object_id, GetObjectSize(object_id)); +} + +bool EvictionPolicy::SetClientQuota(Client* client, int64_t output_memory_quota) { + return false; +} + +bool EvictionPolicy::EnforcePerClientQuota(Client* client, int64_t size, bool is_create, + std::vector* objects_to_evict) { + return true; +} + +void EvictionPolicy::ClientDisconnected(Client* client) {} + +bool EvictionPolicy::RequireSpace(int64_t size, std::vector* objects_to_evict) { + // Check if there is enough space to create the object. + int64_t required_space = + PlasmaAllocator::Allocated() + size - PlasmaAllocator::GetFootprintLimit(); + // Try to free up at least as much space as we need right now but ideally + // up to 20% of the total capacity. + int64_t space_to_free = + std::max(required_space, PlasmaAllocator::GetFootprintLimit() / 5); + ARROW_LOG(DEBUG) << "not enough space to create this object, so evicting objects"; + // Choose some objects to evict, and update the return pointers. + int64_t num_bytes_evicted = ChooseObjectsToEvict(space_to_free, objects_to_evict); + ARROW_LOG(INFO) << "There is not enough space to create this object, so evicting " + << objects_to_evict->size() << " objects to free up " + << num_bytes_evicted << " bytes. The number of bytes in use (before " + << "this eviction) is " << PlasmaAllocator::Allocated() << "."; + return num_bytes_evicted >= required_space && num_bytes_evicted > 0; +} + +void EvictionPolicy::BeginObjectAccess(const ObjectID& object_id) { + // If the object is in the LRU cache, remove it. + cache_.Remove(object_id); + pinned_memory_bytes_ += GetObjectSize(object_id); +} + +void EvictionPolicy::EndObjectAccess(const ObjectID& object_id) { + auto size = GetObjectSize(object_id); + // Add the object to the LRU cache. + cache_.Add(object_id, size); + pinned_memory_bytes_ -= size; +} + +void EvictionPolicy::RemoveObject(const ObjectID& object_id) { + // If the object is in the LRU cache, remove it. + cache_.Remove(object_id); +} + +void EvictionPolicy::RefreshObjects(const std::vector& object_ids) { + for (const auto& object_id : object_ids) { + int64_t size = cache_.Remove(object_id); + if (size != -1) { + cache_.Add(object_id, size); + } + } +} + +int64_t EvictionPolicy::GetObjectSize(const ObjectID& object_id) const { + auto entry = store_info_->objects[object_id].get(); + return entry->data_size + entry->metadata_size; +} + +std::string EvictionPolicy::DebugString() const { return cache_.DebugString(); } + +} // namespace plasma diff --git a/src/ray/plasma/eviction_policy.h b/src/ray/plasma/eviction_policy.h new file mode 100644 index 000000000..b2496d9aa --- /dev/null +++ b/src/ray/plasma/eviction_policy.h @@ -0,0 +1,212 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_EVICTION_POLICY_H +#define PLASMA_EVICTION_POLICY_H + +#include +#include +#include +#include +#include +#include + +#include "plasma/common.h" +#include "plasma/plasma.h" + +namespace plasma { + +// ==== The eviction policy ==== +// +// This file contains declaration for all functions and data structures that +// need to be provided if you want to implement a new eviction algorithm for the +// Plasma store. +// +// It does not implement memory quotas; see quota_aware_policy for that. + +class LRUCache { + public: + LRUCache(const std::string& name, int64_t size) + : name_(name), + original_capacity_(size), + capacity_(size), + used_capacity_(0), + num_evictions_total_(0), + bytes_evicted_total_(0) {} + + void Add(const ObjectID& key, int64_t size); + + int64_t Remove(const ObjectID& key); + + int64_t ChooseObjectsToEvict(int64_t num_bytes_required, + std::vector* objects_to_evict); + + int64_t OriginalCapacity() const; + + int64_t Capacity() const; + + int64_t RemainingCapacity() const; + + void AdjustCapacity(int64_t delta); + + void Foreach(std::function); + + std::string DebugString() const; + + private: + /// A doubly-linked list containing the items in the cache and + /// their sizes in LRU order. + typedef std::list> ItemList; + ItemList item_list_; + /// A hash table mapping the object ID of an object in the cache to its + /// location in the doubly linked list item_list_. + std::unordered_map item_map_; + + /// The name of this cache, used for debugging purposes only. + const std::string name_; + /// The original (max) capacity of this cache in bytes. + const int64_t original_capacity_; + /// The current capacity, which must be <= the original capacity. + int64_t capacity_; + /// The number of bytes used of the available capacity. + int64_t used_capacity_; + /// The number of objects evicted from this cache. + int64_t num_evictions_total_; + /// The number of bytes evicted from this cache. + int64_t bytes_evicted_total_; +}; + +/// The eviction policy. +class EvictionPolicy { + public: + /// Construct an eviction policy. + /// + /// \param store_info Information about the Plasma store that is exposed + /// to the eviction policy. + /// \param max_size Max size in bytes total of objects to store. + explicit EvictionPolicy(PlasmaStoreInfo* store_info, int64_t max_size); + + /// Destroy an eviction policy. + virtual ~EvictionPolicy() {} + + /// This method will be called whenever an object is first created in order to + /// add it to the LRU cache. This is done so that the first time, the Plasma + /// store calls begin_object_access, we can remove the object from the LRU + /// cache. + /// + /// \param object_id The object ID of the object that was created. + /// \param client The pointer to the client. + /// \param is_create Whether we are creating a new object (vs reading an object). + virtual void ObjectCreated(const ObjectID& object_id, Client* client, bool is_create); + + /// Set quota for a client. + /// + /// \param client The pointer to the client. + /// \param output_memory_quota Set the quota for this client. This can only be + /// called once per client. This is effectively the equivalent of giving + /// the client its own LRU cache instance. The memory for this is taken + /// out of the capacity of the global LRU cache for the client lifetime. + /// + /// \return True if enough space can be reserved for the given client quota. + virtual bool SetClientQuota(Client* client, int64_t output_memory_quota); + + /// Determine what objects need to be evicted to enforce the given client's quota. + /// + /// \param client The pointer to the client creating the object. + /// \param size The size of the object to create. + /// \param is_create Whether we are creating a new object (vs reading an object). + /// \param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// + /// \return True if enough space could be freed and false otherwise. + virtual bool EnforcePerClientQuota(Client* client, int64_t size, bool is_create, + std::vector* objects_to_evict); + + /// Called to clean up any resources allocated by this client. This merges any + /// per-client LRU queue created by SetClientQuota into the global LRU queue. + /// + /// \param client The pointer to the client. + virtual void ClientDisconnected(Client* client); + + /// This method will be called when the Plasma store needs more space, perhaps + /// to create a new object. When this method is called, the eviction + /// policy will assume that the objects chosen to be evicted will in fact be + /// evicted from the Plasma store by the caller. + /// + /// \param size The size in bytes of the new object, including both data and + /// metadata. + /// \param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// \return True if enough space can be freed and false otherwise. + virtual bool RequireSpace(int64_t size, std::vector* objects_to_evict); + + /// This method will be called whenever an unused object in the Plasma store + /// starts to be used. When this method is called, the eviction policy will + /// assume that the objects chosen to be evicted will in fact be evicted from + /// the Plasma store by the caller. + /// + /// \param object_id The ID of the object that is now being used. + virtual void BeginObjectAccess(const ObjectID& object_id); + + /// This method will be called whenever an object in the Plasma store that was + /// being used is no longer being used. When this method is called, the + /// eviction policy will assume that the objects chosen to be evicted will in + /// fact be evicted from the Plasma store by the caller. + /// + /// \param object_id The ID of the object that is no longer being used. + virtual void EndObjectAccess(const ObjectID& object_id); + + /// Choose some objects to evict from the Plasma store. When this method is + /// called, the eviction policy will assume that the objects chosen to be + /// evicted will in fact be evicted from the Plasma store by the caller. + /// + /// @note This method is not part of the API. It is exposed in the header file + /// only for testing. + /// + /// \param num_bytes_required The number of bytes of space to try to free up. + /// \param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// \return The total number of bytes of space chosen to be evicted. + virtual int64_t ChooseObjectsToEvict(int64_t num_bytes_required, + std::vector* objects_to_evict); + + /// This method will be called when an object is going to be removed + /// + /// \param object_id The ID of the object that is now being used. + virtual void RemoveObject(const ObjectID& object_id); + + virtual void RefreshObjects(const std::vector& object_ids); + + /// Returns debugging information for this eviction policy. + virtual std::string DebugString() const; + + protected: + /// Returns the size of the object + int64_t GetObjectSize(const ObjectID& object_id) const; + + /// The number of bytes pinned by applications. + int64_t pinned_memory_bytes_; + + /// Pointer to the plasma store info. + PlasmaStoreInfo* store_info_; + /// Datastructure for the LRU cache. + LRUCache cache_; +}; + +} // namespace plasma + +#endif // PLASMA_EVICTION_POLICY_H diff --git a/src/ray/plasma/external_store.cc b/src/ray/plasma/external_store.cc new file mode 100644 index 000000000..8cfbad179 --- /dev/null +++ b/src/ray/plasma/external_store.cc @@ -0,0 +1,63 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include + +#include "arrow/util/memory.h" + +#include "plasma/external_store.h" + +namespace plasma { + +Status ExternalStores::ExtractStoreName(const std::string& endpoint, + std::string* store_name) { + size_t off = endpoint.find_first_of(':'); + if (off == std::string::npos) { + return Status::Invalid("Malformed endpoint " + endpoint); + } + *store_name = endpoint.substr(0, off); + return Status::OK(); +} + +void ExternalStores::RegisterStore(const std::string& store_name, + std::shared_ptr store) { + Stores().insert({store_name, store}); +} + +void ExternalStores::DeregisterStore(const std::string& store_name) { + auto it = Stores().find(store_name); + if (it == Stores().end()) { + return; + } + Stores().erase(it); +} + +std::shared_ptr ExternalStores::GetStore(const std::string& store_name) { + auto it = Stores().find(store_name); + if (it == Stores().end()) { + return nullptr; + } + return it->second; +} + +ExternalStores::StoreMap& ExternalStores::Stores() { + static auto* external_stores = new StoreMap(); + return *external_stores; +} + +} // namespace plasma diff --git a/src/ray/plasma/external_store.h b/src/ray/plasma/external_store.h new file mode 100644 index 000000000..feca46658 --- /dev/null +++ b/src/ray/plasma/external_store.h @@ -0,0 +1,123 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef EXTERNAL_STORE_H +#define EXTERNAL_STORE_H + +#include +#include +#include +#include + +#include "plasma/client.h" + +namespace plasma { + +// ==== The external store ==== +// +// This file contains declaration for all functions that need to be implemented +// for an external storage service so that objects evicted from Plasma store +// can be written to it. + +class ExternalStore { + public: + /// Default constructor. + ExternalStore() = default; + + /// Virtual destructor. + virtual ~ExternalStore() = default; + + /// Connect to the local plasma store. Return the resulting connection. + /// + /// \param endpoint The name of the endpoint to connect to the external + /// storage service. While the formatting of the endpoint name is + /// specific to the implementation of the external store, it always + /// starts with {store-name}://, where {store-name} is the name of the + /// external store. + /// + /// \return The return status. + virtual Status Connect(const std::string& endpoint) = 0; + + /// This method will be called whenever an object in the Plasma store needs + /// to be evicted to the external store. + /// + /// This API is experimental and might change in the future. + /// + /// \param ids The IDs of the objects to put. + /// \param data The object data to put. + /// \return The return status. + virtual Status Put(const std::vector& ids, + const std::vector>& data) = 0; + + /// This method will be called whenever an evicted object in the external + /// store store needs to be accessed. + /// + /// This API is experimental and might change in the future. + /// + /// \param ids The IDs of the objects to get. + /// \param buffers List of buffers the data should be written to. + /// \return The return status. + virtual Status Get(const std::vector& ids, + std::vector> buffers) = 0; +}; + +class ExternalStores { + public: + typedef std::unordered_map> StoreMap; + /// Extracts the external store name from the external store endpoint. + /// + /// \param endpoint The endpoint for the external store. + /// \param[out] store_name The name of the external store. + /// \return The return status. + static Status ExtractStoreName(const std::string& endpoint, std::string* store_name); + + /// Register a new external store. + /// + /// \param store_name Name of the new external store. + /// \param store The new external store object. + static void RegisterStore(const std::string& store_name, + std::shared_ptr store); + + /// Remove an external store from the registry. + /// + /// \param store_name Name of the external store to remove. + static void DeregisterStore(const std::string& store_name); + + /// Obtain the external store given its name. + /// + /// \param store_name Name of the external store. + /// \return The external store object. + static std::shared_ptr GetStore(const std::string& store_name); + + private: + /// Obtain mapping between external store names and store instances. + /// + /// \return Mapping between external store names and store instances. + static StoreMap& Stores(); +}; + +#define REGISTER_EXTERNAL_STORE(name, store) \ + class store##Class { \ + public: \ + store##Class() { ExternalStores::RegisterStore(name, std::make_shared()); } \ + ~store##Class() { ExternalStores::DeregisterStore(name); } \ + }; \ + store##Class singleton_##store = store##Class() + +} // namespace plasma + +#endif // EXTERNAL_STORE_H diff --git a/src/ray/plasma/fling.cc b/src/ray/plasma/fling.cc new file mode 100644 index 000000000..fa16d357d --- /dev/null +++ b/src/ray/plasma/fling.cc @@ -0,0 +1,164 @@ +// Copyright 2013 Sharvil Nanavati +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "plasma/fling.h" + +#include + +#include "arrow/util/logging.h" + +#ifdef _WIN32 +#include // socklen_t +#else +typedef int SOCKET; +#endif + +void init_msg(struct msghdr* msg, struct iovec* iov, char* buf, size_t buf_len) { + iov->iov_base = buf; + iov->iov_len = 1; + + msg->msg_flags = 0; + msg->msg_iov = iov; + msg->msg_iovlen = 1; + msg->msg_control = buf; + msg->msg_controllen = static_cast(buf_len); + msg->msg_name = NULL; + msg->msg_namelen = 0; +} + +int send_fd(int conn, int fd) { + struct msghdr msg; + struct iovec iov; +#ifdef _WIN32 + SOCKET to_send = fh_get(fd); +#else + SOCKET to_send = fd; +#endif + char buf[CMSG_SPACE(sizeof(to_send))]; + memset(&buf, 0, sizeof(buf)); + + init_msg(&msg, &iov, buf, sizeof(buf)); + + struct cmsghdr* header = CMSG_FIRSTHDR(&msg); + if (header == nullptr) { + return -1; + } + header->cmsg_level = SOL_SOCKET; + header->cmsg_type = SCM_RIGHTS; + header->cmsg_len = CMSG_LEN(sizeof(to_send)); + memcpy(CMSG_DATA(header), reinterpret_cast(&to_send), sizeof(to_send)); + +#ifdef _WIN32 + SOCKET sock = fh_get(conn); +#else + SOCKET sock = conn; +#endif + // Send file descriptor. + while (true) { + ssize_t r = sendmsg(sock, &msg, 0); + if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } else if (errno == EMSGSIZE) { + ARROW_LOG(WARNING) << "Failed to send file descriptor" + << " (errno = EMSGSIZE), retrying."; + // If we failed to send the file descriptor, loop until we have sent it + // successfully. TODO(rkn): This is problematic for two reasons. First + // of all, sending the file descriptor should just succeed without any + // errors, but sometimes I see a "Message too long" error number. + // Second, looping like this allows a client to potentially block the + // plasma store event loop which should never happen. + continue; + } else { + ARROW_LOG(INFO) << "Error in send_fd (errno = " << errno << ")"; + return static_cast(r); + } + } else if (r == 0) { + ARROW_LOG(INFO) << "Encountered unexpected EOF"; + return 0; + } else { + ARROW_CHECK(r > 0); + return static_cast(r); + } + } +} + +int recv_fd(int conn) { + struct msghdr msg; + struct iovec iov; + char buf[CMSG_SPACE(sizeof(SOCKET))]; + init_msg(&msg, &iov, buf, sizeof(buf)); + +#ifdef _WIN32 + SOCKET sock = fh_get(conn); +#else + int sock = conn; +#endif + while (true) { + ssize_t r = recvmsg(sock, &msg, 0); + if (r == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } else { + ARROW_LOG(INFO) << "Error in recv_fd (errno = " << errno << ")"; + return -1; + } + } else { + break; + } + } + + SOCKET found_fd = -1; + int oh_noes = 0; + for (struct cmsghdr* header = CMSG_FIRSTHDR(&msg); header != NULL; + header = CMSG_NXTHDR(&msg, header)) + if (header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS) { + ssize_t count = (header->cmsg_len - + (CMSG_DATA(header) - reinterpret_cast(header))) / + sizeof(SOCKET); + for (int i = 0; i < count; ++i) { + SOCKET fd = (reinterpret_cast(CMSG_DATA(header)))[i]; + if (found_fd == -1) { + found_fd = fd; + } else { +#ifdef _WIN32 + closesocket(fd) == 0 || ((WSAGetLastError() == WSAENOTSOCK || WSAGetLastError() == WSANOTINITIALISED) && CloseHandle(reinterpret_cast(fd))); +#else + close(fd); +#endif + oh_noes = 1; + } + } + } + + // The sender sent us more than one file descriptor. We've closed + // them all to prevent fd leaks but notify the caller that we got + // a bad message. + if (oh_noes) { +#ifdef _WIN32 + closesocket(found_fd) == 0 || ((WSAGetLastError() == WSAENOTSOCK || WSAGetLastError() == WSANOTINITIALISED) && CloseHandle(reinterpret_cast(found_fd))); +#else + close(found_fd); +#endif + errno = EBADMSG; + return -1; + } + +#ifdef _WIN32 + int to_receive = fh_open(found_fd, -1); +#else + int to_receive = found_fd; +#endif + return to_receive; +} diff --git a/src/ray/plasma/fling.h b/src/ray/plasma/fling.h new file mode 100644 index 000000000..d1582c3c8 --- /dev/null +++ b/src/ray/plasma/fling.h @@ -0,0 +1,52 @@ +// Copyright 2013 Sharvil Nanavati +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// FLING: Exchanging file descriptors over sockets +// +// This is a little library for sending file descriptors over a socket +// between processes. The reason for doing that (as opposed to using +// filenames to share the files) is so (a) no files remain in the +// filesystem after all the processes terminate, (b) to make sure that +// there are no name collisions and (c) to be able to control who has +// access to the data. +// +// Most of the code is from https://github.com/sharvil/flingfd + +#include +#include +#include +#include +#include + +// This is necessary for Mac OS X, see http://www.apuebook.com/faqs2e.html +// (10). +#if !defined(CMSG_SPACE) && !defined(CMSG_LEN) +#define CMSG_SPACE(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + __DARWIN_ALIGN32(len)) +#define CMSG_LEN(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + (len)) +#endif + +void init_msg(struct msghdr* msg, struct iovec* iov, char* buf, size_t buf_len); + +// Send a file descriptor over a unix domain socket. +// +// \param conn Unix domain socket to send the file descriptor over. +// \param fd File descriptor to send over. +// \return Status code which is < 0 on failure. +int send_fd(int conn, int fd); + +// Receive a file descriptor over a unix domain socket. +// +// \param conn Unix domain socket to receive the file descriptor from. +// \return File descriptor or a value < 0 on failure. +int recv_fd(int conn); diff --git a/src/ray/plasma/hash_table_store.cc b/src/ray/plasma/hash_table_store.cc new file mode 100644 index 000000000..b77d3693f --- /dev/null +++ b/src/ray/plasma/hash_table_store.cc @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include + +#include "arrow/util/logging.h" + +#include "plasma/hash_table_store.h" + +namespace plasma { + +Status HashTableStore::Connect(const std::string& endpoint) { return Status::OK(); } + +Status HashTableStore::Put(const std::vector& ids, + const std::vector>& data) { + for (size_t i = 0; i < ids.size(); ++i) { + table_[ids[i]] = data[i]->ToString(); + } + return Status::OK(); +} + +Status HashTableStore::Get(const std::vector& ids, + std::vector> buffers) { + ARROW_CHECK(ids.size() == buffers.size()); + for (size_t i = 0; i < ids.size(); ++i) { + bool valid; + HashTable::iterator result; + { + result = table_.find(ids[i]); + valid = result != table_.end(); + } + if (valid) { + ARROW_CHECK(buffers[i]->size() == static_cast(result->second.size())); + std::memcpy(buffers[i]->mutable_data(), result->second.data(), + result->second.size()); + } + } + return Status::OK(); +} + +REGISTER_EXTERNAL_STORE("hashtable", HashTableStore); + +} // namespace plasma diff --git a/src/ray/plasma/hash_table_store.h b/src/ray/plasma/hash_table_store.h new file mode 100644 index 000000000..766088bd4 --- /dev/null +++ b/src/ray/plasma/hash_table_store.h @@ -0,0 +1,53 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef HASH_TABLE_STORE_H +#define HASH_TABLE_STORE_H + +#include +#include +#include +#include + +#include "plasma/external_store.h" + +namespace plasma { + +// This is a sample implementation for an external store, for illustration +// purposes only. + +class HashTableStore : public ExternalStore { + public: + HashTableStore() = default; + + Status Connect(const std::string& endpoint) override; + + Status Get(const std::vector& ids, + std::vector> buffers) override; + + Status Put(const std::vector& ids, + const std::vector>& data) override; + + private: + typedef std::unordered_map HashTable; + + HashTable table_; +}; + +} // namespace plasma + +#endif // HASH_TABLE_STORE_H diff --git a/src/ray/plasma/io.cc b/src/ray/plasma/io.cc new file mode 100644 index 000000000..1676596ea --- /dev/null +++ b/src/ray/plasma/io.cc @@ -0,0 +1,257 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/io.h" + +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/util/logging.h" + +#include "plasma/common.h" +#include "plasma/plasma_generated.h" +#ifndef _WIN32 +#include +#include +#endif + +using arrow::Status; + +/// Number of times we try connecting to a socket. +constexpr int64_t kNumConnectAttempts = 80; +/// Time to wait between connection attempts to a socket. +constexpr int64_t kConnectTimeoutMs = 100; + +namespace plasma { + +using flatbuf::MessageType; + +Status WriteBytes(int fd, uint8_t* cursor, size_t length) { + ssize_t nbytes = 0; + size_t bytesleft = length; + size_t offset = 0; + while (bytesleft > 0) { + // While we haven't written the whole message, write to the file descriptor, + // advance the cursor, and decrease the amount left to write. + nbytes = write(fd, cursor + offset, bytesleft); + if (nbytes < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } + return Status::IOError(strerror(errno)); + } else if (nbytes == 0) { + return Status::IOError("Encountered unexpected EOF"); + } + ARROW_CHECK(nbytes > 0); + bytesleft -= nbytes; + offset += nbytes; + } + + return Status::OK(); +} + +Status WriteMessage(int fd, MessageType type, int64_t length, uint8_t* bytes) { + int64_t version = kPlasmaProtocolVersion; + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&version), sizeof(version))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&type), sizeof(type))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&length), sizeof(length))); + return WriteBytes(fd, bytes, length * sizeof(char)); +} + +Status ReadBytes(int fd, uint8_t* cursor, size_t length) { + ssize_t nbytes = 0; + // Termination condition: EOF or read 'length' bytes total. + size_t bytesleft = length; + size_t offset = 0; + while (bytesleft > 0) { + nbytes = read(fd, cursor + offset, bytesleft); + if (nbytes < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } + return Status::IOError(strerror(errno)); + } else if (0 == nbytes) { + return Status::IOError("Encountered unexpected EOF"); + } + ARROW_CHECK(nbytes > 0); + bytesleft -= nbytes; + offset += nbytes; + } + + return Status::OK(); +} + +Status ReadMessage(int fd, MessageType* type, std::vector* buffer) { + int64_t version; + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), + *type = MessageType::PlasmaDisconnectClient); + ARROW_CHECK(version == kPlasmaProtocolVersion) << "version = " << version; + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(type), sizeof(*type)), + *type = MessageType::PlasmaDisconnectClient); + int64_t length_temp; + RETURN_NOT_OK_ELSE( + ReadBytes(fd, reinterpret_cast(&length_temp), sizeof(length_temp)), + *type = MessageType::PlasmaDisconnectClient); + // The length must be read as an int64_t, but it should be used as a size_t. + size_t length = static_cast(length_temp); + if (length > buffer->size()) { + buffer->resize(length); + } + RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer->data(), length), + *type = MessageType::PlasmaDisconnectClient); + return Status::OK(); +} + +int ConnectOrListenIpcSock(const std::string& pathname, bool shall_listen) { + union { + struct sockaddr addr; + struct sockaddr_un un; + struct sockaddr_in in; + } socket_address; + int addrlen; + memset(&socket_address, 0, sizeof(socket_address)); + if (pathname.find("tcp://") == 0) { + addrlen = sizeof(socket_address.in); + socket_address.in.sin_family = AF_INET; + std::string addr = pathname.substr(pathname.find('/') + 2); + size_t i = addr.rfind(':'), j; + if (i >= addr.size()) { + j = i = addr.size(); + } else { + j = i + 1; + } + socket_address.in.sin_addr.s_addr = inet_addr(addr.substr(0, i).c_str()); + socket_address.in.sin_port = htons(static_cast(atoi(addr.substr(j).c_str()))); + if (socket_address.in.sin_addr.s_addr == INADDR_NONE) { + ARROW_LOG(ERROR) << "Socket address is not a valid IPv4 address: " << pathname; + return -1; + } + if (socket_address.in.sin_port == htons(0)) { + ARROW_LOG(ERROR) << "Socket address is missing a valid port: " << pathname; + return -1; + } + } else { + addrlen = sizeof(socket_address.un); + socket_address.un.sun_family = AF_UNIX; + if (pathname.size() + 1 > sizeof(socket_address.un.sun_path)) { + ARROW_LOG(ERROR) << "Socket pathname is too long."; + return -1; + } + strncpy(socket_address.un.sun_path, pathname.c_str(), pathname.size() + 1); + } + + int socket_fd = socket(socket_address.addr.sa_family, SOCK_STREAM, 0); + if (socket_fd < 0) { + ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; + return -1; + } + if (shall_listen) { + // Tell the system to allow the port to be reused. + int on = 1; + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), + sizeof(on)) < 0) { + ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; + close(socket_fd); + return -1; + } + + if (socket_address.addr.sa_family == AF_UNIX) { +#ifdef _WIN32 + _unlink(pathname.c_str()); +#else + unlink(pathname.c_str()); +#endif + } + if (bind(socket_fd, &socket_address.addr, addrlen) != 0) { + ARROW_LOG(ERROR) << "Bind failed for pathname " << pathname; + close(socket_fd); + return -1; + } + + if (listen(socket_fd, 128) == -1) { + ARROW_LOG(ERROR) << "Could not listen to socket " << pathname; + close(socket_fd); + return -1; + } + } else { + if (connect(socket_fd, &socket_address.addr, addrlen) != 0) { + close(socket_fd); + return -1; + } + } + return socket_fd; +} + +Status ConnectIpcSocketRetry(const std::string& pathname, int num_retries, + int64_t timeout, int* fd) { + // Pick the default values if the user did not specify. + if (num_retries < 0) { + num_retries = kNumConnectAttempts; + } + if (timeout < 0) { + timeout = kConnectTimeoutMs; + } + *fd = ConnectOrListenIpcSock(pathname, false); + while (*fd < 0 && num_retries > 0) { + ARROW_LOG(ERROR) << "Connection to IPC socket failed for pathname " << pathname + << ", retrying " << num_retries << " more times"; + // Sleep for timeout milliseconds. + usleep(static_cast(timeout * 1000)); + *fd = ConnectOrListenIpcSock(pathname, false); + --num_retries; + } + + // If we could not connect to the socket, exit. + if (*fd == -1) { + return Status::IOError("Could not connect to socket ", pathname); + } + + return Status::OK(); +} + +int AcceptClient(int socket_fd) { + int client_fd = accept(socket_fd, NULL, NULL); + if (client_fd < 0) { + ARROW_LOG(ERROR) << "Error reading from socket."; + return -1; + } + return client_fd; +} + +std::unique_ptr ReadMessageAsync(int sock) { + int64_t size; + Status s = ReadBytes(sock, reinterpret_cast(&size), sizeof(int64_t)); + if (!s.ok()) { + // The other side has closed the socket. + ARROW_LOG(DEBUG) << "Socket has been closed, or some other error has occurred."; + close(sock); + return NULL; + } + auto message = std::unique_ptr(new uint8_t[size]); + s = ReadBytes(sock, message.get(), size); + if (!s.ok()) { + // The other side has closed the socket. + ARROW_LOG(DEBUG) << "Socket has been closed, or some other error has occurred."; + close(sock); + return NULL; + } + return message; +} + +} // namespace plasma diff --git a/src/ray/plasma/io.h b/src/ray/plasma/io.h new file mode 100644 index 000000000..4e480982c --- /dev/null +++ b/src/ray/plasma/io.h @@ -0,0 +1,69 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_IO_H +#define PLASMA_IO_H + +#include +#include +#include +#include + +#include +#include +#include + +#include "arrow/status.h" +#include "plasma/common.h" +#include "plasma/compat.h" + +namespace plasma { + +namespace flatbuf { + +// Forward declaration outside the namespace, which is defined in plasma_generated.h. +enum class MessageType : int64_t; + +} // namespace flatbuf + +// TODO(pcm): Replace our own custom message header (message type, +// message length, plasma protocol version) with one that is serialized +// using flatbuffers. +constexpr int64_t kPlasmaProtocolVersion = 0x0000000000000000; + +using arrow::Status; + +Status WriteBytes(int fd, uint8_t* cursor, size_t length); + +Status WriteMessage(int fd, flatbuf::MessageType type, int64_t length, uint8_t* bytes); + +Status ReadBytes(int fd, uint8_t* cursor, size_t length); + +Status ReadMessage(int fd, flatbuf::MessageType* type, std::vector* buffer); + +int ConnectOrListenIpcSock(const std::string& pathname, bool shall_listen); + +Status ConnectIpcSocketRetry(const std::string& pathname, int num_retries, + int64_t timeout, int* fd); + +int AcceptClient(int socket_fd); + +std::unique_ptr ReadMessageAsync(int sock); + +} // namespace plasma + +#endif // PLASMA_IO_H diff --git a/src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.cc b/src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.cc new file mode 100644 index 000000000..0964df46f --- /dev/null +++ b/src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.cc @@ -0,0 +1,243 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "arrow/util/logging.h" + +#include "plasma/client.h" + +constexpr jsize OBJECT_ID_SIZE = sizeof(plasma::ObjectID) / sizeof(jbyte); + +inline void jbyteArray_to_object_id(JNIEnv* env, jbyteArray a, plasma::ObjectID* oid) { + env->GetByteArrayRegion(a, 0, OBJECT_ID_SIZE, reinterpret_cast(oid)); +} + +inline void object_id_to_jbyteArray(JNIEnv* env, jbyteArray a, plasma::ObjectID* oid) { + env->SetByteArrayRegion(a, 0, OBJECT_ID_SIZE, reinterpret_cast(oid)); +} + +inline void throw_exception_if_not_OK(JNIEnv* env, const arrow::Status& status) { + if (!status.ok()) { + jclass Exception = + env->FindClass("org/apache/arrow/plasma/exceptions/PlasmaClientException"); + env->ThrowNew(Exception, status.message().c_str()); + } +} + +class JByteArrayGetter { + private: + JNIEnv* _env; + jbyteArray _a; + jbyte* bp; + + public: + JByteArrayGetter(JNIEnv* env, jbyteArray a, jbyte** out) { + _env = env; + _a = a; + + bp = _env->GetByteArrayElements(_a, nullptr); + *out = bp; + } + + ~JByteArrayGetter() { _env->ReleaseByteArrayElements(_a, bp, 0); } +}; + +JNIEXPORT jlong JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_connect( + JNIEnv* env, jclass cls, jstring store_socket_name, jstring manager_socket_name, + jint release_delay) { + const char* s_name = env->GetStringUTFChars(store_socket_name, nullptr); + const char* m_name = env->GetStringUTFChars(manager_socket_name, nullptr); + + plasma::PlasmaClient* client = new plasma::PlasmaClient(); + throw_exception_if_not_OK(env, client->Connect(s_name, m_name, release_delay)); + + env->ReleaseStringUTFChars(store_socket_name, s_name); + env->ReleaseStringUTFChars(manager_socket_name, m_name); + return reinterpret_cast(client); +} + +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_disconnect( + JNIEnv* env, jclass cls, jlong conn) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + + throw_exception_if_not_OK(env, client->Disconnect()); + delete client; + return; +} + +JNIEXPORT jobject JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_create( + JNIEnv* env, jclass cls, jlong conn, jbyteArray object_id, jint size, + jbyteArray metadata) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + plasma::ObjectID oid; + jbyteArray_to_object_id(env, object_id, &oid); + + // prepare metadata buffer + uint8_t* md = nullptr; + jsize md_size = 0; + std::unique_ptr md_getter; + if (metadata != nullptr) { + md_size = env->GetArrayLength(metadata); + } + if (md_size > 0) { + md_getter.reset(new JByteArrayGetter(env, metadata, reinterpret_cast(&md))); + } + + std::shared_ptr data; + Status s = client->Create(oid, size, md, md_size, &data); + if (plasma::IsPlasmaObjectExists(s)) { + jclass exceptionClass = + env->FindClass("org/apache/arrow/plasma/exceptions/DuplicateObjectException"); + env->ThrowNew(exceptionClass, oid.hex().c_str()); + return nullptr; + } + if (plasma::IsPlasmaStoreFull(s)) { + jclass exceptionClass = + env->FindClass("org/apache/arrow/plasma/exceptions/PlasmaOutOfMemoryException"); + env->ThrowNew(exceptionClass, ""); + return nullptr; + } + throw_exception_if_not_OK(env, s); + + return env->NewDirectByteBuffer(data->mutable_data(), size); +} + +JNIEXPORT jbyteArray JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_hash( + JNIEnv* env, jclass cls, jlong conn, jbyteArray object_id) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + plasma::ObjectID oid; + jbyteArray_to_object_id(env, object_id, &oid); + + unsigned char digest[plasma::kDigestSize]; + bool success = client->Hash(oid, digest).ok(); + + if (success) { + jbyteArray ret = env->NewByteArray(plasma::kDigestSize); + env->SetByteArrayRegion(ret, 0, plasma::kDigestSize, + reinterpret_cast(digest)); + return ret; + } else { + return nullptr; + } +} + +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_seal( + JNIEnv* env, jclass cls, jlong conn, jbyteArray object_id) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + plasma::ObjectID oid; + jbyteArray_to_object_id(env, object_id, &oid); + + throw_exception_if_not_OK(env, client->Seal(oid)); +} + +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_release( + JNIEnv* env, jclass cls, jlong conn, jbyteArray object_id) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + plasma::ObjectID oid; + jbyteArray_to_object_id(env, object_id, &oid); + + throw_exception_if_not_OK(env, client->Release(oid)); +} + +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_delete( + JNIEnv* env, jclass cls, jlong conn, jbyteArray object_id) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + plasma::ObjectID oid; + jbyteArray_to_object_id(env, object_id, &oid); + + throw_exception_if_not_OK(env, client->Delete(oid)); +} + +JNIEXPORT jobjectArray JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_get( + JNIEnv* env, jclass cls, jlong conn, jobjectArray object_ids, jint timeout_ms) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + + jsize num_oids = env->GetArrayLength(object_ids); + std::vector oids(num_oids); + std::vector obufs(num_oids); + for (int i = 0; i < num_oids; ++i) { + jbyteArray_to_object_id( + env, reinterpret_cast(env->GetObjectArrayElement(object_ids, i)), + &oids[i]); + } + // TODO: may be blocked. consider to add the thread support + throw_exception_if_not_OK(env, + client->Get(oids.data(), num_oids, timeout_ms, obufs.data())); + + jclass clsByteBuffer = env->FindClass("java/nio/ByteBuffer"); + jclass clsByteBufferArray = env->FindClass("[Ljava/nio/ByteBuffer;"); + + jobjectArray ret = env->NewObjectArray(num_oids, clsByteBufferArray, nullptr); + jobjectArray o = nullptr; + jobject dataBuf, metadataBuf; + for (int i = 0; i < num_oids; ++i) { + o = env->NewObjectArray(2, clsByteBuffer, nullptr); + if (obufs[i].data && obufs[i].data->size() != -1) { + dataBuf = env->NewDirectByteBuffer(const_cast(obufs[i].data->data()), + obufs[i].data->size()); + if (obufs[i].metadata && obufs[i].metadata->size() > 0) { + metadataBuf = env->NewDirectByteBuffer( + const_cast(obufs[i].metadata->data()), obufs[i].metadata->size()); + } else { + metadataBuf = nullptr; + } + } else { + dataBuf = nullptr; + metadataBuf = nullptr; + } + + env->SetObjectArrayElement(o, 0, dataBuf); + env->SetObjectArrayElement(o, 1, metadataBuf); + env->SetObjectArrayElement(ret, i, o); + } + return ret; +} + +JNIEXPORT jboolean JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_contains( + JNIEnv* env, jclass cls, jlong conn, jbyteArray object_id) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + plasma::ObjectID oid; + jbyteArray_to_object_id(env, object_id, &oid); + + bool has_object; + throw_exception_if_not_OK(env, client->Contains(oid, &has_object)); + + return has_object; +} + +JNIEXPORT jlong JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_evict( + JNIEnv* env, jclass cls, jlong conn, jlong num_bytes) { + plasma::PlasmaClient* client = reinterpret_cast(conn); + + int64_t evicted_bytes; + throw_exception_if_not_OK( + env, client->Evict(static_cast(num_bytes), evicted_bytes)); + + return static_cast(evicted_bytes); +} diff --git a/src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.h b/src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.h new file mode 100644 index 000000000..8729c71e4 --- /dev/null +++ b/src/ray/plasma/lib/java/org_apache_arrow_plasma_PlasmaClientJNI.h @@ -0,0 +1,132 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include "jni.h" +/* Header for class org_apache_arrow_plasma_PlasmaClientJNI */ + +#ifndef _Included_org_apache_arrow_plasma_PlasmaClientJNI +#define _Included_org_apache_arrow_plasma_PlasmaClientJNI +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: connect + * Signature: (Ljava/lang/String;Ljava/lang/String;I)J + */ +JNIEXPORT jlong JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_connect( + JNIEnv*, jclass, jstring, jstring, jint); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: disconnect + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_disconnect(JNIEnv*, + jclass, + jlong); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: create + * Signature: (J[BI[B)Ljava/nio/ByteBuffer; + */ +JNIEXPORT jobject JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_create( + JNIEnv*, jclass, jlong, jbyteArray, jint, jbyteArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: hash + * Signature: (J[B)[B + */ +JNIEXPORT jbyteArray JNICALL +Java_org_apache_arrow_plasma_PlasmaClientJNI_hash(JNIEnv*, jclass, jlong, jbyteArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: seal + * Signature: (J[B)V + */ +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_seal(JNIEnv*, jclass, + jlong, + jbyteArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: release + * Signature: (J[B)V + */ +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_release(JNIEnv*, + jclass, jlong, + jbyteArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: delete + * Signature: (J[B)V + */ +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_delete(JNIEnv*, + jclass, jlong, + jbyteArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: get + * Signature: (J[[BI)[[Ljava/nio/ByteBuffer; + */ +JNIEXPORT jobjectArray JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_get( + JNIEnv*, jclass, jlong, jobjectArray, jint); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: contains + * Signature: (J[B)Z + */ +JNIEXPORT jboolean JNICALL +Java_org_apache_arrow_plasma_PlasmaClientJNI_contains(JNIEnv*, jclass, jlong, jbyteArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: fetch + * Signature: (J[[B)V + */ +JNIEXPORT void JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_fetch(JNIEnv*, jclass, + jlong, + jobjectArray); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: wait + * Signature: (J[[BII)[[B + */ +JNIEXPORT jobjectArray JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_wait( + JNIEnv*, jclass, jlong, jobjectArray, jint, jint); + +/* + * Class: org_apache_arrow_plasma_PlasmaClientJNI + * Method: evict + * Signature: (JJ)J + */ +JNIEXPORT jlong JNICALL Java_org_apache_arrow_plasma_PlasmaClientJNI_evict(JNIEnv*, + jclass, jlong, + jlong); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/ray/plasma/malloc.cc b/src/ray/plasma/malloc.cc new file mode 100644 index 000000000..fe9efc4c3 --- /dev/null +++ b/src/ray/plasma/malloc.cc @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/malloc.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "plasma/common.h" +#include "plasma/plasma.h" + +namespace plasma { + +std::unordered_map mmap_records; + +static void* pointer_advance(void* p, ptrdiff_t n) { return (unsigned char*)p + n; } + +static ptrdiff_t pointer_distance(void const* pfrom, void const* pto) { + return (unsigned char const*)pto - (unsigned char const*)pfrom; +} + +void GetMallocMapinfo(void* addr, int* fd, int64_t* map_size, ptrdiff_t* offset) { + // TODO(rshin): Implement a more efficient search through mmap_records. + for (const auto& entry : mmap_records) { + if (addr >= entry.first && addr < pointer_advance(entry.first, entry.second.size)) { + *fd = entry.second.fd; + *map_size = entry.second.size; + *offset = pointer_distance(entry.first, addr); + return; + } + } + *fd = -1; + *map_size = 0; + *offset = 0; +} + +int64_t GetMmapSize(int fd) { + for (const auto& entry : mmap_records) { + if (entry.second.fd == fd) { + return entry.second.size; + } + } + ARROW_LOG(FATAL) << "failed to find entry in mmap_records for fd " << fd; + return -1; // This code is never reached. +} + +} // namespace plasma diff --git a/src/ray/plasma/malloc.h b/src/ray/plasma/malloc.h new file mode 100644 index 000000000..92d6537e9 --- /dev/null +++ b/src/ray/plasma/malloc.h @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_MALLOC_H +#define PLASMA_MALLOC_H + +#include +#include + +#include + +namespace plasma { + +/// Gap between two consecutive mmap regions allocated by fake_mmap. +/// This ensures that the segments of memory returned by +/// fake_mmap are never contiguous and dlmalloc does not coalesce it +/// (in the client we cannot guarantee that these mmaps are contiguous). +constexpr int64_t kMmapRegionsGap = sizeof(size_t); + +void GetMallocMapinfo(void* addr, int* fd, int64_t* map_length, ptrdiff_t* offset); + +/// Get the mmap size corresponding to a specific file descriptor. +/// +/// \param fd The file descriptor to look up. +/// \return The size of the corresponding memory-mapped file. +int64_t GetMmapSize(int fd); + +struct MmapRecord { + int fd; + int64_t size; +}; + +/// Hashtable that contains one entry per segment that we got from the OS +/// via mmap. Associates the address of that segment with its file descriptor +/// and size. +extern std::unordered_map mmap_records; + +} // namespace plasma + +#endif // PLASMA_MALLOC_H diff --git a/src/ray/plasma/plasma.cc b/src/ray/plasma/plasma.cc new file mode 100644 index 000000000..6f38951fb --- /dev/null +++ b/src/ray/plasma/plasma.cc @@ -0,0 +1,99 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/plasma.h" + +#include +#include +#include + +#include "plasma/common.h" +#include "plasma/common_generated.h" +#include "plasma/protocol.h" + +namespace fb = plasma::flatbuf; + +namespace plasma { + +ObjectTableEntry::ObjectTableEntry() : pointer(nullptr), ref_count(0) {} + +ObjectTableEntry::~ObjectTableEntry() { pointer = nullptr; } + +int WarnIfSigpipe(int status, int client_sock) { + if (status >= 0) { + return 0; + } + if (errno == EPIPE || errno == EBADF || errno == ECONNRESET) { + ARROW_LOG(WARNING) << "Received SIGPIPE, BAD FILE DESCRIPTOR, or ECONNRESET when " + "sending a message to client on fd " + << client_sock + << ". The client on the other end may " + "have hung up."; + return errno; + } + ARROW_LOG(FATAL) << "Failed to write message to client on fd " << client_sock << "."; + return -1; // This is never reached. +} + +/** + * This will create a new ObjectInfo buffer. The first sizeof(int64_t) bytes + * of this buffer are the length of the remaining message and the + * remaining message is a serialized version of the object info. + * + * \param object_info The object info to be serialized + * \return The object info buffer. It is the caller's responsibility to free + * this buffer with "delete" after it has been used. + */ +std::unique_ptr CreateObjectInfoBuffer(fb::ObjectInfoT* object_info) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreateObjectInfo(fbb, object_info); + fbb.Finish(message); + auto notification = + std::unique_ptr(new uint8_t[sizeof(int64_t) + fbb.GetSize()]); + *(reinterpret_cast(notification.get())) = fbb.GetSize(); + memcpy(notification.get() + sizeof(int64_t), fbb.GetBufferPointer(), fbb.GetSize()); + return notification; +} + +std::unique_ptr CreatePlasmaNotificationBuffer( + std::vector& object_info) { + flatbuffers::FlatBufferBuilder fbb; + std::vector> info; + for (size_t i = 0; i < object_info.size(); ++i) { + info.push_back(fb::CreateObjectInfo(fbb, &object_info[i])); + } + + auto info_array = fbb.CreateVector(info); + auto message = fb::CreatePlasmaNotification(fbb, info_array); + fbb.Finish(message); + auto notification = + std::unique_ptr(new uint8_t[sizeof(int64_t) + fbb.GetSize()]); + *(reinterpret_cast(notification.get())) = fbb.GetSize(); + memcpy(notification.get() + sizeof(int64_t), fbb.GetBufferPointer(), fbb.GetSize()); + return notification; +} + +ObjectTableEntry* GetObjectTableEntry(PlasmaStoreInfo* store_info, + const ObjectID& object_id) { + auto it = store_info->objects.find(object_id); + if (it == store_info->objects.end()) { + return NULL; + } + return it->second.get(); +} + +} // namespace plasma diff --git a/src/ray/plasma/plasma.fbs b/src/ray/plasma/plasma.fbs new file mode 100644 index 000000000..40556b45a --- /dev/null +++ b/src/ray/plasma/plasma.fbs @@ -0,0 +1,357 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +include "common.fbs"; + +// Plasma protocol specification +namespace plasma.flatbuf; + +enum MessageType:long { + // Message that gets send when a client hangs up. + PlasmaDisconnectClient = 0, + // Create a new object. + PlasmaCreateRequest, + PlasmaCreateReply, + PlasmaCreateAndSealRequest, + PlasmaCreateAndSealReply, + PlasmaAbortRequest, + PlasmaAbortReply, + // Seal an object. + PlasmaSealRequest, + PlasmaSealReply, + // Get an object that is stored on the local Plasma store. + PlasmaGetRequest, + PlasmaGetReply, + // Release an object. + PlasmaReleaseRequest, + PlasmaReleaseReply, + // Delete an object. + PlasmaDeleteRequest, + PlasmaDeleteReply, + // See if the store contains an object (will be deprecated). + PlasmaContainsRequest, + PlasmaContainsReply, + // List all objects in the store. + PlasmaListRequest, + PlasmaListReply, + // Get information for a newly connecting client. + PlasmaConnectRequest, + PlasmaConnectReply, + // Make room for new objects in the plasma store. + PlasmaEvictRequest, + PlasmaEvictReply, + // Subscribe to a list of objects or to all objects. + PlasmaSubscribeRequest, + // Unsubscribe. + PlasmaUnsubscribeRequest, + // Sending and receiving data. + // PlasmaDataRequest initiates sending the data, there will be one + // such message per data transfer. + PlasmaDataRequest, + // PlasmaDataReply contains the actual data and is sent back to the + // object store that requested the data. For each transfer, multiple + // reply messages get sent. Each one contains a fixed number of bytes. + PlasmaDataReply, + // Object notifications. + PlasmaNotification, + // Set memory quota for a client. + PlasmaSetOptionsRequest, + PlasmaSetOptionsReply, + // Get debugging information from the store. + PlasmaGetDebugStringRequest, + PlasmaGetDebugStringReply, + // Create and seal a batch of objects. This should be used to save + // IPC for creating many small objects. + PlasmaCreateAndSealBatchRequest, + PlasmaCreateAndSealBatchReply, + // Touch a number of objects to bump their position in the LRU cache. + PlasmaRefreshLRURequest, + PlasmaRefreshLRUReply, +} + +enum PlasmaError:int { + // Operation was successful. + OK, + // Trying to create an object that already exists. + ObjectExists, + // Trying to access an object that doesn't exist. + ObjectNonexistent, + // Trying to create an object but there isn't enough space in the store. + OutOfMemory, + // Trying to delete an object but it's not sealed. + ObjectNotSealed, + // Trying to delete an object but it's in use. + ObjectInUse, +} + +// Plasma store messages + +struct PlasmaObjectSpec { + // Index of the memory segment (= memory mapped file) that + // this object is allocated in. + segment_index: int; + // The offset in bytes in the memory mapped file of the data. + data_offset: ulong; + // The size in bytes of the data. + data_size: ulong; + // The offset in bytes in the memory mapped file of the metadata. + metadata_offset: ulong; + // The size in bytes of the metadata. + metadata_size: ulong; + // Device to create buffer on. + device_num: int; +} + +table PlasmaSetOptionsRequest { + // The name of the client. + client_name: string; + // The size of the output memory limit in bytes. + output_memory_quota: long; +} + +table PlasmaSetOptionsReply { + // Whether setting options succeeded. + error: PlasmaError; +} + +table PlasmaGetDebugStringRequest { +} + +table PlasmaGetDebugStringReply { + // The debug string from the server. + debug_string: string; +} + +table PlasmaCreateRequest { + // ID of the object to be created. + object_id: string; + // Whether to evict other objects to make room for this one. + evict_if_full: bool; + // The size of the object's data in bytes. + data_size: ulong; + // The size of the object's metadata in bytes. + metadata_size: ulong; + // Device to create buffer on. + device_num: int; +} + +table CudaHandle { + handle: [ubyte]; +} + +table PlasmaCreateReply { + // ID of the object that was created. + object_id: string; + // The object that is returned with this reply. + plasma_object: PlasmaObjectSpec; + // Error that occurred for this call. + error: PlasmaError; + // The file descriptor in the store that corresponds to the file descriptor + // being sent to the client right after this message. + store_fd: int; + // The size in bytes of the segment for the store file descriptor (needed to + // call mmap). + mmap_size: long; + // CUDA IPC Handle for objects on GPU. + ipc_handle: CudaHandle; +} + +table PlasmaCreateAndSealRequest { + // ID of the object to be created. + object_id: string; + // Whether to evict other objects to make room for this one. + evict_if_full: bool; + // The object's data. + data: string; + // The object's metadata. + metadata: string; + // Hash of the object data. + digest: string; +} + +table PlasmaCreateAndSealReply { + // Error that occurred for this call. + error: PlasmaError; +} + +table PlasmaCreateAndSealBatchRequest { + object_ids: [string]; + // Whether to evict other objects to make room for these objects. + evict_if_full: bool; + data: [string]; + metadata: [string]; + digest: [string]; +} + +table PlasmaCreateAndSealBatchReply { + // Error that occurred for this call. + error: PlasmaError; +} + +table PlasmaAbortRequest { + // ID of the object to be aborted. + object_id: string; +} + +table PlasmaAbortReply { + // ID of the object that was aborted. + object_id: string; +} + +table PlasmaSealRequest { + // ID of the object to be sealed. + object_id: string; + // Hash of the object data. + digest: string; +} + +table PlasmaSealReply { + // ID of the object that was sealed. + object_id: string; + // Error code. + error: PlasmaError; +} + +table PlasmaGetRequest { + // IDs of the objects stored at local Plasma store we are getting. + object_ids: [string]; + // The number of milliseconds before the request should timeout. + timeout_ms: long; +} + +table PlasmaGetReply { + // IDs of the objects being returned. + // This number can be smaller than the number of requested + // objects if not all requested objects are stored and sealed + // in the local Plasma store. + object_ids: [string]; + // Plasma object information, in the same order as their IDs. The number of + // elements in both object_ids and plasma_objects arrays must agree. + plasma_objects: [PlasmaObjectSpec]; + // A list of the file descriptors in the store that correspond to the file + // descriptors being sent to the client. The length of this list is the number + // of file descriptors that the store will send to the client after this + // message. + store_fds: [int]; + // Size in bytes of the segment for each store file descriptor (needed to call + // mmap). This list must have the same length as store_fds. + mmap_sizes: [long]; + // The number of elements in both object_ids and plasma_objects arrays must agree. + handles: [CudaHandle]; +} + +table PlasmaReleaseRequest { + // ID of the object to be released. + object_id: string; +} + +table PlasmaReleaseReply { + // ID of the object that was released. + object_id: string; + // Error code. + error: PlasmaError; +} + +table PlasmaDeleteRequest { + // The number of objects to delete. + count: int; + // ID of the object to be deleted. + object_ids: [string]; +} + +table PlasmaDeleteReply { + // The number of objects to delete. + count: int; + // ID of the object that was deleted. + object_ids: [string]; + // Error code. + errors: [PlasmaError]; +} + +table PlasmaContainsRequest { + // ID of the object we are querying. + object_id: string; +} + +table PlasmaContainsReply { + // ID of the object we are querying. + object_id: string; + // 1 if the object is in the store and 0 otherwise. + has_object: int; +} + +table PlasmaListRequest { +} + +table PlasmaListReply { + objects: [ObjectInfo]; +} + +// PlasmaConnect is used by a plasma client the first time it connects with the +// store. This is not really necessary, but is used to get some information +// about the store such as its memory capacity. + +table PlasmaConnectRequest { +} + +table PlasmaConnectReply { + // The memory capacity of the store. + memory_capacity: long; +} + +table PlasmaEvictRequest { + // Number of bytes that shall be freed. + num_bytes: ulong; +} + +table PlasmaEvictReply { + // Number of bytes that have been freed. + num_bytes: ulong; +} + +table PlasmaSubscribeRequest { +} + +table PlasmaNotification { + object_info: [ObjectInfo]; +} + +table PlasmaDataRequest { + // ID of the object that is requested. + object_id: string; + // The host address where the data shall be sent to. + address: string; + // The port of the manager the data shall be sent to. + port: int; +} + +table PlasmaDataReply { + // ID of the object that will be sent. + object_id: string; + // Size of the object data in bytes. + object_size: ulong; + // Size of the metadata in bytes. + metadata_size: ulong; +} + +table PlasmaRefreshLRURequest { + // ID of the objects to be bumped in the LRU cache. + object_ids: [string]; +} + +table PlasmaRefreshLRUReply { +} diff --git a/src/ray/plasma/plasma.h b/src/ray/plasma/plasma.h new file mode 100644 index 000000000..5b49563b3 --- /dev/null +++ b/src/ray/plasma/plasma.h @@ -0,0 +1,177 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_PLASMA_H +#define PLASMA_PLASMA_H + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "plasma/compat.h" + +#include "arrow/status.h" +#include "arrow/util/logging.h" +#include "arrow/util/macros.h" +#include "plasma/common.h" + +#ifdef PLASMA_CUDA +using arrow::cuda::CudaIpcMemHandle; +#endif + +namespace plasma { + +namespace flatbuf { +struct ObjectInfoT; +} // namespace flatbuf + +#define HANDLE_SIGPIPE(s, fd_) \ + do { \ + Status _s = (s); \ + if (!_s.ok()) { \ + if (errno == EPIPE || errno == EBADF || errno == ECONNRESET) { \ + ARROW_LOG(WARNING) \ + << "Received SIGPIPE, BAD FILE DESCRIPTOR, or ECONNRESET when " \ + "sending a message to client on fd " \ + << fd_ \ + << ". " \ + "The client on the other end may have hung up."; \ + } else { \ + return _s; \ + } \ + } \ + } while (0); + +/// Allocation granularity used in plasma for object allocation. +constexpr int64_t kBlockSize = 64; + +/// Contains all information that is associated with a Plasma store client. +struct Client { + explicit Client(int fd); + + /// The file descriptor used to communicate with the client. + int fd; + + /// Object ids that are used by this client. + std::unordered_set object_ids; + + /// File descriptors that are used by this client. + std::unordered_set used_fds; + + /// The file descriptor used to push notifications to client. This is only valid + /// if client subscribes to plasma store. -1 indicates invalid. + int notification_fd; + + std::string name = "anonymous_client"; +}; + +// TODO(pcm): Replace this by the flatbuffers message PlasmaObjectSpec. +struct PlasmaObject { +#ifdef PLASMA_CUDA + // IPC handle for Cuda. + std::shared_ptr ipc_handle; +#endif + /// The file descriptor of the memory mapped file in the store. It is used as + /// a unique identifier of the file in the client to look up the corresponding + /// file descriptor on the client's side. + int store_fd; + /// The offset in bytes in the memory mapped file of the data. + ptrdiff_t data_offset; + /// The offset in bytes in the memory mapped file of the metadata. + ptrdiff_t metadata_offset; + /// The size in bytes of the data. + int64_t data_size; + /// The size in bytes of the metadata. + int64_t metadata_size; + /// Device number object is on. + int device_num; + + bool operator==(const PlasmaObject& other) const { + return ( +#ifdef PLASMA_CUDA + (ipc_handle == other.ipc_handle) && +#endif + (store_fd == other.store_fd) && (data_offset == other.data_offset) && + (metadata_offset == other.metadata_offset) && (data_size == other.data_size) && + (metadata_size == other.metadata_size) && (device_num == other.device_num)); + } +}; + +enum class ObjectStatus : int { + /// The object was not found. + OBJECT_NOT_FOUND = 0, + /// The object was found. + OBJECT_FOUND = 1 +}; + +/// The plasma store information that is exposed to the eviction policy. +struct PlasmaStoreInfo { + /// Objects that are in the Plasma store. + ObjectTable objects; + /// Boolean flag indicating whether to start the object store with hugepages + /// support enabled. Huge pages are substantially larger than normal memory + /// pages (e.g. 2MB or 1GB instead of 4KB) and using them can reduce + /// bookkeeping overhead from the OS. + bool hugepages_enabled; + /// A (platform-dependent) directory where to create the memory-backed file. + std::string directory; +}; + +/// Get an entry from the object table and return NULL if the object_id +/// is not present. +/// +/// \param store_info The PlasmaStoreInfo that contains the object table. +/// \param object_id The object_id of the entry we are looking for. +/// \return The entry associated with the object_id or NULL if the object_id +/// is not present. +ObjectTableEntry* GetObjectTableEntry(PlasmaStoreInfo* store_info, + const ObjectID& object_id); + +/// Print a warning if the status is less than zero. This should be used to check +/// the success of messages sent to plasma clients. We print a warning instead of +/// failing because the plasma clients are allowed to die. This is used to handle +/// situations where the store writes to a client file descriptor, and the client +/// may already have disconnected. If we have processed the disconnection and +/// closed the file descriptor, we should get a BAD FILE DESCRIPTOR error. If we +/// have not, then we should get a SIGPIPE. If we write to a TCP socket that +/// isn't connected yet, then we should get an ECONNRESET. +/// +/// \param status The status to check. If it is less less than zero, we will +/// print a warning. +/// \param client_sock The client socket. This is just used to print some extra +/// information. +/// \return The errno set. +int WarnIfSigpipe(int status, int client_sock); + +std::unique_ptr CreateObjectInfoBuffer(flatbuf::ObjectInfoT* object_info); + +std::unique_ptr CreatePlasmaNotificationBuffer( + std::vector& object_info); + +} // namespace plasma + +#endif // PLASMA_PLASMA_H diff --git a/src/ray/plasma/plasma_allocator.cc b/src/ray/plasma/plasma_allocator.cc new file mode 100644 index 000000000..b67eeea40 --- /dev/null +++ b/src/ray/plasma/plasma_allocator.cc @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include + +#include "plasma/malloc.h" +#include "plasma/plasma_allocator.h" + +namespace plasma { + +extern "C" { +void* dlmemalign(size_t alignment, size_t bytes); +void dlfree(void* mem); +} + +int64_t PlasmaAllocator::footprint_limit_ = 0; +int64_t PlasmaAllocator::allocated_ = 0; + +void* PlasmaAllocator::Memalign(size_t alignment, size_t bytes) { + if (allocated_ + static_cast(bytes) > footprint_limit_) { + return nullptr; + } + void* mem = dlmemalign(alignment, bytes); + ARROW_CHECK(mem); + allocated_ += bytes; + return mem; +} + +void PlasmaAllocator::Free(void* mem, size_t bytes) { + dlfree(mem); + allocated_ -= bytes; +} + +void PlasmaAllocator::SetFootprintLimit(size_t bytes) { + footprint_limit_ = static_cast(bytes); +} + +int64_t PlasmaAllocator::GetFootprintLimit() { return footprint_limit_; } + +int64_t PlasmaAllocator::Allocated() { return allocated_; } + +} // namespace plasma diff --git a/src/ray/plasma/plasma_allocator.h b/src/ray/plasma/plasma_allocator.h new file mode 100644 index 000000000..d9d4cc0ec --- /dev/null +++ b/src/ray/plasma/plasma_allocator.h @@ -0,0 +1,64 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_ALLOCATOR_H +#define PLASMA_ALLOCATOR_H + +#include +#include + +namespace plasma { + +class PlasmaAllocator { + public: + /// Allocates size bytes and returns a pointer to the allocated memory. The + /// memory address will be a multiple of alignment, which must be a power of two. + /// + /// \param alignment Memory alignment. + /// \param bytes Number of bytes. + /// \return Pointer to allocated memory. + static void* Memalign(size_t alignment, size_t bytes); + + /// Frees the memory space pointed to by mem, which must have been returned by + /// a previous call to Memalign() + /// + /// \param mem Pointer to memory to free. + /// \param bytes Number of bytes to be freed. + static void Free(void* mem, size_t bytes); + + /// Sets the memory footprint limit for Plasma. + /// + /// \param bytes Plasma memory footprint limit in bytes. + static void SetFootprintLimit(size_t bytes); + + /// Get the memory footprint limit for Plasma. + /// + /// \return Plasma memory footprint limit in bytes. + static int64_t GetFootprintLimit(); + + /// Get the number of bytes allocated by Plasma so far. + /// \return Number of bytes allocated by Plasma so far. + static int64_t Allocated(); + + private: + static int64_t allocated_; + static int64_t footprint_limit_; +}; + +} // namespace plasma + +#endif // ARROW_PLASMA_ALLOCATOR_H diff --git a/src/ray/plasma/protocol.cc b/src/ray/plasma/protocol.cc new file mode 100644 index 000000000..15614f012 --- /dev/null +++ b/src/ray/plasma/protocol.cc @@ -0,0 +1,831 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/protocol.h" + +#include + +#include "flatbuffers/flatbuffers.h" + +#include "plasma/common.h" +#include "plasma/io.h" +#include "plasma/plasma_generated.h" + +#ifdef PLASMA_CUDA +#include "arrow/gpu/cuda_api.h" +#endif +#include "arrow/util/ubsan.h" + +namespace fb = plasma::flatbuf; + +namespace plasma { + +using fb::MessageType; +using fb::PlasmaError; +using fb::PlasmaObjectSpec; + +using flatbuffers::uoffset_t; + +#define PLASMA_CHECK_ENUM(x, y) \ + static_assert(static_cast(x) == static_cast(y), "protocol mismatch") + +flatbuffers::Offset>> +ToFlatbuffer(flatbuffers::FlatBufferBuilder* fbb, const ObjectID* object_ids, + int64_t num_objects) { + std::vector> results; + for (int64_t i = 0; i < num_objects; i++) { + results.push_back(fbb->CreateString(object_ids[i].binary())); + } + return fbb->CreateVector(arrow::util::MakeNonNull(results.data()), results.size()); +} + +flatbuffers::Offset>> +ToFlatbuffer(flatbuffers::FlatBufferBuilder* fbb, + const std::vector& strings) { + std::vector> results; + for (size_t i = 0; i < strings.size(); i++) { + results.push_back(fbb->CreateString(strings[i])); + } + + return fbb->CreateVector(arrow::util::MakeNonNull(results.data()), results.size()); +} + +flatbuffers::Offset> ToFlatbuffer( + flatbuffers::FlatBufferBuilder* fbb, const std::vector& data) { + return fbb->CreateVector(arrow::util::MakeNonNull(data.data()), data.size()); +} + +Status PlasmaReceive(int sock, MessageType message_type, std::vector* buffer) { + MessageType type; + RETURN_NOT_OK(ReadMessage(sock, &type, buffer)); + ARROW_CHECK(type == message_type) + << "type = " << static_cast(type) + << ", message_type = " << static_cast(message_type); + return Status::OK(); +} + +// Helper function to create a vector of elements from Data (Request/Reply struct). +// The Getter function is used to extract one element from Data. +template +void ToVector(const Data& request, std::vector* out, const Getter& getter) { + int count = request.count(); + out->clear(); + out->reserve(count); + for (int i = 0; i < count; ++i) { + out->push_back(getter(request, i)); + } +} + +template +void ConvertToVector(const FlatbufferVectorPointer fbvector, std::vector* out, + const Converter& converter) { + out->clear(); + out->reserve(fbvector->size()); + for (size_t i = 0; i < fbvector->size(); ++i) { + out->push_back(converter(*fbvector->Get(i))); + } +} + +template +Status PlasmaSend(int sock, MessageType message_type, flatbuffers::FlatBufferBuilder* fbb, + const Message& message) { + fbb->Finish(message); + return WriteMessage(sock, message_type, fbb->GetSize(), fbb->GetBufferPointer()); +} + +Status PlasmaErrorStatus(fb::PlasmaError plasma_error) { + switch (plasma_error) { + case fb::PlasmaError::OK: + return Status::OK(); + case fb::PlasmaError::ObjectExists: + return MakePlasmaError(PlasmaErrorCode::PlasmaObjectExists, + "object already exists in the plasma store"); + case fb::PlasmaError::ObjectNonexistent: + return MakePlasmaError(PlasmaErrorCode::PlasmaObjectNonexistent, + "object does not exist in the plasma store"); + case fb::PlasmaError::OutOfMemory: + return MakePlasmaError(PlasmaErrorCode::PlasmaStoreFull, + "object does not fit in the plasma store"); + default: + ARROW_LOG(FATAL) << "unknown plasma error code " << static_cast(plasma_error); + } + return Status::OK(); +} + +// Set options messages. + +Status SendSetOptionsRequest(int sock, const std::string& client_name, + int64_t output_memory_limit) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaSetOptionsRequest(fbb, fbb.CreateString(client_name), + output_memory_limit); + return PlasmaSend(sock, MessageType::PlasmaSetOptionsRequest, &fbb, message); +} + +Status ReadSetOptionsRequest(uint8_t* data, size_t size, std::string* client_name, + int64_t* output_memory_quota) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *client_name = std::string(message->client_name()->str()); + *output_memory_quota = message->output_memory_quota(); + return Status::OK(); +} + +Status SendSetOptionsReply(int sock, PlasmaError error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaSetOptionsReply(fbb, error); + return PlasmaSend(sock, MessageType::PlasmaSetOptionsReply, &fbb, message); +} + +Status ReadSetOptionsReply(uint8_t* data, size_t size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + return PlasmaErrorStatus(message->error()); +} + +// Get debug string messages. + +Status SendGetDebugStringRequest(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaGetDebugStringRequest(fbb); + return PlasmaSend(sock, MessageType::PlasmaGetDebugStringRequest, &fbb, message); +} + +Status SendGetDebugStringReply(int sock, const std::string& debug_string) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaGetDebugStringReply(fbb, fbb.CreateString(debug_string)); + return PlasmaSend(sock, MessageType::PlasmaGetDebugStringReply, &fbb, message); +} + +Status ReadGetDebugStringReply(uint8_t* data, size_t size, std::string* debug_string) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *debug_string = message->debug_string()->str(); + return Status::OK(); +} + +// Create messages. + +Status SendCreateRequest(int sock, ObjectID object_id, bool evict_if_full, + int64_t data_size, int64_t metadata_size, int device_num) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + fb::CreatePlasmaCreateRequest(fbb, fbb.CreateString(object_id.binary()), + evict_if_full, data_size, metadata_size, device_num); + return PlasmaSend(sock, MessageType::PlasmaCreateRequest, &fbb, message); +} + +Status ReadCreateRequest(uint8_t* data, size_t size, ObjectID* object_id, + bool* evict_if_full, int64_t* data_size, int64_t* metadata_size, + int* device_num) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *evict_if_full = message->evict_if_full(); + *data_size = message->data_size(); + *metadata_size = message->metadata_size(); + *object_id = ObjectID::from_binary(message->object_id()->str()); + *device_num = message->device_num(); + return Status::OK(); +} + +Status SendCreateReply(int sock, ObjectID object_id, PlasmaObject* object, + PlasmaError error_code, int64_t mmap_size) { + flatbuffers::FlatBufferBuilder fbb; + PlasmaObjectSpec plasma_object(object->store_fd, object->data_offset, object->data_size, + object->metadata_offset, object->metadata_size, + object->device_num); + auto object_string = fbb.CreateString(object_id.binary()); +#ifdef PLASMA_CUDA + flatbuffers::Offset ipc_handle; + if (object->device_num != 0) { + std::shared_ptr handle; + ARROW_ASSIGN_OR_RAISE(handle, object->ipc_handle->Serialize()); + ipc_handle = + fb::CreateCudaHandle(fbb, fbb.CreateVector(handle->data(), handle->size())); + } +#endif + fb::PlasmaCreateReplyBuilder crb(fbb); + crb.add_error(static_cast(error_code)); + crb.add_plasma_object(&plasma_object); + crb.add_object_id(object_string); + crb.add_store_fd(object->store_fd); + crb.add_mmap_size(mmap_size); + if (object->device_num != 0) { +#ifdef PLASMA_CUDA + crb.add_ipc_handle(ipc_handle); +#else + ARROW_LOG(FATAL) << "This should be unreachable."; +#endif + } + auto message = crb.Finish(); + return PlasmaSend(sock, MessageType::PlasmaCreateReply, &fbb, message); +} + +Status ReadCreateReply(uint8_t* data, size_t size, ObjectID* object_id, + PlasmaObject* object, int* store_fd, int64_t* mmap_size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + object->store_fd = message->plasma_object()->segment_index(); + object->data_offset = message->plasma_object()->data_offset(); + object->data_size = message->plasma_object()->data_size(); + object->metadata_offset = message->plasma_object()->metadata_offset(); + object->metadata_size = message->plasma_object()->metadata_size(); + + *store_fd = message->store_fd(); + *mmap_size = message->mmap_size(); + + object->device_num = message->plasma_object()->device_num(); +#ifdef PLASMA_CUDA + if (object->device_num != 0) { + ARROW_ASSIGN_OR_RAISE( + object->ipc_handle, + CudaIpcMemHandle::FromBuffer(message->ipc_handle()->handle()->data())); + } +#endif + return PlasmaErrorStatus(message->error()); +} + +Status SendCreateAndSealRequest(int sock, const ObjectID& object_id, bool evict_if_full, + const std::string& data, const std::string& metadata, + unsigned char* digest) { + flatbuffers::FlatBufferBuilder fbb; + auto digest_string = fbb.CreateString(reinterpret_cast(digest), kDigestSize); + auto message = fb::CreatePlasmaCreateAndSealRequest( + fbb, fbb.CreateString(object_id.binary()), evict_if_full, fbb.CreateString(data), + fbb.CreateString(metadata), digest_string); + return PlasmaSend(sock, MessageType::PlasmaCreateAndSealRequest, &fbb, message); +} + +Status ReadCreateAndSealRequest(uint8_t* data, size_t size, ObjectID* object_id, + bool* evict_if_full, std::string* object_data, + std::string* metadata, std::string* digest) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + + *object_id = ObjectID::from_binary(message->object_id()->str()); + *evict_if_full = message->evict_if_full(); + *object_data = message->data()->str(); + *metadata = message->metadata()->str(); + ARROW_CHECK(message->digest()->size() == kDigestSize); + digest->assign(message->digest()->data(), kDigestSize); + return Status::OK(); +} + +Status SendCreateAndSealBatchRequest(int sock, const std::vector& object_ids, + bool evict_if_full, + const std::vector& data, + const std::vector& metadata, + const std::vector& digests) { + flatbuffers::FlatBufferBuilder fbb; + + auto message = fb::CreatePlasmaCreateAndSealBatchRequest( + fbb, ToFlatbuffer(&fbb, object_ids.data(), object_ids.size()), evict_if_full, + ToFlatbuffer(&fbb, data), ToFlatbuffer(&fbb, metadata), + ToFlatbuffer(&fbb, digests)); + + return PlasmaSend(sock, MessageType::PlasmaCreateAndSealBatchRequest, &fbb, message); +} + +Status ReadCreateAndSealBatchRequest(uint8_t* data, size_t size, + std::vector* object_ids, + bool* evict_if_full, + std::vector* object_data, + std::vector* metadata, + std::vector* digests) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + + *evict_if_full = message->evict_if_full(); + ConvertToVector(message->object_ids(), object_ids, + [](const flatbuffers::String& element) { + return ObjectID::from_binary(element.str()); + }); + + ConvertToVector(message->data(), object_data, + [](const flatbuffers::String& element) { return element.str(); }); + + ConvertToVector(message->metadata(), metadata, + [](const flatbuffers::String& element) { return element.str(); }); + + ConvertToVector(message->digest(), digests, + [](const flatbuffers::String& element) { return element.str(); }); + + return Status::OK(); +} + +Status SendCreateAndSealReply(int sock, PlasmaError error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaCreateAndSealReply(fbb, static_cast(error)); + return PlasmaSend(sock, MessageType::PlasmaCreateAndSealReply, &fbb, message); +} + +Status ReadCreateAndSealReply(uint8_t* data, size_t size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + return PlasmaErrorStatus(message->error()); +} + +Status SendCreateAndSealBatchReply(int sock, PlasmaError error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + fb::CreatePlasmaCreateAndSealBatchReply(fbb, static_cast(error)); + return PlasmaSend(sock, MessageType::PlasmaCreateAndSealBatchReply, &fbb, message); +} + +Status ReadCreateAndSealBatchReply(uint8_t* data, size_t size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + return PlasmaErrorStatus(message->error()); +} + +Status SendAbortRequest(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaAbortRequest(fbb, fbb.CreateString(object_id.binary())); + return PlasmaSend(sock, MessageType::PlasmaAbortRequest, &fbb, message); +} + +Status ReadAbortRequest(uint8_t* data, size_t size, ObjectID* object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendAbortReply(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaAbortReply(fbb, fbb.CreateString(object_id.binary())); + return PlasmaSend(sock, MessageType::PlasmaAbortReply, &fbb, message); +} + +Status ReadAbortReply(uint8_t* data, size_t size, ObjectID* object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +// Seal messages. + +Status SendSealRequest(int sock, ObjectID object_id, const std::string& digest) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary()), + fbb.CreateString(digest)); + return PlasmaSend(sock, MessageType::PlasmaSealRequest, &fbb, message); +} + +Status ReadSealRequest(uint8_t* data, size_t size, ObjectID* object_id, + std::string* digest) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + ARROW_CHECK_EQ(message->digest()->size(), kDigestSize); + digest->assign(message->digest()->data(), kDigestSize); + return Status::OK(); +} + +Status SendSealReply(int sock, ObjectID object_id, PlasmaError error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + fb::CreatePlasmaSealReply(fbb, fbb.CreateString(object_id.binary()), error); + return PlasmaSend(sock, MessageType::PlasmaSealReply, &fbb, message); +} + +Status ReadSealReply(uint8_t* data, size_t size, ObjectID* object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return PlasmaErrorStatus(message->error()); +} + +// Release messages. + +Status SendReleaseRequest(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + fb::CreatePlasmaReleaseRequest(fbb, fbb.CreateString(object_id.binary())); + return PlasmaSend(sock, MessageType::PlasmaReleaseRequest, &fbb, message); +} + +Status ReadReleaseRequest(uint8_t* data, size_t size, ObjectID* object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendReleaseReply(int sock, ObjectID object_id, PlasmaError error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + fb::CreatePlasmaReleaseReply(fbb, fbb.CreateString(object_id.binary()), error); + return PlasmaSend(sock, MessageType::PlasmaReleaseReply, &fbb, message); +} + +Status ReadReleaseReply(uint8_t* data, size_t size, ObjectID* object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return PlasmaErrorStatus(message->error()); +} + +// Delete objects messages. + +Status SendDeleteRequest(int sock, const std::vector& object_ids) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaDeleteRequest( + fbb, static_cast(object_ids.size()), + ToFlatbuffer(&fbb, &object_ids[0], object_ids.size())); + return PlasmaSend(sock, MessageType::PlasmaDeleteRequest, &fbb, message); +} + +Status ReadDeleteRequest(uint8_t* data, size_t size, std::vector* object_ids) { + using fb::PlasmaDeleteRequest; + + DCHECK(data); + DCHECK(object_ids); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + ToVector(*message, object_ids, [](const PlasmaDeleteRequest& request, int i) { + return ObjectID::from_binary(request.object_ids()->Get(i)->str()); + }); + return Status::OK(); +} + +Status SendDeleteReply(int sock, const std::vector& object_ids, + const std::vector& errors) { + DCHECK(object_ids.size() == errors.size()); + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaDeleteReply( + fbb, static_cast(object_ids.size()), + ToFlatbuffer(&fbb, &object_ids[0], object_ids.size()), + fbb.CreateVector( + arrow::util::MakeNonNull(reinterpret_cast(errors.data())), + object_ids.size())); + return PlasmaSend(sock, MessageType::PlasmaDeleteReply, &fbb, message); +} + +Status ReadDeleteReply(uint8_t* data, size_t size, std::vector* object_ids, + std::vector* errors) { + using fb::PlasmaDeleteReply; + + DCHECK(data); + DCHECK(object_ids); + DCHECK(errors); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + ToVector(*message, object_ids, [](const PlasmaDeleteReply& request, int i) { + return ObjectID::from_binary(request.object_ids()->Get(i)->str()); + }); + ToVector(*message, errors, [](const PlasmaDeleteReply& request, int i) { + return static_cast(request.errors()->data()[i]); + }); + return Status::OK(); +} + +// Contains messages. + +Status SendContainsRequest(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + fb::CreatePlasmaContainsRequest(fbb, fbb.CreateString(object_id.binary())); + return PlasmaSend(sock, MessageType::PlasmaContainsRequest, &fbb, message); +} + +Status ReadContainsRequest(uint8_t* data, size_t size, ObjectID* object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendContainsReply(int sock, ObjectID object_id, bool has_object) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaContainsReply(fbb, fbb.CreateString(object_id.binary()), + has_object); + return PlasmaSend(sock, MessageType::PlasmaContainsReply, &fbb, message); +} + +Status ReadContainsReply(uint8_t* data, size_t size, ObjectID* object_id, + bool* has_object) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + *has_object = message->has_object(); + return Status::OK(); +} + +// List messages. + +Status SendListRequest(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaListRequest(fbb); + return PlasmaSend(sock, MessageType::PlasmaListRequest, &fbb, message); +} + +Status ReadListRequest(uint8_t* data, size_t size) { return Status::OK(); } + +Status SendListReply(int sock, const ObjectTable& objects) { + flatbuffers::FlatBufferBuilder fbb; + std::vector> object_infos; + for (auto const& entry : objects) { + auto digest = entry.second->state == ObjectState::PLASMA_CREATED + ? fbb.CreateString("") + : fbb.CreateString(reinterpret_cast(entry.second->digest), + kDigestSize); + auto info = fb::CreateObjectInfo(fbb, fbb.CreateString(entry.first.binary()), + entry.second->data_size, entry.second->metadata_size, + entry.second->ref_count, entry.second->create_time, + entry.second->construct_duration, digest); + object_infos.push_back(info); + } + auto message = fb::CreatePlasmaListReply( + fbb, fbb.CreateVector(arrow::util::MakeNonNull(object_infos.data()), + object_infos.size())); + return PlasmaSend(sock, MessageType::PlasmaListReply, &fbb, message); +} + +Status ReadListReply(uint8_t* data, size_t size, ObjectTable* objects) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + for (auto const& object : *message->objects()) { + ObjectID object_id = ObjectID::from_binary(object->object_id()->str()); + auto entry = std::unique_ptr(new ObjectTableEntry()); + entry->data_size = object->data_size(); + entry->metadata_size = object->metadata_size(); + entry->ref_count = object->ref_count(); + entry->create_time = object->create_time(); + entry->construct_duration = object->construct_duration(); + entry->state = object->digest()->size() == 0 ? ObjectState::PLASMA_CREATED + : ObjectState::PLASMA_SEALED; + (*objects)[object_id] = std::move(entry); + } + return Status::OK(); +} + +// Connect messages. + +Status SendConnectRequest(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaConnectRequest(fbb); + return PlasmaSend(sock, MessageType::PlasmaConnectRequest, &fbb, message); +} + +Status ReadConnectRequest(uint8_t* data) { return Status::OK(); } + +Status SendConnectReply(int sock, int64_t memory_capacity) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaConnectReply(fbb, memory_capacity); + return PlasmaSend(sock, MessageType::PlasmaConnectReply, &fbb, message); +} + +Status ReadConnectReply(uint8_t* data, size_t size, int64_t* memory_capacity) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *memory_capacity = message->memory_capacity(); + return Status::OK(); +} + +// Evict messages. + +Status SendEvictRequest(int sock, int64_t num_bytes) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaEvictRequest(fbb, num_bytes); + return PlasmaSend(sock, MessageType::PlasmaEvictRequest, &fbb, message); +} + +Status ReadEvictRequest(uint8_t* data, size_t size, int64_t* num_bytes) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *num_bytes = message->num_bytes(); + return Status::OK(); +} + +Status SendEvictReply(int sock, int64_t num_bytes) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaEvictReply(fbb, num_bytes); + return PlasmaSend(sock, MessageType::PlasmaEvictReply, &fbb, message); +} + +Status ReadEvictReply(uint8_t* data, size_t size, int64_t& num_bytes) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + num_bytes = message->num_bytes(); + return Status::OK(); +} + +// Get messages. + +Status SendGetRequest(int sock, const ObjectID* object_ids, int64_t num_objects, + int64_t timeout_ms) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaGetRequest( + fbb, ToFlatbuffer(&fbb, object_ids, num_objects), timeout_ms); + return PlasmaSend(sock, MessageType::PlasmaGetRequest, &fbb, message); +} + +Status ReadGetRequest(uint8_t* data, size_t size, std::vector& object_ids, + int64_t* timeout_ms) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + for (uoffset_t i = 0; i < message->object_ids()->size(); ++i) { + auto object_id = message->object_ids()->Get(i)->str(); + object_ids.push_back(ObjectID::from_binary(object_id)); + } + *timeout_ms = message->timeout_ms(); + return Status::OK(); +} + +Status SendGetReply(int sock, ObjectID object_ids[], + std::unordered_map& plasma_objects, + int64_t num_objects, const std::vector& store_fds, + const std::vector& mmap_sizes) { + flatbuffers::FlatBufferBuilder fbb; + std::vector objects; + + std::vector> handles; + for (int64_t i = 0; i < num_objects; ++i) { + const PlasmaObject& object = plasma_objects[object_ids[i]]; + objects.push_back(PlasmaObjectSpec(object.store_fd, object.data_offset, + object.data_size, object.metadata_offset, + object.metadata_size, object.device_num)); +#ifdef PLASMA_CUDA + if (object.device_num != 0) { + std::shared_ptr handle; + ARROW_ASSIGN_OR_RAISE(handle, object.ipc_handle->Serialize()); + handles.push_back( + fb::CreateCudaHandle(fbb, fbb.CreateVector(handle->data(), handle->size()))); + } +#endif + } + auto message = fb::CreatePlasmaGetReply( + fbb, ToFlatbuffer(&fbb, object_ids, num_objects), + fbb.CreateVectorOfStructs(arrow::util::MakeNonNull(objects.data()), num_objects), + fbb.CreateVector(arrow::util::MakeNonNull(store_fds.data()), store_fds.size()), + fbb.CreateVector(arrow::util::MakeNonNull(mmap_sizes.data()), mmap_sizes.size()), + fbb.CreateVector(arrow::util::MakeNonNull(handles.data()), handles.size())); + return PlasmaSend(sock, MessageType::PlasmaGetReply, &fbb, message); +} + +Status ReadGetReply(uint8_t* data, size_t size, ObjectID object_ids[], + PlasmaObject plasma_objects[], int64_t num_objects, + std::vector& store_fds, std::vector& mmap_sizes) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); +#ifdef PLASMA_CUDA + int handle_pos = 0; +#endif + DCHECK(VerifyFlatbuffer(message, data, size)); + for (uoffset_t i = 0; i < num_objects; ++i) { + object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); + } + for (uoffset_t i = 0; i < num_objects; ++i) { + const PlasmaObjectSpec* object = message->plasma_objects()->Get(i); + plasma_objects[i].store_fd = object->segment_index(); + plasma_objects[i].data_offset = object->data_offset(); + plasma_objects[i].data_size = object->data_size(); + plasma_objects[i].metadata_offset = object->metadata_offset(); + plasma_objects[i].metadata_size = object->metadata_size(); + plasma_objects[i].device_num = object->device_num(); +#ifdef PLASMA_CUDA + if (object->device_num() != 0) { + const void* ipc_handle = message->handles()->Get(handle_pos)->handle()->data(); + ARROW_ASSIGN_OR_RAISE(plasma_objects[i].ipc_handle, + CudaIpcMemHandle::FromBuffer(ipc_handle)); + handle_pos++; + } +#endif + } + ARROW_CHECK(message->store_fds()->size() == message->mmap_sizes()->size()); + for (uoffset_t i = 0; i < message->store_fds()->size(); i++) { + store_fds.push_back(message->store_fds()->Get(i)); + mmap_sizes.push_back(message->mmap_sizes()->Get(i)); + } + return Status::OK(); +} + +// Subscribe messages. + +Status SendSubscribeRequest(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaSubscribeRequest(fbb); + return PlasmaSend(sock, MessageType::PlasmaSubscribeRequest, &fbb, message); +} + +// Data messages. + +Status SendDataRequest(int sock, ObjectID object_id, const char* address, int port) { + flatbuffers::FlatBufferBuilder fbb; + auto addr = fbb.CreateString(address, strlen(address)); + auto message = + fb::CreatePlasmaDataRequest(fbb, fbb.CreateString(object_id.binary()), addr, port); + return PlasmaSend(sock, MessageType::PlasmaDataRequest, &fbb, message); +} + +Status ReadDataRequest(uint8_t* data, size_t size, ObjectID* object_id, char** address, + int* port) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + DCHECK(message->object_id()->size() == sizeof(ObjectID)); + *object_id = ObjectID::from_binary(message->object_id()->str()); +#ifdef _WIN32 + *address = _strdup(message->address()->c_str()); +#else + *address = strdup(message->address()->c_str()); +#endif + *port = message->port(); + return Status::OK(); +} + +Status SendDataReply(int sock, ObjectID object_id, int64_t object_size, + int64_t metadata_size) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaDataReply(fbb, fbb.CreateString(object_id.binary()), + object_size, metadata_size); + return PlasmaSend(sock, MessageType::PlasmaDataReply, &fbb, message); +} + +Status ReadDataReply(uint8_t* data, size_t size, ObjectID* object_id, + int64_t* object_size, int64_t* metadata_size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + *object_size = static_cast(message->object_size()); + *metadata_size = static_cast(message->metadata_size()); + return Status::OK(); +} + +// RefreshLRU messages. + +Status SendRefreshLRURequest(int sock, const std::vector& object_ids) { + flatbuffers::FlatBufferBuilder fbb; + + auto message = fb::CreatePlasmaRefreshLRURequest( + fbb, ToFlatbuffer(&fbb, object_ids.data(), object_ids.size())); + + return PlasmaSend(sock, MessageType::PlasmaRefreshLRURequest, &fbb, message); +} + +Status ReadRefreshLRURequest(uint8_t* data, size_t size, + std::vector* object_ids) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + for (uoffset_t i = 0; i < message->object_ids()->size(); ++i) { + auto object_id = message->object_ids()->Get(i)->str(); + object_ids->push_back(ObjectID::from_binary(object_id)); + } + return Status::OK(); +} + +Status SendRefreshLRUReply(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = fb::CreatePlasmaRefreshLRUReply(fbb); + return PlasmaSend(sock, MessageType::PlasmaRefreshLRUReply, &fbb, message); +} + +Status ReadRefreshLRUReply(uint8_t* data, size_t size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(VerifyFlatbuffer(message, data, size)); + return Status::OK(); +} + +} // namespace plasma diff --git a/src/ray/plasma/protocol.h b/src/ray/plasma/protocol.h new file mode 100644 index 000000000..37d03a0f2 --- /dev/null +++ b/src/ray/plasma/protocol.h @@ -0,0 +1,251 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_PROTOCOL_H +#define PLASMA_PROTOCOL_H + +#include +#include +#include +#include + +#include "arrow/status.h" +#include "plasma/plasma.h" +#include "plasma/plasma_generated.h" + +namespace plasma { + +using arrow::Status; + +using flatbuf::MessageType; +using flatbuf::PlasmaError; + +template +bool VerifyFlatbuffer(T* object, uint8_t* data, size_t size) { + flatbuffers::Verifier verifier(data, size); + return object->Verify(verifier); +} + +flatbuffers::Offset>> +ToFlatbuffer(flatbuffers::FlatBufferBuilder* fbb, const ObjectID* object_ids, + int64_t num_objects); + +flatbuffers::Offset>> +ToFlatbuffer(flatbuffers::FlatBufferBuilder* fbb, + const std::vector& strings); + +flatbuffers::Offset> ToFlatbuffer( + flatbuffers::FlatBufferBuilder* fbb, const std::vector& data); + +/* Plasma receive message. */ + +Status PlasmaReceive(int sock, MessageType message_type, std::vector* buffer); + +/* Set options messages. */ + +Status SendSetOptionsRequest(int sock, const std::string& client_name, + int64_t output_memory_limit); + +Status ReadSetOptionsRequest(uint8_t* data, size_t size, std::string* client_name, + int64_t* output_memory_quota); + +Status SendSetOptionsReply(int sock, PlasmaError error); + +Status ReadSetOptionsReply(uint8_t* data, size_t size); + +/* Debug string messages. */ + +Status SendGetDebugStringRequest(int sock); + +Status SendGetDebugStringReply(int sock, const std::string& debug_string); + +Status ReadGetDebugStringReply(uint8_t* data, size_t size, std::string* debug_string); + +/* Plasma Create message functions. */ + +Status SendCreateRequest(int sock, ObjectID object_id, bool evict_if_full, + int64_t data_size, int64_t metadata_size, int device_num); + +Status ReadCreateRequest(uint8_t* data, size_t size, ObjectID* object_id, + bool* evict_if_full, int64_t* data_size, int64_t* metadata_size, + int* device_num); + +Status SendCreateReply(int sock, ObjectID object_id, PlasmaObject* object, + PlasmaError error, int64_t mmap_size); + +Status ReadCreateReply(uint8_t* data, size_t size, ObjectID* object_id, + PlasmaObject* object, int* store_fd, int64_t* mmap_size); + +Status SendCreateAndSealRequest(int sock, const ObjectID& object_id, bool evict_if_full, + const std::string& data, const std::string& metadata, + unsigned char* digest); + +Status ReadCreateAndSealRequest(uint8_t* data, size_t size, ObjectID* object_id, + bool* evict_if_full, std::string* object_data, + std::string* metadata, std::string* digest); + +Status SendCreateAndSealBatchRequest(int sock, const std::vector& object_ids, + bool evict_if_full, + const std::vector& data, + const std::vector& metadata, + const std::vector& digests); + +Status ReadCreateAndSealBatchRequest(uint8_t* data, size_t size, + std::vector* object_id, + bool* evict_if_full, + std::vector* object_data, + std::vector* metadata, + std::vector* digests); + +Status SendCreateAndSealReply(int sock, PlasmaError error); + +Status ReadCreateAndSealReply(uint8_t* data, size_t size); + +Status SendCreateAndSealBatchReply(int sock, PlasmaError error); + +Status ReadCreateAndSealBatchReply(uint8_t* data, size_t size); + +Status SendAbortRequest(int sock, ObjectID object_id); + +Status ReadAbortRequest(uint8_t* data, size_t size, ObjectID* object_id); + +Status SendAbortReply(int sock, ObjectID object_id); + +Status ReadAbortReply(uint8_t* data, size_t size, ObjectID* object_id); + +/* Plasma Seal message functions. */ + +Status SendSealRequest(int sock, ObjectID object_id, const std::string& digest); + +Status ReadSealRequest(uint8_t* data, size_t size, ObjectID* object_id, + std::string* digest); + +Status SendSealReply(int sock, ObjectID object_id, PlasmaError error); + +Status ReadSealReply(uint8_t* data, size_t size, ObjectID* object_id); + +/* Plasma Get message functions. */ + +Status SendGetRequest(int sock, const ObjectID* object_ids, int64_t num_objects, + int64_t timeout_ms); + +Status ReadGetRequest(uint8_t* data, size_t size, std::vector& object_ids, + int64_t* timeout_ms); + +Status SendGetReply(int sock, ObjectID object_ids[], + std::unordered_map& plasma_objects, + int64_t num_objects, const std::vector& store_fds, + const std::vector& mmap_sizes); + +Status ReadGetReply(uint8_t* data, size_t size, ObjectID object_ids[], + PlasmaObject plasma_objects[], int64_t num_objects, + std::vector& store_fds, std::vector& mmap_sizes); + +/* Plasma Release message functions. */ + +Status SendReleaseRequest(int sock, ObjectID object_id); + +Status ReadReleaseRequest(uint8_t* data, size_t size, ObjectID* object_id); + +Status SendReleaseReply(int sock, ObjectID object_id, PlasmaError error); + +Status ReadReleaseReply(uint8_t* data, size_t size, ObjectID* object_id); + +/* Plasma Delete objects message functions. */ + +Status SendDeleteRequest(int sock, const std::vector& object_ids); + +Status ReadDeleteRequest(uint8_t* data, size_t size, std::vector* object_ids); + +Status SendDeleteReply(int sock, const std::vector& object_ids, + const std::vector& errors); + +Status ReadDeleteReply(uint8_t* data, size_t size, std::vector* object_ids, + std::vector* errors); + +/* Plasma Contains message functions. */ + +Status SendContainsRequest(int sock, ObjectID object_id); + +Status ReadContainsRequest(uint8_t* data, size_t size, ObjectID* object_id); + +Status SendContainsReply(int sock, ObjectID object_id, bool has_object); + +Status ReadContainsReply(uint8_t* data, size_t size, ObjectID* object_id, + bool* has_object); + +/* Plasma List message functions. */ + +Status SendListRequest(int sock); + +Status ReadListRequest(uint8_t* data, size_t size); + +Status SendListReply(int sock, const ObjectTable& objects); + +Status ReadListReply(uint8_t* data, size_t size, ObjectTable* objects); + +/* Plasma Connect message functions. */ + +Status SendConnectRequest(int sock); + +Status ReadConnectRequest(uint8_t* data, size_t size); + +Status SendConnectReply(int sock, int64_t memory_capacity); + +Status ReadConnectReply(uint8_t* data, size_t size, int64_t* memory_capacity); + +/* Plasma Evict message functions (no reply so far). */ + +Status SendEvictRequest(int sock, int64_t num_bytes); + +Status ReadEvictRequest(uint8_t* data, size_t size, int64_t* num_bytes); + +Status SendEvictReply(int sock, int64_t num_bytes); + +Status ReadEvictReply(uint8_t* data, size_t size, int64_t& num_bytes); + +/* Plasma Subscribe message functions. */ + +Status SendSubscribeRequest(int sock); + +/* Data messages. */ + +Status SendDataRequest(int sock, ObjectID object_id, const char* address, int port); + +Status ReadDataRequest(uint8_t* data, size_t size, ObjectID* object_id, char** address, + int* port); + +Status SendDataReply(int sock, ObjectID object_id, int64_t object_size, + int64_t metadata_size); + +Status ReadDataReply(uint8_t* data, size_t size, ObjectID* object_id, + int64_t* object_size, int64_t* metadata_size); + +/* Plasma refresh LRU cache functions. */ + +Status SendRefreshLRURequest(int sock, const std::vector& object_ids); + +Status ReadRefreshLRURequest(uint8_t* data, size_t size, + std::vector* object_ids); + +Status SendRefreshLRUReply(int sock); + +Status ReadRefreshLRUReply(uint8_t* data, size_t size); + +} // namespace plasma + +#endif /* PLASMA_PROTOCOL */ diff --git a/src/ray/plasma/quota_aware_policy.cc b/src/ray/plasma/quota_aware_policy.cc new file mode 100644 index 000000000..67c4e9248 --- /dev/null +++ b/src/ray/plasma/quota_aware_policy.cc @@ -0,0 +1,177 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "plasma/quota_aware_policy.h" +#include "plasma/common.h" +#include "plasma/plasma_allocator.h" + +#include +#include +#include + +namespace plasma { + +QuotaAwarePolicy::QuotaAwarePolicy(PlasmaStoreInfo* store_info, int64_t max_size) + : EvictionPolicy(store_info, max_size) {} + +bool QuotaAwarePolicy::HasQuota(Client* client, bool is_create) { + if (!is_create) { + return false; // no quota enforcement on read requests yet + } + return per_client_cache_.find(client) != per_client_cache_.end(); +} + +void QuotaAwarePolicy::ObjectCreated(const ObjectID& object_id, Client* client, + bool is_create) { + if (HasQuota(client, is_create)) { + per_client_cache_[client]->Add(object_id, GetObjectSize(object_id)); + owned_by_client_[object_id] = client; + } else { + EvictionPolicy::ObjectCreated(object_id, client, is_create); + } +} + +bool QuotaAwarePolicy::SetClientQuota(Client* client, int64_t output_memory_quota) { + if (per_client_cache_.find(client) != per_client_cache_.end()) { + ARROW_LOG(WARNING) << "Cannot change the client quota once set"; + return false; + } + + if (cache_.Capacity() - output_memory_quota < + cache_.OriginalCapacity() * kGlobalLruReserveFraction) { + ARROW_LOG(WARNING) << "Not enough memory to set client quota: " << DebugString(); + return false; + } + + // those objects will be lazily evicted on the next call + cache_.AdjustCapacity(-output_memory_quota); + per_client_cache_[client] = + std::unique_ptr(new LRUCache(client->name, output_memory_quota)); + return true; +} + +bool QuotaAwarePolicy::EnforcePerClientQuota(Client* client, int64_t size, bool is_create, + std::vector* objects_to_evict) { + if (!HasQuota(client, is_create)) { + return true; + } + + auto& client_cache = per_client_cache_[client]; + if (size > client_cache->Capacity()) { + ARROW_LOG(WARNING) << "object too large (" << size + << " bytes) to fit in client quota " << client_cache->Capacity() + << " " << DebugString(); + return false; + } + + if (client_cache->RemainingCapacity() >= size) { + return true; + } + + int64_t space_to_free = size - client_cache->RemainingCapacity(); + if (space_to_free > 0) { + std::vector candidates; + client_cache->ChooseObjectsToEvict(space_to_free, &candidates); + for (ObjectID& object_id : candidates) { + if (shared_for_read_.count(object_id)) { + // Pinned so we can't evict it, so demote the object to global LRU instead. + // We an do this by simply removing it from all data structures, so that + // the next EndObjectAccess() will add it back to global LRU. + shared_for_read_.erase(object_id); + } else { + objects_to_evict->push_back(object_id); + } + owned_by_client_.erase(object_id); + client_cache->Remove(object_id); + } + } + return true; +} + +void QuotaAwarePolicy::BeginObjectAccess(const ObjectID& object_id) { + if (owned_by_client_.find(object_id) != owned_by_client_.end()) { + shared_for_read_.insert(object_id); + pinned_memory_bytes_ += GetObjectSize(object_id); + return; + } + EvictionPolicy::BeginObjectAccess(object_id); +} + +void QuotaAwarePolicy::EndObjectAccess(const ObjectID& object_id) { + if (owned_by_client_.find(object_id) != owned_by_client_.end()) { + shared_for_read_.erase(object_id); + pinned_memory_bytes_ -= GetObjectSize(object_id); + return; + } + EvictionPolicy::EndObjectAccess(object_id); +} + +void QuotaAwarePolicy::RemoveObject(const ObjectID& object_id) { + if (owned_by_client_.find(object_id) != owned_by_client_.end()) { + per_client_cache_[owned_by_client_[object_id]]->Remove(object_id); + owned_by_client_.erase(object_id); + shared_for_read_.erase(object_id); + return; + } + EvictionPolicy::RemoveObject(object_id); +} + +void QuotaAwarePolicy::RefreshObjects(const std::vector& object_ids) { + for (const auto& object_id : object_ids) { + if (owned_by_client_.find(object_id) != owned_by_client_.end()) { + int64_t size = per_client_cache_[owned_by_client_[object_id]]->Remove(object_id); + per_client_cache_[owned_by_client_[object_id]]->Add(object_id, size); + } + } + EvictionPolicy::RefreshObjects(object_ids); +} + +void QuotaAwarePolicy::ClientDisconnected(Client* client) { + if (per_client_cache_.find(client) == per_client_cache_.end()) { + return; + } + // return capacity back to global LRU + cache_.AdjustCapacity(per_client_cache_[client]->Capacity()); + // clean up any entries used to track this client's quota usage + per_client_cache_[client]->Foreach([this](const ObjectID& obj) { + if (!shared_for_read_.count(obj)) { + // only add it to the global LRU if we have it in pinned mode + // otherwise, EndObjectAccess will add it later + cache_.Add(obj, GetObjectSize(obj)); + } + owned_by_client_.erase(obj); + shared_for_read_.erase(obj); + }); + per_client_cache_.erase(client); +} + +std::string QuotaAwarePolicy::DebugString() const { + std::stringstream result; + result << "num clients with quota: " << per_client_cache_.size(); + result << "\nquota map size: " << owned_by_client_.size(); + result << "\npinned quota map size: " << shared_for_read_.size(); + result << "\nallocated bytes: " << PlasmaAllocator::Allocated(); + result << "\nallocation limit: " << PlasmaAllocator::GetFootprintLimit(); + result << "\npinned bytes: " << pinned_memory_bytes_; + result << cache_.DebugString(); + for (const auto& pair : per_client_cache_) { + result << pair.second->DebugString(); + } + return result.str(); +} + +} // namespace plasma diff --git a/src/ray/plasma/quota_aware_policy.h b/src/ray/plasma/quota_aware_policy.h new file mode 100644 index 000000000..953f0bcdd --- /dev/null +++ b/src/ray/plasma/quota_aware_policy.h @@ -0,0 +1,91 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_QUOTA_AWARE_POLICY_H +#define PLASMA_QUOTA_AWARE_POLICY_H + +#include +#include +#include +#include +#include +#include +#include + +#include "plasma/common.h" +#include "plasma/eviction_policy.h" +#include "plasma/plasma.h" + +namespace plasma { + +/// Reserve this fraction of memory for shared usage. Attempts to set client +/// quotas that would cause the global LRU memory fraction to fall below this +/// value will be rejected. +constexpr double kGlobalLruReserveFraction = 0.3; + +/// Extends the basic eviction policy to implement per-client memory quotas. +/// This effectively gives each client its own LRU queue, which caps its +/// memory usage and protects this memory from being evicted by other clients. +/// +/// The quotas are enforced when objects are first created, by evicting the +/// necessary number of objects from the client's own LRU queue to cap its +/// memory usage. Once that is done, allocation is handled by the normal +/// eviction policy. This may result in the eviction of objects from the +/// global LRU queue, if not enough memory can be allocated even after the +/// evictions from the client's own LRU queue. +/// +/// Some special cases: +/// - When a pinned object is "evicted" from a per-client queue, it is +/// instead transferred into the global LRU queue. +/// - When a client disconnects, its LRU queue is merged into the head of the +/// global LRU queue. +class QuotaAwarePolicy : public EvictionPolicy { + public: + /// Construct a quota-aware eviction policy. + /// + /// \param store_info Information about the Plasma store that is exposed + /// to the eviction policy. + /// \param max_size Max size in bytes total of objects to store. + explicit QuotaAwarePolicy(PlasmaStoreInfo* store_info, int64_t max_size); + void ObjectCreated(const ObjectID& object_id, Client* client, bool is_create) override; + bool SetClientQuota(Client* client, int64_t output_memory_quota) override; + bool EnforcePerClientQuota(Client* client, int64_t size, bool is_create, + std::vector* objects_to_evict) override; + void ClientDisconnected(Client* client) override; + void BeginObjectAccess(const ObjectID& object_id) override; + void EndObjectAccess(const ObjectID& object_id) override; + void RemoveObject(const ObjectID& object_id) override; + void RefreshObjects(const std::vector& object_ids) override; + std::string DebugString() const override; + + private: + /// Returns whether we are enforcing memory quotas for an operation. + bool HasQuota(Client* client, bool is_create); + + /// Per-client LRU caches, if quota is enabled. + std::unordered_map> per_client_cache_; + /// Tracks which client created which object. This only applies to clients + /// that have a memory quota set. + std::unordered_map owned_by_client_; + /// Tracks which objects are mapped for read and hence can't be evicted. + /// However these objects are still tracked within the client caches. + std::unordered_set shared_for_read_; +}; + +} // namespace plasma + +#endif // PLASMA_EVICTION_POLICY_H diff --git a/src/ray/plasma/store.cc b/src/ray/plasma/store.cc new file mode 100644 index 000000000..c11085b52 --- /dev/null +++ b/src/ray/plasma/store.cc @@ -0,0 +1,1330 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// PLASMA STORE: This is a simple object store server process +// +// It accepts incoming client connections on a unix domain socket +// (name passed in via the -s option of the executable) and uses a +// single thread to serve the clients. Each client establishes a +// connection and can create objects, wait for objects and seal +// objects through that connection. +// +// It keeps a hash table that maps object_ids (which are 20 byte long, +// just enough to store and SHA1 hash) to memory mapped files. + +#include "plasma/store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/status.h" + +#include "plasma/common.h" +#include "plasma/common_generated.h" +#include "plasma/fling.h" +#include "plasma/io.h" +#include "plasma/malloc.h" +#include "plasma/plasma_allocator.h" +#include "plasma/protocol.h" + +#ifdef PLASMA_CUDA +#include "arrow/gpu/cuda_api.h" + +using arrow::cuda::CudaBuffer; +using arrow::cuda::CudaContext; +using arrow::cuda::CudaDeviceManager; +#endif + +using arrow::util::ArrowLog; +using arrow::util::ArrowLogLevel; + +namespace fb = plasma::flatbuf; + +namespace plasma { + +void SetMallocGranularity(int value); + +struct GetRequest { + GetRequest(Client* client, const std::vector& object_ids); + /// The client that called get. + Client* client; + /// The ID of the timer that will time out and cause this wait to return to + /// the client if it hasn't already returned. + int64_t timer; + /// The object IDs involved in this request. This is used in the reply. + std::vector object_ids; + /// The object information for the objects in this request. This is used in + /// the reply. + std::unordered_map objects; + /// The minimum number of objects to wait for in this request. + int64_t num_objects_to_wait_for; + /// The number of object requests in this wait request that are already + /// satisfied. + int64_t num_satisfied; +}; + +GetRequest::GetRequest(Client* client, const std::vector& object_ids) + : client(client), + timer(-1), + object_ids(object_ids.begin(), object_ids.end()), + objects(object_ids.size()), + num_satisfied(0) { + std::unordered_set unique_ids(object_ids.begin(), object_ids.end()); + num_objects_to_wait_for = unique_ids.size(); +} + +Client::Client(int fd) : fd(fd), notification_fd(-1) {} + +PlasmaStore::PlasmaStore(EventLoop* loop, std::string directory, bool hugepages_enabled, + const std::string& socket_name, + std::shared_ptr external_store) + : loop_(loop), + eviction_policy_(&store_info_, PlasmaAllocator::GetFootprintLimit()), + external_store_(external_store) { + store_info_.directory = directory; + store_info_.hugepages_enabled = hugepages_enabled; +#ifdef PLASMA_CUDA + auto maybe_manager = CudaDeviceManager::Instance(); + DCHECK_OK(maybe_manager.status()); + manager_ = *maybe_manager; +#endif +} + +// TODO(pcm): Get rid of this destructor by using RAII to clean up data. +PlasmaStore::~PlasmaStore() {} + +const PlasmaStoreInfo* PlasmaStore::GetPlasmaStoreInfo() { return &store_info_; } + +// If this client is not already using the object, add the client to the +// object's list of clients, otherwise do nothing. +void PlasmaStore::AddToClientObjectIds(const ObjectID& object_id, ObjectTableEntry* entry, + Client* client) { + // Check if this client is already using the object. + if (client->object_ids.find(object_id) != client->object_ids.end()) { + return; + } + // If there are no other clients using this object, notify the eviction policy + // that the object is being used. + if (entry->ref_count == 0) { + // Tell the eviction policy that this object is being used. + eviction_policy_.BeginObjectAccess(object_id); + } + // Increase reference count. + entry->ref_count++; + + // Add object id to the list of object ids that this client is using. + client->object_ids.insert(object_id); +} + +// Allocate memory +uint8_t* PlasmaStore::AllocateMemory(size_t size, bool evict_if_full, int* fd, + int64_t* map_size, ptrdiff_t* offset, Client* client, + bool is_create) { + // First free up space from the client's LRU queue if quota enforcement is on. + if (evict_if_full) { + std::vector client_objects_to_evict; + bool quota_ok = eviction_policy_.EnforcePerClientQuota(client, size, is_create, + &client_objects_to_evict); + if (!quota_ok) { + return nullptr; + } + EvictObjects(client_objects_to_evict); + } + + // Try to evict objects until there is enough space. + uint8_t* pointer = nullptr; + while (true) { + // Allocate space for the new object. We use memalign instead of malloc + // in order to align the allocated region to a 64-byte boundary. This is not + // strictly necessary, but it is an optimization that could speed up the + // computation of a hash of the data (see compute_object_hash_parallel in + // plasma_client.cc). Note that even though this pointer is 64-byte aligned, + // it is not guaranteed that the corresponding pointer in the client will be + // 64-byte aligned, but in practice it often will be. + pointer = reinterpret_cast(PlasmaAllocator::Memalign(kBlockSize, size)); + if (pointer || !evict_if_full) { + // If we manage to allocate the memory, return the pointer. If we cannot + // allocate the space, but we are also not allowed to evict anything to + // make more space, return an error to the client. + break; + } + // Tell the eviction policy how much space we need to create this object. + std::vector objects_to_evict; + bool success = eviction_policy_.RequireSpace(size, &objects_to_evict); + EvictObjects(objects_to_evict); + // Return an error to the client if not enough space could be freed to + // create the object. + if (!success) { + break; + } + } + + if (pointer != nullptr) { + GetMallocMapinfo(pointer, fd, map_size, offset); + ARROW_CHECK(*fd != -1); + } + return pointer; +} + +#ifdef PLASMA_CUDA +Status PlasmaStore::AllocateCudaMemory( + int device_num, int64_t size, uint8_t** out_pointer, + std::shared_ptr* out_ipc_handle) { + DCHECK_NE(device_num, 0); + ARROW_ASSIGN_OR_RAISE(auto context, manager_->GetContext(device_num - 1)); + ARROW_ASSIGN_OR_RAISE(auto cuda_buffer, context->Allocate(static_cast(size))); + *out_pointer = reinterpret_cast(cuda_buffer->address()); + // The IPC handle will keep the buffer memory alive + return cuda_buffer->ExportForIpc().Value(out_ipc_handle); +} + +Status PlasmaStore::FreeCudaMemory(int device_num, int64_t size, uint8_t* pointer) { + ARROW_ASSIGN_OR_RAISE(auto context, manager_->GetContext(device_num - 1)); + RETURN_NOT_OK(context->Free(pointer, size)); + return Status::OK(); +} +#endif + +// Create a new object buffer in the hash table. +PlasmaError PlasmaStore::CreateObject(const ObjectID& object_id, bool evict_if_full, + int64_t data_size, int64_t metadata_size, + int device_num, Client* client, + PlasmaObject* result) { + ARROW_LOG(DEBUG) << "creating object " << object_id.hex(); + + auto entry = GetObjectTableEntry(&store_info_, object_id); + if (entry != nullptr) { + // There is already an object with the same ID in the Plasma Store, so + // ignore this request. + return PlasmaError::ObjectExists; + } + + int fd = -1; + int64_t map_size = 0; + ptrdiff_t offset = 0; + uint8_t* pointer = nullptr; + auto total_size = data_size + metadata_size; + + if (device_num == 0) { + pointer = + AllocateMemory(total_size, evict_if_full, &fd, &map_size, &offset, client, true); + if (!pointer) { + ARROW_LOG(ERROR) << "Not enough memory to create the object " << object_id.hex() + << ", data_size=" << data_size + << ", metadata_size=" << metadata_size + << ", will send a reply of PlasmaError::OutOfMemory"; + return PlasmaError::OutOfMemory; + } + } else { +#ifdef PLASMA_CUDA + /// IPC GPU handle to share with clients. + std::shared_ptr<::arrow::cuda::CudaIpcMemHandle> ipc_handle; + auto st = AllocateCudaMemory(device_num, total_size, &pointer, &ipc_handle); + if (!st.ok()) { + ARROW_LOG(ERROR) << "Failed to allocate CUDA memory: " << st.ToString(); + return PlasmaError::OutOfMemory; + } + result->ipc_handle = ipc_handle; +#else + ARROW_LOG(ERROR) << "device_num != 0 but CUDA not enabled"; + return PlasmaError::OutOfMemory; +#endif + } + + auto ptr = std::unique_ptr(new ObjectTableEntry()); + entry = store_info_.objects.emplace(object_id, std::move(ptr)).first->second.get(); + entry->data_size = data_size; + entry->metadata_size = metadata_size; + entry->pointer = pointer; + // TODO(pcm): Set the other fields. + entry->fd = fd; + entry->map_size = map_size; + entry->offset = offset; + entry->state = ObjectState::PLASMA_CREATED; + entry->device_num = device_num; + entry->create_time = std::time(nullptr); + entry->construct_duration = -1; + +#ifdef PLASMA_CUDA + entry->ipc_handle = result->ipc_handle; +#endif + + result->store_fd = fd; + result->data_offset = offset; + result->metadata_offset = offset + data_size; + result->data_size = data_size; + result->metadata_size = metadata_size; + result->device_num = device_num; + // Notify the eviction policy that this object was created. This must be done + // immediately before the call to AddToClientObjectIds so that the + // eviction policy does not have an opportunity to evict the object. + eviction_policy_.ObjectCreated(object_id, client, true); + // Record that this client is using this object. + AddToClientObjectIds(object_id, store_info_.objects[object_id].get(), client); + return PlasmaError::OK; +} + +void PlasmaObject_init(PlasmaObject* object, ObjectTableEntry* entry) { + DCHECK(object != nullptr); + DCHECK(entry != nullptr); + DCHECK(entry->state == ObjectState::PLASMA_SEALED); +#ifdef PLASMA_CUDA + if (entry->device_num != 0) { + object->ipc_handle = entry->ipc_handle; + } +#endif + object->store_fd = entry->fd; + object->data_offset = entry->offset; + object->metadata_offset = entry->offset + entry->data_size; + object->data_size = entry->data_size; + object->metadata_size = entry->metadata_size; + object->device_num = entry->device_num; +} + +void PlasmaStore::RemoveGetRequest(GetRequest* get_request) { + // Remove the get request from each of the relevant object_get_requests hash + // tables if it is present there. It should only be present there if the get + // request timed out or if it was issued by a client that has disconnected. + for (ObjectID& object_id : get_request->object_ids) { + auto object_request_iter = object_get_requests_.find(object_id); + if (object_request_iter != object_get_requests_.end()) { + auto& get_requests = object_request_iter->second; + // Erase get_req from the vector. + auto it = std::find(get_requests.begin(), get_requests.end(), get_request); + if (it != get_requests.end()) { + get_requests.erase(it); + // If the vector is empty, remove the object ID from the map. + if (get_requests.empty()) { + object_get_requests_.erase(object_request_iter); + } + } + } + } + // Remove the get request. + if (get_request->timer != -1) { + ARROW_CHECK(loop_->RemoveTimer(get_request->timer) == kEventLoopOk); + } + delete get_request; +} + +void PlasmaStore::RemoveGetRequestsForClient(Client* client) { + std::unordered_set get_requests_to_remove; + for (auto const& pair : object_get_requests_) { + for (GetRequest* get_request : pair.second) { + if (get_request->client == client) { + get_requests_to_remove.insert(get_request); + } + } + } + + // It shouldn't be possible for a given client to be in the middle of multiple get + // requests. + ARROW_CHECK(get_requests_to_remove.size() <= 1); + for (GetRequest* get_request : get_requests_to_remove) { + RemoveGetRequest(get_request); + } +} + +void PlasmaStore::ReturnFromGet(GetRequest* get_req) { + // Figure out how many file descriptors we need to send. + std::unordered_set fds_to_send; + std::vector store_fds; + std::vector mmap_sizes; + for (const auto& object_id : get_req->object_ids) { + PlasmaObject& object = get_req->objects[object_id]; + int fd = object.store_fd; + if (object.data_size != -1 && fds_to_send.count(fd) == 0 && fd != -1) { + fds_to_send.insert(fd); + store_fds.push_back(fd); + mmap_sizes.push_back(GetMmapSize(fd)); + } + } + + // Send the get reply to the client. + Status s = SendGetReply(get_req->client->fd, &get_req->object_ids[0], get_req->objects, + get_req->object_ids.size(), store_fds, mmap_sizes); + WarnIfSigpipe(s.ok() ? 0 : -1, get_req->client->fd); + // If we successfully sent the get reply message to the client, then also send + // the file descriptors. + if (s.ok()) { + // Send all of the file descriptors for the present objects. + for (int store_fd : store_fds) { + // Only send the file descriptor if it hasn't been sent (see analogous + // logic in GetStoreFd in client.cc). + if (get_req->client->used_fds.find(store_fd) == get_req->client->used_fds.end()) { + WarnIfSigpipe(send_fd(get_req->client->fd, store_fd), get_req->client->fd); + get_req->client->used_fds.insert(store_fd); + } + } + } + + // Remove the get request from each of the relevant object_get_requests hash + // tables if it is present there. It should only be present there if the get + // request timed out. + RemoveGetRequest(get_req); +} + +void PlasmaStore::UpdateObjectGetRequests(const ObjectID& object_id) { + auto it = object_get_requests_.find(object_id); + // If there are no get requests involving this object, then return. + if (it == object_get_requests_.end()) { + return; + } + + auto& get_requests = it->second; + + // After finishing the loop below, get_requests and it will have been + // invalidated by the removal of object_id from object_get_requests_. + size_t index = 0; + size_t num_requests = get_requests.size(); + for (size_t i = 0; i < num_requests; ++i) { + auto get_req = get_requests[index]; + auto entry = GetObjectTableEntry(&store_info_, object_id); + ARROW_CHECK(entry != nullptr); + + PlasmaObject_init(&get_req->objects[object_id], entry); + get_req->num_satisfied += 1; + // Record the fact that this client will be using this object and will + // be responsible for releasing this object. + AddToClientObjectIds(object_id, entry, get_req->client); + + // If this get request is done, reply to the client. + if (get_req->num_satisfied == get_req->num_objects_to_wait_for) { + ReturnFromGet(get_req); + } else { + // The call to ReturnFromGet will remove the current element in the + // array, so we only increment the counter in the else branch. + index += 1; + } + } + + // No get requests should be waiting for this object anymore. The object ID + // may have been removed from the object_get_requests_ by ReturnFromGet, but + // if the get request has not returned yet, then remove the object ID from the + // map here. + it = object_get_requests_.find(object_id); + if (it != object_get_requests_.end()) { + object_get_requests_.erase(object_id); + } +} + +void PlasmaStore::ProcessGetRequest(Client* client, + const std::vector& object_ids, + int64_t timeout_ms) { + // Create a get request for this object. + auto get_req = new GetRequest(client, object_ids); + std::vector evicted_ids; + std::vector evicted_entries; + for (auto object_id : object_ids) { + // Check if this object is already present locally. If so, record that the + // object is being used and mark it as accounted for. + auto entry = GetObjectTableEntry(&store_info_, object_id); + if (entry && entry->state == ObjectState::PLASMA_SEALED) { + // Update the get request to take into account the present object. + PlasmaObject_init(&get_req->objects[object_id], entry); + get_req->num_satisfied += 1; + // If necessary, record that this client is using this object. In the case + // where entry == NULL, this will be called from SealObject. + AddToClientObjectIds(object_id, entry, client); + } else if (entry && entry->state == ObjectState::PLASMA_EVICTED) { + // Make sure the object pointer is not already allocated + ARROW_CHECK(!entry->pointer); + + entry->pointer = + AllocateMemory(entry->data_size + entry->metadata_size, /*evict=*/true, + &entry->fd, &entry->map_size, &entry->offset, client, false); + if (entry->pointer) { + entry->state = ObjectState::PLASMA_CREATED; + entry->create_time = std::time(nullptr); + eviction_policy_.ObjectCreated(object_id, client, false); + AddToClientObjectIds(object_id, store_info_.objects[object_id].get(), client); + evicted_ids.push_back(object_id); + evicted_entries.push_back(entry); + } else { + // We are out of memory and cannot allocate memory for this object. + // Change the state of the object back to PLASMA_EVICTED so some + // other request can try again. + entry->state = ObjectState::PLASMA_EVICTED; + } + } else { + // Add a placeholder plasma object to the get request to indicate that the + // object is not present. This will be parsed by the client. We set the + // data size to -1 to indicate that the object is not present. + get_req->objects[object_id].data_size = -1; + // Add the get request to the relevant data structures. + object_get_requests_[object_id].push_back(get_req); + } + } + + if (!evicted_ids.empty()) { + unsigned char digest[kDigestSize]; + std::vector> buffers; + for (size_t i = 0; i < evicted_ids.size(); ++i) { + ARROW_CHECK(evicted_entries[i]->pointer != nullptr); + buffers.emplace_back(new arrow::MutableBuffer(evicted_entries[i]->pointer, + evicted_entries[i]->data_size)); + } + if (external_store_->Get(evicted_ids, buffers).ok()) { + for (size_t i = 0; i < evicted_ids.size(); ++i) { + evicted_entries[i]->state = ObjectState::PLASMA_SEALED; + std::memcpy(&evicted_entries[i]->digest[0], &digest[0], kDigestSize); + evicted_entries[i]->construct_duration = + std::time(nullptr) - evicted_entries[i]->create_time; + PlasmaObject_init(&get_req->objects[evicted_ids[i]], evicted_entries[i]); + get_req->num_satisfied += 1; + } + } else { + // We tried to get the objects from the external store, but could not get them. + // Set the state of these objects back to PLASMA_EVICTED so some other request + // can try again. + for (size_t i = 0; i < evicted_ids.size(); ++i) { + evicted_entries[i]->state = ObjectState::PLASMA_EVICTED; + } + } + } + + // If all of the objects are present already or if the timeout is 0, return to + // the client. + if (get_req->num_satisfied == get_req->num_objects_to_wait_for || timeout_ms == 0) { + ReturnFromGet(get_req); + } else if (timeout_ms != -1) { + // Set a timer that will cause the get request to return to the client. Note + // that a timeout of -1 is used to indicate that no timer should be set. + get_req->timer = loop_->AddTimer(timeout_ms, [this, get_req](int64_t timer_id) { + ReturnFromGet(get_req); + return kEventLoopTimerDone; + }); + } +} + +int PlasmaStore::RemoveFromClientObjectIds(const ObjectID& object_id, + ObjectTableEntry* entry, Client* client) { + auto it = client->object_ids.find(object_id); + if (it != client->object_ids.end()) { + client->object_ids.erase(it); + // Decrease reference count. + entry->ref_count--; + + // If no more clients are using this object, notify the eviction policy + // that the object is no longer being used. + if (entry->ref_count == 0) { + if (deletion_cache_.count(object_id) == 0) { + // Tell the eviction policy that this object is no longer being used. + eviction_policy_.EndObjectAccess(object_id); + } else { + // Above code does not really delete an object. Instead, it just put an + // object to LRU cache which will be cleaned when the memory is not enough. + deletion_cache_.erase(object_id); + EvictObjects({object_id}); + } + } + // Return 1 to indicate that the client was removed. + return 1; + } else { + // Return 0 to indicate that the client was not removed. + return 0; + } +} + +void PlasmaStore::EraseFromObjectTable(const ObjectID& object_id) { + auto& object = store_info_.objects[object_id]; + auto buff_size = object->data_size + object->metadata_size; + if (object->device_num == 0) { + PlasmaAllocator::Free(object->pointer, buff_size); + } else { +#ifdef PLASMA_CUDA + ARROW_CHECK_OK(FreeCudaMemory(object->device_num, buff_size, object->pointer)); +#endif + } + store_info_.objects.erase(object_id); +} + +void PlasmaStore::ReleaseObject(const ObjectID& object_id, Client* client) { + auto entry = GetObjectTableEntry(&store_info_, object_id); + ARROW_CHECK(entry != nullptr); + // Remove the client from the object's array of clients. + ARROW_CHECK(RemoveFromClientObjectIds(object_id, entry, client) == 1); +} + +// Check if an object is present. +ObjectStatus PlasmaStore::ContainsObject(const ObjectID& object_id) { + auto entry = GetObjectTableEntry(&store_info_, object_id); + return entry && (entry->state == ObjectState::PLASMA_SEALED || + entry->state == ObjectState::PLASMA_EVICTED) + ? ObjectStatus::OBJECT_FOUND + : ObjectStatus::OBJECT_NOT_FOUND; +} + +void PlasmaStore::SealObjects(const std::vector& object_ids, + const std::vector& digests) { + std::vector infos; + + ARROW_LOG(DEBUG) << "sealing " << object_ids.size() << " objects"; + for (size_t i = 0; i < object_ids.size(); ++i) { + ObjectInfoT object_info; + auto entry = GetObjectTableEntry(&store_info_, object_ids[i]); + ARROW_CHECK(entry != nullptr); + ARROW_CHECK(entry->state == ObjectState::PLASMA_CREATED); + // Set the state of object to SEALED. + entry->state = ObjectState::PLASMA_SEALED; + // Set the object digest. + std::memcpy(&entry->digest[0], digests[i].c_str(), kDigestSize); + // Set object construction duration. + entry->construct_duration = std::time(nullptr) - entry->create_time; + + object_info.object_id = object_ids[i].binary(); + object_info.data_size = entry->data_size; + object_info.metadata_size = entry->metadata_size; + object_info.digest = digests[i]; + infos.push_back(object_info); + } + + PushNotifications(infos); + + for (size_t i = 0; i < object_ids.size(); ++i) { + UpdateObjectGetRequests(object_ids[i]); + } +} + +int PlasmaStore::AbortObject(const ObjectID& object_id, Client* client) { + auto entry = GetObjectTableEntry(&store_info_, object_id); + ARROW_CHECK(entry != nullptr) << "To abort an object it must be in the object table."; + ARROW_CHECK(entry->state != ObjectState::PLASMA_SEALED) + << "To abort an object it must not have been sealed."; + auto it = client->object_ids.find(object_id); + if (it == client->object_ids.end()) { + // If the client requesting the abort is not the creator, do not + // perform the abort. + return 0; + } else { + // The client requesting the abort is the creator. Free the object. + EraseFromObjectTable(object_id); + client->object_ids.erase(it); + return 1; + } +} + +PlasmaError PlasmaStore::DeleteObject(ObjectID& object_id) { + auto entry = GetObjectTableEntry(&store_info_, object_id); + // TODO(rkn): This should probably not fail, but should instead throw an + // error. Maybe we should also support deleting objects that have been + // created but not sealed. + if (entry == nullptr) { + // To delete an object it must be in the object table. + return PlasmaError::ObjectNonexistent; + } + + if (entry->state != ObjectState::PLASMA_SEALED) { + // To delete an object it must have been sealed. + // Put it into deletion cache, it will be deleted later. + deletion_cache_.emplace(object_id); + return PlasmaError::ObjectNotSealed; + } + + if (entry->ref_count != 0) { + // To delete an object, there must be no clients currently using it. + // Put it into deletion cache, it will be deleted later. + deletion_cache_.emplace(object_id); + return PlasmaError::ObjectInUse; + } + + eviction_policy_.RemoveObject(object_id); + EraseFromObjectTable(object_id); + // Inform all subscribers that the object has been deleted. + fb::ObjectInfoT notification; + notification.object_id = object_id.binary(); + notification.is_deletion = true; + PushNotification(¬ification); + + return PlasmaError::OK; +} + +void PlasmaStore::EvictObjects(const std::vector& object_ids) { + if (object_ids.size() == 0) { + return; + } + + std::vector> evicted_object_data; + std::vector evicted_entries; + for (const auto& object_id : object_ids) { + ARROW_LOG(DEBUG) << "evicting object " << object_id.hex(); + auto entry = GetObjectTableEntry(&store_info_, object_id); + // TODO(rkn): This should probably not fail, but should instead throw an + // error. Maybe we should also support deleting objects that have been + // created but not sealed. + ARROW_CHECK(entry != nullptr) << "To evict an object it must be in the object table."; + ARROW_CHECK(entry->state == ObjectState::PLASMA_SEALED) + << "To evict an object it must have been sealed."; + ARROW_CHECK(entry->ref_count == 0) + << "To evict an object, there must be no clients currently using it."; + + // If there is a backing external store, then mark object for eviction to + // external store, free the object data pointer and keep a placeholder + // entry in ObjectTable + if (external_store_) { + evicted_object_data.push_back(std::make_shared( + entry->pointer, entry->data_size + entry->metadata_size)); + evicted_entries.push_back(entry); + } else { + // If there is no backing external store, just erase the object entry + // and send a deletion notification. + EraseFromObjectTable(object_id); + // Inform all subscribers that the object has been deleted. + fb::ObjectInfoT notification; + notification.object_id = object_id.binary(); + notification.is_deletion = true; + PushNotification(¬ification); + } + } + + if (external_store_ && !object_ids.empty()) { + ARROW_CHECK_OK(external_store_->Put(object_ids, evicted_object_data)); + for (auto entry : evicted_entries) { + PlasmaAllocator::Free(entry->pointer, entry->data_size + entry->metadata_size); + entry->pointer = nullptr; + entry->state = ObjectState::PLASMA_EVICTED; + } + } +} + +void PlasmaStore::ConnectClient(int listener_sock) { + int client_fd = AcceptClient(listener_sock); + + Client* client = new Client(client_fd); + connected_clients_[client_fd] = std::unique_ptr(client); + + // Add a callback to handle events on this socket. + // TODO(pcm): Check return value. + loop_->AddFileEvent(client_fd, kEventLoopRead, [this, client](int events) { + Status s = ProcessMessage(client); + if (!s.ok()) { + ARROW_LOG(FATAL) << "Failed to process file event: " << s; + } + }); + ARROW_LOG(DEBUG) << "New connection with fd " << client_fd; +} + +void PlasmaStore::DisconnectClient(int client_fd) { + ARROW_CHECK(client_fd > 0); + auto it = connected_clients_.find(client_fd); + ARROW_CHECK(it != connected_clients_.end()); + loop_->RemoveFileEvent(client_fd); + // Close the socket. + close(client_fd); + ARROW_LOG(INFO) << "Disconnecting client on fd " << client_fd; + // Release all the objects that the client was using. + auto client = it->second.get(); + eviction_policy_.ClientDisconnected(client); + std::unordered_map sealed_objects; + for (const auto& object_id : client->object_ids) { + auto it = store_info_.objects.find(object_id); + if (it == store_info_.objects.end()) { + continue; + } + + if (it->second->state == ObjectState::PLASMA_SEALED) { + // Add sealed objects to a temporary list of object IDs. Do not perform + // the remove here, since it potentially modifies the object_ids table. + sealed_objects[it->first] = it->second.get(); + } else { + // Abort unsealed object. + // Don't call AbortObject() because client->object_ids would be modified. + EraseFromObjectTable(object_id); + } + } + + /// Remove all of the client's GetRequests. + RemoveGetRequestsForClient(client); + + for (const auto& entry : sealed_objects) { + RemoveFromClientObjectIds(entry.first, entry.second, client); + } + + if (client->notification_fd > 0) { + // This client has subscribed for notifications. + auto notify_fd = client->notification_fd; + loop_->RemoveFileEvent(notify_fd); + // Close socket. + close(notify_fd); + // Remove notification queue for this fd from global map. + pending_notifications_.erase(notify_fd); + // Reset fd. + client->notification_fd = -1; + } + + connected_clients_.erase(it); +} + +/// Send notifications about sealed objects to the subscribers. This is called +/// in SealObject. If the socket's send buffer is full, the notification will +/// be buffered, and this will be called again when the send buffer has room. +/// Since we call erase on pending_notifications_, all iterators get +/// invalidated, which is why we return a valid iterator to the next client to +/// be used in PushNotification. +/// +/// \param it Iterator that points to the client to send the notification to. +/// \return Iterator pointing to the next client. +PlasmaStore::NotificationMap::iterator PlasmaStore::SendNotifications( + PlasmaStore::NotificationMap::iterator it) { + int client_fd = it->first; + auto& notifications = it->second.object_notifications; + + int num_processed = 0; + bool closed = false; + // Loop over the array of pending notifications and send as many of them as + // possible. + for (size_t i = 0; i < notifications.size(); ++i) { + auto& notification = notifications.at(i); + // Decode the length, which is the first bytes of the message. + int64_t size = *(reinterpret_cast(notification.get())); + + // Attempt to send a notification about this object ID. + ssize_t nbytes = send(client_fd, notification.get(), sizeof(int64_t) + size, 0); + if (nbytes >= 0) { + ARROW_CHECK(nbytes == static_cast(sizeof(int64_t)) + size); + } else if (nbytes == -1 && + (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { + ARROW_LOG(DEBUG) << "The socket's send buffer is full, so we are caching this " + "notification and will send it later."; + // Add a callback to the event loop to send queued notifications whenever + // there is room in the socket's send buffer. Callbacks can be added + // more than once here and will be overwritten. The callback is removed + // at the end of the method. + // TODO(pcm): Introduce status codes and check in case the file descriptor + // is added twice. + loop_->AddFileEvent(client_fd, kEventLoopWrite, [this, client_fd](int events) { + SendNotifications(pending_notifications_.find(client_fd)); + }); + break; + } else { + ARROW_LOG(WARNING) << "Failed to send notification to client on fd " << client_fd; + if (errno == EPIPE) { + closed = true; + break; + } + } + num_processed += 1; + } + // Remove the sent notifications from the array. + notifications.erase(notifications.begin(), notifications.begin() + num_processed); + + // If we have sent all notifications, remove the fd from the event loop. + if (notifications.empty()) { + loop_->RemoveFileEvent(client_fd); + } + + // Stop sending notifications if the pipe was broken. + if (closed) { + close(client_fd); + return pending_notifications_.erase(it); + } else { + return ++it; + } +} + +void PlasmaStore::PushNotification(fb::ObjectInfoT* object_info) { + auto it = pending_notifications_.begin(); + while (it != pending_notifications_.end()) { + std::vector info; + info.push_back(*object_info); + auto notification = CreatePlasmaNotificationBuffer(info); + it->second.object_notifications.emplace_back(std::move(notification)); + it = SendNotifications(it); + } +} + +void PlasmaStore::PushNotifications(std::vector& object_info) { + auto it = pending_notifications_.begin(); + while (it != pending_notifications_.end()) { + auto notifications = CreatePlasmaNotificationBuffer(object_info); + it->second.object_notifications.emplace_back(std::move(notifications)); + it = SendNotifications(it); + } +} + +void PlasmaStore::PushNotification(fb::ObjectInfoT* object_info, int client_fd) { + auto it = pending_notifications_.find(client_fd); + if (it != pending_notifications_.end()) { + std::vector info; + info.push_back(*object_info); + auto notification = CreatePlasmaNotificationBuffer(info); + it->second.object_notifications.emplace_back(std::move(notification)); + SendNotifications(it); + } +} + +// Subscribe to notifications about sealed objects. +void PlasmaStore::SubscribeToUpdates(Client* client) { + ARROW_LOG(DEBUG) << "subscribing to updates on fd " << client->fd; + if (client->notification_fd > 0) { + // This client has already subscribed. Return. + return; + } + + // TODO(rkn): The store could block here if the client doesn't send a file + // descriptor. + int fd = recv_fd(client->fd); + if (fd < 0) { + // This may mean that the client died before sending the file descriptor. + ARROW_LOG(WARNING) << "Failed to receive file descriptor from client on fd " + << client->fd << "."; + return; + } + + // Add this fd to global map, which is needed for this client to receive notifications. + pending_notifications_[fd]; + client->notification_fd = fd; + + // Push notifications to the new subscriber about existing sealed objects. + for (const auto& entry : store_info_.objects) { + if (entry.second->state == ObjectState::PLASMA_SEALED) { + ObjectInfoT info; + info.object_id = entry.first.binary(); + info.data_size = entry.second->data_size; + info.metadata_size = entry.second->metadata_size; + info.digest = + std::string(reinterpret_cast(&entry.second->digest[0]), kDigestSize); + PushNotification(&info, fd); + } + } +} + +Status PlasmaStore::ProcessMessage(Client* client) { + fb::MessageType type; + Status s = ReadMessage(client->fd, &type, &input_buffer_); + ARROW_CHECK(s.ok() || s.IsIOError()); + + uint8_t* input = input_buffer_.data(); + size_t input_size = input_buffer_.size(); + ObjectID object_id; + PlasmaObject object = {}; + + // Process the different types of requests. + switch (type) { + case fb::MessageType::PlasmaCreateRequest: { + bool evict_if_full; + int64_t data_size; + int64_t metadata_size; + int device_num; + RETURN_NOT_OK(ReadCreateRequest(input, input_size, &object_id, &evict_if_full, + &data_size, &metadata_size, &device_num)); + PlasmaError error_code = CreateObject(object_id, evict_if_full, data_size, + metadata_size, device_num, client, &object); + int64_t mmap_size = 0; + if (error_code == PlasmaError::OK && device_num == 0) { + mmap_size = GetMmapSize(object.store_fd); + } + HANDLE_SIGPIPE( + SendCreateReply(client->fd, object_id, &object, error_code, mmap_size), + client->fd); + // Only send the file descriptor if it hasn't been sent (see analogous + // logic in GetStoreFd in client.cc). Similar in ReturnFromGet. + if (error_code == PlasmaError::OK && device_num == 0 && + client->used_fds.find(object.store_fd) == client->used_fds.end()) { + WarnIfSigpipe(send_fd(client->fd, object.store_fd), client->fd); + client->used_fds.insert(object.store_fd); + } + } break; + case fb::MessageType::PlasmaCreateAndSealRequest: { + bool evict_if_full; + std::string data; + std::string metadata; + std::string digest; + digest.reserve(kDigestSize); + RETURN_NOT_OK(ReadCreateAndSealRequest(input, input_size, &object_id, + &evict_if_full, &data, &metadata, &digest)); + // CreateAndSeal currently only supports device_num = 0, which corresponds + // to the host. + int device_num = 0; + PlasmaError error_code = CreateObject(object_id, evict_if_full, data.size(), + metadata.size(), device_num, client, &object); + + // If the object was successfully created, fill out the object data and seal it. + if (error_code == PlasmaError::OK) { + auto entry = GetObjectTableEntry(&store_info_, object_id); + ARROW_CHECK(entry != nullptr); + // Write the inlined data and metadata into the allocated object. + std::memcpy(entry->pointer, data.data(), data.size()); + std::memcpy(entry->pointer + data.size(), metadata.data(), metadata.size()); + SealObjects({object_id}, {digest}); + // Remove the client from the object's array of clients because the + // object is not being used by any client. The client was added to the + // object's array of clients in CreateObject. This is analogous to the + // Release call that happens in the client's Seal method. + ARROW_CHECK(RemoveFromClientObjectIds(object_id, entry, client) == 1); + } + + // Reply to the client. + HANDLE_SIGPIPE(SendCreateAndSealReply(client->fd, error_code), client->fd); + } break; + case fb::MessageType::PlasmaCreateAndSealBatchRequest: { + bool evict_if_full; + std::vector object_ids; + std::vector data; + std::vector metadata; + std::vector digests; + + RETURN_NOT_OK(ReadCreateAndSealBatchRequest( + input, input_size, &object_ids, &evict_if_full, &data, &metadata, &digests)); + + // CreateAndSeal currently only supports device_num = 0, which corresponds + // to the host. + int device_num = 0; + size_t i = 0; + PlasmaError error_code = PlasmaError::OK; + for (i = 0; i < object_ids.size(); i++) { + error_code = CreateObject(object_ids[i], evict_if_full, data[i].size(), + metadata[i].size(), device_num, client, &object); + if (error_code != PlasmaError::OK) { + break; + } + } + + // if OK, seal all the objects, + // if error, abort the previous i objects immediately + if (error_code == PlasmaError::OK) { + for (i = 0; i < object_ids.size(); i++) { + auto entry = GetObjectTableEntry(&store_info_, object_ids[i]); + ARROW_CHECK(entry != nullptr); + // Write the inlined data and metadata into the allocated object. + std::memcpy(entry->pointer, data[i].data(), data[i].size()); + std::memcpy(entry->pointer + data[i].size(), metadata[i].data(), + metadata[i].size()); + } + + SealObjects(object_ids, digests); + // Remove the client from the object's array of clients because the + // object is not being used by any client. The client was added to the + // object's array of clients in CreateObject. This is analogous to the + // Release call that happens in the client's Seal method. + for (i = 0; i < object_ids.size(); i++) { + auto entry = GetObjectTableEntry(&store_info_, object_ids[i]); + ARROW_CHECK(RemoveFromClientObjectIds(object_ids[i], entry, client) == 1); + } + } else { + for (size_t j = 0; j < i; j++) { + AbortObject(object_ids[j], client); + } + } + + HANDLE_SIGPIPE(SendCreateAndSealBatchReply(client->fd, error_code), client->fd); + } break; + case fb::MessageType::PlasmaAbortRequest: { + RETURN_NOT_OK(ReadAbortRequest(input, input_size, &object_id)); + ARROW_CHECK(AbortObject(object_id, client) == 1) << "To abort an object, the only " + "client currently using it " + "must be the creator."; + HANDLE_SIGPIPE(SendAbortReply(client->fd, object_id), client->fd); + } break; + case fb::MessageType::PlasmaGetRequest: { + std::vector object_ids_to_get; + int64_t timeout_ms; + RETURN_NOT_OK(ReadGetRequest(input, input_size, object_ids_to_get, &timeout_ms)); + ProcessGetRequest(client, object_ids_to_get, timeout_ms); + } break; + case fb::MessageType::PlasmaReleaseRequest: { + RETURN_NOT_OK(ReadReleaseRequest(input, input_size, &object_id)); + ReleaseObject(object_id, client); + } break; + case fb::MessageType::PlasmaDeleteRequest: { + std::vector object_ids; + std::vector error_codes; + RETURN_NOT_OK(ReadDeleteRequest(input, input_size, &object_ids)); + error_codes.reserve(object_ids.size()); + for (auto& object_id : object_ids) { + error_codes.push_back(DeleteObject(object_id)); + } + HANDLE_SIGPIPE(SendDeleteReply(client->fd, object_ids, error_codes), client->fd); + } break; + case fb::MessageType::PlasmaContainsRequest: { + RETURN_NOT_OK(ReadContainsRequest(input, input_size, &object_id)); + if (ContainsObject(object_id) == ObjectStatus::OBJECT_FOUND) { + HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 1), client->fd); + } else { + HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 0), client->fd); + } + } break; + case fb::MessageType::PlasmaListRequest: { + RETURN_NOT_OK(ReadListRequest(input, input_size)); + HANDLE_SIGPIPE(SendListReply(client->fd, store_info_.objects), client->fd); + } break; + case fb::MessageType::PlasmaSealRequest: { + std::string digest; + RETURN_NOT_OK(ReadSealRequest(input, input_size, &object_id, &digest)); + SealObjects({object_id}, {digest}); + HANDLE_SIGPIPE(SendSealReply(client->fd, object_id, PlasmaError::OK), client->fd); + } break; + case fb::MessageType::PlasmaEvictRequest: { + // This code path should only be used for testing. + int64_t num_bytes; + RETURN_NOT_OK(ReadEvictRequest(input, input_size, &num_bytes)); + std::vector objects_to_evict; + int64_t num_bytes_evicted = + eviction_policy_.ChooseObjectsToEvict(num_bytes, &objects_to_evict); + EvictObjects(objects_to_evict); + HANDLE_SIGPIPE(SendEvictReply(client->fd, num_bytes_evicted), client->fd); + } break; + case fb::MessageType::PlasmaRefreshLRURequest: { + std::vector object_ids; + RETURN_NOT_OK(ReadRefreshLRURequest(input, input_size, &object_ids)); + eviction_policy_.RefreshObjects(object_ids); + HANDLE_SIGPIPE(SendRefreshLRUReply(client->fd), client->fd); + } break; + case fb::MessageType::PlasmaSubscribeRequest: + SubscribeToUpdates(client); + break; + case fb::MessageType::PlasmaConnectRequest: { + HANDLE_SIGPIPE(SendConnectReply(client->fd, PlasmaAllocator::GetFootprintLimit()), + client->fd); + } break; + case fb::MessageType::PlasmaDisconnectClient: + ARROW_LOG(DEBUG) << "Disconnecting client on fd " << client->fd; + DisconnectClient(client->fd); + break; + case fb::MessageType::PlasmaSetOptionsRequest: { + std::string client_name; + int64_t output_memory_quota; + RETURN_NOT_OK( + ReadSetOptionsRequest(input, input_size, &client_name, &output_memory_quota)); + client->name = client_name; + bool success = eviction_policy_.SetClientQuota(client, output_memory_quota); + HANDLE_SIGPIPE(SendSetOptionsReply(client->fd, success ? PlasmaError::OK + : PlasmaError::OutOfMemory), + client->fd); + } break; + case fb::MessageType::PlasmaGetDebugStringRequest: { + HANDLE_SIGPIPE(SendGetDebugStringReply(client->fd, eviction_policy_.DebugString()), + client->fd); + } break; + default: + // This code should be unreachable. + ARROW_CHECK(0); + } + return Status::OK(); +} + +class PlasmaStoreRunner { + public: + PlasmaStoreRunner() {} + + void Start(char* socket_name, std::string directory, bool hugepages_enabled, + std::shared_ptr external_store) { + // Create the event loop. + loop_.reset(new EventLoop); + store_.reset(new PlasmaStore(loop_.get(), directory, hugepages_enabled, socket_name, + external_store)); + plasma_config = store_->GetPlasmaStoreInfo(); + + // We are using a single memory-mapped file by mallocing and freeing a single + // large amount of space up front. According to the documentation, + // dlmalloc might need up to 128*sizeof(size_t) bytes for internal + // bookkeeping. + void* pointer = plasma::PlasmaAllocator::Memalign( + kBlockSize, PlasmaAllocator::GetFootprintLimit() - 256 * sizeof(size_t)); + ARROW_CHECK(pointer != nullptr); + // This will unmap the file, but the next one created will be as large + // as this one (this is an implementation detail of dlmalloc). + plasma::PlasmaAllocator::Free( + pointer, PlasmaAllocator::GetFootprintLimit() - 256 * sizeof(size_t)); + + int socket = ConnectOrListenIpcSock(socket_name, true); + // TODO(pcm): Check return value. + ARROW_CHECK(socket >= 0); + + loop_->AddFileEvent(socket, kEventLoopRead, [this, socket](int events) { + this->store_->ConnectClient(socket); + }); + loop_->Start(); + } + + void Stop() { loop_->Stop(); } + + void Shutdown() { + loop_->Shutdown(); + loop_ = nullptr; + store_ = nullptr; + } + + private: + std::unique_ptr loop_; + std::unique_ptr store_; +}; + +static std::unique_ptr g_runner = nullptr; + +void HandleSignal(int signal) { + if (signal == SIGTERM) { + ARROW_LOG(INFO) << "SIGTERM Signal received, closing Plasma Server..."; + if (g_runner != nullptr) { + g_runner->Stop(); + } + } +} + +void StartServer(char* socket_name, std::string plasma_directory, bool hugepages_enabled, + std::shared_ptr external_store) { +#ifndef _WIN32 // TODO(mehrdadn): Is there an equivalent of this we need for Windows? + // Ignore SIGPIPE signals. If we don't do this, then when we attempt to write + // to a client that has already died, the store could die. + signal(SIGPIPE, SIG_IGN); +#endif + + g_runner.reset(new PlasmaStoreRunner()); + signal(SIGTERM, HandleSignal); + g_runner->Start(socket_name, plasma_directory, hugepages_enabled, external_store); +} + +} // namespace plasma + +int main(int argc, char* argv[]) { + ArrowLog::StartArrowLog(argv[0], ArrowLogLevel::ARROW_INFO); + ArrowLog::InstallFailureSignalHandler(); + char* socket_name = nullptr; + // Directory where plasma memory mapped files are stored. + std::string plasma_directory; + std::string external_store_endpoint; + bool hugepages_enabled = false; + int64_t system_memory = -1; + int c; + while ((c = getopt(argc, argv, "s:m:d:e:h")) != -1) { + switch (c) { + case 'd': + plasma_directory = std::string(optarg); + break; + case 'e': + external_store_endpoint = std::string(optarg); + break; + case 'h': + hugepages_enabled = true; + break; + case 's': + socket_name = optarg; + break; + case 'm': { + char extra; + int scanned = sscanf(optarg, "%" SCNd64 "%c", &system_memory, &extra); + ARROW_CHECK(scanned == 1); + // Set system memory capacity + plasma::PlasmaAllocator::SetFootprintLimit(static_cast(system_memory)); + ARROW_LOG(INFO) << "Allowing the Plasma store to use up to " + << static_cast(system_memory) / 1000000000 + << "GB of memory."; + break; + } + default: + exit(-1); + } + } + // Sanity check command line options. + if (!socket_name) { + ARROW_LOG(FATAL) << "please specify socket for incoming connections with -s switch"; + } + if (system_memory == -1) { + ARROW_LOG(FATAL) << "please specify the amount of system memory with -m switch"; + } + if (hugepages_enabled && plasma_directory.empty()) { + ARROW_LOG(FATAL) << "if you want to use hugepages, please specify path to huge pages " + "filesystem with -d"; + } + if (plasma_directory.empty()) { +#ifdef __linux__ + plasma_directory = "/dev/shm"; +#else + plasma_directory = "/tmp"; +#endif + } + ARROW_LOG(INFO) << "Starting object store with directory " << plasma_directory + << " and huge page support " + << (hugepages_enabled ? "enabled" : "disabled"); +#ifdef __linux__ + if (!hugepages_enabled) { + // On Linux, check that the amount of memory available in /dev/shm is large + // enough to accommodate the request. If it isn't, then fail. + int shm_fd = open(plasma_directory.c_str(), O_RDONLY); + struct statvfs shm_vfs_stats; + fstatvfs(shm_fd, &shm_vfs_stats); + // The value shm_vfs_stats.f_bsize is the block size, and the value + // shm_vfs_stats.f_bavail is the number of available blocks. + int64_t shm_mem_avail = shm_vfs_stats.f_bsize * shm_vfs_stats.f_bavail; + close(shm_fd); + // Keep some safety margin for allocator fragmentation. + shm_mem_avail = 9 * shm_mem_avail / 10; + if (system_memory > shm_mem_avail) { + ARROW_LOG(WARNING) + << "System memory request exceeds memory available in " << plasma_directory + << ". The request is for " << system_memory + << " bytes, and the amount available is " << shm_mem_avail + << " bytes. You may be able to free up space by deleting files in " + "/dev/shm. If you are inside a Docker container, you may need to " + "pass an argument with the flag '--shm-size' to 'docker run'."; + system_memory = shm_mem_avail; + } + } else { + plasma::SetMallocGranularity(1024 * 1024 * 1024); // 1 GB + } +#endif + // Get external store + std::shared_ptr external_store{nullptr}; + if (!external_store_endpoint.empty()) { + std::string name; + ARROW_CHECK_OK( + plasma::ExternalStores::ExtractStoreName(external_store_endpoint, &name)); + external_store = plasma::ExternalStores::GetStore(name); + if (external_store == nullptr) { + ARROW_LOG(FATAL) << "No such external store \"" << name << "\""; + return -1; + } + ARROW_LOG(DEBUG) << "connecting to external store..."; + ARROW_CHECK_OK(external_store->Connect(external_store_endpoint)); + } + ARROW_LOG(DEBUG) << "starting server listening on " << socket_name; +#ifdef _WINSOCKAPI_ + WSADATA wsadata; + WSAStartup(MAKEWORD(2, 2), &wsadata); +#endif + plasma::StartServer(socket_name, plasma_directory, hugepages_enabled, external_store); + plasma::g_runner->Shutdown(); + plasma::g_runner = nullptr; + + ArrowLog::UninstallSignalAction(); + ArrowLog::ShutDownArrowLog(); +#ifdef _WINSOCKAPI_ + WSACleanup(); +#endif + return 0; +} diff --git a/src/ray/plasma/store.h b/src/ray/plasma/store.h new file mode 100644 index 000000000..7c3b5fbe3 --- /dev/null +++ b/src/ray/plasma/store.h @@ -0,0 +1,250 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_STORE_H +#define PLASMA_STORE_H + +#include +#include +#include +#include +#include +#include + +#include "plasma/common.h" +#include "plasma/events.h" +#include "plasma/external_store.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" +#include "plasma/quota_aware_policy.h" + +namespace arrow { +class Status; +} // namespace arrow + +namespace plasma { + +namespace flatbuf { +struct ObjectInfoT; +enum class PlasmaError; +} // namespace flatbuf + +using flatbuf::ObjectInfoT; +using flatbuf::PlasmaError; + +struct GetRequest; + +struct NotificationQueue { + /// The object notifications for clients. We notify the client about the + /// objects in the order that the objects were sealed or deleted. + std::deque> object_notifications; +}; + +class PlasmaStore { + public: + using NotificationMap = std::unordered_map; + + // TODO: PascalCase PlasmaStore methods. + PlasmaStore(EventLoop* loop, std::string directory, bool hugepages_enabled, + const std::string& socket_name, + std::shared_ptr external_store); + + ~PlasmaStore(); + + /// Get a const pointer to the internal PlasmaStoreInfo object. + const PlasmaStoreInfo* GetPlasmaStoreInfo(); + + /// Create a new object. The client must do a call to release_object to tell + /// the store when it is done with the object. + /// + /// \param object_id Object ID of the object to be created. + /// \param evict_if_full If this is true, then when the object store is full, + /// try to evict objects that are not currently referenced before + /// creating the object. Else, do not evict any objects and + /// immediately return an PlasmaError::OutOfMemory. + /// \param data_size Size in bytes of the object to be created. + /// \param metadata_size Size in bytes of the object metadata. + /// \param device_num The number of the device where the object is being + /// created. + /// device_num = 0 corresponds to the host, + /// device_num = 1 corresponds to GPU0, + /// device_num = 2 corresponds to GPU1, etc. + /// \param client The client that created the object. + /// \param result The object that has been created. + /// \return One of the following error codes: + /// - PlasmaError::OK, if the object was created successfully. + /// - PlasmaError::ObjectExists, if an object with this ID is already + /// present in the store. In this case, the client should not call + /// plasma_release. + /// - PlasmaError::OutOfMemory, if the store is out of memory and + /// cannot create the object. In this case, the client should not call + /// plasma_release. + PlasmaError CreateObject(const ObjectID& object_id, bool evict_if_full, + int64_t data_size, int64_t metadata_size, int device_num, + Client* client, PlasmaObject* result); + + /// Abort a created but unsealed object. If the client is not the + /// creator, then the abort will fail. + /// + /// \param object_id Object ID of the object to be aborted. + /// \param client The client who created the object. If this does not + /// match the creator of the object, then the abort will fail. + /// \return 1 if the abort succeeds, else 0. + int AbortObject(const ObjectID& object_id, Client* client); + + /// Delete a specific object by object_id that have been created in the hash table. + /// + /// \param object_id Object ID of the object to be deleted. + /// \return One of the following error codes: + /// - PlasmaError::OK, if the object was delete successfully. + /// - PlasmaError::ObjectNonexistent, if ths object isn't existed. + /// - PlasmaError::ObjectInUse, if the object is in use. + PlasmaError DeleteObject(ObjectID& object_id); + + /// Evict objects returned by the eviction policy. + /// + /// \param object_ids Object IDs of the objects to be evicted. + void EvictObjects(const std::vector& object_ids); + + /// Process a get request from a client. This method assumes that we will + /// eventually have these objects sealed. If one of the objects has not yet + /// been sealed, the client that requested the object will be notified when it + /// is sealed. + /// + /// For each object, the client must do a call to release_object to tell the + /// store when it is done with the object. + /// + /// \param client The client making this request. + /// \param object_ids Object IDs of the objects to be gotten. + /// \param timeout_ms The timeout for the get request in milliseconds. + void ProcessGetRequest(Client* client, const std::vector& object_ids, + int64_t timeout_ms); + + /// Seal a vector of objects. The objects are now immutable and can be accessed with + /// get. + /// + /// \param object_ids The vector of Object IDs of the objects to be sealed. + /// \param digests The vector of digests of the objects. This is used to tell if two + /// objects with the same object ID are the same. + void SealObjects(const std::vector& object_ids, + const std::vector& digests); + + /// Check if the plasma store contains an object: + /// + /// \param object_id Object ID that will be checked. + /// \return OBJECT_FOUND if the object is in the store, OBJECT_NOT_FOUND if + /// not + ObjectStatus ContainsObject(const ObjectID& object_id); + + /// Record the fact that a particular client is no longer using an object. + /// + /// \param object_id The object ID of the object that is being released. + /// \param client The client making this request. + void ReleaseObject(const ObjectID& object_id, Client* client); + + /// Subscribe a file descriptor to updates about new sealed objects. + /// + /// \param client The client making this request. + void SubscribeToUpdates(Client* client); + + /// Connect a new client to the PlasmaStore. + /// + /// \param listener_sock The socket that is listening to incoming connections. + void ConnectClient(int listener_sock); + + /// Disconnect a client from the PlasmaStore. + /// + /// \param client_fd The client file descriptor that is disconnected. + void DisconnectClient(int client_fd); + + NotificationMap::iterator SendNotifications(NotificationMap::iterator it); + + arrow::Status ProcessMessage(Client* client); + + private: + void PushNotification(ObjectInfoT* object_notification); + + void PushNotifications(std::vector& object_notifications); + + void PushNotification(ObjectInfoT* object_notification, int client_fd); + + void AddToClientObjectIds(const ObjectID& object_id, ObjectTableEntry* entry, + Client* client); + + /// Remove a GetRequest and clean up the relevant data structures. + /// + /// \param get_request The GetRequest to remove. + void RemoveGetRequest(GetRequest* get_request); + + /// Remove all of the GetRequests for a given client. + /// + /// \param client The client whose GetRequests should be removed. + void RemoveGetRequestsForClient(Client* client); + + void ReturnFromGet(GetRequest* get_req); + + void UpdateObjectGetRequests(const ObjectID& object_id); + + int RemoveFromClientObjectIds(const ObjectID& object_id, ObjectTableEntry* entry, + Client* client); + + void EraseFromObjectTable(const ObjectID& object_id); + + uint8_t* AllocateMemory(size_t size, bool evict_if_full, int* fd, int64_t* map_size, + ptrdiff_t* offset, Client* client, bool is_create); +#ifdef PLASMA_CUDA + Status AllocateCudaMemory(int device_num, int64_t size, uint8_t** out_pointer, + std::shared_ptr* out_ipc_handle); + + Status FreeCudaMemory(int device_num, int64_t size, uint8_t* out_pointer); +#endif + + /// Event loop of the plasma store. + EventLoop* loop_; + /// The plasma store information, including the object tables, that is exposed + /// to the eviction policy. + PlasmaStoreInfo store_info_; + /// The state that is managed by the eviction policy. + QuotaAwarePolicy eviction_policy_; + /// Input buffer. This is allocated only once to avoid mallocs for every + /// call to process_message. + std::vector input_buffer_; + /// A hash table mapping object IDs to a vector of the get requests that are + /// waiting for the object to arrive. + std::unordered_map> object_get_requests_; + /// The pending notifications that have not been sent to subscribers because + /// the socket send buffers were full. This is a hash table from client file + /// descriptor to an array of object_ids to send to that client. + /// TODO(pcm): Consider putting this into the Client data structure and + /// reorganize the code slightly. + NotificationMap pending_notifications_; + + std::unordered_map> connected_clients_; + + std::unordered_set deletion_cache_; + + /// Manages worker threads for handling asynchronous/multi-threaded requests + /// for reading/writing data to/from external store. + std::shared_ptr external_store_; +#ifdef PLASMA_CUDA + arrow::cuda::CudaDeviceManager* manager_; +#endif +}; + +} // namespace plasma + +#endif // PLASMA_STORE_H diff --git a/src/ray/plasma/test/client_tests.cc b/src/ray/plasma/test/client_tests.cc new file mode 100644 index 000000000..a3cd8e4f2 --- /dev/null +++ b/src/ray/plasma/test/client_tests.cc @@ -0,0 +1,1084 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include "arrow/testing/gtest_util.h" +#include "arrow/util/io_util.h" + +#include "plasma/client.h" +#include "plasma/common.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" +#include "plasma/test_util.h" + +namespace plasma { + +using arrow::internal::TemporaryDir; + +std::string test_executable; // NOLINT + +void AssertObjectBufferEqual(const ObjectBuffer& object_buffer, + const std::vector& metadata, + const std::vector& data) { + arrow::AssertBufferEqual(*object_buffer.metadata, metadata); + arrow::AssertBufferEqual(*object_buffer.data, data); +} + +class TestPlasmaStore : public ::testing::Test { + public: + // TODO(pcm): At the moment, stdout of the test gets mixed up with + // stdout of the object store. Consider changing that. + + void SetUp() { + ASSERT_OK_AND_ASSIGN(temp_dir_, TemporaryDir::Make("cli-test-")); + store_socket_name_ = temp_dir_->path().ToString() + "store"; + + std::string plasma_directory = + test_executable.substr(0, test_executable.find_last_of("/")); + std::string plasma_command = + plasma_directory + "/plasma-store-server -m 10000000 -s " + store_socket_name_ + + " 1> /dev/null 2> /dev/null & " + "echo $! > " + store_socket_name_ + ".pid"; + PLASMA_CHECK_SYSTEM(system(plasma_command.c_str())); + ARROW_CHECK_OK(client_.Connect(store_socket_name_, "")); + ARROW_CHECK_OK(client2_.Connect(store_socket_name_, "")); + } + + virtual void TearDown() { + ARROW_CHECK_OK(client_.Disconnect()); + ARROW_CHECK_OK(client2_.Disconnect()); + // Kill plasma_store process that we started +#ifdef COVERAGE_BUILD + // Ask plasma_store to exit gracefully and give it time to write out + // coverage files + std::string plasma_term_command = + "kill -TERM `cat " + store_socket_name_ + ".pid` || exit 0"; + PLASMA_CHECK_SYSTEM(system(plasma_term_command.c_str())); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); +#endif + std::string plasma_kill_command = + "kill -KILL `cat " + store_socket_name_ + ".pid` || exit 0"; + PLASMA_CHECK_SYSTEM(system(plasma_kill_command.c_str())); + } + + void CreateObject(PlasmaClient& client, const ObjectID& object_id, + const std::vector& metadata, + const std::vector& data, bool release = true) { + std::shared_ptr data_buffer; + ARROW_CHECK_OK(client.Create(object_id, data.size(), metadata.data(), metadata.size(), + &data_buffer)); + for (size_t i = 0; i < data.size(); i++) { + data_buffer->mutable_data()[i] = data[i]; + } + ARROW_CHECK_OK(client.Seal(object_id)); + if (release) { + ARROW_CHECK_OK(client.Release(object_id)); + } + } + + protected: + PlasmaClient client_; + PlasmaClient client2_; + std::unique_ptr temp_dir_; + std::string store_socket_name_; +}; + +TEST_F(TestPlasmaStore, NewSubscriberTest) { + PlasmaClient local_client, local_client2; + + ARROW_CHECK_OK(local_client.Connect(store_socket_name_, "")); + ARROW_CHECK_OK(local_client2.Connect(store_socket_name_, "")); + + ObjectID object_id = random_object_id(); + + // Test for the object being in local Plasma store. + // First create object. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK( + local_client.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(local_client.Seal(object_id)); + + // Test that new subscriber client2 can receive notifications about existing objects. + int fd = -1; + ARROW_CHECK_OK(local_client2.Subscribe(&fd)); + ASSERT_GT(fd, 0); + + ObjectID object_id2 = random_object_id(); + int64_t data_size2 = 0; + int64_t metadata_size2 = 0; + ARROW_CHECK_OK( + local_client2.GetNotification(fd, &object_id2, &data_size2, &metadata_size2)); + ASSERT_EQ(object_id, object_id2); + ASSERT_EQ(data_size, data_size2); + ASSERT_EQ(metadata_size, metadata_size2); + + // Delete the object. + ARROW_CHECK_OK(local_client.Release(object_id)); + ARROW_CHECK_OK(local_client.Delete(object_id)); + + ARROW_CHECK_OK( + local_client2.GetNotification(fd, &object_id2, &data_size2, &metadata_size2)); + ASSERT_EQ(object_id, object_id2); + ASSERT_EQ(-1, data_size2); + ASSERT_EQ(-1, metadata_size2); + + ARROW_CHECK_OK(local_client2.Disconnect()); + ARROW_CHECK_OK(local_client.Disconnect()); +} + +TEST_F(TestPlasmaStore, BatchNotificationTest) { + PlasmaClient local_client, local_client2; + + ARROW_CHECK_OK(local_client.Connect(store_socket_name_, "")); + ARROW_CHECK_OK(local_client2.Connect(store_socket_name_, "")); + + int fd = -1; + ARROW_CHECK_OK(local_client2.Subscribe(&fd)); + ASSERT_GT(fd, 0); + + ObjectID object_id1 = random_object_id(); + ObjectID object_id2 = random_object_id(); + + std::vector object_ids = {object_id1, object_id2}; + + std::vector data = {"hello", "world!"}; + std::vector metadata = {"1", "23"}; + ARROW_CHECK_OK(local_client.CreateAndSealBatch(object_ids, data, metadata)); + + ObjectID object_id = random_object_id(); + int64_t data_size = 0; + int64_t metadata_size = 0; + ARROW_CHECK_OK( + local_client2.GetNotification(fd, &object_id, &data_size, &metadata_size)); + ASSERT_EQ(object_id, object_id1); + ASSERT_EQ(data_size, 5); + ASSERT_EQ(metadata_size, 1); + + ARROW_CHECK_OK( + local_client2.GetNotification(fd, &object_id, &data_size, &metadata_size)); + ASSERT_EQ(object_id, object_id2); + ASSERT_EQ(data_size, 6); + ASSERT_EQ(metadata_size, 2); + + ARROW_CHECK_OK(local_client2.Disconnect()); + ARROW_CHECK_OK(local_client.Disconnect()); +} + +TEST_F(TestPlasmaStore, SealErrorsTest) { + ObjectID object_id = random_object_id(); + + Status result = client_.Seal(object_id); + ASSERT_TRUE(IsPlasmaObjectNonexistent(result)); + + // Create object. + std::vector data(100, 0); + CreateObject(client_, object_id, {42}, data, false); + + // Trying to seal it again. + result = client_.Seal(object_id); + ASSERT_TRUE(IsPlasmaObjectAlreadySealed(result)); + ARROW_CHECK_OK(client_.Release(object_id)); +} + +TEST_F(TestPlasmaStore, SetQuotaBasicTest) { + bool has_object = false; + ObjectID id1 = random_object_id(); + ObjectID id2 = random_object_id(); + + ARROW_CHECK_OK(client_.SetClientOptions("client1", 5 * 1024 * 1024)); + std::vector big_data(3 * 1024 * 1024, 0); + + // First object fits + CreateObject(client_, id1, {42}, big_data, true); + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); + + // Evicts first object + CreateObject(client_, id2, {42}, big_data, true); + ARROW_CHECK_OK(client_.Contains(id2, &has_object)); + ASSERT_TRUE(has_object); + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_FALSE(has_object); + + // Too big to fit in quota at all + std::shared_ptr data_buffer; + ASSERT_FALSE( + client_.Create(random_object_id(), 7 * 1024 * 1024, {}, 0, &data_buffer).ok()); + ASSERT_TRUE( + client_.Create(random_object_id(), 4 * 1024 * 1024, {}, 0, &data_buffer).ok()); +} + +TEST_F(TestPlasmaStore, SetQuotaProvidesIsolationFromOtherClients) { + bool has_object = false; + ObjectID id1 = random_object_id(); + ObjectID id2 = random_object_id(); + + std::vector big_data(3 * 1024 * 1024, 0); + + // First object, created without quota + CreateObject(client_, id1, {42}, big_data, true); + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); + + // Second client creates a bunch of objects + for (int i = 0; i < 10; i++) { + CreateObject(client2_, random_object_id(), {42}, big_data, true); + } + + // First client's object is evicted + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_FALSE(has_object); + + // Try again with quota enabled + ARROW_CHECK_OK(client_.SetClientOptions("client1", 5 * 1024 * 1024)); + CreateObject(client_, id2, {42}, big_data, true); + ARROW_CHECK_OK(client_.Contains(id2, &has_object)); + ASSERT_TRUE(has_object); + + // Second client creates a bunch of objects + for (int i = 0; i < 10; i++) { + CreateObject(client2_, random_object_id(), {42}, big_data, true); + } + + // First client's object is not evicted + ARROW_CHECK_OK(client_.Contains(id2, &has_object)); + ASSERT_TRUE(has_object); +} + +TEST_F(TestPlasmaStore, SetQuotaProtectsOtherClients) { + bool has_object = false; + ObjectID id1 = random_object_id(); + + std::vector big_data(3 * 1024 * 1024, 0); + + // First client has no quota + CreateObject(client_, id1, {42}, big_data, true); + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); + + // Second client creates a bunch of objects under a quota + ARROW_CHECK_OK(client2_.SetClientOptions("client2", 5 * 1024 * 1024)); + for (int i = 0; i < 10; i++) { + CreateObject(client2_, random_object_id(), {42}, big_data, true); + } + + // First client's object is NOT evicted + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); +} + +TEST_F(TestPlasmaStore, SetQuotaCannotExceedSeventyPercentMemory) { + ASSERT_FALSE(client_.SetClientOptions("client1", 8 * 1024 * 1024).ok()); + ASSERT_TRUE(client_.SetClientOptions("client1", 5 * 1024 * 1024).ok()); + // cannot set quota twice + ASSERT_FALSE(client_.SetClientOptions("client1", 5 * 1024 * 1024).ok()); + // cannot exceed 70% summed + ASSERT_FALSE(client2_.SetClientOptions("client2", 3 * 1024 * 1024).ok()); + ASSERT_TRUE(client2_.SetClientOptions("client2", 1 * 1024 * 1024).ok()); +} + +TEST_F(TestPlasmaStore, SetQuotaDemotesPinnedObjectsToGlobalLRU) { + bool has_object = false; + ASSERT_TRUE(client_.SetClientOptions("client1", 5 * 1024 * 1024).ok()); + + ObjectID id1 = random_object_id(); + ObjectID id2 = random_object_id(); + std::vector big_data(3 * 1024 * 1024, 0); + + // Quota is not enough to fit both id1 and id2, but global LRU is + CreateObject(client_, id1, {42}, big_data, false); + CreateObject(client_, id2, {42}, big_data, false); + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); + ARROW_CHECK_OK(client_.Contains(id2, &has_object)); + ASSERT_TRUE(has_object); + + // Release both objects. Now id1 is in global LRU and id2 is in quota + ARROW_CHECK_OK(client_.Release(id1)); + ARROW_CHECK_OK(client_.Release(id2)); + + // This flushes id1 from the object store + for (int i = 0; i < 10; i++) { + CreateObject(client2_, random_object_id(), {42}, big_data, true); + } + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_FALSE(has_object); + ARROW_CHECK_OK(client_.Contains(id2, &has_object)); + ASSERT_TRUE(has_object); +} + +TEST_F(TestPlasmaStore, SetQuotaDemoteDisconnectToGlobalLRU) { + bool has_object = false; + PlasmaClient local_client; + ARROW_CHECK_OK(local_client.Connect(store_socket_name_, "")); + ARROW_CHECK_OK(local_client.SetClientOptions("local", 5 * 1024 * 1024)); + + ObjectID id1 = random_object_id(); + std::vector big_data(3 * 1024 * 1024, 0); + + // First object fits + CreateObject(local_client, id1, {42}, big_data, true); + for (int i = 0; i < 10; i++) { + CreateObject(client_, random_object_id(), {42}, big_data, true); + } + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); + + // Object is still present after disconnect + ARROW_CHECK_OK(local_client.Disconnect()); + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_TRUE(has_object); + + // But is eligible for global LRU + for (int i = 0; i < 10; i++) { + CreateObject(client_, random_object_id(), {42}, big_data, true); + } + ARROW_CHECK_OK(client_.Contains(id1, &has_object)); + ASSERT_FALSE(has_object); +} + +TEST_F(TestPlasmaStore, SetQuotaCleanupObjectMetadata) { + PlasmaClient local_client; + ARROW_CHECK_OK(local_client.Connect(store_socket_name_, "")); + ARROW_CHECK_OK(local_client.SetClientOptions("local", 5 * 1024 * 1024)); + + ObjectID id0 = random_object_id(); + ObjectID id1 = random_object_id(); + ObjectID id2 = random_object_id(); + ObjectID id3 = random_object_id(); + std::vector big_data(3 * 1024 * 1024, 0); + std::vector small_data(1 * 1024 * 1024, 0); + CreateObject(local_client, id0, {42}, small_data, false); + CreateObject(local_client, id1, {42}, big_data, true); + CreateObject(local_client, id2, {42}, big_data, + true); // spills id0 to global, evicts id1 + CreateObject(local_client, id3, {42}, small_data, false); + + ASSERT_TRUE(client_.DebugString().find("num clients with quota: 1") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("quota map size: 2") != std::string::npos); + ASSERT_TRUE(client_.DebugString().find("pinned quota map size: 1") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) num objects: 0") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(local) num objects: 2") != std::string::npos); + + // release id0 + ARROW_CHECK_OK(local_client.Release(id0)); + ASSERT_TRUE(client_.DebugString().find("(global lru) num objects: 1") != + std::string::npos); + + // delete everything + ARROW_CHECK_OK(local_client.Delete(id0)); + ARROW_CHECK_OK(local_client.Delete(id2)); + ARROW_CHECK_OK(local_client.Delete(id3)); + ARROW_CHECK_OK(local_client.Release(id3)); + ASSERT_TRUE(client_.DebugString().find("quota map size: 0") != std::string::npos); + ASSERT_TRUE(client_.DebugString().find("pinned quota map size: 0") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) num objects: 0") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(local) num objects: 0") != std::string::npos); + + ARROW_CHECK_OK(local_client.Disconnect()); + int tries = 10; // wait for disconnect to complete + while (tries > 0 && + client_.DebugString().find("num clients with quota: 0") == std::string::npos) { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + tries -= 1; + } + ASSERT_TRUE(client_.DebugString().find("num clients with quota: 0") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) capacity: 10000000") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) used: 0%") != std::string::npos); +} + +TEST_F(TestPlasmaStore, SetQuotaCleanupClientDisconnect) { + PlasmaClient local_client; + ARROW_CHECK_OK(local_client.Connect(store_socket_name_, "")); + ARROW_CHECK_OK(local_client.SetClientOptions("local", 5 * 1024 * 1024)); + + ObjectID id1 = random_object_id(); + ObjectID id2 = random_object_id(); + ObjectID id3 = random_object_id(); + std::vector big_data(3 * 1024 * 1024, 0); + std::vector small_data(1 * 1024 * 1024, 0); + CreateObject(local_client, id1, {42}, big_data, true); + CreateObject(local_client, id2, {42}, big_data, true); + CreateObject(local_client, id3, {42}, small_data, false); + + ARROW_CHECK_OK(local_client.Disconnect()); + int tries = 10; // wait for disconnect to complete + while (tries > 0 && + client_.DebugString().find("num clients with quota: 0") == std::string::npos) { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + tries -= 1; + } + ASSERT_TRUE(client_.DebugString().find("num clients with quota: 0") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("quota map size: 0") != std::string::npos); + ASSERT_TRUE(client_.DebugString().find("pinned quota map size: 0") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) num objects: 2") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) capacity: 10000000") != + std::string::npos); + ASSERT_TRUE(client_.DebugString().find("(global lru) used: 41.9431%") != + std::string::npos); +} + +TEST_F(TestPlasmaStore, RefreshLRUTest) { + bool has_object = false; + std::vector object_ids; + + for (int i = 0; i < 10; ++i) { + object_ids.push_back(random_object_id()); + } + + std::vector small_data(1 * 1000 * 1000, 0); + + // we can fit ten small objects into the store + for (const auto& object_id : object_ids) { + CreateObject(client_, object_id, {}, small_data, true); + ARROW_CHECK_OK(client_.Contains(object_ids[0], &has_object)); + ASSERT_TRUE(has_object); + } + + ObjectID id = random_object_id(); + CreateObject(client_, id, {}, small_data, true); + + // the first two objects got evicted (20% of the store) + ARROW_CHECK_OK(client_.Contains(object_ids[0], &has_object)); + ASSERT_FALSE(has_object); + + ARROW_CHECK_OK(client_.Contains(object_ids[1], &has_object)); + ASSERT_FALSE(has_object); + + ARROW_CHECK_OK(client_.Refresh({object_ids[2], object_ids[3]})); + + id = random_object_id(); + CreateObject(client_, id, {}, small_data, true); + id = random_object_id(); + CreateObject(client_, id, {}, small_data, true); + + // the refreshed objects are not evicted + ARROW_CHECK_OK(client_.Contains(object_ids[2], &has_object)); + ASSERT_TRUE(has_object); + ARROW_CHECK_OK(client_.Contains(object_ids[3], &has_object)); + ASSERT_TRUE(has_object); + + // the next object in LRU order is evicted + ARROW_CHECK_OK(client_.Contains(object_ids[4], &has_object)); + ASSERT_FALSE(has_object); +} + +TEST_F(TestPlasmaStore, DeleteTest) { + ObjectID object_id = random_object_id(); + + // Test for deleting non-existence object. + Status result = client_.Delete(object_id); + ARROW_CHECK_OK(result); + + // Test for the object being in local Plasma store. + // First create object. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Seal(object_id)); + + result = client_.Delete(object_id); + ARROW_CHECK_OK(result); + bool has_object = false; + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); + + ARROW_CHECK_OK(client_.Release(object_id)); + // object_id is marked as to-be-deleted, when it is not in use, it will be deleted. + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_FALSE(has_object); + ARROW_CHECK_OK(client_.Delete(object_id)); +} + +TEST_F(TestPlasmaStore, DeleteObjectsTest) { + ObjectID object_id1 = random_object_id(); + ObjectID object_id2 = random_object_id(); + + // Test for deleting non-existence object. + Status result = client_.Delete(std::vector{object_id1, object_id2}); + ARROW_CHECK_OK(result); + // Test for the object being in local Plasma store. + // First create object. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id1, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Seal(object_id1)); + ARROW_CHECK_OK(client_.Create(object_id2, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Seal(object_id2)); + // Release the ref count of Create function. + ARROW_CHECK_OK(client_.Release(object_id1)); + ARROW_CHECK_OK(client_.Release(object_id2)); + // Increase the ref count by calling Get using client2_. + std::vector object_buffers; + ARROW_CHECK_OK(client2_.Get({object_id1, object_id2}, 0, &object_buffers)); + // Objects are still used by client2_. + result = client_.Delete(std::vector{object_id1, object_id2}); + ARROW_CHECK_OK(result); + // The object is used and it should not be deleted right now. + bool has_object = false; + ARROW_CHECK_OK(client_.Contains(object_id1, &has_object)); + ASSERT_TRUE(has_object); + ARROW_CHECK_OK(client_.Contains(object_id2, &has_object)); + ASSERT_TRUE(has_object); + // Decrease the ref count by deleting the PlasmaBuffer (in ObjectBuffer). + // client2_ won't send the release request immediately because the trigger + // condition is not reached. The release is only added to release cache. + object_buffers.clear(); + // Delete the objects. + result = client2_.Delete(std::vector{object_id1, object_id2}); + ARROW_CHECK_OK(client_.Contains(object_id1, &has_object)); + ASSERT_FALSE(has_object); + ARROW_CHECK_OK(client_.Contains(object_id2, &has_object)); + ASSERT_FALSE(has_object); +} + +TEST_F(TestPlasmaStore, ContainsTest) { + ObjectID object_id = random_object_id(); + + // Test for object non-existence. + bool has_object; + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_FALSE(has_object); + + // Test for the object being in local Plasma store. + // First create object. + std::vector data(100, 0); + CreateObject(client_, object_id, {42}, data); + std::vector object_buffers; + ARROW_CHECK_OK(client_.Get({object_id}, -1, &object_buffers)); + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); +} + +TEST_F(TestPlasmaStore, GetTest) { + std::vector object_buffers; + + ObjectID object_id = random_object_id(); + + // Test for object non-existence. + ARROW_CHECK_OK(client_.Get({object_id}, 0, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_FALSE(object_buffers[0].metadata); + ASSERT_FALSE(object_buffers[0].data); + EXPECT_FALSE(client_.IsInUse(object_id)); + + // Test for the object being in local Plasma store. + // First create object. + std::vector data = {3, 5, 6, 7, 9}; + CreateObject(client_, object_id, {42}, data); + EXPECT_FALSE(client_.IsInUse(object_id)); + + object_buffers.clear(); + ARROW_CHECK_OK(client_.Get({object_id}, -1, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_EQ(object_buffers[0].device_num, 0); + AssertObjectBufferEqual(object_buffers[0], {42}, {3, 5, 6, 7, 9}); + + // Metadata keeps object in use + { + auto metadata = object_buffers[0].metadata; + object_buffers.clear(); + ::arrow::AssertBufferEqual(*metadata, std::string{42}); + EXPECT_TRUE(client_.IsInUse(object_id)); + } + // Object is automatically released + EXPECT_FALSE(client_.IsInUse(object_id)); +} + +TEST_F(TestPlasmaStore, LegacyGetTest) { + // Test for old non-releasing Get() variant + ObjectID object_id = random_object_id(); + { + ObjectBuffer object_buffer; + + // Test for object non-existence. + ARROW_CHECK_OK(client_.Get(&object_id, 1, 0, &object_buffer)); + ASSERT_FALSE(object_buffer.metadata); + ASSERT_FALSE(object_buffer.data); + EXPECT_FALSE(client_.IsInUse(object_id)); + + // First create object. + std::vector data = {3, 5, 6, 7, 9}; + CreateObject(client_, object_id, {42}, data); + EXPECT_FALSE(client_.IsInUse(object_id)); + + ARROW_CHECK_OK(client_.Get(&object_id, 1, -1, &object_buffer)); + AssertObjectBufferEqual(object_buffer, {42}, {3, 5, 6, 7, 9}); + } + // Object needs releasing manually + EXPECT_TRUE(client_.IsInUse(object_id)); + ARROW_CHECK_OK(client_.Release(object_id)); + EXPECT_FALSE(client_.IsInUse(object_id)); +} + +TEST_F(TestPlasmaStore, MultipleGetTest) { + ObjectID object_id1 = random_object_id(); + ObjectID object_id2 = random_object_id(); + std::vector object_ids = {object_id1, object_id2}; + std::vector object_buffers; + + int64_t data_size = 4; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id1, data_size, metadata, metadata_size, &data)); + data->mutable_data()[0] = 1; + ARROW_CHECK_OK(client_.Seal(object_id1)); + + ARROW_CHECK_OK(client_.Create(object_id2, data_size, metadata, metadata_size, &data)); + data->mutable_data()[0] = 2; + ARROW_CHECK_OK(client_.Seal(object_id2)); + + ARROW_CHECK_OK(client_.Get(object_ids, -1, &object_buffers)); + ASSERT_EQ(object_buffers[0].data->data()[0], 1); + ASSERT_EQ(object_buffers[1].data->data()[0], 2); +} + +TEST_F(TestPlasmaStore, BatchCreateTest) { + ObjectID object_id1 = random_object_id(); + ObjectID object_id2 = random_object_id(); + std::vector object_ids = {object_id1, object_id2}; + + std::vector data = {"hello", "world"}; + std::vector metadata = {"1", "2"}; + + ARROW_CHECK_OK(client_.CreateAndSealBatch(object_ids, data, metadata)); + + std::vector object_buffers; + + ARROW_CHECK_OK(client_.Get(object_ids, -1, &object_buffers)); + + std::string out1, out2; + out1.assign(reinterpret_cast(object_buffers[0].data->data()), + object_buffers[0].data->size()); + out2.assign(reinterpret_cast(object_buffers[1].data->data()), + object_buffers[1].data->size()); + + ASSERT_STREQ(out1.c_str(), "hello"); + ASSERT_STREQ(out2.c_str(), "world"); +} + +TEST_F(TestPlasmaStore, AbortTest) { + ObjectID object_id = random_object_id(); + std::vector object_buffers; + + // Test for object non-existence. + ARROW_CHECK_OK(client_.Get({object_id}, 0, &object_buffers)); + ASSERT_FALSE(object_buffers[0].data); + + // Test object abort. + // First create object. + int64_t data_size = 4; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + uint8_t* data_ptr; + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); + data_ptr = data->mutable_data(); + // Write some data. + for (int64_t i = 0; i < data_size / 2; i++) { + data_ptr[i] = static_cast(i % 4); + } + // Attempt to abort. Test that this fails before the first release. + Status status = client_.Abort(object_id); + ASSERT_TRUE(status.IsInvalid()); + // Release, then abort. + ARROW_CHECK_OK(client_.Release(object_id)); + EXPECT_TRUE(client_.IsInUse(object_id)); + + ARROW_CHECK_OK(client_.Abort(object_id)); + EXPECT_FALSE(client_.IsInUse(object_id)); + + // Test for object non-existence after the abort. + ARROW_CHECK_OK(client_.Get({object_id}, 0, &object_buffers)); + ASSERT_FALSE(object_buffers[0].data); + + // Create the object successfully this time. + CreateObject(client_, object_id, {42, 43}, {1, 2, 3, 4, 5}); + + // Test that we can get the object. + ARROW_CHECK_OK(client_.Get({object_id}, -1, &object_buffers)); + AssertObjectBufferEqual(object_buffers[0], {42, 43}, {1, 2, 3, 4, 5}); +} + +TEST_F(TestPlasmaStore, OneIdCreateRepeatedlyTest) { + const int64_t loop_times = 5; + + ObjectID object_id = random_object_id(); + std::vector object_buffers; + + // Test for object non-existence. + ARROW_CHECK_OK(client_.Get({object_id}, 0, &object_buffers)); + ASSERT_FALSE(object_buffers[0].data); + + int64_t data_size = 20; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + + // Test the sequence: create -> release -> abort -> ... + for (int64_t i = 0; i < loop_times; i++) { + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Release(object_id)); + ARROW_CHECK_OK(client_.Abort(object_id)); + } + + // Test the sequence: create -> seal -> release -> delete -> ... + for (int64_t i = 0; i < loop_times; i++) { + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Seal(object_id)); + ARROW_CHECK_OK(client_.Release(object_id)); + ARROW_CHECK_OK(client_.Delete(object_id)); + } +} + +TEST_F(TestPlasmaStore, MultipleClientTest) { + ObjectID object_id = random_object_id(); + std::vector object_buffers; + + // Test for object non-existence on the first client. + bool has_object; + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_FALSE(has_object); + + // Test for the object being in local Plasma store. + // First create and seal object on the second client. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client2_.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client2_.Seal(object_id)); + // Test that the first client can get the object. + ARROW_CHECK_OK(client_.Get({object_id}, -1, &object_buffers)); + ASSERT_TRUE(object_buffers[0].data); + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); + + // Test that one client disconnecting does not interfere with the other. + // First create object on the second client. + object_id = random_object_id(); + ARROW_CHECK_OK(client2_.Create(object_id, data_size, metadata, metadata_size, &data)); + // Disconnect the first client. + ARROW_CHECK_OK(client_.Disconnect()); + // Test that the second client can seal and get the created object. + ARROW_CHECK_OK(client2_.Seal(object_id)); + ARROW_CHECK_OK(client2_.Get({object_id}, -1, &object_buffers)); + ASSERT_TRUE(object_buffers[0].data); + ARROW_CHECK_OK(client2_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); +} + +TEST_F(TestPlasmaStore, ManyObjectTest) { + // Create many objects on the first client. Seal one third, abort one third, + // and leave the last third unsealed. + std::vector object_ids; + for (int i = 0; i < 100; i++) { + ObjectID object_id = random_object_id(); + object_ids.push_back(object_id); + + // Test for object non-existence on the first client. + bool has_object; + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_FALSE(has_object); + + // Test for the object being in local Plasma store. + // First create and seal object on the first client. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); + + if (i % 3 == 0) { + // Seal one third of the objects. + ARROW_CHECK_OK(client_.Seal(object_id)); + // Test that the first client can get the object. + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); + } else if (i % 3 == 1) { + // Abort one third of the objects. + ARROW_CHECK_OK(client_.Release(object_id)); + ARROW_CHECK_OK(client_.Abort(object_id)); + } + } + // Disconnect the first client. All unsealed objects should be aborted. + ARROW_CHECK_OK(client_.Disconnect()); + + // Check that the second client can query the object store for the first + // client's objects. + int i = 0; + for (auto const& object_id : object_ids) { + bool has_object; + ARROW_CHECK_OK(client2_.Contains(object_id, &has_object)); + if (i % 3 == 0) { + // The first third should be sealed. + ASSERT_TRUE(has_object); + } else { + // The rest were aborted, so the object is not in the store. + ASSERT_FALSE(has_object); + } + i++; + } +} + +#ifdef PLASMA_CUDA +using arrow::cuda::CudaBuffer; +using arrow::cuda::CudaBufferReader; +using arrow::cuda::CudaBufferWriter; + +// actual CUDA device number + 1 +constexpr int kGpuDeviceNumber = 1; + +namespace { + +void AssertCudaRead(const std::shared_ptr& buffer, + const std::vector& expected_data) { + std::shared_ptr gpu_buffer; + const size_t data_size = expected_data.size(); + + ASSERT_OK_AND_ASSIGN(gpu_buffer, CudaBuffer::FromBuffer(buffer)); + ASSERT_EQ(gpu_buffer->size(), data_size); + + CudaBufferReader reader(gpu_buffer); + std::vector read_data(data_size); + ASSERT_OK_AND_EQ(data_size, reader.Read(data_size, read_data.data())); + + for (size_t i = 0; i < data_size; i++) { + ASSERT_EQ(read_data[i], expected_data[i]); + } +} + +} // namespace + +TEST_F(TestPlasmaStore, GetGPUTest) { + ObjectID object_id = random_object_id(); + std::vector object_buffers; + + // Test for object non-existence. + ARROW_CHECK_OK(client_.Get({object_id}, 0, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_FALSE(object_buffers[0].data); + + // Test for the object being in local Plasma store. + // First create object. + uint8_t data[] = {4, 5, 3, 1}; + int64_t data_size = sizeof(data); + uint8_t metadata[] = {42}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data_buffer; + std::shared_ptr gpu_buffer; + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, + &data_buffer, kGpuDeviceNumber)); + ASSERT_OK_AND_ASSIGN(gpu_buffer, CudaBuffer::FromBuffer(data_buffer)); + CudaBufferWriter writer(gpu_buffer); + ARROW_CHECK_OK(writer.Write(data, data_size)); + ARROW_CHECK_OK(client_.Seal(object_id)); + + object_buffers.clear(); + ARROW_CHECK_OK(client_.Get({object_id}, -1, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_EQ(object_buffers[0].device_num, kGpuDeviceNumber); + // Check data + AssertCudaRead(object_buffers[0].data, {4, 5, 3, 1}); + // Check metadata + AssertCudaRead(object_buffers[0].metadata, {42}); +} + +TEST_F(TestPlasmaStore, DeleteObjectsGPUTest) { + ObjectID object_id1 = random_object_id(); + ObjectID object_id2 = random_object_id(); + + // Test for deleting non-existence object. + Status result = client_.Delete(std::vector{object_id1, object_id2}); + ARROW_CHECK_OK(result); + // Test for the object being in local Plasma store. + // First create object. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id1, data_size, metadata, metadata_size, &data, + kGpuDeviceNumber)); + ARROW_CHECK_OK(client_.Seal(object_id1)); + ARROW_CHECK_OK(client_.Create(object_id2, data_size, metadata, metadata_size, &data, + kGpuDeviceNumber)); + ARROW_CHECK_OK(client_.Seal(object_id2)); + // Release the ref count of Create function. + ARROW_CHECK_OK(client_.Release(object_id1)); + ARROW_CHECK_OK(client_.Release(object_id2)); + // Increase the ref count by calling Get using client2_. + std::vector object_buffers; + ARROW_CHECK_OK(client2_.Get({object_id1, object_id2}, 0, &object_buffers)); + // Objects are still used by client2_. + result = client_.Delete(std::vector{object_id1, object_id2}); + ARROW_CHECK_OK(result); + // The object is used and it should not be deleted right now. + bool has_object = false; + ARROW_CHECK_OK(client_.Contains(object_id1, &has_object)); + ASSERT_TRUE(has_object); + ARROW_CHECK_OK(client_.Contains(object_id2, &has_object)); + ASSERT_TRUE(has_object); + // Decrease the ref count by deleting the PlasmaBuffer (in ObjectBuffer). + // client2_ won't send the release request immediately because the trigger + // condition is not reached. The release is only added to release cache. + object_buffers.clear(); + // Delete the objects. + result = client2_.Delete(std::vector{object_id1, object_id2}); + ARROW_CHECK_OK(client_.Contains(object_id1, &has_object)); + ASSERT_FALSE(has_object); + ARROW_CHECK_OK(client_.Contains(object_id2, &has_object)); + ASSERT_FALSE(has_object); +} + +TEST_F(TestPlasmaStore, RepeatlyCreateGPUTest) { + const int64_t loop_times = 100; + const int64_t object_num = 5; + const int64_t data_size = 40; + + std::vector object_ids; + + // create new gpu objects + for (int64_t i = 0; i < object_num; i++) { + object_ids.push_back(random_object_id()); + ObjectID& object_id = object_ids[i]; + + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id, data_size, 0, 0, &data, kGpuDeviceNumber)); + ARROW_CHECK_OK(client_.Seal(object_id)); + ARROW_CHECK_OK(client_.Release(object_id)); + } + + // delete and create again + for (int64_t i = 0; i < loop_times; i++) { + ObjectID& object_id = object_ids[i % object_num]; + + ARROW_CHECK_OK(client_.Delete(object_id)); + + std::shared_ptr data; + ARROW_CHECK_OK(client_.Create(object_id, data_size, 0, 0, &data, kGpuDeviceNumber)); + ARROW_CHECK_OK(client_.Seal(object_id)); + ARROW_CHECK_OK(client_.Release(object_id)); + } + + // delete all + ARROW_CHECK_OK(client_.Delete(object_ids)); +} + +TEST_F(TestPlasmaStore, GPUBufferLifetime) { + // ARROW-5924: GPU buffer is allowed to persist after Release() + ObjectID object_id = random_object_id(); + const int64_t data_size = 40; + + std::shared_ptr create_buff; + ARROW_CHECK_OK( + client_.Create(object_id, data_size, nullptr, 0, &create_buff, kGpuDeviceNumber)); + ARROW_CHECK_OK(client_.Seal(object_id)); + ARROW_CHECK_OK(client_.Release(object_id)); + + ObjectBuffer get_buff_1; + ARROW_CHECK_OK(client_.Get(&object_id, 1, -1, &get_buff_1)); + ObjectBuffer get_buff_2; + ARROW_CHECK_OK(client_.Get(&object_id, 1, -1, &get_buff_2)); + ARROW_CHECK_OK(client_.Release(object_id)); + ARROW_CHECK_OK(client_.Release(object_id)); + + ObjectBuffer get_buff_3; + ARROW_CHECK_OK(client_.Get(&object_id, 1, -1, &get_buff_3)); + ARROW_CHECK_OK(client_.Release(object_id)); + + ARROW_CHECK_OK(client_.Delete(object_id)); +} + +TEST_F(TestPlasmaStore, MultipleClientGPUTest) { + ObjectID object_id = random_object_id(); + std::vector object_buffers; + + // Test for object non-existence on the first client. + bool has_object; + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_FALSE(has_object); + + // Test for the object being in local Plasma store. + // First create and seal object on the second client. + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + std::shared_ptr data; + ARROW_CHECK_OK(client2_.Create(object_id, data_size, metadata, metadata_size, &data, + kGpuDeviceNumber)); + ARROW_CHECK_OK(client2_.Seal(object_id)); + // Test that the first client can get the object. + ARROW_CHECK_OK(client_.Get({object_id}, -1, &object_buffers)); + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); + + // Test that one client disconnecting does not interfere with the other. + // First create object on the second client. + object_id = random_object_id(); + ARROW_CHECK_OK(client2_.Create(object_id, data_size, metadata, metadata_size, &data, + kGpuDeviceNumber)); + // Disconnect the first client. + ARROW_CHECK_OK(client_.Disconnect()); + // Test that the second client can seal and get the created object. + ARROW_CHECK_OK(client2_.Seal(object_id)); + object_buffers.clear(); + ARROW_CHECK_OK(client2_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); + ARROW_CHECK_OK(client2_.Get({object_id}, -1, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_EQ(object_buffers[0].device_num, kGpuDeviceNumber); + AssertCudaRead(object_buffers[0].metadata, {5}); +} + +#endif // PLASMA_CUDA + +} // namespace plasma + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + plasma::test_executable = std::string(argv[0]); + return RUN_ALL_TESTS(); +} diff --git a/src/ray/plasma/test/external_store_tests.cc b/src/ray/plasma/test/external_store_tests.cc new file mode 100644 index 000000000..804e9cdc8 --- /dev/null +++ b/src/ray/plasma/test/external_store_tests.cc @@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include "arrow/testing/gtest_util.h" +#include "arrow/util/io_util.h" + +#include "plasma/client.h" +#include "plasma/common.h" +#include "plasma/external_store.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" +#include "plasma/test_util.h" + +namespace plasma { + +using arrow::internal::TemporaryDir; + +std::string external_test_executable; // NOLINT + +void AssertObjectBufferEqual(const ObjectBuffer& object_buffer, + const std::string& metadata, const std::string& data) { + arrow::AssertBufferEqual(*object_buffer.metadata, metadata); + arrow::AssertBufferEqual(*object_buffer.data, data); +} + +class TestPlasmaStoreWithExternal : public ::testing::Test { + public: + // TODO(pcm): At the moment, stdout of the test gets mixed up with + // stdout of the object store. Consider changing that. + void SetUp() override { + ASSERT_OK_AND_ASSIGN(temp_dir_, TemporaryDir::Make("ext-test-")); + store_socket_name_ = temp_dir_->path().ToString() + "store"; + + std::string plasma_directory = + external_test_executable.substr(0, external_test_executable.find_last_of('/')); + std::string plasma_command = plasma_directory + + "/plasma-store-server -m 1024000 -e " + + "hashtable://test -s " + store_socket_name_ + + " 1> /tmp/log.stdout 2> /tmp/log.stderr & " + + "echo $! > " + store_socket_name_ + ".pid"; + PLASMA_CHECK_SYSTEM(system(plasma_command.c_str())); + ARROW_CHECK_OK(client_.Connect(store_socket_name_, "")); + } + + void TearDown() override { + ARROW_CHECK_OK(client_.Disconnect()); + // Kill plasma_store process that we started +#ifdef COVERAGE_BUILD + // Ask plasma_store to exit gracefully and give it time to write out + // coverage files + std::string plasma_term_command = + "kill -TERM `cat " + store_socket_name_ + ".pid` || exit 0"; + PLASMA_CHECK_SYSTEM(system(plasma_term_command.c_str())); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); +#endif + std::string plasma_kill_command = + "kill -KILL `cat " + store_socket_name_ + ".pid` || exit 0"; + PLASMA_CHECK_SYSTEM(system(plasma_kill_command.c_str())); + } + + protected: + PlasmaClient client_; + std::unique_ptr temp_dir_; + std::string store_socket_name_; +}; + +TEST_F(TestPlasmaStoreWithExternal, EvictionTest) { + std::vector object_ids; + std::string data(100 * 1024, 'x'); + std::string metadata; + for (int i = 0; i < 20; i++) { + ObjectID object_id = random_object_id(); + object_ids.push_back(object_id); + + // Test for object non-existence. + bool has_object; + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_FALSE(has_object); + + // Test for the object being in local Plasma store. + // Create and seal the object. + ARROW_CHECK_OK(client_.CreateAndSeal(object_id, data, metadata)); + // Test that the client can get the object. + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); + ASSERT_TRUE(has_object); + } + + for (int i = 0; i < 20; i++) { + // Since we are accessing objects sequentially, every object we + // access would be a cache "miss" owing to LRU eviction. + // Try and access the object from the plasma store first, and then try + // external store on failure. This should succeed to fetch the object. + // However, it may evict the next few objects. + std::vector object_buffers; + ARROW_CHECK_OK(client_.Get({object_ids[i]}, -1, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_EQ(object_buffers[0].device_num, 0); + ASSERT_TRUE(object_buffers[0].data); + AssertObjectBufferEqual(object_buffers[0], metadata, data); + } + + // Make sure we still cannot fetch objects that do not exist + std::vector object_buffers; + ARROW_CHECK_OK(client_.Get({random_object_id()}, 100, &object_buffers)); + ASSERT_EQ(object_buffers.size(), 1); + ASSERT_EQ(object_buffers[0].device_num, 0); + ASSERT_EQ(object_buffers[0].data, nullptr); + ASSERT_EQ(object_buffers[0].metadata, nullptr); +} + +} // namespace plasma + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + plasma::external_test_executable = std::string(argv[0]); + return RUN_ALL_TESTS(); +} diff --git a/src/ray/plasma/test/serialization_tests.cc b/src/ray/plasma/test/serialization_tests.cc new file mode 100644 index 000000000..a9eea7be7 --- /dev/null +++ b/src/ray/plasma/test/serialization_tests.cc @@ -0,0 +1,333 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include + +#include +#include + +#include + +#include "arrow/testing/gtest_util.h" +#include "arrow/util/io_util.h" + +#include "plasma/common.h" +#include "plasma/io.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" +#include "plasma/test_util.h" + +namespace fb = plasma::flatbuf; + +namespace plasma { + +using arrow::internal::TemporaryDir; + +/** + * Seek to the beginning of a file and read a message from it. + * + * \param fd File descriptor of the file. + * \param message_type Message type that we expect in the file. + * + * \return Pointer to the content of the message. Needs to be freed by the + * caller. + */ +std::vector read_message_from_file(int fd, MessageType message_type) { + /* Go to the beginning of the file. */ + lseek(fd, 0, SEEK_SET); + MessageType type; + std::vector data; + Status s = ReadMessage(fd, &type, &data); + DCHECK_OK(s); + DCHECK_EQ(type, message_type); + return data; +} + +PlasmaObject random_plasma_object(void) { + unsigned int seed = static_cast(time(NULL)); + int random = rand_r(&seed); + PlasmaObject object = {}; + object.store_fd = random + 7; + object.data_offset = random + 1; + object.metadata_offset = random + 2; + object.data_size = random + 3; + object.metadata_size = random + 4; + object.device_num = 0; + return object; +} + +class TestPlasmaSerialization : public ::testing::Test { + public: + void SetUp() { ASSERT_OK_AND_ASSIGN(temp_dir_, TemporaryDir::Make("ser-test-")); } + + // Create a temporary file. + // A fd is returned which must be closed manually. The file itself + // is deleted at the end of the test. + int CreateTemporaryFile(void) { + char path[1024]; + + std::stringstream ss; + ss << temp_dir_->path().ToString() << "fileXXXXXX"; + strncpy(path, ss.str().c_str(), sizeof(path)); + ARROW_LOG(INFO) << "file path: '" << path << "'"; + return mkstemp(path); + } + + protected: + std::unique_ptr temp_dir_; +}; + +TEST_F(TestPlasmaSerialization, CreateRequest) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + int64_t data_size1 = 42; + int64_t metadata_size1 = 11; + int device_num1 = 0; + ASSERT_OK(SendCreateRequest(fd, object_id1, /*evict_if_full=*/true, data_size1, + metadata_size1, device_num1)); + std::vector data = + read_message_from_file(fd, MessageType::PlasmaCreateRequest); + ObjectID object_id2; + bool evict_if_full; + int64_t data_size2; + int64_t metadata_size2; + int device_num2; + ASSERT_OK(ReadCreateRequest(data.data(), data.size(), &object_id2, &evict_if_full, + &data_size2, &metadata_size2, &device_num2)); + ASSERT_TRUE(evict_if_full); + ASSERT_EQ(data_size1, data_size2); + ASSERT_EQ(metadata_size1, metadata_size2); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(device_num1, device_num2); + close(fd); +} + +TEST_F(TestPlasmaSerialization, CreateReply) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + PlasmaObject object1 = random_plasma_object(); + int64_t mmap_size1 = 1000000; + ASSERT_OK(SendCreateReply(fd, object_id1, &object1, PlasmaError::OK, mmap_size1)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaCreateReply); + ObjectID object_id2; + PlasmaObject object2 = {}; + int store_fd; + int64_t mmap_size2; + ASSERT_OK(ReadCreateReply(data.data(), data.size(), &object_id2, &object2, &store_fd, + &mmap_size2)); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(object1.store_fd, store_fd); + ASSERT_EQ(mmap_size1, mmap_size2); + ASSERT_EQ(memcmp(&object1, &object2, sizeof(object1)), 0); + close(fd); +} + +TEST_F(TestPlasmaSerialization, SealRequest) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + std::string digest1 = std::string(kDigestSize, 7); + ASSERT_OK(SendSealRequest(fd, object_id1, digest1)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaSealRequest); + ObjectID object_id2; + std::string digest2; + ASSERT_OK(ReadSealRequest(data.data(), data.size(), &object_id2, &digest2)); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(memcmp(digest1.data(), digest2.data(), kDigestSize), 0); + close(fd); +} + +TEST_F(TestPlasmaSerialization, SealReply) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + ASSERT_OK(SendSealReply(fd, object_id1, PlasmaError::ObjectExists)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaSealReply); + ObjectID object_id2; + Status s = ReadSealReply(data.data(), data.size(), &object_id2); + ASSERT_EQ(object_id1, object_id2); + ASSERT_TRUE(IsPlasmaObjectExists(s)); + close(fd); +} + +TEST_F(TestPlasmaSerialization, GetRequest) { + int fd = CreateTemporaryFile(); + ObjectID object_ids[2]; + object_ids[0] = random_object_id(); + object_ids[1] = random_object_id(); + int64_t timeout_ms = 1234; + ASSERT_OK(SendGetRequest(fd, object_ids, 2, timeout_ms)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaGetRequest); + std::vector object_ids_return; + int64_t timeout_ms_return; + ASSERT_OK( + ReadGetRequest(data.data(), data.size(), object_ids_return, &timeout_ms_return)); + ASSERT_EQ(object_ids[0], object_ids_return[0]); + ASSERT_EQ(object_ids[1], object_ids_return[1]); + ASSERT_EQ(timeout_ms, timeout_ms_return); + close(fd); +} + +TEST_F(TestPlasmaSerialization, GetReply) { + int fd = CreateTemporaryFile(); + ObjectID object_ids[2]; + object_ids[0] = random_object_id(); + object_ids[1] = random_object_id(); + std::unordered_map plasma_objects; + plasma_objects[object_ids[0]] = random_plasma_object(); + plasma_objects[object_ids[1]] = random_plasma_object(); + std::vector store_fds = {1, 2, 3}; + std::vector mmap_sizes = {100, 200, 300}; + ASSERT_OK(SendGetReply(fd, object_ids, plasma_objects, 2, store_fds, mmap_sizes)); + + std::vector data = read_message_from_file(fd, MessageType::PlasmaGetReply); + ObjectID object_ids_return[2]; + PlasmaObject plasma_objects_return[2]; + std::vector store_fds_return; + std::vector mmap_sizes_return; + memset(&plasma_objects_return, 0, sizeof(plasma_objects_return)); + ASSERT_OK(ReadGetReply(data.data(), data.size(), object_ids_return, + &plasma_objects_return[0], 2, store_fds_return, + mmap_sizes_return)); + + ASSERT_EQ(object_ids[0], object_ids_return[0]); + ASSERT_EQ(object_ids[1], object_ids_return[1]); + + PlasmaObject po, po2; + for (int i = 0; i < 2; ++i) { + po = plasma_objects[object_ids[i]]; + po2 = plasma_objects_return[i]; + ASSERT_EQ(po, po2); + } + ASSERT_TRUE(store_fds == store_fds_return); + ASSERT_TRUE(mmap_sizes == mmap_sizes_return); + close(fd); +} + +TEST_F(TestPlasmaSerialization, ReleaseRequest) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + ASSERT_OK(SendReleaseRequest(fd, object_id1)); + std::vector data = + read_message_from_file(fd, MessageType::PlasmaReleaseRequest); + ObjectID object_id2; + ASSERT_OK(ReadReleaseRequest(data.data(), data.size(), &object_id2)); + ASSERT_EQ(object_id1, object_id2); + close(fd); +} + +TEST_F(TestPlasmaSerialization, ReleaseReply) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + ASSERT_OK(SendReleaseReply(fd, object_id1, PlasmaError::ObjectExists)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaReleaseReply); + ObjectID object_id2; + Status s = ReadReleaseReply(data.data(), data.size(), &object_id2); + ASSERT_EQ(object_id1, object_id2); + ASSERT_TRUE(IsPlasmaObjectExists(s)); + close(fd); +} + +TEST_F(TestPlasmaSerialization, DeleteRequest) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + ASSERT_OK(SendDeleteRequest(fd, std::vector{object_id1})); + std::vector data = + read_message_from_file(fd, MessageType::PlasmaDeleteRequest); + std::vector object_vec; + ASSERT_OK(ReadDeleteRequest(data.data(), data.size(), &object_vec)); + ASSERT_EQ(object_vec.size(), 1); + ASSERT_EQ(object_id1, object_vec[0]); + close(fd); +} + +TEST_F(TestPlasmaSerialization, DeleteReply) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + PlasmaError error1 = PlasmaError::ObjectExists; + ASSERT_OK(SendDeleteReply(fd, std::vector{object_id1}, + std::vector{error1})); + std::vector data = read_message_from_file(fd, MessageType::PlasmaDeleteReply); + std::vector object_vec; + std::vector error_vec; + Status s = ReadDeleteReply(data.data(), data.size(), &object_vec, &error_vec); + ASSERT_EQ(object_vec.size(), 1); + ASSERT_EQ(object_id1, object_vec[0]); + ASSERT_EQ(error_vec.size(), 1); + ASSERT_TRUE(error_vec[0] == PlasmaError::ObjectExists); + ASSERT_TRUE(s.ok()); + close(fd); +} + +TEST_F(TestPlasmaSerialization, EvictRequest) { + int fd = CreateTemporaryFile(); + int64_t num_bytes = 111; + ASSERT_OK(SendEvictRequest(fd, num_bytes)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaEvictRequest); + int64_t num_bytes_received; + ASSERT_OK(ReadEvictRequest(data.data(), data.size(), &num_bytes_received)); + ASSERT_EQ(num_bytes, num_bytes_received); + close(fd); +} + +TEST_F(TestPlasmaSerialization, EvictReply) { + int fd = CreateTemporaryFile(); + int64_t num_bytes = 111; + ASSERT_OK(SendEvictReply(fd, num_bytes)); + std::vector data = read_message_from_file(fd, MessageType::PlasmaEvictReply); + int64_t num_bytes_received; + ASSERT_OK(ReadEvictReply(data.data(), data.size(), num_bytes_received)); + ASSERT_EQ(num_bytes, num_bytes_received); + close(fd); +} + +TEST_F(TestPlasmaSerialization, DataRequest) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + const char* address1 = "address1"; + int port1 = 12345; + ASSERT_OK(SendDataRequest(fd, object_id1, address1, port1)); + /* Reading message back. */ + std::vector data = read_message_from_file(fd, MessageType::PlasmaDataRequest); + ObjectID object_id2; + char* address2; + int port2; + ASSERT_OK(ReadDataRequest(data.data(), data.size(), &object_id2, &address2, &port2)); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(strcmp(address1, address2), 0); + ASSERT_EQ(port1, port2); + free(address2); + close(fd); +} + +TEST_F(TestPlasmaSerialization, DataReply) { + int fd = CreateTemporaryFile(); + ObjectID object_id1 = random_object_id(); + int64_t object_size1 = 146; + int64_t metadata_size1 = 198; + ASSERT_OK(SendDataReply(fd, object_id1, object_size1, metadata_size1)); + /* Reading message back. */ + std::vector data = read_message_from_file(fd, MessageType::PlasmaDataReply); + ObjectID object_id2; + int64_t object_size2; + int64_t metadata_size2; + ASSERT_OK(ReadDataReply(data.data(), data.size(), &object_id2, &object_size2, + &metadata_size2)); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(object_size1, object_size2); + ASSERT_EQ(metadata_size1, metadata_size2); +} + +} // namespace plasma diff --git a/src/ray/plasma/test_util.h b/src/ray/plasma/test_util.h new file mode 100644 index 000000000..3173d9478 --- /dev/null +++ b/src/ray/plasma/test_util.h @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PLASMA_TEST_UTIL_H +#define PLASMA_TEST_UTIL_H + +#include +#include +#include + +#include "plasma/common.h" + +namespace plasma { + +ObjectID random_object_id() { + static uint32_t random_seed = 0; + std::mt19937 gen(random_seed++); + std::uniform_int_distribution d(0, std::numeric_limits::max()); + ObjectID result; + uint8_t* data = result.mutable_data(); + std::generate(data, data + kUniqueIDSize, + [&d, &gen] { return static_cast(d(gen)); }); + return result; +} + +#define PLASMA_CHECK_SYSTEM(expr) \ + do { \ + int status__ = (expr); \ + EXPECT_TRUE(WIFEXITED(status__)); \ + EXPECT_EQ(WEXITSTATUS(status__), 0); \ + } while (false); + +} // namespace plasma + +#endif // PLASMA_TEST_UTIL_H diff --git a/src/ray/plasma/thirdparty/ae/ae.c b/src/ray/plasma/thirdparty/ae/ae.c new file mode 100644 index 000000000..dfb722444 --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/ae.c @@ -0,0 +1,465 @@ +/* A simple event-driven programming library. Originally I wrote this code + * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated + * it in form of a library for easy reuse. + * + * Copyright (c) 2006-2010, Salvatore Sanfilippo + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "plasma/thirdparty/ae/ae.h" +#include "plasma/thirdparty/ae/zmalloc.h" +#include "plasma/thirdparty/ae/config.h" + +/* Include the best multiplexing layer supported by this system. + * The following should be ordered by performances, descending. */ +#ifdef HAVE_EVPORT +#include "plasma/thirdparty/ae/ae_evport.c" +#else + #ifdef HAVE_EPOLL + #include "plasma/thirdparty/ae/ae_epoll.c" + #else + #ifdef HAVE_KQUEUE + #include "plasma/thirdparty/ae/ae_kqueue.c" + #else + #include "plasma/thirdparty/ae/ae_select.c" + #endif + #endif +#endif + +aeEventLoop *aeCreateEventLoop(int setsize) { + aeEventLoop *eventLoop; + int i; + + if ((eventLoop = zmalloc(sizeof(*eventLoop))) == NULL) goto err; + eventLoop->events = zmalloc(sizeof(aeFileEvent)*setsize); + eventLoop->fired = zmalloc(sizeof(aeFiredEvent)*setsize); + if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err; + eventLoop->setsize = setsize; + eventLoop->lastTime = time(NULL); + eventLoop->timeEventHead = NULL; + eventLoop->timeEventNextId = 0; + eventLoop->stop = 0; + eventLoop->maxfd = -1; + eventLoop->beforesleep = NULL; + if (aeApiCreate(eventLoop) == -1) goto err; + /* Events with mask == AE_NONE are not set. So let's initialize the + * vector with it. */ + for (i = 0; i < setsize; i++) + eventLoop->events[i].mask = AE_NONE; + return eventLoop; + +err: + if (eventLoop) { + zfree(eventLoop->events); + zfree(eventLoop->fired); + zfree(eventLoop); + } + return NULL; +} + +/* Return the current set size. */ +int aeGetSetSize(aeEventLoop *eventLoop) { + return eventLoop->setsize; +} + +/* Resize the maximum set size of the event loop. + * If the requested set size is smaller than the current set size, but + * there is already a file descriptor in use that is >= the requested + * set size minus one, AE_ERR is returned and the operation is not + * performed at all. + * + * Otherwise AE_OK is returned and the operation is successful. */ +int aeResizeSetSize(aeEventLoop *eventLoop, int setsize) { + int i; + + if (setsize == eventLoop->setsize) return AE_OK; + if (eventLoop->maxfd >= setsize) return AE_ERR; + if (aeApiResize(eventLoop,setsize) == -1) return AE_ERR; + + eventLoop->events = zrealloc(eventLoop->events,sizeof(aeFileEvent)*setsize); + eventLoop->fired = zrealloc(eventLoop->fired,sizeof(aeFiredEvent)*setsize); + eventLoop->setsize = setsize; + + /* Make sure that if we created new slots, they are initialized with + * an AE_NONE mask. */ + for (i = eventLoop->maxfd+1; i < setsize; i++) + eventLoop->events[i].mask = AE_NONE; + return AE_OK; +} + +void aeDeleteEventLoop(aeEventLoop *eventLoop) { + aeApiFree(eventLoop); + zfree(eventLoop->events); + zfree(eventLoop->fired); + zfree(eventLoop); +} + +void aeStop(aeEventLoop *eventLoop) { + eventLoop->stop = 1; +} + +int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, + aeFileProc *proc, void *clientData) +{ + if (fd >= eventLoop->setsize) { + errno = ERANGE; + return AE_ERR; + } + aeFileEvent *fe = &eventLoop->events[fd]; + + if (aeApiAddEvent(eventLoop, fd, mask) == -1) + return AE_ERR; + fe->mask |= mask; + if (mask & AE_READABLE) fe->rfileProc = proc; + if (mask & AE_WRITABLE) fe->wfileProc = proc; + fe->clientData = clientData; + if (fd > eventLoop->maxfd) + eventLoop->maxfd = fd; + return AE_OK; +} + +void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask) +{ + if (fd >= eventLoop->setsize) return; + aeFileEvent *fe = &eventLoop->events[fd]; + if (fe->mask == AE_NONE) return; + + aeApiDelEvent(eventLoop, fd, mask); + fe->mask = fe->mask & (~mask); + if (fd == eventLoop->maxfd && fe->mask == AE_NONE) { + /* Update the max fd */ + int j; + + for (j = eventLoop->maxfd-1; j >= 0; j--) + if (eventLoop->events[j].mask != AE_NONE) break; + eventLoop->maxfd = j; + } +} + +int aeGetFileEvents(aeEventLoop *eventLoop, int fd) { + if (fd >= eventLoop->setsize) return 0; + aeFileEvent *fe = &eventLoop->events[fd]; + + return fe->mask; +} + +static void aeGetTime(long *seconds, long *milliseconds) +{ + struct timeval tv; + + gettimeofday(&tv, NULL); + *seconds = tv.tv_sec; + *milliseconds = tv.tv_usec/1000; +} + +static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) { + long cur_sec, cur_ms, when_sec, when_ms; + + aeGetTime(&cur_sec, &cur_ms); + when_sec = cur_sec + milliseconds/1000; + when_ms = cur_ms + milliseconds%1000; + if (when_ms >= 1000) { + when_sec ++; + when_ms -= 1000; + } + *sec = when_sec; + *ms = when_ms; +} + +long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, + aeTimeProc *proc, void *clientData, + aeEventFinalizerProc *finalizerProc) +{ + long long id = eventLoop->timeEventNextId++; + aeTimeEvent *te; + + te = zmalloc(sizeof(*te)); + if (te == NULL) return AE_ERR; + te->id = id; + aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms); + te->timeProc = proc; + te->finalizerProc = finalizerProc; + te->clientData = clientData; + te->next = eventLoop->timeEventHead; + eventLoop->timeEventHead = te; + return id; +} + +int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id) +{ + aeTimeEvent *te = eventLoop->timeEventHead; + while(te) { + if (te->id == id) { + te->id = AE_DELETED_EVENT_ID; + return AE_OK; + } + te = te->next; + } + return AE_ERR; /* NO event with the specified ID found */ +} + +/* Search the first timer to fire. + * This operation is useful to know how many time the select can be + * put in sleep without to delay any event. + * If there are no timers NULL is returned. + * + * Note that's O(N) since time events are unsorted. + * Possible optimizations (not needed by Redis so far, but...): + * 1) Insert the event in order, so that the nearest is just the head. + * Much better but still insertion or deletion of timers is O(N). + * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)). + */ +static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop) +{ + aeTimeEvent *te = eventLoop->timeEventHead; + aeTimeEvent *nearest = NULL; + + while(te) { + if (!nearest || te->when_sec < nearest->when_sec || + (te->when_sec == nearest->when_sec && + te->when_ms < nearest->when_ms)) + nearest = te; + te = te->next; + } + return nearest; +} + +/* Process time events */ +static int processTimeEvents(aeEventLoop *eventLoop) { + int processed = 0; + aeTimeEvent *te, *prev; + long long maxId; + time_t now = time(NULL); + + /* If the system clock is moved to the future, and then set back to the + * right value, time events may be delayed in a random way. Often this + * means that scheduled operations will not be performed soon enough. + * + * Here we try to detect system clock skews, and force all the time + * events to be processed ASAP when this happens: the idea is that + * processing events earlier is less dangerous than delaying them + * indefinitely, and practice suggests it is. */ + if (now < eventLoop->lastTime) { + te = eventLoop->timeEventHead; + while(te) { + te->when_sec = 0; + te = te->next; + } + } + eventLoop->lastTime = now; + + prev = NULL; + te = eventLoop->timeEventHead; + maxId = eventLoop->timeEventNextId-1; + while(te) { + long now_sec, now_ms; + long long id; + + /* Remove events scheduled for deletion. */ + if (te->id == AE_DELETED_EVENT_ID) { + aeTimeEvent *next = te->next; + if (prev == NULL) + eventLoop->timeEventHead = te->next; + else + prev->next = te->next; + if (te->finalizerProc) + te->finalizerProc(eventLoop, te->clientData); + zfree(te); + te = next; + continue; + } + + /* Make sure we don't process time events created by time events in + * this iteration. Note that this check is currently useless: we always + * add new timers on the head, however if we change the implementation + * detail, this check may be useful again: we keep it here for future + * defense. */ + if (te->id > maxId) { + te = te->next; + continue; + } + aeGetTime(&now_sec, &now_ms); + if (now_sec > te->when_sec || + (now_sec == te->when_sec && now_ms >= te->when_ms)) + { + int retval; + + id = te->id; + retval = te->timeProc(eventLoop, id, te->clientData); + processed++; + if (retval != AE_NOMORE) { + aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms); + } else { + te->id = AE_DELETED_EVENT_ID; + } + } + prev = te; + te = te->next; + } + return processed; +} + +/* Process every pending time event, then every pending file event + * (that may be registered by time event callbacks just processed). + * Without special flags the function sleeps until some file event + * fires, or when the next time event occurs (if any). + * + * If flags is 0, the function does nothing and returns. + * if flags has AE_ALL_EVENTS set, all the kind of events are processed. + * if flags has AE_FILE_EVENTS set, file events are processed. + * if flags has AE_TIME_EVENTS set, time events are processed. + * if flags has AE_DONT_WAIT set the function returns ASAP until all + * the events that's possible to process without to wait are processed. + * + * The function returns the number of events processed. */ +int aeProcessEvents(aeEventLoop *eventLoop, int flags) +{ + int processed = 0, numevents; + + /* Nothing to do? return ASAP */ + if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0; + + /* Note that we want call select() even if there are no + * file events to process as long as we want to process time + * events, in order to sleep until the next time event is ready + * to fire. */ + if (eventLoop->maxfd != -1 || + ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { + int j; + aeTimeEvent *shortest = NULL; + struct timeval tv, *tvp; + + if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) + shortest = aeSearchNearestTimer(eventLoop); + if (shortest) { + long now_sec, now_ms; + + aeGetTime(&now_sec, &now_ms); + tvp = &tv; + + /* How many milliseconds we need to wait for the next + * time event to fire? */ + long long ms = + (shortest->when_sec - now_sec)*1000 + + shortest->when_ms - now_ms; + + if (ms > 0) { + tvp->tv_sec = ms/1000; + tvp->tv_usec = (ms % 1000)*1000; + } else { + tvp->tv_sec = 0; + tvp->tv_usec = 0; + } + } else { + /* If we have to check for events but need to return + * ASAP because of AE_DONT_WAIT we need to set the timeout + * to zero */ + if (flags & AE_DONT_WAIT) { + tv.tv_sec = tv.tv_usec = 0; + tvp = &tv; + } else { + /* Otherwise we can block */ + tvp = NULL; /* wait forever */ + } + } + + numevents = aeApiPoll(eventLoop, tvp); + for (j = 0; j < numevents; j++) { + aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; + int mask = eventLoop->fired[j].mask; + int fd = eventLoop->fired[j].fd; + int rfired = 0; + + /* note the fe->mask & mask & ... code: maybe an already processed + * event removed an element that fired and we still didn't + * processed, so we check if the event is still valid. */ + if (fe->mask & mask & AE_READABLE) { + rfired = 1; + fe->rfileProc(eventLoop,fd,fe->clientData,mask); + } + if (fe->mask & mask & AE_WRITABLE) { + if (!rfired || fe->wfileProc != fe->rfileProc) + fe->wfileProc(eventLoop,fd,fe->clientData,mask); + } + processed++; + } + } + /* Check time events */ + if (flags & AE_TIME_EVENTS) + processed += processTimeEvents(eventLoop); + + return processed; /* return the number of processed file/time events */ +} + +/* Wait for milliseconds until the given file descriptor becomes + * writable/readable/exception */ +int aeWait(int fd, int mask, long long milliseconds) { + struct pollfd pfd; + int retmask = 0, retval; + + memset(&pfd, 0, sizeof(pfd)); + pfd.fd = fd; + if (mask & AE_READABLE) pfd.events |= POLLIN; + if (mask & AE_WRITABLE) pfd.events |= POLLOUT; + + if ((retval = poll(&pfd, 1, milliseconds))== 1) { + if (pfd.revents & POLLIN) retmask |= AE_READABLE; + if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE; + if (pfd.revents & POLLERR) retmask |= AE_WRITABLE; + if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE; + return retmask; + } else { + return retval; + } +} + +void aeMain(aeEventLoop *eventLoop) { + eventLoop->stop = 0; + while (!eventLoop->stop) { + if (eventLoop->beforesleep != NULL) + eventLoop->beforesleep(eventLoop); + aeProcessEvents(eventLoop, AE_ALL_EVENTS); + } +} + +char *aeGetApiName(void) { + return aeApiName(); +} + +void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) { + eventLoop->beforesleep = beforesleep; +} diff --git a/src/ray/plasma/thirdparty/ae/ae.h b/src/ray/plasma/thirdparty/ae/ae.h new file mode 100644 index 000000000..827c4c9e4 --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/ae.h @@ -0,0 +1,123 @@ +/* A simple event-driven programming library. Originally I wrote this code + * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated + * it in form of a library for easy reuse. + * + * Copyright (c) 2006-2012, Salvatore Sanfilippo + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + +#ifndef __AE_H__ +#define __AE_H__ + +#include + +#define AE_OK 0 +#define AE_ERR -1 + +#define AE_NONE 0 +#define AE_READABLE 1 +#define AE_WRITABLE 2 + +#define AE_FILE_EVENTS 1 +#define AE_TIME_EVENTS 2 +#define AE_ALL_EVENTS (AE_FILE_EVENTS|AE_TIME_EVENTS) +#define AE_DONT_WAIT 4 + +#define AE_NOMORE -1 +#define AE_DELETED_EVENT_ID -1 + +/* Macros */ +#define AE_NOTUSED(V) ((void) V) + +struct aeEventLoop; + +/* Types and data structures */ +typedef void aeFileProc(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask); +typedef int aeTimeProc(struct aeEventLoop *eventLoop, long long id, void *clientData); +typedef void aeEventFinalizerProc(struct aeEventLoop *eventLoop, void *clientData); +typedef void aeBeforeSleepProc(struct aeEventLoop *eventLoop); + +/* File event structure */ +typedef struct aeFileEvent { + int mask; /* one of AE_(READABLE|WRITABLE) */ + aeFileProc *rfileProc; + aeFileProc *wfileProc; + void *clientData; +} aeFileEvent; + +/* Time event structure */ +typedef struct aeTimeEvent { + long long id; /* time event identifier. */ + long when_sec; /* seconds */ + long when_ms; /* milliseconds */ + aeTimeProc *timeProc; + aeEventFinalizerProc *finalizerProc; + void *clientData; + struct aeTimeEvent *next; +} aeTimeEvent; + +/* A fired event */ +typedef struct aeFiredEvent { + int fd; + int mask; +} aeFiredEvent; + +/* State of an event based program */ +typedef struct aeEventLoop { + int maxfd; /* highest file descriptor currently registered */ + int setsize; /* max number of file descriptors tracked */ + long long timeEventNextId; + time_t lastTime; /* Used to detect system clock skew */ + aeFileEvent *events; /* Registered events */ + aeFiredEvent *fired; /* Fired events */ + aeTimeEvent *timeEventHead; + int stop; + void *apidata; /* This is used for polling API specific data */ + aeBeforeSleepProc *beforesleep; +} aeEventLoop; + +/* Prototypes */ +aeEventLoop *aeCreateEventLoop(int setsize); +void aeDeleteEventLoop(aeEventLoop *eventLoop); +void aeStop(aeEventLoop *eventLoop); +int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, + aeFileProc *proc, void *clientData); +void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask); +int aeGetFileEvents(aeEventLoop *eventLoop, int fd); +long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, + aeTimeProc *proc, void *clientData, + aeEventFinalizerProc *finalizerProc); +int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id); +int aeProcessEvents(aeEventLoop *eventLoop, int flags); +int aeWait(int fd, int mask, long long milliseconds); +void aeMain(aeEventLoop *eventLoop); +char *aeGetApiName(void); +void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep); +int aeGetSetSize(aeEventLoop *eventLoop); +int aeResizeSetSize(aeEventLoop *eventLoop, int setsize); + +#endif diff --git a/src/ray/plasma/thirdparty/ae/ae_epoll.c b/src/ray/plasma/thirdparty/ae/ae_epoll.c new file mode 100644 index 000000000..2f70550a9 --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/ae_epoll.c @@ -0,0 +1,137 @@ +/* Linux epoll(2) based ae.c module + * + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + + +#include + +typedef struct aeApiState { + int epfd; + struct epoll_event *events; +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize); + if (!state->events) { + zfree(state); + return -1; + } + state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */ + if (state->epfd == -1) { + zfree(state->events); + zfree(state); + return -1; + } + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + aeApiState *state = eventLoop->apidata; + + state->events = zrealloc(state->events, sizeof(struct epoll_event)*setsize); + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + aeApiState *state = eventLoop->apidata; + + close(state->epfd); + zfree(state->events); + zfree(state); +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct epoll_event ee; + memset(&ee, 0, sizeof(struct epoll_event)); // avoid valgrind warning + /* If the fd was already monitored for some event, we need a MOD + * operation. Otherwise we need an ADD operation. */ + int op = eventLoop->events[fd].mask == AE_NONE ? + EPOLL_CTL_ADD : EPOLL_CTL_MOD; + + ee.events = 0; + mask |= eventLoop->events[fd].mask; /* Merge old events */ + if (mask & AE_READABLE) ee.events |= EPOLLIN; + if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; + ee.data.fd = fd; + if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1; + return 0; +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int delmask) { + aeApiState *state = eventLoop->apidata; + struct epoll_event ee; + memset(&ee, 0, sizeof(struct epoll_event)); // avoid valgrind warning + int mask = eventLoop->events[fd].mask & (~delmask); + + ee.events = 0; + if (mask & AE_READABLE) ee.events |= EPOLLIN; + if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; + ee.data.fd = fd; + if (mask != AE_NONE) { + epoll_ctl(state->epfd,EPOLL_CTL_MOD,fd,&ee); + } else { + /* Note, Kernel < 2.6.9 requires a non null event pointer even for + * EPOLL_CTL_DEL. */ + epoll_ctl(state->epfd,EPOLL_CTL_DEL,fd,&ee); + } +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, numevents = 0; + + retval = epoll_wait(state->epfd,state->events,eventLoop->setsize, + tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1); + if (retval > 0) { + int j; + + numevents = retval; + for (j = 0; j < numevents; j++) { + int mask = 0; + struct epoll_event *e = state->events+j; + + if (e->events & EPOLLIN) mask |= AE_READABLE; + if (e->events & EPOLLOUT) mask |= AE_WRITABLE; + if (e->events & EPOLLERR) mask |= AE_WRITABLE; + if (e->events & EPOLLHUP) mask |= AE_WRITABLE; + eventLoop->fired[j].fd = e->data.fd; + eventLoop->fired[j].mask = mask; + } + } + return numevents; +} + +static char *aeApiName(void) { + return "epoll"; +} diff --git a/src/ray/plasma/thirdparty/ae/ae_evport.c b/src/ray/plasma/thirdparty/ae/ae_evport.c new file mode 100644 index 000000000..b79ed9bc7 --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/ae_evport.c @@ -0,0 +1,320 @@ +/* ae.c module for illumos event ports. + * + * Copyright (c) 2012, Joyent, Inc. All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + + +#include +#include +#include +#include + +#include +#include + +#include + +static int evport_debug = 0; + +/* + * This file implements the ae API using event ports, present on Solaris-based + * systems since Solaris 10. Using the event port interface, we associate file + * descriptors with the port. Each association also includes the set of poll(2) + * events that the consumer is interested in (e.g., POLLIN and POLLOUT). + * + * There's one tricky piece to this implementation: when we return events via + * aeApiPoll, the corresponding file descriptors become dissociated from the + * port. This is necessary because poll events are level-triggered, so if the + * fd didn't become dissociated, it would immediately fire another event since + * the underlying state hasn't changed yet. We must re-associate the file + * descriptor, but only after we know that our caller has actually read from it. + * The ae API does not tell us exactly when that happens, but we do know that + * it must happen by the time aeApiPoll is called again. Our solution is to + * keep track of the last fds returned by aeApiPoll and re-associate them next + * time aeApiPoll is invoked. + * + * To summarize, in this module, each fd association is EITHER (a) represented + * only via the in-kernel association OR (b) represented by pending_fds and + * pending_masks. (b) is only true for the last fds we returned from aeApiPoll, + * and only until we enter aeApiPoll again (at which point we restore the + * in-kernel association). + */ +#define MAX_EVENT_BATCHSZ 512 + +typedef struct aeApiState { + int portfd; /* event port */ + int npending; /* # of pending fds */ + int pending_fds[MAX_EVENT_BATCHSZ]; /* pending fds */ + int pending_masks[MAX_EVENT_BATCHSZ]; /* pending fds' masks */ +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + int i; + aeApiState *state = zmalloc(sizeof(aeApiState)); + if (!state) return -1; + + state->portfd = port_create(); + if (state->portfd == -1) { + zfree(state); + return -1; + } + + state->npending = 0; + + for (i = 0; i < MAX_EVENT_BATCHSZ; i++) { + state->pending_fds[i] = -1; + state->pending_masks[i] = AE_NONE; + } + + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + /* Nothing to resize here. */ + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + aeApiState *state = eventLoop->apidata; + + close(state->portfd); + zfree(state); +} + +static int aeApiLookupPending(aeApiState *state, int fd) { + int i; + + for (i = 0; i < state->npending; i++) { + if (state->pending_fds[i] == fd) + return (i); + } + + return (-1); +} + +/* + * Helper function to invoke port_associate for the given fd and mask. + */ +static int aeApiAssociate(const char *where, int portfd, int fd, int mask) { + int events = 0; + int rv, err; + + if (mask & AE_READABLE) + events |= POLLIN; + if (mask & AE_WRITABLE) + events |= POLLOUT; + + if (evport_debug) + fprintf(stderr, "%s: port_associate(%d, 0x%x) = ", where, fd, events); + + rv = port_associate(portfd, PORT_SOURCE_FD, fd, events, + (void *)(uintptr_t)mask); + err = errno; + + if (evport_debug) + fprintf(stderr, "%d (%s)\n", rv, rv == 0 ? "no error" : strerror(err)); + + if (rv == -1) { + fprintf(stderr, "%s: port_associate: %s\n", where, strerror(err)); + + if (err == EAGAIN) + fprintf(stderr, "aeApiAssociate: event port limit exceeded."); + } + + return rv; +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + int fullmask, pfd; + + if (evport_debug) + fprintf(stderr, "aeApiAddEvent: fd %d mask 0x%x\n", fd, mask); + + /* + * Since port_associate's "events" argument replaces any existing events, we + * must be sure to include whatever events are already associated when + * we call port_associate() again. + */ + fullmask = mask | eventLoop->events[fd].mask; + pfd = aeApiLookupPending(state, fd); + + if (pfd != -1) { + /* + * This fd was recently returned from aeApiPoll. It should be safe to + * assume that the consumer has processed that poll event, but we play + * it safer by simply updating pending_mask. The fd will be + * re-associated as usual when aeApiPoll is called again. + */ + if (evport_debug) + fprintf(stderr, "aeApiAddEvent: adding to pending fd %d\n", fd); + state->pending_masks[pfd] |= fullmask; + return 0; + } + + return (aeApiAssociate("aeApiAddEvent", state->portfd, fd, fullmask)); +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + int fullmask, pfd; + + if (evport_debug) + fprintf(stderr, "del fd %d mask 0x%x\n", fd, mask); + + pfd = aeApiLookupPending(state, fd); + + if (pfd != -1) { + if (evport_debug) + fprintf(stderr, "deleting event from pending fd %d\n", fd); + + /* + * This fd was just returned from aeApiPoll, so it's not currently + * associated with the port. All we need to do is update + * pending_mask appropriately. + */ + state->pending_masks[pfd] &= ~mask; + + if (state->pending_masks[pfd] == AE_NONE) + state->pending_fds[pfd] = -1; + + return; + } + + /* + * The fd is currently associated with the port. Like with the add case + * above, we must look at the full mask for the file descriptor before + * updating that association. We don't have a good way of knowing what the + * events are without looking into the eventLoop state directly. We rely on + * the fact that our caller has already updated the mask in the eventLoop. + */ + + fullmask = eventLoop->events[fd].mask; + if (fullmask == AE_NONE) { + /* + * We're removing *all* events, so use port_dissociate to remove the + * association completely. Failure here indicates a bug. + */ + if (evport_debug) + fprintf(stderr, "aeApiDelEvent: port_dissociate(%d)\n", fd); + + if (port_dissociate(state->portfd, PORT_SOURCE_FD, fd) != 0) { + perror("aeApiDelEvent: port_dissociate"); + abort(); /* will not return */ + } + } else if (aeApiAssociate("aeApiDelEvent", state->portfd, fd, + fullmask) != 0) { + /* + * ENOMEM is a potentially transient condition, but the kernel won't + * generally return it unless things are really bad. EAGAIN indicates + * we've reached a resource limit, for which it doesn't make sense to + * retry (counter-intuitively). All other errors indicate a bug. In any + * of these cases, the best we can do is to abort. + */ + abort(); /* will not return */ + } +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + struct timespec timeout, *tsp; + int mask, i; + uint_t nevents; + port_event_t event[MAX_EVENT_BATCHSZ]; + + /* + * If we've returned fd events before, we must re-associate them with the + * port now, before calling port_get(). See the block comment at the top of + * this file for an explanation of why. + */ + for (i = 0; i < state->npending; i++) { + if (state->pending_fds[i] == -1) + /* This fd has since been deleted. */ + continue; + + if (aeApiAssociate("aeApiPoll", state->portfd, + state->pending_fds[i], state->pending_masks[i]) != 0) { + /* See aeApiDelEvent for why this case is fatal. */ + abort(); + } + + state->pending_masks[i] = AE_NONE; + state->pending_fds[i] = -1; + } + + state->npending = 0; + + if (tvp != NULL) { + timeout.tv_sec = tvp->tv_sec; + timeout.tv_nsec = tvp->tv_usec * 1000; + tsp = &timeout; + } else { + tsp = NULL; + } + + /* + * port_getn can return with errno == ETIME having returned some events (!). + * So if we get ETIME, we check nevents, too. + */ + nevents = 1; + if (port_getn(state->portfd, event, MAX_EVENT_BATCHSZ, &nevents, + tsp) == -1 && (errno != ETIME || nevents == 0)) { + if (errno == ETIME || errno == EINTR) + return 0; + + /* Any other error indicates a bug. */ + perror("aeApiPoll: port_get"); + abort(); + } + + state->npending = nevents; + + for (i = 0; i < nevents; i++) { + mask = 0; + if (event[i].portev_events & POLLIN) + mask |= AE_READABLE; + if (event[i].portev_events & POLLOUT) + mask |= AE_WRITABLE; + + eventLoop->fired[i].fd = event[i].portev_object; + eventLoop->fired[i].mask = mask; + + if (evport_debug) + fprintf(stderr, "aeApiPoll: fd %d mask 0x%x\n", + (int)event[i].portev_object, mask); + + state->pending_fds[i] = event[i].portev_object; + state->pending_masks[i] = (uintptr_t)event[i].portev_user; + } + + return nevents; +} + +static char *aeApiName(void) { + return "evport"; +} diff --git a/src/ray/plasma/thirdparty/ae/ae_kqueue.c b/src/ray/plasma/thirdparty/ae/ae_kqueue.c new file mode 100644 index 000000000..6796f4ceb --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/ae_kqueue.c @@ -0,0 +1,138 @@ +/* Kqueue(2)-based ae.c module + * + * Copyright (C) 2009 Harish Mallipeddi - harish.mallipeddi@gmail.com + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + + +#include +#include +#include + +typedef struct aeApiState { + int kqfd; + struct kevent *events; +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + state->events = zmalloc(sizeof(struct kevent)*eventLoop->setsize); + if (!state->events) { + zfree(state); + return -1; + } + state->kqfd = kqueue(); + if (state->kqfd == -1) { + zfree(state->events); + zfree(state); + return -1; + } + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + aeApiState *state = eventLoop->apidata; + + state->events = zrealloc(state->events, sizeof(struct kevent)*setsize); + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + aeApiState *state = eventLoop->apidata; + + close(state->kqfd); + zfree(state->events); + zfree(state); +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct kevent ke; + + if (mask & AE_READABLE) { + EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, NULL); + if (kevent(state->kqfd, &ke, 1, NULL, 0, NULL) == -1) return -1; + } + if (mask & AE_WRITABLE) { + EV_SET(&ke, fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL); + if (kevent(state->kqfd, &ke, 1, NULL, 0, NULL) == -1) return -1; + } + return 0; +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct kevent ke; + + if (mask & AE_READABLE) { + EV_SET(&ke, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); + kevent(state->kqfd, &ke, 1, NULL, 0, NULL); + } + if (mask & AE_WRITABLE) { + EV_SET(&ke, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); + kevent(state->kqfd, &ke, 1, NULL, 0, NULL); + } +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, numevents = 0; + + if (tvp != NULL) { + struct timespec timeout; + timeout.tv_sec = tvp->tv_sec; + timeout.tv_nsec = tvp->tv_usec * 1000; + retval = kevent(state->kqfd, NULL, 0, state->events, eventLoop->setsize, + &timeout); + } else { + retval = kevent(state->kqfd, NULL, 0, state->events, eventLoop->setsize, + NULL); + } + + if (retval > 0) { + int j; + + numevents = retval; + for(j = 0; j < numevents; j++) { + int mask = 0; + struct kevent *e = state->events+j; + + if (e->filter == EVFILT_READ) mask |= AE_READABLE; + if (e->filter == EVFILT_WRITE) mask |= AE_WRITABLE; + eventLoop->fired[j].fd = e->ident; + eventLoop->fired[j].mask = mask; + } + } + return numevents; +} + +static char *aeApiName(void) { + return "kqueue"; +} diff --git a/src/ray/plasma/thirdparty/ae/ae_select.c b/src/ray/plasma/thirdparty/ae/ae_select.c new file mode 100644 index 000000000..c039a8ea3 --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/ae_select.c @@ -0,0 +1,106 @@ +/* Select()-based ae.c module. + * + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + + +#include +#include + +typedef struct aeApiState { + fd_set rfds, wfds; + /* We need to have a copy of the fd sets as it's not safe to reuse + * FD sets after select(). */ + fd_set _rfds, _wfds; +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + FD_ZERO(&state->rfds); + FD_ZERO(&state->wfds); + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + /* Just ensure we have enough room in the fd_set type. */ + if (setsize >= FD_SETSIZE) return -1; + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + zfree(eventLoop->apidata); +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + + if (mask & AE_READABLE) FD_SET(fd,&state->rfds); + if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds); + return 0; +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + + if (mask & AE_READABLE) FD_CLR(fd,&state->rfds); + if (mask & AE_WRITABLE) FD_CLR(fd,&state->wfds); +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, j, numevents = 0; + + memcpy(&state->_rfds,&state->rfds,sizeof(fd_set)); + memcpy(&state->_wfds,&state->wfds,sizeof(fd_set)); + + retval = select(eventLoop->maxfd+1, + &state->_rfds,&state->_wfds,NULL,tvp); + if (retval > 0) { + for (j = 0; j <= eventLoop->maxfd; j++) { + int mask = 0; + aeFileEvent *fe = &eventLoop->events[j]; + + if (fe->mask == AE_NONE) continue; + if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds)) + mask |= AE_READABLE; + if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds)) + mask |= AE_WRITABLE; + eventLoop->fired[numevents].fd = j; + eventLoop->fired[numevents].mask = mask; + numevents++; + } + } + return numevents; +} + +static char *aeApiName(void) { + return "select"; +} diff --git a/src/ray/plasma/thirdparty/ae/config.h b/src/ray/plasma/thirdparty/ae/config.h new file mode 100644 index 000000000..4f8e1ea1b --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/config.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + +#ifndef __CONFIG_H +#define __CONFIG_H + +#ifdef __APPLE__ +#include +#endif + +/* Test for polling API */ +#ifdef __linux__ +#define HAVE_EPOLL 1 +#endif + +#if (defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__) +#define HAVE_KQUEUE 1 +#endif + +#ifdef __sun +#include +#ifdef _DTRACE_VERSION +#define HAVE_EVPORT 1 +#endif +#endif + + +#endif diff --git a/src/ray/plasma/thirdparty/ae/zmalloc.h b/src/ray/plasma/thirdparty/ae/zmalloc.h new file mode 100644 index 000000000..6c27dd4e5 --- /dev/null +++ b/src/ray/plasma/thirdparty/ae/zmalloc.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * All rights reserved. + * + * Redistribution and use 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. + * * Neither the name of Redis nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * 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. + */ + +#ifndef _ZMALLOC_H +#define _ZMALLOC_H + +#ifndef zmalloc +#define zmalloc malloc +#endif + +#ifndef zfree +#define zfree free +#endif + +#ifndef zrealloc +#define zrealloc realloc +#endif + +#endif /* _ZMALLOC_H */ diff --git a/src/ray/plasma/thirdparty/dlmalloc.c b/src/ray/plasma/thirdparty/dlmalloc.c new file mode 100644 index 000000000..6fb0fb00f --- /dev/null +++ b/src/ray/plasma/thirdparty/dlmalloc.c @@ -0,0 +1,6296 @@ +/* + This is a version (aka dlmalloc) of malloc/free/realloc written by + Doug Lea and released to the public domain, as explained at + http://creativecommons.org/publicdomain/zero/1.0/ Send questions, + comments, complaints, performance data, etc to dl@cs.oswego.edu + +* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + Note: There may be an updated version of this malloc obtainable at + ftp://gee.cs.oswego.edu/pub/misc/malloc.c + Check before installing! + +* Quickstart + + This library is all in one file to simplify the most common usage: + ftp it, compile it (-O3), and link it into another program. All of + the compile-time options default to reasonable values for use on + most platforms. You might later want to step through various + compile-time and dynamic tuning options. + + For convenience, an include file for code using this malloc is at: + ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h + You don't really need this .h file unless you call functions not + defined in your system include files. The .h file contains only the + excerpts from this file needed for using this malloc on ANSI C/C++ + systems, so long as you haven't changed compile-time options about + naming and tuning parameters. If you do, then you can create your + own malloc.h that does include all settings by cutting at the point + indicated below. Note that you may already by default be using a C + library containing a malloc that is based on some version of this + malloc (for example in linux). You might still want to use the one + in this file to customize settings or to avoid overheads associated + with library versions. + +* Vital statistics: + + Supported pointer/size_t representation: 4 or 8 bytes + size_t MUST be an unsigned type of the same width as + pointers. (If you are using an ancient system that declares + size_t as a signed type, or need it to be a different width + than pointers, you can use a previous release of this malloc + (e.g. 2.7.2) supporting these.) + + Alignment: 8 bytes (minimum) + This suffices for nearly all current machines and C compilers. + However, you can define MALLOC_ALIGNMENT to be wider than this + if necessary (up to 128bytes), at the expense of using more space. + + Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) + 8 or 16 bytes (if 8byte sizes) + Each malloced chunk has a hidden word of overhead holding size + and status information, and additional cross-check word + if FOOTERS is defined. + + Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) + 8-byte ptrs: 32 bytes (including overhead) + + Even a request for zero bytes (i.e., malloc(0)) returns a + pointer to something of the minimum allocatable size. + The maximum overhead wastage (i.e., number of extra bytes + allocated than were requested in malloc) is less than or equal + to the minimum size, except for requests >= mmap_threshold that + are serviced via mmap(), where the worst case wastage is about + 32 bytes plus the remainder from a system page (the minimal + mmap unit); typically 4096 or 8192 bytes. + + Security: static-safe; optionally more or less + The "security" of malloc refers to the ability of malicious + code to accentuate the effects of errors (for example, freeing + space that is not currently malloc'ed or overwriting past the + ends of chunks) in code that calls malloc. This malloc + guarantees not to modify any memory locations below the base of + heap, i.e., static variables, even in the presence of usage + errors. The routines additionally detect most improper frees + and reallocs. All this holds as long as the static bookkeeping + for malloc itself is not corrupted by some other means. This + is only one aspect of security -- these checks do not, and + cannot, detect all possible programming errors. + + If FOOTERS is defined nonzero, then each allocated chunk + carries an additional check word to verify that it was malloced + from its space. These check words are the same within each + execution of a program using malloc, but differ across + executions, so externally crafted fake chunks cannot be + freed. This improves security by rejecting frees/reallocs that + could corrupt heap memory, in addition to the checks preventing + writes to statics that are always on. This may further improve + security at the expense of time and space overhead. (Note that + FOOTERS may also be worth using with MSPACES.) + + By default detected errors cause the program to abort (calling + "abort()"). You can override this to instead proceed past + errors by defining PROCEED_ON_ERROR. In this case, a bad free + has no effect, and a malloc that encounters a bad address + caused by user overwrites will ignore the bad address by + dropping pointers and indices to all known memory. This may + be appropriate for programs that should continue if at all + possible in the face of programming errors, although they may + run out of memory because dropped memory is never reclaimed. + + If you don't like either of these options, you can define + CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything + else. And if if you are sure that your program using malloc has + no errors or vulnerabilities, you can define INSECURE to 1, + which might (or might not) provide a small performance improvement. + + It is also possible to limit the maximum total allocatable + space, using malloc_set_footprint_limit. This is not + designed as a security feature in itself (calls to set limits + are not screened or privileged), but may be useful as one + aspect of a secure implementation. + + Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero + When USE_LOCKS is defined, each public call to malloc, free, + etc is surrounded with a lock. By default, this uses a plain + pthread mutex, win32 critical section, or a spin-lock if if + available for the platform and not disabled by setting + USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined, + recursive versions are used instead (which are not required for + base functionality but may be needed in layered extensions). + Using a global lock is not especially fast, and can be a major + bottleneck. It is designed only to provide minimal protection + in concurrent environments, and to provide a basis for + extensions. If you are using malloc in a concurrent program, + consider instead using nedmalloc + (http://www.nedprod.com/programs/portable/nedmalloc/) or + ptmalloc (See http://www.malloc.de), which are derived from + versions of this malloc. + + System requirements: Any combination of MORECORE and/or MMAP/MUNMAP + This malloc can use unix sbrk or any emulation (invoked using + the CALL_MORECORE macro) and/or mmap/munmap or any emulation + (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system + memory. On most unix systems, it tends to work best if both + MORECORE and MMAP are enabled. On Win32, it uses emulations + based on VirtualAlloc. It also uses common C library functions + like memset. + + Compliance: I believe it is compliant with the Single Unix Specification + (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably + others as well. + +* Overview of algorithms + + This is not the fastest, most space-conserving, most portable, or + most tunable malloc ever written. However it is among the fastest + while also being among the most space-conserving, portable and + tunable. Consistent balance across these factors results in a good + general-purpose allocator for malloc-intensive programs. + + In most ways, this malloc is a best-fit allocator. Generally, it + chooses the best-fitting existing chunk for a request, with ties + broken in approximately least-recently-used order. (This strategy + normally maintains low fragmentation.) However, for requests less + than 256bytes, it deviates from best-fit when there is not an + exactly fitting available chunk by preferring to use space adjacent + to that used for the previous small request, as well as by breaking + ties in approximately most-recently-used order. (These enhance + locality of series of small allocations.) And for very large requests + (>= 256Kb by default), it relies on system memory mapping + facilities, if supported. (This helps avoid carrying around and + possibly fragmenting memory used only for large chunks.) + + All operations (except malloc_stats and mallinfo) have execution + times that are bounded by a constant factor of the number of bits in + a size_t, not counting any clearing in calloc or copying in realloc, + or actions surrounding MORECORE and MMAP that have times + proportional to the number of non-contiguous regions returned by + system allocation routines, which is often just 1. In real-time + applications, you can optionally suppress segment traversals using + NO_SEGMENT_TRAVERSAL, which assures bounded execution even when + system allocators return non-contiguous spaces, at the typical + expense of carrying around more memory and increased fragmentation. + + The implementation is not very modular and seriously overuses + macros. Perhaps someday all C compilers will do as good a job + inlining modular code as can now be done by brute-force expansion, + but now, enough of them seem not to. + + Some compilers issue a lot of warnings about code that is + dead/unreachable only on some platforms, and also about intentional + uses of negation on unsigned types. All known cases of each can be + ignored. + + For a longer but out of date high-level description, see + http://gee.cs.oswego.edu/dl/html/malloc.html + +* MSPACES + If MSPACES is defined, then in addition to malloc, free, etc., + this file also defines mspace_malloc, mspace_free, etc. These + are versions of malloc routines that take an "mspace" argument + obtained using create_mspace, to control all internal bookkeeping. + If ONLY_MSPACES is defined, only these versions are compiled. + So if you would like to use this allocator for only some allocations, + and your system malloc for others, you can compile with + ONLY_MSPACES and then do something like... + static mspace mymspace = create_mspace(0,0); // for example + #define mymalloc(bytes) mspace_malloc(mymspace, bytes) + + (Note: If you only need one instance of an mspace, you can instead + use "USE_DL_PREFIX" to relabel the global malloc.) + + You can similarly create thread-local allocators by storing + mspaces as thread-locals. For example: + static __thread mspace tlms = 0; + void* tlmalloc(size_t bytes) { + if (tlms == 0) tlms = create_mspace(0, 0); + return mspace_malloc(tlms, bytes); + } + void tlfree(void* mem) { mspace_free(tlms, mem); } + + Unless FOOTERS is defined, each mspace is completely independent. + You cannot allocate from one and free to another (although + conformance is only weakly checked, so usage errors are not always + caught). If FOOTERS is defined, then each chunk carries around a tag + indicating its originating mspace, and frees are directed to their + originating spaces. Normally, this requires use of locks. + + ------------------------- Compile-time options --------------------------- + +Be careful in setting #define values for numerical constants of type +size_t. On some systems, literal values are not automatically extended +to size_t precision unless they are explicitly casted. You can also +use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below. + +WIN32 default: defined if _WIN32 defined + Defining WIN32 sets up defaults for MS environment and compilers. + Otherwise defaults are for unix. Beware that there seem to be some + cases where this malloc might not be a pure drop-in replacement for + Win32 malloc: Random-looking failures from Win32 GDI API's (eg; + SetDIBits()) may be due to bugs in some video driver implementations + when pixel buffers are malloc()ed, and the region spans more than + one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb) + default granularity, pixel buffers may straddle virtual allocation + regions more often than when using the Microsoft allocator. You can + avoid this by using VirtualAlloc() and VirtualFree() for all pixel + buffers rather than using malloc(). If this is not possible, + recompile this malloc with a larger DEFAULT_GRANULARITY. Note: + in cases where MSC and gcc (cygwin) are known to differ on WIN32, + conditions use _MSC_VER to distinguish them. + +DLMALLOC_EXPORT default: extern + Defines how public APIs are declared. If you want to export via a + Windows DLL, you might define this as + #define DLMALLOC_EXPORT extern __declspec(dllexport) + If you want a POSIX ELF shared object, you might use + #define DLMALLOC_EXPORT extern __attribute__((visibility("default"))) + +MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *)) + Controls the minimum alignment for malloc'ed chunks. It must be a + power of two and at least 8, even on machines for which smaller + alignments would suffice. It may be defined as larger than this + though. Note however that code and data structures are optimized for + the case of 8-byte alignment. + +MSPACES default: 0 (false) + If true, compile in support for independent allocation spaces. + This is only supported if HAVE_MMAP is true. + +ONLY_MSPACES default: 0 (false) + If true, only compile in mspace versions, not regular versions. + +USE_LOCKS default: 0 (false) + Causes each call to each public routine to be surrounded with + pthread or WIN32 mutex lock/unlock. (If set true, this can be + overridden on a per-mspace basis for mspace versions.) If set to a + non-zero value other than 1, locks are used, but their + implementation is left out, so lock functions must be supplied manually, + as described below. + +USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available + If true, uses custom spin locks for locking. This is currently + supported only gcc >= 4.1, older gccs on x86 platforms, and recent + MS compilers. Otherwise, posix locks or win32 critical sections are + used. + +USE_RECURSIVE_LOCKS default: not defined + If defined nonzero, uses recursive (aka reentrant) locks, otherwise + uses plain mutexes. This is not required for malloc proper, but may + be needed for layered allocators such as nedmalloc. + +LOCK_AT_FORK default: not defined + If defined nonzero, performs pthread_atfork upon initialization + to initialize child lock while holding parent lock. The implementation + assumes that pthread locks (not custom locks) are being used. In other + cases, you may need to customize the implementation. + +FOOTERS default: 0 + If true, provide extra checking and dispatching by placing + information in the footers of allocated chunks. This adds + space and time overhead. + +INSECURE default: 0 + If true, omit checks for usage errors and heap space overwrites. + +USE_DL_PREFIX default: NOT defined + Causes compiler to prefix all public routines with the string 'dl'. + This can be useful when you only want to use this malloc in one part + of a program, using your regular system malloc elsewhere. + +MALLOC_INSPECT_ALL default: NOT defined + If defined, compiles malloc_inspect_all and mspace_inspect_all, that + perform traversal of all heap space. Unless access to these + functions is otherwise restricted, you probably do not want to + include them in secure implementations. + +ABORT default: defined as abort() + Defines how to abort on failed checks. On most systems, a failed + check cannot die with an "assert" or even print an informative + message, because the underlying print routines in turn call malloc, + which will fail again. Generally, the best policy is to simply call + abort(). It's not very useful to do more than this because many + errors due to overwriting will show up as address faults (null, odd + addresses etc) rather than malloc-triggered checks, so will also + abort. Also, most compilers know that abort() does not return, so + can better optimize code conditionally calling it. + +PROCEED_ON_ERROR default: defined as 0 (false) + Controls whether detected bad addresses cause them to bypassed + rather than aborting. If set, detected bad arguments to free and + realloc are ignored. And all bookkeeping information is zeroed out + upon a detected overwrite of freed heap space, thus losing the + ability to ever return it from malloc again, but enabling the + application to proceed. If PROCEED_ON_ERROR is defined, the + static variable malloc_corruption_error_count is compiled in + and can be examined to see if errors have occurred. This option + generates slower code than the default abort policy. + +DEBUG default: NOT defined + The DEBUG setting is mainly intended for people trying to modify + this code or diagnose problems when porting to new platforms. + However, it may also be able to better isolate user errors than just + using runtime checks. The assertions in the check routines spell + out in more detail the assumptions and invariants underlying the + algorithms. The checking is fairly extensive, and will slow down + execution noticeably. Calling malloc_stats or mallinfo with DEBUG + set will attempt to check every non-mmapped allocated and free chunk + in the course of computing the summaries. + +ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) + Debugging assertion failures can be nearly impossible if your + version of the assert macro causes malloc to be called, which will + lead to a cascade of further failures, blowing the runtime stack. + ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), + which will usually make debugging easier. + +MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 + The action to take before "return 0" when malloc fails to be able to + return memory because there is none available. + +HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES + True if this system supports sbrk or an emulation of it. + +MORECORE default: sbrk + The name of the sbrk-style system routine to call to obtain more + memory. See below for guidance on writing custom MORECORE + functions. The type of the argument to sbrk/MORECORE varies across + systems. It cannot be size_t, because it supports negative + arguments, so it is normally the signed type of the same width as + size_t (sometimes declared as "intptr_t"). It doesn't much matter + though. Internally, we only call it with arguments less than half + the max value of a size_t, which should work across all reasonable + possibilities, although sometimes generating compiler warnings. + +MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE + If true, take advantage of fact that consecutive calls to MORECORE + with positive arguments always return contiguous increasing + addresses. This is true of unix sbrk. It does not hurt too much to + set it true anyway, since malloc copes with non-contiguities. + Setting it false when definitely non-contiguous saves time + and possibly wasted space it would take to discover this though. + +MORECORE_CANNOT_TRIM default: NOT defined + True if MORECORE cannot release space back to the system when given + negative arguments. This is generally necessary only if you are + using a hand-crafted MORECORE function that cannot handle negative + arguments. + +NO_SEGMENT_TRAVERSAL default: 0 + If non-zero, suppresses traversals of memory segments + returned by either MORECORE or CALL_MMAP. This disables + merging of segments that are contiguous, and selectively + releasing them to the OS if unused, but bounds execution times. + +HAVE_MMAP default: 1 (true) + True if this system supports mmap or an emulation of it. If so, and + HAVE_MORECORE is not true, MMAP is used for all system + allocation. If set and HAVE_MORECORE is true as well, MMAP is + primarily used to directly allocate very large blocks. It is also + used as a backup strategy in cases where MORECORE fails to provide + space from system. Note: A single call to MUNMAP is assumed to be + able to unmap memory that may have be allocated using multiple calls + to MMAP, so long as they are adjacent. + +HAVE_MREMAP default: 1 on linux, else 0 + If true realloc() uses mremap() to re-allocate large blocks and + extend or shrink allocation spaces. + +MMAP_CLEARS default: 1 except on WINCE. + True if mmap clears memory so calloc doesn't need to. This is true + for standard unix mmap using /dev/zero and on WIN32 except for WINCE. + +USE_BUILTIN_FFS default: 0 (i.e., not used) + Causes malloc to use the builtin ffs() function to compute indices. + Some compilers may recognize and intrinsify ffs to be faster than the + supplied C version. Also, the case of x86 using gcc is special-cased + to an asm instruction, so is already as fast as it can be, and so + this setting has no effect. Similarly for Win32 under recent MS compilers. + (On most x86s, the asm version is only slightly faster than the C version.) + +malloc_getpagesize default: derive from system includes, or 4096. + The system page size. To the extent possible, this malloc manages + memory from the system in page-size units. This may be (and + usually is) a function rather than a constant. This is ignored + if WIN32, where page size is determined using getSystemInfo during + initialization. + +USE_DEV_RANDOM default: 0 (i.e., not used) + Causes malloc to use /dev/random to initialize secure magic seed for + stamping footers. Otherwise, the current time is used. + +NO_MALLINFO default: 0 + If defined, don't compile "mallinfo". This can be a simple way + of dealing with mismatches between system declarations and + those in this file. + +MALLINFO_FIELD_TYPE default: size_t + The type of the fields in the mallinfo struct. This was originally + defined as "int" in SVID etc, but is more usefully defined as + size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set + +NO_MALLOC_STATS default: 0 + If defined, don't compile "malloc_stats". This avoids calls to + fprintf and bringing in stdio dependencies you might not want. + +REALLOC_ZERO_BYTES_FREES default: not defined + This should be set if a call to realloc with zero bytes should + be the same as a call to free. Some people think it should. Otherwise, + since this malloc returns a unique pointer for malloc(0), so does + realloc(p, 0). + +LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H +LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H +LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32 + Define these if your system does not have these header files. + You might need to manually insert some of the declarations they provide. + +DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, + system_info.dwAllocationGranularity in WIN32, + otherwise 64K. + Also settable using mallopt(M_GRANULARITY, x) + The unit for allocating and deallocating memory from the system. On + most systems with contiguous MORECORE, there is no reason to + make this more than a page. However, systems with MMAP tend to + either require or encourage larger granularities. You can increase + this value to prevent system allocation functions to be called so + often, especially if they are slow. The value must be at least one + page and must be a power of two. Setting to 0 causes initialization + to either page size or win32 region size. (Note: In previous + versions of malloc, the equivalent of this option was called + "TOP_PAD") + +DEFAULT_TRIM_THRESHOLD default: 2MB + Also settable using mallopt(M_TRIM_THRESHOLD, x) + The maximum amount of unused top-most memory to keep before + releasing via malloc_trim in free(). Automatic trimming is mainly + useful in long-lived programs using contiguous MORECORE. Because + trimming via sbrk can be slow on some systems, and can sometimes be + wasteful (in cases where programs immediately afterward allocate + more large chunks) the value should be high enough so that your + overall system performance would improve by releasing this much + memory. As a rough guide, you might set to a value close to the + average size of a process (program) running on your system. + Releasing this much memory would allow such a process to run in + memory. Generally, it is worth tuning trim thresholds when a + program undergoes phases where several large chunks are allocated + and released in ways that can reuse each other's storage, perhaps + mixed with phases where there are no such chunks at all. The trim + value must be greater than page size to have any useful effect. To + disable trimming completely, you can set to MAX_SIZE_T. Note that the trick + some people use of mallocing a huge space and then freeing it at + program startup, in an attempt to reserve system memory, doesn't + have the intended effect under automatic trimming, since that memory + will immediately be returned to the system. + +DEFAULT_MMAP_THRESHOLD default: 256K + Also settable using mallopt(M_MMAP_THRESHOLD, x) + The request size threshold for using MMAP to directly service a + request. Requests of at least this size that cannot be allocated + using already-existing space will be serviced via mmap. (If enough + normal freed space already exists it is used instead.) Using mmap + segregates relatively large chunks of memory so that they can be + individually obtained and released from the host system. A request + serviced through mmap is never reused by any other request (at least + not directly; the system may just so happen to remap successive + requests to the same locations). Segregating space in this way has + the benefits that: Mmapped space can always be individually released + back to the system, which helps keep the system level memory demands + of a long-lived program low. Also, mapped memory doesn't become + `locked' between other chunks, as can happen with normally allocated + chunks, which means that even trimming via malloc_trim would not + release them. However, it has the disadvantage that the space + cannot be reclaimed, consolidated, and then used to service later + requests, as happens with normal chunks. The advantages of mmap + nearly always outweigh disadvantages for "large" chunks, but the + value of "large" may vary across systems. The default is an + empirically derived value that works well in most systems. You can + disable mmap by setting to MAX_SIZE_T. + +MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP + The number of consolidated frees between checks to release + unused segments when freeing. When using non-contiguous segments, + especially with multiple mspaces, checking only for topmost space + doesn't always suffice to trigger trimming. To compensate for this, + free() will, with a period of MAX_RELEASE_CHECK_RATE (or the + current number of segments, if greater) try to release unused + segments to the OS when freeing chunks that result in + consolidation. The best value for this parameter is a compromise + between slowing down frees with relatively costly checks that + rarely trigger versus holding on to unused memory. To effectively + disable, set to MAX_SIZE_T. This may lead to a very slight speed + improvement at the expense of carrying around more memory. +*/ + + +/* Version identifier to allow people to support multiple versions */ +#ifndef DLMALLOC_VERSION +#define DLMALLOC_VERSION 20806 +#endif /* DLMALLOC_VERSION */ + +#ifndef DLMALLOC_EXPORT +#define DLMALLOC_EXPORT extern +#endif + +#ifndef WIN32 +#ifdef _WIN32 +#define WIN32 1 +#endif /* _WIN32 */ +#ifdef _WIN32_WCE +#define LACKS_FCNTL_H +#define WIN32 1 +#endif /* _WIN32_WCE */ +#endif /* WIN32 */ +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#define HAVE_MMAP 1 +#define HAVE_MORECORE 0 +#define LACKS_UNISTD_H +#define LACKS_SYS_PARAM_H +#define LACKS_SYS_MMAN_H +#define LACKS_STRING_H +#define LACKS_STRINGS_H +#define LACKS_SYS_TYPES_H +#define LACKS_ERRNO_H +#define LACKS_SCHED_H +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef MMAP_CLEARS +#ifdef _WIN32_WCE /* WINCE reportedly does not clear */ +#define MMAP_CLEARS 0 +#else +#define MMAP_CLEARS 1 +#endif /* _WIN32_WCE */ +#endif /*MMAP_CLEARS */ +#endif /* WIN32 */ + +#if defined(DARWIN) || defined(_DARWIN) +/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ +#ifndef HAVE_MORECORE +#define HAVE_MORECORE 0 +#define HAVE_MMAP 1 +/* OSX allocators provide 16 byte alignment */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)16U) +#endif +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ + +#ifndef LACKS_SYS_TYPES_H +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ + +/* The maximum possible size_t value has all bits set */ +#define MAX_SIZE_T (~(size_t)0) + +#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) +#define RECURSIVE_LOCKS_ENABLED 1 +#else +#define RECURSIVE_LOCKS_ENABLED 0 +#endif + +#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) +#define SPIN_LOCKS_ENABLED 1 +#else +#define SPIN_LOCKS_ENABLED 0 +#endif + +#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */ +#define USE_LOCKS ((SPIN_LOCKS_ENABLED != 0) || \ + (RECURSIVE_LOCKS_ENABLED != 0)) +#endif /* USE_LOCKS */ + +#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */ +#if ((defined(__GNUC__) && \ + ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \ + defined(__i386__) || defined(__x86_64__))) || \ + (defined(_MSC_VER) && _MSC_VER>=1310)) +#ifndef USE_SPIN_LOCKS +#define USE_SPIN_LOCKS 1 +#endif /* USE_SPIN_LOCKS */ +#elif USE_SPIN_LOCKS +#error "USE_SPIN_LOCKS defined without implementation" +#endif /* ... locks available... */ +#elif !defined(USE_SPIN_LOCKS) +#define USE_SPIN_LOCKS 0 +#endif /* USE_LOCKS */ + +#ifndef ONLY_MSPACES +#define ONLY_MSPACES 0 +#endif /* ONLY_MSPACES */ +#ifndef MSPACES +#if ONLY_MSPACES +#define MSPACES 1 +#else /* ONLY_MSPACES */ +#define MSPACES 0 +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *))) +#endif /* MALLOC_ALIGNMENT */ +#ifndef FOOTERS +#define FOOTERS 0 +#endif /* FOOTERS */ +#ifndef ABORT +#define ABORT abort() +#endif /* ABORT */ +#ifndef ABORT_ON_ASSERT_FAILURE +#define ABORT_ON_ASSERT_FAILURE 1 +#endif /* ABORT_ON_ASSERT_FAILURE */ +#ifndef PROCEED_ON_ERROR +#define PROCEED_ON_ERROR 0 +#endif /* PROCEED_ON_ERROR */ + +#ifndef INSECURE +#define INSECURE 0 +#endif /* INSECURE */ +#ifndef MALLOC_INSPECT_ALL +#define MALLOC_INSPECT_ALL 0 +#endif /* MALLOC_INSPECT_ALL */ +#ifndef HAVE_MMAP +#define HAVE_MMAP 1 +#endif /* HAVE_MMAP */ +#ifndef MMAP_CLEARS +#define MMAP_CLEARS 1 +#endif /* MMAP_CLEARS */ +#ifndef HAVE_MREMAP +#ifdef linux +#define HAVE_MREMAP 1 +#ifndef _GNU_SOURCE +#define _GNU_SOURCE /* Turns on mremap() definition */ +#endif /* _GNU_SOURCE */ +#else /* linux */ +#define HAVE_MREMAP 0 +#endif /* linux */ +#endif /* HAVE_MREMAP */ +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION errno = ENOMEM; +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef HAVE_MORECORE +#if ONLY_MSPACES +#define HAVE_MORECORE 0 +#else /* ONLY_MSPACES */ +#define HAVE_MORECORE 1 +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ +#if !HAVE_MORECORE +#define MORECORE_CONTIGUOUS 0 +#else /* !HAVE_MORECORE */ +#define MORECORE_DEFAULT sbrk +#ifndef MORECORE_CONTIGUOUS +#define MORECORE_CONTIGUOUS 1 +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ +#ifndef DEFAULT_GRANULARITY +#if (MORECORE_CONTIGUOUS || defined(WIN32)) +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ +#ifndef DEFAULT_TRIM_THRESHOLD +#ifndef MORECORE_CANNOT_TRIM +#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) +#else /* MORECORE_CANNOT_TRIM */ +#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ +#ifndef DEFAULT_MMAP_THRESHOLD +#if HAVE_MMAP +#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) +#else /* HAVE_MMAP */ +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ +#ifndef MAX_RELEASE_CHECK_RATE +#if HAVE_MMAP +#define MAX_RELEASE_CHECK_RATE 4095 +#else +#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* MAX_RELEASE_CHECK_RATE */ +#ifndef USE_BUILTIN_FFS +#define USE_BUILTIN_FFS 0 +#endif /* USE_BUILTIN_FFS */ +#ifndef USE_DEV_RANDOM +#define USE_DEV_RANDOM 0 +#endif /* USE_DEV_RANDOM */ +#ifndef NO_MALLINFO +#define NO_MALLINFO 0 +#endif /* NO_MALLINFO */ +#ifndef MALLINFO_FIELD_TYPE +#define MALLINFO_FIELD_TYPE size_t +#endif /* MALLINFO_FIELD_TYPE */ +#ifndef NO_MALLOC_STATS +#define NO_MALLOC_STATS 0 +#endif /* NO_MALLOC_STATS */ +#ifndef NO_SEGMENT_TRAVERSAL +#define NO_SEGMENT_TRAVERSAL 0 +#endif /* NO_SEGMENT_TRAVERSAL */ + +/* + mallopt tuning options. SVID/XPG defines four standard parameter + numbers for mallopt, normally defined in malloc.h. None of these + are used in this malloc, so setting them has no effect. But this + malloc does support the following options. +*/ + +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) + +/* ------------------------ Mallinfo declarations ------------------------ */ + +#if !NO_MALLINFO +/* + This version of malloc supports the standard SVID/XPG mallinfo + routine that returns a struct containing usage properties and + statistics. It should work on any system that has a + /usr/include/malloc.h defining struct mallinfo. The main + declaration needed is the mallinfo struct that is returned (by-copy) + by mallinfo(). The malloinfo struct contains a bunch of fields that + are not even meaningful in this version of malloc. These fields are + are instead filled by mallinfo() with other numbers that might be of + interest. + + HAVE_USR_INCLUDE_MALLOC_H should be set if you have a + /usr/include/malloc.h file that includes a declaration of struct + mallinfo. If so, it is included; else a compliant version is + declared below. These must be precisely the same for mallinfo() to + work. The original SVID version of this struct, defined on most + systems with mallinfo, declares all fields as ints. But some others + define as unsigned long. If your system defines the fields using a + type of different width than listed here, you MUST #include your + system version and #define HAVE_USR_INCLUDE_MALLOC_H. +*/ + +/* #define HAVE_USR_INCLUDE_MALLOC_H */ + +#ifdef HAVE_USR_INCLUDE_MALLOC_H +#include "/usr/include/malloc.h" +#else /* HAVE_USR_INCLUDE_MALLOC_H */ +#ifndef STRUCT_MALLINFO_DECLARED +/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */ +#define _STRUCT_MALLINFO +#define STRUCT_MALLINFO_DECLARED 1 +struct mallinfo { + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +}; +#endif /* STRUCT_MALLINFO_DECLARED */ +#endif /* HAVE_USR_INCLUDE_MALLOC_H */ +#endif /* NO_MALLINFO */ + +/* + Try to persuade compilers to inline. The most critical functions for + inlining are defined as macros, so these aren't used for them. +*/ + +#ifndef FORCEINLINE + #if defined(__GNUC__) +#define FORCEINLINE __inline __attribute__ ((always_inline)) + #elif defined(_MSC_VER) + #define FORCEINLINE __forceinline + #endif +#endif +#ifndef NOINLINE + #if defined(__GNUC__) + #define NOINLINE __attribute__ ((noinline)) + #elif defined(_MSC_VER) + #define NOINLINE __declspec(noinline) + #else + #define NOINLINE + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#ifndef FORCEINLINE + #define FORCEINLINE inline +#endif +#endif /* __cplusplus */ +#ifndef FORCEINLINE + #define FORCEINLINE +#endif + +#if !ONLY_MSPACES + +/* ------------------- Declarations of public routines ------------------- */ + +#ifndef USE_DL_PREFIX +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlposix_memalign posix_memalign +#define dlrealloc realloc +#define dlrealloc_in_place realloc_in_place +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint +#define dlmalloc_max_footprint malloc_max_footprint +#define dlmalloc_footprint_limit malloc_footprint_limit +#define dlmalloc_set_footprint_limit malloc_set_footprint_limit +#define dlmalloc_inspect_all malloc_inspect_all +#define dlindependent_calloc independent_calloc +#define dlindependent_comalloc independent_comalloc +#define dlbulk_free bulk_free +#endif /* USE_DL_PREFIX */ + +/* + malloc(size_t n) + Returns a pointer to a newly allocated chunk of at least n bytes, or + null if no space is available, in which case errno is set to ENOMEM + on ANSI C systems. + + If n is zero, malloc returns a minimum-sized chunk. (The minimum + size is 16 bytes on most 32bit systems, and 32 bytes on 64bit + systems.) Note that size_t is an unsigned type, so calls with + arguments that would be negative if signed are interpreted as + requests for huge amounts of space, which will often fail. The + maximum supported value of n differs across systems, but is in all + cases less than the maximum representable value of a size_t. +*/ +DLMALLOC_EXPORT void* dlmalloc(size_t); + +/* + free(void* p) + Releases the chunk of memory pointed to by p, that had been previously + allocated using malloc or a related routine such as realloc. + It has no effect if p is null. If p was not malloced or already + freed, free(p) will by default cause the current program to abort. +*/ +DLMALLOC_EXPORT void dlfree(void*); + +/* + calloc(size_t n_elements, size_t element_size); + Returns a pointer to n_elements * element_size bytes, with all locations + set to zero. +*/ +DLMALLOC_EXPORT void* dlcalloc(size_t, size_t); + +/* + realloc(void* p, size_t n) + Returns a pointer to a chunk of size n that contains the same data + as does chunk p up to the minimum of (n, p's size) bytes, or null + if no space is available. + + The returned pointer may or may not be the same as p. The algorithm + prefers extending p in most cases when possible, otherwise it + employs the equivalent of a malloc-copy-free sequence. + + If p is null, realloc is equivalent to malloc. + + If space is not available, realloc returns null, errno is set (if on + ANSI) and p is NOT freed. + + if n is for fewer bytes than already held by p, the newly unused + space is lopped off and freed if possible. realloc with a size + argument of zero (re)allocates a minimum-sized chunk. + + The old unix realloc convention of allowing the last-free'd chunk + to be used as an argument to realloc is not supported. +*/ +DLMALLOC_EXPORT void* dlrealloc(void*, size_t); + +/* + realloc_in_place(void* p, size_t n) + Resizes the space allocated for p to size n, only if this can be + done without moving p (i.e., only if there is adjacent space + available if n is greater than p's current allocated size, or n is + less than or equal to p's size). This may be used instead of plain + realloc if an alternative allocation strategy is needed upon failure + to expand space; for example, reallocation of a buffer that must be + memory-aligned or cleared. You can use realloc_in_place to trigger + these alternatives only when needed. + + Returns p if successful; otherwise null. +*/ +DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t); + +/* + memalign(size_t alignment, size_t n); + Returns a pointer to a newly allocated chunk of n bytes, aligned + in accord with the alignment argument. + + The alignment argument should be a power of two. If the argument is + not a power of two, the nearest greater power is used. + 8-byte alignment is guaranteed by normal malloc calls, so don't + bother calling memalign with an argument of 8 or less. + + Overreliance on memalign is a sure way to fragment space. +*/ +DLMALLOC_EXPORT void* dlmemalign(size_t, size_t); + +/* + int posix_memalign(void** pp, size_t alignment, size_t n); + Allocates a chunk of n bytes, aligned in accord with the alignment + argument. Differs from memalign only in that it (1) assigns the + allocated memory to *pp rather than returning it, (2) fails and + returns EINVAL if the alignment is not a power of two (3) fails and + returns ENOMEM if memory cannot be allocated. +*/ +DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t); + +/* + valloc(size_t n); + Equivalent to memalign(pagesize, n), where pagesize is the page + size of the system. If the pagesize is unknown, 4096 is used. +*/ +DLMALLOC_EXPORT void* dlvalloc(size_t); + +/* + mallopt(int parameter_number, int parameter_value) + Sets tunable parameters The format is to provide a + (parameter-number, parameter-value) pair. mallopt then sets the + corresponding parameter to the argument value if it can (i.e., so + long as the value is meaningful), and returns 1 if successful else + 0. To workaround the fact that mallopt is specified to use int, + not size_t parameters, the value -1 is specially treated as the + maximum unsigned size_t value. + + SVID/XPG/ANSI defines four standard param numbers for mallopt, + normally defined in malloc.h. None of these are use in this malloc, + so setting them has no effect. But this malloc also supports other + options in mallopt. See below for details. Briefly, supported + parameters are as follows (listed defaults are for "typical" + configurations). + + Symbol param # default allowed param values + M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables) + M_GRANULARITY -2 page size any power of 2 >= page size + M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) +*/ +DLMALLOC_EXPORT int dlmallopt(int, int); + +/* + malloc_footprint(); + Returns the number of bytes obtained from the system. The total + number of bytes allocated by malloc, realloc etc., is less than this + value. Unlike mallinfo, this function returns only a precomputed + result, so can be called frequently to monitor memory consumption. + Even if locks are otherwise defined, this function does not use them, + so results might not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint(void); + +/* + malloc_max_footprint(); + Returns the maximum number of bytes obtained from the system. This + value will be greater than current footprint if deallocated space + has been reclaimed by the system. The peak number of bytes allocated + by malloc, realloc etc., is less than this value. Unlike mallinfo, + this function returns only a precomputed result, so can be called + frequently to monitor memory consumption. Even if locks are + otherwise defined, this function does not use them, so results might + not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void); + +/* + malloc_footprint_limit(); + Returns the number of bytes that the heap is allowed to obtain from + the system, returning the last value returned by + malloc_set_footprint_limit, or the maximum size_t value if + never set. The returned value reflects a permission. There is no + guarantee that this number of bytes can actually be obtained from + the system. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint_limit(); + +/* + malloc_set_footprint_limit(); + Sets the maximum number of bytes to obtain from the system, causing + failure returns from malloc and related functions upon attempts to + exceed this value. The argument value may be subject to page + rounding to an enforceable limit; this actual value is returned. + Using an argument of the maximum possible size_t effectively + disables checks. If the argument is less than or equal to the + current malloc_footprint, then all future allocations that require + additional system memory will fail. However, invocation cannot + retroactively deallocate existing used memory. +*/ +DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes); + +#if MALLOC_INSPECT_ALL +/* + malloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg); + Traverses the heap and calls the given handler for each managed + region, skipping all bytes that are (or may be) used for bookkeeping + purposes. Traversal does not include include chunks that have been + directly memory mapped. Each reported region begins at the start + address, and continues up to but not including the end address. The + first used_bytes of the region contain allocated data. If + used_bytes is zero, the region is unallocated. The handler is + invoked with the given callback argument. If locks are defined, they + are held during the entire traversal. It is a bad idea to invoke + other malloc functions from within the handler. + + For example, to count the number of in-use chunks with size greater + than 1000, you could write: + static int count = 0; + void count_chunks(void* start, void* end, size_t used, void* arg) { + if (used >= 1000) ++count; + } + then: + malloc_inspect_all(count_chunks, NULL); + + malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined. +*/ +DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*), + void* arg); + +#endif /* MALLOC_INSPECT_ALL */ + +#if !NO_MALLINFO +/* + mallinfo() + Returns (by copy) a struct containing various summary statistics: + + arena: current total non-mmapped bytes allocated from system + ordblks: the number of free chunks + smblks: always zero. + hblks: current number of mmapped regions + hblkhd: total bytes held in mmapped regions + usmblks: the maximum total allocated space. This will be greater + than current total if trimming has occurred. + fsmblks: always zero + uordblks: current total allocated space (normal or mmapped) + fordblks: total free space + keepcost: the maximum number of bytes that could ideally be released + back to system via malloc_trim. ("ideally" means that + it ignores page restrictions etc.) + + Because these fields are ints, but internal bookkeeping may + be kept as longs, the reported values may wrap around zero and + thus be inaccurate. +*/ +DLMALLOC_EXPORT struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ + +/* + independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); + + independent_calloc is similar to calloc, but instead of returning a + single cleared space, it returns an array of pointers to n_elements + independent elements that can hold contents of size elem_size, each + of which starts out cleared, and can be independently freed, + realloc'ed etc. The elements are guaranteed to be adjacently + allocated (this is not guaranteed to occur with multiple callocs or + mallocs), which may also improve cache locality in some + applications. + + The "chunks" argument is optional (i.e., may be null, which is + probably the most typical usage). If it is null, the returned array + is itself dynamically allocated and should also be freed when it is + no longer needed. Otherwise, the chunks array must be of at least + n_elements in length. It is filled in with the pointers to the + chunks. + + In either case, independent_calloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and "chunks" + is null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_calloc simplifies and speeds up implementations of many + kinds of pools. It may also be useful when constructing large data + structures that initially have a fixed number of fixed-sized nodes, + but the number is not known at compile time, and some of the nodes + may later need to be freed. For example: + + struct Node { int item; struct Node* next; }; + + struct Node* build_list() { + struct Node** pool; + int n = read_number_of_nodes_needed(); + if (n <= 0) return 0; + pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); + if (pool == 0) die(); + // organize into a linked list... + struct Node* first = pool[0]; + for (i = 0; i < n-1; ++i) + pool[i]->next = pool[i+1]; + free(pool); // Can now free the array (or not, if it is needed later) + return first; + } +*/ +DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**); + +/* + independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); + + independent_comalloc allocates, all at once, a set of n_elements + chunks with sizes indicated in the "sizes" array. It returns + an array of pointers to these elements, each of which can be + independently freed, realloc'ed etc. The elements are guaranteed to + be adjacently allocated (this is not guaranteed to occur with + multiple callocs or mallocs), which may also improve cache locality + in some applications. + + The "chunks" argument is optional (i.e., may be null). If it is null + the returned array is itself dynamically allocated and should also + be freed when it is no longer needed. Otherwise, the chunks array + must be of at least n_elements in length. It is filled in with the + pointers to the chunks. + + In either case, independent_comalloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and chunks is + null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_comalloc differs from independent_calloc in that each + element may have a different size, and also that it does not + automatically clear elements. + + independent_comalloc can be used to speed up allocation in cases + where several structs or objects must always be allocated at the + same time. For example: + + struct Head { ... } + struct Foot { ... } + + void send_message(char* msg) { + int msglen = strlen(msg); + size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; + void* chunks[3]; + if (independent_comalloc(3, sizes, chunks) == 0) + die(); + struct Head* head = (struct Head*)(chunks[0]); + char* body = (char*)(chunks[1]); + struct Foot* foot = (struct Foot*)(chunks[2]); + // ... + } + + In general though, independent_comalloc is worth using only for + larger values of n_elements. For small values, you probably won't + detect enough difference from series of malloc calls to bother. + + Overuse of independent_comalloc can increase overall memory usage, + since it cannot reuse existing noncontiguous small chunks that + might be available for some of the elements. +*/ +DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**); + +/* + bulk_free(void* array[], size_t n_elements) + Frees and clears (sets to null) each non-null pointer in the given + array. This is likely to be faster than freeing them one-by-one. + If footers are used, pointers that have been allocated in different + mspaces are not freed or cleared, and the count of all such pointers + is returned. For large arrays of pointers with poor locality, it + may be worthwhile to sort this array before calling bulk_free. +*/ +DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements); + +/* + pvalloc(size_t n); + Equivalent to valloc(minimum-page-that-holds(n)), that is, + round up n to nearest pagesize. + */ +DLMALLOC_EXPORT void* dlpvalloc(size_t); + +/* + malloc_trim(size_t pad); + + If possible, gives memory back to the system (via negative arguments + to sbrk) if there is unused memory at the `high' end of the malloc + pool or in unused MMAP segments. You can call this after freeing + large blocks of memory to potentially reduce the system-level memory + requirements of a program. However, it cannot guarantee to reduce + memory. Under some allocation patterns, some large free blocks of + memory will be locked between two used chunks, so they cannot be + given back to the system. + + The `pad' argument to malloc_trim represents the amount of free + trailing space to leave untrimmed. If this argument is zero, only + the minimum amount of memory to maintain internal data structures + will be left. Non-zero arguments can be supplied to maintain enough + trailing space to service future expected allocations without having + to re-obtain memory from the system. + + Malloc_trim returns 1 if it actually released any memory, else 0. +*/ +DLMALLOC_EXPORT int dlmalloc_trim(size_t); + +/* + malloc_stats(); + Prints on stderr the amount of space obtained from the system (both + via sbrk and mmap), the maximum amount (which may be more than + current if malloc_trim and/or munmap got called), and the current + number of bytes allocated via malloc (or realloc, etc) but not yet + freed. Note that this is the number of bytes allocated, not the + number requested. It will be larger than the number requested + because of alignment and bookkeeping overhead. Because it includes + alignment wastage as being in use, this figure may be greater than + zero even when no user-level chunks are allocated. + + The reported current and maximum system memory can be inaccurate if + a program makes other calls to system memory allocation functions + (normally sbrk) outside of malloc. + + malloc_stats prints only the most commonly interesting statistics. + More information can be obtained by calling mallinfo. +*/ +DLMALLOC_EXPORT void dlmalloc_stats(void); + +/* + malloc_usable_size(void* p); + + Returns the number of bytes you can actually use in + an allocated chunk, which may be more than you requested (although + often not) due to alignment and minimum size constraints. + You can use this many bytes without worrying about + overwriting other allocated objects. This is not a particularly great + programming practice. malloc_usable_size can be more useful in + debugging and assertions, for example: + + p = malloc(n); + assert(malloc_usable_size(p) >= 256); +*/ +size_t dlmalloc_usable_size(void*); + +#endif /* ONLY_MSPACES */ + +#if MSPACES + +/* + mspace is an opaque type representing an independent + region of space that supports mspace_malloc, etc. +*/ +typedef void* mspace; + +/* + create_mspace creates and returns a new independent space with the + given initial capacity, or, if 0, the default granularity size. It + returns null if there is no system memory available to create the + space. If argument locked is non-zero, the space uses a separate + lock to control access. The capacity of the space will grow + dynamically as needed to service mspace_malloc requests. You can + control the sizes of incremental increases of this space by + compiling with a different DEFAULT_GRANULARITY or dynamically + setting with mallopt(M_GRANULARITY, value). +*/ +DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked); + +/* + destroy_mspace destroys the given space, and attempts to return all + of its memory back to the system, returning the total number of + bytes freed. After destruction, the results of access to all memory + used by the space become undefined. +*/ +DLMALLOC_EXPORT size_t destroy_mspace(mspace msp); + +/* + create_mspace_with_base uses the memory supplied as the initial base + of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this + space is used for bookkeeping, so the capacity must be at least this + large. (Otherwise 0 is returned.) When this initial space is + exhausted, additional memory will be obtained from the system. + Destroying this space will deallocate all additionally allocated + space (if possible) but not the initial base. +*/ +DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked); + +/* + mspace_track_large_chunks controls whether requests for large chunks + are allocated in their own untracked mmapped regions, separate from + others in this mspace. By default large chunks are not tracked, + which reduces fragmentation. However, such chunks are not + necessarily released to the system upon destroy_mspace. Enabling + tracking by setting to true may increase fragmentation, but avoids + leakage when relying on destroy_mspace to release all memory + allocated using this space. The function returns the previous + setting. +*/ +DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable); + + +/* + mspace_malloc behaves as malloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes); + +/* + mspace_free behaves as free, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_free is not actually needed. + free may be called instead of mspace_free because freed chunks from + any space are handled by their originating spaces. +*/ +DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem); + +/* + mspace_realloc behaves as realloc, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_realloc is not actually + needed. realloc may be called instead of mspace_realloc because + realloced chunks from any space are handled by their originating + spaces. +*/ +DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize); + +/* + mspace_calloc behaves as calloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + +/* + mspace_memalign behaves as memalign, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + +/* + mspace_independent_calloc behaves as independent_calloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]); + +/* + mspace_independent_comalloc behaves as independent_comalloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]); + +/* + mspace_footprint() returns the number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_footprint(mspace msp); + +/* + mspace_max_footprint() returns the peak number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp); + + +#if !NO_MALLINFO +/* + mspace_mallinfo behaves as mallinfo, but reports properties of + the given space. +*/ +DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp); +#endif /* NO_MALLINFO */ + +/* + malloc_usable_size(void* p) behaves the same as malloc_usable_size; +*/ +DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem); + +/* + mspace_malloc_stats behaves as malloc_stats, but reports + properties of the given space. +*/ +DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp); + +/* + mspace_trim behaves as malloc_trim, but + operates within the given space. +*/ +DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad); + +/* + An alias for mallopt. +*/ +DLMALLOC_EXPORT int mspace_mallopt(int, int); + +#endif /* MSPACES */ + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif /* __cplusplus */ + +/* + ======================================================================== + To make a fully customizable malloc.h header file, cut everything + above this line, put into file malloc.h, edit to suit, and #include it + on the next line, as well as in programs that use this malloc. + ======================================================================== +*/ + +/* #include "malloc.h" */ + +/*------------------------------ internal #includes ---------------------- */ + +#ifdef _MSC_VER +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ +#endif /* _MSC_VER */ +#if !NO_MALLOC_STATS +#include /* for printing in malloc_stats */ +#endif /* NO_MALLOC_STATS */ +#ifndef LACKS_ERRNO_H +#include /* for MALLOC_FAILURE_ACTION */ +#endif /* LACKS_ERRNO_H */ +#ifdef DEBUG +#if ABORT_ON_ASSERT_FAILURE +#undef assert +#define assert(x) if(!(x)) ABORT +#else /* ABORT_ON_ASSERT_FAILURE */ +#include +#endif /* ABORT_ON_ASSERT_FAILURE */ +#else /* DEBUG */ +#ifndef assert +#define assert(x) +#endif +#define DEBUG 0 +#endif /* DEBUG */ +#if !defined(WIN32) && !defined(LACKS_TIME_H) +#include /* for magic initialization */ +#endif /* WIN32 */ +#ifndef LACKS_STDLIB_H +#include /* for abort() */ +#endif /* LACKS_STDLIB_H */ +#ifndef LACKS_STRING_H +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ +#if USE_BUILTIN_FFS +#ifndef LACKS_STRINGS_H +#include /* for ffs */ +#endif /* LACKS_STRINGS_H */ +#endif /* USE_BUILTIN_FFS */ +#if HAVE_MMAP +#ifndef LACKS_SYS_MMAN_H +/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */ +#if (defined(linux) && !defined(__USE_GNU)) +#define __USE_GNU 1 +#include /* for mmap */ +#undef __USE_GNU +#else +#include /* for mmap */ +#endif /* linux */ +#endif /* LACKS_SYS_MMAN_H */ +#ifndef LACKS_FCNTL_H +#include +#endif /* LACKS_FCNTL_H */ +#endif /* HAVE_MMAP */ +#ifndef LACKS_UNISTD_H +#include /* for sbrk, sysconf */ +#else /* LACKS_UNISTD_H */ +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) +extern void* sbrk(ptrdiff_t); +#endif /* FreeBSD etc */ +#endif /* LACKS_UNISTD_H */ + +/* Declarations for locking */ +#if USE_LOCKS +#ifndef WIN32 +#if defined (__SVR4) && defined (__sun) /* solaris */ +#include +#elif !defined(LACKS_SCHED_H) +#include +#endif /* solaris or LACKS_SCHED_H */ +#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS +#include +#endif /* USE_RECURSIVE_LOCKS ... */ +#elif defined(_MSC_VER) +#ifndef _M_AMD64 +/* These are already defined on AMD64 builds */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp); +LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value); +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _M_AMD64 */ +#pragma intrinsic (_InterlockedCompareExchange) +#pragma intrinsic (_InterlockedExchange) +#define interlockedcompareexchange _InterlockedCompareExchange +#define interlockedexchange _InterlockedExchange +#elif defined(WIN32) && defined(__GNUC__) +#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b) +#define interlockedexchange __sync_lock_test_and_set +#endif /* Win32 */ +#else /* USE_LOCKS */ +#endif /* USE_LOCKS */ + +#ifndef LOCK_AT_FORK +#define LOCK_AT_FORK 0 +#endif + +/* Declarations for bit scanning on win32 */ +#if defined(_MSC_VER) && _MSC_VER>=1300 +#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +unsigned char _BitScanForward(unsigned long *index, unsigned long mask); +unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#define BitScanForward _BitScanForward +#define BitScanReverse _BitScanReverse +#pragma intrinsic(_BitScanForward) +#pragma intrinsic(_BitScanReverse) +#endif /* BitScanForward */ +#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */ + +#ifndef WIN32 +#ifndef malloc_getpagesize +# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +# ifndef _SC_PAGE_SIZE +# define _SC_PAGE_SIZE _SC_PAGESIZE +# endif +# endif +# ifdef _SC_PAGE_SIZE +# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) +# else +# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) + extern size_t getpagesize(); +# define malloc_getpagesize getpagesize() +# else +# ifdef WIN32 /* use supplied emulation of getpagesize */ +# define malloc_getpagesize getpagesize() +# else +# ifndef LACKS_SYS_PARAM_H +# include +# endif +# ifdef EXEC_PAGESIZE +# define malloc_getpagesize EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define malloc_getpagesize NBPG +# else +# define malloc_getpagesize (NBPG * CLSIZE) +# endif +# else +# ifdef NBPC +# define malloc_getpagesize NBPC +# else +# ifdef PAGESIZE +# define malloc_getpagesize PAGESIZE +# else /* just guess */ +# define malloc_getpagesize ((size_t)4096U) +# endif +# endif +# endif +# endif +# endif +# endif +# endif +#endif +#endif + +/* ------------------- size_t and alignment properties -------------------- */ + +/* The byte and bit size of a size_t */ +#define SIZE_T_SIZE (sizeof(size_t)) +#define SIZE_T_BITSIZE (sizeof(size_t) << 3) + +/* Some constants coerced to size_t */ +/* Annoying but necessary to avoid errors on some platforms */ +#define SIZE_T_ZERO ((size_t)0) +#define SIZE_T_ONE ((size_t)1) +#define SIZE_T_TWO ((size_t)2) +#define SIZE_T_FOUR ((size_t)4) +#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) +#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) +#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) +#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) + +/* The bit mask value corresponding to MALLOC_ALIGNMENT */ +#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) + +/* True if address a has acceptable alignment */ +#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) + +/* the number of bytes to offset an address to align it */ +#define align_offset(A)\ + ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ + ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) + +/* -------------------------- MMAP preliminaries ------------------------- */ + +/* + If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and + checks to fail so compiler optimizer can delete code rather than + using so many "#if"s. +*/ + + +/* MORECORE and MMAP must return MFAIL on failure */ +#define MFAIL ((void*)(MAX_SIZE_T)) +#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ + +#if HAVE_MMAP + +#ifndef WIN32 +#define MUNMAP_DEFAULT(a, s) munmap((a), (s)) +#define MMAP_PROT (PROT_READ|PROT_WRITE) +#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) +#define MAP_ANONYMOUS MAP_ANON +#endif /* MAP_ANON */ +#ifdef MAP_ANONYMOUS +#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) +#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) +#else /* MAP_ANONYMOUS */ +/* + Nearly all versions of mmap support MAP_ANONYMOUS, so the following + is unlikely to be needed, but is supplied just in case. +*/ +#define MMAP_FLAGS (MAP_PRIVATE) +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ +#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \ + (dev_zero_fd = open("/dev/zero", O_RDWR), \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) +#endif /* MAP_ANONYMOUS */ + +#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s) + +#else /* WIN32 */ + +/* Win32 MMAP via VirtualAlloc */ +static FORCEINLINE void* win32mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ +static FORCEINLINE void* win32direct_mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, + PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* This function supports releasing coalesced segments */ +static FORCEINLINE int win32munmap(void* ptr, size_t size) { + MEMORY_BASIC_INFORMATION minfo; + char* cptr = (char*)ptr; + while (size) { + if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || + minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; +} + +#define MMAP_DEFAULT(s) win32mmap(s) +#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s)) +#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s) +#endif /* WIN32 */ +#endif /* HAVE_MMAP */ + +#if HAVE_MREMAP +#ifndef WIN32 +#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) +#endif /* WIN32 */ +#endif /* HAVE_MREMAP */ + +/** + * Define CALL_MORECORE + */ +#if HAVE_MORECORE + #ifdef MORECORE + #define CALL_MORECORE(S) MORECORE(S) + #else /* MORECORE */ + #define CALL_MORECORE(S) MORECORE_DEFAULT(S) + #endif /* MORECORE */ +#else /* HAVE_MORECORE */ + #define CALL_MORECORE(S) MFAIL +#endif /* HAVE_MORECORE */ + +/** + * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP + */ +#if HAVE_MMAP + #define USE_MMAP_BIT (SIZE_T_ONE) + + #ifdef MMAP + #define CALL_MMAP(s) MMAP(s) + #else /* MMAP */ + #define CALL_MMAP(s) MMAP_DEFAULT(s) + #endif /* MMAP */ + #ifdef MUNMAP + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) + #else /* MUNMAP */ + #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s)) + #endif /* MUNMAP */ + #ifdef DIRECT_MMAP + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #else /* DIRECT_MMAP */ + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s) + #endif /* DIRECT_MMAP */ +#else /* HAVE_MMAP */ + #define USE_MMAP_BIT (SIZE_T_ZERO) + + #define MMAP(s) MFAIL + #define MUNMAP(a, s) (-1) + #define DIRECT_MMAP(s) MFAIL + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #define CALL_MMAP(s) MMAP(s) + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) +#endif /* HAVE_MMAP */ + +/** + * Define CALL_MREMAP + */ +#if HAVE_MMAP && HAVE_MREMAP + #ifdef MREMAP + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv)) + #else /* MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) + #endif /* MREMAP */ +#else /* HAVE_MMAP && HAVE_MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL +#endif /* HAVE_MMAP && HAVE_MREMAP */ + +/* mstate bit set if contiguous morecore disabled or failed */ +#define USE_NONCONTIGUOUS_BIT (4U) + +/* segment bit set in create_mspace_with_base */ +#define EXTERN_BIT (8U) + + +/* --------------------------- Lock preliminaries ------------------------ */ + +/* + When locks are defined, there is one global lock, plus + one per-mspace lock. + + The global lock_ensures that mparams.magic and other unique + mparams values are initialized only once. It also protects + sequences of calls to MORECORE. In many cases sys_alloc requires + two calls, that should not be interleaved with calls by other + threads. This does not protect against direct calls to MORECORE + by other threads not using this lock, so there is still code to + cope the best we can on interference. + + Per-mspace locks surround calls to malloc, free, etc. + By default, locks are simple non-reentrant mutexes. + + Because lock-protected regions generally have bounded times, it is + OK to use the supplied simple spinlocks. Spinlocks are likely to + improve performance for lightly contended applications, but worsen + performance under heavy contention. + + If USE_LOCKS is > 1, the definitions of lock routines here are + bypassed, in which case you will need to define the type MLOCK_T, + and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK + and TRY_LOCK. You must also declare a + static MLOCK_T malloc_global_mutex = { initialization values };. + +*/ + +#if !USE_LOCKS +#define USE_LOCK_BIT (0U) +#define INITIAL_LOCK(l) (0) +#define DESTROY_LOCK(l) (0) +#define ACQUIRE_MALLOC_GLOBAL_LOCK() +#define RELEASE_MALLOC_GLOBAL_LOCK() + +#else +#if USE_LOCKS > 1 +/* ----------------------- User-defined locks ------------------------ */ +/* Define your own lock implementation here */ +/* #define INITIAL_LOCK(lk) ... */ +/* #define DESTROY_LOCK(lk) ... */ +/* #define ACQUIRE_LOCK(lk) ... */ +/* #define RELEASE_LOCK(lk) ... */ +/* #define TRY_LOCK(lk) ... */ +/* static MLOCK_T malloc_global_mutex = ... */ + +#elif USE_SPIN_LOCKS + +/* First, define CAS_LOCK and CLEAR_LOCK on ints */ +/* Note CAS_LOCK defined to return 0 on success */ + +#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) +#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1) +#define CLEAR_LOCK(sl) __sync_lock_release(sl) + +#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) +/* Custom spin locks for older gcc on x86 */ +static FORCEINLINE int x86_cas_lock(int *sl) { + int ret; + int val = 1; + int cmp = 0; + __asm__ __volatile__ ("lock; cmpxchgl %1, %2" + : "=a" (ret) + : "r" (val), "m" (*(sl)), "0"(cmp) + : "memory", "cc"); + return ret; +} + +static FORCEINLINE void x86_clear_lock(int* sl) { + assert(*sl != 0); + int prev = 0; + int ret; + __asm__ __volatile__ ("lock; xchgl %0, %1" + : "=r" (ret) + : "m" (*(sl)), "0"(prev) + : "memory"); +} + +#define CAS_LOCK(sl) x86_cas_lock(sl) +#define CLEAR_LOCK(sl) x86_clear_lock(sl) + +#else /* Win32 MSC */ +#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1) +#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0) + +#endif /* ... gcc spins locks ... */ + +/* How to yield for a spin lock */ +#define SPINS_PER_YIELD 63 +#if defined(_MSC_VER) +#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */ +#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE) +#elif defined (__SVR4) && defined (__sun) /* solaris */ +#define SPIN_LOCK_YIELD thr_yield(); +#elif !defined(LACKS_SCHED_H) +#define SPIN_LOCK_YIELD sched_yield(); +#else +#define SPIN_LOCK_YIELD +#endif /* ... yield ... */ + +#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0 +/* Plain spin locks use single word (embedded in malloc_states) */ +static int spin_acquire_lock(int *sl) { + int spins = 0; + while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) { + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } + return 0; +} + +#define MLOCK_T int +#define TRY_LOCK(sl) !CAS_LOCK(sl) +#define RELEASE_LOCK(sl) CLEAR_LOCK(sl) +#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0) +#define INITIAL_LOCK(sl) (*sl = 0) +#define DESTROY_LOCK(sl) (0) +static MLOCK_T malloc_global_mutex = 0; + +#else /* USE_RECURSIVE_LOCKS */ +/* types for lock owners */ +#ifdef WIN32 +#define THREAD_ID_T DWORD +#define CURRENT_THREAD GetCurrentThreadId() +#define EQ_OWNER(X,Y) ((X) == (Y)) +#else +/* + Note: the following assume that pthread_t is a type that can be + initialized to (casted) zero. If this is not the case, you will need to + somehow redefine these or not use spin locks. +*/ +#define THREAD_ID_T pthread_t +#define CURRENT_THREAD pthread_self() +#define EQ_OWNER(X,Y) pthread_equal(X, Y) +#endif + +struct malloc_recursive_lock { + int sl; + unsigned int c; + THREAD_ID_T threadid; +}; + +#define MLOCK_T struct malloc_recursive_lock +static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0}; + +static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) { + assert(lk->sl != 0); + if (--lk->c == 0) { + CLEAR_LOCK(&lk->sl); + } +} + +static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + int spins = 0; + for (;;) { + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 0; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 0; + } + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } +} + +static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 1; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 1; + } + return 0; +} + +#define RELEASE_LOCK(lk) recursive_release_lock(lk) +#define TRY_LOCK(lk) recursive_try_lock(lk) +#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk) +#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0) +#define DESTROY_LOCK(lk) (0) +#endif /* USE_RECURSIVE_LOCKS */ + +#elif defined(WIN32) /* Win32 critical sections */ +#define MLOCK_T CRITICAL_SECTION +#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0) +#define RELEASE_LOCK(lk) LeaveCriticalSection(lk) +#define TRY_LOCK(lk) TryEnterCriticalSection(lk) +#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000)) +#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0) +#define NEED_GLOBAL_LOCK_INIT + +static MLOCK_T malloc_global_mutex; +static volatile LONG malloc_global_mutex_status; + +/* Use spin loop to initialize global lock */ +static void init_malloc_global_mutex() { + for (;;) { + long stat = malloc_global_mutex_status; + if (stat > 0) + return; + /* transition to < 0 while initializing, then to > 0) */ + if (stat == 0 && + interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) { + InitializeCriticalSection(&malloc_global_mutex); + interlockedexchange(&malloc_global_mutex_status, (LONG)1); + return; + } + SleepEx(0, FALSE); + } +} + +#else /* pthreads-based locks */ +#define MLOCK_T pthread_mutex_t +#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk) +#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk) +#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk)) +#define INITIAL_LOCK(lk) pthread_init_lock(lk) +#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk) + +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE) +/* Cope with old-style linux recursive lock initialization by adding */ +/* skipped internal declaration from pthread.h */ +extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr, + int __kind)); +#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP +#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y) +#endif /* USE_RECURSIVE_LOCKS ... */ + +static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER; + +static int pthread_init_lock (MLOCK_T *lk) { + pthread_mutexattr_t attr; + if (pthread_mutexattr_init(&attr)) return 1; +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 + if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1; +#endif + if (pthread_mutex_init(lk, &attr)) return 1; + if (pthread_mutexattr_destroy(&attr)) return 1; + return 0; +} + +#endif /* ... lock types ... */ + +/* Common code for all lock types */ +#define USE_LOCK_BIT (2U) + +#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK +#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex); +#endif + +#ifndef RELEASE_MALLOC_GLOBAL_LOCK +#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex); +#endif + +#endif /* USE_LOCKS */ + +/* ----------------------- Chunk representations ------------------------ */ + +/* + (The following includes lightly edited explanations by Colin Plumb.) + + The malloc_chunk declaration below is misleading (but accurate and + necessary). It declares a "view" into memory allowing access to + necessary fields at known offsets from a given base. + + Chunks of memory are maintained using a `boundary tag' method as + originally described by Knuth. (See the paper by Paul Wilson + ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such + techniques.) Sizes of free chunks are stored both in the front of + each chunk and at the end. This makes consolidating fragmented + chunks into bigger chunks fast. The head fields also hold bits + representing whether chunks are free or in use. + + Here are some pictures to make it clearer. They are "exploded" to + show that the state of a chunk can be thought of as extending from + the high 31 bits of the head field of its header through the + prev_foot and PINUSE_BIT bit of the following chunk header. + + A chunk that's in use looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk (if P = 0) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 1| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + +- -+ + | | + +- -+ + | : + +- size - sizeof(size_t) available payload bytes -+ + : | + chunk-> +- -+ + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| + | Size of next chunk (may or may not be in use) | +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + And if it's free, it looks like this: + + chunk-> +- -+ + | User payload (must be in use, or we would have merged!) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 0| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Next pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Prev pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- size - sizeof(struct chunk) unused bytes -+ + : | + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0| + | Size of next chunk (must be in use, or we would have merged)| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- User payload -+ + : | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |0| + +-+ + Note that since we always merge adjacent free chunks, the chunks + adjacent to a free chunk must be in use. + + Given a pointer to a chunk (which can be derived trivially from the + payload pointer) we can, in O(1) time, find out whether the adjacent + chunks are free, and if so, unlink them from the lists that they + are on and merge them with the current chunk. + + Chunks always begin on even word boundaries, so the mem portion + (which is returned to the user) is also on an even word boundary, and + thus at least double-word aligned. + + The P (PINUSE_BIT) bit, stored in the unused low-order bit of the + chunk size (which is always a multiple of two words), is an in-use + bit for the *previous* chunk. If that bit is *clear*, then the + word before the current chunk size contains the previous chunk + size, and can be used to find the front of the previous chunk. + The very first chunk allocated always has this bit set, preventing + access to non-existent (or non-owned) memory. If pinuse is set for + any given chunk, then you CANNOT determine the size of the + previous chunk, and might even get a memory addressing fault when + trying to do so. + + The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of + the chunk size redundantly records whether the current chunk is + inuse (unless the chunk is mmapped). This redundancy enables usage + checks within free and realloc, and reduces indirection when freeing + and consolidating chunks. + + Each freshly allocated chunk must have both cinuse and pinuse set. + That is, each allocated chunk borders either a previously allocated + and still in-use chunk, or the base of its memory arena. This is + ensured by making all allocations from the `lowest' part of any + found chunk. Further, no free chunk physically borders another one, + so each free chunk is known to be preceded and followed by either + inuse chunks or the ends of memory. + + Note that the `foot' of the current chunk is actually represented + as the prev_foot of the NEXT chunk. This makes it easier to + deal with alignments etc but can be very confusing when trying + to extend or adapt this code. + + The exceptions to all this are + + 1. The special chunk `top' is the top-most available chunk (i.e., + the one bordering the end of available memory). It is treated + specially. Top is never included in any bin, is used only if + no other chunk is available, and is released back to the + system if it is very large (see M_TRIM_THRESHOLD). In effect, + the top chunk is treated as larger (and thus less well + fitting) than any other available chunk. The top chunk + doesn't update its trailing size field since there is no next + contiguous chunk that would have to index off it. However, + space is still allocated for it (TOP_FOOT_SIZE) to enable + separation or merging when space is extended. + + 3. Chunks allocated via mmap, have both cinuse and pinuse bits + cleared in their head fields. Because they are allocated + one-by-one, each must carry its own prev_foot field, which is + also used to hold the offset this chunk has within its mmapped + region, which is needed to preserve alignment. Each mmapped + chunk is trailed by the first two fields of a fake next-chunk + for sake of usage checks. + +*/ + +struct malloc_chunk { + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk* fd; /* double links -- used only if free. */ + struct malloc_chunk* bk; +}; + +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk* mchunkptr; +typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ +typedef unsigned int bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ + +/* ------------------- Chunks sizes and alignments ----------------------- */ + +#define MCHUNK_SIZE (sizeof(mchunk)) + +#if FOOTERS +#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +#else /* FOOTERS */ +#define CHUNK_OVERHEAD (SIZE_T_SIZE) +#endif /* FOOTERS */ + +/* MMapped chunks need a second word of overhead ... */ +#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +/* ... and additional padding for fake next-chunk at foot */ +#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) + +/* The smallest size we can malloc is an aligned minimal chunk */ +#define MIN_CHUNK_SIZE\ + ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* conversion from malloc headers to user pointers, and back */ +#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) +#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) +/* chunk associated with aligned address A */ +#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) + +/* Bounds on request (not chunk) sizes. */ +#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) + +/* pad request bytes into a usable size */ +#define pad_request(req) \ + (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* pad request, checking for minimum (but not maximum) */ +#define request2size(req) \ + (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) + + +/* ------------------ Operations on head and foot fields ----------------- */ + +/* + The head field of a chunk is or'ed with PINUSE_BIT when previous + adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in + use, unless mmapped, in which case both bits are cleared. + + FLAG4_BIT is not used by this malloc, but might be useful in extensions. +*/ + +#define PINUSE_BIT (SIZE_T_ONE) +#define CINUSE_BIT (SIZE_T_TWO) +#define FLAG4_BIT (SIZE_T_FOUR) +#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) +#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT) + +/* Head value for fenceposts */ +#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) + +/* extraction of fields from head words */ +#define cinuse(p) ((p)->head & CINUSE_BIT) +#define pinuse(p) ((p)->head & PINUSE_BIT) +#define flag4inuse(p) ((p)->head & FLAG4_BIT) +#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT) +#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0) + +#define chunksize(p) ((p)->head & ~(FLAG_BITS)) + +#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) +#define set_flag4(p) ((p)->head |= FLAG4_BIT) +#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT) + +/* Treat space at ptr +/- offset as a chunk */ +#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) +#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) + +/* Ptr to next or previous physical malloc_chunk. */ +#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS))) +#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) )) + +/* extract next chunk's pinuse bit */ +#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) + +/* Get/set size at footer */ +#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) +#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) + +/* Set size, pinuse bit, and foot */ +#define set_size_and_pinuse_of_free_chunk(p, s)\ + ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) + +/* Set size, pinuse bit, foot, and clear next pinuse */ +#define set_free_with_pinuse(p, s, n)\ + (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) + +/* Get the internal overhead associated with chunk p */ +#define overhead_for(p)\ + (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) + +/* Return true if malloced space is not necessarily cleared */ +#if MMAP_CLEARS +#define calloc_must_clear(p) (!is_mmapped(p)) +#else /* MMAP_CLEARS */ +#define calloc_must_clear(p) (1) +#endif /* MMAP_CLEARS */ + +/* ---------------------- Overlaid data structures ----------------------- */ + +/* + When chunks are not in use, they are treated as nodes of either + lists or trees. + + "Small" chunks are stored in circular doubly-linked lists, and look + like this: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space (may be 0 bytes long) . + . . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Larger chunks are kept in a form of bitwise digital trees (aka + tries) keyed on chunksizes. Because malloc_tree_chunks are only for + free chunks greater than 256 bytes, their size doesn't impose any + constraints on user chunk sizes. Each node looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to left child (child[0]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to right child (child[1]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to parent | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | bin index of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Each tree holding treenodes is a tree of unique chunk sizes. Chunks + of the same size are arranged in a circularly-linked list, with only + the oldest chunk (the next to be used, in our FIFO ordering) + actually in the tree. (Tree members are distinguished by a non-null + parent pointer.) If a chunk with the same size an an existing node + is inserted, it is linked off the existing node using pointers that + work in the same way as fd/bk pointers of small chunks. + + Each tree contains a power of 2 sized range of chunk sizes (the + smallest is 0x100 <= x < 0x180), which is is divided in half at each + tree level, with the chunks in the smaller half of the range (0x100 + <= x < 0x140 for the top nose) in the left subtree and the larger + half (0x140 <= x < 0x180) in the right subtree. This is, of course, + done by inspecting individual bits. + + Using these rules, each node's left subtree contains all smaller + sizes than its right subtree. However, the node at the root of each + subtree has no particular ordering relationship to either. (The + dividing line between the subtree sizes is based on trie relation.) + If we remove the last chunk of a given size from the interior of the + tree, we need to replace it with a leaf node. The tree ordering + rules permit a node to be replaced by any leaf below it. + + The smallest chunk in a tree (a common operation in a best-fit + allocator) can be found by walking a path to the leftmost leaf in + the tree. Unlike a usual binary tree, where we follow left child + pointers until we reach a null, here we follow the right child + pointer any time the left one is null, until we reach a leaf with + both child pointers null. The smallest chunk in the tree will be + somewhere along that path. + + The worst case number of steps to add, find, or remove a node is + bounded by the number of bits differentiating chunks within + bins. Under current bin calculations, this ranges from 6 up to 21 + (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case + is of course much better. +*/ + +struct malloc_tree_chunk { + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk* fd; + struct malloc_tree_chunk* bk; + + struct malloc_tree_chunk* child[2]; + struct malloc_tree_chunk* parent; + bindex_t index; +}; + +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk* tchunkptr; +typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ + +/* A little helper macro for trees */ +#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) + +/* ----------------------------- Segments -------------------------------- */ + +/* + Each malloc space may include non-contiguous segments, held in a + list headed by an embedded malloc_segment record representing the + top-most space. Segments also include flags holding properties of + the space. Large chunks that are directly allocated by mmap are not + included in this list. They are instead independently created and + destroyed without otherwise keeping track of them. + + Segment management mainly comes into play for spaces allocated by + MMAP. Any call to MMAP might or might not return memory that is + adjacent to an existing segment. MORECORE normally contiguously + extends the current space, so this space is almost always adjacent, + which is simpler and faster to deal with. (This is why MORECORE is + used preferentially to MMAP when both are available -- see + sys_alloc.) When allocating using MMAP, we don't use any of the + hinting mechanisms (inconsistently) supported in various + implementations of unix mmap, or distinguish reserving from + committing memory. Instead, we just ask for space, and exploit + contiguity when we get it. It is probably possible to do + better than this on some systems, but no general scheme seems + to be significantly better. + + Management entails a simpler variant of the consolidation scheme + used for chunks to reduce fragmentation -- new adjacent memory is + normally prepended or appended to an existing segment. However, + there are limitations compared to chunk consolidation that mostly + reflect the fact that segment processing is relatively infrequent + (occurring only when getting memory from system) and that we + don't expect to have huge numbers of segments: + + * Segments are not indexed, so traversal requires linear scans. (It + would be possible to index these, but is not worth the extra + overhead and complexity for most programs on most platforms.) + * New segments are only appended to old ones when holding top-most + memory; if they cannot be prepended to others, they are held in + different segments. + + Except for the top-most segment of an mstate, each segment record + is kept at the tail of its segment. Segments are added by pushing + segment records onto the list headed by &mstate.seg for the + containing mstate. + + Segment flags control allocation/merge/deallocation policies: + * If EXTERN_BIT set, then we did not allocate this segment, + and so should not try to deallocate or merge with others. + (This currently holds only for the initial segment passed + into create_mspace_with_base.) + * If USE_MMAP_BIT set, the segment may be merged with + other surrounding mmapped segments and trimmed/de-allocated + using munmap. + * If neither bit is set, then the segment was obtained using + MORECORE so can be merged with surrounding MORECORE'd segments + and deallocated/trimmed using MORECORE with negative arguments. +*/ + +struct malloc_segment { + char* base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment* next; /* ptr to next segment */ + flag_t sflags; /* mmap and extern flag */ +}; + +#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT) +#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) + +typedef struct malloc_segment msegment; +typedef struct malloc_segment* msegmentptr; + +/* ---------------------------- malloc_state ----------------------------- */ + +/* + A malloc_state holds all of the bookkeeping for a space. + The main fields are: + + Top + The topmost chunk of the currently active segment. Its size is + cached in topsize. The actual size of topmost space is + topsize+TOP_FOOT_SIZE, which includes space reserved for adding + fenceposts and segment records if necessary when getting more + space from the system. The size at which to autotrim top is + cached from mparams in trim_check, except that it is disabled if + an autotrim fails. + + Designated victim (dv) + This is the preferred chunk for servicing small requests that + don't have exact fits. It is normally the chunk split off most + recently to service another small request. Its size is cached in + dvsize. The link fields of this chunk are not maintained since it + is not kept in a bin. + + SmallBins + An array of bin headers for free chunks. These bins hold chunks + with sizes less than MIN_LARGE_SIZE bytes. Each bin contains + chunks of all the same size, spaced 8 bytes apart. To simplify + use in double-linked lists, each bin header acts as a malloc_chunk + pointing to the real first node, if it exists (else pointing to + itself). This avoids special-casing for headers. But to avoid + waste, we allocate only the fd/bk pointers of bins, and then use + repositioning tricks to treat these as the fields of a chunk. + + TreeBins + Treebins are pointers to the roots of trees holding a range of + sizes. There are 2 equally spaced treebins for each power of two + from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything + larger. + + Bin maps + There is one bit map for small bins ("smallmap") and one for + treebins ("treemap). Each bin sets its bit when non-empty, and + clears the bit when empty. Bit operations are then used to avoid + bin-by-bin searching -- nearly all "search" is done without ever + looking at bins that won't be selected. The bit maps + conservatively use 32 bits per map word, even if on 64bit system. + For a good description of some of the bit-based techniques used + here, see Henry S. Warren Jr's book "Hacker's Delight" (and + supplement at http://hackersdelight.org/). Many of these are + intended to reduce the branchiness of paths through malloc etc, as + well as to reduce the number of memory locations read or written. + + Segments + A list of segments headed by an embedded malloc_segment record + representing the initial space. + + Address check support + The least_addr field is the least address ever obtained from + MORECORE or MMAP. Attempted frees and reallocs of any address less + than this are trapped (unless INSECURE is defined). + + Magic tag + A cross-check field that should always hold same value as mparams.magic. + + Max allowed footprint + The maximum allowed bytes to allocate from system (zero means no limit) + + Flags + Bits recording whether to use MMAP, locks, or contiguous MORECORE + + Statistics + Each space keeps track of current and maximum system memory + obtained via MORECORE or MMAP. + + Trim support + Fields holding the amount of unused topmost memory that should trigger + trimming, and a counter to force periodic scanning to release unused + non-topmost segments. + + Locking + If USE_LOCKS is defined, the "mutex" lock is acquired and released + around every public call using this mspace. + + Extension support + A void* pointer and a size_t field that can be used to help implement + extensions to this malloc. +*/ + +/* Bin types, widths and sizes */ +#define NSMALLBINS (32U) +#define NTREEBINS (32U) +#define SMALLBIN_SHIFT (3U) +#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) +#define TREEBIN_SHIFT (8U) +#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) +#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) +#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) + +struct malloc_state { + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char* least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t release_checks; + size_t magic; + mchunkptr smallbins[(NSMALLBINS+1)*2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + size_t footprint_limit; /* zero means no limit */ + flag_t mflags; +#if USE_LOCKS + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; + void* extp; /* Unused but available for extensions */ + size_t exts; +}; + +typedef struct malloc_state* mstate; + +/* ------------- Global malloc_state and malloc_params ------------------- */ + +/* + malloc_params holds global properties, including those that can be + dynamically set using mallopt. There is a single instance, mparams, + initialized in init_mparams. Note that the non-zeroness of "magic" + also serves as an initialization flag. +*/ + +struct malloc_params { + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; +}; + +static struct malloc_params mparams; + +/* Ensure mparams initialized */ +#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams()) + +#if !ONLY_MSPACES + +/* The global malloc_state used for all non-"mspace" calls */ +static struct malloc_state _gm_; +#define gm (&_gm_) +#define is_global(M) ((M) == &_gm_) + +#endif /* !ONLY_MSPACES */ + +#define is_initialized(M) ((M)->top != 0) + +/* -------------------------- system alloc setup ------------------------- */ + +/* Operations on mflags */ + +#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) +#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) +#if USE_LOCKS +#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) +#else +#define disable_lock(M) +#endif + +#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) +#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) +#if HAVE_MMAP +#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) +#else +#define disable_mmap(M) +#endif + +#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) +#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) + +#define set_lock(M,L)\ + ((M)->mflags = (L)?\ + ((M)->mflags | USE_LOCK_BIT) :\ + ((M)->mflags & ~USE_LOCK_BIT)) + +/* page-align a size */ +#define page_align(S)\ + (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE)) + +/* granularity-align a size */ +#define granularity_align(S)\ + (((S) + (mparams.granularity - SIZE_T_ONE))\ + & ~(mparams.granularity - SIZE_T_ONE)) + + +/* For mmap, use granularity alignment on windows, else page-align */ +#ifdef WIN32 +#define mmap_align(S) granularity_align(S) +#else +#define mmap_align(S) page_align(S) +#endif + +/* For sys_alloc, enough padding to ensure can malloc request on success */ +#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT) + +#define is_page_aligned(S)\ + (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) +#define is_granularity_aligned(S)\ + (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) + +/* True if segment S holds address A */ +#define segment_holds(S, A)\ + ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) + +/* Return segment holding given address */ +static msegmentptr segment_holding(mstate m, char* addr) { + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= sp->base && addr < sp->base + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } +} + +/* Return true if segment contains a segment link */ +static int has_segment_link(mstate m, msegmentptr ss) { + msegmentptr sp = &m->seg; + for (;;) { + if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) + return 1; + if ((sp = sp->next) == 0) + return 0; + } +} + +#ifndef MORECORE_CANNOT_TRIM +#define should_trim(M,s) ((s) > (M)->trim_check) +#else /* MORECORE_CANNOT_TRIM */ +#define should_trim(M,s) (0) +#endif /* MORECORE_CANNOT_TRIM */ + +/* + TOP_FOOT_SIZE is padding at the end of a segment, including space + that may be needed to place segment records and fenceposts when new + noncontiguous segments are added. +*/ +#define TOP_FOOT_SIZE\ + (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) + + +/* ------------------------------- Hooks -------------------------------- */ + +/* + PREACTION should be defined to return 0 on success, and nonzero on + failure. If you are not using locking, you can redefine these to do + anything you like. +*/ + +#if USE_LOCKS +#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0) +#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); } +#else /* USE_LOCKS */ + +#ifndef PREACTION +#define PREACTION(M) (0) +#endif /* PREACTION */ + +#ifndef POSTACTION +#define POSTACTION(M) +#endif /* POSTACTION */ + +#endif /* USE_LOCKS */ + +/* + CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses. + USAGE_ERROR_ACTION is triggered on detected bad frees and + reallocs. The argument p is an address that might have triggered the + fault. It is ignored by the two predefined actions, but might be + useful in custom actions that try to help diagnose errors. +*/ + +#if PROCEED_ON_ERROR + +/* A count of the number of corruption errors causing resets */ +int malloc_corruption_error_count; + +/* default corruption action */ +static void reset_on_error(mstate m); + +#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) +#define USAGE_ERROR_ACTION(m, p) + +#else /* PROCEED_ON_ERROR */ + +#ifndef CORRUPTION_ERROR_ACTION +#define CORRUPTION_ERROR_ACTION(m) ABORT +#endif /* CORRUPTION_ERROR_ACTION */ + +#ifndef USAGE_ERROR_ACTION +#define USAGE_ERROR_ACTION(m,p) ABORT +#endif /* USAGE_ERROR_ACTION */ + +#endif /* PROCEED_ON_ERROR */ + + +/* -------------------------- Debugging setup ---------------------------- */ + +#if ! DEBUG + +#define check_free_chunk(M,P) +#define check_inuse_chunk(M,P) +#define check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) +#define check_malloc_state(M) +#define check_top_chunk(M,P) + +#else /* DEBUG */ +#define check_free_chunk(M,P) do_check_free_chunk(M,P) +#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P) +#define check_top_chunk(M,P) do_check_top_chunk(M,P) +#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) +#define check_malloc_state(M) do_check_malloc_state(M) + +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void* mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); +static size_t traverse_and_check(mstate m); +#endif /* DEBUG */ + +/* ---------------------------- Indexing Bins ---------------------------- */ + +#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) +#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT) +#define small_index2size(i) ((i) << SMALLBIN_SHIFT) +#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) + +/* addressing by index. See above about smallbin repositioning */ +#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1]))) +#define treebin_at(M,i) (&((M)->treebins[i])) + +/* assign tree index for size S to variable I. Use x86 asm if possible */ +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_tree_index(S, I)\ +{\ + unsigned int X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = _bit_scan_reverse (X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K;\ + _BitScanReverse((DWORD *) &K, (DWORD) X);\ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#else /* GNUC */ +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int Y = (unsigned int)X;\ + unsigned int N = ((Y - 0x100) >> 16) & 8;\ + unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\ + N += K;\ + N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\ + K = 14 - N + ((Y <<= K) >> 15);\ + I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\ + }\ +} +#endif /* GNUC */ + +/* Bit representing maximum resolved size in a treebin at i */ +#define bit_for_tree_index(i) \ + (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) + +/* Shift placing maximum resolved bit in a treebin at i as sign bit */ +#define leftshift_for_tree_index(i) \ + ((i == NTREEBINS-1)? 0 : \ + ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) + +/* The size of the smallest chunk held in bin with index i */ +#define minsize_for_tree_index(i) \ + ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ + (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) + + +/* ------------------------ Operations on bin maps ----------------------- */ + +/* bit corresponding to given index */ +#define idx2bit(i) ((binmap_t)(1) << (i)) + +/* Mark/Clear bits with given index */ +#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) +#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) +#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) + +#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) +#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) +#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) + +/* isolate the least set bit of a bitmap */ +#define least_bit(x) ((x) & -(x)) + +/* mask with all bits to left of least bit of x on */ +#define left_bits(x) ((x<<1) | -(x<<1)) + +/* mask with all bits to left of or equal to least bit of x on */ +#define same_or_left_bits(x) ((x) | -(x)) + +/* index corresponding to given bit. Use x86 asm if possible */ + +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = __builtin_ctz(X); \ + I = (bindex_t)J;\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = _bit_scan_forward (X); \ + I = (bindex_t)J;\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + _BitScanForward((DWORD *) &J, X);\ + I = (bindex_t)J;\ +} + +#elif USE_BUILTIN_FFS +#define compute_bit2idx(X, I) I = ffs(X)-1 + +#else +#define compute_bit2idx(X, I)\ +{\ + unsigned int Y = X - 1;\ + unsigned int K = Y >> (16-4) & 16;\ + unsigned int N = K; Y >>= K;\ + N += K = Y >> (8-3) & 8; Y >>= K;\ + N += K = Y >> (4-2) & 4; Y >>= K;\ + N += K = Y >> (2-1) & 2; Y >>= K;\ + N += K = Y >> (1-0) & 1; Y >>= K;\ + I = (bindex_t)(N + Y);\ +} +#endif /* GNUC */ + + +/* ----------------------- Runtime Check Support ------------------------- */ + +/* + For security, the main invariant is that malloc/free/etc never + writes to a static address other than malloc_state, unless static + malloc_state itself has been corrupted, which cannot occur via + malloc (because of these checks). In essence this means that we + believe all pointers, sizes, maps etc held in malloc_state, but + check all of those linked or offsetted from other embedded data + structures. These checks are interspersed with main code in a way + that tends to minimize their run-time cost. + + When FOOTERS is defined, in addition to range checking, we also + verify footer fields of inuse chunks, which can be used guarantee + that the mstate controlling malloc/free is intact. This is a + streamlined version of the approach described by William Robertson + et al in "Run-time Detection of Heap-based Overflows" LISA'03 + http://www.usenix.org/events/lisa03/tech/robertson.html The footer + of an inuse chunk holds the xor of its mstate and a random seed, + that is checked upon calls to free() and realloc(). This is + (probabalistically) unguessable from outside the program, but can be + computed by any code successfully malloc'ing any chunk, so does not + itself provide protection against code that has already broken + security through some other means. Unlike Robertson et al, we + always dynamically check addresses of all offset chunks (previous, + next, etc). This turns out to be cheaper than relying on hashes. +*/ + +#if !INSECURE +/* Check if address a is at least as high as any from MORECORE or MMAP */ +#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) +/* Check if address of next chunk n is higher than base chunk p */ +#define ok_next(p, n) ((char*)(p) < (char*)(n)) +/* Check if p has inuse status */ +#define ok_inuse(p) is_inuse(p) +/* Check if p has its pinuse bit on */ +#define ok_pinuse(p) pinuse(p) + +#else /* !INSECURE */ +#define ok_address(M, a) (1) +#define ok_next(b, n) (1) +#define ok_inuse(p) (1) +#define ok_pinuse(p) (1) +#endif /* !INSECURE */ + +#if (FOOTERS && !INSECURE) +/* Check if (alleged) mstate m has expected magic field */ +#define ok_magic(M) ((M)->magic == mparams.magic) +#else /* (FOOTERS && !INSECURE) */ +#define ok_magic(M) (1) +#endif /* (FOOTERS && !INSECURE) */ + +/* In gcc, use __builtin_expect to minimize impact of checks */ +#if !INSECURE +#if defined(__GNUC__) && __GNUC__ >= 3 +#define RTCHECK(e) __builtin_expect(e, 1) +#else /* GNUC */ +#define RTCHECK(e) (e) +#endif /* GNUC */ +#else /* !INSECURE */ +#define RTCHECK(e) (1) +#endif /* !INSECURE */ + +/* macros to set up inuse chunks with or without footers */ + +#if !FOOTERS + +#define mark_inuse_foot(M,p,s) + +/* Macros for setting head/foot of non-mmapped chunks */ + +/* Set cinuse bit and pinuse bit of next chunk */ +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set cinuse and pinuse of this chunk and pinuse of next chunk */ +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set size, cinuse and pinuse bit of this chunk */ +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) + +#else /* FOOTERS */ + +/* Set foot of inuse chunk to be xor of mstate and seed */ +#define mark_inuse_foot(M,p,s)\ + (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) + +#define get_mstate_for(p)\ + ((mstate)(((mchunkptr)((char*)(p) +\ + (chunksize(p))))->prev_foot ^ mparams.magic)) + +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M,p,s)) + +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\ + mark_inuse_foot(M,p,s)) + +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + mark_inuse_foot(M, p, s)) + +#endif /* !FOOTERS */ + +/* ---------------------------- setting mparams -------------------------- */ + +#if LOCK_AT_FORK +static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); } +static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); } +static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); } +#endif /* LOCK_AT_FORK */ + +/* Initialize mparams */ +static int init_mparams(void) { +#ifdef NEED_GLOBAL_LOCK_INIT + if (malloc_global_mutex_status <= 0) + init_malloc_global_mutex(); +#endif + + ACQUIRE_MALLOC_GLOBAL_LOCK(); + if (mparams.magic == 0) { + size_t magic; + size_t psize; + size_t gsize; + +#ifndef WIN32 + psize = malloc_getpagesize; + gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize); +#else /* WIN32 */ + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + psize = system_info.dwPageSize; + gsize = ((DEFAULT_GRANULARITY != 0)? + DEFAULT_GRANULARITY : system_info.dwAllocationGranularity); + } +#endif /* WIN32 */ + + /* Sanity-check configuration: + size_t must be unsigned and as wide as pointer type. + ints must be at least 4 bytes. + alignment must be at least 8. + Alignment, min chunk size, and page size must all be powers of 2. + */ + if ((sizeof(size_t) != sizeof(char*)) || + (MAX_SIZE_T < MIN_CHUNK_SIZE) || + (sizeof(int) < 4) || + (MALLOC_ALIGNMENT < (size_t)8U) || + ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || + ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || + ((gsize & (gsize-SIZE_T_ONE)) != 0) || + ((psize & (psize-SIZE_T_ONE)) != 0)) + ABORT; + mparams.granularity = gsize; + mparams.page_size = psize; + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; +#if MORECORE_CONTIGUOUS + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; +#else /* MORECORE_CONTIGUOUS */ + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; +#endif /* MORECORE_CONTIGUOUS */ + +#if !ONLY_MSPACES + /* Set up lock for main malloc area */ + gm->mflags = mparams.default_mflags; + (void)INITIAL_LOCK(&gm->mutex); +#endif +#if LOCK_AT_FORK + pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child); +#endif + + { +#if USE_DEV_RANDOM + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && + read(fd, buf, sizeof(buf)) == sizeof(buf)) { + magic = *((size_t *) buf); + close(fd); + } + else +#endif /* USE_DEV_RANDOM */ +#ifdef WIN32 + magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U); +#elif defined(LACKS_TIME_H) + magic = (size_t)&magic ^ (size_t)0x55555555U; +#else + magic = (size_t)(time(0) ^ (size_t)0x55555555U); +#endif + magic |= (size_t)8U; /* ensure nonzero */ + magic &= ~(size_t)7U; /* improve chances of fault for bad values */ + /* Until memory modes commonly available, use volatile-write */ + (*(volatile size_t *)(&(mparams.magic))) = magic; + } + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + return 1; +} + +/* support for mallopt */ +static int change_mparam(int param_number, int value) { + size_t val; + ensure_initialization(); + val = (value == -1)? MAX_SIZE_T : (size_t)value; + switch(param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if (val >= mparams.page_size && ((val & (val-1)) == 0)) { + mparams.granularity = val; + return 1; + } + else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; + } +} + +#if DEBUG +/* ------------------------- Debugging Support --------------------------- */ + +/* Check properties of any chunk, whether free, inuse, mmapped etc */ +static void do_check_any_chunk(mstate m, mchunkptr p) { + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); +} + +/* Check properties of top chunk */ +static void do_check_top_chunk(mstate m, mchunkptr p) { + msegmentptr sp = segment_holding(m, (char*)p); + size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */ + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!pinuse(chunk_plus_offset(p, sz))); +} + +/* Check properties of (inuse) mmapped chunks */ +static void do_check_mmapped_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +} + +/* Check properties of inuse chunks */ +static void do_check_inuse_chunk(mstate m, mchunkptr p) { + do_check_any_chunk(m, p); + assert(is_inuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if (is_mmapped(p)) + do_check_mmapped_chunk(m, p); +} + +/* Check properties of free chunks */ +static void do_check_free_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!is_inuse(p)); + assert(!next_pinuse(p)); + assert (!is_mmapped(p)); + if (p != m->dv && p != m->top) { + if (sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert (next == m->top || is_inuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } + else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); + } +} + +/* Check properties of malloced chunks at the point they are malloced */ +static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~INUSE_BITS; + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } +} + +/* Check a tree and its subtrees. */ +static void do_check_tree(mstate m, tchunkptr t) { + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr)u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!is_inuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if (u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } + else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert (u->parent->child[0] == u || + u->parent->child[1] == u || + *((tbinptr*)(u->parent)) == u); + if (u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if (u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if (u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; + } while (u != t); + assert(head != 0); +} + +/* Check all the chunks in a treebin. */ +static void do_check_treebin(mstate m, bindex_t i) { + tbinptr* tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if (t == 0) + assert(empty); + if (!empty) + do_check_tree(m, t); +} + +/* Check all the chunks in a smallbin. */ +static void do_check_smallbin(mstate m, bindex_t i) { + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if (p == b) + assert(empty); + if (!empty) { + for (; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if (q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } + } +} + +/* Find x in a bin. Used in other check functions. */ +static int bin_find(mstate m, mchunkptr x) { + size_t size = chunksize(x); + if (is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if (smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if (p == x) + return 1; + } while ((p = p->fd) != b); + } + } + else { + bindex_t tidx; + compute_tree_index(size, tidx); + if (treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while (t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if (t != 0) { + tchunkptr u = t; + do { + if (u == (tchunkptr)x) + return 1; + } while ((u = u->fd) != t); + } + } + } + return 0; +} + +/* Traverse each chunk and check it; return total */ +static size_t traverse_and_check(mstate m) { + size_t sum = 0; + if (is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if (is_inuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } + else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; + } + } + return sum; +} + + +/* Check all properties of malloc_state. */ +static void do_check_malloc_state(mstate m) { + bindex_t i; + size_t total; + /* check bins */ + for (i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for (i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if (m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } + + if (m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + /*assert(m->topsize == chunksize(m->top)); redundant */ + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } + + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); +} +#endif /* DEBUG */ + +/* ----------------------------- statistics ------------------------------ */ + +#if !NO_MALLINFO +static struct mallinfo internal_mallinfo(mstate m) { + struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + ensure_initialization(); + if (!PREACTION(m)) { + check_malloc_state(m); + if (is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if (!is_inuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; + } + + POSTACTION(m); + } + return nm; +} +#endif /* !NO_MALLINFO */ + +#if !NO_MALLOC_STATS +static void internal_malloc_stats(mstate m) { + ensure_initialization(); + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!is_inuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + POSTACTION(m); /* drop lock */ + fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + } +} +#endif /* NO_MALLOC_STATS */ + +/* ----------------------- Operations on smallbins ----------------------- */ + +/* + Various forms of linking and unlinking are defined as macros. Even + the ones for trees, which are very long but have very short typical + paths. This is ugly but reduces reliance on inlining support of + compilers. +*/ + +/* Link a free chunk into a smallbin */ +#define insert_small_chunk(M, P, S) {\ + bindex_t I = small_index(S);\ + mchunkptr B = smallbin_at(M, I);\ + mchunkptr F = B;\ + assert(S >= MIN_CHUNK_SIZE);\ + if (!smallmap_is_marked(M, I))\ + mark_smallmap(M, I);\ + else if (RTCHECK(ok_address(M, B->fd)))\ + F = B->fd;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + B->fd = P;\ + F->bk = P;\ + P->fd = F;\ + P->bk = B;\ +} + +/* Unlink a chunk from a smallbin */ +#define unlink_small_chunk(M, P, S) {\ + mchunkptr F = P->fd;\ + mchunkptr B = P->bk;\ + bindex_t I = small_index(S);\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(B == smallbin_at(M,I) ||\ + (ok_address(M, B) && B->fd == P))) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Unlink the first chunk from a smallbin */ +#define unlink_first_small_chunk(M, B, P, I) {\ + mchunkptr F = P->fd;\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Replace dv node, binning the old one */ +/* Used only when dvsize known to be small */ +#define replace_dv(M, P, S) {\ + size_t DVS = M->dvsize;\ + assert(is_small(DVS));\ + if (DVS != 0) {\ + mchunkptr DV = M->dv;\ + insert_small_chunk(M, DV, DVS);\ + }\ + M->dvsize = S;\ + M->dv = P;\ +} + +/* ------------------------- Operations on trees ------------------------- */ + +/* Insert chunk into tree */ +#define insert_large_chunk(M, X, S) {\ + tbinptr* H;\ + bindex_t I;\ + compute_tree_index(S, I);\ + H = treebin_at(M, I);\ + X->index = I;\ + X->child[0] = X->child[1] = 0;\ + if (!treemap_is_marked(M, I)) {\ + mark_treemap(M, I);\ + *H = X;\ + X->parent = (tchunkptr)H;\ + X->fd = X->bk = X;\ + }\ + else {\ + tchunkptr T = *H;\ + size_t K = S << leftshift_for_tree_index(I);\ + for (;;) {\ + if (chunksize(T) != S) {\ + tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ + K <<= 1;\ + if (*C != 0)\ + T = *C;\ + else if (RTCHECK(ok_address(M, C))) {\ + *C = X;\ + X->parent = T;\ + X->fd = X->bk = X;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + else {\ + tchunkptr F = T->fd;\ + if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\ + T->fd = F->bk = X;\ + X->fd = F;\ + X->bk = T;\ + X->parent = 0;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + }\ + }\ +} + +/* + Unlink steps: + + 1. If x is a chained node, unlink it from its same-sized fd/bk links + and choose its bk node as its replacement. + 2. If x was the last node of its size, but not a leaf node, it must + be replaced with a leaf node (not merely one with an open left or + right), to make sure that lefts and rights of descendents + correspond properly to bit masks. We use the rightmost descendent + of x. We could use any other leaf, but this is easy to locate and + tends to counteract removal of leftmosts elsewhere, and so keeps + paths shorter than minimally guaranteed. This doesn't loop much + because on average a node in a tree is near the bottom. + 3. If x is the base of a chain (i.e., has parent links) relink + x's parent and children to x's replacement (or null if none). +*/ + +#define unlink_large_chunk(M, X) {\ + tchunkptr XP = X->parent;\ + tchunkptr R;\ + if (X->bk != X) {\ + tchunkptr F = X->fd;\ + R = X->bk;\ + if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\ + F->bk = R;\ + R->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + tchunkptr* RP;\ + if (((R = *(RP = &(X->child[1]))) != 0) ||\ + ((R = *(RP = &(X->child[0]))) != 0)) {\ + tchunkptr* CP;\ + while ((*(CP = &(R->child[1])) != 0) ||\ + (*(CP = &(R->child[0])) != 0)) {\ + R = *(RP = CP);\ + }\ + if (RTCHECK(ok_address(M, RP)))\ + *RP = 0;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + }\ + if (XP != 0) {\ + tbinptr* H = treebin_at(M, X->index);\ + if (X == *H) {\ + if ((*H = R) == 0) \ + clear_treemap(M, X->index);\ + }\ + else if (RTCHECK(ok_address(M, XP))) {\ + if (XP->child[0] == X) \ + XP->child[0] = R;\ + else \ + XP->child[1] = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + if (R != 0) {\ + if (RTCHECK(ok_address(M, R))) {\ + tchunkptr C0, C1;\ + R->parent = XP;\ + if ((C0 = X->child[0]) != 0) {\ + if (RTCHECK(ok_address(M, C0))) {\ + R->child[0] = C0;\ + C0->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + if ((C1 = X->child[1]) != 0) {\ + if (RTCHECK(ok_address(M, C1))) {\ + R->child[1] = C1;\ + C1->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ +} + +/* Relays to large vs small bin operations */ + +#define insert_chunk(M, P, S)\ + if (is_small(S)) insert_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } + +#define unlink_chunk(M, P, S)\ + if (is_small(S)) unlink_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } + + +/* Relays to internal calls to malloc/free from realloc, memalign etc */ + +#if ONLY_MSPACES +#define internal_malloc(m, b) mspace_malloc(m, b) +#define internal_free(m, mem) mspace_free(m,mem); +#else /* ONLY_MSPACES */ +#if MSPACES +#define internal_malloc(m, b)\ + ((m == gm)? dlmalloc(b) : mspace_malloc(m, b)) +#define internal_free(m, mem)\ + if (m == gm) dlfree(mem); else mspace_free(m,mem); +#else /* MSPACES */ +#define internal_malloc(m, b) dlmalloc(b) +#define internal_free(m, mem) dlfree(mem) +#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ + +/* ----------------------- Direct-mmapping chunks ----------------------- */ + +/* + Directly mmapped chunks are set up with an offset to the start of + the mmapped region stored in the prev_foot field of the chunk. This + allows reconstruction of the required argument to MUNMAP when freed, + and also allows adjustment of the returned chunk to meet alignment + requirements (especially in memalign). +*/ + +/* Malloc using mmap */ +static void* mmap_alloc(mstate m, size_t nb) { + size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if (m->footprint_limit != 0) { + size_t fp = m->footprint + mmsize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + if (mmsize > nb) { /* Check for wrap around 0 */ + char* mm = (char*)(CALL_DIRECT_MMAP(mmsize)); + if (mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr)(mm + offset); + p->prev_foot = offset; + p->head = psize; + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; + + if (m->least_addr == 0 || mm < m->least_addr) + m->least_addr = mm; + if ((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } + } + return 0; +} + +/* Realloc using mmap */ +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) { + size_t oldsize = chunksize(oldp); + (void)flags; /* placate people compiling -Wunused */ + if (is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= nb + SIZE_T_SIZE && + (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + char* cp = (char*)CALL_MREMAP((char*)oldp - offset, + oldmmsize, newmmsize, flags); + if (cp != CMFAIL) { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = psize; + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } + } + return 0; +} + + +/* -------------------------- mspace management -------------------------- */ + +/* Initialize top chunk and its size */ +static void init_top(mstate m, mchunkptr p, size_t psize) { + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr)((char*)p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ +} + +/* Initialize bins for a new mstate that is otherwise zeroed out */ +static void init_bins(mstate m) { + /* Establish circular links for smallbins */ + bindex_t i; + for (i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m,i); + bin->fd = bin->bk = bin; + } +} + +#if PROCEED_ON_ERROR + +/* default corruption action */ +static void reset_on_error(mstate m) { + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallmap = m->treemap = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for (i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); +} +#endif /* PROCEED_ON_ERROR */ + +/* Allocate chunk and prepend remainder with chunk in successor base. */ +static void* prepend_alloc(mstate m, char* newbase, char* oldbase, + size_t nb) { + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char*)oldfirst - (char*)p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char*)oldfirst > (char*)q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if (oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } + else if (oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } + else { + if (!is_inuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); + } + + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); +} + +/* Add a segment to hold a new noncontiguous region */ +static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { + /* Determine locations and sizes of segment, fenceposts, old top */ + char* old_top = (char*)m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char* old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char* asp = rawsp + offset; + char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; + mchunkptr sp = (mchunkptr)csp; + msegmentptr ss = (msegmentptr)(chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmapped; + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for (;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if ((char*)(&(nextp->head)) < old_end) + p = nextp; + else + break; + } + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if (csp != old_top) { + mchunkptr q = (mchunkptr)old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } + + check_top_chunk(m, m->top); +} + +/* -------------------------- System allocation -------------------------- */ + +/* Get memory from system using MORECORE or MMAP */ +static void* sys_alloc(mstate m, size_t nb) { + char* tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; + size_t asize; /* allocation size */ + + ensure_initialization(); + + /* Directly map large chunks, but only if already initialized */ + if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) { + void* mem = mmap_alloc(m, nb); + if (mem != 0) + return mem; + } + + asize = granularity_align(nb + SYS_ALLOC_PADDING); + if (asize <= nb) + return 0; /* wraparound */ + if (m->footprint_limit != 0) { + size_t fp = m->footprint + asize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + + /* + Try getting memory in any of three ways (in most-preferred to + least-preferred order): + 1. A call to MORECORE that can normally contiguously extend memory. + (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or + or main space is mmapped or a previous contiguous call failed) + 2. A call to MMAP new space (disabled if not HAVE_MMAP). + Note that under the default settings, if MORECORE is unable to + fulfill a request, and HAVE_MMAP is true, then mmap is + used as a noncontiguous system allocator. This is a useful backup + strategy for systems with holes in address spaces -- in this case + sbrk cannot contiguously expand the heap, but mmap may be able to + find space. + 3. A call to MORECORE that cannot usually contiguously extend memory. + (disabled if not HAVE_MORECORE) + + In all cases, we need to request enough bytes from system to ensure + we can malloc nb bytes upon success, so pad with enough space for + top_foot, plus alignment-pad to make sure we don't lose bytes if + not on boundary, and round this up to a granularity unit. + */ + + if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char* br = CMFAIL; + size_t ssize = asize; /* sbrk call size */ + msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); + ACQUIRE_MALLOC_GLOBAL_LOCK(); + + if (ss == 0) { /* First time through or recovery */ + char* base = (char*)CALL_MORECORE(0); + if (base != CMFAIL) { + size_t fp; + /* Adjust to end on a page boundary */ + if (!is_page_aligned(base)) + ssize += (page_align((size_t)base) - (size_t)base); + fp = m->footprint + ssize; /* recheck limits */ + if (ssize > nb && ssize < HALF_MAX_SIZE_T && + (m->footprint_limit == 0 || + (fp > m->footprint && fp <= m->footprint_limit)) && + (br = (char*)(CALL_MORECORE(ssize))) == base) { + tbase = base; + tsize = ssize; + } + } + } + else { + /* Subtract out existing available top space from MORECORE request. */ + ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING); + /* Use mem here only if it did continuously extend old space */ + if (ssize < HALF_MAX_SIZE_T && + (br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) { + tbase = br; + tsize = ssize; + } + } + + if (tbase == CMFAIL) { /* Cope with partial failure */ + if (br != CMFAIL) { /* Try to use/extend the space we did get */ + if (ssize < HALF_MAX_SIZE_T && + ssize < nb + SYS_ALLOC_PADDING) { + size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize); + if (esize < HALF_MAX_SIZE_T) { + char* end = (char*)CALL_MORECORE(esize); + if (end != CMFAIL) + ssize += esize; + else { /* Can't use; try to release */ + (void) CALL_MORECORE(-ssize); + br = CMFAIL; + } + } + } + } + if (br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = ssize; + } + else + disable_contiguous(m); /* Don't try contiguous path in the future */ + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + } + + if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + char* mp = (char*)(CALL_MMAP(asize)); + if (mp != CMFAIL) { + tbase = mp; + tsize = asize; + mmap_flag = USE_MMAP_BIT; + } + } + + if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + if (asize < HALF_MAX_SIZE_T) { + char* br = CMFAIL; + char* end = CMFAIL; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + br = (char*)(CALL_MORECORE(asize)); + end = (char*)(CALL_MORECORE(0)); + RELEASE_MALLOC_GLOBAL_LOCK(); + if (br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if (ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } + } + + if (tbase != CMFAIL) { + + if ((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if (!is_initialized(m)) { /* first-time initialization */ + if (m->least_addr == 0 || tbase < m->least_addr) + m->least_addr = tbase; + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmap_flag; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + init_bins(m); +#if !ONLY_MSPACES + if (is_global(m)) + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + else +#endif + { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + /* Only consider most recent segment if traversal suppressed */ + while (sp != 0 && tbase != sp->base + sp->size) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag && + segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } + else { + if (tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while (sp != 0 && sp->base != tbase + tsize) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag) { + char* oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } + else + add_segment(m, tbase, tsize, mmap_flag); + } + } + + if (nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } + } + + MALLOC_FAILURE_ACTION; + return 0; +} + +/* ----------------------- system deallocation -------------------------- */ + +/* Unmap and unlink any mmapped segments that don't contain used chunks */ +static size_t release_unused_segments(mstate m) { + size_t released = 0; + int nsegs = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + ++nsegs; + if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr)p; + assert(segment_holds(sp, (char*)sp)); + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + else { + unlink_large_chunk(m, tp); + } + if (CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } + else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } + } + if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */ + break; + pred = sp; + sp = next; + } + /* Reset check counter */ + m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)? + (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE); + return released; +} + +static int sys_trim(mstate m, size_t pad) { + size_t released = 0; + ensure_initialization(); + if (pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if (m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - + SIZE_T_ONE) * unit; + msegmentptr sp = segment_holding(m, (char*)m->top); + + if (!is_extern_segment(sp)) { + if (is_mmapped_segment(sp)) { + if (HAVE_MMAP && + sp->size >= extra && + !has_segment_link(m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + (void)newsize; /* placate people compiling -Wunused-variable */ + /* Prefer mremap, fall back to munmap */ + if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || + (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { + released = extra; + } + } + } + else if (HAVE_MORECORE) { + if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char* old_br = (char*)(CALL_MORECORE(0)); + if (old_br == sp->base + sp->size) { + char* rel_br = (char*)(CALL_MORECORE(-extra)); + char* new_br = (char*)(CALL_MORECORE(0)); + if (rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MALLOC_GLOBAL_LOCK(); + } + } + + if (released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); + } + } + + /* Unmap any unused mmapped segments */ + if (HAVE_MMAP) + released += release_unused_segments(m); + + /* On failure, disable autotrim to avoid repeated failed future calls */ + if (released == 0 && m->topsize > m->trim_check) + m->trim_check = MAX_SIZE_T; + } + + return (released != 0)? 1 : 0; +} + +/* Consolidate and bin a chunk. Differs from exported versions + of free mainly in that the chunk need not be marked as inuse. +*/ +static void dispose_chunk(mstate m, mchunkptr p, size_t psize) { + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + mchunkptr prev; + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + m->footprint -= psize; + return; + } + prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */ + if (p != m->dv) { + unlink_chunk(m, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + m->dvsize = psize; + set_free_with_pinuse(p, psize, next); + return; + } + } + else { + CORRUPTION_ERROR_ACTION(m); + return; + } + } + if (RTCHECK(ok_address(m, next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == m->top) { + size_t tsize = m->topsize += psize; + m->top = p; + p->head = tsize | PINUSE_BIT; + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + return; + } + else if (next == m->dv) { + size_t dsize = m->dvsize += psize; + m->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + return; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(m, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == m->dv) { + m->dvsize = psize; + return; + } + } + } + else { + set_free_with_pinuse(p, psize, next); + } + insert_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + } +} + +/* ---------------------------- malloc --------------------------- */ + +/* allocate a large request from the best fitting chunk in a treebin */ +static void* tmalloc_large(mstate m, size_t nb) { + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + if ((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for (;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + v = t; + if ((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + if (rt != 0 && rt != t) + rst = rt; + if (t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } + } + if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if (leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } + } + + while (t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); + } + + /* If dv is a better fit, return 0 so malloc will use it */ + if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { + if (RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } + } + CORRUPTION_ERROR_ACTION(m); + } + return 0; +} + +/* allocate a small request from the best fitting chunk in a treebin */ +static void* tmalloc_small(mstate m, size_t nb) { + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while ((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + } + + if (RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } + } + + CORRUPTION_ERROR_ACTION(m); + return 0; +} + +#if !ONLY_MSPACES + +void* dlmalloc(size_t bytes) { + /* + Basic algorithm: + If a small request (< 256 bytes minus per-chunk overhead): + 1. If one exists, use a remainderless chunk in associated smallbin. + (Remainderless means that there are too few excess bytes to + represent as a chunk.) + 2. If it is big enough, use the dv chunk, which is normally the + chunk adjacent to the one used for the most recent small request. + 3. If one exists, split the smallest available chunk in a bin, + saving remainder in dv. + 4. If it is big enough, use the top chunk. + 5. If available, get memory from system and use it + Otherwise, for a large request: + 1. Find the smallest available binned chunk that fits, and use it + if it is better fitting than dv chunk, splitting if necessary. + 2. If better fitting than any binned chunk, use the dv chunk. + 3. If it is big enough, use the top chunk. + 4. If request size >= mmap threshold, try to directly mmap this chunk. + 5. If available, get memory from system and use it + + The ugly goto's here ensure that postaction occurs along all paths. + */ + +#if USE_LOCKS + ensure_initialization(); /* initialize in sys_alloc if not using locks */ +#endif + + if (!PREACTION(gm)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb > gm->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + + if (nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } + else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + mem = sys_alloc(gm, nb); + + postaction: + POSTACTION(gm); + return mem; + } + + return 0; +} + +/* ---------------------------- free --------------------------- */ + +void dlfree(void* mem) { + /* + Consolidate freed chunks with preceeding or succeeding bordering + free chunks, if they exist, and then place in a bin. Intermixed + with special cases for top, dv, mmapped chunks, and usage errors. + */ + + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } +#else /* FOOTERS */ +#define fm gm +#endif /* FOOTERS */ + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +#if !FOOTERS +#undef fm +#endif /* FOOTERS */ +} + +void* dlcalloc(size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +#endif /* !ONLY_MSPACES */ + +/* ------------ Internal support for realloc, memalign, etc -------------- */ + +/* Try to realloc; only in-place unless can_move true */ +static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb, + int can_move) { + mchunkptr newp = 0; + size_t oldsize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, oldsize); + if (RTCHECK(ok_address(m, p) && ok_inuse(p) && + ok_next(p, next) && ok_pinuse(next))) { + if (is_mmapped(p)) { + newp = mmap_resize(m, p, nb, can_move); + } + else if (oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + else if (next == m->top) { /* extend into top */ + if (oldsize + m->topsize > nb) { + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + newtop->head = newtopsize |PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = p; + } + } + else if (next == m->dv) { /* extend into dv */ + size_t dvs = m->dvsize; + if (oldsize + dvs >= nb) { + size_t dsize = oldsize + dvs - nb; + if (dsize >= MIN_CHUNK_SIZE) { + mchunkptr r = chunk_plus_offset(p, nb); + mchunkptr n = chunk_plus_offset(r, dsize); + set_inuse(m, p, nb); + set_size_and_pinuse_of_free_chunk(r, dsize); + clear_pinuse(n); + m->dvsize = dsize; + m->dv = r; + } + else { /* exhaust dv */ + size_t newsize = oldsize + dvs; + set_inuse(m, p, newsize); + m->dvsize = 0; + m->dv = 0; + } + newp = p; + } + } + else if (!cinuse(next)) { /* extend into next free chunk */ + size_t nextsize = chunksize(next); + if (oldsize + nextsize >= nb) { + size_t rsize = oldsize + nextsize - nb; + unlink_chunk(m, next, nextsize); + if (rsize < MIN_CHUNK_SIZE) { + size_t newsize = oldsize + nextsize; + set_inuse(m, p, newsize); + } + else { + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + } + } + else { + USAGE_ERROR_ACTION(m, chunk2mem(p)); + } + return newp; +} + +static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while (a < alignment) a <<= 1; + alignment = a; + } + if (bytes >= MAX_REQUEST - alignment) { + if (m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; + } + } + else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + mem = internal_malloc(m, req); + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (PREACTION(m)) + return 0; + if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */ + /* + Find an aligned spot inside chunk. Since we need to give + back leading space in a chunk of at least MIN_CHUNK_SIZE, if + the first calculation places us at a spot with less than + MIN_CHUNK_SIZE leader, we can move to the next aligned spot. + We've allocated enough total room so that this is always + possible. + */ + char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment - + SIZE_T_ONE)) & + -alignment)); + char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? + br : br+alignment; + mchunkptr newp = (mchunkptr)pos; + size_t leadsize = pos - (char*)(p); + size_t newsize = chunksize(p) - leadsize; + + if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = newsize; + } + else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + dispose_chunk(m, p, leadsize); + } + p = newp; + } + + /* Give back spare room at the end */ + if (!is_mmapped(p)) { + size_t size = chunksize(p); + if (size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + dispose_chunk(m, remainder, remainder_size); + } + } + + mem = chunk2mem(p); + assert (chunksize(p) >= nb); + assert(((size_t)mem & (alignment - 1)) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + } + } + return mem; +} + +/* + Common support for independent_X routines, handling + all of the combinations that can result. + The opts arg has: + bit 0 set if all elements are same size (using sizes[0]) + bit 1 set if elements should be zeroed +*/ +static void** ialloc(mstate m, + size_t n_elements, + size_t* sizes, + int opts, + void* chunks[]) { + + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void** marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + ensure_initialization(); + /* compute array length, if needed */ + if (chunks != 0) { + if (n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } + else { + /* if empty req, must still return chunk representing empty array */ + if (n_elements == 0) + return (void**)internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void*))); + } + + /* compute total element size */ + if (opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } + else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for (i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } + + size = contents_size + array_size; + + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if (was_enabled) + enable_mmap(m); + if (mem == 0) + return 0; + + if (PREACTION(m)) return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if (opts & 0x2) { /* optionally clear the elements */ + memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } + + /* If not provided, allocate the pointer array as final part of chunk */ + if (marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void**) (chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; + } + + /* split out elements */ + for (i = 0; ; ++i) { + marray[i] = chunk2mem(p); + if (i != n_elements-1) { + if (element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } + else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } + } + +#if DEBUG + if (marray != chunks) { + /* final element must have exactly exhausted chunk */ + if (element_size != 0) { + assert(remainder_size == element_size); + } + else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); + } + for (i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); + +#endif /* DEBUG */ + + POSTACTION(m); + return marray; +} + +/* Try to free all pointers in the given array. + Note: this could be made faster, by delaying consolidation, + at the price of disabling some user integrity checks, We + still optimize some consolidations by combining adjacent + chunks before freeing, which will occur often if allocated + with ialloc or the array is sorted. +*/ +static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) { + size_t unfreed = 0; + if (!PREACTION(m)) { + void** a; + void** fence = &(array[nelem]); + for (a = array; a != fence; ++a) { + void* mem = *a; + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t psize = chunksize(p); +#if FOOTERS + if (get_mstate_for(p) != m) { + ++unfreed; + continue; + } +#endif + check_inuse_chunk(m, p); + *a = 0; + if (RTCHECK(ok_address(m, p) && ok_inuse(p))) { + void ** b = a + 1; /* try to merge with next chunk */ + mchunkptr next = next_chunk(p); + if (b != fence && *b == chunk2mem(next)) { + size_t newsize = chunksize(next) + psize; + set_inuse(m, p, newsize); + *b = chunk2mem(p); + } + else + dispose_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + break; + } + } + } + if (should_trim(m, m->topsize)) + sys_trim(m, 0); + POSTACTION(m); + } + return unfreed; +} + +/* Traversal */ +#if MALLOC_INSPECT_ALL +static void internal_inspect_all(mstate m, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + if (is_initialized(m)) { + mchunkptr top = m->top; + msegmentptr s; + for (s = &m->seg; s != 0; s = s->next) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) { + mchunkptr next = next_chunk(q); + size_t sz = chunksize(q); + size_t used; + void* start; + if (is_inuse(q)) { + used = sz - CHUNK_OVERHEAD; /* must not be mmapped */ + start = chunk2mem(q); + } + else { + used = 0; + if (is_small(sz)) { /* offset by possible bookkeeping */ + start = (void*)((char*)q + sizeof(struct malloc_chunk)); + } + else { + start = (void*)((char*)q + sizeof(struct malloc_tree_chunk)); + } + } + if (start < (void*)next) /* skip if all space is bookkeeping */ + handler(start, next, used, arg); + if (q == top) + break; + q = next; + } + } + } +} +#endif /* MALLOC_INSPECT_ALL */ + +/* ------------------ Exported realloc, memalign, etc -------------------- */ + +#if !ONLY_MSPACES + +void* dlrealloc(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = dlmalloc(bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + dlfree(oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = internal_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + internal_free(m, oldmem); + } + } + } + } + return mem; +} + +void* dlrealloc_in_place(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* dlmemalign(size_t alignment, size_t bytes) { + if (alignment <= MALLOC_ALIGNMENT) { + return dlmalloc(bytes); + } + return internal_memalign(gm, alignment, bytes); +} + +int dlposix_memalign(void** pp, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment == MALLOC_ALIGNMENT) + mem = dlmalloc(bytes); + else { + size_t d = alignment / sizeof(void*); + size_t r = alignment % sizeof(void*); + if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0) + return EINVAL; + else if (bytes <= MAX_REQUEST - alignment) { + if (alignment < MIN_CHUNK_SIZE) + alignment = MIN_CHUNK_SIZE; + mem = internal_memalign(gm, alignment, bytes); + } + } + if (mem == 0) + return ENOMEM; + else { + *pp = mem; + return 0; + } +} + +void* dlvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); +} + +void* dlpvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +} + +void** dlindependent_calloc(size_t n_elements, size_t elem_size, + void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); +} + +void** dlindependent_comalloc(size_t n_elements, size_t sizes[], + void* chunks[]) { + return ialloc(gm, n_elements, sizes, 0, chunks); +} + +size_t dlbulk_free(void* array[], size_t nelem) { + return internal_bulk_free(gm, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void dlmalloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + ensure_initialization(); + if (!PREACTION(gm)) { + internal_inspect_all(gm, handler, arg); + POSTACTION(gm); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int dlmalloc_trim(size_t pad) { + int result = 0; + ensure_initialization(); + if (!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; +} + +size_t dlmalloc_footprint(void) { + return gm->footprint; +} + +size_t dlmalloc_max_footprint(void) { + return gm->max_footprint; +} + +size_t dlmalloc_footprint_limit(void) { + size_t maf = gm->footprint_limit; + return maf == 0 ? MAX_SIZE_T : maf; +} + +size_t dlmalloc_set_footprint_limit(size_t bytes) { + ensure_initialization(); + size_t result; /* invert sense of 0 */ + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + return gm->footprint_limit = result; +} + +#if !NO_MALLINFO +struct mallinfo dlmallinfo(void) { + return internal_mallinfo(gm); +} +#endif /* NO_MALLINFO */ + +#if !NO_MALLOC_STATS +void dlmalloc_stats() { + internal_malloc_stats(gm); +} +#endif /* NO_MALLOC_STATS */ + +int dlmallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +size_t dlmalloc_usable_size(void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +#endif /* !ONLY_MSPACES */ + +/* ----------------------------- user mspaces ---------------------------- */ + +#if MSPACES + +static mstate init_user_mstate(char* tbase, size_t tsize) { + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate)(chunk2mem(msp)); + memset(m, 0, msize); + (void)INITIAL_LOCK(&m->mutex); + msp->head = (msize|INUSE_BITS); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + m->mflags = mparams.default_mflags; + m->extp = 0; + m->exts = 0; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; +} + +mspace create_mspace(size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0)? mparams.granularity : + (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char* tbase = (char*)(CALL_MMAP(tsize)); + if (tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + m->seg.sflags = USE_MMAP_BIT; + set_lock(m, locked); + } + } + return (mspace)m; +} + +mspace create_mspace_with_base(void* base, size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity > msize + TOP_FOOT_SIZE && + capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + m = init_user_mstate((char*)base, capacity); + m->seg.sflags = EXTERN_BIT; + set_lock(m, locked); + } + return (mspace)m; +} + +int mspace_track_large_chunks(mspace msp, int enable) { + int ret = 0; + mstate ms = (mstate)msp; + if (!PREACTION(ms)) { + if (!use_mmap(ms)) { + ret = 1; + } + if (!enable) { + enable_mmap(ms); + } else { + disable_mmap(ms); + } + POSTACTION(ms); + } + return ret; +} + +size_t destroy_mspace(mspace msp) { + size_t freed = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + msegmentptr sp = &ms->seg; + (void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */ + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + flag_t flag = sp->sflags; + (void)base; /* placate people compiling -Wunused-variable */ + sp = sp->next; + if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) && + CALL_MUNMAP(base, size) == 0) + freed += size; + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return freed; +} + +/* + mspace versions of routines are near-clones of the global + versions. This is not so nice but better than the alternatives. +*/ + +void* mspace_malloc(mspace msp, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (!PREACTION(ms)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } + else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + mem = sys_alloc(ms, nb); + + postaction: + POSTACTION(ms); + return mem; + } + + return 0; +} + +void mspace_free(mspace msp, void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + (void)msp; /* placate people compiling -Wunused */ +#else /* FOOTERS */ + mstate fm = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +} + +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = mspace_malloc(msp, bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + mspace_free(msp, oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = mspace_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + mspace_free(m, oldmem); + } + } + } + } + return mem; +} + +void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + (void)msp; /* placate people compiling -Wunused */ + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (alignment <= MALLOC_ALIGNMENT) + return mspace_malloc(msp, bytes); + return internal_memalign(ms, alignment, bytes); +} + +void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); +} + +void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); +} + +size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) { + return internal_bulk_free((mstate)msp, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void mspace_inspect_all(mspace msp, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + internal_inspect_all(ms, handler, arg); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int mspace_trim(mspace msp, size_t pad) { + int result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLOC_STATS +void mspace_malloc_stats(mspace msp) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + internal_malloc_stats(ms); + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* NO_MALLOC_STATS */ + +size_t mspace_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_max_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->max_footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_footprint_limit(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + size_t maf = ms->footprint_limit; + result = (maf == 0) ? MAX_SIZE_T : maf; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_set_footprint_limit(mspace msp, size_t bytes) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + ms->footprint_limit = result; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLINFO +struct mallinfo mspace_mallinfo(mspace msp) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + return internal_mallinfo(ms); +} +#endif /* NO_MALLINFO */ + +size_t mspace_usable_size(const void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +int mspace_mallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +#endif /* MSPACES */ + + +/* -------------------- Alternative MORECORE functions ------------------- */ + +/* + Guidelines for creating a custom version of MORECORE: + + * For best performance, MORECORE should allocate in multiples of pagesize. + * MORECORE may allocate more memory than requested. (Or even less, + but this will usually result in a malloc failure.) + * MORECORE must not allocate memory when given argument zero, but + instead return one past the end address of memory from previous + nonzero call. + * For best performance, consecutive calls to MORECORE with positive + arguments should return increasing addresses, indicating that + space has been contiguously extended. + * Even though consecutive calls to MORECORE need not return contiguous + addresses, it must be OK for malloc'ed chunks to span multiple + regions in those cases where they do happen to be contiguous. + * MORECORE need not handle negative arguments -- it may instead + just return MFAIL when given negative arguments. + Negative arguments are always multiples of pagesize. MORECORE + must not misinterpret negative args as large positive unsigned + args. You can suppress all such calls from even occurring by defining + MORECORE_CANNOT_TRIM, + + As an example alternative MORECORE, here is a custom allocator + kindly contributed for pre-OSX macOS. It uses virtually but not + necessarily physically contiguous non-paged memory (locked in, + present and won't get swapped out). You can use it by uncommenting + this section, adding some #includes, and setting up the appropriate + defines above: + + #define MORECORE osMoreCore + + There is also a shutdown routine that should somehow be called for + cleanup upon program exit. + + #define MAX_POOL_ENTRIES 100 + #define MINIMUM_MORECORE_SIZE (64 * 1024U) + static int next_os_pool; + void *our_os_pools[MAX_POOL_ENTRIES]; + + void *osMoreCore(int size) + { + void *ptr = 0; + static void *sbrk_top = 0; + + if (size > 0) + { + if (size < MINIMUM_MORECORE_SIZE) + size = MINIMUM_MORECORE_SIZE; + if (CurrentExecutionLevel() == kTaskLevel) + ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); + if (ptr == 0) + { + return (void *) MFAIL; + } + // save ptrs so they can be freed during cleanup + our_os_pools[next_os_pool] = ptr; + next_os_pool++; + ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); + sbrk_top = (char *) ptr + size; + return ptr; + } + else if (size < 0) + { + // we don't currently support shrink behavior + return (void *) MFAIL; + } + else + { + return sbrk_top; + } + } + + // cleanup any allocated memory pools + // called as last thing before shutting down driver + + void osCleanupMem(void) + { + void **ptr; + + for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) + if (*ptr) + { + PoolDeallocate(*ptr); + *ptr = 0; + } + } + +*/ + + +/* ----------------------------------------------------------------------- +History: + v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + * fix bad comparison in dlposix_memalign + * don't reuse adjusted asize in sys_alloc + * add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion + * reduce compiler warnings -- thanks to all who reported/suggested these + + v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee) + * Always perform unlink checks unless INSECURE + * Add posix_memalign. + * Improve realloc to expand in more cases; expose realloc_in_place. + Thanks to Peter Buhr for the suggestion. + * Add footprint_limit, inspect_all, bulk_free. Thanks + to Barry Hayes and others for the suggestions. + * Internal refactorings to avoid calls while holding locks + * Use non-reentrant locks by default. Thanks to Roland McGrath + for the suggestion. + * Small fixes to mspace_destroy, reset_on_error. + * Various configuration extensions/changes. Thanks + to all who contributed these. + + V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu) + * Update Creative Commons URL + + V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) + * Use zeros instead of prev foot for is_mmapped + * Add mspace_track_large_chunks; thanks to Jean Brouwers + * Fix set_inuse in internal_realloc; thanks to Jean Brouwers + * Fix insufficient sys_alloc padding when using 16byte alignment + * Fix bad error check in mspace_footprint + * Adaptations for ptmalloc; thanks to Wolfram Gloger. + * Reentrant spin locks; thanks to Earl Chew and others + * Win32 improvements; thanks to Niall Douglas and Earl Chew + * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options + * Extension hook in malloc_state + * Various small adjustments to reduce warnings on some compilers + * Various configuration extensions/changes for more platforms. Thanks + to all who contributed these. + + V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee) + * Add max_footprint functions + * Ensure all appropriate literals are size_t + * Fix conditional compilation problem for some #define settings + * Avoid concatenating segments with the one provided + in create_mspace_with_base + * Rename some variables to avoid compiler shadowing warnings + * Use explicit lock initialization. + * Better handling of sbrk interference. + * Simplify and fix segment insertion, trimming and mspace_destroy + * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x + * Thanks especially to Dennis Flanagan for help on these. + + V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee) + * Fix memalign brace error. + + V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee) + * Fix improper #endif nesting in C++ + * Add explicit casts needed for C++ + + V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee) + * Use trees for large bins + * Support mspaces + * Use segments to unify sbrk-based and mmap-based system allocation, + removing need for emulation on most platforms without sbrk. + * Default safety checks + * Optional footer checks. Thanks to William Robertson for the idea. + * Internal code refactoring + * Incorporate suggestions and platform-specific changes. + Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas, + Aaron Bachmann, Emery Berger, and others. + * Speed up non-fastbin processing enough to remove fastbins. + * Remove useless cfree() to avoid conflicts with other apps. + * Remove internal memcpy, memset. Compilers handle builtins better. + * Remove some options that no one ever used and rename others. + + V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee) + * Fix malloc_state bitmap array misdeclaration + + V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee) + * Allow tuning of FIRST_SORTED_BIN_SIZE + * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte. + * Better detection and support for non-contiguousness of MORECORE. + Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger + * Bypass most of malloc if no frees. Thanks To Emery Berger. + * Fix freeing of old top non-contiguous chunk im sysmalloc. + * Raised default trim and map thresholds to 256K. + * Fix mmap-related #defines. Thanks to Lubos Lunak. + * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield. + * Branch-free bin calculation + * Default trim and mmap thresholds now 256K. + + V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) + * Introduce independent_comalloc and independent_calloc. + Thanks to Michael Pachos for motivation and help. + * Make optional .h file available + * Allow > 2GB requests on 32bit systems. + * new WIN32 sbrk, mmap, munmap, lock code from . + Thanks also to Andreas Mueller , + and Anonymous. + * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for + helping test this.) + * memalign: check alignment arg + * realloc: don't try to shift chunks backwards, since this + leads to more fragmentation in some programs and doesn't + seem to help in any others. + * Collect all cases in malloc requiring system memory into sysmalloc + * Use mmap as backup to sbrk + * Place all internal state in malloc_state + * Introduce fastbins (although similar to 2.5.1) + * Many minor tunings and cosmetic improvements + * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK + * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS + Thanks to Tony E. Bennett and others. + * Include errno.h to support default failure action. + + V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) + * return null for negative arguments + * Added Several WIN32 cleanups from Martin C. Fong + * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' + (e.g. WIN32 platforms) + * Cleanup header file inclusion for WIN32 platforms + * Cleanup code to avoid Microsoft Visual C++ compiler complaints + * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing + memory allocation routines + * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) + * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to + usage of 'assert' in non-WIN32 code + * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to + avoid infinite loop + * Always call 'fREe()' rather than 'free()' + + V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) + * Fixed ordering problem with boundary-stamping + + V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) + * Added pvalloc, as recommended by H.J. Liu + * Added 64bit pointer support mainly from Wolfram Gloger + * Added anonymously donated WIN32 sbrk emulation + * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen + * malloc_extend_top: fix mask error that caused wastage after + foreign sbrks + * Add linux mremap support code from HJ Liu + + V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) + * Integrated most documentation with the code. + * Add support for mmap, with help from + Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Use last_remainder in more cases. + * Pack bins using idea from colin@nyx10.cs.du.edu + * Use ordered bins instead of best-fit threshhold + * Eliminate block-local decls to simplify tracing and debugging. + * Support another case of realloc via move into top + * Fix error occuring when initial sbrk_base not word-aligned. + * Rely on page size for units instead of SBRK_UNIT to + avoid surprises about sbrk alignment conventions. + * Add mallinfo, mallopt. Thanks to Raymond Nijssen + (raymond@es.ele.tue.nl) for the suggestion. + * Add `pad' argument to malloc_trim and top_pad mallopt parameter. + * More precautions for cases where other routines call sbrk, + courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Added macros etc., allowing use in linux libc from + H.J. Lu (hjl@gnu.ai.mit.edu) + * Inverted this history list + + V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) + * Re-tuned and fixed to behave more nicely with V2.6.0 changes. + * Removed all preallocation code since under current scheme + the work required to undo bad preallocations exceeds + the work saved in good cases for most test programs. + * No longer use return list or unconsolidated bins since + no scheme using them consistently outperforms those that don't + given above changes. + * Use best fit for very large chunks to prevent some worst-cases. + * Added some support for debugging + + V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) + * Removed footers when chunks are in use. Thanks to + Paul Wilson (wilson@cs.texas.edu) for the suggestion. + + V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) + * Added malloc_trim, with help from Wolfram Gloger + (wmglo@Dent.MED.Uni-Muenchen.DE). + + V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) + + V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) + * realloc: try to expand in both directions + * malloc: swap order of clean-bin strategy; + * realloc: only conditionally expand backwards + * Try not to scavenge used bins + * Use bin counts as a guide to preallocation + * Occasionally bin return list chunks in first scan + * Add a few optimizations from colin@nyx10.cs.du.edu + + V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) + * faster bin computation & slightly different binning + * merged all consolidations to one part of malloc proper + (eliminating old malloc_find_space & malloc_clean_bin) + * Scan 2 returns chunks (not just 1) + * Propagate failure in realloc if malloc returns 0 + * Add stuff to allow compilation on non-ANSI compilers + from kpv@research.att.com + + V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) + * removed potential for odd address access in prev_chunk + * removed dependency on getpagesize.h + * misc cosmetics and a bit more internal documentation + * anticosmetics: mangled names in macros to evade debugger strangeness + * tested on sparc, hp-700, dec-mips, rs6000 + with gcc & native cc (hp, dec only) allowing + Detlefs & Zorn comparison study (in SIGPLAN Notices.) + + Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) + * Based loosely on libg++-1.2X malloc. (It retains some of the overall + structure of old version, but most details differ.) + +*/ diff --git a/src/ray/test/run_object_manager_tests.sh b/src/ray/test/run_object_manager_tests.sh index a739f6eee..b6b0730bd 100755 --- a/src/ray/test/run_object_manager_tests.sh +++ b/src/ray/test/run_object_manager_tests.sh @@ -6,7 +6,7 @@ set -e set -x -bazel build "//:object_manager_stress_test" "//:object_manager_test" "@plasma//:plasma_store_server" +bazel build "//:object_manager_stress_test" "//:object_manager_test" "//:plasma_store_server" # Get the directory in which this script is executing. SCRIPT_DIR="`dirname \"$0\"`" @@ -24,7 +24,7 @@ fi REDIS_MODULE="./bazel-bin/libray_redis_module.so" LOAD_MODULE_ARGS="--loadmodule ${REDIS_MODULE}" -STORE_EXEC="./bazel-bin/external/plasma/plasma_store_server" +STORE_EXEC="./bazel-bin/plasma_store_server" # Allow cleanup commands to fail. bazel run //:redis-cli -- -p 6379 shutdown || true diff --git a/src/ray/test/run_object_manager_valgrind.sh b/src/ray/test/run_object_manager_valgrind.sh index 1fcdb77f3..32c6e8340 100755 --- a/src/ray/test/run_object_manager_valgrind.sh +++ b/src/ray/test/run_object_manager_valgrind.sh @@ -6,7 +6,7 @@ set -e set -x -bazel build "//:object_manager_stress_test" "//:object_manager_test" "@plasma//:plasma_store_server" +bazel build "//:object_manager_stress_test" "//:object_manager_test" "//:plasma_store_server" # Get the directory in which this script is executing. SCRIPT_DIR="`dirname \"$0\"`" @@ -24,7 +24,7 @@ fi REDIS_MODULE="./bazel-bin/libray_redis_module.so" LOAD_MODULE_ARGS="--loadmodule ${REDIS_MODULE}" -STORE_EXEC="./bazel-bin/external/plasma/plasma_store_server" +STORE_EXEC="./bazel-bin/plasma_store_server" VALGRIND_CMD="valgrind --track-origins=yes --leak-check=full --show-leak-kinds=all --leak-check-heuristics=stdstring --error-exitcode=1" diff --git a/streaming/src/test/run_streaming_queue_test.sh b/streaming/src/test/run_streaming_queue_test.sh index a8da1863a..0187f2a26 100755 --- a/streaming/src/test/run_streaming_queue_test.sh +++ b/streaming/src/test/run_streaming_queue_test.sh @@ -35,7 +35,7 @@ if [ -z "$RAY_ROOT" ] ; then exit 1 fi -bazel build "//:core_worker_test" "//:mock_worker" "//:raylet" "//:gcs_server" "//:libray_redis_module.so" "@plasma//:plasma_store_server" "//:redis-server" "//:redis-cli" +bazel build "//:core_worker_test" "//:mock_worker" "//:raylet" "//:gcs_server" "//:libray_redis_module.so" "//:plasma_store_server" "//:redis-server" "//:redis-cli" bazel build //streaming:streaming_test_worker bazel build //streaming:streaming_queue_tests @@ -47,7 +47,7 @@ fi REDIS_MODULE="./bazel-bin/libray_redis_module.so" REDIS_SERVER_EXEC="./bazel-bin/redis-server" -STORE_EXEC="./bazel-bin/external/plasma/plasma_store_server" +STORE_EXEC="./bazel-bin/plasma_store_server" REDIS_CLIENT_EXEC="./bazel-bin/redis-cli" RAYLET_EXEC="./bazel-bin/raylet" STREAMING_TEST_WORKER_EXEC="./bazel-bin/streaming/streaming_test_worker" diff --git a/thirdparty/patches/arrow-headers-unused.patch b/thirdparty/patches/arrow-headers-unused.patch deleted file mode 100644 index 8653ed863..000000000 --- a/thirdparty/patches/arrow-headers-unused.patch +++ /dev/null @@ -1,14 +0,0 @@ -diff --git cpp/src/plasma/client.cc cpp/src/plasma/client.cc ---- cpp/src/plasma/client.cc -+++ cpp/src/plasma/client.cc -@@ -22,4 +22,0 @@ --#ifdef _WIN32 --#include --#endif -- -diff --git cpp/src/plasma/plasma.h cpp/src/plasma/plasma.h ---- cpp/src/plasma/plasma.h -+++ cpp/src/plasma/plasma.h -@@ -28,1 +28,0 @@ --#include // pid_t --- diff --git a/thirdparty/patches/arrow-windows-dlmalloc.patch b/thirdparty/patches/arrow-windows-dlmalloc.patch deleted file mode 100644 index ed4e07bde..000000000 --- a/thirdparty/patches/arrow-windows-dlmalloc.patch +++ /dev/null @@ -1,57 +0,0 @@ -diff --git cpp/src/plasma/malloc.cc cpp/src/plasma/malloc.cc ---- cpp/src/plasma/malloc.cc -+++ cpp/src/plasma/malloc.cc -@@ -26,2 +26,0 @@ --#include --#include -diff --git cpp/src/plasma/dlmalloc.cc cpp/src/plasma/dlmalloc.cc ---- cpp/src/plasma/dlmalloc.cc -+++ cpp/src/plasma/dlmalloc.cc -@@ -25,2 +25,6 @@ -+#ifdef _WIN32 -+#include -+#else - #include - #include -+#endif -@@ -76,5 +80,8 @@ int create_buffer(int64_t size) { -- if (!CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, -- (DWORD)((uint64_t)size >> (CHAR_BIT * sizeof(DWORD))), -- (DWORD)(uint64_t)size, NULL)) { -+ HANDLE h = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, -+ (DWORD)((uint64_t)size >> (CHAR_BIT * sizeof(DWORD))), -+ (DWORD)(uint64_t)size, NULL); -+ if (h) { -+ fd = fh_open(reinterpret_cast(h), -1); -+ } else { - fd = -1; - } -@@ -119,9 +126,18 @@ -+ void* pointer; -+#ifdef _WIN32 -+ pointer = MapViewOfFile(reinterpret_cast(fh_get(fd)), FILE_MAP_ALL_ACCESS, 0, 0, size); -+ if (pointer == NULL) { -+ ARROW_LOG(ERROR) << "MapViewOfFile failed with error: " << GetLastError(); -+ return reinterpret_cast(-1); -+ } -+#else -- void* pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); -+ pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (pointer == MAP_FAILED) { - ARROW_LOG(ERROR) << "mmap failed with error: " << std::strerror(errno); - if (errno == ENOMEM && plasma_config->hugepages_enabled) { - ARROW_LOG(ERROR) - << " (this probably means you have to increase /proc/sys/vm/nr_hugepages)"; - } - return pointer; - } -+#endif -@@ -155,1 +169,6 @@ -+ int r; -+#ifdef _WIN32 -+ r = UnmapViewOfFile(addr) ? 0 : -1; -+#else -- int r = munmap(addr, size); -+ r = munmap(addr, size); -+#endif --- diff --git a/thirdparty/patches/arrow-windows-nonstdc.patch b/thirdparty/patches/arrow-windows-nonstdc.patch index 8ad88ed3c..6fd59ad55 100644 --- a/thirdparty/patches/arrow-windows-nonstdc.patch +++ b/thirdparty/patches/arrow-windows-nonstdc.patch @@ -5,13 +5,4 @@ diff --git cpp/src/arrow/io/mman.h cpp/src/arrow/io/mman.h +#ifdef _WIN32 +typedef long long off_t; +#endif -diff --git cpp/src/plasma/protocol.cc cpp/src/plasma/protocol.cc ---- cpp/src/plasma/protocol.cc -+++ cpp/src/plasma/protocol.cc -@@ -760,1 +760,5 @@ -+#ifdef _WIN32 -+ *address = _strdup(message->address()->c_str()); -+#else - *address = strdup(message->address()->c_str()); -+#endif -- diff --git a/thirdparty/patches/arrow-windows-sigpipe.patch b/thirdparty/patches/arrow-windows-sigpipe.patch deleted file mode 100644 index 1931716ed..000000000 --- a/thirdparty/patches/arrow-windows-sigpipe.patch +++ /dev/null @@ -1,10 +0,0 @@ -diff --git cpp/src/plasma/store.cc cpp/src/plasma/store.cc ---- cpp/src/plasma/store.cc -+++ cpp/src/plasma/store.cc -@@ -1185,3 +1185,5 @@ void StartServer(char* socket_name, std::string plasma_directory, bool hugepages_enabled, -+#ifndef _WIN32 // TODO(mehrdadn): Is there an equivalent of this we need for Windows? - // Ignore SIGPIPE signals. If we don't do this, then when we attempt to write - // to a client that has already died, the store could die. - signal(SIGPIPE, SIG_IGN); -+#endif --- diff --git a/thirdparty/patches/arrow-windows-socket.patch b/thirdparty/patches/arrow-windows-socket.patch deleted file mode 100644 index e0e8079ba..000000000 --- a/thirdparty/patches/arrow-windows-socket.patch +++ /dev/null @@ -1,159 +0,0 @@ -diff --git cpp/src/plasma/client.cc cpp/src/plasma/client.cc ---- cpp/src/plasma/client.cc -+++ cpp/src/plasma/client.cc -@@ -28,1 +28,5 @@ -+#ifdef _WIN32 -+#include -+#else - #include -+#endif -@@ -33,1 +37,3 @@ -+#ifndef _WIN32 - #include -+#endif -@@ -178,6 +184,14 @@ -+#ifdef _WIN32 -+ pointer_ = reinterpret_cast(MapViewOfFile(reinterpret_cast(fh_get(fd)), FILE_MAP_ALL_ACCESS, 0, 0, length_)); -+ // TODO(pcm): Don't fail here, instead return a Status. -+ if (pointer_ == NULL) { -+ ARROW_LOG(FATAL) << "mmap failed"; -+ } -+#else - pointer_ = reinterpret_cast( - mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); - // TODO(pcm): Don't fail here, instead return a Status. - if (pointer_ == MAP_FAILED) { - ARROW_LOG(FATAL) << "mmap failed"; - } -+#endif -@@ -189,1 +195,6 @@ -+ int r; -+#ifdef _WIN32 -+ r = UnmapViewOfFile(pointer_) ? 0 : -1; -+#else -- int r = munmap(pointer_, length_); -+ r = munmap(pointer_, length_); -+#endif -@@ -990,5 +1009,17 @@ -+#ifdef _WINSOCKAPI_ -+ SOCKET sockets[2] = { INVALID_SOCKET, INVALID_SOCKET }; -+ socketpair(AF_INET, SOCK_STREAM, 0, sockets); -+ sock[0] = fh_open(sockets[0], -1); -+ sock[1] = fh_open(sockets[1], -1); -+#else - socketpair(AF_UNIX, SOCK_STREAM, 0, sock); -+#endif - // Make the socket non-blocking. -+#ifdef _WINSOCKAPI_ -+ unsigned long value = 1; -+ ARROW_CHECK(ioctlsocket(sock[1], FIONBIO, &value) == 0); -+#else - int flags = fcntl(sock[1], F_GETFL, 0); - ARROW_CHECK(fcntl(sock[1], F_SETFL, flags | O_NONBLOCK) == 0); -+#endif - // Tell the Plasma store about the subscription. -diff --git cpp/src/plasma/fling.cc cpp/src/plasma/fling.cc ---- cpp/src/plasma/fling.cc -+++ cpp/src/plasma/fling.cc -@@ -19,7 +19,14 @@ - #include "arrow/util/logging.h" - -+#ifdef _WIN32 -+#include // socklen_t -+#else -+typedef int SOCKET; -+#endif -+ - void init_msg(struct msghdr* msg, struct iovec* iov, char* buf, size_t buf_len) { - iov->iov_base = buf; - iov->iov_len = 1; - -+ msg->msg_flags = 0; - msg->msg_iov = iov; -@@ -36,3 +43,8 @@ -+#ifdef _WIN32 -+ SOCKET to_send = fh_get(fd); -+#else -+ SOCKET to_send = fd; -+#endif -- char buf[CMSG_SPACE(sizeof(int))]; -+ char buf[CMSG_SPACE(sizeof(to_send))]; -- memset(&buf, 0, CMSG_SPACE(sizeof(int))); -+ memset(&buf, 0, sizeof(buf)); - -@@ -47,7 +59,12 @@ -- header->cmsg_len = CMSG_LEN(sizeof(int)); -+ header->cmsg_len = CMSG_LEN(sizeof(to_send)); -- memcpy(CMSG_DATA(header), reinterpret_cast(&fd), sizeof(int)); -+ memcpy(CMSG_DATA(header), reinterpret_cast(&to_send), sizeof(to_send)); - -+#ifdef _WIN32 -+ SOCKET sock = fh_get(conn); -+#else -+ SOCKET sock = conn; -+#endif - // Send file descriptor. - while (true) { -- ssize_t r = sendmsg(conn, &msg, 0); -+ ssize_t r = sendmsg(sock, &msg, 0); - if (r < 0) { -@@ -83,6 +100,11 @@ -- char buf[CMSG_SPACE(sizeof(int))]; -+ char buf[CMSG_SPACE(sizeof(SOCKET))]; - init_msg(&msg, &iov, buf, sizeof(buf)); - -+#ifdef _WIN32 -+ SOCKET sock = fh_get(conn); -+#else -+ int sock = conn; -+#endif - while (true) { -- ssize_t r = recvmsg(conn, &msg, 0); -+ ssize_t r = recvmsg(sock, &msg, 0); - if (r == -1) { -@@ -100,18 +122,22 @@ -- int found_fd = -1; -+ SOCKET found_fd = -1; - int oh_noes = 0; - for (struct cmsghdr* header = CMSG_FIRSTHDR(&msg); header != NULL; - header = CMSG_NXTHDR(&msg, header)) - if (header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS) { - ssize_t count = (header->cmsg_len - - (CMSG_DATA(header) - reinterpret_cast(header))) / -- sizeof(int); -+ sizeof(SOCKET); - for (int i = 0; i < count; ++i) { -- int fd = (reinterpret_cast(CMSG_DATA(header)))[i]; -+ SOCKET fd = (reinterpret_cast(CMSG_DATA(header)))[i]; - if (found_fd == -1) { - found_fd = fd; - } else { -+#ifdef _WIN32 -+ closesocket(fd) == 0 || ((WSAGetLastError() == WSAENOTSOCK || WSAGetLastError() == WSANOTINITIALISED) && CloseHandle(reinterpret_cast(fd))); -+#else - close(fd); -+#endif - oh_noes = 1; - } - } - } -@@ -122,8 +148,17 @@ - if (oh_noes) { -+#ifdef _WIN32 -+ closesocket(found_fd) == 0 || ((WSAGetLastError() == WSAENOTSOCK || WSAGetLastError() == WSANOTINITIALISED) && CloseHandle(reinterpret_cast(found_fd))); -+#else - close(found_fd); -+#endif - errno = EBADMSG; - return -1; - } - -- return found_fd; -+#ifdef _WIN32 -+ int to_receive = fh_open(found_fd, -1); -+#else -+ int to_receive = found_fd; -+#endif -+ return to_receive; - } --- diff --git a/thirdparty/patches/arrow-windows-tcp.patch b/thirdparty/patches/arrow-windows-tcp.patch deleted file mode 100644 index 98fa49c96..000000000 --- a/thirdparty/patches/arrow-windows-tcp.patch +++ /dev/null @@ -1,190 +0,0 @@ -diff --git cpp/src/plasma/io.h cpp/src/plasma/io.h ---- cpp/src/plasma/io.h -+++ cpp/src/plasma/io.h -@@ -30,2 +30,3 @@ - #include "arrow/status.h" -+#include "plasma/common.h" - #include "plasma/compat.h" -@@ -57,3 +58,1 @@ --int BindIpcSock(const std::string& pathname, bool shall_listen); -- --int ConnectIpcSock(const std::string& pathname); -+int ConnectOrListenIpcSock(const std::string& pathname, bool shall_listen); -diff --git cpp/src/plasma/store.cc cpp/src/plasma/store.cc ---- cpp/src/plasma/store.cc -+++ cpp/src/plasma/store.cc -@@ -1150,1 +1150,1 @@ -- int socket = BindIpcSock(socket_name, true); -+ int socket = ConnectOrListenIpcSock(socket_name, true); -@@ -1301,1 +1301,5 @@ -+#ifdef _WINSOCKAPI_ -+ WSADATA wsadata; -+ WSAStartup(MAKEWORD(2, 2), &wsadata); -+#endif - plasma::StartServer(socket_name, plasma_directory, hugepages_enabled, external_store); -@@ -1307,1 +1311,4 @@ -+#ifdef _WINSOCKAPI_ -+ WSACleanup(); -+#endif - return 0; -diff --git cpp/src/plasma/io.cc cpp/src/plasma/io.cc ---- cpp/src/plasma/io.cc -+++ cpp/src/plasma/io.cc -@@ -29,1 +29,5 @@ -+#ifndef _WIN32 -+#include -+#include -+#endif - -@@ -117,39 +121,79 @@ --int BindIpcSock(const std::string& pathname, bool shall_listen) { -- struct sockaddr_un socket_address; -- int socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); -+int ConnectOrListenIpcSock(const std::string& pathname, bool shall_listen) { -+ union { -+ struct sockaddr addr; -+ struct sockaddr_un un; -+ struct sockaddr_in in; -+ } socket_address; -+ int addrlen; -+ memset(&socket_address, 0, sizeof(socket_address)); -+ if (pathname.find("tcp://") == 0) { -+ addrlen = sizeof(socket_address.in); -+ socket_address.in.sin_family = AF_INET; -+ std::string addr = pathname.substr(pathname.find('/') + 2); -+ size_t i = addr.rfind(':'), j; -+ if (i >= addr.size()) { -+ j = i = addr.size(); -+ } else { -+ j = i + 1; -+ } -+ socket_address.in.sin_addr.s_addr = inet_addr(addr.substr(0, i).c_str()); -+ socket_address.in.sin_port = htons(static_cast(atoi(addr.substr(j).c_str()))); -+ if (socket_address.in.sin_addr.s_addr == INADDR_NONE) { -+ ARROW_LOG(ERROR) << "Socket address is not a valid IPv4 address: " << pathname; -+ return -1; -+ } -+ if (socket_address.in.sin_port == htons(0)) { -+ ARROW_LOG(ERROR) << "Socket address is missing a valid port: " << pathname; -+ return -1; -+ } -+ } else { -+ addrlen = sizeof(socket_address.un); -+ socket_address.un.sun_family = AF_UNIX; -+ if (pathname.size() + 1 > sizeof(socket_address.un.sun_path)) { -+ ARROW_LOG(ERROR) << "Socket pathname is too long."; -+ return -1; -+ } -+ strncpy(socket_address.un.sun_path, pathname.c_str(), pathname.size() + 1); -+ } -+ -+ int socket_fd = socket(socket_address.addr.sa_family, SOCK_STREAM, 0); - if (socket_fd < 0) { - ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; - return -1; - } -- // Tell the system to allow the port to be reused. -- int on = 1; -- if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), -- sizeof(on)) < 0) { -- ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; -- close(socket_fd); -- return -1; -- } -+ if (shall_listen) { -+ // Tell the system to allow the port to be reused. -+ int on = 1; -+ if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), -+ sizeof(on)) < 0) { -+ ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; -+ close(socket_fd); -+ return -1; -+ } - -- unlink(pathname.c_str()); -- memset(&socket_address, 0, sizeof(socket_address)); -- socket_address.sun_family = AF_UNIX; -- if (pathname.size() + 1 > sizeof(socket_address.sun_path)) { -- ARROW_LOG(ERROR) << "Socket pathname is too long."; -- close(socket_fd); -- return -1; -- } -- strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); -+ if (socket_address.addr.sa_family == AF_UNIX) { -+#ifdef _WIN32 -+ _unlink(pathname.c_str()); -+#else -+ unlink(pathname.c_str()); -+#endif -+ } -+ if (bind(socket_fd, &socket_address.addr, addrlen) != 0) { -+ ARROW_LOG(ERROR) << "Bind failed for pathname " << pathname; -+ close(socket_fd); -+ return -1; -+ } - -- if (bind(socket_fd, reinterpret_cast(&socket_address), -- sizeof(socket_address)) != 0) { -- ARROW_LOG(ERROR) << "Bind failed for pathname " << pathname; -- close(socket_fd); -- return -1; -- } -- if (shall_listen && listen(socket_fd, 128) == -1) { -- ARROW_LOG(ERROR) << "Could not listen to socket " << pathname; -- close(socket_fd); -- return -1; -+ if (listen(socket_fd, 128) == -1) { -+ ARROW_LOG(ERROR) << "Could not listen to socket " << pathname; -+ close(socket_fd); -+ return -1; -+ } -+ } else { -+ if (connect(socket_fd, &socket_address.addr, addrlen) != 0) { -+ close(socket_fd); -+ return -1; -+ } - } - return socket_fd; - } -@@ -166,9 +270,9 @@ -- *fd = ConnectIpcSock(pathname); -+ *fd = ConnectOrListenIpcSock(pathname, false); - while (*fd < 0 && num_retries > 0) { - ARROW_LOG(ERROR) << "Connection to IPC socket failed for pathname " << pathname - << ", retrying " << num_retries << " more times"; - // Sleep for timeout milliseconds. - usleep(static_cast(timeout * 1000)); -- *fd = ConnectIpcSock(pathname); -+ *fd = ConnectOrListenIpcSock(pathname, false); - --num_retries; - } -@@ -184,28 +228,0 @@ --int ConnectIpcSock(const std::string& pathname) { -- struct sockaddr_un socket_address; -- int socket_fd; -- -- socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); -- if (socket_fd < 0) { -- ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; -- return -1; -- } -- -- memset(&socket_address, 0, sizeof(socket_address)); -- socket_address.sun_family = AF_UNIX; -- if (pathname.size() + 1 > sizeof(socket_address.sun_path)) { -- ARROW_LOG(ERROR) << "Socket pathname is too long."; -- close(socket_fd); -- return -1; -- } -- strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); -- -- if (connect(socket_fd, reinterpret_cast(&socket_address), -- sizeof(socket_address)) != 0) { -- close(socket_fd); -- return -1; -- } -- -- return socket_fd; --} -- ---