blob: 633e1202e3b4311c1b47e89cdaf225e70e63b9f4 [file] [log] [blame]
danielk1977bc2ca9e2008-11-13 14:28:28 +00001/*
2** 2008 November 05
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**
13** This file implements the default page cache implementation (the
14** sqlite3_pcache interface). It also contains part of the implementation
15** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
16** If the default page cache implementation is overriden, then neither of
17** these two features are available.
danielk1977bc2ca9e2008-11-13 14:28:28 +000018*/
19
20#include "sqliteInt.h"
21
22typedef struct PCache1 PCache1;
23typedef struct PgHdr1 PgHdr1;
24typedef struct PgFreeslot PgFreeslot;
25
drh9d13f112010-08-24 18:06:35 +000026/* Each page cache is an instance of the following object. Every
27** open database file (including each in-memory database and each
28** temporary or transient database) has a single page cache which
29** is an instance of this object.
30**
31** Pointers to structures of this type are cast and returned as
32** opaque sqlite3_pcache* handles.
danielk1977bc2ca9e2008-11-13 14:28:28 +000033*/
34struct PCache1 {
35 /* Cache configuration parameters. Page size (szPage) and the purgeable
36 ** flag (bPurgeable) are set when the cache is created. nMax may be
37 ** modified at any time by a call to the pcache1CacheSize() method.
38 ** The global mutex must be held when accessing nMax.
39 */
40 int szPage; /* Size of allocated pages in bytes */
41 int bPurgeable; /* True if cache is purgeable */
danielk197744cd45c2008-11-15 11:22:45 +000042 unsigned int nMin; /* Minimum number of pages reserved */
43 unsigned int nMax; /* Configured "cache_size" value */
danielk1977bc2ca9e2008-11-13 14:28:28 +000044
45 /* Hash table of all pages. The following variables may only be accessed
46 ** when the accessor is holding the global mutex (see pcache1EnterMutex()
47 ** and pcache1LeaveMutex()).
48 */
danielk197744cd45c2008-11-15 11:22:45 +000049 unsigned int nRecyclable; /* Number of pages in the LRU list */
50 unsigned int nPage; /* Total number of pages in apHash */
51 unsigned int nHash; /* Number of slots in apHash[] */
danielk1977bc2ca9e2008-11-13 14:28:28 +000052 PgHdr1 **apHash; /* Hash table for fast lookup by key */
danielk1977f90b7262009-01-07 15:18:20 +000053
54 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
danielk1977bc2ca9e2008-11-13 14:28:28 +000055};
56
57/*
58** Each cache entry is represented by an instance of the following
59** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
drh69e931e2009-06-03 21:04:35 +000060** directly before this structure in memory (see the PGHDR1_TO_PAGE()
danielk1977bc2ca9e2008-11-13 14:28:28 +000061** macro below).
62*/
63struct PgHdr1 {
64 unsigned int iKey; /* Key value (page number) */
65 PgHdr1 *pNext; /* Next in hash table chain */
66 PCache1 *pCache; /* Cache that currently owns this page */
67 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
68 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
69};
70
71/*
72** Free slots in the allocator used to divide up the buffer provided using
73** the SQLITE_CONFIG_PAGECACHE mechanism.
74*/
75struct PgFreeslot {
76 PgFreeslot *pNext; /* Next free slot */
77};
78
79/*
80** Global data used by this cache.
81*/
82static SQLITE_WSD struct PCacheGlobal {
83 sqlite3_mutex *mutex; /* static mutex MUTEX_STATIC_LRU */
84
85 int nMaxPage; /* Sum of nMaxPage for purgeable caches */
86 int nMinPage; /* Sum of nMinPage for purgeable caches */
87 int nCurrentPage; /* Number of purgeable pages allocated */
88 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
89
90 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
91 int szSlot; /* Size of each free slot */
drh50d1b5f2010-08-27 12:21:06 +000092 int nSlot; /* The number of pcache slots */
93 int nFreeSlot; /* Number of unused pcache slots */
94 int nReserve; /* Try to keep nFreeSlot above this */
danielk1977bc2ca9e2008-11-13 14:28:28 +000095 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
96 PgFreeslot *pFree; /* Free page blocks */
drhf4622dc2009-05-22 11:10:24 +000097 int isInit; /* True if initialized */
danielk197744cd45c2008-11-15 11:22:45 +000098} pcache1_g;
danielk1977bc2ca9e2008-11-13 14:28:28 +000099
100/*
101** All code in this file should access the global structure above via the
102** alias "pcache1". This ensures that the WSD emulation is used when
103** compiling for systems that do not support real WSD.
104*/
105#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
106
107/*
108** When a PgHdr1 structure is allocated, the associated PCache1.szPage
drh69e931e2009-06-03 21:04:35 +0000109** bytes of data are located directly before it in memory (i.e. the total
danielk1977bc2ca9e2008-11-13 14:28:28 +0000110** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
111** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
112** an argument and returns a pointer to the associated block of szPage
113** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
114** a pointer to a block of szPage bytes of data and the return value is
115** a pointer to the associated PgHdr1 structure.
116**
drh69e931e2009-06-03 21:04:35 +0000117** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000118*/
drh69e931e2009-06-03 21:04:35 +0000119#define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage)
120#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
danielk1977bc2ca9e2008-11-13 14:28:28 +0000121
122/*
123** Macros to enter and leave the global LRU mutex.
124*/
125#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
126#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
127
128/******************************************************************************/
129/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
130
131/*
132** This function is called during initialization if a static buffer is
133** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
134** verb to sqlite3_config(). Parameter pBuf points to an allocation large
135** enough to contain 'n' buffers of 'sz' bytes each.
136*/
137void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
drhf4622dc2009-05-22 11:10:24 +0000138 if( pcache1.isInit ){
139 PgFreeslot *p;
140 sz = ROUNDDOWN8(sz);
141 pcache1.szSlot = sz;
drh50d1b5f2010-08-27 12:21:06 +0000142 pcache1.nSlot = pcache1.nFreeSlot = n;
143 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
drhf4622dc2009-05-22 11:10:24 +0000144 pcache1.pStart = pBuf;
145 pcache1.pFree = 0;
146 while( n-- ){
147 p = (PgFreeslot*)pBuf;
148 p->pNext = pcache1.pFree;
149 pcache1.pFree = p;
150 pBuf = (void*)&((char*)pBuf)[sz];
151 }
152 pcache1.pEnd = pBuf;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000153 }
danielk1977bc2ca9e2008-11-13 14:28:28 +0000154}
155
156/*
157** Malloc function used within this file to allocate space from the buffer
158** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
159** such buffer exists or there is no space left in it, this function falls
160** back to sqlite3Malloc().
161*/
162static void *pcache1Alloc(int nByte){
163 void *p;
164 assert( sqlite3_mutex_held(pcache1.mutex) );
drh29dfbe32010-07-28 17:01:24 +0000165 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
danielk1977bc2ca9e2008-11-13 14:28:28 +0000166 if( nByte<=pcache1.szSlot && pcache1.pFree ){
drhdd1f4322009-05-22 11:12:23 +0000167 assert( pcache1.isInit );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000168 p = (PgHdr1 *)pcache1.pFree;
169 pcache1.pFree = pcache1.pFree->pNext;
drh50d1b5f2010-08-27 12:21:06 +0000170 pcache1.nFreeSlot--;
171 assert( pcache1.nFreeSlot>=0 );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000172 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
173 }else{
174
175 /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
176 ** global pcache mutex and unlock the pager-cache object pCache. This is
177 ** so that if the attempt to allocate a new buffer causes the the
178 ** configured soft-heap-limit to be breached, it will be possible to
179 ** reclaim memory from this pager-cache.
180 */
181 pcache1LeaveMutex();
182 p = sqlite3Malloc(nByte);
183 pcache1EnterMutex();
184 if( p ){
185 int sz = sqlite3MallocSize(p);
186 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
187 }
drh107b56e2010-03-12 16:32:53 +0000188 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
danielk1977bc2ca9e2008-11-13 14:28:28 +0000189 }
190 return p;
191}
192
193/*
194** Free an allocated buffer obtained from pcache1Alloc().
195*/
196static void pcache1Free(void *p){
197 assert( sqlite3_mutex_held(pcache1.mutex) );
198 if( p==0 ) return;
199 if( p>=pcache1.pStart && p<pcache1.pEnd ){
200 PgFreeslot *pSlot;
201 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
202 pSlot = (PgFreeslot*)p;
203 pSlot->pNext = pcache1.pFree;
204 pcache1.pFree = pSlot;
drh50d1b5f2010-08-27 12:21:06 +0000205 pcache1.nFreeSlot++;
206 assert( pcache1.nFreeSlot<=pcache1.nSlot );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000207 }else{
drh107b56e2010-03-12 16:32:53 +0000208 int iSize;
209 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
210 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
211 iSize = sqlite3MallocSize(p);
danielk1977bc2ca9e2008-11-13 14:28:28 +0000212 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
213 sqlite3_free(p);
214 }
215}
216
drhc8f503a2010-08-20 09:14:13 +0000217#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
218/*
drh9d13f112010-08-24 18:06:35 +0000219** Return the size of a pcache allocation
drhc8f503a2010-08-20 09:14:13 +0000220*/
221static int pcache1MemSize(void *p){
222 assert( sqlite3_mutex_held(pcache1.mutex) );
223 if( p>=pcache1.pStart && p<pcache1.pEnd ){
224 return pcache1.szSlot;
225 }else{
226 int iSize;
227 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
228 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
229 iSize = sqlite3MallocSize(p);
230 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
231 return iSize;
232 }
233}
234#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
235
danielk1977bc2ca9e2008-11-13 14:28:28 +0000236/*
237** Allocate a new page object initially associated with cache pCache.
238*/
239static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
240 int nByte = sizeof(PgHdr1) + pCache->szPage;
drh69e931e2009-06-03 21:04:35 +0000241 void *pPg = pcache1Alloc(nByte);
242 PgHdr1 *p;
243 if( pPg ){
244 p = PAGE_TO_PGHDR1(pCache, pPg);
danielk1977bc2ca9e2008-11-13 14:28:28 +0000245 if( pCache->bPurgeable ){
246 pcache1.nCurrentPage++;
247 }
drh69e931e2009-06-03 21:04:35 +0000248 }else{
249 p = 0;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000250 }
251 return p;
252}
253
254/*
255** Free a page object allocated by pcache1AllocPage().
drhf18a61d2009-07-17 11:44:07 +0000256**
257** The pointer is allowed to be NULL, which is prudent. But it turns out
258** that the current implementation happens to never call this routine
259** with a NULL pointer, so we mark the NULL test with ALWAYS().
danielk1977bc2ca9e2008-11-13 14:28:28 +0000260*/
261static void pcache1FreePage(PgHdr1 *p){
drhf18a61d2009-07-17 11:44:07 +0000262 if( ALWAYS(p) ){
danielk1977bc2ca9e2008-11-13 14:28:28 +0000263 if( p->pCache->bPurgeable ){
264 pcache1.nCurrentPage--;
265 }
drh69e931e2009-06-03 21:04:35 +0000266 pcache1Free(PGHDR1_TO_PAGE(p));
danielk1977bc2ca9e2008-11-13 14:28:28 +0000267 }
268}
269
270/*
271** Malloc function used by SQLite to obtain space from the buffer configured
272** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
273** exists, this function falls back to sqlite3Malloc().
274*/
275void *sqlite3PageMalloc(int sz){
276 void *p;
277 pcache1EnterMutex();
278 p = pcache1Alloc(sz);
279 pcache1LeaveMutex();
280 return p;
281}
282
283/*
284** Free an allocated buffer obtained from sqlite3PageMalloc().
285*/
286void sqlite3PageFree(void *p){
287 pcache1EnterMutex();
288 pcache1Free(p);
289 pcache1LeaveMutex();
290}
291
drh50d1b5f2010-08-27 12:21:06 +0000292
293/*
294** Return true if it desirable to avoid allocating a new page cache
295** entry.
296**
297** If memory was allocated specifically to the page cache using
298** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
299** it is desirable to avoid allocating a new page cache entry because
300** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
301** for all page cache needs and we should not need to spill the
302** allocation onto the heap.
303**
304** Or, the heap is used for all page cache memory put the heap is
305** under memory pressure, then again it is desirable to avoid
306** allocating a new page cache entry in order to avoid stressing
307** the heap even further.
308*/
309static int pcache1UnderMemoryPressure(PCache1 *pCache){
310 assert( sqlite3_mutex_held(pcache1.mutex) );
311 if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
312 return pcache1.nFreeSlot<pcache1.nReserve;
313 }else{
314 return sqlite3HeapNearlyFull();
315 }
316}
317
danielk1977bc2ca9e2008-11-13 14:28:28 +0000318/******************************************************************************/
319/******** General Implementation Functions ************************************/
320
321/*
322** This function is used to resize the hash table used by the cache passed
323** as the first argument.
324**
325** The global mutex must be held when this function is called.
326*/
327static int pcache1ResizeHash(PCache1 *p){
328 PgHdr1 **apNew;
danielk197744cd45c2008-11-15 11:22:45 +0000329 unsigned int nNew;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000330 unsigned int i;
331
332 assert( sqlite3_mutex_held(pcache1.mutex) );
333
334 nNew = p->nHash*2;
335 if( nNew<256 ){
336 nNew = 256;
337 }
338
339 pcache1LeaveMutex();
drh085bb7f2008-12-06 14:34:33 +0000340 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
danielk1977bc2ca9e2008-11-13 14:28:28 +0000341 apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
drh085bb7f2008-12-06 14:34:33 +0000342 if( p->nHash ){ sqlite3EndBenignMalloc(); }
danielk1977bc2ca9e2008-11-13 14:28:28 +0000343 pcache1EnterMutex();
344 if( apNew ){
345 memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
346 for(i=0; i<p->nHash; i++){
347 PgHdr1 *pPage;
348 PgHdr1 *pNext = p->apHash[i];
drhb27b7f52008-12-10 18:03:45 +0000349 while( (pPage = pNext)!=0 ){
danielk1977bc2ca9e2008-11-13 14:28:28 +0000350 unsigned int h = pPage->iKey % nNew;
351 pNext = pPage->pNext;
352 pPage->pNext = apNew[h];
353 apNew[h] = pPage;
354 }
355 }
356 sqlite3_free(p->apHash);
357 p->apHash = apNew;
358 p->nHash = nNew;
359 }
360
361 return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
362}
363
364/*
365** This function is used internally to remove the page pPage from the
366** global LRU list, if is part of it. If pPage is not part of the global
367** LRU list, then this function is a no-op.
368**
369** The global mutex must be held when this function is called.
370*/
371static void pcache1PinPage(PgHdr1 *pPage){
372 assert( sqlite3_mutex_held(pcache1.mutex) );
373 if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
374 if( pPage->pLruPrev ){
375 pPage->pLruPrev->pLruNext = pPage->pLruNext;
376 }
377 if( pPage->pLruNext ){
378 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
379 }
380 if( pcache1.pLruHead==pPage ){
381 pcache1.pLruHead = pPage->pLruNext;
382 }
383 if( pcache1.pLruTail==pPage ){
384 pcache1.pLruTail = pPage->pLruPrev;
385 }
386 pPage->pLruNext = 0;
387 pPage->pLruPrev = 0;
388 pPage->pCache->nRecyclable--;
389 }
390}
391
392
393/*
394** Remove the page supplied as an argument from the hash table
395** (PCache1.apHash structure) that it is currently stored in.
396**
397** The global mutex must be held when this function is called.
398*/
399static void pcache1RemoveFromHash(PgHdr1 *pPage){
400 unsigned int h;
401 PCache1 *pCache = pPage->pCache;
402 PgHdr1 **pp;
403
404 h = pPage->iKey % pCache->nHash;
405 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
406 *pp = (*pp)->pNext;
407
408 pCache->nPage--;
409}
410
411/*
412** If there are currently more than pcache.nMaxPage pages allocated, try
413** to recycle pages to reduce the number allocated to pcache.nMaxPage.
414*/
415static void pcache1EnforceMaxPage(void){
416 assert( sqlite3_mutex_held(pcache1.mutex) );
417 while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
418 PgHdr1 *p = pcache1.pLruTail;
419 pcache1PinPage(p);
420 pcache1RemoveFromHash(p);
421 pcache1FreePage(p);
422 }
423}
424
425/*
426** Discard all pages from cache pCache with a page number (key value)
427** greater than or equal to iLimit. Any pinned pages that meet this
428** criteria are unpinned before they are discarded.
429**
430** The global mutex must be held when this function is called.
431*/
432static void pcache1TruncateUnsafe(
433 PCache1 *pCache,
434 unsigned int iLimit
435){
shane75ac1de2009-06-09 18:58:52 +0000436 TESTONLY( unsigned int nPage = 0; ) /* Used to assert pCache->nPage is correct */
danielk1977bc2ca9e2008-11-13 14:28:28 +0000437 unsigned int h;
438 assert( sqlite3_mutex_held(pcache1.mutex) );
439 for(h=0; h<pCache->nHash; h++){
440 PgHdr1 **pp = &pCache->apHash[h];
441 PgHdr1 *pPage;
drhb27b7f52008-12-10 18:03:45 +0000442 while( (pPage = *pp)!=0 ){
danielk1977bc2ca9e2008-11-13 14:28:28 +0000443 if( pPage->iKey>=iLimit ){
danielk1977ea24ac42009-05-08 06:52:47 +0000444 pCache->nPage--;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000445 *pp = pPage->pNext;
danielk1977ea24ac42009-05-08 06:52:47 +0000446 pcache1PinPage(pPage);
danielk1977bc2ca9e2008-11-13 14:28:28 +0000447 pcache1FreePage(pPage);
448 }else{
449 pp = &pPage->pNext;
danielk1977ea24ac42009-05-08 06:52:47 +0000450 TESTONLY( nPage++; )
danielk1977bc2ca9e2008-11-13 14:28:28 +0000451 }
452 }
453 }
danielk1977ea24ac42009-05-08 06:52:47 +0000454 assert( pCache->nPage==nPage );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000455}
456
457/******************************************************************************/
458/******** sqlite3_pcache Methods **********************************************/
459
460/*
461** Implementation of the sqlite3_pcache.xInit method.
462*/
danielk197762c14b32008-11-19 09:05:26 +0000463static int pcache1Init(void *NotUsed){
464 UNUSED_PARAMETER(NotUsed);
drhf4622dc2009-05-22 11:10:24 +0000465 assert( pcache1.isInit==0 );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000466 memset(&pcache1, 0, sizeof(pcache1));
467 if( sqlite3GlobalConfig.bCoreMutex ){
468 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
469 }
drhf4622dc2009-05-22 11:10:24 +0000470 pcache1.isInit = 1;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000471 return SQLITE_OK;
472}
473
474/*
475** Implementation of the sqlite3_pcache.xShutdown method.
shane7c7c3112009-08-17 15:31:23 +0000476** Note that the static mutex allocated in xInit does
477** not need to be freed.
danielk1977bc2ca9e2008-11-13 14:28:28 +0000478*/
danielk197762c14b32008-11-19 09:05:26 +0000479static void pcache1Shutdown(void *NotUsed){
480 UNUSED_PARAMETER(NotUsed);
drhf4622dc2009-05-22 11:10:24 +0000481 assert( pcache1.isInit!=0 );
drhb0937192009-05-22 10:53:29 +0000482 memset(&pcache1, 0, sizeof(pcache1));
danielk1977bc2ca9e2008-11-13 14:28:28 +0000483}
484
485/*
486** Implementation of the sqlite3_pcache.xCreate method.
487**
488** Allocate a new cache.
489*/
490static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
491 PCache1 *pCache;
492
493 pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
494 if( pCache ){
495 memset(pCache, 0, sizeof(PCache1));
496 pCache->szPage = szPage;
497 pCache->bPurgeable = (bPurgeable ? 1 : 0);
498 if( bPurgeable ){
499 pCache->nMin = 10;
500 pcache1EnterMutex();
501 pcache1.nMinPage += pCache->nMin;
502 pcache1LeaveMutex();
503 }
504 }
505 return (sqlite3_pcache *)pCache;
506}
507
508/*
509** Implementation of the sqlite3_pcache.xCachesize method.
510**
511** Configure the cache_size limit for a cache.
512*/
513static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
514 PCache1 *pCache = (PCache1 *)p;
515 if( pCache->bPurgeable ){
516 pcache1EnterMutex();
517 pcache1.nMaxPage += (nMax - pCache->nMax);
518 pCache->nMax = nMax;
519 pcache1EnforceMaxPage();
520 pcache1LeaveMutex();
521 }
522}
523
524/*
525** Implementation of the sqlite3_pcache.xPagecount method.
526*/
527static int pcache1Pagecount(sqlite3_pcache *p){
528 int n;
529 pcache1EnterMutex();
530 n = ((PCache1 *)p)->nPage;
531 pcache1LeaveMutex();
532 return n;
533}
534
535/*
536** Implementation of the sqlite3_pcache.xFetch method.
537**
538** Fetch a page by key value.
539**
540** Whether or not a new page may be allocated by this function depends on
drhf18a61d2009-07-17 11:44:07 +0000541** the value of the createFlag argument. 0 means do not allocate a new
542** page. 1 means allocate a new page if space is easily available. 2
543** means to try really hard to allocate a new page.
544**
545** For a non-purgeable cache (a cache used as the storage for an in-memory
546** database) there is really no difference between createFlag 1 and 2. So
547** the calling function (pcache.c) will never have a createFlag of 1 on
548** a non-purgable cache.
danielk1977bc2ca9e2008-11-13 14:28:28 +0000549**
550** There are three different approaches to obtaining space for a page,
551** depending on the value of parameter createFlag (which may be 0, 1 or 2).
552**
553** 1. Regardless of the value of createFlag, the cache is searched for a
554** copy of the requested page. If one is found, it is returned.
555**
556** 2. If createFlag==0 and the page is not already in the cache, NULL is
557** returned.
558**
drh50d1b5f2010-08-27 12:21:06 +0000559** 3. If createFlag is 1, and the page is not already in the cache, then
560** return NULL (do not allocate a new page) if any of the following
561** conditions are true:
danielk1977bc2ca9e2008-11-13 14:28:28 +0000562**
563** (a) the number of pages pinned by the cache is greater than
564** PCache1.nMax, or
drh50d1b5f2010-08-27 12:21:06 +0000565**
danielk1977bc2ca9e2008-11-13 14:28:28 +0000566** (b) the number of pages pinned by the cache is greater than
567** the sum of nMax for all purgeable caches, less the sum of
drh50d1b5f2010-08-27 12:21:06 +0000568** nMin for all other purgeable caches, or
danielk1977bc2ca9e2008-11-13 14:28:28 +0000569**
570** 4. If none of the first three conditions apply and the cache is marked
571** as purgeable, and if one of the following is true:
572**
573** (a) The number of pages allocated for the cache is already
574** PCache1.nMax, or
575**
576** (b) The number of pages allocated for all purgeable caches is
577** already equal to or greater than the sum of nMax for all
578** purgeable caches,
579**
drh50d1b5f2010-08-27 12:21:06 +0000580** (c) The system is under memory pressure and wants to avoid
581** unnecessary pages cache entry allocations
582**
danielk1977bc2ca9e2008-11-13 14:28:28 +0000583** then attempt to recycle a page from the LRU list. If it is the right
584** size, return the recycled buffer. Otherwise, free the buffer and
585** proceed to step 5.
586**
587** 5. Otherwise, allocate and return a new page buffer.
588*/
589static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
danielk197744cd45c2008-11-15 11:22:45 +0000590 unsigned int nPinned;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000591 PCache1 *pCache = (PCache1 *)p;
592 PgHdr1 *pPage = 0;
593
drhf18a61d2009-07-17 11:44:07 +0000594 assert( pCache->bPurgeable || createFlag!=1 );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000595 pcache1EnterMutex();
596 if( createFlag==1 ) sqlite3BeginBenignMalloc();
597
598 /* Search the hash table for an existing entry. */
599 if( pCache->nHash>0 ){
600 unsigned int h = iKey % pCache->nHash;
601 for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
602 }
603
604 if( pPage || createFlag==0 ){
605 pcache1PinPage(pPage);
606 goto fetch_out;
607 }
608
609 /* Step 3 of header comment. */
610 nPinned = pCache->nPage - pCache->nRecyclable;
drhf18a61d2009-07-17 11:44:07 +0000611 if( createFlag==1 && (
danielk1977bc2ca9e2008-11-13 14:28:28 +0000612 nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
danielk19776fa0fe12009-03-05 14:59:39 +0000613 || nPinned>=(pCache->nMax * 9 / 10)
drh50d1b5f2010-08-27 12:21:06 +0000614 || pcache1UnderMemoryPressure(pCache)
danielk1977bc2ca9e2008-11-13 14:28:28 +0000615 )){
616 goto fetch_out;
617 }
618
619 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
620 goto fetch_out;
621 }
622
623 /* Step 4. Try to recycle a page buffer if appropriate. */
624 if( pCache->bPurgeable && pcache1.pLruTail && (
drh50d1b5f2010-08-27 12:21:06 +0000625 (pCache->nPage+1>=pCache->nMax)
626 || pcache1.nCurrentPage>=pcache1.nMaxPage
627 || pcache1UnderMemoryPressure(pCache)
danielk1977bc2ca9e2008-11-13 14:28:28 +0000628 )){
629 pPage = pcache1.pLruTail;
630 pcache1RemoveFromHash(pPage);
631 pcache1PinPage(pPage);
632 if( pPage->pCache->szPage!=pCache->szPage ){
633 pcache1FreePage(pPage);
634 pPage = 0;
635 }else{
636 pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
637 }
638 }
639
640 /* Step 5. If a usable page buffer has still not been found,
641 ** attempt to allocate a new one.
642 */
643 if( !pPage ){
644 pPage = pcache1AllocPage(pCache);
645 }
646
647 if( pPage ){
648 unsigned int h = iKey % pCache->nHash;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000649 pCache->nPage++;
650 pPage->iKey = iKey;
651 pPage->pNext = pCache->apHash[h];
652 pPage->pCache = pCache;
danielk1977e1fd5082009-01-23 16:45:00 +0000653 pPage->pLruPrev = 0;
654 pPage->pLruNext = 0;
drh69e931e2009-06-03 21:04:35 +0000655 *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
danielk1977bc2ca9e2008-11-13 14:28:28 +0000656 pCache->apHash[h] = pPage;
657 }
658
659fetch_out:
danielk1977f90b7262009-01-07 15:18:20 +0000660 if( pPage && iKey>pCache->iMaxKey ){
661 pCache->iMaxKey = iKey;
662 }
danielk1977bc2ca9e2008-11-13 14:28:28 +0000663 if( createFlag==1 ) sqlite3EndBenignMalloc();
664 pcache1LeaveMutex();
665 return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
666}
667
668
669/*
670** Implementation of the sqlite3_pcache.xUnpin method.
671**
672** Mark a page as unpinned (eligible for asynchronous recycling).
673*/
674static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
675 PCache1 *pCache = (PCache1 *)p;
drh69e931e2009-06-03 21:04:35 +0000676 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
677
678 assert( pPage->pCache==pCache );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000679 pcache1EnterMutex();
680
681 /* It is an error to call this function if the page is already
682 ** part of the global LRU list.
683 */
684 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
685 assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
686
687 if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
688 pcache1RemoveFromHash(pPage);
689 pcache1FreePage(pPage);
690 }else{
691 /* Add the page to the global LRU list. Normally, the page is added to
692 ** the head of the list (last page to be recycled). However, if the
693 ** reuseUnlikely flag passed to this function is true, the page is added
694 ** to the tail of the list (first page to be recycled).
695 */
696 if( pcache1.pLruHead ){
697 pcache1.pLruHead->pLruPrev = pPage;
698 pPage->pLruNext = pcache1.pLruHead;
699 pcache1.pLruHead = pPage;
700 }else{
701 pcache1.pLruTail = pPage;
702 pcache1.pLruHead = pPage;
703 }
704 pCache->nRecyclable++;
705 }
706
707 pcache1LeaveMutex();
708}
709
710/*
711** Implementation of the sqlite3_pcache.xRekey method.
712*/
713static void pcache1Rekey(
714 sqlite3_pcache *p,
715 void *pPg,
716 unsigned int iOld,
717 unsigned int iNew
718){
719 PCache1 *pCache = (PCache1 *)p;
drh69e931e2009-06-03 21:04:35 +0000720 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
danielk1977bc2ca9e2008-11-13 14:28:28 +0000721 PgHdr1 **pp;
722 unsigned int h;
723 assert( pPage->iKey==iOld );
drh69e931e2009-06-03 21:04:35 +0000724 assert( pPage->pCache==pCache );
danielk1977bc2ca9e2008-11-13 14:28:28 +0000725
726 pcache1EnterMutex();
727
728 h = iOld%pCache->nHash;
729 pp = &pCache->apHash[h];
730 while( (*pp)!=pPage ){
731 pp = &(*pp)->pNext;
732 }
733 *pp = pPage->pNext;
734
735 h = iNew%pCache->nHash;
736 pPage->iKey = iNew;
737 pPage->pNext = pCache->apHash[h];
738 pCache->apHash[h] = pPage;
drh98829a62009-11-20 13:18:14 +0000739 if( iNew>pCache->iMaxKey ){
danielk1977f90b7262009-01-07 15:18:20 +0000740 pCache->iMaxKey = iNew;
741 }
742
danielk1977bc2ca9e2008-11-13 14:28:28 +0000743 pcache1LeaveMutex();
744}
745
746/*
747** Implementation of the sqlite3_pcache.xTruncate method.
748**
749** Discard all unpinned pages in the cache with a page number equal to
750** or greater than parameter iLimit. Any pinned pages with a page number
751** equal to or greater than iLimit are implicitly unpinned.
752*/
753static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
754 PCache1 *pCache = (PCache1 *)p;
755 pcache1EnterMutex();
danielk1977f90b7262009-01-07 15:18:20 +0000756 if( iLimit<=pCache->iMaxKey ){
757 pcache1TruncateUnsafe(pCache, iLimit);
758 pCache->iMaxKey = iLimit-1;
759 }
danielk1977bc2ca9e2008-11-13 14:28:28 +0000760 pcache1LeaveMutex();
761}
762
763/*
764** Implementation of the sqlite3_pcache.xDestroy method.
765**
766** Destroy a cache allocated using pcache1Create().
767*/
768static void pcache1Destroy(sqlite3_pcache *p){
769 PCache1 *pCache = (PCache1 *)p;
770 pcache1EnterMutex();
771 pcache1TruncateUnsafe(pCache, 0);
772 pcache1.nMaxPage -= pCache->nMax;
773 pcache1.nMinPage -= pCache->nMin;
774 pcache1EnforceMaxPage();
775 pcache1LeaveMutex();
776 sqlite3_free(pCache->apHash);
777 sqlite3_free(pCache);
778}
779
780/*
781** This function is called during initialization (sqlite3_initialize()) to
782** install the default pluggable cache module, assuming the user has not
783** already provided an alternative.
784*/
785void sqlite3PCacheSetDefault(void){
dan558814f2010-06-02 05:53:53 +0000786 static const sqlite3_pcache_methods defaultMethods = {
danielk1977bc2ca9e2008-11-13 14:28:28 +0000787 0, /* pArg */
788 pcache1Init, /* xInit */
789 pcache1Shutdown, /* xShutdown */
790 pcache1Create, /* xCreate */
791 pcache1Cachesize, /* xCachesize */
792 pcache1Pagecount, /* xPagecount */
793 pcache1Fetch, /* xFetch */
794 pcache1Unpin, /* xUnpin */
795 pcache1Rekey, /* xRekey */
796 pcache1Truncate, /* xTruncate */
797 pcache1Destroy /* xDestroy */
798 };
799 sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
800}
801
802#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
803/*
804** This function is called to free superfluous dynamically allocated memory
805** held by the pager system. Memory in use by any SQLite pager allocated
806** by the current thread may be sqlite3_free()ed.
807**
808** nReq is the number of bytes of memory required. Once this much has
809** been released, the function returns. The return value is the total number
810** of bytes of memory released.
811*/
812int sqlite3PcacheReleaseMemory(int nReq){
813 int nFree = 0;
814 if( pcache1.pStart==0 ){
815 PgHdr1 *p;
816 pcache1EnterMutex();
shanehbd2aaf92010-09-01 02:38:21 +0000817 while( (nReq<0 || nFree<nReq) && ((p=pcache1.pLruTail)!=0) ){
drhc8f503a2010-08-20 09:14:13 +0000818 nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
danielk1977bc2ca9e2008-11-13 14:28:28 +0000819 pcache1PinPage(p);
820 pcache1RemoveFromHash(p);
821 pcache1FreePage(p);
822 }
823 pcache1LeaveMutex();
824 }
825 return nFree;
826}
827#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
828
829#ifdef SQLITE_TEST
830/*
831** This function is used by test procedures to inspect the internal state
832** of the global cache.
833*/
834void sqlite3PcacheStats(
835 int *pnCurrent, /* OUT: Total number of pages cached */
836 int *pnMax, /* OUT: Global maximum cache size */
837 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
838 int *pnRecyclable /* OUT: Total number of pages available for recycling */
839){
840 PgHdr1 *p;
841 int nRecyclable = 0;
842 for(p=pcache1.pLruHead; p; p=p->pLruNext){
843 nRecyclable++;
844 }
845 *pnCurrent = pcache1.nCurrentPage;
846 *pnMax = pcache1.nMaxPage;
847 *pnMin = pcache1.nMinPage;
848 *pnRecyclable = nRecyclable;
849}
850#endif