LCOV - differential code coverage report
Current view: top level - src/backend/storage/ipc - shmem.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: 1a1248818fb8b8b0353c292c632d6a6af77e8209 vs 8e82d6610e7280d7870c0c36ff1c797e3cfb3e09 Lines: 75.1 % 341 256 3 82 1 255 3 1
Current Date: 2026-10-12 11:56:10 +0200 Functions: 90.5 % 21 19 2 1 18
Baseline: lcov-20261012-baseline Branches: 53.4 % 290 155 7 128 1 154
Baseline Date: 2026-10-12 10:36:06 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 80.0 % 15 12 3 1 11
(30,360] days: 78.9 % 247 195 3 49 195
(360..) days: 62.0 % 79 49 30 49
Function coverage date bins:
(30,360] days: 92.9 % 14 13 1 13
(360..) days: 85.7 % 7 6 1 1 5
Branch coverage date bins:
(7,30] days: 58.3 % 24 14 1 9 1 13
(30,360] days: 55.9 % 236 132 6 98 132
(360..) days: 30.0 % 30 9 21 9

 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-2026, 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                 :                :  * This module provides facilities to allocate fixed-size structures in shared
                                 23                 :                :  * memory, for things like variables shared between all backend processes.
                                 24                 :                :  * Each such structure has a string name to identify it, specified when it is
                                 25                 :                :  * requested.  shmem_hash.c provides a shared hash table implementation on top
                                 26                 :                :  * of that.
                                 27                 :                :  *
                                 28                 :                :  * Shared memory areas should usually not be allocated after postmaster
                                 29                 :                :  * startup, although we do allow small allocations later for the benefit of
                                 30                 :                :  * extension modules that are loaded after startup.  Despite that allowance,
                                 31                 :                :  * extensions that need shared memory should be added in
                                 32                 :                :  * shared_preload_libraries, because the allowance is quite small and there is
                                 33                 :                :  * no guarantee that any memory is available after startup.
                                 34                 :                :  *
                                 35                 :                :  * Nowadays, there is also another way to allocate shared memory called
                                 36                 :                :  * Dynamic Shared Memory.  See dsm.c for that facility.  One big difference
                                 37                 :                :  * between traditional shared memory handled by shmem.c and dynamic shared
                                 38                 :                :  * memory is that traditional shared memory areas are mapped to the same
                                 39                 :                :  * address in all processes, so you can use normal pointers in shared memory
                                 40                 :                :  * structs.  With Dynamic Shared Memory, you must use offsets or DSA pointers
                                 41                 :                :  * instead.
                                 42                 :                :  *
                                 43                 :                :  * Shared memory managed by shmem.c can never be freed, once allocated.  Each
                                 44                 :                :  * hash table has its own free list, so hash buckets can be reused when an
                                 45                 :                :  * item is deleted.
                                 46                 :                :  *
                                 47                 :                :  * Usage
                                 48                 :                :  * -----
                                 49                 :                :  *
                                 50                 :                :  * To allocate shared memory, you need to register a set of callback functions
                                 51                 :                :  * which handle the lifecycle of the allocation.  In the request_fn callback,
                                 52                 :                :  * call ShmemRequestStruct() with the desired name and size.  When the area is
                                 53                 :                :  * later allocated or attached to, the global variable pointed to by the .ptr
                                 54                 :                :  * option is set to the shared memory location of the allocation.  The init_fn
                                 55                 :                :  * callback can perform additional initialization.
                                 56                 :                :  *
                                 57                 :                :  *  typedef struct MyShmemData {
                                 58                 :                :  *      ...
                                 59                 :                :  *  } MyShmemData;
                                 60                 :                :  *
                                 61                 :                :  *  static MyShmemData *MyShmem;
                                 62                 :                :  *
                                 63                 :                :  *  static void my_shmem_request(void *arg);
                                 64                 :                :  *  static void my_shmem_init(void *arg);
                                 65                 :                :  *
                                 66                 :                :  *  const ShmemCallbacks MyShmemCallbacks = {
                                 67                 :                :  *      .request_fn = my_shmem_request,
                                 68                 :                :  *      .init_fn = my_shmem_init,
                                 69                 :                :  *  };
                                 70                 :                :  *
                                 71                 :                :  *  static void
                                 72                 :                :  *  my_shmem_request(void *arg)
                                 73                 :                :  *  {
                                 74                 :                :  *      ShmemRequestStruct(.name = "My shmem area",
                                 75                 :                :  *                         .size = sizeof(MyShmemData),
                                 76                 :                :  *                         .ptr = (void **) &MyShmem,
                                 77                 :                :  *          );
                                 78                 :                :  *  }
                                 79                 :                :  *
                                 80                 :                :  * In builtin PostgreSQL code, add the callbacks to the list in
                                 81                 :                :  * src/include/storage/subsystemlist.h.  In an add-in module, you can register
                                 82                 :                :  * the callbacks by calling RegisterShmemCallbacks(&MyShmemCallbacks) in the
                                 83                 :                :  * extension's _PG_init() function.
                                 84                 :                :  *
                                 85                 :                :  * Lifecycle
                                 86                 :                :  * ---------
                                 87                 :                :  *
                                 88                 :                :  * Initializing shared memory happens in multiple phases.  In the first phase,
                                 89                 :                :  * during postmaster startup, all the request_fn callbacks are called.  Only
                                 90                 :                :  * after all the request_fn callbacks have been called and all the shmem areas
                                 91                 :                :  * have been requested by the ShmemRequestStruct() calls we know how much
                                 92                 :                :  * shared memory we need in total.  After that, postmaster allocates global
                                 93                 :                :  * shared memory segment, and calls all the init_fn callbacks to initialize
                                 94                 :                :  * all the requested shmem areas.
                                 95                 :                :  *
                                 96                 :                :  * In standard Unix-ish environments, individual backends do not need to
                                 97                 :                :  * re-establish their local pointers into shared memory, because they inherit
                                 98                 :                :  * correct values of those variables via fork() from the postmaster.  However,
                                 99                 :                :  * this does not work in the EXEC_BACKEND case.  In ports using EXEC_BACKEND,
                                100                 :                :  * backend startup also calls the shmem_request callbacks to re-establish the
                                101                 :                :  * knowledge about each shared memory area, sets the pointer variables
                                102                 :                :  * (*options->ptr), and calls the attach_fn callback, if any, for additional
                                103                 :                :  * per-backend setup.
                                104                 :                :  *
                                105                 :                :  * Legacy ShmemInitStruct()/ShmemInitHash() functions
                                106                 :                :  * --------------------------------------------------
                                107                 :                :  *
                                108                 :                :  * ShmemInitStruct()/ShmemInitHash() is another way of registering shmem
                                109                 :                :  * areas.  It pre-dates the ShmemRequestStruct()/ShmemRequestHash() functions,
                                110                 :                :  * and should not be used in new code, but as of this writing it is still
                                111                 :                :  * widely used in extensions.
                                112                 :                :  *
                                113                 :                :  * To allocate a shmem area with ShmemInitStruct(), you need to separately
                                114                 :                :  * register the size needed for the area by calling RequestAddinShmemSpace()
                                115                 :                :  * from the extension's shmem_request_hook, and allocate the area by calling
                                116                 :                :  * ShmemInitStruct() from the extension's shmem_startup_hook.  There are no
                                117                 :                :  * init/attach callbacks.  Instead, the caller of ShmemInitStruct() must check
                                118                 :                :  * the return status of ShmemInitStruct() and initialize the struct if it was
                                119                 :                :  * not previously initialized.
                                120                 :                :  *
                                121                 :                :  * Calling ShmemAlloc() directly
                                122                 :                :  * -----------------------------
                                123                 :                :  *
                                124                 :                :  * There's a more low-level way of allocating shared memory too: you can call
                                125                 :                :  * ShmemAlloc() directly.  It's used to implement the higher level mechanisms,
                                126                 :                :  * and should generally not be called directly.
                                127                 :                :  */
                                128                 :                : 
                                129                 :                : #include "postgres.h"
                                130                 :                : 
                                131                 :                : #include <unistd.h>
                                132                 :                : 
                                133                 :                : #include "access/slru.h"
                                134                 :                : #include "common/int.h"
                                135                 :                : #include "fmgr.h"
                                136                 :                : #include "funcapi.h"
                                137                 :                : #include "miscadmin.h"
                                138                 :                : #include "port/pg_bitutils.h"
                                139                 :                : #include "port/pg_numa.h"
                                140                 :                : #include "storage/lwlock.h"
                                141                 :                : #include "storage/pg_shmem.h"
                                142                 :                : #include "storage/shmem.h"
                                143                 :                : #include "storage/shmem_internal.h"
                                144                 :                : #include "storage/spin.h"
                                145                 :                : #include "utils/builtins.h"
                                146                 :                : #include "utils/tuplestore.h"
                                147                 :                : 
                                148                 :                : typedef struct ShmemIndexEnt ShmemIndexEnt;
                                149                 :                : 
                                150                 :                : /*
                                151                 :                :  * Registered callbacks.
                                152                 :                :  *
                                153                 :                :  * During postmaster startup, we accumulate the callbacks from all subsystems
                                154                 :                :  * in this list.
                                155                 :                :  *
                                156                 :                :  * This is in process private memory, although on Unix-like systems, we expect
                                157                 :                :  * all the registrations to happen at postmaster startup time and be inherited
                                158                 :                :  * by all the child processes via fork().
                                159                 :                :  */
                                160                 :                : static List *registered_shmem_callbacks;
                                161                 :                : 
                                162                 :                : /*
                                163                 :                :  * In the shmem request phase, all the shmem areas requested with the
                                164                 :                :  * ShmemRequest*() functions are accumulated in the 'pending_shmem_requests'
                                165                 :                :  * list.  The List, the ShmemRequest structs, and the 'options' are all
                                166                 :                :  * allocated in TopMemoryContext.
                                167                 :                :  */
                                168                 :                : typedef struct
                                169                 :                : {
                                170                 :                :     ShmemStructOpts *options;
                                171                 :                :     ShmemRequestKind kind;
                                172                 :                : 
                                173                 :                :     /* InitShmemIndexEntry() sets this pointer when the area is allocated */
                                174                 :                :     ShmemIndexEnt *index_entry;
                                175                 :                : } ShmemRequest;
                                176                 :                : 
                                177                 :                : static List *pending_shmem_requests;    /* List of ShmemRequests */
                                178                 :                : 
                                179                 :                : /*
                                180                 :                :  * Per-process state machine, for sanity checking that we do things in the
                                181                 :                :  * right order.
                                182                 :                :  *
                                183                 :                :  * Postmaster:
                                184                 :                :  *   INITIAL -> REQUESTING -> INITIALIZING -> DONE
                                185                 :                :  *
                                186                 :                :  * Backends in EXEC_BACKEND mode:
                                187                 :                :  *   INITIAL -> REQUESTING -> ATTACHING -> DONE
                                188                 :                :  *
                                189                 :                :  * Late request:
                                190                 :                :  *   DONE -> REQUESTING -> AFTER_STARTUP_ATTACH_OR_INIT -> DONE
                                191                 :                :  */
                                192                 :                : enum shmem_request_state
                                193                 :                : {
                                194                 :                :     /* Initial state */
                                195                 :                :     SRS_INITIAL,
                                196                 :                : 
                                197                 :                :     /*
                                198                 :                :      * When we start calling the shmem_request callbacks, we enter the
                                199                 :                :      * SRS_REQUESTING phase.  All ShmemRequestStruct calls happen in this
                                200                 :                :      * state.
                                201                 :                :      */
                                202                 :                :     SRS_REQUESTING,
                                203                 :                : 
                                204                 :                :     /*
                                205                 :                :      * Postmaster has finished all shmem requests, and is now initializing the
                                206                 :                :      * shared memory segment.  init_fn callbacks are called in this state.
                                207                 :                :      */
                                208                 :                :     SRS_INITIALIZING,
                                209                 :                : 
                                210                 :                :     /*
                                211                 :                :      * A postmaster child process is starting up.  attach_fn callbacks are
                                212                 :                :      * called in this state.
                                213                 :                :      */
                                214                 :                :     SRS_ATTACHING,
                                215                 :                : 
                                216                 :                :     /* An after-startup allocation or attachment is in progress */
                                217                 :                :     SRS_AFTER_STARTUP_ATTACH_OR_INIT,
                                218                 :                : 
                                219                 :                :     /* Normal state after shmem initialization / attachment */
                                220                 :                :     SRS_DONE,
                                221                 :                : };
                                222                 :                : static enum shmem_request_state shmem_request_state = SRS_INITIAL;
                                223                 :                : 
                                224                 :                : /*
                                225                 :                :  * This is the first data structure stored in the shared memory segment, at
                                226                 :                :  * the offset that PGShmemHeader->content_offset points to.  Allocations by
                                227                 :                :  * ShmemAlloc() are carved out of the space after this.
                                228                 :                :  *
                                229                 :                :  * For the base pointer and the total size of the shmem segment, we rely on
                                230                 :                :  * the PGShmemHeader.
                                231                 :                :  */
                                232                 :                : typedef struct ShmemAllocatorData
                                233                 :                : {
                                234                 :                :     Size        free_offset;    /* offset to first free space from ShmemBase */
                                235                 :                : 
                                236                 :                :     /* protects 'free_offset' */
                                237                 :                :     slock_t     shmem_lock;
                                238                 :                : 
                                239                 :                :     HASHHDR    *index;          /* location of ShmemIndex */
                                240                 :                :     size_t      index_size;     /* size of shmem region holding ShmemIndex */
                                241                 :                :     LWLock      index_lock;     /* protects ShmemIndex */
                                242                 :                : } ShmemAllocatorData;
                                243                 :                : 
                                244                 :                : #define ShmemIndexLock (&ShmemAllocator->index_lock)
                                245                 :                : 
                                246                 :                : static void *ShmemAllocRaw(Size size, Size alignment, Size *allocated_size);
                                247                 :                : 
                                248                 :                : /* shared memory global variables */
                                249                 :                : 
                                250                 :                : static PGShmemHeader *ShmemSegHdr;  /* shared mem segment header */
                                251                 :                : static void *ShmemBase;         /* start address of shared memory */
                                252                 :                : static void *ShmemEnd;          /* end+1 address of shared memory */
                                253                 :                : 
                                254                 :                : static ShmemAllocatorData *ShmemAllocator;
                                255                 :                : 
                                256                 :                : /*
                                257                 :                :  * ShmemIndex is a global directory of shmem areas, itself also stored in the
                                258                 :                :  * shared memory.
                                259                 :                :  */
                                260                 :                : static HTAB *ShmemIndex;
                                261                 :                : 
                                262                 :                :  /* max size of data structure string name */
                                263                 :                : #define SHMEM_INDEX_KEYSIZE      (48)
                                264                 :                : 
                                265                 :                : /*
                                266                 :                :  * # of additional entries to reserve in the shmem index table, for
                                267                 :                :  * allocations after postmaster startup.  (This is not a hard limit, the hash
                                268                 :                :  * table can grow larger than that if there is shared memory available)
                                269                 :                :  */
                                270                 :                : #define SHMEM_INDEX_ADDITIONAL_SIZE      (128)
                                271                 :                : 
                                272                 :                : /* this is a hash bucket in the shmem index table */
                                273                 :                : typedef struct ShmemIndexEnt
                                274                 :                : {
                                275                 :                :     char        key[SHMEM_INDEX_KEYSIZE];   /* string name */
                                276                 :                :     void       *location;       /* location in shared mem */
                                277                 :                :     Size        size;           /* # bytes requested for the structure */
                                278                 :                :     Size        allocated_size; /* # bytes actually allocated */
                                279                 :                :     bool        initialized;    /* has the init callback been run? */
                                280                 :                : } ShmemIndexEnt;
                                281                 :                : 
                                282                 :                : /* To get reliable results for NUMA inquiry we need to "touch pages" once */
                                283                 :                : static bool firstNumaTouch = true;
                                284                 :                : 
                                285                 :                : static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
                                286                 :                : static void ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks);
                                287                 :                : static void InitShmemIndexEntry(ShmemRequest *request);
                                288                 :                : static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
                                289                 :                : 
                                290                 :                : Datum       pg_numa_available(PG_FUNCTION_ARGS);
                                291                 :                : 
                                292                 :                : /*
                                293                 :                :  *  ShmemRequestStruct() --- request a named shared memory area
                                294                 :                :  *
                                295                 :                :  * Subsystems call this to register their shared memory needs.  This is
                                296                 :                :  * usually done early in postmaster startup, before the shared memory segment
                                297                 :                :  * has been created, so that the size can be included in the estimate for
                                298                 :                :  * total amount of shared memory needed.  We set aside a small amount of
                                299                 :                :  * memory for allocations that happen later, for the benefit of non-preloaded
                                300                 :                :  * extensions, but that should not be relied upon.
                                301                 :                :  *
                                302                 :                :  * This does not yet allocate the memory, but merely registers the need for
                                303                 :                :  * it.  The actual allocation happens later in the postmaster startup
                                304                 :                :  * sequence.
                                305                 :                :  *
                                306                 :                :  * This must be called from a shmem_request callback function, registered with
                                307                 :                :  * RegisterShmemCallbacks().  This enforces a coding pattern that works the
                                308                 :                :  * same in normal Unix systems and with EXEC_BACKEND.  On Unix systems, the
                                309                 :                :  * shmem_request callbacks are called once, early in postmaster startup, and
                                310                 :                :  * the child processes inherit the struct descriptors and any other
                                311                 :                :  * per-process state from the postmaster.  In EXEC_BACKEND mode, shmem_request
                                312                 :                :  * callbacks are *also* called in each backend, at backend startup, to
                                313                 :                :  * re-establish the struct descriptors.  By calling the same function in both
                                314                 :                :  * cases, we ensure that all the shmem areas are registered the same way in
                                315                 :                :  * all processes.
                                316                 :                :  *
                                317                 :                :  * 'options' defines the name and size of the area, and any other optional
                                318                 :                :  * features.  Leave unused options as zeros.  The options are copied to
                                319                 :                :  * longer-lived memory, so it doesn't need to live after the
                                320                 :                :  * ShmemRequestStruct() call and can point to a local variable in the calling
                                321                 :                :  * function.  The 'name' must point to a long-lived string though, only the
                                322                 :                :  * pointer to it is copied.
                                323                 :                :  */
                                324                 :                : void
  189 heikki.linnakangas@i      325                 :CBC       82386 : ShmemRequestStructWithOpts(const ShmemStructOpts *options)
                                326                 :                : {
                                327                 :                :     ShmemStructOpts *options_copy;
                                328                 :                : 
                                329                 :          82386 :     options_copy = MemoryContextAlloc(TopMemoryContext,
                                330                 :                :                                       sizeof(ShmemStructOpts));
                                331                 :          82386 :     memcpy(options_copy, options, sizeof(ShmemStructOpts));
                                332                 :                : 
                                333                 :          82386 :     ShmemRequestInternal(options_copy, SHMEM_KIND_STRUCT);
                                334                 :          82385 : }
                                335                 :                : 
                                336                 :                : /*
                                337                 :                :  * Internal workhorse of ShmemRequestStruct() and ShmemRequestHash().
                                338                 :                :  *
                                339                 :                :  * Note: Unlike in the public ShmemRequestStruct() and ShmemRequestHash()
                                340                 :                :  * functions, 'options' is *not* copied.  It must be allocated in
                                341                 :                :  * TopMemoryContext by the caller, and will be freed after the init/attach
                                342                 :                :  * callbacks have been called.  This allows ShmemRequestHash() to pass a
                                343                 :                :  * pointer to the extended ShmemHashOpts struct instead.
                                344                 :                :  */
                                345                 :                : void
                                346                 :         101706 : ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
                                347                 :                : {
                                348                 :                :     MemoryContext oldcontext;
                                349                 :                :     ShmemRequest *request;
                                350                 :                : 
                                351                 :                :     /* Check that we're in the right state */
   12                           352         [ -  + ]:         101706 :     if (shmem_request_state != SRS_REQUESTING)
   12 heikki.linnakangas@i      353         [ #  # ]:UBC           0 :         elog(ERROR, "ShmemRequestStruct can only be called from a shmem_request callback");
                                354                 :                : 
                                355                 :                :     /* Check the options */
  189 heikki.linnakangas@i      356         [ -  + ]:CBC      101706 :     if (options->name == NULL)
  189 heikki.linnakangas@i      357         [ #  # ]:UBC           0 :         elog(ERROR, "shared memory request is missing 'name' option");
                                358                 :                : 
   12 heikki.linnakangas@i      359         [ +  + ]:CBC      101706 :     if (options->size == SHMEM_ATTACH_UNKNOWN_SIZE)
                                360                 :                :     {
                                361         [ +  + ]:              4 :         if (ShmemIndex == NULL)
  189                           362         [ +  - ]:              1 :             elog(ERROR, "SHMEM_ATTACH_UNKNOWN_SIZE cannot be used during startup");
                                363                 :                :     }
   12                           364         [ -  + ]:         101702 :     else if (options->size <= 0)
   12 heikki.linnakangas@i      365         [ #  # ]:UBC           0 :         elog(ERROR, "invalid size %zd for shared memory request for \"%s\"",
                                366                 :                :              options->size, options->name);
                                367                 :                : 
  189 heikki.linnakangas@i      368   [ +  +  -  + ]:CBC      101705 :     if (options->alignment != 0 && pg_nextpower2_size_t(options->alignment) != options->alignment)
  189 heikki.linnakangas@i      369         [ #  # ]:UBC           0 :         elog(ERROR, "invalid alignment %zu for shared memory request for \"%s\"",
                                370                 :                :              options->alignment, options->name);
                                371                 :                : 
                                372                 :                :     /* Check that it's not already registered in this process */
  189 heikki.linnakangas@i      373   [ +  +  +  +  :CBC     4169494 :     foreach_ptr(ShmemRequest, existing, pending_shmem_requests)
                                              +  + ]
                                374                 :                :     {
                                375         [ -  + ]:        3966084 :         if (strcmp(existing->options->name, options->name) == 0)
  189 heikki.linnakangas@i      376         [ #  # ]:UBC           0 :             ereport(ERROR,
                                377                 :                :                     (errmsg("shared memory struct \"%s\" is already registered",
                                378                 :                :                             options->name)));
                                379                 :                :     }
                                380                 :                : 
                                381                 :                :     /* Request looks valid, remember it */
   45 heikki.linnakangas@i      382                 :CBC      101705 :     oldcontext = MemoryContextSwitchTo(TopMemoryContext);
   56 michael@paquier.xyz       383                 :         101705 :     request = palloc_object(ShmemRequest);
  189 heikki.linnakangas@i      384                 :         101705 :     request->options = options;
                                385                 :         101705 :     request->kind = kind;
   45                           386                 :         101705 :     request->index_entry = NULL;
  189                           387                 :         101705 :     pending_shmem_requests = lappend(pending_shmem_requests, request);
   45                           388                 :         101705 :     MemoryContextSwitchTo(oldcontext);
  189                           389                 :         101705 : }
                                390                 :                : 
                                391                 :                : /*
                                392                 :                :  *  ShmemGetRequestedSize() --- estimate the total size of all registered shared
                                393                 :                :  *                              memory structures.
                                394                 :                :  *
                                395                 :                :  * This is called at postmaster startup, before the shared memory segment has
                                396                 :                :  * been created.
                                397                 :                :  */
                                398                 :                : size_t
                                399                 :           2391 : ShmemGetRequestedSize(void)
                                400                 :                : {
                                401                 :                :     size_t      size;
                                402                 :                : 
                                403                 :                :     /* memory needed for the ShmemIndex */
                                404                 :           2391 :     size = hash_estimate_size(list_length(pending_shmem_requests) + SHMEM_INDEX_ADDITIONAL_SIZE,
                                405                 :                :                               sizeof(ShmemIndexEnt));
                                406                 :           2391 :     size = CACHELINEALIGN(size);
                                407                 :                : 
                                408                 :                :     /* memory needed for all the requested areas */
                                409   [ +  -  +  +  :         193693 :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                                410                 :                :     {
                                411                 :         188911 :         size_t      alignment = request->options->alignment;
                                412                 :                : 
                                413                 :                :         /* pad the start address for alignment like ShmemAllocRaw() does */
                                414         [ +  + ]:         188911 :         if (alignment < PG_CACHE_LINE_SIZE)
                                415                 :         181738 :             alignment = PG_CACHE_LINE_SIZE;
                                416                 :         188911 :         size = TYPEALIGN(alignment, size);
                                417                 :                : 
                                418                 :         188911 :         size = add_size(size, request->options->size);
                                419                 :                :     }
                                420                 :                : 
                                421                 :           2391 :     return size;
                                422                 :                : }
                                423                 :                : 
                                424                 :                : /*
                                425                 :                :  *  ShmemInitRequested() --- allocate and initialize requested shared memory
                                426                 :                :  *                            structures.
                                427                 :                :  *
                                428                 :                :  * This is called once at postmaster startup, after the shared memory segment
                                429                 :                :  * has been created.
                                430                 :                :  */
                                431                 :                : void
                                432                 :           1283 : ShmemInitRequested(void)
                                433                 :                : {
                                434                 :                :     /* should be called only by the postmaster or a standalone backend */
                                435         [ -  + ]:           1283 :     Assert(!IsUnderPostmaster);
                                436         [ -  + ]:           1283 :     Assert(shmem_request_state == SRS_INITIALIZING);
                                437                 :                : 
                                438                 :                :     /*
                                439                 :                :      * Initialize the ShmemIndex entries and perform basic initialization of
                                440                 :                :      * all the requested memory areas.  There are no concurrent processes yet,
                                441                 :                :      * so no need for locking.
                                442                 :                :      */
                                443   [ +  -  +  +  :         103933 :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                                444                 :                :     {
                                445                 :         101367 :         InitShmemIndexEntry(request);
                                446                 :                :     }
                                447                 :                : 
                                448                 :                :     /*
                                449                 :                :      * Call the subsystem-specific init callbacks to finish initialization of
                                450                 :                :      * all the areas.
                                451                 :                :      */
                                452   [ +  -  +  +  :          59044 :     foreach_ptr(const ShmemCallbacks, callbacks, registered_shmem_callbacks)
                                              +  + ]
                                453                 :                :     {
                                454         [ +  + ]:          56478 :         if (callbacks->init_fn)
                                455                 :          52625 :             callbacks->init_fn(callbacks->opaque_arg);
                                456                 :                :     }
                                457                 :                : 
                                458                 :                :     /* Now we can mark all the areas as initialized and free the requests */
   45                           459   [ +  -  +  +  :         103933 :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                                460                 :                :     {
                                461                 :         101367 :         request->index_entry->initialized = true;
                                462                 :         101367 :         pfree(request->options);
                                463                 :                :     }
                                464                 :           1283 :     list_free_deep(pending_shmem_requests);
                                465                 :           1283 :     pending_shmem_requests = NIL;
                                466                 :                : 
  189                           467                 :           1283 :     shmem_request_state = SRS_DONE;
                                468                 :           1283 : }
                                469                 :                : 
                                470                 :                : /*
                                471                 :                :  * Re-establish process private state related to shmem areas.
                                472                 :                :  *
                                473                 :                :  * This is called at backend startup in EXEC_BACKEND mode, in every backend.
                                474                 :                :  */
                                475                 :                : #ifdef EXEC_BACKEND
                                476                 :                : void
                                477                 :                : ShmemAttachRequested(void)
                                478                 :                : {
                                479                 :                :     ListCell   *lc;
                                480                 :                : 
                                481                 :                :     /* Must be initializing a (non-standalone) backend */
                                482                 :                :     Assert(IsUnderPostmaster);
                                483                 :                :     Assert(ShmemAllocator->index != NULL);
                                484                 :                :     Assert(shmem_request_state == SRS_REQUESTING);
                                485                 :                :     shmem_request_state = SRS_ATTACHING;
                                486                 :                : 
                                487                 :                :     LWLockAcquire(ShmemIndexLock, LW_SHARED);
                                488                 :                : 
                                489                 :                :     /*
                                490                 :                :      * Attach to all the requested memory areas.
                                491                 :                :      */
                                492                 :                :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                493                 :                :     {
                                494                 :                :         AttachShmemIndexEntry(request, false);
                                495                 :                :         pfree(request->options);
                                496                 :                :     }
                                497                 :                :     list_free_deep(pending_shmem_requests);
                                498                 :                :     pending_shmem_requests = NIL;
                                499                 :                : 
                                500                 :                :     /* Call attach callbacks */
                                501                 :                :     foreach(lc, registered_shmem_callbacks)
                                502                 :                :     {
                                503                 :                :         const ShmemCallbacks *callbacks = (const ShmemCallbacks *) lfirst(lc);
                                504                 :                : 
                                505                 :                :         if (callbacks->attach_fn)
                                506                 :                :             callbacks->attach_fn(callbacks->opaque_arg);
                                507                 :                :     }
                                508                 :                : 
                                509                 :                :     LWLockRelease(ShmemIndexLock);
                                510                 :                : 
                                511                 :                :     shmem_request_state = SRS_DONE;
                                512                 :                : }
                                513                 :                : #endif
                                514                 :                : 
                                515                 :                : /*
                                516                 :                :  * Insert requested shmem area into the shared memory index and initialize it.
                                517                 :                :  *
                                518                 :                :  * Note that this only does performs basic initialization depending on
                                519                 :                :  * ShmemRequestKind, like setting the global pointer variable to the area for
                                520                 :                :  * SHMEM_KIND_STRUCT or setting up the backend-private HTAB control struct.
                                521                 :                :  * This does *not* call the subsystem-specific init callbacks.  That's done
                                522                 :                :  * later after all the shmem areas have been initialized or attached to.
                                523                 :                :  */
                                524                 :                : static void
                                525                 :         101376 : InitShmemIndexEntry(ShmemRequest *request)
                                526                 :                : {
                                527                 :         101376 :     const char *name = request->options->name;
                                528                 :                :     ShmemIndexEnt *index_entry;
                                529                 :                :     bool        found;
                                530                 :                :     size_t      allocated_size;
                                531                 :                :     void       *structPtr;
                                532                 :                : 
                                533                 :                :     /* Size must be known at this point. */
   24                           534         [ -  + ]:         101376 :     Assert(request->options->size != SHMEM_ATTACH_UNKNOWN_SIZE);
                                535                 :                : 
                                536                 :                :     /* look it up in the shmem index */
                                537                 :                :     index_entry = (ShmemIndexEnt *)
  189                           538                 :         101376 :         hash_search(ShmemIndex, name, HASH_ENTER_NULL, &found);
                                539         [ -  + ]:         101376 :     if (found)
  189 heikki.linnakangas@i      540         [ #  # ]:UBC           0 :         elog(ERROR, "shared memory struct \"%s\" is already initialized", name);
  189 heikki.linnakangas@i      541         [ -  + ]:CBC      101376 :     if (!index_entry)
                                542                 :                :     {
                                543                 :                :         /* tried to add it to the hash table, but there was no space */
  189 heikki.linnakangas@i      544         [ #  # ]:UBC           0 :         ereport(ERROR,
                                545                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                546                 :                :                  errmsg("could not create ShmemIndex entry for data structure \"%s\"",
                                547                 :                :                         name)));
                                548                 :                :     }
                                549                 :                : 
                                550                 :                :     /*
                                551                 :                :      * We inserted the entry to the shared memory index.  Allocate requested
                                552                 :                :      * amount of shared memory for it, and initialize the index entry.
                                553                 :                :      */
  189 heikki.linnakangas@i      554                 :CBC      101376 :     structPtr = ShmemAllocRaw(request->options->size,
                                555                 :         101376 :                               request->options->alignment,
                                556                 :                :                               &allocated_size);
                                557         [ +  + ]:         101376 :     if (structPtr == NULL)
                                558                 :                :     {
                                559                 :                :         /* out of memory; remove the failed ShmemIndex entry */
                                560                 :              1 :         hash_search(ShmemIndex, name, HASH_REMOVE, NULL);
                                561         [ +  - ]:              1 :         ereport(ERROR,
                                562                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                563                 :                :                  errmsg("not enough shared memory for data structure"
                                564                 :                :                         " \"%s\" (%zd bytes requested)",
                                565                 :                :                         name, request->options->size)));
                                566                 :                :     }
                                567                 :         101375 :     index_entry->size = request->options->size;
                                568                 :         101375 :     index_entry->allocated_size = allocated_size;
                                569                 :         101375 :     index_entry->location = structPtr;
                                570                 :                : 
                                571                 :                :     /*
                                572                 :                :      * The area is considered fully initialized only after the subsystem's
                                573                 :                :      * init callback has been called.  For now, perform only basic
                                574                 :                :      * initialization based on the kind of shmem area it is.
                                575                 :                :      */
   45                           576                 :         101375 :     index_entry->initialized = false;
  189                           577   [ +  +  +  - ]:         101375 :     switch (request->kind)
                                578                 :                :     {
                                579                 :          82115 :         case SHMEM_KIND_STRUCT:
                                580         [ +  - ]:          82115 :             if (request->options->ptr)
                                581                 :          82115 :                 *(request->options->ptr) = index_entry->location;
                                582                 :          82115 :             break;
                                583                 :          10275 :         case SHMEM_KIND_HASH:
                                584                 :          10275 :             shmem_hash_init(structPtr, request->options);
                                585                 :          10275 :             break;
                                586                 :           8985 :         case SHMEM_KIND_SLRU:
                                587                 :           8985 :             shmem_slru_init(structPtr, request->options);
                                588                 :           8985 :             break;
                                589                 :                :     }
                                590                 :                : 
                                591                 :                :     /* return the pointer to the entry to the caller */
   45                           592                 :         101375 :     request->index_entry = index_entry;
  189                           593                 :         101375 : }
                                594                 :                : 
                                595                 :                : /*
                                596                 :                :  * Look up a named shmem area in the shared memory index and attach to it.
                                597                 :                :  *
                                598                 :                :  * Note that this only performs the basic attachment actions depending on
                                599                 :                :  * ShmemRequestKind, like setting the global pointer variable to the area for
                                600                 :                :  * SHMEM_KIND_STRUCT or setting up the backend-private HTAB control struct.
                                601                 :                :  * This does *not* call the subsystem-specific attach callbacks.  That's done
                                602                 :                :  * later after all the shmem areas have been initialized or attached to.
                                603                 :                :  */
                                604                 :                : static bool
                                605                 :             11 : AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
                                606                 :                : {
                                607                 :             11 :     const char *name = request->options->name;
                                608                 :                :     ShmemIndexEnt *index_entry;
                                609                 :                : 
                                610                 :                :     /* Look it up in the shmem index */
                                611                 :                :     index_entry = (ShmemIndexEnt *)
                                612                 :             11 :         hash_search(ShmemIndex, name, HASH_FIND, NULL);
                                613         [ -  + ]:             11 :     if (!index_entry)
                                614                 :                :     {
  189 heikki.linnakangas@i      615         [ #  # ]:UBC           0 :         if (!missing_ok)
                                616         [ #  # ]:              0 :             ereport(ERROR,
                                617                 :                :                     (errmsg("could not find ShmemIndex entry for data structure \"%s\"",
                                618                 :                :                             request->options->name)));
                                619                 :              0 :         return false;
                                620                 :                :     }
                                621                 :                : 
                                622                 :                :     /*
                                623                 :                :      * If it was previously allocated but not fully initialized, error out.
                                624                 :                :      * There is currently no way of retrying or cleaning up an uninitialized
                                625                 :                :      * entry, it just lingers until the server is shut down.  But this can
                                626                 :                :      * only happen when allocating areas after postmaster startup, and it's
                                627                 :                :      * unlikely that you could successfully retry anyway.  The most likely
                                628                 :                :      * reason for failed initialization is that you are out of shared memory
                                629                 :                :      * and retrying won't help with that.
                                630                 :                :      */
   45 heikki.linnakangas@i      631         [ -  + ]:CBC          11 :     if (!index_entry->initialized)
   45 heikki.linnakangas@i      632         [ #  # ]:UBC           0 :         ereport(ERROR,
                                633                 :                :                 (errmsg("cannot attach to shared memory struct \"%s\" because it was not fully initialized",
                                634                 :                :                         request->options->name)));
                                635                 :                : 
                                636                 :                :     /* Check that the size in the index matches the request */
  189 heikki.linnakangas@i      637         [ +  + ]:CBC          11 :     if (index_entry->size != request->options->size &&
                                638         [ +  + ]:              3 :         request->options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
                                639                 :                :     {
                                640         [ +  - ]:              1 :         ereport(ERROR,
                                641                 :                :                 (errmsg("shared memory struct \"%s\" was created with"
                                642                 :                :                         " different size: existing %zu, requested %zd",
                                643                 :                :                         name, index_entry->size, request->options->size)));
                                644                 :                :     }
                                645                 :                : 
                                646                 :                :     /*
                                647                 :                :      * Re-establish the caller's pointer variable, or do other actions to
                                648                 :                :      * attach depending on the kind of shmem area it is.
                                649                 :                :      */
                                650   [ +  -  -  - ]:             10 :     switch (request->kind)
                                651                 :                :     {
                                652                 :             10 :         case SHMEM_KIND_STRUCT:
                                653         [ +  - ]:             10 :             if (request->options->ptr)
                                654                 :             10 :                 *(request->options->ptr) = index_entry->location;
                                655                 :             10 :             break;
  189 heikki.linnakangas@i      656                 :UBC           0 :         case SHMEM_KIND_HASH:
                                657                 :              0 :             shmem_hash_attach(index_entry->location, request->options);
                                658                 :              0 :             break;
                                659                 :              0 :         case SHMEM_KIND_SLRU:
                                660                 :              0 :             shmem_slru_attach(index_entry->location, request->options);
                                661                 :              0 :             break;
                                662                 :                :     }
                                663                 :                : 
   45 heikki.linnakangas@i      664                 :CBC          10 :     request->index_entry = index_entry;
                                665                 :                : 
  189                           666                 :             10 :     return true;
                                667                 :                : }
                                668                 :                : 
                                669                 :                : /*
                                670                 :                :  *  InitShmemAllocator() --- set up basic pointers to shared memory.
                                671                 :                :  *
                                672                 :                :  * Called at postmaster or stand-alone backend startup, to initialize the
                                673                 :                :  * allocator's data structure in the shared memory segment.  In EXEC_BACKEND,
                                674                 :                :  * this is also called at backend startup, to set up pointers to the
                                675                 :                :  * already-initialized data structure.
                                676                 :                :  */
                                677                 :                : void
  255                           678                 :           1283 : InitShmemAllocator(PGShmemHeader *seghdr)
                                679                 :                : {
                                680                 :                :     Size        offset;
                                681                 :                :     int64       hash_nelems;
                                682                 :                :     HASHCTL     info;
                                683                 :                :     int         hash_flags;
                                684                 :                : 
                                685                 :                : #ifndef EXEC_BACKEND
  200                           686         [ -  + ]:           1283 :     Assert(!IsUnderPostmaster);
                                687                 :                : #endif
  255                           688         [ -  + ]:           1283 :     Assert(seghdr != NULL);
                                689                 :                : 
  189                           690         [ -  + ]:           1283 :     if (IsUnderPostmaster)
                                691                 :                :     {
  189 heikki.linnakangas@i      692         [ #  # ]:UBC           0 :         Assert(shmem_request_state == SRS_INITIAL);
                                693                 :                :     }
                                694                 :                :     else
                                695                 :                :     {
  189 heikki.linnakangas@i      696         [ -  + ]:CBC        1283 :         Assert(shmem_request_state == SRS_REQUESTING);
                                697                 :           1283 :         shmem_request_state = SRS_INITIALIZING;
                                698                 :                :     }
                                699                 :                : 
                                700                 :                :     /*
                                701                 :                :      * We assume the pointer and offset are MAXALIGN.  Not a hard requirement,
                                702                 :                :      * but it's true today and keeps the math below simpler.
                                703                 :                :      */
  255                           704         [ -  + ]:           1283 :     Assert(seghdr == (void *) MAXALIGN(seghdr));
                                705         [ -  + ]:           1283 :     Assert(seghdr->content_offset == MAXALIGN(seghdr->content_offset));
                                706                 :                : 
                                707                 :                :     /*
                                708                 :                :      * Allocations after this point should go through ShmemAlloc, which
                                709                 :                :      * expects to allocate everything on cache line boundaries.  Make sure the
                                710                 :                :      * first allocation begins on a cache line boundary.
                                711                 :                :      */
  200                           712                 :           1283 :     offset = CACHELINEALIGN(seghdr->content_offset + sizeof(ShmemAllocatorData));
                                713         [ -  + ]:           1283 :     if (offset > seghdr->totalsize)
  200 heikki.linnakangas@i      714         [ #  # ]:UBC           0 :         ereport(ERROR,
                                715                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                716                 :                :                  errmsg("out of shared memory (%zu bytes requested)",
                                717                 :                :                         offset)));
                                718                 :                : 
                                719                 :                :     /*
                                720                 :                :      * In postmaster or stand-alone backend, initialize the shared memory
                                721                 :                :      * allocator so that we can allocate shared memory for ShmemIndex using
                                722                 :                :      * ShmemAlloc().  In a regular backend just set up the pointers required
                                723                 :                :      * by ShmemAlloc().
                                724                 :                :      */
  200 heikki.linnakangas@i      725                 :CBC        1283 :     ShmemAllocator = (ShmemAllocatorData *) ((char *) seghdr + seghdr->content_offset);
                                726         [ +  - ]:           1283 :     if (!IsUnderPostmaster)
                                727                 :                :     {
                                728                 :           1283 :         SpinLockInit(&ShmemAllocator->shmem_lock);
                                729                 :           1283 :         ShmemAllocator->free_offset = offset;
                                730                 :           1283 :         LWLockInitialize(&ShmemAllocator->index_lock, LWTRANCHE_SHMEM_INDEX);
                                731                 :                :     }
                                732                 :                : 
  685 peter@eisentraut.org      733                 :           1283 :     ShmemSegHdr = seghdr;
                                734                 :           1283 :     ShmemBase = seghdr;
                                735                 :           1283 :     ShmemEnd = (char *) ShmemBase + seghdr->totalsize;
                                736                 :                : 
                                737                 :                :     /*
                                738                 :                :      * Create (or attach to) the shared memory index of shmem areas.
                                739                 :                :      *
                                740                 :                :      * This is the same initialization as ShmemInitHash() does, but we cannot
                                741                 :                :      * use ShmemInitHash() here because it relies on ShmemIndex being already
                                742                 :                :      * initialized.
                                743                 :                :      */
  189 heikki.linnakangas@i      744                 :           1283 :     hash_nelems = list_length(pending_shmem_requests) + SHMEM_INDEX_ADDITIONAL_SIZE;
                                745                 :                : 
  200                           746                 :           1283 :     info.keysize = SHMEM_INDEX_KEYSIZE;
                                747                 :           1283 :     info.entrysize = sizeof(ShmemIndexEnt);
  191                           748                 :           1283 :     hash_flags = HASH_ELEM | HASH_STRINGS | HASH_FIXED_SIZE;
                                749                 :                : 
  200                           750         [ +  - ]:           1283 :     if (!IsUnderPostmaster)
                                751                 :                :     {
  189                           752                 :           1283 :         ShmemAllocator->index_size = hash_estimate_size(hash_nelems, info.entrysize);
  191                           753                 :           1283 :         ShmemAllocator->index = (HASHHDR *) ShmemAlloc(ShmemAllocator->index_size);
                                754                 :                :     }
                                755                 :           2566 :     ShmemIndex = shmem_hash_create(ShmemAllocator->index,
                                756                 :           1283 :                                    ShmemAllocator->index_size,
                                757                 :                :                                    IsUnderPostmaster,
                                758                 :                :                                    "ShmemIndex", hash_nelems,
                                759                 :                :                                    &info, hash_flags);
  200                           760         [ -  + ]:           1283 :     Assert(ShmemIndex != NULL);
                                761                 :                : 
                                762                 :                :     /*
                                763                 :                :      * Add an entry for ShmemIndex itself into ShmemIndex, so that it's
                                764                 :                :      * visible in the pg_shmem_allocations view
                                765                 :                :      */
  194                           766         [ +  - ]:           1283 :     if (!IsUnderPostmaster)
                                767                 :                :     {
                                768                 :                :         bool        found;
                                769                 :                :         ShmemIndexEnt *result = (ShmemIndexEnt *)
                                770                 :           1283 :             hash_search(ShmemIndex, "ShmemIndex", HASH_ENTER, &found);
                                771                 :                : 
                                772         [ -  + ]:           1283 :         Assert(!found);
  191                           773                 :           1283 :         result->size = ShmemAllocator->index_size;
                                774                 :           1283 :         result->allocated_size = ShmemAllocator->index_size;
  194                           775                 :           1283 :         result->location = ShmemAllocator->index;
   45                           776                 :           1283 :         result->initialized = true;
                                777                 :                :     }
11052 scrappy@hub.org           778                 :           1283 : }
                                779                 :                : 
                                780                 :                : /*
                                781                 :                :  * Reset state on postmaster crash restart.
                                782                 :                :  */
                                783                 :                : void
  189 heikki.linnakangas@i      784                 :              6 : ResetShmemAllocator(void)
                                785                 :                : {
                                786         [ -  + ]:              6 :     Assert(!IsUnderPostmaster);
   12                           787                 :              6 :     ShmemAllocator = NULL;
                                788                 :              6 :     ShmemIndex = NULL;
  189                           789                 :              6 :     shmem_request_state = SRS_INITIAL;
                                790                 :                : 
                                791                 :              6 :     pending_shmem_requests = NIL;
                                792                 :                : 
                                793                 :                :     /*
                                794                 :                :      * Note that we don't clear the registered callbacks.  We will need to
                                795                 :                :      * call them again as we restart
                                796                 :                :      */
                                797                 :              6 : }
                                798                 :                : 
                                799                 :                : /*
                                800                 :                :  * ShmemAlloc -- allocate max-aligned chunk from shared memory
                                801                 :                :  *
                                802                 :                :  * Throws error if request cannot be satisfied.
                                803                 :                :  *
                                804                 :                :  * Assumes ShmemSegHdr is initialized.
                                805                 :                :  */
                                806                 :                : void *
 7302 tgl@sss.pgh.pa.us         807                 :           1283 : ShmemAlloc(Size size)
                                808                 :                : {
                                809                 :                :     void       *newSpace;
                                810                 :                :     Size        allocated_size;
                                811                 :                : 
  189 heikki.linnakangas@i      812                 :           1283 :     newSpace = ShmemAllocRaw(size, 0, &allocated_size);
 3693 tgl@sss.pgh.pa.us         813         [ -  + ]:           1283 :     if (!newSpace)
 3693 tgl@sss.pgh.pa.us         814         [ #  # ]:UBC           0 :         ereport(ERROR,
                                815                 :                :                 (errcode(ERRCODE_OUT_OF_MEMORY),
                                816                 :                :                  errmsg("out of shared memory (%zu bytes requested)",
                                817                 :                :                         size)));
 3693 tgl@sss.pgh.pa.us         818                 :CBC        1283 :     return newSpace;
                                819                 :                : }
                                820                 :                : 
                                821                 :                : /*
                                822                 :                :  * ShmemAllocNoError -- allocate max-aligned chunk from shared memory
                                823                 :                :  *
                                824                 :                :  * As ShmemAlloc, but returns NULL if out of space, rather than erroring.
                                825                 :                :  */
                                826                 :                : void *
 3693 tgl@sss.pgh.pa.us         827                 :UBC           0 : ShmemAllocNoError(Size size)
                                828                 :                : {
                                829                 :                :     Size        allocated_size;
                                830                 :                : 
  189 heikki.linnakangas@i      831                 :              0 :     return ShmemAllocRaw(size, 0, &allocated_size);
                                832                 :                : }
                                833                 :                : 
                                834                 :                : /*
                                835                 :                :  * ShmemAllocRaw -- allocate align chunk and return allocated size
                                836                 :                :  *
                                837                 :                :  * Also sets *allocated_size to the number of bytes allocated, which will
                                838                 :                :  * be equal to the number requested plus any padding we choose to add.
                                839                 :                :  *
                                840                 :                :  * Returns NULL in case space can not be allocated.
                                841                 :                :  */
                                842                 :                : static void *
  189 heikki.linnakangas@i      843                 :CBC      102659 : ShmemAllocRaw(Size size, Size alignment, Size *allocated_size)
                                844                 :                : {
                                845                 :                :     Size        rawStart;
                                846                 :                :     Size        newStart;
                                847                 :                :     Size        newFree;
                                848                 :                :     void       *newSpace;
                                849                 :                : 
                                850                 :                :     /*
                                851                 :                :      * Ensure all space is adequately aligned.  We used to only MAXALIGN this
                                852                 :                :      * space but experience has proved that on modern systems that is not good
                                853                 :                :      * enough.  Many parts of the system are very sensitive to critical data
                                854                 :                :      * structures getting split across cache line boundaries.  To avoid that,
                                855                 :                :      * attempt to align the beginning of the allocation to a cache line
                                856                 :                :      * boundary.  The calling code will still need to be careful about how it
                                857                 :                :      * uses the allocated space - e.g. by padding each element in an array of
                                858                 :                :      * structures out to a power-of-two size - but without this, even that
                                859                 :                :      * won't be sufficient.
                                860                 :                :      */
                                861         [ +  + ]:         102659 :     if (alignment < PG_CACHE_LINE_SIZE)
                                862                 :          98810 :         alignment = PG_CACHE_LINE_SIZE;
                                863                 :                : 
 4014 rhaas@postgresql.org      864         [ -  + ]:         102659 :     Assert(ShmemSegHdr != NULL);
                                865                 :                : 
  200 heikki.linnakangas@i      866                 :         102659 :     SpinLockAcquire(&ShmemAllocator->shmem_lock);
                                867                 :                : 
  189                           868                 :         102659 :     rawStart = ShmemAllocator->free_offset;
                                869                 :         102659 :     newStart = TYPEALIGN(alignment, rawStart);
                                870                 :                : 
                                871                 :                :     /*
                                872                 :                :      * newFree = newStart + size, which is the start of the remaining space
                                873                 :                :      * after the allocation.  If it exceeds the shmem segment size, we don't
                                874                 :                :      * have enough space available.
                                875                 :                :      */
   24                           876         [ +  - ]:         102659 :     if (!pg_add_size_overflow(newStart, size, &newFree) &&
                                877         [ +  + ]:         102659 :         newFree <= ShmemSegHdr->totalsize)
                                878                 :                :     {
  683 peter@eisentraut.org      879                 :         102658 :         newSpace = (char *) ShmemBase + newStart;
  255 heikki.linnakangas@i      880                 :         102658 :         ShmemAllocator->free_offset = newFree;
                                881                 :                :     }
                                882                 :                :     else
10627 bruce@momjian.us          883                 :              1 :         newSpace = NULL;
                                884                 :                : 
  200 heikki.linnakangas@i      885                 :         102659 :     SpinLockRelease(&ShmemAllocator->shmem_lock);
                                886                 :                : 
                                887                 :                :     /* note this assert is okay with newSpace == NULL */
  189                           888         [ -  + ]:         102659 :     Assert(newSpace == (void *) TYPEALIGN(alignment, newSpace));
                                889                 :                : 
                                890                 :         102659 :     *allocated_size = newFree - rawStart;
10268 bruce@momjian.us          891                 :         102659 :     return newSpace;
                                892                 :                : }
                                893                 :                : 
                                894                 :                : /*
                                895                 :                :  * ShmemAddrIsValid -- test if an address refers to shared memory
                                896                 :                :  *
                                897                 :                :  * Returns true if the pointer points within the shared memory segment.
                                898                 :                :  */
                                899                 :                : bool
 5726 heikki.linnakangas@i      900                 :           1703 : ShmemAddrIsValid(const void *addr)
                                901                 :                : {
 6553 tgl@sss.pgh.pa.us         902   [ +  -  +  - ]:           1703 :     return (addr >= ShmemBase) && (addr < ShmemEnd);
                                903                 :                : }
                                904                 :                : 
                                905                 :                : /*
                                906                 :                :  * Register callbacks that define a shared memory area (or multiple areas).
                                907                 :                :  *
                                908                 :                :  * The system will call the callbacks at different stages of postmaster or
                                909                 :                :  * backend startup, to allocate and initialize the area.
                                910                 :                :  *
                                911                 :                :  * This is normally called early during postmaster startup, but if the
                                912                 :                :  * SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP is set, this can also be used after
                                913                 :                :  * startup, although after startup there's no guarantee that there's enough
                                914                 :                :  * shared memory available.  When called after startup, this immediately calls
                                915                 :                :  * the right callbacks depending on whether another backend had already
                                916                 :                :  * initialized the area.
                                917                 :                :  *
                                918                 :                :  * Note: In EXEC_BACKEND mode, this needs to be called in every backend
                                919                 :                :  * process.  That's needed because we cannot pass down the callback function
                                920                 :                :  * pointers from the postmaster process, because different processes may have
                                921                 :                :  * loaded libraries to different addresses.
                                922                 :                :  */
                                923                 :                : void
  189 heikki.linnakangas@i      924                 :          56983 : RegisterShmemCallbacks(const ShmemCallbacks *callbacks)
                                925                 :                : {
   47                           926         [ +  + ]:          56983 :     if (shmem_request_state == SRS_DONE)
                                927                 :                :     {
                                928                 :                :         /*
                                929                 :                :          * After-startup initialization or attachment.  Call the appropriate
                                930                 :                :          * callbacks immediately.
                                931                 :                :          *
                                932                 :                :          * This is not allowed from the postmaster, because the postmaster
                                933                 :                :          * cannot acquire locks.
                                934                 :                :          */
  189                           935         [ -  + ]:             22 :         if ((callbacks->flags & SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP) == 0)
  189 heikki.linnakangas@i      936         [ #  # ]:UBC           0 :             elog(ERROR, "cannot request shared memory at this time");
   47 heikki.linnakangas@i      937   [ +  +  -  + ]:CBC          22 :         Assert(IsUnderPostmaster || !IsPostmasterEnvironment);
                                938                 :                : 
  189                           939                 :             22 :         CallShmemCallbacksAfterStartup(callbacks);
                                940                 :                :     }
   47                           941         [ +  - ]:          56961 :     else if (shmem_request_state == SRS_INITIAL)
                                942                 :                :     {
                                943                 :                :         /* Remember the callbacks for later */
  189                           944                 :          56961 :         registered_shmem_callbacks = lappend(registered_shmem_callbacks,
                                945                 :                :                                              unconstify(ShmemCallbacks *, callbacks));
                                946                 :                :     }
                                947                 :                :     else
   47 heikki.linnakangas@i      948         [ #  # ]:UBC           0 :         elog(ERROR, "cannot request shared memory at this time");
  189 heikki.linnakangas@i      949                 :CBC       56978 : }
                                950                 :                : 
                                951                 :                : /*
                                952                 :                :  * Register a shmem area (or multiple areas) after startup.
                                953                 :                :  */
                                954                 :                : static void
                                955                 :             22 : CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
                                956                 :                : {
                                957         [ -  + ]:             22 :     Assert(shmem_request_state == SRS_DONE);
                                958         [ -  + ]:             22 :     Assert(pending_shmem_requests == NIL);
                                959                 :                : 
   45                           960         [ +  + ]:             22 :     PG_TRY();
                                961                 :                :     {
                                962                 :             22 :         shmem_request_state = SRS_REQUESTING;
                                963                 :                : 
                                964                 :                :         /*
                                965                 :                :          * Call the request callback first.  The callback makes
                                966                 :                :          * ShmemRequest*() calls for each shmem area, adding them to
                                967                 :                :          * pending_shmem_requests.
                                968                 :                :          */
                                969         [ +  - ]:             22 :         if (callbacks->request_fn)
                                970                 :             22 :             callbacks->request_fn(callbacks->opaque_arg);
                                971                 :                : 
                                972                 :                :         /* Process all the requests */
                                973                 :             22 :         shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
                                974         [ +  - ]:             22 :         if (pending_shmem_requests != NIL)
                                975                 :             22 :             ProcessShmemRequestsAfterStartup(callbacks);
                                976                 :                :     }
                                977                 :              5 :     PG_FINALLY();
                                978                 :                :     {
                                979   [ +  -  +  +  :             66 :         foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                                980                 :             22 :             pfree(request->options);
                                981                 :             22 :         list_free_deep(pending_shmem_requests);
                                982                 :             22 :         pending_shmem_requests = NIL;
                                983                 :                : 
  189                           984                 :             22 :         shmem_request_state = SRS_DONE;
                                985                 :                :     }
   45                           986         [ +  + ]:             22 :     PG_END_TRY();
                                987                 :             17 : }
                                988                 :                : 
                                989                 :                : static void
                                990                 :             22 : ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
                                991                 :                : {
                                992                 :                :     bool        found_any;
                                993                 :                :     bool        notfound_any;
                                994                 :                : 
                                995                 :                :     /* There should be some requests to process */
                                996         [ -  + ]:             22 :     Assert(pending_shmem_requests != NIL);
                                997                 :                : 
                                998                 :                :     /* Caller manages the global state variable */
                                999         [ -  + ]:             22 :     Assert(shmem_request_state == SRS_AFTER_STARTUP_ATTACH_OR_INIT);
                               1000                 :                : 
                               1001                 :                :     /*
                               1002                 :                :      * Hold ShmemIndexLock while we allocate all the shmem entries and run all
                               1003                 :                :      * the initializers.
                               1004                 :                :      */
  200                          1005                 :             22 :     LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
                               1006                 :                : 
                               1007                 :                :     /*
                               1008                 :                :      * Check if the requested shared memory areas have already been
                               1009                 :                :      * initialized.  We assume all the areas requested by the request callback
                               1010                 :                :      * to form a coherent unit such that they're all already initialized or
                               1011                 :                :      * none.  Otherwise it would be ambiguous which callback, init or attach,
                               1012                 :                :      * to callback afterwards.
                               1013                 :                :      */
  189                          1014                 :             22 :     found_any = notfound_any = false;
                               1015   [ +  -  +  +  :             62 :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                               1016                 :                :     {
                               1017                 :                :         ShmemIndexEnt *index_entry;
                               1018                 :                : 
                               1019                 :                :         index_entry = (ShmemIndexEnt *)
   45                          1020                 :             22 :             hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL);
                               1021         [ +  + ]:             22 :         if (index_entry)
                               1022                 :                :         {
                               1023                 :                :             /*
                               1024                 :                :              * Check for a half-initialized area.  (See also similar check in
                               1025                 :                :              * AttachShmemIndexEntry())
                               1026                 :                :              */
                               1027         [ +  + ]:             12 :             if (!index_entry->initialized)
                               1028         [ +  - ]:              1 :                 ereport(ERROR,
                               1029                 :                :                         (errmsg("cannot attach to shared memory struct \"%s\" because it was not fully initialized",
                               1030                 :                :                                 request->options->name)));
  189                          1031                 :             11 :             found_any = true;
                               1032                 :                :         }
                               1033                 :                :         else
                               1034                 :                :         {
   24                          1035         [ +  + ]:             10 :             if (request->options->size == SHMEM_ATTACH_UNKNOWN_SIZE)
                               1036         [ +  - ]:              1 :                 ereport(ERROR,
                               1037                 :                :                         (errmsg("cannot attach to shared memory struct \"%s\" because it does not exist",
                               1038                 :                :                                 request->options->name),
                               1039                 :                :                          errdetail("SHMEM_ATTACH_UNKNOWN_SIZE can only be used to attach to an existing shared memory structure.")));
  189                          1040                 :              9 :             notfound_any = true;
                               1041                 :                :         }
                               1042                 :                :     }
                               1043   [ +  +  -  + ]:             20 :     if (found_any && notfound_any)
   97 heikki.linnakangas@i     1044         [ #  # ]:UBC           0 :         elog(ERROR, "some of the requested shmem areas have already been initialized");
                               1045                 :                : 
                               1046                 :                :     /*
                               1047                 :                :      * Allocate or attach all the shmem areas requested by the request_fn
                               1048                 :                :      * callback.
                               1049                 :                :      */
  189 heikki.linnakangas@i     1050   [ +  -  +  +  :CBC          56 :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                               1051                 :                :     {
                               1052         [ +  + ]:             20 :         if (found_any)
                               1053                 :             11 :             AttachShmemIndexEntry(request, false);
                               1054                 :                :         else
                               1055                 :              9 :             InitShmemIndexEntry(request);
                               1056                 :                :     }
                               1057                 :                : 
                               1058                 :                :     /* Finish by calling the appropriate subsystem-specific callback */
                               1059         [ +  + ]:             18 :     if (found_any)
                               1060                 :                :     {
                               1061         [ +  + ]:             10 :         if (callbacks->attach_fn)
                               1062                 :              6 :             callbacks->attach_fn(callbacks->opaque_arg);
                               1063                 :                :     }
                               1064                 :                :     else
                               1065                 :                :     {
                               1066         [ +  + ]:              8 :         if (callbacks->init_fn)
                               1067                 :              6 :             callbacks->init_fn(callbacks->opaque_arg);
                               1068                 :                :     }
                               1069                 :                : 
   45                          1070   [ +  -  +  +  :             51 :     foreach_ptr(ShmemRequest, request, pending_shmem_requests)
                                              +  + ]
                               1071                 :                :     {
                               1072                 :             17 :         request->index_entry->initialized = true;
                               1073                 :                :     }
                               1074                 :                : 
 7586 tgl@sss.pgh.pa.us        1075                 :             17 :     LWLockRelease(ShmemIndexLock);
  189 heikki.linnakangas@i     1076                 :             17 : }
                               1077                 :                : 
                               1078                 :                : /*
                               1079                 :                :  * Call all shmem request callbacks.
                               1080                 :                :  */
                               1081                 :                : void
                               1082                 :           1287 : ShmemCallRequestCallbacks(void)
                               1083                 :                : {
                               1084                 :                :     ListCell   *lc;
                               1085                 :                : 
                               1086         [ -  + ]:           1287 :     Assert(shmem_request_state == SRS_INITIAL);
                               1087                 :           1287 :     shmem_request_state = SRS_REQUESTING;
                               1088                 :                : 
                               1089   [ +  -  +  +  :          57941 :     foreach(lc, registered_shmem_callbacks)
                                              +  + ]
                               1090                 :                :     {
                               1091                 :          56655 :         const ShmemCallbacks *callbacks = (const ShmemCallbacks *) lfirst(lc);
                               1092                 :                : 
                               1093         [ +  - ]:          56655 :         if (callbacks->request_fn)
                               1094                 :          56655 :             callbacks->request_fn(callbacks->opaque_arg);
                               1095                 :                :     }
11052 scrappy@hub.org          1096                 :           1286 : }
                               1097                 :                : 
                               1098                 :                : /*
                               1099                 :                :  * ShmemInitStruct -- Create/attach to a structure in shared memory.
                               1100                 :                :  *
                               1101                 :                :  *      This is called during initialization to find or allocate
                               1102                 :                :  *      a data structure in shared memory.  If no other process
                               1103                 :                :  *      has created the structure, this routine allocates space
                               1104                 :                :  *      for it.  If it exists already, a pointer to the existing
                               1105                 :                :  *      structure is returned.
                               1106                 :                :  *
                               1107                 :                :  *  Returns: pointer to the object.  *foundPtr is set true if the object was
                               1108                 :                :  *      already in the shmem index (hence, already initialized).
                               1109                 :                :  *
                               1110                 :                :  * Note: This is a legacy interface, kept for backwards compatibility with
                               1111                 :                :  * extensions.  Use ShmemRequestStruct() in new code!
                               1112                 :                :  */
                               1113                 :                : void *
  189 heikki.linnakangas@i     1114                 :UBC           0 : ShmemInitStruct(const char *name, Size size, bool *foundPtr)
                               1115                 :                : {
                               1116                 :              0 :     void       *ptr = NULL;
                               1117                 :              0 :     ShmemStructOpts options = {
                               1118                 :                :         .name = name,
                               1119                 :                :         .size = size,
                               1120                 :                :         .ptr = &ptr,
                               1121                 :                :     };
                               1122                 :              0 :     ShmemRequest request = {&options, SHMEM_KIND_STRUCT};
                               1123                 :                : 
                               1124   [ #  #  #  #  :              0 :     Assert(shmem_request_state == SRS_DONE ||
                                              #  # ]
                               1125                 :                :            shmem_request_state == SRS_INITIALIZING ||
                               1126                 :                :            shmem_request_state == SRS_REQUESTING);
                               1127                 :                : 
                               1128                 :              0 :     LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
                               1129                 :                : 
                               1130                 :                :     /* Look up the existing entry if any */
   18                          1131                 :              0 :     *foundPtr = AttachShmemIndexEntry(&request, true);
                               1132                 :                : 
                               1133                 :                :     /* Initialize it if not found */
  189                          1134         [ #  # ]:              0 :     if (!*foundPtr)
                               1135                 :                :     {
                               1136                 :              0 :         InitShmemIndexEntry(&request);
                               1137                 :                :         /* no additional initialization needed */
   45                          1138                 :              0 :         request.index_entry->initialized = true;
                               1139                 :                :     }
                               1140                 :                : 
  189                          1141                 :              0 :     LWLockRelease(ShmemIndexLock);
                               1142                 :                : 
                               1143         [ #  # ]:              0 :     Assert(ptr != NULL);
                               1144                 :              0 :     return ptr;
                               1145                 :                : }
                               1146                 :                : 
                               1147                 :                : /* SQL SRF showing allocated shared memory */
                               1148                 :                : Datum
 2468 rhaas@postgresql.org     1149                 :CBC           4 : pg_get_shmem_allocations(PG_FUNCTION_ARGS)
                               1150                 :                : {
                               1151                 :                : #define PG_GET_SHMEM_SIZES_COLS 4
                               1152                 :              4 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
                               1153                 :                :     HASH_SEQ_STATUS hstat;
                               1154                 :                :     ShmemIndexEnt *ent;
 2342 tgl@sss.pgh.pa.us        1155                 :              4 :     Size        named_allocated = 0;
                               1156                 :                :     Datum       values[PG_GET_SHMEM_SIZES_COLS];
                               1157                 :                :     bool        nulls[PG_GET_SHMEM_SIZES_COLS];
                               1158                 :                : 
 1455 michael@paquier.xyz      1159                 :              4 :     InitMaterializedSRF(fcinfo, 0);
                               1160                 :                : 
 2468 rhaas@postgresql.org     1161                 :              4 :     LWLockAcquire(ShmemIndexLock, LW_SHARED);
                               1162                 :                : 
                               1163                 :              4 :     hash_seq_init(&hstat, ShmemIndex);
                               1164                 :                : 
                               1165                 :                :     /* output all allocated entries */
                               1166                 :              4 :     memset(nulls, 0, sizeof(nulls));
                               1167         [ +  + ]:            326 :     while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
                               1168                 :                :     {
                               1169                 :            322 :         values[0] = CStringGetTextDatum(ent->key);
                               1170                 :            322 :         values[1] = Int64GetDatum((char *) ent->location - (char *) ShmemSegHdr);
                               1171                 :            322 :         values[2] = Int64GetDatum(ent->size);
                               1172                 :            322 :         values[3] = Int64GetDatum(ent->allocated_size);
                               1173                 :            322 :         named_allocated += ent->allocated_size;
                               1174                 :                : 
 1680 michael@paquier.xyz      1175                 :            322 :         tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
                               1176                 :                :                              values, nulls);
                               1177                 :                :     }
                               1178                 :                : 
                               1179                 :                :     /* output shared memory allocated but not counted via the shmem index */
 2468 rhaas@postgresql.org     1180                 :              4 :     values[0] = CStringGetTextDatum("<anonymous>");
                               1181                 :              4 :     nulls[1] = true;
  255 heikki.linnakangas@i     1182                 :              4 :     values[2] = Int64GetDatum(ShmemAllocator->free_offset - named_allocated);
 2468 rhaas@postgresql.org     1183                 :              4 :     values[3] = values[2];
 1680 michael@paquier.xyz      1184                 :              4 :     tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
                               1185                 :                : 
                               1186                 :                :     /* output as-of-yet unused shared memory */
 2468 rhaas@postgresql.org     1187                 :              4 :     nulls[0] = true;
  255 heikki.linnakangas@i     1188                 :              4 :     values[1] = Int64GetDatum(ShmemAllocator->free_offset);
 2468 rhaas@postgresql.org     1189                 :              4 :     nulls[1] = false;
  255 heikki.linnakangas@i     1190                 :              4 :     values[2] = Int64GetDatum(ShmemSegHdr->totalsize - ShmemAllocator->free_offset);
 2468 rhaas@postgresql.org     1191                 :              4 :     values[3] = values[2];
 1680 michael@paquier.xyz      1192                 :              4 :     tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
                               1193                 :                : 
 2468 rhaas@postgresql.org     1194                 :              4 :     LWLockRelease(ShmemIndexLock);
                               1195                 :                : 
                               1196                 :              4 :     return (Datum) 0;
                               1197                 :                : }
                               1198                 :                : 
                               1199                 :                : /*
                               1200                 :                :  * SQL SRF showing NUMA memory nodes for allocated shared memory
                               1201                 :                :  *
                               1202                 :                :  * Compared to pg_get_shmem_allocations(), this function does not return
                               1203                 :                :  * information about shared anonymous allocations and unused shared memory.
                               1204                 :                :  */
                               1205                 :                : Datum
  553 tomas.vondra@postgre     1206                 :              4 : pg_get_shmem_allocations_numa(PG_FUNCTION_ARGS)
                               1207                 :                : {
                               1208                 :                : #define PG_GET_SHMEM_NUMA_SIZES_COLS 3
                               1209                 :              4 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
                               1210                 :                :     HASH_SEQ_STATUS hstat;
                               1211                 :                :     ShmemIndexEnt *ent;
                               1212                 :                :     Datum       values[PG_GET_SHMEM_NUMA_SIZES_COLS];
                               1213                 :                :     bool        nulls[PG_GET_SHMEM_NUMA_SIZES_COLS];
                               1214                 :                :     Size        os_page_size;
                               1215                 :                :     void      **page_ptrs;
                               1216                 :                :     int        *pages_status;
                               1217                 :                :     uint64      shm_total_page_count,
                               1218                 :                :                 shm_ent_page_count,
                               1219                 :                :                 max_nodes;
                               1220                 :                :     Size       *nodes;
                               1221                 :                : 
                               1222         [ +  - ]:              4 :     if (pg_numa_init() == -1)
   20 michael@paquier.xyz      1223         [ +  - ]:GNC           4 :         ereport(ERROR,
                               1224                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1225                 :                :                  errmsg("libnuma initialization failed or NUMA is not supported on this platform")));
                               1226                 :                : 
  553 tomas.vondra@postgre     1227                 :UBC           0 :     InitMaterializedSRF(fcinfo, 0);
                               1228                 :                : 
                               1229                 :              0 :     max_nodes = pg_numa_get_max_node();
  259                          1230                 :              0 :     nodes = palloc_array(Size, max_nodes + 2);
                               1231                 :                : 
                               1232                 :                :     /*
                               1233                 :                :      * Shared memory allocations can vary in size and may not align with OS
                               1234                 :                :      * memory page boundaries, while NUMA queries work on pages.
                               1235                 :                :      *
                               1236                 :                :      * To correctly map each allocation to NUMA nodes, we need to: 1.
                               1237                 :                :      * Determine the OS memory page size. 2. Align each allocation's start/end
                               1238                 :                :      * addresses to page boundaries. 3. Query NUMA node information for all
                               1239                 :                :      * pages spanning the allocation.
                               1240                 :                :      */
  551                          1241                 :              0 :     os_page_size = pg_get_shmem_pagesize();
                               1242                 :                : 
                               1243                 :                :     /*
                               1244                 :                :      * Allocate memory for page pointers and status based on total shared
                               1245                 :                :      * memory size. This simplified approach allocates enough space for all
                               1246                 :                :      * pages in shared memory rather than calculating the exact requirements
                               1247                 :                :      * for each segment.
                               1248                 :                :      *
                               1249                 :                :      * Add 1, because we don't know how exactly the segments align to OS
                               1250                 :                :      * pages, so the allocation might use one more memory page. In practice
                               1251                 :                :      * this is not very likely, and moreover we have more entries, each of
                               1252                 :                :      * them using only fraction of the total pages.
                               1253                 :                :      */
  553                          1254                 :              0 :     shm_total_page_count = (ShmemSegHdr->totalsize / os_page_size) + 1;
  306 michael@paquier.xyz      1255                 :              0 :     page_ptrs = palloc0_array(void *, shm_total_page_count);
                               1256                 :              0 :     pages_status = palloc_array(int, shm_total_page_count);
                               1257                 :                : 
  553 tomas.vondra@postgre     1258         [ #  # ]:              0 :     if (firstNumaTouch)
                               1259         [ #  # ]:              0 :         elog(DEBUG1, "NUMA: page-faulting shared memory segments for proper NUMA readouts");
                               1260                 :                : 
                               1261                 :              0 :     LWLockAcquire(ShmemIndexLock, LW_SHARED);
                               1262                 :                : 
                               1263                 :              0 :     hash_seq_init(&hstat, ShmemIndex);
                               1264                 :                : 
                               1265                 :                :     /* output all allocated entries */
                               1266         [ #  # ]:              0 :     while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
                               1267                 :                :     {
                               1268                 :                :         char       *startptr,
                               1269                 :                :                    *endptr;
                               1270                 :                :         Size        total_len;
                               1271                 :                : 
                               1272                 :                :         /*
                               1273                 :                :          * Calculate the range of OS pages used by this segment. The segment
                               1274                 :                :          * may start / end half-way through a page, we want to count these
                               1275                 :                :          * pages too. So we align the start/end pointers down/up, and then
                               1276                 :                :          * calculate the number of pages from that.
                               1277                 :                :          */
                               1278                 :              0 :         startptr = (char *) TYPEALIGN_DOWN(os_page_size, ent->location);
                               1279                 :              0 :         endptr = (char *) TYPEALIGN(os_page_size,
                               1280                 :                :                                     (char *) ent->location + ent->allocated_size);
                               1281                 :              0 :         total_len = (endptr - startptr);
                               1282                 :                : 
                               1283                 :              0 :         shm_ent_page_count = total_len / os_page_size;
                               1284                 :                : 
                               1285                 :                :         /*
                               1286                 :                :          * If we ever get 0xff (-1) back from kernel inquiry, then we probably
                               1287                 :                :          * have a bug in mapping buffers to OS pages.
                               1288                 :                :          */
                               1289                 :              0 :         memset(pages_status, 0xff, sizeof(int) * shm_ent_page_count);
                               1290                 :                : 
                               1291                 :                :         /*
                               1292                 :                :          * Setup page_ptrs[] with pointers to all OS pages for this segment,
                               1293                 :                :          * and get the NUMA status using pg_numa_query_pages.
                               1294                 :                :          *
                               1295                 :                :          * In order to get reliable results we also need to touch memory
                               1296                 :                :          * pages, so that inquiry about NUMA memory node doesn't return -2
                               1297                 :                :          * (ENOENT, which indicates unmapped/unallocated pages).
                               1298                 :                :          */
   93 peter@eisentraut.org     1299         [ #  # ]:UNC           0 :         for (uint64 i = 0; i < shm_ent_page_count; i++)
                               1300                 :                :         {
  553 tomas.vondra@postgre     1301                 :UBC           0 :             page_ptrs[i] = startptr + (i * os_page_size);
                               1302                 :                : 
                               1303                 :              0 :             if (firstNumaTouch)
                               1304                 :                :                 pg_numa_touch_mem_if_required(page_ptrs[i]);
                               1305                 :                : 
                               1306         [ #  # ]:              0 :             CHECK_FOR_INTERRUPTS();
                               1307                 :                :         }
                               1308                 :                : 
                               1309         [ #  # ]:              0 :         if (pg_numa_query_pages(0, shm_ent_page_count, page_ptrs, pages_status) == -1)
                               1310         [ #  # ]:              0 :             elog(ERROR, "failed NUMA pages inquiry status: %m");
                               1311                 :                : 
                               1312                 :                :         /* Count number of NUMA nodes used for this shared memory entry */
  259                          1313                 :              0 :         memset(nodes, 0, sizeof(Size) * (max_nodes + 2));
                               1314                 :                : 
   93 peter@eisentraut.org     1315         [ #  # ]:UNC           0 :         for (uint64 i = 0; i < shm_ent_page_count; i++)
                               1316                 :                :         {
  553 tomas.vondra@postgre     1317                 :UBC           0 :             int         s = pages_status[i];
                               1318                 :                : 
                               1319                 :                :             /* Ensure we are adding only valid index to the array */
  259                          1320   [ #  #  #  # ]:              0 :             if (s >= 0 && s <= max_nodes)
                               1321                 :                :             {
                               1322                 :                :                 /* valid NUMA node */
                               1323                 :              0 :                 nodes[s]++;
                               1324                 :              0 :                 continue;
                               1325                 :                :             }
                               1326         [ #  # ]:              0 :             else if (s == -2)
                               1327                 :                :             {
                               1328                 :                :                 /* -2 means ENOENT (e.g. page was moved to swap) */
                               1329                 :              0 :                 nodes[max_nodes + 1]++;
                               1330                 :              0 :                 continue;
                               1331                 :                :             }
                               1332                 :                : 
                               1333         [ #  # ]:              0 :             elog(ERROR, "invalid NUMA node id outside of allowed range "
                               1334                 :                :                  "[0, " UINT64_FORMAT "]: %d", max_nodes, s);
                               1335                 :                :         }
                               1336                 :                : 
                               1337                 :                :         /* no NULLs for regular nodes */
                               1338                 :              0 :         memset(nulls, 0, sizeof(nulls));
                               1339                 :                : 
                               1340                 :                :         /*
                               1341                 :                :          * Add one entry for each NUMA node, including those without allocated
                               1342                 :                :          * memory for this segment.
                               1343                 :                :          */
   93 peter@eisentraut.org     1344         [ #  # ]:UNC           0 :         for (uint64 i = 0; i <= max_nodes; i++)
                               1345                 :                :         {
  553 tomas.vondra@postgre     1346                 :UBC           0 :             values[0] = CStringGetTextDatum(ent->key);
  430 peter@eisentraut.org     1347                 :              0 :             values[1] = Int32GetDatum(i);
  553 tomas.vondra@postgre     1348                 :              0 :             values[2] = Int64GetDatum(nodes[i] * os_page_size);
                               1349                 :                : 
                               1350                 :              0 :             tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
                               1351                 :                :                                  values, nulls);
                               1352                 :                :         }
                               1353                 :                : 
                               1354                 :                :         /* The last entry is used for pages without a NUMA node. */
  259                          1355                 :              0 :         nulls[1] = true;
                               1356                 :              0 :         values[0] = CStringGetTextDatum(ent->key);
                               1357                 :              0 :         values[2] = Int64GetDatum(nodes[max_nodes + 1] * os_page_size);
                               1358                 :                : 
                               1359                 :              0 :         tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
                               1360                 :                :                              values, nulls);
                               1361                 :                :     }
                               1362                 :                : 
  553                          1363                 :              0 :     LWLockRelease(ShmemIndexLock);
                               1364                 :              0 :     firstNumaTouch = false;
                               1365                 :                : 
                               1366                 :              0 :     return (Datum) 0;
                               1367                 :                : }
                               1368                 :                : 
                               1369                 :                : /*
                               1370                 :                :  * Determine the memory page size used for the shared memory segment.
                               1371                 :                :  *
                               1372                 :                :  * If the shared segment was allocated using huge pages, returns the size of
                               1373                 :                :  * a huge page. Otherwise returns the size of regular memory page.
                               1374                 :                :  *
                               1375                 :                :  * This should be used only after shared memory has been initialized.
                               1376                 :                :  */
                               1377                 :                : Size
  551 tomas.vondra@postgre     1378                 :CBC           2 : pg_get_shmem_pagesize(void)
                               1379                 :                : {
                               1380                 :                :     Size        os_page_size;
                               1381                 :                : #ifdef WIN32
                               1382                 :                :     SYSTEM_INFO sysinfo;
                               1383                 :                : 
                               1384                 :                :     GetSystemInfo(&sysinfo);
                               1385                 :                :     os_page_size = sysinfo.dwPageSize;
                               1386                 :                : #else
                               1387                 :              2 :     os_page_size = sysconf(_SC_PAGESIZE);
                               1388                 :                : #endif
                               1389                 :                : 
                               1390         [ -  + ]:              2 :     Assert(huge_pages_status != HUGE_PAGES_UNKNOWN);
                               1391                 :                : 
                               1392         [ -  + ]:              2 :     if (huge_pages_status == HUGE_PAGES_ON)
  551 tomas.vondra@postgre     1393                 :UBC           0 :         GetHugePageSize(&os_page_size, NULL);
                               1394                 :                : 
  551 tomas.vondra@postgre     1395                 :CBC           2 :     return os_page_size;
                               1396                 :                : }
                               1397                 :                : 
                               1398                 :                : Datum
                               1399                 :              5 : pg_numa_available(PG_FUNCTION_ARGS)
                               1400                 :                : {
                               1401                 :              5 :     PG_RETURN_BOOL(pg_numa_init() != -1);
                               1402                 :                : }
        

Generated by: LCOV version 2.0-1