memory_segment_mapped.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Copyright (C) 2013 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <util/memory_segment_mapped.h>
  15. #include <exceptions/exceptions.h>
  16. #include <boost/scoped_ptr.hpp>
  17. #include <boost/interprocess/exceptions.hpp>
  18. #include <boost/interprocess/managed_mapped_file.hpp>
  19. #include <boost/interprocess/offset_ptr.hpp>
  20. #include <boost/interprocess/mapped_region.hpp>
  21. #include <cassert>
  22. #include <string>
  23. #include <new>
  24. using namespace boost::interprocess;
  25. namespace isc {
  26. namespace util {
  27. // Definition of class static constant so it can be referenced by address
  28. // or reference.
  29. const size_t MemorySegmentMapped::INITIAL_SIZE;
  30. // We customize managed_mapped_file to make it completely lock free. In our
  31. // usage the application (or the system of applications) is expected to ensure
  32. // there's at most one writer process or concurrent writing the shared memory
  33. // segment is protected at a higher level. Using the null mutex is mainly for
  34. // eliminating unnecessary dependency; the default version would require
  35. // (probably depending on the system) Pthread library that is actually not
  36. // needed and could cause various build time troubles.
  37. typedef basic_managed_mapped_file<char,
  38. rbtree_best_fit<null_mutex_family>,
  39. iset_index> BaseSegment;
  40. struct MemorySegmentMapped::Impl {
  41. Impl(const std::string& filename, size_t initial_size) :
  42. read_only_(false), filename_(filename),
  43. base_sgmt_(new BaseSegment(open_or_create, filename.c_str(),
  44. initial_size))
  45. {}
  46. Impl(const std::string& filename, bool read_only) :
  47. read_only_(read_only), filename_(filename),
  48. base_sgmt_(read_only ?
  49. new BaseSegment(open_read_only, filename.c_str()) :
  50. new BaseSegment(open_only, filename.c_str()))
  51. {}
  52. // Internal helper to grow the underlying mapped segment.
  53. void growSegment() {
  54. // We first need to unmap it before calling grow().
  55. const size_t prev_size = base_sgmt_->get_size();
  56. base_sgmt_.reset();
  57. const size_t new_size = prev_size * 2;
  58. assert(new_size != 0); // assume grow fails before size overflow
  59. if (!BaseSegment::grow(filename_.c_str(), new_size - prev_size)) {
  60. throw std::bad_alloc();
  61. }
  62. try {
  63. // Remap the grown file; this should succeed, but it's not 100%
  64. // guaranteed. If it fails we treat it as if we fail to create
  65. // the new segment.
  66. base_sgmt_.reset(new BaseSegment(open_only, filename_.c_str()));
  67. } catch (const boost::interprocess::interprocess_exception& ex) {
  68. throw std::bad_alloc();
  69. }
  70. }
  71. // remember if the segment is opened read-only or not
  72. const bool read_only_;
  73. // mapped file; remember it in case we need to grow it.
  74. const std::string filename_;
  75. // actual Boost implementation of mapped segment.
  76. boost::scoped_ptr<BaseSegment> base_sgmt_;
  77. };
  78. MemorySegmentMapped::MemorySegmentMapped(const std::string& filename) :
  79. impl_(NULL)
  80. {
  81. try {
  82. impl_ = new Impl(filename, true);
  83. } catch (const boost::interprocess::interprocess_exception& ex) {
  84. isc_throw(MemorySegmentOpenError,
  85. "failed to open mapped memory segment for " << filename
  86. << ": " << ex.what());
  87. }
  88. }
  89. MemorySegmentMapped::MemorySegmentMapped(const std::string& filename,
  90. bool create, size_t initial_size) :
  91. impl_(NULL)
  92. {
  93. try {
  94. if (create) {
  95. impl_ = new Impl(filename, initial_size);
  96. } else {
  97. impl_ = new Impl(filename, false);
  98. }
  99. } catch (const boost::interprocess::interprocess_exception& ex) {
  100. isc_throw(MemorySegmentOpenError,
  101. "failed to open mapped memory segment for " << filename
  102. << ": " << ex.what());
  103. }
  104. }
  105. MemorySegmentMapped::~MemorySegmentMapped() {
  106. if (impl_->base_sgmt_ && !impl_->read_only_) {
  107. impl_->base_sgmt_->flush(); // note: this is exception free
  108. }
  109. delete impl_;
  110. }
  111. void*
  112. MemorySegmentMapped::allocate(size_t size) {
  113. if (impl_->read_only_) {
  114. isc_throw(MemorySegmentError, "allocate attempt on read-only segment");
  115. }
  116. // We explicitly check the free memory size; it appears
  117. // managed_mapped_file::allocate() could incorrectly return a seemingly
  118. // valid pointer for some very large requested size.
  119. if (impl_->base_sgmt_->get_free_memory() >= size) {
  120. void* ptr = impl_->base_sgmt_->allocate(size, std::nothrow);
  121. if (ptr) {
  122. return (ptr);
  123. }
  124. }
  125. // Grow the mapped segment doubling the size until we have sufficient
  126. // free memory in the revised segment for the requested size.
  127. do {
  128. impl_->growSegment();
  129. } while (impl_->base_sgmt_->get_free_memory() < size);
  130. isc_throw(MemorySegmentGrown, "mapped memory segment grown, size: "
  131. << impl_->base_sgmt_->get_size() << ", free size: "
  132. << impl_->base_sgmt_->get_free_memory());
  133. }
  134. void
  135. MemorySegmentMapped::deallocate(void* ptr, size_t) {
  136. if (impl_->read_only_) {
  137. isc_throw(MemorySegmentError,
  138. "deallocate attempt on read-only segment");
  139. }
  140. // the underlying deallocate() would deal with the case where ptr == NULL,
  141. // but it's an undocumented behavior, so we handle it ourselves for safety.
  142. if (!ptr) {
  143. return;
  144. }
  145. impl_->base_sgmt_->deallocate(ptr);
  146. }
  147. bool
  148. MemorySegmentMapped::allMemoryDeallocated() const {
  149. return (impl_->base_sgmt_->all_memory_deallocated());
  150. }
  151. void*
  152. MemorySegmentMapped::getNamedAddressImpl(const char* name) {
  153. offset_ptr<void>* storage =
  154. impl_->base_sgmt_->find<offset_ptr<void> >(name).first;
  155. if (storage) {
  156. return (storage->get());
  157. }
  158. return (NULL);
  159. }
  160. bool
  161. MemorySegmentMapped::setNamedAddressImpl(const char* name, void* addr) {
  162. if (impl_->read_only_) {
  163. isc_throw(MemorySegmentError, "setNamedAddress on read-only segment");
  164. }
  165. if (addr && !impl_->base_sgmt_->belongs_to_segment(addr)) {
  166. isc_throw(MemorySegmentError, "address is out of segment: " << addr);
  167. }
  168. bool grown = false;
  169. while (true) {
  170. offset_ptr<void>* storage =
  171. impl_->base_sgmt_->find_or_construct<offset_ptr<void> >(
  172. name, std::nothrow)();
  173. if (storage) {
  174. *storage = addr;
  175. return (grown);
  176. }
  177. impl_->growSegment();
  178. grown = true;
  179. }
  180. }
  181. bool
  182. MemorySegmentMapped::clearNamedAddressImpl(const char* name) {
  183. if (impl_->read_only_) {
  184. isc_throw(MemorySegmentError,
  185. "clearNamedAddress on read-only segment");
  186. }
  187. return (impl_->base_sgmt_->destroy<offset_ptr<void> >(name));
  188. }
  189. void
  190. MemorySegmentMapped::shrinkToFit() {
  191. if (impl_->read_only_) {
  192. isc_throw(MemorySegmentError, "shrinkToFit on read-only segment");
  193. }
  194. // It appears an assertion failure is triggered within Boost if the size
  195. // is too small (happening if shrink_to_fit() is called twice without
  196. // allocating any memory from the shrunk segment). To work this around
  197. // we'll make it no-op if the size is already reasonably small.
  198. // Using INITIAL_SIZE is not 100% reliable as it's irrelevant to the
  199. // internal constraint of the Boost implementation. But, in practice,
  200. // it should be sufficiently large and safe.
  201. if (getSize() < INITIAL_SIZE) {
  202. return;
  203. }
  204. // First, (unmap and) close the underlying file.
  205. impl_->base_sgmt_.reset();
  206. BaseSegment::shrink_to_fit(impl_->filename_.c_str());
  207. try {
  208. // Remap the shrunk file; this should succeed, but it's not 100%
  209. // guaranteed. If it fails we treat it as if we fail to create
  210. // the new segment.
  211. impl_->base_sgmt_.reset(
  212. new BaseSegment(open_only, impl_->filename_.c_str()));
  213. } catch (const boost::interprocess::interprocess_exception& ex) {
  214. isc_throw(MemorySegmentError,
  215. "remap after shrink failed; segment is now unusable");
  216. }
  217. }
  218. size_t
  219. MemorySegmentMapped::getSize() const {
  220. return (impl_->base_sgmt_->get_size());
  221. }
  222. size_t
  223. MemorySegmentMapped::getCheckSum() const {
  224. const size_t pagesize =
  225. boost::interprocess::mapped_region::get_page_size();
  226. const uint8_t* const cp_begin = static_cast<const uint8_t*>(
  227. impl_->base_sgmt_->get_address());
  228. const uint8_t* const cp_end = cp_begin + impl_->base_sgmt_->get_size();
  229. size_t sum = 0;
  230. for (const uint8_t* cp = cp_begin; cp < cp_end; cp += pagesize) {
  231. sum += *cp;
  232. }
  233. return (sum);
  234. }
  235. } // namespace util
  236. } // namespace isc