| 42 | } |
| 43 | |
| 44 | void MemoryBlock::Split(MetadataCache* cache, |
| 45 | size_t size, |
| 46 | size_t extra_padding_size) { |
| 47 | auto desc = cache->LoadDesc(this); |
| 48 | // make sure the split fits |
| 49 | PADDLE_ENFORCE_GE(desc->total_size, |
| 50 | size, |
| 51 | common::errors::InvalidArgument( |
| 52 | "The size of memory block (%d) to split is " |
| 53 | "not larger than size of request memory (%d)", |
| 54 | desc->total_size, |
| 55 | size)); |
| 56 | |
| 57 | size_t pay_load_size = sizeof(MemoryBlock::Desc) + extra_padding_size; |
| 58 | |
| 59 | // bail out if there is no room for another partition |
| 60 | if (desc->total_size - size <= pay_load_size) { |
| 61 | return; |
| 62 | } |
| 63 | |
| 64 | // find the position of the split |
| 65 | void* right_partition = reinterpret_cast<uint8_t*>(this) + size; |
| 66 | |
| 67 | size_t remaining_size = desc->total_size - size; |
| 68 | |
| 69 | // Add the new block as a buddy |
| 70 | // Write the metadata for the new block |
| 71 | auto new_block_right_buddy = desc->right_buddy; |
| 72 | |
| 73 | cache->Save(static_cast<MemoryBlock*>(right_partition), |
| 74 | MemoryBlock::Desc(FREE_CHUNK, |
| 75 | desc->index, |
| 76 | remaining_size - pay_load_size, |
| 77 | remaining_size, |
| 78 | this, |
| 79 | new_block_right_buddy)); |
| 80 | |
| 81 | desc->right_buddy = static_cast<MemoryBlock*>(right_partition); |
| 82 | desc->size = size - pay_load_size; |
| 83 | desc->total_size = size; |
| 84 | |
| 85 | desc->UpdateGuards(); |
| 86 | |
| 87 | // Write metadata for the new block's right buddy |
| 88 | if (new_block_right_buddy != nullptr) { |
| 89 | auto buddy_desc = cache->LoadDesc(new_block_right_buddy); |
| 90 | |
| 91 | buddy_desc->left_buddy = static_cast<MemoryBlock*>(right_partition); |
| 92 | buddy_desc->UpdateGuards(); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | void MemoryBlock::Merge(MetadataCache* cache, MemoryBlock* right_buddy) { |
| 97 | // only free blocks can be merged |
no test coverage detected