]>
git.saurik.com Git - apt.git/blob - apt-pkg/contrib/mmap.cc
1 // -*- mode: cpp; mode: fold -*-
3 // $Id: mmap.cc,v 1.22 2001/05/27 05:19:30 jgg Exp $
4 /* ######################################################################
6 MMap Class - Provides 'real' mmap or a faked mmap using read().
10 Some broken versions of glibc2 (libc6) have a broken definition
11 of mmap that accepts a char * -- all other systems (and libc5) use
12 void *. We can't safely do anything here that would be portable, so
13 libc6 generates warnings -- which should be errors, g++ isn't properly
16 ##################################################################### */
18 // Include Files /*{{{*/
22 #include <apt-pkg/mmap.h>
23 #include <apt-pkg/error.h>
24 #include <apt-pkg/fileutl.h>
25 #include <apt-pkg/macros.h>
37 // MMap::MMap - Constructor /*{{{*/
38 // ---------------------------------------------------------------------
40 MMap::MMap(FileFd
&F
,unsigned long Flags
) : Flags(Flags
), iSize(0),
41 Base(0), SyncToFd(NULL
)
43 if ((Flags
& NoImmMap
) != NoImmMap
)
47 // MMap::MMap - Constructor /*{{{*/
48 // ---------------------------------------------------------------------
50 MMap::MMap(unsigned long Flags
) : Flags(Flags
), iSize(0),
51 Base(0), SyncToFd(NULL
)
55 // MMap::~MMap - Destructor /*{{{*/
56 // ---------------------------------------------------------------------
63 // MMap::Map - Perform the mapping /*{{{*/
64 // ---------------------------------------------------------------------
66 bool MMap::Map(FileFd
&Fd
)
70 // Set the permissions.
73 if ((Flags
& ReadOnly
) != ReadOnly
)
75 if ((Flags
& Public
) != Public
)
79 return _error
->Error(_("Can't mmap an empty file"));
81 // We can't mmap compressed fd's directly, so we need to read it completely
82 if (Fd
.IsCompressed() == true)
84 if ((Flags
& ReadOnly
) != ReadOnly
)
85 return _error
->Error("Compressed file %s can only be mapped readonly", Fd
.Name().c_str());
87 SyncToFd
= new FileFd();
88 if (Fd
.Seek(0L) == false || Fd
.Read(Base
, iSize
) == false)
89 return _error
->Error("Compressed file %s can't be read into mmap", Fd
.Name().c_str());
94 Base
= (Flags
& Fallback
) ? MAP_FAILED
: mmap(0,iSize
,Prot
,Map
,Fd
.Fd(),0);
95 if (Base
== (void *)-1)
97 if (errno
== ENODEV
|| errno
== EINVAL
|| (Flags
& Fallback
))
99 // The filesystem doesn't support this particular kind of mmap.
100 // So we allocate a buffer and read the whole file into it.
101 if ((Flags
& ReadOnly
) == ReadOnly
)
103 // for readonly, we don't need sync, so make it simple
104 Base
= malloc(iSize
);
105 SyncToFd
= new FileFd();
106 return Fd
.Read(Base
, iSize
);
108 // FIXME: Writing to compressed fd's ?
109 int const dupped_fd
= dup(Fd
.Fd());
111 return _error
->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd
.Fd());
113 Base
= calloc(iSize
, 1);
114 SyncToFd
= new FileFd (dupped_fd
);
115 if (!SyncToFd
->Seek(0L) || !SyncToFd
->Read(Base
, iSize
))
119 return _error
->Errno("mmap",_("Couldn't make mmap of %llu bytes"),
126 // MMap::Close - Close the map /*{{{*/
127 // ---------------------------------------------------------------------
129 bool MMap::Close(bool DoSync
)
131 if ((Flags
& UnMapped
) == UnMapped
|| validData() == false || iSize
== 0)
137 if (SyncToFd
!= NULL
)
145 if (munmap((char *)Base
, iSize
) != 0)
146 _error
->WarningE("mmap", _("Unable to close mmap"));
154 // MMap::Sync - Syncronize the map with the disk /*{{{*/
155 // ---------------------------------------------------------------------
156 /* This is done in syncronous mode - the docs indicate that this will
157 not return till all IO is complete */
160 if ((Flags
& UnMapped
) == UnMapped
)
163 if ((Flags
& ReadOnly
) != ReadOnly
)
165 if (SyncToFd
!= NULL
)
167 if (!SyncToFd
->Seek(0) || !SyncToFd
->Write(Base
, iSize
))
172 #ifdef _POSIX_SYNCHRONIZED_IO
173 if (msync((char *)Base
, iSize
, MS_SYNC
) < 0)
174 return _error
->Errno("msync", _("Unable to synchronize mmap"));
181 // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
182 // ---------------------------------------------------------------------
184 bool MMap::Sync(unsigned long Start
,unsigned long Stop
)
186 if ((Flags
& UnMapped
) == UnMapped
)
189 if ((Flags
& ReadOnly
) != ReadOnly
)
193 if (!SyncToFd
->Seek(0) ||
194 !SyncToFd
->Write (((char *)Base
)+Start
, Stop
-Start
))
199 #ifdef _POSIX_SYNCHRONIZED_IO
200 unsigned long long const PSize
= sysconf(_SC_PAGESIZE
);
201 if (msync((char *)Base
+(Start
/PSize
)*PSize
, Stop
- Start
, MS_SYNC
) < 0)
202 return _error
->Errno("msync", _("Unable to synchronize mmap"));
210 // DynamicMMap::DynamicMMap - Constructor /*{{{*/
211 // ---------------------------------------------------------------------
213 DynamicMMap::DynamicMMap(FileFd
&F
,unsigned long Flags
,unsigned long const &Workspace
,
214 unsigned long const &Grow
, unsigned long const &Limit
) :
215 MMap(F
,Flags
| NoImmMap
), Fd(&F
), WorkSpace(Workspace
),
216 GrowFactor(Grow
), Limit(Limit
)
218 // disable Moveable if we don't grow
220 this->Flags
&= ~Moveable
;
223 // kfreebsd doesn't have mremap, so we use the fallback
224 if ((this->Flags
& Moveable
) == Moveable
)
225 this->Flags
|= Fallback
;
228 unsigned long long EndOfFile
= Fd
->Size();
229 if (EndOfFile
> WorkSpace
)
230 WorkSpace
= EndOfFile
;
231 else if(WorkSpace
> 0)
233 Fd
->Seek(WorkSpace
- 1);
235 Fd
->Write(&C
,sizeof(C
));
242 // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
243 // ---------------------------------------------------------------------
244 /* We try here to use mmap to reserve some space - this is much more
245 cooler than the fallback solution to simply allocate a char array
246 and could come in handy later than we are able to grow such an mmap */
247 DynamicMMap::DynamicMMap(unsigned long Flags
,unsigned long const &WorkSpace
,
248 unsigned long const &Grow
, unsigned long const &Limit
) :
249 MMap(Flags
| NoImmMap
| UnMapped
), Fd(0), WorkSpace(WorkSpace
),
250 GrowFactor(Grow
), Limit(Limit
)
252 // disable Moveable if we don't grow
254 this->Flags
&= ~Moveable
;
257 // kfreebsd doesn't have mremap, so we use the fallback
258 if ((this->Flags
& Moveable
) == Moveable
)
259 this->Flags
|= Fallback
;
262 #ifdef _POSIX_MAPPED_FILES
263 if ((this->Flags
& Fallback
) != Fallback
) {
264 // Set the permissions.
265 int Prot
= PROT_READ
;
267 int Map
= MAP_PRIVATE
| MAP_ANONYMOUS
;
269 int Map
= MAP_PRIVATE
| MAP_ANON
;
271 if ((this->Flags
& ReadOnly
) != ReadOnly
)
273 if ((this->Flags
& Public
) == Public
)
275 Map
= MAP_SHARED
| MAP_ANONYMOUS
;
277 Map
= MAP_SHARED
| MAP_ANON
;
280 // use anonymous mmap() to get the memory
281 Base
= (unsigned char*) mmap(0, WorkSpace
, Prot
, Map
, -1, 0);
283 if(Base
== MAP_FAILED
)
284 _error
->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace
);
290 // fallback to a static allocated space
291 Base
= calloc(WorkSpace
, 1);
295 // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
296 // ---------------------------------------------------------------------
297 /* We truncate the file to the size of the memory data set */
298 DynamicMMap::~DynamicMMap()
302 if (validData() == false)
304 #ifdef _POSIX_MAPPED_FILES
305 munmap(Base
, WorkSpace
);
312 unsigned long long EndOfFile
= iSize
;
315 if(ftruncate(Fd
->Fd(),EndOfFile
) < 0)
316 _error
->Errno("ftruncate", _("Failed to truncate file"));
319 // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
320 // ---------------------------------------------------------------------
321 /* This allocates a block of memory aligned to the given size */
322 unsigned long DynamicMMap::RawAllocate(unsigned long long Size
,unsigned long Aln
)
324 unsigned long long Result
= iSize
;
326 Result
+= Aln
- (iSize%Aln
);
328 iSize
= Result
+ Size
;
330 // try to grow the buffer
331 while(Result
+ Size
> WorkSpace
)
335 _error
->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
336 "of APT::Cache-Start. Current value: %lu. (man 5 apt.conf)"), WorkSpace
);
343 // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
344 // ---------------------------------------------------------------------
345 /* This allocates an Item of size ItemSize so that it is aligned to its
347 unsigned long DynamicMMap::Allocate(unsigned long ItemSize
)
349 if (unlikely(ItemSize
== 0))
351 _error
->Fatal("Can't allocate an item of size zero");
355 // Look for a matching pool entry
358 for (I
= Pools
; I
!= Pools
+ PoolCount
; ++I
)
360 if (I
->ItemSize
== 0)
362 if (I
->ItemSize
== ItemSize
)
365 // No pool is allocated, use an unallocated one
366 if (I
== Pools
+ PoolCount
)
368 // Woops, we ran out, the calling code should allocate more.
371 _error
->Error("Ran out of allocation pools");
376 I
->ItemSize
= ItemSize
;
380 unsigned long Result
= 0;
381 // Out of space, allocate some more
384 const unsigned long size
= 20*1024;
385 I
->Count
= size
/ItemSize
;
386 Pool
* oldPools
= Pools
;
387 _error
->PushToStack();
388 Result
= RawAllocate(size
,ItemSize
);
389 bool const newError
= _error
->PendingError();
390 _error
->MergeWithStack();
391 if (Pools
!= oldPools
)
392 I
+= Pools
- oldPools
;
394 // Does the allocation failed ?
395 if (Result
== 0 && newError
)
403 I
->Start
+= ItemSize
;
404 return Result
/ItemSize
;
407 // DynamicMMap::WriteString - Write a string to the file /*{{{*/
408 // ---------------------------------------------------------------------
409 /* Strings are not aligned to anything */
410 unsigned long DynamicMMap::WriteString(const char *String
,
413 if (Len
== (unsigned long)-1)
414 Len
= strlen(String
);
416 _error
->PushToStack();
417 unsigned long const Result
= RawAllocate(Len
+1,0);
418 bool const newError
= _error
->PendingError();
419 _error
->MergeWithStack();
421 if (Base
== NULL
|| (Result
== 0 && newError
))
424 memcpy((char *)Base
+ Result
,String
,Len
);
425 ((char *)Base
)[Result
+ Len
] = 0;
429 // DynamicMMap::Grow - Grow the mmap /*{{{*/
430 // ---------------------------------------------------------------------
431 /* This method is a wrapper around different methods to (try to) grow
432 a mmap (or our char[]-fallback). Encounterable environments:
433 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
434 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
435 3. Moveable + Fallback -> realloc
436 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
437 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
438 6. !Moveable + Fallback -> not possible
439 [ While Moveable and Fallback stands for the equally named flags and
440 "linux" indicates a linux kernel instead of a freebsd kernel. ]
441 So what you can see here is, that a MMAP which want to be growable need
442 to be moveable to have a real chance but that this method will at least try
443 the nearly impossible 4 to grow it before it finally give up: Never say never. */
444 bool DynamicMMap::Grow() {
445 if (Limit
!= 0 && WorkSpace
>= Limit
)
446 return _error
->Error(_("Unable to increase the size of the MMap as the "
447 "limit of %lu bytes is already reached."), Limit
);
449 return _error
->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
451 unsigned long long const newSize
= WorkSpace
+ GrowFactor
;
454 Fd
->Seek(newSize
- 1);
456 Fd
->Write(&C
,sizeof(C
));
459 unsigned long const poolOffset
= Pools
- ((Pool
*) Base
);
461 if ((Flags
& Fallback
) != Fallback
) {
462 #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
463 #ifdef MREMAP_MAYMOVE
465 if ((Flags
& Moveable
) == Moveable
)
466 Base
= mremap(Base
, WorkSpace
, newSize
, MREMAP_MAYMOVE
);
469 Base
= mremap(Base
, WorkSpace
, newSize
, 0);
471 if(Base
== MAP_FAILED
)
477 if ((Flags
& Moveable
) != Moveable
)
480 Base
= realloc(Base
, newSize
);
484 /* Set new memory to 0 */
485 memset((char*)Base
+ WorkSpace
, 0, newSize
- WorkSpace
);
488 Pools
=(Pool
*) Base
+ poolOffset
;