lmgr.c 26.2 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * lmgr.c
4
 *	  POSTGRES lock manager code
5
 *
6
 * Portions Copyright (c) 2006-2008, Greenplum inc
7
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
B
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
9
 * Portions Copyright (c) 1994, Regents of the University of California
10 11 12
 *
 *
 * IDENTIFICATION
13
 *	  src/backend/storage/lmgr/lmgr.c
14 15 16
 *
 *-------------------------------------------------------------------------
 */
17

18
#include "postgres.h"
19

20
#include "access/subtrans.h"
21 22
#include "access/transam.h"
#include "access/xact.h"
23
#include "catalog/catalog.h"
24
#include "miscadmin.h"
25
#include "storage/lmgr.h"
26
#include "storage/procarray.h"
27
#include "utils/inval.h"
28

29 30
#include "access/heapam.h"
#include "catalog/namespace.h"
31
#include "cdb/cdbvars.h"
32
#include "utils/lsyscache.h"        /* CDB: get_rel_namespace() */
33 34


35 36 37 38 39 40 41 42 43 44
/*
 * Struct to hold context info for transaction lock waits.
 *
 * 'oper' is the operation that needs to wait for the other transaction; 'rel'
 * and 'ctid' specify the address of the tuple being waited for.
 */
typedef struct XactLockTableWaitInfo
{
	XLTW_Oper	oper;
	Relation	rel;
B
Bruce Momjian 已提交
45
	ItemPointer ctid;
46 47 48 49
} XactLockTableWaitInfo;

static void XactLockTableWaitErrorCb(void *arg);

50
/*
B
Bruce Momjian 已提交
51
 * RelationInitLockInfo
52
 *		Initializes the lock information in a relation descriptor.
53 54
 *
 *		relcache.c must call this during creation of any reldesc.
55 56 57 58
 */
void
RelationInitLockInfo(Relation relation)
{
59
	Assert(RelationIsValid(relation));
60
	Assert(OidIsValid(RelationGetRelid(relation)));
61

62
	relation->rd_lockInfo.lockRelId.relId = RelationGetRelid(relation);
63

64
	if (relation->rd_rel->relisshared)
65
		relation->rd_lockInfo.lockRelId.dbId = InvalidOid;
66
	else
67
		relation->rd_lockInfo.lockRelId.dbId = MyDatabaseId;
68 69
}

70 71 72 73 74 75 76
/*
 * SetLocktagRelationOid
 *		Set up a locktag for a relation, given only relation OID
 */
static inline void
SetLocktagRelationOid(LOCKTAG *tag, Oid relid)
{
B
Bruce Momjian 已提交
77
	Oid			dbid;
78 79 80 81 82 83 84 85 86 87 88 89

	if (IsSharedRelation(relid))
		dbid = InvalidOid;
	else
		dbid = MyDatabaseId;

	SET_LOCKTAG_RELATION(*tag, dbid, relid);
}

/*
 *		LockRelationOid
 *
B
Bruce Momjian 已提交
90
 * Lock a relation given only its OID.  This should generally be used
91 92 93 94 95 96
 * before attempting to open the relation's relcache entry.
 */
void
LockRelationOid(Oid relid, LOCKMODE lockmode)
{
	LOCKTAG		tag;
97
	LOCALLOCK  *locallock;
98 99 100 101
	LockAcquireResult res;

	SetLocktagRelationOid(&tag, relid);

102
	res = LockAcquireExtended(&tag, lockmode, false, false, true, &locallock);
103 104

	/*
B
Bruce Momjian 已提交
105 106
	 * Now that we have the lock, check for invalidation messages, so that we
	 * will update or flush any stale relcache entry before we try to use it.
107 108 109 110 111
	 * RangeVarGetRelid() specifically relies on us for this.  We can skip
	 * this in the not-uncommon case that we already had the same type of lock
	 * being requested, since then no one else could have modified the
	 * relcache entry in an undesirable way.  (In the case where our own xact
	 * modifies the rel, the relcache update happens via
B
Bruce Momjian 已提交
112
	 * CommandCounterIncrement, not here.)
113 114 115 116 117 118
	 *
	 * However, in corner cases where code acts on tables (usually catalogs)
	 * recursively, we might get here while still processing invalidation
	 * messages in some outer execution of this function or a sibling.  The
	 * "cleared" status of the lock tells us whether we really are done
	 * absorbing relevant inval messages.
119
	 */
120 121
	if (res != LOCKACQUIRE_ALREADY_CLEAR)
	{
122
		AcceptInvalidationMessages();
123 124
		MarkLockClear(locallock);
	}
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
}

/*
 *		ConditionalLockRelationOid
 *
 * As above, but only lock if we can get the lock without blocking.
 * Returns TRUE iff the lock was acquired.
 *
 * NOTE: we do not currently need conditional versions of all the
 * LockXXX routines in this file, but they could easily be added if needed.
 */
bool
ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
{
	LOCKTAG		tag;
140
	LOCALLOCK  *locallock;
141 142 143 144
	LockAcquireResult res;

	SetLocktagRelationOid(&tag, relid);

145
	res = LockAcquireExtended(&tag, lockmode, false, true, true, &locallock);
146 147 148 149 150

	if (res == LOCKACQUIRE_NOT_AVAIL)
		return false;

	/*
B
Bruce Momjian 已提交
151 152
	 * Now that we have the lock, check for invalidation messages; see notes
	 * in LockRelationOid.
153
	 */
154 155
	if (res != LOCKACQUIRE_ALREADY_CLEAR)
	{
156
		AcceptInvalidationMessages();
157 158
		MarkLockClear(locallock);
	}
159 160 161 162 163 164 165

	return true;
}

/*
 *		UnlockRelationId
 *
166 167
 * Unlock, given a LockRelId.  This is preferred over UnlockRelationOid
 * for speed reasons.
168 169 170 171 172 173 174 175 176 177 178
 */
void
UnlockRelationId(LockRelId *relid, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_RELATION(tag, relid->dbId, relid->relId);

	LockRelease(&tag, lockmode, false);
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
/*
 *		UnlockRelationOid
 *
 * Unlock, given only a relation Oid.  Use UnlockRelationId if you can.
 */
void
UnlockRelationOid(Oid relid, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SetLocktagRelationOid(&tag, relid);

	LockRelease(&tag, lockmode, false);
}

194
/*
V
Vadim B. Mikheev 已提交
195
 *		LockRelation
196 197 198 199
 *
 * This is a convenience routine for acquiring an additional lock on an
 * already-open relation.  Never try to do "relation_open(foo, NoLock)"
 * and then lock with this.
200 201
 */
void
V
Vadim B. Mikheev 已提交
202
LockRelation(Relation relation, LOCKMODE lockmode)
203
{
V
Vadim B. Mikheev 已提交
204
	LOCKTAG		tag;
205
	LOCALLOCK  *locallock;
206
	LockAcquireResult res;
207

208 209 210
	SET_LOCKTAG_RELATION(tag,
						 relation->rd_lockInfo.lockRelId.dbId,
						 relation->rd_lockInfo.lockRelId.relId);
V
Vadim B. Mikheev 已提交
211

212
	res = LockAcquireExtended(&tag, lockmode, false, false, true, &locallock);
213 214

	/*
B
Bruce Momjian 已提交
215 216
	 * Now that we have the lock, check for invalidation messages; see notes
	 * in LockRelationOid.
217
	 */
218 219
	if (res != LOCKACQUIRE_ALREADY_CLEAR)
	{
220
		AcceptInvalidationMessages();
221 222
		MarkLockClear(locallock);
	}
V
Vadim B. Mikheev 已提交
223
}
224

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
/*
 *		LockRelationNoWait
 *
 * Similar to LockReation, except that it is not waiting
 * for the lock if it is not available.
 *
 */
LockAcquireResult
LockRelationNoWait(Relation relation, LOCKMODE lockmode)
{
	LOCKTAG		tag;
	LockAcquireResult res;

	SET_LOCKTAG_RELATION(tag,
						 relation->rd_lockInfo.lockRelId.dbId,
						 relation->rd_lockInfo.lockRelId.relId);

	res = LockAcquire(&tag, lockmode, false, true);

	/*
	 * Now that we have the lock, check for invalidation messages; see notes
	 * in LockRelationOid.
	 */
	if (res != LOCKACQUIRE_ALREADY_HELD)
		AcceptInvalidationMessages();

	return res;
}

254 255 256
/*
 *		ConditionalLockRelation
 *
257 258 259
 * This is a convenience routine for acquiring an additional lock on an
 * already-open relation.  Never try to do "relation_open(foo, NoLock)"
 * and then lock with this.
260 261 262 263 264
 */
bool
ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
{
	LOCKTAG		tag;
265
	LOCALLOCK  *locallock;
266
	LockAcquireResult res;
267

268 269 270
	SET_LOCKTAG_RELATION(tag,
						 relation->rd_lockInfo.lockRelId.dbId,
						 relation->rd_lockInfo.lockRelId.relId);
271

272
	res = LockAcquireExtended(&tag, lockmode, false, true, true, &locallock);
273 274

	if (res == LOCKACQUIRE_NOT_AVAIL)
275 276 277
		return false;

	/*
B
Bruce Momjian 已提交
278 279
	 * Now that we have the lock, check for invalidation messages; see notes
	 * in LockRelationOid.
280
	 */
281 282
	if (res != LOCKACQUIRE_ALREADY_CLEAR)
	{
283
		AcceptInvalidationMessages();
284 285
		MarkLockClear(locallock);
	}
286 287 288 289

	return true;
}

290
/*
V
Vadim B. Mikheev 已提交
291
 *		UnlockRelation
292 293 294
 *
 * This is a convenience routine for unlocking a relation without also
 * closing it.
295 296
 */
void
V
Vadim B. Mikheev 已提交
297
UnlockRelation(Relation relation, LOCKMODE lockmode)
298
{
V
Vadim B. Mikheev 已提交
299
	LOCKTAG		tag;
300

301 302 303
	SET_LOCKTAG_RELATION(tag,
						 relation->rd_lockInfo.lockRelId.dbId,
						 relation->rd_lockInfo.lockRelId.relId);
304

305
	LockRelease(&tag, lockmode, false);
306 307
}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
/*
 *		LockHasWaitersRelation
 *
 * This is a functiion to check if someone else is waiting on a
 * lock, we are currently holding.
 */
bool
LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_RELATION(tag,
						 relation->rd_lockInfo.lockRelId.dbId,
						 relation->rd_lockInfo.lockRelId.relId);

	return LockHasWaiters(&tag, lockmode, false);
}

326
/*
327
 *		LockRelationIdForSession
328
 *
B
Bruce Momjian 已提交
329
 * This routine grabs a session-level lock on the target relation.  The
330
 * session lock persists across transaction boundaries.  It will be removed
331
 * when UnlockRelationIdForSession() is called, or if an ereport(ERROR) occurs,
332 333 334 335 336 337 338
 * or if the backend exits.
 *
 * Note that one should also grab a transaction-level lock on the rel
 * in any transaction that actually uses the rel, to ensure that the
 * relcache entry is up to date.
 */
void
339
LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
340 341 342
{
	LOCKTAG		tag;

343
	SET_LOCKTAG_RELATION(tag, relid->dbId, relid->relId);
344

345
	(void) LockAcquire(&tag, lockmode, true, false);
346 347 348
}

/*
349
 *		UnlockRelationIdForSession
350 351
 */
void
352
UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
353 354 355
{
	LOCKTAG		tag;

356
	SET_LOCKTAG_RELATION(tag, relid->dbId, relid->relId);
357

358
	LockRelease(&tag, lockmode, true);
V
Vadim B. Mikheev 已提交
359
}
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
/*
 *		LockRelationForExtension
 *
 * This lock tag is used to interlock addition of pages to relations.
 * We need such locking because bufmgr/smgr definition of P_NEW is not
 * race-condition-proof.
 *
 * We assume the caller is already holding some type of regular lock on
 * the relation, so no AcceptInvalidationMessages call is needed here.
 */
void
LockRelationForExtension(Relation relation, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_RELATION_EXTEND(tag,
								relation->rd_lockInfo.lockRelId.dbId,
								relation->rd_lockInfo.lockRelId.relId);

380
	(void) LockAcquire(&tag, lockmode, false, false);
381 382 383 384 385 386 387 388 389 390 391 392 393 394
}

/*
 *		UnlockRelationForExtension
 */
void
UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_RELATION_EXTEND(tag,
								relation->rd_lockInfo.lockRelId.dbId,
								relation->rd_lockInfo.lockRelId.relId);

395
	LockRelease(&tag, lockmode, false);
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
LockAcquireResult
LockRelationAppendOnlySegmentFile(RelFileNode *relFileNode, int32 segno, LOCKMODE lockmode, bool dontWait)
{
	LOCKTAG		tag;

	SET_LOCKTAG_RELATION_APPENDONLY_SEGMENT_FILE(tag,
						 relFileNode->dbNode,
						 relFileNode->relNode,
						 segno);

	return LockAcquire(&tag, lockmode, false, dontWait);
}

void
UnlockRelationAppendOnlySegmentFile(RelFileNode *relFileNode, int32 segno, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_RELATION_APPENDONLY_SEGMENT_FILE(tag,
						 relFileNode->dbNode,
						 relFileNode->relNode,
						 segno);

	LockRelease(&tag, lockmode, false);
}


425
/*
V
Vadim B. Mikheev 已提交
426
 *		LockPage
427 428
 *
 * Obtain a page-level lock.  This is currently used by some index access
429
 * methods to lock individual index pages.
430 431
 */
void
V
Vadim B. Mikheev 已提交
432
LockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
433
{
V
Vadim B. Mikheev 已提交
434
	LOCKTAG		tag;
435

436 437 438 439
	SET_LOCKTAG_PAGE(tag,
					 relation->rd_lockInfo.lockRelId.dbId,
					 relation->rd_lockInfo.lockRelId.relId,
					 blkno);
V
Vadim B. Mikheev 已提交
440

441
	(void) LockAcquire(&tag, lockmode, false, false);
V
Vadim B. Mikheev 已提交
442
}
443

444 445 446 447 448 449 450 451 452 453 454
/*
 *		ConditionalLockPage
 *
 * As above, but only lock if we can get the lock without blocking.
 * Returns TRUE iff the lock was acquired.
 */
bool
ConditionalLockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
{
	LOCKTAG		tag;

455 456 457 458
	SET_LOCKTAG_PAGE(tag,
					 relation->rd_lockInfo.lockRelId.dbId,
					 relation->rd_lockInfo.lockRelId.relId,
					 blkno);
459

460
	return (LockAcquire(&tag, lockmode, false, true) != LOCKACQUIRE_NOT_AVAIL);
461 462
}

463
/*
V
Vadim B. Mikheev 已提交
464
 *		UnlockPage
465 466
 */
void
V
Vadim B. Mikheev 已提交
467
UnlockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
468
{
V
Vadim B. Mikheev 已提交
469
	LOCKTAG		tag;
470

471 472 473 474
	SET_LOCKTAG_PAGE(tag,
					 relation->rd_lockInfo.lockRelId.dbId,
					 relation->rd_lockInfo.lockRelId.relId,
					 blkno);
475

476
	LockRelease(&tag, lockmode, false);
477 478
}

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
/*
 *		LockTuple
 *
 * Obtain a tuple-level lock.  This is used in a less-than-intuitive fashion
 * because we can't afford to keep a separate lock in shared memory for every
 * tuple.  See heap_lock_tuple before using this!
 */
void
LockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_TUPLE(tag,
					  relation->rd_lockInfo.lockRelId.dbId,
					  relation->rd_lockInfo.lockRelId.relId,
					  ItemPointerGetBlockNumber(tid),
					  ItemPointerGetOffsetNumber(tid));

497
	(void) LockAcquire(&tag, lockmode, false, false);
498 499
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
/*
 *		ConditionalLockTuple
 *
 * As above, but only lock if we can get the lock without blocking.
 * Returns TRUE iff the lock was acquired.
 */
bool
ConditionalLockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_TUPLE(tag,
					  relation->rd_lockInfo.lockRelId.dbId,
					  relation->rd_lockInfo.lockRelId.relId,
					  ItemPointerGetBlockNumber(tid),
					  ItemPointerGetOffsetNumber(tid));

517
	return (LockAcquire(&tag, lockmode, false, true) != LOCKACQUIRE_NOT_AVAIL);
518 519
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533
/*
 *		UnlockTuple
 */
void
UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_TUPLE(tag,
					  relation->rd_lockInfo.lockRelId.dbId,
					  relation->rd_lockInfo.lockRelId.relId,
					  ItemPointerGetBlockNumber(tid),
					  ItemPointerGetOffsetNumber(tid));

534
	LockRelease(&tag, lockmode, false);
535 536
}

537 538 539 540
/*
 *		XactLockTableInsert
 *
 * Insert a lock showing that the given transaction ID is running ---
541 542
 * this is done when an XID is acquired by a transaction or subtransaction.
 * The lock can then be used to wait for the transaction to finish.
543
 */
544
void
V
Vadim B. Mikheev 已提交
545
XactLockTableInsert(TransactionId xid)
546
{
V
Vadim B. Mikheev 已提交
547
	LOCKTAG		tag;
548

549
	SET_LOCKTAG_TRANSACTION(tag, xid);
550

551
	(void) LockAcquire(&tag, ExclusiveLock, false, false);
552 553
}

554 555 556 557 558
/*
 *		XactLockTableDelete
 *
 * Delete the lock showing that the given transaction ID is running.
 * (This is never used for main transaction IDs; those locks are only
B
Bruce Momjian 已提交
559
 * released implicitly at transaction end.  But we do use it for subtrans IDs.)
560 561 562 563 564 565
 */
void
XactLockTableDelete(TransactionId xid)
{
	LOCKTAG		tag;

566
	SET_LOCKTAG_TRANSACTION(tag, xid);
567

568
	LockRelease(&tag, ExclusiveLock, false);
569 570
}

571 572 573
/*
 *		XactLockTableWait
 *
574 575 576
 * Wait for the specified transaction to commit or abort.  If an operation
 * is specified, an error context callback is set up.  If 'oper' is passed as
 * None, no error context callback is set up.
577
 *
578 579 580 581
 * Note that this does the right thing for subtransactions: if we wait on a
 * subtransaction, we will exit as soon as it aborts or its top parent commits.
 * It takes some extra work to ensure this, because to save on shared memory
 * the XID lock of a subtransaction is released when it ends, whether
B
Bruce Momjian 已提交
582
 * successfully or unsuccessfully.  So we have to check if it's "still running"
583
 * and if so wait for its parent.
584
 */
585
void
586 587
XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid,
				  XLTW_Oper oper)
588
{
V
Vadim B. Mikheev 已提交
589
	LOCKTAG		tag;
590 591
	XactLockTableWaitInfo info;
	ErrorContextCallback callback;
592
	bool		first = true;
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

	/*
	 * If an operation is specified, set up our verbose error context
	 * callback.
	 */
	if (oper != XLTW_None)
	{
		Assert(RelationIsValid(rel));
		Assert(ItemPointerIsValid(ctid));

		info.rel = rel;
		info.ctid = ctid;
		info.oper = oper;

		callback.callback = XactLockTableWaitErrorCb;
		callback.arg = &info;
		callback.previous = error_context_stack;
		error_context_stack = &callback;
	}
612

613 614 615
	for (;;)
	{
		Assert(TransactionIdIsValid(xid));
616
		Assert(!TransactionIdEquals(xid, GetTopTransactionIdIfAny()));
617

618
		SET_LOCKTAG_TRANSACTION(tag, xid);
619

620
		(void) LockAcquire(&tag, ShareLock, false, false);
621

622
		LockRelease(&tag, ShareLock, false);
623

624 625
		if (!TransactionIdIsInProgress(xid))
			break;
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

		/*
		 * If the Xid belonged to a subtransaction, then the lock would have
		 * gone away as soon as it was finished; for correct tuple visibility,
		 * the right action is to wait on its parent transaction to go away.
		 * But instead of going levels up one by one, we can just wait for the
		 * topmost transaction to finish with the same end result, which also
		 * incurs less locktable traffic.
		 *
		 * Some uses of this function don't involve tuple visibility -- such
		 * as when building snapshots for logical decoding.  It is possible to
		 * see a transaction in ProcArray before it registers itself in the
		 * locktable.  The topmost transaction in that case is the same xid,
		 * so we try again after a short sleep.  (Don't sleep the first time
		 * through, to avoid slowing down the normal case.)
		 */
		if (!first)
			pg_usleep(1000L);
		first = false;
		xid = SubTransGetTopmostTransaction(xid);
646
	}
647 648 649

	if (oper != XLTW_None)
		error_context_stack = callback.previous;
650
}
651

652 653 654 655 656 657 658 659 660 661
/*
 *		ConditionalXactLockTableWait
 *
 * As above, but only lock if we can get the lock without blocking.
 * Returns TRUE if the lock was acquired.
 */
bool
ConditionalXactLockTableWait(TransactionId xid)
{
	LOCKTAG		tag;
662
	bool		first = true;
663 664 665 666

	for (;;)
	{
		Assert(TransactionIdIsValid(xid));
667
		Assert(!TransactionIdEquals(xid, GetTopTransactionIdIfAny()));
668 669 670

		SET_LOCKTAG_TRANSACTION(tag, xid);

671
		if (LockAcquire(&tag, ShareLock, false, true) == LOCKACQUIRE_NOT_AVAIL)
672 673
			return false;

674
		LockRelease(&tag, ShareLock, false);
675 676 677

		if (!TransactionIdIsInProgress(xid))
			break;
678 679 680 681 682 683

		/* See XactLockTableWait about this case */
		if (!first)
			pg_usleep(1000L);
		first = false;
		xid = SubTransGetTopmostTransaction(xid);
684 685 686 687
	}

	return true;
}
688

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
/*
 * XactLockTableWaitErrorContextCb
 *		Error context callback for transaction lock waits.
 */
static void
XactLockTableWaitErrorCb(void *arg)
{
	XactLockTableWaitInfo *info = (XactLockTableWaitInfo *) arg;

	/*
	 * We would like to print schema name too, but that would require a
	 * syscache lookup.
	 */
	if (info->oper != XLTW_None &&
		ItemPointerIsValid(info->ctid) && RelationIsValid(info->rel))
	{
		const char *cxt;

		switch (info->oper)
		{
			case XLTW_Update:
				cxt = gettext_noop("while updating tuple (%u,%u) in relation \"%s\"");
				break;
			case XLTW_Delete:
				cxt = gettext_noop("while deleting tuple (%u,%u) in relation \"%s\"");
				break;
			case XLTW_Lock:
				cxt = gettext_noop("while locking tuple (%u,%u) in relation \"%s\"");
				break;
			case XLTW_LockUpdated:
				cxt = gettext_noop("while locking updated version (%u,%u) of tuple in relation \"%s\"");
				break;
			case XLTW_InsertIndex:
				cxt = gettext_noop("while inserting index tuple (%u,%u) in relation \"%s\"");
				break;
			case XLTW_InsertIndexUnique:
				cxt = gettext_noop("while checking uniqueness of tuple (%u,%u) in relation \"%s\"");
				break;
			case XLTW_FetchUpdated:
				cxt = gettext_noop("while rechecking updated tuple (%u,%u) in relation \"%s\"");
				break;
			case XLTW_RecheckExclusionConstr:
				cxt = gettext_noop("while checking exclusion constraint on tuple (%u,%u) in relation \"%s\"");
				break;

			default:
				return;
		}

		errcontext(cxt,
				   ItemPointerGetBlockNumber(info->ctid),
				   ItemPointerGetOffsetNumber(info->ctid),
				   RelationGetRelationName(info->rel));
	}
}

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
/*
 * WaitForLockersMultiple
 *		Wait until no transaction holds locks that conflict with the given
 *		locktags at the given lockmode.
 *
 * To do this, obtain the current list of lockers, and wait on their VXIDs
 * until they are finished.
 *
 * Note we don't try to acquire the locks on the given locktags, only the VXIDs
 * of its lock holders; if somebody grabs a conflicting lock on the objects
 * after we obtained our initial list of lockers, we will not wait for them.
 */
void
WaitForLockersMultiple(List *locktags, LOCKMODE lockmode)
{
	List	   *holders = NIL;
	ListCell   *lc;

	/* Done if no locks to wait for */
	if (list_length(locktags) == 0)
		return;

	/* Collect the transactions we need to wait on */
	foreach(lc, locktags)
	{
		LOCKTAG    *locktag = lfirst(lc);

		holders = lappend(holders, GetLockConflicts(locktag, lockmode));
	}

	/*
	 * Note: GetLockConflicts() never reports our own xid, hence we need not
B
Bruce Momjian 已提交
777
	 * check for that.  Also, prepared xacts are not reported, which is fine
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
	 * since they certainly aren't going to do anything anymore.
	 */

	/* Finally wait for each such transaction to complete */
	foreach(lc, holders)
	{
		VirtualTransactionId *lockholders = lfirst(lc);

		while (VirtualTransactionIdIsValid(*lockholders))
		{
			VirtualXactLock(*lockholders, true);
			lockholders++;
		}
	}

	list_free_deep(holders);
}

/*
 * WaitForLockers
 *
 * Same as WaitForLockersMultiple, for a single lock tag.
 */
void
WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode)
{
B
Bruce Momjian 已提交
804
	List	   *l;
805 806 807 808 809 810 811

	l = list_make1(&heaplocktag);
	WaitForLockersMultiple(l, lockmode);
	list_free(l);
}


812 813 814 815
/*
 *		LockDatabaseObject
 *
 * Obtain a lock on a general object of the current database.  Don't use
816 817
 * this for shared objects (such as tablespaces).  It's unwise to apply it
 * to relations, also, since a lock taken this way will NOT conflict with
818
 * locks taken via LockRelation and friends.
819 820 821 822 823 824 825 826 827 828 829 830 831
 */
void
LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid,
				   LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_OBJECT(tag,
					   MyDatabaseId,
					   classid,
					   objid,
					   objsubid);

832
	(void) LockAcquire(&tag, lockmode, false, false);
833 834 835

	/* Make sure syscaches are up-to-date with any changes we waited for */
	AcceptInvalidationMessages();
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
}

/*
 *		UnlockDatabaseObject
 */
void
UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid,
					 LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_OBJECT(tag,
					   MyDatabaseId,
					   classid,
					   objid,
					   objsubid);

853
	LockRelease(&tag, lockmode, false);
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
}

/*
 *		LockSharedObject
 *
 * Obtain a lock on a shared-across-databases object.
 */
void
LockSharedObject(Oid classid, Oid objid, uint16 objsubid,
				 LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_OBJECT(tag,
					   InvalidOid,
					   classid,
					   objid,
					   objsubid);

873
	(void) LockAcquire(&tag, lockmode, false, false);
874 875 876

	/* Make sure syscaches are up-to-date with any changes we waited for */
	AcceptInvalidationMessages();
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
}

/*
 *		UnlockSharedObject
 */
void
UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid,
				   LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_OBJECT(tag,
					   InvalidOid,
					   classid,
					   objid,
					   objsubid);

894
	LockRelease(&tag, lockmode, false);
895
}
896

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
/*
 *		LockSharedObjectForSession
 *
 * Obtain a session-level lock on a shared-across-databases object.
 * See LockRelationIdForSession for notes about session-level locks.
 */
void
LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid,
						   LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_OBJECT(tag,
					   InvalidOid,
					   classid,
					   objid,
					   objsubid);

	(void) LockAcquire(&tag, lockmode, true, false);
}

/*
 *		UnlockSharedObjectForSession
 */
void
UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid,
							 LOCKMODE lockmode)
{
	LOCKTAG		tag;

	SET_LOCKTAG_OBJECT(tag,
					   InvalidOid,
					   classid,
					   objid,
					   objsubid);

	LockRelease(&tag, lockmode, true);
}

936 937

/*
938
 * Append a description of a lockable object to buf.
939
 *
940 941 942
 * Ideally we would print names for the numeric values, but that requires
 * getting locks on system tables, which might cause problems since this is
 * typically used to report deadlock situations.
943
 */
944 945
void
DescribeLockTag(StringInfo buf, const LOCKTAG *tag)
946
{
947
	switch ((LockTagType) tag->locktag_type)
948 949
	{
		case LOCKTAG_RELATION:
950 951 952 953 954
			appendStringInfo(buf,
							 _("relation %u of database %u"),
							 tag->locktag_field2,
							 tag->locktag_field1);
			break;
955
		case LOCKTAG_RELATION_EXTEND:
956 957 958 959 960
			appendStringInfo(buf,
							 _("extension of relation %u of database %u"),
							 tag->locktag_field2,
							 tag->locktag_field1);
			break;
961
		case LOCKTAG_PAGE:
962 963 964 965 966 967
			appendStringInfo(buf,
							 _("page %u of relation %u of database %u"),
							 tag->locktag_field3,
							 tag->locktag_field2,
							 tag->locktag_field1);
			break;
968
		case LOCKTAG_TUPLE:
969 970 971 972 973 974 975
			appendStringInfo(buf,
							 _("tuple (%u,%u) of relation %u of database %u"),
							 tag->locktag_field3,
							 tag->locktag_field4,
							 tag->locktag_field2,
							 tag->locktag_field1);
			break;
976
		case LOCKTAG_RELATION_APPENDONLY_SEGMENT_FILE:
977 978 979 980 981
			appendStringInfo(buf,
							 _("segment file %u of appendonly relation %u of database %u"),
							 tag->locktag_field3,
							 tag->locktag_field2,
							 tag->locktag_field1);
982 983
			break;
		case LOCKTAG_TRANSACTION:
984 985 986 987
			appendStringInfo(buf,
							 _("transaction %u"),
							 tag->locktag_field1);
			break;
988 989 990 991 992
		case LOCKTAG_VIRTUALTRANSACTION:
			appendStringInfo(buf,
							 _("virtual transaction %d/%u"),
							 tag->locktag_field1,
							 tag->locktag_field2);
993 994
			break;
		case LOCKTAG_OBJECT:
995 996 997 998 999
			appendStringInfo(buf,
							 _("object %u of class %u of database %u"),
							 tag->locktag_field3,
							 tag->locktag_field2,
							 tag->locktag_field1);
1000 1001
			break;
		case LOCKTAG_USERLOCK:
1002 1003 1004 1005 1006 1007 1008
			/* reserved for old contrib code, now on pgfoundry */
			appendStringInfo(buf,
							 _("user lock [%u,%u,%u]"),
							 tag->locktag_field1,
							 tag->locktag_field2,
							 tag->locktag_field3);
			break;
1009
		case LOCKTAG_ADVISORY:
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
			appendStringInfo(buf,
							 _("advisory lock [%u,%u,%u,%u]"),
							 tag->locktag_field1,
							 tag->locktag_field2,
							 tag->locktag_field3,
							 tag->locktag_field4);
			break;
		default:
			appendStringInfo(buf,
							 _("unrecognized locktag type %d"),
1020
							 (int) tag->locktag_type);
1021 1022 1023
			break;
	}
}
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

/*
 * LockTagIsTemp
 *		Determine whether a locktag is for a lock on a temporary object
 *
 * In PostgreSQL, 2PC cannot deal with temporary objects. Commit
 * f3032cbe377ecc570989e1bd2fe1aea455c12cc3 replace this method with global
 * variable MyXactAccessedTempRel, so it's no longer needed.
 *
 * However, GPDB supports 2PC with temporary objects. Hence, it still relies
 * on this method to check certain LOCKTAG is on temporary object or not, so
 * that GPDB can skip the lock information in `TwoPhaseRecordOnDisk` for the
 * temporary objects. That's to prevent replay redundant lock acquiring and
 * releasing during `xact_redo()` on non-existent temporary objects.
 */
bool
LockTagIsTemp(const LOCKTAG *tag)
{
	switch (tag->locktag_type)
	{
		case LOCKTAG_RELATION:
		case LOCKTAG_RELATION_EXTEND:
		case LOCKTAG_PAGE:
		case LOCKTAG_TUPLE:
		case LOCKTAG_RELATION_APPENDONLY_SEGMENT_FILE:
			/* check for lock on a temp relation */
			/* field1 is dboid, field2 is reloid for all of these */
			if ((Oid) tag->locktag_field1 == InvalidOid)
				return false;	/* shared, so not temp */
			if (isTempNamespace(get_rel_namespace((Oid) tag->locktag_field2)))
				return true;
			break;
		case LOCKTAG_TRANSACTION:
			/* there are no temp transactions */
			break;
		case LOCKTAG_OBJECT:
			/* there are currently no non-table temp objects */
			break;
		case LOCKTAG_USERLOCK:
		case LOCKTAG_ADVISORY:
			/* assume these aren't temp */
			break;
	}
	return false;				/* default case */
}
Z
Zhenghua Lyu 已提交
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

/*
 * Because of the current disign of AO table's visibility map,
 * we have to keep upgrading locks for AO table.
 */
bool
CondUpgradeRelLock(Oid relid)
{
	Relation rel;
	bool upgrade = false;

	rel = try_relation_open(relid, NoLock, true);

	if (!rel)
		elog(ERROR, "Relation open failed!");
1084
	else if (RelationIsAppendOptimized(rel))
Z
Zhenghua Lyu 已提交
1085 1086 1087 1088 1089 1090 1091 1092
		upgrade = true;
	else
		upgrade = false;

	relation_close(rel, NoLock);

	return upgrade;
}