]>
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>
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());
86 Base
= new unsigned char[iSize
];
87 if (Fd
.Seek(0L) == false || Fd
.Read(Base
, iSize
) == false)
93 Base
= mmap(0,iSize
,Prot
,Map
,Fd
.Fd(),0);
94 if (Base
== (void *)-1)
96 if (errno
== ENODEV
|| errno
== EINVAL
)
98 // The filesystem doesn't support this particular kind of mmap.
99 // So we allocate a buffer and read the whole file into it.
100 int const dupped_fd
= dup(Fd
.Fd());
102 return _error
->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd
.Fd());
104 Base
= new unsigned char[iSize
];
105 SyncToFd
= new FileFd (dupped_fd
);
106 if (!SyncToFd
->Seek(0L) || !SyncToFd
->Read(Base
, iSize
))
110 return _error
->Errno("mmap",_("Couldn't make mmap of %llu bytes"),
117 // MMap::Close - Close the map /*{{{*/
118 // ---------------------------------------------------------------------
120 bool MMap::Close(bool DoSync
)
122 if ((Flags
& UnMapped
) == UnMapped
|| validData() == false || iSize
== 0)
128 if (SyncToFd
!= NULL
)
130 delete[] (char *)Base
;
136 if (munmap((char *)Base
, iSize
) != 0)
137 _error
->WarningE("mmap", _("Unable to close mmap"));
145 // MMap::Sync - Syncronize the map with the disk /*{{{*/
146 // ---------------------------------------------------------------------
147 /* This is done in syncronous mode - the docs indicate that this will
148 not return till all IO is complete */
151 if ((Flags
& UnMapped
) == UnMapped
)
154 #ifdef _POSIX_SYNCHRONIZED_IO
155 if ((Flags
& ReadOnly
) != ReadOnly
)
157 if (SyncToFd
!= NULL
)
159 if (!SyncToFd
->Seek(0) || !SyncToFd
->Write(Base
, iSize
))
164 if (msync((char *)Base
, iSize
, MS_SYNC
) < 0)
165 return _error
->Errno("msync", _("Unable to synchronize mmap"));
172 // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
173 // ---------------------------------------------------------------------
175 bool MMap::Sync(unsigned long Start
,unsigned long Stop
)
177 if ((Flags
& UnMapped
) == UnMapped
)
180 #ifdef _POSIX_SYNCHRONIZED_IO
181 unsigned long long PSize
= sysconf(_SC_PAGESIZE
);
182 if ((Flags
& ReadOnly
) != ReadOnly
)
186 if (!SyncToFd
->Seek(0) ||
187 !SyncToFd
->Write (((char *)Base
)+Start
, Stop
-Start
))
192 if (msync((char *)Base
+(unsigned long long)(Start
/PSize
)*PSize
,Stop
- Start
,MS_SYNC
) < 0)
193 return _error
->Errno("msync", _("Unable to synchronize mmap"));
201 // DynamicMMap::DynamicMMap - Constructor /*{{{*/
202 // ---------------------------------------------------------------------
204 DynamicMMap::DynamicMMap(FileFd
&F
,unsigned long Flags
,unsigned long const &Workspace
,
205 unsigned long const &Grow
, unsigned long const &Limit
) :
206 MMap(F
,Flags
| NoImmMap
), Fd(&F
), WorkSpace(Workspace
),
207 GrowFactor(Grow
), Limit(Limit
)
209 if (_error
->PendingError() == true)
212 unsigned long long EndOfFile
= Fd
->Size();
213 if (EndOfFile
> WorkSpace
)
214 WorkSpace
= EndOfFile
;
215 else if(WorkSpace
> 0)
217 Fd
->Seek(WorkSpace
- 1);
219 Fd
->Write(&C
,sizeof(C
));
226 // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
227 // ---------------------------------------------------------------------
228 /* We try here to use mmap to reserve some space - this is much more
229 cooler than the fallback solution to simply allocate a char array
230 and could come in handy later than we are able to grow such an mmap */
231 DynamicMMap::DynamicMMap(unsigned long Flags
,unsigned long const &WorkSpace
,
232 unsigned long const &Grow
, unsigned long const &Limit
) :
233 MMap(Flags
| NoImmMap
| UnMapped
), Fd(0), WorkSpace(WorkSpace
),
234 GrowFactor(Grow
), Limit(Limit
)
236 if (_error
->PendingError() == true)
239 // disable Moveable if we don't grow
241 this->Flags
&= ~Moveable
;
244 // kfreebsd doesn't have mremap, so we use the fallback
245 if ((this->Flags
& Moveable
) == Moveable
)
246 this->Flags
|= Fallback
;
249 #ifdef _POSIX_MAPPED_FILES
250 if ((this->Flags
& Fallback
) != Fallback
) {
251 // Set the permissions.
252 int Prot
= PROT_READ
;
254 int Map
= MAP_PRIVATE
| MAP_ANONYMOUS
;
256 int Map
= MAP_PRIVATE
| MAP_ANON
;
258 if ((this->Flags
& ReadOnly
) != ReadOnly
)
260 if ((this->Flags
& Public
) == Public
)
262 Map
= MAP_SHARED
| MAP_ANONYMOUS
;
264 Map
= MAP_SHARED
| MAP_ANON
;
267 // use anonymous mmap() to get the memory
268 Base
= (unsigned char*) mmap(0, WorkSpace
, Prot
, Map
, -1, 0);
270 if(Base
== MAP_FAILED
)
271 _error
->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace
);
277 // fallback to a static allocated space
278 Base
= new unsigned char[WorkSpace
];
279 memset(Base
,0,WorkSpace
);
283 // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
284 // ---------------------------------------------------------------------
285 /* We truncate the file to the size of the memory data set */
286 DynamicMMap::~DynamicMMap()
290 if (validData() == false)
292 #ifdef _POSIX_MAPPED_FILES
293 munmap(Base
, WorkSpace
);
295 delete [] (unsigned char *)Base
;
300 unsigned long long EndOfFile
= iSize
;
303 if(ftruncate(Fd
->Fd(),EndOfFile
) < 0)
304 _error
->Errno("ftruncate", _("Failed to truncate file"));
307 // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
308 // ---------------------------------------------------------------------
309 /* This allocates a block of memory aligned to the given size */
310 unsigned long DynamicMMap::RawAllocate(unsigned long long Size
,unsigned long Aln
)
312 unsigned long long Result
= iSize
;
314 Result
+= Aln
- (iSize%Aln
);
316 iSize
= Result
+ Size
;
318 // try to grow the buffer
319 while(Result
+ Size
> WorkSpace
)
323 _error
->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
324 "of APT::Cache-Limit. Current value: %lu. (man 5 apt.conf)"), WorkSpace
);
331 // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
332 // ---------------------------------------------------------------------
333 /* This allocates an Item of size ItemSize so that it is aligned to its
335 unsigned long DynamicMMap::Allocate(unsigned long ItemSize
)
337 // Look for a matching pool entry
340 for (I
= Pools
; I
!= Pools
+ PoolCount
; ++I
)
342 if (I
->ItemSize
== 0)
344 if (I
->ItemSize
== ItemSize
)
347 // No pool is allocated, use an unallocated one
348 if (I
== Pools
+ PoolCount
)
350 // Woops, we ran out, the calling code should allocate more.
353 _error
->Error("Ran out of allocation pools");
358 I
->ItemSize
= ItemSize
;
362 unsigned long Result
= 0;
363 // Out of space, allocate some more
366 const unsigned long size
= 20*1024;
367 I
->Count
= size
/ItemSize
;
368 Pool
* oldPools
= Pools
;
369 Result
= RawAllocate(size
,ItemSize
);
370 if (Pools
!= oldPools
)
371 I
+= Pools
- oldPools
;
373 // Does the allocation failed ?
374 if (Result
== 0 && _error
->PendingError())
382 I
->Start
+= ItemSize
;
383 return Result
/ItemSize
;
386 // DynamicMMap::WriteString - Write a string to the file /*{{{*/
387 // ---------------------------------------------------------------------
388 /* Strings are not aligned to anything */
389 unsigned long DynamicMMap::WriteString(const char *String
,
392 if (Len
== (unsigned long)-1)
393 Len
= strlen(String
);
395 unsigned long const Result
= RawAllocate(Len
+1,0);
397 if (Result
== 0 && _error
->PendingError())
400 memcpy((char *)Base
+ Result
,String
,Len
);
401 ((char *)Base
)[Result
+ Len
] = 0;
405 // DynamicMMap::Grow - Grow the mmap /*{{{*/
406 // ---------------------------------------------------------------------
407 /* This method is a wrapper around different methods to (try to) grow
408 a mmap (or our char[]-fallback). Encounterable environments:
409 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
410 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
411 3. Moveable + Fallback -> realloc
412 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
413 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
414 6. !Moveable + Fallback -> not possible
415 [ While Moveable and Fallback stands for the equally named flags and
416 "linux" indicates a linux kernel instead of a freebsd kernel. ]
417 So what you can see here is, that a MMAP which want to be growable need
418 to be moveable to have a real chance but that this method will at least try
419 the nearly impossible 4 to grow it before it finally give up: Never say never. */
420 bool DynamicMMap::Grow() {
421 if (Limit
!= 0 && WorkSpace
>= Limit
)
422 return _error
->Error(_("Unable to increase the size of the MMap as the "
423 "limit of %lu bytes is already reached."), Limit
);
425 return _error
->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
427 unsigned long long const newSize
= WorkSpace
+ GrowFactor
;
430 Fd
->Seek(newSize
- 1);
432 Fd
->Write(&C
,sizeof(C
));
435 unsigned long const poolOffset
= Pools
- ((Pool
*) Base
);
437 if ((Flags
& Fallback
) != Fallback
) {
438 #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
439 #ifdef MREMAP_MAYMOVE
441 if ((Flags
& Moveable
) == Moveable
)
442 Base
= mremap(Base
, WorkSpace
, newSize
, MREMAP_MAYMOVE
);
445 Base
= mremap(Base
, WorkSpace
, newSize
, 0);
447 if(Base
== MAP_FAILED
)
453 if ((Flags
& Moveable
) != Moveable
)
456 Base
= realloc(Base
, newSize
);
461 Pools
=(Pool
*) Base
+ poolOffset
;