PostgreSQL Source Code  git master
memutils.h File Reference
#include "nodes/memnodes.h"
Include dependency graph for memutils.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define MaxAllocSize   ((Size) 0x3fffffff) /* 1 gigabyte - 1 */
 
#define AllocSizeIsValid(size)   ((Size) (size) <= MaxAllocSize)
 
#define MaxAllocHugeSize   (SIZE_MAX / 2)
 
#define AllocHugeSizeIsValid(size)   ((Size) (size) <= MaxAllocHugeSize)
 
#define MemoryContextResetAndDeleteChildren(ctx)   MemoryContextReset(ctx)
 
#define MemoryContextCopyAndSetIdentifier(cxt, id)    MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id))
 
#define AllocSetContextCreate    AllocSetContextCreateInternal
 
#define ALLOCSET_DEFAULT_MINSIZE   0
 
#define ALLOCSET_DEFAULT_INITSIZE   (8 * 1024)
 
#define ALLOCSET_DEFAULT_MAXSIZE   (8 * 1024 * 1024)
 
#define ALLOCSET_DEFAULT_SIZES    ALLOCSET_DEFAULT_MINSIZE, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE
 
#define ALLOCSET_SMALL_MINSIZE   0
 
#define ALLOCSET_SMALL_INITSIZE   (1 * 1024)
 
#define ALLOCSET_SMALL_MAXSIZE   (8 * 1024)
 
#define ALLOCSET_SMALL_SIZES    ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE
 
#define ALLOCSET_START_SMALL_SIZES    ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE
 
#define ALLOCSET_SEPARATE_THRESHOLD   8192
 
#define SLAB_DEFAULT_BLOCK_SIZE   (8 * 1024)
 
#define SLAB_LARGE_BLOCK_SIZE   (8 * 1024 * 1024)
 

Functions

void MemoryContextInit (void)
 
void MemoryContextReset (MemoryContext context)
 
void MemoryContextDelete (MemoryContext context)
 
void MemoryContextResetOnly (MemoryContext context)
 
void MemoryContextResetChildren (MemoryContext context)
 
void MemoryContextDeleteChildren (MemoryContext context)
 
void MemoryContextSetIdentifier (MemoryContext context, const char *id)
 
void MemoryContextSetParent (MemoryContext context, MemoryContext new_parent)
 
Size GetMemoryChunkSpace (void *pointer)
 
MemoryContext MemoryContextGetParent (MemoryContext context)
 
bool MemoryContextIsEmpty (MemoryContext context)
 
Size MemoryContextMemAllocated (MemoryContext context, bool recurse)
 
void MemoryContextStats (MemoryContext context)
 
void MemoryContextStatsDetail (MemoryContext context, int max_children, bool print_to_stderr)
 
void MemoryContextAllowInCriticalSection (MemoryContext context, bool allow)
 
bool MemoryContextContains (MemoryContext context, void *pointer)
 
static MemoryContext GetMemoryChunkContext (void *pointer)
 
void MemoryContextCreate (MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
 
void HandleLogMemoryContextInterrupt (void)
 
void ProcessLogMemoryContextInterrupt (void)
 
MemoryContext AllocSetContextCreateInternal (MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
 
MemoryContext SlabContextCreate (MemoryContext parent, const char *name, Size blockSize, Size chunkSize)
 
MemoryContext GenerationContextCreate (MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
 

Variables

PGDLLIMPORT MemoryContext TopMemoryContext
 
PGDLLIMPORT MemoryContext ErrorContext
 
PGDLLIMPORT MemoryContext PostmasterContext
 
PGDLLIMPORT MemoryContext CacheMemoryContext
 
PGDLLIMPORT MemoryContext MessageContext
 
PGDLLIMPORT MemoryContext TopTransactionContext
 
PGDLLIMPORT MemoryContext CurTransactionContext
 
PGDLLIMPORT MemoryContext PortalContext
 

Macro Definition Documentation

◆ AllocHugeSizeIsValid

#define AllocHugeSizeIsValid (   size)    ((Size) (size) <= MaxAllocHugeSize)

Definition at line 46 of file memutils.h.

◆ ALLOCSET_DEFAULT_INITSIZE

#define ALLOCSET_DEFAULT_INITSIZE   (8 * 1024)

Definition at line 195 of file memutils.h.

◆ ALLOCSET_DEFAULT_MAXSIZE

#define ALLOCSET_DEFAULT_MAXSIZE   (8 * 1024 * 1024)

Definition at line 196 of file memutils.h.

◆ ALLOCSET_DEFAULT_MINSIZE

#define ALLOCSET_DEFAULT_MINSIZE   0

Definition at line 194 of file memutils.h.

◆ ALLOCSET_DEFAULT_SIZES

Definition at line 197 of file memutils.h.

◆ ALLOCSET_SEPARATE_THRESHOLD

#define ALLOCSET_SEPARATE_THRESHOLD   8192

Definition at line 224 of file memutils.h.

◆ ALLOCSET_SMALL_INITSIZE

#define ALLOCSET_SMALL_INITSIZE   (1 * 1024)

Definition at line 205 of file memutils.h.

◆ ALLOCSET_SMALL_MAXSIZE

#define ALLOCSET_SMALL_MAXSIZE   (8 * 1024)

Definition at line 206 of file memutils.h.

◆ ALLOCSET_SMALL_MINSIZE

#define ALLOCSET_SMALL_MINSIZE   0

Definition at line 204 of file memutils.h.

◆ ALLOCSET_SMALL_SIZES

Definition at line 207 of file memutils.h.

◆ ALLOCSET_START_SMALL_SIZES

#define ALLOCSET_START_SMALL_SIZES    ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE

Definition at line 214 of file memutils.h.

◆ AllocSetContextCreate

#define AllocSetContextCreate    AllocSetContextCreateInternal

Definition at line 173 of file memutils.h.

◆ AllocSizeIsValid

#define AllocSizeIsValid (   size)    ((Size) (size) <= MaxAllocSize)

Definition at line 42 of file memutils.h.

◆ MaxAllocHugeSize

#define MaxAllocHugeSize   (SIZE_MAX / 2)

Definition at line 44 of file memutils.h.

◆ MaxAllocSize

#define MaxAllocSize   ((Size) 0x3fffffff) /* 1 gigabyte - 1 */

Definition at line 40 of file memutils.h.

◆ MemoryContextCopyAndSetIdentifier

#define MemoryContextCopyAndSetIdentifier (   cxt,
  id 
)     MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id))

Definition at line 98 of file memutils.h.

◆ MemoryContextResetAndDeleteChildren

#define MemoryContextResetAndDeleteChildren (   ctx)    MemoryContextReset(ctx)

Definition at line 67 of file memutils.h.

◆ SLAB_DEFAULT_BLOCK_SIZE

#define SLAB_DEFAULT_BLOCK_SIZE   (8 * 1024)

Definition at line 226 of file memutils.h.

◆ SLAB_LARGE_BLOCK_SIZE

#define SLAB_LARGE_BLOCK_SIZE   (8 * 1024 * 1024)

Definition at line 227 of file memutils.h.

Function Documentation

◆ AllocSetContextCreateInternal()

MemoryContext AllocSetContextCreateInternal ( MemoryContext  parent,
const char *  name,
Size  minContextSize,
Size  initBlockSize,
Size  maxBlockSize 
)

Definition at line 379 of file aset.c.

384 {
385  int freeListIndex;
386  Size firstBlockSize;
387  AllocSet set;
388  AllocBlock block;
389 
390  /* Assert we padded AllocChunkData properly */
392  "sizeof(AllocChunkData) is not maxaligned");
395  "padding calculation in AllocChunkData is wrong");
396 
397  /*
398  * First, validate allocation parameters. Once these were regular runtime
399  * test and elog's, but in practice Asserts seem sufficient because nobody
400  * varies their parameters at runtime. We somewhat arbitrarily enforce a
401  * minimum 1K block size.
402  */
403  Assert(initBlockSize == MAXALIGN(initBlockSize) &&
404  initBlockSize >= 1024);
405  Assert(maxBlockSize == MAXALIGN(maxBlockSize) &&
406  maxBlockSize >= initBlockSize &&
407  AllocHugeSizeIsValid(maxBlockSize)); /* must be safe to double */
408  Assert(minContextSize == 0 ||
409  (minContextSize == MAXALIGN(minContextSize) &&
410  minContextSize >= 1024 &&
411  minContextSize <= maxBlockSize));
412 
413  /*
414  * Check whether the parameters match either available freelist. We do
415  * not need to demand a match of maxBlockSize.
416  */
417  if (minContextSize == ALLOCSET_DEFAULT_MINSIZE &&
418  initBlockSize == ALLOCSET_DEFAULT_INITSIZE)
419  freeListIndex = 0;
420  else if (minContextSize == ALLOCSET_SMALL_MINSIZE &&
421  initBlockSize == ALLOCSET_SMALL_INITSIZE)
422  freeListIndex = 1;
423  else
424  freeListIndex = -1;
425 
426  /*
427  * If a suitable freelist entry exists, just recycle that context.
428  */
429  if (freeListIndex >= 0)
430  {
431  AllocSetFreeList *freelist = &context_freelists[freeListIndex];
432 
433  if (freelist->first_free != NULL)
434  {
435  /* Remove entry from freelist */
436  set = freelist->first_free;
437  freelist->first_free = (AllocSet) set->header.nextchild;
438  freelist->num_free--;
439 
440  /* Update its maxBlockSize; everything else should be OK */
441  set->maxBlockSize = maxBlockSize;
442 
443  /* Reinitialize its header, installing correct name and parent */
447  parent,
448  name);
449 
450  ((MemoryContext) set)->mem_allocated =
451  set->keeper->endptr - ((char *) set);
452 
453  return (MemoryContext) set;
454  }
455  }
456 
457  /* Determine size of initial block */
458  firstBlockSize = MAXALIGN(sizeof(AllocSetContext)) +
460  if (minContextSize != 0)
461  firstBlockSize = Max(firstBlockSize, minContextSize);
462  else
463  firstBlockSize = Max(firstBlockSize, initBlockSize);
464 
465  /*
466  * Allocate the initial block. Unlike other aset.c blocks, it starts with
467  * the context header and its block header follows that.
468  */
469  set = (AllocSet) malloc(firstBlockSize);
470  if (set == NULL)
471  {
472  if (TopMemoryContext)
474  ereport(ERROR,
475  (errcode(ERRCODE_OUT_OF_MEMORY),
476  errmsg("out of memory"),
477  errdetail("Failed while creating memory context \"%s\".",
478  name)));
479  }
480 
481  /*
482  * Avoid writing code that can fail between here and MemoryContextCreate;
483  * we'd leak the header/initial block if we ereport in this stretch.
484  */
485 
486  /* Fill in the initial block's block header */
487  block = (AllocBlock) (((char *) set) + MAXALIGN(sizeof(AllocSetContext)));
488  block->aset = set;
489  block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ;
490  block->endptr = ((char *) set) + firstBlockSize;
491  block->prev = NULL;
492  block->next = NULL;
493 
494  /* Mark unallocated space NOACCESS; leave the block header alone. */
495  VALGRIND_MAKE_MEM_NOACCESS(block->freeptr, block->endptr - block->freeptr);
496 
497  /* Remember block as part of block list */
498  set->blocks = block;
499  /* Mark block as not to be released at reset time */
500  set->keeper = block;
501 
502  /* Finish filling in aset-specific parts of the context header */
503  MemSetAligned(set->freelist, 0, sizeof(set->freelist));
504 
505  set->initBlockSize = initBlockSize;
506  set->maxBlockSize = maxBlockSize;
507  set->nextBlockSize = initBlockSize;
508  set->freeListIndex = freeListIndex;
509 
510  /*
511  * Compute the allocation chunk size limit for this context. It can't be
512  * more than ALLOC_CHUNK_LIMIT because of the fixed number of freelists.
513  * If maxBlockSize is small then requests exceeding the maxBlockSize, or
514  * even a significant fraction of it, should be treated as large chunks
515  * too. For the typical case of maxBlockSize a power of 2, the chunk size
516  * limit will be at most 1/8th maxBlockSize, so that given a stream of
517  * requests that are all the maximum chunk size we will waste at most
518  * 1/8th of the allocated space.
519  *
520  * We have to have allocChunkLimit a power of two, because the requested
521  * and actually-allocated sizes of any chunk must be on the same side of
522  * the limit, else we get confused about whether the chunk is "big".
523  *
524  * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD.
525  */
527  "ALLOC_CHUNK_LIMIT != ALLOCSET_SEPARATE_THRESHOLD");
528 
529  set->allocChunkLimit = ALLOC_CHUNK_LIMIT;
530  while ((Size) (set->allocChunkLimit + ALLOC_CHUNKHDRSZ) >
531  (Size) ((maxBlockSize - ALLOC_BLOCKHDRSZ) / ALLOC_CHUNK_FRACTION))
532  set->allocChunkLimit >>= 1;
533 
534  /* Finally, do the type-independent part of context creation */
538  parent,
539  name);
540 
541  ((MemoryContext) set)->mem_allocated = firstBlockSize;
542 
543  return (MemoryContext) set;
544 }
#define ALLOC_CHUNKHDRSZ
Definition: aset.c:101
struct AllocBlockData * AllocBlock
Definition: aset.c:103
static const MemoryContextMethods AllocSetMethods
Definition: aset.c:285
#define ALLOC_BLOCKHDRSZ
Definition: aset.c:100
#define ALLOC_CHUNK_FRACTION
Definition: aset.c:83
#define ALLOC_CHUNK_LIMIT
Definition: aset.c:81
static AllocSetFreeList context_freelists[2]
Definition: aset.c:253
AllocSetContext * AllocSet
Definition: aset.c:137
#define MAXALIGN(LEN)
Definition: c.h:768
#define offsetof(type, field)
Definition: c.h:738
#define Max(x, y)
Definition: c.h:991
#define MemSetAligned(start, val, len)
Definition: c.h:1049
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:929
size_t Size
Definition: c.h:551
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
const char * name
Definition: encode.c:561
#define malloc(a)
Definition: header.h:50
Assert(fmt[strlen(fmt) - 1] !='\n')
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:505
void MemoryContextCreate(MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:815
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition: memdebug.h:27
#define ALLOCSET_SMALL_MINSIZE
Definition: memutils.h:204
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:194
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:46
#define ALLOCSET_SEPARATE_THRESHOLD
Definition: memutils.h:224
#define ALLOCSET_SMALL_INITSIZE
Definition: memutils.h:205
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:195
@ T_AllocSetContext
Definition: nodes.h:301
struct MemoryContextData * MemoryContext
Definition: palloc.h:36
AllocBlock prev
Definition: aset.c:154
AllocSet aset
Definition: aset.c:153
char * freeptr
Definition: aset.c:156
AllocBlock next
Definition: aset.c:155
char * endptr
Definition: aset.c:157
MemoryContextData header
Definition: aset.c:123
Size maxBlockSize
Definition: aset.c:129
AllocBlock keeper
Definition: aset.c:132
int num_free
Definition: aset.c:248
AllocSetContext * first_free
Definition: aset.c:249
MemoryContext nextchild
Definition: memnodes.h:89

References ALLOC_BLOCKHDRSZ, ALLOC_CHUNK_FRACTION, ALLOC_CHUNK_LIMIT, ALLOC_CHUNKHDRSZ, AllocSetContext::allocChunkLimit, AllocHugeSizeIsValid, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MINSIZE, ALLOCSET_SEPARATE_THRESHOLD, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MINSIZE, AllocSetMethods, AllocBlockData::aset, Assert(), AllocSetContext::blocks, context_freelists, AllocBlockData::endptr, ereport, errcode(), errdetail(), errmsg(), ERROR, AllocSetFreeList::first_free, AllocSetContext::freelist, AllocSetContext::freeListIndex, AllocBlockData::freeptr, AllocSetContext::header, AllocSetContext::initBlockSize, AllocSetContext::keeper, malloc, Max, MAXALIGN, AllocSetContext::maxBlockSize, MemoryContextCreate(), MemoryContextStats(), MemSetAligned, name, AllocBlockData::next, AllocSetContext::nextBlockSize, MemoryContextData::nextchild, AllocSetFreeList::num_free, offsetof, AllocBlockData::prev, StaticAssertStmt, T_AllocSetContext, TopMemoryContext, and VALGRIND_MAKE_MEM_NOACCESS.

◆ GenerationContextCreate()

MemoryContext GenerationContextCreate ( MemoryContext  parent,
const char *  name,
Size  minContextSize,
Size  initBlockSize,
Size  maxBlockSize 
)

Definition at line 215 of file generation.c.

220 {
221  Size firstBlockSize;
222  Size allocSize;
223  GenerationContext *set;
224  GenerationBlock *block;
225 
226  /* Assert we padded GenerationChunk properly */
228  "sizeof(GenerationChunk) is not maxaligned");
231  "padding calculation in GenerationChunk is wrong");
232 
233  /*
234  * First, validate allocation parameters. Asserts seem sufficient because
235  * nobody varies their parameters at runtime. We somewhat arbitrarily
236  * enforce a minimum 1K block size.
237  */
238  Assert(initBlockSize == MAXALIGN(initBlockSize) &&
239  initBlockSize >= 1024);
240  Assert(maxBlockSize == MAXALIGN(maxBlockSize) &&
241  maxBlockSize >= initBlockSize &&
242  AllocHugeSizeIsValid(maxBlockSize)); /* must be safe to double */
243  Assert(minContextSize == 0 ||
244  (minContextSize == MAXALIGN(minContextSize) &&
245  minContextSize >= 1024 &&
246  minContextSize <= maxBlockSize));
247 
248  /* Determine size of initial block */
249  allocSize = MAXALIGN(sizeof(GenerationContext)) +
251  if (minContextSize != 0)
252  allocSize = Max(allocSize, minContextSize);
253  else
254  allocSize = Max(allocSize, initBlockSize);
255 
256  /*
257  * Allocate the initial block. Unlike other generation.c blocks, it
258  * starts with the context header and its block header follows that.
259  */
260  set = (GenerationContext *) malloc(allocSize);
261  if (set == NULL)
262  {
264  ereport(ERROR,
265  (errcode(ERRCODE_OUT_OF_MEMORY),
266  errmsg("out of memory"),
267  errdetail("Failed while creating memory context \"%s\".",
268  name)));
269  }
270 
271  /*
272  * Avoid writing code that can fail between here and MemoryContextCreate;
273  * we'd leak the header if we ereport in this stretch.
274  */
275  dlist_init(&set->blocks);
276 
277  /* Fill in the initial block's block header */
278  block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext)));
279  /* determine the block size and initialize it */
280  firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext));
281  GenerationBlockInit(block, firstBlockSize);
282 
283  /* add it to the doubly-linked list of blocks */
284  dlist_push_head(&set->blocks, &block->node);
285 
286  /* use it as the current allocation block */
287  set->block = block;
288 
289  /* No free block, yet */
290  set->freeblock = NULL;
291 
292  /* Mark block as not to be released at reset time */
293  set->keeper = block;
294 
295  /* Fill in GenerationContext-specific header fields */
296  set->initBlockSize = initBlockSize;
297  set->maxBlockSize = maxBlockSize;
298  set->nextBlockSize = initBlockSize;
299 
300  /*
301  * Compute the allocation chunk size limit for this context.
302  *
303  * Follows similar ideas as AllocSet, see aset.c for details ...
304  */
305  set->allocChunkLimit = maxBlockSize;
306  while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) >
307  (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION))
308  set->allocChunkLimit >>= 1;
309 
310  /* Finally, do the type-independent part of context creation */
314  parent,
315  name);
316 
317  ((MemoryContext) set)->mem_allocated = firstBlockSize;
318 
319  return (MemoryContext) set;
320 }
#define Generation_CHUNK_FRACTION
Definition: generation.c:47
#define Generation_CHUNKHDRSZ
Definition: generation.c:45
static void GenerationBlockInit(GenerationBlock *block, Size blksize)
Definition: generation.c:577
#define Generation_BLOCKHDRSZ
Definition: generation.c:44
static const MemoryContextMethods GenerationMethods
Definition: generation.c:184
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
@ T_GenerationContext
Definition: nodes.h:303
dlist_node node
Definition: generation.c:91
dlist_head blocks
Definition: generation.c:74

References GenerationContext::allocChunkLimit, AllocHugeSizeIsValid, Assert(), GenerationContext::block, GenerationContext::blocks, dlist_init(), dlist_push_head(), ereport, errcode(), errdetail(), errmsg(), ERROR, GenerationContext::freeblock, Generation_BLOCKHDRSZ, Generation_CHUNK_FRACTION, Generation_CHUNKHDRSZ, GenerationBlockInit(), GenerationMethods, GenerationContext::initBlockSize, GenerationContext::keeper, malloc, Max, MAXALIGN, GenerationContext::maxBlockSize, MemoryContextCreate(), MemoryContextStats(), name, GenerationContext::nextBlockSize, GenerationBlock::node, offsetof, StaticAssertStmt, T_GenerationContext, and TopMemoryContext.

Referenced by gistvacuumscan(), ReorderBufferAllocate(), and tuplesort_begin_batch().

◆ GetMemoryChunkContext()

static MemoryContext GetMemoryChunkContext ( void *  pointer)
inlinestatic

Definition at line 114 of file memutils.h.

115 {
116  MemoryContext context;
117 
118  /*
119  * Try to detect bogus pointers handed to us, poorly though we can.
120  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
121  * allocated chunk.
122  */
123  Assert(pointer != NULL);
124  Assert(pointer == (void *) MAXALIGN(pointer));
125 
126  /*
127  * OK, it's probably safe to look at the context.
128  */
129  context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
130 
132 
133  return context;
134 }
#define AssertArg(condition)
Definition: c.h:817
#define MemoryContextIsValid(context)
Definition: memnodes.h:104

References Assert(), AssertArg, MAXALIGN, and MemoryContextIsValid.

Referenced by create_unique_path(), enlarge_list(), GetMemoryChunkSpace(), list_delete_first_n(), list_delete_nth_cell(), mark_dummy_rel(), pfree(), repalloc(), repalloc_huge(), and reparameterize_path_by_child().

◆ GetMemoryChunkSpace()

◆ HandleLogMemoryContextInterrupt()

void HandleLogMemoryContextInterrupt ( void  )

Definition at line 1024 of file mcxt.c.

1025 {
1026  InterruptPending = true;
1027  LogMemoryContextPending = true;
1028  /* latch will be set by procsignal_sigusr1_handler */
1029 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t InterruptPending
Definition: globals.c:30

References InterruptPending, and LogMemoryContextPending.

Referenced by procsignal_sigusr1_handler().

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 418 of file mcxt.c.

419 {
421 
422  context->allowInCritSection = allow;
423 }
bool allowInCritSection
Definition: memnodes.h:83

References MemoryContextData::allowInCritSection, AssertArg, and MemoryContextIsValid.

Referenced by InitSync(), MemoryContextInit(), and XLOGShmemInit().

◆ MemoryContextContains()

bool MemoryContextContains ( MemoryContext  context,
void *  pointer 
)

Definition at line 758 of file mcxt.c.

759 {
760  MemoryContext ptr_context;
761 
762  /*
763  * NB: Can't use GetMemoryChunkContext() here - that performs assertions
764  * that aren't acceptable here since we might be passed memory not
765  * allocated by any memory context.
766  *
767  * Try to detect bogus pointers handed to us, poorly though we can.
768  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
769  * allocated chunk.
770  */
771  if (pointer == NULL || pointer != (void *) MAXALIGN(pointer))
772  return false;
773 
774  /*
775  * OK, it's probably safe to look at the context.
776  */
777  ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
778 
779  return ptr_context == context;
780 }

References MAXALIGN.

Referenced by eval_windowfunction(), finalize_aggregate(), finalize_partialaggregate(), and finalize_windowaggregate().

◆ MemoryContextCreate()

void MemoryContextCreate ( MemoryContext  node,
NodeTag  tag,
const MemoryContextMethods methods,
MemoryContext  parent,
const char *  name 
)

Definition at line 815 of file mcxt.c.

820 {
821  /* Creating new memory contexts is not allowed in a critical section */
822  Assert(CritSectionCount == 0);
823 
824  /* Initialize all standard fields of memory context header */
825  node->type = tag;
826  node->isReset = true;
827  node->methods = methods;
828  node->parent = parent;
829  node->firstchild = NULL;
830  node->mem_allocated = 0;
831  node->prevchild = NULL;
832  node->name = name;
833  node->ident = NULL;
834  node->reset_cbs = NULL;
835 
836  /* OK to link node into context tree */
837  if (parent)
838  {
839  node->nextchild = parent->firstchild;
840  if (parent->firstchild != NULL)
841  parent->firstchild->prevchild = node;
842  parent->firstchild = node;
843  /* inherit allowInCritSection flag from parent */
844  node->allowInCritSection = parent->allowInCritSection;
845  }
846  else
847  {
848  node->nextchild = NULL;
849  node->allowInCritSection = false;
850  }
851 
852  VALGRIND_CREATE_MEMPOOL(node, 0, false);
853 }
volatile uint32 CritSectionCount
Definition: globals.c:42
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
MemoryContext prevchild
Definition: memnodes.h:88
MemoryContext firstchild
Definition: memnodes.h:87
const char * ident
Definition: memnodes.h:91
MemoryContext parent
Definition: memnodes.h:86
MemoryContextCallback * reset_cbs
Definition: memnodes.h:92
NodeTag type
Definition: memnodes.h:80
Size mem_allocated
Definition: memnodes.h:84
const char * name
Definition: memnodes.h:90

References MemoryContextData::allowInCritSection, Assert(), CritSectionCount, MemoryContextData::firstchild, MemoryContextData::ident, MemoryContextData::isReset, MemoryContextData::mem_allocated, MemoryContextData::methods, name, MemoryContextData::name, MemoryContextData::nextchild, MemoryContextData::parent, MemoryContextData::prevchild, MemoryContextData::reset_cbs, MemoryContextData::type, and VALGRIND_CREATE_MEMPOOL.

Referenced by AllocSetContextCreateInternal(), GenerationContextCreate(), and SlabContextCreate().

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 218 of file mcxt.c.

219 {
221  /* We had better not be deleting TopMemoryContext ... */
222  Assert(context != TopMemoryContext);
223  /* And not CurrentMemoryContext, either */
224  Assert(context != CurrentMemoryContext);
225 
226  /* save a function call in common case where there are no children */
227  if (context->firstchild != NULL)
229 
230  /*
231  * It's not entirely clear whether 'tis better to do this before or after
232  * delinking the context; but an error in a callback will likely result in
233  * leaking the whole context (if it's not a root context) if we do it
234  * after, so let's do it before.
235  */
237 
238  /*
239  * We delink the context from its parent before deleting it, so that if
240  * there's an error we won't have deleted/busted contexts still attached
241  * to the context tree. Better a leak than a crash.
242  */
243  MemoryContextSetParent(context, NULL);
244 
245  /*
246  * Also reset the context's ident pointer, in case it points into the
247  * context. This would only matter if someone tries to get stats on the
248  * (already unlinked) context, which is unlikely, but let's be safe.
249  */
250  context->ident = NULL;
251 
252  context->methods->delete_context(context);
253 
254  VALGRIND_DESTROY_MEMPOOL(context);
255 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:309
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:361
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:263
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
void(* delete_context)(MemoryContext context)
Definition: memnodes.h:65

References Assert(), AssertArg, CurrentMemoryContext, MemoryContextMethods::delete_context, MemoryContextData::firstchild, MemoryContextData::ident, MemoryContextCallResetCallbacks(), MemoryContextDeleteChildren(), MemoryContextIsValid, MemoryContextSetParent(), MemoryContextData::methods, TopMemoryContext, and VALGRIND_DESTROY_MEMPOOL.

Referenced by AfterTriggerEndXact(), afterTriggerInvokeEvents(), ApplyLauncherMain(), AtCleanup_Memory(), AtCommit_Memory(), AtEOSubXact_SPI(), AtEOXact_LargeObject(), AtSubCleanup_Memory(), AtSubCommit_Memory(), AttachPartitionEnsureIndexes(), blbuild(), blinsert(), brin_free_desc(), brin_minmax_multi_union(), bringetbitmap(), brininsert(), bt_check_every_level(), btendscan(), btree_xlog_cleanup(), btvacuumscan(), BuildParamLogString(), BuildRelationExtStatistics(), CloneRowTriggersToPartition(), cluster(), compactify_ranges(), compile_plperl_function(), compile_pltcl_function(), compute_expr_stats(), compute_index_stats(), ComputeExtStatisticsRows(), createTrgmNFA(), CreateTriggerFiringOn(), decr_dcc_refcount(), DeleteExpandedObject(), DiscreteKnapsack(), do_analyze_rel(), do_start_bgworker(), do_start_worker(), DoCopyTo(), DropCachedPlan(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), end_heap_rewrite(), EndCopy(), EndCopyFrom(), ensure_free_space_in_buffer(), EventTriggerEndCompleteQuery(), EventTriggerInvoke(), exec_replication_command(), exec_simple_query(), ExecEndAgg(), ExecEndMemoize(), ExecEndRecursiveUnion(), ExecEndSetOp(), ExecEndWindowAgg(), ExecHashTableDestroy(), execute_sql_string(), file_acquire_sample_rows(), fill_hba_view(), fill_ident_view(), fmgr_sql(), free_plperl_function(), FreeCachedExpression(), FreeDecodingContext(), FreeExecutorState(), FreeExprContext(), freeGISTstate(), FreeSnapshotBuilder(), geqo_eval(), get_actual_variable_range(), get_rel_sync_entry(), gin_xlog_cleanup(), ginbuild(), ginbulkdelete(), ginendscan(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gist_xlog_cleanup(), gistbuild(), gistvacuumscan(), hash_destroy(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), load_hba(), load_ident(), load_tzoffsets(), makeArrayResultArr(), makeMdArrayResult(), MemoryContextDeleteChildren(), NIFinishBuild(), pg_decode_shutdown(), pgstat_clear_backend_activity_snapshot(), pgstat_clear_snapshot(), plperl_spi_freeplan(), plperl_spi_prepare(), plpgsql_free_function_memory(), pltcl_handler(), pltcl_SPI_prepare(), PLy_cursor_dealloc(), PLy_plan_dealloc(), PLy_pop_execution_context(), PLy_procedure_delete(), PLy_spi_execute_fetch_result(), PortalDrop(), PostgresMain(), printtup_shutdown(), publicationListToArray(), rebuild_database_list(), ReindexMultipleTables(), ReindexPartitions(), ReindexRelationConcurrently(), RelationBuildDesc(), RelationBuildRuleLock(), RelationDestroyRelation(), ReleaseCachedPlan(), ReorderBufferFree(), ResetUnloggedRelations(), RevalidateCachedQuery(), shdepReassignOwned(), shutdown_MultiFuncCall(), spg_xlog_cleanup(), spgbuild(), spgendscan(), spginsert(), SPI_finish(), SPI_freeplan(), SPI_freetuptable(), StartChildProcess(), statext_dependencies_build(), strlist_to_textarray(), test_pattern(), tokenize_inc_file(), tuplesort_end(), union_tuples(), vacuum(), and validateForeignKeyConstraint().

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 263 of file mcxt.c.

264 {
266 
267  /*
268  * MemoryContextDelete will delink the child from me, so just iterate as
269  * long as there is a child.
270  */
271  while (context->firstchild != NULL)
273 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218

References AssertArg, MemoryContextData::firstchild, MemoryContextDelete(), and MemoryContextIsValid.

Referenced by AtAbort_Portals(), AtSubAbort_Portals(), exec_stmt_block(), MemoryContextDelete(), MemoryContextReset(), PersistHoldablePortal(), PortalRunMulti(), and RelationClose().

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 99 of file mcxt.c.

100 {
101  AssertState(TopMemoryContext == NULL);
102 
103  /*
104  * First, initialize TopMemoryContext, which is the parent of all others.
105  */
107  "TopMemoryContext",
109 
110  /*
111  * Not having any other place to point CurrentMemoryContext, make it point
112  * to TopMemoryContext. Caller should change this soon!
113  */
115 
116  /*
117  * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
118  * we don't really expect much to be allocated in it. More to the point,
119  * require it to contain at least 8K at all times. This is the only case
120  * where retained memory in a context is *essential* --- we want to be
121  * sure ErrorContext still has some memory even if we've run out
122  * elsewhere! Also, allow allocations in ErrorContext within a critical
123  * section. Otherwise a PANIC will cause an assertion failure in the error
124  * reporting code, before printing out the real cause of the failure.
125  *
126  * This should be the last step in this function, as elog.c assumes memory
127  * management works once ErrorContext is non-null.
128  */
130  "ErrorContext",
131  8 * 1024,
132  8 * 1024,
133  8 * 1024);
135 }
#define AssertState(condition)
Definition: c.h:818
MemoryContext ErrorContext
Definition: mcxt.c:49
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:418
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AssertState, CurrentMemoryContext, ErrorContext, MemoryContextAllowInCriticalSection(), and TopMemoryContext.

Referenced by main().

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 458 of file mcxt.c.

459 {
461 
462  /*
463  * For now, we consider a memory context nonempty if it has any children;
464  * perhaps this should be changed later.
465  */
466  if (context->firstchild != NULL)
467  return false;
468  /* Otherwise use the type-specific inquiry */
469  return context->methods->is_empty(context);
470 }
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:67

References AssertArg, MemoryContextData::firstchild, MemoryContextMethods::is_empty, MemoryContextIsValid, and MemoryContextData::methods.

Referenced by AtSubCommit_Memory().

◆ MemoryContextMemAllocated()

Size MemoryContextMemAllocated ( MemoryContext  context,
bool  recurse 
)

Definition at line 477 of file mcxt.c.

478 {
479  Size total = context->mem_allocated;
480 
482 
483  if (recurse)
484  {
485  MemoryContext child;
486 
487  for (child = context->firstchild;
488  child != NULL;
489  child = child->nextchild)
490  total += MemoryContextMemAllocated(child, true);
491  }
492 
493  return total;
494 }
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition: mcxt.c:477

References AssertArg, MemoryContextData::firstchild, MemoryContextData::mem_allocated, MemoryContextIsValid, and MemoryContextData::nextchild.

Referenced by hash_agg_check_limits(), and hash_agg_update_metrics().

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 143 of file mcxt.c.

144 {
146 
147  /* save a function call in common case where there are no children */
148  if (context->firstchild != NULL)
150 
151  /* save a function call if no pallocs since startup or last reset */
152  if (!context->isReset)
153  MemoryContextResetOnly(context);
154 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:162

References AssertArg, MemoryContextData::firstchild, MemoryContextData::isReset, MemoryContextDeleteChildren(), MemoryContextIsValid, and MemoryContextResetOnly().

Referenced by _bt_preprocess_array_keys(), AfterTriggerExecute(), apply_handle_stream_stop(), apply_spooled_messages(), basic_archive_file(), bloomBuildCallback(), brin_memtuple_initialize(), bt_check_level_from_leftmost(), btree_redo(), btvacuumpage(), BuildRelationExtStatistics(), buildSubPlanHash(), cache_purge_all(), check_domain_for_new_field(), check_domain_for_new_tuple(), CloneRowTriggersToPartition(), CopyOneRowTo(), CreateTriggerFiringOn(), dumptuples(), each_object_field_end(), each_worker_jsonb(), elements_array_element_end(), elements_worker_jsonb(), errstart(), EventTriggerInvoke(), exec_dynquery_with_params(), exec_stmt_block(), exec_stmt_dynexecute(), exec_stmt_forc(), exec_stmt_foreach_a(), exec_stmt_open(), exec_stmt_raise(), exec_stmt_return_query(), ExecFindMatchingSubPlans(), ExecHashTableReset(), ExecMakeTableFunctionResult(), ExecProjectSet(), ExecQualAndReset(), ExecRecursiveUnion(), execTuplesUnequal(), execute_foreign_modify(), expanded_record_set_field_internal(), expanded_record_set_tuple(), fetch_more_data(), file_acquire_sample_rows(), get_short_term_cxt(), gin_redo(), ginBuildCallback(), ginHeapTupleBulkInsert(), ginInsertCleanup(), ginVacuumPostingTreeLeaves(), gist_indexsortbuild(), gist_redo(), gistBuildCallback(), gistgetbitmap(), gistgettuple(), gistinsert(), gistProcessEmptyingQueue(), gistrescan(), gistScanPage(), gistSortedBuildCallback(), HandleParallelMessages(), heapam_index_build_range_scan(), heapam_index_validate_scan(), IndexCheckExclusion(), keyGetItem(), libpqrcv_processTuples(), LogicalRepApplyLoop(), lookup_ts_dictionary_cache(), make_tuple_from_result_row(), pg_decode_change(), pg_decode_truncate(), pgoutput_change(), pgoutput_truncate(), plperl_return_next_internal(), PLy_input_convert(), PLy_input_from_tuple(), printtup(), process_ordered_aggregate_single(), ReScanExprContext(), resetSpGistScanOpaque(), scanPendingInsert(), sepgsql_avc_reset(), spg_redo(), spginsert(), spgistBuildCallback(), spgWalk(), startScanKey(), statext_dependencies_build(), storeRow(), tfuncFetchRows(), tfuncLoadRows(), tuplesort_free(), and validateForeignKeyConstraint().

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 195 of file mcxt.c.

196 {
197  MemoryContext child;
198 
200 
201  for (child = context->firstchild; child != NULL; child = child->nextchild)
202  {
204  MemoryContextResetOnly(child);
205  }
206 }
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:195

References AssertArg, MemoryContextData::firstchild, MemoryContextIsValid, MemoryContextResetOnly(), and MemoryContextData::nextchild.

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 162 of file mcxt.c.

163 {
165 
166  /* Nothing to do if no pallocs since startup or last reset */
167  if (!context->isReset)
168  {
170 
171  /*
172  * If context->ident points into the context's memory, it will become
173  * a dangling pointer. We could prevent that by setting it to NULL
174  * here, but that would break valid coding patterns that keep the
175  * ident elsewhere, e.g. in a parent context. Another idea is to use
176  * MemoryContextContains(), but we don't require ident strings to be
177  * in separately-palloc'd chunks, so that risks false positives. So
178  * for now we assume the programmer got it right.
179  */
180 
181  context->methods->reset(context);
182  context->isReset = true;
183  VALGRIND_DESTROY_MEMPOOL(context);
184  VALGRIND_CREATE_MEMPOOL(context, 0, false);
185  }
186 }
void(* reset)(MemoryContext context)
Definition: memnodes.h:64

References AssertArg, MemoryContextData::isReset, MemoryContextCallResetCallbacks(), MemoryContextIsValid, MemoryContextData::methods, MemoryContextMethods::reset, VALGRIND_CREATE_MEMPOOL, and VALGRIND_DESTROY_MEMPOOL.

Referenced by AllocSetDelete(), JsonTableResetContextItem(), MemoryContextReset(), MemoryContextResetChildren(), and mergeruns().

◆ MemoryContextSetIdentifier()

void MemoryContextSetIdentifier ( MemoryContext  context,
const char *  id 
)

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 361 of file mcxt.c.

362 {
364  AssertArg(context != new_parent);
365 
366  /* Fast path if it's got correct parent already */
367  if (new_parent == context->parent)
368  return;
369 
370  /* Delink from existing parent, if any */
371  if (context->parent)
372  {
373  MemoryContext parent = context->parent;
374 
375  if (context->prevchild != NULL)
376  context->prevchild->nextchild = context->nextchild;
377  else
378  {
379  Assert(parent->firstchild == context);
380  parent->firstchild = context->nextchild;
381  }
382 
383  if (context->nextchild != NULL)
384  context->nextchild->prevchild = context->prevchild;
385  }
386 
387  /* And relink */
388  if (new_parent)
389  {
390  AssertArg(MemoryContextIsValid(new_parent));
391  context->parent = new_parent;
392  context->prevchild = NULL;
393  context->nextchild = new_parent->firstchild;
394  if (new_parent->firstchild != NULL)
395  new_parent->firstchild->prevchild = context;
396  new_parent->firstchild = context;
397  }
398  else
399  {
400  context->parent = NULL;
401  context->prevchild = NULL;
402  context->nextchild = NULL;
403  }
404 }

References Assert(), AssertArg, MemoryContextData::firstchild, MemoryContextIsValid, MemoryContextData::nextchild, MemoryContextData::parent, and MemoryContextData::prevchild.

Referenced by _SPI_save_plan(), CachedPlanSetParentContext(), CompleteCachedPlan(), exec_parse_message(), GetCachedExpression(), GetCachedPlan(), load_domaintype_info(), MemoryContextDelete(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRowSecurity(), RelationClearRelation(), RevalidateCachedQuery(), SaveCachedPlan(), SPI_keepplan(), and TransferExpandedObject().

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

Definition at line 505 of file mcxt.c.

506 {
507  /* A hard-wired limit on the number of children is usually good enough */
508  MemoryContextStatsDetail(context, 100, true);
509 }
void MemoryContextStatsDetail(MemoryContext context, int max_children, bool print_to_stderr)
Definition: mcxt.c:520

References MemoryContextStatsDetail().

Referenced by AllocSetContextCreateInternal(), finish_xact_command(), GenerationContextCreate(), MemoryContextAlloc(), MemoryContextAllocExtended(), MemoryContextAllocHuge(), MemoryContextAllocZero(), MemoryContextAllocZeroAligned(), palloc(), palloc0(), palloc_extended(), repalloc(), repalloc_huge(), SlabContextCreate(), and test_pattern().

◆ MemoryContextStatsDetail()

void MemoryContextStatsDetail ( MemoryContext  context,
int  max_children,
bool  print_to_stderr 
)

Definition at line 520 of file mcxt.c.

522 {
523  MemoryContextCounters grand_totals;
524 
525  memset(&grand_totals, 0, sizeof(grand_totals));
526 
527  MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals, print_to_stderr);
528 
529  if (print_to_stderr)
530  fprintf(stderr,
531  "Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used\n",
532  grand_totals.totalspace, grand_totals.nblocks,
533  grand_totals.freespace, grand_totals.freechunks,
534  grand_totals.totalspace - grand_totals.freespace);
535  else
536 
537  /*
538  * Use LOG_SERVER_ONLY to prevent the memory contexts from being sent
539  * to the connected client.
540  *
541  * We don't buffer the information about all memory contexts in a
542  * backend into StringInfo and log it as one message. Otherwise which
543  * may require the buffer to be enlarged very much and lead to OOM
544  * error since there can be a large number of memory contexts in a
545  * backend. Instead, we log one message per memory context.
546  */
548  (errhidestmt(true),
549  errhidecontext(true),
550  errmsg_internal("Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used",
551  grand_totals.totalspace, grand_totals.nblocks,
552  grand_totals.freespace, grand_totals.freechunks,
553  grand_totals.totalspace - grand_totals.freespace)));
554 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errhidestmt(bool hide_stmt)
Definition: elog.c:1245
int errhidecontext(bool hide_ctx)
Definition: elog.c:1264
#define LOG_SERVER_ONLY
Definition: elog.h:26
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals, bool print_to_stderr)
Definition: mcxt.c:564
#define fprintf
Definition: port.h:229

References ereport, errhidecontext(), errhidestmt(), errmsg_internal(), fprintf, MemoryContextCounters::freechunks, MemoryContextCounters::freespace, LOG_SERVER_ONLY, MemoryContextStatsInternal(), MemoryContextCounters::nblocks, and MemoryContextCounters::totalspace.

Referenced by MemoryContextStats(), and ProcessLogMemoryContextInterrupt().

◆ ProcessLogMemoryContextInterrupt()

void ProcessLogMemoryContextInterrupt ( void  )

Definition at line 1041 of file mcxt.c.

1042 {
1043  LogMemoryContextPending = false;
1044 
1045  /*
1046  * Use LOG_SERVER_ONLY to prevent this message from being sent to the
1047  * connected client.
1048  */
1050  (errhidestmt(true),
1051  errhidecontext(true),
1052  errmsg("logging memory contexts of PID %d", MyProcPid)));
1053 
1054  /*
1055  * When a backend process is consuming huge memory, logging all its memory
1056  * contexts might overrun available disk space. To prevent this, we limit
1057  * the number of child contexts to log per parent to 100.
1058  *
1059  * As with MemoryContextStats(), we suppose that practical cases where the
1060  * dump gets long will typically be huge numbers of siblings under the
1061  * same parent context; while the additional debugging value from seeing
1062  * details about individual siblings beyond 100 will not be large.
1063  */
1065 }
int MyProcPid
Definition: globals.c:44

References ereport, errhidecontext(), errhidestmt(), errmsg(), LOG_SERVER_ONLY, LogMemoryContextPending, MemoryContextStatsDetail(), MyProcPid, and TopMemoryContext.

Referenced by HandleAutoVacLauncherInterrupts(), HandleCheckpointerInterrupts(), HandleMainLoopInterrupts(), HandlePgArchInterrupts(), HandleStartupProcInterrupts(), HandleWalWriterInterrupts(), and ProcessInterrupts().

◆ SlabContextCreate()

MemoryContext SlabContextCreate ( MemoryContext  parent,
const char *  name,
Size  blockSize,
Size  chunkSize 
)

Definition at line 175 of file slab.c.

179 {
180  int chunksPerBlock;
181  Size fullChunkSize;
182  Size freelistSize;
183  Size headerSize;
184  SlabContext *slab;
185  int i;
186 
187  /* Assert we padded SlabChunk properly */
188  StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)),
189  "sizeof(SlabChunk) is not maxaligned");
191  sizeof(SlabChunk),
192  "padding calculation in SlabChunk is wrong");
193 
194  /* Make sure the linked list node fits inside a freed chunk */
195  if (chunkSize < sizeof(int))
196  chunkSize = sizeof(int);
197 
198  /* chunk, including SLAB header (both addresses nicely aligned) */
199  fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize);
200 
201  /* Make sure the block can store at least one chunk. */
202  if (blockSize < fullChunkSize + sizeof(SlabBlock))
203  elog(ERROR, "block size %zu for slab is too small for %zu chunks",
204  blockSize, chunkSize);
205 
206  /* Compute maximum number of chunks per block */
207  chunksPerBlock = (blockSize - sizeof(SlabBlock)) / fullChunkSize;
208 
209  /* The freelist starts with 0, ends with chunksPerBlock. */
210  freelistSize = sizeof(dlist_head) * (chunksPerBlock + 1);
211 
212  /*
213  * Allocate the context header. Unlike aset.c, we never try to combine
214  * this with the first regular block; not worth the extra complication.
215  */
216 
217  /* Size of the memory context header */
218  headerSize = offsetof(SlabContext, freelist) + freelistSize;
219 
220 #ifdef MEMORY_CONTEXT_CHECKING
221 
222  /*
223  * With memory checking, we need to allocate extra space for the bitmap of
224  * free chunks. The bitmap is an array of bools, so we don't need to worry
225  * about alignment.
226  */
227  headerSize += chunksPerBlock * sizeof(bool);
228 #endif
229 
230  slab = (SlabContext *) malloc(headerSize);
231  if (slab == NULL)
232  {
234  ereport(ERROR,
235  (errcode(ERRCODE_OUT_OF_MEMORY),
236  errmsg("out of memory"),
237  errdetail("Failed while creating memory context \"%s\".",
238  name)));
239  }
240 
241  /*
242  * Avoid writing code that can fail between here and MemoryContextCreate;
243  * we'd leak the header if we ereport in this stretch.
244  */
245 
246  /* Fill in SlabContext-specific header fields */
247  slab->chunkSize = chunkSize;
248  slab->fullChunkSize = fullChunkSize;
249  slab->blockSize = blockSize;
250  slab->headerSize = headerSize;
251  slab->chunksPerBlock = chunksPerBlock;
252  slab->minFreeChunks = 0;
253  slab->nblocks = 0;
254 
255  /* initialize the freelist slots */
256  for (i = 0; i < (slab->chunksPerBlock + 1); i++)
257  dlist_init(&slab->freelist[i]);
258 
259 #ifdef MEMORY_CONTEXT_CHECKING
260  /* set the freechunks pointer right after the freelists array */
261  slab->freechunks
262  = (bool *) slab + offsetof(SlabContext, freelist) + freelistSize;
263 #endif
264 
265  /* Finally, do the type-independent part of context creation */
268  &SlabMethods,
269  parent,
270  name);
271 
272  return (MemoryContext) slab;
273 }
unsigned char bool
Definition: c.h:402
struct dlist_head dlist_head
int i
Definition: isn.c:73
@ T_SlabContext
Definition: nodes.h:302
struct SlabBlock SlabBlock
static const MemoryContextMethods SlabMethods
Definition: slab.c:147
struct SlabChunk SlabChunk
Definition: slab.c:89

References SlabContext::blockSize, SlabContext::chunkSize, SlabContext::chunksPerBlock, dlist_init(), elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, SlabContext::freelist, SlabContext::fullChunkSize, SlabContext::headerSize, i, malloc, MAXALIGN, MemoryContextCreate(), MemoryContextStats(), SlabContext::minFreeChunks, name, SlabContext::nblocks, offsetof, SlabMethods, StaticAssertStmt, T_SlabContext, and TopMemoryContext.

Referenced by ReorderBufferAllocate().

Variable Documentation

◆ CacheMemoryContext

PGDLLIMPORT MemoryContext CacheMemoryContext
extern

Definition at line 51 of file mcxt.c.

Referenced by _SPI_save_plan(), AllocateRelationDesc(), assign_record_type_typmod(), AttrDefaultFetch(), BuildEventTriggerCache(), BuildHardcodedDescriptor(), CatalogCacheCreateEntry(), CatalogCacheInitializeCache(), CheckConstraintFetch(), CreateCacheMemoryContext(), ensure_record_cache_typmod_slot_exists(), FetchTableStates(), generate_partition_qual(), get_attribute_options(), get_rel_sync_entry(), get_tablespace(), GetCachedExpression(), GetCachedPlan(), GetFdwRoutineForRelation(), init_ts_config_cache(), init_tuple_slot(), InitCatCache(), InitializeAttoptCache(), InitializeRelfilenodeMap(), InitializeTableSpaceCache(), load_domaintype_info(), load_enum_cache_data(), load_rangetype_info(), load_relcache_init_file(), logicalrep_partmap_init(), logicalrep_relmap_init(), lookup_ts_config_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), pgoutput_startup(), pgstat_prep_pending_entry(), pgstat_setup_memcxt(), register_on_commit_action(), RehashCatCache(), RelationBuildLocalRelation(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildPublicationDesc(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), RelationGetFKeyList(), RelationGetIdentityKeyBitmap(), RelationGetIndexAttrBitmap(), RelationGetIndexList(), RelationGetStatExtList(), RelationInitIndexAccessInfo(), RelationParseRelOptions(), RememberToFreeTupleDescAtEOX(), SaveCachedPlan(), SearchCatCacheList(), set_schema_sent_in_streamed_txn(), and SPI_keepplan().

◆ CurTransactionContext

◆ ErrorContext

◆ MessageContext

◆ PortalContext

◆ PostmasterContext

◆ TopMemoryContext

PGDLLIMPORT MemoryContext TopMemoryContext
extern

Definition at line 48 of file mcxt.c.

Referenced by _PG_init(), add_reloption(), allocate_reloption(), AllocateAttribute(), AllocSetContextCreateInternal(), ApplyLauncherMain(), ApplyWorkerMain(), AtAbort_Memory(), AtCleanup_Memory(), AtCommit_Memory(), AtStart_Memory(), AttachSession(), AutoVacLauncherMain(), BackendRun(), BackgroundWriterMain(), BaseBackupAddTarget(), be_tls_open_server(), cache_single_string(), check_foreign_key(), check_primary_key(), CheckpointerMain(), ClientAuthentication(), compile_plperl_function(), compile_pltcl_function(), CreateCacheMemoryContext(), dblink_connect(), dblink_init(), DCH_cache_getnew(), do_autovacuum(), do_compile(), do_start_bgworker(), dsm_create_descriptor(), dsm_impl_sysv(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), Exec_ListenCommit(), executeDateTimeMethod(), find_plan(), finish_xact_command(), GenerationContextCreate(), GetLocalBufferStorage(), GetLockConflicts(), GetSessionDsmHandle(), HandleParallelMessages(), hash_create(), init_string_reloption(), InitDeadLockChecking(), initialize_reloptions(), initialize_target_list(), InitializeClientEncoding(), InitializeLatchWaitSet(), InitializeParallelDSM(), InitializeSearchPath(), InitializeSession(), InitSync(), InitXLogInsert(), llvm_compile_module(), llvm_create_context(), llvm_session_initialize(), LockAcquireExtended(), LogicalRepApplyLoop(), LWLockRegisterTranche(), make_icu_collator(), MarkGUCPrefixReserved(), mdinit(), MemoryContextAlloc(), MemoryContextAllocExtended(), MemoryContextAllocHuge(), MemoryContextAllocZero(), MemoryContextAllocZeroAligned(), MemoryContextDelete(), MemoryContextInit(), mxid_to_string(), newLOfd(), NUM_cache_getnew(), on_dsm_detach(), PageSetChecksumCopy(), palloc(), palloc0(), palloc_extended(), ParallelWorkerMain(), PerformAuthentication(), pg_backup_start(), pg_get_backend_memory_contexts(), pg_newlocale_from_collation(), pgstat_attach_shmem(), pgstat_prep_snapshot(), pgstat_setup_backend_status_context(), plperl_spi_prepare(), plpgsql_estate_setup(), plpython3_inline_handler(), plsample_func_handler(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_cursor_query(), PLy_procedure_create(), PLy_spi_execute_fetch_result(), PLy_spi_prepare(), populate_typ_list(), PostgresMain(), PostmasterMain(), pq_init(), PrepareClientEncoding(), ProcessLogMemoryContextInterrupt(), ProcessStartupPacket(), PushOverrideSearchPath(), px_find_cipher(), px_find_digest(), recomputeNamespacePath(), register_label_provider(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), RelationCreateStorage(), RelationDropStorage(), repalloc(), repalloc_huge(), RequestNamedLWLockTranche(), ResourceArrayEnlarge(), ResourceOwnerCreate(), RestoreReindexState(), ri_HashCompareOp(), roles_is_member_of(), secure_open_gssapi(), sepgsql_avc_init(), sepgsql_xact_callback(), set_authn_id(), SetDatabasePath(), SharedRecordTypmodRegistryAttach(), SharedRecordTypmodRegistryInit(), SlabContextCreate(), SPI_connect_ext(), StartChildProcess(), WalWriterMain(), and XLOGShmemInit().

◆ TopTransactionContext