interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / pcache1.c

1315 lines · 46437 bytes Raw Blame History
1/*
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 overridden, then neither of
17** these two features are available.
18**
19** A Page cache line looks like this:
20**
21** -------------------------------------------------------------
22** | database page content | PgHdr1 | MemPage | PgHdr |
23** -------------------------------------------------------------
24**
25** The database page content is up front (so that buffer overreads tend to
26** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
27** is the extension added by the btree.c module containing information such
28** as the database page number and how that database page is used. PgHdr
29** is added by the pcache.c layer and contains information used to keep track
30** of which pages are "dirty". PgHdr1 is an extension added by this
31** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
32** PgHdr1 contains information needed to look up a page by its page number.
33** The superclass sqlite3_pcache_page.pBuf points to the start of the
34** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
35**
36** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
37** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
38** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
39** size can vary according to architecture, compile-time options, and
40** SQLite library version number.
41**
42** Historical note: It used to be that if the SQLITE_PCACHE_SEPARATE_HEADER
43** was defined, then the page content would be held in a separate memory
44** allocation from the PgHdr1. This was intended to avoid clownshoe memory
45** allocations. However, the btree layer needs a small (16-byte) overrun
46** area after the page content buffer. The header serves as that overrun
47** area. Therefore SQLITE_PCACHE_SEPARATE_HEADER was discontinued to avoid
48** any possibility of a memory error.
49**
50** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
51** with this module. Information is passed back and forth as PgHdr1 pointers.
52**
53** The pcache.c and pager.c modules deal pointers to PgHdr objects.
54** The btree.c module deals with pointers to MemPage objects.
55**
56** SOURCE OF PAGE CACHE MEMORY:
57**
58** Memory for a page might come from any of three sources:
59**
60** (1) The general-purpose memory allocator - sqlite3Malloc()
61** (2) Global page-cache memory provided using sqlite3_config() with
62** SQLITE_CONFIG_PAGECACHE.
63** (3) PCache-local bulk allocation.
64**
65** The third case is a chunk of heap memory (defaulting to 100 pages worth)
66** that is allocated when the page cache is created. The size of the local
67** bulk allocation can be adjusted using
68**
69** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
70**
71** If N is positive, then N pages worth of memory are allocated using a single
72** sqlite3Malloc() call and that memory is used for the first N pages allocated.
73** Or if N is negative, then -1024*N bytes of memory are allocated and used
74** for as many pages as can be accommodated.
75**
76** Only one of (2) or (3) can be used. Once the memory available to (2) or
77** (3) is exhausted, subsequent allocations fail over to the general-purpose
78** memory allocator (1).
79**
80** Earlier versions of SQLite used only methods (1) and (2). But experiments
81** show that method (3) with N==100 provides about a 5% performance boost for
82** common workloads.
83*/
84#include "sqliteInt.h"
85
86typedef struct PCache1 PCache1;
87typedef struct PgHdr1 PgHdr1;
88typedef struct PgFreeslot PgFreeslot;
89typedef struct PGroup PGroup;
90
91/*
92** Each cache entry is represented by an instance of the following
93** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
94** directly before this structure and is used to cache the page content.
95**
96** When reading a corrupt database file, it is possible that SQLite might
97** read a few bytes (no more than 16 bytes) past the end of the page buffer.
98** It will only read past the end of the page buffer, never write. This
99** object is positioned immediately after the page buffer to serve as an
100** overrun area, so that overreads are harmless.
101**
102** Under some circumstances, using a strategically corrupt db file, one
103** or two varints may be read from past the end of the page buffer and
104** returned to the user (as rowid values). For this reason, we ensure that
105** the first few elements of PgHdr1 are not pointers. If they were, then
106** a determined attacker might be able to read the value of the pointer,
107** which can be used as part of a larger exploit. Furthermore, because the
108** first two elements of PgHdr1 are isBulkLocal and isAnchor - u16 variables
109** that always contain either 1 or 0 - the PgHdr1 structure always begins
110** with 4 bytes with the high-bit cleared, and so code attempting to read
111** varints can never progress past this point and read any more sensitive
112** information further inside the structure.
113**
114** Variables isBulkLocal and isAnchor were once type "u8". That works,
115** but causes a 2-byte gap in the structure for most architectures (since
116** pointers must be either 4 or 8-byte aligned). As this structure is located
117** in memory directly after the associated page data, if the database is
118** corrupt, code at the b-tree layer may overread the page buffer and
119** read part of this structure before the corruption is detected. This
120** can cause a valgrind error if the uninitialized gap is accessed. Using u16
121** ensures there is no such gap, and therefore no bytes of uninitialized
122** memory in the structure. Keeping the u16 type also lets isBulkLocal,
123** isAnchor and iKey fill exactly the 8 bytes (2+2+4) that precede the
124** 8-byte-aligned "page" member, so no uninitialized padding is exposed to
125** an overread.
126**
127** The pLruNext and pLruPrev pointers form a double-linked circular list
128** of all pages that are unpinned. The PGroup.lru element (which should be
129** the only element on the list with PgHdr1.isAnchor set to 1) forms the
130** beginning and the end of the list.
131*/
132struct PgHdr1 {
133 u16 isBulkLocal; /* This page from bulk local storage */
134 u16 isAnchor; /* This is the PGroup.lru element */
135 unsigned int iKey; /* Key value (page number) */
136 sqlite3_pcache_page page; /* Base class. pBuf & pExtra. Deliberately not the
137 ** first member - see the note above. */
138 PgHdr1 *pNext; /* Next in hash table chain */
139 PCache1 *pCache; /* Cache that currently owns this page */
140 PgHdr1 *pLruNext; /* Next in circular LRU list of unpinned pages */
141 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
142 /* NB: pLruPrev is only valid if pLruNext!=0 */
143};
144
145/*
146** Given the sqlite3_pcache_page object handed out to the pcache.c layer,
147** recover the PgHdr1 that contains it. PgHdr1.page is no longer required to
148** be the first member of PgHdr1, so this goes through the "page" member
149** rather than casting the structure pointer. The fetch methods produce the
150** other direction directly with &pPage->page, only on paths where pPage is
151** known to be non-NULL. PAGE_TO_PGHDR1() is likewise only ever given a
152** non-NULL page that this module previously handed out.
153*/
154#define PAGE_TO_PGHDR1(pPg) \
155 ((PgHdr1*)(((char*)(pPg)) - offsetof(PgHdr1,page)))
156
157/*
158** A page is pinned if it is not on the LRU list. To be "pinned" means
159** that the page is in active use and must not be deallocated.
160*/
161#define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
162#define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
163
164/* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
165** of one or more PCaches that are able to recycle each other's unpinned
166** pages when they are under memory pressure. A PGroup is an instance of
167** the following object.
168**
169** This page cache implementation works in one of two modes:
170**
171** (1) Every PCache is the sole member of its own PGroup. There is
172** one PGroup per PCache.
173**
174** (2) There is a single global PGroup that all PCaches are a member
175** of.
176**
177** Mode 1 uses more memory (since PCache instances are not able to rob
178** unused pages from other PCaches) but it also operates without a mutex,
179** and is therefore often faster. Mode 2 requires a mutex in order to be
180** threadsafe, but recycles pages more efficiently.
181**
182** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
183** PGroup which is the pcache1.grp global variable and its mutex is
184** SQLITE_MUTEX_STATIC_LRU.
185*/
186struct PGroup {
187 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
188 unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
189 unsigned int nMinPage; /* Sum of nMin for purgeable caches */
190 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
191 unsigned int nPurgeable; /* Number of purgeable pages allocated */
192 PgHdr1 lru; /* The beginning and end of the LRU list */
193};
194
195/* Each page cache is an instance of the following object. Every
196** open database file (including each in-memory database and each
197** temporary or transient database) has a single page cache which
198** is an instance of this object.
199**
200** Pointers to structures of this type are cast and returned as
201** opaque sqlite3_pcache* handles.
202*/
203struct PCache1 {
204 /* Cache configuration parameters. Page size (szPage) and the purgeable
205 ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
206 ** cache is created and are never changed thereafter. nMax may be
207 ** modified at any time by a call to the pcache1Cachesize() method.
208 ** The PGroup mutex must be held when accessing nMax.
209 */
210 PGroup *pGroup; /* PGroup this cache belongs to */
211 unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
212 int szPage; /* Size of database content section */
213 int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
214 int szAlloc; /* Total size of one pcache line */
215 int bPurgeable; /* True if cache is purgeable */
216 unsigned int nMin; /* Minimum number of pages reserved */
217 unsigned int nMax; /* Configured "cache_size" value */
218 unsigned int n90pct; /* nMax*9/10 */
219 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
220 unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/
221
222 /* Hash table of all pages. The following variables may only be accessed
223 ** when the accessor is holding the PGroup mutex.
224 */
225 unsigned int nRecyclable; /* Number of pages in the LRU list */
226 unsigned int nPage; /* Total number of pages in apHash */
227 unsigned int nHash; /* Number of slots in apHash[] */
228 PgHdr1 **apHash; /* Hash table for fast lookup by key */
229 PgHdr1 *pFree; /* List of unused pcache-local pages */
230 void *pBulk; /* Bulk memory used by pcache-local */
231};
232
233/*
234** Free slots in the allocator used to divide up the global page cache
235** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
236*/
237struct PgFreeslot {
238 PgFreeslot *pNext; /* Next free slot */
239};
240
241/*
242** Global data used by this cache.
243*/
244static SQLITE_WSD struct PCacheGlobal {
245 PGroup grp; /* The global PGroup for mode (2) */
246
247 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
248 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
249 ** fixed at sqlite3_initialize() time and do not require mutex protection.
250 ** The nFreeSlot and pFree values do require mutex protection.
251 */
252 int isInit; /* True if initialized */
253 int separateCache; /* Use a new PGroup for each PCache */
254 int nInitPage; /* Initial bulk allocation size */
255 int szSlot; /* Size of each free slot */
256 int nSlot; /* The number of pcache slots */
257 int nReserve; /* Try to keep nFreeSlot above this */
258 void *pStart, *pEnd; /* Bounds of global page cache memory */
259 /* Above requires no mutex. Use mutex below for variable that follow. */
260 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
261 PgFreeslot *pFree; /* Free page blocks */
262 int nFreeSlot; /* Number of unused pcache slots */
263 int bUnderPressure; /* True if low on PAGECACHE memory */
264} pcache1_g;
265
266/*
267** All code in this file should access the global structure above via the
268** alias "pcache1". This ensures that the WSD emulation is used when
269** compiling for systems that do not support real WSD.
270*/
271#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
272
273/*
274** Macros to enter and leave the PCache LRU mutex.
275*/
276#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
277# define pcache1EnterMutex(X) assert((X)->mutex==0)
278# define pcache1LeaveMutex(X) assert((X)->mutex==0)
279# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
280#else
281# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
282# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
283# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
284#endif
285
286/******************************************************************************/
287/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
288
289
290/*
291** This function is called during initialization if a static buffer is
292** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
293** verb to sqlite3_config(). Parameter pBuf points to an allocation large
294** enough to contain 'n' buffers of 'sz' bytes each.
295**
296** This routine is called from sqlite3_initialize() and so it is guaranteed
297** to be serialized already. There is no need for further mutexing.
298*/
299void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
300 if( pcache1.isInit ){
301 PgFreeslot *p;
302 if( pBuf==0 ) sz = n = 0;
303 if( n==0 ) sz = 0;
304 sz = ROUNDDOWN8(sz);
305 pcache1.szSlot = sz;
306 pcache1.nSlot = pcache1.nFreeSlot = n;
307 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
308 pcache1.pStart = pBuf;
309 pcache1.pFree = 0;
310 AtomicStore(&pcache1.bUnderPressure,0);
311 while( n-- ){
312 p = (PgFreeslot*)pBuf;
313 p->pNext = pcache1.pFree;
314 pcache1.pFree = p;
315 pBuf = (void*)&((char*)pBuf)[sz];
316 }
317 pcache1.pEnd = pBuf;
318 }
319}
320
321/*
322** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
323** true if pCache->pFree ends up containing one or more free pages.
324*/
325static int pcache1InitBulk(PCache1 *pCache){
326 i64 szBulk;
327 char *zBulk;
328 if( pcache1.nInitPage==0 ) return 0;
329 /* Do not bother with a bulk allocation if the cache size very small */
330 if( pCache->nMax<3 ) return 0;
331 sqlite3BeginBenignMalloc();
332 if( pcache1.nInitPage>0 ){
333 szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
334 }else{
335 szBulk = -1024 * (i64)pcache1.nInitPage;
336 }
337 if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
338 szBulk = pCache->szAlloc*(i64)pCache->nMax;
339 }
340 if( szBulk>=pCache->szAlloc ){
341 zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
342 sqlite3EndBenignMalloc();
343 if( zBulk ){
344 int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
345 do{
346 PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
347 pX->page.pBuf = zBulk;
348 pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX));
349 assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) );
350 pX->isBulkLocal = 1;
351 pX->isAnchor = 0;
352 pX->pNext = pCache->pFree;
353 pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
354 pCache->pFree = pX;
355 zBulk += pCache->szAlloc;
356 }while( --nBulk );
357 }
358 }
359 return pCache->pFree!=0;
360}
361
362/*
363** Malloc function used within this file to allocate space from the buffer
364** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
365** such buffer exists or there is no space left in it, this function falls
366** back to sqlite3Malloc().
367**
368** Multiple threads can run this routine at the same time. Global variables
369** in pcache1 need to be protected via mutex.
370*/
371static void *pcache1Alloc(int nByte){
372 void *p = 0;
373 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
374 if( nByte<=pcache1.szSlot ){
375 sqlite3_mutex_enter(pcache1.mutex);
376 p = (PgHdr1 *)pcache1.pFree;
377 if( p ){
378 pcache1.pFree = pcache1.pFree->pNext;
379 pcache1.nFreeSlot--;
380 AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve);
381 assert( pcache1.nFreeSlot>=0 );
382 sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
383 sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
384 }
385 sqlite3_mutex_leave(pcache1.mutex);
386 }
387 if( p==0 ){
388 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
389 ** it from sqlite3Malloc instead.
390 */
391 p = sqlite3Malloc(nByte);
392#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
393 if( p ){
394 int sz = sqlite3MallocSize(p);
395 sqlite3_mutex_enter(pcache1.mutex);
396 sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
397 sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
398 sqlite3_mutex_leave(pcache1.mutex);
399 }
400#endif
401 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
402 }
403 return p;
404}
405
406/*
407** Free an allocated buffer obtained from pcache1Alloc().
408*/
409static void pcache1Free(void *p){
410 if( p==0 ) return;
411 if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
412 PgFreeslot *pSlot;
413 sqlite3_mutex_enter(pcache1.mutex);
414 sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
415 pSlot = (PgFreeslot*)p;
416 pSlot->pNext = pcache1.pFree;
417 pcache1.pFree = pSlot;
418 pcache1.nFreeSlot++;
419 AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve);
420 assert( pcache1.nFreeSlot<=pcache1.nSlot );
421 sqlite3_mutex_leave(pcache1.mutex);
422 }else{
423 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
424 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
425#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
426 {
427 int nFreed = 0;
428 nFreed = sqlite3MallocSize(p);
429 sqlite3_mutex_enter(pcache1.mutex);
430 sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
431 sqlite3_mutex_leave(pcache1.mutex);
432 }
433#endif
434 sqlite3_free(p);
435 }
436}
437
438#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
439/*
440** Return the size of a pcache allocation
441*/
442static int pcache1MemSize(void *p){
443 if( p>=pcache1.pStart && p<pcache1.pEnd ){
444 return pcache1.szSlot;
445 }else{
446 int iSize;
447 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
448 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
449 iSize = sqlite3MallocSize(p);
450 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
451 return iSize;
452 }
453}
454#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
455
456/*
457** Allocate a new page object initially associated with cache pCache.
458*/
459static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
460 PgHdr1 *p = 0;
461 void *pPg;
462
463 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
464 if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
465 assert( pCache->pFree!=0 );
466 p = pCache->pFree;
467 pCache->pFree = p->pNext;
468 p->pNext = 0;
469 }else{
470#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
471 /* The group mutex must be released before pcache1Alloc() is called. This
472 ** is because it might call sqlite3_release_memory(), which assumes that
473 ** this mutex is not held. */
474 assert( pcache1.separateCache==0 );
475 assert( pCache->pGroup==&pcache1.grp );
476 pcache1LeaveMutex(pCache->pGroup);
477#endif
478 if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
479 pPg = pcache1Alloc(pCache->szAlloc);
480 if( benignMalloc ){ sqlite3EndBenignMalloc(); }
481#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
482 pcache1EnterMutex(pCache->pGroup);
483#endif
484 if( pPg==0 ) return 0;
485 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
486 p->page.pBuf = pPg;
487 p->page.pExtra = (u8*)p + ROUND8(sizeof(*p));
488 assert( EIGHT_BYTE_ALIGNMENT( p->page.pExtra ) );
489 p->isBulkLocal = 0;
490 p->isAnchor = 0;
491 p->pLruPrev = 0; /* Initializing this saves a valgrind error */
492 }
493 (*pCache->pnPurgeable)++;
494 return p;
495}
496
497/*
498** Free a page object allocated by pcache1AllocPage().
499*/
500static void pcache1FreePage(PgHdr1 *p){
501 PCache1 *pCache;
502 assert( p!=0 );
503 pCache = p->pCache;
504 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
505 if( p->isBulkLocal ){
506 p->pNext = pCache->pFree;
507 pCache->pFree = p;
508 }else{
509 pcache1Free(p->page.pBuf);
510 }
511 (*pCache->pnPurgeable)--;
512}
513
514/*
515** Malloc function used by SQLite to obtain space from the buffer configured
516** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
517** exists, this function falls back to sqlite3Malloc().
518*/
519void *sqlite3PageMalloc(int sz){
520 assert( sz<=65536+8 ); /* These allocations are never very large */
521 return pcache1Alloc(sz);
522}
523
524/*
525** Free an allocated buffer obtained from sqlite3PageMalloc().
526*/
527void sqlite3PageFree(void *p){
528 pcache1Free(p);
529}
530
531
532/*
533** Return true if it desirable to avoid allocating a new page cache
534** entry.
535**
536** If memory was allocated specifically to the page cache using
537** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
538** it is desirable to avoid allocating a new page cache entry because
539** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
540** for all page cache needs and we should not need to spill the
541** allocation onto the heap.
542**
543** Or, the heap is used for all page cache memory but the heap is
544** under memory pressure, then again it is desirable to avoid
545** allocating a new page cache entry in order to avoid stressing
546** the heap even further.
547*/
548static int pcache1UnderMemoryPressure(PCache1 *pCache){
549 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
550 return AtomicLoad(&pcache1.bUnderPressure);
551 }else{
552 return sqlite3HeapNearlyFull();
553 }
554}
555
556/******************************************************************************/
557/******** General Implementation Functions ************************************/
558
559/*
560** This function is used to resize the hash table used by the cache passed
561** as the first argument.
562**
563** The PCache mutex must be held when this function is called.
564*/
565static void pcache1ResizeHash(PCache1 *p){
566 PgHdr1 **apNew;
567 u64 nNew;
568 u32 i;
569
570 assert( sqlite3_mutex_held(p->pGroup->mutex) );
571
572 nNew = 2*(u64)p->nHash;
573 if( nNew<256 ){
574 nNew = 256;
575 }
576 assert( (nNew & (nNew-1))==0 ); /* nNew is always a power of two */
577
578 pcache1LeaveMutex(p->pGroup);
579 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
580 apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
581 if( p->nHash ){ sqlite3EndBenignMalloc(); }
582 pcache1EnterMutex(p->pGroup);
583 if( apNew ){
584 for(i=0; i<p->nHash; i++){
585 PgHdr1 *pPage;
586 PgHdr1 *pNext = p->apHash[i];
587 while( (pPage = pNext)!=0 ){
588 unsigned int h = (unsigned int)(pPage->iKey & (nNew-1));
589 pNext = pPage->pNext;
590 pPage->pNext = apNew[h];
591 apNew[h] = pPage;
592 }
593 }
594 sqlite3_free(p->apHash);
595 p->apHash = apNew;
596 p->nHash = nNew;
597 }
598}
599
600/*
601** This function is used internally to remove the page pPage from the
602** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
603** LRU list, then this function is a no-op.
604**
605** The PGroup mutex must be held when this function is called.
606*/
607static sqlite3_pcache_page *pcache1PinPage(PgHdr1 *pPage){
608 assert( pPage!=0 );
609 assert( PAGE_IS_UNPINNED(pPage) );
610 assert( pPage->pLruNext );
611 assert( pPage->pLruPrev );
612 assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
613 pPage->pLruPrev->pLruNext = pPage->pLruNext;
614 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
615 pPage->pLruNext = 0;
616 /* pPage->pLruPrev = 0;
617 ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
618 assert( pPage->isAnchor==0 );
619 assert( pPage->pCache->pGroup->lru.isAnchor==1 );
620 pPage->pCache->nRecyclable--;
621 return &pPage->page;
622}
623
624
625/*
626** Remove the page supplied as an argument from the hash table
627** (PCache1.apHash structure) that it is currently stored in.
628** Also free the page if freePage is true.
629**
630** The PGroup mutex must be held when this function is called.
631*/
632static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
633 unsigned int h;
634 PCache1 *pCache = pPage->pCache;
635 PgHdr1 **pp;
636
637 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
638 assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 );
639 h = pPage->iKey & (pCache->nHash-1);
640 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
641 *pp = (*pp)->pNext;
642
643 pCache->nPage--;
644 if( freeFlag ) pcache1FreePage(pPage);
645}
646
647/*
648** If there are currently more than nMaxPage pages allocated, try
649** to recycle pages to reduce the number allocated to nMaxPage.
650*/
651static void pcache1EnforceMaxPage(PCache1 *pCache){
652 PGroup *pGroup = pCache->pGroup;
653 PgHdr1 *p;
654 assert( sqlite3_mutex_held(pGroup->mutex) );
655 while( pGroup->nPurgeable>pGroup->nMaxPage
656 && (p=pGroup->lru.pLruPrev)->isAnchor==0
657 ){
658 assert( p->pCache->pGroup==pGroup );
659 assert( PAGE_IS_UNPINNED(p) );
660 pcache1PinPage(p);
661 pcache1RemoveFromHash(p, 1);
662 }
663 if( pCache->nPage==0 && pCache->pBulk ){
664 sqlite3_free(pCache->pBulk);
665 pCache->pBulk = pCache->pFree = 0;
666 }
667}
668
669/*
670** Discard all pages from cache pCache with a page number (key value)
671** greater than or equal to iLimit. Any pinned pages that meet this
672** criteria are unpinned before they are discarded.
673**
674** The PCache mutex must be held when this function is called.
675*/
676static void pcache1TruncateUnsafe(
677 PCache1 *pCache, /* The cache to truncate */
678 unsigned int iLimit /* Drop pages with this pgno or larger */
679){
680 TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
681 unsigned int h, iStop;
682 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
683 assert( pCache->iMaxKey >= iLimit );
684 assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 );
685 if( pCache->iMaxKey - iLimit < pCache->nHash ){
686 /* If we are just shaving the last few pages off the end of the
687 ** cache, then there is no point in scanning the entire hash table.
688 ** Only scan those hash slots that might contain pages that need to
689 ** be removed. */
690 h = iLimit & (pCache->nHash-1);
691 iStop = pCache->iMaxKey & (pCache->nHash-1);
692 TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
693 }else{
694 /* This is the general case where many pages are being removed.
695 ** It is necessary to scan the entire hash table */
696 h = pCache->nHash/2;
697 iStop = h - 1;
698 }
699 for(;;){
700 PgHdr1 **pp;
701 PgHdr1 *pPage;
702 assert( h<pCache->nHash );
703 pp = &pCache->apHash[h];
704 while( (pPage = *pp)!=0 ){
705 if( pPage->iKey>=iLimit ){
706 pCache->nPage--;
707 *pp = pPage->pNext;
708 if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
709 pcache1FreePage(pPage);
710 }else{
711 pp = &pPage->pNext;
712 TESTONLY( if( nPage>=0 ) nPage++; )
713 }
714 }
715 if( h==iStop ) break;
716 h = (h+1) & (pCache->nHash-1);
717 }
718 assert( nPage<0 || pCache->nPage==(unsigned)nPage );
719}
720
721/******************************************************************************/
722/******** sqlite3_pcache Methods **********************************************/
723
724/*
725** Implementation of the sqlite3_pcache.xInit method.
726*/
727static int pcache1Init(void *NotUsed){
728 UNUSED_PARAMETER(NotUsed);
729 assert( pcache1.isInit==0 );
730 memset(&pcache1, 0, sizeof(pcache1));
731
732
733 /*
734 ** The pcache1.separateCache variable is true if each PCache has its own
735 ** private PGroup (mode-1). pcache1.separateCache is false if the single
736 ** PGroup in pcache1.grp is used for all page caches (mode-2).
737 **
738 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
739 **
740 ** * Use a unified cache in single-threaded applications that have
741 ** configured a start-time buffer for use as page-cache memory using
742 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
743 ** pBuf argument.
744 **
745 ** * Otherwise use separate caches (mode-1)
746 */
747#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
748 pcache1.separateCache = 0;
749#elif SQLITE_THREADSAFE
750 pcache1.separateCache = sqlite3GlobalConfig.pPage==0
751 || sqlite3GlobalConfig.bCoreMutex>0;
752#else
753 pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
754#endif
755
756#if SQLITE_THREADSAFE
757 if( sqlite3GlobalConfig.bCoreMutex ){
758 pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
759 pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
760 }
761#endif
762 if( pcache1.separateCache
763 && sqlite3GlobalConfig.nPage!=0
764 && sqlite3GlobalConfig.pPage==0
765 ){
766 pcache1.nInitPage = sqlite3GlobalConfig.nPage;
767 }else{
768 pcache1.nInitPage = 0;
769 }
770 pcache1.grp.mxPinned = 10;
771 pcache1.isInit = 1;
772 return SQLITE_OK;
773}
774
775/*
776** Implementation of the sqlite3_pcache.xShutdown method.
777** Note that the static mutex allocated in xInit does
778** not need to be freed.
779*/
780static void pcache1Shutdown(void *NotUsed){
781 UNUSED_PARAMETER(NotUsed);
782 assert( pcache1.isInit!=0 );
783 memset(&pcache1, 0, sizeof(pcache1));
784}
785
786/* forward declaration */
787static void pcache1Destroy(sqlite3_pcache *p);
788
789/*
790** Implementation of the sqlite3_pcache.xCreate method.
791**
792** Allocate a new cache.
793*/
794static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
795 PCache1 *pCache; /* The newly created page cache */
796 PGroup *pGroup; /* The group the new page cache will belong to */
797 i64 sz; /* Bytes of memory required to allocate the new cache */
798
799 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
800 assert( szExtra < 300 );
801
802 sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
803 pCache = (PCache1 *)sqlite3MallocZero(sz);
804 if( pCache ){
805 if( pcache1.separateCache ){
806 pGroup = (PGroup*)&pCache[1];
807 pGroup->mxPinned = 10;
808 }else{
809 pGroup = &pcache1.grp;
810 }
811 pcache1EnterMutex(pGroup);
812 if( pGroup->lru.isAnchor==0 ){
813 pGroup->lru.isAnchor = 1;
814 pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
815 }
816 pCache->pGroup = pGroup;
817 pCache->szPage = szPage;
818 pCache->szExtra = szExtra;
819 pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
820 pCache->bPurgeable = (bPurgeable ? 1 : 0);
821 pcache1ResizeHash(pCache);
822 if( bPurgeable ){
823 pCache->nMin = 10;
824 pGroup->nMinPage += pCache->nMin;
825 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
826 pCache->pnPurgeable = &pGroup->nPurgeable;
827 }else{
828 pCache->pnPurgeable = &pCache->nPurgeableDummy;
829 }
830 pcache1LeaveMutex(pGroup);
831 if( pCache->nHash==0 ){
832 pcache1Destroy((sqlite3_pcache*)pCache);
833 pCache = 0;
834 }
835 }
836 return (sqlite3_pcache *)pCache;
837}
838
839/*
840** Implementation of the sqlite3_pcache.xCachesize method.
841**
842** Configure the cache_size limit for a cache.
843*/
844static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
845 PCache1 *pCache = (PCache1 *)p;
846 u32 n;
847 assert( nMax>=0 );
848 if( pCache->bPurgeable ){
849 PGroup *pGroup = pCache->pGroup;
850 pcache1EnterMutex(pGroup);
851 n = (u32)nMax;
852 if( n > 0x7fff0000 - pGroup->nMaxPage + pCache->nMax ){
853 n = 0x7fff0000 - pGroup->nMaxPage + pCache->nMax;
854 }
855 pGroup->nMaxPage += (n - pCache->nMax);
856 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
857 pCache->nMax = n;
858 pCache->n90pct = pCache->nMax*9/10;
859 pcache1EnforceMaxPage(pCache);
860 pcache1LeaveMutex(pGroup);
861 }
862}
863
864/*
865** Implementation of the sqlite3_pcache.xShrink method.
866**
867** Free up as much memory as possible.
868*/
869static void pcache1Shrink(sqlite3_pcache *p){
870 PCache1 *pCache = (PCache1*)p;
871 if( pCache->bPurgeable ){
872 PGroup *pGroup = pCache->pGroup;
873 unsigned int savedMaxPage;
874 pcache1EnterMutex(pGroup);
875 savedMaxPage = pGroup->nMaxPage;
876 pGroup->nMaxPage = 0;
877 pcache1EnforceMaxPage(pCache);
878 pGroup->nMaxPage = savedMaxPage;
879 pcache1LeaveMutex(pGroup);
880 }
881}
882
883/*
884** Implementation of the sqlite3_pcache.xPagecount method.
885*/
886static int pcache1Pagecount(sqlite3_pcache *p){
887 int n;
888 PCache1 *pCache = (PCache1*)p;
889 pcache1EnterMutex(pCache->pGroup);
890 n = pCache->nPage;
891 pcache1LeaveMutex(pCache->pGroup);
892 return n;
893}
894
895
896/*
897** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
898** in the header of the pcache1Fetch() procedure.
899**
900** This steps are broken out into a separate procedure because they are
901** usually not needed, and by avoiding the stack initialization required
902** for these steps, the main pcache1Fetch() procedure can run faster.
903*/
904static SQLITE_NOINLINE sqlite3_pcache_page *pcache1FetchStage2(
905 PCache1 *pCache,
906 unsigned int iKey,
907 int createFlag
908){
909 unsigned int nPinned;
910 PGroup *pGroup = pCache->pGroup;
911 PgHdr1 *pPage = 0;
912
913 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
914 assert( pCache->nPage >= pCache->nRecyclable );
915 nPinned = pCache->nPage - pCache->nRecyclable;
916 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
917 assert( pCache->n90pct == pCache->nMax*9/10 );
918 if( createFlag==1 && (
919 nPinned>=pGroup->mxPinned
920 || nPinned>=pCache->n90pct
921 || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
922 )){
923 return 0;
924 }
925
926 if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
927 assert( pCache->nHash>0 && pCache->apHash );
928 assert( (pCache->nHash & (pCache->nHash-1))==0 );
929
930 /* Step 4. Try to recycle a page. */
931 if( pCache->bPurgeable
932 && !pGroup->lru.pLruPrev->isAnchor
933 && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
934 ){
935 PCache1 *pOther;
936 pPage = pGroup->lru.pLruPrev;
937 assert( PAGE_IS_UNPINNED(pPage) );
938 pcache1RemoveFromHash(pPage, 0);
939 pcache1PinPage(pPage);
940 pOther = pPage->pCache;
941 if( pOther->szAlloc != pCache->szAlloc ){
942 pcache1FreePage(pPage);
943 pPage = 0;
944 }else{
945 pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
946 }
947 }
948
949 /* Step 5. If a usable page buffer has still not been found,
950 ** attempt to allocate a new one.
951 */
952 if( !pPage ){
953 pPage = pcache1AllocPage(pCache, createFlag==1);
954 }
955
956 if( pPage ){
957 unsigned int h = iKey & (pCache->nHash-1);
958 pCache->nPage++;
959 pPage->iKey = iKey;
960 pPage->pNext = pCache->apHash[h];
961 pPage->pCache = pCache;
962 pPage->pLruNext = 0;
963 /* pPage->pLruPrev = 0;
964 ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
965 *(void **)pPage->page.pExtra = 0;
966 pCache->apHash[h] = pPage;
967 if( iKey>pCache->iMaxKey ){
968 pCache->iMaxKey = iKey;
969 }
970 return &pPage->page;
971 }
972 return 0;
973}
974
975/*
976** Implementation of the sqlite3_pcache.xFetch method.
977**
978** Fetch a page by key value.
979**
980** Whether or not a new page may be allocated by this function depends on
981** the value of the createFlag argument. 0 means do not allocate a new
982** page. 1 means allocate a new page if space is easily available. 2
983** means to try really hard to allocate a new page.
984**
985** For a non-purgeable cache (a cache used as the storage for an in-memory
986** database) there is really no difference between createFlag 1 and 2. So
987** the calling function (pcache.c) will never have a createFlag of 1 on
988** a non-purgeable cache.
989**
990** There are three different approaches to obtaining space for a page,
991** depending on the value of parameter createFlag (which may be 0, 1 or 2).
992**
993** 1. Regardless of the value of createFlag, the cache is searched for a
994** copy of the requested page. If one is found, it is returned.
995**
996** 2. If createFlag==0 and the page is not already in the cache, NULL is
997** returned.
998**
999** 3. If createFlag is 1, and the page is not already in the cache, then
1000** return NULL (do not allocate a new page) if any of the following
1001** conditions are true:
1002**
1003** (a) the number of pages pinned by the cache is greater than
1004** PCache1.nMax, or
1005**
1006** (b) the number of pages pinned by the cache is greater than
1007** the sum of nMax for all purgeable caches, less the sum of
1008** nMin for all other purgeable caches, or
1009**
1010** 4. If none of the first three conditions apply and the cache is marked
1011** as purgeable, and if one of the following is true:
1012**
1013** (a) The number of pages allocated for the cache is already
1014** PCache1.nMax, or
1015**
1016** (b) The number of pages allocated for all purgeable caches is
1017** already equal to or greater than the sum of nMax for all
1018** purgeable caches,
1019**
1020** (c) The system is under memory pressure and wants to avoid
1021** unnecessary pages cache entry allocations
1022**
1023** then attempt to recycle a page from the LRU list. If it is the right
1024** size, return the recycled buffer. Otherwise, free the buffer and
1025** proceed to step 5.
1026**
1027** 5. Otherwise, allocate and return a new page buffer.
1028**
1029** There are two versions of this routine. pcache1FetchWithMutex() is
1030** the general case. pcache1FetchNoMutex() is a faster implementation for
1031** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
1032** invokes the appropriate routine.
1033*/
1034static sqlite3_pcache_page *pcache1FetchNoMutex(
1035 sqlite3_pcache *p,
1036 unsigned int iKey,
1037 int createFlag
1038){
1039 PCache1 *pCache = (PCache1 *)p;
1040 PgHdr1 *pPage = 0;
1041
1042 /* Step 1: Search the hash table for an existing entry. nHash is always
1043 ** a power of two when the cache is in use (see pcache1ResizeHash()), so
1044 ** the modulo reduces to a mask, avoiding a hardware divide. */
1045 assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 );
1046 pPage = pCache->apHash[iKey & (pCache->nHash-1u)];
1047 while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
1048
1049 /* Step 2: If the page was found in the hash table, then return it.
1050 ** If the page was not in the hash table and createFlag is 0, abort.
1051 ** Otherwise (page not in hash and createFlag!=0) continue with
1052 ** subsequent steps to try to create the page. */
1053 if( pPage ){
1054 if( PAGE_IS_UNPINNED(pPage) ){
1055 return pcache1PinPage(pPage);
1056 }else{
1057 return &pPage->page;
1058 }
1059 }else if( createFlag ){
1060 /* Steps 3, 4, and 5 implemented by this subroutine */
1061 return pcache1FetchStage2(pCache, iKey, createFlag);
1062 }else{
1063 return 0;
1064 }
1065}
1066#if PCACHE1_MIGHT_USE_GROUP_MUTEX
1067static sqlite3_pcache_page *pcache1FetchWithMutex(
1068 sqlite3_pcache *p,
1069 unsigned int iKey,
1070 int createFlag
1071){
1072 PCache1 *pCache = (PCache1 *)p;
1073 sqlite3_pcache_page *pPage;
1074
1075 pcache1EnterMutex(pCache->pGroup);
1076 pPage = pcache1FetchNoMutex(p, iKey, createFlag);
1077 assert( pPage==0 || pCache->iMaxKey>=iKey );
1078 pcache1LeaveMutex(pCache->pGroup);
1079 return pPage;
1080}
1081#endif
1082static sqlite3_pcache_page *pcache1Fetch(
1083 sqlite3_pcache *p,
1084 unsigned int iKey,
1085 int createFlag
1086){
1087#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
1088 PCache1 *pCache = (PCache1 *)p;
1089#endif
1090
1091 assert( pCache->bPurgeable || createFlag!=1 );
1092 assert( pCache->bPurgeable || pCache->nMin==0 );
1093 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
1094 assert( pCache->nMin==0 || pCache->bPurgeable );
1095 assert( pCache->nHash>0 );
1096#if PCACHE1_MIGHT_USE_GROUP_MUTEX
1097 if( pCache->pGroup->mutex ){
1098 return pcache1FetchWithMutex(p, iKey, createFlag);
1099 }else
1100#endif
1101 {
1102 return pcache1FetchNoMutex(p, iKey, createFlag);
1103 }
1104}
1105
1106
1107/*
1108** Implementation of the sqlite3_pcache.xUnpin method.
1109**
1110** Mark a page as unpinned (eligible for asynchronous recycling).
1111*/
1112static void pcache1Unpin(
1113 sqlite3_pcache *p,
1114 sqlite3_pcache_page *pPg,
1115 int reuseUnlikely
1116){
1117 PCache1 *pCache = (PCache1 *)p;
1118 PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
1119 PGroup *pGroup = pCache->pGroup;
1120
1121 assert( pPage->pCache==pCache );
1122 pcache1EnterMutex(pGroup);
1123
1124 /* It is an error to call this function if the page is already
1125 ** part of the PGroup LRU list.
1126 */
1127 assert( pPage->pLruNext==0 );
1128 assert( PAGE_IS_PINNED(pPage) );
1129
1130 if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
1131 pcache1RemoveFromHash(pPage, 1);
1132 }else{
1133 /* Add the page to the PGroup LRU list. */
1134 PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
1135 pPage->pLruPrev = &pGroup->lru;
1136 (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
1137 *ppFirst = pPage;
1138 pCache->nRecyclable++;
1139 }
1140
1141 pcache1LeaveMutex(pCache->pGroup);
1142}
1143
1144/*
1145** Implementation of the sqlite3_pcache.xRekey method.
1146*/
1147static void pcache1Rekey(
1148 sqlite3_pcache *p,
1149 sqlite3_pcache_page *pPg,
1150 unsigned int iOld,
1151 unsigned int iNew
1152){
1153 PCache1 *pCache = (PCache1 *)p;
1154 PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
1155 PgHdr1 **pp;
1156 unsigned int hOld, hNew;
1157 assert( pPage->iKey==iOld );
1158 assert( pPage->pCache==pCache );
1159 assert( iOld!=iNew ); /* The page number really is changing */
1160
1161 pcache1EnterMutex(pCache->pGroup);
1162
1163 assert( pcache1FetchNoMutex(p, iOld, 0)==&pPage->page ); /* pPg really iOld */
1164 assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 );
1165 hOld = iOld & (pCache->nHash-1);
1166 pp = &pCache->apHash[hOld];
1167 while( (*pp)!=pPage ){
1168 pp = &(*pp)->pNext;
1169 }
1170 *pp = pPage->pNext;
1171
1172 assert( pcache1FetchNoMutex(p, iNew, 0)==0 ); /* iNew not in cache */
1173 hNew = iNew & (pCache->nHash-1);
1174 pPage->iKey = iNew;
1175 pPage->pNext = pCache->apHash[hNew];
1176 pCache->apHash[hNew] = pPage;
1177 if( iNew>pCache->iMaxKey ){
1178 pCache->iMaxKey = iNew;
1179 }
1180
1181 pcache1LeaveMutex(pCache->pGroup);
1182}
1183
1184/*
1185** Implementation of the sqlite3_pcache.xTruncate method.
1186**
1187** Discard all unpinned pages in the cache with a page number equal to
1188** or greater than parameter iLimit. Any pinned pages with a page number
1189** equal to or greater than iLimit are implicitly unpinned.
1190*/
1191static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
1192 PCache1 *pCache = (PCache1 *)p;
1193 pcache1EnterMutex(pCache->pGroup);
1194 if( iLimit<=pCache->iMaxKey ){
1195 pcache1TruncateUnsafe(pCache, iLimit);
1196 pCache->iMaxKey = iLimit-1;
1197 }
1198 pcache1LeaveMutex(pCache->pGroup);
1199}
1200
1201/*
1202** Implementation of the sqlite3_pcache.xDestroy method.
1203**
1204** Destroy a cache allocated using pcache1Create().
1205*/
1206static void pcache1Destroy(sqlite3_pcache *p){
1207 PCache1 *pCache = (PCache1 *)p;
1208 PGroup *pGroup = pCache->pGroup;
1209 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
1210 pcache1EnterMutex(pGroup);
1211 if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
1212 assert( pGroup->nMaxPage >= pCache->nMax );
1213 pGroup->nMaxPage -= pCache->nMax;
1214 assert( pGroup->nMinPage >= pCache->nMin );
1215 pGroup->nMinPage -= pCache->nMin;
1216 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
1217 pcache1EnforceMaxPage(pCache);
1218 pcache1LeaveMutex(pGroup);
1219 sqlite3_free(pCache->pBulk);
1220 sqlite3_free(pCache->apHash);
1221 sqlite3_free(pCache);
1222}
1223
1224/*
1225** This function is called during initialization (sqlite3_initialize()) to
1226** install the default pluggable cache module, assuming the user has not
1227** already provided an alternative.
1228*/
1229void sqlite3PCacheSetDefault(void){
1230 static const sqlite3_pcache_methods2 defaultMethods = {
1231 1, /* iVersion */
1232 0, /* pArg */
1233 pcache1Init, /* xInit */
1234 pcache1Shutdown, /* xShutdown */
1235 pcache1Create, /* xCreate */
1236 pcache1Cachesize, /* xCachesize */
1237 pcache1Pagecount, /* xPagecount */
1238 pcache1Fetch, /* xFetch */
1239 pcache1Unpin, /* xUnpin */
1240 pcache1Rekey, /* xRekey */
1241 pcache1Truncate, /* xTruncate */
1242 pcache1Destroy, /* xDestroy */
1243 pcache1Shrink /* xShrink */
1244 };
1245 sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
1246}
1247
1248/*
1249** Return the size of the header on each page of this PCACHE implementation.
1250*/
1251int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
1252
1253/*
1254** Return the global mutex used by this PCACHE implementation. The
1255** sqlite3_status() routine needs access to this mutex.
1256*/
1257sqlite3_mutex *sqlite3Pcache1Mutex(void){
1258 return pcache1.mutex;
1259}
1260
1261#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
1262/*
1263** This function is called to free superfluous dynamically allocated memory
1264** held by the pager system. Memory in use by any SQLite pager allocated
1265** by the current thread may be sqlite3_free()ed.
1266**
1267** nReq is the number of bytes of memory required. Once this much has
1268** been released, the function returns. The return value is the total number
1269** of bytes of memory released.
1270*/
1271int sqlite3PcacheReleaseMemory(int nReq){
1272 int nFree = 0;
1273 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
1274 assert( sqlite3_mutex_notheld(pcache1.mutex) );
1275 if( sqlite3GlobalConfig.pPage==0 ){
1276 PgHdr1 *p;
1277 pcache1EnterMutex(&pcache1.grp);
1278 while( (nReq<0 || nFree<nReq)
1279 && (p=pcache1.grp.lru.pLruPrev)!=0
1280 && p->isAnchor==0
1281 ){
1282 nFree += pcache1MemSize(p->page.pBuf);
1283 assert( PAGE_IS_UNPINNED(p) );
1284 pcache1PinPage(p);
1285 pcache1RemoveFromHash(p, 1);
1286 }
1287 pcache1LeaveMutex(&pcache1.grp);
1288 }
1289 return nFree;
1290}
1291#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
1292
1293#ifdef SQLITE_TEST
1294/*
1295** This function is used by test procedures to inspect the internal state
1296** of the global cache.
1297*/
1298void sqlite3PcacheStats(
1299 int *pnCurrent, /* OUT: Total number of pages cached */
1300 int *pnMax, /* OUT: Global maximum cache size */
1301 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
1302 int *pnRecyclable /* OUT: Total number of pages available for recycling */
1303){
1304 PgHdr1 *p;
1305 int nRecyclable = 0;
1306 for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
1307 assert( PAGE_IS_UNPINNED(p) );
1308 nRecyclable++;
1309 }
1310 *pnCurrent = pcache1.grp.nPurgeable;
1311 *pnMax = (int)pcache1.grp.nMaxPage;
1312 *pnMin = (int)pcache1.grp.nMinPage;
1313 *pnRecyclable = nRecyclable;
1314}
1315#endif