1 /*-------------------------------------------------------------------------
4 * POSTGRES heap access method input/output code.
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
18 #include "access/hio.h"
19 #include "storage/bufmgr.h"
20 #include "storage/freespace.h"
21 #include "storage/lmgr.h"
25 * RelationPutHeapTuple - place tuple at specified page
27 * !!! EREPORT(ERROR) IS DISALLOWED HERE !!! Must PANIC on failure!!!
29 * Note - caller must hold BUFFER_LOCK_EXCLUSIVE on the buffer.
32 RelationPutHeapTuple(Relation relation
,
41 /* Add the tuple to the page */
42 pageHeader
= BufferGetPage(buffer
);
44 offnum
= PageAddItem(pageHeader
, (Item
) tuple
->t_data
,
45 tuple
->t_len
, InvalidOffsetNumber
, false, true);
47 if (offnum
== InvalidOffsetNumber
)
48 elog(PANIC
, "failed to add tuple to page");
50 /* Update tuple->t_self to the actual position where it was stored */
51 ItemPointerSet(&(tuple
->t_self
), BufferGetBlockNumber(buffer
), offnum
);
53 /* Insert the correct position into CTID of the stored tuple, too */
54 itemId
= PageGetItemId(pageHeader
, offnum
);
55 item
= PageGetItem(pageHeader
, itemId
);
56 ((HeapTupleHeader
) item
)->t_ctid
= tuple
->t_self
;
60 * RelationGetBufferForTuple
62 * Returns pinned and exclusive-locked buffer of a page in given relation
63 * with free space >= given len.
65 * If otherBuffer is not InvalidBuffer, then it references a previously
66 * pinned buffer of another page in the same relation; on return, this
67 * buffer will also be exclusive-locked. (This case is used by heap_update;
68 * the otherBuffer contains the tuple being updated.)
70 * The reason for passing otherBuffer is that if two backends are doing
71 * concurrent heap_update operations, a deadlock could occur if they try
72 * to lock the same two buffers in opposite orders. To ensure that this
73 * can't happen, we impose the rule that buffers of a relation must be
74 * locked in increasing page number order. This is most conveniently done
75 * by having RelationGetBufferForTuple lock them both, with suitable care
78 * NOTE: it is unlikely, but not quite impossible, for otherBuffer to be the
79 * same buffer we select for insertion of the new tuple (this could only
80 * happen if space is freed in that page after heap_update finds there's not
81 * enough there). In that case, the page will be pinned and locked only once.
83 * If use_fsm is true (the normal case), we use FSM to help us find free
84 * space. If use_fsm is false, we always append a new empty page to the
85 * end of the relation if the tuple won't fit on the current target page.
86 * This can save some cycles when we know the relation is new and doesn't
87 * contain useful amounts of free space.
89 * The use_fsm = false case is also useful for non-WAL-logged additions to a
90 * relation, if the caller holds exclusive lock and is careful to invalidate
91 * relation->rd_targblock before the first insertion --- that ensures that
92 * all insertions will occur into newly added pages and not be intermixed
93 * with tuples from other transactions. That way, a crash can't risk losing
94 * any committed data of other transactions. (See heap_insert's comments
95 * for additional constraints needed for safe usage of this behavior.)
97 * We always try to avoid filling existing pages further than the fillfactor.
98 * This is OK since this routine is not consulted when updating a tuple and
99 * keeping it on the same page, which is the scenario fillfactor is meant
100 * to reserve space for.
102 * ereport(ERROR) is allowed here, so this routine *must* be called
103 * before any (unlogged) changes are made in buffer pool.
106 RelationGetBufferForTuple(Relation relation
, Size len
,
107 Buffer otherBuffer
, bool use_fsm
)
109 Buffer buffer
= InvalidBuffer
;
113 BlockNumber targetBlock
,
117 len
= MAXALIGN(len
); /* be conservative */
120 * If we're gonna fail for oversize tuple, do it right away
122 if (len
> MaxHeapTupleSize
)
124 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED
),
125 errmsg("row is too big: size %lu, maximum size %lu",
127 (unsigned long) MaxHeapTupleSize
)));
129 /* Compute desired extra freespace due to fillfactor option */
130 saveFreeSpace
= RelationGetTargetPageFreeSpace(relation
,
131 HEAP_DEFAULT_FILLFACTOR
);
133 if (otherBuffer
!= InvalidBuffer
)
134 otherBlock
= BufferGetBlockNumber(otherBuffer
);
136 otherBlock
= InvalidBlockNumber
; /* just to keep compiler quiet */
139 * We first try to put the tuple on the same page we last inserted a tuple
140 * on, as cached in the relcache entry. If that doesn't work, we ask the
141 * shared Free Space Map to locate a suitable page. Since the FSM's info
142 * might be out of date, we have to be prepared to loop around and retry
143 * multiple times. (To insure this isn't an infinite loop, we must update
144 * the FSM with the correct amount of free space on each page that proves
145 * not to be suitable.) If the FSM has no record of a page with enough
146 * free space, we give up and extend the relation.
148 * When use_fsm is false, we either put the tuple onto the existing target
149 * page or extend the relation.
151 if (len
+ saveFreeSpace
<= MaxHeapTupleSize
)
152 targetBlock
= relation
->rd_targblock
;
155 /* can't fit, don't screw up FSM request tracking by trying */
156 targetBlock
= InvalidBlockNumber
;
160 if (targetBlock
== InvalidBlockNumber
&& use_fsm
)
163 * We have no cached target page, so ask the FSM for an initial
166 targetBlock
= GetPageWithFreeSpace(relation
, len
+ saveFreeSpace
);
169 * If the FSM knows nothing of the rel, try the last page before we
170 * give up and extend. This avoids one-tuple-per-page syndrome during
171 * bootstrapping or in a recently-started system.
173 if (targetBlock
== InvalidBlockNumber
)
175 BlockNumber nblocks
= RelationGetNumberOfBlocks(relation
);
178 targetBlock
= nblocks
- 1;
182 while (targetBlock
!= InvalidBlockNumber
)
185 * Read and exclusive-lock the target block, as well as the other
186 * block if one was given, taking suitable care with lock ordering and
187 * the possibility they are the same block.
189 if (otherBuffer
== InvalidBuffer
)
192 buffer
= ReadBuffer(relation
, targetBlock
);
193 LockBuffer(buffer
, BUFFER_LOCK_EXCLUSIVE
);
195 else if (otherBlock
== targetBlock
)
198 buffer
= otherBuffer
;
199 LockBuffer(buffer
, BUFFER_LOCK_EXCLUSIVE
);
201 else if (otherBlock
< targetBlock
)
203 /* lock other buffer first */
204 buffer
= ReadBuffer(relation
, targetBlock
);
205 LockBuffer(otherBuffer
, BUFFER_LOCK_EXCLUSIVE
);
206 LockBuffer(buffer
, BUFFER_LOCK_EXCLUSIVE
);
210 /* lock target buffer first */
211 buffer
= ReadBuffer(relation
, targetBlock
);
212 LockBuffer(buffer
, BUFFER_LOCK_EXCLUSIVE
);
213 LockBuffer(otherBuffer
, BUFFER_LOCK_EXCLUSIVE
);
217 * Now we can check to see if there's enough free space here. If so,
220 page
= BufferGetPage(buffer
);
221 pageFreeSpace
= PageGetHeapFreeSpace(page
);
222 if (len
+ saveFreeSpace
<= pageFreeSpace
)
224 /* use this page as future insert target, too */
225 relation
->rd_targblock
= targetBlock
;
230 * Not enough space, so we must give up our page locks and pin (if
231 * any) and prepare to look elsewhere. We don't care which order we
232 * unlock the two buffers in, so this can be slightly simpler than the
235 LockBuffer(buffer
, BUFFER_LOCK_UNLOCK
);
236 if (otherBuffer
== InvalidBuffer
)
237 ReleaseBuffer(buffer
);
238 else if (otherBlock
!= targetBlock
)
240 LockBuffer(otherBuffer
, BUFFER_LOCK_UNLOCK
);
241 ReleaseBuffer(buffer
);
244 /* Without FSM, always fall out of the loop and extend */
249 * Update FSM as to condition of this page, and ask for another page
252 targetBlock
= RecordAndGetPageWithFreeSpace(relation
,
255 len
+ saveFreeSpace
);
259 * Have to extend the relation.
261 * We have to use a lock to ensure no one else is extending the rel at the
262 * same time, else we will both try to initialize the same new page. We
263 * can skip locking for new or temp relations, however, since no one else
264 * could be accessing them.
266 needLock
= !RELATION_IS_LOCAL(relation
);
269 LockRelationForExtension(relation
, ExclusiveLock
);
272 * XXX This does an lseek - rather expensive - but at the moment it is the
273 * only way to accurately determine how many blocks are in a relation. Is
274 * it worth keeping an accurate file length in shared memory someplace,
275 * rather than relying on the kernel to do it for us?
277 buffer
= ReadBuffer(relation
, P_NEW
);
280 * We can be certain that locking the otherBuffer first is OK, since it
281 * must have a lower page number.
283 if (otherBuffer
!= InvalidBuffer
)
284 LockBuffer(otherBuffer
, BUFFER_LOCK_EXCLUSIVE
);
287 * Now acquire lock on the new page.
289 LockBuffer(buffer
, BUFFER_LOCK_EXCLUSIVE
);
292 * Release the file-extension lock; it's now OK for someone else to extend
293 * the relation some more. Note that we cannot release this lock before
294 * we have buffer lock on the new page, or we risk a race condition
295 * against vacuumlazy.c --- see comments therein.
298 UnlockRelationForExtension(relation
, ExclusiveLock
);
301 * We need to initialize the empty new page. Double-check that it really
302 * is empty (this should never happen, but if it does we don't want to
303 * risk wiping out valid data).
305 page
= BufferGetPage(buffer
);
307 if (!PageIsNew(page
))
308 elog(ERROR
, "page %u of relation \"%s\" should be empty but is not",
309 BufferGetBlockNumber(buffer
),
310 RelationGetRelationName(relation
));
312 PageInit(page
, BufferGetPageSize(buffer
), 0);
314 if (len
> PageGetHeapFreeSpace(page
))
316 /* We should not get here given the test at the top */
317 elog(PANIC
, "tuple is too big: size %lu", (unsigned long) len
);
321 * Remember the new page as our target for future insertions.
323 * XXX should we enter the new page into the free space map immediately,
324 * or just keep it for this backend's exclusive use in the short run
325 * (until VACUUM sees it)? Seems to depend on whether you expect the
326 * current backend to make more insertions or not, which is probably a
327 * good bet most of the time. So for now, don't add it to FSM yet.
329 relation
->rd_targblock
= BufferGetBlockNumber(buffer
);