Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * bulk_write.c
4 : : * Efficiently and reliably populate a new relation
5 : : *
6 : : * The assumption is that no other backends access the relation while we are
7 : : * loading it, so we can take some shortcuts. Pages already present in the
8 : : * indicated fork when the bulk write operation is started are not modified
9 : : * unless explicitly written to. Do not mix operations through the regular
10 : : * buffer manager and the bulk loading interface!
11 : : *
12 : : * We bypass the buffer manager to avoid the locking overhead, and call
13 : : * smgrextend() directly. A downside is that the pages will need to be
14 : : * re-read into shared buffers on first use after the build finishes. That's
15 : : * usually a good tradeoff for large relations, and for small relations, the
16 : : * overhead isn't very significant compared to creating the relation in the
17 : : * first place.
18 : : *
19 : : * The pages are WAL-logged if needed. To save on WAL header overhead, we
20 : : * WAL-log several pages in one record.
21 : : *
22 : : * One tricky point is that because we bypass the buffer manager, we need to
23 : : * register the relation for fsyncing at the next checkpoint ourselves, and
24 : : * make sure that the relation is correctly fsync'd by us or the checkpointer
25 : : * even if a checkpoint happens concurrently.
26 : : *
27 : : *
28 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
29 : : * Portions Copyright (c) 1994, Regents of the University of California
30 : : *
31 : : *
32 : : * IDENTIFICATION
33 : : * src/backend/storage/smgr/bulk_write.c
34 : : *
35 : : *-------------------------------------------------------------------------
36 : : */
37 : : #include "postgres.h"
38 : :
39 : : #include "access/xloginsert.h"
40 : : #include "access/xlogrecord.h"
41 : : #include "storage/bufpage.h"
42 : : #include "storage/bulk_write.h"
43 : : #include "storage/smgr.h"
44 : : #include "utils/rel.h"
45 : :
46 : : #define MAX_PENDING_WRITES XLR_MAX_BLOCK_ID
47 : :
48 : : static const PGIOAlignedBlock zero_buffer = {0}; /* worth BLCKSZ */
49 : :
50 : : typedef struct PendingWrite
51 : : {
52 : : BulkWriteBuffer buf;
53 : : BlockNumber blkno;
54 : : bool page_std;
55 : : } PendingWrite;
56 : :
57 : : /*
58 : : * Bulk writer state for one relation fork.
59 : : */
60 : : struct BulkWriteState
61 : : {
62 : : /* Information about the target relation we're writing */
63 : : SMgrRelation smgr;
64 : : ForkNumber forknum;
65 : : bool use_wal;
66 : :
67 : : /* We keep several writes queued, and WAL-log them in batches */
68 : : int npending;
69 : : PendingWrite pending_writes[MAX_PENDING_WRITES];
70 : :
71 : : /* Current size of the relation */
72 : : BlockNumber relsize;
73 : :
74 : : /* The RedoRecPtr at the time that the bulk operation started */
75 : : XLogRecPtr start_RedoRecPtr;
76 : :
77 : : MemoryContext memcxt;
78 : : };
79 : :
80 : : static void smgr_bulk_flush(BulkWriteState *bulkstate);
81 : :
82 : : /*
83 : : * Start a bulk write operation on a relation fork.
84 : : */
85 : : BulkWriteState *
1009 heikki.linnakangas@i 86 :CBC 33993 : smgr_bulk_start_rel(Relation rel, ForkNumber forknum)
87 : : {
88 : 33993 : return smgr_bulk_start_smgr(RelationGetSmgr(rel),
89 : : forknum,
90 [ + + + + : 33993 : RelationNeedsWAL(rel) || forknum == INIT_FORKNUM);
+ + + + +
+ ]
91 : : }
92 : :
93 : : /*
94 : : * Start a bulk write operation on a relation fork.
95 : : *
96 : : * This is like smgr_bulk_start_rel, but can be used without a relcache entry.
97 : : */
98 : : BulkWriteState *
99 : 34123 : smgr_bulk_start_smgr(SMgrRelation smgr, ForkNumber forknum, bool use_wal)
100 : : {
101 : : BulkWriteState *state;
102 : :
353 michael@paquier.xyz 103 : 34123 : state = palloc_object(BulkWriteState);
1009 heikki.linnakangas@i 104 : 34123 : state->smgr = smgr;
105 : 34123 : state->forknum = forknum;
106 : 34123 : state->use_wal = use_wal;
107 : :
108 : 34123 : state->npending = 0;
736 109 : 34123 : state->relsize = smgrnblocks(smgr, forknum);
110 : :
1009 111 : 34123 : state->start_RedoRecPtr = GetRedoRecPtr();
112 : :
113 : : /*
114 : : * Remember the memory context. We will use it to allocate all the
115 : : * buffers later.
116 : : */
117 : 34123 : state->memcxt = CurrentMemoryContext;
118 : :
119 : 34123 : return state;
120 : : }
121 : :
122 : : /*
123 : : * Finish bulk write operation.
124 : : *
125 : : * This WAL-logs and flushes any remaining pending writes to disk, and fsyncs
126 : : * the relation if needed.
127 : : */
128 : : void
129 : 34123 : smgr_bulk_finish(BulkWriteState *bulkstate)
130 : : {
131 : : /* WAL-log and flush any remaining pages */
132 : 34123 : smgr_bulk_flush(bulkstate);
133 : :
134 : : /*
135 : : * Fsync the relation, or register it for the next checkpoint, if
136 : : * necessary.
137 : : */
834 138 [ + + ]: 34123 : if (SmgrIsTemp(bulkstate->smgr))
139 : : {
140 : : /* Temporary relations don't need to be fsync'd, ever */
141 : : }
142 [ + + ]: 32378 : else if (!bulkstate->use_wal)
143 : : {
144 : : /*----------
145 : : * This is either an unlogged relation, or a permanent relation but we
146 : : * skipped WAL-logging because wal_level=minimal:
147 : : *
148 : : * A) Unlogged relation
149 : : *
150 : : * Unlogged relations will go away on crash, but they need to be
151 : : * fsync'd on a clean shutdown. It's sufficient to call
152 : : * smgrregistersync(), that ensures that the checkpointer will
153 : : * flush it at the shutdown checkpoint. (It will flush it on the
154 : : * next online checkpoint too, which is not strictly necessary.)
155 : : *
156 : : * Note that the init-fork of an unlogged relation is not
157 : : * considered unlogged for our purposes. It's treated like a
158 : : * regular permanent relation. The callers will pass use_wal=true
159 : : * for the init fork.
160 : : *
161 : : * B) Permanent relation, WAL-logging skipped because wal_level=minimal
162 : : *
163 : : * This is a new relation, and we didn't WAL-log the pages as we
164 : : * wrote, but they need to be fsync'd before commit.
165 : : *
166 : : * We don't need to do that here, however. The fsync() is done at
167 : : * commit, by smgrDoPendingSyncs() (*).
168 : : *
169 : : * (*) smgrDoPendingSyncs() might decide to WAL-log the whole
170 : : * relation at commit instead of fsyncing it, if the relation was
171 : : * very small, but it's smgrDoPendingSyncs() responsibility in any
172 : : * case.
173 : : *
174 : : * We cannot distinguish the two here, so conservatively assume it's
175 : : * an unlogged relation. A permanent relation with wal_level=minimal
176 : : * would require no actions, see above.
177 : : */
178 : 2954 : smgrregistersync(bulkstate->smgr, bulkstate->forknum);
179 : : }
180 : : else
181 : : {
182 : : bool need_sync;
183 : :
184 : : /*
185 : : * Permanent relation, WAL-logged normally.
186 : : *
187 : : * We already WAL-logged all the pages, so they will be replayed from
188 : : * WAL on crash. However, when we wrote out the pages, we passed
189 : : * skipFsync=true to avoid the overhead of registering all the writes
190 : : * with the checkpointer. Register the whole relation now.
191 : : *
192 : : * There is one hole in that idea: If a checkpoint occurred while we
193 : : * were writing the pages, it already missed fsyncing the pages we had
194 : : * written before the checkpoint started. A crash later on would
195 : : * replay the WAL starting from the checkpoint, therefore it wouldn't
196 : : * replay our earlier WAL records. So if a checkpoint started after
197 : : * the bulk write, fsync the files now.
198 : : *
199 : : * The sync request is registered before re-checking the redo pointer:
200 : : * if it has still not moved, any checkpoint that moves it later
201 : : * absorbs the request before syncing. The first check skips the
202 : : * request when a checkpoint already happened during the writes.
203 : : */
4 michael@paquier.xyz 204 :GNC 29424 : need_sync = (bulkstate->start_RedoRecPtr != GetRedoRecPtr());
205 [ + + ]: 29424 : if (!need_sync)
206 : : {
207 : 29422 : smgrregistersync(bulkstate->smgr, bulkstate->forknum);
208 : 29422 : need_sync = (bulkstate->start_RedoRecPtr != GetRedoRecPtr());
209 : : }
210 : :
211 [ + + ]: 29424 : if (need_sync)
212 : : {
1009 heikki.linnakangas@i 213 :CBC 2 : smgrimmedsync(bulkstate->smgr, bulkstate->forknum);
214 [ - + ]: 2 : elog(DEBUG1, "flushed relation because a checkpoint occurred concurrently");
215 : : }
216 : : }
217 : 34123 : }
218 : :
219 : : static int
220 : 146926 : buffer_cmp(const void *a, const void *b)
221 : : {
222 : 146926 : const PendingWrite *bufa = (const PendingWrite *) a;
223 : 146926 : const PendingWrite *bufb = (const PendingWrite *) b;
224 : :
225 : : /* We should not see duplicated writes for the same block */
226 [ - + ]: 146926 : Assert(bufa->blkno != bufb->blkno);
227 [ + + ]: 146926 : if (bufa->blkno > bufb->blkno)
228 : 69491 : return 1;
229 : : else
230 : 77435 : return -1;
231 : : }
232 : :
233 : : /*
234 : : * Finish all the pending writes.
235 : : */
236 : : static void
237 : 34837 : smgr_bulk_flush(BulkWriteState *bulkstate)
238 : : {
239 : 34837 : int npending = bulkstate->npending;
240 : 34837 : PendingWrite *pending_writes = bulkstate->pending_writes;
241 : :
242 [ + + ]: 34837 : if (npending == 0)
243 : 205 : return;
244 : :
245 [ + + ]: 34632 : if (npending > 1)
246 : 7413 : qsort(pending_writes, npending, sizeof(PendingWrite), buffer_cmp);
247 : :
248 [ + + ]: 34632 : if (bulkstate->use_wal)
249 : : {
250 : : BlockNumber blknos[MAX_PENDING_WRITES];
251 : : Page pages[MAX_PENDING_WRITES];
252 : 29666 : bool page_std = true;
253 : :
254 [ + + ]: 85998 : for (int i = 0; i < npending; i++)
255 : : {
256 : 56332 : blknos[i] = pending_writes[i].blkno;
257 : 56332 : pages[i] = pending_writes[i].buf->data;
258 : :
259 : : /*
260 : : * If any of the pages use !page_std, we log them all as such.
261 : : * That's a bit wasteful, but in practice, a mix of standard and
262 : : * non-standard page layout is rare. None of the built-in AMs do
263 : : * that.
264 : : */
265 [ + + ]: 56332 : if (!pending_writes[i].page_std)
266 : 23 : page_std = false;
267 : : }
268 : 29666 : log_newpages(&bulkstate->smgr->smgr_rlocator.locator, bulkstate->forknum,
269 : : npending, blknos, pages, page_std);
270 : : }
271 : :
272 [ + + ]: 110019 : for (int i = 0; i < npending; i++)
273 : : {
274 : 75387 : BlockNumber blkno = pending_writes[i].blkno;
275 : 75387 : Page page = pending_writes[i].buf->data;
276 : :
246 andres@anarazel.de 277 : 75387 : PageSetChecksum(page, blkno);
278 : :
736 heikki.linnakangas@i 279 [ + + ]: 75387 : if (blkno >= bulkstate->relsize)
280 : : {
281 : : /*
282 : : * If we have to write pages nonsequentially, fill in the space
283 : : * with zeroes until we come back and overwrite. This is not
284 : : * logically necessary on standard Unix filesystems (unwritten
285 : : * space will read as zeroes anyway), but it should help to avoid
286 : : * fragmentation. The dummy pages aren't WAL-logged though.
287 : : */
288 [ + + ]: 75387 : while (blkno > bulkstate->relsize)
289 : : {
290 : : /* don't set checksum for all-zero page */
1009 291 : 350 : smgrextend(bulkstate->smgr, bulkstate->forknum,
292 : : bulkstate->relsize,
293 : : &zero_buffer,
294 : : true);
736 295 : 350 : bulkstate->relsize++;
296 : : }
297 : :
1009 298 : 75037 : smgrextend(bulkstate->smgr, bulkstate->forknum, blkno, page, true);
736 299 : 75037 : bulkstate->relsize++;
300 : : }
301 : : else
1009 302 : 350 : smgrwrite(bulkstate->smgr, bulkstate->forknum, blkno, page, true);
303 : 75387 : pfree(page);
304 : : }
305 : :
306 : 34632 : bulkstate->npending = 0;
307 : : }
308 : :
309 : : /*
310 : : * Queue write of 'buf'.
311 : : *
312 : : * NB: this takes ownership of 'buf'!
313 : : *
314 : : * You are only allowed to write a given block once as part of one bulk write
315 : : * operation.
316 : : */
317 : : void
318 : 75387 : smgr_bulk_write(BulkWriteState *bulkstate, BlockNumber blocknum, BulkWriteBuffer buf, bool page_std)
319 : : {
320 : : PendingWrite *w;
321 : :
322 : 75387 : w = &bulkstate->pending_writes[bulkstate->npending++];
323 : 75387 : w->buf = buf;
324 : 75387 : w->blkno = blocknum;
325 : 75387 : w->page_std = page_std;
326 : :
327 [ + + ]: 75387 : if (bulkstate->npending == MAX_PENDING_WRITES)
328 : 714 : smgr_bulk_flush(bulkstate);
329 : 75387 : }
330 : :
331 : : /*
332 : : * Allocate a new buffer which can later be written with smgr_bulk_write().
333 : : *
334 : : * There is no function to free the buffer. When you pass it to
335 : : * smgr_bulk_write(), it takes ownership and frees it when it's no longer
336 : : * needed.
337 : : *
338 : : * This is currently implemented as a simple palloc, but could be implemented
339 : : * using a ring buffer or larger chunks in the future, so don't rely on it.
340 : : */
341 : : BulkWriteBuffer
342 : 75387 : smgr_bulk_get_buf(BulkWriteState *bulkstate)
343 : : {
344 : 75387 : return MemoryContextAllocAligned(bulkstate->memcxt, BLCKSZ, PG_IO_ALIGN_SIZE, 0);
345 : : }
|