Fix incorrect order of database-locking operations in InitPostgres().
Fix incorrect order of database-locking operations in InitPostgres().

We should set MyProc->databaseId after acquiring the per-database lock,
not beforehand.  The old way risked deadlock against processes trying to
copy or delete the target database, since they would first acquire the lock
and then wait for processes with matching databaseId to exit; that left a
window wherein an incoming process could set its databaseId and then block
on the lock, while the other process had the lock and waited in vain for
the incoming process to exit.

CountOtherDBBackends() would time out and fail after 5 seconds, so this
just resulted in an unexpected failure not a permanent lockup, but it's
still annoying when it happens.  A real-world example of a use-case is that
short-duration connections to a template database should not cause CREATE
DATABASE to fail.

Doing it in the other order should be fine since the contract has always
been that processes searching the ProcArray for a database ID must hold the
relevant per-database lock while searching.  Thus, this actually removes
the former race condition that required an assumption that storing to
MyProc->databaseId is atomic.

It's been like this for a long time, so back-patch to all active branches.

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