Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * gist.c
4 : : * interface routines for the postgres GiST index access method.
5 : : *
6 : : *
7 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
8 : : * Portions Copyright (c) 1994, Regents of the University of California
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/access/gist/gist.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/gist_private.h"
18 : : #include "access/gistscan.h"
19 : : #include "access/xloginsert.h"
20 : : #include "catalog/pg_collation.h"
21 : : #include "commands/vacuum.h"
22 : : #include "miscadmin.h"
23 : : #include "nodes/execnodes.h"
24 : : #include "storage/predicate.h"
25 : : #include "utils/fmgrprotos.h"
26 : : #include "utils/index_selfuncs.h"
27 : : #include "utils/memutils.h"
28 : : #include "utils/rel.h"
29 : :
30 : : /* non-export function prototypes */
31 : : static void gistfixsplit(GISTInsertState *state, GISTSTATE *giststate);
32 : : static bool gistinserttuple(GISTInsertState *state, GISTInsertStack *stack,
33 : : GISTSTATE *giststate, IndexTuple tuple, OffsetNumber oldoffnum);
34 : : static bool gistinserttuples(GISTInsertState *state, GISTInsertStack *stack,
35 : : GISTSTATE *giststate,
36 : : IndexTuple *tuples, int ntup, OffsetNumber oldoffnum,
37 : : Buffer leftchild, Buffer rightchild,
38 : : bool unlockbuf, bool unlockleftchild);
39 : : static void gistfinishsplit(GISTInsertState *state, GISTInsertStack *stack,
40 : : GISTSTATE *giststate, List *splitinfo, bool unlockbuf);
41 : : static void gistprunepage(Relation rel, Page page, Buffer buffer,
42 : : Relation heapRel);
43 : :
44 : :
45 : : #define ROTATEDIST(d) do { \
46 : : SplitPageLayout *tmp = palloc0_object(SplitPageLayout); \
47 : : tmp->block.blkno = InvalidBlockNumber; \
48 : : tmp->buffer = InvalidBuffer; \
49 : : tmp->next = (d); \
50 : : (d)=tmp; \
51 : : } while(0)
52 : :
53 : :
54 : : /*
55 : : * GiST handler function: return IndexAmRoutine with access method parameters
56 : : * and callbacks.
57 : : */
58 : : Datum
59 : 8786 : gisthandler(PG_FUNCTION_ARGS)
60 : : {
61 : : static const IndexAmRoutine amroutine = {
62 : : .type = T_IndexAmRoutine,
63 : : .amstrategies = 0,
64 : : .amsupport = GISTNProcs,
65 : : .amoptsprocnum = GIST_OPTIONS_PROC,
66 : : .amcanorder = false,
67 : : .amcanorderbyop = true,
68 : : .amcanhash = false,
69 : : .amconsistentequality = false,
70 : : .amconsistentordering = false,
71 : : .amcanbackward = false,
72 : : .amcanunique = false,
73 : : .amcanmulticol = true,
74 : : .amoptionalkey = true,
75 : : .amsearcharray = false,
76 : : .amsearchnulls = true,
77 : : .amstorage = true,
78 : : .amclusterable = true,
79 : : .ampredlocks = true,
80 : : .amcanparallel = false,
81 : : .amcanbuildparallel = false,
82 : : .amcaninclude = true,
83 : : .amusemaintenanceworkmem = false,
84 : : .amsummarizing = false,
85 : : .amparallelvacuumoptions =
86 : : VACUUM_OPTION_PARALLEL_BULKDEL | VACUUM_OPTION_PARALLEL_COND_CLEANUP,
87 : : .amkeytype = InvalidOid,
88 : :
89 : : .ambuild = gistbuild,
90 : : .ambuildempty = gistbuildempty,
91 : : .aminsert = gistinsert,
92 : : .aminsertcleanup = NULL,
93 : : .ambulkdelete = gistbulkdelete,
94 : : .amvacuumcleanup = gistvacuumcleanup,
95 : : .amcanreturn = gistcanreturn,
96 : : .amcostestimate = gistcostestimate,
97 : : .amgettreeheight = NULL,
98 : : .amoptions = gistoptions,
99 : : .amproperty = gistproperty,
100 : : .ambuildphasename = NULL,
101 : : .amvalidate = gistvalidate,
102 : : .amadjustmembers = gistadjustmembers,
103 : : .ambeginscan = gistbeginscan,
104 : : .amrescan = gistrescan,
105 : : .amgettuple = gistgettuple,
106 : : .amgetbitmap = gistgetbitmap,
107 : : .amendscan = gistendscan,
108 : : .ammarkpos = NULL,
109 : : .amrestrpos = NULL,
110 : : .amestimateparallelscan = NULL,
111 : : .aminitparallelscan = NULL,
112 : : .amparallelrescan = NULL,
113 : : .amtranslatestrategy = NULL,
114 : : .amtranslatecmptype = gisttranslatecmptype,
115 : : };
116 : :
117 : 8786 : PG_RETURN_POINTER(&amroutine);
118 : : }
119 : :
120 : : /*
121 : : * Create and return a temporary memory context for use by GiST. We
122 : : * _always_ invoke user-provided methods in a temporary memory
123 : : * context, so that memory leaks in those functions cannot cause
124 : : * problems. Also, we use some additional temporary contexts in the
125 : : * GiST code itself, to avoid the need to do some awkward manual
126 : : * memory management.
127 : : */
128 : : MemoryContext
129 : 6356 : createTempGistContext(void)
130 : : {
131 : 6356 : return AllocSetContextCreate(CurrentMemoryContext,
132 : : "GiST temporary context",
133 : : ALLOCSET_DEFAULT_SIZES);
134 : : }
135 : :
136 : : /*
137 : : * gistbuildempty() -- build an empty gist index in the initialization fork
138 : : */
139 : : void
140 : 6 : gistbuildempty(Relation index)
141 : : {
142 : : Buffer buffer;
143 : :
144 : : /* Initialize the root page */
145 : 6 : buffer = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
146 : : EB_SKIP_EXTENSION_LOCK | EB_LOCK_FIRST);
147 : :
148 : : /* Initialize and xlog buffer */
149 : 6 : START_CRIT_SECTION();
150 : 6 : GISTInitBuffer(buffer, F_LEAF);
151 : 6 : MarkBufferDirty(buffer);
152 : 6 : log_newpage_buffer(buffer, true);
153 : 6 : END_CRIT_SECTION();
154 : :
155 : : /* Unlock and release the buffer */
156 : 6 : UnlockReleaseBuffer(buffer);
157 : 6 : }
158 : :
159 : : /*
160 : : * gistinsert -- wrapper for GiST tuple insertion.
161 : : *
162 : : * This is the public interface routine for tuple insertion in GiSTs.
163 : : * It doesn't do any work; just locks the relation and passes the buck.
164 : : */
165 : : bool
166 : 194526 : gistinsert(Relation r, Datum *values, bool *isnull,
167 : : ItemPointer ht_ctid, Relation heapRel,
168 : : IndexUniqueCheck checkUnique,
169 : : bool indexUnchanged,
170 : : IndexInfo *indexInfo)
171 : : {
172 : 194526 : GISTSTATE *giststate = (GISTSTATE *) indexInfo->ii_AmCache;
173 : : IndexTuple itup;
174 : : MemoryContext oldCxt;
175 : :
176 : : /* Initialize GISTSTATE cache if first call in this statement */
177 [ + + ]: 194526 : if (giststate == NULL)
178 : : {
179 : 1257 : oldCxt = MemoryContextSwitchTo(indexInfo->ii_Context);
180 : 1257 : giststate = initGISTstate(r);
181 : 1257 : giststate->tempCxt = createTempGistContext();
182 : 1257 : indexInfo->ii_AmCache = giststate;
183 : 1257 : MemoryContextSwitchTo(oldCxt);
184 : : }
185 : :
186 : 194526 : oldCxt = MemoryContextSwitchTo(giststate->tempCxt);
187 : :
188 : 194526 : itup = gistFormTuple(giststate, r, values, isnull, true);
189 : 194525 : itup->t_tid = *ht_ctid;
190 : :
191 : 194525 : gistdoinsert(r, itup, 0, giststate, heapRel, false);
192 : :
193 : : /* cleanup */
194 : 194519 : MemoryContextSwitchTo(oldCxt);
195 : 194519 : MemoryContextReset(giststate->tempCxt);
196 : :
197 : 194519 : return false;
198 : : }
199 : :
200 : :
201 : : /*
202 : : * Place tuples from 'itup' to 'buffer'. If 'oldoffnum' is valid, the tuple
203 : : * at that offset is atomically removed along with inserting the new tuples.
204 : : * This is used to replace a tuple with a new one.
205 : : *
206 : : * If 'leftchildbuf' is valid, we're inserting the downlink for the page
207 : : * to the right of 'leftchildbuf', or updating the downlink for 'leftchildbuf'.
208 : : * F_FOLLOW_RIGHT flag on 'leftchildbuf' is cleared and NSN is set.
209 : : *
210 : : * If 'markfollowright' is true and the page is split, the left child is
211 : : * marked with F_FOLLOW_RIGHT flag. That is the normal case. During buffered
212 : : * index build, however, there is no concurrent access and the page splitting
213 : : * is done in a slightly simpler fashion, and false is passed.
214 : : *
215 : : * If there is not enough room on the page, it is split. All the split
216 : : * pages are kept pinned and locked and returned in *splitinfo, the caller
217 : : * is responsible for inserting the downlinks for them. However, if
218 : : * 'buffer' is the root page and it needs to be split, gistplacetopage()
219 : : * performs the split as one atomic operation, and *splitinfo is set to NIL.
220 : : * In that case, we continue to hold the root page locked, and the child
221 : : * pages are released; note that new tuple(s) are *not* on the root page
222 : : * but in one of the new child pages.
223 : : *
224 : : * If 'newblkno' is not NULL, returns the block number of page the first
225 : : * new/updated tuple was inserted to. Usually it's the given page, but could
226 : : * be its right sibling if the page was split.
227 : : *
228 : : * Returns 'true' if the page was split, 'false' otherwise.
229 : : */
230 : : bool
231 : 1026625 : gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
232 : : Buffer buffer,
233 : : IndexTuple *itup, int ntup, OffsetNumber oldoffnum,
234 : : BlockNumber *newblkno,
235 : : Buffer leftchildbuf,
236 : : List **splitinfo,
237 : : bool markfollowright,
238 : : Relation heapRel,
239 : : bool is_build)
240 : : {
241 : 1026625 : BlockNumber blkno = BufferGetBlockNumber(buffer);
242 : 1026625 : Page page = BufferGetPage(buffer);
243 : 1026625 : bool is_leaf = (GistPageIsLeaf(page)) ? true : false;
244 : : XLogRecPtr recptr;
245 : : bool is_split;
246 : :
247 : : /*
248 : : * Refuse to modify a page that's incompletely split. This should not
249 : : * happen because we finish any incomplete splits while we walk down the
250 : : * tree. However, it's remotely possible that another concurrent inserter
251 : : * splits a parent page, and errors out before completing the split. We
252 : : * will just throw an error in that case, and leave any split we had in
253 : : * progress unfinished too. The next insert that comes along will clean up
254 : : * the mess.
255 : : */
256 [ - + ]: 1026625 : if (GistFollowRight(page))
257 [ # # ]: 0 : elog(ERROR, "concurrent GiST page split was incomplete");
258 : :
259 : : /* should never try to insert to a deleted page */
260 : : Assert(!GistPageIsDeleted(page));
261 : :
262 : 1026625 : *splitinfo = NIL;
263 : :
264 : : /*
265 : : * if isupdate, remove old key: This node's key has been modified, either
266 : : * because a child split occurred or because we needed to adjust our key
267 : : * for an insert in a child node. Therefore, remove the old version of
268 : : * this node's key.
269 : : *
270 : : * for WAL replay, in the non-split case we handle this by setting up a
271 : : * one-element todelete array; in the split case, it's handled implicitly
272 : : * because the tuple vector passed to gistSplit won't include this tuple.
273 : : */
274 : 1026625 : is_split = gistnospace(page, itup, ntup, oldoffnum, freespace);
275 : :
276 : : /*
277 : : * If leaf page is full, try at first to delete dead tuples. And then
278 : : * check again.
279 : : */
280 [ + + + + : 1026625 : if (is_split && GistPageIsLeaf(page) && GistPageHasGarbage(page))
+ + ]
281 : : {
282 : 12 : gistprunepage(rel, page, buffer, heapRel);
283 : 12 : is_split = gistnospace(page, itup, ntup, oldoffnum, freespace);
284 : : }
285 : :
286 [ + + ]: 1026625 : if (is_split)
287 : : {
288 : : /* no space for insertion */
289 : : IndexTuple *itvec;
290 : : int tlen;
291 : 14299 : SplitPageLayout *dist = NULL,
292 : : *ptr;
293 : 14299 : BlockNumber oldrlink = InvalidBlockNumber;
294 : 14299 : GistNSN oldnsn = InvalidXLogRecPtr;
295 : : SplitPageLayout rootpg;
296 : : bool is_rootsplit;
297 : : int npage;
298 : :
299 : 14299 : is_rootsplit = (blkno == GIST_ROOT_BLKNO);
300 : :
301 : : /*
302 : : * Form index tuples vector to split. If we're replacing an old tuple,
303 : : * remove the old version from the vector.
304 : : */
305 : 14299 : itvec = gistextractpage(page, &tlen);
306 [ + + + - : 14299 : if (OffsetNumberIsValid(oldoffnum))
+ + ]
307 : : {
308 : : /* on inner page we should remove old tuple */
309 : 2754 : int pos = oldoffnum - FirstOffsetNumber;
310 : :
311 : 2754 : tlen--;
312 [ + + ]: 2754 : if (pos != tlen)
313 : 1793 : memmove(itvec + pos, itvec + pos + 1, sizeof(IndexTuple) * (tlen - pos));
314 : : }
315 : 14299 : itvec = gistjoinvector(itvec, &tlen, itup, ntup);
316 : 14299 : dist = gistSplit(rel, page, itvec, tlen, giststate);
317 : :
318 : : /*
319 : : * Check that split didn't produce too many pages.
320 : : */
321 : 14299 : npage = 0;
322 [ + + ]: 42938 : for (ptr = dist; ptr; ptr = ptr->next)
323 : 28639 : npage++;
324 : : /* in a root split, we'll add one more page to the list below */
325 [ + + ]: 14299 : if (is_rootsplit)
326 : 212 : npage++;
327 [ - + ]: 14299 : if (npage > GIST_MAX_SPLIT_PAGES)
328 [ # # ]: 0 : elog(ERROR, "GiST page split into too many halves (%d, maximum %d)",
329 : : npage, GIST_MAX_SPLIT_PAGES);
330 : :
331 : : /*
332 : : * Set up pages to work with. Allocate new buffers for all but the
333 : : * leftmost page. The original page becomes the new leftmost page, and
334 : : * is just replaced with the new contents.
335 : : *
336 : : * For a root-split, allocate new buffers for all child pages, the
337 : : * original page is overwritten with new root page containing
338 : : * downlinks to the new child pages.
339 : : */
340 : 14299 : ptr = dist;
341 [ + + ]: 14299 : if (!is_rootsplit)
342 : : {
343 : : /* save old rightlink and NSN */
344 : 14087 : oldrlink = GistPageGetOpaque(page)->rightlink;
345 : 14087 : oldnsn = GistPageGetNSN(page);
346 : :
347 : 14087 : dist->buffer = buffer;
348 : 14087 : dist->block.blkno = BufferGetBlockNumber(buffer);
349 : 14087 : dist->page = PageGetTempPageCopySpecial(BufferGetPage(buffer));
350 : :
351 : : /* clean all flags except F_LEAF */
352 : 14087 : GistPageGetOpaque(dist->page)->flags = (is_leaf) ? F_LEAF : 0;
353 : :
354 : 14087 : ptr = ptr->next;
355 : : }
356 [ + + ]: 28851 : for (; ptr; ptr = ptr->next)
357 : : {
358 : : /* Allocate new page */
359 : 14552 : ptr->buffer = gistNewBuffer(rel, heapRel);
360 : 14552 : GISTInitBuffer(ptr->buffer, (is_leaf) ? F_LEAF : 0);
361 : 14552 : ptr->page = BufferGetPage(ptr->buffer);
362 : 14552 : ptr->block.blkno = BufferGetBlockNumber(ptr->buffer);
363 : 14552 : PredicateLockPageSplit(rel,
364 : : BufferGetBlockNumber(buffer),
365 : : BufferGetBlockNumber(ptr->buffer));
366 : : }
367 : :
368 : : /*
369 : : * Now that we know which blocks the new pages go to, set up downlink
370 : : * tuples to point to them.
371 : : */
372 [ + + ]: 42938 : for (ptr = dist; ptr; ptr = ptr->next)
373 : : {
374 : 28639 : ItemPointerSetBlockNumber(&(ptr->itup->t_tid), ptr->block.blkno);
375 : 28639 : GistTupleSetValid(ptr->itup);
376 : : }
377 : :
378 : : /*
379 : : * If this is a root split, we construct the new root page with the
380 : : * downlinks here directly, instead of requiring the caller to insert
381 : : * them. Add the new root page to the list along with the child pages.
382 : : */
383 [ + + ]: 14299 : if (is_rootsplit)
384 : : {
385 : : IndexTuple *downlinks;
386 : 212 : int ndownlinks = 0;
387 : : int i;
388 : :
389 : 212 : rootpg.buffer = buffer;
390 : 212 : rootpg.page = PageGetTempPageCopySpecial(BufferGetPage(rootpg.buffer));
391 : 212 : GistPageGetOpaque(rootpg.page)->flags = 0;
392 : :
393 : : /* Prepare a vector of all the downlinks */
394 [ + + ]: 638 : for (ptr = dist; ptr; ptr = ptr->next)
395 : 426 : ndownlinks++;
396 : 212 : downlinks = palloc_array(IndexTuple, ndownlinks);
397 [ + + ]: 638 : for (i = 0, ptr = dist; ptr; ptr = ptr->next)
398 : 426 : downlinks[i++] = ptr->itup;
399 : :
400 : 212 : rootpg.block.blkno = GIST_ROOT_BLKNO;
401 : 212 : rootpg.block.num = ndownlinks;
402 : 212 : rootpg.list = gistfillitupvec(downlinks, ndownlinks,
403 : : &(rootpg.lenlist));
404 : 212 : rootpg.itup = NULL;
405 : :
406 : 212 : rootpg.next = dist;
407 : 212 : dist = &rootpg;
408 : : }
409 : : else
410 : : {
411 : : /* Prepare split-info to be returned to caller */
412 [ + + ]: 42300 : for (ptr = dist; ptr; ptr = ptr->next)
413 : : {
414 : 28213 : GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
415 : :
416 : 28213 : si->buf = ptr->buffer;
417 : 28213 : si->downlink = ptr->itup;
418 : 28213 : *splitinfo = lappend(*splitinfo, si);
419 : : }
420 : : }
421 : :
422 : : /*
423 : : * Fill all pages. All the pages are new, ie. freshly allocated empty
424 : : * pages, or a temporary copy of the old page.
425 : : */
426 [ + + ]: 43150 : for (ptr = dist; ptr; ptr = ptr->next)
427 : : {
428 : 28851 : char *data = (char *) (ptr->list);
429 : :
430 [ + + ]: 1119553 : for (int i = 0; i < ptr->block.num; i++)
431 : : {
432 : 1090702 : IndexTuple thistup = (IndexTuple) data;
433 : :
434 [ - + ]: 1090702 : if (PageAddItem(ptr->page, data, IndexTupleSize(thistup), i + FirstOffsetNumber, false, false) == InvalidOffsetNumber)
435 [ # # ]: 0 : elog(ERROR, "failed to add item to index page in \"%s\"", RelationGetRelationName(rel));
436 : :
437 : : /*
438 : : * If this is the first inserted/updated tuple, let the caller
439 : : * know which page it landed on.
440 : : */
441 [ + + + + ]: 1090702 : if (newblkno && ItemPointerEquals(&thistup->t_tid, &(*itup)->t_tid))
442 : 516 : *newblkno = ptr->block.blkno;
443 : :
444 : 1090702 : data += IndexTupleSize(thistup);
445 : : }
446 : :
447 : : /* Set up rightlinks */
448 [ + + + + ]: 28851 : if (ptr->next && ptr->block.blkno != GIST_ROOT_BLKNO)
449 : 28680 : GistPageGetOpaque(ptr->page)->rightlink =
450 : 14340 : ptr->next->block.blkno;
451 : : else
452 : 14511 : GistPageGetOpaque(ptr->page)->rightlink = oldrlink;
453 : :
454 : : /*
455 : : * Mark the all but the right-most page with the follow-right
456 : : * flag. It will be cleared as soon as the downlink is inserted
457 : : * into the parent, but this ensures that if we error out before
458 : : * that, the index is still consistent. (in buffering build mode,
459 : : * any error will abort the index build anyway, so this is not
460 : : * needed.)
461 : : */
462 [ + + + + : 28851 : if (ptr->next && !is_rootsplit && markfollowright)
+ + ]
463 : 13614 : GistMarkFollowRight(ptr->page);
464 : : else
465 : 15237 : GistClearFollowRight(ptr->page);
466 : :
467 : : /*
468 : : * Copy the NSN of the original page to all pages. The
469 : : * F_FOLLOW_RIGHT flags ensure that scans will follow the
470 : : * rightlinks until the downlinks are inserted.
471 : : */
472 : 28851 : GistPageSetNSN(ptr->page, oldnsn);
473 : : }
474 : :
475 : : /*
476 : : * gistXLogSplit() needs to WAL log a lot of pages, prepare WAL
477 : : * insertion for that. NB: The number of pages and data segments
478 : : * specified here must match the calculations in gistXLogSplit()!
479 : : */
480 [ + + + + : 14299 : if (!is_build && RelationNeedsWAL(rel))
- + - - -
- ]
481 : 2220 : XLogEnsureRecordSpace(npage, 1 + npage * 2);
482 : :
483 : 14299 : START_CRIT_SECTION();
484 : :
485 : : /*
486 : : * Must mark buffers dirty before XLogInsert, even though we'll still
487 : : * be changing their opaque fields below.
488 : : */
489 [ + + ]: 43150 : for (ptr = dist; ptr; ptr = ptr->next)
490 : 28851 : MarkBufferDirty(ptr->buffer);
491 [ + + ]: 14299 : if (BufferIsValid(leftchildbuf))
492 : 2663 : MarkBufferDirty(leftchildbuf);
493 : :
494 : : /*
495 : : * The first page in the chain was a temporary working copy meant to
496 : : * replace the old page. Copy it over the old page.
497 : : */
498 : 14299 : PageRestoreTempPage(dist->page, BufferGetPage(dist->buffer));
499 : 14299 : dist->page = BufferGetPage(dist->buffer);
500 : :
501 : : /*
502 : : * Write the WAL record.
503 : : *
504 : : * If we're building a new index, however, we don't WAL-log changes
505 : : * yet. The LSN-NSN interlock between parent and child requires that
506 : : * LSNs never move backwards, so set the LSNs to a value that's
507 : : * smaller than any real or fake unlogged LSN that might be generated
508 : : * later. (There can't be any concurrent scans during index build, so
509 : : * we don't need to be able to detect concurrent splits yet.)
510 : : */
511 [ + + ]: 14299 : if (is_build)
512 : 12076 : recptr = GistBuildLSN;
513 : : else
514 : : {
515 [ + + - + : 2223 : if (RelationNeedsWAL(rel))
- - - - ]
516 : 2220 : recptr = gistXLogSplit(is_leaf,
517 : : dist, oldrlink, oldnsn, leftchildbuf,
518 : : markfollowright);
519 : : else
520 : 3 : recptr = XLogGetFakeLSN(rel);
521 : : }
522 : :
523 [ + + ]: 43150 : for (ptr = dist; ptr; ptr = ptr->next)
524 : 28851 : PageSetLSN(ptr->page, recptr);
525 : :
526 : : /*
527 : : * Return the new child buffers to the caller.
528 : : *
529 : : * If this was a root split, we've already inserted the downlink
530 : : * pointers, in the form of a new root page. Therefore we can release
531 : : * all the new buffers, and keep just the root page locked.
532 : : */
533 [ + + ]: 14299 : if (is_rootsplit)
534 : : {
535 [ + + ]: 638 : for (ptr = dist->next; ptr; ptr = ptr->next)
536 : 426 : UnlockReleaseBuffer(ptr->buffer);
537 : : }
538 : : }
539 : : else
540 : : {
541 : : /*
542 : : * Enough space. We always get here if ntup==0.
543 : : */
544 : 1012326 : START_CRIT_SECTION();
545 : :
546 : : /*
547 : : * Delete old tuple if any, then insert new tuple(s) if any. If
548 : : * possible, use the fast path of PageIndexTupleOverwrite.
549 : : */
550 [ + + + - : 1012326 : if (OffsetNumberIsValid(oldoffnum))
+ + ]
551 : : {
552 [ + + ]: 462723 : if (ntup == 1)
553 : : {
554 : : /* One-for-one replacement, so use PageIndexTupleOverwrite */
555 [ - + ]: 451306 : if (!PageIndexTupleOverwrite(page, oldoffnum, *itup, IndexTupleSize(*itup)))
556 [ # # ]: 0 : elog(ERROR, "failed to add item to index page in \"%s\"",
557 : : RelationGetRelationName(rel));
558 : : }
559 : : else
560 : : {
561 : : /* Delete old, then append new tuple(s) to page */
562 : 11417 : PageIndexTupleDelete(page, oldoffnum);
563 : 11417 : gistfillbuffer(page, itup, ntup, InvalidOffsetNumber);
564 : : }
565 : : }
566 : : else
567 : : {
568 : : /* Just append new tuples at the end of the page */
569 : 549603 : gistfillbuffer(page, itup, ntup, InvalidOffsetNumber);
570 : : }
571 : :
572 : 1012326 : MarkBufferDirty(buffer);
573 : :
574 [ + + ]: 1012326 : if (BufferIsValid(leftchildbuf))
575 : 10951 : MarkBufferDirty(leftchildbuf);
576 : :
577 [ + + ]: 1012326 : if (is_build)
578 : 699416 : recptr = GistBuildLSN;
579 : : else
580 : : {
581 [ + + + + : 312910 : if (RelationNeedsWAL(rel))
+ - + - ]
582 : 312858 : {
583 : 312858 : OffsetNumber ndeloffs = 0,
584 : : deloffs[1];
585 : :
586 [ + + + - : 312858 : if (OffsetNumberIsValid(oldoffnum))
+ + ]
587 : : {
588 : 120599 : deloffs[0] = oldoffnum;
589 : 120599 : ndeloffs = 1;
590 : : }
591 : :
592 : 312858 : recptr = gistXLogUpdate(buffer,
593 : : deloffs, ndeloffs, itup, ntup,
594 : : leftchildbuf);
595 : : }
596 : : else
597 : 52 : recptr = XLogGetFakeLSN(rel);
598 : : }
599 : 1012326 : PageSetLSN(page, recptr);
600 : :
601 [ + + ]: 1012326 : if (newblkno)
602 : 69580 : *newblkno = blkno;
603 : : }
604 : :
605 : : /*
606 : : * If we inserted the downlink for a child page, set NSN and clear
607 : : * F_FOLLOW_RIGHT flag on the left child, so that concurrent scans know to
608 : : * follow the rightlink if and only if they looked at the parent page
609 : : * before we inserted the downlink.
610 : : *
611 : : * Note that we do this *after* writing the WAL record. That means that
612 : : * the possible full page image in the WAL record does not include these
613 : : * changes, and they must be replayed even if the page is restored from
614 : : * the full page image. There's a chicken-and-egg problem: if we updated
615 : : * the child pages first, we wouldn't know the recptr of the WAL record
616 : : * we're about to write.
617 : : */
618 [ + + ]: 1026625 : if (BufferIsValid(leftchildbuf))
619 : : {
620 : 13614 : Page leftpg = BufferGetPage(leftchildbuf);
621 : :
622 : 13614 : GistPageSetNSN(leftpg, recptr);
623 : 13614 : GistClearFollowRight(leftpg);
624 : :
625 : 13614 : PageSetLSN(leftpg, recptr);
626 : : }
627 : :
628 : 1026625 : END_CRIT_SECTION();
629 : :
630 : 1026625 : return is_split;
631 : : }
632 : :
633 : : /*
634 : : * Workhorse routine for doing insertion into a GiST index. Note that
635 : : * this routine assumes it is invoked in a short-lived memory context,
636 : : * so it does not bother releasing palloc'd allocations.
637 : : */
638 : : void
639 : 537495 : gistdoinsert(Relation r, IndexTuple itup, Size freespace,
640 : : GISTSTATE *giststate, Relation heapRel, bool is_build)
641 : : {
642 : : ItemId iid;
643 : : IndexTuple idxtuple;
644 : : GISTInsertStack firststack;
645 : : GISTInsertStack *stack;
646 : : GISTInsertState state;
647 : 537495 : bool xlocked = false;
648 : :
649 : 537495 : memset(&state, 0, sizeof(GISTInsertState));
650 : 537495 : state.freespace = freespace;
651 : 537495 : state.r = r;
652 : 537495 : state.heapRel = heapRel;
653 : 537495 : state.is_build = is_build;
654 : :
655 : : /* Start from the root */
656 : 537495 : firststack.blkno = GIST_ROOT_BLKNO;
657 : 537495 : firststack.lsn = InvalidXLogRecPtr;
658 : 537495 : firststack.retry_from_parent = false;
659 : 537495 : firststack.parent = NULL;
660 : 537495 : firststack.downlinkoffnum = InvalidOffsetNumber;
661 : 537495 : state.stack = stack = &firststack;
662 : :
663 : : /*
664 : : * Walk down along the path of smallest penalty, updating the parent
665 : : * pointers with the key we're inserting as we go. If we crash in the
666 : : * middle, the tree is consistent, although the possible parent updates
667 : : * were a waste.
668 : : */
669 : : for (;;)
670 : : {
671 : : /*
672 : : * If we split an internal page while descending the tree, we have to
673 : : * retry at the parent. (Normally, the LSN-NSN interlock below would
674 : : * also catch this and cause us to retry. But LSNs are not updated
675 : : * during index build.)
676 : : */
677 [ + + ]: 1220958 : while (stack->retry_from_parent)
678 : : {
679 [ - + ]: 160 : if (xlocked)
680 : 0 : LockBuffer(stack->buffer, GIST_UNLOCK);
681 : 160 : xlocked = false;
682 : 160 : ReleaseBuffer(stack->buffer);
683 : 160 : state.stack = stack = stack->parent;
684 : : }
685 : :
686 [ + + ]: 1220798 : if (!XLogRecPtrIsValid(stack->lsn))
687 : 1220714 : stack->buffer = ReadBuffer(state.r, stack->blkno);
688 : :
689 : : /*
690 : : * Be optimistic and grab shared lock first. Swap it for an exclusive
691 : : * lock later if we need to update the page.
692 : : */
693 [ + + ]: 1220798 : if (!xlocked)
694 : : {
695 : 1220797 : LockBuffer(stack->buffer, GIST_SHARE);
696 : 1220797 : gistcheckpage(state.r, stack->buffer);
697 : : }
698 : :
699 : 1220798 : stack->page = BufferGetPage(stack->buffer);
700 : 1220798 : stack->lsn = xlocked ?
701 [ + + ]: 1220798 : PageGetLSN(stack->page) : BufferGetLSNAtomic(stack->buffer);
702 : : Assert(!RelationNeedsWAL(state.r) || XLogRecPtrIsValid(stack->lsn));
703 : :
704 : : /*
705 : : * If this page was split but the downlink was never inserted to the
706 : : * parent because the inserting backend crashed before doing that, fix
707 : : * that now.
708 : : */
709 [ - + ]: 1220798 : if (GistFollowRight(stack->page))
710 : : {
711 [ # # ]: 0 : if (!xlocked)
712 : : {
713 : 0 : LockBuffer(stack->buffer, GIST_UNLOCK);
714 : 0 : LockBuffer(stack->buffer, GIST_EXCLUSIVE);
715 : 0 : xlocked = true;
716 : : /* someone might've completed the split when we unlocked */
717 [ # # ]: 0 : if (!GistFollowRight(stack->page))
718 : 0 : continue;
719 : : }
720 : 0 : gistfixsplit(&state, giststate);
721 : :
722 : 0 : UnlockReleaseBuffer(stack->buffer);
723 : 0 : xlocked = false;
724 : 0 : state.stack = stack = stack->parent;
725 : 0 : continue;
726 : : }
727 : :
728 [ + + + - ]: 1904029 : if ((stack->blkno != GIST_ROOT_BLKNO &&
729 : 683231 : stack->parent->lsn < GistPageGetNSN(stack->page)) ||
730 [ - + ]: 1220798 : GistPageIsDeleted(stack->page))
731 : : {
732 : : /*
733 : : * Concurrent split or page deletion detected. There's no
734 : : * guarantee that the downlink for this page is consistent with
735 : : * the tuple we're inserting anymore, so go back to parent and
736 : : * rechoose the best child.
737 : : */
738 : 0 : UnlockReleaseBuffer(stack->buffer);
739 : 0 : xlocked = false;
740 : 0 : state.stack = stack = stack->parent;
741 : 0 : continue;
742 : : }
743 : :
744 [ + + ]: 1220798 : if (!GistPageIsLeaf(stack->page))
745 : : {
746 : : /*
747 : : * This is an internal page so continue to walk down the tree.
748 : : * Find the child node that has the minimum insertion penalty.
749 : : */
750 : : BlockNumber childblkno;
751 : : IndexTuple newtup;
752 : : GISTInsertStack *item;
753 : : OffsetNumber downlinkoffnum;
754 : :
755 : 683303 : downlinkoffnum = gistchoose(state.r, stack->page, itup, giststate);
756 : 683303 : iid = PageGetItemId(stack->page, downlinkoffnum);
757 : 683303 : idxtuple = (IndexTuple) PageGetItem(stack->page, iid);
758 : 683303 : childblkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
759 : :
760 : : /*
761 : : * Check that it's not a leftover invalid tuple from pre-9.1
762 : : */
763 [ - + ]: 683303 : if (GistTupleIsInvalid(idxtuple))
764 [ # # ]: 0 : ereport(ERROR,
765 : : (errcode(ERRCODE_INDEX_CORRUPTED),
766 : : errmsg("index \"%s\" contains an inner tuple marked as invalid",
767 : : RelationGetRelationName(r)),
768 : : errdetail("This is caused by an incomplete page split at crash recovery before upgrading to PostgreSQL 9.1."),
769 : : errhint("Please REINDEX it.")));
770 : :
771 : : /*
772 : : * Check that the key representing the target child node is
773 : : * consistent with the key we're inserting. Update it if it's not.
774 : : */
775 : 683303 : newtup = gistgetadjusted(state.r, idxtuple, itup, giststate);
776 [ + + ]: 683303 : if (newtup)
777 : : {
778 : : /*
779 : : * Swap shared lock for an exclusive one. Beware, the page may
780 : : * change while we unlock/lock the page...
781 : : */
782 [ + - ]: 405426 : if (!xlocked)
783 : : {
784 : 405426 : LockBuffer(stack->buffer, GIST_UNLOCK);
785 : 405426 : LockBuffer(stack->buffer, GIST_EXCLUSIVE);
786 : 405426 : xlocked = true;
787 : 405426 : stack->page = BufferGetPage(stack->buffer);
788 : :
789 [ - + ]: 405426 : if (PageGetLSN(stack->page) != stack->lsn)
790 : : {
791 : : /* the page was changed while we unlocked it, retry */
792 : 0 : continue;
793 : : }
794 : : }
795 : :
796 : : /*
797 : : * Update the tuple.
798 : : *
799 : : * We still hold the lock after gistinserttuple(), but it
800 : : * might have to split the page to make the updated tuple fit.
801 : : * In that case the updated tuple might migrate to the other
802 : : * half of the split, so we have to go back to the parent and
803 : : * descend back to the half that's a better fit for the new
804 : : * tuple.
805 : : */
806 [ + + ]: 405426 : if (gistinserttuple(&state, stack, giststate, newtup,
807 : : downlinkoffnum))
808 : : {
809 : : /*
810 : : * If this was a root split, the root page continues to be
811 : : * the parent and the updated tuple went to one of the
812 : : * child pages, so we just need to retry from the root
813 : : * page.
814 : : */
815 [ + + ]: 84 : if (stack->blkno != GIST_ROOT_BLKNO)
816 : : {
817 : 83 : UnlockReleaseBuffer(stack->buffer);
818 : 83 : xlocked = false;
819 : 83 : state.stack = stack = stack->parent;
820 : : }
821 : 84 : continue;
822 : : }
823 : : }
824 : 683219 : LockBuffer(stack->buffer, GIST_UNLOCK);
825 : 683219 : xlocked = false;
826 : :
827 : : /* descend to the chosen child */
828 : 683219 : item = palloc0_object(GISTInsertStack);
829 : 683219 : item->blkno = childblkno;
830 : 683219 : item->parent = stack;
831 : 683219 : item->downlinkoffnum = downlinkoffnum;
832 : 683219 : state.stack = stack = item;
833 : : }
834 : : else
835 : : {
836 : : /*
837 : : * Leaf page. Insert the new key. We've already updated all the
838 : : * parents on the way down, but we might have to split the page if
839 : : * it doesn't fit. gistinserttuple() will take care of that.
840 : : */
841 : :
842 : : /*
843 : : * Swap shared lock for an exclusive one. Be careful, the page may
844 : : * change while we unlock/lock the page...
845 : : */
846 [ + - ]: 537495 : if (!xlocked)
847 : : {
848 : 537495 : LockBuffer(stack->buffer, GIST_UNLOCK);
849 : 537495 : LockBuffer(stack->buffer, GIST_EXCLUSIVE);
850 : 537495 : xlocked = true;
851 : 537495 : stack->page = BufferGetPage(stack->buffer);
852 : 537495 : stack->lsn = PageGetLSN(stack->page);
853 : :
854 [ + + ]: 537495 : if (stack->blkno == GIST_ROOT_BLKNO)
855 : : {
856 : : /*
857 : : * the only page that can become inner instead of leaf is
858 : : * the root page, so for root we should recheck it
859 : : */
860 [ - + ]: 23728 : if (!GistPageIsLeaf(stack->page))
861 : : {
862 : : /*
863 : : * very rare situation: during unlock/lock index with
864 : : * number of pages = 1 was increased
865 : : */
866 : 0 : LockBuffer(stack->buffer, GIST_UNLOCK);
867 : 0 : xlocked = false;
868 : 0 : continue;
869 : : }
870 : :
871 : : /*
872 : : * we don't need to check root split, because checking
873 : : * leaf/inner is enough to recognize split for root
874 : : */
875 : : }
876 [ + - + - ]: 1027534 : else if ((GistFollowRight(stack->page) ||
877 : 513767 : stack->parent->lsn < GistPageGetNSN(stack->page)) ||
878 [ - + ]: 513767 : GistPageIsDeleted(stack->page))
879 : : {
880 : : /*
881 : : * The page was split or deleted while we momentarily
882 : : * unlocked the page. Go back to parent.
883 : : */
884 : 0 : UnlockReleaseBuffer(stack->buffer);
885 : 0 : xlocked = false;
886 : 0 : state.stack = stack = stack->parent;
887 : 0 : continue;
888 : : }
889 : : }
890 : :
891 : : /* now state.stack->(page, buffer and blkno) points to leaf page */
892 : :
893 : 537495 : gistinserttuple(&state, stack, giststate, itup,
894 : : InvalidOffsetNumber);
895 : 537489 : LockBuffer(stack->buffer, GIST_UNLOCK);
896 : :
897 : : /* Release any pins we might still hold before exiting */
898 [ + + ]: 1757948 : for (; stack; stack = stack->parent)
899 : 1220459 : ReleaseBuffer(stack->buffer);
900 : 537489 : break;
901 : : }
902 : : }
903 : 537489 : }
904 : :
905 : : /*
906 : : * Traverse the tree to find path from root page to specified "child" block.
907 : : *
908 : : * returns a new insertion stack, starting from the parent of "child", up
909 : : * to the root. *downlinkoffnum is set to the offset of the downlink in the
910 : : * direct parent of child.
911 : : *
912 : : * To prevent deadlocks, this should lock only one page at a time.
913 : : */
914 : : static GISTInsertStack *
915 : 0 : gistFindPath(Relation r, BlockNumber child, OffsetNumber *downlinkoffnum)
916 : : {
917 : : Page page;
918 : : Buffer buffer;
919 : : OffsetNumber i,
920 : : maxoff;
921 : : ItemId iid;
922 : : IndexTuple idxtuple;
923 : : List *fifo;
924 : : GISTInsertStack *top,
925 : : *ptr;
926 : : BlockNumber blkno;
927 : :
928 : 0 : top = palloc0_object(GISTInsertStack);
929 : 0 : top->blkno = GIST_ROOT_BLKNO;
930 : 0 : top->downlinkoffnum = InvalidOffsetNumber;
931 : :
932 : 0 : fifo = list_make1(top);
933 [ # # ]: 0 : while (fifo != NIL)
934 : : {
935 : : /* Get next page to visit */
936 : 0 : top = linitial(fifo);
937 : 0 : fifo = list_delete_first(fifo);
938 : :
939 : 0 : buffer = ReadBuffer(r, top->blkno);
940 : 0 : LockBuffer(buffer, GIST_SHARE);
941 : 0 : gistcheckpage(r, buffer);
942 : 0 : page = BufferGetPage(buffer);
943 : :
944 [ # # ]: 0 : if (GistPageIsLeaf(page))
945 : : {
946 : : /*
947 : : * Because we scan the index top-down, all the rest of the pages
948 : : * in the queue must be leaf pages as well.
949 : : */
950 : 0 : UnlockReleaseBuffer(buffer);
951 : 0 : break;
952 : : }
953 : :
954 : : /* currently, internal pages are never deleted */
955 : : Assert(!GistPageIsDeleted(page));
956 : :
957 : 0 : top->lsn = BufferGetLSNAtomic(buffer);
958 : :
959 : : /*
960 : : * If F_FOLLOW_RIGHT is set, the page to the right doesn't have a
961 : : * downlink. This should not normally happen..
962 : : */
963 [ # # ]: 0 : if (GistFollowRight(page))
964 [ # # ]: 0 : elog(ERROR, "concurrent GiST page split was incomplete");
965 : :
966 [ # # # # ]: 0 : if (top->parent && top->parent->lsn < GistPageGetNSN(page) &&
967 [ # # ]: 0 : GistPageGetOpaque(page)->rightlink != InvalidBlockNumber /* sanity check */ )
968 : : {
969 : : /*
970 : : * Page was split while we looked elsewhere. We didn't see the
971 : : * downlink to the right page when we scanned the parent, so add
972 : : * it to the queue now.
973 : : *
974 : : * Put the right page ahead of the queue, so that we visit it
975 : : * next. That's important, because if this is the lowest internal
976 : : * level, just above leaves, we might already have queued up some
977 : : * leaf pages, and we assume that there can't be any non-leaf
978 : : * pages behind leaf pages.
979 : : */
980 : 0 : ptr = palloc0_object(GISTInsertStack);
981 : 0 : ptr->blkno = GistPageGetOpaque(page)->rightlink;
982 : 0 : ptr->downlinkoffnum = InvalidOffsetNumber;
983 : 0 : ptr->parent = top->parent;
984 : :
985 : 0 : fifo = lcons(ptr, fifo);
986 : : }
987 : :
988 : 0 : maxoff = PageGetMaxOffsetNumber(page);
989 : :
990 [ # # ]: 0 : for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
991 : : {
992 : 0 : iid = PageGetItemId(page, i);
993 : 0 : idxtuple = (IndexTuple) PageGetItem(page, iid);
994 : 0 : blkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
995 [ # # ]: 0 : if (blkno == child)
996 : : {
997 : : /* Found it! */
998 : 0 : UnlockReleaseBuffer(buffer);
999 : 0 : *downlinkoffnum = i;
1000 : 0 : return top;
1001 : : }
1002 : : else
1003 : : {
1004 : : /* Append this child to the list of pages to visit later */
1005 : 0 : ptr = palloc0_object(GISTInsertStack);
1006 : 0 : ptr->blkno = blkno;
1007 : 0 : ptr->downlinkoffnum = i;
1008 : 0 : ptr->parent = top;
1009 : :
1010 : 0 : fifo = lappend(fifo, ptr);
1011 : : }
1012 : : }
1013 : :
1014 : 0 : UnlockReleaseBuffer(buffer);
1015 : : }
1016 : :
1017 [ # # ]: 0 : elog(ERROR, "failed to re-find parent of a page in index \"%s\", block %u",
1018 : : RelationGetRelationName(r), child);
1019 : : return NULL; /* keep compiler quiet */
1020 : : }
1021 : :
1022 : : /*
1023 : : * Updates the stack so that child->parent is the correct parent of the
1024 : : * child. child->parent must be exclusively locked on entry, and will
1025 : : * remain so at exit, but it might not be the same page anymore.
1026 : : */
1027 : : static void
1028 : 13614 : gistFindCorrectParent(Relation r, GISTInsertStack *child, bool is_build)
1029 : : {
1030 : 13614 : GISTInsertStack *parent = child->parent;
1031 : : ItemId iid;
1032 : : IndexTuple idxtuple;
1033 : : OffsetNumber maxoff;
1034 : : GISTInsertStack *ptr;
1035 : :
1036 : 13614 : gistcheckpage(r, parent->buffer);
1037 : 13614 : parent->page = BufferGetPage(parent->buffer);
1038 : 13614 : maxoff = PageGetMaxOffsetNumber(parent->page);
1039 : :
1040 : : /* Check if the downlink is still where it was before */
1041 [ + + - + ]: 13614 : if (child->downlinkoffnum != InvalidOffsetNumber && child->downlinkoffnum <= maxoff)
1042 : : {
1043 : 13600 : iid = PageGetItemId(parent->page, child->downlinkoffnum);
1044 : 13600 : idxtuple = (IndexTuple) PageGetItem(parent->page, iid);
1045 [ - + ]: 13600 : if (ItemPointerGetBlockNumber(&(idxtuple->t_tid)) == child->blkno)
1046 : 13600 : return; /* still there */
1047 : : }
1048 : :
1049 : : /*
1050 : : * The page has changed since we looked. During normal operation, every
1051 : : * update of a page changes its LSN, so the LSN we memorized should have
1052 : : * changed too.
1053 : : *
1054 : : * During index build, however, we don't WAL-log the changes until we have
1055 : : * built the index, so the LSN doesn't change. There is no concurrent
1056 : : * activity during index build, but we might have changed the parent
1057 : : * ourselves.
1058 : : *
1059 : : * We will also get here if child->downlinkoffnum is invalid. That happens
1060 : : * if 'parent' had been updated by an earlier call to this function on its
1061 : : * grandchild, which had to move right.
1062 : : */
1063 : : Assert(parent->lsn != PageGetLSN(parent->page) || is_build ||
1064 : : child->downlinkoffnum == InvalidOffsetNumber);
1065 : :
1066 : : /*
1067 : : * Scan the page to re-find the downlink. If the page was split, it might
1068 : : * have moved to a different page, so follow the right links until we find
1069 : : * it.
1070 : : */
1071 : : while (true)
1072 : 7 : {
1073 : : OffsetNumber i;
1074 : :
1075 : 21 : maxoff = PageGetMaxOffsetNumber(parent->page);
1076 [ + + ]: 94 : for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
1077 : : {
1078 : 87 : iid = PageGetItemId(parent->page, i);
1079 : 87 : idxtuple = (IndexTuple) PageGetItem(parent->page, iid);
1080 [ + + ]: 87 : if (ItemPointerGetBlockNumber(&(idxtuple->t_tid)) == child->blkno)
1081 : : {
1082 : : /* yes!!, found */
1083 : 14 : child->downlinkoffnum = i;
1084 : 14 : return;
1085 : : }
1086 : : }
1087 : :
1088 : 7 : parent->blkno = GistPageGetOpaque(parent->page)->rightlink;
1089 : 7 : parent->downlinkoffnum = InvalidOffsetNumber;
1090 : 7 : UnlockReleaseBuffer(parent->buffer);
1091 [ - + ]: 7 : if (parent->blkno == InvalidBlockNumber)
1092 : : {
1093 : : /*
1094 : : * End of chain and still didn't find parent. It's a very-very
1095 : : * rare situation when the root was split.
1096 : : */
1097 : 0 : break;
1098 : : }
1099 : 7 : parent->buffer = ReadBuffer(r, parent->blkno);
1100 : 7 : LockBuffer(parent->buffer, GIST_EXCLUSIVE);
1101 : 7 : gistcheckpage(r, parent->buffer);
1102 : 7 : parent->page = BufferGetPage(parent->buffer);
1103 : : }
1104 : :
1105 : : /*
1106 : : * awful!!, we need search tree to find parent ... , but before we should
1107 : : * release all old parent
1108 : : */
1109 : :
1110 : 0 : ptr = child->parent->parent; /* child->parent already released above */
1111 [ # # ]: 0 : while (ptr)
1112 : : {
1113 : 0 : ReleaseBuffer(ptr->buffer);
1114 : 0 : ptr = ptr->parent;
1115 : : }
1116 : :
1117 : : /* ok, find new path */
1118 : 0 : ptr = parent = gistFindPath(r, child->blkno, &child->downlinkoffnum);
1119 : :
1120 : : /* read all buffers as expected by caller */
1121 : : /* note we don't lock them or gistcheckpage them here! */
1122 [ # # ]: 0 : while (ptr)
1123 : : {
1124 : 0 : ptr->buffer = ReadBuffer(r, ptr->blkno);
1125 : 0 : ptr->page = BufferGetPage(ptr->buffer);
1126 : 0 : ptr = ptr->parent;
1127 : : }
1128 : :
1129 : : /* install new chain of parents to stack */
1130 : 0 : child->parent = parent;
1131 : :
1132 : : /* make recursive call to normal processing */
1133 : 0 : LockBuffer(child->parent->buffer, GIST_EXCLUSIVE);
1134 : 0 : gistFindCorrectParent(r, child, is_build);
1135 : : }
1136 : :
1137 : : /*
1138 : : * Form a downlink pointer for the page in 'buf'.
1139 : : */
1140 : : static IndexTuple
1141 : 0 : gistformdownlink(Relation rel, Buffer buf, GISTSTATE *giststate,
1142 : : GISTInsertStack *stack, bool is_build)
1143 : : {
1144 : 0 : Page page = BufferGetPage(buf);
1145 : : OffsetNumber maxoff;
1146 : : OffsetNumber offset;
1147 : 0 : IndexTuple downlink = NULL;
1148 : :
1149 : 0 : maxoff = PageGetMaxOffsetNumber(page);
1150 [ # # ]: 0 : for (offset = FirstOffsetNumber; offset <= maxoff; offset = OffsetNumberNext(offset))
1151 : : {
1152 : : IndexTuple ituple = (IndexTuple)
1153 : 0 : PageGetItem(page, PageGetItemId(page, offset));
1154 : :
1155 [ # # ]: 0 : if (downlink == NULL)
1156 : 0 : downlink = CopyIndexTuple(ituple);
1157 : : else
1158 : : {
1159 : : IndexTuple newdownlink;
1160 : :
1161 : 0 : newdownlink = gistgetadjusted(rel, downlink, ituple,
1162 : : giststate);
1163 [ # # ]: 0 : if (newdownlink)
1164 : 0 : downlink = newdownlink;
1165 : : }
1166 : : }
1167 : :
1168 : : /*
1169 : : * If the page is completely empty, we can't form a meaningful downlink
1170 : : * for it. But we have to insert a downlink for the page. Any key will do,
1171 : : * as long as its consistent with the downlink of parent page, so that we
1172 : : * can legally insert it to the parent. A minimal one that matches as few
1173 : : * scans as possible would be best, to keep scans from doing useless work,
1174 : : * but we don't know how to construct that. So we just use the downlink of
1175 : : * the original page that was split - that's as far from optimal as it can
1176 : : * get but will do..
1177 : : */
1178 [ # # ]: 0 : if (!downlink)
1179 : : {
1180 : : ItemId iid;
1181 : :
1182 : 0 : LockBuffer(stack->parent->buffer, GIST_EXCLUSIVE);
1183 : 0 : gistFindCorrectParent(rel, stack, is_build);
1184 : 0 : iid = PageGetItemId(stack->parent->page, stack->downlinkoffnum);
1185 : 0 : downlink = (IndexTuple) PageGetItem(stack->parent->page, iid);
1186 : 0 : downlink = CopyIndexTuple(downlink);
1187 : 0 : LockBuffer(stack->parent->buffer, GIST_UNLOCK);
1188 : : }
1189 : :
1190 : 0 : ItemPointerSetBlockNumber(&(downlink->t_tid), BufferGetBlockNumber(buf));
1191 : 0 : GistTupleSetValid(downlink);
1192 : :
1193 : 0 : return downlink;
1194 : : }
1195 : :
1196 : :
1197 : : /*
1198 : : * Complete the incomplete split of state->stack->page.
1199 : : */
1200 : : static void
1201 : 0 : gistfixsplit(GISTInsertState *state, GISTSTATE *giststate)
1202 : : {
1203 : 0 : GISTInsertStack *stack = state->stack;
1204 : : Buffer buf;
1205 : : Page page;
1206 : 0 : List *splitinfo = NIL;
1207 : :
1208 [ # # ]: 0 : ereport(LOG,
1209 : : (errmsg("fixing incomplete split in index \"%s\", block %u",
1210 : : RelationGetRelationName(state->r), stack->blkno)));
1211 : :
1212 : : Assert(GistFollowRight(stack->page));
1213 : : Assert(OffsetNumberIsValid(stack->downlinkoffnum));
1214 : :
1215 : 0 : buf = stack->buffer;
1216 : :
1217 : : /*
1218 : : * Read the chain of split pages, following the rightlinks. Construct a
1219 : : * downlink tuple for each page.
1220 : : */
1221 : : for (;;)
1222 : 0 : {
1223 : 0 : GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
1224 : : IndexTuple downlink;
1225 : :
1226 : 0 : page = BufferGetPage(buf);
1227 : :
1228 : : /* Form the new downlink tuples to insert to parent */
1229 : 0 : downlink = gistformdownlink(state->r, buf, giststate, stack, state->is_build);
1230 : :
1231 : 0 : si->buf = buf;
1232 : 0 : si->downlink = downlink;
1233 : :
1234 : 0 : splitinfo = lappend(splitinfo, si);
1235 : :
1236 [ # # ]: 0 : if (GistFollowRight(page))
1237 : : {
1238 : : /* lock next page */
1239 : 0 : buf = ReadBuffer(state->r, GistPageGetOpaque(page)->rightlink);
1240 : 0 : LockBuffer(buf, GIST_EXCLUSIVE);
1241 : : }
1242 : : else
1243 : 0 : break;
1244 : : }
1245 : :
1246 : : /* Insert the downlinks */
1247 : 0 : gistfinishsplit(state, stack, giststate, splitinfo, false);
1248 : 0 : }
1249 : :
1250 : : /*
1251 : : * Insert or replace a tuple in stack->buffer. If 'oldoffnum' is valid, the
1252 : : * tuple at 'oldoffnum' is replaced, otherwise the tuple is inserted as new.
1253 : : * 'stack' represents the path from the root to the page being updated.
1254 : : *
1255 : : * The caller must hold an exclusive lock on stack->buffer. The lock is still
1256 : : * held on return, but the page might not contain the inserted tuple if the
1257 : : * page was split. The function returns true if the page was split, false
1258 : : * otherwise.
1259 : : */
1260 : : static bool
1261 : 942921 : gistinserttuple(GISTInsertState *state, GISTInsertStack *stack,
1262 : : GISTSTATE *giststate, IndexTuple tuple, OffsetNumber oldoffnum)
1263 : : {
1264 : 942921 : return gistinserttuples(state, stack, giststate, &tuple, 1, oldoffnum,
1265 : : InvalidBuffer, InvalidBuffer, false, false);
1266 : : }
1267 : :
1268 : : /* ----------------
1269 : : * An extended workhorse version of gistinserttuple(). This version allows
1270 : : * inserting multiple tuples, or replacing a single tuple with multiple tuples.
1271 : : * This is used to recursively update the downlinks in the parent when a page
1272 : : * is split.
1273 : : *
1274 : : * If leftchild and rightchild are valid, we're inserting/replacing the
1275 : : * downlink for rightchild, and leftchild is its left sibling. We clear the
1276 : : * F_FOLLOW_RIGHT flag and update NSN on leftchild, atomically with the
1277 : : * insertion of the downlink.
1278 : : *
1279 : : * To avoid holding locks for longer than necessary, when recursing up the
1280 : : * tree to update the parents, the locking is a bit peculiar here. On entry,
1281 : : * the caller must hold an exclusive lock on stack->buffer, as well as
1282 : : * leftchild and rightchild if given. On return:
1283 : : *
1284 : : * - Lock on stack->buffer is released, if 'unlockbuf' is true. The page is
1285 : : * always kept pinned, however.
1286 : : * - Lock on 'leftchild' is released, if 'unlockleftchild' is true. The page
1287 : : * is kept pinned.
1288 : : * - Lock and pin on 'rightchild' are always released.
1289 : : *
1290 : : * Returns 'true' if the page had to be split. Note that if the page was
1291 : : * split, the inserted/updated tuples might've been inserted to a right
1292 : : * sibling of stack->buffer instead of stack->buffer itself.
1293 : : */
1294 : : static bool
1295 : 956535 : gistinserttuples(GISTInsertState *state, GISTInsertStack *stack,
1296 : : GISTSTATE *giststate,
1297 : : IndexTuple *tuples, int ntup, OffsetNumber oldoffnum,
1298 : : Buffer leftchild, Buffer rightchild,
1299 : : bool unlockbuf, bool unlockleftchild)
1300 : : {
1301 : : List *splitinfo;
1302 : : bool is_split;
1303 : :
1304 : : /*
1305 : : * Check for any rw conflicts (in serializable isolation level) just
1306 : : * before we intend to modify the page
1307 : : */
1308 : 956535 : CheckForSerializableConflictIn(state->r, NULL, BufferGetBlockNumber(stack->buffer));
1309 : :
1310 : : /* Insert the tuple(s) to the page, splitting the page if necessary */
1311 : 956529 : is_split = gistplacetopage(state->r, state->freespace, giststate,
1312 : : stack->buffer,
1313 : : tuples, ntup,
1314 : : oldoffnum, NULL,
1315 : : leftchild,
1316 : : &splitinfo,
1317 : : true,
1318 : : state->heapRel,
1319 : 956529 : state->is_build);
1320 : :
1321 : : /*
1322 : : * Before recursing up in case the page was split, release locks on the
1323 : : * child pages. We don't need to keep them locked when updating the
1324 : : * parent.
1325 : : */
1326 [ + + ]: 956529 : if (BufferIsValid(rightchild))
1327 : 13614 : UnlockReleaseBuffer(rightchild);
1328 [ + + + + ]: 956529 : if (BufferIsValid(leftchild) && unlockleftchild)
1329 : 2593 : LockBuffer(leftchild, GIST_UNLOCK);
1330 : :
1331 : : /*
1332 : : * If we had to split, insert/update the downlinks in the parent. If the
1333 : : * caller requested us to release the lock on stack->buffer, tell
1334 : : * gistfinishsplit() to do that as soon as it's safe to do so. If we
1335 : : * didn't have to split, release it ourselves.
1336 : : */
1337 [ + + ]: 956529 : if (splitinfo)
1338 : 13575 : gistfinishsplit(state, stack, giststate, splitinfo, unlockbuf);
1339 [ + + ]: 942954 : else if (unlockbuf)
1340 : 10982 : LockBuffer(stack->buffer, GIST_UNLOCK);
1341 : :
1342 : 956529 : return is_split;
1343 : : }
1344 : :
1345 : : /*
1346 : : * Finish an incomplete split by inserting/updating the downlinks in parent
1347 : : * page. 'splitinfo' contains all the child pages involved in the split,
1348 : : * from left-to-right.
1349 : : *
1350 : : * On entry, the caller must hold a lock on stack->buffer and all the child
1351 : : * pages in 'splitinfo'. If 'unlockbuf' is true, the lock on stack->buffer is
1352 : : * released on return. The child pages are always unlocked and unpinned.
1353 : : */
1354 : : static void
1355 : 13575 : gistfinishsplit(GISTInsertState *state, GISTInsertStack *stack,
1356 : : GISTSTATE *giststate, List *splitinfo, bool unlockbuf)
1357 : : {
1358 : : GISTPageSplitInfo *right;
1359 : : GISTPageSplitInfo *left;
1360 : : IndexTuple tuples[2];
1361 : :
1362 : : /* A split always contains at least two halves */
1363 : : Assert(list_length(splitinfo) >= 2);
1364 : :
1365 : : /*
1366 : : * We need to insert downlinks for each new page, and update the downlink
1367 : : * for the original (leftmost) page in the split. Begin at the rightmost
1368 : : * page, inserting one downlink at a time until there's only two pages
1369 : : * left. Finally insert the downlink for the last new page and update the
1370 : : * downlink for the original page as one operation.
1371 : : */
1372 : 13575 : LockBuffer(stack->parent->buffer, GIST_EXCLUSIVE);
1373 : :
1374 : : /*
1375 : : * Insert downlinks for the siblings from right to left, until there are
1376 : : * only two siblings left.
1377 : : */
1378 [ + + ]: 13614 : for (int pos = list_length(splitinfo) - 1; pos > 1; pos--)
1379 : : {
1380 : 39 : right = (GISTPageSplitInfo *) list_nth(splitinfo, pos);
1381 : 39 : left = (GISTPageSplitInfo *) list_nth(splitinfo, pos - 1);
1382 : :
1383 : 39 : gistFindCorrectParent(state->r, stack, state->is_build);
1384 [ + + ]: 39 : if (gistinserttuples(state, stack->parent, giststate,
1385 : : &right->downlink, 1,
1386 : : InvalidOffsetNumber,
1387 : : left->buf, right->buf, false, false))
1388 : : {
1389 : : /*
1390 : : * If the parent page was split, the existing downlink might have
1391 : : * moved.
1392 : : */
1393 : 5 : stack->downlinkoffnum = InvalidOffsetNumber;
1394 : : }
1395 : : /* gistinserttuples() released the lock on right->buf. */
1396 : : }
1397 : :
1398 : 13575 : right = (GISTPageSplitInfo *) lsecond(splitinfo);
1399 : 13575 : left = (GISTPageSplitInfo *) linitial(splitinfo);
1400 : :
1401 : : /*
1402 : : * Finally insert downlink for the remaining right page and update the
1403 : : * downlink for the original page to not contain the tuples that were
1404 : : * moved to the new pages.
1405 : : */
1406 : 13575 : tuples[0] = left->downlink;
1407 : 13575 : tuples[1] = right->downlink;
1408 : 13575 : gistFindCorrectParent(state->r, stack, state->is_build);
1409 : 13575 : (void) gistinserttuples(state, stack->parent, giststate,
1410 : : tuples, 2,
1411 : 13575 : stack->downlinkoffnum,
1412 : : left->buf, right->buf,
1413 : : true, /* Unlock parent */
1414 : : unlockbuf /* Unlock stack->buffer if caller
1415 : : * wants that */
1416 : : );
1417 : :
1418 : : /*
1419 : : * The downlink might have moved when we updated it. Even if the page
1420 : : * wasn't split, because gistinserttuples() implements updating the old
1421 : : * tuple by removing and re-inserting it!
1422 : : */
1423 : 13575 : stack->downlinkoffnum = InvalidOffsetNumber;
1424 : :
1425 : : Assert(left->buf == stack->buffer);
1426 : :
1427 : : /*
1428 : : * If we split the page because we had to adjust the downlink on an
1429 : : * internal page, while descending the tree for inserting a new tuple,
1430 : : * then this might no longer be the correct page for the new tuple. The
1431 : : * downlink to this page might not cover the new tuple anymore, it might
1432 : : * need to go to the newly-created right sibling instead. Tell the caller
1433 : : * to walk back up the stack, to re-check at the parent which page to
1434 : : * insert to.
1435 : : *
1436 : : * Normally, the LSN-NSN interlock during the tree descend would also
1437 : : * detect that a concurrent split happened (by ourselves), and cause us to
1438 : : * retry at the parent. But that mechanism doesn't work during index
1439 : : * build, because we don't do WAL-logging, and don't update LSNs, during
1440 : : * index build.
1441 : : */
1442 : 13575 : stack->retry_from_parent = true;
1443 : 13575 : }
1444 : :
1445 : : /*
1446 : : * gistSplit -- split a page in the tree and fill struct
1447 : : * used for XLOG and real writes buffers. Function is recursive, ie
1448 : : * it will split page until keys will fit in every page.
1449 : : */
1450 : : SplitPageLayout *
1451 : 15277 : gistSplit(Relation r,
1452 : : Page page,
1453 : : IndexTuple *itup, /* contains compressed entry */
1454 : : int len,
1455 : : GISTSTATE *giststate)
1456 : : {
1457 : : IndexTuple *lvectup,
1458 : : *rvectup;
1459 : : GistSplitVector v;
1460 : : int i;
1461 : 15277 : SplitPageLayout *res = NULL;
1462 : :
1463 : : /* this should never recurse very deeply, but better safe than sorry */
1464 : 15277 : check_stack_depth();
1465 : :
1466 : : /* there's no point in splitting an empty page */
1467 : : Assert(len > 0);
1468 : :
1469 : : /*
1470 : : * If a single tuple doesn't fit on a page, no amount of splitting will
1471 : : * help.
1472 : : */
1473 [ - + ]: 15277 : if (len == 1)
1474 [ # # ]: 0 : ereport(ERROR,
1475 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1476 : : errmsg("index row size %zu exceeds maximum %zu for index \"%s\"",
1477 : : IndexTupleSize(itup[0]), GiSTPageSize,
1478 : : RelationGetRelationName(r))));
1479 : :
1480 : 15277 : memset(v.spl_lisnull, true,
1481 : 15277 : sizeof(bool) * giststate->nonLeafTupdesc->natts);
1482 : 15277 : memset(v.spl_risnull, true,
1483 : 15277 : sizeof(bool) * giststate->nonLeafTupdesc->natts);
1484 : 15277 : gistSplitByKey(r, page, itup, len, giststate, &v, 0);
1485 : :
1486 : : /* form left and right vector */
1487 : 15277 : lvectup = palloc_array(IndexTuple, len + 1);
1488 : 15277 : rvectup = palloc_array(IndexTuple, len + 1);
1489 : :
1490 [ + + ]: 725268 : for (i = 0; i < v.splitVector.spl_nleft; i++)
1491 : 709991 : lvectup[i] = itup[v.splitVector.spl_left[i] - 1];
1492 : :
1493 [ + + ]: 816108 : for (i = 0; i < v.splitVector.spl_nright; i++)
1494 : 800831 : rvectup[i] = itup[v.splitVector.spl_right[i] - 1];
1495 : :
1496 : : /* finalize splitting (may need another split) */
1497 [ + + ]: 15277 : if (!gistfitpage(rvectup, v.splitVector.spl_nright))
1498 : : {
1499 : 456 : res = gistSplit(r, page, rvectup, v.splitVector.spl_nright, giststate);
1500 : : }
1501 : : else
1502 : : {
1503 : 14821 : ROTATEDIST(res);
1504 : 14821 : res->block.num = v.splitVector.spl_nright;
1505 : 14821 : res->list = gistfillitupvec(rvectup, v.splitVector.spl_nright, &(res->lenlist));
1506 : 14821 : res->itup = gistFormTuple(giststate, r, v.spl_rattr, v.spl_risnull, false);
1507 : : }
1508 : :
1509 [ + + ]: 15277 : if (!gistfitpage(lvectup, v.splitVector.spl_nleft))
1510 : : {
1511 : : SplitPageLayout *resptr,
1512 : : *subres;
1513 : :
1514 : 287 : resptr = subres = gistSplit(r, page, lvectup, v.splitVector.spl_nleft, giststate);
1515 : :
1516 : : /* install on list's tail */
1517 [ + + ]: 727 : while (resptr->next)
1518 : 440 : resptr = resptr->next;
1519 : :
1520 : 287 : resptr->next = res;
1521 : 287 : res = subres;
1522 : : }
1523 : : else
1524 : : {
1525 : 14990 : ROTATEDIST(res);
1526 : 14990 : res->block.num = v.splitVector.spl_nleft;
1527 : 14990 : res->list = gistfillitupvec(lvectup, v.splitVector.spl_nleft, &(res->lenlist));
1528 : 14990 : res->itup = gistFormTuple(giststate, r, v.spl_lattr, v.spl_lisnull, false);
1529 : : }
1530 : :
1531 : 15277 : return res;
1532 : : }
1533 : :
1534 : : /*
1535 : : * Create a GISTSTATE and fill it with information about the index
1536 : : */
1537 : : GISTSTATE *
1538 : 6108 : initGISTstate(Relation index)
1539 : : {
1540 : : GISTSTATE *giststate;
1541 : : MemoryContext scanCxt;
1542 : : MemoryContext oldCxt;
1543 : : int i;
1544 : :
1545 : : /* safety check to protect fixed-size arrays in GISTSTATE */
1546 [ - + ]: 6108 : if (index->rd_att->natts > INDEX_MAX_KEYS)
1547 [ # # ]: 0 : elog(ERROR, "numberOfAttributes %d > %d",
1548 : : index->rd_att->natts, INDEX_MAX_KEYS);
1549 : :
1550 : : /* Create the memory context that will hold the GISTSTATE */
1551 : 6108 : scanCxt = AllocSetContextCreate(CurrentMemoryContext,
1552 : : "GiST scan context",
1553 : : ALLOCSET_DEFAULT_SIZES);
1554 : 6108 : oldCxt = MemoryContextSwitchTo(scanCxt);
1555 : :
1556 : : /* Create and fill in the GISTSTATE */
1557 : 6108 : giststate = palloc_object(GISTSTATE);
1558 : :
1559 : 6108 : giststate->scanCxt = scanCxt;
1560 : 6108 : giststate->tempCxt = scanCxt; /* caller must change this if needed */
1561 : 6108 : giststate->leafTupdesc = index->rd_att;
1562 : :
1563 : : /*
1564 : : * The truncated tupdesc for non-leaf index tuples, which doesn't contain
1565 : : * the INCLUDE attributes.
1566 : : *
1567 : : * It is used to form tuples during tuple adjustment and page split.
1568 : : * B-tree creates shortened tuple descriptor for every truncated tuple,
1569 : : * because it is doing this less often: it does not have to form truncated
1570 : : * tuples during page split. Also, B-tree is not adjusting tuples on
1571 : : * internal pages the way GiST does.
1572 : : */
1573 : 12216 : giststate->nonLeafTupdesc = CreateTupleDescTruncatedCopy(index->rd_att,
1574 : 6108 : IndexRelationGetNumberOfKeyAttributes(index));
1575 : :
1576 [ + + ]: 16300 : for (i = 0; i < IndexRelationGetNumberOfKeyAttributes(index); i++)
1577 : : {
1578 : 10192 : fmgr_info_copy(&(giststate->consistentFn[i]),
1579 : 10192 : index_getprocinfo(index, i + 1, GIST_CONSISTENT_PROC),
1580 : : scanCxt);
1581 : 10192 : fmgr_info_copy(&(giststate->unionFn[i]),
1582 : 10192 : index_getprocinfo(index, i + 1, GIST_UNION_PROC),
1583 : : scanCxt);
1584 : :
1585 : : /* opclasses are not required to provide a Compress method */
1586 [ + + ]: 10192 : if (OidIsValid(index_getprocid(index, i + 1, GIST_COMPRESS_PROC)))
1587 : 3490 : fmgr_info_copy(&(giststate->compressFn[i]),
1588 : 3490 : index_getprocinfo(index, i + 1, GIST_COMPRESS_PROC),
1589 : : scanCxt);
1590 : : else
1591 : 6702 : giststate->compressFn[i].fn_oid = InvalidOid;
1592 : :
1593 : : /* opclasses are not required to provide a Decompress method */
1594 [ + + ]: 10192 : if (OidIsValid(index_getprocid(index, i + 1, GIST_DECOMPRESS_PROC)))
1595 : 979 : fmgr_info_copy(&(giststate->decompressFn[i]),
1596 : 979 : index_getprocinfo(index, i + 1, GIST_DECOMPRESS_PROC),
1597 : : scanCxt);
1598 : : else
1599 : 9213 : giststate->decompressFn[i].fn_oid = InvalidOid;
1600 : :
1601 : 10192 : fmgr_info_copy(&(giststate->penaltyFn[i]),
1602 : 10192 : index_getprocinfo(index, i + 1, GIST_PENALTY_PROC),
1603 : : scanCxt);
1604 : 10192 : fmgr_info_copy(&(giststate->picksplitFn[i]),
1605 : 10192 : index_getprocinfo(index, i + 1, GIST_PICKSPLIT_PROC),
1606 : : scanCxt);
1607 : 10192 : fmgr_info_copy(&(giststate->equalFn[i]),
1608 : 10192 : index_getprocinfo(index, i + 1, GIST_EQUAL_PROC),
1609 : : scanCxt);
1610 : :
1611 : : /* opclasses are not required to provide a Distance method */
1612 [ + + ]: 10192 : if (OidIsValid(index_getprocid(index, i + 1, GIST_DISTANCE_PROC)))
1613 : 1160 : fmgr_info_copy(&(giststate->distanceFn[i]),
1614 : 1160 : index_getprocinfo(index, i + 1, GIST_DISTANCE_PROC),
1615 : : scanCxt);
1616 : : else
1617 : 9032 : giststate->distanceFn[i].fn_oid = InvalidOid;
1618 : :
1619 : : /* opclasses are not required to provide a Fetch method */
1620 [ + + ]: 10192 : if (OidIsValid(index_getprocid(index, i + 1, GIST_FETCH_PROC)))
1621 : 815 : fmgr_info_copy(&(giststate->fetchFn[i]),
1622 : 815 : index_getprocinfo(index, i + 1, GIST_FETCH_PROC),
1623 : : scanCxt);
1624 : : else
1625 : 9377 : giststate->fetchFn[i].fn_oid = InvalidOid;
1626 : :
1627 : : /*
1628 : : * If the index column has a specified collation, we should honor that
1629 : : * while doing comparisons. However, we may have a collatable storage
1630 : : * type for a noncollatable indexed data type. If there's no index
1631 : : * collation then specify default collation in case the support
1632 : : * functions need collation. This is harmless if the support
1633 : : * functions don't care about collation, so we just do it
1634 : : * unconditionally. (We could alternatively call get_typcollation,
1635 : : * but that seems like expensive overkill --- there aren't going to be
1636 : : * any cases where a GiST storage type has a nondefault collation.)
1637 : : */
1638 [ + + ]: 10192 : if (OidIsValid(index->rd_indcollation[i]))
1639 : 98 : giststate->supportCollation[i] = index->rd_indcollation[i];
1640 : : else
1641 : 10094 : giststate->supportCollation[i] = DEFAULT_COLLATION_OID;
1642 : : }
1643 : :
1644 : : /* No opclass information for INCLUDE attributes */
1645 [ + + ]: 6458 : for (; i < index->rd_att->natts; i++)
1646 : : {
1647 : 350 : giststate->consistentFn[i].fn_oid = InvalidOid;
1648 : 350 : giststate->unionFn[i].fn_oid = InvalidOid;
1649 : 350 : giststate->compressFn[i].fn_oid = InvalidOid;
1650 : 350 : giststate->decompressFn[i].fn_oid = InvalidOid;
1651 : 350 : giststate->penaltyFn[i].fn_oid = InvalidOid;
1652 : 350 : giststate->picksplitFn[i].fn_oid = InvalidOid;
1653 : 350 : giststate->equalFn[i].fn_oid = InvalidOid;
1654 : 350 : giststate->distanceFn[i].fn_oid = InvalidOid;
1655 : 350 : giststate->fetchFn[i].fn_oid = InvalidOid;
1656 : 350 : giststate->supportCollation[i] = InvalidOid;
1657 : : }
1658 : :
1659 : 6108 : MemoryContextSwitchTo(oldCxt);
1660 : :
1661 : 6108 : return giststate;
1662 : : }
1663 : :
1664 : : void
1665 : 4654 : freeGISTstate(GISTSTATE *giststate)
1666 : : {
1667 : : /* It's sufficient to delete the scanCxt */
1668 : 4654 : MemoryContextDelete(giststate->scanCxt);
1669 : 4654 : }
1670 : :
1671 : : /*
1672 : : * gistprunepage() -- try to remove LP_DEAD items from the given page.
1673 : : * Function assumes that buffer is exclusively locked.
1674 : : */
1675 : : static void
1676 : 12 : gistprunepage(Relation rel, Page page, Buffer buffer, Relation heapRel)
1677 : : {
1678 : : OffsetNumber deletable[MaxIndexTuplesPerPage];
1679 : 12 : int ndeletable = 0;
1680 : : OffsetNumber offnum,
1681 : : maxoff;
1682 : :
1683 : : Assert(GistPageIsLeaf(page));
1684 : :
1685 : : /*
1686 : : * Scan over all items to see which ones need to be deleted according to
1687 : : * LP_DEAD flags.
1688 : : */
1689 : 12 : maxoff = PageGetMaxOffsetNumber(page);
1690 : 12 : for (offnum = FirstOffsetNumber;
1691 [ + + ]: 2232 : offnum <= maxoff;
1692 : 2220 : offnum = OffsetNumberNext(offnum))
1693 : : {
1694 : 2220 : ItemId itemId = PageGetItemId(page, offnum);
1695 : :
1696 [ + + ]: 2220 : if (ItemIdIsDead(itemId))
1697 : 1628 : deletable[ndeletable++] = offnum;
1698 : : }
1699 : :
1700 [ + - ]: 12 : if (ndeletable > 0)
1701 : : {
1702 : 12 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
1703 : :
1704 [ + - + - : 12 : if (XLogStandbyInfoActive() && RelationNeedsWAL(rel))
- + - - -
- ]
1705 : : snapshotConflictHorizon =
1706 : 12 : index_compute_xid_horizon_for_tuples(rel, heapRel, buffer,
1707 : : deletable, ndeletable);
1708 : :
1709 : 12 : START_CRIT_SECTION();
1710 : :
1711 : 12 : PageIndexMultiDelete(page, deletable, ndeletable);
1712 : :
1713 : : /*
1714 : : * Mark the page as not containing any LP_DEAD items. This is not
1715 : : * certainly true (there might be some that have recently been marked,
1716 : : * but weren't included in our target-item list), but it will almost
1717 : : * always be true and it doesn't seem worth an additional page scan to
1718 : : * check it. Remember that F_HAS_GARBAGE is only a hint anyway.
1719 : : */
1720 : 12 : GistClearPageHasGarbage(page);
1721 : :
1722 : 12 : MarkBufferDirty(buffer);
1723 : :
1724 : : /* XLOG stuff */
1725 [ + - - + : 12 : if (RelationNeedsWAL(rel))
- - - - ]
1726 : 12 : {
1727 : : XLogRecPtr recptr;
1728 : :
1729 : 12 : recptr = gistXLogDelete(buffer,
1730 : : deletable, ndeletable,
1731 : : snapshotConflictHorizon,
1732 : : heapRel);
1733 : :
1734 : 12 : PageSetLSN(page, recptr);
1735 : : }
1736 : : else
1737 : 0 : PageSetLSN(page, XLogGetFakeLSN(rel));
1738 : :
1739 : 12 : END_CRIT_SECTION();
1740 : : }
1741 : :
1742 : : /*
1743 : : * Note: if we didn't find any LP_DEAD items, then the page's
1744 : : * F_HAS_GARBAGE hint bit is falsely set. We do not bother expending a
1745 : : * separate write to clear it, however. We will clear it when we split
1746 : : * the page.
1747 : : */
1748 : 12 : }
|