LCOV - differential code coverage report
Current view: top level - src/backend/access/hash - hashpage.c (source / functions) Coverage Total Hit UBC CBC
Current: 1a1248818fb8b8b0353c292c632d6a6af77e8209 vs 8e82d6610e7280d7870c0c36ff1c797e3cfb3e09 Lines: 88.7 % 488 433 55 433
Current Date: 2026-10-12 11:56:10 +0200 Functions: 100.0 % 19 19 19
Baseline: lcov-20261012-baseline Branches: 56.8 % 264 150 114 150
Baseline Date: 2026-10-12 10:36:06 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 2 2 2
(30,360] days: 70.0 % 10 7 3 7
(360..) days: 89.1 % 476 424 52 424
Function coverage date bins:
(360..) days: 100.0 % 19 19 19
Branch coverage date bins:
(360..) days: 56.8 % 264 150 114 150

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * hashpage.c
                                  4                 :                :  *    Hash table page management code for the Postgres hash access method
                                  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/hash/hashpage.c
                                 12                 :                :  *
                                 13                 :                :  * NOTES
                                 14                 :                :  *    Postgres hash pages look like ordinary relation pages.  The opaque
                                 15                 :                :  *    data at high addresses includes information about the page including
                                 16                 :                :  *    whether a page is an overflow page or a true bucket, the bucket
                                 17                 :                :  *    number, and the block numbers of the preceding and following pages
                                 18                 :                :  *    in the same bucket.
                                 19                 :                :  *
                                 20                 :                :  *    The first page in a hash relation, page zero, is special -- it stores
                                 21                 :                :  *    information describing the hash table; it is referred to as the
                                 22                 :                :  *    "meta page." Pages one and higher store the actual data.
                                 23                 :                :  *
                                 24                 :                :  *    There are also bitmap pages, which are not manipulated here;
                                 25                 :                :  *    see hashovfl.c.
                                 26                 :                :  *
                                 27                 :                :  *-------------------------------------------------------------------------
                                 28                 :                :  */
                                 29                 :                : #include "postgres.h"
                                 30                 :                : 
                                 31                 :                : #include "access/hash.h"
                                 32                 :                : #include "access/hash_xlog.h"
                                 33                 :                : #include "access/xloginsert.h"
                                 34                 :                : #include "miscadmin.h"
                                 35                 :                : #include "port/pg_bitutils.h"
                                 36                 :                : #include "storage/predicate.h"
                                 37                 :                : #include "storage/smgr.h"
                                 38                 :                : #include "utils/injection_point.h"
                                 39                 :                : #include "utils/rel.h"
                                 40                 :                : 
                                 41                 :                : static bool _hash_alloc_buckets(Relation rel, BlockNumber firstblock,
                                 42                 :                :                                 uint32 nblocks);
                                 43                 :                : static void _hash_splitbucket(Relation rel, Buffer metabuf,
                                 44                 :                :                               Bucket obucket, Bucket nbucket,
                                 45                 :                :                               Buffer obuf,
                                 46                 :                :                               Buffer nbuf,
                                 47                 :                :                               HTAB *htab,
                                 48                 :                :                               uint32 maxbucket,
                                 49                 :                :                               uint32 highmask, uint32 lowmask);
                                 50                 :                : static void log_split_page(Relation rel, Buffer buf);
                                 51                 :                : 
                                 52                 :                : 
                                 53                 :                : /*
                                 54                 :                :  *  _hash_getbuf() -- Get a buffer by block number for read or write.
                                 55                 :                :  *
                                 56                 :                :  *      'access' must be HASH_READ, HASH_WRITE, or HASH_NOLOCK.
                                 57                 :                :  *      'flags' is a bitwise OR of the allowed page types.
                                 58                 :                :  *
                                 59                 :                :  *      This must be used only to fetch pages that are expected to be valid
                                 60                 :                :  *      already.  _hash_checkpage() is applied using the given flags.
                                 61                 :                :  *
                                 62                 :                :  *      When this routine returns, the appropriate lock is set on the
                                 63                 :                :  *      requested buffer and its reference count has been incremented
                                 64                 :                :  *      (ie, the buffer is "locked and pinned").
                                 65                 :                :  *
                                 66                 :                :  *      P_NEW is disallowed because this routine can only be used
                                 67                 :                :  *      to access pages that are known to be before the filesystem EOF.
                                 68                 :                :  *      Extending the index should be done with _hash_getnewbuf.
                                 69                 :                :  */
                                 70                 :                : Buffer
 7102 tgl@sss.pgh.pa.us          71                 :CBC     1342025 : _hash_getbuf(Relation rel, BlockNumber blkno, int access, int flags)
                                 72                 :                : {
                                 73                 :                :     Buffer      buf;
                                 74                 :                : 
 7116                            75         [ -  + ]:        1342025 :     if (blkno == P_NEW)
 7116 tgl@sss.pgh.pa.us          76         [ #  # ]:UBC           0 :         elog(ERROR, "hash AM does not use P_NEW");
                                 77                 :                : 
 8439 tgl@sss.pgh.pa.us          78                 :CBC     1342025 :     buf = ReadBuffer(rel, blkno);
                                 79                 :                : 
                                 80         [ +  + ]:        1342025 :     if (access != HASH_NOLOCK)
                                 81                 :         850255 :         LockBuffer(buf, access);
                                 82                 :                : 
                                 83                 :                :     /* ref count and lock type are correct */
                                 84                 :                : 
 7102                            85                 :        1342025 :     _hash_checkpage(rel, buf, flags);
                                 86                 :                : 
                                 87                 :        1342025 :     return buf;
                                 88                 :                : }
                                 89                 :                : 
                                 90                 :                : /*
                                 91                 :                :  * _hash_getbuf_with_condlock_cleanup() -- Try to get a buffer for cleanup.
                                 92                 :                :  *
                                 93                 :                :  *      We read the page and try to acquire a cleanup lock.  If we get it,
                                 94                 :                :  *      we return the buffer; otherwise, we return InvalidBuffer.
                                 95                 :                :  */
                                 96                 :                : Buffer
 3603 rhaas@postgresql.org       97                 :            892 : _hash_getbuf_with_condlock_cleanup(Relation rel, BlockNumber blkno, int flags)
                                 98                 :                : {
                                 99                 :                :     Buffer      buf;
                                100                 :                : 
                                101         [ -  + ]:            892 :     if (blkno == P_NEW)
 3603 rhaas@postgresql.org      102         [ #  # ]:UBC           0 :         elog(ERROR, "hash AM does not use P_NEW");
                                103                 :                : 
 3603 rhaas@postgresql.org      104                 :CBC         892 :     buf = ReadBuffer(rel, blkno);
                                105                 :                : 
                                106         [ -  + ]:            892 :     if (!ConditionalLockBufferForCleanup(buf))
                                107                 :                :     {
 3603 rhaas@postgresql.org      108                 :UBC           0 :         ReleaseBuffer(buf);
                                109                 :              0 :         return InvalidBuffer;
                                110                 :                :     }
                                111                 :                : 
                                112                 :                :     /* ref count and lock type are correct */
                                113                 :                : 
 3603 rhaas@postgresql.org      114                 :CBC         892 :     _hash_checkpage(rel, buf, flags);
                                115                 :                : 
                                116                 :            892 :     return buf;
                                117                 :                : }
                                118                 :                : 
                                119                 :                : /*
                                120                 :                :  *  _hash_getinitbuf() -- Get and initialize a buffer by block number.
                                121                 :                :  *
                                122                 :                :  *      This must be used only to fetch pages that are known to be before
                                123                 :                :  *      the index's filesystem EOF, but are to be filled from scratch.
                                124                 :                :  *      _hash_pageinit() is applied automatically.  Otherwise it has
                                125                 :                :  *      effects similar to _hash_getbuf() with access = HASH_WRITE.
                                126                 :                :  *
                                127                 :                :  *      When this routine returns, a write lock is set on the
                                128                 :                :  *      requested buffer and its reference count has been incremented
                                129                 :                :  *      (ie, the buffer is "locked and pinned").
                                130                 :                :  *
                                131                 :                :  *      P_NEW is disallowed because this routine can only be used
                                132                 :                :  *      to access pages that are known to be before the filesystem EOF.
                                133                 :                :  *      Extending the index should be done with _hash_getnewbuf.
                                134                 :                :  */
                                135                 :                : Buffer
 7102 tgl@sss.pgh.pa.us         136                 :             46 : _hash_getinitbuf(Relation rel, BlockNumber blkno)
                                137                 :                : {
                                138                 :                :     Buffer      buf;
                                139                 :                : 
                                140         [ -  + ]:             46 :     if (blkno == P_NEW)
 7102 tgl@sss.pgh.pa.us         141         [ #  # ]:UBC           0 :         elog(ERROR, "hash AM does not use P_NEW");
                                142                 :                : 
 4351 heikki.linnakangas@i      143                 :CBC          46 :     buf = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_ZERO_AND_LOCK,
                                144                 :                :                              NULL);
                                145                 :                : 
                                146                 :                :     /* ref count and lock type are correct */
                                147                 :                : 
                                148                 :                :     /* initialize the page */
 3827 kgrittn@postgresql.o      149                 :             46 :     _hash_pageinit(BufferGetPage(buf), BufferGetPageSize(buf));
                                150                 :                : 
 8439 tgl@sss.pgh.pa.us         151                 :             46 :     return buf;
                                152                 :                : }
                                153                 :                : 
                                154                 :                : /*
                                155                 :                :  *  _hash_initbuf() -- Get and initialize a buffer by bucket number.
                                156                 :                :  */
                                157                 :                : void
 3506 rhaas@postgresql.org      158                 :           5589 : _hash_initbuf(Buffer buf, uint32 max_bucket, uint32 num_bucket, uint32 flag,
                                159                 :                :               bool initpage)
                                160                 :                : {
                                161                 :                :     HashPageOpaque pageopaque;
                                162                 :                :     Page        page;
                                163                 :                : 
                                164                 :           5589 :     page = BufferGetPage(buf);
                                165                 :                : 
                                166                 :                :     /* initialize the page */
                                167         [ +  + ]:           5589 :     if (initpage)
                                168                 :            291 :         _hash_pageinit(page, BufferGetPageSize(buf));
                                169                 :                : 
 1655 michael@paquier.xyz       170                 :           5589 :     pageopaque = HashPageGetOpaque(page);
                                171                 :                : 
                                172                 :                :     /*
                                173                 :                :      * Set hasho_prevblkno with current hashm_maxbucket. This value will be
                                174                 :                :      * used to validate cached HashMetaPageData. See
                                175                 :                :      * _hash_getbucketbuf_from_hashkey().
                                176                 :                :      */
 3506 rhaas@postgresql.org      177                 :           5589 :     pageopaque->hasho_prevblkno = max_bucket;
                                178                 :           5589 :     pageopaque->hasho_nextblkno = InvalidBlockNumber;
                                179                 :           5589 :     pageopaque->hasho_bucket = num_bucket;
                                180                 :           5589 :     pageopaque->hasho_flag = flag;
                                181                 :           5589 :     pageopaque->hasho_page_id = HASHO_PAGE_ID;
                                182                 :           5589 : }
                                183                 :                : 
                                184                 :                : /*
                                185                 :                :  *  _hash_getnewbuf() -- Get a new page at the end of the index.
                                186                 :                :  *
                                187                 :                :  *      This has the same API as _hash_getinitbuf, except that we are adding
                                188                 :                :  *      a page to the index, and hence expect the page to be past the
                                189                 :                :  *      logical EOF.  (However, we have to support the case where it isn't,
                                190                 :                :  *      since a prior try might have crashed after extending the filesystem
                                191                 :                :  *      EOF but before updating the metapage to reflect the added page.)
                                192                 :                :  *
                                193                 :                :  *      It is caller's responsibility to ensure that only one process can
                                194                 :                :  *      extend the index at a time.  In practice, this function is called
                                195                 :                :  *      only while holding write lock on the metapage, because adding a page
                                196                 :                :  *      is always associated with an update of metapage data.
                                197                 :                :  */
                                198                 :                : Buffer
 5766                           199                 :           6856 : _hash_getnewbuf(Relation rel, BlockNumber blkno, ForkNumber forkNum)
                                200                 :                : {
                                201                 :           6856 :     BlockNumber nblocks = RelationGetNumberOfBlocksInFork(rel, forkNum);
                                202                 :                :     Buffer      buf;
                                203                 :                : 
 7116 tgl@sss.pgh.pa.us         204         [ -  + ]:           6856 :     if (blkno == P_NEW)
 7116 tgl@sss.pgh.pa.us         205         [ #  # ]:UBC           0 :         elog(ERROR, "hash AM does not use P_NEW");
 7116 tgl@sss.pgh.pa.us         206         [ -  + ]:CBC        6856 :     if (blkno > nblocks)
 7116 tgl@sss.pgh.pa.us         207         [ #  # ]:UBC           0 :         elog(ERROR, "access to noncontiguous page in hash index \"%s\"",
                                208                 :                :              RelationGetRelationName(rel));
                                209                 :                : 
                                210                 :                :     /* smgr insists we explicitly extend the relation */
 7116 tgl@sss.pgh.pa.us         211         [ +  + ]:CBC        6856 :     if (blkno == nblocks)
                                212                 :                :     {
 1146 tmunro@postgresql.or      213                 :           5964 :         buf = ExtendBufferedRel(BMR_REL(rel), forkNum, NULL,
                                214                 :                :                                 EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
 7116 tgl@sss.pgh.pa.us         215         [ -  + ]:           5964 :         if (BufferGetBlockNumber(buf) != blkno)
 7116 tgl@sss.pgh.pa.us         216         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected hash relation size: %u, should be %u",
                                217                 :                :                  BufferGetBlockNumber(buf), blkno);
                                218                 :                :     }
                                219                 :                :     else
                                220                 :                :     {
 4351 heikki.linnakangas@i      221                 :CBC         892 :         buf = ReadBufferExtended(rel, forkNum, blkno, RBM_ZERO_AND_LOCK,
                                222                 :                :                                  NULL);
                                223                 :                :     }
                                224                 :                : 
                                225                 :                :     /* ref count and lock type are correct */
                                226                 :                : 
                                227                 :                :     /* initialize the page */
 3827 kgrittn@postgresql.o      228                 :           6856 :     _hash_pageinit(BufferGetPage(buf), BufferGetPageSize(buf));
                                229                 :                : 
 7116 tgl@sss.pgh.pa.us         230                 :           6856 :     return buf;
                                231                 :                : }
                                232                 :                : 
                                233                 :                : /*
                                234                 :                :  *  _hash_getbuf_with_strategy() -- Get a buffer with nondefault strategy.
                                235                 :                :  *
                                236                 :                :  *      This is identical to _hash_getbuf() but also allows a buffer access
                                237                 :                :  *      strategy to be specified.  We use this for VACUUM operations.
                                238                 :                :  */
                                239                 :                : Buffer
 7075                           240                 :            798 : _hash_getbuf_with_strategy(Relation rel, BlockNumber blkno,
                                241                 :                :                            int access, int flags,
                                242                 :                :                            BufferAccessStrategy bstrategy)
                                243                 :                : {
                                244                 :                :     Buffer      buf;
                                245                 :                : 
                                246         [ -  + ]:            798 :     if (blkno == P_NEW)
 7075 tgl@sss.pgh.pa.us         247         [ #  # ]:UBC           0 :         elog(ERROR, "hash AM does not use P_NEW");
                                248                 :                : 
 6555 heikki.linnakangas@i      249                 :CBC         798 :     buf = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL, bstrategy);
                                250                 :                : 
 7075 tgl@sss.pgh.pa.us         251         [ +  - ]:            798 :     if (access != HASH_NOLOCK)
                                252                 :            798 :         LockBuffer(buf, access);
                                253                 :                : 
                                254                 :                :     /* ref count and lock type are correct */
                                255                 :                : 
                                256                 :            798 :     _hash_checkpage(rel, buf, flags);
                                257                 :                : 
                                258                 :            798 :     return buf;
                                259                 :                : }
                                260                 :                : 
                                261                 :                : /*
                                262                 :                :  *  _hash_relbuf() -- release a locked buffer.
                                263                 :                :  *
                                264                 :                :  * Lock and pin (refcount) are both dropped.
                                265                 :                :  */
                                266                 :                : void
 8439                           267                 :         788929 : _hash_relbuf(Relation rel, Buffer buf)
                                268                 :                : {
 7500                           269                 :         788929 :     UnlockReleaseBuffer(buf);
 8439                           270                 :         788929 : }
                                271                 :                : 
                                272                 :                : /*
                                273                 :                :  *  _hash_dropbuf() -- release an unlocked buffer.
                                274                 :                :  *
                                275                 :                :  * This is used to unpin a buffer on which we hold no lock.
                                276                 :                :  */
                                277                 :                : void
                                278                 :         562075 : _hash_dropbuf(Relation rel, Buffer buf)
                                279                 :                : {
                                280                 :         562075 :     ReleaseBuffer(buf);
                                281                 :         562075 : }
                                282                 :                : 
                                283                 :                : /*
                                284                 :                :  *  _hash_dropscanbuf() -- release buffers used in scan.
                                285                 :                :  *
                                286                 :                :  * This routine unpins the buffers used during scan on which we
                                287                 :                :  * hold no lock.
                                288                 :                :  */
                                289                 :                : void
 3603 rhaas@postgresql.org      290                 :            842 : _hash_dropscanbuf(Relation rel, HashScanOpaque so)
                                291                 :                : {
                                292                 :                :     /* release pin we hold on primary bucket page */
                                293         [ +  + ]:            842 :     if (BufferIsValid(so->hashso_bucket_buf) &&
 3307                           294         [ +  + ]:            345 :         so->hashso_bucket_buf != so->currPos.buf)
 3603                           295                 :             95 :         _hash_dropbuf(rel, so->hashso_bucket_buf);
                                296                 :            842 :     so->hashso_bucket_buf = InvalidBuffer;
                                297                 :                : 
                                298                 :                :     /* release pin we hold on primary bucket page  of bucket being split */
                                299         [ +  + ]:            842 :     if (BufferIsValid(so->hashso_split_bucket_buf) &&
 3307                           300         [ +  + ]:              3 :         so->hashso_split_bucket_buf != so->currPos.buf)
 3603                           301                 :              1 :         _hash_dropbuf(rel, so->hashso_split_bucket_buf);
                                302                 :            842 :     so->hashso_split_bucket_buf = InvalidBuffer;
                                303                 :                : 
                                304                 :                :     /* release any pin we still hold */
 3307                           305         [ +  + ]:            842 :     if (BufferIsValid(so->currPos.buf))
                                306                 :            252 :         _hash_dropbuf(rel, so->currPos.buf);
                                307                 :            842 :     so->currPos.buf = InvalidBuffer;
                                308                 :                : 
                                309                 :                :     /* reset split scan */
 3603                           310                 :            842 :     so->hashso_buc_populated = false;
                                311                 :            842 :     so->hashso_buc_split = false;
                                312                 :            842 : }
                                313                 :                : 
                                314                 :                : 
                                315                 :                : /*
                                316                 :                :  *  _hash_init() -- Initialize the metadata page of a hash index,
                                317                 :                :  *              the initial buckets, and the initial bitmap page.
                                318                 :                :  *
                                319                 :                :  * The initial number of buckets is dependent on num_tuples, an estimate
                                320                 :                :  * of the number of tuples to be loaded into the index initially.  The
                                321                 :                :  * chosen number of buckets is returned.
                                322                 :                :  *
                                323                 :                :  * We are fairly cavalier about locking here, since we know that no one else
                                324                 :                :  * could be accessing this index.  In particular the rule about not holding
                                325                 :                :  * multiple buffer locks is ignored.
                                326                 :                :  */
                                327                 :                : uint32
 3506                           328                 :            216 : _hash_init(Relation rel, double num_tuples, ForkNumber forkNum)
                                329                 :                : {
                                330                 :                :     Buffer      metabuf;
                                331                 :                :     Buffer      buf;
                                332                 :                :     Buffer      bitmapbuf;
                                333                 :                :     Page        pg;
                                334                 :                :     HashMetaPage metap;
                                335                 :                :     RegProcedure procid;
                                336                 :                :     int32       data_width;
                                337                 :                :     int32       item_width;
                                338                 :                :     int32       ffactor;
                                339                 :                :     uint32      num_buckets;
                                340                 :                :     uint32      i;
                                341                 :                :     bool        use_wal;
                                342                 :                : 
                                343                 :                :     /* safety check */
 5766                           344         [ -  + ]:            216 :     if (RelationGetNumberOfBlocksInFork(rel, forkNum) != 0)
 8484 tgl@sss.pgh.pa.us         345         [ #  # ]:UBC           0 :         elog(ERROR, "cannot initialize non-empty hash index \"%s\"",
                                346                 :                :              RelationGetRelationName(rel));
                                347                 :                : 
                                348                 :                :     /*
                                349                 :                :      * WAL log creation of pages if the relation is persistent, or this is the
                                350                 :                :      * init fork.  Init forks for unlogged relations always need to be WAL
                                351                 :                :      * logged.
                                352                 :                :      */
 3374 rhaas@postgresql.org      353   [ +  +  +  +  :CBC         216 :     use_wal = RelationNeedsWAL(rel) || forkNum == INIT_FORKNUM;
                                     -  +  -  -  +  
                                                 + ]
                                354                 :                : 
                                355                 :                :     /*
                                356                 :                :      * Determine the target fill factor (in tuples per bucket) for this index.
                                357                 :                :      * The idea is to make the fill factor correspond to pages about as full
                                358                 :                :      * as the user-settable fillfactor parameter says.  We can compute it
                                359                 :                :      * exactly since the index datatype (i.e. uint32 hash key) is fixed-width.
                                360                 :                :      */
 6601 tgl@sss.pgh.pa.us         361                 :            216 :     data_width = sizeof(uint32);
 7565                           362                 :            216 :     item_width = MAXALIGN(sizeof(IndexTupleData)) + MAXALIGN(data_width) +
                                363                 :                :         sizeof(ItemIdData);     /* include the line pointer */
 2513 michael@paquier.xyz       364   [ +  -  -  +  :            216 :     ffactor = HashGetTargetPageUsage(rel) / item_width;
                                              +  + ]
                                365                 :                :     /* keep to a sane range */
 8439 tgl@sss.pgh.pa.us         366         [ -  + ]:            216 :     if (ffactor < 10)
 8439 tgl@sss.pgh.pa.us         367                 :UBC           0 :         ffactor = 10;
                                368                 :                : 
 3329 rhaas@postgresql.org      369                 :CBC         216 :     procid = index_getprocid(rel, 1, HASHSTANDARD_PROC);
                                370                 :                : 
                                371                 :                :     /*
                                372                 :                :      * We initialize the metapage, the first N bucket pages, and the first
                                373                 :                :      * bitmap page in sequence, using _hash_getnewbuf to cause smgrextend()
                                374                 :                :      * calls to occur.  This ensures that the smgr level has the right idea of
                                375                 :                :      * the physical index length.
                                376                 :                :      *
                                377                 :                :      * Critical section not required, because on error the creation of the
                                378                 :                :      * whole relation will be rolled back.
                                379                 :                :      */
 3506                           380                 :            216 :     metabuf = _hash_getnewbuf(rel, HASH_METAPAGE, forkNum);
                                381                 :            216 :     _hash_init_metabuffer(metabuf, num_tuples, procid, ffactor, false);
                                382                 :            216 :     MarkBufferDirty(metabuf);
                                383                 :                : 
                                384                 :            216 :     pg = BufferGetPage(metabuf);
                                385                 :            216 :     metap = HashPageGetMeta(pg);
                                386                 :                : 
                                387                 :                :     /* XLOG stuff */
 3374                           388         [ +  + ]:            216 :     if (use_wal)
                                389                 :                :     {
                                390                 :                :         xl_hash_init_meta_page xlrec;
                                391                 :                :         XLogRecPtr  recptr;
                                392                 :                : 
 3499                           393                 :            170 :         xlrec.num_tuples = num_tuples;
                                394                 :            170 :         xlrec.procid = metap->hashm_procid;
                                395                 :            170 :         xlrec.ffactor = metap->hashm_ffactor;
                                396                 :                : 
                                397                 :            170 :         XLogBeginInsert();
  608 peter@eisentraut.org      398                 :            170 :         XLogRegisterData(&xlrec, SizeOfHashInitMetaPage);
 3265 tgl@sss.pgh.pa.us         399                 :            170 :         XLogRegisterBuffer(0, metabuf, REGBUF_WILL_INIT | REGBUF_STANDARD);
                                400                 :                : 
 3499 rhaas@postgresql.org      401                 :            170 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_INIT_META_PAGE);
                                402                 :                : 
                                403                 :            170 :         PageSetLSN(BufferGetPage(metabuf), recptr);
                                404                 :                :     }
                                405                 :                : 
 3506                           406                 :            216 :     num_buckets = metap->hashm_maxbucket + 1;
                                407                 :                : 
                                408                 :                :     /*
                                409                 :                :      * Release buffer lock on the metapage while we initialize buckets.
                                410                 :                :      * Otherwise, we'll be in interrupt holdoff and the CHECK_FOR_INTERRUPTS
                                411                 :                :      * won't accomplish anything.  It's a bad idea to hold buffer locks for
                                412                 :                :      * long intervals in any case, since that can block the bgwriter.
                                413                 :                :      */
                                414                 :            216 :     LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
                                415                 :                : 
                                416                 :                :     /*
                                417                 :                :      * Initialize and WAL Log the first N buckets
                                418                 :                :      */
                                419         [ +  + ]:           5514 :     for (i = 0; i < num_buckets; i++)
                                420                 :                :     {
                                421                 :                :         BlockNumber blkno;
                                422                 :                : 
                                423                 :                :         /* Allow interrupts, in case N is huge */
                                424         [ -  + ]:           5298 :         CHECK_FOR_INTERRUPTS();
                                425                 :                : 
                                426         [ +  + ]:           5298 :         blkno = BUCKET_TO_BLKNO(metap, i);
                                427                 :           5298 :         buf = _hash_getnewbuf(rel, blkno, forkNum);
                                428                 :           5298 :         _hash_initbuf(buf, metap->hashm_maxbucket, i, LH_BUCKET_PAGE, false);
                                429                 :           5298 :         MarkBufferDirty(buf);
                                430                 :                : 
 3374                           431         [ +  + ]:           5298 :         if (use_wal)
 1559                           432                 :           5152 :             log_newpage(&rel->rd_locator,
                                433                 :                :                         forkNum,
                                434                 :                :                         blkno,
                                435                 :                :                         BufferGetPage(buf),
                                436                 :                :                         true);
 3506                           437                 :           5298 :         _hash_relbuf(rel, buf);
                                438                 :                :     }
                                439                 :                : 
                                440                 :                :     /* Now reacquire buffer lock on metapage */
                                441                 :            216 :     LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
                                442                 :                : 
                                443                 :                :     /*
                                444                 :                :      * Initialize bitmap page
                                445                 :                :      */
                                446                 :            216 :     bitmapbuf = _hash_getnewbuf(rel, num_buckets + 1, forkNum);
                                447                 :            216 :     _hash_initbitmapbuffer(bitmapbuf, metap->hashm_bmsize, false);
                                448                 :            216 :     MarkBufferDirty(bitmapbuf);
                                449                 :                : 
                                450                 :                :     /* add the new bitmap page to the metapage's list of bitmaps */
                                451                 :                :     /* metapage already has a write lock */
                                452         [ -  + ]:            216 :     if (metap->hashm_nmaps >= HASH_MAX_BITMAPS)
 3506 rhaas@postgresql.org      453         [ #  # ]:UBC           0 :         ereport(ERROR,
                                454                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                455                 :                :                  errmsg("out of overflow pages in hash index \"%s\"",
                                456                 :                :                         RelationGetRelationName(rel))));
                                457                 :                : 
 3506 rhaas@postgresql.org      458                 :CBC         216 :     metap->hashm_mapp[metap->hashm_nmaps] = num_buckets + 1;
                                459                 :                : 
                                460                 :            216 :     metap->hashm_nmaps++;
                                461                 :            216 :     MarkBufferDirty(metabuf);
                                462                 :                : 
                                463                 :                :     /* XLOG stuff */
 3374                           464         [ +  + ]:            216 :     if (use_wal)
                                465                 :                :     {
                                466                 :                :         xl_hash_init_bitmap_page xlrec;
                                467                 :                :         XLogRecPtr  recptr;
                                468                 :                : 
 3499                           469                 :            170 :         xlrec.bmsize = metap->hashm_bmsize;
                                470                 :                : 
                                471                 :            170 :         XLogBeginInsert();
  608 peter@eisentraut.org      472                 :            170 :         XLogRegisterData(&xlrec, SizeOfHashInitBitmapPage);
 3499 rhaas@postgresql.org      473                 :            170 :         XLogRegisterBuffer(0, bitmapbuf, REGBUF_WILL_INIT);
                                474                 :                : 
                                475                 :                :         /*
                                476                 :                :          * This is safe only because nobody else can be modifying the index at
                                477                 :                :          * this stage; it's only visible to the transaction that is creating
                                478                 :                :          * it.
                                479                 :                :          */
                                480                 :            170 :         XLogRegisterBuffer(1, metabuf, REGBUF_STANDARD);
                                481                 :                : 
                                482                 :            170 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_INIT_BITMAP_PAGE);
                                483                 :                : 
                                484                 :            170 :         PageSetLSN(BufferGetPage(bitmapbuf), recptr);
                                485                 :            170 :         PageSetLSN(BufferGetPage(metabuf), recptr);
                                486                 :                :     }
                                487                 :                : 
                                488                 :                :     /* all done */
 3506                           489                 :            216 :     _hash_relbuf(rel, bitmapbuf);
                                490                 :            216 :     _hash_relbuf(rel, metabuf);
                                491                 :                : 
                                492                 :            216 :     return num_buckets;
                                493                 :                : }
                                494                 :                : 
                                495                 :                : /*
                                496                 :                :  *  _hash_init_metabuffer() -- Initialize the metadata page of a hash index.
                                497                 :                :  */
                                498                 :                : void
                                499                 :            246 : _hash_init_metabuffer(Buffer buf, double num_tuples, RegProcedure procid,
                                500                 :                :                       uint16 ffactor, bool initpage)
                                501                 :                : {
                                502                 :                :     HashMetaPage metap;
                                503                 :                :     HashPageOpaque pageopaque;
                                504                 :                :     Page        page;
                                505                 :                :     double      dnumbuckets;
                                506                 :                :     uint32      num_buckets;
                                507                 :                :     uint32      spare_index;
                                508                 :                :     uint32      lshift;
                                509                 :                : 
                                510                 :                :     /*
                                511                 :                :      * Choose the number of initial bucket pages to match the fill factor
                                512                 :                :      * given the estimated number of tuples.  We round up the result to the
                                513                 :                :      * total number of buckets which has to be allocated before using its
                                514                 :                :      * hashm_spares element. However always force at least 2 bucket pages. The
                                515                 :                :      * upper limit is determined by considerations explained in
                                516                 :                :      * _hash_expandtable().
                                517                 :                :      */
 6785 tgl@sss.pgh.pa.us         518                 :            246 :     dnumbuckets = num_tuples / ffactor;
                                519         [ +  + ]:            246 :     if (dnumbuckets <= 2.0)
                                520                 :             72 :         num_buckets = 2;
                                521         [ -  + ]:            174 :     else if (dnumbuckets >= (double) 0x40000000)
 6785 tgl@sss.pgh.pa.us         522                 :UBC           0 :         num_buckets = 0x40000000;
                                523                 :                :     else
 3479 rhaas@postgresql.org      524                 :CBC         174 :         num_buckets = _hash_get_totalbuckets(_hash_spareindex(dnumbuckets));
                                525                 :                : 
                                526                 :            246 :     spare_index = _hash_spareindex(num_buckets);
                                527         [ -  + ]:            246 :     Assert(spare_index < HASH_MAX_SPLITPOINTS);
                                528                 :                : 
 3506                           529                 :            246 :     page = BufferGetPage(buf);
                                530         [ +  + ]:            246 :     if (initpage)
                                531                 :             30 :         _hash_pageinit(page, BufferGetPageSize(buf));
                                532                 :                : 
 1655 michael@paquier.xyz       533                 :            246 :     pageopaque = HashPageGetOpaque(page);
 8442 tgl@sss.pgh.pa.us         534                 :            246 :     pageopaque->hasho_prevblkno = InvalidBlockNumber;
                                535                 :            246 :     pageopaque->hasho_nextblkno = InvalidBlockNumber;
 1928 peter@eisentraut.org      536                 :            246 :     pageopaque->hasho_bucket = InvalidBucket;
 8441 tgl@sss.pgh.pa.us         537                 :            246 :     pageopaque->hasho_flag = LH_META_PAGE;
 7126                           538                 :            246 :     pageopaque->hasho_page_id = HASHO_PAGE_ID;
                                539                 :                : 
 3506 rhaas@postgresql.org      540                 :            246 :     metap = HashPageGetMeta(page);
                                541                 :                : 
10627 bruce@momjian.us          542                 :            246 :     metap->hashm_magic = HASH_MAGIC;
                                543                 :            246 :     metap->hashm_version = HASH_VERSION;
 8442 tgl@sss.pgh.pa.us         544                 :            246 :     metap->hashm_ntuples = 0;
10627 bruce@momjian.us          545                 :            246 :     metap->hashm_nmaps = 0;
 8439 tgl@sss.pgh.pa.us         546                 :            246 :     metap->hashm_ffactor = ffactor;
 3506 rhaas@postgresql.org      547                 :            246 :     metap->hashm_bsize = HashGetMaxBitmapSize(page);
                                548                 :                : 
                                549                 :                :     /* find largest bitmap array size that will fit in page size */
 2378 drowley@postgresql.o      550                 :            246 :     lshift = pg_leftmost_one_pos32(metap->hashm_bsize);
                                551         [ -  + ]:            246 :     Assert(lshift > 0);
                                552                 :            246 :     metap->hashm_bmsize = 1 << lshift;
                                553                 :            246 :     metap->hashm_bmshift = lshift + BYTE_TO_BIT;
 8442 tgl@sss.pgh.pa.us         554         [ -  + ]:            246 :     Assert((1 << BMPG_SHIFT(metap)) == (BMPG_MASK(metap) + 1));
                                555                 :                : 
                                556                 :                :     /*
                                557                 :                :      * Label the index with its primary hash support function's OID.  This is
                                558                 :                :      * pretty useless for normal operation (in fact, hashm_procid is not used
                                559                 :                :      * anywhere), but it might be handy for forensic purposes so we keep it.
                                560                 :                :      */
 3506 rhaas@postgresql.org      561                 :            246 :     metap->hashm_procid = procid;
                                562                 :                : 
                                563                 :                :     /*
                                564                 :                :      * We initialize the index with N buckets, 0 .. N-1, occupying physical
                                565                 :                :      * blocks 1 to N.  The first freespace bitmap page is in block N+1.
                                566                 :                :      */
 3479                           567                 :            246 :     metap->hashm_maxbucket = num_buckets - 1;
                                568                 :                : 
                                569                 :                :     /*
                                570                 :                :      * Set highmask as next immediate ((2 ^ x) - 1), which should be
                                571                 :                :      * sufficient to cover num_buckets.
                                572                 :                :      */
 2378 drowley@postgresql.o      573                 :            246 :     metap->hashm_highmask = pg_nextpower2_32(num_buckets + 1) - 1;
 3479 rhaas@postgresql.org      574                 :            246 :     metap->hashm_lowmask = (metap->hashm_highmask >> 1);
                                575                 :                : 
 7824 neilc@samurai.com         576   [ -  +  -  -  :            246 :     MemSet(metap->hashm_spares, 0, sizeof(metap->hashm_spares));
                                     -  -  -  -  -  
                                                 - ]
                                577   [ -  +  -  -  :            246 :     MemSet(metap->hashm_mapp, 0, sizeof(metap->hashm_mapp));
                                     -  -  -  -  -  
                                                 - ]
                                578                 :                : 
                                579                 :                :     /* Set up mapping for one spare page after the initial splitpoints */
 3479 rhaas@postgresql.org      580                 :            246 :     metap->hashm_spares[spare_index] = 1;
                                581                 :            246 :     metap->hashm_ovflpoint = spare_index;
 8442 tgl@sss.pgh.pa.us         582                 :            246 :     metap->hashm_firstfree = 0;
                                583                 :                : 
                                584                 :                :     /*
                                585                 :                :      * Set pd_lower just past the end of the metadata.  This is essential,
                                586                 :                :      * because without doing so, metadata will be lost if xlog.c compresses
                                587                 :                :      * the page.
                                588                 :                :      */
 3506 rhaas@postgresql.org      589                 :            246 :     ((PageHeader) page)->pd_lower =
                                590                 :            246 :         ((char *) metap + sizeof(HashMetaPageData)) - (char *) page;
11052 scrappy@hub.org           591                 :            246 : }
                                592                 :                : 
                                593                 :                : /*
                                594                 :                :  *  _hash_pageinit() -- Initialize a new hash index page.
                                595                 :                :  */
                                596                 :                : void
                                597                 :           7418 : _hash_pageinit(Page page, Size size)
                                598                 :                : {
10627 bruce@momjian.us          599                 :           7418 :     PageInit(page, size, sizeof(HashPageOpaqueData));
11052 scrappy@hub.org           600                 :           7418 : }
                                601                 :                : 
                                602                 :                : /*
                                603                 :                :  * Attempt to expand the hash table by creating one new bucket.
                                604                 :                :  *
                                605                 :                :  * This will silently do nothing if we don't get cleanup lock on old or
                                606                 :                :  * new bucket.
                                607                 :                :  *
                                608                 :                :  * Complete the pending splits and remove the tuples from old bucket,
                                609                 :                :  * if there are any left over from the previous split.
                                610                 :                :  *
                                611                 :                :  * The caller must hold a pin, but no lock, on the metapage buffer.
                                612                 :                :  * The buffer is returned in the same state.
                                613                 :                :  */
                                614                 :                : void
                                615                 :            892 : _hash_expandtable(Relation rel, Buffer metabuf)
                                616                 :                : {
                                617                 :                :     HashMetaPage metap;
                                618                 :                :     Bucket      old_bucket;
                                619                 :                :     Bucket      new_bucket;
                                620                 :                :     uint32      spare_ndx;
                                621                 :                :     BlockNumber start_oblkno;
                                622                 :                :     BlockNumber start_nblkno;
                                623                 :                :     Buffer      buf_nblkno;
                                624                 :                :     Buffer      buf_oblkno;
                                625                 :                :     Page        opage;
                                626                 :                :     Page        npage;
                                627                 :                :     HashPageOpaque oopaque;
                                628                 :                :     HashPageOpaque nopaque;
                                629                 :                :     uint32      maxbucket;
                                630                 :                :     uint32      highmask;
                                631                 :                :     uint32      lowmask;
 3499 rhaas@postgresql.org      632                 :            892 :     bool        metap_update_masks = false;
                                633                 :            892 :     bool        metap_update_splitpoint = false;
                                634                 :                :     XLogRecPtr  recptr;
                                635                 :                : 
 3603 rhaas@postgresql.org      636                 :UBC           0 : restart_expand:
                                637                 :                : 
                                638                 :                :     /*
                                639                 :                :      * Write-lock the meta page.  It used to be necessary to acquire a
                                640                 :                :      * heavyweight lock to begin a split, but that is no longer required.
                                641                 :                :      */
 3580 rhaas@postgresql.org      642                 :CBC         892 :     LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
                                643                 :                : 
 7645 tgl@sss.pgh.pa.us         644                 :            892 :     _hash_checkpage(rel, metabuf, LH_META_PAGE);
 3827 kgrittn@postgresql.o      645                 :            892 :     metap = HashPageGetMeta(BufferGetPage(metabuf));
                                646                 :                : 
                                647                 :                :     /*
                                648                 :                :      * Check to see if split is still needed; someone else might have already
                                649                 :                :      * done one while we waited for the lock.
                                650                 :                :      *
                                651                 :                :      * Make sure this stays in sync with _hash_doinsert()
                                652                 :                :      */
 8439 tgl@sss.pgh.pa.us         653                 :            892 :     if (metap->hashm_ntuples <=
                                654         [ -  + ]:            892 :         (double) metap->hashm_ffactor * (metap->hashm_maxbucket + 1))
 8439 tgl@sss.pgh.pa.us         655                 :UBC           0 :         goto fail;
                                656                 :                : 
                                657                 :                :     /*
                                658                 :                :      * Can't split anymore if maxbucket has reached its maximum possible
                                659                 :                :      * value.
                                660                 :                :      *
                                661                 :                :      * Ideally we'd allow bucket numbers up to UINT_MAX-1 (no higher because
                                662                 :                :      * the calculation maxbucket+1 mustn't overflow).  Currently we restrict
                                663                 :                :      * to half that to prevent failure of pg_ceil_log2_32() and insufficient
                                664                 :                :      * space in hashm_spares[].  It's moot anyway because an index with 2^32
                                665                 :                :      * buckets would certainly overflow BlockNumber and hence
                                666                 :                :      * _hash_alloc_buckets() would fail, but if we supported buckets smaller
                                667                 :                :      * than a disk block then this would be an independent constraint.
                                668                 :                :      *
                                669                 :                :      * If you change this, see also the maximum initial number of buckets in
                                670                 :                :      * _hash_init().
                                671                 :                :      */
 7267 tgl@sss.pgh.pa.us         672         [ -  + ]:CBC         892 :     if (metap->hashm_maxbucket >= (uint32) 0x7FFFFFFE)
 7267 tgl@sss.pgh.pa.us         673                 :UBC           0 :         goto fail;
                                674                 :                : 
                                675                 :                :     /*
                                676                 :                :      * Determine which bucket is to be split, and attempt to take cleanup lock
                                677                 :                :      * on the old bucket.  If we can't get the lock, give up.
                                678                 :                :      *
                                679                 :                :      * The cleanup lock protects us not only against other backends, but
                                680                 :                :      * against our own backend as well.
                                681                 :                :      *
                                682                 :                :      * The cleanup lock is mainly to protect the split from concurrent
                                683                 :                :      * inserts. See src/backend/access/hash/README, Lock Definitions for
                                684                 :                :      * further details.  Due to this locking restriction, if there is any
                                685                 :                :      * pending scan, the split will give up which is not good, but harmless.
                                686                 :                :      */
 7116 tgl@sss.pgh.pa.us         687                 :CBC         892 :     new_bucket = metap->hashm_maxbucket + 1;
                                688                 :                : 
 8442                           689                 :            892 :     old_bucket = (new_bucket & metap->hashm_lowmask);
                                690                 :                : 
 8439                           691         [ +  + ]:            892 :     start_oblkno = BUCKET_TO_BLKNO(metap, old_bucket);
                                692                 :                : 
 3603 rhaas@postgresql.org      693                 :            892 :     buf_oblkno = _hash_getbuf_with_condlock_cleanup(rel, start_oblkno, LH_BUCKET_PAGE);
                                694         [ -  + ]:            892 :     if (!buf_oblkno)
 8439 tgl@sss.pgh.pa.us         695                 :UBC           0 :         goto fail;
                                696                 :                : 
 3603 rhaas@postgresql.org      697                 :CBC         892 :     opage = BufferGetPage(buf_oblkno);
 1655 michael@paquier.xyz       698                 :            892 :     oopaque = HashPageGetOpaque(opage);
                                699                 :                : 
                                700                 :                :     /*
                                701                 :                :      * We want to finish the split from a bucket as there is no apparent
                                702                 :                :      * benefit by not doing so and it will make the code complicated to finish
                                703                 :                :      * the split that involves multiple buckets considering the case where new
                                704                 :                :      * split also fails.  We don't need to consider the new bucket for
                                705                 :                :      * completing the split here as it is not possible that a re-split of new
                                706                 :                :      * bucket starts when there is still a pending split from old bucket.
                                707                 :                :      */
 3603 rhaas@postgresql.org      708         [ -  + ]:            892 :     if (H_BUCKET_BEING_SPLIT(oopaque))
                                709                 :                :     {
                                710                 :                :         /*
                                711                 :                :          * Copy bucket mapping info now; refer the comment in code below where
                                712                 :                :          * we copy this information before calling _hash_splitbucket to see
                                713                 :                :          * why this is okay.
                                714                 :                :          */
 3603 rhaas@postgresql.org      715                 :UBC           0 :         maxbucket = metap->hashm_maxbucket;
                                716                 :              0 :         highmask = metap->hashm_highmask;
                                717                 :              0 :         lowmask = metap->hashm_lowmask;
                                718                 :                : 
                                719                 :                :         /*
                                720                 :                :          * Release the lock on metapage and old_bucket, before completing the
                                721                 :                :          * split.
                                722                 :                :          */
 3580                           723                 :              0 :         LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
                                724                 :              0 :         LockBuffer(buf_oblkno, BUFFER_LOCK_UNLOCK);
                                725                 :                : 
 3603                           726                 :              0 :         _hash_finish_split(rel, metabuf, buf_oblkno, old_bucket, maxbucket,
                                727                 :                :                            highmask, lowmask);
                                728                 :                : 
                                729                 :                :         /* release the pin on old buffer and retry for expand. */
                                730                 :              0 :         _hash_dropbuf(rel, buf_oblkno);
                                731                 :                : 
                                732                 :              0 :         goto restart_expand;
                                733                 :                :     }
                                734                 :                : 
                                735                 :                :     /*
                                736                 :                :      * Clean the tuples remained from the previous split.  This operation
                                737                 :                :      * requires cleanup lock and we already have one on the old bucket, so
                                738                 :                :      * let's do it. We also don't want to allow further splits from the bucket
                                739                 :                :      * till the garbage of previous split is cleaned.  This has two
                                740                 :                :      * advantages; first, it helps in avoiding the bloat due to garbage and
                                741                 :                :      * second is, during cleanup of bucket, we are always sure that the
                                742                 :                :      * garbage tuples belong to most recently split bucket.  On the contrary,
                                743                 :                :      * if we allow cleanup of bucket after meta page is updated to indicate
                                744                 :                :      * the new split and before the actual split, the cleanup operation won't
                                745                 :                :      * be able to decide whether the tuple has been moved to the newly created
                                746                 :                :      * bucket and ended up deleting such tuples.
                                747                 :                :      */
 3603 rhaas@postgresql.org      748         [ -  + ]:CBC         892 :     if (H_NEEDS_SPLIT_CLEANUP(oopaque))
                                749                 :                :     {
                                750                 :                :         /*
                                751                 :                :          * Copy bucket mapping info now; refer to the comment in code below
                                752                 :                :          * where we copy this information before calling _hash_splitbucket to
                                753                 :                :          * see why this is okay.
                                754                 :                :          */
 3598 rhaas@postgresql.org      755                 :UBC           0 :         maxbucket = metap->hashm_maxbucket;
                                756                 :              0 :         highmask = metap->hashm_highmask;
                                757                 :              0 :         lowmask = metap->hashm_lowmask;
                                758                 :                : 
                                759                 :                :         /* Release the metapage lock. */
 3580                           760                 :              0 :         LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
                                761                 :                : 
 3603                           762                 :              0 :         hashbucketcleanup(rel, old_bucket, buf_oblkno, start_oblkno, NULL,
                                763                 :                :                           maxbucket, highmask, lowmask, NULL, NULL, true,
                                764                 :                :                           NULL, NULL);
                                765                 :                : 
                                766                 :              0 :         _hash_dropbuf(rel, buf_oblkno);
                                767                 :                : 
                                768                 :              0 :         goto restart_expand;
                                769                 :                :     }
                                770                 :                : 
                                771                 :                :     /*
                                772                 :                :      * There shouldn't be any active scan on new bucket.
                                773                 :                :      *
                                774                 :                :      * Note: it is safe to compute the new bucket's blkno here, even though we
                                775                 :                :      * may still need to update the BUCKET_TO_BLKNO mapping.  This is because
                                776                 :                :      * the current value of hashm_spares[hashm_ovflpoint] correctly shows
                                777                 :                :      * where we are going to put a new splitpoint's worth of buckets.
                                778                 :                :      */
 7116 tgl@sss.pgh.pa.us         779         [ +  - ]:CBC         892 :     start_nblkno = BUCKET_TO_BLKNO(metap, new_bucket);
                                780                 :                : 
                                781                 :                :     /*
                                782                 :                :      * If the split point is increasing we need to allocate a new batch of
                                783                 :                :      * bucket pages.
                                784                 :                :      */
 3479 rhaas@postgresql.org      785                 :            892 :     spare_ndx = _hash_spareindex(new_bucket + 1);
 7116 tgl@sss.pgh.pa.us         786         [ +  + ]:            892 :     if (spare_ndx > metap->hashm_ovflpoint)
                                787                 :                :     {
                                788                 :                :         uint32      buckets_to_add;
                                789                 :                : 
                                790         [ -  + ]:             40 :         Assert(spare_ndx == metap->hashm_ovflpoint + 1);
                                791                 :                : 
                                792                 :                :         /*
                                793                 :                :          * We treat allocation of buckets as a separate WAL-logged action.
                                794                 :                :          * Even if we fail after this operation, won't leak bucket pages;
                                795                 :                :          * rather, the next split will consume this space. In any case, even
                                796                 :                :          * without failure we don't use all the space in one split operation.
                                797                 :                :          */
 3479 rhaas@postgresql.org      798                 :             40 :         buckets_to_add = _hash_get_totalbuckets(spare_ndx) - new_bucket;
                                799         [ -  + ]:             40 :         if (!_hash_alloc_buckets(rel, start_nblkno, buckets_to_add))
                                800                 :                :         {
                                801                 :                :             /* can't split due to BlockNumber overflow */
 3603 rhaas@postgresql.org      802                 :UBC           0 :             _hash_relbuf(rel, buf_oblkno);
 7116 tgl@sss.pgh.pa.us         803                 :              0 :             goto fail;
                                804                 :                :         }
                                805                 :                :     }
                                806                 :                : 
                                807                 :                :     /*
                                808                 :                :      * Physically allocate the new bucket's primary page.  We want to do this
                                809                 :                :      * before changing the metapage's mapping info, in case we can't get the
                                810                 :                :      * disk space.
                                811                 :                :      *
                                812                 :                :      * XXX It doesn't make sense to call _hash_getnewbuf first, zeroing the
                                813                 :                :      * buffer, and then only afterwards check whether we have a cleanup lock.
                                814                 :                :      * However, since no scan can be accessing the buffer yet, any concurrent
                                815                 :                :      * accesses will just be from processes like the bgwriter or checkpointer
                                816                 :                :      * which don't care about its contents, so it doesn't really matter.
                                817                 :                :      */
 4214 tgl@sss.pgh.pa.us         818                 :CBC         892 :     buf_nblkno = _hash_getnewbuf(rel, start_nblkno, MAIN_FORKNUM);
 3603 rhaas@postgresql.org      819         [ -  + ]:            892 :     if (!IsBufferCleanupOK(buf_nblkno))
                                820                 :                :     {
 3603 rhaas@postgresql.org      821                 :UBC           0 :         _hash_relbuf(rel, buf_oblkno);
                                822                 :              0 :         _hash_relbuf(rel, buf_nblkno);
                                823                 :              0 :         goto fail;
                                824                 :                :     }
                                825                 :                : 
                                826                 :                :     /*
                                827                 :                :      * Since we are scribbling on the pages in the shared buffers, establish a
                                828                 :                :      * critical section.  Any failure in this next code leaves us with a big
                                829                 :                :      * problem: the metapage is effectively corrupt but could get written back
                                830                 :                :      * to disk.
                                831                 :                :      */
 7795 tgl@sss.pgh.pa.us         832                 :CBC         892 :     START_CRIT_SECTION();
                                833                 :                : 
                                834                 :                :     /*
                                835                 :                :      * Okay to proceed with split.  Update the metapage bucket mapping info.
                                836                 :                :      */
 8439                           837                 :            892 :     metap->hashm_maxbucket = new_bucket;
                                838                 :                : 
 8442                           839         [ +  + ]:            892 :     if (new_bucket > metap->hashm_highmask)
                                840                 :                :     {
                                841                 :                :         /* Starting a new doubling */
                                842                 :             14 :         metap->hashm_lowmask = metap->hashm_highmask;
                                843                 :             14 :         metap->hashm_highmask = new_bucket | metap->hashm_lowmask;
 3499 rhaas@postgresql.org      844                 :             14 :         metap_update_masks = true;
                                845                 :                :     }
                                846                 :                : 
                                847                 :                :     /*
                                848                 :                :      * If the split point is increasing we need to adjust the hashm_spares[]
                                849                 :                :      * array and hashm_ovflpoint so that future overflow pages will be created
                                850                 :                :      * beyond this new batch of bucket pages.
                                851                 :                :      */
 9220 tgl@sss.pgh.pa.us         852         [ +  + ]:            892 :     if (spare_ndx > metap->hashm_ovflpoint)
                                853                 :                :     {
                                854                 :             40 :         metap->hashm_spares[spare_ndx] = metap->hashm_spares[metap->hashm_ovflpoint];
                                855                 :             40 :         metap->hashm_ovflpoint = spare_ndx;
 3499 rhaas@postgresql.org      856                 :             40 :         metap_update_splitpoint = true;
                                857                 :                :     }
                                858                 :                : 
 3512                           859                 :            892 :     MarkBufferDirty(metabuf);
                                860                 :                : 
                                861                 :                :     /*
                                862                 :                :      * Copy bucket mapping info now; this saves re-accessing the meta page
                                863                 :                :      * inside _hash_splitbucket's inner loop.  Note that once we drop the
                                864                 :                :      * split lock, other splits could begin, so these values might be out of
                                865                 :                :      * date before _hash_splitbucket finishes.  That's okay, since all it
                                866                 :                :      * needs is to tell which of these two buckets to map hashkeys into.
                                867                 :                :      */
 8439 tgl@sss.pgh.pa.us         868                 :            892 :     maxbucket = metap->hashm_maxbucket;
                                869                 :            892 :     highmask = metap->hashm_highmask;
                                870                 :            892 :     lowmask = metap->hashm_lowmask;
                                871                 :                : 
 3512 rhaas@postgresql.org      872                 :            892 :     opage = BufferGetPage(buf_oblkno);
 1655 michael@paquier.xyz       873                 :            892 :     oopaque = HashPageGetOpaque(opage);
                                874                 :                : 
                                875                 :                :     /*
                                876                 :                :      * Mark the old bucket to indicate that split is in progress.  (At
                                877                 :                :      * operation end, we will clear the split-in-progress flag.)  Also, for a
                                878                 :                :      * primary bucket page, hasho_prevblkno stores the number of buckets that
                                879                 :                :      * existed as of the last split, so we must update that value here.
                                880                 :                :      */
 3512 rhaas@postgresql.org      881                 :            892 :     oopaque->hasho_flag |= LH_BUCKET_BEING_SPLIT;
                                882                 :            892 :     oopaque->hasho_prevblkno = maxbucket;
                                883                 :                : 
                                884                 :            892 :     MarkBufferDirty(buf_oblkno);
                                885                 :                : 
                                886                 :            892 :     npage = BufferGetPage(buf_nblkno);
                                887                 :                : 
                                888                 :                :     /*
                                889                 :                :      * initialize the new bucket's primary page and mark it to indicate that
                                890                 :                :      * split is in progress.
                                891                 :                :      */
 1655 michael@paquier.xyz       892                 :            892 :     nopaque = HashPageGetOpaque(npage);
 3512 rhaas@postgresql.org      893                 :            892 :     nopaque->hasho_prevblkno = maxbucket;
                                894                 :            892 :     nopaque->hasho_nextblkno = InvalidBlockNumber;
                                895                 :            892 :     nopaque->hasho_bucket = new_bucket;
                                896                 :            892 :     nopaque->hasho_flag = LH_BUCKET_PAGE | LH_BUCKET_BEING_POPULATED;
                                897                 :            892 :     nopaque->hasho_page_id = HASHO_PAGE_ID;
                                898                 :                : 
                                899                 :            892 :     MarkBufferDirty(buf_nblkno);
                                900                 :                : 
                                901                 :                :     /* XLOG stuff */
 3499                           902   [ +  -  -  +  :            892 :     if (RelationNeedsWAL(rel))
                                        -  -  -  - ]
                                903                 :            892 :     {
                                904                 :                :         xl_hash_split_allocate_page xlrec;
                                905                 :                : 
                                906                 :            892 :         xlrec.new_bucket = maxbucket;
                                907                 :            892 :         xlrec.old_bucket_flag = oopaque->hasho_flag;
                                908                 :            892 :         xlrec.new_bucket_flag = nopaque->hasho_flag;
                                909                 :            892 :         xlrec.flags = 0;
                                910                 :                : 
                                911                 :            892 :         XLogBeginInsert();
                                912                 :                : 
                                913                 :            892 :         XLogRegisterBuffer(0, buf_oblkno, REGBUF_STANDARD);
                                914                 :            892 :         XLogRegisterBuffer(1, buf_nblkno, REGBUF_WILL_INIT);
                                915                 :            892 :         XLogRegisterBuffer(2, metabuf, REGBUF_STANDARD);
                                916                 :                : 
                                917         [ +  + ]:            892 :         if (metap_update_masks)
                                918                 :                :         {
                                919                 :             14 :             xlrec.flags |= XLH_SPLIT_META_UPDATE_MASKS;
  608 peter@eisentraut.org      920                 :             14 :             XLogRegisterBufData(2, &metap->hashm_lowmask, sizeof(uint32));
                                921                 :             14 :             XLogRegisterBufData(2, &metap->hashm_highmask, sizeof(uint32));
                                922                 :                :         }
                                923                 :                : 
 3499 rhaas@postgresql.org      924         [ +  + ]:            892 :         if (metap_update_splitpoint)
                                925                 :                :         {
                                926                 :             40 :             xlrec.flags |= XLH_SPLIT_META_UPDATE_SPLITPOINT;
  608 peter@eisentraut.org      927                 :             40 :             XLogRegisterBufData(2, &metap->hashm_ovflpoint,
                                928                 :                :                                 sizeof(uint32));
 3499 rhaas@postgresql.org      929                 :             40 :             XLogRegisterBufData(2,
  608 peter@eisentraut.org      930                 :             40 :                                 &metap->hashm_spares[metap->hashm_ovflpoint],
                                931                 :                :                                 sizeof(uint32));
                                932                 :                :         }
                                933                 :                : 
                                934                 :            892 :         XLogRegisterData(&xlrec, SizeOfHashSplitAllocPage);
                                935                 :                : 
 3499 rhaas@postgresql.org      936                 :            892 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SPLIT_ALLOCATE_PAGE);
                                937                 :                :     }
                                938                 :                :     else
  204 pg@bowt.ie                939                 :UBC           0 :         recptr = XLogGetFakeLSN(rel);
                                940                 :                : 
  204 pg@bowt.ie                941                 :CBC         892 :     PageSetLSN(BufferGetPage(buf_oblkno), recptr);
                                942                 :            892 :     PageSetLSN(BufferGetPage(buf_nblkno), recptr);
                                943                 :            892 :     PageSetLSN(BufferGetPage(metabuf), recptr);
                                944                 :                : 
 3512 rhaas@postgresql.org      945         [ -  + ]:            892 :     END_CRIT_SECTION();
                                946                 :                : 
                                947                 :                :     /* drop lock, but keep pin */
 3580                           948                 :            892 :     LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
                                949                 :                : 
                                950                 :                :     /* Relocate records to the new bucket */
 4210 tgl@sss.pgh.pa.us         951                 :            892 :     _hash_splitbucket(rel, metabuf,
                                952                 :                :                       old_bucket, new_bucket,
                                953                 :                :                       buf_oblkno, buf_nblkno, NULL,
                                954                 :                :                       maxbucket, highmask, lowmask);
                                955                 :                : 
                                956                 :                :     /* all done, now release the pins on primary buckets. */
 3356 rhaas@postgresql.org      957                 :            891 :     _hash_dropbuf(rel, buf_oblkno);
                                958                 :            891 :     _hash_dropbuf(rel, buf_nblkno);
                                959                 :                : 
 8439 tgl@sss.pgh.pa.us         960                 :            891 :     return;
                                961                 :                : 
                                962                 :                :     /* Here if decide not to split or fail to acquire old bucket lock */
 8439 tgl@sss.pgh.pa.us         963                 :UBC           0 : fail:
                                964                 :                : 
                                965                 :                :     /* We didn't write the metapage, so just drop lock */
 3580 rhaas@postgresql.org      966                 :              0 :     LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
                                967                 :                : }
                                968                 :                : 
                                969                 :                : 
                                970                 :                : /*
                                971                 :                :  * _hash_alloc_buckets -- allocate a new splitpoint's worth of bucket pages
                                972                 :                :  *
                                973                 :                :  * This does not need to initialize the new bucket pages; we'll do that as
                                974                 :                :  * each one is used by _hash_expandtable().  But we have to extend the logical
                                975                 :                :  * EOF to the end of the splitpoint; this keeps smgr's idea of the EOF in
                                976                 :                :  * sync with ours, so that we don't get complaints from smgr.
                                977                 :                :  *
                                978                 :                :  * We do this by writing a page of zeroes at the end of the splitpoint range.
                                979                 :                :  * We expect that the filesystem will ensure that the intervening pages read
                                980                 :                :  * as zeroes too.  On many filesystems this "hole" will not be allocated
                                981                 :                :  * immediately, which means that the index file may end up more fragmented
                                982                 :                :  * than if we forced it all to be allocated now; but since we don't scan
                                983                 :                :  * hash indexes sequentially anyway, that probably doesn't matter.
                                984                 :                :  *
                                985                 :                :  * XXX It's annoying that this code is executed with the metapage lock held.
                                986                 :                :  * We need to interlock against _hash_addovflpage() adding a new overflow page
                                987                 :                :  * concurrently, but it'd likely be better to use LockRelationForExtension
                                988                 :                :  * for the purpose.  OTOH, adding a splitpoint is a very infrequent operation,
                                989                 :                :  * so it may not be worth worrying about.
                                990                 :                :  *
                                991                 :                :  * Returns true if successful, or false if allocation failed due to
                                992                 :                :  * BlockNumber overflow.
                                993                 :                :  */
                                994                 :                : static bool
 7116 tgl@sss.pgh.pa.us         995                 :CBC          40 : _hash_alloc_buckets(Relation rel, BlockNumber firstblock, uint32 nblocks)
                                996                 :                : {
                                997                 :                :     BlockNumber lastblock;
                                998                 :                :     PGIOAlignedBlock zerobuf;
                                999                 :                :     Page        page;
                               1000                 :                :     HashPageOpaque ovflopaque;
                               1001                 :                : 
 7267                          1002                 :             40 :     lastblock = firstblock + nblocks - 1;
                               1003                 :                : 
                               1004                 :                :     /*
                               1005                 :                :      * Check for overflow in block number calculation; if so, we cannot extend
                               1006                 :                :      * the index anymore.
                               1007                 :                :      */
                               1008   [ +  -  -  + ]:             40 :     if (lastblock < firstblock || lastblock == InvalidBlockNumber)
 7116 tgl@sss.pgh.pa.us        1009                 :UBC           0 :         return false;
                               1010                 :                : 
 2963 tgl@sss.pgh.pa.us        1011                 :CBC          40 :     page = (Page) zerobuf.data;
                               1012                 :                : 
                               1013                 :                :     /*
                               1014                 :                :      * Initialize the page.  Just zeroing the page won't work; see
                               1015                 :                :      * _hash_freeovflpage for similar usage.  We take care to make the special
                               1016                 :                :      * space valid for the benefit of tools such as pageinspect.
                               1017                 :                :      */
 3499 rhaas@postgresql.org     1018                 :             40 :     _hash_pageinit(page, BLCKSZ);
                               1019                 :                : 
 1655 michael@paquier.xyz      1020                 :             40 :     ovflopaque = HashPageGetOpaque(page);
                               1021                 :                : 
 3477 rhaas@postgresql.org     1022                 :             40 :     ovflopaque->hasho_prevblkno = InvalidBlockNumber;
                               1023                 :             40 :     ovflopaque->hasho_nextblkno = InvalidBlockNumber;
 1928 peter@eisentraut.org     1024                 :             40 :     ovflopaque->hasho_bucket = InvalidBucket;
 3477 rhaas@postgresql.org     1025                 :             40 :     ovflopaque->hasho_flag = LH_UNUSED_PAGE;
                               1026                 :             40 :     ovflopaque->hasho_page_id = HASHO_PAGE_ID;
                               1027                 :                : 
 3499                          1028   [ +  -  -  +  :             40 :     if (RelationNeedsWAL(rel))
                                        -  -  -  - ]
 1559                          1029                 :             40 :         log_newpage(&rel->rd_locator,
                               1030                 :                :                     MAIN_FORKNUM,
                               1031                 :                :                     lastblock,
                               1032                 :                :                     zerobuf.data,
                               1033                 :                :                     true);
                               1034                 :                : 
  199 andres@anarazel.de       1035                 :             40 :     PageSetChecksum(page, lastblock);
 1918 tgl@sss.pgh.pa.us        1036                 :             40 :     smgrextend(RelationGetSmgr(rel), MAIN_FORKNUM, lastblock, zerobuf.data,
                               1037                 :                :                false);
                               1038                 :                : 
 7116                          1039                 :             40 :     return true;
                               1040                 :                : }
                               1041                 :                : 
                               1042                 :                : 
                               1043                 :                : /*
                               1044                 :                :  * _hash_splitbucket -- split 'obucket' into 'obucket' and 'nbucket'
                               1045                 :                :  *
                               1046                 :                :  * This routine is used to partition the tuples between old and new bucket and
                               1047                 :                :  * is used to finish the incomplete split operations.  To finish the previously
                               1048                 :                :  * interrupted split operation, the caller needs to fill htab.  If htab is set,
                               1049                 :                :  * then we skip the movement of tuples that exists in htab, otherwise NULL
                               1050                 :                :  * value of htab indicates movement of all the tuples that belong to the new
                               1051                 :                :  * bucket.
                               1052                 :                :  *
                               1053                 :                :  * We are splitting a bucket that consists of a base bucket page and zero
                               1054                 :                :  * or more overflow (bucket chain) pages.  We must relocate tuples that
                               1055                 :                :  * belong in the new bucket.
                               1056                 :                :  *
                               1057                 :                :  * The caller must hold cleanup locks on both buckets to ensure that
                               1058                 :                :  * no one else is trying to access them (see README).
                               1059                 :                :  *
                               1060                 :                :  * The caller must hold a pin, but no lock, on the metapage buffer.
                               1061                 :                :  * The buffer is returned in the same state.  (The metapage is only
                               1062                 :                :  * touched if it becomes necessary to add or remove overflow pages.)
                               1063                 :                :  *
                               1064                 :                :  * Split needs to retain pin on primary bucket pages of both old and new
                               1065                 :                :  * buckets till end of operation.  This is to prevent vacuum from starting
                               1066                 :                :  * while a split is in progress.
                               1067                 :                :  *
                               1068                 :                :  * In addition, the caller must have created the new bucket's base page,
                               1069                 :                :  * which is passed in buffer nbuf, pinned and write-locked.  The lock will be
                               1070                 :                :  * released here and pin must be released by the caller.  (The API is set up
                               1071                 :                :  * this way because we must do _hash_getnewbuf() before releasing the metapage
                               1072                 :                :  * write lock.  So instead of passing the new bucket's start block number, we
                               1073                 :                :  * pass an actual buffer.)
                               1074                 :                :  */
                               1075                 :                : static void
 8442                          1076                 :            893 : _hash_splitbucket(Relation rel,
                               1077                 :                :                   Buffer metabuf,
                               1078                 :                :                   Bucket obucket,
                               1079                 :                :                   Bucket nbucket,
                               1080                 :                :                   Buffer obuf,
                               1081                 :                :                   Buffer nbuf,
                               1082                 :                :                   HTAB *htab,
                               1083                 :                :                   uint32 maxbucket,
                               1084                 :                :                   uint32 highmask,
                               1085                 :                :                   uint32 lowmask)
                               1086                 :                : {
                               1087                 :                :     Buffer      bucket_obuf;
                               1088                 :                :     Buffer      bucket_nbuf;
                               1089                 :                :     Page        opage;
                               1090                 :                :     Page        npage;
                               1091                 :                :     HashPageOpaque oopaque;
                               1092                 :                :     HashPageOpaque nopaque;
                               1093                 :                :     OffsetNumber itup_offsets[MaxIndexTuplesPerPage];
                               1094                 :                :     IndexTuple  itups[MaxIndexTuplesPerPage];
 3499 rhaas@postgresql.org     1095                 :            893 :     Size        all_tups_size = 0;
                               1096                 :                :     int         i;
                               1097                 :            893 :     uint16      nitups = 0;
                               1098                 :                :     XLogRecPtr  recptr;
                               1099                 :                : 
 3603                          1100                 :            893 :     bucket_obuf = obuf;
                               1101                 :            893 :     opage = BufferGetPage(obuf);
 1655 michael@paquier.xyz      1102                 :            893 :     oopaque = HashPageGetOpaque(opage);
                               1103                 :                : 
 3603 rhaas@postgresql.org     1104                 :            893 :     bucket_nbuf = nbuf;
                               1105                 :            893 :     npage = BufferGetPage(nbuf);
 1655 michael@paquier.xyz      1106                 :            893 :     nopaque = HashPageGetOpaque(npage);
                               1107                 :                : 
                               1108                 :                :     /* Copy the predicate locks from old bucket to new bucket. */
 3110 teodor@sigaev.ru         1109                 :            893 :     PredicateLockPageSplit(rel,
                               1110                 :                :                            BufferGetBlockNumber(bucket_obuf),
                               1111                 :                :                            BufferGetBlockNumber(bucket_nbuf));
                               1112                 :                : 
    2 pg@bowt.ie               1113                 :            893 :     INJECTION_POINT("hash-split-before-relocation", NULL);
                               1114                 :                : 
                               1115                 :                :     /*
                               1116                 :                :      * Partition the tuples in the old bucket between the old bucket and the
                               1117                 :                :      * new bucket, advancing along the old bucket's overflow bucket chain and
                               1118                 :                :      * adding overflow pages to the new bucket as needed.  Outer loop iterates
                               1119                 :                :      * once per page in old bucket.
                               1120                 :                :      */
                               1121                 :                :     for (;;)
10627 bruce@momjian.us         1122                 :            226 :     {
                               1123                 :                :         BlockNumber oblkno;
                               1124                 :                :         OffsetNumber ooffnum;
                               1125                 :                :         OffsetNumber omaxoffnum;
                               1126                 :                : 
                               1127                 :                :         /* Scan each tuple in old page */
 6189 tgl@sss.pgh.pa.us        1128                 :           1118 :         omaxoffnum = PageGetMaxOffsetNumber(opage);
                               1129                 :           1118 :         for (ooffnum = FirstOffsetNumber;
                               1130         [ +  + ]:         205786 :              ooffnum <= omaxoffnum;
                               1131                 :         204668 :              ooffnum = OffsetNumberNext(ooffnum))
                               1132                 :                :         {
                               1133                 :                :             IndexTuple  itup;
                               1134                 :                :             Size        itemsz;
                               1135                 :                :             Bucket      bucket;
 3603 rhaas@postgresql.org     1136                 :         204668 :             bool        found = false;
                               1137                 :                : 
                               1138                 :                :             /* skip dead tuples */
 3625                          1139         [ -  + ]:         204668 :             if (ItemIdIsDead(PageGetItemId(opage, ooffnum)))
 3625 rhaas@postgresql.org     1140                 :UBC           0 :                 continue;
                               1141                 :                : 
                               1142                 :                :             /*
                               1143                 :                :              * Before inserting a tuple, probe the hash table containing TIDs
                               1144                 :                :              * of tuples belonging to new bucket, if we find a match, then
                               1145                 :                :              * skip that tuple, else fetch the item's hash key (conveniently
                               1146                 :                :              * stored in the item) and determine which bucket it now belongs
                               1147                 :                :              * in.
                               1148                 :                :              */
 6189 tgl@sss.pgh.pa.us        1149                 :CBC      204668 :             itup = (IndexTuple) PageGetItem(opage,
                               1150                 :         204668 :                                             PageGetItemId(opage, ooffnum));
                               1151                 :                : 
 3603 rhaas@postgresql.org     1152         [ +  + ]:         204668 :             if (htab)
                               1153                 :            318 :                 (void) hash_search(htab, &itup->t_tid, HASH_FIND, &found);
                               1154                 :                : 
                               1155         [ -  + ]:         204668 :             if (found)
 3603 rhaas@postgresql.org     1156                 :UBC           0 :                 continue;
                               1157                 :                : 
 6189 tgl@sss.pgh.pa.us        1158                 :CBC      204668 :             bucket = _hash_hashkey2bucket(_hash_get_indextuple_hashkey(itup),
                               1159                 :                :                                           maxbucket, highmask, lowmask);
                               1160                 :                : 
                               1161         [ +  + ]:         204668 :             if (bucket == nbucket)
                               1162                 :                :             {
                               1163                 :                :                 IndexTuple  new_itup;
                               1164                 :                : 
                               1165                 :                :                 /*
                               1166                 :                :                  * make a copy of index tuple as we have to scribble on it.
                               1167                 :                :                  */
 3603 rhaas@postgresql.org     1168                 :          83862 :                 new_itup = CopyIndexTuple(itup);
                               1169                 :                : 
                               1170                 :                :                 /*
                               1171                 :                :                  * mark the index tuple as moved by split, such tuples are
                               1172                 :                :                  * skipped by scan if there is split in progress for a bucket.
                               1173                 :                :                  */
                               1174                 :          83862 :                 new_itup->t_info |= INDEX_MOVED_BY_SPLIT_MASK;
                               1175                 :                : 
                               1176                 :                :                 /*
                               1177                 :                :                  * insert the tuple into the new bucket.  if it doesn't fit on
                               1178                 :                :                  * the current page in the new bucket, we must allocate a new
                               1179                 :                :                  * overflow page and place the tuple on that page instead.
                               1180                 :                :                  */
 3148 tgl@sss.pgh.pa.us        1181                 :          83862 :                 itemsz = IndexTupleSize(new_itup);
 6189                          1182                 :          83862 :                 itemsz = MAXALIGN(itemsz);
                               1183                 :                : 
 3499 rhaas@postgresql.org     1184         [ +  + ]:          83862 :                 if (PageGetFreeSpaceForMultipleTuples(npage, nitups + 1) < (all_tups_size + itemsz))
                               1185                 :                :                 {
                               1186                 :                :                     /*
                               1187                 :                :                      * Change the shared buffer state in critical section,
                               1188                 :                :                      * otherwise any error could make it unrecoverable.
                               1189                 :                :                      */
                               1190                 :             52 :                     START_CRIT_SECTION();
                               1191                 :                : 
                               1192                 :             52 :                     _hash_pgaddmultitup(rel, nbuf, itups, itup_offsets, nitups);
 3580                          1193                 :             52 :                     MarkBufferDirty(nbuf);
                               1194                 :                :                     /* log the split operation before releasing the lock */
 3499                          1195                 :             52 :                     log_split_page(rel, nbuf);
                               1196                 :                : 
                               1197         [ -  + ]:             52 :                     END_CRIT_SECTION();
                               1198                 :                : 
                               1199                 :                :                     /* drop lock, but keep pin */
 3580                          1200                 :             52 :                     LockBuffer(nbuf, BUFFER_LOCK_UNLOCK);
                               1201                 :                : 
                               1202                 :                :                     /* be tidy */
 3499                          1203         [ +  + ]:          21216 :                     for (i = 0; i < nitups; i++)
                               1204                 :          21164 :                         pfree(itups[i]);
                               1205                 :             52 :                     nitups = 0;
                               1206                 :             52 :                     all_tups_size = 0;
                               1207                 :                : 
                               1208                 :                :                     /* chain to a new overflow page */
 1860 michael@paquier.xyz      1209                 :             52 :                     nbuf = _hash_addovflpage(rel, metabuf, nbuf, (nbuf == bucket_nbuf));
 3827 kgrittn@postgresql.o     1210                 :             52 :                     npage = BufferGetPage(nbuf);
 1655 michael@paquier.xyz      1211                 :             52 :                     nopaque = HashPageGetOpaque(npage);
                               1212                 :                :                 }
                               1213                 :                : 
 3499 rhaas@postgresql.org     1214                 :          83862 :                 itups[nitups++] = new_itup;
                               1215                 :          83862 :                 all_tups_size += itemsz;
                               1216                 :                :             }
                               1217                 :                :             else
                               1218                 :                :             {
                               1219                 :                :                 /*
                               1220                 :                :                  * the tuple stays on this page, so nothing to do.
                               1221                 :                :                  */
 6189 tgl@sss.pgh.pa.us        1222         [ -  + ]:         120806 :                 Assert(bucket == obucket);
                               1223                 :                :             }
                               1224                 :                :         }
                               1225                 :                : 
                               1226                 :           1118 :         oblkno = oopaque->hasho_nextblkno;
                               1227                 :                : 
                               1228                 :                :         /* retain the pin on the old primary bucket */
 3603 rhaas@postgresql.org     1229         [ +  + ]:           1118 :         if (obuf == bucket_obuf)
 3580                          1230                 :            892 :             LockBuffer(obuf, BUFFER_LOCK_UNLOCK);
                               1231                 :                :         else
 6189 tgl@sss.pgh.pa.us        1232                 :            226 :             _hash_relbuf(rel, obuf);
                               1233                 :                : 
                               1234                 :                :         /* Exit loop if no more overflow pages in old bucket */
                               1235         [ +  + ]:           1118 :         if (!BlockNumberIsValid(oblkno))
                               1236                 :                :         {
                               1237                 :                :             /*
                               1238                 :                :              * Change the shared buffer state in critical section, otherwise
                               1239                 :                :              * any error could make it unrecoverable.
                               1240                 :                :              */
 3499 rhaas@postgresql.org     1241                 :            892 :             START_CRIT_SECTION();
                               1242                 :                : 
                               1243                 :            892 :             _hash_pgaddmultitup(rel, nbuf, itups, itup_offsets, nitups);
 3512                          1244                 :            892 :             MarkBufferDirty(nbuf);
                               1245                 :                :             /* log the split operation before releasing the lock */
 3499                          1246                 :            892 :             log_split_page(rel, nbuf);
                               1247                 :                : 
                               1248         [ -  + ]:            892 :             END_CRIT_SECTION();
                               1249                 :                : 
 3512                          1250         [ +  + ]:            892 :             if (nbuf == bucket_nbuf)
                               1251                 :            888 :                 LockBuffer(nbuf, BUFFER_LOCK_UNLOCK);
                               1252                 :                :             else
                               1253                 :              4 :                 _hash_relbuf(rel, nbuf);
                               1254                 :                : 
                               1255                 :                :             /* be tidy */
 3499                          1256         [ +  + ]:          63590 :             for (i = 0; i < nitups; i++)
                               1257                 :          62698 :                 pfree(itups[i]);
 6189 tgl@sss.pgh.pa.us        1258                 :            892 :             break;
                               1259                 :                :         }
                               1260                 :                : 
                               1261                 :                :         /* Else, advance to next old page */
 3603 rhaas@postgresql.org     1262                 :            226 :         obuf = _hash_getbuf(rel, oblkno, HASH_READ, LH_OVERFLOW_PAGE);
 3827 kgrittn@postgresql.o     1263                 :            226 :         opage = BufferGetPage(obuf);
 1655 michael@paquier.xyz      1264                 :            226 :         oopaque = HashPageGetOpaque(opage);
                               1265                 :                :     }
                               1266                 :                : 
                               1267                 :                :     /*
                               1268                 :                :      * We're at the end of the old bucket chain, so we're done partitioning
                               1269                 :                :      * the tuples.  Mark the old and new buckets to indicate split is
                               1270                 :                :      * finished.
                               1271                 :                :      *
                               1272                 :                :      * To avoid deadlocks due to locking order of buckets, first lock the old
                               1273                 :                :      * bucket and then the new bucket.
                               1274                 :                :      */
 3580 rhaas@postgresql.org     1275                 :            892 :     LockBuffer(bucket_obuf, BUFFER_LOCK_EXCLUSIVE);
 3603                          1276                 :            892 :     opage = BufferGetPage(bucket_obuf);
 1655 michael@paquier.xyz      1277                 :            892 :     oopaque = HashPageGetOpaque(opage);
                               1278                 :                : 
 3580 rhaas@postgresql.org     1279                 :            892 :     LockBuffer(bucket_nbuf, BUFFER_LOCK_EXCLUSIVE);
 3603                          1280                 :            892 :     npage = BufferGetPage(bucket_nbuf);
 1655 michael@paquier.xyz      1281                 :            892 :     nopaque = HashPageGetOpaque(npage);
                               1282                 :                : 
 3499 rhaas@postgresql.org     1283                 :            892 :     START_CRIT_SECTION();
                               1284                 :                : 
 3603                          1285                 :            892 :     oopaque->hasho_flag &= ~LH_BUCKET_BEING_SPLIT;
                               1286                 :            892 :     nopaque->hasho_flag &= ~LH_BUCKET_BEING_POPULATED;
                               1287                 :                : 
                               1288                 :                :     /*
                               1289                 :                :      * After the split is finished, mark the old bucket to indicate that it
                               1290                 :                :      * contains deletable tuples.  We will clear split-cleanup flag after
                               1291                 :                :      * deleting such tuples either at the end of split or at the next split
                               1292                 :                :      * from old bucket or at the time of vacuum.
                               1293                 :                :      */
                               1294                 :            892 :     oopaque->hasho_flag |= LH_BUCKET_NEEDS_SPLIT_CLEANUP;
                               1295                 :                : 
                               1296                 :                :     /*
                               1297                 :                :      * now write the buffers, here we don't release the locks as caller is
                               1298                 :                :      * responsible to release locks.
                               1299                 :                :      */
                               1300                 :            892 :     MarkBufferDirty(bucket_obuf);
                               1301                 :            892 :     MarkBufferDirty(bucket_nbuf);
                               1302                 :                : 
 3499                          1303   [ +  -  -  +  :            892 :     if (RelationNeedsWAL(rel))
                                        -  -  -  - ]
                               1304                 :            892 :     {
                               1305                 :                :         xl_hash_split_complete xlrec;
                               1306                 :                : 
                               1307                 :            892 :         xlrec.old_bucket_flag = oopaque->hasho_flag;
                               1308                 :            892 :         xlrec.new_bucket_flag = nopaque->hasho_flag;
                               1309                 :                : 
                               1310                 :            892 :         XLogBeginInsert();
                               1311                 :                : 
  608 peter@eisentraut.org     1312                 :            892 :         XLogRegisterData(&xlrec, SizeOfHashSplitComplete);
                               1313                 :                : 
 3499 rhaas@postgresql.org     1314                 :            892 :         XLogRegisterBuffer(0, bucket_obuf, REGBUF_STANDARD);
                               1315                 :            892 :         XLogRegisterBuffer(1, bucket_nbuf, REGBUF_STANDARD);
                               1316                 :                : 
                               1317                 :            892 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SPLIT_COMPLETE);
                               1318                 :                :     }
                               1319                 :                :     else
  204 pg@bowt.ie               1320                 :UBC           0 :         recptr = XLogGetFakeLSN(rel);
                               1321                 :                : 
  204 pg@bowt.ie               1322                 :CBC         892 :     PageSetLSN(BufferGetPage(bucket_obuf), recptr);
                               1323                 :            892 :     PageSetLSN(BufferGetPage(bucket_nbuf), recptr);
                               1324                 :                : 
 3499 rhaas@postgresql.org     1325         [ -  + ]:            892 :     END_CRIT_SECTION();
                               1326                 :                : 
                               1327                 :                :     /*
                               1328                 :                :      * If possible, clean up the old bucket.  We might not be able to do this
                               1329                 :                :      * if someone else has a pin on it, but if not then we can go ahead.  This
                               1330                 :                :      * isn't absolutely necessary, but it reduces bloat; if we don't do it
                               1331                 :                :      * now, VACUUM will do it eventually, but maybe not until new overflow
                               1332                 :                :      * pages have been allocated.  Note that there's no need to clean up the
                               1333                 :                :      * new bucket.
                               1334                 :                :      */
 3356                          1335         [ +  - ]:            892 :     if (IsBufferCleanupOK(bucket_obuf))
                               1336                 :                :     {
                               1337                 :            892 :         LockBuffer(bucket_nbuf, BUFFER_LOCK_UNLOCK);
                               1338                 :            892 :         hashbucketcleanup(rel, obucket, bucket_obuf,
                               1339                 :                :                           BufferGetBlockNumber(bucket_obuf), NULL,
                               1340                 :                :                           maxbucket, highmask, lowmask, NULL, NULL, true,
                               1341                 :                :                           NULL, NULL);
                               1342                 :                :     }
                               1343                 :                :     else
                               1344                 :                :     {
 3356 rhaas@postgresql.org     1345                 :UBC           0 :         LockBuffer(bucket_nbuf, BUFFER_LOCK_UNLOCK);
                               1346                 :              0 :         LockBuffer(bucket_obuf, BUFFER_LOCK_UNLOCK);
                               1347                 :                :     }
 3603 rhaas@postgresql.org     1348                 :CBC         892 : }
                               1349                 :                : 
                               1350                 :                : /*
                               1351                 :                :  *  _hash_finish_split() -- Finish the previously interrupted split operation
                               1352                 :                :  *
                               1353                 :                :  * To complete the split operation, we form the hash table of TIDs in new
                               1354                 :                :  * bucket which is then used by split operation to skip tuples that are
                               1355                 :                :  * already moved before the split operation was previously interrupted.
                               1356                 :                :  *
                               1357                 :                :  * The caller must hold a pin, but no lock, on the metapage and old bucket's
                               1358                 :                :  * primary page buffer.  The buffers are returned in the same state.  (The
                               1359                 :                :  * metapage is only touched if it becomes necessary to add or remove overflow
                               1360                 :                :  * pages.)
                               1361                 :                :  */
                               1362                 :                : void
                               1363                 :              1 : _hash_finish_split(Relation rel, Buffer metabuf, Buffer obuf, Bucket obucket,
                               1364                 :                :                    uint32 maxbucket, uint32 highmask, uint32 lowmask)
                               1365                 :                : {
                               1366                 :                :     HASHCTL     hash_ctl;
                               1367                 :                :     HTAB       *tidhtab;
                               1368                 :              1 :     Buffer      bucket_nbuf = InvalidBuffer;
                               1369                 :                :     Buffer      nbuf;
                               1370                 :                :     Page        npage;
                               1371                 :                :     BlockNumber nblkno;
                               1372                 :                :     BlockNumber bucket_nblkno;
                               1373                 :                :     HashPageOpaque npageopaque;
                               1374                 :                :     Bucket      nbucket;
                               1375                 :                :     bool        found;
                               1376                 :                : 
                               1377                 :                :     /* Initialize hash tables used to track TIDs */
                               1378                 :              1 :     hash_ctl.keysize = sizeof(ItemPointerData);
                               1379                 :              1 :     hash_ctl.entrysize = sizeof(ItemPointerData);
                               1380                 :              1 :     hash_ctl.hcxt = CurrentMemoryContext;
                               1381                 :                : 
                               1382                 :                :     tidhtab =
                               1383                 :              1 :         hash_create("bucket ctids",
                               1384                 :                :                     256,        /* arbitrary initial size */
                               1385                 :                :                     &hash_ctl,
                               1386                 :                :                     HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
                               1387                 :                : 
                               1388                 :              1 :     bucket_nblkno = nblkno = _hash_get_newblock_from_oldbucket(rel, obucket);
                               1389                 :                : 
                               1390                 :                :     /*
                               1391                 :                :      * Scan the new bucket and build hash table of TIDs
                               1392                 :                :      */
                               1393                 :                :     for (;;)
 3603 rhaas@postgresql.org     1394                 :UBC           0 :     {
                               1395                 :                :         OffsetNumber noffnum;
                               1396                 :                :         OffsetNumber nmaxoffnum;
                               1397                 :                : 
 3603 rhaas@postgresql.org     1398                 :CBC           1 :         nbuf = _hash_getbuf(rel, nblkno, HASH_READ,
                               1399                 :                :                             LH_BUCKET_PAGE | LH_OVERFLOW_PAGE);
                               1400                 :                : 
                               1401                 :                :         /* remember the primary bucket buffer to acquire cleanup lock on it. */
                               1402         [ +  - ]:              1 :         if (nblkno == bucket_nblkno)
                               1403                 :              1 :             bucket_nbuf = nbuf;
                               1404                 :                : 
                               1405                 :              1 :         npage = BufferGetPage(nbuf);
 1655 michael@paquier.xyz      1406                 :              1 :         npageopaque = HashPageGetOpaque(npage);
                               1407                 :                : 
                               1408                 :                :         /* Scan each tuple in new page */
 3603 rhaas@postgresql.org     1409                 :              1 :         nmaxoffnum = PageGetMaxOffsetNumber(npage);
                               1410                 :              1 :         for (noffnum = FirstOffsetNumber;
                               1411         [ +  + ]:              2 :              noffnum <= nmaxoffnum;
                               1412                 :              1 :              noffnum = OffsetNumberNext(noffnum))
                               1413                 :                :         {
                               1414                 :                :             IndexTuple  itup;
                               1415                 :                : 
                               1416                 :                :             /* Fetch the item's TID and insert it in hash table. */
                               1417                 :              1 :             itup = (IndexTuple) PageGetItem(npage,
                               1418                 :              1 :                                             PageGetItemId(npage, noffnum));
                               1419                 :                : 
                               1420                 :              1 :             (void) hash_search(tidhtab, &itup->t_tid, HASH_ENTER, &found);
                               1421                 :                : 
                               1422         [ -  + ]:              1 :             Assert(!found);
                               1423                 :                :         }
                               1424                 :                : 
                               1425                 :              1 :         nblkno = npageopaque->hasho_nextblkno;
                               1426                 :                : 
                               1427                 :                :         /*
                               1428                 :                :          * release our write lock without modifying buffer and ensure to
                               1429                 :                :          * retain the pin on primary bucket.
                               1430                 :                :          */
                               1431         [ +  - ]:              1 :         if (nbuf == bucket_nbuf)
 3580                          1432                 :              1 :             LockBuffer(nbuf, BUFFER_LOCK_UNLOCK);
                               1433                 :                :         else
 3603 rhaas@postgresql.org     1434                 :UBC           0 :             _hash_relbuf(rel, nbuf);
                               1435                 :                : 
                               1436                 :                :         /* Exit loop if no more overflow pages in new bucket */
 3603 rhaas@postgresql.org     1437         [ +  - ]:CBC           1 :         if (!BlockNumberIsValid(nblkno))
                               1438                 :              1 :             break;
                               1439                 :                :     }
                               1440                 :                : 
                               1441                 :                :     /*
                               1442                 :                :      * Conditionally get the cleanup lock on old and new buckets to perform
                               1443                 :                :      * the split operation.  If we don't get the cleanup locks, silently give
                               1444                 :                :      * up and next insertion on old bucket will try again to complete the
                               1445                 :                :      * split.
                               1446                 :                :      */
                               1447         [ -  + ]:              1 :     if (!ConditionalLockBufferForCleanup(obuf))
                               1448                 :                :     {
 3603 rhaas@postgresql.org     1449                 :UBC           0 :         hash_destroy(tidhtab);
                               1450                 :              0 :         return;
                               1451                 :                :     }
 3603 rhaas@postgresql.org     1452         [ -  + ]:CBC           1 :     if (!ConditionalLockBufferForCleanup(bucket_nbuf))
                               1453                 :                :     {
 3580 rhaas@postgresql.org     1454                 :UBC           0 :         LockBuffer(obuf, BUFFER_LOCK_UNLOCK);
 3603                          1455                 :              0 :         hash_destroy(tidhtab);
                               1456                 :              0 :         return;
                               1457                 :                :     }
                               1458                 :                : 
 3603 rhaas@postgresql.org     1459                 :CBC           1 :     npage = BufferGetPage(bucket_nbuf);
 1655 michael@paquier.xyz      1460                 :              1 :     npageopaque = HashPageGetOpaque(npage);
 3603 rhaas@postgresql.org     1461                 :              1 :     nbucket = npageopaque->hasho_bucket;
                               1462                 :                : 
    2 pg@bowt.ie               1463                 :              1 :     INJECTION_POINT("hash-finish-incomplete-split", NULL);
                               1464                 :                : 
 3512 rhaas@postgresql.org     1465                 :              1 :     _hash_splitbucket(rel, metabuf, obucket,
                               1466                 :                :                       nbucket, obuf, bucket_nbuf, tidhtab,
                               1467                 :                :                       maxbucket, highmask, lowmask);
                               1468                 :                : 
 3356                          1469                 :              1 :     _hash_dropbuf(rel, bucket_nbuf);
 3603                          1470                 :              1 :     hash_destroy(tidhtab);
                               1471                 :                : }
                               1472                 :                : 
                               1473                 :                : /*
                               1474                 :                :  *  log_split_page() -- Log the split operation
                               1475                 :                :  *
                               1476                 :                :  *  We log the split operation when the new page in new bucket gets full,
                               1477                 :                :  *  so we log the entire page.
                               1478                 :                :  *
                               1479                 :                :  *  'buf' must be locked by the caller which is also responsible for unlocking
                               1480                 :                :  *  it.
                               1481                 :                :  */
                               1482                 :                : static void
 3499                          1483                 :            944 : log_split_page(Relation rel, Buffer buf)
                               1484                 :                : {
                               1485                 :                :     XLogRecPtr  recptr;
                               1486                 :                : 
                               1487   [ +  -  -  +  :            944 :     if (RelationNeedsWAL(rel))
                                        -  -  -  - ]
                               1488                 :                :     {
                               1489                 :            944 :         XLogBeginInsert();
                               1490                 :                : 
                               1491                 :            944 :         XLogRegisterBuffer(0, buf, REGBUF_FORCE_IMAGE | REGBUF_STANDARD);
                               1492                 :                : 
                               1493                 :            944 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SPLIT_PAGE);
                               1494                 :                :     }
                               1495                 :                :     else
   88 pg@bowt.ie               1496                 :UBC           0 :         recptr = XLogGetFakeLSN(rel);
                               1497                 :                : 
   88 pg@bowt.ie               1498                 :CBC         944 :     PageSetLSN(BufferGetPage(buf), recptr);
 3499 rhaas@postgresql.org     1499                 :            944 : }
                               1500                 :                : 
                               1501                 :                : /*
                               1502                 :                :  *  _hash_getcachedmetap() -- Returns cached metapage data.
                               1503                 :                :  *
                               1504                 :                :  *  If metabuf is not InvalidBuffer, caller must hold a pin, but no lock, on
                               1505                 :                :  *  the metapage.  If not set, we'll set it before returning if we have to
                               1506                 :                :  *  refresh the cache, and return with a pin but no lock on it; caller is
                               1507                 :                :  *  responsible for releasing the pin.
                               1508                 :                :  *
                               1509                 :                :  *  We refresh the cache if it's not initialized yet or force_refresh is true.
                               1510                 :                :  */
                               1511                 :                : HashMetaPage
 3534                          1512                 :         492534 : _hash_getcachedmetap(Relation rel, Buffer *metabuf, bool force_refresh)
                               1513                 :                : {
                               1514                 :                :     Page        page;
                               1515                 :                : 
                               1516         [ -  + ]:         492534 :     Assert(metabuf);
                               1517   [ +  +  +  + ]:         492534 :     if (force_refresh || rel->rd_amcache == NULL)
                               1518                 :                :     {
 3435 bruce@momjian.us         1519                 :            733 :         char       *cache = NULL;
                               1520                 :                : 
                               1521                 :                :         /*
                               1522                 :                :          * It's important that we don't set rd_amcache to an invalid value.
                               1523                 :                :          * Either MemoryContextAlloc or _hash_getbuf could fail, so don't
                               1524                 :                :          * install a pointer to the newly-allocated storage in the actual
                               1525                 :                :          * relcache entry until both have succeeded.
                               1526                 :                :          */
 3534 rhaas@postgresql.org     1527         [ +  + ]:            733 :         if (rel->rd_amcache == NULL)
                               1528                 :            320 :             cache = MemoryContextAlloc(rel->rd_indexcxt,
                               1529                 :                :                                        sizeof(HashMetaPageData));
                               1530                 :                : 
                               1531                 :                :         /* Read the metapage. */
                               1532         [ -  + ]:            733 :         if (BufferIsValid(*metabuf))
 3534 rhaas@postgresql.org     1533                 :UBC           0 :             LockBuffer(*metabuf, BUFFER_LOCK_SHARE);
                               1534                 :                :         else
 3534 rhaas@postgresql.org     1535                 :CBC         733 :             *metabuf = _hash_getbuf(rel, HASH_METAPAGE, HASH_READ,
                               1536                 :                :                                     LH_META_PAGE);
                               1537                 :            733 :         page = BufferGetPage(*metabuf);
                               1538                 :                : 
                               1539                 :                :         /* Populate the cache. */
                               1540         [ +  + ]:            733 :         if (rel->rd_amcache == NULL)
                               1541                 :            320 :             rel->rd_amcache = cache;
                               1542                 :            733 :         memcpy(rel->rd_amcache, HashPageGetMeta(page),
                               1543                 :                :                sizeof(HashMetaPageData));
                               1544                 :                : 
                               1545                 :                :         /* Release metapage lock, but keep the pin. */
                               1546                 :            733 :         LockBuffer(*metabuf, BUFFER_LOCK_UNLOCK);
                               1547                 :                :     }
                               1548                 :                : 
                               1549                 :         492534 :     return (HashMetaPage) rel->rd_amcache;
                               1550                 :                : }
                               1551                 :                : 
                               1552                 :                : /*
                               1553                 :                :  *  _hash_getbucketbuf_from_hashkey() -- Get the bucket's buffer for the given
                               1554                 :                :  *                                       hashkey.
                               1555                 :                :  *
                               1556                 :                :  *  Bucket pages do not move or get removed once they are allocated. This give
                               1557                 :                :  *  us an opportunity to use the previously saved metapage contents to reach
                               1558                 :                :  *  the target bucket buffer, instead of reading from the metapage every time.
                               1559                 :                :  *  This saves one buffer access every time we want to reach the target bucket
                               1560                 :                :  *  buffer, which is very helpful savings in bufmgr traffic and contention.
                               1561                 :                :  *
                               1562                 :                :  *  The access type parameter (HASH_READ or HASH_WRITE) indicates whether the
                               1563                 :                :  *  bucket buffer has to be locked for reading or writing.
                               1564                 :                :  *
                               1565                 :                :  *  The out parameter cachedmetap is set with metapage contents used for
                               1566                 :                :  *  hashkey to bucket buffer mapping. Some callers need this info to reach the
                               1567                 :                :  *  old bucket in case of bucket split, see _hash_doinsert().
                               1568                 :                :  */
                               1569                 :                : Buffer
                               1570                 :         492096 : _hash_getbucketbuf_from_hashkey(Relation rel, uint32 hashkey, int access,
                               1571                 :                :                                 HashMetaPage *cachedmetap)
                               1572                 :                : {
                               1573                 :                :     HashMetaPage metap;
                               1574                 :                :     Buffer      buf;
                               1575                 :         492096 :     Buffer      metabuf = InvalidBuffer;
                               1576                 :                :     Page        page;
                               1577                 :                :     Bucket      bucket;
                               1578                 :                :     BlockNumber blkno;
                               1579                 :                :     HashPageOpaque opaque;
                               1580                 :                : 
                               1581                 :                :     /* We read from target bucket buffer, hence locking is must. */
                               1582   [ +  +  -  + ]:         492096 :     Assert(access == HASH_READ || access == HASH_WRITE);
                               1583                 :                : 
                               1584                 :         492096 :     metap = _hash_getcachedmetap(rel, &metabuf, false);
                               1585         [ +  - ]:         492096 :     Assert(metap != NULL);
                               1586                 :                : 
                               1587                 :                :     /*
                               1588                 :                :      * Loop until we get a lock on the correct target bucket.
                               1589                 :                :      */
                               1590                 :                :     for (;;)
                               1591                 :                :     {
                               1592                 :                :         /*
                               1593                 :                :          * Compute the target bucket number, and convert to block number.
                               1594                 :                :          */
                               1595                 :         492509 :         bucket = _hash_hashkey2bucket(hashkey,
                               1596                 :                :                                       metap->hashm_maxbucket,
                               1597                 :                :                                       metap->hashm_highmask,
                               1598                 :                :                                       metap->hashm_lowmask);
                               1599                 :                : 
                               1600         [ +  + ]:         492509 :         blkno = BUCKET_TO_BLKNO(metap, bucket);
                               1601                 :                : 
                               1602                 :                :         /* Fetch the primary bucket page for the bucket */
                               1603                 :         492509 :         buf = _hash_getbuf(rel, blkno, access, LH_BUCKET_PAGE);
                               1604                 :         492509 :         page = BufferGetPage(buf);
 1655 michael@paquier.xyz      1605                 :         492509 :         opaque = HashPageGetOpaque(page);
 3534 rhaas@postgresql.org     1606         [ -  + ]:         492509 :         Assert(opaque->hasho_bucket == bucket);
 3443                          1607         [ -  + ]:         492509 :         Assert(opaque->hasho_prevblkno != InvalidBlockNumber);
                               1608                 :                : 
                               1609                 :                :         /*
                               1610                 :                :          * If this bucket hasn't been split, we're done.
                               1611                 :                :          */
                               1612         [ +  + ]:         492509 :         if (opaque->hasho_prevblkno <= metap->hashm_maxbucket)
 3534                          1613                 :         492096 :             break;
                               1614                 :                : 
                               1615                 :                :         /* Drop lock on this buffer, update cached metapage, and retry. */
                               1616                 :            413 :         _hash_relbuf(rel, buf);
                               1617                 :            413 :         metap = _hash_getcachedmetap(rel, &metabuf, true);
                               1618         [ -  + ]:            413 :         Assert(metap != NULL);
                               1619                 :                :     }
                               1620                 :                : 
                               1621         [ +  + ]:         492096 :     if (BufferIsValid(metabuf))
                               1622                 :            727 :         _hash_dropbuf(rel, metabuf);
                               1623                 :                : 
                               1624         [ +  + ]:         492096 :     if (cachedmetap)
                               1625                 :         491751 :         *cachedmetap = metap;
                               1626                 :                : 
                               1627                 :         492096 :     return buf;
                               1628                 :                : }
        

Generated by: LCOV version 2.0-1