xref: /sqlite-3.40.0/src/mem3.c (revision cd7274ce)
1 /*
2 ** 2007 October 14
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains the C functions that implement a memory
13 ** allocation subsystem for use by SQLite.
14 **
15 ** This version of the memory allocation subsystem omits all
16 ** use of malloc().  All dynamically allocatable memory is
17 ** contained in a static array, mem.aPool[].  The size of this
18 ** fixed memory pool is SQLITE_MEMORY_SIZE bytes.
19 **
20 ** This version of the memory allocation subsystem is used if
21 ** and only if SQLITE_MEMORY_SIZE is defined.
22 **
23 ** $Id: mem3.c,v 1.6 2007/11/07 15:13:25 drh Exp $
24 */
25 
26 /*
27 ** This version of the memory allocator is used only when
28 ** SQLITE_MEMORY_SIZE is defined.
29 */
30 #if defined(SQLITE_MEMORY_SIZE)
31 #include "sqliteInt.h"
32 
33 /*
34 ** Maximum size (in Mem3Blocks) of a "small" chunk.
35 */
36 #define MX_SMALL 10
37 
38 
39 /*
40 ** Number of freelist hash slots
41 */
42 #define N_HASH  61
43 
44 /*
45 ** A memory allocation (also called a "chunk") consists of two or
46 ** more blocks where each block is 8 bytes.  The first 8 bytes are
47 ** a header that is not returned to the user.
48 **
49 ** A chunk is two or more blocks that is either checked out or
50 ** free.  The first block has format u.hdr.  u.hdr.size is the
51 ** size of the allocation in blocks if the allocation is free.
52 ** If the allocation is checked out, u.hdr.size is the negative
53 ** of the size.  Similarly, u.hdr.prevSize is the size of the
54 ** immediately previous allocation.
55 **
56 ** We often identify a chunk by its index in mem.aPool[].  When
57 ** this is done, the chunk index refers to the second block of
58 ** the chunk.  In this way, the first chunk has an index of 1.
59 ** A chunk index of 0 means "no such chunk" and is the equivalent
60 ** of a NULL pointer.
61 **
62 ** The second block of free chunks is of the form u.list.  The
63 ** two fields form a double-linked list of chunks of related sizes.
64 ** Pointers to the head of the list are stored in mem.aiSmall[]
65 ** for smaller chunks and mem.aiHash[] for larger chunks.
66 **
67 ** The second block of a chunk is user data if the chunk is checked
68 ** out.
69 */
70 typedef struct Mem3Block Mem3Block;
71 struct Mem3Block {
72   union {
73     struct {
74       int prevSize;   /* Size of previous chunk in Mem3Block elements */
75       int size;       /* Size of current chunk in Mem3Block elements */
76     } hdr;
77     struct {
78       int next;       /* Index in mem.aPool[] of next free chunk */
79       int prev;       /* Index in mem.aPool[] of previous free chunk */
80     } list;
81   } u;
82 };
83 
84 /*
85 ** All of the static variables used by this module are collected
86 ** into a single structure named "mem".  This is to keep the
87 ** static variables organized and to reduce namespace pollution
88 ** when this module is combined with other in the amalgamation.
89 */
90 static struct {
91   /*
92   ** True if we are evaluating an out-of-memory callback.
93   */
94   int alarmBusy;
95 
96   /*
97   ** Mutex to control access to the memory allocation subsystem.
98   */
99   sqlite3_mutex *mutex;
100 
101   /*
102   ** The minimum amount of free space that we have seen.
103   */
104   int mnMaster;
105 
106   /*
107   ** iMaster is the index of the master chunk.  Most new allocations
108   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
109   ** of the current master.  iMaster is 0 if there is not master chunk.
110   ** The master chunk is not in either the aiHash[] or aiSmall[].
111   */
112   int iMaster;
113   int szMaster;
114 
115   /*
116   ** Array of lists of free blocks according to the block size
117   ** for smaller chunks, or a hash on the block size for larger
118   ** chunks.
119   */
120   int aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
121   int aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
122 
123   /*
124   ** Memory available for allocation
125   */
126   Mem3Block aPool[SQLITE_MEMORY_SIZE/sizeof(Mem3Block)+2];
127 } mem;
128 
129 /*
130 ** Unlink the chunk at mem.aPool[i] from list it is currently
131 ** on.  *pRoot is the list that i is a member of.
132 */
133 static void memsys3UnlinkFromList(int i, int *pRoot){
134   int next = mem.aPool[i].u.list.next;
135   int prev = mem.aPool[i].u.list.prev;
136   assert( sqlite3_mutex_held(mem.mutex) );
137   if( prev==0 ){
138     *pRoot = next;
139   }else{
140     mem.aPool[prev].u.list.next = next;
141   }
142   if( next ){
143     mem.aPool[next].u.list.prev = prev;
144   }
145   mem.aPool[i].u.list.next = 0;
146   mem.aPool[i].u.list.prev = 0;
147 }
148 
149 /*
150 ** Unlink the chunk at index i from
151 ** whatever list is currently a member of.
152 */
153 static void memsys3Unlink(int i){
154   int size, hash;
155   assert( sqlite3_mutex_held(mem.mutex) );
156   size = mem.aPool[i-1].u.hdr.size;
157   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
158   assert( size>=2 );
159   if( size <= MX_SMALL ){
160     memsys3UnlinkFromList(i, &mem.aiSmall[size-2]);
161   }else{
162     hash = size % N_HASH;
163     memsys3UnlinkFromList(i, &mem.aiHash[hash]);
164   }
165 }
166 
167 /*
168 ** Link the chunk at mem.aPool[i] so that is on the list rooted
169 ** at *pRoot.
170 */
171 static void memsys3LinkIntoList(int i, int *pRoot){
172   assert( sqlite3_mutex_held(mem.mutex) );
173   mem.aPool[i].u.list.next = *pRoot;
174   mem.aPool[i].u.list.prev = 0;
175   if( *pRoot ){
176     mem.aPool[*pRoot].u.list.prev = i;
177   }
178   *pRoot = i;
179 }
180 
181 /*
182 ** Link the chunk at index i into either the appropriate
183 ** small chunk list, or into the large chunk hash table.
184 */
185 static void memsys3Link(int i){
186   int size, hash;
187   assert( sqlite3_mutex_held(mem.mutex) );
188   size = mem.aPool[i-1].u.hdr.size;
189   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
190   assert( size>=2 );
191   if( size <= MX_SMALL ){
192     memsys3LinkIntoList(i, &mem.aiSmall[size-2]);
193   }else{
194     hash = size % N_HASH;
195     memsys3LinkIntoList(i, &mem.aiHash[hash]);
196   }
197 }
198 
199 /*
200 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
201 **
202 ** Also:  Initialize the memory allocation subsystem the first time
203 ** this routine is called.
204 */
205 static void memsys3Enter(void){
206   if( mem.mutex==0 ){
207     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
208     mem.aPool[0].u.hdr.size = SQLITE_MEMORY_SIZE/8;
209     mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.prevSize = SQLITE_MEMORY_SIZE/8;
210     mem.iMaster = 1;
211     mem.szMaster = SQLITE_MEMORY_SIZE/8;
212     mem.mnMaster = mem.szMaster;
213   }
214   sqlite3_mutex_enter(mem.mutex);
215 }
216 
217 /*
218 ** Return the amount of memory currently checked out.
219 */
220 sqlite3_int64 sqlite3_memory_used(void){
221   sqlite3_int64 n;
222   memsys3Enter();
223   n = SQLITE_MEMORY_SIZE - mem.szMaster*8;
224   sqlite3_mutex_leave(mem.mutex);
225   return n;
226 }
227 
228 /*
229 ** Return the maximum amount of memory that has ever been
230 ** checked out since either the beginning of this process
231 ** or since the most recent reset.
232 */
233 sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
234   sqlite3_int64 n;
235   memsys3Enter();
236   n = SQLITE_MEMORY_SIZE - mem.mnMaster*8;
237   if( resetFlag ){
238     mem.mnMaster = mem.szMaster;
239   }
240   sqlite3_mutex_leave(mem.mutex);
241   return n;
242 }
243 
244 /*
245 ** Change the alarm callback.
246 **
247 ** This is a no-op for the static memory allocator.  The purpose
248 ** of the memory alarm is to support sqlite3_soft_heap_limit().
249 ** But with this memory allocator, the soft_heap_limit is really
250 ** a hard limit that is fixed at SQLITE_MEMORY_SIZE.
251 */
252 int sqlite3_memory_alarm(
253   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
254   void *pArg,
255   sqlite3_int64 iThreshold
256 ){
257   return SQLITE_OK;
258 }
259 
260 /*
261 ** Called when we are unable to satisfy an allocation of nBytes.
262 */
263 static void memsys3OutOfMemory(int nByte){
264   if( !mem.alarmBusy ){
265     mem.alarmBusy = 1;
266     assert( sqlite3_mutex_held(mem.mutex) );
267     sqlite3_mutex_leave(mem.mutex);
268     sqlite3_release_memory(nByte);
269     sqlite3_mutex_enter(mem.mutex);
270     mem.alarmBusy = 0;
271   }
272 }
273 
274 /*
275 ** Return the size of an outstanding allocation, in bytes.  The
276 ** size returned omits the 8-byte header overhead.  This only
277 ** works for chunks that are currently checked out.
278 */
279 static int memsys3Size(void *p){
280   Mem3Block *pBlock = (Mem3Block*)p;
281   assert( pBlock[-1].u.hdr.size<0 );
282   return (-1-pBlock[-1].u.hdr.size)*8;
283 }
284 
285 /*
286 ** Chunk i is a free chunk that has been unlinked.  Adjust its
287 ** size parameters for check-out and return a pointer to the
288 ** user portion of the chunk.
289 */
290 static void *memsys3Checkout(int i, int nBlock){
291   assert( sqlite3_mutex_held(mem.mutex) );
292   assert( mem.aPool[i-1].u.hdr.size==nBlock );
293   assert( mem.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
294   mem.aPool[i-1].u.hdr.size = -nBlock;
295   mem.aPool[i+nBlock-1].u.hdr.prevSize = -nBlock;
296   return &mem.aPool[i];
297 }
298 
299 /*
300 ** Carve a piece off of the end of the mem.iMaster free chunk.
301 ** Return a pointer to the new allocation.  Or, if the master chunk
302 ** is not large enough, return 0.
303 */
304 static void *memsys3FromMaster(int nBlock){
305   assert( sqlite3_mutex_held(mem.mutex) );
306   assert( mem.szMaster>=nBlock );
307   if( nBlock>=mem.szMaster-1 ){
308     /* Use the entire master */
309     void *p = memsys3Checkout(mem.iMaster, mem.szMaster);
310     mem.iMaster = 0;
311     mem.szMaster = 0;
312     mem.mnMaster = 0;
313     return p;
314   }else{
315     /* Split the master block.  Return the tail. */
316     int newi;
317     newi = mem.iMaster + mem.szMaster - nBlock;
318     assert( newi > mem.iMaster+1 );
319     mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = -nBlock;
320     mem.aPool[newi-1].u.hdr.size = -nBlock;
321     mem.szMaster -= nBlock;
322     mem.aPool[newi-1].u.hdr.prevSize = mem.szMaster;
323     mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster;
324     if( mem.szMaster < mem.mnMaster ){
325       mem.mnMaster = mem.szMaster;
326     }
327     return (void*)&mem.aPool[newi];
328   }
329 }
330 
331 /*
332 ** *pRoot is the head of a list of free chunks of the same size
333 ** or same size hash.  In other words, *pRoot is an entry in either
334 ** mem.aiSmall[] or mem.aiHash[].
335 **
336 ** This routine examines all entries on the given list and tries
337 ** to coalesce each entries with adjacent free chunks.
338 **
339 ** If it sees a chunk that is larger than mem.iMaster, it replaces
340 ** the current mem.iMaster with the new larger chunk.  In order for
341 ** this mem.iMaster replacement to work, the master chunk must be
342 ** linked into the hash tables.  That is not the normal state of
343 ** affairs, of course.  The calling routine must link the master
344 ** chunk before invoking this routine, then must unlink the (possibly
345 ** changed) master chunk once this routine has finished.
346 */
347 static void memsys3Merge(int *pRoot){
348   int iNext, prev, size, i;
349 
350   assert( sqlite3_mutex_held(mem.mutex) );
351   for(i=*pRoot; i>0; i=iNext){
352     iNext = mem.aPool[i].u.list.next;
353     size = mem.aPool[i-1].u.hdr.size;
354     assert( size>0 );
355     if( mem.aPool[i-1].u.hdr.prevSize>0 ){
356       memsys3UnlinkFromList(i, pRoot);
357       prev = i - mem.aPool[i-1].u.hdr.prevSize;
358       assert( prev>=0 );
359       if( prev==iNext ){
360         iNext = mem.aPool[prev].u.list.next;
361       }
362       memsys3Unlink(prev);
363       size = i + size - prev;
364       mem.aPool[prev-1].u.hdr.size = size;
365       mem.aPool[prev+size-1].u.hdr.prevSize = size;
366       memsys3Link(prev);
367       i = prev;
368     }
369     if( size>mem.szMaster ){
370       mem.iMaster = i;
371       mem.szMaster = size;
372     }
373   }
374 }
375 
376 /*
377 ** Return a block of memory of at least nBytes in size.
378 ** Return NULL if unable.
379 */
380 static void *memsys3Malloc(int nByte){
381   int i;
382   int nBlock;
383   int toFree;
384 
385   assert( sqlite3_mutex_held(mem.mutex) );
386   assert( sizeof(Mem3Block)==8 );
387   if( nByte<=0 ){
388     nBlock = 2;
389   }else{
390     nBlock = (nByte + 15)/8;
391   }
392   assert( nBlock >= 2 );
393 
394   /* STEP 1:
395   ** Look for an entry of the correct size in either the small
396   ** chunk table or in the large chunk hash table.  This is
397   ** successful most of the time (about 9 times out of 10).
398   */
399   if( nBlock <= MX_SMALL ){
400     i = mem.aiSmall[nBlock-2];
401     if( i>0 ){
402       memsys3UnlinkFromList(i, &mem.aiSmall[nBlock-2]);
403       return memsys3Checkout(i, nBlock);
404     }
405   }else{
406     int hash = nBlock % N_HASH;
407     for(i=mem.aiHash[hash]; i>0; i=mem.aPool[i].u.list.next){
408       if( mem.aPool[i-1].u.hdr.size==nBlock ){
409         memsys3UnlinkFromList(i, &mem.aiHash[hash]);
410         return memsys3Checkout(i, nBlock);
411       }
412     }
413   }
414 
415   /* STEP 2:
416   ** Try to satisfy the allocation by carving a piece off of the end
417   ** of the master chunk.  This step usually works if step 1 fails.
418   */
419   if( mem.szMaster>=nBlock ){
420     return memsys3FromMaster(nBlock);
421   }
422 
423 
424   /* STEP 3:
425   ** Loop through the entire memory pool.  Coalesce adjacent free
426   ** chunks.  Recompute the master chunk as the largest free chunk.
427   ** Then try again to satisfy the allocation by carving a piece off
428   ** of the end of the master chunk.  This step happens very
429   ** rarely (we hope!)
430   */
431   for(toFree=nBlock*16; toFree<SQLITE_MEMORY_SIZE*2; toFree *= 2){
432     memsys3OutOfMemory(toFree);
433     if( mem.iMaster ){
434       memsys3Link(mem.iMaster);
435       mem.iMaster = 0;
436       mem.szMaster = 0;
437     }
438     for(i=0; i<N_HASH; i++){
439       memsys3Merge(&mem.aiHash[i]);
440     }
441     for(i=0; i<MX_SMALL-1; i++){
442       memsys3Merge(&mem.aiSmall[i]);
443     }
444     if( mem.szMaster ){
445       memsys3Unlink(mem.iMaster);
446       if( mem.szMaster>=nBlock ){
447         return memsys3FromMaster(nBlock);
448       }
449     }
450   }
451 
452   /* If none of the above worked, then we fail. */
453   return 0;
454 }
455 
456 /*
457 ** Free an outstanding memory allocation.
458 */
459 void memsys3Free(void *pOld){
460   Mem3Block *p = (Mem3Block*)pOld;
461   int i;
462   int size;
463   assert( sqlite3_mutex_held(mem.mutex) );
464   assert( p>mem.aPool && p<&mem.aPool[SQLITE_MEMORY_SIZE/8] );
465   i = p - mem.aPool;
466   size = -mem.aPool[i-1].u.hdr.size;
467   assert( size>=2 );
468   assert( mem.aPool[i+size-1].u.hdr.prevSize==-size );
469   mem.aPool[i-1].u.hdr.size = size;
470   mem.aPool[i+size-1].u.hdr.prevSize = size;
471   memsys3Link(i);
472 
473   /* Try to expand the master using the newly freed chunk */
474   if( mem.iMaster ){
475     while( mem.aPool[mem.iMaster-1].u.hdr.prevSize>0 ){
476       size = mem.aPool[mem.iMaster-1].u.hdr.prevSize;
477       mem.iMaster -= size;
478       mem.szMaster += size;
479       memsys3Unlink(mem.iMaster);
480       mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster;
481       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
482     }
483     while( mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size>0 ){
484       memsys3Unlink(mem.iMaster+mem.szMaster);
485       mem.szMaster += mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size;
486       mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster;
487       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
488     }
489   }
490 }
491 
492 /*
493 ** Allocate nBytes of memory
494 */
495 void *sqlite3_malloc(int nBytes){
496   sqlite3_int64 *p = 0;
497   if( nBytes>0 ){
498     memsys3Enter();
499     p = memsys3Malloc(nBytes);
500     sqlite3_mutex_leave(mem.mutex);
501   }
502   return (void*)p;
503 }
504 
505 /*
506 ** Free memory.
507 */
508 void sqlite3_free(void *pPrior){
509   if( pPrior==0 ){
510     return;
511   }
512   assert( mem.mutex!=0 );
513   sqlite3_mutex_enter(mem.mutex);
514   memsys3Free(pPrior);
515   sqlite3_mutex_leave(mem.mutex);
516 }
517 
518 /*
519 ** Change the size of an existing memory allocation
520 */
521 void *sqlite3_realloc(void *pPrior, int nBytes){
522   int nOld;
523   void *p;
524   if( pPrior==0 ){
525     return sqlite3_malloc(nBytes);
526   }
527   if( nBytes<=0 ){
528     sqlite3_free(pPrior);
529     return 0;
530   }
531   assert( mem.mutex!=0 );
532   nOld = memsys3Size(pPrior);
533   if( nBytes<=nOld && nBytes>=nOld-128 ){
534     return pPrior;
535   }
536   sqlite3_mutex_enter(mem.mutex);
537   p = memsys3Malloc(nBytes);
538   if( p ){
539     if( nOld<nBytes ){
540       memcpy(p, pPrior, nOld);
541     }else{
542       memcpy(p, pPrior, nBytes);
543     }
544     memsys3Free(pPrior);
545   }
546   sqlite3_mutex_leave(mem.mutex);
547   return p;
548 }
549 
550 /*
551 ** Open the file indicated and write a log of all unfreed memory
552 ** allocations into that log.
553 */
554 void sqlite3_memdebug_dump(const char *zFilename){
555 #ifdef SQLITE_DEBUG
556   FILE *out;
557   int i, j, size;
558   if( zFilename==0 || zFilename[0]==0 ){
559     out = stdout;
560   }else{
561     out = fopen(zFilename, "w");
562     if( out==0 ){
563       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
564                       zFilename);
565       return;
566     }
567   }
568   memsys3Enter();
569   fprintf(out, "CHUNKS:\n");
570   for(i=1; i<=SQLITE_MEMORY_SIZE/8; i+=size){
571     size = mem.aPool[i-1].u.hdr.size;
572     if( size>=-1 && size<=1 ){
573       fprintf(out, "%p size error\n", &mem.aPool[i]);
574       assert( 0 );
575       break;
576     }
577     if( mem.aPool[i+(size<0?-size:size)-1].u.hdr.prevSize!=size ){
578       fprintf(out, "%p tail size does not match\n", &mem.aPool[i]);
579       assert( 0 );
580       break;
581     }
582     if( size<0 ){
583       size = -size;
584       fprintf(out, "%p %6d bytes checked out\n", &mem.aPool[i], size*8-8);
585     }else{
586       fprintf(out, "%p %6d bytes free%s\n", &mem.aPool[i], size*8-8,
587                   i==mem.iMaster ? " **master**" : "");
588     }
589   }
590   for(i=0; i<MX_SMALL-1; i++){
591     if( mem.aiSmall[i]==0 ) continue;
592     fprintf(out, "small(%2d):", i);
593     for(j = mem.aiSmall[i]; j>0; j=mem.aPool[j].u.list.next){
594       fprintf(out, " %p(%d)", &mem.aPool[j], mem.aPool[j-1].u.hdr.size*8-8);
595     }
596     fprintf(out, "\n");
597   }
598   for(i=0; i<N_HASH; i++){
599     if( mem.aiHash[i]==0 ) continue;
600     fprintf(out, "hash(%2d):", i);
601     for(j = mem.aiHash[i]; j>0; j=mem.aPool[j].u.list.next){
602       fprintf(out, " %p(%d)", &mem.aPool[j], mem.aPool[j-1].u.hdr.size*8-8);
603     }
604     fprintf(out, "\n");
605   }
606   fprintf(out, "master=%d\n", mem.iMaster);
607   fprintf(out, "nowUsed=%d\n", SQLITE_MEMORY_SIZE - mem.szMaster*8);
608   fprintf(out, "mxUsed=%d\n", SQLITE_MEMORY_SIZE - mem.mnMaster*8);
609   sqlite3_mutex_leave(mem.mutex);
610   if( out==stdout ){
611     fflush(stdout);
612   }else{
613     fclose(out);
614   }
615 #endif
616 }
617 
618 
619 #endif /* !SQLITE_MEMORY_SIZE */
620