1 /*-------------------------------------------------------------------------
4 * BTree-specific page management code for the Postgres btree access
7 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtpage.c,v 1.53 2001/07/15 22:48:16 tgl Exp $
15 * Postgres btree pages look like ordinary relation pages. The opaque
16 * data at high addresses includes pointers to left and right siblings
17 * and flag data describing page state. The first page in a btree, page
18 * zero, is special -- it stores meta-information describing the tree.
19 * Pages one and higher store the actual tree data.
21 *-------------------------------------------------------------------------
27 #include "access/nbtree.h"
28 #include "miscadmin.h"
29 #include "storage/lmgr.h"
31 extern bool FixBTree; /* comments in nbtree.c */
32 extern Buffer _bt_fixroot(Relation rel, Buffer oldrootbuf, bool release);
35 * We use high-concurrency locking on btrees. There are two cases in
36 * which we don't do locking. One is when we're building the btree.
37 * Since the creating transaction has not committed, no one can see
38 * the index, and there's no reason to share locks. The second case
39 * is when we're just starting up the database system. We use some
40 * special-purpose initialization code in the relation cache manager
41 * (see utils/cache/relcache.c) to allow us to do indexed scans on
42 * the system catalogs before we'd normally be able to. This happens
43 * before the lock table is fully initialized, so we can't use it.
44 * Strictly speaking, this violates 2pl, but we don't do 2pl on the
45 * system catalogs anyway, so I declare this to be okay.
48 #define USELOCKING (!BuildingBtree && !IsInitProcessingMode())
51 * _bt_metapinit() -- Initialize the metadata page of a btree.
54 _bt_metapinit(Relation rel)
61 /* can't be sharing this with anyone, now... */
63 LockRelation(rel, AccessExclusiveLock);
65 if (RelationGetNumberOfBlocks(rel) != 0)
66 elog(ERROR, "Cannot initialize non-empty btree %s",
67 RelationGetRelationName(rel));
69 buf = ReadBuffer(rel, P_NEW);
70 pg = BufferGetPage(buf);
71 _bt_pageinit(pg, BufferGetPageSize(buf));
73 metad.btm_magic = BTREE_MAGIC;
74 metad.btm_version = BTREE_VERSION;
75 metad.btm_root = P_NONE;
77 memcpy((char *) BTPageGetMeta(pg), (char *) &metad, sizeof(metad));
79 op = (BTPageOpaque) PageGetSpecialPointer(pg);
80 op->btpo_flags = BTP_META;
86 UnlockRelation(rel, AccessExclusiveLock);
90 * _bt_getroot() -- Get the root page of the btree.
92 * Since the root page can move around the btree file, we have to read
93 * its location from the metadata page, and then read the root page
94 * itself. If no root page exists yet, we have to create one. The
95 * standard class of race conditions exists here; I think I covered
96 * them all in the Hopi Indian rain dance of lock requests below.
98 * The access type parameter (BT_READ or BT_WRITE) controls whether
99 * a new root page will be created or not. If access = BT_READ,
100 * and no root page exists, we just return InvalidBuffer. For
101 * BT_WRITE, we try to create the root page if it doesn't exist.
102 * NOTE that the returned root page will have only a read lock set
103 * on it even if access = BT_WRITE!
105 * On successful return, the root page is pinned and read-locked.
106 * The metadata page is not locked or pinned on exit.
109 _bt_getroot(Relation rel, int access)
113 BTPageOpaque metaopaque;
116 BTPageOpaque rootopaque;
117 BlockNumber rootblkno;
118 BTMetaPageData *metad;
120 metabuf = _bt_getbuf(rel, BTREE_METAPAGE, BT_READ);
121 metapg = BufferGetPage(metabuf);
122 metaopaque = (BTPageOpaque) PageGetSpecialPointer(metapg);
123 metad = BTPageGetMeta(metapg);
125 if (!(metaopaque->btpo_flags & BTP_META) ||
126 metad->btm_magic != BTREE_MAGIC)
127 elog(ERROR, "Index %s is not a btree",
128 RelationGetRelationName(rel));
130 if (metad->btm_version != BTREE_VERSION)
131 elog(ERROR, "Version mismatch on %s: version %d file, version %d code",
132 RelationGetRelationName(rel),
133 metad->btm_version, BTREE_VERSION);
135 /* if no root page initialized yet, do it */
136 if (metad->btm_root == P_NONE)
138 /* If access = BT_READ, caller doesn't want us to create root yet */
139 if (access == BT_READ)
141 _bt_relbuf(rel, metabuf);
142 return InvalidBuffer;
145 /* trade in our read lock for a write lock */
146 LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
147 LockBuffer(metabuf, BT_WRITE);
150 * Race condition: if someone else initialized the metadata
151 * between the time we released the read lock and acquired the
152 * write lock, above, we must avoid doing it again.
154 if (metad->btm_root == P_NONE)
158 * Get, initialize, write, and leave a lock of the appropriate
159 * type on the new root page. Since this is the first page in
160 * the tree, it's a leaf as well as the root.
162 rootbuf = _bt_getbuf(rel, P_NEW, BT_WRITE);
163 rootblkno = BufferGetBlockNumber(rootbuf);
164 rootpage = BufferGetPage(rootbuf);
166 /* NO ELOG(ERROR) till meta is updated */
167 START_CRIT_SECTION();
169 metad->btm_root = rootblkno;
170 metad->btm_level = 1;
172 _bt_pageinit(rootpage, BufferGetPageSize(rootbuf));
173 rootopaque = (BTPageOpaque) PageGetSpecialPointer(rootpage);
174 rootopaque->btpo_flags |= (BTP_LEAF | BTP_ROOT);
178 xl_btree_newroot xlrec;
182 xlrec.node = rel->rd_node;
184 BlockIdSet(&(xlrec.rootblk), rootblkno);
185 rdata.buffer = InvalidBuffer;
186 rdata.data = (char *) &xlrec;
187 rdata.len = SizeOfBtreeNewroot;
190 recptr = XLogInsert(RM_BTREE_ID,
191 XLOG_BTREE_NEWROOT | XLOG_BTREE_LEAF, &rdata);
193 PageSetLSN(rootpage, recptr);
194 PageSetSUI(rootpage, ThisStartUpID);
195 PageSetLSN(metapg, recptr);
196 PageSetSUI(metapg, ThisStartUpID);
201 _bt_wrtnorelbuf(rel, rootbuf);
203 /* swap write lock for read lock */
204 LockBuffer(rootbuf, BUFFER_LOCK_UNLOCK);
205 LockBuffer(rootbuf, BT_READ);
207 /* okay, metadata is correct, write and release it */
208 _bt_wrtbuf(rel, metabuf);
214 * Metadata initialized by someone else. In order to
215 * guarantee no deadlocks, we have to release the metadata
216 * page and start all over again.
218 _bt_relbuf(rel, metabuf);
219 return _bt_getroot(rel, access);
224 rootblkno = metad->btm_root;
225 _bt_relbuf(rel, metabuf); /* done with the meta page */
227 rootbuf = _bt_getbuf(rel, rootblkno, BT_READ);
231 * Race condition: If the root page split between the time we looked
232 * at the metadata page and got the root buffer, then we got the wrong
233 * buffer. Release it and try again.
235 rootpage = BufferGetPage(rootbuf);
236 rootopaque = (BTPageOpaque) PageGetSpecialPointer(rootpage);
238 if (!P_ISROOT(rootopaque))
242 * It happened, but if root page splitter failed to create new
243 * root page then we'll go in loop trying to call _bt_getroot
251 if (BTreeInvalidParent(rootopaque)) /* unupdated! */
253 LockBuffer(rootbuf, BUFFER_LOCK_UNLOCK);
254 LockBuffer(rootbuf, BT_WRITE);
256 /* handle concurrent fix of root page */
257 if (BTreeInvalidParent(rootopaque)) /* unupdated! */
259 elog(NOTICE, "bt_getroot[%s]: fixing root page", RelationGetRelationName(rel));
260 newrootbuf = _bt_fixroot(rel, rootbuf, true);
261 LockBuffer(newrootbuf, BUFFER_LOCK_UNLOCK);
262 LockBuffer(newrootbuf, BT_READ);
263 rootbuf = newrootbuf;
264 rootpage = BufferGetPage(rootbuf);
265 rootopaque = (BTPageOpaque) PageGetSpecialPointer(rootpage);
266 /* New root might be splitted while changing lock */
267 if (P_ISROOT(rootopaque))
269 /* rootbuf is read locked */
274 /* someone else already fixed root */
275 LockBuffer(rootbuf, BUFFER_LOCK_UNLOCK);
276 LockBuffer(rootbuf, BT_READ);
281 * Ok, here we have old root page with btpo_parent pointing to
282 * upper level - check parent page because of there is good
283 * chance that parent is root page.
285 newrootbuf = _bt_getbuf(rel, rootopaque->btpo_parent, BT_READ);
286 _bt_relbuf(rel, rootbuf);
287 rootbuf = newrootbuf;
288 rootpage = BufferGetPage(rootbuf);
289 rootopaque = (BTPageOpaque) PageGetSpecialPointer(rootpage);
290 if (P_ISROOT(rootopaque))
296 _bt_relbuf(rel, rootbuf);
297 return _bt_getroot(rel, access);
301 * By here, we have a correct lock on the root block, its reference
302 * count is correct, and we have no lock set on the metadata page.
303 * Return the root block.
309 * _bt_getbuf() -- Get a buffer by block number for read or write.
311 * When this routine returns, the appropriate lock is set on the
312 * requested buffer and its reference count has been incremented
313 * (ie, the buffer is "locked and pinned").
316 _bt_getbuf(Relation rel, BlockNumber blkno, int access)
322 /* Read an existing block of the relation */
323 buf = ReadBuffer(rel, blkno);
324 LockBuffer(buf, access);
331 * Extend the relation by one page.
333 * Extend bufmgr code is unclean and so we have to use extra locking
336 LockPage(rel, 0, ExclusiveLock);
337 buf = ReadBuffer(rel, blkno);
338 LockBuffer(buf, access);
339 UnlockPage(rel, 0, ExclusiveLock);
341 /* Initialize the new page before returning it */
342 page = BufferGetPage(buf);
343 _bt_pageinit(page, BufferGetPageSize(buf));
346 /* ref count and lock type are correct */
351 * _bt_relbuf() -- release a locked buffer.
353 * Lock and pin (refcount) are both dropped. Note that either read or
354 * write lock can be dropped this way, but if we modified the buffer,
355 * this is NOT the right way to release a write lock.
358 _bt_relbuf(Relation rel, Buffer buf)
360 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
365 * _bt_wrtbuf() -- write a btree page to disk.
367 * This routine releases the lock held on the buffer and our refcount
368 * for it. It is an error to call _bt_wrtbuf() without a write lock
369 * and a pin on the buffer.
371 * NOTE: actually, the buffer manager just marks the shared buffer page
372 * dirty here, the real I/O happens later. Since we can't persuade the
373 * Unix kernel to schedule disk writes in a particular order, there's not
374 * much point in worrying about this. The most we can say is that all the
375 * writes will occur before commit.
378 _bt_wrtbuf(Relation rel, Buffer buf)
380 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
385 * _bt_wrtnorelbuf() -- write a btree page to disk, but do not release
386 * our reference or lock.
388 * It is an error to call _bt_wrtnorelbuf() without a write lock
389 * and a pin on the buffer.
394 _bt_wrtnorelbuf(Relation rel, Buffer buf)
396 WriteNoReleaseBuffer(buf);
400 * _bt_pageinit() -- Initialize a new page.
403 _bt_pageinit(Page page, Size size)
407 * Cargo_cult programming -- don't really need this to be zero, but
408 * creating new pages is an infrequent occurrence and it makes me feel
409 * good when I know they're empty.
412 MemSet(page, 0, size);
414 PageInit(page, size, sizeof(BTPageOpaqueData));
415 ((BTPageOpaque) PageGetSpecialPointer(page))->btpo_parent =
420 * _bt_metaproot() -- Change the root page of the btree.
422 * Lehman and Yao require that the root page move around in order to
423 * guarantee deadlock-free short-term, fine-granularity locking. When
424 * we split the root page, we record the new parent in the metadata page
425 * for the relation. This routine does the work.
427 * No direct preconditions, but if you don't have the write lock on
428 * at least the old root page when you call this, you're making a big
429 * mistake. On exit, metapage data is correct and we no longer have
430 * a pin or lock on the metapage.
433 _bt_metaproot(Relation rel, BlockNumber rootbknum, int level)
437 BTPageOpaque metaopaque;
438 BTMetaPageData *metad;
440 metabuf = _bt_getbuf(rel, BTREE_METAPAGE, BT_WRITE);
441 metap = BufferGetPage(metabuf);
442 metaopaque = (BTPageOpaque) PageGetSpecialPointer(metap);
443 Assert(metaopaque->btpo_flags & BTP_META);
444 metad = BTPageGetMeta(metap);
445 metad->btm_root = rootbknum;
446 if (level == 0) /* called from _do_insert */
447 metad->btm_level += 1;
449 metad->btm_level = level; /* called from btsort */
450 _bt_wrtbuf(rel, metabuf);
454 * Delete an item from a btree page.
456 * This routine assumes that the caller has pinned and locked the buffer,
457 * and will write the buffer afterwards.
460 _bt_itemdel(Relation rel, Buffer buf, ItemPointer tid)
462 Page page = BufferGetPage(buf);
465 offno = ItemPointerGetOffsetNumber(tid);
467 START_CRIT_SECTION();
469 PageIndexTupleDelete(page, offno);
473 xl_btree_delete xlrec;
475 XLogRecData rdata[2];
477 xlrec.target.node = rel->rd_node;
478 xlrec.target.tid = *tid;
479 rdata[0].buffer = InvalidBuffer;
480 rdata[0].data = (char *) &xlrec;
481 rdata[0].len = SizeOfBtreeDelete;
482 rdata[0].next = &(rdata[1]);
484 rdata[1].buffer = buf;
485 rdata[1].data = NULL;
487 rdata[1].next = NULL;
489 recptr = XLogInsert(RM_BTREE_ID, XLOG_BTREE_DELETE, rdata);
491 PageSetLSN(page, recptr);
492 PageSetSUI(page, ThisStartUpID);