| 857 | } |
| 858 | |
| 859 | int FlatContiguousStreamerEntity::build_contiguous_memory() { |
| 860 | degrade_to_mmap(); |
| 861 | |
| 862 | const size_t count = use_key_info_map() ? id_key_count() : vector_count(); |
| 863 | if (count == 0) { |
| 864 | return 0; |
| 865 | } |
| 866 | |
| 867 | const size_t vector_size = meta().element_size(); |
| 868 | const size_t stride = |
| 869 | (vector_size + kVectorAlignment - 1) & ~(kVectorAlignment - 1); |
| 870 | const size_t data_size = count * stride; |
| 871 | const size_t allocation_size = |
| 872 | ailego::MemoryHelper::AlignHugePageSize(data_size); |
| 873 | char *raw = static_cast<char *>( |
| 874 | ailego::MemoryHelper::AllocateHugePage(allocation_size)); |
| 875 | if (!raw) { |
| 876 | LOG_ERROR("Failed to allocate Flat contiguous memory, size=%zu", |
| 877 | allocation_size); |
| 878 | return IndexError_Runtime; |
| 879 | } |
| 880 | |
| 881 | auto storage = std::make_shared<ContiguousStorage>(); |
| 882 | storage->vector_memory = |
| 883 | std::shared_ptr<char>(raw, ContiguousDeleter{allocation_size}); |
| 884 | storage->vector_stride = stride; |
| 885 | storage->vector_count = count; |
| 886 | if (use_key_info_map()) { |
| 887 | storage->key_to_position.reserve(count); |
| 888 | } |
| 889 | storage->position_to_key.assign(count, static_cast<uint64_t>(kInvalidKey)); |
| 890 | |
| 891 | for (uint32_t id = 0; id < count; ++id) { |
| 892 | IndexStorage::MemoryBlock block; |
| 893 | uint64_t vector_key = kInvalidKey; |
| 894 | int ret = 0; |
| 895 | if (use_key_info_map()) { |
| 896 | vector_key = key(id); |
| 897 | ret = FlatStreamerEntity::get_vector_by_key(vector_key, block); |
| 898 | if (ret == 0) { |
| 899 | storage->key_to_position[vector_key] = id; |
| 900 | } |
| 901 | } else { |
| 902 | ret = get_vector_by_position(id, block); |
| 903 | if (ret == 0) { |
| 904 | ret = get_key_by_position(id, &vector_key); |
| 905 | } |
| 906 | } |
| 907 | if (ret != 0 || block.data() == nullptr) { |
| 908 | LOG_ERROR("Failed to load Flat vector into contiguous memory, id=%u", id); |
| 909 | return IndexError_ReadData; |
| 910 | } |
| 911 | std::memcpy(raw + static_cast<size_t>(id) * stride, block.data(), |
| 912 | vector_size); |
| 913 | storage->position_to_key[id] = vector_key; |
| 914 | } |
| 915 | |
| 916 | std::atomic_store_explicit( |