Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 :
11 : #include "heterog_mem_blocks_manager.h"
12 :
13 : constexpr u32 SMALL_PAGE_SIZE = 4096;
14 :
15 : namespace hccl {
16 0 : HeterogMemBlocksManager::HeterogMemBlocksManager()
17 0 : : isinited_(false),
18 0 : beginAddr_(nullptr),
19 0 : memSize_(0),
20 0 : memStartAddr_(nullptr)
21 0 : {}
22 :
23 0 : HeterogMemBlocksManager::~HeterogMemBlocksManager()
24 : {
25 0 : if (memStartAddr_ != nullptr) {
26 0 : delete[] memStartAddr_;
27 : }
28 0 : memStartAddr_ = nullptr;
29 0 : beginAddr_ = nullptr;
30 0 : }
31 :
32 0 : HcclResult HeterogMemBlocksManager::Init(u32 memBlockNum)
33 : {
34 0 : if (isinited_) {
35 0 : return HCCL_SUCCESS;
36 : }
37 0 : HCCL_INFO(
38 : "HeterogMemBlocksManager Init memBlockNum(%u) expected links num[%u]", memBlockNum,
39 : memBlockNum / (MEM_BLOCK_RECV_WQE_BATCH_NUM * MEM_BLOCK_DOUBLE));
40 :
41 0 : u64 memLen = MEM_BLOCK_SIZE * memBlockNum + SMALL_PAGE_SIZE;
42 0 : memStartAddr_ = new (std::nothrow) s8[memLen];
43 0 : if (memStartAddr_ == nullptr) {
44 0 : HCCL_ERROR("[Create][HeterogMemBlocksManager]memStartAddr_ is nullptr");
45 0 : return HCCL_E_PARA;
46 : }
47 0 : u64 pageSizeNum = reinterpret_cast<u64>(memStartAddr_) / SMALL_PAGE_SIZE;
48 0 : beginAddr_ = reinterpret_cast<void*>((pageSizeNum + 1) * SMALL_PAGE_SIZE);
49 :
50 0 : CHK_SAFETY_FUNC_RET(memset_s(beginAddr_, MEM_BLOCK_SIZE * memBlockNum, 0, MEM_BLOCK_SIZE * memBlockNum));
51 :
52 0 : usableBlockQue_.Init(memBlockNum + 1);
53 0 : memSize_ = MEM_BLOCK_SIZE * memBlockNum;
54 0 : for (u32 i = 0; i < memBlockNum; i++) {
55 0 : CHK_RET(usableBlockQue_.Push(static_cast<void*>(static_cast<char*>(beginAddr_) + i * MEM_BLOCK_SIZE)));
56 : }
57 0 : isinited_ = true;
58 0 : return HCCL_SUCCESS;
59 : }
60 :
61 0 : HcclResult HeterogMemBlocksManager::Alloc(std::list<void*>& blockList)
62 : {
63 0 : std::unique_lock<std::mutex> lock(usableBlockQueMutex_);
64 0 : if (blockList.size() > usableBlockQue_.Size()) {
65 0 : HCCL_ERROR(
66 : "[HeterogMemBlocksManager][Alloc]lack of resources, blockListSize[%u] usableBlockQue_Size[%u]",
67 : blockList.size(), usableBlockQue_.Size());
68 0 : return HCCL_E_PARA;
69 : }
70 :
71 0 : for (auto& block : blockList) {
72 0 : CHK_RET(usableBlockQue_.Pop(block));
73 : }
74 0 : return HCCL_SUCCESS;
75 0 : }
76 : } // namespace hccl
|