Skip to content

Commit 23c743b

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 1f95181 commit 23c743b

File tree

6 files changed

+92
-33
lines changed

6 files changed

+92
-33
lines changed

contrib/pg_visibility/pg_visibility.c

+26-6
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "funcapi.h"
1919
#include "miscadmin.h"
2020
#include "storage/bufmgr.h"
21+
#include "storage/proc.h"
2122
#include "storage/procarray.h"
2223
#include "storage/smgr.h"
2324
#include "utils/rel.h"
@@ -385,6 +386,7 @@ pg_truncate_visibility_map(PG_FUNCTION_ARGS)
385386
Relation rel;
386387
ForkNumber fork;
387388
BlockNumber block;
389+
BlockNumber old_block;
388390

389391
rel = relation_open(relid, AccessExclusiveLock);
390392

@@ -394,15 +396,24 @@ pg_truncate_visibility_map(PG_FUNCTION_ARGS)
394396
/* Forcibly reset cached file size */
395397
RelationGetSmgr(rel)->smgr_cached_nblocks[VISIBILITYMAP_FORKNUM] = InvalidBlockNumber;
396398

399+
/* Compute new and old size before entering critical section. */
400+
fork = VISIBILITYMAP_FORKNUM;
397401
block = visibilitymap_prepare_truncate(rel, 0);
398-
if (BlockNumberIsValid(block))
399-
{
400-
fork = VISIBILITYMAP_FORKNUM;
401-
smgrtruncate(RelationGetSmgr(rel), &fork, 1, &block);
402-
}
402+
old_block = BlockNumberIsValid(block) ? smgrnblocks(RelationGetSmgr(rel), fork) : 0;
403+
404+
/*
405+
* WAL-logging, buffer dropping, file truncation must be atomic and all on
406+
* one side of a checkpoint. See RelationTruncate() for discussion.
407+
*/
408+
Assert(!MyProc->delayChkpt);
409+
MyProc->delayChkpt = true;
410+
Assert(!MyProc->delayChkptEnd);
411+
MyProc->delayChkptEnd = true;
412+
START_CRIT_SECTION();
403413

404414
if (RelationNeedsWAL(rel))
405415
{
416+
XLogRecPtr lsn;
406417
xl_smgr_truncate xlrec;
407418

408419
xlrec.blkno = 0;
@@ -412,9 +423,18 @@ pg_truncate_visibility_map(PG_FUNCTION_ARGS)
412423
XLogBeginInsert();
413424
XLogRegisterData((char *) &xlrec, sizeof(xlrec));
414425

415-
XLogInsert(RM_SMGR_ID, XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
426+
lsn = XLogInsert(RM_SMGR_ID,
427+
XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
428+
XLogFlush(lsn);
416429
}
417430

431+
if (BlockNumberIsValid(block))
432+
smgrtruncate(RelationGetSmgr(rel), &fork, 1, &old_block, &block);
433+
434+
END_CRIT_SECTION();
435+
MyProc->delayChkpt = false;
436+
MyProc->delayChkptEnd = false;
437+
418438
/*
419439
* Release the lock right away, not at commit time.
420440
*

src/backend/catalog/storage.c

+32-12
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
280280
bool vm;
281281
bool need_fsm_vacuum = false;
282282
ForkNumber forks[MAX_FORKNUM];
283+
BlockNumber old_blocks[MAX_FORKNUM];
283284
BlockNumber blocks[MAX_FORKNUM];
284285
int nforks = 0;
285286
SMgrRelation reln;
@@ -295,6 +296,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
295296

296297
/* Prepare for truncation of MAIN fork of the relation */
297298
forks[nforks] = MAIN_FORKNUM;
299+
old_blocks[nforks] = smgrnblocks(reln, MAIN_FORKNUM);
298300
blocks[nforks] = nblocks;
299301
nforks++;
300302

@@ -306,6 +308,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
306308
if (BlockNumberIsValid(blocks[nforks]))
307309
{
308310
forks[nforks] = FSM_FORKNUM;
311+
old_blocks[nforks] = smgrnblocks(reln, FSM_FORKNUM);
309312
nforks++;
310313
need_fsm_vacuum = true;
311314
}
@@ -319,6 +322,7 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
319322
if (BlockNumberIsValid(blocks[nforks]))
320323
{
321324
forks[nforks] = VISIBILITYMAP_FORKNUM;
325+
old_blocks[nforks] = smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
322326
nforks++;
323327
}
324328
}
@@ -357,14 +361,20 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
357361
MyProc->delayChkptEnd = true; /* DELAY_CHKPT_COMPLETE */
358362

359363
/*
360-
* We WAL-log the truncation before actually truncating, which means
361-
* trouble if the truncation fails. If we then crash, the WAL replay
362-
* likely isn't going to succeed in the truncation either, and cause a
363-
* PANIC. It's tempting to put a critical section here, but that cure
364-
* would be worse than the disease. It would turn a usually harmless
365-
* failure to truncate, that might spell trouble at WAL replay, into a
366-
* certain PANIC.
364+
* We WAL-log the truncation first and then truncate in a critical
365+
* section. Truncation drops buffers, even if dirty, and then truncates
366+
* disk files. All of that work needs to complete before the lock is
367+
* released, or else old versions of pages on disk that are missing recent
368+
* changes would become accessible again. We'll try the whole operation
369+
* again in crash recovery if we panic, but even then we can't give up
370+
* because we don't want standbys' relation sizes to diverge and break
371+
* replay or visibility invariants downstream. The critical section also
372+
* suppresses interrupts.
373+
*
374+
* (See also pg_visibilitymap.c if changing this code.)
367375
*/
376+
START_CRIT_SECTION();
377+
368378
if (RelationNeedsWAL(rel))
369379
{
370380
/*
@@ -388,18 +398,20 @@ RelationTruncate(Relation rel, BlockNumber nblocks)
388398
* hit the disk before the WAL record, and the truncation of the FSM
389399
* or visibility map. If we crashed during that window, we'd be left
390400
* with a truncated heap, but the FSM or visibility map would still
391-
* contain entries for the non-existent heap pages.
401+
* contain entries for the non-existent heap pages, and standbys would
402+
* also never replay the truncation.
392403
*/
393-
if (fsm || vm)
394-
XLogFlush(lsn);
404+
XLogFlush(lsn);
395405
}
396406

397407
/*
398408
* This will first remove any buffers from the buffer pool that should no
399409
* longer exist after truncation is complete, and then truncate the
400410
* corresponding files on disk.
401411
*/
402-
smgrtruncate(RelationGetSmgr(rel), forks, nforks, blocks);
412+
smgrtruncate(RelationGetSmgr(rel), forks, nforks, old_blocks, blocks);
413+
414+
END_CRIT_SECTION();
403415

404416
/* We've done all the critical work, so checkpoints are OK now. */
405417
MyProc->delayChkpt = false;
@@ -983,6 +995,7 @@ smgr_redo(XLogReaderState *record)
983995
Relation rel;
984996
ForkNumber forks[MAX_FORKNUM];
985997
BlockNumber blocks[MAX_FORKNUM];
998+
BlockNumber old_blocks[MAX_FORKNUM];
986999
int nforks = 0;
9871000
bool need_fsm_vacuum = false;
9881001

@@ -1017,6 +1030,7 @@ smgr_redo(XLogReaderState *record)
10171030
if ((xlrec->flags & SMGR_TRUNCATE_HEAP) != 0)
10181031
{
10191032
forks[nforks] = MAIN_FORKNUM;
1033+
old_blocks[nforks] = smgrnblocks(reln, MAIN_FORKNUM);
10201034
blocks[nforks] = xlrec->blkno;
10211035
nforks++;
10221036

@@ -1034,6 +1048,7 @@ smgr_redo(XLogReaderState *record)
10341048
if (BlockNumberIsValid(blocks[nforks]))
10351049
{
10361050
forks[nforks] = FSM_FORKNUM;
1051+
old_blocks[nforks] = smgrnblocks(reln, FSM_FORKNUM);
10371052
nforks++;
10381053
need_fsm_vacuum = true;
10391054
}
@@ -1045,13 +1060,18 @@ smgr_redo(XLogReaderState *record)
10451060
if (BlockNumberIsValid(blocks[nforks]))
10461061
{
10471062
forks[nforks] = VISIBILITYMAP_FORKNUM;
1063+
old_blocks[nforks] = smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
10481064
nforks++;
10491065
}
10501066
}
10511067

10521068
/* Do the real work to truncate relation forks */
10531069
if (nforks > 0)
1054-
smgrtruncate(reln, forks, nforks, blocks);
1070+
{
1071+
START_CRIT_SECTION();
1072+
smgrtruncate(reln, forks, nforks, old_blocks, blocks);
1073+
END_CRIT_SECTION();
1074+
}
10551075

10561076
/*
10571077
* 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
@@ -818,19 +818,21 @@ mdnblocks(SMgrRelation reln, ForkNumber forknum)
818818

819819
/*
820820
* mdtruncate() -- Truncate relation to specified number of blocks.
821+
*
822+
* Guaranteed not to allocate memory, so it can be used in a critical section.
823+
* Caller must have called smgrnblocks() to obtain curnblk while holding a
824+
* sufficient lock to prevent a change in relation size, and not used any smgr
825+
* functions for this relation or handled interrupts in between. This makes
826+
* sure we have opened all active segments, so that truncate loop will get
827+
* them all!
821828
*/
822829
void
823-
mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
830+
mdtruncate(SMgrRelation reln, ForkNumber forknum,
831+
BlockNumber curnblk, BlockNumber nblocks)
824832
{
825-
BlockNumber curnblk;
826833
BlockNumber priorblocks;
827834
int curopensegs;
828835

829-
/*
830-
* NOTE: mdnblocks makes sure we have opened all active segments, so that
831-
* truncation loop will get them all!
832-
*/
833-
curnblk = mdnblocks(reln, forknum);
834836
if (nblocks > curnblk)
835837
{
836838
/* Bogus request ... but no complaint if InRecovery */
@@ -1099,7 +1101,7 @@ _fdvec_resize(SMgrRelation reln,
10991101
reln->md_seg_fds[forknum] =
11001102
MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
11011103
}
1102-
else
1104+
else if (nseg > reln->md_num_open_segs[forknum])
11031105
{
11041106
/*
11051107
* It doesn't seem worthwhile complicating the code to amortize
@@ -1111,6 +1113,16 @@ _fdvec_resize(SMgrRelation reln,
11111113
repalloc(reln->md_seg_fds[forknum],
11121114
sizeof(MdfdVec) * nseg);
11131115
}
1116+
else
1117+
{
1118+
/*
1119+
* We don't reallocate a smaller array, because we want mdtruncate()
1120+
* to be able to promise that it won't allocate memory, so that it is
1121+
* allowed in a critical section. This means that a bit of space in
1122+
* the array is now wasted, until the next time we add a segment and
1123+
* reallocate.
1124+
*/
1125+
}
11141126

11151127
reln->md_num_open_segs[forknum] = nseg;
11161128
}

src/backend/storage/smgr/smgr.c

+10-4
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ typedef struct f_smgr
6060
BlockNumber blocknum, BlockNumber nblocks);
6161
BlockNumber (*smgr_nblocks) (SMgrRelation reln, ForkNumber forknum);
6262
void (*smgr_truncate) (SMgrRelation reln, ForkNumber forknum,
63-
BlockNumber nblocks);
63+
BlockNumber old_blocks, BlockNumber nblocks);
6464
void (*smgr_immedsync) (SMgrRelation reln, ForkNumber forknum);
6565
} f_smgr;
6666

@@ -590,10 +590,15 @@ smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum)
590590
*
591591
* The caller must hold AccessExclusiveLock on the relation, to ensure that
592592
* other backends receive the smgr invalidation event that this function sends
593-
* before they access any forks of the relation again.
593+
* before they access any forks of the relation again. The current size of
594+
* the forks should be provided in old_nblocks. This function should normally
595+
* be called in a critical section, but the current size must be checked
596+
* outside the critical section, and no interrupts or smgr functions relating
597+
* to this relation should be called in between.
594598
*/
595599
void
596-
smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks, BlockNumber *nblocks)
600+
smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks,
601+
BlockNumber *old_nblocks, BlockNumber *nblocks)
597602
{
598603
int i;
599604

@@ -621,7 +626,8 @@ smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks, BlockNumber *nb
621626
/* Make the cached size is invalid if we encounter an error. */
622627
reln->smgr_cached_nblocks[forknum[i]] = InvalidBlockNumber;
623628

624-
smgrsw[reln->smgr_which].smgr_truncate(reln, forknum[i], nblocks[i]);
629+
smgrsw[reln->smgr_which].smgr_truncate(reln, forknum[i],
630+
old_nblocks[i], nblocks[i]);
625631

626632
/*
627633
* 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
@@ -38,7 +38,7 @@ extern void mdwriteback(SMgrRelation reln, ForkNumber forknum,
3838
BlockNumber blocknum, BlockNumber nblocks);
3939
extern BlockNumber mdnblocks(SMgrRelation reln, ForkNumber forknum);
4040
extern void mdtruncate(SMgrRelation reln, ForkNumber forknum,
41-
BlockNumber nblocks);
41+
BlockNumber old_blocks, BlockNumber nblocks);
4242
extern void mdimmedsync(SMgrRelation reln, ForkNumber forknum);
4343

4444
extern void ForgetDatabaseSyncRequests(Oid dbid);

src/include/storage/smgr.h

+3-2
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,9 @@ extern void smgrwriteback(SMgrRelation reln, ForkNumber forknum,
100100
BlockNumber blocknum, BlockNumber nblocks);
101101
extern BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum);
102102
extern BlockNumber smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum);
103-
extern void smgrtruncate(SMgrRelation reln, ForkNumber *forknum,
104-
int nforks, BlockNumber *nblocks);
103+
extern void smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks,
104+
BlockNumber *old_nblocks,
105+
BlockNumber *nblocks);
105106
extern void smgrimmedsync(SMgrRelation reln, ForkNumber forknum);
106107
extern void AtEOXact_SMgr(void);
107108

0 commit comments

Comments
 (0)