memory_segment_mapped.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 <util/unittests/check_valgrind.h>
  16. #include <exceptions/exceptions.h>
  17. #include <boost/scoped_ptr.hpp>
  18. #include <boost/interprocess/exceptions.hpp>
  19. #include <boost/interprocess/managed_mapped_file.hpp>
  20. #include <boost/interprocess/offset_ptr.hpp>
  21. #include <boost/interprocess/mapped_region.hpp>
  22. #include <boost/interprocess/sync/file_lock.hpp>
  23. #include <cassert>
  24. #include <string>
  25. #include <new>
  26. // boost::interprocess namespace is big and can cause unexpected import
  27. // (e.g., it has "read_only"), so it's safer to be specific for shortcuts.
  28. using boost::interprocess::basic_managed_mapped_file;
  29. using boost::interprocess::rbtree_best_fit;
  30. using boost::interprocess::null_mutex_family;
  31. using boost::interprocess::iset_index;
  32. using boost::interprocess::create_only_t;
  33. using boost::interprocess::create_only;
  34. using boost::interprocess::open_or_create_t;
  35. using boost::interprocess::open_or_create;
  36. using boost::interprocess::open_read_only;
  37. using boost::interprocess::open_only;
  38. using boost::interprocess::offset_ptr;
  39. namespace isc {
  40. namespace util {
  41. // Definition of class static constant so it can be referenced by address
  42. // or reference.
  43. const size_t MemorySegmentMapped::INITIAL_SIZE;
  44. // We customize managed_mapped_file to make it completely lock free. In our
  45. // usage the application (or the system of applications) is expected to ensure
  46. // there's at most one writer process or concurrent writing the shared memory
  47. // segment is protected at a higher level. Using the null mutex is mainly for
  48. // eliminating unnecessary dependency; the default version would require
  49. // (probably depending on the system) Pthread library that is actually not
  50. // needed and could cause various build time troubles.
  51. typedef basic_managed_mapped_file<char,
  52. rbtree_best_fit<null_mutex_family>,
  53. iset_index> BaseSegment;
  54. struct MemorySegmentMapped::Impl {
  55. // Constructor for create-only (and read-write) mode. this case is
  56. // tricky because we want to remove any existing file but we also want
  57. // to detect possible conflict with other readers or writers using
  58. // file lock.
  59. Impl(const std::string& filename, create_only_t, size_t initial_size) :
  60. read_only_(false), filename_(filename)
  61. {
  62. try {
  63. // First, try opening it in boost create_only mode; it fails if
  64. // the file exists (among other reasons).
  65. base_sgmt_.reset(new BaseSegment(create_only, filename.c_str(),
  66. initial_size));
  67. } catch (const boost::interprocess::interprocess_exception& ex) {
  68. // We assume this is because the file exists; otherwise creating
  69. // file_lock would fail with interprocess_exception, and that's
  70. // what we want here (we wouldn't be able to create a segment
  71. // anyway).
  72. lock_.reset(new boost::interprocess::file_lock(filename.c_str()));
  73. // Confirm there's no other reader or writer, and then release
  74. // the lock before we remove the file; there's a chance of race
  75. // here, but this check doesn't intend to guarantee 100% safety
  76. // and so it should be okay.
  77. checkWriter();
  78. lock_.reset();
  79. // now remove the file (if it happens to have been delete, this
  80. // will be no-op), then re-open it with create_only. this time
  81. // it should succeed, and if it fails again, that's fatal for this
  82. // constructor.
  83. boost::interprocess::file_mapping::remove(filename.c_str());
  84. base_sgmt_.reset(new BaseSegment(create_only, filename.c_str(),
  85. initial_size));
  86. }
  87. // confirm there's no other user and there won't either.
  88. lock_.reset(new boost::interprocess::file_lock(filename.c_str()));
  89. checkWriter();
  90. }
  91. // Constructor for open-or-write (and read-write) mode
  92. Impl(const std::string& filename, open_or_create_t, size_t initial_size) :
  93. read_only_(false), filename_(filename),
  94. base_sgmt_(new BaseSegment(open_or_create, filename.c_str(),
  95. initial_size)),
  96. lock_(new boost::interprocess::file_lock(filename.c_str()))
  97. {
  98. checkWriter();
  99. }
  100. // Constructor for existing segment, either read-only or read-write
  101. Impl(const std::string& filename, bool read_only) :
  102. read_only_(read_only), filename_(filename),
  103. base_sgmt_(read_only_ ?
  104. new BaseSegment(open_read_only, filename.c_str()) :
  105. new BaseSegment(open_only, filename.c_str())),
  106. lock_(new boost::interprocess::file_lock(filename.c_str()))
  107. {
  108. if (read_only_) {
  109. checkReader();
  110. } else {
  111. checkWriter();
  112. }
  113. }
  114. // Internal helper to grow the underlying mapped segment.
  115. void growSegment() {
  116. // We first need to unmap it before calling grow().
  117. const size_t prev_size = base_sgmt_->get_size();
  118. base_sgmt_->flush();
  119. base_sgmt_.reset();
  120. // Double the segment size. In theory, this process could repeat
  121. // so many times, counting to "infinity", and new_size eventually
  122. // overflows. That would cause a harsh disruption or unexpected
  123. // behavior. But we basically assume grow() would fail before this
  124. // happens, so we assert it shouldn't happen.
  125. const size_t new_size = prev_size * 2;
  126. assert(new_size > prev_size);
  127. const bool grown = BaseSegment::grow(filename_.c_str(),
  128. new_size - prev_size);
  129. // Remap the file, whether or not grow() succeeded. this should
  130. // normally succeed(*), but it's not 100% guaranteed. We abort
  131. // if it fails (see the method description in the header file).
  132. // (*) Although it's not formally documented, the implementation
  133. // of grow() seems to provide strong guarantee, i.e, if it fails
  134. // the underlying file can be used with the previous size.
  135. try {
  136. base_sgmt_.reset(new BaseSegment(open_only, filename_.c_str()));
  137. } catch (...) {
  138. abort();
  139. }
  140. if (!grown) {
  141. throw std::bad_alloc();
  142. }
  143. }
  144. // remember if the segment is opened read-only or not
  145. const bool read_only_;
  146. // mapped file; remember it in case we need to grow it.
  147. const std::string filename_;
  148. // actual Boost implementation of mapped segment.
  149. boost::scoped_ptr<BaseSegment> base_sgmt_;
  150. private:
  151. // helper methods and member to detect any reader-writer conflict at
  152. // the time of construction using an advisory file lock. The lock will
  153. // be held throughout the lifetime of the object and will be released
  154. // automatically.
  155. void checkReader() {
  156. if (!lock_->try_lock_sharable()) {
  157. isc_throw(MemorySegmentOpenError,
  158. "mapped memory segment can't be opened as read-only "
  159. "with a writer process");
  160. }
  161. }
  162. void checkWriter() {
  163. if (!lock_->try_lock()) {
  164. isc_throw(MemorySegmentOpenError,
  165. "mapped memory segment can't be opened as read-write "
  166. "with other reader or writer processes");
  167. }
  168. }
  169. boost::scoped_ptr<boost::interprocess::file_lock> lock_;
  170. };
  171. MemorySegmentMapped::MemorySegmentMapped(const std::string& filename) :
  172. impl_(NULL)
  173. {
  174. try {
  175. impl_ = new Impl(filename, true);
  176. } catch (const boost::interprocess::interprocess_exception& ex) {
  177. isc_throw(MemorySegmentOpenError,
  178. "failed to open mapped memory segment for " << filename
  179. << ": " << ex.what());
  180. }
  181. }
  182. MemorySegmentMapped::MemorySegmentMapped(const std::string& filename,
  183. OpenMode mode, size_t initial_size) :
  184. impl_(NULL)
  185. {
  186. try {
  187. switch (mode) {
  188. case OPEN_FOR_WRITE:
  189. impl_ = new Impl(filename, false);
  190. break;
  191. case OPEN_OR_CREATE:
  192. impl_ = new Impl(filename, open_or_create, initial_size);
  193. break;
  194. case CREATE_ONLY:
  195. impl_ = new Impl(filename, create_only, initial_size);
  196. break;
  197. default:
  198. isc_throw(InvalidParameter,
  199. "invalid open mode for MemorySegmentMapped: " << mode);
  200. }
  201. } catch (const boost::interprocess::interprocess_exception& ex) {
  202. isc_throw(MemorySegmentOpenError,
  203. "failed to open mapped memory segment for " << filename
  204. << ": " << ex.what());
  205. }
  206. }
  207. MemorySegmentMapped::~MemorySegmentMapped() {
  208. if (impl_->base_sgmt_ && !impl_->read_only_) {
  209. impl_->base_sgmt_->flush(); // note: this is exception free
  210. }
  211. delete impl_;
  212. }
  213. void*
  214. MemorySegmentMapped::allocate(size_t size) {
  215. if (impl_->read_only_) {
  216. isc_throw(MemorySegmentError, "allocate attempt on read-only segment");
  217. }
  218. // We explicitly check the free memory size; it appears
  219. // managed_mapped_file::allocate() could incorrectly return a seemingly
  220. // valid pointer for some very large requested size.
  221. if (impl_->base_sgmt_->get_free_memory() >= size) {
  222. void* ptr = impl_->base_sgmt_->allocate(size, std::nothrow);
  223. if (ptr) {
  224. return (ptr);
  225. }
  226. }
  227. // Grow the mapped segment doubling the size until we have sufficient
  228. // free memory in the revised segment for the requested size.
  229. do {
  230. impl_->growSegment();
  231. } while (impl_->base_sgmt_->get_free_memory() < size);
  232. isc_throw(MemorySegmentGrown, "mapped memory segment grown, size: "
  233. << impl_->base_sgmt_->get_size() << ", free size: "
  234. << impl_->base_sgmt_->get_free_memory());
  235. }
  236. void
  237. MemorySegmentMapped::deallocate(void* ptr, size_t) {
  238. if (impl_->read_only_) {
  239. isc_throw(MemorySegmentError,
  240. "deallocate attempt on read-only segment");
  241. }
  242. // the underlying deallocate() would deal with the case where ptr == NULL,
  243. // but it's an undocumented behavior, so we handle it ourselves for safety.
  244. if (!ptr) {
  245. return;
  246. }
  247. impl_->base_sgmt_->deallocate(ptr);
  248. }
  249. bool
  250. MemorySegmentMapped::allMemoryDeallocated() const {
  251. return (impl_->base_sgmt_->all_memory_deallocated());
  252. }
  253. void*
  254. MemorySegmentMapped::getNamedAddressImpl(const char* name) {
  255. offset_ptr<void>* storage =
  256. impl_->base_sgmt_->find<offset_ptr<void> >(name).first;
  257. if (storage) {
  258. return (storage->get());
  259. }
  260. return (NULL);
  261. }
  262. bool
  263. MemorySegmentMapped::setNamedAddressImpl(const char* name, void* addr) {
  264. if (impl_->read_only_) {
  265. isc_throw(MemorySegmentError, "setNamedAddress on read-only segment");
  266. }
  267. if (addr && !impl_->base_sgmt_->belongs_to_segment(addr)) {
  268. isc_throw(MemorySegmentError, "address is out of segment: " << addr);
  269. }
  270. bool grown = false;
  271. while (true) {
  272. offset_ptr<void>* storage =
  273. impl_->base_sgmt_->find_or_construct<offset_ptr<void> >(
  274. name, std::nothrow)();
  275. if (storage) {
  276. *storage = addr;
  277. return (grown);
  278. }
  279. impl_->growSegment();
  280. grown = true;
  281. }
  282. }
  283. bool
  284. MemorySegmentMapped::clearNamedAddressImpl(const char* name) {
  285. if (impl_->read_only_) {
  286. isc_throw(MemorySegmentError,
  287. "clearNamedAddress on read-only segment");
  288. }
  289. return (impl_->base_sgmt_->destroy<offset_ptr<void> >(name));
  290. }
  291. void
  292. MemorySegmentMapped::shrinkToFit() {
  293. if (impl_->read_only_) {
  294. isc_throw(MemorySegmentError, "shrinkToFit on read-only segment");
  295. }
  296. // It appears an assertion failure is triggered within Boost if the size
  297. // is too small (happening if shrink_to_fit() is called twice without
  298. // allocating any memory from the shrunk segment). To work this around
  299. // we'll make it no-op if the size is already reasonably small.
  300. // Using INITIAL_SIZE is not 100% reliable as it's irrelevant to the
  301. // internal constraint of the Boost implementation. But, in practice,
  302. // it should be sufficiently large and safe.
  303. if (getSize() < INITIAL_SIZE) {
  304. return;
  305. }
  306. // First, unmap the underlying file.
  307. impl_->base_sgmt_->flush();
  308. impl_->base_sgmt_.reset();
  309. BaseSegment::shrink_to_fit(impl_->filename_.c_str());
  310. try {
  311. // Remap the shrunk file; this should succeed, but it's not 100%
  312. // guaranteed. If it fails we treat it as if we fail to create
  313. // the new segment. Note that this is different from the case where
  314. // reset() after grow() fails. While the same argument can apply
  315. // in theory, it should be less likely that other methods will be
  316. // called after shrinkToFit() (and the destructor can still be called
  317. // safely), so we give the application an opportunity to handle the
  318. // case as gracefully as possible.
  319. impl_->base_sgmt_.reset(
  320. new BaseSegment(open_only, impl_->filename_.c_str()));
  321. } catch (const boost::interprocess::interprocess_exception& ex) {
  322. isc_throw(MemorySegmentError,
  323. "remap after shrink failed; segment is now unusable");
  324. }
  325. }
  326. size_t
  327. MemorySegmentMapped::getSize() const {
  328. return (impl_->base_sgmt_->get_size());
  329. }
  330. size_t
  331. MemorySegmentMapped::getCheckSum() const {
  332. const size_t pagesize =
  333. boost::interprocess::mapped_region::get_page_size();
  334. const uint8_t* const cp_begin = static_cast<const uint8_t*>(
  335. impl_->base_sgmt_->get_address());
  336. const uint8_t* const cp_end = cp_begin + impl_->base_sgmt_->get_size();
  337. size_t sum = 0;
  338. for (const uint8_t* cp = cp_begin; cp < cp_end; cp += pagesize) {
  339. sum += *cp;
  340. }
  341. return (sum);
  342. }
  343. } // namespace util
  344. } // namespace isc