workspace_allocator.cpp 1.1 KB
Newer Older
PanZezhong's avatar
PanZezhong committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "../allocator.hpp"

#include "../utils.hpp"

inline size_t aligned_size(size_t size_, size_t align) {
    return (size_ + align - 1) & ~(align - 1);
}

inline void *allocate(size_t size_) {
    void *ptr;
    RUN_INFINI(infinirtMalloc(&ptr, size_));
    return ptr;
}

WorkspaceAllocator::WorkspaceAllocator(size_t initial_size_, size_t align) {
    _align = align;
PanZezhong's avatar
PanZezhong committed
17
18
    _total_size = 0;
    _memory = nullptr;
PanZezhong's avatar
PanZezhong committed
19
20
21
22
23
24
25
26
27
    if (initial_size_ > 0) {
        _total_size = aligned_size(initial_size_, _align);
        _memory = allocate(_total_size);
    }
}

void *WorkspaceAllocator::alloc(size_t new_size) {
    if (_total_size < new_size) {
        if (_total_size != 0) {
PanZezhong's avatar
PanZezhong committed
28
            RUN_INFINI(infinirtDeviceSynchronize());
PanZezhong's avatar
PanZezhong committed
29
30
            RUN_INFINI(infinirtFree(_memory));
        }
PanZezhong's avatar
PanZezhong committed
31
        _total_size = aligned_size(new_size, _align);
PanZezhong's avatar
PanZezhong committed
32
33
34
35
36
37
38
39
40
41
        _memory = allocate(_total_size);
    }
    return _memory;
}

void WorkspaceAllocator::release(void *ptr) {
}

WorkspaceAllocator::~WorkspaceAllocator() {
    if (_memory != nullptr) {
PanZezhong's avatar
PanZezhong committed
42
        RUN_INFINI(infinirtDeviceSynchronize());
PanZezhong's avatar
PanZezhong committed
43
44
45
        RUN_INFINI(infinirtFree(_memory));
    }
}