mmap.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: mmap.cc,v 1.22 2001/05/27 05:19:30 jgg Exp $
  4. /* ######################################################################
  5. MMap Class - Provides 'real' mmap or a faked mmap using read().
  6. MMap cover class.
  7. Some broken versions of glibc2 (libc6) have a broken definition
  8. of mmap that accepts a char * -- all other systems (and libc5) use
  9. void *. We can't safely do anything here that would be portable, so
  10. libc6 generates warnings -- which should be errors, g++ isn't properly
  11. strict.
  12. ##################################################################### */
  13. /*}}}*/
  14. // Include Files /*{{{*/
  15. #define _BSD_SOURCE
  16. #include <config.h>
  17. #include <apt-pkg/mmap.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/fileutl.h>
  20. #include <apt-pkg/macros.h>
  21. #include <string>
  22. #include <sys/mman.h>
  23. #include <unistd.h>
  24. #include <stdlib.h>
  25. #include <errno.h>
  26. #include <cstring>
  27. #include <apti18n.h>
  28. /*}}}*/
  29. // MMap::MMap - Constructor /*{{{*/
  30. // ---------------------------------------------------------------------
  31. /* */
  32. MMap::MMap(FileFd &F,unsigned long Flags) : Flags(Flags), iSize(0),
  33. Base(0), SyncToFd(NULL)
  34. {
  35. if ((Flags & NoImmMap) != NoImmMap)
  36. Map(F);
  37. }
  38. /*}}}*/
  39. // MMap::MMap - Constructor /*{{{*/
  40. // ---------------------------------------------------------------------
  41. /* */
  42. MMap::MMap(unsigned long Flags) : Flags(Flags), iSize(0),
  43. Base(0), SyncToFd(NULL)
  44. {
  45. }
  46. /*}}}*/
  47. // MMap::~MMap - Destructor /*{{{*/
  48. // ---------------------------------------------------------------------
  49. /* */
  50. MMap::~MMap()
  51. {
  52. Close();
  53. }
  54. /*}}}*/
  55. // MMap::Map - Perform the mapping /*{{{*/
  56. // ---------------------------------------------------------------------
  57. /* */
  58. bool MMap::Map(FileFd &Fd)
  59. {
  60. iSize = Fd.Size();
  61. // Set the permissions.
  62. int Prot = PROT_READ;
  63. int Map = MAP_SHARED;
  64. if ((Flags & ReadOnly) != ReadOnly)
  65. Prot |= PROT_WRITE;
  66. if ((Flags & Public) != Public)
  67. Map = MAP_PRIVATE;
  68. if (iSize == 0)
  69. return _error->Error(_("Can't mmap an empty file"));
  70. // We can't mmap compressed fd's directly, so we need to read it completely
  71. if (Fd.IsCompressed() == true)
  72. {
  73. if ((Flags & ReadOnly) != ReadOnly)
  74. return _error->Error("Compressed file %s can only be mapped readonly", Fd.Name().c_str());
  75. Base = malloc(iSize);
  76. SyncToFd = new FileFd();
  77. if (Fd.Seek(0L) == false || Fd.Read(Base, iSize) == false)
  78. return _error->Error("Compressed file %s can't be read into mmap", Fd.Name().c_str());
  79. return true;
  80. }
  81. // Map it.
  82. Base = (Flags & Fallback) ? MAP_FAILED : mmap(0,iSize,Prot,Map,Fd.Fd(),0);
  83. if (Base == (void *)-1)
  84. {
  85. if (errno == ENODEV || errno == EINVAL || (Flags & Fallback))
  86. {
  87. // The filesystem doesn't support this particular kind of mmap.
  88. // So we allocate a buffer and read the whole file into it.
  89. if ((Flags & ReadOnly) == ReadOnly)
  90. {
  91. // for readonly, we don't need sync, so make it simple
  92. Base = malloc(iSize);
  93. SyncToFd = new FileFd();
  94. return Fd.Read(Base, iSize);
  95. }
  96. // FIXME: Writing to compressed fd's ?
  97. int const dupped_fd = dup(Fd.Fd());
  98. if (dupped_fd == -1)
  99. return _error->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd.Fd());
  100. Base = calloc(iSize, 1);
  101. SyncToFd = new FileFd (dupped_fd);
  102. if (!SyncToFd->Seek(0L) || !SyncToFd->Read(Base, iSize))
  103. return false;
  104. }
  105. else
  106. return _error->Errno("mmap",_("Couldn't make mmap of %llu bytes"),
  107. iSize);
  108. }
  109. return true;
  110. }
  111. /*}}}*/
  112. // MMap::Close - Close the map /*{{{*/
  113. // ---------------------------------------------------------------------
  114. /* */
  115. bool MMap::Close(bool DoSync)
  116. {
  117. if ((Flags & UnMapped) == UnMapped || validData() == false || iSize == 0)
  118. return true;
  119. if (DoSync == true)
  120. Sync();
  121. if (SyncToFd != NULL)
  122. {
  123. free(Base);
  124. delete SyncToFd;
  125. SyncToFd = NULL;
  126. }
  127. else
  128. {
  129. if (munmap((char *)Base, iSize) != 0)
  130. _error->WarningE("mmap", _("Unable to close mmap"));
  131. }
  132. iSize = 0;
  133. Base = 0;
  134. return true;
  135. }
  136. /*}}}*/
  137. // MMap::Sync - Syncronize the map with the disk /*{{{*/
  138. // ---------------------------------------------------------------------
  139. /* This is done in syncronous mode - the docs indicate that this will
  140. not return till all IO is complete */
  141. bool MMap::Sync()
  142. {
  143. if ((Flags & UnMapped) == UnMapped)
  144. return true;
  145. if ((Flags & ReadOnly) != ReadOnly)
  146. {
  147. if (SyncToFd != NULL)
  148. {
  149. if (!SyncToFd->Seek(0) || !SyncToFd->Write(Base, iSize))
  150. return false;
  151. }
  152. else
  153. {
  154. #ifdef _POSIX_SYNCHRONIZED_IO
  155. if (msync((char *)Base, iSize, MS_SYNC) < 0)
  156. return _error->Errno("msync", _("Unable to synchronize mmap"));
  157. #endif
  158. }
  159. }
  160. return true;
  161. }
  162. /*}}}*/
  163. // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
  164. // ---------------------------------------------------------------------
  165. /* */
  166. bool MMap::Sync(unsigned long Start,unsigned long Stop)
  167. {
  168. if ((Flags & UnMapped) == UnMapped)
  169. return true;
  170. if ((Flags & ReadOnly) != ReadOnly)
  171. {
  172. if (SyncToFd != 0)
  173. {
  174. if (!SyncToFd->Seek(0) ||
  175. !SyncToFd->Write (((char *)Base)+Start, Stop-Start))
  176. return false;
  177. }
  178. else
  179. {
  180. #ifdef _POSIX_SYNCHRONIZED_IO
  181. unsigned long long const PSize = sysconf(_SC_PAGESIZE);
  182. if (msync((char *)Base+(Start/PSize)*PSize, Stop - Start, MS_SYNC) < 0)
  183. return _error->Errno("msync", _("Unable to synchronize mmap"));
  184. #endif
  185. }
  186. }
  187. return true;
  188. }
  189. /*}}}*/
  190. // DynamicMMap::DynamicMMap - Constructor /*{{{*/
  191. // ---------------------------------------------------------------------
  192. /* */
  193. DynamicMMap::DynamicMMap(FileFd &F,unsigned long Flags,unsigned long const &Workspace,
  194. unsigned long const &Grow, unsigned long const &Limit) :
  195. MMap(F,Flags | NoImmMap), Fd(&F), WorkSpace(Workspace),
  196. GrowFactor(Grow), Limit(Limit)
  197. {
  198. // disable Moveable if we don't grow
  199. if (Grow == 0)
  200. this->Flags &= ~Moveable;
  201. #ifndef __linux__
  202. // kfreebsd doesn't have mremap, so we use the fallback
  203. if ((this->Flags & Moveable) == Moveable)
  204. this->Flags |= Fallback;
  205. #endif
  206. unsigned long long EndOfFile = Fd->Size();
  207. if (EndOfFile > WorkSpace)
  208. WorkSpace = EndOfFile;
  209. else if(WorkSpace > 0)
  210. {
  211. Fd->Seek(WorkSpace - 1);
  212. char C = 0;
  213. Fd->Write(&C,sizeof(C));
  214. }
  215. Map(F);
  216. iSize = EndOfFile;
  217. }
  218. /*}}}*/
  219. // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
  220. // ---------------------------------------------------------------------
  221. /* We try here to use mmap to reserve some space - this is much more
  222. cooler than the fallback solution to simply allocate a char array
  223. and could come in handy later than we are able to grow such an mmap */
  224. DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
  225. unsigned long const &Grow, unsigned long const &Limit) :
  226. MMap(Flags | NoImmMap | UnMapped), Fd(0), WorkSpace(WorkSpace),
  227. GrowFactor(Grow), Limit(Limit)
  228. {
  229. // disable Moveable if we don't grow
  230. if (Grow == 0)
  231. this->Flags &= ~Moveable;
  232. #ifndef __linux__
  233. // kfreebsd doesn't have mremap, so we use the fallback
  234. if ((this->Flags & Moveable) == Moveable)
  235. this->Flags |= Fallback;
  236. #endif
  237. #ifdef _POSIX_MAPPED_FILES
  238. if ((this->Flags & Fallback) != Fallback) {
  239. // Set the permissions.
  240. int Prot = PROT_READ;
  241. #ifdef MAP_ANONYMOUS
  242. int Map = MAP_PRIVATE | MAP_ANONYMOUS;
  243. #else
  244. int Map = MAP_PRIVATE | MAP_ANON;
  245. #endif
  246. if ((this->Flags & ReadOnly) != ReadOnly)
  247. Prot |= PROT_WRITE;
  248. if ((this->Flags & Public) == Public)
  249. #ifdef MAP_ANONYMOUS
  250. Map = MAP_SHARED | MAP_ANONYMOUS;
  251. #else
  252. Map = MAP_SHARED | MAP_ANON;
  253. #endif
  254. // use anonymous mmap() to get the memory
  255. Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
  256. if(Base == MAP_FAILED)
  257. _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
  258. iSize = 0;
  259. return;
  260. }
  261. #endif
  262. // fallback to a static allocated space
  263. Base = calloc(WorkSpace, 1);
  264. iSize = 0;
  265. }
  266. /*}}}*/
  267. // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
  268. // ---------------------------------------------------------------------
  269. /* We truncate the file to the size of the memory data set */
  270. DynamicMMap::~DynamicMMap()
  271. {
  272. if (Fd == 0)
  273. {
  274. if (validData() == false)
  275. return;
  276. #ifdef _POSIX_MAPPED_FILES
  277. munmap(Base, WorkSpace);
  278. #else
  279. free(Base);
  280. #endif
  281. return;
  282. }
  283. unsigned long long EndOfFile = iSize;
  284. iSize = WorkSpace;
  285. Close(false);
  286. if(ftruncate(Fd->Fd(),EndOfFile) < 0)
  287. _error->Errno("ftruncate", _("Failed to truncate file"));
  288. }
  289. /*}}}*/
  290. // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
  291. // ---------------------------------------------------------------------
  292. /* This allocates a block of memory aligned to the given size */
  293. unsigned long DynamicMMap::RawAllocate(unsigned long long Size,unsigned long Aln)
  294. {
  295. unsigned long long Result = iSize;
  296. if (Aln != 0)
  297. Result += Aln - (iSize%Aln);
  298. iSize = Result + Size;
  299. // try to grow the buffer
  300. while(Result + Size > WorkSpace)
  301. {
  302. if(!Grow())
  303. {
  304. _error->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
  305. "of APT::Cache-Start. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
  306. return 0;
  307. }
  308. }
  309. return Result;
  310. }
  311. /*}}}*/
  312. // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
  313. // ---------------------------------------------------------------------
  314. /* This allocates an Item of size ItemSize so that it is aligned to its
  315. size in the file. */
  316. unsigned long DynamicMMap::Allocate(unsigned long ItemSize)
  317. {
  318. if (unlikely(ItemSize == 0))
  319. {
  320. _error->Fatal("Can't allocate an item of size zero");
  321. return 0;
  322. }
  323. // Look for a matching pool entry
  324. Pool *I;
  325. Pool *Empty = 0;
  326. for (I = Pools; I != Pools + PoolCount; ++I)
  327. {
  328. if (I->ItemSize == 0)
  329. Empty = I;
  330. if (I->ItemSize == ItemSize)
  331. break;
  332. }
  333. // No pool is allocated, use an unallocated one
  334. if (I == Pools + PoolCount)
  335. {
  336. // Woops, we ran out, the calling code should allocate more.
  337. if (Empty == 0)
  338. {
  339. _error->Error("Ran out of allocation pools");
  340. return 0;
  341. }
  342. I = Empty;
  343. I->ItemSize = ItemSize;
  344. I->Count = 0;
  345. }
  346. unsigned long Result = 0;
  347. // Out of space, allocate some more
  348. if (I->Count == 0)
  349. {
  350. const unsigned long size = 20*1024;
  351. I->Count = size/ItemSize;
  352. Pool* oldPools = Pools;
  353. _error->PushToStack();
  354. Result = RawAllocate(size,ItemSize);
  355. bool const newError = _error->PendingError();
  356. _error->MergeWithStack();
  357. if (Pools != oldPools)
  358. I += Pools - oldPools;
  359. // Does the allocation failed ?
  360. if (Result == 0 && newError)
  361. return 0;
  362. I->Start = Result;
  363. }
  364. else
  365. Result = I->Start;
  366. I->Count--;
  367. I->Start += ItemSize;
  368. return Result/ItemSize;
  369. }
  370. /*}}}*/
  371. // DynamicMMap::WriteString - Write a string to the file /*{{{*/
  372. // ---------------------------------------------------------------------
  373. /* Strings are not aligned to anything */
  374. unsigned long DynamicMMap::WriteString(const char *String,
  375. unsigned long Len)
  376. {
  377. if (Len == (unsigned long)-1)
  378. Len = strlen(String);
  379. _error->PushToStack();
  380. unsigned long const Result = RawAllocate(Len+1,0);
  381. bool const newError = _error->PendingError();
  382. _error->MergeWithStack();
  383. if (Base == NULL || (Result == 0 && newError))
  384. return 0;
  385. memcpy((char *)Base + Result,String,Len);
  386. ((char *)Base)[Result + Len] = 0;
  387. return Result;
  388. }
  389. /*}}}*/
  390. // DynamicMMap::Grow - Grow the mmap /*{{{*/
  391. // ---------------------------------------------------------------------
  392. /* This method is a wrapper around different methods to (try to) grow
  393. a mmap (or our char[]-fallback). Encounterable environments:
  394. 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
  395. 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  396. 3. Moveable + Fallback -> realloc
  397. 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
  398. 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  399. 6. !Moveable + Fallback -> not possible
  400. [ While Moveable and Fallback stands for the equally named flags and
  401. "linux" indicates a linux kernel instead of a freebsd kernel. ]
  402. So what you can see here is, that a MMAP which want to be growable need
  403. to be moveable to have a real chance but that this method will at least try
  404. the nearly impossible 4 to grow it before it finally give up: Never say never. */
  405. bool DynamicMMap::Grow() {
  406. if (Limit != 0 && WorkSpace >= Limit)
  407. return _error->Error(_("Unable to increase the size of the MMap as the "
  408. "limit of %lu bytes is already reached."), Limit);
  409. if (GrowFactor <= 0)
  410. return _error->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
  411. unsigned long long const newSize = WorkSpace + GrowFactor;
  412. if(Fd != 0) {
  413. Fd->Seek(newSize - 1);
  414. char C = 0;
  415. Fd->Write(&C,sizeof(C));
  416. }
  417. unsigned long const poolOffset = Pools - ((Pool*) Base);
  418. if ((Flags & Fallback) != Fallback) {
  419. #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
  420. #ifdef MREMAP_MAYMOVE
  421. if ((Flags & Moveable) == Moveable)
  422. Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
  423. else
  424. #endif
  425. Base = mremap(Base, WorkSpace, newSize, 0);
  426. if(Base == MAP_FAILED)
  427. return false;
  428. #else
  429. return false;
  430. #endif
  431. } else {
  432. if ((Flags & Moveable) != Moveable)
  433. return false;
  434. Base = realloc(Base, newSize);
  435. if (Base == NULL)
  436. return false;
  437. else
  438. /* Set new memory to 0 */
  439. memset((char*)Base + WorkSpace, 0, newSize - WorkSpace);
  440. }
  441. Pools =(Pool*) Base + poolOffset;
  442. WorkSpace = newSize;
  443. return true;
  444. }
  445. /*}}}*/