You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

arena.cc 9.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /**
  2. * Copyright 2019 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. #include "minddata/dataset/util/arena.h"
  17. #include <unistd.h>
  18. #include <utility>
  19. #include "minddata/dataset/util/log_adapter.h"
  20. #include "minddata/dataset/util/system_pool.h"
  21. namespace mindspore {
  22. namespace dataset {
  23. struct MemHdr {
  24. uint32_t sig;
  25. uint64_t addr;
  26. uint64_t blk_size;
  27. MemHdr(uint64_t a, uint64_t sz) : sig(0xDEADBEEF), addr(a), blk_size(sz) {}
  28. static void setHdr(void *p, uint64_t addr, uint64_t sz) { new (p) MemHdr(addr, sz); }
  29. static void getHdr(void *p, MemHdr *hdr) {
  30. auto *tmp = reinterpret_cast<MemHdr *>(p);
  31. *hdr = *tmp;
  32. }
  33. };
  34. ArenaImpl::ArenaImpl(void *ptr, size_t sz) : size_in_bytes_(sz), ptr_(ptr) {
  35. // Divide the memory into blocks. Ignore the last partial block.
  36. uint64_t num_blks = size_in_bytes_ / ARENA_BLK_SZ;
  37. MS_LOG(DEBUG) << "Arena memory pool is created. Number of blocks : " << num_blks << ". Block size : " << ARENA_BLK_SZ
  38. << ".";
  39. tr_.Insert(0, num_blks);
  40. }
  41. Status ArenaImpl::Allocate(size_t n, void **p) {
  42. if (n == 0) {
  43. *p = nullptr;
  44. return Status::OK();
  45. }
  46. // Round up n to 1K block
  47. uint64_t req_size = static_cast<uint64_t>(n) + ARENA_WALL_OVERHEAD_SZ;
  48. if (req_size > this->get_max_size()) {
  49. return Status(StatusCode::kMDOutOfMemory);
  50. }
  51. uint64_t reqBlk = SizeToBlk(req_size);
  52. // Do a first fit search
  53. auto blk = tr_.Top();
  54. if (blk.second && reqBlk <= blk.first.priority) {
  55. uint64_t addr = blk.first.key;
  56. uint64_t size = blk.first.priority;
  57. // Trim to the required size and return the rest to the tree.
  58. tr_.Pop();
  59. if (size > reqBlk) {
  60. tr_.Insert(addr + reqBlk, size - reqBlk);
  61. }
  62. char *q = static_cast<char *>(ptr_) + addr * ARENA_BLK_SZ;
  63. MemHdr::setHdr(q, addr, reqBlk);
  64. *p = get_user_addr(q);
  65. } else {
  66. return Status(StatusCode::kMDOutOfMemory);
  67. }
  68. return Status::OK();
  69. }
  70. std::pair<std::pair<uint64_t, uint64_t>, bool> ArenaImpl::FindPrevBlk(uint64_t addr) {
  71. for (auto &it : tr_) {
  72. if (it.key + it.priority == addr) {
  73. return std::make_pair(std::make_pair(it.key, it.priority), true);
  74. } else if (it.key > addr) {
  75. break;
  76. }
  77. }
  78. return std::make_pair(std::make_pair(0, 0), false);
  79. }
  80. void ArenaImpl::Deallocate(void *p) {
  81. auto *q = get_base_addr(p);
  82. MemHdr hdr(0, 0);
  83. MemHdr::getHdr(q, &hdr);
  84. MS_ASSERT(hdr.sig == 0xDEADBEEF);
  85. // We are going to insert a free block back to the treap. But first, check if we can combine
  86. // with the free blocks before and after to form a bigger block.
  87. // Query if we have a free block after us.
  88. auto nextBlk = tr_.Search(hdr.addr + hdr.blk_size);
  89. if (nextBlk.second) {
  90. // Form a bigger block
  91. hdr.blk_size += nextBlk.first.priority;
  92. tr_.DeleteKey(nextBlk.first.key);
  93. }
  94. // Next find a block in front of us.
  95. auto result = FindPrevBlk(hdr.addr);
  96. if (result.second) {
  97. // We can combine with this block
  98. hdr.addr = result.first.first;
  99. hdr.blk_size += result.first.second;
  100. tr_.DeleteKey(result.first.first);
  101. }
  102. // Now we can insert the free node
  103. tr_.Insert(hdr.addr, hdr.blk_size);
  104. }
  105. bool ArenaImpl::BlockEnlarge(uint64_t *addr, uint64_t old_sz, uint64_t new_sz) {
  106. uint64_t size = old_sz;
  107. // The logic is very much identical to Deallocate. We will see if we can combine with the blocks before and after.
  108. auto next_blk = tr_.Search(*addr + old_sz);
  109. if (next_blk.second) {
  110. size += next_blk.first.priority;
  111. if (size >= new_sz) {
  112. // In this case, we can just enlarge the block without doing any moving.
  113. tr_.DeleteKey(next_blk.first.key);
  114. // Return unused back to the tree.
  115. if (size > new_sz) {
  116. tr_.Insert(*addr + new_sz, size - new_sz);
  117. }
  118. }
  119. return true;
  120. }
  121. // If we still get here, we have to look at the block before us.
  122. auto result = FindPrevBlk(*addr);
  123. if (result.second) {
  124. // We can combine with this block together with the next block (if any)
  125. size += result.first.second;
  126. *addr = result.first.first;
  127. if (size >= new_sz) {
  128. // We can combine with this block together with the next block (if any)
  129. tr_.DeleteKey(*addr);
  130. if (next_blk.second) {
  131. tr_.DeleteKey(next_blk.first.key);
  132. }
  133. // Return unused back to the tree.
  134. if (size > new_sz) {
  135. tr_.Insert(*addr + new_sz, size - new_sz);
  136. }
  137. return true;
  138. }
  139. }
  140. return false;
  141. }
  142. Status ArenaImpl::FreeAndAlloc(void **pp, size_t old_sz, size_t new_sz) {
  143. MS_ASSERT(pp);
  144. MS_ASSERT(*pp);
  145. void *p = nullptr;
  146. void *q = *pp;
  147. RETURN_IF_NOT_OK(Allocate(new_sz, &p));
  148. errno_t err = memmove_s(p, new_sz, q, old_sz);
  149. if (err) {
  150. RETURN_STATUS_UNEXPECTED("Error from memmove: " + std::to_string(err));
  151. }
  152. *pp = p;
  153. // Free the old one.
  154. Deallocate(q);
  155. return Status::OK();
  156. }
  157. Status ArenaImpl::Reallocate(void **pp, size_t old_sz, size_t new_sz) {
  158. MS_ASSERT(pp);
  159. MS_ASSERT(*pp);
  160. uint64_t actual_size = static_cast<uint64_t>(new_sz) + ARENA_WALL_OVERHEAD_SZ;
  161. if (actual_size > this->get_max_size()) {
  162. RETURN_STATUS_UNEXPECTED("Request size too big : " + std::to_string(new_sz));
  163. }
  164. uint64_t req_blk = SizeToBlk(actual_size);
  165. char *oldAddr = reinterpret_cast<char *>(*pp);
  166. auto *oldHdr = get_base_addr(oldAddr);
  167. MemHdr hdr(0, 0);
  168. MemHdr::getHdr(oldHdr, &hdr);
  169. MS_ASSERT(hdr.sig == 0xDEADBEEF);
  170. if (hdr.blk_size > req_blk) {
  171. // Refresh the header with the new smaller size.
  172. MemHdr::setHdr(oldHdr, hdr.addr, req_blk);
  173. // Return the unused memory back to the tree. Unlike allocate, we we need to merge with the block after us.
  174. auto next_blk = tr_.Search(hdr.addr + hdr.blk_size);
  175. if (next_blk.second) {
  176. hdr.blk_size += next_blk.first.priority;
  177. tr_.DeleteKey(next_blk.first.key);
  178. }
  179. tr_.Insert(hdr.addr + req_blk, hdr.blk_size - req_blk);
  180. } else if (hdr.blk_size < req_blk) {
  181. uint64_t addr = hdr.addr;
  182. // Attempt a block enlarge. No guarantee it is always successful.
  183. bool success = BlockEnlarge(&addr, hdr.blk_size, req_blk);
  184. if (success) {
  185. auto *newHdr = static_cast<char *>(ptr_) + addr * ARENA_BLK_SZ;
  186. MemHdr::setHdr(newHdr, addr, req_blk);
  187. if (addr != hdr.addr) {
  188. errno_t err =
  189. memmove_s(get_user_addr(newHdr), (req_blk * ARENA_BLK_SZ) - ARENA_WALL_OVERHEAD_SZ, oldAddr, old_sz);
  190. if (err) {
  191. RETURN_STATUS_UNEXPECTED("Error from memmove: " + std::to_string(err));
  192. }
  193. }
  194. *pp = get_user_addr(newHdr);
  195. return Status::OK();
  196. }
  197. return FreeAndAlloc(pp, old_sz, new_sz);
  198. }
  199. return Status::OK();
  200. }
  201. int ArenaImpl::PercentFree() const {
  202. uint64_t sz = 0;
  203. for (auto &it : tr_) {
  204. sz += it.priority;
  205. }
  206. double ratio = static_cast<double>(sz * ARENA_BLK_SZ) / static_cast<double>(size_in_bytes_);
  207. return static_cast<int>(ratio * 100.0);
  208. }
  209. uint64_t ArenaImpl::SizeToBlk(uint64_t sz) {
  210. uint64_t req_blk = sz / ARENA_BLK_SZ;
  211. if (sz % ARENA_BLK_SZ) {
  212. ++req_blk;
  213. }
  214. return req_blk;
  215. }
  216. std::ostream &operator<<(std::ostream &os, const ArenaImpl &s) {
  217. for (auto &it : s.tr_) {
  218. os << "Address : " << it.key << ". Size : " << it.priority << "\n";
  219. }
  220. return os;
  221. }
  222. Status Arena::Init() {
  223. try {
  224. int64_t sz = size_in_MB_ * 1048576L;
  225. #ifdef ENABLE_GPUQUE
  226. if (is_cuda_malloc_) {
  227. auto ret = cudaHostAlloc(&ptr_, sz, cudaHostAllocDefault);
  228. if (ret != cudaSuccess) {
  229. MS_LOG(ERROR) << "cudaHostAlloc failed, ret[" << static_cast<int>(ret) << "], " << cudaGetErrorString(ret);
  230. return Status(StatusCode::kMDOutOfMemory);
  231. }
  232. impl_ = std::make_unique<ArenaImpl>(ptr_, sz);
  233. } else {
  234. RETURN_IF_NOT_OK(DeMalloc(sz, &ptr_, false));
  235. impl_ = std::make_unique<ArenaImpl>(ptr_, sz);
  236. }
  237. #else
  238. RETURN_IF_NOT_OK(DeMalloc(sz, &ptr_, false));
  239. impl_ = std::make_unique<ArenaImpl>(ptr_, sz);
  240. #endif
  241. } catch (std::bad_alloc &e) {
  242. return Status(StatusCode::kMDOutOfMemory);
  243. }
  244. return Status::OK();
  245. }
  246. #ifdef ENABLE_GPUQUE
  247. Arena::Arena(size_t val_in_MB, bool is_cuda_malloc)
  248. : ptr_(nullptr), size_in_MB_(val_in_MB), is_cuda_malloc_(is_cuda_malloc) {}
  249. Status Arena::CreateArena(std::shared_ptr<Arena> *p_ba, size_t val_in_MB, bool is_cuda_malloc) {
  250. RETURN_UNEXPECTED_IF_NULL(p_ba);
  251. auto ba = new (std::nothrow) Arena(val_in_MB, is_cuda_malloc);
  252. if (ba == nullptr) {
  253. return Status(StatusCode::kMDOutOfMemory);
  254. }
  255. (*p_ba).reset(ba);
  256. RETURN_IF_NOT_OK(ba->Init());
  257. return Status::OK();
  258. }
  259. #else
  260. Arena::Arena(size_t val_in_MB) : ptr_(nullptr), size_in_MB_(val_in_MB) {}
  261. Status Arena::CreateArena(std::shared_ptr<Arena> *p_ba, size_t val_in_MB) {
  262. RETURN_UNEXPECTED_IF_NULL(p_ba);
  263. auto ba = new (std::nothrow) Arena(val_in_MB);
  264. if (ba == nullptr) {
  265. return Status(StatusCode::kMDOutOfMemory);
  266. }
  267. (*p_ba).reset(ba);
  268. RETURN_IF_NOT_OK(ba->Init());
  269. return Status::OK();
  270. }
  271. #endif
  272. } // namespace dataset
  273. } // namespace mindspore