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 8.5 kB

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