Fix ordering issue with WAL operations in GIN fast insert path
authorMichael Paquier <[email protected]>
Thu, 13 Oct 2022 00:31:57 +0000 (09:31 +0900)
committerMichael Paquier <[email protected]>
Thu, 13 Oct 2022 00:31:57 +0000 (09:31 +0900)
Contrary to what is documented in src/backend/access/transam/README,
ginHeapTupleFastInsert() had a few ordering issues with the way it does
its WAL operations when inserting items in its fast path.

First, when using a separate list, XLogBeginInsert() was being always
called before START_CRIT_SECTION(), and in this case a second thing was
wrong when merging lists, as an exclusive lock was taken on the tail
page *before* calling XLogBeginInsert().  Finally, when inserting items
into a tail page, the order of XLogBeginInsert() and
START_CRIT_SECTION() was reversed.  This commit addresses all these
issues by moving the calls of XLogBeginInsert() after all the pages
logged are locked and pinned, within a critical section.

Author:  Matthias van de Meent, Zhang Mingli
Discussion: https://postgr.es/m/CAEze2WhL8uLMqynnnCu1LAPwxD5RKEo0nHV+eXGg_N6ELU88HQ@mail.gmail.com

src/backend/access/gin/ginfast.c

index ab4bb67d4b456b4d9db22a8e5af763a513107d18..f750b5ed9e90a172a27cedb5d719bc1a7641b7d1 100644 (file)
@@ -285,9 +285,6 @@ ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector)
        memset(&sublist, 0, sizeof(GinMetaPageData));
        makeSublist(index, collector->tuples, collector->ntuples, &sublist);
 
-       if (needWal)
-           XLogBeginInsert();
-
        /*
         * metapage was unlocked, see above
         */
@@ -307,6 +304,9 @@ ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector)
 
            metadata->nPendingPages = sublist.nPendingPages;
            metadata->nPendingHeapTuples = sublist.nPendingHeapTuples;
+
+           if (needWal)
+               XLogBeginInsert();
        }
        else
        {
@@ -335,7 +335,10 @@ ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector)
            metadata->nPendingHeapTuples += sublist.nPendingHeapTuples;
 
            if (needWal)
+           {
+               XLogBeginInsert();
                XLogRegisterBuffer(1, buffer, REGBUF_STANDARD);
+           }
        }
    }
    else
@@ -361,11 +364,11 @@ ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector)
 
        data.ntuples = collector->ntuples;
 
+       START_CRIT_SECTION();
+
        if (needWal)
            XLogBeginInsert();
 
-       START_CRIT_SECTION();
-
        /*
         * Increase counter of heap tuples
         */