LCOV - differential code coverage report
Current view: top level - src/backend/storage/ipc - shmem.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: 806555e3000d0b0e0c536c1dc65548128d457d86 vs 1d325ad99cb2dec0e8b45ba36909ee0a497d2a57 Lines: 88.2 % 187 165 22 6 159 10
Current Date: 2025-12-17 08:58:58 +0900 Functions: 100.0 % 16 16 3 13
Baseline: lcov-20251217-005640-baseline Branches: 44.1 % 102 45 2 55 2 43
Baseline Date: 2025-12-16 12:57:12 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 3 3 3
(7,30] days: 100.0 % 2 2 2
(30,360] days: 91.8 % 49 45 4 1 44
(360..) days: 86.5 % 133 115 18 115
Function coverage date bins:
(30,360] days: 100.0 % 3 3 1 2
(360..) days: 100.0 % 13 13 2 11
Branch coverage date bins:
(7,30] days: 50.0 % 4 2 2 2
(30,360] days: 52.8 % 36 19 17 19
(360..) days: 38.7 % 62 24 38 24

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * shmem.c
                                  4                 :                :  *    create shared memory and initialize shared memory data structures.
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *    src/backend/storage/ipc/shmem.c
                                 12                 :                :  *
                                 13                 :                :  *-------------------------------------------------------------------------
                                 14                 :                :  */
                                 15                 :                : /*
                                 16                 :                :  * POSTGRES processes share one or more regions of shared memory.
                                 17                 :                :  * The shared memory is created by a postmaster and is inherited
                                 18                 :                :  * by each backend via fork() (or, in some ports, via other OS-specific
                                 19                 :                :  * methods).  The routines in this file are used for allocating and
                                 20                 :                :  * binding to shared memory data structures.
                                 21                 :                :  *
                                 22                 :                :  * NOTES:
                                 23                 :                :  *      (a) There are three kinds of shared memory data structures
                                 24                 :                :  *  available to POSTGRES: fixed-size structures, queues and hash
                                 25                 :                :  *  tables.  Fixed-size structures contain things like global variables
                                 26                 :                :  *  for a module and should never be allocated after the shared memory
                                 27                 :                :  *  initialization phase.  Hash tables have a fixed maximum size, but
                                 28                 :                :  *  their actual size can vary dynamically.  When entries are added
                                 29                 :                :  *  to the table, more space is allocated.  Queues link data structures
                                 30                 :                :  *  that have been allocated either within fixed-size structures or as hash
                                 31                 :                :  *  buckets.  Each shared data structure has a string name to identify
                                 32                 :                :  *  it (assigned in the module that declares it).
                                 33                 :                :  *
                                 34                 :                :  *      (b) During initialization, each module looks for its
                                 35                 :                :  *  shared data structures in a hash table called the "Shmem Index".
                                 36                 :                :  *  If the data structure is not present, the caller can allocate
                                 37                 :                :  *  a new one and initialize it.  If the data structure is present,
                                 38                 :                :  *  the caller "attaches" to the structure by initializing a pointer
                                 39                 :                :  *  in the local address space.
                                 40                 :                :  *      The shmem index has two purposes: first, it gives us
                                 41                 :                :  *  a simple model of how the world looks when a backend process
                                 42                 :                :  *  initializes.  If something is present in the shmem index,
                                 43                 :                :  *  it is initialized.  If it is not, it is uninitialized.  Second,
                                 44                 :                :  *  the shmem index allows us to allocate shared memory on demand
                                 45                 :                :  *  instead of trying to preallocate structures and hard-wire the
                                 46                 :                :  *  sizes and locations in header files.  If you are using a lot
                                 47                 :                :  *  of shared memory in a lot of different places (and changing
                                 48                 :                :  *  things during development), this is important.
                                 49                 :                :  *
                                 50                 :                :  *      (c) In standard Unix-ish environments, individual backends do not
                                 51                 :                :  *  need to re-establish their local pointers into shared memory, because
                                 52                 :                :  *  they inherit correct values of those variables via fork() from the
                                 53                 :                :  *  postmaster.  However, this does not work in the EXEC_BACKEND case.
                                 54                 :                :  *  In ports using EXEC_BACKEND, new backends have to set up their local
                                 55                 :                :  *  pointers using the method described in (b) above.
                                 56                 :                :  *
                                 57                 :                :  *      (d) memory allocation model: shared memory can never be
                                 58                 :                :  *  freed, once allocated.   Each hash table has its own free list,
                                 59                 :                :  *  so hash buckets can be reused when an item is deleted.  However,
                                 60                 :                :  *  if one hash table grows very large and then shrinks, its space
                                 61                 :                :  *  cannot be redistributed to other tables.  We could build a simple
                                 62                 :                :  *  hash bucket garbage collector if need be.  Right now, it seems
                                 63                 :                :  *  unnecessary.
                                 64                 :                :  */
                                 65                 :                : 
                                 66                 :                : #include "postgres.h"
                                 67                 :                : 
                                 68                 :                : #include "common/int.h"
                                 69                 :                : #include "fmgr.h"
                                 70                 :                : #include "funcapi.h"
                                 71                 :                : #include "miscadmin.h"
                                 72                 :                : #include "port/pg_numa.h"
                                 73                 :                : #include "storage/lwlock.h"
                                 74                 :                : #include "storage/pg_shmem.h"
                                 75                 :                : #include "storage/shmem.h"
                                 76                 :                : #include "storage/spin.h"
                                 77                 :                : #include "utils/builtins.h"
                                 78                 :                : 
                                 79                 :                : static void *ShmemAllocRaw(Size size, Size *allocated_size);
                                 80                 :                : static void *ShmemAllocUnlocked(Size size);
                                 81                 :                : 
                                 82                 :                : /* shared memory global variables */
                                 83                 :                : 
                                 84                 :                : static PGShmemHeader *ShmemSegHdr;  /* shared mem segment header */
                                 85                 :                : 
                                 86                 :                : static void *ShmemBase;         /* start address of shared memory */
                                 87                 :                : 
                                 88                 :                : static void *ShmemEnd;          /* end+1 address of shared memory */
                                 89                 :                : 
                                 90                 :                : slock_t    *ShmemLock;          /* spinlock for shared memory and LWLock
                                 91                 :                :                                  * allocation */
                                 92                 :                : 
                                 93                 :                : static HTAB *ShmemIndex = NULL; /* primary index hashtable for shmem */
                                 94                 :                : 
                                 95                 :                : /* To get reliable results for NUMA inquiry we need to "touch pages" once */
                                 96                 :                : static bool firstNumaTouch = true;
                                 97                 :                : 
                                 98                 :                : Datum       pg_numa_available(PG_FUNCTION_ARGS);
                                 99                 :                : 
                                100                 :                : /*
                                101                 :                :  *  InitShmemAccess() --- set up basic pointers to shared memory.
                                102                 :                :  */
                                103                 :                : void
  386 peter@eisentraut.org      104                 :CBC        1069 : InitShmemAccess(PGShmemHeader *seghdr)
                                105                 :                : {
                                106                 :           1069 :     ShmemSegHdr = seghdr;
                                107                 :           1069 :     ShmemBase = seghdr;
                                108                 :           1069 :     ShmemEnd = (char *) ShmemBase + seghdr->totalsize;
 7287 tgl@sss.pgh.pa.us         109                 :           1069 : }
                                110                 :                : 
                                111                 :                : /*
                                112                 :                :  *  InitShmemAllocation() --- set up shared-memory space allocation.
                                113                 :                :  *
                                114                 :                :  * This should be called only in the postmaster or a standalone backend.
                                115                 :                :  */
                                116                 :                : void
                                117                 :           1069 : InitShmemAllocation(void)
                                118                 :                : {
                                119                 :           1069 :     PGShmemHeader *shmhdr = ShmemSegHdr;
                                120                 :                :     char       *aligned;
                                121                 :                : 
                                122         [ -  + ]:           1069 :     Assert(shmhdr != NULL);
                                123                 :                : 
                                124                 :                :     /*
                                125                 :                :      * Initialize the spinlock used by ShmemAlloc.  We must use
                                126                 :                :      * ShmemAllocUnlocked, since obviously ShmemAlloc can't be called yet.
                                127                 :                :      */
 3292                           128                 :           1069 :     ShmemLock = (slock_t *) ShmemAllocUnlocked(sizeof(slock_t));
                                129                 :                : 
                                130                 :           1069 :     SpinLockInit(ShmemLock);
                                131                 :                : 
                                132                 :                :     /*
                                133                 :                :      * Allocations after this point should go through ShmemAlloc, which
                                134                 :                :      * expects to allocate everything on cache line boundaries.  Make sure the
                                135                 :                :      * first allocation begins on a cache line boundary.
                                136                 :                :      */
 3527 rhaas@postgresql.org      137                 :           1069 :     aligned = (char *)
                                138                 :           1069 :         (CACHELINEALIGN((((char *) shmhdr) + shmhdr->freeoffset)));
                                139                 :           1069 :     shmhdr->freeoffset = aligned - (char *) shmhdr;
                                140                 :                : 
                                141                 :                :     /* ShmemIndex can't be set up yet (need LWLocks first) */
 6254 tgl@sss.pgh.pa.us         142                 :           1069 :     shmhdr->index = NULL;
 7287                           143                 :           1069 :     ShmemIndex = (HTAB *) NULL;
10753 scrappy@hub.org           144                 :           1069 : }
                                145                 :                : 
                                146                 :                : /*
                                147                 :                :  * ShmemAlloc -- allocate max-aligned chunk from shared memory
                                148                 :                :  *
                                149                 :                :  * Throws error if request cannot be satisfied.
                                150                 :                :  *
                                151                 :                :  * Assumes ShmemLock and ShmemSegHdr are initialized.
                                152                 :                :  */
                                153                 :                : void *
 7003 tgl@sss.pgh.pa.us         154                 :           3210 : ShmemAlloc(Size size)
                                155                 :                : {
                                156                 :                :     void       *newSpace;
                                157                 :                :     Size        allocated_size;
                                158                 :                : 
 2169 rhaas@postgresql.org      159                 :           3210 :     newSpace = ShmemAllocRaw(size, &allocated_size);
 3394 tgl@sss.pgh.pa.us         160         [ -  + ]:           3210 :     if (!newSpace)
 3394 tgl@sss.pgh.pa.us         161         [ #  # ]:UBC           0 :         ereport(ERROR,
                                162                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                163                 :                :                  errmsg("out of shared memory (%zu bytes requested)",
                                164                 :                :                         size)));
 3394 tgl@sss.pgh.pa.us         165                 :CBC        3210 :     return newSpace;
                                166                 :                : }
                                167                 :                : 
                                168                 :                : /*
                                169                 :                :  * ShmemAllocNoError -- allocate max-aligned chunk from shared memory
                                170                 :                :  *
                                171                 :                :  * As ShmemAlloc, but returns NULL if out of space, rather than erroring.
                                172                 :                :  */
                                173                 :                : void *
                                174                 :         434558 : ShmemAllocNoError(Size size)
                                175                 :                : {
                                176                 :                :     Size        allocated_size;
                                177                 :                : 
 2169 rhaas@postgresql.org      178                 :         434558 :     return ShmemAllocRaw(size, &allocated_size);
                                179                 :                : }
                                180                 :                : 
                                181                 :                : /*
                                182                 :                :  * ShmemAllocRaw -- allocate align chunk and return allocated size
                                183                 :                :  *
                                184                 :                :  * Also sets *allocated_size to the number of bytes allocated, which will
                                185                 :                :  * be equal to the number requested plus any padding we choose to add.
                                186                 :                :  */
                                187                 :                : static void *
                                188                 :         516866 : ShmemAllocRaw(Size size, Size *allocated_size)
                                189                 :                : {
                                190                 :                :     Size        newStart;
                                191                 :                :     Size        newFree;
                                192                 :                :     void       *newSpace;
                                193                 :                : 
                                194                 :                :     /*
                                195                 :                :      * Ensure all space is adequately aligned.  We used to only MAXALIGN this
                                196                 :                :      * space but experience has proved that on modern systems that is not good
                                197                 :                :      * enough.  Many parts of the system are very sensitive to critical data
                                198                 :                :      * structures getting split across cache line boundaries.  To avoid that,
                                199                 :                :      * attempt to align the beginning of the allocation to a cache line
                                200                 :                :      * boundary.  The calling code will still need to be careful about how it
                                201                 :                :      * uses the allocated space - e.g. by padding each element in an array of
                                202                 :                :      * structures out to a power-of-two size - but without this, even that
                                203                 :                :      * won't be sufficient.
                                204                 :                :      */
 3543                           205                 :         516866 :     size = CACHELINEALIGN(size);
 2169                           206                 :         516866 :     *allocated_size = size;
                                207                 :                : 
 3715                           208         [ -  + ]:         516866 :     Assert(ShmemSegHdr != NULL);
                                209                 :                : 
 8845 tgl@sss.pgh.pa.us         210         [ -  + ]:         516866 :     SpinLockAcquire(ShmemLock);
                                211                 :                : 
 3715 rhaas@postgresql.org      212                 :         516866 :     newStart = ShmemSegHdr->freeoffset;
                                213                 :                : 
 8123 tgl@sss.pgh.pa.us         214                 :         516866 :     newFree = newStart + size;
 3715 rhaas@postgresql.org      215         [ +  - ]:         516866 :     if (newFree <= ShmemSegHdr->totalsize)
                                216                 :                :     {
  384 peter@eisentraut.org      217                 :         516866 :         newSpace = (char *) ShmemBase + newStart;
 3715 rhaas@postgresql.org      218                 :         516866 :         ShmemSegHdr->freeoffset = newFree;
                                219                 :                :     }
                                220                 :                :     else
10328 bruce@momjian.us          221                 :UBC           0 :         newSpace = NULL;
                                222                 :                : 
 8845 tgl@sss.pgh.pa.us         223                 :CBC      516866 :     SpinLockRelease(ShmemLock);
                                224                 :                : 
                                225                 :                :     /* note this assert is okay with newSpace == NULL */
 3527 rhaas@postgresql.org      226         [ -  + ]:         516866 :     Assert(newSpace == (void *) CACHELINEALIGN(newSpace));
                                227                 :                : 
 9969 bruce@momjian.us          228                 :         516866 :     return newSpace;
                                229                 :                : }
                                230                 :                : 
                                231                 :                : /*
                                232                 :                :  * ShmemAllocUnlocked -- allocate max-aligned chunk from shared memory
                                233                 :                :  *
                                234                 :                :  * Allocate space without locking ShmemLock.  This should be used for,
                                235                 :                :  * and only for, allocations that must happen before ShmemLock is ready.
                                236                 :                :  *
                                237                 :                :  * We consider maxalign, rather than cachealign, sufficient here.
                                238                 :                :  */
                                239                 :                : static void *
 3292 tgl@sss.pgh.pa.us         240                 :           1069 : ShmemAllocUnlocked(Size size)
                                241                 :                : {
                                242                 :                :     Size        newStart;
                                243                 :                :     Size        newFree;
                                244                 :                :     void       *newSpace;
                                245                 :                : 
                                246                 :                :     /*
                                247                 :                :      * Ensure allocated space is adequately aligned.
                                248                 :                :      */
                                249                 :           1069 :     size = MAXALIGN(size);
                                250                 :                : 
                                251         [ -  + ]:           1069 :     Assert(ShmemSegHdr != NULL);
                                252                 :                : 
                                253                 :           1069 :     newStart = ShmemSegHdr->freeoffset;
                                254                 :                : 
                                255                 :           1069 :     newFree = newStart + size;
                                256         [ -  + ]:           1069 :     if (newFree > ShmemSegHdr->totalsize)
 3292 tgl@sss.pgh.pa.us         257         [ #  # ]:UBC           0 :         ereport(ERROR,
                                258                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                259                 :                :                  errmsg("out of shared memory (%zu bytes requested)",
                                260                 :                :                         size)));
 3292 tgl@sss.pgh.pa.us         261                 :CBC        1069 :     ShmemSegHdr->freeoffset = newFree;
                                262                 :                : 
  384 peter@eisentraut.org      263                 :           1069 :     newSpace = (char *) ShmemBase + newStart;
                                264                 :                : 
 3292 tgl@sss.pgh.pa.us         265         [ -  + ]:           1069 :     Assert(newSpace == (void *) MAXALIGN(newSpace));
                                266                 :                : 
                                267                 :           1069 :     return newSpace;
                                268                 :                : }
                                269                 :                : 
                                270                 :                : /*
                                271                 :                :  * ShmemAddrIsValid -- test if an address refers to shared memory
                                272                 :                :  *
                                273                 :                :  * Returns true if the pointer points within the shared memory segment.
                                274                 :                :  */
                                275                 :                : bool
 5427 heikki.linnakangas@i      276                 :          80767 : ShmemAddrIsValid(const void *addr)
                                277                 :                : {
 6254 tgl@sss.pgh.pa.us         278   [ +  -  +  - ]:          80767 :     return (addr >= ShmemBase) && (addr < ShmemEnd);
                                279                 :                : }
                                280                 :                : 
                                281                 :                : /*
                                282                 :                :  *  InitShmemIndex() --- set up or attach to shmem index table.
                                283                 :                :  */
                                284                 :                : void
 8845                           285                 :           1069 : InitShmemIndex(void)
                                286                 :                : {
                                287                 :                :     HASHCTL     info;
                                288                 :                : 
                                289                 :                :     /*
                                290                 :                :      * Create the shared memory shmem index.
                                291                 :                :      *
                                292                 :                :      * Since ShmemInitHash calls ShmemInitStruct, which expects the ShmemIndex
                                293                 :                :      * hashtable to exist already, we have a bit of a circularity problem in
                                294                 :                :      * initializing the ShmemIndex itself.  The special "ShmemIndex" hash
                                295                 :                :      * table name will tell ShmemInitStruct to fake it.
                                296                 :                :      */
                                297                 :           1069 :     info.keysize = SHMEM_INDEX_KEYSIZE;
 8843                           298                 :           1069 :     info.entrysize = sizeof(ShmemIndexEnt);
                                299                 :                : 
 8845                           300                 :           1069 :     ShmemIndex = ShmemInitHash("ShmemIndex",
                                301                 :                :                                SHMEM_INDEX_SIZE, SHMEM_INDEX_SIZE,
                                302                 :                :                                &info,
                                303                 :                :                                HASH_ELEM | HASH_STRINGS);
                                304                 :           1069 : }
                                305                 :                : 
                                306                 :                : /*
                                307                 :                :  * ShmemInitHash -- Create and initialize, or attach to, a
                                308                 :                :  *      shared memory hash table.
                                309                 :                :  *
                                310                 :                :  * We assume caller is doing some kind of synchronization
                                311                 :                :  * so that two processes don't try to create/initialize the same
                                312                 :                :  * table at once.  (In practice, all creations are done in the postmaster
                                313                 :                :  * process; child processes should always be attaching to existing tables.)
                                314                 :                :  *
                                315                 :                :  * max_size is the estimated maximum number of hashtable entries.  This is
                                316                 :                :  * not a hard limit, but the access efficiency will degrade if it is
                                317                 :                :  * exceeded substantially (since it's used to compute directory size and
                                318                 :                :  * the hash table buckets will get overfull).
                                319                 :                :  *
                                320                 :                :  * init_size is the number of hashtable entries to preallocate.  For a table
                                321                 :                :  * whose maximum size is certain, this should be equal to max_size; that
                                322                 :                :  * ensures that no run-time out-of-shared-memory failures can occur.
                                323                 :                :  *
                                324                 :                :  * *infoP and hash_flags must specify at least the entry sizes and key
                                325                 :                :  * comparison semantics (see hash_create()).  Flag bits and values specific
                                326                 :                :  * to shared-memory hash tables are added here, except that callers may
                                327                 :                :  * choose to specify HASH_PARTITION and/or HASH_FIXED_SIZE.
                                328                 :                :  *
                                329                 :                :  * Note: before Postgres 9.0, this function returned NULL for some failure
                                330                 :                :  * cases.  Now, it always throws error instead, so callers need not check
                                331                 :                :  * for NULL.
                                332                 :                :  */
                                333                 :                : HTAB *
 3101                           334                 :           9628 : ShmemInitHash(const char *name,     /* table string name for shmem index */
                                335                 :                :               int64 init_size,  /* initial table size */
                                336                 :                :               int64 max_size,   /* max size of the table */
                                337                 :                :               HASHCTL *infoP,   /* info about key and bucket size */
                                338                 :                :               int hash_flags)   /* info about infoP */
                                339                 :                : {
                                340                 :                :     bool        found;
                                341                 :                :     void       *location;
                                342                 :                : 
                                343                 :                :     /*
                                344                 :                :      * Hash tables allocated in shared memory have a fixed directory; it can't
                                345                 :                :      * grow or other backends wouldn't be able to find it. So, make sure we
                                346                 :                :      * make it big enough to start with.
                                347                 :                :      *
                                348                 :                :      * The shared memory allocator must be specified too.
                                349                 :                :      */
 9426                           350                 :           9628 :     infoP->dsize = infoP->max_dsize = hash_select_dirsize(max_size);
 3394                           351                 :           9628 :     infoP->alloc = ShmemAllocNoError;
 8023                           352                 :           9628 :     hash_flags |= HASH_SHARED_MEM | HASH_ALLOC | HASH_DIRSIZE;
                                353                 :                : 
                                354                 :                :     /* look it up in the shmem index */
 9795                           355                 :           9628 :     location = ShmemInitStruct(name,
                                356                 :                :                                hash_get_shared_size(infoP, hash_flags),
                                357                 :                :                                &found);
                                358                 :                : 
                                359                 :                :     /*
                                360                 :                :      * if it already exists, attach to it rather than allocate and initialize
                                361                 :                :      * new space
                                362                 :                :      */
10328 bruce@momjian.us          363         [ -  + ]:           9628 :     if (found)
10328 bruce@momjian.us          364                 :UBC           0 :         hash_flags |= HASH_ATTACH;
                                365                 :                : 
                                366                 :                :     /* Pass location of hashtable header to hash_create */
 8843 tgl@sss.pgh.pa.us         367                 :CBC        9628 :     infoP->hctl = (HASHHDR *) location;
                                368                 :                : 
 8839                           369                 :           9628 :     return hash_create(name, init_size, infoP, hash_flags);
                                370                 :                : }
                                371                 :                : 
                                372                 :                : /*
                                373                 :                :  * ShmemInitStruct -- Create/attach to a structure in shared memory.
                                374                 :                :  *
                                375                 :                :  *      This is called during initialization to find or allocate
                                376                 :                :  *      a data structure in shared memory.  If no other process
                                377                 :                :  *      has created the structure, this routine allocates space
                                378                 :                :  *      for it.  If it exists already, a pointer to the existing
                                379                 :                :  *      structure is returned.
                                380                 :                :  *
                                381                 :                :  *  Returns: pointer to the object.  *foundPtr is set true if the object was
                                382                 :                :  *      already in the shmem index (hence, already initialized).
                                383                 :                :  *
                                384                 :                :  *  Note: before Postgres 9.0, this function returned NULL for some failure
                                385                 :                :  *  cases.  Now, it always throws error instead, so callers need not check
                                386                 :                :  *  for NULL.
                                387                 :                :  */
                                388                 :                : void *
                                389                 :          80167 : ShmemInitStruct(const char *name, Size size, bool *foundPtr)
                                390                 :                : {
                                391                 :                :     ShmemIndexEnt *result;
                                392                 :                :     void       *structPtr;
                                393                 :                : 
 7287                           394                 :          80167 :     LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
                                395                 :                : 
10035 bruce@momjian.us          396         [ +  + ]:          80167 :     if (!ShmemIndex)
                                397                 :                :     {
 7287 tgl@sss.pgh.pa.us         398                 :           1069 :         PGShmemHeader *shmemseghdr = ShmemSegHdr;
                                399                 :                : 
                                400                 :                :         /* Must be trying to create/attach to ShmemIndex itself */
 7562 neilc@samurai.com         401         [ -  + ]:           1069 :         Assert(strcmp(name, "ShmemIndex") == 0);
                                402                 :                : 
 8033 bruce@momjian.us          403         [ -  + ]:           1069 :         if (IsUnderPostmaster)
                                404                 :                :         {
                                405                 :                :             /* Must be initializing a (non-standalone) backend */
 6254 tgl@sss.pgh.pa.us         406         [ #  # ]:UBC           0 :             Assert(shmemseghdr->index != NULL);
                                407                 :              0 :             structPtr = shmemseghdr->index;
 3045 peter_e@gmx.net           408                 :              0 :             *foundPtr = true;
                                409                 :                :         }
                                410                 :                :         else
                                411                 :                :         {
                                412                 :                :             /*
                                413                 :                :              * If the shmem index doesn't exist, we are bootstrapping: we must
                                414                 :                :              * be trying to init the shmem index itself.
                                415                 :                :              *
                                416                 :                :              * Notice that the ShmemIndexLock is released before the shmem
                                417                 :                :              * index has been initialized.  This should be OK because no other
                                418                 :                :              * process can be accessing shared memory yet.
                                419                 :                :              */
 6254 tgl@sss.pgh.pa.us         420         [ -  + ]:CBC        1069 :             Assert(shmemseghdr->index == NULL);
 7287                           421                 :           1069 :             structPtr = ShmemAlloc(size);
 6254                           422                 :           1069 :             shmemseghdr->index = structPtr;
 3045 peter_e@gmx.net           423                 :           1069 :             *foundPtr = false;
                                424                 :                :         }
 7088 tgl@sss.pgh.pa.us         425                 :           1069 :         LWLockRelease(ShmemIndexLock);
 7287                           426                 :           1069 :         return structPtr;
                                427                 :                :     }
                                428                 :                : 
                                429                 :                :     /* look it up in the shmem index */
                                430                 :                :     result = (ShmemIndexEnt *)
 7021                           431                 :          79098 :         hash_search(ShmemIndex, name, HASH_ENTER_NULL, foundPtr);
                                432                 :                : 
10328 bruce@momjian.us          433         [ -  + ]:          79098 :     if (!result)
                                434                 :                :     {
 7287 tgl@sss.pgh.pa.us         435                 :UBC           0 :         LWLockRelease(ShmemIndexLock);
 8182                           436         [ #  # ]:              0 :         ereport(ERROR,
                                437                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                438                 :                :                  errmsg("could not create ShmemIndex entry for data structure \"%s\"",
                                439                 :                :                         name)));
                                440                 :                :     }
                                441                 :                : 
 9150 tgl@sss.pgh.pa.us         442         [ -  + ]:CBC       79098 :     if (*foundPtr)
                                443                 :                :     {
                                444                 :                :         /*
                                445                 :                :          * Structure is in the shmem index so someone else has allocated it
                                446                 :                :          * already.  The size better be the same as the size we are trying to
                                447                 :                :          * initialize to, or there is a name conflict (or worse).
                                448                 :                :          */
10328 bruce@momjian.us          449         [ #  # ]:UBC           0 :         if (result->size != size)
                                450                 :                :         {
 7287 tgl@sss.pgh.pa.us         451                 :              0 :             LWLockRelease(ShmemIndexLock);
 5712                           452         [ #  # ]:              0 :             ereport(ERROR,
                                453                 :                :                     (errmsg("ShmemIndex entry size is wrong for data structure"
                                454                 :                :                             " \"%s\": expected %zu, actual %zu",
                                455                 :                :                             name, size, result->size)));
                                456                 :                :         }
 6254                           457                 :              0 :         structPtr = result->location;
                                458                 :                :     }
                                459                 :                :     else
                                460                 :                :     {
                                461                 :                :         Size        allocated_size;
                                462                 :                : 
                                463                 :                :         /* It isn't in the table yet. allocate and initialize it */
 2169 rhaas@postgresql.org      464                 :CBC       79098 :         structPtr = ShmemAllocRaw(size, &allocated_size);
 5712 tgl@sss.pgh.pa.us         465         [ -  + ]:          79098 :         if (structPtr == NULL)
                                466                 :                :         {
                                467                 :                :             /* out of memory; remove the failed ShmemIndex entry */
 7021 tgl@sss.pgh.pa.us         468                 :UBC           0 :             hash_search(ShmemIndex, name, HASH_REMOVE, NULL);
 7287                           469                 :              0 :             LWLockRelease(ShmemIndexLock);
 5712                           470         [ #  # ]:              0 :             ereport(ERROR,
                                471                 :                :                     (errcode(ERRCODE_OUT_OF_MEMORY),
                                472                 :                :                      errmsg("not enough shared memory for data structure"
                                473                 :                :                             " \"%s\" (%zu bytes requested)",
                                474                 :                :                             name, size)));
                                475                 :                :         }
10328 bruce@momjian.us          476                 :CBC       79098 :         result->size = size;
 2169 rhaas@postgresql.org      477                 :          79098 :         result->allocated_size = allocated_size;
 6254 tgl@sss.pgh.pa.us         478                 :          79098 :         result->location = structPtr;
                                479                 :                :     }
                                480                 :                : 
 7287                           481                 :          79098 :     LWLockRelease(ShmemIndexLock);
                                482                 :                : 
 5712                           483         [ -  + ]:          79098 :     Assert(ShmemAddrIsValid(structPtr));
                                484                 :                : 
 3527 rhaas@postgresql.org      485         [ -  + ]:          79098 :     Assert(structPtr == (void *) CACHELINEALIGN(structPtr));
                                486                 :                : 
 9969 bruce@momjian.us          487                 :          79098 :     return structPtr;
                                488                 :                : }
                                489                 :                : 
                                490                 :                : 
                                491                 :                : /*
                                492                 :                :  * Add two Size values, checking for overflow
                                493                 :                :  */
                                494                 :                : Size
 7424 tgl@sss.pgh.pa.us         495                 :         534109 : add_size(Size s1, Size s2)
                                496                 :                : {
                                497                 :                :     Size        result;
                                498                 :                : 
   23 jchampion@postgresql      499         [ -  + ]:GNC      534109 :     if (pg_add_size_overflow(s1, s2, &result))
 7424 tgl@sss.pgh.pa.us         500         [ #  # ]:UBC           0 :         ereport(ERROR,
                                501                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                502                 :                :                  errmsg("requested shared memory size overflows size_t")));
 7424 tgl@sss.pgh.pa.us         503                 :CBC      534109 :     return result;
                                504                 :                : }
                                505                 :                : 
                                506                 :                : /*
                                507                 :                :  * Multiply two Size values, checking for overflow
                                508                 :                :  */
                                509                 :                : Size
                                510                 :         253049 : mul_size(Size s1, Size s2)
                                511                 :                : {
                                512                 :                :     Size        result;
                                513                 :                : 
   23 jchampion@postgresql      514         [ -  + ]:GNC      253049 :     if (pg_mul_size_overflow(s1, s2, &result))
 7424 tgl@sss.pgh.pa.us         515         [ #  # ]:UBC           0 :         ereport(ERROR,
                                516                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                517                 :                :                  errmsg("requested shared memory size overflows size_t")));
 7424 tgl@sss.pgh.pa.us         518                 :CBC      253049 :     return result;
                                519                 :                : }
                                520                 :                : 
                                521                 :                : /* SQL SRF showing allocated shared memory */
                                522                 :                : Datum
 2169 rhaas@postgresql.org      523                 :              3 : pg_get_shmem_allocations(PG_FUNCTION_ARGS)
                                524                 :                : {
                                525                 :                : #define PG_GET_SHMEM_SIZES_COLS 4
                                526                 :              3 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
                                527                 :                :     HASH_SEQ_STATUS hstat;
                                528                 :                :     ShmemIndexEnt *ent;
 2043 tgl@sss.pgh.pa.us         529                 :              3 :     Size        named_allocated = 0;
                                530                 :                :     Datum       values[PG_GET_SHMEM_SIZES_COLS];
                                531                 :                :     bool        nulls[PG_GET_SHMEM_SIZES_COLS];
                                532                 :                : 
 1156 michael@paquier.xyz       533                 :              3 :     InitMaterializedSRF(fcinfo, 0);
                                534                 :                : 
 2169 rhaas@postgresql.org      535                 :              3 :     LWLockAcquire(ShmemIndexLock, LW_SHARED);
                                536                 :                : 
                                537                 :              3 :     hash_seq_init(&hstat, ShmemIndex);
                                538                 :                : 
                                539                 :                :     /* output all allocated entries */
                                540                 :              3 :     memset(nulls, 0, sizeof(nulls));
                                541         [ +  + ]:            227 :     while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
                                542                 :                :     {
                                543                 :            224 :         values[0] = CStringGetTextDatum(ent->key);
                                544                 :            224 :         values[1] = Int64GetDatum((char *) ent->location - (char *) ShmemSegHdr);
                                545                 :            224 :         values[2] = Int64GetDatum(ent->size);
                                546                 :            224 :         values[3] = Int64GetDatum(ent->allocated_size);
                                547                 :            224 :         named_allocated += ent->allocated_size;
                                548                 :                : 
 1381 michael@paquier.xyz       549                 :            224 :         tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
                                550                 :                :                              values, nulls);
                                551                 :                :     }
                                552                 :                : 
                                553                 :                :     /* output shared memory allocated but not counted via the shmem index */
 2169 rhaas@postgresql.org      554                 :              3 :     values[0] = CStringGetTextDatum("<anonymous>");
                                555                 :              3 :     nulls[1] = true;
                                556                 :              3 :     values[2] = Int64GetDatum(ShmemSegHdr->freeoffset - named_allocated);
                                557                 :              3 :     values[3] = values[2];
 1381 michael@paquier.xyz       558                 :              3 :     tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
                                559                 :                : 
                                560                 :                :     /* output as-of-yet unused shared memory */
 2169 rhaas@postgresql.org      561                 :              3 :     nulls[0] = true;
                                562                 :              3 :     values[1] = Int64GetDatum(ShmemSegHdr->freeoffset);
                                563                 :              3 :     nulls[1] = false;
                                564                 :              3 :     values[2] = Int64GetDatum(ShmemSegHdr->totalsize - ShmemSegHdr->freeoffset);
                                565                 :              3 :     values[3] = values[2];
 1381 michael@paquier.xyz       566                 :              3 :     tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
                                567                 :                : 
 2169 rhaas@postgresql.org      568                 :              3 :     LWLockRelease(ShmemIndexLock);
                                569                 :                : 
                                570                 :              3 :     return (Datum) 0;
                                571                 :                : }
                                572                 :                : 
                                573                 :                : /*
                                574                 :                :  * SQL SRF showing NUMA memory nodes for allocated shared memory
                                575                 :                :  *
                                576                 :                :  * Compared to pg_get_shmem_allocations(), this function does not return
                                577                 :                :  * information about shared anonymous allocations and unused shared memory.
                                578                 :                :  */
                                579                 :                : Datum
  254 tomas.vondra@postgre      580                 :              3 : pg_get_shmem_allocations_numa(PG_FUNCTION_ARGS)
                                581                 :                : {
                                582                 :                : #define PG_GET_SHMEM_NUMA_SIZES_COLS 3
                                583                 :              3 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
                                584                 :                :     HASH_SEQ_STATUS hstat;
                                585                 :                :     ShmemIndexEnt *ent;
                                586                 :                :     Datum       values[PG_GET_SHMEM_NUMA_SIZES_COLS];
                                587                 :                :     bool        nulls[PG_GET_SHMEM_NUMA_SIZES_COLS];
                                588                 :                :     Size        os_page_size;
                                589                 :                :     void      **page_ptrs;
                                590                 :                :     int        *pages_status;
                                591                 :                :     uint64      shm_total_page_count,
                                592                 :                :                 shm_ent_page_count,
                                593                 :                :                 max_nodes;
                                594                 :                :     Size       *nodes;
                                595                 :                : 
                                596         [ -  + ]:              3 :     if (pg_numa_init() == -1)
  254 tomas.vondra@postgre      597         [ #  # ]:UBC           0 :         elog(ERROR, "libnuma initialization failed or NUMA is not supported on this platform");
                                598                 :                : 
  254 tomas.vondra@postgre      599                 :CBC           3 :     InitMaterializedSRF(fcinfo, 0);
                                600                 :                : 
                                601                 :              3 :     max_nodes = pg_numa_get_max_node();
    7 michael@paquier.xyz       602                 :GNC           3 :     nodes = palloc_array(Size, max_nodes + 1);
                                603                 :                : 
                                604                 :                :     /*
                                605                 :                :      * Shared memory allocations can vary in size and may not align with OS
                                606                 :                :      * memory page boundaries, while NUMA queries work on pages.
                                607                 :                :      *
                                608                 :                :      * To correctly map each allocation to NUMA nodes, we need to: 1.
                                609                 :                :      * Determine the OS memory page size. 2. Align each allocation's start/end
                                610                 :                :      * addresses to page boundaries. 3. Query NUMA node information for all
                                611                 :                :      * pages spanning the allocation.
                                612                 :                :      */
  252 tomas.vondra@postgre      613                 :CBC           3 :     os_page_size = pg_get_shmem_pagesize();
                                614                 :                : 
                                615                 :                :     /*
                                616                 :                :      * Allocate memory for page pointers and status based on total shared
                                617                 :                :      * memory size. This simplified approach allocates enough space for all
                                618                 :                :      * pages in shared memory rather than calculating the exact requirements
                                619                 :                :      * for each segment.
                                620                 :                :      *
                                621                 :                :      * Add 1, because we don't know how exactly the segments align to OS
                                622                 :                :      * pages, so the allocation might use one more memory page. In practice
                                623                 :                :      * this is not very likely, and moreover we have more entries, each of
                                624                 :                :      * them using only fraction of the total pages.
                                625                 :                :      */
  254                           626                 :              3 :     shm_total_page_count = (ShmemSegHdr->totalsize / os_page_size) + 1;
    7 michael@paquier.xyz       627                 :GNC           3 :     page_ptrs = palloc0_array(void *, shm_total_page_count);
                                628                 :              3 :     pages_status = palloc_array(int, shm_total_page_count);
                                629                 :                : 
  254 tomas.vondra@postgre      630         [ +  - ]:CBC           3 :     if (firstNumaTouch)
                                631         [ -  + ]:              3 :         elog(DEBUG1, "NUMA: page-faulting shared memory segments for proper NUMA readouts");
                                632                 :                : 
                                633                 :              3 :     LWLockAcquire(ShmemIndexLock, LW_SHARED);
                                634                 :                : 
                                635                 :              3 :     hash_seq_init(&hstat, ShmemIndex);
                                636                 :                : 
                                637                 :                :     /* output all allocated entries */
                                638                 :              3 :     memset(nulls, 0, sizeof(nulls));
                                639         [ +  + ]:            227 :     while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
                                640                 :                :     {
                                641                 :                :         int         i;
                                642                 :                :         char       *startptr,
                                643                 :                :                    *endptr;
                                644                 :                :         Size        total_len;
                                645                 :                : 
                                646                 :                :         /*
                                647                 :                :          * Calculate the range of OS pages used by this segment. The segment
                                648                 :                :          * may start / end half-way through a page, we want to count these
                                649                 :                :          * pages too. So we align the start/end pointers down/up, and then
                                650                 :                :          * calculate the number of pages from that.
                                651                 :                :          */
                                652                 :            224 :         startptr = (char *) TYPEALIGN_DOWN(os_page_size, ent->location);
                                653                 :            224 :         endptr = (char *) TYPEALIGN(os_page_size,
                                654                 :                :                                     (char *) ent->location + ent->allocated_size);
                                655                 :            224 :         total_len = (endptr - startptr);
                                656                 :                : 
                                657                 :            224 :         shm_ent_page_count = total_len / os_page_size;
                                658                 :                : 
                                659                 :                :         /*
                                660                 :                :          * If we ever get 0xff (-1) back from kernel inquiry, then we probably
                                661                 :                :          * have a bug in mapping buffers to OS pages.
                                662                 :                :          */
                                663                 :            224 :         memset(pages_status, 0xff, sizeof(int) * shm_ent_page_count);
                                664                 :                : 
                                665                 :                :         /*
                                666                 :                :          * Setup page_ptrs[] with pointers to all OS pages for this segment,
                                667                 :                :          * and get the NUMA status using pg_numa_query_pages.
                                668                 :                :          *
                                669                 :                :          * In order to get reliable results we also need to touch memory
                                670                 :                :          * pages, so that inquiry about NUMA memory node doesn't return -2
                                671                 :                :          * (ENOENT, which indicates unmapped/unallocated pages).
                                672                 :                :          */
                                673         [ +  + ]:          73690 :         for (i = 0; i < shm_ent_page_count; i++)
                                674                 :                :         {
                                675                 :          73466 :             page_ptrs[i] = startptr + (i * os_page_size);
                                676                 :                : 
                                677         [ +  - ]:          73466 :             if (firstNumaTouch)
  169                           678                 :          73466 :                 pg_numa_touch_mem_if_required(page_ptrs[i]);
                                679                 :                : 
  254                           680         [ -  + ]:          73466 :             CHECK_FOR_INTERRUPTS();
                                681                 :                :         }
                                682                 :                : 
                                683         [ -  + ]:            224 :         if (pg_numa_query_pages(0, shm_ent_page_count, page_ptrs, pages_status) == -1)
  254 tomas.vondra@postgre      684         [ #  # ]:UBC           0 :             elog(ERROR, "failed NUMA pages inquiry status: %m");
                                685                 :                : 
                                686                 :                :         /* Count number of NUMA nodes used for this shared memory entry */
  254 tomas.vondra@postgre      687                 :CBC         224 :         memset(nodes, 0, sizeof(Size) * (max_nodes + 1));
                                688                 :                : 
                                689         [ +  + ]:          73690 :         for (i = 0; i < shm_ent_page_count; i++)
                                690                 :                :         {
                                691                 :          73466 :             int         s = pages_status[i];
                                692                 :                : 
                                693                 :                :             /* Ensure we are adding only valid index to the array */
                                694   [ +  -  -  + ]:          73466 :             if (s < 0 || s > max_nodes)
                                695                 :                :             {
  254 tomas.vondra@postgre      696         [ #  # ]:UBC           0 :                 elog(ERROR, "invalid NUMA node id outside of allowed range "
                                697                 :                :                      "[0, " UINT64_FORMAT "]: %d", max_nodes, s);
                                698                 :                :             }
                                699                 :                : 
  254 tomas.vondra@postgre      700                 :CBC       73466 :             nodes[s]++;
                                701                 :                :         }
                                702                 :                : 
                                703                 :                :         /*
                                704                 :                :          * Add one entry for each NUMA node, including those without allocated
                                705                 :                :          * memory for this segment.
                                706                 :                :          */
                                707         [ +  + ]:            448 :         for (i = 0; i <= max_nodes; i++)
                                708                 :                :         {
                                709                 :            224 :             values[0] = CStringGetTextDatum(ent->key);
  131 peter@eisentraut.org      710                 :GNC         224 :             values[1] = Int32GetDatum(i);
  254 tomas.vondra@postgre      711                 :CBC         224 :             values[2] = Int64GetDatum(nodes[i] * os_page_size);
                                712                 :                : 
                                713                 :            224 :             tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
                                714                 :                :                                  values, nulls);
                                715                 :                :         }
                                716                 :                :     }
                                717                 :                : 
                                718                 :              3 :     LWLockRelease(ShmemIndexLock);
                                719                 :              3 :     firstNumaTouch = false;
                                720                 :                : 
                                721                 :              3 :     return (Datum) 0;
                                722                 :                : }
                                723                 :                : 
                                724                 :                : /*
                                725                 :                :  * Determine the memory page size used for the shared memory segment.
                                726                 :                :  *
                                727                 :                :  * If the shared segment was allocated using huge pages, returns the size of
                                728                 :                :  * a huge page. Otherwise returns the size of regular memory page.
                                729                 :                :  *
                                730                 :                :  * This should be used only after the server is started.
                                731                 :                :  */
                                732                 :                : Size
  252                           733                 :              7 : pg_get_shmem_pagesize(void)
                                734                 :                : {
                                735                 :                :     Size        os_page_size;
                                736                 :                : #ifdef WIN32
                                737                 :                :     SYSTEM_INFO sysinfo;
                                738                 :                : 
                                739                 :                :     GetSystemInfo(&sysinfo);
                                740                 :                :     os_page_size = sysinfo.dwPageSize;
                                741                 :                : #else
                                742                 :              7 :     os_page_size = sysconf(_SC_PAGESIZE);
                                743                 :                : #endif
                                744                 :                : 
                                745         [ -  + ]:              7 :     Assert(IsUnderPostmaster);
                                746         [ -  + ]:              7 :     Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
                                747                 :                : 
                                748         [ -  + ]:              7 :     if (huge_pages_status == HUGE_PAGES_ON)
  252 tomas.vondra@postgre      749                 :UBC           0 :         GetHugePageSize(&os_page_size, NULL);
                                750                 :                : 
  252 tomas.vondra@postgre      751                 :CBC           7 :     return os_page_size;
                                752                 :                : }
                                753                 :                : 
                                754                 :                : Datum
                                755                 :              4 : pg_numa_available(PG_FUNCTION_ARGS)
                                756                 :                : {
                                757                 :              4 :     PG_RETURN_BOOL(pg_numa_init() != -1);
                                758                 :                : }
        

Generated by: LCOV version 2.4-beta