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

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