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. if (_error->PendingError() == true)
  199. return;
  200. // disable Moveable if we don't grow
  201. if (Grow == 0)
  202. this->Flags &= ~Moveable;
  203. #ifndef __linux__
  204. // kfreebsd doesn't have mremap, so we use the fallback
  205. if ((this->Flags & Moveable) == Moveable)
  206. this->Flags |= Fallback;
  207. #endif
  208. unsigned long long EndOfFile = Fd->Size();
  209. if (EndOfFile > WorkSpace)
  210. WorkSpace = EndOfFile;
  211. else if(WorkSpace > 0)
  212. {
  213. Fd->Seek(WorkSpace - 1);
  214. char C = 0;
  215. Fd->Write(&C,sizeof(C));
  216. }
  217. Map(F);
  218. iSize = EndOfFile;
  219. }
  220. /*}}}*/
  221. // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
  222. // ---------------------------------------------------------------------
  223. /* We try here to use mmap to reserve some space - this is much more
  224. cooler than the fallback solution to simply allocate a char array
  225. and could come in handy later than we are able to grow such an mmap */
  226. DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
  227. unsigned long const &Grow, unsigned long const &Limit) :
  228. MMap(Flags | NoImmMap | UnMapped), Fd(0), WorkSpace(WorkSpace),
  229. GrowFactor(Grow), Limit(Limit)
  230. {
  231. if (_error->PendingError() == true)
  232. return;
  233. // disable Moveable if we don't grow
  234. if (Grow == 0)
  235. this->Flags &= ~Moveable;
  236. #ifndef __linux__
  237. // kfreebsd doesn't have mremap, so we use the fallback
  238. if ((this->Flags & Moveable) == Moveable)
  239. this->Flags |= Fallback;
  240. #endif
  241. #ifdef _POSIX_MAPPED_FILES
  242. if ((this->Flags & Fallback) != Fallback) {
  243. // Set the permissions.
  244. int Prot = PROT_READ;
  245. #ifdef MAP_ANONYMOUS
  246. int Map = MAP_PRIVATE | MAP_ANONYMOUS;
  247. #else
  248. int Map = MAP_PRIVATE | MAP_ANON;
  249. #endif
  250. if ((this->Flags & ReadOnly) != ReadOnly)
  251. Prot |= PROT_WRITE;
  252. if ((this->Flags & Public) == Public)
  253. #ifdef MAP_ANONYMOUS
  254. Map = MAP_SHARED | MAP_ANONYMOUS;
  255. #else
  256. Map = MAP_SHARED | MAP_ANON;
  257. #endif
  258. // use anonymous mmap() to get the memory
  259. Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
  260. if(Base == MAP_FAILED)
  261. _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
  262. iSize = 0;
  263. return;
  264. }
  265. #endif
  266. // fallback to a static allocated space
  267. Base = calloc(WorkSpace, 1);
  268. iSize = 0;
  269. }
  270. /*}}}*/
  271. // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
  272. // ---------------------------------------------------------------------
  273. /* We truncate the file to the size of the memory data set */
  274. DynamicMMap::~DynamicMMap()
  275. {
  276. if (Fd == 0)
  277. {
  278. if (validData() == false)
  279. return;
  280. #ifdef _POSIX_MAPPED_FILES
  281. munmap(Base, WorkSpace);
  282. #else
  283. free(Base);
  284. #endif
  285. return;
  286. }
  287. unsigned long long EndOfFile = iSize;
  288. iSize = WorkSpace;
  289. Close(false);
  290. if(ftruncate(Fd->Fd(),EndOfFile) < 0)
  291. _error->Errno("ftruncate", _("Failed to truncate file"));
  292. }
  293. /*}}}*/
  294. // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
  295. // ---------------------------------------------------------------------
  296. /* This allocates a block of memory aligned to the given size */
  297. unsigned long DynamicMMap::RawAllocate(unsigned long long Size,unsigned long Aln)
  298. {
  299. unsigned long long Result = iSize;
  300. if (Aln != 0)
  301. Result += Aln - (iSize%Aln);
  302. iSize = Result + Size;
  303. // try to grow the buffer
  304. while(Result + Size > WorkSpace)
  305. {
  306. if(!Grow())
  307. {
  308. _error->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
  309. "of APT::Cache-Start. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
  310. return 0;
  311. }
  312. }
  313. return Result;
  314. }
  315. /*}}}*/
  316. // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
  317. // ---------------------------------------------------------------------
  318. /* This allocates an Item of size ItemSize so that it is aligned to its
  319. size in the file. */
  320. unsigned long DynamicMMap::Allocate(unsigned long ItemSize)
  321. {
  322. if (unlikely(ItemSize == 0))
  323. {
  324. _error->Fatal("Can't allocate an item of size zero");
  325. return 0;
  326. }
  327. // Look for a matching pool entry
  328. Pool *I;
  329. Pool *Empty = 0;
  330. for (I = Pools; I != Pools + PoolCount; ++I)
  331. {
  332. if (I->ItemSize == 0)
  333. Empty = I;
  334. if (I->ItemSize == ItemSize)
  335. break;
  336. }
  337. // No pool is allocated, use an unallocated one
  338. if (I == Pools + PoolCount)
  339. {
  340. // Woops, we ran out, the calling code should allocate more.
  341. if (Empty == 0)
  342. {
  343. _error->Error("Ran out of allocation pools");
  344. return 0;
  345. }
  346. I = Empty;
  347. I->ItemSize = ItemSize;
  348. I->Count = 0;
  349. }
  350. unsigned long Result = 0;
  351. // Out of space, allocate some more
  352. if (I->Count == 0)
  353. {
  354. const unsigned long size = 20*1024;
  355. I->Count = size/ItemSize;
  356. Pool* oldPools = Pools;
  357. Result = RawAllocate(size,ItemSize);
  358. if (Pools != oldPools)
  359. I += Pools - oldPools;
  360. // Does the allocation failed ?
  361. if (Result == 0 && _error->PendingError())
  362. return 0;
  363. I->Start = Result;
  364. }
  365. else
  366. Result = I->Start;
  367. I->Count--;
  368. I->Start += ItemSize;
  369. return Result/ItemSize;
  370. }
  371. /*}}}*/
  372. // DynamicMMap::WriteString - Write a string to the file /*{{{*/
  373. // ---------------------------------------------------------------------
  374. /* Strings are not aligned to anything */
  375. unsigned long DynamicMMap::WriteString(const char *String,
  376. unsigned long Len)
  377. {
  378. if (Len == (unsigned long)-1)
  379. Len = strlen(String);
  380. unsigned long const Result = RawAllocate(Len+1,0);
  381. if (Base == NULL || (Result == 0 && _error->PendingError()))
  382. return 0;
  383. memcpy((char *)Base + Result,String,Len);
  384. ((char *)Base)[Result + Len] = 0;
  385. return Result;
  386. }
  387. /*}}}*/
  388. // DynamicMMap::Grow - Grow the mmap /*{{{*/
  389. // ---------------------------------------------------------------------
  390. /* This method is a wrapper around different methods to (try to) grow
  391. a mmap (or our char[]-fallback). Encounterable environments:
  392. 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
  393. 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  394. 3. Moveable + Fallback -> realloc
  395. 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
  396. 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  397. 6. !Moveable + Fallback -> not possible
  398. [ While Moveable and Fallback stands for the equally named flags and
  399. "linux" indicates a linux kernel instead of a freebsd kernel. ]
  400. So what you can see here is, that a MMAP which want to be growable need
  401. to be moveable to have a real chance but that this method will at least try
  402. the nearly impossible 4 to grow it before it finally give up: Never say never. */
  403. bool DynamicMMap::Grow() {
  404. if (Limit != 0 && WorkSpace >= Limit)
  405. return _error->Error(_("Unable to increase the size of the MMap as the "
  406. "limit of %lu bytes is already reached."), Limit);
  407. if (GrowFactor <= 0)
  408. return _error->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
  409. unsigned long long const newSize = WorkSpace + GrowFactor;
  410. if(Fd != 0) {
  411. Fd->Seek(newSize - 1);
  412. char C = 0;
  413. Fd->Write(&C,sizeof(C));
  414. }
  415. unsigned long const poolOffset = Pools - ((Pool*) Base);
  416. if ((Flags & Fallback) != Fallback) {
  417. #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
  418. #ifdef MREMAP_MAYMOVE
  419. if ((Flags & Moveable) == Moveable)
  420. Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
  421. else
  422. #endif
  423. Base = mremap(Base, WorkSpace, newSize, 0);
  424. if(Base == MAP_FAILED)
  425. return false;
  426. #else
  427. return false;
  428. #endif
  429. } else {
  430. if ((Flags & Moveable) != Moveable)
  431. return false;
  432. Base = realloc(Base, newSize);
  433. if (Base == NULL)
  434. return false;
  435. else
  436. /* Set new memory to 0 */
  437. memset((char*)Base + WorkSpace, 0, newSize - WorkSpace);
  438. }
  439. Pools =(Pool*) Base + poolOffset;
  440. WorkSpace = newSize;
  441. return true;
  442. }
  443. /*}}}*/