Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1Xz7SG-0004nW-56 for pgsql-bugs@arkaria.postgresql.org; Thu, 11 Dec 2014 17:23:08 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.80) (envelope-from ) id 1Xz7SF-0007rO-L9 for pgsql-bugs@arkaria.postgresql.org; Thu, 11 Dec 2014 17:23:07 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:DHE_RSA_AES_256_CBC_SHA256:256) (Exim 4.80) (envelope-from ) id 1Xz7SE-0007rH-9v for pgsql-bugs@postgresql.org; Thu, 11 Dec 2014 17:23:06 +0000 Received: from outmail148098.authsmtp.com ([62.13.148.98]) by makus.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1Xz7S8-0006k6-UV for pgsql-bugs@postgresql.org; Thu, 11 Dec 2014 17:23:04 +0000 Received: from mail-c235.authsmtp.com (mail-c235.authsmtp.com [62.13.128.235]) by punt17.authsmtp.com (8.14.2/8.14.2/) with ESMTP id sBBHMp8W064442; Thu, 11 Dec 2014 17:22:51 GMT Received: from alvin.alvh.no-ip.org (client-186-37-106-102.imovil.entelpcs.cl [186.37.106.102] (may be forged)) (authenticated bits=0) by mail.authsmtp.com (8.14.2/8.14.2/) with ESMTP id sBBHMlkK007940; Thu, 11 Dec 2014 17:22:49 GMT Received: by alvin.alvh.no-ip.org (Postfix, from userid 1000) id DEF0A792; Thu, 11 Dec 2014 14:22:56 -0300 (CLST) Date: Thu, 11 Dec 2014 14:22:56 -0300 From: Alvaro Herrera To: Mark Kirkwood Cc: Andrew Sackville-West , pgsql-bugs@postgresql.org, Paulo Tanimoto Subject: Re: regression, deadlock in high frequency single-row UPDATE Message-ID: <20141211172256.GB20615@alvh.no-ip.org> References: <20140804161205.GA30380@andrew-ThinkPad-X230> <20140804163027.GI5475@eldon.alvh.no-ip.org> <20141208235552.GZ6930@andrew-ThinkPad-X230> <54868FA2.80003@catalyst.net.nz> <5487B8F2.6050806@catalyst.net.nz> <20141210193314.GZ1768@alvh.no-ip.org> <5488C197.3060900@catalyst.net.nz> <548943C7.2030507@catalyst.net.nz> <20141211130653.GG1768@alvh.no-ip.org> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="QKdGvSO+nmPlgiQ/" Content-Disposition: inline Content-Transfer-Encoding: 8bit In-Reply-To: <20141211130653.GG1768@alvh.no-ip.org> User-Agent: Mutt/1.5.23 (2014-03-12) X-Server-Quench: 54d65e2d-815a-11e4-b396-002590a15da7 X-AuthReport-Spam: If SPAM / abuse - report it at: http://www.authsmtp.com/abuse X-AuthRoute: OCdxZQATClZcSBoa BzkeAQdJTRslYBtL RB4bawxAL0wMSABN M15eIxoPcUtFHBZ1 VjUUWVRVVE1wXml3 aQBVZEtcakxQXAJ0 UUhPXFNSFhptCRse BlBdIGsKClkdA35w Yk9mXj5fVEd+cQh4 RhpSEDgEMXpoaWVO TUFZIgdJIgBDeAJF alJ6XXNcYGBTN30u JQJhdwMbABpkHWxP Tw4XIEkJQEENWnYw ShkOGTIkHgUEQW0z LhMmYlAGEV8MP0M5 IBM6WFQXNxJXEApB V3x1LAZlCjEA X-Authentic-SMTP: 61633235383639.1023:706 X-AuthFastPath: 0 (Was 255) X-AuthSMTP-Origin: 186.37.106.102/587 X-AuthVirus-Status: No virus detected - but ensure you scan with your own anti-virus system. X-Pg-Spam-Score: -2.6 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-bugs Precedence: bulk Sender: pgsql-bugs-owner@postgresql.org --QKdGvSO+nmPlgiQ/ Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: 8bit Alvaro Herrera wrote: > I'm going to experiment with that idea and see if it leads to a > solution. I tried the other idea yesterday (to keep the HW tuple lock > we acquire in heap_lock_tuple until heap_update is done) but aside from > being very complicated and bug-prone, it doesn't solve the problem > anyway. Here's a preliminary patch. It does solve the deadlock in my simplified test case. If Andrew can confirm that it fixes his original problem too, that'd be good. Before this can be committed I need an isolationtester spec file that reproduces the problem. Now that I understand why it happens it should be easy to produce: just have a transaction that does BEGIN, then the insert, and keeps the transaction open; enough other sessions run the UPDATE until the problem pops up. (Also, comments on Would_MultiXactIdWait_Block need work.) FWIW this code should also have slightly better performance than the original coding, since the heavyweight tuple lock acquisition is skipped in some cases. Not sure if that is measurable, though. Maybe in extreme cases such as the one in #8470 ... -- Álvaro Herrera http://www.2ndQuadrant.com/ PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services --QKdGvSO+nmPlgiQ/ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="deadlock.patch" diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index df4853b..5f92627 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -93,6 +93,9 @@ static void HeapSatisfiesHOTandKeyUpdate(Relation relation, bool *satisfies_hot, bool *satisfies_key, bool *satisfies_id, HeapTuple oldtup, HeapTuple newtup); +static bool heap_acquire_tuplock(Relation relation, ItemPointer tid, + LockTupleMode mode, LockWaitPolicy wait_policy, + bool *have_tuple_lock); static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, @@ -110,6 +113,8 @@ static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 in int *remaining); static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining); +static bool Would_MultiXactIdWait_Block(MultiXactId multi, MultiXactStatus status, + uint16 infomask); static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup); static HeapTuple ExtractReplicaIdentity(Relation rel, HeapTuple tup, bool key_modified, bool *copy); @@ -2700,11 +2705,8 @@ l1: * this arranges that we stay at the head of the line while rechecking * tuple state. */ - if (!have_tuple_lock) - { - LockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive); - have_tuple_lock = true; - } + heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive, + LockWaitBlock, &have_tuple_lock); /* * Sleep until concurrent transaction ends. Note that we don't care @@ -3224,21 +3226,6 @@ l2: LockBuffer(buffer, BUFFER_LOCK_UNLOCK); /* - * Acquire tuple lock to establish our priority for the tuple (see - * heap_lock_tuple). LockTuple will release us when we are - * next-in-line for the tuple. - * - * If we are forced to "start over" below, we keep the tuple lock; - * this arranges that we stay at the head of the line while rechecking - * tuple state. - */ - if (!have_tuple_lock) - { - LockTupleTuplock(relation, &(oldtup.t_self), *lockmode); - have_tuple_lock = true; - } - - /* * Now we have to do something about the existing locker. If it's a * multi, sleep on it; we might be awakened before it is completely * gone (or even not sleep at all in some cases); we need to preserve @@ -3248,12 +3235,30 @@ l2: * before actually going to sleep. If the update doesn't conflict * with the locks, we just continue without sleeping (but making sure * it is preserved). + * + * Before sleeping, we need to acquire tuple lock to establish our + * priority for the tuple (see heap_lock_tuple). LockTuple will + * release us when we are next-in-line for the tuple. Note we must not + * acquire the tuple lock until we're sure we're going to sleep; + * otherwise we're open for race conditions with other transactions + * holding the tuple lock which sleep on us. + * + * If we are forced to "start over" below, we keep the tuple lock; + * this arranges that we stay at the head of the line while rechecking + * tuple state. */ if (infomask & HEAP_XMAX_IS_MULTI) { TransactionId update_xact; int remain; + /* acquire tuple lock, if necessary */ + if (Would_MultiXactIdWait_Block((MultiXactId) xwait, mxact_status, infomask)) + { + heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode, + LockWaitBlock, &have_tuple_lock); + } + /* wait for multixact */ MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask, relation, &oldtup.t_data->t_ctid, XLTW_Update, @@ -3330,7 +3335,12 @@ l2: } else { - /* wait for regular transaction to end */ + /* + * Wait for regular transaction to end; but first, acquire + * tuple lock. + */ + heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode, + LockWaitBlock, &have_tuple_lock); XactLockTableWait(xwait, relation, &oldtup.t_data->t_ctid, XLTW_Update); LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); @@ -4038,6 +4048,48 @@ get_mxact_status_for_lock(LockTupleMode mode, bool is_update) return (MultiXactStatus) retval; } +/* + * Acquire heavyweight lock on the given tuple, in preparation for acquiring + * its normal, Xmax-based tuple lock. + * + * have_tuple_lock is an input and output parameter: on input, it indicates + * whether the lock has previously been acquired (and this function does + * nothing in that case). If this function returns success, have_tuple_lock + * has been flipped to true. + * + * Returns false if it was unable to obtain the lock; this can only happen if + * wait_policy is Skip. + */ +static bool +heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode, + LockWaitPolicy wait_policy, bool *have_tuple_lock) +{ + if (*have_tuple_lock) + return true; + + switch (wait_policy) + { + case LockWaitBlock: + LockTupleTuplock(relation, tid, mode); + break; + + case LockWaitSkip: + if (!ConditionalLockTupleTuplock(relation, tid, mode)) + return false; + break; + + case LockWaitError: + if (!ConditionalLockTupleTuplock(relation, tid, mode)) + ereport(ERROR, + (errcode(ERRCODE_LOCK_NOT_AVAILABLE), + errmsg("could not obtain lock on row in relation \"%s\"", + RelationGetRelationName(relation)))); + break; + } + *have_tuple_lock = true; + + return true; +} /* * heap_lock_tuple - lock a tuple in shared or exclusive mode @@ -4171,42 +4223,6 @@ l3: } /* - * Acquire tuple lock to establish our priority for the tuple. - * LockTuple will release us when we are next-in-line for the tuple. - * We must do this even if we are share-locking. - * - * If we are forced to "start over" below, we keep the tuple lock; - * this arranges that we stay at the head of the line while rechecking - * tuple state. - */ - if (!have_tuple_lock) - { - switch (wait_policy) - { - case LockWaitBlock: - LockTupleTuplock(relation, tid, mode); - break; - case LockWaitSkip: - if (!ConditionalLockTupleTuplock(relation, tid, mode)) - { - result = HeapTupleWouldBlock; - /* recovery code expects to have buffer lock held */ - LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE); - goto failed; - } - break; - case LockWaitError: - if (!ConditionalLockTupleTuplock(relation, tid, mode)) - ereport(ERROR, - (errcode(ERRCODE_LOCK_NOT_AVAILABLE), - errmsg("could not obtain lock on row in relation \"%s\"", - RelationGetRelationName(relation)))); - break; - } - have_tuple_lock = true; - } - - /* * Initially assume that we will have to wait for the locking * transaction(s) to finish. We check various cases below in which * this can be turned off. @@ -4327,6 +4343,9 @@ l3: * We don't need to allow old multixacts here; if that had * been the case, HeapTupleSatisfiesUpdate would have returned * MayBeUpdated and we wouldn't be here. + * + * XXX looks like this can be replaced with a call to + * Would_MultiXactIdWait_Block */ nmembers = GetMultiXactIdMembers(xwait, &members, false, @@ -4397,6 +4416,28 @@ l3: if (require_sleep) { + /* + * Acquire tuple lock to establish our priority for the tuple. + * LockTuple will release us when we are next-in-line for the tuple. + * We must do this even if we are share-locking. + * + * If we are forced to "start over" below, we keep the tuple lock; + * this arranges that we stay at the head of the line while rechecking + * tuple state. + */ + if (!heap_acquire_tuplock(relation, tid, mode, wait_policy, + &have_tuple_lock)) + { + /* + * This can only happen if wait_policy is Skip and the lock + * couldn't be obtained. + */ + result = HeapTupleWouldBlock; + /* recovery code expects to have buffer lock held */ + LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE); + goto failed; + } + if (infomask & HEAP_XMAX_IS_MULTI) { MultiXactStatus status = get_mxact_status_for_lock(mode, false); @@ -6188,6 +6229,48 @@ Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, } /* + * return true if sleeping on the given multixact with the given status would + * cause to sleep until some xact is done. + */ +static bool +Would_MultiXactIdWait_Block(MultiXactId multi, MultiXactStatus status, + uint16 infomask) +{ + bool allow_old; + int nmembers; + MultiXactMember *members; + bool result = false; + + allow_old = !(infomask & HEAP_LOCK_MASK) && HEAP_XMAX_IS_LOCKED_ONLY(infomask); + nmembers = GetMultiXactIdMembers(multi, &members, allow_old, + HEAP_XMAX_IS_LOCKED_ONLY(infomask)); + + if (nmembers >= 0) + { + int i; + + for (i = 0; i < nmembers; i++) + { + TransactionId memxid = members[i].xid; + MultiXactStatus memstatus = members[i].status; + + if (TransactionIdIsCurrentTransactionId(memxid)) + continue; + + if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus), + LOCKMODE_from_mxstatus(status))) + continue; + + result = true; + break; + } + pfree(members); + } + + return result; +} + +/* * MultiXactIdWait * Sleep on a MultiXactId. * --QKdGvSO+nmPlgiQ/ Content-Type: text/plain Content-Disposition: inline Content-Transfer-Encoding: 8bit MIME-Version: 1.0 -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs --QKdGvSO+nmPlgiQ/--