PostgreSQL Source Code git master
Loading...
Searching...
No Matches
shmem.c File Reference
#include "postgres.h"
#include "common/int.h"
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "port/pg_numa.h"
#include "storage/lwlock.h"
#include "storage/pg_shmem.h"
#include "storage/shmem.h"
#include "storage/spin.h"
#include "utils/builtins.h"
Include dependency graph for shmem.c:

Go to the source code of this file.

Data Structures

struct  ShmemAllocatorData
 

Macros

#define PG_GET_SHMEM_SIZES_COLS   4
 
#define PG_GET_SHMEM_NUMA_SIZES_COLS   3
 

Typedefs

typedef struct ShmemAllocatorData ShmemAllocatorData
 

Functions

static void * ShmemAllocRaw (Size size, Size *allocated_size)
 
Datum pg_numa_available (PG_FUNCTION_ARGS)
 
void InitShmemAllocator (PGShmemHeader *seghdr)
 
void * ShmemAlloc (Size size)
 
void * ShmemAllocNoError (Size size)
 
bool ShmemAddrIsValid (const void *addr)
 
void InitShmemIndex (void)
 
HTABShmemInitHash (const char *name, int64 init_size, int64 max_size, HASHCTL *infoP, int hash_flags)
 
void * ShmemInitStruct (const char *name, Size size, bool *foundPtr)
 
Size add_size (Size s1, Size s2)
 
Size mul_size (Size s1, Size s2)
 
Datum pg_get_shmem_allocations (PG_FUNCTION_ARGS)
 
Datum pg_get_shmem_allocations_numa (PG_FUNCTION_ARGS)
 
Size pg_get_shmem_pagesize (void)
 

Variables

static PGShmemHeaderShmemSegHdr
 
static void * ShmemBase
 
static void * ShmemEnd
 
static ShmemAllocatorDataShmemAllocator
 
slock_t * ShmemLock
 
static HTABShmemIndex = NULL
 
static bool firstNumaTouch = true
 

Macro Definition Documentation

◆ PG_GET_SHMEM_NUMA_SIZES_COLS

#define PG_GET_SHMEM_NUMA_SIZES_COLS   3

◆ PG_GET_SHMEM_SIZES_COLS

#define PG_GET_SHMEM_SIZES_COLS   4

Typedef Documentation

◆ ShmemAllocatorData

Function Documentation

◆ add_size()

Size add_size ( Size  s1,
Size  s2 
)

Definition at line 482 of file shmem.c.

483{
484 Size result;
485
486 if (pg_add_size_overflow(s1, s2, &result))
488 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
489 errmsg("requested shared memory size overflows size_t")));
490 return result;
491}
size_t Size
Definition c.h:631
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
static bool pg_add_size_overflow(size_t a, size_t b, size_t *result)
Definition int.h:608
char * s1
char * s2

References ereport, errcode(), errmsg(), ERROR, pg_add_size_overflow(), s1, and s2.

Referenced by _brin_parallel_estimate_shared(), _bt_parallel_estimate_shared(), _gin_parallel_estimate_shared(), AioShmemSize(), ApplyLauncherShmemSize(), AsyncShmemInit(), AsyncShmemSize(), AutoVacuumShmemSize(), BackendStatusShmemSize(), BackgroundWorkerShmemSize(), btestimateparallelscan(), BTreeShmemSize(), BufferManagerShmemSize(), CalculateShmemSize(), CheckpointerShmemSize(), CreateAnonymousSegment(), estimate_variable_size(), EstimateClientConnectionInfoSpace(), EstimateComboCIDStateSpace(), EstimateGUCStateSpace(), EstimateLibraryStateSpace(), EstimateParamExecSpace(), EstimateParamListSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), ExecAggEstimate(), ExecAppendEstimate(), ExecBitmapHeapEstimate(), ExecBitmapHeapInitializeDSM(), ExecHashEstimate(), ExecIncrementalSortEstimate(), ExecMemoizeEstimate(), ExecSortEstimate(), expand_planner_arrays(), FastPathLockShmemSize(), hash_estimate_size(), index_parallelscan_estimate(), index_parallelscan_initialize(), InitializeShmemGUCs(), InjectionPointShmemSize(), LockManagerShmemSize(), LWLockShmemSize(), MultiXactShmemSize(), pgaio_worker_shmem_size(), PgArchShmemSize(), PGProcShmemSize(), pgss_memsize(), PMSignalShmemSize(), PredicateLockShmemInit(), PredicateLockShmemSize(), ProcArrayShmemInit(), ProcArrayShmemSize(), ProcGlobalShmemSize(), ProcSignalShmemSize(), ReplicationOriginShmemSize(), ReplicationSlotsShmemSize(), RequestAddinShmemSpace(), SerializeTransactionState(), SharedInvalShmemSize(), shm_toc_estimate(), StatsShmemSize(), StrategyShmemSize(), table_parallelscan_estimate(), tuplesort_estimate_shared(), TwoPhaseShmemSize(), WaitEventCustomShmemSize(), WaitLSNShmemSize(), WalRcvShmemSize(), WalSndShmemSize(), and XLOGShmemSize().

◆ InitShmemAllocator()

void InitShmemAllocator ( PGShmemHeader seghdr)

Definition at line 122 of file shmem.c.

123{
124 Assert(seghdr != NULL);
125
126 /*
127 * We assume the pointer and offset are MAXALIGN. Not a hard requirement,
128 * but it's true today and keeps the math below simpler.
129 */
130 Assert(seghdr == (void *) MAXALIGN(seghdr));
131 Assert(seghdr->content_offset == MAXALIGN(seghdr->content_offset));
132
133 ShmemSegHdr = seghdr;
134 ShmemBase = seghdr;
135 ShmemEnd = (char *) ShmemBase + seghdr->totalsize;
136
137#ifndef EXEC_BACKEND
139#endif
141 {
142 PGShmemHeader *shmhdr = ShmemSegHdr;
143
144 ShmemAllocator = (ShmemAllocatorData *) ((char *) shmhdr + shmhdr->content_offset);
146 }
147 else
148 {
149 Size offset;
150
151 /*
152 * Allocations after this point should go through ShmemAlloc, which
153 * expects to allocate everything on cache line boundaries. Make sure
154 * the first allocation begins on a cache line boundary.
155 */
156 offset = CACHELINEALIGN(seghdr->content_offset + sizeof(ShmemAllocatorData));
157 if (offset > seghdr->totalsize)
159 (errcode(ERRCODE_OUT_OF_MEMORY),
160 errmsg("out of shared memory (%zu bytes requested)",
161 offset)));
162
163 ShmemAllocator = (ShmemAllocatorData *) ((char *) seghdr + seghdr->content_offset);
164
167 ShmemAllocator->free_offset = offset;
168 /* ShmemIndex can't be set up yet (need LWLocks first) */
169 ShmemAllocator->index = NULL;
170 ShmemIndex = (HTAB *) NULL;
171 }
172}
#define CACHELINEALIGN(LEN)
Definition c.h:841
#define MAXALIGN(LEN)
Definition c.h:838
#define Assert(condition)
Definition c.h:885
bool IsUnderPostmaster
Definition globals.c:120
static void * ShmemBase
Definition shmem.c:101
static void * ShmemEnd
Definition shmem.c:102
slock_t * ShmemLock
Definition shmem.c:105
static PGShmemHeader * ShmemSegHdr
Definition shmem.c:100
static HTAB * ShmemIndex
Definition shmem.c:106
static ShmemAllocatorData * ShmemAllocator
Definition shmem.c:104
static void SpinLockInit(volatile slock_t *lock)
Definition spin.h:50
Size totalsize
Definition pg_shmem.h:34
Size content_offset
Definition pg_shmem.h:35
slock_t shmem_lock
Definition shmem.c:93

References Assert, CACHELINEALIGN, PGShmemHeader::content_offset, ereport, errcode(), errmsg(), ERROR, ShmemAllocatorData::free_offset, ShmemAllocatorData::index, IsUnderPostmaster, MAXALIGN, ShmemAllocatorData::shmem_lock, ShmemAllocator, ShmemBase, ShmemEnd, ShmemIndex, ShmemLock, ShmemSegHdr, SpinLockInit(), and PGShmemHeader::totalsize.

Referenced by CreateSharedMemoryAndSemaphores().

◆ InitShmemIndex()

void InitShmemIndex ( void  )

Definition at line 274 of file shmem.c.

275{
276 HASHCTL info;
277
278 /*
279 * Create the shared memory shmem index.
280 *
281 * Since ShmemInitHash calls ShmemInitStruct, which expects the ShmemIndex
282 * hashtable to exist already, we have a bit of a circularity problem in
283 * initializing the ShmemIndex itself. The special "ShmemIndex" hash
284 * table name will tell ShmemInitStruct to fake it.
285 */
287 info.entrysize = sizeof(ShmemIndexEnt);
288
289 ShmemIndex = ShmemInitHash("ShmemIndex",
291 &info,
293}
#define HASH_STRINGS
Definition hsearch.h:96
#define HASH_ELEM
Definition hsearch.h:95
HTAB * ShmemInitHash(const char *name, int64 init_size, int64 max_size, HASHCTL *infoP, int hash_flags)
Definition shmem.c:323
#define SHMEM_INDEX_SIZE
Definition shmem.h:52
#define SHMEM_INDEX_KEYSIZE
Definition shmem.h:50
Size keysize
Definition hsearch.h:75
Size entrysize
Definition hsearch.h:76

References HASHCTL::entrysize, HASH_ELEM, HASH_STRINGS, HASHCTL::keysize, SHMEM_INDEX_KEYSIZE, SHMEM_INDEX_SIZE, ShmemIndex, and ShmemInitHash().

Referenced by CreateOrAttachShmemStructs().

◆ mul_size()

Size mul_size ( Size  s1,
Size  s2 
)

Definition at line 497 of file shmem.c.

498{
499 Size result;
500
501 if (pg_mul_size_overflow(s1, s2, &result))
503 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
504 errmsg("requested shared memory size overflows size_t")));
505 return result;
506}
static bool pg_mul_size_overflow(size_t a, size_t b, size_t *result)
Definition int.h:642

References ereport, errcode(), errmsg(), ERROR, pg_mul_size_overflow(), s1, and s2.

Referenced by _brin_begin_parallel(), _bt_begin_parallel(), _gin_begin_parallel(), AioBackendShmemSize(), AioHandleDataShmemSize(), AioHandleIOVShmemSize(), AioHandleShmemSize(), ApplyLauncherShmemSize(), AsyncShmemInit(), AsyncShmemSize(), AutoVacuumShmemSize(), BackendStatusShmemInit(), BackendStatusShmemSize(), BackgroundWorkerShmemSize(), BTreeShmemSize(), BufferManagerShmemSize(), CheckpointerShmemSize(), EstimateComboCIDStateSpace(), EstimatePendingSyncsSpace(), EstimateReindexStateSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), ExecAggEstimate(), ExecBitmapHeapEstimate(), ExecBitmapHeapInitializeDSM(), ExecHashEstimate(), ExecIncrementalSortEstimate(), ExecInitParallelPlan(), ExecMemoizeEstimate(), ExecParallelRetrieveInstrumentation(), ExecParallelRetrieveJitInstrumentation(), ExecParallelSetupTupleQueues(), ExecSortEstimate(), FastPathLockShmemSize(), hash_estimate_size(), InitializeParallelDSM(), LWLockShmemSize(), parallel_vacuum_init(), PGProcShmemSize(), PGSemaphoreShmemSize(), PMSignalShmemSize(), PredicateLockShmemInit(), PredicateLockShmemSize(), ProcArrayShmemInit(), ProcArrayShmemSize(), ProcSignalShmemSize(), ReplicationOriginShmemSize(), ReplicationSlotsShmemSize(), SharedInvalShmemSize(), shm_toc_estimate(), tuplesort_estimate_shared(), TwoPhaseShmemSize(), WaitLSNShmemSize(), WalSndShmemSize(), and XLOGShmemSize().

◆ pg_get_shmem_allocations()

Datum pg_get_shmem_allocations ( PG_FUNCTION_ARGS  )

Definition at line 510 of file shmem.c.

511{
512#define PG_GET_SHMEM_SIZES_COLS 4
513 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
514 HASH_SEQ_STATUS hstat;
515 ShmemIndexEnt *ent;
516 Size named_allocated = 0;
518 bool nulls[PG_GET_SHMEM_SIZES_COLS];
519
520 InitMaterializedSRF(fcinfo, 0);
521
522 LWLockAcquire(ShmemIndexLock, LW_SHARED);
523
524 hash_seq_init(&hstat, ShmemIndex);
525
526 /* output all allocated entries */
527 memset(nulls, 0, sizeof(nulls));
528 while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
529 {
530 values[0] = CStringGetTextDatum(ent->key);
531 values[1] = Int64GetDatum((char *) ent->location - (char *) ShmemSegHdr);
532 values[2] = Int64GetDatum(ent->size);
534 named_allocated += ent->allocated_size;
535
536 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
537 values, nulls);
538 }
539
540 /* output shared memory allocated but not counted via the shmem index */
541 values[0] = CStringGetTextDatum("<anonymous>");
542 nulls[1] = true;
543 values[2] = Int64GetDatum(ShmemAllocator->free_offset - named_allocated);
544 values[3] = values[2];
545 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
546
547 /* output as-of-yet unused shared memory */
548 nulls[0] = true;
550 nulls[1] = false;
552 values[3] = values[2];
553 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
554
555 LWLockRelease(ShmemIndexLock);
556
557 return (Datum) 0;
558}
static Datum values[MAXATTR]
Definition bootstrap.c:147
#define CStringGetTextDatum(s)
Definition builtins.h:98
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1380
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition funcapi.c:76
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1176
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1793
@ LW_SHARED
Definition lwlock.h:113
static Datum Int64GetDatum(int64 X)
Definition postgres.h:423
uint64_t Datum
Definition postgres.h:70
#define PG_GET_SHMEM_SIZES_COLS
void * location
Definition shmem.h:58
Size size
Definition shmem.h:59
Size allocated_size
Definition shmem.h:60
char key[SHMEM_INDEX_KEYSIZE]
Definition shmem.h:57
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:784

References ShmemIndexEnt::allocated_size, CStringGetTextDatum, ShmemAllocatorData::free_offset, hash_seq_init(), hash_seq_search(), InitMaterializedSRF(), Int64GetDatum(), ShmemIndexEnt::key, ShmemIndexEnt::location, LW_SHARED, LWLockAcquire(), LWLockRelease(), PG_GET_SHMEM_SIZES_COLS, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, ShmemAllocator, ShmemIndex, ShmemSegHdr, ShmemIndexEnt::size, PGShmemHeader::totalsize, tuplestore_putvalues(), and values.

◆ pg_get_shmem_allocations_numa()

Datum pg_get_shmem_allocations_numa ( PG_FUNCTION_ARGS  )

Definition at line 567 of file shmem.c.

568{
569#define PG_GET_SHMEM_NUMA_SIZES_COLS 3
570 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
571 HASH_SEQ_STATUS hstat;
572 ShmemIndexEnt *ent;
575 Size os_page_size;
576 void **page_ptrs;
577 int *pages_status;
578 uint64 shm_total_page_count,
579 shm_ent_page_count,
580 max_nodes;
581 Size *nodes;
582
583 if (pg_numa_init() == -1)
584 elog(ERROR, "libnuma initialization failed or NUMA is not supported on this platform");
585
586 InitMaterializedSRF(fcinfo, 0);
587
588 max_nodes = pg_numa_get_max_node();
589 nodes = palloc_array(Size, max_nodes + 2);
590
591 /*
592 * Shared memory allocations can vary in size and may not align with OS
593 * memory page boundaries, while NUMA queries work on pages.
594 *
595 * To correctly map each allocation to NUMA nodes, we need to: 1.
596 * Determine the OS memory page size. 2. Align each allocation's start/end
597 * addresses to page boundaries. 3. Query NUMA node information for all
598 * pages spanning the allocation.
599 */
600 os_page_size = pg_get_shmem_pagesize();
601
602 /*
603 * Allocate memory for page pointers and status based on total shared
604 * memory size. This simplified approach allocates enough space for all
605 * pages in shared memory rather than calculating the exact requirements
606 * for each segment.
607 *
608 * Add 1, because we don't know how exactly the segments align to OS
609 * pages, so the allocation might use one more memory page. In practice
610 * this is not very likely, and moreover we have more entries, each of
611 * them using only fraction of the total pages.
612 */
613 shm_total_page_count = (ShmemSegHdr->totalsize / os_page_size) + 1;
614 page_ptrs = palloc0_array(void *, shm_total_page_count);
615 pages_status = palloc_array(int, shm_total_page_count);
616
617 if (firstNumaTouch)
618 elog(DEBUG1, "NUMA: page-faulting shared memory segments for proper NUMA readouts");
619
620 LWLockAcquire(ShmemIndexLock, LW_SHARED);
621
622 hash_seq_init(&hstat, ShmemIndex);
623
624 /* output all allocated entries */
625 while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
626 {
627 int i;
628 char *startptr,
629 *endptr;
630 Size total_len;
631
632 /*
633 * Calculate the range of OS pages used by this segment. The segment
634 * may start / end half-way through a page, we want to count these
635 * pages too. So we align the start/end pointers down/up, and then
636 * calculate the number of pages from that.
637 */
638 startptr = (char *) TYPEALIGN_DOWN(os_page_size, ent->location);
639 endptr = (char *) TYPEALIGN(os_page_size,
640 (char *) ent->location + ent->allocated_size);
641 total_len = (endptr - startptr);
642
643 shm_ent_page_count = total_len / os_page_size;
644
645 /*
646 * If we ever get 0xff (-1) back from kernel inquiry, then we probably
647 * have a bug in mapping buffers to OS pages.
648 */
649 memset(pages_status, 0xff, sizeof(int) * shm_ent_page_count);
650
651 /*
652 * Setup page_ptrs[] with pointers to all OS pages for this segment,
653 * and get the NUMA status using pg_numa_query_pages.
654 *
655 * In order to get reliable results we also need to touch memory
656 * pages, so that inquiry about NUMA memory node doesn't return -2
657 * (ENOENT, which indicates unmapped/unallocated pages).
658 */
659 for (i = 0; i < shm_ent_page_count; i++)
660 {
661 page_ptrs[i] = startptr + (i * os_page_size);
662
663 if (firstNumaTouch)
665
667 }
668
669 if (pg_numa_query_pages(0, shm_ent_page_count, page_ptrs, pages_status) == -1)
670 elog(ERROR, "failed NUMA pages inquiry status: %m");
671
672 /* Count number of NUMA nodes used for this shared memory entry */
673 memset(nodes, 0, sizeof(Size) * (max_nodes + 2));
674
675 for (i = 0; i < shm_ent_page_count; i++)
676 {
677 int s = pages_status[i];
678
679 /* Ensure we are adding only valid index to the array */
680 if (s >= 0 && s <= max_nodes)
681 {
682 /* valid NUMA node */
683 nodes[s]++;
684 continue;
685 }
686 else if (s == -2)
687 {
688 /* -2 means ENOENT (e.g. page was moved to swap) */
689 nodes[max_nodes + 1]++;
690 continue;
691 }
692
693 elog(ERROR, "invalid NUMA node id outside of allowed range "
694 "[0, " UINT64_FORMAT "]: %d", max_nodes, s);
695 }
696
697 /* no NULLs for regular nodes */
698 memset(nulls, 0, sizeof(nulls));
699
700 /*
701 * Add one entry for each NUMA node, including those without allocated
702 * memory for this segment.
703 */
704 for (i = 0; i <= max_nodes; i++)
705 {
706 values[0] = CStringGetTextDatum(ent->key);
707 values[1] = Int32GetDatum(i);
708 values[2] = Int64GetDatum(nodes[i] * os_page_size);
709
710 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
711 values, nulls);
712 }
713
714 /* The last entry is used for pages without a NUMA node. */
715 nulls[1] = true;
716 values[0] = CStringGetTextDatum(ent->key);
717 values[2] = Int64GetDatum(nodes[max_nodes + 1] * os_page_size);
718
719 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
720 values, nulls);
721 }
722
723 LWLockRelease(ShmemIndexLock);
724 firstNumaTouch = false;
725
726 return (Datum) 0;
727}
#define TYPEALIGN(ALIGNVAL, LEN)
Definition c.h:831
#define UINT64_FORMAT
Definition c.h:577
uint64_t uint64
Definition c.h:559
#define TYPEALIGN_DOWN(ALIGNVAL, LEN)
Definition c.h:843
#define DEBUG1
Definition elog.h:30
#define elog(elevel,...)
Definition elog.h:226
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_array(type, count)
Definition fe_memutils.h:77
int i
Definition isn.c:77
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
PGDLLIMPORT int pg_numa_get_max_node(void)
Definition pg_numa.c:138
#define pg_numa_touch_mem_if_required(ptr)
Definition pg_numa.h:37
PGDLLIMPORT int pg_numa_query_pages(int pid, unsigned long count, void **pages, int *status)
Definition pg_numa.c:132
PGDLLIMPORT int pg_numa_init(void)
Definition pg_numa.c:125
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
Size pg_get_shmem_pagesize(void)
Definition shmem.c:738
#define PG_GET_SHMEM_NUMA_SIZES_COLS
static bool firstNumaTouch
Definition shmem.c:109

References ShmemIndexEnt::allocated_size, CHECK_FOR_INTERRUPTS, CStringGetTextDatum, DEBUG1, elog, ERROR, firstNumaTouch, hash_seq_init(), hash_seq_search(), i, InitMaterializedSRF(), Int32GetDatum(), Int64GetDatum(), ShmemIndexEnt::key, ShmemIndexEnt::location, LW_SHARED, LWLockAcquire(), LWLockRelease(), palloc0_array, palloc_array, PG_GET_SHMEM_NUMA_SIZES_COLS, pg_get_shmem_pagesize(), pg_numa_get_max_node(), pg_numa_init(), pg_numa_query_pages(), pg_numa_touch_mem_if_required, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, ShmemIndex, ShmemSegHdr, PGShmemHeader::totalsize, tuplestore_putvalues(), TYPEALIGN, TYPEALIGN_DOWN, UINT64_FORMAT, and values.

◆ pg_get_shmem_pagesize()

Size pg_get_shmem_pagesize ( void  )

Definition at line 738 of file shmem.c.

739{
740 Size os_page_size;
741#ifdef WIN32
742 SYSTEM_INFO sysinfo;
743
744 GetSystemInfo(&sysinfo);
745 os_page_size = sysinfo.dwPageSize;
746#else
747 os_page_size = sysconf(_SC_PAGESIZE);
748#endif
749
752
754 GetHugePageSize(&os_page_size, NULL);
755
756 return os_page_size;
757}
int huge_pages_status
Definition guc_tables.c:590
@ HUGE_PAGES_UNKNOWN
Definition pg_shmem.h:56
@ HUGE_PAGES_ON
Definition pg_shmem.h:54
void GetHugePageSize(Size *hugepagesize, int *mmap_flags)
Definition sysv_shmem.c:480

References Assert, GetHugePageSize(), HUGE_PAGES_ON, huge_pages_status, HUGE_PAGES_UNKNOWN, and IsUnderPostmaster.

Referenced by pg_buffercache_os_pages_internal(), and pg_get_shmem_allocations_numa().

◆ pg_numa_available()

Datum pg_numa_available ( PG_FUNCTION_ARGS  )

Definition at line 760 of file shmem.c.

761{
763}
#define PG_RETURN_BOOL(x)
Definition fmgr.h:360

References pg_numa_init(), and PG_RETURN_BOOL.

◆ ShmemAddrIsValid()

bool ShmemAddrIsValid ( const void *  addr)

Definition at line 265 of file shmem.c.

266{
267 return (addr >= ShmemBase) && (addr < ShmemEnd);
268}

References ShmemBase, and ShmemEnd.

Referenced by ReleasePredXact(), and ShmemInitStruct().

◆ ShmemAlloc()

void * ShmemAlloc ( Size  size)

Definition at line 182 of file shmem.c.

183{
184 void *newSpace;
185 Size allocated_size;
186
187 newSpace = ShmemAllocRaw(size, &allocated_size);
188 if (!newSpace)
190 (errcode(ERRCODE_OUT_OF_MEMORY),
191 errmsg("out of shared memory (%zu bytes requested)",
192 size)));
193 return newSpace;
194}
static void * ShmemAllocRaw(Size size, Size *allocated_size)
Definition shmem.c:216

References ereport, errcode(), errmsg(), ERROR, and ShmemAllocRaw().

Referenced by CreateLWLocks(), PGReserveSemaphores(), ShmemInitStruct(), and StatsShmemInit().

◆ ShmemAllocNoError()

void * ShmemAllocNoError ( Size  size)

Definition at line 202 of file shmem.c.

203{
204 Size allocated_size;
205
206 return ShmemAllocRaw(size, &allocated_size);
207}

References ShmemAllocRaw().

Referenced by ShmemInitHash().

◆ ShmemAllocRaw()

static void * ShmemAllocRaw ( Size  size,
Size allocated_size 
)
static

Definition at line 216 of file shmem.c.

217{
218 Size newStart;
219 Size newFree;
220 void *newSpace;
221
222 /*
223 * Ensure all space is adequately aligned. We used to only MAXALIGN this
224 * space but experience has proved that on modern systems that is not good
225 * enough. Many parts of the system are very sensitive to critical data
226 * structures getting split across cache line boundaries. To avoid that,
227 * attempt to align the beginning of the allocation to a cache line
228 * boundary. The calling code will still need to be careful about how it
229 * uses the allocated space - e.g. by padding each element in an array of
230 * structures out to a power-of-two size - but without this, even that
231 * won't be sufficient.
232 */
233 size = CACHELINEALIGN(size);
234 *allocated_size = size;
235
236 Assert(ShmemSegHdr != NULL);
237
239
240 newStart = ShmemAllocator->free_offset;
241
242 newFree = newStart + size;
243 if (newFree <= ShmemSegHdr->totalsize)
244 {
245 newSpace = (char *) ShmemBase + newStart;
246 ShmemAllocator->free_offset = newFree;
247 }
248 else
249 newSpace = NULL;
250
252
253 /* note this assert is okay with newSpace == NULL */
254 Assert(newSpace == (void *) CACHELINEALIGN(newSpace));
255
256 return newSpace;
257}
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56

References Assert, CACHELINEALIGN, ShmemAllocatorData::free_offset, ShmemAllocator, ShmemBase, ShmemLock, ShmemSegHdr, SpinLockAcquire(), and SpinLockRelease().

Referenced by ShmemAlloc(), ShmemAllocNoError(), and ShmemInitStruct().

◆ ShmemInitHash()

HTAB * ShmemInitHash ( const char *  name,
int64  init_size,
int64  max_size,
HASHCTL infoP,
int  hash_flags 
)

Definition at line 323 of file shmem.c.

328{
329 bool found;
330 void *location;
331
332 /*
333 * Hash tables allocated in shared memory have a fixed directory; it can't
334 * grow or other backends wouldn't be able to find it. So, make sure we
335 * make it big enough to start with.
336 *
337 * The shared memory allocator must be specified too.
338 */
339 infoP->dsize = infoP->max_dsize = hash_select_dirsize(max_size);
340 infoP->alloc = ShmemAllocNoError;
341 hash_flags |= HASH_SHARED_MEM | HASH_ALLOC | HASH_DIRSIZE;
342
343 /* look it up in the shmem index */
344 location = ShmemInitStruct(name,
345 hash_get_shared_size(infoP, hash_flags),
346 &found);
347
348 /*
349 * if it already exists, attach to it rather than allocate and initialize
350 * new space
351 */
352 if (found)
353 hash_flags |= HASH_ATTACH;
354
355 /* Pass location of hashtable header to hash_create */
356 infoP->hctl = (HASHHDR *) location;
357
358 return hash_create(name, init_size, infoP, hash_flags);
359}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
Size hash_get_shared_size(HASHCTL *info, int flags)
Definition dynahash.c:854
int64 hash_select_dirsize(int64 num_entries)
Definition dynahash.c:830
#define HASH_ALLOC
Definition hsearch.h:101
#define HASH_DIRSIZE
Definition hsearch.h:94
#define HASH_ATTACH
Definition hsearch.h:104
#define HASH_SHARED_MEM
Definition hsearch.h:103
void * ShmemAllocNoError(Size size)
Definition shmem.c:202
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378
HashAllocFunc alloc
Definition hsearch.h:84
int64 max_dsize
Definition hsearch.h:73
HASHHDR * hctl
Definition hsearch.h:88
int64 dsize
Definition hsearch.h:72
const char * name

References HASHCTL::alloc, HASHCTL::dsize, HASH_ALLOC, HASH_ATTACH, hash_create(), HASH_DIRSIZE, hash_get_shared_size(), hash_select_dirsize(), HASH_SHARED_MEM, HASHCTL::hctl, HASHCTL::max_dsize, name, ShmemAllocNoError(), and ShmemInitStruct().

Referenced by InitBufTable(), InitShmemIndex(), LockManagerShmemInit(), pgss_shmem_startup(), PredicateLockShmemInit(), and WaitEventCustomShmemInit().

◆ ShmemInitStruct()

void * ShmemInitStruct ( const char *  name,
Size  size,
bool *  foundPtr 
)

Definition at line 378 of file shmem.c.

379{
380 ShmemIndexEnt *result;
381 void *structPtr;
382
383 LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
384
385 if (!ShmemIndex)
386 {
387 /* Must be trying to create/attach to ShmemIndex itself */
388 Assert(strcmp(name, "ShmemIndex") == 0);
389
391 {
392 /* Must be initializing a (non-standalone) backend */
393 Assert(ShmemAllocator->index != NULL);
394 structPtr = ShmemAllocator->index;
395 *foundPtr = true;
396 }
397 else
398 {
399 /*
400 * If the shmem index doesn't exist, we are bootstrapping: we must
401 * be trying to init the shmem index itself.
402 *
403 * Notice that the ShmemIndexLock is released before the shmem
404 * index has been initialized. This should be OK because no other
405 * process can be accessing shared memory yet.
406 */
407 Assert(ShmemAllocator->index == NULL);
408 structPtr = ShmemAlloc(size);
409 ShmemAllocator->index = structPtr;
410 *foundPtr = false;
411 }
412 LWLockRelease(ShmemIndexLock);
413 return structPtr;
414 }
415
416 /* look it up in the shmem index */
417 result = (ShmemIndexEnt *)
419
420 if (!result)
421 {
422 LWLockRelease(ShmemIndexLock);
424 (errcode(ERRCODE_OUT_OF_MEMORY),
425 errmsg("could not create ShmemIndex entry for data structure \"%s\"",
426 name)));
427 }
428
429 if (*foundPtr)
430 {
431 /*
432 * Structure is in the shmem index so someone else has allocated it
433 * already. The size better be the same as the size we are trying to
434 * initialize to, or there is a name conflict (or worse).
435 */
436 if (result->size != size)
437 {
438 LWLockRelease(ShmemIndexLock);
440 (errmsg("ShmemIndex entry size is wrong for data structure"
441 " \"%s\": expected %zu, actual %zu",
442 name, size, result->size)));
443 }
444 structPtr = result->location;
445 }
446 else
447 {
448 Size allocated_size;
449
450 /* It isn't in the table yet. allocate and initialize it */
451 structPtr = ShmemAllocRaw(size, &allocated_size);
452 if (structPtr == NULL)
453 {
454 /* out of memory; remove the failed ShmemIndex entry */
456 LWLockRelease(ShmemIndexLock);
458 (errcode(ERRCODE_OUT_OF_MEMORY),
459 errmsg("not enough shared memory for data structure"
460 " \"%s\" (%zu bytes requested)",
461 name, size)));
462 }
463 result->size = size;
464 result->allocated_size = allocated_size;
465 result->location = structPtr;
466 }
467
468 LWLockRelease(ShmemIndexLock);
469
470 Assert(ShmemAddrIsValid(structPtr));
471
472 Assert(structPtr == (void *) CACHELINEALIGN(structPtr));
473
474 return structPtr;
475}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
@ HASH_REMOVE
Definition hsearch.h:115
@ HASH_ENTER_NULL
Definition hsearch.h:116
@ LW_EXCLUSIVE
Definition lwlock.h:112
bool ShmemAddrIsValid(const void *addr)
Definition shmem.c:265
void * ShmemAlloc(Size size)
Definition shmem.c:182

References ShmemIndexEnt::allocated_size, Assert, CACHELINEALIGN, ereport, errcode(), errmsg(), ERROR, HASH_ENTER_NULL, HASH_REMOVE, hash_search(), ShmemAllocatorData::index, IsUnderPostmaster, ShmemIndexEnt::location, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), name, ShmemAddrIsValid(), ShmemAlloc(), ShmemAllocator, ShmemAllocRaw(), ShmemIndex, and ShmemIndexEnt::size.

Referenced by AioShmemInit(), ApplyLauncherShmemInit(), AsyncShmemInit(), AutoVacuumShmemInit(), BackendStatusShmemInit(), BackgroundWorkerShmemInit(), BTreeShmemInit(), BufferManagerShmemInit(), CheckpointerShmemInit(), CommitTsShmemInit(), dsm_shmem_init(), DSMRegistryShmemInit(), InitProcGlobal(), injection_shmem_startup(), InjectionPointShmemInit(), LockManagerShmemInit(), LogicalDecodingCtlShmemInit(), MultiXactShmemInit(), pgaio_worker_shmem_init(), PgArchShmemInit(), pgss_shmem_startup(), PMSignalShmemInit(), PredicateLockShmemInit(), ProcArrayShmemInit(), ProcSignalShmemInit(), ReplicationOriginShmemInit(), ReplicationSlotsShmemInit(), SerialInit(), SharedInvalShmemInit(), ShmemInitHash(), SimpleLruInit(), SlotSyncShmemInit(), StatsShmemInit(), StrategyInitialize(), SyncScanShmemInit(), test_aio_shmem_startup(), TwoPhaseShmemInit(), VarsupShmemInit(), WaitEventCustomShmemInit(), WaitLSNShmemInit(), WalRcvShmemInit(), WalSndShmemInit(), WalSummarizerShmemInit(), XLogPrefetchShmemInit(), XLogRecoveryShmemInit(), and XLOGShmemInit().

Variable Documentation

◆ firstNumaTouch

bool firstNumaTouch = true
static

Definition at line 109 of file shmem.c.

Referenced by pg_get_shmem_allocations_numa().

◆ ShmemAllocator

ShmemAllocatorData* ShmemAllocator
static

◆ ShmemBase

void* ShmemBase
static

Definition at line 101 of file shmem.c.

Referenced by InitShmemAllocator(), ShmemAddrIsValid(), and ShmemAllocRaw().

◆ ShmemEnd

void* ShmemEnd
static

Definition at line 102 of file shmem.c.

Referenced by InitShmemAllocator(), and ShmemAddrIsValid().

◆ ShmemIndex

HTAB* ShmemIndex = NULL
static

◆ ShmemLock

slock_t* ShmemLock

Definition at line 105 of file shmem.c.

Referenced by GetLWTrancheName(), InitShmemAllocator(), LWLockNewTrancheId(), and ShmemAllocRaw().

◆ ShmemSegHdr

PGShmemHeader* ShmemSegHdr
static