Grab heavyweight tuple lock only before sleeping
Grab heavyweight tuple lock only before sleeping

We were trying to acquire the lock even when we were subsequently
not sleeping in some other transaction, which opens us up unnecessarily
to deadlocks.  In particular, this is troublesome if an update tries to
lock an updated version of a tuple and finds itself doing EvalPlanQual
update chain walking; more than two sessions doing this concurrently
will find themselves sleeping on each other because the HW tuple lock
acquisition in heap_lock_tuple called from EvalPlanQualFetch races with
the same tuple lock being acquired in heap_update -- one of these
sessions sleeps on the other one to finish while holding the tuple lock,
and the other one sleeps on the tuple lock.

Per trouble report from Andrew Sackville-West in
http://www.postgresql.org/message-id/20140731233051.GN17765@andrew-ThinkPad-X230

His scenario can be simplified down to a relatively simple
isolationtester spec file which I don't include in this commit; the
reason is that the current isolationtester is not able to deal with more
than one blocked session concurrently and it blocks instead of raising
the expected deadlock.  In the future, if we improve isolationtester, it
would be good to include the spec file in the isolation schedule.  I
posted it in
http://www.postgresql.org/message-id/20141212205254.GC1768@alvh.no-ip.org

Hat tip to Mark Kirkwood, who helped diagnose the trouble.

greenplum-db/gpdb,oberstet/postgres-xl,zeroae/postgres-xl,lisakowen/gpdb,lisakowen/gpdb,jmcatamney/gpdb,ovr/postgres-xl,pavanvd/postgres-xl,pavanvd/postgres-xl,lisakowen/gpdb,greenplum-db/gpdb,oberstet/postgres-xl,50wu/gpdb,xinzweb/gpdb,zeroae/postgres-xl,50wu/gpdb,ovr/postgres-xl,greenplum-db/gpdb,ashwinstar/gpdb,adam8157/gpdb,greenplum-db/gpdb,ashwinstar/gpdb,jmcatamney/gpdb,greenplum-db/gpdb,adam8157/gpdb,oberstet/postgres-xl,oberstet/postgres-xl,adam8157/gpdb,xinzweb/gpdb,50wu/gpdb,xinzweb/gpdb,zeroae/postgres-xl,yazun/postgres-xl,ashwinstar/gpdb,jmcatamney/gpdb,techdragon/Postgres-XL,xinzweb/gpdb,techdragon/Postgres-XL,yazun/postgres-xl,yazun/postgres-xl,adam8157/gpdb,zeroae/postgres-xl,lisakowen/gpdb,50wu/gpdb,50wu/gpdb,greenplum-db/gpdb,jmcatamney/gpdb,jmcatamney/gpdb,techdragon/Postgres-XL,pavanvd/postgres-xl,jmcatamney/gpdb,jmcatamney/gpdb,jmcatamney/gpdb,xinzweb/gpdb,50wu/gpdb,yazun/postgres-xl,adam8157/gpdb,ashwinstar/gpdb,lisakowen/gpdb,ashwinstar/gpdb,ovr/postgres-xl,Postgres-XL/Postgres-XL,ovr/postgres-xl,Postgres-XL/Postgres-XL,yazun/postgres-xl,zeroae/postgres-xl,greenplum-db/gpdb,ashwinstar/gpdb,techdragon/Postgres-XL,techdragon/Postgres-XL,Postgres-XL/Postgres-XL,50wu/gpdb,greenplum-db/gpdb,50wu/gpdb,ovr/postgres-xl,pavanvd/postgres-xl,xinzweb/gpdb,lisakowen/gpdb,ashwinstar/gpdb,Postgres-XL/Postgres-XL,pavanvd/postgres-xl,adam8157/gpdb,lisakowen/gpdb,xinzweb/gpdb,ashwinstar/gpdb,oberstet/postgres-xl,lisakowen/gpdb,Postgres-XL/Postgres-XL,xinzweb/gpdb,adam8157/gpdb,adam8157/gpdb