]> granicus.if.org Git - postgresql/blob - src/include/access/gist_private.h
Change the signature of rm_desc so that it's passed a XLogRecord.
[postgresql] / src / include / access / gist_private.h
1 /*-------------------------------------------------------------------------
2  *
3  * gist_private.h
4  *        private declarations for GiST -- declarations related to the
5  *        internal implementation of GiST, not the public API
6  *
7  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/access/gist_private.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef GIST_PRIVATE_H
15 #define GIST_PRIVATE_H
16
17 #include "access/gist.h"
18 #include "access/itup.h"
19 #include "fmgr.h"
20 #include "storage/bufmgr.h"
21 #include "storage/buffile.h"
22 #include "utils/rbtree.h"
23 #include "utils/hsearch.h"
24
25 /*
26  * Maximum number of "halves" a page can be split into in one operation.
27  * Typically a split produces 2 halves, but can be more if keys have very
28  * different lengths, or when inserting multiple keys in one operation (as
29  * when inserting downlinks to an internal node).  There is no theoretical
30  * limit on this, but in practice if you get more than a handful page halves
31  * in one split, there's something wrong with the opclass implementation.
32  * GIST_MAX_SPLIT_PAGES is an arbitrary limit on that, used to size some
33  * local arrays used during split.  Note that there is also a limit on the
34  * number of buffers that can be held locked at a time, MAX_SIMUL_LWLOCKS,
35  * so if you raise this higher than that limit, you'll just get a different
36  * error.
37  */
38 #define GIST_MAX_SPLIT_PAGES            75
39
40 /* Buffer lock modes */
41 #define GIST_SHARE      BUFFER_LOCK_SHARE
42 #define GIST_EXCLUSIVE  BUFFER_LOCK_EXCLUSIVE
43 #define GIST_UNLOCK BUFFER_LOCK_UNLOCK
44
45 typedef struct
46 {
47         BlockNumber prev;
48         uint32          freespace;
49         char            tupledata[1];
50 } GISTNodeBufferPage;
51
52 #define BUFFER_PAGE_DATA_OFFSET MAXALIGN(offsetof(GISTNodeBufferPage, tupledata))
53 /* Returns free space in node buffer page */
54 #define PAGE_FREE_SPACE(nbp) (nbp->freespace)
55 /* Checks if node buffer page is empty */
56 #define PAGE_IS_EMPTY(nbp) (nbp->freespace == BLCKSZ - BUFFER_PAGE_DATA_OFFSET)
57 /* Checks if node buffers page don't contain sufficient space for index tuple */
58 #define PAGE_NO_SPACE(nbp, itup) (PAGE_FREE_SPACE(nbp) < \
59                                                                                 MAXALIGN(IndexTupleSize(itup)))
60
61 /*
62  * GISTSTATE: information needed for any GiST index operation
63  *
64  * This struct retains call info for the index's opclass-specific support
65  * functions (per index column), plus the index's tuple descriptor.
66  *
67  * scanCxt holds the GISTSTATE itself as well as any data that lives for the
68  * lifetime of the index operation.  We pass this to the support functions
69  * via fn_mcxt, so that they can store scan-lifespan data in it.  The
70  * functions are invoked in tempCxt, which is typically short-lifespan
71  * (that is, it's reset after each tuple).  However, tempCxt can be the same
72  * as scanCxt if we're not bothering with per-tuple context resets.
73  */
74 typedef struct GISTSTATE
75 {
76         MemoryContext scanCxt;          /* context for scan-lifespan data */
77         MemoryContext tempCxt;          /* short-term context for calling functions */
78
79         TupleDesc       tupdesc;                /* index's tuple descriptor */
80
81         FmgrInfo        consistentFn[INDEX_MAX_KEYS];
82         FmgrInfo        unionFn[INDEX_MAX_KEYS];
83         FmgrInfo        compressFn[INDEX_MAX_KEYS];
84         FmgrInfo        decompressFn[INDEX_MAX_KEYS];
85         FmgrInfo        penaltyFn[INDEX_MAX_KEYS];
86         FmgrInfo        picksplitFn[INDEX_MAX_KEYS];
87         FmgrInfo        equalFn[INDEX_MAX_KEYS];
88         FmgrInfo        distanceFn[INDEX_MAX_KEYS];
89
90         /* Collations to pass to the support functions */
91         Oid                     supportCollation[INDEX_MAX_KEYS];
92 } GISTSTATE;
93
94
95 /*
96  * During a GiST index search, we must maintain a queue of unvisited items,
97  * which can be either individual heap tuples or whole index pages.  If it
98  * is an ordered search, the unvisited items should be visited in distance
99  * order.  Unvisited items at the same distance should be visited in
100  * depth-first order, that is heap items first, then lower index pages, then
101  * upper index pages; this rule avoids doing extra work during a search that
102  * ends early due to LIMIT.
103  *
104  * To perform an ordered search, we use an RBTree to manage the distance-order
105  * queue.  Each GISTSearchTreeItem stores all unvisited items of the same
106  * distance; they are GISTSearchItems chained together via their next fields.
107  *
108  * In a non-ordered search (no order-by operators), the RBTree degenerates
109  * to a single item, which we use as a queue of unvisited index pages only.
110  * In this case matched heap items from the current index leaf page are
111  * remembered in GISTScanOpaqueData.pageData[] and returned directly from
112  * there, instead of building a separate GISTSearchItem for each one.
113  */
114
115 /* Individual heap tuple to be visited */
116 typedef struct GISTSearchHeapItem
117 {
118         ItemPointerData heapPtr;
119         bool            recheck;                /* T if quals must be rechecked */
120 } GISTSearchHeapItem;
121
122 /* Unvisited item, either index page or heap tuple */
123 typedef struct GISTSearchItem
124 {
125         struct GISTSearchItem *next;    /* list link */
126         BlockNumber blkno;                      /* index page number, or InvalidBlockNumber */
127         union
128         {
129                 GistNSN         parentlsn;      /* parent page's LSN, if index page */
130                 /* we must store parentlsn to detect whether a split occurred */
131                 GISTSearchHeapItem heap;        /* heap info, if heap tuple */
132         }                       data;
133 } GISTSearchItem;
134
135 #define GISTSearchItemIsHeap(item)      ((item).blkno == InvalidBlockNumber)
136
137 /*
138  * Within a GISTSearchTreeItem's chain, heap items always appear before
139  * index-page items, since we want to visit heap items first.  lastHeap points
140  * to the last heap item in the chain, or is NULL if there are none.
141  */
142 typedef struct GISTSearchTreeItem
143 {
144         RBNode          rbnode;                 /* this is an RBTree item */
145         GISTSearchItem *head;           /* first chain member */
146         GISTSearchItem *lastHeap;       /* last heap-tuple member, if any */
147         double          distances[1];   /* array with numberOfOrderBys entries */
148 } GISTSearchTreeItem;
149
150 #define GSTIHDRSZ offsetof(GISTSearchTreeItem, distances)
151
152 /*
153  * GISTScanOpaqueData: private state for a scan of a GiST index
154  */
155 typedef struct GISTScanOpaqueData
156 {
157         GISTSTATE  *giststate;          /* index information, see above */
158         RBTree     *queue;                      /* queue of unvisited items */
159         MemoryContext queueCxt;         /* context holding the queue */
160         bool            qual_ok;                /* false if qual can never be satisfied */
161         bool            firstCall;              /* true until first gistgettuple call */
162
163         GISTSearchTreeItem *curTreeItem;        /* current queue item, if any */
164
165         /* pre-allocated workspace arrays */
166         GISTSearchTreeItem *tmpTreeItem;        /* workspace to pass to rb_insert */
167         double     *distances;          /* output area for gistindex_keytest */
168
169         /* In a non-ordered search, returnable heap items are stored here: */
170         GISTSearchHeapItem pageData[BLCKSZ / sizeof(IndexTupleData)];
171         OffsetNumber nPageData;         /* number of valid items in array */
172         OffsetNumber curPageData;       /* next item to return */
173 } GISTScanOpaqueData;
174
175 typedef GISTScanOpaqueData *GISTScanOpaque;
176
177
178 /* XLog stuff */
179
180 #define XLOG_GIST_PAGE_UPDATE           0x00
181  /* #define XLOG_GIST_NEW_ROOT                   0x20 */        /* not used anymore */
182 #define XLOG_GIST_PAGE_SPLIT            0x30
183  /* #define XLOG_GIST_INSERT_COMPLETE    0x40 */        /* not used anymore */
184 #define XLOG_GIST_CREATE_INDEX          0x50
185  /* #define XLOG_GIST_PAGE_DELETE                0x60 */        /* not used anymore */
186
187 typedef struct gistxlogPageUpdate
188 {
189         RelFileNode node;
190         BlockNumber blkno;
191
192         /*
193          * If this operation completes a page split, by inserting a downlink for
194          * the split page, leftchild points to the left half of the split.
195          */
196         BlockNumber leftchild;
197
198         /* number of deleted offsets */
199         uint16          ntodelete;
200
201         /*
202          * follow: 1. todelete OffsetNumbers 2. tuples to insert
203          */
204 } gistxlogPageUpdate;
205
206 typedef struct gistxlogPageSplit
207 {
208         RelFileNode node;
209         BlockNumber origblkno;          /* splitted page */
210         BlockNumber origrlink;          /* rightlink of the page before split */
211         GistNSN         orignsn;                /* NSN of the page before split */
212         bool            origleaf;               /* was splitted page a leaf page? */
213
214         BlockNumber leftchild;          /* like in gistxlogPageUpdate */
215         uint16          npage;                  /* # of pages in the split */
216         bool            markfollowright;        /* set F_FOLLOW_RIGHT flags */
217
218         /*
219          * follow: 1. gistxlogPage and array of IndexTupleData per page
220          */
221 } gistxlogPageSplit;
222
223 typedef struct gistxlogPage
224 {
225         BlockNumber blkno;
226         int                     num;                    /* number of index tuples following */
227 } gistxlogPage;
228
229 /* SplitedPageLayout - gistSplit function result */
230 typedef struct SplitedPageLayout
231 {
232         gistxlogPage block;
233         IndexTupleData *list;
234         int                     lenlist;
235         IndexTuple      itup;                   /* union key for page */
236         Page            page;                   /* to operate */
237         Buffer          buffer;                 /* to write after all proceed */
238
239         struct SplitedPageLayout *next;
240 } SplitedPageLayout;
241
242 /*
243  * GISTInsertStack used for locking buffers and transfer arguments during
244  * insertion
245  */
246 typedef struct GISTInsertStack
247 {
248         /* current page */
249         BlockNumber blkno;
250         Buffer          buffer;
251         Page            page;
252
253         /*
254          * log sequence number from page->lsn to recognize page update and compare
255          * it with page's nsn to recognize page split
256          */
257         GistNSN         lsn;
258
259         /* offset of the downlink in the parent page, that points to this page */
260         OffsetNumber downlinkoffnum;
261
262         /* pointer to parent */
263         struct GISTInsertStack *parent;
264 } GISTInsertStack;
265
266 /* Working state and results for multi-column split logic in gistsplit.c */
267 typedef struct GistSplitVector
268 {
269         GIST_SPLITVEC splitVector;      /* passed to/from user PickSplit method */
270
271         Datum           spl_lattr[INDEX_MAX_KEYS];              /* Union of subkeys in
272                                                                                                  * splitVector.spl_left */
273         bool            spl_lisnull[INDEX_MAX_KEYS];
274
275         Datum           spl_rattr[INDEX_MAX_KEYS];              /* Union of subkeys in
276                                                                                                  * splitVector.spl_right */
277         bool            spl_risnull[INDEX_MAX_KEYS];
278
279         bool       *spl_dontcare;       /* flags tuples which could go to either side
280                                                                  * of the split for zero penalty */
281 } GistSplitVector;
282
283 typedef struct
284 {
285         Relation        r;
286         Size            freespace;              /* free space to be left */
287
288         GISTInsertStack *stack;
289 } GISTInsertState;
290
291 /* root page of a gist index */
292 #define GIST_ROOT_BLKNO                         0
293
294 /*
295  * Before PostgreSQL 9.1, we used rely on so-called "invalid tuples" on inner
296  * pages to finish crash recovery of incomplete page splits. If a crash
297  * happened in the middle of a page split, so that the downlink pointers were
298  * not yet inserted, crash recovery inserted a special downlink pointer. The
299  * semantics of an invalid tuple was that it if you encounter one in a scan,
300  * it must always be followed, because we don't know if the tuples on the
301  * child page match or not.
302  *
303  * We no longer create such invalid tuples, we now mark the left-half of such
304  * an incomplete split with the F_FOLLOW_RIGHT flag instead, and finish the
305  * split properly the next time we need to insert on that page. To retain
306  * on-disk compatibility for the sake of pg_upgrade, we still store 0xffff as
307  * the offset number of all inner tuples. If we encounter any invalid tuples
308  * with 0xfffe during insertion, we throw an error, though scans still handle
309  * them. You should only encounter invalid tuples if you pg_upgrade a pre-9.1
310  * gist index which already has invalid tuples in it because of a crash. That
311  * should be rare, and you are recommended to REINDEX anyway if you have any
312  * invalid tuples in an index, so throwing an error is as far as we go with
313  * supporting that.
314  */
315 #define TUPLE_IS_VALID          0xffff
316 #define TUPLE_IS_INVALID        0xfffe
317
318 #define  GistTupleIsInvalid(itup)       ( ItemPointerGetOffsetNumber( &((itup)->t_tid) ) == TUPLE_IS_INVALID )
319 #define  GistTupleSetValid(itup)        ItemPointerSetOffsetNumber( &((itup)->t_tid), TUPLE_IS_VALID )
320
321
322
323
324 /*
325  * A buffer attached to an internal node, used when building an index in
326  * buffering mode.
327  */
328 typedef struct
329 {
330         BlockNumber nodeBlocknum;       /* index block # this buffer is for */
331         int32           blocksCount;    /* current # of blocks occupied by buffer */
332
333         BlockNumber pageBlocknum;       /* temporary file block # */
334         GISTNodeBufferPage *pageBuffer;         /* in-memory buffer page */
335
336         /* is this buffer queued for emptying? */
337         bool            queuedForEmptying;
338
339         /* is this a temporary copy, not in the hash table? */
340         bool            isTemp;
341
342         int                     level;                  /* 0 == leaf */
343 } GISTNodeBuffer;
344
345 /*
346  * Does specified level have buffers? (Beware of multiple evaluation of
347  * arguments.)
348  */
349 #define LEVEL_HAS_BUFFERS(nlevel, gfbb) \
350         ((nlevel) != 0 && (nlevel) % (gfbb)->levelStep == 0 && \
351          (nlevel) != (gfbb)->rootlevel)
352
353 /* Is specified buffer at least half-filled (should be queued for emptying)? */
354 #define BUFFER_HALF_FILLED(nodeBuffer, gfbb) \
355         ((nodeBuffer)->blocksCount > (gfbb)->pagesPerBuffer / 2)
356
357 /*
358  * Is specified buffer full? Our buffers can actually grow indefinitely,
359  * beyond the "maximum" size, so this just means whether the buffer has grown
360  * beyond the nominal maximum size.
361  */
362 #define BUFFER_OVERFLOWED(nodeBuffer, gfbb) \
363         ((nodeBuffer)->blocksCount > (gfbb)->pagesPerBuffer)
364
365 /*
366  * Data structure with general information about build buffers.
367  */
368 typedef struct GISTBuildBuffers
369 {
370         /* Persistent memory context for the buffers and metadata. */
371         MemoryContext context;
372
373         BufFile    *pfile;                      /* Temporary file to store buffers in */
374         long            nFileBlocks;    /* Current size of the temporary file */
375
376         /*
377          * resizable array of free blocks.
378          */
379         long       *freeBlocks;
380         int                     nFreeBlocks;    /* # of currently free blocks in the array */
381         int                     freeBlocksLen;  /* current allocated length of the array */
382
383         /* Hash for buffers by block number */
384         HTAB       *nodeBuffersTab;
385
386         /* List of buffers scheduled for emptying */
387         List       *bufferEmptyingQueue;
388
389         /*
390          * Parameters to the buffering build algorithm. levelStep determines which
391          * levels in the tree have buffers, and pagesPerBuffer determines how
392          * large each buffer is.
393          */
394         int                     levelStep;
395         int                     pagesPerBuffer;
396
397         /* Array of lists of buffers on each level, for final emptying */
398         List      **buffersOnLevels;
399         int                     buffersOnLevelsLen;
400
401         /*
402          * Dynamically-sized array of buffers that currently have their last page
403          * loaded in main memory.
404          */
405         GISTNodeBuffer **loadedBuffers;
406         int                     loadedBuffersCount;             /* # of entries in loadedBuffers */
407         int                     loadedBuffersLen;               /* allocated size of loadedBuffers */
408
409         /* Level of the current root node (= height of the index tree - 1) */
410         int                     rootlevel;
411 } GISTBuildBuffers;
412
413 /*
414  * Storage type for GiST's reloptions
415  */
416 typedef struct GiSTOptions
417 {
418         int32           vl_len_;                /* varlena header (do not touch directly!) */
419         int                     fillfactor;             /* page fill factor in percent (0..100) */
420         int                     bufferingModeOffset;    /* use buffering build? */
421 } GiSTOptions;
422
423 /* gist.c */
424 extern Datum gistbuildempty(PG_FUNCTION_ARGS);
425 extern Datum gistinsert(PG_FUNCTION_ARGS);
426 extern MemoryContext createTempGistContext(void);
427 extern GISTSTATE *initGISTstate(Relation index);
428 extern void freeGISTstate(GISTSTATE *giststate);
429 extern void gistdoinsert(Relation r,
430                          IndexTuple itup,
431                          Size freespace,
432                          GISTSTATE *GISTstate);
433
434 /* A List of these is returned from gistplacetopage() in *splitinfo */
435 typedef struct
436 {
437         Buffer          buf;                    /* the split page "half" */
438         IndexTuple      downlink;               /* downlink for this half. */
439 } GISTPageSplitInfo;
440
441 extern bool gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
442                                 Buffer buffer,
443                                 IndexTuple *itup, int ntup,
444                                 OffsetNumber oldoffnum, BlockNumber *newblkno,
445                                 Buffer leftchildbuf,
446                                 List **splitinfo,
447                                 bool markleftchild);
448
449 extern SplitedPageLayout *gistSplit(Relation r, Page page, IndexTuple *itup,
450                   int len, GISTSTATE *giststate);
451
452 /* gistxlog.c */
453 extern void gist_redo(XLogRecPtr lsn, XLogRecord *record);
454 extern void gist_desc(StringInfo buf, XLogRecord *record);
455 extern void gist_xlog_startup(void);
456 extern void gist_xlog_cleanup(void);
457
458 extern XLogRecPtr gistXLogUpdate(RelFileNode node, Buffer buffer,
459                            OffsetNumber *todelete, int ntodelete,
460                            IndexTuple *itup, int ntup,
461                            Buffer leftchild);
462
463 extern XLogRecPtr gistXLogSplit(RelFileNode node,
464                           BlockNumber blkno, bool page_is_leaf,
465                           SplitedPageLayout *dist,
466                           BlockNumber origrlink, GistNSN oldnsn,
467                           Buffer leftchild, bool markfollowright);
468
469 /* gistget.c */
470 extern Datum gistgettuple(PG_FUNCTION_ARGS);
471 extern Datum gistgetbitmap(PG_FUNCTION_ARGS);
472
473 /* gistutil.c */
474
475 #define GiSTPageSize   \
476         ( BLCKSZ - SizeOfPageHeaderData - MAXALIGN(sizeof(GISTPageOpaqueData)) )
477
478 #define GIST_MIN_FILLFACTOR                     10
479 #define GIST_DEFAULT_FILLFACTOR         90
480
481 extern Datum gistoptions(PG_FUNCTION_ARGS);
482 extern bool gistfitpage(IndexTuple *itvec, int len);
483 extern bool gistnospace(Page page, IndexTuple *itvec, int len, OffsetNumber todelete, Size freespace);
484 extern void gistcheckpage(Relation rel, Buffer buf);
485 extern Buffer gistNewBuffer(Relation r);
486 extern void gistfillbuffer(Page page, IndexTuple *itup, int len,
487                            OffsetNumber off);
488 extern IndexTuple *gistextractpage(Page page, int *len /* out */ );
489 extern IndexTuple *gistjoinvector(
490                            IndexTuple *itvec, int *len,
491                            IndexTuple *additvec, int addlen);
492 extern IndexTupleData *gistfillitupvec(IndexTuple *vec, int veclen, int *memlen);
493
494 extern IndexTuple gistunion(Relation r, IndexTuple *itvec,
495                   int len, GISTSTATE *giststate);
496 extern IndexTuple gistgetadjusted(Relation r,
497                                 IndexTuple oldtup,
498                                 IndexTuple addtup,
499                                 GISTSTATE *giststate);
500 extern IndexTuple gistFormTuple(GISTSTATE *giststate,
501                           Relation r, Datum *attdata, bool *isnull, bool newValues);
502
503 extern OffsetNumber gistchoose(Relation r, Page p,
504                    IndexTuple it,
505                    GISTSTATE *giststate);
506 extern void gistcentryinit(GISTSTATE *giststate, int nkey,
507                            GISTENTRY *e, Datum k,
508                            Relation r, Page pg,
509                            OffsetNumber o, bool l, bool isNull);
510
511 extern void GISTInitBuffer(Buffer b, uint32 f);
512 extern void gistdentryinit(GISTSTATE *giststate, int nkey, GISTENTRY *e,
513                            Datum k, Relation r, Page pg, OffsetNumber o,
514                            bool l, bool isNull);
515
516 extern float gistpenalty(GISTSTATE *giststate, int attno,
517                         GISTENTRY *key1, bool isNull1,
518                         GISTENTRY *key2, bool isNull2);
519 extern void gistMakeUnionItVec(GISTSTATE *giststate, IndexTuple *itvec, int len,
520                                    Datum *attr, bool *isnull);
521 extern bool gistKeyIsEQ(GISTSTATE *giststate, int attno, Datum a, Datum b);
522 extern void gistDeCompressAtt(GISTSTATE *giststate, Relation r, IndexTuple tuple, Page p,
523                                   OffsetNumber o, GISTENTRY *attdata, bool *isnull);
524
525 extern void gistMakeUnionKey(GISTSTATE *giststate, int attno,
526                                  GISTENTRY *entry1, bool isnull1,
527                                  GISTENTRY *entry2, bool isnull2,
528                                  Datum *dst, bool *dstisnull);
529
530 extern XLogRecPtr gistGetFakeLSN(Relation rel);
531
532 /* gistvacuum.c */
533 extern Datum gistbulkdelete(PG_FUNCTION_ARGS);
534 extern Datum gistvacuumcleanup(PG_FUNCTION_ARGS);
535
536 /* gistsplit.c */
537 extern void gistSplitByKey(Relation r, Page page, IndexTuple *itup,
538                            int len, GISTSTATE *giststate,
539                            GistSplitVector *v,
540                            int attno);
541
542 /* gistbuild.c */
543 extern Datum gistbuild(PG_FUNCTION_ARGS);
544 extern void gistValidateBufferingOption(char *value);
545
546 /* gistbuildbuffers.c */
547 extern GISTBuildBuffers *gistInitBuildBuffers(int pagesPerBuffer, int levelStep,
548                                          int maxLevel);
549 extern GISTNodeBuffer *gistGetNodeBuffer(GISTBuildBuffers *gfbb,
550                                   GISTSTATE *giststate,
551                                   BlockNumber blkno, int level);
552 extern void gistPushItupToNodeBuffer(GISTBuildBuffers *gfbb,
553                                                  GISTNodeBuffer *nodeBuffer, IndexTuple item);
554 extern bool gistPopItupFromNodeBuffer(GISTBuildBuffers *gfbb,
555                                                   GISTNodeBuffer *nodeBuffer, IndexTuple *item);
556 extern void gistFreeBuildBuffers(GISTBuildBuffers *gfbb);
557 extern void gistRelocateBuildBuffersOnSplit(GISTBuildBuffers *gfbb,
558                                                                 GISTSTATE *giststate, Relation r,
559                                                                 int level, Buffer buffer,
560                                                                 List *splitinfo);
561 extern void gistUnloadNodeBuffers(GISTBuildBuffers *gfbb);
562
563 #endif   /* GIST_PRIVATE_H */