memory_segment_mapped.cc 17 KB

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