mmap.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 <apt-pkg/mmap.h>
  17. #include <apt-pkg/error.h>
  18. #include <apti18n.h>
  19. #include <sys/mman.h>
  20. #include <sys/stat.h>
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #include <stdlib.h>
  24. #include <cstring>
  25. /*}}}*/
  26. // MMap::MMap - Constructor /*{{{*/
  27. // ---------------------------------------------------------------------
  28. /* */
  29. MMap::MMap(FileFd &F,unsigned long Flags) : Flags(Flags), iSize(0),
  30. Base(0)
  31. {
  32. if ((Flags & NoImmMap) != NoImmMap)
  33. Map(F);
  34. }
  35. /*}}}*/
  36. // MMap::MMap - Constructor /*{{{*/
  37. // ---------------------------------------------------------------------
  38. /* */
  39. MMap::MMap(unsigned long Flags) : Flags(Flags), iSize(0),
  40. Base(0)
  41. {
  42. }
  43. /*}}}*/
  44. // MMap::~MMap - Destructor /*{{{*/
  45. // ---------------------------------------------------------------------
  46. /* */
  47. MMap::~MMap()
  48. {
  49. Close();
  50. }
  51. /*}}}*/
  52. // MMap::Map - Perform the mapping /*{{{*/
  53. // ---------------------------------------------------------------------
  54. /* */
  55. bool MMap::Map(FileFd &Fd)
  56. {
  57. iSize = Fd.Size();
  58. // Set the permissions.
  59. int Prot = PROT_READ;
  60. int Map = MAP_SHARED;
  61. if ((Flags & ReadOnly) != ReadOnly)
  62. Prot |= PROT_WRITE;
  63. if ((Flags & Public) != Public)
  64. Map = MAP_PRIVATE;
  65. if (iSize == 0)
  66. return _error->Error(_("Can't mmap an empty file"));
  67. // Map it.
  68. Base = mmap(0,iSize,Prot,Map,Fd.Fd(),0);
  69. if (Base == (void *)-1)
  70. return _error->Errno("mmap",_("Couldn't make mmap of %lu bytes"),iSize);
  71. return true;
  72. }
  73. /*}}}*/
  74. // MMap::Close - Close the map /*{{{*/
  75. // ---------------------------------------------------------------------
  76. /* */
  77. bool MMap::Close(bool DoSync)
  78. {
  79. if ((Flags & UnMapped) == UnMapped || Base == 0 || iSize == 0)
  80. return true;
  81. if (DoSync == true)
  82. Sync();
  83. if (munmap((char *)Base,iSize) != 0)
  84. _error->Warning("Unable to munmap");
  85. iSize = 0;
  86. Base = 0;
  87. return true;
  88. }
  89. /*}}}*/
  90. // MMap::Sync - Syncronize the map with the disk /*{{{*/
  91. // ---------------------------------------------------------------------
  92. /* This is done in syncronous mode - the docs indicate that this will
  93. not return till all IO is complete */
  94. bool MMap::Sync()
  95. {
  96. if ((Flags & UnMapped) == UnMapped)
  97. return true;
  98. #ifdef _POSIX_SYNCHRONIZED_IO
  99. if ((Flags & ReadOnly) != ReadOnly)
  100. if (msync((char *)Base,iSize,MS_SYNC) < 0)
  101. return _error->Errno("msync","Unable to write mmap");
  102. #endif
  103. return true;
  104. }
  105. /*}}}*/
  106. // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
  107. // ---------------------------------------------------------------------
  108. /* */
  109. bool MMap::Sync(unsigned long Start,unsigned long Stop)
  110. {
  111. if ((Flags & UnMapped) == UnMapped)
  112. return true;
  113. #ifdef _POSIX_SYNCHRONIZED_IO
  114. unsigned long PSize = sysconf(_SC_PAGESIZE);
  115. if ((Flags & ReadOnly) != ReadOnly)
  116. if (msync((char *)Base+(int)(Start/PSize)*PSize,Stop - Start,MS_SYNC) < 0)
  117. return _error->Errno("msync","Unable to write mmap");
  118. #endif
  119. return true;
  120. }
  121. /*}}}*/
  122. // DynamicMMap::DynamicMMap - Constructor /*{{{*/
  123. // ---------------------------------------------------------------------
  124. /* */
  125. DynamicMMap::DynamicMMap(FileFd &F,unsigned long Flags,unsigned long const &Workspace,
  126. unsigned long const &Grow, unsigned long const &Limit) :
  127. MMap(F,Flags | NoImmMap), Fd(&F), WorkSpace(Workspace),
  128. GrowFactor(Grow), Limit(Limit)
  129. {
  130. if (_error->PendingError() == true)
  131. return;
  132. unsigned long EndOfFile = Fd->Size();
  133. if (EndOfFile > WorkSpace)
  134. WorkSpace = EndOfFile;
  135. else if(WorkSpace > 0)
  136. {
  137. Fd->Seek(WorkSpace - 1);
  138. char C = 0;
  139. Fd->Write(&C,sizeof(C));
  140. }
  141. Map(F);
  142. iSize = EndOfFile;
  143. }
  144. /*}}}*/
  145. // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
  146. // ---------------------------------------------------------------------
  147. /* We try here to use mmap to reserve some space - this is much more
  148. cooler than the fallback solution to simply allocate a char array
  149. and could come in handy later than we are able to grow such an mmap */
  150. DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
  151. unsigned long const &Grow, unsigned long const &Limit) :
  152. MMap(Flags | NoImmMap | UnMapped), Fd(0), WorkSpace(WorkSpace),
  153. GrowFactor(Grow), Limit(Limit)
  154. {
  155. if (_error->PendingError() == true)
  156. return;
  157. // disable Moveable if we don't grow
  158. if (Grow == 0)
  159. Flags &= ~Moveable;
  160. #ifndef __linux__
  161. // kfreebsd doesn't have mremap, so we use the fallback
  162. if ((Flags & Moveable) == Moveable)
  163. Flags |= Fallback;
  164. #endif
  165. #ifdef _POSIX_MAPPED_FILES
  166. if ((Flags & Fallback) != Fallback) {
  167. // Set the permissions.
  168. int Prot = PROT_READ;
  169. int Map = MAP_PRIVATE | MAP_ANONYMOUS;
  170. if ((Flags & ReadOnly) != ReadOnly)
  171. Prot |= PROT_WRITE;
  172. if ((Flags & Public) == Public)
  173. Map = MAP_SHARED | MAP_ANONYMOUS;
  174. // use anonymous mmap() to get the memory
  175. Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
  176. if(Base == MAP_FAILED)
  177. _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
  178. iSize = 0;
  179. return;
  180. }
  181. #endif
  182. // fallback to a static allocated space
  183. Base = new unsigned char[WorkSpace];
  184. memset(Base,0,WorkSpace);
  185. iSize = 0;
  186. }
  187. /*}}}*/
  188. // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
  189. // ---------------------------------------------------------------------
  190. /* We truncate the file to the size of the memory data set */
  191. DynamicMMap::~DynamicMMap()
  192. {
  193. if (Fd == 0)
  194. {
  195. #ifdef _POSIX_MAPPED_FILES
  196. munmap(Base, WorkSpace);
  197. #else
  198. delete [] (unsigned char *)Base;
  199. #endif
  200. return;
  201. }
  202. unsigned long EndOfFile = iSize;
  203. iSize = WorkSpace;
  204. Close(false);
  205. if(ftruncate(Fd->Fd(),EndOfFile) < 0)
  206. _error->Errno("ftruncate", _("Failed to truncate file"));
  207. }
  208. /*}}}*/
  209. // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
  210. // ---------------------------------------------------------------------
  211. /* This allocates a block of memory aligned to the given size */
  212. unsigned long DynamicMMap::RawAllocate(unsigned long Size,unsigned long Aln)
  213. {
  214. unsigned long Result = iSize;
  215. if (Aln != 0)
  216. Result += Aln - (iSize%Aln);
  217. iSize = Result + Size;
  218. // try to grow the buffer
  219. while(Result + Size > WorkSpace)
  220. {
  221. if(!Grow())
  222. {
  223. _error->Error(_("Dynamic MMap ran out of room. Please increase the size "
  224. "of APT::Cache-Limit. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
  225. return 0;
  226. }
  227. }
  228. return Result;
  229. }
  230. /*}}}*/
  231. // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
  232. // ---------------------------------------------------------------------
  233. /* This allocates an Item of size ItemSize so that it is aligned to its
  234. size in the file. */
  235. unsigned long DynamicMMap::Allocate(unsigned long ItemSize)
  236. {
  237. // Look for a matching pool entry
  238. Pool *I;
  239. Pool *Empty = 0;
  240. for (I = Pools; I != Pools + PoolCount; I++)
  241. {
  242. if (I->ItemSize == 0)
  243. Empty = I;
  244. if (I->ItemSize == ItemSize)
  245. break;
  246. }
  247. // No pool is allocated, use an unallocated one
  248. if (I == Pools + PoolCount)
  249. {
  250. // Woops, we ran out, the calling code should allocate more.
  251. if (Empty == 0)
  252. {
  253. _error->Error("Ran out of allocation pools");
  254. return 0;
  255. }
  256. I = Empty;
  257. I->ItemSize = ItemSize;
  258. I->Count = 0;
  259. }
  260. unsigned long Result = 0;
  261. // Out of space, allocate some more
  262. if (I->Count == 0)
  263. {
  264. const unsigned long size = 20*1024;
  265. I->Count = size/ItemSize;
  266. Result = RawAllocate(size,ItemSize);
  267. // Does the allocation failed ?
  268. if (Result == 0 && _error->PendingError())
  269. return 0;
  270. I->Start = Result;
  271. }
  272. else
  273. Result = I->Start;
  274. I->Count--;
  275. I->Start += ItemSize;
  276. return Result/ItemSize;
  277. }
  278. /*}}}*/
  279. // DynamicMMap::WriteString - Write a string to the file /*{{{*/
  280. // ---------------------------------------------------------------------
  281. /* Strings are not aligned to anything */
  282. unsigned long DynamicMMap::WriteString(const char *String,
  283. unsigned long Len)
  284. {
  285. if (Len == (unsigned long)-1)
  286. Len = strlen(String);
  287. unsigned long Result = RawAllocate(Len+1,0);
  288. if (Result == 0 && _error->PendingError())
  289. return 0;
  290. memcpy((char *)Base + Result,String,Len);
  291. ((char *)Base)[Result + Len] = 0;
  292. return Result;
  293. }
  294. /*}}}*/
  295. // DynamicMMap::Grow - Grow the mmap /*{{{*/
  296. // ---------------------------------------------------------------------
  297. /* This method is a wrapper around different methods to (try to) grow
  298. a mmap (or our char[]-fallback). Encounterable environments:
  299. 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
  300. 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  301. 3. Moveable + Fallback -> realloc
  302. 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
  303. 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  304. 6. !Moveable + Fallback -> not possible
  305. [ While Moveable and Fallback stands for the equally named flags and
  306. "linux" indicates a linux kernel instead of a freebsd kernel. ]
  307. So what you can see here is, that a MMAP which want to be growable need
  308. to be moveable to have a real chance but that this method will at least try
  309. the nearly impossible 4 to grow it before it finally give up: Never say never. */
  310. bool DynamicMMap::Grow() {
  311. if (Limit != 0 && WorkSpace >= Limit)
  312. return _error->Error(_("The size of a MMap has already reached the defined limit of %lu bytes,"
  313. "abort the try to grow the MMap."), Limit);
  314. unsigned long const newSize = WorkSpace + 1024*1024;
  315. if(Fd != 0) {
  316. Fd->Seek(newSize - 1);
  317. char C = 0;
  318. Fd->Write(&C,sizeof(C));
  319. }
  320. if ((Flags & Fallback) != Fallback) {
  321. #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
  322. #ifdef MREMAP_MAYMOVE
  323. if ((Flags & Moveable) == Moveable)
  324. Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
  325. else
  326. #endif
  327. Base = mremap(Base, WorkSpace, newSize, 0);
  328. if(Base == MAP_FAILED)
  329. return false;
  330. #else
  331. return false;
  332. #endif
  333. } else {
  334. if ((Flags & Moveable) != Moveable)
  335. return false;
  336. Base = realloc(Base, newSize);
  337. if (Base == NULL)
  338. return false;
  339. }
  340. WorkSpace = newSize;
  341. return true;
  342. }
  343. /*}}}*/