LCOV - code coverage report
Current view: top level - src/backend/access/hash - hashpage.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.3 % 478 422
Test Date: 2026-10-29 00:16:02 Functions: 100.0 % 19 19
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 58.0 % 226 131

             Branch data     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
      71                 :     1295952 : _hash_getbuf(Relation rel, BlockNumber blkno, int access, int flags)
      72                 :             : {
      73                 :             :     Buffer      buf;
      74                 :             : 
      75         [ -  + ]:     1295952 :     if (blkno == P_NEW)
      76         [ #  # ]:           0 :         elog(ERROR, "hash AM does not use P_NEW");
      77                 :             : 
      78                 :     1295952 :     buf = ReadBuffer(rel, blkno);
      79                 :             : 
      80         [ +  + ]:     1295952 :     if (access != HASH_NOLOCK)
      81                 :      809719 :         LockBuffer(buf, access);
      82                 :             : 
      83                 :             :     /* ref count and lock type are correct */
      84                 :             : 
      85                 :     1295952 :     _hash_checkpage(rel, buf, flags);
      86                 :             : 
      87                 :     1295952 :     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
      97                 :         766 : _hash_getbuf_with_condlock_cleanup(Relation rel, BlockNumber blkno, int flags)
      98                 :             : {
      99                 :             :     Buffer      buf;
     100                 :             : 
     101         [ -  + ]:         766 :     if (blkno == P_NEW)
     102         [ #  # ]:           0 :         elog(ERROR, "hash AM does not use P_NEW");
     103                 :             : 
     104                 :         766 :     buf = ReadBuffer(rel, blkno);
     105                 :             : 
     106         [ -  + ]:         766 :     if (!ConditionalLockBufferForCleanup(buf))
     107                 :             :     {
     108                 :           0 :         ReleaseBuffer(buf);
     109                 :           0 :         return InvalidBuffer;
     110                 :             :     }
     111                 :             : 
     112                 :             :     /* ref count and lock type are correct */
     113                 :             : 
     114                 :         766 :     _hash_checkpage(rel, buf, flags);
     115                 :             : 
     116                 :         766 :     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
     136                 :          47 : _hash_getinitbuf(Relation rel, BlockNumber blkno)
     137                 :             : {
     138                 :             :     Buffer      buf;
     139                 :             : 
     140         [ -  + ]:          47 :     if (blkno == P_NEW)
     141         [ #  # ]:           0 :         elog(ERROR, "hash AM does not use P_NEW");
     142                 :             : 
     143                 :          47 :     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 */
     149                 :          47 :     _hash_pageinit(BufferGetPage(buf), BufferGetPageSize(buf));
     150                 :             : 
     151                 :          47 :     return buf;
     152                 :             : }
     153                 :             : 
     154                 :             : /*
     155                 :             :  *  _hash_initbuf() -- Get and initialize a buffer by bucket number.
     156                 :             :  */
     157                 :             : void
     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                 :             : 
     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                 :             :      */
     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
     199                 :        6717 : _hash_getnewbuf(Relation rel, BlockNumber blkno, ForkNumber forkNum)
     200                 :             : {
     201                 :        6717 :     BlockNumber nblocks = RelationGetNumberOfBlocksInFork(rel, forkNum);
     202                 :             :     Buffer      buf;
     203                 :             : 
     204         [ -  + ]:        6717 :     if (blkno == P_NEW)
     205         [ #  # ]:           0 :         elog(ERROR, "hash AM does not use P_NEW");
     206         [ -  + ]:        6717 :     if (blkno > nblocks)
     207         [ #  # ]:           0 :         elog(ERROR, "access to noncontiguous page in hash index \"%s\"",
     208                 :             :              RelationGetRelationName(rel));
     209                 :             : 
     210                 :             :     /* smgr insists we explicitly extend the relation */
     211         [ +  + ]:        6717 :     if (blkno == nblocks)
     212                 :             :     {
     213                 :        5951 :         buf = ExtendBufferedRel(BMR_REL(rel), forkNum, NULL,
     214                 :             :                                 EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
     215         [ -  + ]:        5951 :         if (BufferGetBlockNumber(buf) != blkno)
     216         [ #  # ]:           0 :             elog(ERROR, "unexpected hash relation size: %u, should be %u",
     217                 :             :                  BufferGetBlockNumber(buf), blkno);
     218                 :             :     }
     219                 :             :     else
     220                 :             :     {
     221                 :         766 :         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 */
     228                 :        6717 :     _hash_pageinit(BufferGetPage(buf), BufferGetPageSize(buf));
     229                 :             : 
     230                 :        6717 :     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
     240                 :         858 : _hash_getbuf_with_strategy(Relation rel, BlockNumber blkno,
     241                 :             :                            int access, int flags,
     242                 :             :                            BufferAccessStrategy bstrategy)
     243                 :             : {
     244                 :             :     Buffer      buf;
     245                 :             : 
     246         [ -  + ]:         858 :     if (blkno == P_NEW)
     247         [ #  # ]:           0 :         elog(ERROR, "hash AM does not use P_NEW");
     248                 :             : 
     249                 :         858 :     buf = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL, bstrategy);
     250                 :             : 
     251         [ +  - ]:         858 :     if (access != HASH_NOLOCK)
     252                 :         858 :         LockBuffer(buf, access);
     253                 :             : 
     254                 :             :     /* ref count and lock type are correct */
     255                 :             : 
     256                 :         858 :     _hash_checkpage(rel, buf, flags);
     257                 :             : 
     258                 :         858 :     return buf;
     259                 :             : }
     260                 :             : 
     261                 :             : /*
     262                 :             :  *  _hash_relbuf() -- release a locked buffer.
     263                 :             :  *
     264                 :             :  * Lock and pin (refcount) are both dropped.
     265                 :             :  */
     266                 :             : void
     267                 :      753555 : _hash_relbuf(Relation rel, Buffer buf)
     268                 :             : {
     269                 :      753555 :     UnlockReleaseBuffer(buf);
     270                 :      753555 : }
     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                 :      551672 : _hash_dropbuf(Relation rel, Buffer buf)
     279                 :             : {
     280                 :      551672 :     ReleaseBuffer(buf);
     281                 :      551672 : }
     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
     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) &&
     294         [ +  + ]:         345 :         so->hashso_bucket_buf != so->currPos.buf)
     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) &&
     300         [ +  + ]:           3 :         so->hashso_split_bucket_buf != so->currPos.buf)
     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 */
     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 */
     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
     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 */
     344         [ -  + ]:         216 :     if (RelationGetNumberOfBlocksInFork(rel, forkNum) != 0)
     345         [ #  # ]:           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                 :             :      */
     353   [ +  +  +  +  :         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                 :             :      */
     361                 :         216 :     data_width = sizeof(uint32);
     362                 :         216 :     item_width = MAXALIGN(sizeof(IndexTupleData)) + MAXALIGN(data_width) +
     363                 :             :         sizeof(ItemIdData);     /* include the line pointer */
     364         [ +  + ]:         216 :     ffactor = HashGetTargetPageUsage(rel) / item_width;
     365                 :             :     /* keep to a sane range */
     366         [ -  + ]:         216 :     if (ffactor < 10)
     367                 :           0 :         ffactor = 10;
     368                 :             : 
     369                 :         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                 :             :      */
     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 */
     388         [ +  + ]:         216 :     if (use_wal)
     389                 :             :     {
     390                 :             :         xl_hash_init_meta_page xlrec;
     391                 :             :         XLogRecPtr  recptr;
     392                 :             : 
     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();
     398                 :         170 :         XLogRegisterData(&xlrec, SizeOfHashInitMetaPage);
     399                 :         170 :         XLogRegisterBuffer(0, metabuf, REGBUF_WILL_INIT | REGBUF_STANDARD);
     400                 :             : 
     401                 :         170 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_INIT_META_PAGE);
     402                 :             : 
     403                 :         170 :         PageSetLSN(BufferGetPage(metabuf), recptr);
     404                 :             :     }
     405                 :             : 
     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                 :             : 
     431         [ +  + ]:        5298 :         if (use_wal)
     432                 :        5152 :             log_newpage(&rel->rd_locator,
     433                 :             :                         forkNum,
     434                 :             :                         blkno,
     435                 :             :                         BufferGetPage(buf),
     436                 :             :                         true);
     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)
     453         [ #  # ]:           0 :         ereport(ERROR,
     454                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     455                 :             :                  errmsg("out of overflow pages in hash index \"%s\"",
     456                 :             :                         RelationGetRelationName(rel))));
     457                 :             : 
     458                 :         216 :     metap->hashm_mapp[metap->hashm_nmaps] = num_buckets + 1;
     459                 :             : 
     460                 :         216 :     metap->hashm_nmaps++;
     461                 :         216 :     MarkBufferDirty(metabuf);
     462                 :             : 
     463                 :             :     /* XLOG stuff */
     464         [ +  + ]:         216 :     if (use_wal)
     465                 :             :     {
     466                 :             :         xl_hash_init_bitmap_page xlrec;
     467                 :             :         XLogRecPtr  recptr;
     468                 :             : 
     469                 :         170 :         xlrec.bmsize = metap->hashm_bmsize;
     470                 :             : 
     471                 :         170 :         XLogBeginInsert();
     472                 :         170 :         XLogRegisterData(&xlrec, SizeOfHashInitBitmapPage);
     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 */
     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                 :             :      */
     518                 :         246 :     dnumbuckets = num_tuples / ffactor;
     519         [ +  + ]:         246 :     if (dnumbuckets <= 2.0)
     520                 :          72 :         num_buckets = 2;
     521         [ -  + ]:         174 :     else if (dnumbuckets >= (double) 0x40000000)
     522                 :           0 :         num_buckets = 0x40000000;
     523                 :             :     else
     524                 :         174 :         num_buckets = _hash_get_totalbuckets(_hash_spareindex(dnumbuckets));
     525                 :             : 
     526                 :         246 :     spare_index = _hash_spareindex(num_buckets);
     527                 :             :     Assert(spare_index < HASH_MAX_SPLITPOINTS);
     528                 :             : 
     529                 :         246 :     page = BufferGetPage(buf);
     530         [ +  + ]:         246 :     if (initpage)
     531                 :          30 :         _hash_pageinit(page, BufferGetPageSize(buf));
     532                 :             : 
     533                 :         246 :     pageopaque = HashPageGetOpaque(page);
     534                 :         246 :     pageopaque->hasho_prevblkno = InvalidBlockNumber;
     535                 :         246 :     pageopaque->hasho_nextblkno = InvalidBlockNumber;
     536                 :         246 :     pageopaque->hasho_bucket = InvalidBucket;
     537                 :         246 :     pageopaque->hasho_flag = LH_META_PAGE;
     538                 :         246 :     pageopaque->hasho_page_id = HASHO_PAGE_ID;
     539                 :             : 
     540                 :         246 :     metap = HashPageGetMeta(page);
     541                 :             : 
     542                 :         246 :     metap->hashm_magic = HASH_MAGIC;
     543                 :         246 :     metap->hashm_version = HASH_VERSION;
     544                 :         246 :     metap->hashm_ntuples = 0;
     545                 :         246 :     metap->hashm_nmaps = 0;
     546                 :         246 :     metap->hashm_ffactor = ffactor;
     547                 :         246 :     metap->hashm_bsize = HashGetMaxBitmapSize(page);
     548                 :             : 
     549                 :             :     /* find largest bitmap array size that will fit in page size */
     550                 :         246 :     lshift = pg_leftmost_one_pos32(metap->hashm_bsize);
     551                 :             :     Assert(lshift > 0);
     552                 :         246 :     metap->hashm_bmsize = 1 << lshift;
     553                 :         246 :     metap->hashm_bmshift = lshift + BYTE_TO_BIT;
     554                 :             :     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                 :             :      */
     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                 :             :      */
     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                 :             :      */
     573                 :         246 :     metap->hashm_highmask = pg_nextpower2_32(num_buckets + 1) - 1;
     574                 :         246 :     metap->hashm_lowmask = (metap->hashm_highmask >> 1);
     575                 :             : 
     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 */
     580                 :         246 :     metap->hashm_spares[spare_index] = 1;
     581                 :         246 :     metap->hashm_ovflpoint = spare_index;
     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                 :             :      */
     589                 :         246 :     ((PageHeader) page)->pd_lower =
     590                 :         246 :         ((char *) metap + sizeof(HashMetaPageData)) - (char *) page;
     591                 :         246 : }
     592                 :             : 
     593                 :             : /*
     594                 :             :  *  _hash_pageinit() -- Initialize a new hash index page.
     595                 :             :  */
     596                 :             : void
     597                 :        7293 : _hash_pageinit(Page page, Size size)
     598                 :             : {
     599                 :        7293 :     PageInit(page, size, sizeof(HashPageOpaqueData));
     600                 :        7293 : }
     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                 :         766 : _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;
     632                 :         766 :     bool        metap_update_masks = false;
     633                 :         766 :     bool        metap_update_splitpoint = false;
     634                 :             :     XLogRecPtr  recptr;
     635                 :             : 
     636                 :           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                 :             :      */
     642                 :         766 :     LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
     643                 :             : 
     644                 :         766 :     _hash_checkpage(rel, metabuf, LH_META_PAGE);
     645                 :         766 :     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                 :             :      */
     653                 :         766 :     if (metap->hashm_ntuples <=
     654         [ -  + ]:         766 :         (double) metap->hashm_ffactor * (metap->hashm_maxbucket + 1))
     655                 :           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                 :             :      */
     672         [ -  + ]:         766 :     if (metap->hashm_maxbucket >= (uint32) 0x7FFFFFFE)
     673                 :           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                 :             :      */
     687                 :         766 :     new_bucket = metap->hashm_maxbucket + 1;
     688                 :             : 
     689                 :         766 :     old_bucket = (new_bucket & metap->hashm_lowmask);
     690                 :             : 
     691         [ +  + ]:         766 :     start_oblkno = BUCKET_TO_BLKNO(metap, old_bucket);
     692                 :             : 
     693                 :         766 :     buf_oblkno = _hash_getbuf_with_condlock_cleanup(rel, start_oblkno, LH_BUCKET_PAGE);
     694         [ -  + ]:         766 :     if (!buf_oblkno)
     695                 :           0 :         goto fail;
     696                 :             : 
     697                 :         766 :     opage = BufferGetPage(buf_oblkno);
     698                 :         766 :     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                 :             :      */
     708         [ -  + ]:         766 :     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                 :             :          */
     715                 :           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                 :             :          */
     723                 :           0 :         LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
     724                 :           0 :         LockBuffer(buf_oblkno, BUFFER_LOCK_UNLOCK);
     725                 :             : 
     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                 :             :      */
     748         [ -  + ]:         766 :     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                 :             :          */
     755                 :           0 :         maxbucket = metap->hashm_maxbucket;
     756                 :           0 :         highmask = metap->hashm_highmask;
     757                 :           0 :         lowmask = metap->hashm_lowmask;
     758                 :             : 
     759                 :             :         /* Release the metapage lock. */
     760                 :           0 :         LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
     761                 :             : 
     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                 :             :      */
     779         [ +  - ]:         766 :     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                 :             :      */
     785                 :         766 :     spare_ndx = _hash_spareindex(new_bucket + 1);
     786         [ +  + ]:         766 :     if (spare_ndx > metap->hashm_ovflpoint)
     787                 :             :     {
     788                 :             :         uint32      buckets_to_add;
     789                 :             : 
     790                 :             :         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                 :             :          */
     798                 :          38 :         buckets_to_add = _hash_get_totalbuckets(spare_ndx) - new_bucket;
     799         [ -  + ]:          38 :         if (!_hash_alloc_buckets(rel, start_nblkno, buckets_to_add))
     800                 :             :         {
     801                 :             :             /* can't split due to BlockNumber overflow */
     802                 :           0 :             _hash_relbuf(rel, buf_oblkno);
     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                 :             :      */
     818                 :         766 :     buf_nblkno = _hash_getnewbuf(rel, start_nblkno, MAIN_FORKNUM);
     819         [ -  + ]:         766 :     if (!IsBufferCleanupOK(buf_nblkno))
     820                 :             :     {
     821                 :           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                 :             :      */
     832                 :         766 :     START_CRIT_SECTION();
     833                 :             : 
     834                 :             :     /*
     835                 :             :      * Okay to proceed with split.  Update the metapage bucket mapping info.
     836                 :             :      */
     837                 :         766 :     metap->hashm_maxbucket = new_bucket;
     838                 :             : 
     839         [ +  + ]:         766 :     if (new_bucket > metap->hashm_highmask)
     840                 :             :     {
     841                 :             :         /* Starting a new doubling */
     842                 :          13 :         metap->hashm_lowmask = metap->hashm_highmask;
     843                 :          13 :         metap->hashm_highmask = new_bucket | metap->hashm_lowmask;
     844                 :          13 :         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                 :             :      */
     852         [ +  + ]:         766 :     if (spare_ndx > metap->hashm_ovflpoint)
     853                 :             :     {
     854                 :          38 :         metap->hashm_spares[spare_ndx] = metap->hashm_spares[metap->hashm_ovflpoint];
     855                 :          38 :         metap->hashm_ovflpoint = spare_ndx;
     856                 :          38 :         metap_update_splitpoint = true;
     857                 :             :     }
     858                 :             : 
     859                 :         766 :     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                 :             :      */
     868                 :         766 :     maxbucket = metap->hashm_maxbucket;
     869                 :         766 :     highmask = metap->hashm_highmask;
     870                 :         766 :     lowmask = metap->hashm_lowmask;
     871                 :             : 
     872                 :         766 :     opage = BufferGetPage(buf_oblkno);
     873                 :         766 :     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                 :             :      */
     881                 :         766 :     oopaque->hasho_flag |= LH_BUCKET_BEING_SPLIT;
     882                 :         766 :     oopaque->hasho_prevblkno = maxbucket;
     883                 :             : 
     884                 :         766 :     MarkBufferDirty(buf_oblkno);
     885                 :             : 
     886                 :         766 :     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                 :             :      */
     892                 :         766 :     nopaque = HashPageGetOpaque(npage);
     893                 :         766 :     nopaque->hasho_prevblkno = maxbucket;
     894                 :         766 :     nopaque->hasho_nextblkno = InvalidBlockNumber;
     895                 :         766 :     nopaque->hasho_bucket = new_bucket;
     896                 :         766 :     nopaque->hasho_flag = LH_BUCKET_PAGE | LH_BUCKET_BEING_POPULATED;
     897                 :         766 :     nopaque->hasho_page_id = HASHO_PAGE_ID;
     898                 :             : 
     899                 :         766 :     MarkBufferDirty(buf_nblkno);
     900                 :             : 
     901                 :             :     /* XLOG stuff */
     902   [ +  -  -  +  :         766 :     if (RelationNeedsWAL(rel))
             -  -  -  - ]
     903                 :         766 :     {
     904                 :             :         xl_hash_split_allocate_page xlrec;
     905                 :             : 
     906                 :         766 :         xlrec.new_bucket = maxbucket;
     907                 :         766 :         xlrec.old_bucket_flag = oopaque->hasho_flag;
     908                 :         766 :         xlrec.new_bucket_flag = nopaque->hasho_flag;
     909                 :         766 :         xlrec.flags = 0;
     910                 :             : 
     911                 :         766 :         XLogBeginInsert();
     912                 :             : 
     913                 :         766 :         XLogRegisterBuffer(0, buf_oblkno, REGBUF_STANDARD);
     914                 :         766 :         XLogRegisterBuffer(1, buf_nblkno, REGBUF_WILL_INIT);
     915                 :         766 :         XLogRegisterBuffer(2, metabuf, REGBUF_STANDARD);
     916                 :             : 
     917         [ +  + ]:         766 :         if (metap_update_masks)
     918                 :             :         {
     919                 :          13 :             xlrec.flags |= XLH_SPLIT_META_UPDATE_MASKS;
     920                 :          13 :             XLogRegisterBufData(2, &metap->hashm_lowmask, sizeof(uint32));
     921                 :          13 :             XLogRegisterBufData(2, &metap->hashm_highmask, sizeof(uint32));
     922                 :             :         }
     923                 :             : 
     924         [ +  + ]:         766 :         if (metap_update_splitpoint)
     925                 :             :         {
     926                 :          38 :             xlrec.flags |= XLH_SPLIT_META_UPDATE_SPLITPOINT;
     927                 :          38 :             XLogRegisterBufData(2, &metap->hashm_ovflpoint,
     928                 :             :                                 sizeof(uint32));
     929                 :          38 :             XLogRegisterBufData(2,
     930                 :          38 :                                 &metap->hashm_spares[metap->hashm_ovflpoint],
     931                 :             :                                 sizeof(uint32));
     932                 :             :         }
     933                 :             : 
     934                 :         766 :         XLogRegisterData(&xlrec, SizeOfHashSplitAllocPage);
     935                 :             : 
     936                 :         766 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SPLIT_ALLOCATE_PAGE);
     937                 :             :     }
     938                 :             :     else
     939                 :           0 :         recptr = XLogGetFakeLSN(rel);
     940                 :             : 
     941                 :         766 :     PageSetLSN(BufferGetPage(buf_oblkno), recptr);
     942                 :         766 :     PageSetLSN(BufferGetPage(buf_nblkno), recptr);
     943                 :         766 :     PageSetLSN(BufferGetPage(metabuf), recptr);
     944                 :             : 
     945                 :         766 :     END_CRIT_SECTION();
     946                 :             : 
     947                 :             :     /* drop lock, but keep pin */
     948                 :         766 :     LockBuffer(metabuf, BUFFER_LOCK_UNLOCK);
     949                 :             : 
     950                 :             :     /* Relocate records to the new bucket */
     951                 :         766 :     _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. */
     957                 :         765 :     _hash_dropbuf(rel, buf_oblkno);
     958                 :         765 :     _hash_dropbuf(rel, buf_nblkno);
     959                 :             : 
     960                 :         765 :     return;
     961                 :             : 
     962                 :             :     /* Here if decide not to split or fail to acquire old bucket lock */
     963                 :           0 : fail:
     964                 :             : 
     965                 :             :     /* We didn't write the metapage, so just drop lock */
     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
     995                 :          38 : _hash_alloc_buckets(Relation rel, BlockNumber firstblock, uint32 nblocks)
     996                 :             : {
     997                 :             :     BlockNumber lastblock;
     998                 :             :     PGIOAlignedBlock zerobuf;
     999                 :             :     Page        page;
    1000                 :             :     HashPageOpaque ovflopaque;
    1001                 :             : 
    1002                 :          38 :     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   [ +  -  -  + ]:          38 :     if (lastblock < firstblock || lastblock == InvalidBlockNumber)
    1009                 :           0 :         return false;
    1010                 :             : 
    1011                 :          38 :     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                 :             :      */
    1018                 :          38 :     _hash_pageinit(page, BLCKSZ);
    1019                 :             : 
    1020                 :          38 :     ovflopaque = HashPageGetOpaque(page);
    1021                 :             : 
    1022                 :          38 :     ovflopaque->hasho_prevblkno = InvalidBlockNumber;
    1023                 :          38 :     ovflopaque->hasho_nextblkno = InvalidBlockNumber;
    1024                 :          38 :     ovflopaque->hasho_bucket = InvalidBucket;
    1025                 :          38 :     ovflopaque->hasho_flag = LH_UNUSED_PAGE;
    1026                 :          38 :     ovflopaque->hasho_page_id = HASHO_PAGE_ID;
    1027                 :             : 
    1028   [ +  -  -  +  :          38 :     if (RelationNeedsWAL(rel))
             -  -  -  - ]
    1029                 :          38 :         log_newpage(&rel->rd_locator,
    1030                 :             :                     MAIN_FORKNUM,
    1031                 :             :                     lastblock,
    1032                 :             :                     zerobuf.data,
    1033                 :             :                     true);
    1034                 :             : 
    1035                 :          38 :     PageSetChecksum(page, lastblock);
    1036                 :          38 :     smgrextend(RelationGetSmgr(rel), MAIN_FORKNUM, lastblock, zerobuf.data,
    1037                 :             :                false);
    1038                 :             : 
    1039                 :          38 :     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
    1076                 :         767 : _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];
    1095                 :         767 :     Size        all_tups_size = 0;
    1096                 :             :     int         i;
    1097                 :         767 :     uint16      nitups = 0;
    1098                 :             :     XLogRecPtr  recptr;
    1099                 :             : 
    1100                 :         767 :     bucket_obuf = obuf;
    1101                 :         767 :     opage = BufferGetPage(obuf);
    1102                 :         767 :     oopaque = HashPageGetOpaque(opage);
    1103                 :             : 
    1104                 :         767 :     bucket_nbuf = nbuf;
    1105                 :         767 :     npage = BufferGetPage(nbuf);
    1106                 :         767 :     nopaque = HashPageGetOpaque(npage);
    1107                 :             : 
    1108                 :             :     /* Copy the predicate locks from old bucket to new bucket. */
    1109                 :         767 :     PredicateLockPageSplit(rel,
    1110                 :             :                            BufferGetBlockNumber(bucket_obuf),
    1111                 :             :                            BufferGetBlockNumber(bucket_nbuf));
    1112                 :             : 
    1113                 :         767 :     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 (;;)
    1122                 :         225 :     {
    1123                 :             :         BlockNumber oblkno;
    1124                 :             :         OffsetNumber ooffnum;
    1125                 :             :         OffsetNumber omaxoffnum;
    1126                 :             : 
    1127                 :             :         /* Scan each tuple in old page */
    1128                 :         991 :         omaxoffnum = PageGetMaxOffsetNumber(opage);
    1129                 :         991 :         for (ooffnum = FirstOffsetNumber;
    1130         [ +  + ]:      199004 :              ooffnum <= omaxoffnum;
    1131                 :      198013 :              ooffnum = OffsetNumberNext(ooffnum))
    1132                 :             :         {
    1133                 :             :             IndexTuple  itup;
    1134                 :             :             Size        itemsz;
    1135                 :             :             Bucket      bucket;
    1136                 :      198013 :             bool        found = false;
    1137                 :             : 
    1138                 :             :             /* skip dead tuples */
    1139         [ -  + ]:      198013 :             if (ItemIdIsDead(PageGetItemId(opage, ooffnum)))
    1140                 :           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                 :             :              */
    1149                 :      198013 :             itup = (IndexTuple) PageGetItem(opage,
    1150                 :      198013 :                                             PageGetItemId(opage, ooffnum));
    1151                 :             : 
    1152         [ +  + ]:      198013 :             if (htab)
    1153                 :         318 :                 (void) hash_search(htab, &itup->t_tid, HASH_FIND, &found);
    1154                 :             : 
    1155         [ -  + ]:      198013 :             if (found)
    1156                 :           0 :                 continue;
    1157                 :             : 
    1158                 :      198013 :             bucket = _hash_hashkey2bucket(_hash_get_indextuple_hashkey(itup),
    1159                 :             :                                           maxbucket, highmask, lowmask);
    1160                 :             : 
    1161         [ +  + ]:      198013 :             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                 :             :                  */
    1168                 :       80503 :                 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                 :       80503 :                 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                 :             :                  */
    1181                 :       80503 :                 itemsz = IndexTupleSize(new_itup);
    1182                 :       80503 :                 itemsz = MAXALIGN(itemsz);
    1183                 :             : 
    1184         [ +  + ]:       80503 :                 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);
    1193                 :          52 :                     MarkBufferDirty(nbuf);
    1194                 :             :                     /* log the split operation before releasing the lock */
    1195                 :          52 :                     log_split_page(rel, nbuf);
    1196                 :             : 
    1197                 :          52 :                     END_CRIT_SECTION();
    1198                 :             : 
    1199                 :             :                     /* drop lock, but keep pin */
    1200                 :          52 :                     LockBuffer(nbuf, BUFFER_LOCK_UNLOCK);
    1201                 :             : 
    1202                 :             :                     /* be tidy */
    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 */
    1209                 :          52 :                     nbuf = _hash_addovflpage(rel, metabuf, nbuf, (nbuf == bucket_nbuf));
    1210                 :          52 :                     npage = BufferGetPage(nbuf);
    1211                 :          52 :                     nopaque = HashPageGetOpaque(npage);
    1212                 :             :                 }
    1213                 :             : 
    1214                 :       80503 :                 itups[nitups++] = new_itup;
    1215                 :       80503 :                 all_tups_size += itemsz;
    1216                 :             :             }
    1217                 :             :             else
    1218                 :             :             {
    1219                 :             :                 /*
    1220                 :             :                  * the tuple stays on this page, so nothing to do.
    1221                 :             :                  */
    1222                 :             :                 Assert(bucket == obucket);
    1223                 :             :             }
    1224                 :             :         }
    1225                 :             : 
    1226                 :         991 :         oblkno = oopaque->hasho_nextblkno;
    1227                 :             : 
    1228                 :             :         /* retain the pin on the old primary bucket */
    1229         [ +  + ]:         991 :         if (obuf == bucket_obuf)
    1230                 :         766 :             LockBuffer(obuf, BUFFER_LOCK_UNLOCK);
    1231                 :             :         else
    1232                 :         225 :             _hash_relbuf(rel, obuf);
    1233                 :             : 
    1234                 :             :         /* Exit loop if no more overflow pages in old bucket */
    1235         [ +  + ]:         991 :         if (!BlockNumberIsValid(oblkno))
    1236                 :             :         {
    1237                 :             :             /*
    1238                 :             :              * Change the shared buffer state in critical section, otherwise
    1239                 :             :              * any error could make it unrecoverable.
    1240                 :             :              */
    1241                 :         766 :             START_CRIT_SECTION();
    1242                 :             : 
    1243                 :         766 :             _hash_pgaddmultitup(rel, nbuf, itups, itup_offsets, nitups);
    1244                 :         766 :             MarkBufferDirty(nbuf);
    1245                 :             :             /* log the split operation before releasing the lock */
    1246                 :         766 :             log_split_page(rel, nbuf);
    1247                 :             : 
    1248                 :         766 :             END_CRIT_SECTION();
    1249                 :             : 
    1250         [ +  + ]:         766 :             if (nbuf == bucket_nbuf)
    1251                 :         762 :                 LockBuffer(nbuf, BUFFER_LOCK_UNLOCK);
    1252                 :             :             else
    1253                 :           4 :                 _hash_relbuf(rel, nbuf);
    1254                 :             : 
    1255                 :             :             /* be tidy */
    1256         [ +  + ]:       60105 :             for (i = 0; i < nitups; i++)
    1257                 :       59339 :                 pfree(itups[i]);
    1258                 :         766 :             break;
    1259                 :             :         }
    1260                 :             : 
    1261                 :             :         /* Else, advance to next old page */
    1262                 :         225 :         obuf = _hash_getbuf(rel, oblkno, HASH_READ, LH_OVERFLOW_PAGE);
    1263                 :         225 :         opage = BufferGetPage(obuf);
    1264                 :         225 :         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                 :             :      */
    1275                 :         766 :     LockBuffer(bucket_obuf, BUFFER_LOCK_EXCLUSIVE);
    1276                 :         766 :     opage = BufferGetPage(bucket_obuf);
    1277                 :         766 :     oopaque = HashPageGetOpaque(opage);
    1278                 :             : 
    1279                 :         766 :     LockBuffer(bucket_nbuf, BUFFER_LOCK_EXCLUSIVE);
    1280                 :         766 :     npage = BufferGetPage(bucket_nbuf);
    1281                 :         766 :     nopaque = HashPageGetOpaque(npage);
    1282                 :             : 
    1283                 :         766 :     START_CRIT_SECTION();
    1284                 :             : 
    1285                 :         766 :     oopaque->hasho_flag &= ~LH_BUCKET_BEING_SPLIT;
    1286                 :         766 :     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                 :         766 :     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                 :         766 :     MarkBufferDirty(bucket_obuf);
    1301                 :         766 :     MarkBufferDirty(bucket_nbuf);
    1302                 :             : 
    1303   [ +  -  -  +  :         766 :     if (RelationNeedsWAL(rel))
             -  -  -  - ]
    1304                 :         766 :     {
    1305                 :             :         xl_hash_split_complete xlrec;
    1306                 :             : 
    1307                 :         766 :         xlrec.old_bucket_flag = oopaque->hasho_flag;
    1308                 :         766 :         xlrec.new_bucket_flag = nopaque->hasho_flag;
    1309                 :             : 
    1310                 :         766 :         XLogBeginInsert();
    1311                 :             : 
    1312                 :         766 :         XLogRegisterData(&xlrec, SizeOfHashSplitComplete);
    1313                 :             : 
    1314                 :         766 :         XLogRegisterBuffer(0, bucket_obuf, REGBUF_STANDARD);
    1315                 :         766 :         XLogRegisterBuffer(1, bucket_nbuf, REGBUF_STANDARD);
    1316                 :             : 
    1317                 :         766 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SPLIT_COMPLETE);
    1318                 :             :     }
    1319                 :             :     else
    1320                 :           0 :         recptr = XLogGetFakeLSN(rel);
    1321                 :             : 
    1322                 :         766 :     PageSetLSN(BufferGetPage(bucket_obuf), recptr);
    1323                 :         766 :     PageSetLSN(BufferGetPage(bucket_nbuf), recptr);
    1324                 :             : 
    1325                 :         766 :     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                 :             :      */
    1335         [ +  - ]:         766 :     if (IsBufferCleanupOK(bucket_obuf))
    1336                 :             :     {
    1337                 :         766 :         LockBuffer(bucket_nbuf, BUFFER_LOCK_UNLOCK);
    1338                 :         766 :         hashbucketcleanup(rel, obucket, bucket_obuf,
    1339                 :             :                           BufferGetBlockNumber(bucket_obuf), NULL,
    1340                 :             :                           maxbucket, highmask, lowmask, NULL, NULL, true,
    1341                 :             :                           NULL, NULL);
    1342                 :             :     }
    1343                 :             :     else
    1344                 :             :     {
    1345                 :           0 :         LockBuffer(bucket_nbuf, BUFFER_LOCK_UNLOCK);
    1346                 :           0 :         LockBuffer(bucket_obuf, BUFFER_LOCK_UNLOCK);
    1347                 :             :     }
    1348                 :         766 : }
    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 (;;)
    1394                 :           0 :     {
    1395                 :             :         OffsetNumber noffnum;
    1396                 :             :         OffsetNumber nmaxoffnum;
    1397                 :             : 
    1398                 :           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);
    1406                 :           1 :         npageopaque = HashPageGetOpaque(npage);
    1407                 :             : 
    1408                 :             :         /* Scan each tuple in new page */
    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                 :             :             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)
    1432                 :           1 :             LockBuffer(nbuf, BUFFER_LOCK_UNLOCK);
    1433                 :             :         else
    1434                 :           0 :             _hash_relbuf(rel, nbuf);
    1435                 :             : 
    1436                 :             :         /* Exit loop if no more overflow pages in new bucket */
    1437         [ +  - ]:           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                 :             :     {
    1449                 :           0 :         _hash_dropbuf(rel, bucket_nbuf);
    1450                 :           0 :         hash_destroy(tidhtab);
    1451                 :           0 :         return;
    1452                 :             :     }
    1453         [ -  + ]:           1 :     if (!ConditionalLockBufferForCleanup(bucket_nbuf))
    1454                 :             :     {
    1455                 :           0 :         LockBuffer(obuf, BUFFER_LOCK_UNLOCK);
    1456                 :           0 :         _hash_dropbuf(rel, bucket_nbuf);
    1457                 :           0 :         hash_destroy(tidhtab);
    1458                 :           0 :         return;
    1459                 :             :     }
    1460                 :             : 
    1461                 :           1 :     npage = BufferGetPage(bucket_nbuf);
    1462                 :           1 :     npageopaque = HashPageGetOpaque(npage);
    1463                 :           1 :     nbucket = npageopaque->hasho_bucket;
    1464                 :             : 
    1465                 :           1 :     INJECTION_POINT("hash-finish-incomplete-split", NULL);
    1466                 :             : 
    1467                 :           1 :     _hash_splitbucket(rel, metabuf, obucket,
    1468                 :             :                       nbucket, obuf, bucket_nbuf, tidhtab,
    1469                 :             :                       maxbucket, highmask, lowmask);
    1470                 :             : 
    1471                 :           1 :     _hash_dropbuf(rel, bucket_nbuf);
    1472                 :           1 :     hash_destroy(tidhtab);
    1473                 :             : }
    1474                 :             : 
    1475                 :             : /*
    1476                 :             :  *  log_split_page() -- Log the split operation
    1477                 :             :  *
    1478                 :             :  *  We log the split operation when the new page in new bucket gets full,
    1479                 :             :  *  so we log the entire page.
    1480                 :             :  *
    1481                 :             :  *  'buf' must be locked by the caller which is also responsible for unlocking
    1482                 :             :  *  it.
    1483                 :             :  */
    1484                 :             : static void
    1485                 :         818 : log_split_page(Relation rel, Buffer buf)
    1486                 :             : {
    1487                 :             :     XLogRecPtr  recptr;
    1488                 :             : 
    1489   [ +  -  -  +  :         818 :     if (RelationNeedsWAL(rel))
             -  -  -  - ]
    1490                 :             :     {
    1491                 :         818 :         XLogBeginInsert();
    1492                 :             : 
    1493                 :         818 :         XLogRegisterBuffer(0, buf, REGBUF_FORCE_IMAGE | REGBUF_STANDARD);
    1494                 :             : 
    1495                 :         818 :         recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SPLIT_PAGE);
    1496                 :             :     }
    1497                 :             :     else
    1498                 :           0 :         recptr = XLogGetFakeLSN(rel);
    1499                 :             : 
    1500                 :         818 :     PageSetLSN(BufferGetPage(buf), recptr);
    1501                 :         818 : }
    1502                 :             : 
    1503                 :             : /*
    1504                 :             :  *  _hash_getcachedmetap() -- Returns cached metapage data.
    1505                 :             :  *
    1506                 :             :  *  If metabuf is not InvalidBuffer, caller must hold a pin, but no lock, on
    1507                 :             :  *  the metapage.  If not set, we'll set it before returning if we have to
    1508                 :             :  *  refresh the cache, and return with a pin but no lock on it; caller is
    1509                 :             :  *  responsible for releasing the pin.
    1510                 :             :  *
    1511                 :             :  *  We refresh the cache if it's not initialized yet or force_refresh is true.
    1512                 :             :  */
    1513                 :             : HashMetaPage
    1514                 :      486982 : _hash_getcachedmetap(Relation rel, Buffer *metabuf, bool force_refresh)
    1515                 :             : {
    1516                 :             :     Page        page;
    1517                 :             : 
    1518                 :             :     Assert(metabuf);
    1519   [ +  +  +  + ]:      486982 :     if (force_refresh || rel->rd_amcache == NULL)
    1520                 :             :     {
    1521                 :         719 :         char       *cache = NULL;
    1522                 :             : 
    1523                 :             :         /*
    1524                 :             :          * It's important that we don't set rd_amcache to an invalid value.
    1525                 :             :          * Either MemoryContextAlloc or _hash_getbuf could fail, so don't
    1526                 :             :          * install a pointer to the newly-allocated storage in the actual
    1527                 :             :          * relcache entry until both have succeeded.
    1528                 :             :          */
    1529         [ +  + ]:         719 :         if (rel->rd_amcache == NULL)
    1530                 :         331 :             cache = MemoryContextAlloc(rel->rd_indexcxt,
    1531                 :             :                                        sizeof(HashMetaPageData));
    1532                 :             : 
    1533                 :             :         /* Read the metapage. */
    1534         [ +  + ]:         719 :         if (BufferIsValid(*metabuf))
    1535                 :           1 :             LockBuffer(*metabuf, BUFFER_LOCK_SHARE);
    1536                 :             :         else
    1537                 :         718 :             *metabuf = _hash_getbuf(rel, HASH_METAPAGE, HASH_READ,
    1538                 :             :                                     LH_META_PAGE);
    1539                 :         719 :         page = BufferGetPage(*metabuf);
    1540                 :             : 
    1541                 :             :         /* Populate the cache. */
    1542         [ +  + ]:         719 :         if (rel->rd_amcache == NULL)
    1543                 :         331 :             rel->rd_amcache = cache;
    1544                 :         719 :         memcpy(rel->rd_amcache, HashPageGetMeta(page),
    1545                 :             :                sizeof(HashMetaPageData));
    1546                 :             : 
    1547                 :             :         /* Release metapage lock, but keep the pin. */
    1548                 :         719 :         LockBuffer(*metabuf, BUFFER_LOCK_UNLOCK);
    1549                 :             :     }
    1550                 :             : 
    1551                 :      486982 :     return (HashMetaPage) rel->rd_amcache;
    1552                 :             : }
    1553                 :             : 
    1554                 :             : /*
    1555                 :             :  *  _hash_getbucketbuf_from_hashkey() -- Get the bucket's buffer for the given
    1556                 :             :  *                                       hashkey.
    1557                 :             :  *
    1558                 :             :  *  Bucket pages do not move or get removed once they are allocated. This give
    1559                 :             :  *  us an opportunity to use the previously saved metapage contents to reach
    1560                 :             :  *  the target bucket buffer, instead of reading from the metapage every time.
    1561                 :             :  *  This saves one buffer access every time we want to reach the target bucket
    1562                 :             :  *  buffer, which is very helpful savings in bufmgr traffic and contention.
    1563                 :             :  *
    1564                 :             :  *  The access type parameter (HASH_READ or HASH_WRITE) indicates whether the
    1565                 :             :  *  bucket buffer has to be locked for reading or writing.
    1566                 :             :  *
    1567                 :             :  *  The out parameter cachedmetap is set with metapage contents used for
    1568                 :             :  *  hashkey to bucket buffer mapping. Some callers need this info to reach the
    1569                 :             :  *  old bucket in case of bucket split, see _hash_doinsert().
    1570                 :             :  */
    1571                 :             : Buffer
    1572                 :      486556 : _hash_getbucketbuf_from_hashkey(Relation rel, uint32 hashkey, int access,
    1573                 :             :                                 HashMetaPage *cachedmetap)
    1574                 :             : {
    1575                 :             :     HashMetaPage metap;
    1576                 :             :     Buffer      buf;
    1577                 :      486556 :     Buffer      metabuf = InvalidBuffer;
    1578                 :             :     Page        page;
    1579                 :             :     Bucket      bucket;
    1580                 :             :     BlockNumber blkno;
    1581                 :             :     HashPageOpaque opaque;
    1582                 :             : 
    1583                 :             :     /* We read from target bucket buffer, hence locking is must. */
    1584                 :             :     Assert(access == HASH_READ || access == HASH_WRITE);
    1585                 :             : 
    1586                 :      486556 :     metap = _hash_getcachedmetap(rel, &metabuf, false);
    1587                 :             :     Assert(metap != NULL);
    1588                 :             : 
    1589                 :             :     /*
    1590                 :             :      * Loop until we get a lock on the correct target bucket.
    1591                 :             :      */
    1592                 :             :     for (;;)
    1593                 :             :     {
    1594                 :             :         /*
    1595                 :             :          * Compute the target bucket number, and convert to block number.
    1596                 :             :          */
    1597                 :      486943 :         bucket = _hash_hashkey2bucket(hashkey,
    1598                 :             :                                       metap->hashm_maxbucket,
    1599                 :             :                                       metap->hashm_highmask,
    1600                 :             :                                       metap->hashm_lowmask);
    1601                 :             : 
    1602         [ +  + ]:      486943 :         blkno = BUCKET_TO_BLKNO(metap, bucket);
    1603                 :             : 
    1604                 :             :         /* Fetch the primary bucket page for the bucket */
    1605                 :      486943 :         buf = _hash_getbuf(rel, blkno, access, LH_BUCKET_PAGE);
    1606                 :      486943 :         page = BufferGetPage(buf);
    1607                 :      486943 :         opaque = HashPageGetOpaque(page);
    1608                 :             :         Assert(opaque->hasho_bucket == bucket);
    1609                 :             :         Assert(opaque->hasho_prevblkno != InvalidBlockNumber);
    1610                 :             : 
    1611                 :             :         /*
    1612                 :             :          * If this bucket hasn't been split, we're done.
    1613                 :             :          */
    1614         [ +  + ]:      486943 :         if (opaque->hasho_prevblkno <= metap->hashm_maxbucket)
    1615                 :      486556 :             break;
    1616                 :             : 
    1617                 :             :         /* Drop lock on this buffer, update cached metapage, and retry. */
    1618                 :         387 :         _hash_relbuf(rel, buf);
    1619                 :         387 :         metap = _hash_getcachedmetap(rel, &metabuf, true);
    1620                 :             :         Assert(metap != NULL);
    1621                 :             :     }
    1622                 :             : 
    1623         [ +  + ]:      486556 :     if (BufferIsValid(metabuf))
    1624                 :         702 :         _hash_dropbuf(rel, metabuf);
    1625                 :             : 
    1626         [ +  + ]:      486556 :     if (cachedmetap)
    1627                 :      486211 :         *cachedmetap = metap;
    1628                 :             : 
    1629                 :      486556 :     return buf;
    1630                 :             : }
        

Generated by: LCOV version 2.0-1