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() : isinited_(false), beginAddr_(nullptr),
17 0 : memSize_(0), memStartAddr_(nullptr)
18 : {
19 0 : }
20 :
21 0 : HeterogMemBlocksManager::~HeterogMemBlocksManager()
22 : {
23 0 : if (memStartAddr_ != nullptr) {
24 0 : delete[] memStartAddr_;
25 : }
26 0 : memStartAddr_ = nullptr;
27 0 : beginAddr_ = nullptr;
28 0 : }
29 :
30 0 : HcclResult HeterogMemBlocksManager::Init(u32 memBlockNum)
31 : {
32 0 : if (isinited_) {
33 0 : return HCCL_SUCCESS;
34 : }
35 0 : HCCL_INFO("HeterogMemBlocksManager Init memBlockNum(%u) expected links num[%u]", memBlockNum,
36 : memBlockNum / (MEM_BLOCK_RECV_WQE_BATCH_NUM * MEM_BLOCK_DOUBLE));
37 :
38 0 : u64 memLen = MEM_BLOCK_SIZE * memBlockNum + SMALL_PAGE_SIZE;
39 0 : memStartAddr_ = new (std::nothrow) s8[memLen];
40 0 : if (memStartAddr_ == nullptr) {
41 0 : HCCL_ERROR("[Create][HeterogMemBlocksManager]memStartAddr_ is nullptr");
42 0 : return HCCL_E_PARA;
43 : }
44 0 : u64 pageSizeNum = reinterpret_cast<u64>(memStartAddr_) / SMALL_PAGE_SIZE;
45 0 : beginAddr_ = reinterpret_cast<void*>((pageSizeNum + 1) * SMALL_PAGE_SIZE);
46 :
47 0 : CHK_SAFETY_FUNC_RET(memset_s(beginAddr_, MEM_BLOCK_SIZE * memBlockNum, 0, MEM_BLOCK_SIZE * memBlockNum));
48 :
49 0 : usableBlockQue_.Init(memBlockNum + 1);
50 0 : memSize_ = MEM_BLOCK_SIZE * memBlockNum;
51 0 : for (u32 i = 0; i < memBlockNum; i++) {
52 0 : CHK_RET(usableBlockQue_.Push(static_cast<void*>(static_cast<char *>(beginAddr_) + i * MEM_BLOCK_SIZE)));
53 : }
54 0 : isinited_ = true;
55 0 : return HCCL_SUCCESS;
56 : }
57 :
58 0 : HcclResult HeterogMemBlocksManager::Alloc(std::list<void *> &blockList)
59 : {
60 0 : std::unique_lock<std::mutex> lock(usableBlockQueMutex_);
61 0 : if (blockList.size() > usableBlockQue_.Size()) {
62 0 : HCCL_ERROR("[HeterogMemBlocksManager][Alloc]lack of resources, blockListSize[%u] usableBlockQue_Size[%u]",
63 : blockList.size(), usableBlockQue_.Size());
64 0 : return HCCL_E_PARA;
65 : }
66 :
67 0 : for (auto &block : blockList) {
68 0 : CHK_RET(usableBlockQue_.Pop(block));
69 : }
70 0 : return HCCL_SUCCESS;
71 0 : }
72 : } // namespace hccl
|