• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2022 Huawei Technologies Co., Ltd
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef MINDSPORE_LITE_SRC_EXTENDRT_DYNAMIC_MEM_MANAGER_H_
18 #define MINDSPORE_LITE_SRC_EXTENDRT_DYNAMIC_MEM_MANAGER_H_
19 
20 #include <memory>
21 #include <vector>
22 #include <mutex>
23 #include <map>
24 #include <unordered_map>
25 #include <deque>
26 #include "src/extendrt/numa_adapter.h"
27 
28 namespace mindspore {
29 struct Block {
30   // used_ may be true when ref_count_ == 0
31   bool used_ = false;
32   void *data_ = nullptr;
33   size_t size_;
34   int64_t index_;
35   int64_t ref_count_ = 0;
36   int64_t pre_index_ = -1;
37   int64_t next_index_ = -1;
38 };
39 
40 class MemOperator {
41  public:
42   explicit MemOperator(int node_id);
43   ~MemOperator();
44 
45   void *Malloc(size_t size);
46   void Free(void *ptr);
47   int SetRefCount(void *ptr, int ref_count);
48   int IncRefCount(void *ptr, int ref_count);
49   int DecRefCount(void *ptr, int ref_count);
50   int RefCount(void *ptr);
set_node_id(int node_id)51   inline void set_node_id(int node_id) { node_id_ = node_id; }
node_id(void)52   inline int node_id(void) const { return node_id_; }
53 
54  private:
55   Block *GetBlock();
56   void EraseFreeBlock(const int64_t index);
57   void AddGarbageBlock(const int64_t index);
58   void *Allocate(size_t rounded_size, int node_id, size_t *allocate_size);
59 
60  private:
61   int node_id_ = -1;
62   // all data blocks
63   size_t block_count_ = 0;
64   int64_t garbage_block_;
65   std::shared_ptr<numa::NUMAAdapter> numa_instance_ = nullptr;
66   std::mutex mutex_;
67   std::vector<Block> blocks_;
68   // key: data size, value: Block index
69   std::multimap<size_t, int64_t> free_blocks_;
70   // key: data addr, value: Block index
71   std::unordered_map<void *, int64_t> datas_;
72   std::unordered_map<void *, size_t> all_datas_;
73 };
74 
75 class DynamicMemManager {
76  public:
77   DynamicMemManager() = default;
78   ~DynamicMemManager() = default;
79 
80   std::shared_ptr<MemOperator> GetMemOperator(const int node_id);
81 
82  private:
83   std::map<int, std::shared_ptr<MemOperator>> nodes_mem_;
84   std::mutex mutex_;
85 };
86 }  // namespace mindspore
87 
88 #endif  // MINDSPORE_LITE_SRC_EXTENDRT_DYNAMIC_MEM_MANAGER_H_
89