| 45 | } |
| 46 | |
| 47 | Status Suballocator::Allocate(int64_t bytes, unique_ptr<Suballocation>* result) { |
| 48 | DCHECK_GE(bytes, 0); |
| 49 | if (UNLIKELY(bytes > MAX_ALLOCATION_BYTES)) { |
| 50 | return Status(Substitute("Requested memory allocation of $0 bytes, larger than max " |
| 51 | "supported of $1 bytes", |
| 52 | bytes, MAX_ALLOCATION_BYTES)); |
| 53 | } |
| 54 | unique_ptr<Suballocation> free_node; |
| 55 | bytes = max(bytes, MIN_ALLOCATION_BYTES); |
| 56 | const int target_list_idx = ComputeListIndex(bytes); |
| 57 | for (int i = target_list_idx; i < NUM_FREE_LISTS; ++i) { |
| 58 | free_node = PopFreeListHead(i); |
| 59 | if (free_node != nullptr) break; |
| 60 | } |
| 61 | |
| 62 | if (free_node == nullptr) { |
| 63 | // Unable to find free allocation, need to get more memory from buffer pool. |
| 64 | RETURN_IF_ERROR(AllocateBuffer(bytes, &free_node)); |
| 65 | if (free_node == nullptr) { |
| 66 | *result = nullptr; |
| 67 | return Status::OK(); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Free node may be larger than required. |
| 72 | const int free_list_idx = ComputeListIndex(free_node->len_); |
| 73 | if (free_list_idx != target_list_idx) { |
| 74 | RETURN_IF_ERROR(SplitToSize(move(free_node), bytes, &free_node)); |
| 75 | DCHECK(free_node != nullptr); |
| 76 | } |
| 77 | |
| 78 | free_node->in_use_ = true; |
| 79 | allocated_ += free_node->len_; |
| 80 | *result = move(free_node); |
| 81 | return Status::OK(); |
| 82 | } |
| 83 | |
| 84 | int Suballocator::ComputeListIndex(int64_t bytes) const { |
| 85 | return BitUtil::Log2CeilingNonZero64(bytes) - LOG_MIN_ALLOCATION_BYTES; |