1 /*-------------------------------------------------------------------------
4 * code to create and destroy physical storage for relations
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/catalog/storage.c
14 * Some of this code used to be in storage/smgr/smgr.c, and the
15 * function names still reflect that.
17 *-------------------------------------------------------------------------
22 #include "access/visibilitymap.h"
23 #include "access/xact.h"
24 #include "access/xlog.h"
25 #include "access/xloginsert.h"
26 #include "access/xlogutils.h"
27 #include "catalog/catalog.h"
28 #include "catalog/storage.h"
29 #include "catalog/storage_xlog.h"
30 #include "storage/freespace.h"
31 #include "storage/smgr.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
36 * We keep a list of all relations (represented as RelFileNode values)
37 * that have been created or deleted in the current transaction. When
38 * a relation is created, we create the physical file immediately, but
39 * remember it so that we can delete the file again if the current
40 * transaction is aborted. Conversely, a deletion request is NOT
41 * executed immediately, but is just entered in the list. When and if
42 * the transaction commits, we can delete the physical file.
44 * To handle subtransactions, every entry is marked with its transaction
45 * nesting level. At subtransaction commit, we reassign the subtransaction's
46 * entries to the parent nesting level. At subtransaction abort, we can
47 * immediately execute the abort-time actions for all entries of the current
50 * NOTE: the list is kept in TopMemoryContext to be sure it won't disappear
51 * unbetimes. It'd probably be OK to keep it in TopTransactionContext,
52 * but I'm being paranoid.
55 typedef struct PendingRelDelete
57 RelFileNode relnode; /* relation that may need to be deleted */
58 BackendId backend; /* InvalidBackendId if not a temp rel */
59 bool atCommit; /* T=delete at commit; F=delete at abort */
60 int nestLevel; /* xact nesting level of request */
61 struct PendingRelDelete *next; /* linked-list link */
64 static PendingRelDelete *pendingDeletes = NULL; /* head of linked list */
67 * RelationCreateStorage
68 * Create physical storage for a relation.
70 * Create the underlying disk file storage for the relation. This only
71 * creates the main fork; additional forks are created lazily by the
72 * modules that need them.
74 * This function is transactional. The creation is WAL-logged, and if the
75 * transaction aborts later on, the storage will be destroyed.
78 RelationCreateStorage(RelFileNode rnode, char relpersistence)
80 PendingRelDelete *pending;
85 switch (relpersistence)
87 case RELPERSISTENCE_TEMP:
88 backend = MyBackendId;
91 case RELPERSISTENCE_UNLOGGED:
92 backend = InvalidBackendId;
95 case RELPERSISTENCE_PERMANENT:
96 backend = InvalidBackendId;
100 elog(ERROR, "invalid relpersistence: %c", relpersistence);
101 return; /* placate compiler */
104 srel = smgropen(rnode, backend);
105 smgrcreate(srel, MAIN_FORKNUM, false);
108 log_smgrcreate(&srel->smgr_rnode.node, MAIN_FORKNUM);
110 /* Add the relation to the list of stuff to delete at abort */
111 pending = (PendingRelDelete *)
112 MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete));
113 pending->relnode = rnode;
114 pending->backend = backend;
115 pending->atCommit = false; /* delete if abort */
116 pending->nestLevel = GetCurrentTransactionNestLevel();
117 pending->next = pendingDeletes;
118 pendingDeletes = pending;
122 * Perform XLogInsert of an XLOG_SMGR_CREATE record to WAL.
125 log_smgrcreate(RelFileNode *rnode, ForkNumber forkNum)
127 xl_smgr_create xlrec;
130 * Make an XLOG entry reporting the file creation.
132 xlrec.rnode = *rnode;
133 xlrec.forkNum = forkNum;
136 XLogRegisterData((char *) &xlrec, sizeof(xlrec));
137 XLogInsert(RM_SMGR_ID, XLOG_SMGR_CREATE | XLR_SPECIAL_REL_UPDATE);
141 * RelationDropStorage
142 * Schedule unlinking of physical storage at transaction commit.
145 RelationDropStorage(Relation rel)
147 PendingRelDelete *pending;
149 /* Add the relation to the list of stuff to delete at commit */
150 pending = (PendingRelDelete *)
151 MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete));
152 pending->relnode = rel->rd_node;
153 pending->backend = rel->rd_backend;
154 pending->atCommit = true; /* delete if commit */
155 pending->nestLevel = GetCurrentTransactionNestLevel();
156 pending->next = pendingDeletes;
157 pendingDeletes = pending;
160 * NOTE: if the relation was created in this transaction, it will now be
161 * present in the pending-delete list twice, once with atCommit true and
162 * once with atCommit false. Hence, it will be physically deleted at end
163 * of xact in either case (and the other entry will be ignored by
164 * smgrDoPendingDeletes, so no error will occur). We could instead remove
165 * the existing list entry and delete the physical file immediately, but
166 * for now I'll keep the logic simple.
169 RelationCloseSmgr(rel);
173 * RelationPreserveStorage
174 * Mark a relation as not to be deleted after all.
176 * We need this function because relation mapping changes are committed
177 * separately from commit of the whole transaction, so it's still possible
178 * for the transaction to abort after the mapping update is done.
179 * When a new physical relation is installed in the map, it would be
180 * scheduled for delete-on-abort, so we'd delete it, and be in trouble.
181 * The relation mapper fixes this by telling us to not delete such relations
182 * after all as part of its commit.
184 * We also use this to reuse an old build of an index during ALTER TABLE, this
185 * time removing the delete-at-commit entry.
187 * No-op if the relation is not among those scheduled for deletion.
190 RelationPreserveStorage(RelFileNode rnode, bool atCommit)
192 PendingRelDelete *pending;
193 PendingRelDelete *prev;
194 PendingRelDelete *next;
197 for (pending = pendingDeletes; pending != NULL; pending = next)
199 next = pending->next;
200 if (RelFileNodeEquals(rnode, pending->relnode)
201 && pending->atCommit == atCommit)
203 /* unlink and delete list entry */
207 pendingDeletes = next;
209 /* prev does not change */
213 /* unrelated entry, don't touch it */
221 * Physically truncate a relation to the specified number of blocks.
223 * This includes getting rid of any buffers for the blocks that are to be
227 RelationTruncate(Relation rel, BlockNumber nblocks)
232 /* Open it at the smgr level if not already done */
233 RelationOpenSmgr(rel);
236 * Make sure smgr_targblock etc aren't pointing somewhere past new end
238 rel->rd_smgr->smgr_targblock = InvalidBlockNumber;
239 rel->rd_smgr->smgr_fsm_nblocks = InvalidBlockNumber;
240 rel->rd_smgr->smgr_vm_nblocks = InvalidBlockNumber;
242 /* Truncate the FSM first if it exists */
243 fsm = smgrexists(rel->rd_smgr, FSM_FORKNUM);
245 FreeSpaceMapTruncateRel(rel, nblocks);
247 /* Truncate the visibility map too if it exists. */
248 vm = smgrexists(rel->rd_smgr, VISIBILITYMAP_FORKNUM);
250 visibilitymap_truncate(rel, nblocks);
253 * We WAL-log the truncation before actually truncating, which means
254 * trouble if the truncation fails. If we then crash, the WAL replay
255 * likely isn't going to succeed in the truncation either, and cause a
256 * PANIC. It's tempting to put a critical section here, but that cure
257 * would be worse than the disease. It would turn a usually harmless
258 * failure to truncate, that might spell trouble at WAL replay, into a
261 if (RelationNeedsWAL(rel))
264 * Make an XLOG entry reporting the file truncation.
267 xl_smgr_truncate xlrec;
269 xlrec.blkno = nblocks;
270 xlrec.rnode = rel->rd_node;
273 XLogRegisterData((char *) &xlrec, sizeof(xlrec));
275 lsn = XLogInsert(RM_SMGR_ID,
276 XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
279 * Flush, because otherwise the truncation of the main relation might
280 * hit the disk before the WAL record, and the truncation of the FSM
281 * or visibility map. If we crashed during that window, we'd be left
282 * with a truncated heap, but the FSM or visibility map would still
283 * contain entries for the non-existent heap pages.
289 /* Do the real work */
290 smgrtruncate(rel->rd_smgr, MAIN_FORKNUM, nblocks);
294 * smgrDoPendingDeletes() -- Take care of relation deletes at end of xact.
296 * This also runs when aborting a subxact; we want to clean up a failed
297 * subxact immediately.
299 * Note: It's possible that we're being asked to remove a relation that has
300 * no physical storage in any fork. In particular, it's possible that we're
301 * cleaning up an old temporary relation for which RemovePgTempFiles has
302 * already recovered the physical storage.
305 smgrDoPendingDeletes(bool isCommit)
307 int nestLevel = GetCurrentTransactionNestLevel();
308 PendingRelDelete *pending;
309 PendingRelDelete *prev;
310 PendingRelDelete *next;
314 SMgrRelation *srels = NULL;
317 for (pending = pendingDeletes; pending != NULL; pending = next)
319 next = pending->next;
320 if (pending->nestLevel < nestLevel)
322 /* outer-level entries should not be processed yet */
327 /* unlink list entry first, so we don't retry on failure */
331 pendingDeletes = next;
332 /* do deletion if called for */
333 if (pending->atCommit == isCommit)
337 srel = smgropen(pending->relnode, pending->backend);
339 /* allocate the initial array, or extend it, if needed */
343 srels = palloc(sizeof(SMgrRelation) * maxrels);
345 else if (maxrels <= nrels)
348 srels = repalloc(srels, sizeof(SMgrRelation) * maxrels);
351 srels[nrels++] = srel;
353 /* must explicitly free the list entry */
355 /* prev does not change */
361 smgrdounlinkall(srels, nrels, false);
363 for (i = 0; i < nrels; i++)
371 * smgrGetPendingDeletes() -- Get a list of non-temp relations to be deleted.
373 * The return value is the number of relations scheduled for termination.
374 * *ptr is set to point to a freshly-palloc'd array of RelFileNodes.
375 * If there are no relations to be deleted, *ptr is set to NULL.
377 * Only non-temporary relations are included in the returned list. This is OK
378 * because the list is used only in contexts where temporary relations don't
379 * matter: we're either writing to the two-phase state file (and transactions
380 * that have touched temp tables can't be prepared) or we're writing to xlog
381 * (and all temporary files will be zapped if we restart anyway, so no need
382 * for redo to do it also).
384 * Note that the list does not include anything scheduled for termination
385 * by upper-level transactions.
388 smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
390 int nestLevel = GetCurrentTransactionNestLevel();
393 PendingRelDelete *pending;
396 for (pending = pendingDeletes; pending != NULL; pending = pending->next)
398 if (pending->nestLevel >= nestLevel && pending->atCommit == forCommit
399 && pending->backend == InvalidBackendId)
407 rptr = (RelFileNode *) palloc(nrels * sizeof(RelFileNode));
409 for (pending = pendingDeletes; pending != NULL; pending = pending->next)
411 if (pending->nestLevel >= nestLevel && pending->atCommit == forCommit
412 && pending->backend == InvalidBackendId)
414 *rptr = pending->relnode;
422 * PostPrepare_smgr -- Clean up after a successful PREPARE
424 * What we have to do here is throw away the in-memory state about pending
425 * relation deletes. It's all been recorded in the 2PC state file and
426 * it's no longer smgr's job to worry about it.
429 PostPrepare_smgr(void)
431 PendingRelDelete *pending;
432 PendingRelDelete *next;
434 for (pending = pendingDeletes; pending != NULL; pending = next)
436 next = pending->next;
437 pendingDeletes = next;
438 /* must explicitly free the list entry */
445 * AtSubCommit_smgr() --- Take care of subtransaction commit.
447 * Reassign all items in the pending-deletes list to the parent transaction.
450 AtSubCommit_smgr(void)
452 int nestLevel = GetCurrentTransactionNestLevel();
453 PendingRelDelete *pending;
455 for (pending = pendingDeletes; pending != NULL; pending = pending->next)
457 if (pending->nestLevel >= nestLevel)
458 pending->nestLevel = nestLevel - 1;
463 * AtSubAbort_smgr() --- Take care of subtransaction abort.
465 * Delete created relations and forget about deleted relations.
466 * We can execute these operations immediately because we know this
467 * subtransaction will not commit.
470 AtSubAbort_smgr(void)
472 smgrDoPendingDeletes(false);
476 smgr_redo(XLogReaderState *record)
478 XLogRecPtr lsn = record->EndRecPtr;
479 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
481 /* Backup blocks are not used in smgr records */
482 Assert(!XLogRecHasAnyBlockRefs(record));
484 if (info == XLOG_SMGR_CREATE)
486 xl_smgr_create *xlrec = (xl_smgr_create *) XLogRecGetData(record);
489 reln = smgropen(xlrec->rnode, InvalidBackendId);
490 smgrcreate(reln, xlrec->forkNum, true);
492 else if (info == XLOG_SMGR_TRUNCATE)
494 xl_smgr_truncate *xlrec = (xl_smgr_truncate *) XLogRecGetData(record);
498 reln = smgropen(xlrec->rnode, InvalidBackendId);
501 * Forcibly create relation if it doesn't exist (which suggests that
502 * it was dropped somewhere later in the WAL sequence). As in
503 * XLogReadBufferForRedo, we prefer to recreate the rel and replay the
504 * log as best we can until the drop is seen.
506 smgrcreate(reln, MAIN_FORKNUM, true);
509 * Before we perform the truncation, update minimum recovery point to
510 * cover this WAL record. Once the relation is truncated, there's no
511 * going back. The buffer manager enforces the WAL-first rule for
512 * normal updates to relation files, so that the minimum recovery
513 * point is always updated before the corresponding change in the data
514 * file is flushed to disk. We have to do the same manually here.
516 * Doing this before the truncation means that if the truncation fails
517 * for some reason, you cannot start up the system even after restart,
518 * until you fix the underlying situation so that the truncation will
519 * succeed. Alternatively, we could update the minimum recovery point
520 * after truncation, but that would leave a small window where the
521 * WAL-first rule could be violated.
525 smgrtruncate(reln, MAIN_FORKNUM, xlrec->blkno);
527 /* Also tell xlogutils.c about it */
528 XLogTruncateRelation(xlrec->rnode, MAIN_FORKNUM, xlrec->blkno);
530 /* Truncate FSM and VM too */
531 rel = CreateFakeRelcacheEntry(xlrec->rnode);
533 if (smgrexists(reln, FSM_FORKNUM))
534 FreeSpaceMapTruncateRel(rel, xlrec->blkno);
535 if (smgrexists(reln, VISIBILITYMAP_FORKNUM))
536 visibilitymap_truncate(rel, xlrec->blkno);
538 FreeFakeRelcacheEntry(rel);
541 elog(PANIC, "smgr_redo: unknown op code %u", info);