LCOV - differential code coverage report
Current view: top level - src/backend/access/heap - hio.c (source / functions) Coverage Total Hit LBC UBC CBC
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 88.2 % 237 209 5 23 209
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 5 5 5
Baseline: lcov-20261128-baseline Branches: 72.5 % 222 161 2 59 161
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 4 4 4
(360..) days: 87.9 % 232 204 5 23 204
Function coverage date bins:
(360..) days: 100.0 % 5 5 5
Branch coverage date bins:
(7,30] days: 50.0 % 2 1 1 1
(360..) days: 72.7 % 220 160 2 58 160

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * hio.c
                                  4                 :                :  *    POSTGRES heap access method input/output code.
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *    src/backend/access/heap/hio.c
                                 12                 :                :  *
                                 13                 :                :  *-------------------------------------------------------------------------
                                 14                 :                :  */
                                 15                 :                : 
                                 16                 :                : #include "postgres.h"
                                 17                 :                : 
                                 18                 :                : #include "access/heapam.h"
                                 19                 :                : #include "access/hio.h"
                                 20                 :                : #include "access/htup_details.h"
                                 21                 :                : #include "access/visibilitymap.h"
                                 22                 :                : #include "storage/bufmgr.h"
                                 23                 :                : #include "storage/freespace.h"
                                 24                 :                : #include "storage/lmgr.h"
                                 25                 :                : 
                                 26                 :                : 
                                 27                 :                : /*
                                 28                 :                :  * RelationPutHeapTuple - place tuple at specified page
                                 29                 :                :  *
                                 30                 :                :  * !!! EREPORT(ERROR) IS DISALLOWED HERE !!!  Must PANIC on failure!!!
                                 31                 :                :  *
                                 32                 :                :  * Note - caller must hold BUFFER_LOCK_EXCLUSIVE on the buffer.
                                 33                 :                :  */
                                 34                 :                : void
11099 scrappy@hub.org            35                 :CBC    16340192 : RelationPutHeapTuple(Relation relation,
                                 36                 :                :                      Buffer buffer,
                                 37                 :                :                      HeapTuple tuple,
                                 38                 :                :                      bool token)
                                 39                 :                : {
                                 40                 :                :     Page        pageHeader;
                                 41                 :                :     OffsetNumber offnum;
                                 42                 :                : 
                                 43                 :                :     /*
                                 44                 :                :      * A tuple that's being inserted speculatively should already have its
                                 45                 :                :      * token set.
                                 46                 :                :      */
 4222 andres@anarazel.de         47   [ +  +  -  + ]:       16340192 :     Assert(!token || HeapTupleHeaderIsSpeculative(tuple->t_data));
                                 48                 :                : 
                                 49                 :                :     /*
                                 50                 :                :      * Do not allow tuples with invalid combinations of hint bits to be placed
                                 51                 :                :      * on a page.  This combination is detected as corruption by the
                                 52                 :                :      * contrib/amcheck logic, so if you disable this assertion, make
                                 53                 :                :      * corresponding changes there.
                                 54                 :                :      */
 2228 rhaas@postgresql.org       55   [ -  +  -  - ]:       16340192 :     Assert(!((tuple->t_data->t_infomask & HEAP_XMAX_COMMITTED) &&
                                 56                 :                :              (tuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI)));
                                 57                 :                : 
                                 58                 :                :     /* caller should have cleared the flag */
   19 andres@anarazel.de         59         [ -  + ]:       16340192 :     Assert(!HeapTupleHeaderIsDatum(tuple->t_data));
                                 60                 :                : 
                                 61                 :                :     /* Add the tuple to the page */
 3874 kgrittn@postgresql.o       62                 :       16340192 :     pageHeader = BufferGetPage(buffer);
                                 63                 :                : 
  397 peter@eisentraut.org       64                 :       16340192 :     offnum = PageAddItem(pageHeader, tuple->t_data, tuple->t_len, InvalidOffsetNumber, false, true);
 9644 vadim4o@yahoo.com          65         [ -  + ]:       16340192 :     if (offnum == InvalidOffsetNumber)
 8531 tgl@sss.pgh.pa.us          66         [ #  # ]:UBC           0 :         elog(PANIC, "failed to add tuple to page");
                                 67                 :                : 
                                 68                 :                :     /* Update tuple->t_self to the actual position where it was stored */
 9269 tgl@sss.pgh.pa.us          69                 :CBC    16340192 :     ItemPointerSet(&(tuple->t_self), BufferGetBlockNumber(buffer), offnum);
                                 70                 :                : 
                                 71                 :                :     /*
                                 72                 :                :      * Insert the correct position into CTID of the stored tuple, too (unless
                                 73                 :                :      * this is a speculative insertion, in which case the token is held in
                                 74                 :                :      * CTID field instead)
                                 75                 :                :      */
 4222 andres@anarazel.de         76         [ +  + ]:       16340192 :     if (!token)
                                 77                 :                :     {
                                 78                 :       16337914 :         ItemId      itemId = PageGetItemId(pageHeader, offnum);
 3195 tgl@sss.pgh.pa.us          79                 :       16337914 :         HeapTupleHeader item = (HeapTupleHeader) PageGetItem(pageHeader, itemId);
                                 80                 :                : 
                                 81                 :       16337914 :         item->t_ctid = tuple->t_self;
                                 82                 :                :     }
11099 scrappy@hub.org            83                 :       16340192 : }
                                 84                 :                : 
                                 85                 :                : /*
                                 86                 :                :  * Read in a buffer in mode, using bulk-insert strategy if bistate isn't NULL.
                                 87                 :                :  */
                                 88                 :                : static Buffer
 6596 tgl@sss.pgh.pa.us          89                 :       12608375 : ReadBufferBI(Relation relation, BlockNumber targetBlock,
                                 90                 :                :              ReadBufferMode mode, BulkInsertState bistate)
                                 91                 :                : {
                                 92                 :                :     Buffer      buffer;
                                 93                 :                : 
                                 94                 :                :     /* If not bulk-insert, exactly like ReadBuffer */
                                 95         [ +  + ]:       12608375 :     if (!bistate)
 2855 andres@anarazel.de         96                 :        9874884 :         return ReadBufferExtended(relation, MAIN_FORKNUM, targetBlock,
                                 97                 :                :                                   mode, NULL);
                                 98                 :                : 
                                 99                 :                :     /* If we have the desired block already pinned, re-pin and return it */
 6596 tgl@sss.pgh.pa.us         100         [ +  + ]:        2733491 :     if (bistate->current_buf != InvalidBuffer)
                                101                 :                :     {
                                102         [ +  + ]:        2693233 :         if (BufferGetBlockNumber(bistate->current_buf) == targetBlock)
                                103                 :                :         {
                                104                 :                :             /*
                                105                 :                :              * Currently the LOCK variants are only used for extending
                                106                 :                :              * relation, which should never reach this branch.
                                107                 :                :              */
 2855 andres@anarazel.de        108   [ +  -  -  + ]:        2676384 :             Assert(mode != RBM_ZERO_AND_LOCK &&
                                109                 :                :                    mode != RBM_ZERO_AND_CLEANUP_LOCK);
                                110                 :                : 
 6596 tgl@sss.pgh.pa.us         111                 :        2676384 :             IncrBufferRefCount(bistate->current_buf);
                                112                 :        2676384 :             return bistate->current_buf;
                                113                 :                :         }
                                114                 :                :         /* ... else drop the old buffer */
                                115                 :          16849 :         ReleaseBuffer(bistate->current_buf);
                                116                 :          16849 :         bistate->current_buf = InvalidBuffer;
                                117                 :                :     }
                                118                 :                : 
                                119                 :                :     /* Perform a read using the buffer strategy */
                                120                 :          57107 :     buffer = ReadBufferExtended(relation, MAIN_FORKNUM, targetBlock,
                                121                 :                :                                 mode, bistate->strategy);
                                122                 :                : 
                                123                 :                :     /* Save the selected block as target for future inserts */
                                124                 :          57107 :     IncrBufferRefCount(buffer);
                                125                 :          57107 :     bistate->current_buf = buffer;
                                126                 :                : 
                                127                 :          57107 :     return buffer;
                                128                 :                : }
                                129                 :                : 
                                130                 :                : /*
                                131                 :                :  * For each heap page which is all-visible, acquire a pin on the appropriate
                                132                 :                :  * visibility map page, if we haven't already got one.
                                133                 :                :  *
                                134                 :                :  * To avoid complexity in the callers, either buffer1 or buffer2 may be
                                135                 :                :  * InvalidBuffer if only one buffer is involved. For the same reason, block2
                                136                 :                :  * may be smaller than block1.
                                137                 :                :  *
                                138                 :                :  * Returns whether buffer locks were temporarily released.
                                139                 :                :  */
                                140                 :                : static bool
 5633 rhaas@postgresql.org      141                 :       14839133 : GetVisibilityMapPins(Relation relation, Buffer buffer1, Buffer buffer2,
                                142                 :                :                      BlockNumber block1, BlockNumber block2,
                                143                 :                :                      Buffer *vmbuffer1, Buffer *vmbuffer2)
                                144                 :                : {
                                145                 :                :     bool        need_to_pin_buffer1;
                                146                 :                :     bool        need_to_pin_buffer2;
 1332 andres@anarazel.de        147                 :       14839133 :     bool        released_locks = false;
                                148                 :                : 
                                149                 :                :     /*
                                150                 :                :      * Swap buffers around to handle case of a single block/buffer, and to
                                151                 :                :      * handle if lock ordering rules require to lock block2 first.
                                152                 :                :      */
                                153   [ +  +  +  + ]:       29677434 :     if (!BufferIsValid(buffer1) ||
                                154         [ +  + ]:       17068228 :         (BufferIsValid(buffer2) && block1 > block2))
                                155                 :                :     {
                                156                 :        2198771 :         Buffer      tmpbuf = buffer1;
                                157                 :        2198771 :         Buffer     *tmpvmbuf = vmbuffer1;
                                158                 :        2198771 :         BlockNumber tmpblock = block1;
                                159                 :                : 
                                160                 :        2198771 :         buffer1 = buffer2;
                                161                 :        2198771 :         vmbuffer1 = vmbuffer2;
                                162                 :        2198771 :         block1 = block2;
                                163                 :                : 
                                164                 :        2198771 :         buffer2 = tmpbuf;
                                165                 :        2198771 :         vmbuffer2 = tmpvmbuf;
                                166                 :        2198771 :         block2 = tmpblock;
                                167                 :                :     }
                                168                 :                : 
 5633 rhaas@postgresql.org      169         [ -  + ]:       14839133 :     Assert(BufferIsValid(buffer1));
 2856 akapila@postgresql.o      170   [ +  +  +  - ]:       14839133 :     Assert(buffer2 == InvalidBuffer || block1 <= block2);
                                171                 :                : 
                                172                 :                :     while (1)
                                173                 :                :     {
                                174                 :                :         /* Figure out which pins we need but don't have. */
 3874 kgrittn@postgresql.o      175                 :       14839133 :         need_to_pin_buffer1 = PageIsAllVisible(BufferGetPage(buffer1))
 5633 rhaas@postgresql.org      176   [ +  +  -  + ]:       14839133 :             && !visibilitymap_pin_ok(block1, *vmbuffer1);
                                177                 :       14839133 :         need_to_pin_buffer2 = buffer2 != InvalidBuffer
 3874 kgrittn@postgresql.o      178         [ +  + ]:        2229927 :             && PageIsAllVisible(BufferGetPage(buffer2))
 5633 rhaas@postgresql.org      179   [ +  +  -  + ]:       17069060 :             && !visibilitymap_pin_ok(block2, *vmbuffer2);
                                180   [ +  -  +  - ]:       14839133 :         if (!need_to_pin_buffer1 && !need_to_pin_buffer2)
 1332 andres@anarazel.de        181                 :       14839133 :             break;
                                182                 :                : 
                                183                 :                :         /* We must unlock both buffers before doing any I/O. */
 1332 andres@anarazel.de        184                 :UBC           0 :         released_locks = true;
 5633 rhaas@postgresql.org      185                 :              0 :         LockBuffer(buffer1, BUFFER_LOCK_UNLOCK);
                                186   [ #  #  #  # ]:              0 :         if (buffer2 != InvalidBuffer && buffer2 != buffer1)
                                187                 :              0 :             LockBuffer(buffer2, BUFFER_LOCK_UNLOCK);
                                188                 :                : 
                                189                 :                :         /* Get pins. */
                                190         [ #  # ]:              0 :         if (need_to_pin_buffer1)
                                191                 :              0 :             visibilitymap_pin(relation, block1, vmbuffer1);
                                192         [ #  # ]:              0 :         if (need_to_pin_buffer2)
                                193                 :              0 :             visibilitymap_pin(relation, block2, vmbuffer2);
                                194                 :                : 
                                195                 :                :         /* Relock buffers. */
                                196                 :              0 :         LockBuffer(buffer1, BUFFER_LOCK_EXCLUSIVE);
                                197   [ #  #  #  # ]:              0 :         if (buffer2 != InvalidBuffer && buffer2 != buffer1)
                                198                 :              0 :             LockBuffer(buffer2, BUFFER_LOCK_EXCLUSIVE);
                                199                 :                : 
                                200                 :                :         /*
                                201                 :                :          * If there are two buffers involved and we pinned just one of them,
                                202                 :                :          * it's possible that the second one became all-visible while we were
                                203                 :                :          * busy pinning the first one.  If it looks like that's a possible
                                204                 :                :          * scenario, we'll need to make a second pass through this loop.
                                205                 :                :          */
                                206   [ #  #  #  # ]:              0 :         if (buffer2 == InvalidBuffer || buffer1 == buffer2
                                207   [ #  #  #  # ]:              0 :             || (need_to_pin_buffer1 && need_to_pin_buffer2))
                                208                 :                :             break;
                                209                 :                :     }
                                210                 :                : 
 1332 andres@anarazel.de        211                 :CBC    14839133 :     return released_locks;
                                212                 :                : }
                                213                 :                : 
                                214                 :                : /*
                                215                 :                :  * Extend the relation. By multiple pages, if beneficial.
                                216                 :                :  *
                                217                 :                :  * If the caller needs multiple pages (num_pages > 1), we always try to extend
                                218                 :                :  * by at least that much.
                                219                 :                :  *
                                220                 :                :  * If there is contention on the extension lock, we don't just extend "for
                                221                 :                :  * ourselves", but we try to help others. We can do so by adding empty pages
                                222                 :                :  * into the FSM. Typically there is no contention when we can't use the FSM.
                                223                 :                :  *
                                224                 :                :  * We do have to limit the number of pages to extend by to some value, as the
                                225                 :                :  * buffers for all the extended pages need to, temporarily, be pinned. For now
                                226                 :                :  * we define MAX_BUFFERS_TO_EXTEND_BY to be 64 buffers, it's hard to see
                                227                 :                :  * benefits with higher numbers. This partially is because copyfrom.c's
                                228                 :                :  * MAX_BUFFERED_TUPLES / MAX_BUFFERED_BYTES prevents larger multi_inserts.
                                229                 :                :  *
                                230                 :                :  * Returns a buffer for a newly extended block. If possible, the buffer is
                                231                 :                :  * returned exclusively locked. *did_unlock is set to true if the lock had to
                                232                 :                :  * be released, false otherwise.
                                233                 :                :  *
                                234                 :                :  *
                                235                 :                :  * XXX: It would likely be beneficial for some workloads to extend more
                                236                 :                :  * aggressively, e.g. using a heuristic based on the relation size.
                                237                 :                :  */
                                238                 :                : static Buffer
                                239                 :         155978 : RelationAddBlocks(Relation relation, BulkInsertState bistate,
                                240                 :                :                   int num_pages, bool use_fsm, bool *did_unlock)
                                241                 :                : {
                                242                 :                : #define MAX_BUFFERS_TO_EXTEND_BY 64
                                243                 :                :     Buffer      victim_buffers[MAX_BUFFERS_TO_EXTEND_BY];
                                244                 :         155978 :     BlockNumber first_block = InvalidBlockNumber;
                                245                 :         155978 :     BlockNumber last_block = InvalidBlockNumber;
                                246                 :                :     uint32      extend_by_pages;
                                247                 :                :     uint32      not_in_fsm_pages;
                                248                 :                :     Buffer      buffer;
                                249                 :                :     Page        page;
                                250                 :                : 
                                251                 :                :     /*
                                252                 :                :      * Determine by how many pages to try to extend by.
                                253                 :                :      */
                                254   [ +  +  +  + ]:         155978 :     if (bistate == NULL && !use_fsm)
                                255                 :                :     {
                                256                 :                :         /*
                                257                 :                :          * If we have neither bistate, nor can use the FSM, we can't bulk
                                258                 :                :          * extend - there'd be no way to find the additional pages.
                                259                 :                :          */
                                260                 :            811 :         extend_by_pages = 1;
                                261                 :                :     }
                                262                 :                :     else
                                263                 :                :     {
                                264                 :                :         uint32      waitcount;
                                265                 :                : 
                                266                 :                :         /*
                                267                 :                :          * Try to extend at least by the number of pages the caller needs. We
                                268                 :                :          * can remember the additional pages (either via FSM or bistate).
                                269                 :                :          */
                                270                 :         155167 :         extend_by_pages = num_pages;
                                271                 :                : 
                                272   [ +  +  +  + ]:         155167 :         if (!RELATION_IS_LOCAL(relation))
                                273                 :          94269 :             waitcount = RelationExtensionLockWaiterCount(relation);
                                274                 :                :         else
                                275                 :          60898 :             waitcount = 0;
                                276                 :                : 
                                277                 :                :         /*
                                278                 :                :          * Multiply the number of pages to extend by the number of waiters. Do
                                279                 :                :          * this even if we're not using the FSM, as it still relieves
                                280                 :                :          * contention, by deferring the next time this backend needs to
                                281                 :                :          * extend. In that case the extended pages will be found via
                                282                 :                :          * bistate->next_free.
                                283                 :                :          */
                                284                 :         155167 :         extend_by_pages += extend_by_pages * waitcount;
                                285                 :                : 
                                286                 :                :         /* ---
                                287                 :                :          * If we previously extended using the same bistate, it's very likely
                                288                 :                :          * we'll extend some more. Try to extend by as many pages as
                                289                 :                :          * before. This can be important for performance for several reasons,
                                290                 :                :          * including:
                                291                 :                :          *
                                292                 :                :          * - It prevents mdzeroextend() switching between extending the
                                293                 :                :          *   relation in different ways, which is inefficient for some
                                294                 :                :          *   filesystems.
                                295                 :                :          *
                                296                 :                :          * - Contention is often intermittent. Even if we currently don't see
                                297                 :                :          *   other waiters (see above), extending by larger amounts can
                                298                 :                :          *   prevent future contention.
                                299                 :                :          * ---
                                300                 :                :          */
 1202                           301         [ +  + ]:         155167 :         if (bistate)
                                302                 :          12920 :             extend_by_pages = Max(extend_by_pages, bistate->already_extended_by);
                                303                 :                : 
                                304                 :                :         /*
                                305                 :                :          * Can't extend by more than MAX_BUFFERS_TO_EXTEND_BY, we need to pin
                                306                 :                :          * them all concurrently.
                                307                 :                :          */
 1332                           308                 :         155167 :         extend_by_pages = Min(extend_by_pages, MAX_BUFFERS_TO_EXTEND_BY);
                                309                 :                :     }
                                310                 :                : 
                                311                 :                :     /*
                                312                 :                :      * How many of the extended pages should be entered into the FSM?
                                313                 :                :      *
                                314                 :                :      * If we have a bistate, only enter pages that we don't need ourselves
                                315                 :                :      * into the FSM.  Otherwise every other backend will immediately try to
                                316                 :                :      * use the pages this backend needs for itself, causing unnecessary
                                317                 :                :      * contention.  If we don't have a bistate, we can't avoid the FSM.
                                318                 :                :      *
                                319                 :                :      * Never enter the page returned into the FSM, we'll immediately use it.
                                320                 :                :      */
                                321   [ +  +  +  + ]:         155978 :     if (num_pages > 1 && bistate == NULL)
                                322                 :            319 :         not_in_fsm_pages = 1;
                                323                 :                :     else
                                324                 :         155659 :         not_in_fsm_pages = num_pages;
                                325                 :                : 
                                326                 :                :     /* prepare to put another buffer into the bistate */
                                327   [ +  +  +  + ]:         155978 :     if (bistate && bistate->current_buf != InvalidBuffer)
                                328                 :                :     {
                                329                 :          10668 :         ReleaseBuffer(bistate->current_buf);
                                330                 :          10668 :         bistate->current_buf = InvalidBuffer;
                                331                 :                :     }
                                332                 :                : 
                                333                 :                :     /*
                                334                 :                :      * Extend the relation. We ask for the first returned page to be locked,
                                335                 :                :      * so that we are sure that nobody has inserted into the page
                                336                 :                :      * concurrently.
                                337                 :                :      *
                                338                 :                :      * With the current MAX_BUFFERS_TO_EXTEND_BY there's no danger of
                                339                 :                :      * [auto]vacuum trying to truncate later pages as REL_TRUNCATE_MINIMUM is
                                340                 :                :      * way larger.
                                341                 :                :      */
 1193 tmunro@postgresql.or      342         [ +  + ]:         155978 :     first_block = ExtendBufferedRelBy(BMR_REL(relation), MAIN_FORKNUM,
                                343                 :                :                                       bistate ? bistate->strategy : NULL,
                                344                 :                :                                       EB_LOCK_FIRST,
                                345                 :                :                                       extend_by_pages,
                                346                 :                :                                       victim_buffers,
                                347                 :                :                                       &extend_by_pages);
 1332 andres@anarazel.de        348                 :         155977 :     buffer = victim_buffers[0]; /* the buffer the function will return */
                                349                 :         155977 :     last_block = first_block + (extend_by_pages - 1);
                                350         [ -  + ]:         155977 :     Assert(first_block == BufferGetBlockNumber(buffer));
                                351                 :                : 
                                352                 :                :     /*
                                353                 :                :      * Relation is now extended. Initialize the page. We do this here, before
                                354                 :                :      * potentially releasing the lock on the page, because it allows us to
                                355                 :                :      * double check that the page contents are empty (this should never
                                356                 :                :      * happen, but if it does we don't want to risk wiping out valid data).
                                357                 :                :      */
                                358                 :         155977 :     page = BufferGetPage(buffer);
                                359         [ -  + ]:         155977 :     if (!PageIsNew(page))
 1332 andres@anarazel.de        360         [ #  # ]:UBC           0 :         elog(ERROR, "page %u of relation \"%s\" should be empty but is not",
                                361                 :                :              first_block,
                                362                 :                :              RelationGetRelationName(relation));
                                363                 :                : 
 1332 andres@anarazel.de        364                 :CBC      155977 :     PageInit(page, BufferGetPageSize(buffer), 0);
                                365                 :         155977 :     MarkBufferDirty(buffer);
                                366                 :                : 
                                367                 :                :     /*
                                368                 :                :      * If we decided to put pages into the FSM, release the buffer lock (but
                                369                 :                :      * not pin), we don't want to do IO while holding a buffer lock. This will
                                370                 :                :      * necessitate a bit more extensive checking in our caller.
                                371                 :                :      */
                                372   [ +  +  +  + ]:         155977 :     if (use_fsm && not_in_fsm_pages < extend_by_pages)
                                373                 :                :     {
                                374                 :            486 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                                375                 :            486 :         *did_unlock = true;
                                376                 :                :     }
                                377                 :                :     else
                                378                 :         155491 :         *did_unlock = false;
                                379                 :                : 
                                380                 :                :     /*
                                381                 :                :      * Relation is now extended. Release pins on all buffers, except for the
                                382                 :                :      * first (which we'll return).  If we decided to put pages into the FSM,
                                383                 :                :      * we can do that as part of the same loop.
                                384                 :                :      */
                                385         [ +  + ]:         179475 :     for (uint32 i = 1; i < extend_by_pages; i++)
                                386                 :                :     {
                                387                 :          23498 :         BlockNumber curBlock = first_block + i;
                                388                 :                : 
                                389         [ -  + ]:          23498 :         Assert(curBlock == BufferGetBlockNumber(victim_buffers[i]));
                                390         [ -  + ]:          23498 :         Assert(BlockNumberIsValid(curBlock));
                                391                 :                : 
                                392                 :          23498 :         ReleaseBuffer(victim_buffers[i]);
                                393                 :                : 
                                394   [ +  +  +  + ]:          23498 :         if (use_fsm && i >= not_in_fsm_pages)
                                395                 :                :         {
                                396                 :           6413 :             Size        freespace = BufferGetPageSize(victim_buffers[i]) -
                                397                 :                :                 SizeOfPageHeaderData;
                                398                 :                : 
                                399                 :           6413 :             RecordPageWithFreeSpace(relation, curBlock, freespace);
                                400                 :                :         }
                                401                 :                :     }
                                402                 :                : 
                                403   [ +  +  +  + ]:         155977 :     if (use_fsm && not_in_fsm_pages < extend_by_pages)
                                404                 :                :     {
                                405                 :            486 :         BlockNumber first_fsm_block = first_block + not_in_fsm_pages;
                                406                 :                : 
  136 melanieplageman@gmai      407                 :            486 :         FreeSpaceMapVacuumRange(relation, first_fsm_block, last_block + 1);
                                408                 :                :     }
                                409                 :                : 
 1332 andres@anarazel.de        410         [ +  + ]:         155977 :     if (bistate)
                                411                 :                :     {
                                412                 :                :         /*
                                413                 :                :          * Remember the additional pages we extended by, so we later can use
                                414                 :                :          * them without looking into the FSM.
                                415                 :                :          */
                                416         [ +  + ]:          12920 :         if (extend_by_pages > 1)
                                417                 :                :         {
                                418                 :           1312 :             bistate->next_free = first_block + 1;
                                419                 :           1312 :             bistate->last_free = last_block;
                                420                 :                :         }
                                421                 :                :         else
                                422                 :                :         {
                                423                 :          11608 :             bistate->next_free = InvalidBlockNumber;
                                424                 :          11608 :             bistate->last_free = InvalidBlockNumber;
                                425                 :                :         }
                                426                 :                : 
                                427                 :                :         /* maintain bistate->current_buf */
                                428                 :          12920 :         IncrBufferRefCount(buffer);
                                429                 :          12920 :         bistate->current_buf = buffer;
 1202                           430                 :          12920 :         bistate->already_extended_by += extend_by_pages;
                                431                 :                :     }
                                432                 :                : 
 1332                           433                 :         155977 :     return buffer;
                                434                 :                : #undef MAX_BUFFERS_TO_EXTEND_BY
                                435                 :                : }
                                436                 :                : 
                                437                 :                : /*
                                438                 :                :  * RelationGetBufferForTuple
                                439                 :                :  *
                                440                 :                :  *  Returns pinned and exclusive-locked buffer of a page in given relation
                                441                 :                :  *  with free space >= given len.
                                442                 :                :  *
                                443                 :                :  *  If num_pages is > 1, we will try to extend the relation by at least that
                                444                 :                :  *  many pages when we decide to extend the relation. This is more efficient
                                445                 :                :  *  for callers that know they will need multiple pages
                                446                 :                :  *  (e.g. heap_multi_insert()).
                                447                 :                :  *
                                448                 :                :  *  If otherBuffer is not InvalidBuffer, then it references a previously
                                449                 :                :  *  pinned buffer of another page in the same relation; on return, this
                                450                 :                :  *  buffer will also be exclusive-locked.  (This case is used by heap_update;
                                451                 :                :  *  the otherBuffer contains the tuple being updated.)
                                452                 :                :  *
                                453                 :                :  *  The reason for passing otherBuffer is that if two backends are doing
                                454                 :                :  *  concurrent heap_update operations, a deadlock could occur if they try
                                455                 :                :  *  to lock the same two buffers in opposite orders.  To ensure that this
                                456                 :                :  *  can't happen, we impose the rule that buffers of a relation must be
                                457                 :                :  *  locked in increasing page number order.  This is most conveniently done
                                458                 :                :  *  by having RelationGetBufferForTuple lock them both, with suitable care
                                459                 :                :  *  for ordering.
                                460                 :                :  *
                                461                 :                :  *  NOTE: it is unlikely, but not quite impossible, for otherBuffer to be the
                                462                 :                :  *  same buffer we select for insertion of the new tuple (this could only
                                463                 :                :  *  happen if space is freed in that page after heap_update finds there's not
                                464                 :                :  *  enough there).  In that case, the page will be pinned and locked only once.
                                465                 :                :  *
                                466                 :                :  *  We also handle the possibility that the all-visible flag will need to be
                                467                 :                :  *  cleared on one or both pages.  If so, pin on the associated visibility map
                                468                 :                :  *  page must be acquired before acquiring buffer lock(s), to avoid possibly
                                469                 :                :  *  doing I/O while holding buffer locks.  The pins are passed back to the
                                470                 :                :  *  caller using the input-output arguments vmbuffer and vmbuffer_other.
                                471                 :                :  *  Note that in some cases the caller might have already acquired such pins,
                                472                 :                :  *  which is indicated by these arguments not being InvalidBuffer on entry.
                                473                 :                :  *
                                474                 :                :  *  We normally use FSM to help us find free space.  However,
                                475                 :                :  *  if HEAP_INSERT_SKIP_FSM is specified, we just append a new empty page to
                                476                 :                :  *  the end of the relation if the tuple won't fit on the current target page.
                                477                 :                :  *  This can save some cycles when we know the relation is new and doesn't
                                478                 :                :  *  contain useful amounts of free space.
                                479                 :                :  *
                                480                 :                :  *  HEAP_INSERT_SKIP_FSM is also useful for non-WAL-logged additions to a
                                481                 :                :  *  relation, if the caller holds exclusive lock and is careful to invalidate
                                482                 :                :  *  relation's smgr_targblock before the first insertion --- that ensures that
                                483                 :                :  *  all insertions will occur into newly added pages and not be intermixed
                                484                 :                :  *  with tuples from other transactions.  That way, a crash can't risk losing
                                485                 :                :  *  any committed data of other transactions.  (See heap_insert's comments
                                486                 :                :  *  for additional constraints needed for safe usage of this behavior.)
                                487                 :                :  *
                                488                 :                :  *  The caller can also provide a BulkInsertState object to optimize many
                                489                 :                :  *  insertions into the same relation.  This keeps a pin on the current
                                490                 :                :  *  insertion target page (to save pin/unpin cycles) and also passes a
                                491                 :                :  *  BULKWRITE buffer selection strategy object to the buffer manager.
                                492                 :                :  *  Passing NULL for bistate selects the default behavior.
                                493                 :                :  *
                                494                 :                :  *  We don't fill existing pages further than the fillfactor, except for large
                                495                 :                :  *  tuples in nearly-empty pages.  This is OK since this routine is not
                                496                 :                :  *  consulted when updating a tuple and keeping it on the same page, which is
                                497                 :                :  *  the scenario fillfactor is meant to reserve space for.
                                498                 :                :  *
                                499                 :                :  *  ereport(ERROR) is allowed here, so this routine *must* be called
                                500                 :                :  *  before any (unlogged) changes are made in buffer pool.
                                501                 :                :  */
                                502                 :                : Buffer
 9327 tgl@sss.pgh.pa.us         503                 :       14805916 : RelationGetBufferForTuple(Relation relation, Size len,
                                504                 :                :                           Buffer otherBuffer, uint32 options,
                                505                 :                :                           BulkInsertState bistate,
                                506                 :                :                           Buffer *vmbuffer, Buffer *vmbuffer_other,
                                507                 :                :                           int num_pages)
                                508                 :                : {
 6596                           509                 :       14805916 :     bool        use_fsm = !(options & HEAP_INSERT_SKIP_FSM);
 9331                           510                 :       14805916 :     Buffer      buffer = InvalidBuffer;
                                511                 :                :     Page        page;
                                512                 :                :     Size        nearlyEmptyFreeSpace,
 2069 noah@leadboat.com         513                 :       14805916 :                 pageFreeSpace = 0,
                                514                 :       14805916 :                 saveFreeSpace = 0,
                                515                 :       14805916 :                 targetFreeSpace = 0;
                                516                 :                :     BlockNumber targetBlock,
                                517                 :                :                 otherBlock;
                                518                 :                :     bool        unlockedTargetBuffer;
                                519                 :                :     bool        recheckVmPins;
                                520                 :                : 
 9644 vadim4o@yahoo.com         521                 :       14805916 :     len = MAXALIGN(len);        /* be conservative */
                                522                 :                : 
                                523                 :                :     /* if the caller doesn't know by how many pages to extend, extend by 1 */
 1332 andres@anarazel.de        524         [ +  + ]:       14805916 :     if (num_pages <= 0)
                                525                 :       14304748 :         num_pages = 1;
                                526                 :                : 
                                527                 :                :     /* Bulk insert is not supported for updates, only inserts. */
 6596 tgl@sss.pgh.pa.us         528   [ +  +  -  + ]:       14805916 :     Assert(otherBuffer == InvalidBuffer || !bistate);
                                529                 :                : 
                                530                 :                :     /*
                                531                 :                :      * If we're gonna fail for oversize tuple, do it right away
                                532                 :                :      */
 7236                           533         [ -  + ]:       14805916 :     if (len > MaxHeapTupleSize)
 8531 tgl@sss.pgh.pa.us         534         [ #  # ]:UBC           0 :         ereport(ERROR,
                                535                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                536                 :                :                  errmsg("row is too big: size %zu, maximum size %zu",
                                537                 :                :                         len, MaxHeapTupleSize)));
                                538                 :                : 
                                539                 :                :     /* Compute desired extra freespace due to fillfactor option */
  961 akorotkov@postgresql      540         [ +  + ]:CBC    14805916 :     saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
                                541                 :                :                                                    HEAP_DEFAULT_FILLFACTOR);
                                542                 :                : 
                                543                 :                :     /*
                                544                 :                :      * Since pages without tuples can still have line pointers, we consider
                                545                 :                :      * pages "empty" when the unavailable space is slight.  This threshold is
                                546                 :                :      * somewhat arbitrary, but it should prevent most unnecessary relation
                                547                 :                :      * extensions while inserting large tuples into low-fillfactor tables.
                                548                 :                :      */
 2069 noah@leadboat.com         549                 :       14805916 :     nearlyEmptyFreeSpace = MaxHeapTupleSize -
                                550                 :                :         (MaxHeapTuplesPerPage / 8 * sizeof(ItemIdData));
                                551         [ +  + ]:       14805916 :     if (len + saveFreeSpace > nearlyEmptyFreeSpace)
                                552                 :           4058 :         targetFreeSpace = Max(len, nearlyEmptyFreeSpace);
                                553                 :                :     else
                                554                 :       14801858 :         targetFreeSpace = len + saveFreeSpace;
                                555                 :                : 
 9283 tgl@sss.pgh.pa.us         556         [ +  + ]:       14805916 :     if (otherBuffer != InvalidBuffer)
                                557                 :        2214500 :         otherBlock = BufferGetBlockNumber(otherBuffer);
                                558                 :                :     else
 3447                           559                 :       12591416 :         otherBlock = InvalidBlockNumber;    /* just to keep compiler quiet */
                                560                 :                : 
                                561                 :                :     /*
                                562                 :                :      * We first try to put the tuple on the same page we last inserted a tuple
                                563                 :                :      * on, as cached in the BulkInsertState or relcache entry.  If that
                                564                 :                :      * doesn't work, we ask the Free Space Map to locate a suitable page.
                                565                 :                :      * Since the FSM's info might be out of date, we have to be prepared to
                                566                 :                :      * loop around and retry multiple times. (To ensure this isn't an infinite
                                567                 :                :      * loop, we must update the FSM with the correct amount of free space on
                                568                 :                :      * each page that proves not to be suitable.)  If the FSM has no record of
                                569                 :                :      * a page with enough free space, we give up and extend the relation.
                                570                 :                :      *
                                571                 :                :      * When use_fsm is false, we either put the tuple onto the existing target
                                572                 :                :      * page or extend the relation.
                                573                 :                :      */
 2069 noah@leadboat.com         574   [ +  +  +  + ]:       14805916 :     if (bistate && bistate->current_buf != InvalidBuffer)
 6596 tgl@sss.pgh.pa.us         575                 :        2676384 :         targetBlock = BufferGetBlockNumber(bistate->current_buf);
                                576                 :                :     else
 6136                           577         [ +  + ]:       12129532 :         targetBlock = RelationGetTargetBlock(relation);
                                578                 :                : 
 7831                           579   [ +  +  +  + ]:       14805916 :     if (targetBlock == InvalidBlockNumber && use_fsm)
                                580                 :                :     {
                                581                 :                :         /*
                                582                 :                :          * We have no cached target page, so ask the FSM for an initial
                                583                 :                :          * target.
                                584                 :                :          */
 2069 noah@leadboat.com         585                 :          61361 :         targetBlock = GetPageWithFreeSpace(relation, targetFreeSpace);
                                586                 :                :     }
                                587                 :                : 
                                588                 :                :     /*
                                589                 :                :      * If the FSM knows nothing of the rel, try the last page before we give
                                590                 :                :      * up and extend.  This avoids one-tuple-per-page syndrome during
                                591                 :                :      * bootstrapping or in a recently-started system.
                                592                 :                :      */
 1999 tomas.vondra@postgre      593         [ +  + ]:       14805916 :     if (targetBlock == InvalidBlockNumber)
                                594                 :                :     {
                                595                 :          46685 :         BlockNumber nblocks = RelationGetNumberOfBlocks(relation);
                                596                 :                : 
                                597         [ +  + ]:          46685 :         if (nblocks > 0)
                                598                 :          26882 :             targetBlock = nblocks - 1;
                                599                 :                :     }
                                600                 :                : 
 3886 rhaas@postgresql.org      601                 :       14805916 : loop:
 9283 tgl@sss.pgh.pa.us         602         [ +  + ]:       14971843 :     while (targetBlock != InvalidBlockNumber)
                                603                 :                :     {
                                604                 :                :         /*
                                605                 :                :          * Read and exclusive-lock the target block, as well as the other
                                606                 :                :          * block if one was given, taking suitable care with lock ordering and
                                607                 :                :          * the possibility they are the same block.
                                608                 :                :          *
                                609                 :                :          * If the page-level all-visible flag is set, caller will need to
                                610                 :                :          * clear both that and the corresponding visibility map bit.  However,
                                611                 :                :          * by the time we return, we'll have x-locked the buffer, and we don't
                                612                 :                :          * want to do any I/O while in that state.  So we check the bit here
                                613                 :                :          * before taking the lock, and pin the page if it appears necessary.
                                614                 :                :          * Checking without the lock creates a risk of getting the wrong
                                615                 :                :          * answer, so we'll have to recheck after acquiring the lock.
                                616                 :                :          */
                                617         [ +  + ]:       14825914 :         if (otherBuffer == InvalidBuffer)
                                618                 :                :         {
                                619                 :                :             /* easy case */
 2855 andres@anarazel.de        620                 :       12608375 :             buffer = ReadBufferBI(relation, targetBlock, RBM_NORMAL, bistate);
 3874 kgrittn@postgresql.o      621         [ +  + ]:       12608374 :             if (PageIsAllVisible(BufferGetPage(buffer)))
 5639 rhaas@postgresql.org      622                 :          19391 :                 visibilitymap_pin(relation, targetBlock, vmbuffer);
                                623                 :                : 
                                624                 :                :             /*
                                625                 :                :              * If the page is empty, pin vmbuffer to set all_frozen bit later.
                                626                 :                :              */
 2141 tomas.vondra@postgre      627   [ +  +  +  + ]:       12613991 :             if ((options & HEAP_INSERT_FROZEN) &&
                                628                 :           5617 :                 (PageGetMaxOffsetNumber(BufferGetPage(buffer)) == 0))
                                629                 :           1613 :                 visibilitymap_pin(relation, targetBlock, vmbuffer);
                                630                 :                : 
 9283 tgl@sss.pgh.pa.us         631                 :       12608374 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                                632                 :                :         }
                                633         [ +  + ]:        2217539 :         else if (otherBlock == targetBlock)
                                634                 :                :         {
                                635                 :                :             /* also easy case */
                                636                 :           2283 :             buffer = otherBuffer;
 3874 kgrittn@postgresql.o      637         [ +  + ]:           2283 :             if (PageIsAllVisible(BufferGetPage(buffer)))
 5639 rhaas@postgresql.org      638                 :              2 :                 visibilitymap_pin(relation, targetBlock, vmbuffer);
 9283 tgl@sss.pgh.pa.us         639                 :           2283 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                                640                 :                :         }
                                641         [ +  + ]:        2215256 :         else if (otherBlock < targetBlock)
                                642                 :                :         {
                                643                 :                :             /* lock other buffer first */
                                644                 :        2197939 :             buffer = ReadBuffer(relation, targetBlock);
 3874 kgrittn@postgresql.o      645         [ +  + ]:        2197939 :             if (PageIsAllVisible(BufferGetPage(buffer)))
 5639 rhaas@postgresql.org      646                 :           1372 :                 visibilitymap_pin(relation, targetBlock, vmbuffer);
 9283 tgl@sss.pgh.pa.us         647                 :        2197939 :             LockBuffer(otherBuffer, BUFFER_LOCK_EXCLUSIVE);
 9327                           648                 :        2197939 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                                649                 :                :         }
                                650                 :                :         else
                                651                 :                :         {
                                652                 :                :             /* lock target buffer first */
 9283                           653                 :          17317 :             buffer = ReadBuffer(relation, targetBlock);
 3874 kgrittn@postgresql.o      654         [ +  + ]:          17317 :             if (PageIsAllVisible(BufferGetPage(buffer)))
 5639 rhaas@postgresql.org      655                 :            285 :                 visibilitymap_pin(relation, targetBlock, vmbuffer);
 9283 tgl@sss.pgh.pa.us         656                 :          17317 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                                657                 :          17317 :             LockBuffer(otherBuffer, BUFFER_LOCK_EXCLUSIVE);
                                658                 :                :         }
                                659                 :                : 
                                660                 :                :         /*
                                661                 :                :          * We now have the target page (and the other buffer, if any) pinned
                                662                 :                :          * and locked.  However, since our initial PageIsAllVisible checks
                                663                 :                :          * were performed before acquiring the lock, the results might now be
                                664                 :                :          * out of date, either for the selected victim buffer, or for the
                                665                 :                :          * other buffer passed by the caller.  In that case, we'll need to
                                666                 :                :          * give up our locks, go get the pin(s) we failed to get earlier, and
                                667                 :                :          * re-lock.  That's pretty painful, but hopefully shouldn't happen
                                668                 :                :          * often.
                                669                 :                :          *
                                670                 :                :          * Note that there's a small possibility that we didn't pin the page
                                671                 :                :          * above but still have the correct page pinned anyway, either because
                                672                 :                :          * we've already made a previous pass through this loop, or because
                                673                 :                :          * caller passed us the right page anyway.
                                674                 :                :          *
                                675                 :                :          * Note also that it's possible that by the time we get the pin and
                                676                 :                :          * retake the buffer locks, the visibility map bit will have been
                                677                 :                :          * cleared by some other backend anyway.  In that case, we'll have
                                678                 :                :          * done a bit of extra work for no gain, but there's no real harm
                                679                 :                :          * done.
                                680                 :                :          */
 1332 andres@anarazel.de        681                 :       14825913 :         GetVisibilityMapPins(relation, buffer, otherBuffer,
                                682                 :                :                              targetBlock, otherBlock, vmbuffer,
                                683                 :                :                              vmbuffer_other);
                                684                 :                : 
                                685                 :                :         /*
                                686                 :                :          * Now we can check to see if there's enough free space here. If so,
                                687                 :                :          * we're done.
                                688                 :                :          */
 3874 kgrittn@postgresql.o      689                 :       14825913 :         page = BufferGetPage(buffer);
                                690                 :                : 
                                691                 :                :         /*
                                692                 :                :          * If necessary initialize page, it'll be used soon.  We could avoid
                                693                 :                :          * dirtying the buffer here, and rely on the caller to do so whenever
                                694                 :                :          * it puts a tuple onto the page, but there seems not much benefit in
                                695                 :                :          * doing so.
                                696                 :                :          */
 2855 andres@anarazel.de        697         [ +  + ]:       14825913 :         if (PageIsNew(page))
                                698                 :                :         {
                                699                 :          18392 :             PageInit(page, BufferGetPageSize(buffer), 0);
                                700                 :          18392 :             MarkBufferDirty(buffer);
                                701                 :                :         }
                                702                 :                : 
 6712 tgl@sss.pgh.pa.us         703                 :       14825913 :         pageFreeSpace = PageGetHeapFreeSpace(page);
 2069 noah@leadboat.com         704         [ +  + ]:       14825913 :         if (targetFreeSpace <= pageFreeSpace)
                                705                 :                :         {
                                706                 :                :             /* use this page as future insert target, too */
 6136 tgl@sss.pgh.pa.us         707                 :       14649937 :             RelationSetTargetBlock(relation, targetBlock);
 9283                           708                 :       14649937 :             return buffer;
                                709                 :                :         }
                                710                 :                : 
                                711                 :                :         /*
                                712                 :                :          * Not enough space, so we must give up our page locks and pin (if
                                713                 :                :          * any) and prepare to look elsewhere.  We don't care which order we
                                714                 :                :          * unlock the two buffers in, so this can be slightly simpler than the
                                715                 :                :          * code above.
                                716                 :                :          */
                                717         [ +  + ]:         175976 :         if (otherBuffer == InvalidBuffer)
  246 andres@anarazel.de        718                 :         160549 :             UnlockReleaseBuffer(buffer);
 9283 tgl@sss.pgh.pa.us         719         [ +  + ]:          15427 :         else if (otherBlock != targetBlock)
                                720                 :                :         {
  246 andres@anarazel.de        721                 :          13144 :             UnlockReleaseBuffer(buffer);
 9283 tgl@sss.pgh.pa.us         722                 :          13144 :             LockBuffer(otherBuffer, BUFFER_LOCK_UNLOCK);
                                723                 :                :         }
                                724                 :                :         else
  246 andres@anarazel.de        725                 :           2283 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                                726                 :                : 
                                727                 :                :         /* Is there an ongoing bulk extension? */
 1332                           728   [ +  +  +  + ]:         175976 :         if (bistate && bistate->next_free != InvalidBlockNumber)
                                729                 :                :         {
                                730         [ -  + ]:          16651 :             Assert(bistate->next_free <= bistate->last_free);
                                731                 :                : 
                                732                 :                :             /*
                                733                 :                :              * We bulk extended the relation before, and there are still some
                                734                 :                :              * unused pages from that extension, so we don't need to look in
                                735                 :                :              * the FSM for a new page. But do record the free space from the
                                736                 :                :              * last page, somebody might insert narrower tuples later.
                                737                 :                :              */
                                738         [ +  + ]:          16651 :             if (use_fsm)
                                739                 :           5498 :                 RecordPageWithFreeSpace(relation, targetBlock, pageFreeSpace);
                                740                 :                : 
                                741                 :          16651 :             targetBlock = bistate->next_free;
                                742         [ +  + ]:          16651 :             if (bistate->next_free >= bistate->last_free)
                                743                 :                :             {
                                744                 :           1045 :                 bistate->next_free = InvalidBlockNumber;
                                745                 :           1045 :                 bistate->last_free = InvalidBlockNumber;
                                746                 :                :             }
                                747                 :                :             else
                                748                 :          15606 :                 bistate->next_free++;
                                749                 :                :         }
                                750         [ +  + ]:         159325 :         else if (!use_fsm)
                                751                 :                :         {
                                752                 :                :             /* Without FSM, always fall out of the loop and extend */
                                753                 :          10049 :             break;
                                754                 :                :         }
                                755                 :                :         else
                                756                 :                :         {
                                757                 :                :             /*
                                758                 :                :              * Update FSM as to condition of this page, and ask for another
                                759                 :                :              * page to try.
                                760                 :                :              */
                                761                 :         149276 :             targetBlock = RecordAndGetPageWithFreeSpace(relation,
                                762                 :                :                                                         targetBlock,
                                763                 :                :                                                         pageFreeSpace,
                                764                 :                :                                                         targetFreeSpace);
                                765                 :                :         }
                                766                 :                :     }
                                767                 :                : 
                                768                 :                :     /* Have to extend the relation */
                                769                 :         155978 :     buffer = RelationAddBlocks(relation, bistate, num_pages, use_fsm,
                                770                 :                :                                &unlockedTargetBuffer);
                                771                 :                : 
                                772                 :         155977 :     targetBlock = BufferGetBlockNumber(buffer);
 2855                           773                 :         155977 :     page = BufferGetPage(buffer);
                                774                 :                : 
                                775                 :                :     /*
                                776                 :                :      * The page is empty, pin vmbuffer to set all_frozen bit. We don't want to
                                777                 :                :      * do IO while the buffer is locked, so we unlock the page first if IO is
                                778                 :                :      * needed (necessitating checks below).
                                779                 :                :      */
 2141 tomas.vondra@postgre      780         [ +  + ]:         155977 :     if (options & HEAP_INSERT_FROZEN)
                                781                 :                :     {
 1332 andres@anarazel.de        782         [ -  + ]:            373 :         Assert(PageGetMaxOffsetNumber(page) == 0);
                                783                 :                : 
                                784         [ +  + ]:            373 :         if (!visibilitymap_pin_ok(targetBlock, *vmbuffer))
                                785                 :                :         {
                                786         [ +  - ]:            346 :             if (!unlockedTargetBuffer)
                                787                 :            346 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                                788                 :            346 :             unlockedTargetBuffer = true;
                                789                 :            346 :             visibilitymap_pin(relation, targetBlock, vmbuffer);
                                790                 :                :         }
                                791                 :                :     }
                                792                 :                : 
                                793                 :                :     /*
                                794                 :                :      * Reacquire locks if necessary.
                                795                 :                :      *
                                796                 :                :      * If the target buffer was unlocked above, or is unlocked while
                                797                 :                :      * reacquiring the lock on otherBuffer below, it's unlikely, but possible,
                                798                 :                :      * that another backend used space on this page. We check for that below,
                                799                 :                :      * and retry if necessary.
                                800                 :                :      */
                                801                 :         155977 :     recheckVmPins = false;
                                802         [ +  + ]:         155977 :     if (unlockedTargetBuffer)
                                803                 :                :     {
                                804                 :                :         /* released lock on target buffer above */
                                805         [ -  + ]:            832 :         if (otherBuffer != InvalidBuffer)
 1332 andres@anarazel.de        806                 :LBC         (2) :             LockBuffer(otherBuffer, BUFFER_LOCK_EXCLUSIVE);
 1332 andres@anarazel.de        807                 :CBC         832 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                                808                 :            832 :         recheckVmPins = true;
                                809                 :                :     }
                                810         [ +  + ]:         155145 :     else if (otherBuffer != InvalidBuffer)
                                811                 :                :     {
                                812                 :                :         /*
                                813                 :                :          * We did not release the target buffer, and otherBuffer is valid,
                                814                 :                :          * need to lock the other buffer. It's guaranteed to be of a lower
                                815                 :                :          * page number than the new page.  To conform with the deadlock
                                816                 :                :          * prevent rules, we ought to lock otherBuffer first, but that would
                                817                 :                :          * give other backends a chance to put tuples on our page. To reduce
                                818                 :                :          * the likelihood of that, attempt to lock the other buffer
                                819                 :                :          * conditionally, that's very likely to work.
                                820                 :                :          *
                                821                 :                :          * Alternatively, we could acquire the lock on otherBuffer before
                                822                 :                :          * extending the relation, but that'd require holding the lock while
                                823                 :                :          * performing IO, which seems worse than an unlikely retry.
                                824                 :                :          */
 2855                           825         [ -  + ]:          12388 :         Assert(otherBuffer != buffer);
 2055 tgl@sss.pgh.pa.us         826         [ -  + ]:          12388 :         Assert(targetBlock > otherBlock);
                                827                 :                : 
 2855 andres@anarazel.de        828         [ -  + ]:          12388 :         if (unlikely(!ConditionalLockBuffer(otherBuffer)))
                                829                 :                :         {
 1332 andres@anarazel.de        830                 :LBC         (2) :             unlockedTargetBuffer = true;
 2855                           831                 :            (2) :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                                832                 :            (2) :             LockBuffer(otherBuffer, BUFFER_LOCK_EXCLUSIVE);
                                833                 :            (2) :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                                834                 :                :         }
 1332 andres@anarazel.de        835                 :CBC       12388 :         recheckVmPins = true;
                                836                 :                :     }
                                837                 :                : 
                                838                 :                :     /*
                                839                 :                :      * If one of the buffers was unlocked (always the case if otherBuffer is
                                840                 :                :      * valid), it's possible, although unlikely, that an all-visible flag
                                841                 :                :      * became set.  We can use GetVisibilityMapPins to deal with that. It's
                                842                 :                :      * possible that GetVisibilityMapPins() might need to temporarily release
                                843                 :                :      * buffer locks, in which case we'll need to check if there's still enough
                                844                 :                :      * space on the page below.
                                845                 :                :      */
                                846         [ +  + ]:         155977 :     if (recheckVmPins)
                                847                 :                :     {
                                848         [ -  + ]:          13220 :         if (GetVisibilityMapPins(relation, otherBuffer, buffer,
                                849                 :                :                                  otherBlock, targetBlock, vmbuffer_other,
                                850                 :                :                                  vmbuffer))
 1332 andres@anarazel.de        851                 :UBC           0 :             unlockedTargetBuffer = true;
                                852                 :                :     }
                                853                 :                : 
                                854                 :                :     /*
                                855                 :                :      * If the target buffer was temporarily unlocked since the relation
                                856                 :                :      * extension, it's possible, although unlikely, that all the space on the
                                857                 :                :      * page was already used. If so, we just retry from the start.  If we
                                858                 :                :      * didn't unlock, something has gone wrong if there's not enough space -
                                859                 :                :      * the test at the top should have prevented reaching this case.
                                860                 :                :      */
 1332 andres@anarazel.de        861                 :CBC      155977 :     pageFreeSpace = PageGetHeapFreeSpace(page);
                                862         [ -  + ]:         155977 :     if (len > pageFreeSpace)
                                863                 :                :     {
 1332 andres@anarazel.de        864         [ #  # ]:UBC           0 :         if (unlockedTargetBuffer)
                                865                 :                :         {
                                866         [ #  # ]:              0 :             if (otherBuffer != InvalidBuffer)
                                867                 :              0 :                 LockBuffer(otherBuffer, BUFFER_LOCK_UNLOCK);
 1520 tgl@sss.pgh.pa.us         868                 :              0 :             UnlockReleaseBuffer(buffer);
                                869                 :                : 
                                870                 :              0 :             goto loop;
                                871                 :                :         }
 4692                           872         [ #  # ]:              0 :         elog(PANIC, "tuple is too big: size %zu", len);
                                873                 :                :     }
                                874                 :                : 
                                875                 :                :     /*
                                876                 :                :      * Remember the new page as our target for future insertions.
                                877                 :                :      *
                                878                 :                :      * XXX should we enter the new page into the free space map immediately,
                                879                 :                :      * or just keep it for this backend's exclusive use in the short run
                                880                 :                :      * (until VACUUM sees it)?  Seems to depend on whether you expect the
                                881                 :                :      * current backend to make more insertions or not, which is probably a
                                882                 :                :      * good bet most of the time.  So for now, don't add it to FSM yet.
                                883                 :                :      */
 1332 andres@anarazel.de        884                 :CBC      155977 :     RelationSetTargetBlock(relation, targetBlock);
                                885                 :                : 
 9331 tgl@sss.pgh.pa.us         886                 :         155977 :     return buffer;
                                887                 :                : }
        

Generated by: LCOV version 2.0-1