Age Owner Branch data TLA 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
3968 tgl@sss.pgh.pa.us 59 :CBC 8806 : 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 : :
333 117 : 8806 : 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
7737 bruce@momjian.us 129 : 6338 : createTempGistContext(void)
130 : : {
131 : 6338 : 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
3968 tgl@sss.pgh.pa.us 140 : 6 : gistbuildempty(Relation index)
141 : : {
142 : : Buffer buffer;
143 : :
144 : : /* Initialize the root page */
1193 tmunro@postgresql.or 145 : 6 : buffer = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
146 : : EB_SKIP_EXTENSION_LOCK | EB_LOCK_FIRST);
147 : :
148 : : /* Initialize and xlog buffer */
5038 heikki.linnakangas@i 149 : 6 : START_CRIT_SECTION();
150 : 6 : GISTInitBuffer(buffer, F_LEAF);
151 : 6 : MarkBufferDirty(buffer);
4742 152 : 6 : log_newpage_buffer(buffer, true);
5038 153 [ - + ]: 6 : END_CRIT_SECTION();
154 : :
155 : : /* Unlock and release the buffer */
156 : 6 : UnlockReleaseBuffer(buffer);
5813 rhaas@postgresql.org 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
3968 tgl@sss.pgh.pa.us 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 : : {
3579 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();
730 peter@eisentraut.org 182 : 1257 : indexInfo->ii_AmCache = giststate;
3579 tgl@sss.pgh.pa.us 183 : 1257 : MemoryContextSwitchTo(oldCxt);
184 : : }
185 : :
5538 186 : 194526 : oldCxt = MemoryContextSwitchTo(giststate->tempCxt);
187 : :
751 michael@paquier.xyz 188 : 194526 : itup = gistFormTuple(giststate, r, values, isnull, true);
10674 bruce@momjian.us 189 : 194525 : itup->t_tid = *ht_ctid;
190 : :
2796 heikki.linnakangas@i 191 : 194525 : gistdoinsert(r, itup, 0, giststate, heapRel, false);
192 : :
193 : : /* cleanup */
5538 tgl@sss.pgh.pa.us 194 : 194519 : MemoryContextSwitchTo(oldCxt);
3579 195 : 194519 : MemoryContextReset(giststate->tempCxt);
196 : :
3968 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
5560 heikki.linnakangas@i 231 : 1027091 : 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 : : {
5217 241 : 1027091 : BlockNumber blkno = BufferGetBlockNumber(buffer);
3874 kgrittn@postgresql.o 242 : 1027091 : Page page = BufferGetPage(buffer);
5819 heikki.linnakangas@i 243 : 1027091 : 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 [ - + ]: 1027091 : if (GistFollowRight(page))
5819 heikki.linnakangas@i 257 [ # # ]:UBC 0 : elog(ERROR, "concurrent GiST page split was incomplete");
258 : :
259 : : /* should never try to insert to a deleted page */
2138 heikki.linnakangas@i 260 [ - + ]:CBC 1027091 : Assert(!GistPageIsDeleted(page));
261 : :
5819 262 : 1027091 : *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 : : */
5560 274 : 1027091 : 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 : : */
4098 teodor@sigaev.ru 280 [ + + + + : 1027091 : if (is_split && GistPageIsLeaf(page) && GistPageHasGarbage(page))
+ + ]
281 : : {
2825 heikki.linnakangas@i 282 : 12 : gistprunepage(rel, page, buffer, heapRel);
4098 teodor@sigaev.ru 283 : 12 : is_split = gistnospace(page, itup, ntup, oldoffnum, freespace);
284 : : }
285 : :
5819 heikki.linnakangas@i 286 [ + + ]: 1027091 : if (is_split)
287 : : {
288 : : /* no space for insertion */
289 : : IndexTuple *itvec;
290 : : int tlen;
1061 rhaas@postgresql.org 291 : 14277 : SplitPageLayout *dist = NULL,
292 : : *ptr;
5819 heikki.linnakangas@i 293 : 14277 : BlockNumber oldrlink = InvalidBlockNumber;
303 alvherre@kurilemu.de 294 : 14277 : GistNSN oldnsn = InvalidXLogRecPtr;
295 : : SplitPageLayout rootpg;
296 : : bool is_rootsplit;
297 : : int npage;
298 : :
5819 heikki.linnakangas@i 299 : 14277 : 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 : 14277 : itvec = gistextractpage(page, &tlen);
306 [ + + + - : 14277 : if (OffsetNumberIsValid(oldoffnum))
+ + ]
307 : : {
308 : : /* on inner page we should remove old tuple */
309 : 2758 : int pos = oldoffnum - FirstOffsetNumber;
310 : :
7360 bruce@momjian.us 311 : 2758 : tlen--;
312 [ + + ]: 2758 : if (pos != tlen)
313 : 1836 : memmove(itvec + pos, itvec + pos + 1, sizeof(IndexTuple) * (tlen - pos));
314 : : }
5819 heikki.linnakangas@i 315 : 14277 : itvec = gistjoinvector(itvec, &tlen, itup, ntup);
5560 316 : 14277 : dist = gistSplit(rel, page, itvec, tlen, giststate);
317 : :
318 : : /*
319 : : * Check that split didn't produce too many pages.
320 : : */
4622 321 : 14277 : npage = 0;
322 [ + + ]: 42935 : for (ptr = dist; ptr; ptr = ptr->next)
323 : 28658 : npage++;
324 : : /* in a root split, we'll add one more page to the list below */
325 [ + + ]: 14277 : if (is_rootsplit)
326 : 212 : npage++;
327 [ - + ]: 14277 : if (npage > GIST_MAX_SPLIT_PAGES)
4622 heikki.linnakangas@i 328 [ # # ]:UBC 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 : : */
5819 heikki.linnakangas@i 340 :CBC 14277 : ptr = dist;
341 [ + + ]: 14277 : if (!is_rootsplit)
342 : : {
343 : : /* save old rightlink and NSN */
344 : 14065 : oldrlink = GistPageGetOpaque(page)->rightlink;
5063 345 : 14065 : oldnsn = GistPageGetNSN(page);
346 : :
5819 347 : 14065 : dist->buffer = buffer;
348 : 14065 : dist->block.blkno = BufferGetBlockNumber(buffer);
3874 kgrittn@postgresql.o 349 : 14065 : dist->page = PageGetTempPageCopySpecial(BufferGetPage(buffer));
350 : :
351 : : /* clean all flags except F_LEAF */
7507 teodor@sigaev.ru 352 : 14065 : GistPageGetOpaque(dist->page)->flags = (is_leaf) ? F_LEAF : 0;
353 : :
5819 heikki.linnakangas@i 354 : 14065 : ptr = ptr->next;
355 : : }
356 [ + + ]: 28870 : for (; ptr; ptr = ptr->next)
357 : : {
358 : : /* Allocate new page */
1337 andres@anarazel.de 359 : 14593 : ptr->buffer = gistNewBuffer(rel, heapRel);
5819 heikki.linnakangas@i 360 : 14593 : GISTInitBuffer(ptr->buffer, (is_leaf) ? F_LEAF : 0);
3874 kgrittn@postgresql.o 361 : 14593 : ptr->page = BufferGetPage(ptr->buffer);
5819 heikki.linnakangas@i 362 : 14593 : ptr->block.blkno = BufferGetBlockNumber(ptr->buffer);
3168 teodor@sigaev.ru 363 : 14593 : 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 : : */
7360 bruce@momjian.us 372 [ + + ]: 42935 : for (ptr = dist; ptr; ptr = ptr->next)
373 : : {
5819 heikki.linnakangas@i 374 : 28658 : ItemPointerSetBlockNumber(&(ptr->itup->t_tid), ptr->block.blkno);
375 : 28658 : 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 [ + + ]: 14277 : if (is_rootsplit)
384 : : {
385 : : IndexTuple *downlinks;
5711 bruce@momjian.us 386 : 212 : int ndownlinks = 0;
387 : : int i;
388 : :
5819 heikki.linnakangas@i 389 : 212 : rootpg.buffer = buffer;
3874 kgrittn@postgresql.o 390 : 212 : rootpg.page = PageGetTempPageCopySpecial(BufferGetPage(rootpg.buffer));
5819 heikki.linnakangas@i 391 : 212 : GistPageGetOpaque(rootpg.page)->flags = 0;
392 : :
393 : : /* Prepare a vector of all the downlinks */
394 [ + + ]: 637 : for (ptr = dist; ptr; ptr = ptr->next)
395 : 425 : ndownlinks++;
353 michael@paquier.xyz 396 : 212 : downlinks = palloc_array(IndexTuple, ndownlinks);
5819 heikki.linnakangas@i 397 [ + + ]: 637 : for (i = 0, ptr = dist; ptr; ptr = ptr->next)
398 : 425 : 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 [ + + ]: 42298 : for (ptr = dist; ptr; ptr = ptr->next)
413 : : {
353 michael@paquier.xyz 414 : 28233 : GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
415 : :
5819 heikki.linnakangas@i 416 : 28233 : si->buf = ptr->buffer;
417 : 28233 : si->downlink = ptr->itup;
418 : 28233 : *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 [ + + ]: 43147 : for (ptr = dist; ptr; ptr = ptr->next)
427 : : {
5711 bruce@momjian.us 428 : 28870 : char *data = (char *) (ptr->list);
429 : :
1557 drowley@postgresql.o 430 [ + + ]: 1118051 : for (int i = 0; i < ptr->block.num; i++)
431 : : {
5217 heikki.linnakangas@i 432 : 1089181 : IndexTuple thistup = (IndexTuple) data;
433 : :
397 peter@eisentraut.org 434 [ - + ]: 1089181 : if (PageAddItem(ptr->page, data, IndexTupleSize(thistup), i + FirstOffsetNumber, false, false) == InvalidOffsetNumber)
5560 heikki.linnakangas@i 435 [ # # ]:UBC 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 : : */
5217 heikki.linnakangas@i 441 [ + + + + ]:CBC 1089181 : if (newblkno && ItemPointerEquals(&thistup->t_tid, &(*itup)->t_tid))
442 : 516 : *newblkno = ptr->block.blkno;
443 : :
444 : 1089181 : data += IndexTupleSize(thistup);
445 : : }
446 : :
447 : : /* Set up rightlinks */
5819 448 [ + + + + ]: 28870 : if (ptr->next && ptr->block.blkno != GIST_ROOT_BLKNO)
449 : 28762 : GistPageGetOpaque(ptr->page)->rightlink =
450 : 14381 : ptr->next->block.blkno;
451 : : else
452 : 14489 : 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 : : */
5560 462 [ + + + + : 28870 : if (ptr->next && !is_rootsplit && markfollowright)
+ + ]
5819 463 : 13656 : GistMarkFollowRight(ptr->page);
464 : : else
465 : 15214 : 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 : : */
5063 472 : 28870 : 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 : : */
2796 480 [ + + + + : 14277 : if (!is_build && RelationNeedsWAL(rel))
- + - - -
- ]
4391 481 : 2222 : XLogEnsureRecordSpace(npage, 1 + npage * 2);
482 : :
7507 teodor@sigaev.ru 483 : 14277 : 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 : : */
7360 bruce@momjian.us 489 [ + + ]: 43147 : for (ptr = dist; ptr; ptr = ptr->next)
7547 tgl@sss.pgh.pa.us 490 : 28870 : MarkBufferDirty(ptr->buffer);
5819 heikki.linnakangas@i 491 [ + + ]: 14277 : if (BufferIsValid(leftchildbuf))
492 : 2669 : 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 : : */
3874 kgrittn@postgresql.o 498 : 14277 : PageRestoreTempPage(dist->page, BufferGetPage(dist->buffer));
499 : 14277 : 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 : : */
2796 heikki.linnakangas@i 511 [ + + ]: 14277 : if (is_build)
512 : 12051 : recptr = GistBuildLSN;
513 : : else
514 : : {
515 [ + + - + : 2226 : if (RelationNeedsWAL(rel))
- - - - ]
516 : 2222 : recptr = gistXLogSplit(is_leaf,
517 : : dist, oldrlink, oldnsn, leftchildbuf,
518 : : markfollowright);
519 : : else
260 pg@bowt.ie 520 : 4 : recptr = XLogGetFakeLSN(rel);
521 : : }
522 : :
7360 bruce@momjian.us 523 [ + + ]: 43147 : for (ptr = dist; ptr; ptr = ptr->next)
5819 heikki.linnakangas@i 524 : 28870 : 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 [ + + ]: 14277 : if (is_rootsplit)
534 : : {
535 [ + + ]: 637 : for (ptr = dist->next; ptr; ptr = ptr->next)
536 : 425 : UnlockReleaseBuffer(ptr->buffer);
537 : : }
538 : : }
539 : : else
540 : : {
541 : : /*
542 : : * Enough space. We always get here if ntup==0.
543 : : */
7507 teodor@sigaev.ru 544 : 1012814 : 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 : : */
5819 heikki.linnakangas@i 550 [ + + + - : 1012814 : if (OffsetNumberIsValid(oldoffnum))
+ + ]
551 : : {
3732 tgl@sss.pgh.pa.us 552 [ + + ]: 463121 : if (ntup == 1)
553 : : {
554 : : /* One-for-one replacement, so use PageIndexTupleOverwrite */
397 peter@eisentraut.org 555 [ - + ]: 451735 : if (!PageIndexTupleOverwrite(page, oldoffnum, *itup, IndexTupleSize(*itup)))
3732 tgl@sss.pgh.pa.us 556 [ # # ]:UBC 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 */
3732 tgl@sss.pgh.pa.us 562 :CBC 11386 : PageIndexTupleDelete(page, oldoffnum);
563 : 11386 : gistfillbuffer(page, itup, ntup, InvalidOffsetNumber);
564 : : }
565 : : }
566 : : else
567 : : {
568 : : /* Just append new tuples at the end of the page */
569 : 549693 : gistfillbuffer(page, itup, ntup, InvalidOffsetNumber);
570 : : }
571 : :
5819 heikki.linnakangas@i 572 : 1012814 : MarkBufferDirty(buffer);
573 : :
574 [ + + ]: 1012814 : if (BufferIsValid(leftchildbuf))
575 : 10987 : MarkBufferDirty(leftchildbuf);
576 : :
2796 577 [ + + ]: 1012814 : if (is_build)
578 : 699880 : recptr = GistBuildLSN;
579 : : else
580 : : {
581 [ + + + + : 312934 : if (RelationNeedsWAL(rel))
+ - + - ]
7737 bruce@momjian.us 582 : 312882 : {
2796 heikki.linnakangas@i 583 : 312882 : OffsetNumber ndeloffs = 0,
584 : : deloffs[1];
585 : :
586 [ + + + - : 312882 : if (OffsetNumberIsValid(oldoffnum))
+ + ]
587 : : {
588 : 120625 : deloffs[0] = oldoffnum;
589 : 120625 : ndeloffs = 1;
590 : : }
591 : :
592 : 312882 : recptr = gistXLogUpdate(buffer,
593 : : deloffs, ndeloffs, itup, ntup,
594 : : leftchildbuf);
595 : : }
596 : : else
260 pg@bowt.ie 597 : 52 : recptr = XLogGetFakeLSN(rel);
598 : : }
2796 heikki.linnakangas@i 599 : 1012814 : PageSetLSN(page, recptr);
600 : :
5217 601 [ + + ]: 1012814 : 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 : : */
5819 618 [ + + ]: 1027091 : if (BufferIsValid(leftchildbuf))
619 : : {
3874 kgrittn@postgresql.o 620 : 13656 : Page leftpg = BufferGetPage(leftchildbuf);
621 : :
5063 heikki.linnakangas@i 622 : 13656 : GistPageSetNSN(leftpg, recptr);
5819 623 : 13656 : GistClearFollowRight(leftpg);
624 : :
625 : 13656 : PageSetLSN(leftpg, recptr);
626 : : }
627 : :
628 [ - + ]: 1027091 : END_CRIT_SECTION();
629 : :
630 : 1027091 : 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
2899 akorotkov@postgresql 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;
5819 heikki.linnakangas@i 647 : 537495 : bool xlocked = false;
648 : :
649 : 537495 : memset(&state, 0, sizeof(GISTInsertState));
650 : 537495 : state.freespace = freespace;
651 : 537495 : state.r = r;
2899 akorotkov@postgresql 652 : 537495 : state.heapRel = heapRel;
2796 heikki.linnakangas@i 653 : 537495 : state.is_build = is_build;
654 : :
655 : : /* Start from the root */
5819 656 : 537495 : firststack.blkno = GIST_ROOT_BLKNO;
303 alvherre@kurilemu.de 657 : 537495 : firststack.lsn = InvalidXLogRecPtr;
2755 heikki.linnakangas@i 658 : 537495 : firststack.retry_from_parent = false;
5819 659 : 537495 : firststack.parent = NULL;
5615 660 : 537495 : firststack.downlinkoffnum = InvalidOffsetNumber;
5819 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 : : */
2755 677 [ + + ]: 1219622 : while (stack->retry_from_parent)
678 : : {
679 [ - + ]: 208 : if (xlocked)
2755 heikki.linnakangas@i 680 :UBC 0 : LockBuffer(stack->buffer, GIST_UNLOCK);
2755 heikki.linnakangas@i 681 :CBC 208 : xlocked = false;
682 : 208 : ReleaseBuffer(stack->buffer);
683 : 208 : state.stack = stack = stack->parent;
684 : : }
685 : :
387 alvherre@kurilemu.de 686 [ + + ]: 1219414 : if (!XLogRecPtrIsValid(stack->lsn))
5819 heikki.linnakangas@i 687 : 1219335 : 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 [ + - ]: 1219414 : if (!xlocked)
694 : : {
695 : 1219414 : LockBuffer(stack->buffer, GIST_SHARE);
696 : 1219414 : gistcheckpage(state.r, stack->buffer);
697 : : }
698 : :
456 peter@eisentraut.org 699 : 1219414 : stack->page = BufferGetPage(stack->buffer);
3245 alvherre@alvh.no-ip. 700 : 1219414 : stack->lsn = xlocked ?
701 [ - + ]: 1219414 : PageGetLSN(stack->page) : BufferGetLSNAtomic(stack->buffer);
387 alvherre@kurilemu.de 702 [ + + + + : 1219414 : 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 : : */
5819 heikki.linnakangas@i 709 [ - + ]: 1219414 : if (GistFollowRight(stack->page))
710 : : {
5819 heikki.linnakangas@i 711 [ # # ]:UBC 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 : :
2684 heikki.linnakangas@i 728 [ + + + - ]:CBC 1901271 : if ((stack->blkno != GIST_ROOT_BLKNO &&
729 : 681857 : stack->parent->lsn < GistPageGetNSN(stack->page)) ||
730 [ - + ]: 1219414 : 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 : : */
5819 heikki.linnakangas@i 738 :UBC 0 : UnlockReleaseBuffer(stack->buffer);
739 : 0 : xlocked = false;
740 : 0 : state.stack = stack = stack->parent;
7824 teodor@sigaev.ru 741 : 0 : continue;
742 : : }
743 : :
5819 heikki.linnakangas@i 744 [ + + ]:CBC 1219414 : 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 : :
5615 755 : 681919 : downlinkoffnum = gistchoose(state.r, stack->page, itup, giststate);
756 : 681919 : iid = PageGetItemId(stack->page, downlinkoffnum);
5819 757 : 681919 : idxtuple = (IndexTuple) PageGetItem(stack->page, iid);
758 : 681919 : childblkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
759 : :
760 : : /*
761 : : * Check that it's not a leftover invalid tuple from pre-9.1
762 : : */
763 [ - + ]: 681919 : if (GistTupleIsInvalid(idxtuple))
5819 heikki.linnakangas@i 764 [ # # ]:UBC 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 : : */
5819 heikki.linnakangas@i 775 :CBC 681919 : newtup = gistgetadjusted(state.r, idxtuple, itup, giststate);
776 [ + + ]: 681919 : 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 [ + - ]: 405850 : if (!xlocked)
783 : : {
784 : 405850 : LockBuffer(stack->buffer, GIST_UNLOCK);
785 : 405850 : LockBuffer(stack->buffer, GIST_EXCLUSIVE);
786 : 405850 : xlocked = true;
456 peter@eisentraut.org 787 : 405850 : stack->page = BufferGetPage(stack->buffer);
788 : :
5083 alvherre@alvh.no-ip. 789 [ - + ]: 405850 : if (PageGetLSN(stack->page) != stack->lsn)
790 : : {
791 : : /* the page was changed while we unlocked it, retry */
5819 heikki.linnakangas@i 792 :UBC 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 : : */
5314 heikki.linnakangas@i 806 [ + + ]:CBC 405850 : 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 : : */
5802 815 [ + - ]: 79 : if (stack->blkno != GIST_ROOT_BLKNO)
816 : : {
817 : 79 : UnlockReleaseBuffer(stack->buffer);
818 : 79 : xlocked = false;
819 : 79 : state.stack = stack = stack->parent;
820 : : }
5819 821 : 79 : continue;
822 : : }
823 : : }
824 : 681840 : LockBuffer(stack->buffer, GIST_UNLOCK);
825 : 681840 : xlocked = false;
826 : :
827 : : /* descend to the chosen child */
353 michael@paquier.xyz 828 : 681840 : item = palloc0_object(GISTInsertStack);
5819 heikki.linnakangas@i 829 : 681840 : item->blkno = childblkno;
830 : 681840 : item->parent = stack;
5615 831 : 681840 : item->downlinkoffnum = downlinkoffnum;
5819 832 : 681840 : 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;
456 peter@eisentraut.org 851 : 537495 : stack->page = BufferGetPage(stack->buffer);
5819 heikki.linnakangas@i 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 : : */
5819 heikki.linnakangas@i 866 :UBC 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 : : }
2684 heikki.linnakangas@i 876 [ + - + - ]:CBC 1027534 : else if ((GistFollowRight(stack->page) ||
2138 877 : 513767 : stack->parent->lsn < GistPageGetNSN(stack->page)) ||
2684 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 : : */
5819 heikki.linnakangas@i 884 :UBC 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 : :
5314 heikki.linnakangas@i 893 :CBC 537495 : gistinserttuple(&state, stack, giststate, itup,
894 : : InvalidOffsetNumber);
5819 895 : 537489 : LockBuffer(stack->buffer, GIST_UNLOCK);
896 : :
897 : : /* Release any pins we might still hold before exiting */
898 [ + + ]: 1756525 : for (; stack; stack = stack->parent)
899 : 1219036 : ReleaseBuffer(stack->buffer);
7837 teodor@sigaev.ru 900 : 537489 : break;
901 : : }
902 : : }
7824 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 *
5615 heikki.linnakangas@i 915 :UBC 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 : :
353 michael@paquier.xyz 928 : 0 : top = palloc0_object(GISTInsertStack);
7824 teodor@sigaev.ru 929 : 0 : top->blkno = GIST_ROOT_BLKNO;
5615 heikki.linnakangas@i 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 : :
7548 tgl@sss.pgh.pa.us 939 : 0 : buffer = ReadBuffer(r, top->blkno);
940 : 0 : LockBuffer(buffer, GIST_SHARE);
7692 941 : 0 : gistcheckpage(r, buffer);
456 peter@eisentraut.org 942 : 0 : page = BufferGetPage(buffer);
943 : :
7737 bruce@momjian.us 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 : : */
7547 tgl@sss.pgh.pa.us 950 : 0 : UnlockReleaseBuffer(buffer);
5615 heikki.linnakangas@i 951 : 0 : break;
952 : : }
953 : :
954 : : /* currently, internal pages are never deleted */
2684 955 [ # # ]: 0 : Assert(!GistPageIsDeleted(page));
956 : :
3245 alvherre@alvh.no-ip. 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 : : */
5819 heikki.linnakangas@i 963 [ # # ]: 0 : if (GistFollowRight(page))
964 [ # # ]: 0 : elog(ERROR, "concurrent GiST page split was incomplete");
965 : :
5063 966 [ # # # # ]: 0 : if (top->parent && top->parent->lsn < GistPageGetNSN(page) &&
7737 bruce@momjian.us 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 : : */
353 michael@paquier.xyz 980 : 0 : ptr = palloc0_object(GISTInsertStack);
7824 teodor@sigaev.ru 981 : 0 : ptr->blkno = GistPageGetOpaque(page)->rightlink;
5615 heikki.linnakangas@i 982 : 0 : ptr->downlinkoffnum = InvalidOffsetNumber;
983 : 0 : ptr->parent = top->parent;
984 : :
985 : 0 : fifo = lcons(ptr, fifo);
986 : : }
987 : :
7824 teodor@sigaev.ru 988 : 0 : maxoff = PageGetMaxOffsetNumber(page);
989 : :
7737 bruce@momjian.us 990 [ # # ]: 0 : for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
991 : : {
7824 teodor@sigaev.ru 992 : 0 : iid = PageGetItemId(page, i);
993 : 0 : idxtuple = (IndexTuple) PageGetItem(page, iid);
994 : 0 : blkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
7737 bruce@momjian.us 995 [ # # ]: 0 : if (blkno == child)
996 : : {
997 : : /* Found it! */
7547 tgl@sss.pgh.pa.us 998 : 0 : UnlockReleaseBuffer(buffer);
5615 heikki.linnakangas@i 999 : 0 : *downlinkoffnum = i;
7824 teodor@sigaev.ru 1000 : 0 : return top;
1001 : : }
1002 : : else
1003 : : {
1004 : : /* Append this child to the list of pages to visit later */
353 michael@paquier.xyz 1005 : 0 : ptr = palloc0_object(GISTInsertStack);
7824 teodor@sigaev.ru 1006 : 0 : ptr->blkno = blkno;
5615 heikki.linnakangas@i 1007 : 0 : ptr->downlinkoffnum = i;
7824 teodor@sigaev.ru 1008 : 0 : ptr->parent = top;
1009 : :
5615 heikki.linnakangas@i 1010 : 0 : fifo = lappend(fifo, ptr);
1011 : : }
1012 : : }
1013 : :
7547 tgl@sss.pgh.pa.us 1014 : 0 : UnlockReleaseBuffer(buffer);
1015 : : }
1016 : :
5615 heikki.linnakangas@i 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
1159 heikki.linnakangas@i 1028 :CBC 13656 : gistFindCorrectParent(Relation r, GISTInsertStack *child, bool is_build)
1029 : : {
7737 bruce@momjian.us 1030 : 13656 : GISTInsertStack *parent = child->parent;
1031 : : ItemId iid;
1032 : : IndexTuple idxtuple;
1033 : : OffsetNumber maxoff;
1034 : : GISTInsertStack *ptr;
1035 : :
7692 tgl@sss.pgh.pa.us 1036 : 13656 : gistcheckpage(r, parent->buffer);
456 peter@eisentraut.org 1037 : 13656 : parent->page = BufferGetPage(parent->buffer);
1159 heikki.linnakangas@i 1038 : 13656 : maxoff = PageGetMaxOffsetNumber(parent->page);
1039 : :
1040 : : /* Check if the downlink is still where it was before */
1041 [ + + + - ]: 13656 : if (child->downlinkoffnum != InvalidOffsetNumber && child->downlinkoffnum <= maxoff)
1042 : : {
1043 : 13647 : iid = PageGetItemId(parent->page, child->downlinkoffnum);
1044 : 13647 : idxtuple = (IndexTuple) PageGetItem(parent->page, iid);
1045 [ + - ]: 13647 : if (ItemPointerGetBlockNumber(&(idxtuple->t_tid)) == child->blkno)
1046 : 13647 : 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 : : */
603 1063 [ - + + - : 9 : 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)
1159 1072 : 6 : {
1073 : : OffsetNumber i;
1074 : :
1075 : 15 : maxoff = PageGetMaxOffsetNumber(parent->page);
1076 [ + + ]: 68 : for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
1077 : : {
1078 : 62 : iid = PageGetItemId(parent->page, i);
1079 : 62 : idxtuple = (IndexTuple) PageGetItem(parent->page, iid);
1080 [ + + ]: 62 : if (ItemPointerGetBlockNumber(&(idxtuple->t_tid)) == child->blkno)
1081 : : {
1082 : : /* yes!!, found */
1083 : 9 : child->downlinkoffnum = i;
1084 : 9 : return;
1085 : : }
1086 : : }
1087 : :
1088 : 6 : parent->blkno = GistPageGetOpaque(parent->page)->rightlink;
1089 : 6 : parent->downlinkoffnum = InvalidOffsetNumber;
1090 : 6 : UnlockReleaseBuffer(parent->buffer);
1091 [ - + ]: 6 : 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 : : */
1159 heikki.linnakangas@i 1097 :UBC 0 : break;
1098 : : }
1159 heikki.linnakangas@i 1099 :CBC 6 : parent->buffer = ReadBuffer(r, parent->blkno);
1100 : 6 : LockBuffer(parent->buffer, GIST_EXCLUSIVE);
1101 : 6 : gistcheckpage(r, parent->buffer);
456 peter@eisentraut.org 1102 : 6 : 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 : :
1159 heikki.linnakangas@i 1110 :UBC 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);
456 peter@eisentraut.org 1125 : 0 : ptr->page = BufferGetPage(ptr->buffer);
1159 heikki.linnakangas@i 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
5819 1141 : 0 : gistformdownlink(Relation rel, Buffer buf, GISTSTATE *giststate,
1142 : : GISTInsertStack *stack, bool is_build)
1143 : : {
3874 kgrittn@postgresql.o 1144 : 0 : Page page = BufferGetPage(buf);
1145 : : OffsetNumber maxoff;
1146 : : OffsetNumber offset;
5711 bruce@momjian.us 1147 : 0 : IndexTuple downlink = NULL;
1148 : :
5819 heikki.linnakangas@i 1149 : 0 : maxoff = PageGetMaxOffsetNumber(page);
1150 [ # # ]: 0 : for (offset = FirstOffsetNumber; offset <= maxoff; offset = OffsetNumberNext(offset))
1151 : : {
1152 : : IndexTuple ituple = (IndexTuple)
1289 tgl@sss.pgh.pa.us 1153 : 0 : PageGetItem(page, PageGetItemId(page, offset));
1154 : :
5819 heikki.linnakangas@i 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);
1159 1183 : 0 : gistFindCorrectParent(rel, stack, is_build);
5615 1184 : 0 : iid = PageGetItemId(stack->parent->page, stack->downlinkoffnum);
5819 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 : :
2185 peter@eisentraut.org 1208 [ # # ]: 0 : ereport(LOG,
1209 : : (errmsg("fixing incomplete split in index \"%s\", block %u",
1210 : : RelationGetRelationName(state->r), stack->blkno)));
1211 : :
5819 heikki.linnakangas@i 1212 [ # # ]: 0 : Assert(GistFollowRight(stack->page));
5615 1213 [ # # # # : 0 : Assert(OffsetNumberIsValid(stack->downlinkoffnum));
# # ]
1214 : :
5819 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 : {
353 michael@paquier.xyz 1223 : 0 : GISTPageSplitInfo *si = palloc_object(GISTPageSplitInfo);
1224 : : IndexTuple downlink;
1225 : :
3874 kgrittn@postgresql.o 1226 : 0 : page = BufferGetPage(buf);
1227 : :
1228 : : /* Form the new downlink tuples to insert to parent */
1159 heikki.linnakangas@i 1229 : 0 : downlink = gistformdownlink(state->r, buf, giststate, stack, state->is_build);
1230 : :
5819 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 */
5314 1247 : 0 : gistfinishsplit(state, stack, giststate, splitinfo, false);
5819 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
5314 heikki.linnakangas@i 1261 :CBC 943345 : gistinserttuple(GISTInsertState *state, GISTInsertStack *stack,
1262 : : GISTSTATE *giststate, IndexTuple tuple, OffsetNumber oldoffnum)
1263 : : {
1264 : 943345 : 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
5819 1295 : 957001 : 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 : : */
2496 tmunro@postgresql.or 1308 : 957001 : CheckForSerializableConflictIn(state->r, NULL, BufferGetBlockNumber(stack->buffer));
1309 : :
1310 : : /* Insert the tuple(s) to the page, splitting the page if necessary */
5560 heikki.linnakangas@i 1311 : 956995 : 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,
2796 1319 : 956995 : 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 : : */
5314 1326 [ + + ]: 956995 : if (BufferIsValid(rightchild))
1327 : 13656 : UnlockReleaseBuffer(rightchild);
1328 [ + + + + ]: 956995 : if (BufferIsValid(leftchild) && unlockleftchild)
1329 : 2601 : 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 : : */
5819 1337 [ + + ]: 956995 : if (splitinfo)
5314 1338 : 13553 : gistfinishsplit(state, stack, giststate, splitinfo, unlockbuf);
1339 [ + + ]: 943442 : else if (unlockbuf)
1340 : 10952 : LockBuffer(stack->buffer, GIST_UNLOCK);
1341 : :
5819 1342 : 956995 : 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 : 13553 : 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 [ - + ]: 13553 : 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 : 13553 : 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 : : */
2691 tgl@sss.pgh.pa.us 1378 [ + + ]: 13656 : for (int pos = list_length(splitinfo) - 1; pos > 1; pos--)
1379 : : {
1380 : 103 : right = (GISTPageSplitInfo *) list_nth(splitinfo, pos);
1381 : 103 : left = (GISTPageSplitInfo *) list_nth(splitinfo, pos - 1);
1382 : :
1159 heikki.linnakangas@i 1383 : 103 : gistFindCorrectParent(state->r, stack, state->is_build);
5819 1384 [ + + ]: 103 : 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 : : */
2542 1393 : 2 : stack->downlinkoffnum = InvalidOffsetNumber;
1394 : : }
1395 : : /* gistinserttuples() released the lock on right->buf. */
1396 : : }
1397 : :
2691 tgl@sss.pgh.pa.us 1398 : 13553 : right = (GISTPageSplitInfo *) lsecond(splitinfo);
1399 : 13553 : 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 : : */
5819 heikki.linnakangas@i 1406 : 13553 : tuples[0] = left->downlink;
1407 : 13553 : tuples[1] = right->downlink;
1159 1408 : 13553 : gistFindCorrectParent(state->r, stack, state->is_build);
1409 : 13553 : (void) gistinserttuples(state, stack->parent, giststate,
1410 : : tuples, 2,
1411 : 13553 : 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 : 13553 : stack->downlinkoffnum = InvalidOffsetNumber;
1424 : :
5819 1425 [ - + ]: 13553 : 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 : : */
2755 1442 : 13553 : stack->retry_from_parent = true;
7831 teodor@sigaev.ru 1443 : 13553 : }
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 *
11051 scrappy@hub.org 1451 : 15318 : 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;
1061 rhaas@postgresql.org 1461 : 15318 : SplitPageLayout *res = NULL;
1462 : :
1463 : : /* this should never recurse very deeply, but better safe than sorry */
4439 heikki.linnakangas@i 1464 : 15318 : check_stack_depth();
1465 : :
1466 : : /* there's no point in splitting an empty page */
1467 [ - + ]: 15318 : 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 [ - + ]: 15318 : if (len == 1)
4439 heikki.linnakangas@i 1474 [ # # ]:UBC 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 : :
2820 akorotkov@postgresql 1480 :CBC 15318 : memset(v.spl_lisnull, true,
1481 : 15318 : sizeof(bool) * giststate->nonLeafTupdesc->natts);
1482 : 15318 : memset(v.spl_risnull, true,
1483 : 15318 : sizeof(bool) * giststate->nonLeafTupdesc->natts);
5039 tgl@sss.pgh.pa.us 1484 : 15318 : gistSplitByKey(r, page, itup, len, giststate, &v, 0);
1485 : :
1486 : : /* form left and right vector */
353 michael@paquier.xyz 1487 : 15318 : lvectup = palloc_array(IndexTuple, len + 1);
1488 : 15318 : rvectup = palloc_array(IndexTuple, len + 1);
1489 : :
7458 teodor@sigaev.ru 1490 [ + + ]: 724640 : for (i = 0; i < v.splitVector.spl_nleft; i++)
1491 : 709322 : lvectup[i] = itup[v.splitVector.spl_left[i] - 1];
1492 : :
1493 [ + + ]: 815530 : for (i = 0; i < v.splitVector.spl_nright; i++)
1494 : 800212 : rvectup[i] = itup[v.splitVector.spl_right[i] - 1];
1495 : :
1496 : : /* finalize splitting (may need another split) */
1497 [ + + ]: 15318 : if (!gistfitpage(rvectup, v.splitVector.spl_nright))
1498 : : {
1499 : 455 : res = gistSplit(r, page, rvectup, v.splitVector.spl_nright, giststate);
1500 : : }
1501 : : else
1502 : : {
7507 1503 : 14863 : ROTATEDIST(res);
7458 1504 : 14863 : res->block.num = v.splitVector.spl_nright;
7360 bruce@momjian.us 1505 : 14863 : res->list = gistfillitupvec(rvectup, v.splitVector.spl_nright, &(res->lenlist));
5819 heikki.linnakangas@i 1506 : 14863 : res->itup = gistFormTuple(giststate, r, v.spl_rattr, v.spl_risnull, false);
1507 : : }
1508 : :
7458 teodor@sigaev.ru 1509 [ + + ]: 15318 : if (!gistfitpage(lvectup, v.splitVector.spl_nleft))
1510 : : {
1511 : : SplitPageLayout *resptr,
1512 : : *subres;
1513 : :
1514 : 351 : resptr = subres = gistSplit(r, page, lvectup, v.splitVector.spl_nleft, giststate);
1515 : :
1516 : : /* install on list's tail */
7360 bruce@momjian.us 1517 [ + + ]: 855 : while (resptr->next)
7507 teodor@sigaev.ru 1518 : 504 : resptr = resptr->next;
1519 : :
1520 : 351 : resptr->next = res;
1521 : 351 : res = subres;
1522 : : }
1523 : : else
1524 : : {
1525 : 14967 : ROTATEDIST(res);
7458 1526 : 14967 : res->block.num = v.splitVector.spl_nleft;
7360 bruce@momjian.us 1527 : 14967 : res->list = gistfillitupvec(lvectup, v.splitVector.spl_nleft, &(res->lenlist));
5819 heikki.linnakangas@i 1528 : 14967 : res->itup = gistFormTuple(giststate, r, v.spl_lattr, v.spl_lisnull, false);
1529 : : }
1530 : :
7507 teodor@sigaev.ru 1531 : 15318 : return res;
1532 : : }
1533 : :
1534 : : /*
1535 : : * Create a GISTSTATE and fill it with information about the index
1536 : : */
1537 : : GISTSTATE *
5538 tgl@sss.pgh.pa.us 1538 : 6091 : 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 */
9230 1546 [ - + ]: 6091 : if (index->rd_att->natts > INDEX_MAX_KEYS)
8531 tgl@sss.pgh.pa.us 1547 [ # # ]:UBC 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 */
5538 tgl@sss.pgh.pa.us 1551 :CBC 6091 : scanCxt = AllocSetContextCreate(CurrentMemoryContext,
1552 : : "GiST scan context",
1553 : : ALLOCSET_DEFAULT_SIZES);
1554 : 6091 : oldCxt = MemoryContextSwitchTo(scanCxt);
1555 : :
1556 : : /* Create and fill in the GISTSTATE */
353 michael@paquier.xyz 1557 : 6091 : giststate = palloc_object(GISTSTATE);
1558 : :
5538 tgl@sss.pgh.pa.us 1559 : 6091 : giststate->scanCxt = scanCxt;
3447 1560 : 6091 : giststate->tempCxt = scanCxt; /* caller must change this if needed */
2820 akorotkov@postgresql 1561 : 6091 : 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 : : */
708 drowley@postgresql.o 1573 : 12182 : giststate->nonLeafTupdesc = CreateTupleDescTruncatedCopy(index->rd_att,
1574 : 6091 : IndexRelationGetNumberOfKeyAttributes(index));
1575 : :
2820 akorotkov@postgresql 1576 [ + + ]: 16266 : for (i = 0; i < IndexRelationGetNumberOfKeyAttributes(index); i++)
1577 : : {
9184 tgl@sss.pgh.pa.us 1578 : 10175 : fmgr_info_copy(&(giststate->consistentFn[i]),
7865 neilc@samurai.com 1579 : 10175 : index_getprocinfo(index, i + 1, GIST_CONSISTENT_PROC),
1580 : : scanCxt);
9184 tgl@sss.pgh.pa.us 1581 : 10175 : fmgr_info_copy(&(giststate->unionFn[i]),
9165 bruce@momjian.us 1582 : 10175 : index_getprocinfo(index, i + 1, GIST_UNION_PROC),
1583 : : scanCxt);
1584 : :
1585 : : /* opclasses are not required to provide a Compress method */
3357 tgl@sss.pgh.pa.us 1586 [ + + ]: 10175 : if (OidIsValid(index_getprocid(index, i + 1, GIST_COMPRESS_PROC)))
1587 : 3473 : fmgr_info_copy(&(giststate->compressFn[i]),
1588 : 3473 : 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 [ + + ]: 10175 : if (OidIsValid(index_getprocid(index, i + 1, GIST_DECOMPRESS_PROC)))
1595 : 974 : fmgr_info_copy(&(giststate->decompressFn[i]),
1596 : 974 : index_getprocinfo(index, i + 1, GIST_DECOMPRESS_PROC),
1597 : : scanCxt);
1598 : : else
1599 : 9201 : giststate->decompressFn[i].fn_oid = InvalidOid;
1600 : :
9184 1601 : 10175 : fmgr_info_copy(&(giststate->penaltyFn[i]),
9165 bruce@momjian.us 1602 : 10175 : index_getprocinfo(index, i + 1, GIST_PENALTY_PROC),
1603 : : scanCxt);
9184 tgl@sss.pgh.pa.us 1604 : 10175 : fmgr_info_copy(&(giststate->picksplitFn[i]),
7865 neilc@samurai.com 1605 : 10175 : index_getprocinfo(index, i + 1, GIST_PICKSPLIT_PROC),
1606 : : scanCxt);
9184 tgl@sss.pgh.pa.us 1607 : 10175 : fmgr_info_copy(&(giststate->equalFn[i]),
9165 bruce@momjian.us 1608 : 10175 : index_getprocinfo(index, i + 1, GIST_EQUAL_PROC),
1609 : : scanCxt);
1610 : :
1611 : : /* opclasses are not required to provide a Distance method */
5839 tgl@sss.pgh.pa.us 1612 [ + + ]: 10175 : if (OidIsValid(index_getprocid(index, i + 1, GIST_DISTANCE_PROC)))
1613 : 1160 : fmgr_info_copy(&(giststate->distanceFn[i]),
3447 1614 : 1160 : index_getprocinfo(index, i + 1, GIST_DISTANCE_PROC),
1615 : : scanCxt);
1616 : : else
5839 1617 : 9015 : giststate->distanceFn[i].fn_oid = InvalidOid;
1618 : :
1619 : : /* opclasses are not required to provide a Fetch method */
4265 heikki.linnakangas@i 1620 [ + + ]: 10175 : if (OidIsValid(index_getprocid(index, i + 1, GIST_FETCH_PROC)))
1621 : 815 : fmgr_info_copy(&(giststate->fetchFn[i]),
4207 bruce@momjian.us 1622 : 815 : index_getprocinfo(index, i + 1, GIST_FETCH_PROC),
1623 : : scanCxt);
1624 : : else
4265 heikki.linnakangas@i 1625 : 9360 : 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 : : */
5699 tgl@sss.pgh.pa.us 1638 [ + + ]: 10175 : if (OidIsValid(index->rd_indcollation[i]))
1639 : 98 : giststate->supportCollation[i] = index->rd_indcollation[i];
1640 : : else
1641 : 10077 : giststate->supportCollation[i] = DEFAULT_COLLATION_OID;
1642 : : }
1643 : :
1644 : : /* No opclass information for INCLUDE attributes */
2820 akorotkov@postgresql 1645 [ + + ]: 6441 : 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 : :
5538 tgl@sss.pgh.pa.us 1659 : 6091 : MemoryContextSwitchTo(oldCxt);
1660 : :
1661 : 6091 : return giststate;
1662 : : }
1663 : :
1664 : : void
9165 bruce@momjian.us 1665 : 4637 : freeGISTstate(GISTSTATE *giststate)
1666 : : {
1667 : : /* It's sufficient to delete the scanCxt */
5538 tgl@sss.pgh.pa.us 1668 : 4637 : MemoryContextDelete(giststate->scanCxt);
11051 scrappy@hub.org 1669 : 4637 : }
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
2825 heikki.linnakangas@i 1676 : 12 : gistprunepage(Relation rel, Page page, Buffer buffer, Relation heapRel)
1677 : : {
1678 : : OffsetNumber deletable[MaxIndexTuplesPerPage];
3824 rhaas@postgresql.org 1679 : 12 : int ndeletable = 0;
1680 : : OffsetNumber offnum,
1681 : : maxoff;
1682 : :
4098 teodor@sigaev.ru 1683 [ - + ]: 12 : 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 : 1629 : deletable[ndeletable++] = offnum;
1698 : : }
1699 : :
1700 [ + - ]: 12 : if (ndeletable > 0)
1701 : : {
1472 pg@bowt.ie 1702 : 12 : TransactionId snapshotConflictHorizon = InvalidTransactionId;
1703 : :
2132 1704 [ + - + - : 12 : if (XLogStandbyInfoActive() && RelationNeedsWAL(rel))
- + - - -
- ]
1705 : : snapshotConflictHorizon =
1706 : 12 : index_compute_xid_horizon_for_tuples(rel, heapRel, buffer,
1707 : : deletable, ndeletable);
1708 : :
4098 teodor@sigaev.ru 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 : :
2899 akorotkov@postgresql 1729 : 12 : recptr = gistXLogDelete(buffer,
1730 : : deletable, ndeletable,
1731 : : snapshotConflictHorizon,
1732 : : heapRel);
1733 : :
4098 teodor@sigaev.ru 1734 : 12 : PageSetLSN(page, recptr);
1735 : : }
1736 : : else
260 pg@bowt.ie 1737 :UBC 0 : PageSetLSN(page, XLogGetFakeLSN(rel));
1738 : :
4098 teodor@sigaev.ru 1739 [ - + ]:CBC 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 : }
|