Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 0350b87

Browse files
committed
Fix corruption when relation truncation fails.
RelationTruncate() does three things, while holding an AccessExclusiveLock and preventing checkpoints: 1. Logs the truncation. 2. Drops buffers, even if they're dirty. 3. Truncates some number of files. Step 2 could previously be canceled if it had to wait for I/O, and step 3 could and still can fail in file APIs. All orderings of these operations have data corruption hazards if interrupted, so we can't give up until the whole operation is done. When dirty pages were discarded but the corresponding blocks were left on disk due to ERROR, old page versions could come back from disk, reviving deleted data (see pgsql-bugs #18146 and several like it). When primary and standby were allowed to disagree on relation size, standbys could panic (see pgsql-bugs #18426) or revive data unknown to visibility management on the primary (theorized). Changes: * WAL is now unconditionally flushed first * smgrtruncate() is now called in a critical section, preventing interrupts and causing PANIC on file API failure * smgrtruncate() has a new parameter for existing fork sizes, because it can't call smgrnblocks() itself inside a critical section The changes apply to RelationTruncate(), smgr_redo() and pg_truncate_visibility_map(). That last is also brought up to date with other evolutions of the truncation protocol. The VACUUM FileTruncate() failure mode had been discussed in older reports than the ones referenced below, with independent analysis from many people, but earlier theories on how to fix it were too complicated to back-patch. The more recently invented cancellation bug was diagnosed by Alexander Lakhin. Other corruption scenarios were spotted by me while iterating on this patch and earlier commit 75818b3. Back-patch to all supported releases. Reviewed-by: Michael Paquier <michael@paquier.xyz> Reviewed-by: Robert Haas <robertmhaas@gmail.com> Reported-by: rootcause000@gmail.com Reported-by: Alexander Lakhin <exclusion@gmail.com> Discussion: https://postgr.es/m/18146-04e908c662113ad5%40postgresql.org Discussion: https://postgr.es/m/18426-2d18da6586f152d6%40postgresql.org
1 parent 9e85b20 commit 0350b87

File tree

6 files changed

+88
-33
lines changed

6 files changed

+88
-33
lines changed

contrib/pg_visibility/pg_visibility.c

+22-6
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@ pg_truncate_visibility_map(PG_FUNCTION_ARGS)
380380
Relation rel;
381381
ForkNumber fork;
382382
BlockNumber block;
383+
BlockNumber old_block;
383384

384385
rel = relation_open(relid, AccessExclusiveLock);
385386

@@ -389,15 +390,22 @@ pg_truncate_visibility_map(PG_FUNCTION_ARGS)
389390
/* Forcibly reset cached file size */
390391
RelationGetSmgr(rel)->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM] = InvalidBlockNumber;
391392

393+
/* Compute new and old size before entering critical section. */
394+
fork = VISIBILITYMAP_FORKNUM;
392395
block = visibilitymap_prepare_truncate(rel, 0);
393-
if (BlockNumberIsValid(block))
394-
{
395-
fork = VISIBILITYMAP_FORKNUM;
396-
smgrtruncate(RelationGetSmgr(rel), &fork, 1, &block);
397-
}
396+
old_block = BlockNumberIsValid(block) ? smgrnblocks(RelationGetSmgr(rel), fork) : 0;
397+
398+
/*
399+
* WAL-logging, buffer dropping, file truncation must be atomic and all on
400+
* one side of a checkpoint. See RelationTruncate() for discussion.
401+
*/
402+
Assert((MyProc->delayChkptFlags & (DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE)) == 0);
403+
MyProc->delayChkptFlags |= DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE;
404+
START_CRIT_SECTION();
398405

399406
if (RelationNeedsWAL(rel))
400407
{
408+
XLogRecPtr lsn;
401409
xl_smgr_truncate xlrec;
402410

403411
xlrec.blkno = 0;
@@ -407,9 +415,17 @@ pg_truncate_visibility_map(PG_FUNCTION_ARGS)
407415
XLogBeginInsert();
408416
XLogRegisterData((char *) &xlrec, sizeof(xlrec));
409417

410-
XLogInsert(RM_SMGR_ID, XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
418+
lsn = XLogInsert(RM_SMGR_ID,
419+
XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
420+
XLogFlush(lsn);
411421
}
412422

423+
if (BlockNumberIsValid(block))
424+
smgrtruncate(RelationGetSmgr(rel), &fork, 1, &old_block, &block);
425+
426+
END_CRIT_SECTION();
427+
MyProc->delayChkptFlags &= ~(DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE);
428+
413429
/*
414430
* Release the lock right away, not at commit time.
415431
*

src/backend/catalog/storage.c

+32-12
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
291291
bool vm;
292292
bool need_fsm_vacuum = false;
293293
ForkNumber forks[MAX_FORKNUM];
294+
BlockNumber old_blocks[MAX_FORKNUM];
294295
BlockNumber blocks[MAX_FORKNUM];
295296
int nforks = 0;
296297
SMgrRelation reln;
@@ -306,6 +307,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
306307

307308
/* Prepare for truncation of MAIN fork of the relation */
308309
forks[nforks] = MAIN_FORKNUM;
310+
old_blocks[nforks] = smgrnblocks(reln, MAIN_FORKNUM);
309311
blocks[nforks] = nblocks;
310312
nforks++;
311313

@@ -317,6 +319,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
317319
if (BlockNumberIsValid(blocks[nforks]))
318320
{
319321
forks[nforks] = FSM_FORKNUM;
322+
old_blocks[nforks] = smgrnblocks(reln, FSM_FORKNUM);
320323
nforks++;
321324
need_fsm_vacuum = true;
322325
}
@@ -330,6 +333,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
330333
if (BlockNumberIsValid(blocks[nforks]))
331334
{
332335
forks[nforks] = VISIBILITYMAP_FORKNUM;
336+
old_blocks[nforks] = smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
333337
nforks++;
334338
}
335339
}
@@ -366,14 +370,20 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
366370
MyProc->delayChkptFlags |= DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE;
367371

368372
/*
369-
* We WAL-log the truncation before actually truncating, which means
370-
* trouble if the truncation fails. If we then crash, the WAL replay
371-
* likely isn't going to succeed in the truncation either, and cause a
372-
* PANIC. It's tempting to put a critical section here, but that cure
373-
* would be worse than the disease. It would turn a usually harmless
374-
* failure to truncate, that might spell trouble at WAL replay, into a
375-
* certain PANIC.
373+
* We WAL-log the truncation first and then truncate in a critical
374+
* section. Truncation drops buffers, even if dirty, and then truncates
375+
* disk files. All of that work needs to complete before the lock is
376+
* released, or else old versions of pages on disk that are missing recent
377+
* changes would become accessible again. We'll try the whole operation
378+
* again in crash recovery if we panic, but even then we can't give up
379+
* because we don't want standbys' relation sizes to diverge and break
380+
* replay or visibility invariants downstream. The critical section also
381+
* suppresses interrupts.
382+
*
383+
* (See also pg_visibilitymap.c if changing this code.)
376384
*/
385+
START_CRIT_SECTION();
386+
377387
if (RelationNeedsWAL(rel))
378388
{
379389
/*
@@ -397,18 +407,20 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
397407
* hit the disk before the WAL record, and the truncation of the FSM
398408
* or visibility map. If we crashed during that window, we'd be left
399409
* with a truncated heap, but the FSM or visibility map would still
400-
* contain entries for the non-existent heap pages.
410+
* contain entries for the non-existent heap pages, and standbys would
411+
* also never replay the truncation.
401412
*/
402-
if (fsm || vm)
403-
XLogFlush(lsn);
413+
XLogFlush(lsn);
404414
}
405415

406416
/*
407417
* This will first remove any buffers from the buffer pool that should no
408418
* longer exist after truncation is complete, and then truncate the
409419
* corresponding files on disk.
410420
*/
411-
smgrtruncate(RelationGetSmgr(rel), forks, nforks, blocks);
421+
smgrtruncate(RelationGetSmgr(rel), forks, nforks, old_blocks, blocks);
422+
423+
END_CRIT_SECTION();
412424

413425
/* We've done all the critical work, so checkpoints are OK now. */
414426
MyProc->delayChkptFlags &= ~(DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE);
@@ -973,6 +985,7 @@ smgr_redo(XLogReaderState *record)
973985
Relation rel;
974986
ForkNumber forks[MAX_FORKNUM];
975987
BlockNumber blocks[MAX_FORKNUM];
988+
BlockNumber old_blocks[MAX_FORKNUM];
976989
int nforks = 0;
977990
bool need_fsm_vacuum = false;
978991

@@ -1007,6 +1020,7 @@ smgr_redo(XLogReaderState *record)
10071020
if ((xlrec->flags & SMGR_TRUNCATE_HEAP) != 0)
10081021
{
10091022
forks[nforks] = MAIN_FORKNUM;
1023+
old_blocks[nforks] = smgrnblocks(reln, MAIN_FORKNUM);
10101024
blocks[nforks] = xlrec->blkno;
10111025
nforks++;
10121026

@@ -1024,6 +1038,7 @@ smgr_redo(XLogReaderState *record)
10241038
if (BlockNumberIsValid(blocks[nforks]))
10251039
{
10261040
forks[nforks] = FSM_FORKNUM;
1041+
old_blocks[nforks] = smgrnblocks(reln, FSM_FORKNUM);
10271042
nforks++;
10281043
need_fsm_vacuum = true;
10291044
}
@@ -1035,13 +1050,18 @@ smgr_redo(XLogReaderState *record)
10351050
if (BlockNumberIsValid(blocks[nforks]))
10361051
{
10371052
forks[nforks] = VISIBILITYMAP_FORKNUM;
1053+
old_blocks[nforks] = smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
10381054
nforks++;
10391055
}
10401056
}
10411057

10421058
/* Do the real work to truncate relation forks */
10431059
if (nforks > 0)
1044-
smgrtruncate(reln, forks, nforks, blocks);
1060+
{
1061+
START_CRIT_SECTION();
1062+
smgrtruncate(reln, forks, nforks, old_blocks, blocks);
1063+
END_CRIT_SECTION();
1064+
}
10451065

10461066
/*
10471067
* Update upper-level FSM pages to account for the truncation. This is

src/backend/storage/smgr/md.c

+20-8
Original file line numberDiff line numberDiff line change
@@ -1141,19 +1141,21 @@ mdnblocks(SMgrRelation reln, ForkNumber forknum)
11411141

11421142
/*
11431143
* mdtruncate() -- Truncate relation to specified number of blocks.
1144+
*
1145+
* Guaranteed not to allocate memory, so it can be used in a critical section.
1146+
* Caller must have called smgrnblocks() to obtain curnblk while holding a
1147+
* sufficient lock to prevent a change in relation size, and not used any smgr
1148+
* functions for this relation or handled interrupts in between. This makes
1149+
* sure we have opened all active segments, so that truncate loop will get
1150+
* them all!
11441151
*/
11451152
void
1146-
mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
1153+
mdtruncate(SMgrRelation reln, ForkNumber forknum,
1154+
BlockNumber curnblk, BlockNumber nblocks)
11471155
{
1148-
BlockNumber curnblk;
11491156
BlockNumber priorblocks;
11501157
int curopensegs;
11511158

1152-
/*
1153-
* NOTE: mdnblocks makes sure we have opened all active segments, so that
1154-
* truncation loop will get them all!
1155-
*/
1156-
curnblk = mdnblocks(reln, forknum);
11571159
if (nblocks > curnblk)
11581160
{
11591161
/* Bogus request ... but no complaint if InRecovery */
@@ -1492,7 +1494,7 @@ _fdvec_resize(SMgrRelation reln,
14921494
reln->md_seg_fds[forknum] =
14931495
MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
14941496
}
1495-
else
1497+
else if (nseg > reln->md_num_open_segs[forknum])
14961498
{
14971499
/*
14981500
* It doesn't seem worthwhile complicating the code to amortize
@@ -1504,6 +1506,16 @@ _fdvec_resize(SMgrRelation reln,
15041506
repalloc(reln->md_seg_fds[forknum],
15051507
sizeof(MdfdVec) * nseg);
15061508
}
1509+
else
1510+
{
1511+
/*
1512+
* We don't reallocate a smaller array, because we want mdtruncate()
1513+
* to be able to promise that it won't allocate memory, so that it is
1514+
* allowed in a critical section. This means that a bit of space in
1515+
* the array is now wasted, until the next time we add a segment and
1516+
* reallocate.
1517+
*/
1518+
}
15071519

15081520
reln->md_num_open_segs[forknum] = nseg;
15091521
}

src/backend/storage/smgr/smgr.c

+10-4
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ typedef struct f_smgr
9999
BlockNumber blocknum, BlockNumber nblocks);
100100
BlockNumber (*smgr_nblocks) (SMgrRelation reln, ForkNumber forknum);
101101
void (*smgr_truncate) (SMgrRelation reln, ForkNumber forknum,
102-
BlockNumber nblocks);
102+
BlockNumber old_blocks, BlockNumber nblocks);
103103
void (*smgr_immedsync) (SMgrRelation reln, ForkNumber forknum);
104104
void (*smgr_registersync) (SMgrRelation reln, ForkNumber forknum);
105105
} f_smgr;
@@ -697,10 +697,15 @@ smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum)
697697
*
698698
* The caller must hold AccessExclusiveLock on the relation, to ensure that
699699
* other backends receive the smgr invalidation event that this function sends
700-
* before they access any forks of the relation again.
700+
* before they access any forks of the relation again. The current size of
701+
* the forks should be provided in old_nblocks. This function should normally
702+
* be called in a critical section, but the current size must be checked
703+
* outside the critical section, and no interrupts or smgr functions relating
704+
* to this relation should be called in between.
701705
*/
702706
void
703-
smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks, BlockNumber *nblocks)
707+
smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks,
708+
BlockNumber *old_nblocks, BlockNumber *nblocks)
704709
{
705710
int i;
706711

@@ -728,7 +733,8 @@ smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks, BlockNumber *nb
728733
/* Make the cached size is invalid if we encounter an error. */
729734
reln->smgr_cached_nblocks[forknum[i]] = InvalidBlockNumber;
730735

731-
smgrsw[reln->smgr_which].smgr_truncate(reln, forknum[i], nblocks[i]);
736+
smgrsw[reln->smgr_which].smgr_truncate(reln, forknum[i],
737+
old_nblocks[i], nblocks[i]);
732738

733739
/*
734740
* We might as well update the local smgr_cached_nblocks values. The

src/include/storage/md.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ extern void mdwriteback(SMgrRelation reln, ForkNumber forknum,
4141
BlockNumber blocknum, BlockNumber nblocks);
4242
extern BlockNumber mdnblocks(SMgrRelation reln, ForkNumber forknum);
4343
extern void mdtruncate(SMgrRelation reln, ForkNumber forknum,
44-
BlockNumber nblocks);
44+
BlockNumber old_blocks, BlockNumber nblocks);
4545
extern void mdimmedsync(SMgrRelation reln, ForkNumber forknum);
4646
extern void mdregistersync(SMgrRelation reln, ForkNumber forknum);
4747

src/include/storage/smgr.h

+3-2
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,9 @@ extern void smgrwriteback(SMgrRelation reln, ForkNumber forknum,
103103
BlockNumber blocknum, BlockNumber nblocks);
104104
extern BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum);
105105
extern BlockNumber smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum);
106-
extern void smgrtruncate(SMgrRelation reln, ForkNumber *forknum,
107-
int nforks, BlockNumber *nblocks);
106+
extern void smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks,
107+
BlockNumber *old_nblocks,
108+
BlockNumber *nblocks);
108109
extern void smgrimmedsync(SMgrRelation reln, ForkNumber forknum);
109110
extern void smgrregistersync(SMgrRelation reln, ForkNumber forknum);
110111
extern void AtEOXact_SMgr(void);

0 commit comments

Comments
 (0)