1 /*-------------------------------------------------------------------------
4 * private declarations for GiST -- declarations related to the
5 * internal implementation of GiST, not the public API
7 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/include/access/gist_private.h
12 *-------------------------------------------------------------------------
14 #ifndef GIST_PRIVATE_H
15 #define GIST_PRIVATE_H
17 #include "access/gist.h"
18 #include "access/itup.h"
19 #include "access/xlogreader.h"
21 #include "lib/pairingheap.h"
22 #include "storage/bufmgr.h"
23 #include "storage/buffile.h"
24 #include "utils/hsearch.h"
27 * Maximum number of "halves" a page can be split into in one operation.
28 * Typically a split produces 2 halves, but can be more if keys have very
29 * different lengths, or when inserting multiple keys in one operation (as
30 * when inserting downlinks to an internal node). There is no theoretical
31 * limit on this, but in practice if you get more than a handful page halves
32 * in one split, there's something wrong with the opclass implementation.
33 * GIST_MAX_SPLIT_PAGES is an arbitrary limit on that, used to size some
34 * local arrays used during split. Note that there is also a limit on the
35 * number of buffers that can be held locked at a time, MAX_SIMUL_LWLOCKS,
36 * so if you raise this higher than that limit, you'll just get a different
39 #define GIST_MAX_SPLIT_PAGES 75
41 /* Buffer lock modes */
42 #define GIST_SHARE BUFFER_LOCK_SHARE
43 #define GIST_EXCLUSIVE BUFFER_LOCK_EXCLUSIVE
44 #define GIST_UNLOCK BUFFER_LOCK_UNLOCK
50 char tupledata[FLEXIBLE_ARRAY_MEMBER];
53 #define BUFFER_PAGE_DATA_OFFSET MAXALIGN(offsetof(GISTNodeBufferPage, tupledata))
54 /* Returns free space in node buffer page */
55 #define PAGE_FREE_SPACE(nbp) (nbp->freespace)
56 /* Checks if node buffer page is empty */
57 #define PAGE_IS_EMPTY(nbp) (nbp->freespace == BLCKSZ - BUFFER_PAGE_DATA_OFFSET)
58 /* Checks if node buffers page don't contain sufficient space for index tuple */
59 #define PAGE_NO_SPACE(nbp, itup) (PAGE_FREE_SPACE(nbp) < \
60 MAXALIGN(IndexTupleSize(itup)))
63 * GISTSTATE: information needed for any GiST index operation
65 * This struct retains call info for the index's opclass-specific support
66 * functions (per index column), plus the index's tuple descriptor.
68 * scanCxt holds the GISTSTATE itself as well as any data that lives for the
69 * lifetime of the index operation. We pass this to the support functions
70 * via fn_mcxt, so that they can store scan-lifespan data in it. The
71 * functions are invoked in tempCxt, which is typically short-lifespan
72 * (that is, it's reset after each tuple). However, tempCxt can be the same
73 * as scanCxt if we're not bothering with per-tuple context resets.
75 typedef struct GISTSTATE
77 MemoryContext scanCxt; /* context for scan-lifespan data */
78 MemoryContext tempCxt; /* short-term context for calling functions */
80 TupleDesc tupdesc; /* index's tuple descriptor */
82 FmgrInfo consistentFn[INDEX_MAX_KEYS];
83 FmgrInfo unionFn[INDEX_MAX_KEYS];
84 FmgrInfo compressFn[INDEX_MAX_KEYS];
85 FmgrInfo decompressFn[INDEX_MAX_KEYS];
86 FmgrInfo penaltyFn[INDEX_MAX_KEYS];
87 FmgrInfo picksplitFn[INDEX_MAX_KEYS];
88 FmgrInfo equalFn[INDEX_MAX_KEYS];
89 FmgrInfo distanceFn[INDEX_MAX_KEYS];
91 /* Collations to pass to the support functions */
92 Oid supportCollation[INDEX_MAX_KEYS];
97 * During a GiST index search, we must maintain a queue of unvisited items,
98 * which can be either individual heap tuples or whole index pages. If it
99 * is an ordered search, the unvisited items should be visited in distance
100 * order. Unvisited items at the same distance should be visited in
101 * depth-first order, that is heap items first, then lower index pages, then
102 * upper index pages; this rule avoids doing extra work during a search that
103 * ends early due to LIMIT.
105 * To perform an ordered search, we use an RBTree to manage the distance-order
106 * queue. Each GISTSearchTreeItem stores all unvisited items of the same
107 * distance; they are GISTSearchItems chained together via their next fields.
109 * In a non-ordered search (no order-by operators), the RBTree degenerates
110 * to a single item, which we use as a queue of unvisited index pages only.
111 * In this case matched heap items from the current index leaf page are
112 * remembered in GISTScanOpaqueData.pageData[] and returned directly from
113 * there, instead of building a separate GISTSearchItem for each one.
116 /* Individual heap tuple to be visited */
117 typedef struct GISTSearchHeapItem
119 ItemPointerData heapPtr;
120 bool recheck; /* T if quals must be rechecked */
121 } GISTSearchHeapItem;
123 /* Unvisited item, either index page or heap tuple */
124 typedef struct GISTSearchItem
126 pairingheap_node phNode;
127 BlockNumber blkno; /* index page number, or InvalidBlockNumber */
130 GistNSN parentlsn; /* parent page's LSN, if index page */
131 /* we must store parentlsn to detect whether a split occurred */
132 GISTSearchHeapItem heap; /* heap info, if heap tuple */
134 double distances[FLEXIBLE_ARRAY_MEMBER]; /* numberOfOrderBys
138 #define GISTSearchItemIsHeap(item) ((item).blkno == InvalidBlockNumber)
140 #define SizeOfGISTSearchItem(n_distances) (offsetof(GISTSearchItem, distances) + sizeof(double) * (n_distances))
143 * GISTScanOpaqueData: private state for a scan of a GiST index
145 typedef struct GISTScanOpaqueData
147 GISTSTATE *giststate; /* index information, see above */
148 pairingheap *queue; /* queue of unvisited items */
149 MemoryContext queueCxt; /* context holding the queue */
150 bool qual_ok; /* false if qual can never be satisfied */
151 bool firstCall; /* true until first gistgettuple call */
153 /* pre-allocated workspace arrays */
154 double *distances; /* output area for gistindex_keytest */
156 /* In a non-ordered search, returnable heap items are stored here: */
157 GISTSearchHeapItem pageData[BLCKSZ / sizeof(IndexTupleData)];
158 OffsetNumber nPageData; /* number of valid items in array */
159 OffsetNumber curPageData; /* next item to return */
160 } GISTScanOpaqueData;
162 typedef GISTScanOpaqueData *GISTScanOpaque;
167 #define XLOG_GIST_PAGE_UPDATE 0x00
168 /* #define XLOG_GIST_NEW_ROOT 0x20 */ /* not used anymore */
169 #define XLOG_GIST_PAGE_SPLIT 0x30
170 /* #define XLOG_GIST_INSERT_COMPLETE 0x40 */ /* not used anymore */
171 #define XLOG_GIST_CREATE_INDEX 0x50
172 /* #define XLOG_GIST_PAGE_DELETE 0x60 */ /* not used anymore */
175 * Backup Blk 0: updated page.
176 * Backup Blk 1: If this operation completes a page split, by inserting a
177 * downlink for the split page, the left half of the split
179 typedef struct gistxlogPageUpdate
181 /* number of deleted offsets */
186 * In payload of blk 0 : 1. todelete OffsetNumbers 2. tuples to insert
188 } gistxlogPageUpdate;
191 * Backup Blk 0: If this operation completes a page split, by inserting a
192 * downlink for the split page, the left half of the split
193 * Backup Blk 1 - npage: split pages (1 is the original page)
195 typedef struct gistxlogPageSplit
197 BlockNumber origrlink; /* rightlink of the page before split */
198 GistNSN orignsn; /* NSN of the page before split */
199 bool origleaf; /* was splitted page a leaf page? */
201 uint16 npage; /* # of pages in the split */
202 bool markfollowright; /* set F_FOLLOW_RIGHT flags */
205 * follow: 1. gistxlogPage and array of IndexTupleData per page
209 typedef struct gistxlogPage
212 int num; /* number of index tuples following */
215 /* SplitedPageLayout - gistSplit function result */
216 typedef struct SplitedPageLayout
219 IndexTupleData *list;
221 IndexTuple itup; /* union key for page */
222 Page page; /* to operate */
223 Buffer buffer; /* to write after all proceed */
225 struct SplitedPageLayout *next;
229 * GISTInsertStack used for locking buffers and transfer arguments during
232 typedef struct GISTInsertStack
240 * log sequence number from page->lsn to recognize page update and compare
241 * it with page's nsn to recognize page split
245 /* offset of the downlink in the parent page, that points to this page */
246 OffsetNumber downlinkoffnum;
248 /* pointer to parent */
249 struct GISTInsertStack *parent;
252 /* Working state and results for multi-column split logic in gistsplit.c */
253 typedef struct GistSplitVector
255 GIST_SPLITVEC splitVector; /* passed to/from user PickSplit method */
257 Datum spl_lattr[INDEX_MAX_KEYS]; /* Union of subkeys in
258 * splitVector.spl_left */
259 bool spl_lisnull[INDEX_MAX_KEYS];
261 Datum spl_rattr[INDEX_MAX_KEYS]; /* Union of subkeys in
262 * splitVector.spl_right */
263 bool spl_risnull[INDEX_MAX_KEYS];
265 bool *spl_dontcare; /* flags tuples which could go to either side
266 * of the split for zero penalty */
272 Size freespace; /* free space to be left */
274 GISTInsertStack *stack;
277 /* root page of a gist index */
278 #define GIST_ROOT_BLKNO 0
281 * Before PostgreSQL 9.1, we used rely on so-called "invalid tuples" on inner
282 * pages to finish crash recovery of incomplete page splits. If a crash
283 * happened in the middle of a page split, so that the downlink pointers were
284 * not yet inserted, crash recovery inserted a special downlink pointer. The
285 * semantics of an invalid tuple was that it if you encounter one in a scan,
286 * it must always be followed, because we don't know if the tuples on the
287 * child page match or not.
289 * We no longer create such invalid tuples, we now mark the left-half of such
290 * an incomplete split with the F_FOLLOW_RIGHT flag instead, and finish the
291 * split properly the next time we need to insert on that page. To retain
292 * on-disk compatibility for the sake of pg_upgrade, we still store 0xffff as
293 * the offset number of all inner tuples. If we encounter any invalid tuples
294 * with 0xfffe during insertion, we throw an error, though scans still handle
295 * them. You should only encounter invalid tuples if you pg_upgrade a pre-9.1
296 * gist index which already has invalid tuples in it because of a crash. That
297 * should be rare, and you are recommended to REINDEX anyway if you have any
298 * invalid tuples in an index, so throwing an error is as far as we go with
301 #define TUPLE_IS_VALID 0xffff
302 #define TUPLE_IS_INVALID 0xfffe
304 #define GistTupleIsInvalid(itup) ( ItemPointerGetOffsetNumber( &((itup)->t_tid) ) == TUPLE_IS_INVALID )
305 #define GistTupleSetValid(itup) ItemPointerSetOffsetNumber( &((itup)->t_tid), TUPLE_IS_VALID )
311 * A buffer attached to an internal node, used when building an index in
316 BlockNumber nodeBlocknum; /* index block # this buffer is for */
317 int32 blocksCount; /* current # of blocks occupied by buffer */
319 BlockNumber pageBlocknum; /* temporary file block # */
320 GISTNodeBufferPage *pageBuffer; /* in-memory buffer page */
322 /* is this buffer queued for emptying? */
323 bool queuedForEmptying;
325 /* is this a temporary copy, not in the hash table? */
328 int level; /* 0 == leaf */
332 * Does specified level have buffers? (Beware of multiple evaluation of
335 #define LEVEL_HAS_BUFFERS(nlevel, gfbb) \
336 ((nlevel) != 0 && (nlevel) % (gfbb)->levelStep == 0 && \
337 (nlevel) != (gfbb)->rootlevel)
339 /* Is specified buffer at least half-filled (should be queued for emptying)? */
340 #define BUFFER_HALF_FILLED(nodeBuffer, gfbb) \
341 ((nodeBuffer)->blocksCount > (gfbb)->pagesPerBuffer / 2)
344 * Is specified buffer full? Our buffers can actually grow indefinitely,
345 * beyond the "maximum" size, so this just means whether the buffer has grown
346 * beyond the nominal maximum size.
348 #define BUFFER_OVERFLOWED(nodeBuffer, gfbb) \
349 ((nodeBuffer)->blocksCount > (gfbb)->pagesPerBuffer)
352 * Data structure with general information about build buffers.
354 typedef struct GISTBuildBuffers
356 /* Persistent memory context for the buffers and metadata. */
357 MemoryContext context;
359 BufFile *pfile; /* Temporary file to store buffers in */
360 long nFileBlocks; /* Current size of the temporary file */
363 * resizable array of free blocks.
366 int nFreeBlocks; /* # of currently free blocks in the array */
367 int freeBlocksLen; /* current allocated length of the array */
369 /* Hash for buffers by block number */
370 HTAB *nodeBuffersTab;
372 /* List of buffers scheduled for emptying */
373 List *bufferEmptyingQueue;
376 * Parameters to the buffering build algorithm. levelStep determines which
377 * levels in the tree have buffers, and pagesPerBuffer determines how
378 * large each buffer is.
383 /* Array of lists of buffers on each level, for final emptying */
384 List **buffersOnLevels;
385 int buffersOnLevelsLen;
388 * Dynamically-sized array of buffers that currently have their last page
389 * loaded in main memory.
391 GISTNodeBuffer **loadedBuffers;
392 int loadedBuffersCount; /* # of entries in loadedBuffers */
393 int loadedBuffersLen; /* allocated size of loadedBuffers */
395 /* Level of the current root node (= height of the index tree - 1) */
400 * Storage type for GiST's reloptions
402 typedef struct GiSTOptions
404 int32 vl_len_; /* varlena header (do not touch directly!) */
405 int fillfactor; /* page fill factor in percent (0..100) */
406 int bufferingModeOffset; /* use buffering build? */
410 extern Datum gistbuildempty(PG_FUNCTION_ARGS);
411 extern Datum gistinsert(PG_FUNCTION_ARGS);
412 extern MemoryContext createTempGistContext(void);
413 extern GISTSTATE *initGISTstate(Relation index);
414 extern void freeGISTstate(GISTSTATE *giststate);
415 extern void gistdoinsert(Relation r,
418 GISTSTATE *GISTstate);
420 /* A List of these is returned from gistplacetopage() in *splitinfo */
423 Buffer buf; /* the split page "half" */
424 IndexTuple downlink; /* downlink for this half. */
427 extern bool gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
429 IndexTuple *itup, int ntup,
430 OffsetNumber oldoffnum, BlockNumber *newblkno,
435 extern SplitedPageLayout *gistSplit(Relation r, Page page, IndexTuple *itup,
436 int len, GISTSTATE *giststate);
439 extern void gist_redo(XLogReaderState *record);
440 extern void gist_desc(StringInfo buf, XLogReaderState *record);
441 extern const char *gist_identify(uint8 info);
442 extern void gist_xlog_startup(void);
443 extern void gist_xlog_cleanup(void);
445 extern XLogRecPtr gistXLogUpdate(RelFileNode node, Buffer buffer,
446 OffsetNumber *todelete, int ntodelete,
447 IndexTuple *itup, int ntup,
450 extern XLogRecPtr gistXLogSplit(RelFileNode node,
451 BlockNumber blkno, bool page_is_leaf,
452 SplitedPageLayout *dist,
453 BlockNumber origrlink, GistNSN oldnsn,
454 Buffer leftchild, bool markfollowright);
457 extern Datum gistgettuple(PG_FUNCTION_ARGS);
458 extern Datum gistgetbitmap(PG_FUNCTION_ARGS);
462 #define GiSTPageSize \
463 ( BLCKSZ - SizeOfPageHeaderData - MAXALIGN(sizeof(GISTPageOpaqueData)) )
465 #define GIST_MIN_FILLFACTOR 10
466 #define GIST_DEFAULT_FILLFACTOR 90
468 extern Datum gistoptions(PG_FUNCTION_ARGS);
469 extern bool gistfitpage(IndexTuple *itvec, int len);
470 extern bool gistnospace(Page page, IndexTuple *itvec, int len, OffsetNumber todelete, Size freespace);
471 extern void gistcheckpage(Relation rel, Buffer buf);
472 extern Buffer gistNewBuffer(Relation r);
473 extern void gistfillbuffer(Page page, IndexTuple *itup, int len,
475 extern IndexTuple *gistextractpage(Page page, int *len /* out */ );
476 extern IndexTuple *gistjoinvector(
477 IndexTuple *itvec, int *len,
478 IndexTuple *additvec, int addlen);
479 extern IndexTupleData *gistfillitupvec(IndexTuple *vec, int veclen, int *memlen);
481 extern IndexTuple gistunion(Relation r, IndexTuple *itvec,
482 int len, GISTSTATE *giststate);
483 extern IndexTuple gistgetadjusted(Relation r,
486 GISTSTATE *giststate);
487 extern IndexTuple gistFormTuple(GISTSTATE *giststate,
488 Relation r, Datum *attdata, bool *isnull, bool isleaf);
490 extern OffsetNumber gistchoose(Relation r, Page p,
492 GISTSTATE *giststate);
494 extern void GISTInitBuffer(Buffer b, uint32 f);
495 extern void gistdentryinit(GISTSTATE *giststate, int nkey, GISTENTRY *e,
496 Datum k, Relation r, Page pg, OffsetNumber o,
497 bool l, bool isNull);
499 extern float gistpenalty(GISTSTATE *giststate, int attno,
500 GISTENTRY *key1, bool isNull1,
501 GISTENTRY *key2, bool isNull2);
502 extern void gistMakeUnionItVec(GISTSTATE *giststate, IndexTuple *itvec, int len,
503 Datum *attr, bool *isnull);
504 extern bool gistKeyIsEQ(GISTSTATE *giststate, int attno, Datum a, Datum b);
505 extern void gistDeCompressAtt(GISTSTATE *giststate, Relation r, IndexTuple tuple, Page p,
506 OffsetNumber o, GISTENTRY *attdata, bool *isnull);
508 extern void gistMakeUnionKey(GISTSTATE *giststate, int attno,
509 GISTENTRY *entry1, bool isnull1,
510 GISTENTRY *entry2, bool isnull2,
511 Datum *dst, bool *dstisnull);
513 extern XLogRecPtr gistGetFakeLSN(Relation rel);
516 extern Datum gistbulkdelete(PG_FUNCTION_ARGS);
517 extern Datum gistvacuumcleanup(PG_FUNCTION_ARGS);
520 extern void gistSplitByKey(Relation r, Page page, IndexTuple *itup,
521 int len, GISTSTATE *giststate,
526 extern Datum gistbuild(PG_FUNCTION_ARGS);
527 extern void gistValidateBufferingOption(char *value);
529 /* gistbuildbuffers.c */
530 extern GISTBuildBuffers *gistInitBuildBuffers(int pagesPerBuffer, int levelStep,
532 extern GISTNodeBuffer *gistGetNodeBuffer(GISTBuildBuffers *gfbb,
533 GISTSTATE *giststate,
534 BlockNumber blkno, int level);
535 extern void gistPushItupToNodeBuffer(GISTBuildBuffers *gfbb,
536 GISTNodeBuffer *nodeBuffer, IndexTuple item);
537 extern bool gistPopItupFromNodeBuffer(GISTBuildBuffers *gfbb,
538 GISTNodeBuffer *nodeBuffer, IndexTuple *item);
539 extern void gistFreeBuildBuffers(GISTBuildBuffers *gfbb);
540 extern void gistRelocateBuildBuffersOnSplit(GISTBuildBuffers *gfbb,
541 GISTSTATE *giststate, Relation r,
542 int level, Buffer buffer,
544 extern void gistUnloadNodeBuffers(GISTBuildBuffers *gfbb);
546 #endif /* GIST_PRIVATE_H */