device_memory.cpp 1.97 KB
Newer Older
Chao Liu's avatar
Chao Liu committed
1
// SPDX-License-Identifier: MIT
2
// Copyright (c) 2018-2024, Advanced Micro Devices, Inc. All rights reserved.
Chao Liu's avatar
Chao Liu committed
3

4
5
#include <stdexcept>
#include <iostream>
6

7
#include "ck/host_utility/hip_check_error.hpp"
8
#include "ck/library/utility/device_memory.hpp"
Chao Liu's avatar
Chao Liu committed
9
10
11
12
13
14

DeviceMem::DeviceMem(std::size_t mem_size) : mMemSize(mem_size)
{
    hip_check_error(hipMalloc(static_cast<void**>(&mpDeviceBuf), mMemSize));
}

15
16
17
18
19
20
21
22
23
24
void DeviceMem::Realloc(std::size_t mem_size)
{
    if(mpDeviceBuf)
    {
        hip_check_error(hipFree(mpDeviceBuf));
    }
    mMemSize = mem_size;
    hip_check_error(hipMalloc(static_cast<void**>(&mpDeviceBuf), mMemSize));
}

25
void* DeviceMem::GetDeviceBuffer() const { return mpDeviceBuf; }
Chao Liu's avatar
Chao Liu committed
26

27
std::size_t DeviceMem::GetBufferSize() const { return mMemSize; }
Chao Liu's avatar
Chao Liu committed
28

29
void DeviceMem::ToDevice(const void* p) const
Chao Liu's avatar
Chao Liu committed
30
{
31
32
33
34
35
36
37
38
39
    if(mpDeviceBuf)
    {
        hip_check_error(
            hipMemcpy(mpDeviceBuf, const_cast<void*>(p), mMemSize, hipMemcpyHostToDevice));
    }
    else
    {
        throw std::runtime_error("ToDevice with an empty pointer");
    }
Chao Liu's avatar
Chao Liu committed
40
41
}

42
43
44
45
46
void DeviceMem::ToDevice(const void* p, const std::size_t cpySize) const
{
    hip_check_error(hipMemcpy(mpDeviceBuf, const_cast<void*>(p), cpySize, hipMemcpyHostToDevice));
}

47
void DeviceMem::FromDevice(void* p) const
Chao Liu's avatar
Chao Liu committed
48
{
49
50
51
52
53
54
55
56
    if(mpDeviceBuf)
    {
        hip_check_error(hipMemcpy(p, mpDeviceBuf, mMemSize, hipMemcpyDeviceToHost));
    }
    else
    {
        throw std::runtime_error("FromDevice with an empty pointer");
    }
Chao Liu's avatar
Chao Liu committed
57
58
}

59
60
61
62
63
void DeviceMem::FromDevice(void* p, const std::size_t cpySize) const
{
    hip_check_error(hipMemcpy(p, mpDeviceBuf, cpySize, hipMemcpyDeviceToHost));
}

64
65
66
67
68
69
70
void DeviceMem::SetZero() const
{
    if(mpDeviceBuf)
    {
        hip_check_error(hipMemset(mpDeviceBuf, 0, mMemSize));
    }
}
Chao Liu's avatar
Chao Liu committed
71

72
73
74
75
DeviceMem::~DeviceMem()
{
    if(mpDeviceBuf)
    {
76
77
78
79
80
81
82
83
        try
        {
            hip_check_error(hipFree(mpDeviceBuf));
        }
        catch(std::runtime_error& re)
        {
            std::cerr << re.what() << std::endl;
        }
84
85
    }
}