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

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