Branch data Line data Source code
1 : : /*
2 : : * brin.c
3 : : * Implementation of BRIN indexes for Postgres
4 : : *
5 : : * See src/backend/access/brin/README for details.
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/brin/brin.c
12 : : *
13 : : * TODO
14 : : * * ScalarArrayOpExpr (amsearcharray -> SK_SEARCHARRAY)
15 : : */
16 : : #include "postgres.h"
17 : :
18 : : #include "access/brin.h"
19 : : #include "access/brin_page.h"
20 : : #include "access/brin_pageops.h"
21 : : #include "access/brin_xlog.h"
22 : : #include "access/relation.h"
23 : : #include "access/reloptions.h"
24 : : #include "access/relscan.h"
25 : : #include "access/table.h"
26 : : #include "access/tableam.h"
27 : : #include "access/xloginsert.h"
28 : : #include "catalog/index.h"
29 : : #include "catalog/pg_am.h"
30 : : #include "commands/vacuum.h"
31 : : #include "executor/instrument.h"
32 : : #include "miscadmin.h"
33 : : #include "pgstat.h"
34 : : #include "postmaster/autovacuum.h"
35 : : #include "storage/bufmgr.h"
36 : : #include "storage/condition_variable.h"
37 : : #include "storage/freespace.h"
38 : : #include "storage/proc.h"
39 : : #include "tcop/tcopprot.h"
40 : : #include "utils/acl.h"
41 : : #include "utils/datum.h"
42 : : #include "utils/fmgrprotos.h"
43 : : #include "utils/guc.h"
44 : : #include "utils/index_selfuncs.h"
45 : : #include "utils/memutils.h"
46 : : #include "utils/rel.h"
47 : : #include "utils/tuplesort.h"
48 : : #include "utils/wait_event.h"
49 : :
50 : : /* Magic numbers for parallel state sharing */
51 : : #define PARALLEL_KEY_BRIN_SHARED UINT64CONST(0xB000000000000001)
52 : : #define PARALLEL_KEY_TUPLESORT UINT64CONST(0xB000000000000002)
53 : : #define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xB000000000000003)
54 : : #define PARALLEL_KEY_WAL_USAGE UINT64CONST(0xB000000000000004)
55 : : #define PARALLEL_KEY_BUFFER_USAGE UINT64CONST(0xB000000000000005)
56 : :
57 : : /*
58 : : * Status for index builds performed in parallel. This is allocated in a
59 : : * dynamic shared memory segment.
60 : : */
61 : : typedef struct BrinShared
62 : : {
63 : : /*
64 : : * These fields are not modified during the build. They primarily exist
65 : : * for the benefit of worker processes that need to create state
66 : : * corresponding to that used by the leader.
67 : : */
68 : : Oid heaprelid;
69 : : Oid indexrelid;
70 : : bool isconcurrent;
71 : : BlockNumber pagesPerRange;
72 : : int scantuplesortstates;
73 : :
74 : : /* Query ID, for report in worker processes */
75 : : int64 queryid;
76 : :
77 : : /*
78 : : * workersdonecv is used to monitor the progress of workers. All parallel
79 : : * participants must indicate that they are done before leader can use
80 : : * results built by the workers (and before leader can write the data into
81 : : * the index).
82 : : */
83 : : ConditionVariable workersdonecv;
84 : :
85 : : /*
86 : : * mutex protects all fields before heapdesc.
87 : : *
88 : : * These fields contain status information of interest to BRIN index
89 : : * builds that must work just the same when an index is built in parallel.
90 : : */
91 : : slock_t mutex;
92 : :
93 : : /*
94 : : * Mutable state that is maintained by workers, and reported back to
95 : : * leader at end of the scans.
96 : : *
97 : : * nparticipantsdone is number of worker processes finished.
98 : : *
99 : : * reltuples is the total number of input heap tuples.
100 : : *
101 : : * indtuples is the total number of tuples that made it into the index.
102 : : *
103 : : * brokenhotchain indicates if any worker detected a broken HOT chain
104 : : * during build.
105 : : */
106 : : int nparticipantsdone;
107 : : double reltuples;
108 : : double indtuples;
109 : : bool brokenhotchain;
110 : :
111 : : /*
112 : : * ParallelTableScanDescData data follows. Can't directly embed here, as
113 : : * implementations of the parallel table scan desc interface might need
114 : : * stronger alignment.
115 : : */
116 : : } BrinShared;
117 : :
118 : : /*
119 : : * Return pointer to a BrinShared's parallel table scan.
120 : : *
121 : : * c.f. shm_toc_allocate as to why BUFFERALIGN is used, rather than just
122 : : * MAXALIGN.
123 : : */
124 : : #define ParallelTableScanFromBrinShared(shared) \
125 : : (ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(BrinShared)))
126 : :
127 : : /*
128 : : * Status for leader in parallel index build.
129 : : */
130 : : typedef struct BrinLeader
131 : : {
132 : : /* parallel context itself */
133 : : ParallelContext *pcxt;
134 : :
135 : : /*
136 : : * nparticipanttuplesorts is the exact number of worker processes
137 : : * successfully launched, plus one leader process if it participates as a
138 : : * worker (only DISABLE_LEADER_PARTICIPATION builds avoid leader
139 : : * participating as a worker).
140 : : */
141 : : int nparticipanttuplesorts;
142 : :
143 : : /*
144 : : * Leader process convenience pointers to shared state (leader avoids TOC
145 : : * lookups).
146 : : *
147 : : * brinshared is the shared state for entire build. sharedsort is the
148 : : * shared, tuplesort-managed state passed to each process tuplesort.
149 : : * snapshot is the snapshot used by the scan iff an MVCC snapshot is
150 : : * required.
151 : : */
152 : : BrinShared *brinshared;
153 : : Sharedsort *sharedsort;
154 : : Snapshot snapshot;
155 : : WalUsage *walusage;
156 : : BufferUsage *bufferusage;
157 : : } BrinLeader;
158 : :
159 : : /*
160 : : * We use a BrinBuildState during initial construction of a BRIN index.
161 : : * The running state is kept in a BrinMemTuple.
162 : : */
163 : : typedef struct BrinBuildState
164 : : {
165 : : Relation bs_irel;
166 : : double bs_numtuples;
167 : : double bs_reltuples;
168 : : Buffer bs_currentInsertBuf;
169 : : BlockNumber bs_pagesPerRange;
170 : : BlockNumber bs_currRangeStart;
171 : : BlockNumber bs_maxRangeStart;
172 : : BrinRevmap *bs_rmAccess;
173 : : BrinDesc *bs_bdesc;
174 : : BrinMemTuple *bs_dtuple;
175 : :
176 : : BrinTuple *bs_emptyTuple;
177 : : Size bs_emptyTupleLen;
178 : : MemoryContext bs_context;
179 : :
180 : : /*
181 : : * bs_leader is only present when a parallel index build is performed, and
182 : : * only in the leader process. (Actually, only the leader process has a
183 : : * BrinBuildState.)
184 : : */
185 : : BrinLeader *bs_leader;
186 : : int bs_worker_id;
187 : :
188 : : /*
189 : : * The sortstate is used by workers (including the leader). It has to be
190 : : * part of the build state, because that's the only thing passed to the
191 : : * build callback etc.
192 : : */
193 : : Tuplesortstate *bs_sortstate;
194 : : } BrinBuildState;
195 : :
196 : : /*
197 : : * We use a BrinInsertState to capture running state spanning multiple
198 : : * brininsert invocations, within the same command.
199 : : */
200 : : typedef struct BrinInsertState
201 : : {
202 : : BrinRevmap *bis_rmAccess;
203 : : BrinDesc *bis_desc;
204 : : BlockNumber bis_pages_per_range;
205 : : } BrinInsertState;
206 : :
207 : : /*
208 : : * Struct used as "opaque" during index scans
209 : : */
210 : : typedef struct BrinOpaque
211 : : {
212 : : BlockNumber bo_pagesPerRange;
213 : : BrinRevmap *bo_rmAccess;
214 : : BrinDesc *bo_bdesc;
215 : : } BrinOpaque;
216 : :
217 : : #define BRIN_ALL_BLOCKRANGES InvalidBlockNumber
218 : :
219 : : static BrinBuildState *initialize_brin_buildstate(Relation idxRel,
220 : : BrinRevmap *revmap,
221 : : BlockNumber pagesPerRange,
222 : : BlockNumber tablePages);
223 : : static BrinInsertState *initialize_brin_insertstate(Relation idxRel, IndexInfo *indexInfo);
224 : : static void terminate_brin_buildstate(BrinBuildState *state);
225 : : static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange,
226 : : bool include_partial, double *numSummarized, double *numExisting);
227 : : static void form_and_insert_tuple(BrinBuildState *state);
228 : : static void form_and_spill_tuple(BrinBuildState *state);
229 : : static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a,
230 : : BrinTuple *b);
231 : : static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy);
232 : : static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc,
233 : : BrinMemTuple *dtup, const Datum *values, const bool *nulls);
234 : : static bool check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys);
235 : : static void brin_fill_empty_ranges(BrinBuildState *state,
236 : : BlockNumber prevRange, BlockNumber nextRange);
237 : :
238 : : /* parallel index builds */
239 : : static void _brin_begin_parallel(BrinBuildState *buildstate, Relation heap, Relation index,
240 : : bool isconcurrent, int request);
241 : : static void _brin_end_parallel(BrinLeader *brinleader, BrinBuildState *state);
242 : : static Size _brin_parallel_estimate_shared(Relation heap, Snapshot snapshot);
243 : : static double _brin_parallel_heapscan(BrinBuildState *state,
244 : : bool *brokenhotchain);
245 : : static double _brin_parallel_merge(BrinBuildState *state,
246 : : IndexInfo *indexInfo);
247 : : static void _brin_leader_participate_as_worker(BrinBuildState *buildstate,
248 : : Relation heap, Relation index);
249 : : static void _brin_parallel_scan_and_build(BrinBuildState *state,
250 : : BrinShared *brinshared,
251 : : Sharedsort *sharedsort,
252 : : Relation heap, Relation index,
253 : : int sortmem, bool progress);
254 : :
255 : : /*
256 : : * BRIN handler function: return IndexAmRoutine with access method parameters
257 : : * and callbacks.
258 : : */
259 : : Datum
260 : 2853 : brinhandler(PG_FUNCTION_ARGS)
261 : : {
262 : : static const IndexAmRoutine amroutine = {
263 : : .type = T_IndexAmRoutine,
264 : : .amstrategies = 0,
265 : : .amsupport = BRIN_LAST_OPTIONAL_PROCNUM,
266 : : .amoptsprocnum = BRIN_PROCNUM_OPTIONS,
267 : : .amcanorder = false,
268 : : .amcanorderbyop = false,
269 : : .amcanhash = false,
270 : : .amconsistentequality = false,
271 : : .amconsistentordering = false,
272 : : .amcanbackward = false,
273 : : .amcanunique = false,
274 : : .amcanmulticol = true,
275 : : .amoptionalkey = true,
276 : : .amsearcharray = false,
277 : : .amsearchnulls = true,
278 : : .amstorage = true,
279 : : .amclusterable = false,
280 : : .ampredlocks = false,
281 : : .amcanparallel = false,
282 : : .amcanbuildparallel = true,
283 : : .amcaninclude = false,
284 : : .amusemaintenanceworkmem = false,
285 : : .amsummarizing = true,
286 : : .amparallelvacuumoptions =
287 : : VACUUM_OPTION_PARALLEL_CLEANUP,
288 : : .amkeytype = InvalidOid,
289 : :
290 : : .ambuild = brinbuild,
291 : : .ambuildempty = brinbuildempty,
292 : : .aminsert = brininsert,
293 : : .aminsertcleanup = brininsertcleanup,
294 : : .ambulkdelete = brinbulkdelete,
295 : : .amvacuumcleanup = brinvacuumcleanup,
296 : : .amcanreturn = NULL,
297 : : .amcostestimate = brincostestimate,
298 : : .amgettreeheight = NULL,
299 : : .amoptions = brinoptions,
300 : : .amproperty = NULL,
301 : : .ambuildphasename = NULL,
302 : : .amvalidate = brinvalidate,
303 : : .amadjustmembers = NULL,
304 : : .ambeginscan = brinbeginscan,
305 : : .amrescan = brinrescan,
306 : : .amgettuple = NULL,
307 : : .amgetbitmap = bringetbitmap,
308 : : .amendscan = brinendscan,
309 : : .ammarkpos = NULL,
310 : : .amrestrpos = NULL,
311 : : .amestimateparallelscan = NULL,
312 : : .aminitparallelscan = NULL,
313 : : .amparallelrescan = NULL,
314 : : .amtranslatestrategy = NULL,
315 : : .amtranslatecmptype = NULL,
316 : : };
317 : :
318 : 2853 : PG_RETURN_POINTER(&amroutine);
319 : : }
320 : :
321 : : /*
322 : : * Initialize a BrinInsertState to maintain state to be used across multiple
323 : : * tuple inserts, within the same command.
324 : : */
325 : : static BrinInsertState *
326 : 726 : initialize_brin_insertstate(Relation idxRel, IndexInfo *indexInfo)
327 : : {
328 : : BrinInsertState *bistate;
329 : : MemoryContext oldcxt;
330 : :
331 : 726 : oldcxt = MemoryContextSwitchTo(indexInfo->ii_Context);
332 : 726 : bistate = palloc0_object(BrinInsertState);
333 : 726 : bistate->bis_desc = brin_build_desc(idxRel);
334 : 726 : bistate->bis_rmAccess = brinRevmapInitialize(idxRel,
335 : : &bistate->bis_pages_per_range);
336 : 726 : indexInfo->ii_AmCache = bistate;
337 : 726 : MemoryContextSwitchTo(oldcxt);
338 : :
339 : 726 : return bistate;
340 : : }
341 : :
342 : : /*
343 : : * A tuple in the heap is being inserted. To keep a brin index up to date,
344 : : * we need to obtain the relevant index tuple and compare its stored values
345 : : * with those of the new tuple. If the tuple values are not consistent with
346 : : * the summary tuple, we need to update the index tuple.
347 : : *
348 : : * If autosummarization is enabled, check if we need to summarize the previous
349 : : * page range.
350 : : *
351 : : * If the range is not currently summarized (i.e. the revmap returns NULL for
352 : : * it), there's nothing to do for this tuple.
353 : : */
354 : : bool
355 : 68794 : brininsert(Relation idxRel, Datum *values, bool *nulls,
356 : : ItemPointer heaptid, Relation heapRel,
357 : : IndexUniqueCheck checkUnique,
358 : : bool indexUnchanged,
359 : : IndexInfo *indexInfo)
360 : : {
361 : : BlockNumber pagesPerRange;
362 : : BlockNumber origHeapBlk;
363 : : BlockNumber heapBlk;
364 : 68794 : BrinInsertState *bistate = (BrinInsertState *) indexInfo->ii_AmCache;
365 : : BrinRevmap *revmap;
366 : : BrinDesc *bdesc;
367 : 68794 : Buffer buf = InvalidBuffer;
368 : 68794 : MemoryContext tupcxt = NULL;
369 : 68794 : MemoryContext oldcxt = CurrentMemoryContext;
370 [ + + ]: 68794 : bool autosummarize = BrinGetAutoSummarize(idxRel);
371 : :
372 : : /*
373 : : * If first time through in this statement, initialize the insert state
374 : : * that we keep for all the inserts in the command.
375 : : */
376 [ + + ]: 68794 : if (!bistate)
377 : 726 : bistate = initialize_brin_insertstate(idxRel, indexInfo);
378 : :
379 : 68794 : revmap = bistate->bis_rmAccess;
380 : 68794 : bdesc = bistate->bis_desc;
381 : 68794 : pagesPerRange = bistate->bis_pages_per_range;
382 : :
383 : : /*
384 : : * origHeapBlk is the block number where the insertion occurred. heapBlk
385 : : * is the first block in the corresponding page range.
386 : : */
387 : 68794 : origHeapBlk = ItemPointerGetBlockNumber(heaptid);
388 : 68794 : heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
389 : :
390 : : for (;;)
391 : 0 : {
392 : 68794 : bool need_insert = false;
393 : : OffsetNumber off;
394 : : BrinTuple *brtup;
395 : : BrinMemTuple *dtup;
396 : :
397 [ - + ]: 68794 : CHECK_FOR_INTERRUPTS();
398 : :
399 : : /*
400 : : * If auto-summarization is enabled and we just inserted the first
401 : : * tuple into the first block of a new non-first page range, request a
402 : : * summarization run of the previous range.
403 : : */
404 [ + + + + ]: 68794 : if (autosummarize &&
405 [ + - ]: 145 : heapBlk > 0 &&
406 [ + + ]: 145 : heapBlk == origHeapBlk &&
407 : 145 : ItemPointerGetOffsetNumber(heaptid) == FirstOffsetNumber)
408 : : {
409 : 8 : BlockNumber lastPageRange = heapBlk - 1;
410 : : BrinTuple *lastPageTuple;
411 : :
412 : : lastPageTuple =
413 : 8 : brinGetTupleForHeapBlock(revmap, lastPageRange, &buf, &off,
414 : : NULL, BUFFER_LOCK_SHARE);
415 [ + + ]: 8 : if (!lastPageTuple)
416 : : {
417 : : bool recorded;
418 : :
419 : 6 : recorded = AutoVacuumRequestWork(AVW_BRINSummarizeRange,
420 : : RelationGetRelid(idxRel),
421 : : lastPageRange);
422 [ - + ]: 6 : if (!recorded)
423 [ # # ]: 0 : ereport(LOG,
424 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
425 : : errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
426 : : RelationGetRelationName(idxRel),
427 : : lastPageRange)));
428 : : }
429 : : else
430 : 2 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
431 : : }
432 : :
433 : 68794 : brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
434 : : NULL, BUFFER_LOCK_SHARE);
435 : :
436 : : /* if range is unsummarized, there's nothing to do */
437 [ + + ]: 68794 : if (!brtup)
438 : 41875 : break;
439 : :
440 : : /* First time through in this brininsert call? */
441 [ + - ]: 26919 : if (tupcxt == NULL)
442 : : {
443 : 26919 : tupcxt = AllocSetContextCreate(CurrentMemoryContext,
444 : : "brininsert cxt",
445 : : ALLOCSET_DEFAULT_SIZES);
446 : 26919 : MemoryContextSwitchTo(tupcxt);
447 : : }
448 : :
449 : 26919 : dtup = brin_deform_tuple(bdesc, brtup, NULL);
450 : :
451 : 26919 : need_insert = add_values_to_range(idxRel, bdesc, dtup, values, nulls);
452 : :
453 [ + + ]: 26919 : if (!need_insert)
454 : : {
455 : : /*
456 : : * The tuple is consistent with the new values, so there's nothing
457 : : * to do.
458 : : */
459 : 14347 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
460 : : }
461 : : else
462 : : {
463 : 12572 : Page page = BufferGetPage(buf);
464 : 12572 : ItemId lp = PageGetItemId(page, off);
465 : : Size origsz;
466 : : BrinTuple *origtup;
467 : : Size newsz;
468 : : BrinTuple *newtup;
469 : : bool samepage;
470 : :
471 : : /*
472 : : * Make a copy of the old tuple, so that we can compare it after
473 : : * re-acquiring the lock.
474 : : */
475 : 12572 : origsz = ItemIdGetLength(lp);
476 : 12572 : origtup = brin_copy_tuple(brtup, origsz, NULL, NULL);
477 : :
478 : : /*
479 : : * Before releasing the lock, check if we can attempt a same-page
480 : : * update. Another process could insert a tuple concurrently in
481 : : * the same page though, so downstream we must be prepared to cope
482 : : * if this turns out to not be possible after all.
483 : : */
484 : 12572 : newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
485 : 12572 : samepage = brin_can_do_samepage_update(buf, origsz, newsz);
486 : 12572 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
487 : :
488 : : /*
489 : : * Try to update the tuple. If this doesn't work for whatever
490 : : * reason, we need to restart from the top; the revmap might be
491 : : * pointing at a different tuple for this block now, so we need to
492 : : * recompute to ensure both our new heap tuple and the other
493 : : * inserter's are covered by the combined tuple. It might be that
494 : : * we don't need to update at all.
495 : : */
496 [ - + ]: 12572 : if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
497 : : buf, off, origtup, origsz, newtup, newsz,
498 : : samepage))
499 : : {
500 : : /* no luck; start over */
501 : 0 : MemoryContextReset(tupcxt);
502 : 0 : continue;
503 : : }
504 : : }
505 : :
506 : : /* success! */
507 : 26919 : break;
508 : : }
509 : :
510 [ + + ]: 68794 : if (BufferIsValid(buf))
511 : 26921 : ReleaseBuffer(buf);
512 : 68794 : MemoryContextSwitchTo(oldcxt);
513 [ + + ]: 68794 : if (tupcxt != NULL)
514 : 26919 : MemoryContextDelete(tupcxt);
515 : :
516 : 68794 : return false;
517 : : }
518 : :
519 : : /*
520 : : * Callback to clean up the BrinInsertState once all tuple inserts are done.
521 : : */
522 : : void
523 : 744 : brininsertcleanup(Relation index, IndexInfo *indexInfo)
524 : : {
525 : 744 : BrinInsertState *bistate = (BrinInsertState *) indexInfo->ii_AmCache;
526 : :
527 : : /* bail out if cache not initialized */
528 [ + + ]: 744 : if (bistate == NULL)
529 : 18 : return;
530 : :
531 : : /* do this first to avoid dangling pointer if we fail partway through */
532 : 726 : indexInfo->ii_AmCache = NULL;
533 : :
534 : : /*
535 : : * Clean up the revmap. Note that the brinDesc has already been cleaned up
536 : : * as part of its own memory context.
537 : : */
538 : 726 : brinRevmapTerminate(bistate->bis_rmAccess);
539 : 726 : pfree(bistate);
540 : : }
541 : :
542 : : /*
543 : : * Initialize state for a BRIN index scan.
544 : : *
545 : : * We read the metapage here to determine the pages-per-range number that this
546 : : * index was built with. Note that since this cannot be changed while we're
547 : : * holding lock on index, it's not necessary to recompute it during brinrescan.
548 : : */
549 : : IndexScanDesc
550 : 1964 : brinbeginscan(Relation r, int nkeys, int norderbys)
551 : : {
552 : : IndexScanDesc scan;
553 : : BrinOpaque *opaque;
554 : :
555 : 1964 : scan = RelationGetIndexScan(r, nkeys, norderbys);
556 : :
557 : 1964 : opaque = palloc_object(BrinOpaque);
558 : 1964 : opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange);
559 : 1964 : opaque->bo_bdesc = brin_build_desc(r);
560 : 1964 : scan->opaque = opaque;
561 : :
562 : 1964 : return scan;
563 : : }
564 : :
565 : : /*
566 : : * Execute the index scan.
567 : : *
568 : : * This works by reading index TIDs from the revmap, and obtaining the index
569 : : * tuples pointed to by them; the summary values in the index tuples are
570 : : * compared to the scan keys. We return into the TID bitmap all the pages in
571 : : * ranges corresponding to index tuples that match the scan keys.
572 : : *
573 : : * If a TID from the revmap is read as InvalidTID, we know that range is
574 : : * unsummarized. Pages in those ranges need to be returned regardless of scan
575 : : * keys.
576 : : */
577 : : int64
578 : 1964 : bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
579 : : {
580 : 1964 : Relation idxRel = scan->indexRelation;
581 : 1964 : Buffer buf = InvalidBuffer;
582 : : BrinDesc *bdesc;
583 : : Oid heapOid;
584 : : Relation heapRel;
585 : : BrinOpaque *opaque;
586 : : BlockNumber nblocks;
587 : 1964 : int64 totalpages = 0;
588 : : FmgrInfo *consistentFn;
589 : : MemoryContext oldcxt;
590 : : MemoryContext perRangeCxt;
591 : : BrinMemTuple *dtup;
592 : 1964 : BrinTuple *btup = NULL;
593 : 1964 : Size btupsz = 0;
594 : : ScanKey **keys,
595 : : **nullkeys;
596 : : int *nkeys,
597 : : *nnullkeys;
598 : : char *ptr;
599 : : Size len;
600 : : char *tmp PG_USED_FOR_ASSERTS_ONLY;
601 : :
602 : 1964 : opaque = (BrinOpaque *) scan->opaque;
603 : 1964 : bdesc = opaque->bo_bdesc;
604 [ - + - - : 1964 : pgstat_count_index_scan(idxRel);
+ - ]
605 [ + + ]: 1964 : if (scan->instrument)
606 : 36 : scan->instrument->nsearches++;
607 : :
608 : : /*
609 : : * We need to know the size of the table so that we know how long to
610 : : * iterate on the revmap.
611 : : */
612 : 1964 : heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
613 : 1964 : heapRel = table_open(heapOid, AccessShareLock);
614 : 1964 : nblocks = RelationGetNumberOfBlocks(heapRel);
615 : 1964 : table_close(heapRel, AccessShareLock);
616 : :
617 : : /*
618 : : * Make room for the consistent support procedures of indexed columns. We
619 : : * don't look them up here; we do that lazily the first time we see a scan
620 : : * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
621 : : */
622 : 1964 : consistentFn = palloc0_array(FmgrInfo, bdesc->bd_tupdesc->natts);
623 : :
624 : : /*
625 : : * Make room for per-attribute lists of scan keys that we'll pass to the
626 : : * consistent support procedure. We don't know which attributes have scan
627 : : * keys, so we allocate space for all attributes. That may use more memory
628 : : * but it's probably cheaper than determining which attributes are used.
629 : : *
630 : : * We keep null and regular keys separate, so that we can pass just the
631 : : * regular keys to the consistent function easily.
632 : : *
633 : : * To reduce the allocation overhead, we allocate one big chunk and then
634 : : * carve it into smaller arrays ourselves. All the pieces have exactly the
635 : : * same lifetime, so that's OK.
636 : : *
637 : : * XXX The widest index can have 32 attributes, so the amount of wasted
638 : : * memory is negligible. We could invent a more compact approach (with
639 : : * just space for used attributes) but that would make the matching more
640 : : * complex so it's not a good trade-off.
641 : : */
642 : 1964 : len =
643 : 1964 : MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* regular keys */
644 : 1964 : MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
645 : 1964 : MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts) +
646 : 1964 : MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* NULL keys */
647 : 1964 : MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
648 : 1964 : MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
649 : :
650 : 1964 : ptr = palloc(len);
651 : 1964 : tmp = ptr;
652 : :
653 : 1964 : keys = (ScanKey **) ptr;
654 : 1964 : ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
655 : :
656 : 1964 : nullkeys = (ScanKey **) ptr;
657 : 1964 : ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
658 : :
659 : 1964 : nkeys = (int *) ptr;
660 : 1964 : ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
661 : :
662 : 1964 : nnullkeys = (int *) ptr;
663 : 1964 : ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
664 : :
665 [ + + ]: 46652 : for (int i = 0; i < bdesc->bd_tupdesc->natts; i++)
666 : : {
667 : 44688 : keys[i] = (ScanKey *) ptr;
668 : 44688 : ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
669 : :
670 : 44688 : nullkeys[i] = (ScanKey *) ptr;
671 : 44688 : ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
672 : : }
673 : :
674 : : Assert(tmp + len == ptr);
675 : :
676 : : /* zero the number of keys */
677 : 1964 : memset(nkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
678 : 1964 : memset(nnullkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
679 : :
680 : : /* Preprocess the scan keys - split them into per-attribute arrays. */
681 [ + + ]: 3928 : for (int keyno = 0; keyno < scan->numberOfKeys; keyno++)
682 : : {
683 : 1964 : ScanKey key = &scan->keyData[keyno];
684 : 1964 : AttrNumber keyattno = key->sk_attno;
685 : :
686 : : /*
687 : : * The collation of the scan key must match the collation used in the
688 : : * index column (but only if the search is not IS NULL/ IS NOT NULL).
689 : : * Otherwise we shouldn't be using this index ...
690 : : */
691 : : Assert((key->sk_flags & SK_ISNULL) ||
692 : : (key->sk_collation ==
693 : : TupleDescAttr(bdesc->bd_tupdesc,
694 : : keyattno - 1)->attcollation));
695 : :
696 : : /*
697 : : * First time we see this index attribute, so init as needed.
698 : : *
699 : : * This is a bit of an overkill - we don't know how many scan keys are
700 : : * there for this attribute, so we simply allocate the largest number
701 : : * possible (as if all keys were for this attribute). This may waste a
702 : : * bit of memory, but we only expect small number of scan keys in
703 : : * general, so this should be negligible, and repeated repalloc calls
704 : : * are not free either.
705 : : */
706 [ + - ]: 1964 : if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
707 : : {
708 : : FmgrInfo *consistentFI;
709 : :
710 : : /* First time we see this attribute, so no key/null keys. */
711 : : Assert(nkeys[keyattno - 1] == 0);
712 : : Assert(nnullkeys[keyattno - 1] == 0);
713 : :
714 : 1964 : consistentFI = index_getprocinfo(idxRel, keyattno,
715 : : BRIN_PROCNUM_CONSISTENT);
716 : 1964 : fmgr_info_copy(&consistentFn[keyattno - 1], consistentFI,
717 : : CurrentMemoryContext);
718 : : }
719 : :
720 : : /* Add key to the proper per-attribute array. */
721 [ + + ]: 1964 : if (key->sk_flags & SK_ISNULL)
722 : : {
723 : 24 : nullkeys[keyattno - 1][nnullkeys[keyattno - 1]] = key;
724 : 24 : nnullkeys[keyattno - 1]++;
725 : : }
726 : : else
727 : : {
728 : 1940 : keys[keyattno - 1][nkeys[keyattno - 1]] = key;
729 : 1940 : nkeys[keyattno - 1]++;
730 : : }
731 : : }
732 : :
733 : : /* allocate an initial in-memory tuple, out of the per-range memcxt */
734 : 1964 : dtup = brin_new_memtuple(bdesc);
735 : :
736 : : /*
737 : : * Setup and use a per-range memory context, which is reset every time we
738 : : * loop below. This avoids having to free the tuples within the loop.
739 : : */
740 : 1964 : perRangeCxt = AllocSetContextCreate(CurrentMemoryContext,
741 : : "bringetbitmap cxt",
742 : : ALLOCSET_DEFAULT_SIZES);
743 : 1964 : oldcxt = MemoryContextSwitchTo(perRangeCxt);
744 : :
745 : : /*
746 : : * Now scan the revmap. We start by querying for heap page 0,
747 : : * incrementing by the number of pages per range; this gives us a full
748 : : * view of the table. We make use of uint64 for heapBlk as a BlockNumber
749 : : * could wrap for tables with close to 2^32 pages.
750 : : */
751 [ + + ]: 129732 : for (uint64 heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
752 : : {
753 : : bool addrange;
754 : 127768 : bool gottuple = false;
755 : : BrinTuple *tup;
756 : : OffsetNumber off;
757 : : Size size;
758 : :
759 [ - + ]: 127768 : CHECK_FOR_INTERRUPTS();
760 : :
761 : 127768 : MemoryContextReset(perRangeCxt);
762 : :
763 : 127768 : tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, (BlockNumber) heapBlk, &buf,
764 : : &off, &size, BUFFER_LOCK_SHARE);
765 [ + + ]: 127768 : if (tup)
766 : : {
767 : 126624 : gottuple = true;
768 : 126624 : btup = brin_copy_tuple(tup, size, btup, &btupsz);
769 : 126624 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
770 : : }
771 : :
772 : : /*
773 : : * For page ranges with no indexed tuple, we must return the whole
774 : : * range; otherwise, compare it to the scan keys.
775 : : */
776 [ + + ]: 127768 : if (!gottuple)
777 : : {
778 : 1144 : addrange = true;
779 : : }
780 : : else
781 : : {
782 : 126624 : dtup = brin_deform_tuple(bdesc, btup, dtup);
783 [ - + ]: 126624 : if (dtup->bt_placeholder)
784 : : {
785 : : /*
786 : : * Placeholder tuples are always returned, regardless of the
787 : : * values stored in them.
788 : : */
789 : 0 : addrange = true;
790 : : }
791 : : else
792 : : {
793 : : int attno;
794 : :
795 : : /*
796 : : * Compare scan keys with summary values stored for the range.
797 : : * If scan keys are matched, the page range must be added to
798 : : * the bitmap. We initially assume the range needs to be
799 : : * added; in particular this serves the case where there are
800 : : * no keys.
801 : : */
802 : 126624 : addrange = true;
803 [ + + ]: 3136046 : for (attno = 1; attno <= bdesc->bd_tupdesc->natts; attno++)
804 : : {
805 : : BrinValues *bval;
806 : : Datum add;
807 : : Oid collation;
808 : :
809 : : /*
810 : : * skip attributes without any scan keys (both regular and
811 : : * IS [NOT] NULL)
812 : : */
813 [ + + + + ]: 3045156 : if (nkeys[attno - 1] == 0 && nnullkeys[attno - 1] == 0)
814 : 2918532 : continue;
815 : :
816 : 126624 : bval = &dtup->bt_columns[attno - 1];
817 : :
818 : : /*
819 : : * If the BRIN tuple indicates that this range is empty,
820 : : * we can skip it: there's nothing to match. We don't
821 : : * need to examine the next columns.
822 : : */
823 [ - + ]: 126624 : if (dtup->bt_empty_range)
824 : : {
825 : 0 : addrange = false;
826 : 0 : break;
827 : : }
828 : :
829 : : /*
830 : : * First check if there are any IS [NOT] NULL scan keys,
831 : : * and if we're violating them. In that case we can
832 : : * terminate early, without invoking the support function.
833 : : *
834 : : * As there may be more keys, we can only determine
835 : : * mismatch within this loop.
836 : : */
837 [ + - ]: 126624 : if (bdesc->bd_info[attno - 1]->oi_regular_nulls &&
838 [ + + ]: 126624 : !check_null_keys(bval, nullkeys[attno - 1],
839 : 126624 : nnullkeys[attno - 1]))
840 : : {
841 : : /*
842 : : * If any of the IS [NOT] NULL keys failed, the page
843 : : * range as a whole can't pass. So terminate the loop.
844 : : */
845 : 664 : addrange = false;
846 : 664 : break;
847 : : }
848 : :
849 : : /*
850 : : * So either there are no IS [NOT] NULL keys, or all
851 : : * passed. If there are no regular scan keys, we're done -
852 : : * the page range matches. If there are regular keys, but
853 : : * the page range is marked as 'all nulls' it can't
854 : : * possibly pass (we're assuming the operators are
855 : : * strict).
856 : : */
857 : :
858 : : /* No regular scan keys - page range as a whole passes. */
859 [ + + ]: 125960 : if (!nkeys[attno - 1])
860 : 824 : continue;
861 : :
862 : : Assert((nkeys[attno - 1] > 0) &&
863 : : (nkeys[attno - 1] <= scan->numberOfKeys));
864 : :
865 : : /* If it is all nulls, it cannot possibly be consistent. */
866 [ + + ]: 125136 : if (bval->bv_allnulls)
867 : : {
868 : 252 : addrange = false;
869 : 252 : break;
870 : : }
871 : :
872 : : /*
873 : : * Collation from the first key (has to be the same for
874 : : * all keys for the same attribute).
875 : : */
876 : 124884 : collation = keys[attno - 1][0]->sk_collation;
877 : :
878 : : /*
879 : : * Check whether the scan key is consistent with the page
880 : : * range values; if so, have the pages in the range added
881 : : * to the output bitmap.
882 : : *
883 : : * The opclass may or may not support processing of
884 : : * multiple scan keys. We can determine that based on the
885 : : * number of arguments - functions with extra parameter
886 : : * (number of scan keys) do support this, otherwise we
887 : : * have to simply pass the scan keys one by one.
888 : : */
889 [ + + ]: 124884 : if (consistentFn[attno - 1].fn_nargs >= 4)
890 : : {
891 : : /* Check all keys at once */
892 : 52792 : add = FunctionCall4Coll(&consistentFn[attno - 1],
893 : : collation,
894 : : PointerGetDatum(bdesc),
895 : : PointerGetDatum(bval),
896 : 26396 : PointerGetDatum(keys[attno - 1]),
897 : 26396 : Int32GetDatum(nkeys[attno - 1]));
898 : 26396 : addrange = DatumGetBool(add);
899 : : }
900 : : else
901 : : {
902 : : /*
903 : : * Check keys one by one
904 : : *
905 : : * When there are multiple scan keys, failure to meet
906 : : * the criteria for a single one of them is enough to
907 : : * discard the range as a whole, so break out of the
908 : : * loop as soon as a false return value is obtained.
909 : : */
910 : : int keyno;
911 : :
912 [ + + ]: 172052 : for (keyno = 0; keyno < nkeys[attno - 1]; keyno++)
913 : : {
914 : 98488 : add = FunctionCall3Coll(&consistentFn[attno - 1],
915 : 98488 : keys[attno - 1][keyno]->sk_collation,
916 : : PointerGetDatum(bdesc),
917 : : PointerGetDatum(bval),
918 : 98488 : PointerGetDatum(keys[attno - 1][keyno]));
919 : 98488 : addrange = DatumGetBool(add);
920 [ + + ]: 98488 : if (!addrange)
921 : 24924 : break;
922 : : }
923 : : }
924 : :
925 : : /*
926 : : * If we found a scan key eliminating the range, no need
927 : : * to check additional ones.
928 : : */
929 [ + + ]: 124884 : if (!addrange)
930 : 34818 : break;
931 : : }
932 : : }
933 : : }
934 : :
935 : : /* add the pages in the range to the output bitmap, if needed */
936 [ + + ]: 127768 : if (addrange)
937 : : {
938 : : uint64 pageno;
939 : :
940 : 92034 : for (pageno = heapBlk;
941 [ + + ]: 190684 : pageno <= Min(nblocks, heapBlk + opaque->bo_pagesPerRange) - 1;
942 : 98650 : pageno++)
943 : : {
944 : 98650 : MemoryContextSwitchTo(oldcxt);
945 : 98650 : tbm_add_page(tbm, pageno);
946 : 98650 : totalpages++;
947 : 98650 : MemoryContextSwitchTo(perRangeCxt);
948 : : }
949 : : }
950 : : }
951 : :
952 : 1964 : MemoryContextSwitchTo(oldcxt);
953 : 1964 : MemoryContextDelete(perRangeCxt);
954 : :
955 [ + - ]: 1964 : if (buf != InvalidBuffer)
956 : 1964 : ReleaseBuffer(buf);
957 : :
958 : : /*
959 : : * XXX We have an approximation of the number of *pages* that our scan
960 : : * returns, but we don't have a precise idea of the number of heap tuples
961 : : * involved.
962 : : */
963 : 1964 : return totalpages * 10;
964 : : }
965 : :
966 : : /*
967 : : * Re-initialize state for a BRIN index scan
968 : : */
969 : : void
970 : 1964 : brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys,
971 : : ScanKey orderbys, int norderbys)
972 : : {
973 : : /*
974 : : * Other index AMs preprocess the scan keys at this point, or sometime
975 : : * early during the scan; this lets them optimize by removing redundant
976 : : * keys, or doing early returns when they are impossible to satisfy; see
977 : : * _bt_preprocess_keys for an example. Something like that could be added
978 : : * here someday, too.
979 : : */
980 : :
981 [ + - + - ]: 1964 : if (scankey && scan->numberOfKeys > 0)
982 : 1964 : memcpy(scan->keyData, scankey, scan->numberOfKeys * sizeof(ScanKeyData));
983 : 1964 : }
984 : :
985 : : /*
986 : : * Close down a BRIN index scan
987 : : */
988 : : void
989 : 1964 : brinendscan(IndexScanDesc scan)
990 : : {
991 : 1964 : BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
992 : :
993 : 1964 : brinRevmapTerminate(opaque->bo_rmAccess);
994 : 1964 : brin_free_desc(opaque->bo_bdesc);
995 : 1964 : pfree(opaque);
996 : 1964 : }
997 : :
998 : : /*
999 : : * Per-heap-tuple callback for table_index_build_scan.
1000 : : *
1001 : : * Note we don't worry about the page range at the end of the table here; it is
1002 : : * present in the build state struct after we're called the last time, but not
1003 : : * inserted into the index. Caller must ensure to do so, if appropriate.
1004 : : */
1005 : : static void
1006 : 539359 : brinbuildCallback(Relation index,
1007 : : ItemPointer tid,
1008 : : Datum *values,
1009 : : bool *isnull,
1010 : : bool tupleIsAlive,
1011 : : void *brstate)
1012 : : {
1013 : 539359 : BrinBuildState *state = (BrinBuildState *) brstate;
1014 : : BlockNumber thisblock;
1015 : :
1016 : 539359 : thisblock = ItemPointerGetBlockNumber(tid);
1017 : :
1018 : : /*
1019 : : * If we're in a block that belongs to a future range, summarize what
1020 : : * we've got and start afresh. Note the scan might have skipped many
1021 : : * pages, if they were devoid of live tuples; make sure to insert index
1022 : : * tuples for those too.
1023 : : */
1024 [ + + ]: 540878 : while (thisblock > state->bs_currRangeStart + state->bs_pagesPerRange - 1)
1025 : : {
1026 : :
1027 : : BRIN_elog((DEBUG2,
1028 : : "brinbuildCallback: completed a range: %u--%u",
1029 : : state->bs_currRangeStart,
1030 : : state->bs_currRangeStart + state->bs_pagesPerRange));
1031 : :
1032 : : /* create the index tuple and insert it */
1033 : 1519 : form_and_insert_tuple(state);
1034 : :
1035 : : /* set state to correspond to the next range */
1036 : 1519 : state->bs_currRangeStart += state->bs_pagesPerRange;
1037 : :
1038 : : /* re-initialize state for it */
1039 : 1519 : brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
1040 : : }
1041 : :
1042 : : /* Accumulate the current tuple into the running state */
1043 : 539359 : (void) add_values_to_range(index, state->bs_bdesc, state->bs_dtuple,
1044 : : values, isnull);
1045 : 539359 : }
1046 : :
1047 : : /*
1048 : : * Per-heap-tuple callback for table_index_build_scan with parallelism.
1049 : : *
1050 : : * A version of the callback used by parallel index builds. The main difference
1051 : : * is that instead of writing the BRIN tuples into the index, we write them
1052 : : * into a shared tuplesort, and leave the insertion up to the leader (which may
1053 : : * reorder them a bit etc.). The callback also does not generate empty ranges,
1054 : : * those will be added by the leader when merging results from workers.
1055 : : */
1056 : : static void
1057 : 4981 : brinbuildCallbackParallel(Relation index,
1058 : : ItemPointer tid,
1059 : : Datum *values,
1060 : : bool *isnull,
1061 : : bool tupleIsAlive,
1062 : : void *brstate)
1063 : : {
1064 : 4981 : BrinBuildState *state = (BrinBuildState *) brstate;
1065 : : BlockNumber thisblock;
1066 : :
1067 : 4981 : thisblock = ItemPointerGetBlockNumber(tid);
1068 : :
1069 : : /*
1070 : : * If we're in a block that belongs to a different range, summarize what
1071 : : * we've got and start afresh. Note the scan might have skipped many
1072 : : * pages, if they were devoid of live tuples; we do not create empty BRIN
1073 : : * ranges here - the leader is responsible for filling them in.
1074 : : *
1075 : : * Unlike serial builds, parallel index builds allow synchronized seqscans
1076 : : * (because that's what parallel scans do). This means the block may wrap
1077 : : * around to the beginning of the relation, so the condition needs to
1078 : : * check for both future and past ranges.
1079 : : */
1080 [ + - ]: 4981 : if ((thisblock < state->bs_currRangeStart) ||
1081 [ + + ]: 4981 : (thisblock > state->bs_currRangeStart + state->bs_pagesPerRange - 1))
1082 : : {
1083 : :
1084 : : BRIN_elog((DEBUG2,
1085 : : "brinbuildCallbackParallel: completed a range: %u--%u",
1086 : : state->bs_currRangeStart,
1087 : : state->bs_currRangeStart + state->bs_pagesPerRange));
1088 : :
1089 : : /* create the index tuple and write it into the tuplesort */
1090 : 19 : form_and_spill_tuple(state);
1091 : :
1092 : : /*
1093 : : * Set state to correspond to the next range (for this block).
1094 : : *
1095 : : * This skips ranges that are either empty (and so we don't get any
1096 : : * tuples to summarize), or processed by other workers. We can't
1097 : : * differentiate those cases here easily, so we leave it up to the
1098 : : * leader to fill empty ranges where needed.
1099 : : */
1100 : : state->bs_currRangeStart
1101 : 19 : = state->bs_pagesPerRange * (thisblock / state->bs_pagesPerRange);
1102 : :
1103 : : /* re-initialize state for it */
1104 : 19 : brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
1105 : : }
1106 : :
1107 : : /* Accumulate the current tuple into the running state */
1108 : 4981 : (void) add_values_to_range(index, state->bs_bdesc, state->bs_dtuple,
1109 : : values, isnull);
1110 : 4981 : }
1111 : :
1112 : : /*
1113 : : * brinbuild() -- build a new BRIN index.
1114 : : */
1115 : : IndexBuildResult *
1116 : 241 : brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
1117 : : {
1118 : : IndexBuildResult *result;
1119 : : double reltuples;
1120 : : double idxtuples;
1121 : : BrinRevmap *revmap;
1122 : : BrinBuildState *state;
1123 : : Buffer meta;
1124 : : BlockNumber pagesPerRange;
1125 : :
1126 : : /*
1127 : : * We expect to be called exactly once for any index relation.
1128 : : */
1129 [ - + ]: 241 : if (RelationGetNumberOfBlocks(index) != 0)
1130 [ # # ]: 0 : elog(ERROR, "index \"%s\" already contains data",
1131 : : RelationGetRelationName(index));
1132 : :
1133 : : /*
1134 : : * Critical section not required, because on error the creation of the
1135 : : * whole relation will be rolled back.
1136 : : */
1137 : :
1138 : 241 : meta = ExtendBufferedRel(BMR_REL(index), MAIN_FORKNUM, NULL,
1139 : : EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
1140 : : Assert(BufferGetBlockNumber(meta) == BRIN_METAPAGE_BLKNO);
1141 : :
1142 [ + + ]: 241 : brin_metapage_init(BufferGetPage(meta), BrinGetPagesPerRange(index),
1143 : : BRIN_CURRENT_VERSION);
1144 : 241 : MarkBufferDirty(meta);
1145 : :
1146 [ + + + + : 241 : if (RelationNeedsWAL(index))
+ + - + ]
1147 : : {
1148 : : xl_brin_createidx xlrec;
1149 : : XLogRecPtr recptr;
1150 : : Page page;
1151 : :
1152 : 183 : xlrec.version = BRIN_CURRENT_VERSION;
1153 [ + + ]: 183 : xlrec.pagesPerRange = BrinGetPagesPerRange(index);
1154 : :
1155 : 183 : XLogBeginInsert();
1156 : 183 : XLogRegisterData(&xlrec, SizeOfBrinCreateIdx);
1157 : 183 : XLogRegisterBuffer(0, meta, REGBUF_WILL_INIT | REGBUF_STANDARD);
1158 : :
1159 : 183 : recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
1160 : :
1161 : 183 : page = BufferGetPage(meta);
1162 : 183 : PageSetLSN(page, recptr);
1163 : : }
1164 : :
1165 : 241 : UnlockReleaseBuffer(meta);
1166 : :
1167 : : /*
1168 : : * Initialize our state, including the deformed tuple state.
1169 : : */
1170 : 241 : revmap = brinRevmapInitialize(index, &pagesPerRange);
1171 : 241 : state = initialize_brin_buildstate(index, revmap, pagesPerRange,
1172 : : RelationGetNumberOfBlocks(heap));
1173 : :
1174 : : /*
1175 : : * Attempt to launch parallel worker scan when required
1176 : : *
1177 : : * XXX plan_create_index_workers makes the number of workers dependent on
1178 : : * maintenance_work_mem, requiring 32MB for each worker. That makes sense
1179 : : * for btree, but not for BRIN, which can do with much less memory. So
1180 : : * maybe make that somehow less strict, optionally?
1181 : : */
1182 [ + + ]: 241 : if (indexInfo->ii_ParallelWorkers > 0)
1183 : 7 : _brin_begin_parallel(state, heap, index, indexInfo->ii_Concurrent,
1184 : : indexInfo->ii_ParallelWorkers);
1185 : :
1186 : : /*
1187 : : * If parallel build requested and at least one worker process was
1188 : : * successfully launched, set up coordination state, wait for workers to
1189 : : * complete. Then read all tuples from the shared tuplesort and insert
1190 : : * them into the index.
1191 : : *
1192 : : * In serial mode, simply scan the table and build the index one index
1193 : : * tuple at a time.
1194 : : */
1195 [ + + ]: 241 : if (state->bs_leader)
1196 : : {
1197 : : SortCoordinate coordinate;
1198 : :
1199 : 6 : coordinate = palloc0_object(SortCoordinateData);
1200 : 6 : coordinate->isWorker = false;
1201 : 6 : coordinate->nParticipants =
1202 : 6 : state->bs_leader->nparticipanttuplesorts;
1203 : 6 : coordinate->sharedsort = state->bs_leader->sharedsort;
1204 : :
1205 : : /*
1206 : : * Begin leader tuplesort.
1207 : : *
1208 : : * In cases where parallelism is involved, the leader receives the
1209 : : * same share of maintenance_work_mem as a serial sort (it is
1210 : : * generally treated in the same way as a serial sort once we return).
1211 : : * Parallel worker Tuplesortstates will have received only a fraction
1212 : : * of maintenance_work_mem, though.
1213 : : *
1214 : : * We rely on the lifetime of the Leader Tuplesortstate almost not
1215 : : * overlapping with any worker Tuplesortstate's lifetime. There may
1216 : : * be some small overlap, but that's okay because we rely on leader
1217 : : * Tuplesortstate only allocating a small, fixed amount of memory
1218 : : * here. When its tuplesort_performsort() is called (by our caller),
1219 : : * and significant amounts of memory are likely to be used, all
1220 : : * workers must have already freed almost all memory held by their
1221 : : * Tuplesortstates (they are about to go away completely, too). The
1222 : : * overall effect is that maintenance_work_mem always represents an
1223 : : * absolute high watermark on the amount of memory used by a CREATE
1224 : : * INDEX operation, regardless of the use of parallelism or any other
1225 : : * factor.
1226 : : */
1227 : 6 : state->bs_sortstate =
1228 : 6 : tuplesort_begin_index_brin(maintenance_work_mem, coordinate,
1229 : : TUPLESORT_NONE);
1230 : :
1231 : : /* scan the relation and merge per-worker results */
1232 : 6 : reltuples = _brin_parallel_merge(state, indexInfo);
1233 : :
1234 : 6 : _brin_end_parallel(state->bs_leader, state);
1235 : : }
1236 : : else /* no parallel index build */
1237 : : {
1238 : : /*
1239 : : * Now scan the relation. No syncscan allowed here because we want
1240 : : * the heap blocks in physical order (we want to produce the ranges
1241 : : * starting from block 0, and the callback also relies on this to not
1242 : : * generate summary for the same range twice).
1243 : : */
1244 : 235 : reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
1245 : : brinbuildCallback, state, NULL);
1246 : :
1247 : : /*
1248 : : * process the final batch
1249 : : *
1250 : : * XXX Note this does not update state->bs_currRangeStart, i.e. it
1251 : : * stays set to the last range added to the index. This is OK, because
1252 : : * that's what brin_fill_empty_ranges expects.
1253 : : */
1254 : 235 : form_and_insert_tuple(state);
1255 : :
1256 : : /*
1257 : : * Backfill the final ranges with empty data.
1258 : : *
1259 : : * This saves us from doing what amounts to full table scans when the
1260 : : * index with a predicate like WHERE (nonnull_column IS NULL), or
1261 : : * other very selective predicates.
1262 : : */
1263 : 235 : brin_fill_empty_ranges(state,
1264 : : state->bs_currRangeStart,
1265 : : state->bs_maxRangeStart);
1266 : : }
1267 : :
1268 : : /* release resources */
1269 : 241 : idxtuples = state->bs_numtuples;
1270 : 241 : brinRevmapTerminate(state->bs_rmAccess);
1271 : 241 : terminate_brin_buildstate(state);
1272 : :
1273 : : /*
1274 : : * Return statistics
1275 : : */
1276 : 241 : result = palloc_object(IndexBuildResult);
1277 : :
1278 : 241 : result->heap_tuples = reltuples;
1279 : 241 : result->index_tuples = idxtuples;
1280 : :
1281 : 241 : return result;
1282 : : }
1283 : :
1284 : : void
1285 : 4 : brinbuildempty(Relation index)
1286 : : {
1287 : : Buffer metabuf;
1288 : :
1289 : : /* An empty BRIN index has a metapage only. */
1290 : 4 : metabuf = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
1291 : : EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
1292 : :
1293 : : /* Initialize and xlog metabuffer. */
1294 : 4 : START_CRIT_SECTION();
1295 [ - + ]: 4 : brin_metapage_init(BufferGetPage(metabuf), BrinGetPagesPerRange(index),
1296 : : BRIN_CURRENT_VERSION);
1297 : 4 : MarkBufferDirty(metabuf);
1298 : 4 : log_newpage_buffer(metabuf, true);
1299 : 4 : END_CRIT_SECTION();
1300 : :
1301 : 4 : UnlockReleaseBuffer(metabuf);
1302 : 4 : }
1303 : :
1304 : : /*
1305 : : * brinbulkdelete
1306 : : * Since there are no per-heap-tuple index tuples in BRIN indexes,
1307 : : * there's not a lot we can do here.
1308 : : *
1309 : : * XXX we could mark item tuples as "dirty" (when a minimum or maximum heap
1310 : : * tuple is deleted), meaning the need to re-run summarization on the affected
1311 : : * range. Would need to add an extra flag in brintuples for that.
1312 : : */
1313 : : IndexBulkDeleteResult *
1314 : 13 : brinbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
1315 : : IndexBulkDeleteCallback callback, void *callback_state)
1316 : : {
1317 : : /* allocate stats if first time through, else re-use existing struct */
1318 [ + - ]: 13 : if (stats == NULL)
1319 : 13 : stats = palloc0_object(IndexBulkDeleteResult);
1320 : :
1321 : 13 : return stats;
1322 : : }
1323 : :
1324 : : /*
1325 : : * This routine is in charge of "vacuuming" a BRIN index: we just summarize
1326 : : * ranges that are currently unsummarized.
1327 : : */
1328 : : IndexBulkDeleteResult *
1329 : 90 : brinvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
1330 : : {
1331 : : Relation heapRel;
1332 : :
1333 : : /* No-op in ANALYZE ONLY mode */
1334 [ + + ]: 90 : if (info->analyze_only)
1335 : 3 : return stats;
1336 : :
1337 [ + + ]: 87 : if (!stats)
1338 : 78 : stats = palloc0_object(IndexBulkDeleteResult);
1339 : 87 : stats->num_pages = RelationGetNumberOfBlocks(info->index);
1340 : : /* rest of stats is initialized by zeroing */
1341 : :
1342 : 87 : heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
1343 : : AccessShareLock);
1344 : :
1345 : 87 : brin_vacuum_scan(info->index, info->strategy);
1346 : :
1347 : 87 : brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
1348 : : &stats->num_index_tuples, &stats->num_index_tuples);
1349 : :
1350 : 87 : table_close(heapRel, AccessShareLock);
1351 : :
1352 : 87 : return stats;
1353 : : }
1354 : :
1355 : : /*
1356 : : * reloptions processor for BRIN indexes
1357 : : */
1358 : : bytea *
1359 : 834 : brinoptions(Datum reloptions, bool validate)
1360 : : {
1361 : : static const relopt_parse_elt tab[] = {
1362 : : {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
1363 : : {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
1364 : : };
1365 : :
1366 : 834 : return (bytea *) build_reloptions(reloptions, validate,
1367 : : RELOPT_KIND_BRIN,
1368 : : sizeof(BrinOptions),
1369 : : tab, lengthof(tab));
1370 : : }
1371 : :
1372 : : /*
1373 : : * SQL-callable function to scan through an index and summarize all ranges
1374 : : * that are not currently summarized.
1375 : : */
1376 : : Datum
1377 : 47 : brin_summarize_new_values(PG_FUNCTION_ARGS)
1378 : : {
1379 : 47 : Datum relation = PG_GETARG_DATUM(0);
1380 : :
1381 : 47 : return DirectFunctionCall2(brin_summarize_range,
1382 : : relation,
1383 : : Int64GetDatum((int64) BRIN_ALL_BLOCKRANGES));
1384 : : }
1385 : :
1386 : : /*
1387 : : * SQL-callable function to summarize the indicated page range, if not already
1388 : : * summarized. If the second argument is BRIN_ALL_BLOCKRANGES, all
1389 : : * unsummarized ranges are summarized.
1390 : : */
1391 : : Datum
1392 : 134 : brin_summarize_range(PG_FUNCTION_ARGS)
1393 : : {
1394 : 134 : Oid indexoid = PG_GETARG_OID(0);
1395 : 134 : int64 heapBlk64 = PG_GETARG_INT64(1);
1396 : : BlockNumber heapBlk;
1397 : : Oid heapoid;
1398 : : Relation indexRel;
1399 : : Relation heapRel;
1400 : : Oid save_userid;
1401 : : int save_sec_context;
1402 : : int save_nestlevel;
1403 : 134 : double numSummarized = 0;
1404 : :
1405 [ - + ]: 134 : if (RecoveryInProgress())
1406 [ # # ]: 0 : ereport(ERROR,
1407 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1408 : : errmsg("recovery is in progress"),
1409 : : errhint("BRIN control functions cannot be executed during recovery.")));
1410 : :
1411 [ + + + + ]: 134 : if (heapBlk64 > BRIN_ALL_BLOCKRANGES || heapBlk64 < 0)
1412 [ + - ]: 24 : ereport(ERROR,
1413 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1414 : : errmsg("block number out of range: %" PRId64, heapBlk64)));
1415 : 110 : heapBlk = (BlockNumber) heapBlk64;
1416 : :
1417 : : /*
1418 : : * We must lock table before index to avoid deadlocks. However, if the
1419 : : * passed indexoid isn't an index then IndexGetRelation() will fail.
1420 : : * Rather than emitting a not-very-helpful error message, postpone
1421 : : * complaining, expecting that the is-it-an-index test below will fail.
1422 : : */
1423 : 110 : heapoid = IndexGetRelation(indexoid, true);
1424 [ + + ]: 110 : if (OidIsValid(heapoid))
1425 : : {
1426 : 98 : heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
1427 : :
1428 : : /*
1429 : : * Autovacuum calls us. For its benefit, switch to the table owner's
1430 : : * userid, so that any index functions are run as that user. Also
1431 : : * lock down security-restricted operations and arrange to make GUC
1432 : : * variable changes local to this command. This is harmless, albeit
1433 : : * unnecessary, when called from SQL, because we fail shortly if the
1434 : : * user does not own the index.
1435 : : */
1436 : 98 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
1437 : 98 : SetUserIdAndSecContext(heapRel->rd_rel->relowner,
1438 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
1439 : 98 : save_nestlevel = NewGUCNestLevel();
1440 : 98 : RestrictSearchPath();
1441 : : }
1442 : : else
1443 : : {
1444 : 12 : heapRel = NULL;
1445 : : /* Set these just to suppress "uninitialized variable" warnings */
1446 : 12 : save_userid = InvalidOid;
1447 : 12 : save_sec_context = -1;
1448 : 12 : save_nestlevel = -1;
1449 : : }
1450 : :
1451 : 110 : indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
1452 : :
1453 : : /* Must be a BRIN index */
1454 [ + - ]: 98 : if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
1455 [ + + ]: 98 : indexRel->rd_rel->relam != BRIN_AM_OID)
1456 [ + - ]: 12 : ereport(ERROR,
1457 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1458 : : errmsg("\"%s\" is not a BRIN index",
1459 : : RelationGetRelationName(indexRel))));
1460 : :
1461 : : /* User must own the index (comparable to privileges needed for VACUUM) */
1462 [ + - - + ]: 86 : if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid))
1463 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX,
1464 : 0 : RelationGetRelationName(indexRel));
1465 : :
1466 : : /*
1467 : : * Since we did the IndexGetRelation call above without any lock, it's
1468 : : * barely possible that a race against an index drop/recreation could have
1469 : : * netted us the wrong table. Recheck.
1470 : : */
1471 [ + - - + ]: 86 : if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
1472 [ # # ]: 0 : ereport(ERROR,
1473 : : (errcode(ERRCODE_UNDEFINED_TABLE),
1474 : : errmsg("could not open parent table of index \"%s\"",
1475 : : RelationGetRelationName(indexRel))));
1476 : :
1477 : : /* see gin_clean_pending_list() */
1478 [ + - ]: 86 : if (indexRel->rd_index->indisvalid)
1479 : 86 : brinsummarize(indexRel, heapRel, heapBlk, true, &numSummarized, NULL);
1480 : : else
1481 [ # # ]: 0 : ereport(DEBUG1,
1482 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1483 : : errmsg("index \"%s\" is not valid",
1484 : : RelationGetRelationName(indexRel))));
1485 : :
1486 : : /* Roll back any GUC changes executed by index functions */
1487 : 86 : AtEOXact_GUC(false, save_nestlevel);
1488 : :
1489 : : /* Restore userid and security context */
1490 : 86 : SetUserIdAndSecContext(save_userid, save_sec_context);
1491 : :
1492 : 86 : index_close(indexRel, ShareUpdateExclusiveLock);
1493 : 86 : table_close(heapRel, ShareUpdateExclusiveLock);
1494 : :
1495 : 86 : PG_RETURN_INT32((int32) numSummarized);
1496 : : }
1497 : :
1498 : : /*
1499 : : * SQL-callable interface to mark a range as no longer summarized
1500 : : */
1501 : : Datum
1502 : 69 : brin_desummarize_range(PG_FUNCTION_ARGS)
1503 : : {
1504 : 69 : Oid indexoid = PG_GETARG_OID(0);
1505 : 69 : int64 heapBlk64 = PG_GETARG_INT64(1);
1506 : : BlockNumber heapBlk;
1507 : : Oid heapoid;
1508 : : Relation heapRel;
1509 : : Relation indexRel;
1510 : : bool done;
1511 : :
1512 [ - + ]: 69 : if (RecoveryInProgress())
1513 [ # # ]: 0 : ereport(ERROR,
1514 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1515 : : errmsg("recovery is in progress"),
1516 : : errhint("BRIN control functions cannot be executed during recovery.")));
1517 : :
1518 [ + - + + ]: 69 : if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0)
1519 [ + - ]: 12 : ereport(ERROR,
1520 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1521 : : errmsg("block number out of range: %" PRId64,
1522 : : heapBlk64)));
1523 : 57 : heapBlk = (BlockNumber) heapBlk64;
1524 : :
1525 : : /*
1526 : : * We must lock table before index to avoid deadlocks. However, if the
1527 : : * passed indexoid isn't an index then IndexGetRelation() will fail.
1528 : : * Rather than emitting a not-very-helpful error message, postpone
1529 : : * complaining, expecting that the is-it-an-index test below will fail.
1530 : : *
1531 : : * Unlike brin_summarize_range(), autovacuum never calls this. Hence, we
1532 : : * don't switch userid.
1533 : : */
1534 : 57 : heapoid = IndexGetRelation(indexoid, true);
1535 [ + - ]: 57 : if (OidIsValid(heapoid))
1536 : 57 : heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
1537 : : else
1538 : 0 : heapRel = NULL;
1539 : :
1540 : 57 : indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
1541 : :
1542 : : /* Must be a BRIN index */
1543 [ + - ]: 57 : if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
1544 [ - + ]: 57 : indexRel->rd_rel->relam != BRIN_AM_OID)
1545 [ # # ]: 0 : ereport(ERROR,
1546 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1547 : : errmsg("\"%s\" is not a BRIN index",
1548 : : RelationGetRelationName(indexRel))));
1549 : :
1550 : : /* User must own the index (comparable to privileges needed for VACUUM) */
1551 [ - + ]: 57 : if (!object_ownercheck(RelationRelationId, indexoid, GetUserId()))
1552 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_INDEX,
1553 : 0 : RelationGetRelationName(indexRel));
1554 : :
1555 : : /*
1556 : : * Since we did the IndexGetRelation call above without any lock, it's
1557 : : * barely possible that a race against an index drop/recreation could have
1558 : : * netted us the wrong table. Recheck.
1559 : : */
1560 [ + - - + ]: 57 : if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
1561 [ # # ]: 0 : ereport(ERROR,
1562 : : (errcode(ERRCODE_UNDEFINED_TABLE),
1563 : : errmsg("could not open parent table of index \"%s\"",
1564 : : RelationGetRelationName(indexRel))));
1565 : :
1566 : : /* see gin_clean_pending_list() */
1567 [ + - ]: 57 : if (indexRel->rd_index->indisvalid)
1568 : : {
1569 : : /* the revmap does the hard work */
1570 : : do
1571 : : {
1572 : 57 : done = brinRevmapDesummarizeRange(indexRel, heapBlk);
1573 : : }
1574 [ - + ]: 57 : while (!done);
1575 : : }
1576 : : else
1577 [ # # ]: 0 : ereport(DEBUG1,
1578 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1579 : : errmsg("index \"%s\" is not valid",
1580 : : RelationGetRelationName(indexRel))));
1581 : :
1582 : 57 : index_close(indexRel, ShareUpdateExclusiveLock);
1583 : 57 : table_close(heapRel, ShareUpdateExclusiveLock);
1584 : :
1585 : 57 : PG_RETURN_VOID();
1586 : : }
1587 : :
1588 : : /*
1589 : : * Build a BrinDesc used to create or scan a BRIN index
1590 : : */
1591 : : BrinDesc *
1592 : 3020 : brin_build_desc(Relation rel)
1593 : : {
1594 : : BrinOpcInfo **opcinfo;
1595 : : BrinDesc *bdesc;
1596 : : TupleDesc tupdesc;
1597 : 3020 : int totalstored = 0;
1598 : : int keyno;
1599 : : long totalsize;
1600 : : MemoryContext cxt;
1601 : : MemoryContext oldcxt;
1602 : :
1603 : 3020 : cxt = AllocSetContextCreate(CurrentMemoryContext,
1604 : : "brin desc cxt",
1605 : : ALLOCSET_SMALL_SIZES);
1606 : 3020 : oldcxt = MemoryContextSwitchTo(cxt);
1607 : 3020 : tupdesc = RelationGetDescr(rel);
1608 : :
1609 : : /*
1610 : : * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1611 : : * the number of columns stored, since the number is opclass-defined.
1612 : : */
1613 : 3020 : opcinfo = palloc_array(BrinOpcInfo *, tupdesc->natts);
1614 [ + + ]: 50722 : for (keyno = 0; keyno < tupdesc->natts; keyno++)
1615 : : {
1616 : : FmgrInfo *opcInfoFn;
1617 : 47702 : Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1618 : :
1619 : 47702 : opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
1620 : :
1621 : 95404 : opcinfo[keyno] = (BrinOpcInfo *)
1622 : 47702 : DatumGetPointer(FunctionCall1(opcInfoFn, ObjectIdGetDatum(attr->atttypid)));
1623 : 47702 : totalstored += opcinfo[keyno]->oi_nstored;
1624 : : }
1625 : :
1626 : : /* Allocate our result struct and fill it in */
1627 : 3020 : totalsize = offsetof(BrinDesc, bd_info) +
1628 : 3020 : sizeof(BrinOpcInfo *) * tupdesc->natts;
1629 : :
1630 : 3020 : bdesc = palloc(totalsize);
1631 : 3020 : bdesc->bd_context = cxt;
1632 : 3020 : bdesc->bd_index = rel;
1633 : 3020 : bdesc->bd_tupdesc = tupdesc;
1634 : 3020 : bdesc->bd_disktdesc = NULL; /* generated lazily */
1635 : 3020 : bdesc->bd_totalstored = totalstored;
1636 : :
1637 [ + + ]: 50722 : for (keyno = 0; keyno < tupdesc->natts; keyno++)
1638 : 47702 : bdesc->bd_info[keyno] = opcinfo[keyno];
1639 : 3020 : pfree(opcinfo);
1640 : :
1641 : 3020 : MemoryContextSwitchTo(oldcxt);
1642 : :
1643 : 3020 : return bdesc;
1644 : : }
1645 : :
1646 : : void
1647 : 2285 : brin_free_desc(BrinDesc *bdesc)
1648 : : {
1649 : : /* make sure the tupdesc is still valid */
1650 : : Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1651 : : /* no need for retail pfree */
1652 : 2285 : MemoryContextDelete(bdesc->bd_context);
1653 : 2285 : }
1654 : :
1655 : : /*
1656 : : * Fetch index's statistical data into *stats
1657 : : */
1658 : : void
1659 : 8944 : brinGetStats(Relation index, BrinStatsData *stats)
1660 : : {
1661 : : Buffer metabuffer;
1662 : : Page metapage;
1663 : : BrinMetaPageData *metadata;
1664 : :
1665 : 8944 : metabuffer = ReadBuffer(index, BRIN_METAPAGE_BLKNO);
1666 : 8944 : LockBuffer(metabuffer, BUFFER_LOCK_SHARE);
1667 : 8944 : metapage = BufferGetPage(metabuffer);
1668 : 8944 : metadata = (BrinMetaPageData *) PageGetContents(metapage);
1669 : :
1670 : 8944 : stats->pagesPerRange = metadata->pagesPerRange;
1671 : 8944 : stats->revmapNumPages = metadata->lastRevmapPage - 1;
1672 : :
1673 : 8944 : UnlockReleaseBuffer(metabuffer);
1674 : 8944 : }
1675 : :
1676 : : /*
1677 : : * Initialize a BrinBuildState appropriate to create tuples on the given index.
1678 : : */
1679 : : static BrinBuildState *
1680 : 307 : initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap,
1681 : : BlockNumber pagesPerRange, BlockNumber tablePages)
1682 : : {
1683 : : BrinBuildState *state;
1684 : 307 : BlockNumber lastRange = 0;
1685 : :
1686 : 307 : state = palloc_object(BrinBuildState);
1687 : :
1688 : 307 : state->bs_irel = idxRel;
1689 : 307 : state->bs_numtuples = 0;
1690 : 307 : state->bs_reltuples = 0;
1691 : 307 : state->bs_currentInsertBuf = InvalidBuffer;
1692 : 307 : state->bs_pagesPerRange = pagesPerRange;
1693 : 307 : state->bs_currRangeStart = 0;
1694 : 307 : state->bs_rmAccess = revmap;
1695 : 307 : state->bs_bdesc = brin_build_desc(idxRel);
1696 : 307 : state->bs_dtuple = brin_new_memtuple(state->bs_bdesc);
1697 : 307 : state->bs_leader = NULL;
1698 : 307 : state->bs_worker_id = 0;
1699 : 307 : state->bs_sortstate = NULL;
1700 : :
1701 : : /* Remember the memory context to use for an empty tuple, if needed. */
1702 : 307 : state->bs_context = CurrentMemoryContext;
1703 : 307 : state->bs_emptyTuple = NULL;
1704 : 307 : state->bs_emptyTupleLen = 0;
1705 : :
1706 : : /*
1707 : : * Calculate the start of the last page range. Page numbers are 0-based,
1708 : : * so to calculate the index we need to subtract one. The integer division
1709 : : * gives us the index of the page range.
1710 : : */
1711 [ + + ]: 307 : if (tablePages > 0)
1712 : 230 : lastRange = ((tablePages - 1) / pagesPerRange) * pagesPerRange;
1713 : :
1714 : : /* Now calculate the start of the next range. */
1715 : 307 : state->bs_maxRangeStart = lastRange + state->bs_pagesPerRange;
1716 : :
1717 : 307 : return state;
1718 : : }
1719 : :
1720 : : /*
1721 : : * Release resources associated with a BrinBuildState.
1722 : : */
1723 : : static void
1724 : 299 : terminate_brin_buildstate(BrinBuildState *state)
1725 : : {
1726 : : /*
1727 : : * Release the last index buffer used. We might as well ensure that
1728 : : * whatever free space remains in that page is available in FSM, too.
1729 : : */
1730 [ + + ]: 299 : if (!BufferIsInvalid(state->bs_currentInsertBuf))
1731 : : {
1732 : : Page page;
1733 : : Size freespace;
1734 : : BlockNumber blk;
1735 : :
1736 : 241 : page = BufferGetPage(state->bs_currentInsertBuf);
1737 : 241 : freespace = PageGetFreeSpace(page);
1738 : 241 : blk = BufferGetBlockNumber(state->bs_currentInsertBuf);
1739 : 241 : ReleaseBuffer(state->bs_currentInsertBuf);
1740 : 241 : RecordPageWithFreeSpace(state->bs_irel, blk, freespace);
1741 : 241 : FreeSpaceMapVacuumRange(state->bs_irel, blk, blk + 1);
1742 : : }
1743 : :
1744 : 299 : brin_free_desc(state->bs_bdesc);
1745 : 299 : pfree(state->bs_dtuple);
1746 : 299 : pfree(state);
1747 : 299 : }
1748 : :
1749 : : /*
1750 : : * On the given BRIN index, summarize the heap page range that corresponds
1751 : : * to the heap block number given.
1752 : : *
1753 : : * This routine can run in parallel with insertions into the heap. To avoid
1754 : : * missing those values from the summary tuple, we first insert a placeholder
1755 : : * index tuple into the index, then execute the heap scan; transactions
1756 : : * concurrent with the scan update the placeholder tuple. After the scan, we
1757 : : * union the placeholder tuple with the one computed by this routine. The
1758 : : * update of the index value happens in a loop, so that if somebody updates
1759 : : * the placeholder tuple after we read it, we detect the case and try again.
1760 : : * This ensures that the concurrently inserted tuples are not lost.
1761 : : *
1762 : : * A further corner case is this routine being asked to summarize the partial
1763 : : * range at the end of the table. heapNumBlocks is the (possibly outdated)
1764 : : * table size; if we notice that the requested range lies beyond that size,
1765 : : * we re-compute the table size after inserting the placeholder tuple, to
1766 : : * avoid missing pages that were appended recently.
1767 : : */
1768 : : static void
1769 : 1498 : summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel,
1770 : : BlockNumber heapBlk, BlockNumber heapNumBlks)
1771 : : {
1772 : : Buffer phbuf;
1773 : : BrinTuple *phtup;
1774 : : Size phsz;
1775 : : OffsetNumber offset;
1776 : : BlockNumber scanNumBlks;
1777 : :
1778 : : /*
1779 : : * Insert the placeholder tuple
1780 : : */
1781 : 1498 : phbuf = InvalidBuffer;
1782 : 1498 : phtup = brin_form_placeholder_tuple(state->bs_bdesc, heapBlk, &phsz);
1783 : 1498 : offset = brin_doinsert(state->bs_irel, state->bs_pagesPerRange,
1784 : : state->bs_rmAccess, &phbuf,
1785 : : heapBlk, phtup, phsz);
1786 : :
1787 : : /*
1788 : : * Compute range end. We hold ShareUpdateExclusive lock on table, so it
1789 : : * cannot shrink concurrently (but it can grow).
1790 : : */
1791 : : Assert(heapBlk % state->bs_pagesPerRange == 0);
1792 [ + + ]: 1498 : if (heapBlk + state->bs_pagesPerRange > heapNumBlks)
1793 : : {
1794 : : /*
1795 : : * If we're asked to scan what we believe to be the final range on the
1796 : : * table (i.e. a range that might be partial) we need to recompute our
1797 : : * idea of what the latest page is after inserting the placeholder
1798 : : * tuple. Anyone that grows the table later will update the
1799 : : * placeholder tuple, so it doesn't matter that we won't scan these
1800 : : * pages ourselves. Careful: the table might have been extended
1801 : : * beyond the current range, so clamp our result.
1802 : : *
1803 : : * Fortunately, this should occur infrequently.
1804 : : */
1805 [ + - ]: 16 : scanNumBlks = Min(RelationGetNumberOfBlocks(heapRel) - heapBlk,
1806 : : state->bs_pagesPerRange);
1807 : : }
1808 : : else
1809 : : {
1810 : : /* Easy case: range is known to be complete */
1811 : 1482 : scanNumBlks = state->bs_pagesPerRange;
1812 : : }
1813 : :
1814 : : /*
1815 : : * Execute the partial heap scan covering the heap blocks in the specified
1816 : : * page range, summarizing the heap tuples in it. This scan stops just
1817 : : * short of brinbuildCallback creating the new index entry.
1818 : : *
1819 : : * Note that it is critical we use the "any visible" mode of
1820 : : * table_index_build_range_scan here: otherwise, we would miss tuples
1821 : : * inserted by transactions that are still in progress, among other corner
1822 : : * cases.
1823 : : */
1824 : 1498 : state->bs_currRangeStart = heapBlk;
1825 : 1498 : table_index_build_range_scan(heapRel, state->bs_irel, indexInfo, false, true, false,
1826 : : heapBlk, scanNumBlks,
1827 : : brinbuildCallback, state, NULL);
1828 : :
1829 : : /*
1830 : : * Now we update the values obtained by the scan with the placeholder
1831 : : * tuple. We do this in a loop which only terminates if we're able to
1832 : : * update the placeholder tuple successfully; if we are not, this means
1833 : : * somebody else modified the placeholder tuple after we read it.
1834 : : */
1835 : : for (;;)
1836 : 0 : {
1837 : : BrinTuple *newtup;
1838 : : Size newsize;
1839 : : bool didupdate;
1840 : : bool samepage;
1841 : :
1842 [ - + ]: 1498 : CHECK_FOR_INTERRUPTS();
1843 : :
1844 : : /*
1845 : : * Update the summary tuple and try to update.
1846 : : */
1847 : 1498 : newtup = brin_form_tuple(state->bs_bdesc,
1848 : : heapBlk, state->bs_dtuple, &newsize);
1849 : 1498 : samepage = brin_can_do_samepage_update(phbuf, phsz, newsize);
1850 : : didupdate =
1851 : 1498 : brin_doupdate(state->bs_irel, state->bs_pagesPerRange,
1852 : : state->bs_rmAccess, heapBlk, phbuf, offset,
1853 : : phtup, phsz, newtup, newsize, samepage);
1854 : 1498 : brin_free_tuple(phtup);
1855 : 1498 : brin_free_tuple(newtup);
1856 : :
1857 : : /* If the update succeeded, we're done. */
1858 [ + - ]: 1498 : if (didupdate)
1859 : 1498 : break;
1860 : :
1861 : : /*
1862 : : * If the update didn't work, it might be because somebody updated the
1863 : : * placeholder tuple concurrently. Extract the new version, union it
1864 : : * with the values we have from the scan, and start over. (There are
1865 : : * other reasons for the update to fail, but it's simple to treat them
1866 : : * the same.)
1867 : : */
1868 : 0 : phtup = brinGetTupleForHeapBlock(state->bs_rmAccess, heapBlk, &phbuf,
1869 : : &offset, &phsz, BUFFER_LOCK_SHARE);
1870 : : /* the placeholder tuple must exist */
1871 [ # # ]: 0 : if (phtup == NULL)
1872 [ # # ]: 0 : elog(ERROR, "missing placeholder tuple");
1873 : 0 : phtup = brin_copy_tuple(phtup, phsz, NULL, NULL);
1874 : 0 : LockBuffer(phbuf, BUFFER_LOCK_UNLOCK);
1875 : :
1876 : : /* merge it into the tuple from the heap scan */
1877 : 0 : union_tuples(state->bs_bdesc, state->bs_dtuple, phtup);
1878 : : }
1879 : :
1880 : 1498 : ReleaseBuffer(phbuf);
1881 : 1498 : }
1882 : :
1883 : : /*
1884 : : * Summarize page ranges that are not already summarized. If pageRange is
1885 : : * BRIN_ALL_BLOCKRANGES then the whole table is scanned; otherwise, only the
1886 : : * page range containing the given heap page number is scanned.
1887 : : * If include_partial is true, then the partial range at the end of the table
1888 : : * is summarized, otherwise not.
1889 : : *
1890 : : * For each new index tuple inserted, *numSummarized (if not NULL) is
1891 : : * incremented; for each existing tuple, *numExisting (if not NULL) is
1892 : : * incremented.
1893 : : */
1894 : : static void
1895 : 173 : brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange,
1896 : : bool include_partial, double *numSummarized, double *numExisting)
1897 : : {
1898 : : BrinRevmap *revmap;
1899 : 173 : BrinBuildState *state = NULL;
1900 : 173 : IndexInfo *indexInfo = NULL;
1901 : : BlockNumber heapNumBlocks;
1902 : : BlockNumber pagesPerRange;
1903 : : Buffer buf;
1904 : : BlockNumber startBlk;
1905 : :
1906 : 173 : revmap = brinRevmapInitialize(index, &pagesPerRange);
1907 : :
1908 : : /* determine range of pages to process */
1909 : 173 : heapNumBlocks = RelationGetNumberOfBlocks(heapRel);
1910 [ + + ]: 173 : if (pageRange == BRIN_ALL_BLOCKRANGES)
1911 : 122 : startBlk = 0;
1912 : : else
1913 : : {
1914 : 51 : startBlk = (pageRange / pagesPerRange) * pagesPerRange;
1915 : 51 : heapNumBlocks = Min(heapNumBlocks, startBlk + pagesPerRange);
1916 : : }
1917 [ - + ]: 173 : if (startBlk > heapNumBlocks)
1918 : : {
1919 : : /* Nothing to do if start point is beyond end of table */
1920 : 0 : brinRevmapTerminate(revmap);
1921 : 0 : return;
1922 : : }
1923 : :
1924 : : /*
1925 : : * Scan the revmap to find unsummarized items.
1926 : : */
1927 : 173 : buf = InvalidBuffer;
1928 [ + + ]: 10944 : for (; startBlk < heapNumBlocks; startBlk += pagesPerRange)
1929 : : {
1930 : : BrinTuple *tup;
1931 : : OffsetNumber off;
1932 : :
1933 : : /*
1934 : : * Unless requested to summarize even a partial range, go away now if
1935 : : * we think the next range is partial. Caller would pass true when it
1936 : : * is typically run once bulk data loading is done
1937 : : * (brin_summarize_new_values), and false when it is typically the
1938 : : * result of arbitrarily-scheduled maintenance command (vacuuming).
1939 : : */
1940 [ + + ]: 10837 : if (!include_partial &&
1941 [ + + ]: 2248 : (startBlk + pagesPerRange > heapNumBlocks))
1942 : 66 : break;
1943 : :
1944 [ - + ]: 10771 : CHECK_FOR_INTERRUPTS();
1945 : :
1946 : 10771 : tup = brinGetTupleForHeapBlock(revmap, startBlk, &buf, &off, NULL,
1947 : : BUFFER_LOCK_SHARE);
1948 [ + + ]: 10771 : if (tup == NULL)
1949 : : {
1950 : : /* no revmap entry for this heap range. Summarize it. */
1951 [ + + ]: 1498 : if (state == NULL)
1952 : : {
1953 : : /* first time through */
1954 : : Assert(!indexInfo);
1955 : 58 : state = initialize_brin_buildstate(index, revmap,
1956 : : pagesPerRange,
1957 : : InvalidBlockNumber);
1958 : 58 : indexInfo = BuildIndexInfo(index);
1959 : : }
1960 : 1498 : summarize_range(indexInfo, state, heapRel, startBlk, heapNumBlocks);
1961 : :
1962 : : /* and re-initialize state for the next range */
1963 : 1498 : brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
1964 : :
1965 [ + - ]: 1498 : if (numSummarized)
1966 : 1498 : *numSummarized += 1.0;
1967 : : }
1968 : : else
1969 : : {
1970 [ + + ]: 9273 : if (numExisting)
1971 : 2113 : *numExisting += 1.0;
1972 : 9273 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
1973 : : }
1974 : : }
1975 : :
1976 [ + + ]: 173 : if (BufferIsValid(buf))
1977 : 128 : ReleaseBuffer(buf);
1978 : :
1979 : : /* free resources */
1980 : 173 : brinRevmapTerminate(revmap);
1981 [ + + ]: 173 : if (state)
1982 : : {
1983 : 58 : terminate_brin_buildstate(state);
1984 : 58 : pfree(indexInfo);
1985 : : }
1986 : : }
1987 : :
1988 : : /*
1989 : : * Given a deformed tuple in the build state, convert it into the on-disk
1990 : : * format and insert it into the index, making the revmap point to it.
1991 : : */
1992 : : static void
1993 : 1754 : form_and_insert_tuple(BrinBuildState *state)
1994 : : {
1995 : : BrinTuple *tup;
1996 : : Size size;
1997 : :
1998 : 1754 : tup = brin_form_tuple(state->bs_bdesc, state->bs_currRangeStart,
1999 : : state->bs_dtuple, &size);
2000 : 1754 : brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
2001 : : &state->bs_currentInsertBuf, state->bs_currRangeStart,
2002 : : tup, size);
2003 : 1754 : state->bs_numtuples++;
2004 : :
2005 : 1754 : pfree(tup);
2006 : 1754 : }
2007 : :
2008 : : /*
2009 : : * Given a deformed tuple in the build state, convert it into the on-disk
2010 : : * format and write it to a (shared) tuplesort (the leader will insert it
2011 : : * into the index later).
2012 : : */
2013 : : static void
2014 : 33 : form_and_spill_tuple(BrinBuildState *state)
2015 : : {
2016 : : BrinTuple *tup;
2017 : : Size size;
2018 : :
2019 : : /* don't insert empty tuples in parallel build */
2020 [ + + ]: 33 : if (state->bs_dtuple->bt_empty_range)
2021 : 12 : return;
2022 : :
2023 : 21 : tup = brin_form_tuple(state->bs_bdesc, state->bs_currRangeStart,
2024 : : state->bs_dtuple, &size);
2025 : :
2026 : : /* write the BRIN tuple to the tuplesort */
2027 : 21 : tuplesort_putbrintuple(state->bs_sortstate, tup, size);
2028 : :
2029 : 21 : state->bs_numtuples++;
2030 : :
2031 : 21 : pfree(tup);
2032 : : }
2033 : :
2034 : : /*
2035 : : * Given two deformed tuples, adjust the first one so that it's consistent
2036 : : * with the summary values in both.
2037 : : */
2038 : : static void
2039 : 0 : union_tuples(BrinDesc *bdesc, BrinMemTuple *a, BrinTuple *b)
2040 : : {
2041 : : int keyno;
2042 : : BrinMemTuple *db;
2043 : : MemoryContext cxt;
2044 : : MemoryContext oldcxt;
2045 : :
2046 : : /* Use our own memory context to avoid retail pfree */
2047 : 0 : cxt = AllocSetContextCreate(CurrentMemoryContext,
2048 : : "brin union",
2049 : : ALLOCSET_DEFAULT_SIZES);
2050 : 0 : oldcxt = MemoryContextSwitchTo(cxt);
2051 : 0 : db = brin_deform_tuple(bdesc, b, NULL);
2052 : 0 : MemoryContextSwitchTo(oldcxt);
2053 : :
2054 : : /*
2055 : : * Check if the ranges are empty.
2056 : : *
2057 : : * If at least one of them is empty, we don't need to call per-key union
2058 : : * functions at all. If "b" is empty, we just use "a" as the result (it
2059 : : * might be empty fine, but that's fine). If "a" is empty but "b" is not,
2060 : : * we use "b" as the result (but we have to copy the data into "a" first).
2061 : : *
2062 : : * Only when both ranges are non-empty, we actually do the per-key merge.
2063 : : */
2064 : :
2065 : : /* If "b" is empty - ignore it and just use "a" (even if it's empty etc.). */
2066 [ # # ]: 0 : if (db->bt_empty_range)
2067 : : {
2068 : : /* skip the per-key merge */
2069 : 0 : MemoryContextDelete(cxt);
2070 : 0 : return;
2071 : : }
2072 : :
2073 : : /*
2074 : : * Now we know "b" is not empty. If "a" is empty, then "b" is the result.
2075 : : * But we need to copy the data from "b" to "a" first, because that's how
2076 : : * we pass result out.
2077 : : *
2078 : : * We have to copy all the global/per-key flags etc. too.
2079 : : */
2080 [ # # ]: 0 : if (a->bt_empty_range)
2081 : : {
2082 [ # # ]: 0 : for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
2083 : : {
2084 : : int i;
2085 : 0 : BrinValues *col_a = &a->bt_columns[keyno];
2086 : 0 : BrinValues *col_b = &db->bt_columns[keyno];
2087 : 0 : BrinOpcInfo *opcinfo = bdesc->bd_info[keyno];
2088 : :
2089 : 0 : col_a->bv_allnulls = col_b->bv_allnulls;
2090 : 0 : col_a->bv_hasnulls = col_b->bv_hasnulls;
2091 : :
2092 : : /* If "b" has no data, we're done. */
2093 [ # # ]: 0 : if (col_b->bv_allnulls)
2094 : 0 : continue;
2095 : :
2096 [ # # ]: 0 : for (i = 0; i < opcinfo->oi_nstored; i++)
2097 : 0 : col_a->bv_values[i] =
2098 : 0 : datumCopy(col_b->bv_values[i],
2099 : 0 : opcinfo->oi_typcache[i]->typbyval,
2100 : 0 : opcinfo->oi_typcache[i]->typlen);
2101 : : }
2102 : :
2103 : : /* "a" started empty, but "b" was not empty, so remember that */
2104 : 0 : a->bt_empty_range = false;
2105 : :
2106 : : /* skip the per-key merge */
2107 : 0 : MemoryContextDelete(cxt);
2108 : 0 : return;
2109 : : }
2110 : :
2111 : : /* Now we know neither range is empty. */
2112 [ # # ]: 0 : for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
2113 : : {
2114 : : FmgrInfo *unionFn;
2115 : 0 : BrinValues *col_a = &a->bt_columns[keyno];
2116 : 0 : BrinValues *col_b = &db->bt_columns[keyno];
2117 : 0 : BrinOpcInfo *opcinfo = bdesc->bd_info[keyno];
2118 : :
2119 [ # # ]: 0 : if (opcinfo->oi_regular_nulls)
2120 : : {
2121 : : /* Does the "b" summary represent any NULL values? */
2122 [ # # # # ]: 0 : bool b_has_nulls = (col_b->bv_hasnulls || col_b->bv_allnulls);
2123 : :
2124 : : /* Adjust "hasnulls". */
2125 [ # # # # ]: 0 : if (!col_a->bv_allnulls && b_has_nulls)
2126 : 0 : col_a->bv_hasnulls = true;
2127 : :
2128 : : /* If there are no values in B, there's nothing left to do. */
2129 [ # # ]: 0 : if (col_b->bv_allnulls)
2130 : 0 : continue;
2131 : :
2132 : : /*
2133 : : * Adjust "allnulls". If A doesn't have values, just copy the
2134 : : * values from B into A, and we're done. We cannot run the
2135 : : * operators in this case, because values in A might contain
2136 : : * garbage. Note we already established that B contains values.
2137 : : *
2138 : : * Also adjust "hasnulls" in order not to forget the summary
2139 : : * represents NULL values. This is not redundant with the earlier
2140 : : * update, because that only happens when allnulls=false.
2141 : : */
2142 [ # # ]: 0 : if (col_a->bv_allnulls)
2143 : 0 : {
2144 : : int i;
2145 : :
2146 : 0 : col_a->bv_allnulls = false;
2147 : 0 : col_a->bv_hasnulls = true;
2148 : :
2149 [ # # ]: 0 : for (i = 0; i < opcinfo->oi_nstored; i++)
2150 : 0 : col_a->bv_values[i] =
2151 : 0 : datumCopy(col_b->bv_values[i],
2152 : 0 : opcinfo->oi_typcache[i]->typbyval,
2153 : 0 : opcinfo->oi_typcache[i]->typlen);
2154 : :
2155 : 0 : continue;
2156 : : }
2157 : : }
2158 : :
2159 : 0 : unionFn = index_getprocinfo(bdesc->bd_index, keyno + 1,
2160 : : BRIN_PROCNUM_UNION);
2161 : 0 : FunctionCall3Coll(unionFn,
2162 : 0 : bdesc->bd_index->rd_indcollation[keyno],
2163 : : PointerGetDatum(bdesc),
2164 : : PointerGetDatum(col_a),
2165 : : PointerGetDatum(col_b));
2166 : : }
2167 : :
2168 : 0 : MemoryContextDelete(cxt);
2169 : : }
2170 : :
2171 : : /*
2172 : : * brin_vacuum_scan
2173 : : * Do a complete scan of the index during VACUUM.
2174 : : *
2175 : : * This routine scans the complete index looking for uncataloged index pages,
2176 : : * i.e. those that might have been lost due to a crash after index extension
2177 : : * and such.
2178 : : */
2179 : : static void
2180 : 87 : brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
2181 : : {
2182 : : BlockRangeReadStreamPrivate p;
2183 : : ReadStream *stream;
2184 : : Buffer buf;
2185 : :
2186 : 87 : p.current_blocknum = 0;
2187 : 87 : p.last_exclusive = RelationGetNumberOfBlocks(idxrel);
2188 : :
2189 : : /*
2190 : : * It is safe to use batchmode as block_range_read_stream_cb takes no
2191 : : * locks.
2192 : : */
2193 : 87 : stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE |
2194 : : READ_STREAM_FULL |
2195 : : READ_STREAM_USE_BATCHING,
2196 : : strategy,
2197 : : idxrel,
2198 : : MAIN_FORKNUM,
2199 : : block_range_read_stream_cb,
2200 : : &p,
2201 : : 0);
2202 : :
2203 : : /*
2204 : : * Scan the index in physical order, and clean up any possible mess in
2205 : : * each page.
2206 : : */
2207 [ + + ]: 468 : while ((buf = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
2208 : : {
2209 [ - + ]: 381 : CHECK_FOR_INTERRUPTS();
2210 : :
2211 : 381 : brin_page_cleanup(idxrel, buf);
2212 : :
2213 : 381 : ReleaseBuffer(buf);
2214 : : }
2215 : :
2216 : 87 : read_stream_end(stream);
2217 : :
2218 : : /*
2219 : : * Update all upper pages in the index's FSM, as well. This ensures not
2220 : : * only that we propagate leaf-page FSM updates made by brin_page_cleanup,
2221 : : * but also that any pre-existing damage or out-of-dateness is repaired.
2222 : : */
2223 : 87 : FreeSpaceMapVacuum(idxrel);
2224 : 87 : }
2225 : :
2226 : : static bool
2227 : 571259 : add_values_to_range(Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup,
2228 : : const Datum *values, const bool *nulls)
2229 : : {
2230 : : int keyno;
2231 : :
2232 : : /* If the range starts empty, we're certainly going to modify it. */
2233 : 571259 : bool modified = dtup->bt_empty_range;
2234 : :
2235 : : /*
2236 : : * Compare the key values of the new tuple to the stored index values; our
2237 : : * deformed tuple will get updated if the new tuple doesn't fit the
2238 : : * original range (note this means we can't break out of the loop early).
2239 : : * Make a note of whether this happens, so that we know to insert the
2240 : : * modified tuple later.
2241 : : */
2242 [ + + ]: 1307499 : for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
2243 : : {
2244 : : Datum result;
2245 : : BrinValues *bval;
2246 : : FmgrInfo *addValue;
2247 : : bool has_nulls;
2248 : :
2249 : 736240 : bval = &dtup->bt_columns[keyno];
2250 : :
2251 : : /*
2252 : : * Does the range have actual NULL values? Either of the flags can be
2253 : : * set, but we ignore the state before adding first row.
2254 : : *
2255 : : * We have to remember this, because we'll modify the flags and we
2256 : : * need to know if the range started as empty.
2257 : : */
2258 [ + + ]: 1448467 : has_nulls = ((!dtup->bt_empty_range) &&
2259 [ + + + + ]: 712227 : (bval->bv_hasnulls || bval->bv_allnulls));
2260 : :
2261 : : /*
2262 : : * If the value we're adding is NULL, handle it locally. Otherwise
2263 : : * call the BRIN_PROCNUM_ADDVALUE procedure.
2264 : : */
2265 [ + - + + ]: 736240 : if (bdesc->bd_info[keyno]->oi_regular_nulls && nulls[keyno])
2266 : : {
2267 : : /*
2268 : : * If the new value is null, we record that we saw it if it's the
2269 : : * first one; otherwise, there's nothing to do.
2270 : : */
2271 [ + + ]: 11779 : if (!bval->bv_hasnulls)
2272 : : {
2273 : 2418 : bval->bv_hasnulls = true;
2274 : 2418 : modified = true;
2275 : : }
2276 : :
2277 : 11779 : continue;
2278 : : }
2279 : :
2280 : 724461 : addValue = index_getprocinfo(idxRel, keyno + 1,
2281 : : BRIN_PROCNUM_ADDVALUE);
2282 : 1448922 : result = FunctionCall4Coll(addValue,
2283 : 724461 : idxRel->rd_indcollation[keyno],
2284 : : PointerGetDatum(bdesc),
2285 : : PointerGetDatum(bval),
2286 : 724461 : values[keyno],
2287 : 724461 : BoolGetDatum(nulls[keyno]));
2288 : : /* if that returned true, we need to insert the updated tuple */
2289 : 724461 : modified |= DatumGetBool(result);
2290 : :
2291 : : /*
2292 : : * If the range was had actual NULL values (i.e. did not start empty),
2293 : : * make sure we don't forget about the NULL values. Either the
2294 : : * allnulls flag is still set to true, or (if the opclass cleared it)
2295 : : * we need to set hasnulls=true.
2296 : : *
2297 : : * XXX This can only happen when the opclass modified the tuple, so
2298 : : * the modified flag should be set.
2299 : : */
2300 [ + + + + : 724461 : if (has_nulls && !(bval->bv_hasnulls || bval->bv_allnulls))
+ - ]
2301 : : {
2302 : : Assert(modified);
2303 : 2 : bval->bv_hasnulls = true;
2304 : : }
2305 : : }
2306 : :
2307 : : /*
2308 : : * After updating summaries for all the keys, mark it as not empty.
2309 : : *
2310 : : * If we're actually changing the flag value (i.e. tuple started as
2311 : : * empty), we should have modified the tuple. So we should not see empty
2312 : : * range that was not modified.
2313 : : */
2314 : : Assert(!dtup->bt_empty_range || modified);
2315 : 571259 : dtup->bt_empty_range = false;
2316 : :
2317 : 571259 : return modified;
2318 : : }
2319 : :
2320 : : static bool
2321 : 126624 : check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
2322 : : {
2323 : : int keyno;
2324 : :
2325 : : /*
2326 : : * First check if there are any IS [NOT] NULL scan keys, and if we're
2327 : : * violating them.
2328 : : */
2329 [ + + ]: 127448 : for (keyno = 0; keyno < nnullkeys; keyno++)
2330 : : {
2331 : 1488 : ScanKey key = nullkeys[keyno];
2332 : :
2333 : : Assert(key->sk_attno == bval->bv_attno);
2334 : :
2335 : : /* Handle only IS NULL/IS NOT NULL tests */
2336 [ - + ]: 1488 : if (!(key->sk_flags & SK_ISNULL))
2337 : 0 : continue;
2338 : :
2339 [ + + ]: 1488 : if (key->sk_flags & SK_SEARCHNULL)
2340 : : {
2341 : : /* IS NULL scan key, but range has no NULLs */
2342 [ + + + + ]: 744 : if (!bval->bv_allnulls && !bval->bv_hasnulls)
2343 : 652 : return false;
2344 : : }
2345 [ + - ]: 744 : else if (key->sk_flags & SK_SEARCHNOTNULL)
2346 : : {
2347 : : /*
2348 : : * For IS NOT NULL, we can only skip ranges that are known to have
2349 : : * only nulls.
2350 : : */
2351 [ + + ]: 744 : if (bval->bv_allnulls)
2352 : 12 : return false;
2353 : : }
2354 : : else
2355 : : {
2356 : : /*
2357 : : * Neither IS NULL nor IS NOT NULL was used; assume all indexable
2358 : : * operators are strict and thus return false with NULL value in
2359 : : * the scan key.
2360 : : */
2361 : 0 : return false;
2362 : : }
2363 : : }
2364 : :
2365 : 125960 : return true;
2366 : : }
2367 : :
2368 : : /*
2369 : : * Create parallel context, and launch workers for leader.
2370 : : *
2371 : : * buildstate argument should be initialized (with the exception of the
2372 : : * tuplesort states, which may later be created based on shared
2373 : : * state initially set up here).
2374 : : *
2375 : : * isconcurrent indicates if operation is CREATE INDEX CONCURRENTLY.
2376 : : *
2377 : : * request is the target number of parallel worker processes to launch.
2378 : : *
2379 : : * Sets buildstate's BrinLeader, which caller must use to shut down parallel
2380 : : * mode by passing it to _brin_end_parallel() at the very end of its index
2381 : : * build. If not even a single worker process can be launched, this is
2382 : : * never set, and caller should proceed with a serial index build.
2383 : : */
2384 : : static void
2385 : 7 : _brin_begin_parallel(BrinBuildState *buildstate, Relation heap, Relation index,
2386 : : bool isconcurrent, int request)
2387 : : {
2388 : : ParallelContext *pcxt;
2389 : : int scantuplesortstates;
2390 : : Snapshot snapshot;
2391 : : Size estbrinshared;
2392 : : Size estsort;
2393 : : BrinShared *brinshared;
2394 : : Sharedsort *sharedsort;
2395 : 7 : BrinLeader *brinleader = palloc0_object(BrinLeader);
2396 : : WalUsage *walusage;
2397 : : BufferUsage *bufferusage;
2398 : 7 : bool leaderparticipates = true;
2399 : : int querylen;
2400 : :
2401 : : #ifdef DISABLE_LEADER_PARTICIPATION
2402 : : leaderparticipates = false;
2403 : : #endif
2404 : :
2405 : : /*
2406 : : * Enter parallel mode, and create context for parallel build of brin
2407 : : * index
2408 : : */
2409 : 7 : EnterParallelMode();
2410 : : Assert(request > 0);
2411 : 7 : pcxt = CreateParallelContext("postgres", "_brin_parallel_build_main",
2412 : : request);
2413 : :
2414 : 7 : scantuplesortstates = leaderparticipates ? request + 1 : request;
2415 : :
2416 : : /*
2417 : : * Prepare for scan of the base relation. In a normal index build, we use
2418 : : * SnapshotAny because we must retrieve all tuples and do our own time
2419 : : * qual checks (because we have to index RECENTLY_DEAD tuples). In a
2420 : : * concurrent build, we take a regular MVCC snapshot and index whatever's
2421 : : * live according to that.
2422 : : */
2423 [ + - ]: 7 : if (!isconcurrent)
2424 : 7 : snapshot = SnapshotAny;
2425 : : else
2426 : 0 : snapshot = RegisterSnapshot(GetTransactionSnapshot());
2427 : :
2428 : : /*
2429 : : * Estimate size for our own PARALLEL_KEY_BRIN_SHARED workspace.
2430 : : */
2431 : 7 : estbrinshared = _brin_parallel_estimate_shared(heap, snapshot);
2432 : 7 : shm_toc_estimate_chunk(&pcxt->estimator, estbrinshared);
2433 : 7 : estsort = tuplesort_estimate_shared(scantuplesortstates);
2434 : 7 : shm_toc_estimate_chunk(&pcxt->estimator, estsort);
2435 : :
2436 : 7 : shm_toc_estimate_keys(&pcxt->estimator, 2);
2437 : :
2438 : : /*
2439 : : * Estimate space for WalUsage and BufferUsage -- PARALLEL_KEY_WAL_USAGE
2440 : : * and PARALLEL_KEY_BUFFER_USAGE.
2441 : : *
2442 : : * If there are no extensions loaded that care, we could skip this. We
2443 : : * have no way of knowing whether anyone's looking at pgWalUsage or
2444 : : * pgBufferUsage, so do it unconditionally.
2445 : : */
2446 : 7 : shm_toc_estimate_chunk(&pcxt->estimator,
2447 : : mul_size(sizeof(WalUsage), pcxt->nworkers));
2448 : 7 : shm_toc_estimate_keys(&pcxt->estimator, 1);
2449 : 7 : shm_toc_estimate_chunk(&pcxt->estimator,
2450 : : mul_size(sizeof(BufferUsage), pcxt->nworkers));
2451 : 7 : shm_toc_estimate_keys(&pcxt->estimator, 1);
2452 : :
2453 : : /* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
2454 [ + - ]: 7 : if (debug_query_string)
2455 : : {
2456 : 7 : querylen = strlen(debug_query_string);
2457 : 7 : shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
2458 : 7 : shm_toc_estimate_keys(&pcxt->estimator, 1);
2459 : : }
2460 : : else
2461 : 0 : querylen = 0; /* keep compiler quiet */
2462 : :
2463 : : /* Everyone's had a chance to ask for space, so now create the DSM */
2464 : 7 : InitializeParallelDSM(pcxt);
2465 : :
2466 : : /* If no DSM segment was available, back out (do serial build) */
2467 [ - + ]: 7 : if (pcxt->seg == NULL)
2468 : : {
2469 [ # # ]: 0 : if (IsMVCCSnapshot(snapshot))
2470 : 0 : UnregisterSnapshot(snapshot);
2471 : 0 : DestroyParallelContext(pcxt);
2472 : 0 : ExitParallelMode();
2473 : 0 : return;
2474 : : }
2475 : :
2476 : : /* Store shared build state, for which we reserved space */
2477 : 7 : brinshared = (BrinShared *) shm_toc_allocate(pcxt->toc, estbrinshared);
2478 : : /* Initialize immutable state */
2479 : 7 : brinshared->heaprelid = RelationGetRelid(heap);
2480 : 7 : brinshared->indexrelid = RelationGetRelid(index);
2481 : 7 : brinshared->isconcurrent = isconcurrent;
2482 : 7 : brinshared->scantuplesortstates = scantuplesortstates;
2483 : 7 : brinshared->pagesPerRange = buildstate->bs_pagesPerRange;
2484 : 7 : brinshared->queryid = pgstat_get_my_query_id();
2485 : 7 : ConditionVariableInit(&brinshared->workersdonecv);
2486 : 7 : SpinLockInit(&brinshared->mutex);
2487 : :
2488 : : /* Initialize mutable state */
2489 : 7 : brinshared->nparticipantsdone = 0;
2490 : 7 : brinshared->reltuples = 0.0;
2491 : 7 : brinshared->indtuples = 0.0;
2492 : 7 : brinshared->brokenhotchain = false;
2493 : :
2494 : 7 : table_parallelscan_initialize(heap,
2495 : : ParallelTableScanFromBrinShared(brinshared),
2496 : : snapshot);
2497 : :
2498 : : /*
2499 : : * Store shared tuplesort-private state, for which we reserved space.
2500 : : * Then, initialize opaque state using tuplesort routine.
2501 : : */
2502 : 7 : sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
2503 : 7 : tuplesort_initialize_shared(sharedsort, scantuplesortstates,
2504 : : pcxt->seg);
2505 : :
2506 : : /*
2507 : : * Store shared tuplesort-private state, for which we reserved space.
2508 : : * Then, initialize opaque state using tuplesort routine.
2509 : : */
2510 : 7 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_BRIN_SHARED, brinshared);
2511 : 7 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT, sharedsort);
2512 : :
2513 : : /* Store query string for workers */
2514 [ + - ]: 7 : if (debug_query_string)
2515 : : {
2516 : : char *sharedquery;
2517 : :
2518 : 7 : sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
2519 : 7 : memcpy(sharedquery, debug_query_string, querylen + 1);
2520 : 7 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
2521 : : }
2522 : :
2523 : : /*
2524 : : * Allocate space for each worker's WalUsage and BufferUsage; no need to
2525 : : * initialize.
2526 : : */
2527 : 7 : walusage = shm_toc_allocate(pcxt->toc,
2528 : 7 : mul_size(sizeof(WalUsage), pcxt->nworkers));
2529 : 7 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_WAL_USAGE, walusage);
2530 : 7 : bufferusage = shm_toc_allocate(pcxt->toc,
2531 : 7 : mul_size(sizeof(BufferUsage), pcxt->nworkers));
2532 : 7 : shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufferusage);
2533 : :
2534 : : /* Launch workers, saving status for leader/caller */
2535 : 7 : LaunchParallelWorkers(pcxt);
2536 : 7 : brinleader->pcxt = pcxt;
2537 : 7 : brinleader->nparticipanttuplesorts = pcxt->nworkers_launched;
2538 [ + - ]: 7 : if (leaderparticipates)
2539 : 7 : brinleader->nparticipanttuplesorts++;
2540 : 7 : brinleader->brinshared = brinshared;
2541 : 7 : brinleader->sharedsort = sharedsort;
2542 : 7 : brinleader->snapshot = snapshot;
2543 : 7 : brinleader->walusage = walusage;
2544 : 7 : brinleader->bufferusage = bufferusage;
2545 : :
2546 : : /* If no workers were successfully launched, back out (do serial build) */
2547 [ + + ]: 7 : if (pcxt->nworkers_launched == 0)
2548 : : {
2549 : 1 : _brin_end_parallel(brinleader, NULL);
2550 : 1 : return;
2551 : : }
2552 : :
2553 : : /* Save leader state now that it's clear build will be parallel */
2554 : 6 : buildstate->bs_leader = brinleader;
2555 : :
2556 : : /* Join heap scan ourselves */
2557 [ + - ]: 6 : if (leaderparticipates)
2558 : 6 : _brin_leader_participate_as_worker(buildstate, heap, index);
2559 : :
2560 : : /*
2561 : : * Caller needs to wait for all launched workers when we return. Make
2562 : : * sure that the failure-to-start case will not hang forever.
2563 : : */
2564 : 6 : WaitForParallelWorkersToAttach(pcxt);
2565 : : }
2566 : :
2567 : : /*
2568 : : * Shut down workers, destroy parallel context, and end parallel mode.
2569 : : */
2570 : : static void
2571 : 7 : _brin_end_parallel(BrinLeader *brinleader, BrinBuildState *state)
2572 : : {
2573 : : int i;
2574 : :
2575 : : /* Shutdown worker processes */
2576 : 7 : WaitForParallelWorkersToFinish(brinleader->pcxt);
2577 : :
2578 : : /*
2579 : : * Next, accumulate WAL usage. (This must wait for the workers to finish,
2580 : : * or we might get incomplete data.)
2581 : : */
2582 [ + + ]: 15 : for (i = 0; i < brinleader->pcxt->nworkers_launched; i++)
2583 : 8 : InstrAccumParallelQuery(&brinleader->bufferusage[i], &brinleader->walusage[i]);
2584 : :
2585 : : /* Free last reference to MVCC snapshot, if one was used */
2586 [ - + ]: 7 : if (IsMVCCSnapshot(brinleader->snapshot))
2587 : 0 : UnregisterSnapshot(brinleader->snapshot);
2588 : 7 : DestroyParallelContext(brinleader->pcxt);
2589 : 7 : ExitParallelMode();
2590 : 7 : }
2591 : :
2592 : : /*
2593 : : * Within leader, wait for end of heap scan.
2594 : : *
2595 : : * When called, parallel heap scan started by _brin_begin_parallel() will
2596 : : * already be underway within worker processes (when leader participates
2597 : : * as a worker, we should end up here just as workers are finishing).
2598 : : *
2599 : : * Returns the total number of heap tuples scanned. Also sets *brokenhotchain
2600 : : * to whether any participant detected a broken HOT chain.
2601 : : */
2602 : : static double
2603 : 6 : _brin_parallel_heapscan(BrinBuildState *state, bool *brokenhotchain)
2604 : : {
2605 : 6 : BrinShared *brinshared = state->bs_leader->brinshared;
2606 : : int nparticipanttuplesorts;
2607 : :
2608 : 6 : nparticipanttuplesorts = state->bs_leader->nparticipanttuplesorts;
2609 : : for (;;)
2610 : : {
2611 : 18 : SpinLockAcquire(&brinshared->mutex);
2612 [ + + ]: 18 : if (brinshared->nparticipantsdone == nparticipanttuplesorts)
2613 : : {
2614 : : /* copy the data into leader state */
2615 : 6 : state->bs_reltuples = brinshared->reltuples;
2616 : 6 : state->bs_numtuples = brinshared->indtuples;
2617 : 6 : *brokenhotchain = brinshared->brokenhotchain;
2618 : :
2619 : 6 : SpinLockRelease(&brinshared->mutex);
2620 : 6 : break;
2621 : : }
2622 : 12 : SpinLockRelease(&brinshared->mutex);
2623 : :
2624 : 12 : ConditionVariableSleep(&brinshared->workersdonecv,
2625 : : WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN);
2626 : : }
2627 : :
2628 : 6 : ConditionVariableCancelSleep();
2629 : :
2630 : 6 : return state->bs_reltuples;
2631 : : }
2632 : :
2633 : : /*
2634 : : * Wait for all participants to finish producing their partial summaries.
2635 : : * In the leader, read the summaries in block range order and combine those
2636 : : * for the same range. Write one summary per range, using an empty summary
2637 : : * for any range with no indexed tuples.
2638 : : *
2639 : : * Return the total number of live heap tuples reported by the participants.
2640 : : * Set indexInfo->ii_BrokenHotChain if any participant detected a potentially
2641 : : * broken HOT chain.
2642 : : */
2643 : : static double
2644 : 6 : _brin_parallel_merge(BrinBuildState *state, IndexInfo *indexInfo)
2645 : : {
2646 : : BrinTuple *btup;
2647 : 6 : BrinMemTuple *memtuple = NULL;
2648 : : Size tuplen;
2649 : 6 : BlockNumber prevblkno = InvalidBlockNumber;
2650 : : MemoryContext rangeCxt,
2651 : : oldCxt;
2652 : : double reltuples;
2653 : :
2654 : : /* wait for workers to scan table and produce partial results */
2655 : 6 : reltuples = _brin_parallel_heapscan(state,
2656 : : &indexInfo->ii_BrokenHotChain);
2657 : :
2658 : : /* do the actual sort in the leader */
2659 : 6 : tuplesort_performsort(state->bs_sortstate);
2660 : :
2661 : : /*
2662 : : * Initialize BrinMemTuple we'll use to union summaries from workers (in
2663 : : * case they happened to produce parts of the same page range).
2664 : : */
2665 : 6 : memtuple = brin_new_memtuple(state->bs_bdesc);
2666 : :
2667 : : /*
2668 : : * Create a memory context we'll reset to combine results for a single
2669 : : * page range (received from the workers). We don't expect huge number of
2670 : : * overlaps under regular circumstances, because for large tables the
2671 : : * chunk size is likely larger than the BRIN page range), but it can
2672 : : * happen, and the union functions may do all kinds of stuff. So we better
2673 : : * reset the context once in a while.
2674 : : */
2675 : 6 : rangeCxt = AllocSetContextCreate(CurrentMemoryContext,
2676 : : "brin union",
2677 : : ALLOCSET_DEFAULT_SIZES);
2678 : 6 : oldCxt = MemoryContextSwitchTo(rangeCxt);
2679 : :
2680 : : /*
2681 : : * Read the BRIN tuples from the shared tuplesort, sorted by block number.
2682 : : * That probably gives us an index that is cheaper to scan, thanks to
2683 : : * mostly getting data from the same index page as before.
2684 : : */
2685 [ + + ]: 27 : while ((btup = tuplesort_getbrintuple(state->bs_sortstate, &tuplen, true)) != NULL)
2686 : : {
2687 : : /* Ranges should be multiples of pages_per_range for the index. */
2688 : : Assert(btup->bt_blkno % state->bs_leader->brinshared->pagesPerRange == 0);
2689 : :
2690 : : /*
2691 : : * Do we need to union summaries for the same page range?
2692 : : *
2693 : : * If this is the first brin tuple we read, then just deform it into
2694 : : * the memtuple, and continue with the next one from tuplesort. We
2695 : : * however may need to insert empty summaries into the index.
2696 : : *
2697 : : * If it's the same block as the last we saw, we simply union the brin
2698 : : * tuple into it, and we're done - we don't even need to insert empty
2699 : : * ranges, because that was done earlier when we saw the first brin
2700 : : * tuple (for this range).
2701 : : *
2702 : : * Finally, if it's not the first brin tuple, and it's not the same
2703 : : * page range, we need to do the insert and then deform the tuple into
2704 : : * the memtuple. Then we'll insert empty ranges before the new brin
2705 : : * tuple, if needed.
2706 : : */
2707 [ + + ]: 21 : if (prevblkno == InvalidBlockNumber)
2708 : : {
2709 : : /* First brin tuples, just deform into memtuple. */
2710 : 2 : memtuple = brin_deform_tuple(state->bs_bdesc, btup, memtuple);
2711 : :
2712 : : /* continue to insert empty pages before thisblock */
2713 : : }
2714 [ - + ]: 19 : else if (memtuple->bt_blkno == btup->bt_blkno)
2715 : : {
2716 : : /*
2717 : : * Not the first brin tuple, but same page range as the previous
2718 : : * one, so we can merge it into the memtuple.
2719 : : */
2720 : 0 : union_tuples(state->bs_bdesc, memtuple, btup);
2721 : 0 : continue;
2722 : : }
2723 : : else
2724 : : {
2725 : : BrinTuple *tmp;
2726 : : Size len;
2727 : :
2728 : : /*
2729 : : * We got brin tuple for a different page range, so form a brin
2730 : : * tuple from the memtuple, insert it, and re-init the memtuple
2731 : : * from the new brin tuple.
2732 : : */
2733 : 19 : tmp = brin_form_tuple(state->bs_bdesc, memtuple->bt_blkno,
2734 : : memtuple, &len);
2735 : :
2736 : 19 : brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
2737 : : &state->bs_currentInsertBuf, tmp->bt_blkno, tmp, len);
2738 : :
2739 : : /*
2740 : : * Reset the per-output-range context. This frees all the memory
2741 : : * possibly allocated by the union functions, and also the BRIN
2742 : : * tuple we just formed and inserted.
2743 : : */
2744 : 19 : MemoryContextReset(rangeCxt);
2745 : :
2746 : 19 : memtuple = brin_deform_tuple(state->bs_bdesc, btup, memtuple);
2747 : :
2748 : : /* continue to insert empty pages before thisblock */
2749 : : }
2750 : :
2751 : : /* Fill empty ranges for all ranges missing in the tuplesort. */
2752 : 21 : brin_fill_empty_ranges(state, prevblkno, btup->bt_blkno);
2753 : :
2754 : 21 : prevblkno = btup->bt_blkno;
2755 : : }
2756 : :
2757 : 6 : tuplesort_end(state->bs_sortstate);
2758 : :
2759 : : /* Fill the BRIN tuple for the last page range with data. */
2760 [ + + ]: 6 : if (prevblkno != InvalidBlockNumber)
2761 : : {
2762 : : BrinTuple *tmp;
2763 : : Size len;
2764 : :
2765 : 2 : tmp = brin_form_tuple(state->bs_bdesc, memtuple->bt_blkno,
2766 : : memtuple, &len);
2767 : :
2768 : 2 : brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
2769 : : &state->bs_currentInsertBuf, tmp->bt_blkno, tmp, len);
2770 : :
2771 : 2 : pfree(tmp);
2772 : : }
2773 : :
2774 : : /* Fill empty ranges at the end, for all ranges missing in the tuplesort. */
2775 : 6 : brin_fill_empty_ranges(state, prevblkno, state->bs_maxRangeStart);
2776 : :
2777 : : /*
2778 : : * Switch back to the original memory context, and destroy the one we
2779 : : * created to isolate the union_tuple calls.
2780 : : */
2781 : 6 : MemoryContextSwitchTo(oldCxt);
2782 : 6 : MemoryContextDelete(rangeCxt);
2783 : :
2784 : 6 : return reltuples;
2785 : : }
2786 : :
2787 : : /*
2788 : : * Returns size of shared memory required to store state for a parallel
2789 : : * brin index build based on the snapshot its parallel scan will use.
2790 : : */
2791 : : static Size
2792 : 7 : _brin_parallel_estimate_shared(Relation heap, Snapshot snapshot)
2793 : : {
2794 : : /* c.f. shm_toc_allocate as to why BUFFERALIGN is used */
2795 : 7 : return add_size(BUFFERALIGN(sizeof(BrinShared)),
2796 : : table_parallelscan_estimate(heap, snapshot));
2797 : : }
2798 : :
2799 : : /*
2800 : : * Within leader, participate as a parallel worker.
2801 : : */
2802 : : static void
2803 : 6 : _brin_leader_participate_as_worker(BrinBuildState *buildstate, Relation heap, Relation index)
2804 : : {
2805 : 6 : BrinLeader *brinleader = buildstate->bs_leader;
2806 : : int sortmem;
2807 : :
2808 : : /*
2809 : : * Might as well use reliable figure when doling out maintenance_work_mem
2810 : : * (when requested number of workers were not launched, this will be
2811 : : * somewhat higher than it is for other workers).
2812 : : */
2813 : 6 : sortmem = maintenance_work_mem / brinleader->nparticipanttuplesorts;
2814 : :
2815 : : /* Perform work common to all participants */
2816 : 6 : _brin_parallel_scan_and_build(buildstate, brinleader->brinshared,
2817 : : brinleader->sharedsort, heap, index, sortmem, true);
2818 : 6 : }
2819 : :
2820 : : /*
2821 : : * Perform a worker's portion of a parallel sort.
2822 : : *
2823 : : * This generates a tuplesort for the worker portion of the table.
2824 : : *
2825 : : * sortmem is the amount of working memory to use within each worker,
2826 : : * expressed in KBs.
2827 : : *
2828 : : * When this returns, workers are done, and need only release resources.
2829 : : */
2830 : : static void
2831 : 14 : _brin_parallel_scan_and_build(BrinBuildState *state,
2832 : : BrinShared *brinshared, Sharedsort *sharedsort,
2833 : : Relation heap, Relation index,
2834 : : int sortmem, bool progress)
2835 : : {
2836 : : SortCoordinate coordinate;
2837 : : TableScanDesc scan;
2838 : : double reltuples;
2839 : : IndexInfo *indexInfo;
2840 : :
2841 : : /* Initialize local tuplesort coordination state */
2842 : 14 : coordinate = palloc0_object(SortCoordinateData);
2843 : 14 : coordinate->isWorker = true;
2844 : 14 : coordinate->nParticipants = -1;
2845 : 14 : coordinate->sharedsort = sharedsort;
2846 : :
2847 : : /* Begin "partial" tuplesort */
2848 : 14 : state->bs_sortstate = tuplesort_begin_index_brin(sortmem, coordinate,
2849 : : TUPLESORT_NONE);
2850 : :
2851 : : /* Join parallel scan */
2852 : 14 : indexInfo = BuildIndexInfo(index);
2853 : 14 : indexInfo->ii_Concurrent = brinshared->isconcurrent;
2854 : :
2855 : 14 : scan = table_beginscan_parallel(heap,
2856 : : ParallelTableScanFromBrinShared(brinshared),
2857 : : SO_NONE);
2858 : :
2859 : 14 : reltuples = table_index_build_scan(heap, index, indexInfo, true, true,
2860 : : brinbuildCallbackParallel, state, scan);
2861 : :
2862 : : /* insert the last item */
2863 : 14 : form_and_spill_tuple(state);
2864 : :
2865 : : /* sort the BRIN ranges built by this worker */
2866 : 14 : tuplesort_performsort(state->bs_sortstate);
2867 : :
2868 : 14 : state->bs_reltuples += reltuples;
2869 : :
2870 : : /*
2871 : : * Done. Record ambuild statistics, and whether we encountered a broken
2872 : : * HOT chain.
2873 : : */
2874 : 14 : SpinLockAcquire(&brinshared->mutex);
2875 : 14 : brinshared->nparticipantsdone++;
2876 : 14 : brinshared->reltuples += state->bs_reltuples;
2877 : 14 : brinshared->indtuples += state->bs_numtuples;
2878 [ + + ]: 14 : if (indexInfo->ii_BrokenHotChain)
2879 : 1 : brinshared->brokenhotchain = true;
2880 : 14 : SpinLockRelease(&brinshared->mutex);
2881 : :
2882 : : /* Notify leader */
2883 : 14 : ConditionVariableSignal(&brinshared->workersdonecv);
2884 : :
2885 : 14 : tuplesort_end(state->bs_sortstate);
2886 : 14 : }
2887 : :
2888 : : /*
2889 : : * Perform work within a launched parallel process.
2890 : : */
2891 : : void
2892 : 8 : _brin_parallel_build_main(dsm_segment *seg, shm_toc *toc)
2893 : : {
2894 : : char *sharedquery;
2895 : : BrinShared *brinshared;
2896 : : Sharedsort *sharedsort;
2897 : : BrinBuildState *buildstate;
2898 : : Relation heapRel;
2899 : : Relation indexRel;
2900 : : LOCKMODE heapLockmode;
2901 : : LOCKMODE indexLockmode;
2902 : : WalUsage *walusage;
2903 : : BufferUsage *bufferusage;
2904 : : int sortmem;
2905 : :
2906 : : /*
2907 : : * The only possible status flag that can be set to the parallel worker is
2908 : : * PROC_IN_SAFE_IC.
2909 : : */
2910 : : Assert((MyProc->statusFlags == 0) ||
2911 : : (MyProc->statusFlags == PROC_IN_SAFE_IC));
2912 : :
2913 : : /* Set debug_query_string for individual workers first */
2914 : 8 : sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, true);
2915 : 8 : debug_query_string = sharedquery;
2916 : :
2917 : : /* Report the query string from leader */
2918 : 8 : pgstat_report_activity(STATE_RUNNING, debug_query_string);
2919 : :
2920 : : /* Look up brin shared state */
2921 : 8 : brinshared = shm_toc_lookup(toc, PARALLEL_KEY_BRIN_SHARED, false);
2922 : :
2923 : : /* Open relations using lock modes known to be obtained by index.c */
2924 [ + - ]: 8 : if (!brinshared->isconcurrent)
2925 : : {
2926 : 8 : heapLockmode = ShareLock;
2927 : 8 : indexLockmode = AccessExclusiveLock;
2928 : : }
2929 : : else
2930 : : {
2931 : 0 : heapLockmode = ShareUpdateExclusiveLock;
2932 : 0 : indexLockmode = RowExclusiveLock;
2933 : : }
2934 : :
2935 : : /* Track query ID */
2936 : 8 : pgstat_report_query_id(brinshared->queryid, false);
2937 : :
2938 : : /* Open relations within worker */
2939 : 8 : heapRel = table_open(brinshared->heaprelid, heapLockmode);
2940 : 8 : indexRel = index_open(brinshared->indexrelid, indexLockmode);
2941 : :
2942 : 8 : buildstate = initialize_brin_buildstate(indexRel, NULL,
2943 : : brinshared->pagesPerRange,
2944 : : InvalidBlockNumber);
2945 : :
2946 : : /* Look up shared state private to tuplesort.c */
2947 : 8 : sharedsort = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT, false);
2948 : 8 : tuplesort_attach_shared(sharedsort, seg);
2949 : :
2950 : : /* Prepare to track buffer usage during parallel execution */
2951 : 8 : InstrStartParallelQuery();
2952 : :
2953 : : /*
2954 : : * Might as well use reliable figure when doling out maintenance_work_mem
2955 : : * (when requested number of workers were not launched, this will be
2956 : : * somewhat higher than it is for other workers).
2957 : : */
2958 : 8 : sortmem = maintenance_work_mem / brinshared->scantuplesortstates;
2959 : :
2960 : 8 : _brin_parallel_scan_and_build(buildstate, brinshared, sharedsort,
2961 : : heapRel, indexRel, sortmem, false);
2962 : :
2963 : : /* Report WAL/buffer usage during parallel execution */
2964 : 8 : bufferusage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
2965 : 8 : walusage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
2966 : 8 : InstrEndParallelQuery(&bufferusage[ParallelWorkerNumber],
2967 : 8 : &walusage[ParallelWorkerNumber]);
2968 : :
2969 : 8 : index_close(indexRel, indexLockmode);
2970 : 8 : table_close(heapRel, heapLockmode);
2971 : 8 : }
2972 : :
2973 : : /*
2974 : : * brin_build_empty_tuple
2975 : : * Maybe initialize a BRIN tuple representing empty range.
2976 : : *
2977 : : * Returns a BRIN tuple representing an empty page range starting at the
2978 : : * specified block number. The empty tuple is initialized only once, when it's
2979 : : * needed for the first time, stored in the memory context bs_context to ensure
2980 : : * proper life span, and reused on following calls. All empty tuples are
2981 : : * exactly the same except for the bt_blkno field, which is set to the value
2982 : : * in blkno parameter.
2983 : : */
2984 : : static void
2985 : 11 : brin_build_empty_tuple(BrinBuildState *state, BlockNumber blkno)
2986 : : {
2987 : : /* First time an empty tuple is requested? If yes, initialize it. */
2988 [ + + ]: 11 : if (state->bs_emptyTuple == NULL)
2989 : : {
2990 : : MemoryContext oldcxt;
2991 : 6 : BrinMemTuple *dtuple = brin_new_memtuple(state->bs_bdesc);
2992 : :
2993 : : /* Allocate the tuple in context for the whole index build. */
2994 : 6 : oldcxt = MemoryContextSwitchTo(state->bs_context);
2995 : :
2996 : 6 : state->bs_emptyTuple = brin_form_tuple(state->bs_bdesc, blkno, dtuple,
2997 : : &state->bs_emptyTupleLen);
2998 : :
2999 : 6 : MemoryContextSwitchTo(oldcxt);
3000 : : }
3001 : : else
3002 : : {
3003 : : /* If we already have an empty tuple, just update the block. */
3004 : 5 : state->bs_emptyTuple->bt_blkno = blkno;
3005 : : }
3006 : 11 : }
3007 : :
3008 : : /*
3009 : : * brin_fill_empty_ranges
3010 : : * Add BRIN index tuples representing empty page ranges.
3011 : : *
3012 : : * prevRange/nextRange determine for which page ranges to add empty summaries.
3013 : : * Both boundaries are exclusive, i.e. only ranges starting at blkno for which
3014 : : * (prevRange < blkno < nextRange) will be added to the index.
3015 : : *
3016 : : * If prevRange is InvalidBlockNumber, this means there was no previous page
3017 : : * range (i.e. the first empty range to add is for blkno=0).
3018 : : *
3019 : : * The empty tuple is built only once, and then reused for all future calls.
3020 : : */
3021 : : static void
3022 : 262 : brin_fill_empty_ranges(BrinBuildState *state,
3023 : : BlockNumber prevRange, BlockNumber nextRange)
3024 : : {
3025 : : BlockNumber blkno;
3026 : :
3027 : : /*
3028 : : * If we already summarized some ranges, we need to start with the next
3029 : : * one. Otherwise start from the first range of the table.
3030 : : */
3031 [ + + ]: 262 : blkno = (prevRange == InvalidBlockNumber) ? 0 : (prevRange + state->bs_pagesPerRange);
3032 : :
3033 : : /* Generate empty ranges until we hit the next non-empty range. */
3034 [ + + ]: 273 : while (blkno < nextRange)
3035 : : {
3036 : : /* Did we already build the empty tuple? If not, do it now. */
3037 : 11 : brin_build_empty_tuple(state, blkno);
3038 : :
3039 : 11 : brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
3040 : : &state->bs_currentInsertBuf,
3041 : 11 : blkno, state->bs_emptyTuple, state->bs_emptyTupleLen);
3042 : :
3043 : : /* try next page range */
3044 : 11 : blkno += state->bs_pagesPerRange;
3045 : : }
3046 : 262 : }
|