PostgreSQL Source Code git master
Loading...
Searching...
No Matches
shmem.c File Reference
#include "postgres.h"
#include <unistd.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 "utils/tuplestore.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 voidShmemAllocRaw (Size size, Size *allocated_size)
 
Datum pg_numa_available (PG_FUNCTION_ARGS)
 
void InitShmemAllocator (PGShmemHeader *seghdr)
 
voidShmemAlloc (Size size)
 
voidShmemAllocNoError (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)
 
voidShmemInitStruct (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 voidShmemBase
 
static voidShmemEnd
 
static ShmemAllocatorDataShmemAllocator
 
slock_tShmemLock
 
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 485 of file shmem.c.

486{
487 Size result;
488
489 if (pg_add_size_overflow(s1, s2, &result))
492 errmsg("requested shared memory size overflows size_t")));
493 return result;
494}
size_t Size
Definition c.h:688
int errcode(int sqlerrcode)
Definition elog.c:874
#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
static char * errmsg
static int fb(int x)
char * s1
char * s2

References ereport, errcode(), errmsg, ERROR, fb(), 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(), MultiXactSharedStateShmemSize(), 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 125 of file shmem.c.

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

References Assert, CACHELINEALIGN, ereport, errcode(), errmsg, ERROR, fb(), 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 277 of file shmem.c.

278{
279 HASHCTL info;
280
281 /*
282 * Create the shared memory shmem index.
283 *
284 * Since ShmemInitHash calls ShmemInitStruct, which expects the ShmemIndex
285 * hashtable to exist already, we have a bit of a circularity problem in
286 * initializing the ShmemIndex itself. The special "ShmemIndex" hash
287 * table name will tell ShmemInitStruct to fake it.
288 */
290 info.entrysize = sizeof(ShmemIndexEnt);
291
292 ShmemIndex = ShmemInitHash("ShmemIndex",
294 &info,
296}
#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:326
#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 500 of file shmem.c.

501{
502 Size result;
503
504 if (pg_mul_size_overflow(s1, s2, &result))
507 errmsg("requested shared memory size overflows size_t")));
508 return result;
509}
static bool pg_mul_size_overflow(size_t a, size_t b, size_t *result)
Definition int.h:642

References ereport, errcode(), errmsg, ERROR, fb(), 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(), MultiXactSharedStateShmemSize(), 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 513 of file shmem.c.

514{
515#define PG_GET_SHMEM_SIZES_COLS 4
516 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
521 bool nulls[PG_GET_SHMEM_SIZES_COLS];
522
523 InitMaterializedSRF(fcinfo, 0);
524
526
528
529 /* output all allocated entries */
530 memset(nulls, 0, sizeof(nulls));
531 while ((ent = (ShmemIndexEnt *) hash_seq_search(&hstat)) != NULL)
532 {
533 values[0] = CStringGetTextDatum(ent->key);
534 values[1] = Int64GetDatum((char *) ent->location - (char *) ShmemSegHdr);
535 values[2] = Int64GetDatum(ent->size);
536 values[3] = Int64GetDatum(ent->allocated_size);
537 named_allocated += ent->allocated_size;
538
539 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
540 values, nulls);
541 }
542
543 /* output shared memory allocated but not counted via the shmem index */
544 values[0] = CStringGetTextDatum("<anonymous>");
545 nulls[1] = true;
547 values[3] = values[2];
548 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
549
550 /* output as-of-yet unused shared memory */
551 nulls[0] = true;
553 nulls[1] = false;
555 values[3] = values[2];
556 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
557
559
560 return (Datum) 0;
561}
static Datum values[MAXATTR]
Definition bootstrap.c:188
#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:1177
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1794
@ LW_SHARED
Definition lwlock.h:113
static Datum Int64GetDatum(int64 X)
Definition postgres.h:413
uint64_t Datum
Definition postgres.h:70
#define PG_GET_SHMEM_SIZES_COLS
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785

References CStringGetTextDatum, fb(), ShmemAllocatorData::free_offset, hash_seq_init(), hash_seq_search(), InitMaterializedSRF(), Int64GetDatum(), LW_SHARED, LWLockAcquire(), LWLockRelease(), PG_GET_SHMEM_SIZES_COLS, ShmemAllocator, ShmemIndex, ShmemSegHdr, PGShmemHeader::totalsize, tuplestore_putvalues(), and values.

◆ pg_get_shmem_allocations_numa()

Datum pg_get_shmem_allocations_numa ( PG_FUNCTION_ARGS  )

Definition at line 570 of file shmem.c.

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

References CHECK_FOR_INTERRUPTS, CStringGetTextDatum, DEBUG1, elog, ERROR, fb(), firstNumaTouch, hash_seq_init(), hash_seq_search(), i, InitMaterializedSRF(), Int32GetDatum(), Int64GetDatum(), 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, 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 741 of file shmem.c.

742{
744#ifdef WIN32
746
748 os_page_size = sysinfo.dwPageSize;
749#else
751#endif
752
755
758
759 return os_page_size;
760}
int huge_pages_status
Definition guc_tables.c:591
@ 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, fb(), 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 763 of file shmem.c.

764{
766}
#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 268 of file shmem.c.

269{
270 return (addr >= ShmemBase) && (addr < ShmemEnd);
271}

References ShmemBase, and ShmemEnd.

Referenced by ReleasePredXact(), and ShmemInitStruct().

◆ ShmemAlloc()

void * ShmemAlloc ( Size  size)

Definition at line 185 of file shmem.c.

186{
187 void *newSpace;
188 Size allocated_size;
189
190 newSpace = ShmemAllocRaw(size, &allocated_size);
191 if (!newSpace)
194 errmsg("out of shared memory (%zu bytes requested)",
195 size)));
196 return newSpace;
197}
static void * ShmemAllocRaw(Size size, Size *allocated_size)
Definition shmem.c:219

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

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

◆ ShmemAllocNoError()

void * ShmemAllocNoError ( Size  size)

Definition at line 205 of file shmem.c.

206{
207 Size allocated_size;
208
209 return ShmemAllocRaw(size, &allocated_size);
210}

References ShmemAllocRaw().

Referenced by ShmemInitHash().

◆ ShmemAllocRaw()

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

Definition at line 219 of file shmem.c.

220{
223 void *newSpace;
224
225 /*
226 * Ensure all space is adequately aligned. We used to only MAXALIGN this
227 * space but experience has proved that on modern systems that is not good
228 * enough. Many parts of the system are very sensitive to critical data
229 * structures getting split across cache line boundaries. To avoid that,
230 * attempt to align the beginning of the allocation to a cache line
231 * boundary. The calling code will still need to be careful about how it
232 * uses the allocated space - e.g. by padding each element in an array of
233 * structures out to a power-of-two size - but without this, even that
234 * won't be sufficient.
235 */
236 size = CACHELINEALIGN(size);
237 *allocated_size = size;
238
240
242
244
245 newFree = newStart + size;
246 if (newFree <= ShmemSegHdr->totalsize)
247 {
248 newSpace = (char *) ShmemBase + newStart;
250 }
251 else
252 newSpace = NULL;
253
255
256 /* note this assert is okay with newSpace == NULL */
258
259 return newSpace;
260}
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, fb(), 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 326 of file shmem.c.

331{
332 bool found;
333 void *location;
334
335 /*
336 * Hash tables allocated in shared memory have a fixed directory; it can't
337 * grow or other backends wouldn't be able to find it. So, make sure we
338 * make it big enough to start with.
339 *
340 * The shared memory allocator must be specified too.
341 */
342 infoP->dsize = infoP->max_dsize = hash_select_dirsize(max_size);
343 infoP->alloc = ShmemAllocNoError;
345
346 /* look it up in the shmem index */
347 location = ShmemInitStruct(name,
349 &found);
350
351 /*
352 * if it already exists, attach to it rather than allocate and initialize
353 * new space
354 */
355 if (found)
357
358 /* Pass location of hashtable header to hash_create */
359 infoP->hctl = (HASHHDR *) location;
360
362}
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:205
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:381
const char * name

References fb(), HASH_ALLOC, HASH_ATTACH, hash_create(), HASH_DIRSIZE, hash_get_shared_size(), hash_select_dirsize(), HASH_SHARED_MEM, 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 381 of file shmem.c.

382{
383 ShmemIndexEnt *result;
384 void *structPtr;
385
387
388 if (!ShmemIndex)
389 {
390 /* Must be trying to create/attach to ShmemIndex itself */
391 Assert(strcmp(name, "ShmemIndex") == 0);
392
394 {
395 /* Must be initializing a (non-standalone) backend */
398 *foundPtr = true;
399 }
400 else
401 {
402 /*
403 * If the shmem index doesn't exist, we are bootstrapping: we must
404 * be trying to init the shmem index itself.
405 *
406 * Notice that the ShmemIndexLock is released before the shmem
407 * index has been initialized. This should be OK because no other
408 * process can be accessing shared memory yet.
409 */
411 structPtr = ShmemAlloc(size);
413 *foundPtr = false;
414 }
416 return structPtr;
417 }
418
419 /* look it up in the shmem index */
420 result = (ShmemIndexEnt *)
422
423 if (!result)
424 {
428 errmsg("could not create ShmemIndex entry for data structure \"%s\"",
429 name)));
430 }
431
432 if (*foundPtr)
433 {
434 /*
435 * Structure is in the shmem index so someone else has allocated it
436 * already. The size better be the same as the size we are trying to
437 * initialize to, or there is a name conflict (or worse).
438 */
439 if (result->size != size)
440 {
443 (errmsg("ShmemIndex entry size is wrong for data structure"
444 " \"%s\": expected %zu, actual %zu",
445 name, size, result->size)));
446 }
447 structPtr = result->location;
448 }
449 else
450 {
451 Size allocated_size;
452
453 /* It isn't in the table yet. allocate and initialize it */
454 structPtr = ShmemAllocRaw(size, &allocated_size);
455 if (structPtr == NULL)
456 {
457 /* out of memory; remove the failed ShmemIndex entry */
462 errmsg("not enough shared memory for data structure"
463 " \"%s\" (%zu bytes requested)",
464 name, size)));
465 }
466 result->size = size;
467 result->allocated_size = allocated_size;
468 result->location = structPtr;
469 }
470
472
474
476
477 return structPtr;
478}
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:268
void * ShmemAlloc(Size size)
Definition shmem.c:185
void * location
Definition shmem.h:58
Size size
Definition shmem.h:59
Size allocated_size
Definition shmem.h:60

References ShmemIndexEnt::allocated_size, Assert, CACHELINEALIGN, ereport, errcode(), errmsg, ERROR, fb(), 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 112 of file shmem.c.

Referenced by pg_get_shmem_allocations_numa().

◆ ShmemAllocator

ShmemAllocatorData* ShmemAllocator
static

◆ ShmemBase

void* ShmemBase
static

Definition at line 104 of file shmem.c.

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

◆ ShmemEnd

void* ShmemEnd
static

Definition at line 105 of file shmem.c.

Referenced by InitShmemAllocator(), and ShmemAddrIsValid().

◆ ShmemIndex

◆ ShmemLock

slock_t* ShmemLock

Definition at line 108 of file shmem.c.

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

◆ ShmemSegHdr

PGShmemHeader* ShmemSegHdr
static