PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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.

Data Structures

struct  StandardChunkHeader
 

Macros

#define MaxAllocSize   ((Size) 0x3fffffff) /* 1 gigabyte - 1 */
 
#define AllocSizeIsValid(size)   ((Size) (size) <= MaxAllocSize)
 
#define MaxAllocHugeSize   ((Size) -1 >> 1) /* SIZE_MAX / 2 */
 
#define AllocHugeSizeIsValid(size)   ((Size) (size) <= MaxAllocHugeSize)
 
#define STANDARDCHUNKHEADERSIZE   MAXALIGN(sizeof(StandardChunkHeader))
 
#define MemoryContextResetAndDeleteChildren(ctx)   MemoryContextReset(ctx)
 
#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
 

Typedefs

typedef struct StandardChunkHeader StandardChunkHeader
 

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 MemoryContextSetParent (MemoryContext context, MemoryContext new_parent)
 
Size GetMemoryChunkSpace (void *pointer)
 
MemoryContext GetMemoryChunkContext (void *pointer)
 
MemoryContext MemoryContextGetParent (MemoryContext context)
 
bool MemoryContextIsEmpty (MemoryContext context)
 
void MemoryContextStats (MemoryContext context)
 
void MemoryContextStatsDetail (MemoryContext context, int max_children)
 
void MemoryContextAllowInCriticalSection (MemoryContext context, bool allow)
 
bool MemoryContextContains (MemoryContext context, void *pointer)
 
MemoryContext MemoryContextCreate (NodeTag tag, Size size, MemoryContextMethods *methods, MemoryContext parent, const char *name)
 
MemoryContext AllocSetContextCreate (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

#define AllocHugeSizeIsValid (   size)    ((Size) (size) <= MaxAllocHugeSize)
#define ALLOCSET_DEFAULT_INITSIZE   (8 * 1024)
#define ALLOCSET_DEFAULT_MAXSIZE   (8 * 1024 * 1024)

Definition at line 144 of file memutils.h.

Referenced by ApplyLauncherMain(), ApplyLoop(), pgoutput_startup(), and publicationListToArray().

#define ALLOCSET_DEFAULT_MINSIZE   0

Definition at line 142 of file memutils.h.

Referenced by ApplyLauncherMain(), ApplyLoop(), pgoutput_startup(), and publicationListToArray().

Definition at line 145 of file memutils.h.

Referenced by afterTriggerAddEvent(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), ApplyWorkerMain(), AtStart_Memory(), AtSubStart_Memory(), AutoVacLauncherMain(), BackgroundWriterMain(), begin_heap_rewrite(), BeginCopy(), blbuild(), blinsert(), brin_new_memtuple(), bringetbitmap(), brininsert(), btvacuumscan(), BuildEventTriggerCache(), CheckpointerMain(), cluster(), compute_index_stats(), CopyTo(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContext(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), do_analyze_rel(), do_autovacuum(), do_compile(), do_start_worker(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), EventTriggerInvoke(), exec_parse_message(), exec_replication_command(), ExecHashTableCreate(), ExecInitFunctionScan(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitUnique(), ExecInitWindowAgg(), file_acquire_sample_rows(), geqo_eval(), get_stmt_mcontext(), GetLocalBufferStorage(), gin_xlog_startup(), ginbeginscan(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistrescan(), HandleParallelMessages(), hash_create(), index_register(), init_sql_fcache(), initArrayResult(), initArrayResultArr(), initGISTstate(), initialize_peragg(), InitXLogInsert(), inline_function(), inline_set_returning_function(), logicalrep_relmap_init(), materializeQueryResult(), mdinit(), MemoryContextInit(), NIStartBuild(), ParallelWorkerMain(), PerformAuthentication(), pg_decode_startup(), plperl_return_next(), plperl_spi_prepare(), plpgsql_compile_inline(), plpgsql_estate_setup(), plpython_inline_handler(), PLy_cursor_plan(), PLy_cursor_query(), PLy_get_scratch_context(), PLy_procedure_create(), PLy_spi_execute_fetch_result(), PLy_spi_prepare(), PLyObject_ToComposite(), PLyString_ToComposite(), PortalCreateHoldStore(), postgresBeginForeignScan(), PostgresMain(), PostmasterMain(), printtup_startup(), rebuild_database_list(), RelationBuildPartitionDesc(), ReorderBufferAllocate(), ResetUnloggedRelations(), sepgsql_avc_init(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), SPI_connect(), spi_dest_startup(), StartupDecodingContext(), strlist_to_textarray(), tqueueReceiveSlot(), tuplesort_begin_common(), union_tuples(), vacuum(), WalWriterMain(), and XLOGShmemInit().

#define ALLOCSET_SEPARATE_THRESHOLD   8192
#define ALLOCSET_SMALL_INITSIZE   (1 * 1024)

Definition at line 153 of file memutils.h.

Referenced by get_agg_clause_costs_walker().

#define ALLOCSET_SMALL_MAXSIZE   (8 * 1024)

Definition at line 154 of file memutils.h.

#define ALLOCSET_SMALL_MINSIZE   0

Definition at line 152 of file memutils.h.

#define MaxAllocHugeSize   ((Size) -1 >> 1) /* SIZE_MAX / 2 */

Definition at line 44 of file memutils.h.

Referenced by grow_memtuples(), and qtext_load_file().

#define STANDARDCHUNKHEADERSIZE   MAXALIGN(sizeof(StandardChunkHeader))

Typedef Documentation

Function Documentation

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

Definition at line 440 of file aset.c.

References ALLOC_BLOCKHDRSZ, ALLOC_CHUNK_FRACTION, ALLOC_CHUNK_LIMIT, ALLOC_CHUNKHDRSZ, AllocSetContext::allocChunkLimit, AllocHugeSizeIsValid, ALLOCSET_SEPARATE_THRESHOLD, AllocSetMethods, AllocBlockData::aset, AllocSetContext::blocks, elog, AllocBlockData::endptr, ereport, errcode(), errdetail(), errmsg(), ERROR, AllocBlockData::freeptr, AllocSetContext::initBlockSize, AllocSetContext::keeper, malloc, MAXALIGN, AllocSetContext::maxBlockSize, MemoryContextCreate(), MemoryContextStats(), name, AllocBlockData::next, AllocSetContext::nextBlockSize, NULL, StaticAssertStmt, T_AllocSetContext, TopMemoryContext, and VALGRIND_MAKE_MEM_NOACCESS.

Referenced by _bt_preprocess_array_keys(), _SPI_make_plan_non_temp(), _SPI_save_plan(), afterTriggerAddEvent(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), ApplyLauncherMain(), ApplyLoop(), ApplyWorkerMain(), AtStart_Memory(), AtSubStart_Memory(), AutoVacLauncherMain(), BackgroundWriterMain(), begin_heap_rewrite(), BeginCopy(), blbuild(), blinsert(), brin_build_desc(), brin_new_memtuple(), bringetbitmap(), brininsert(), btvacuumscan(), BuildCachedPlan(), BuildEventTriggerCache(), CheckpointerMain(), cluster(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_index_stats(), CopyCachedPlan(), CopyTo(), CreateCachedPlan(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContext(), CreatePortal(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), do_analyze_rel(), do_autovacuum(), do_compile(), do_start_worker(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), EventTriggerInvoke(), exec_parse_message(), exec_replication_command(), ExecHashTableCreate(), ExecInitFunctionScan(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitUnique(), ExecInitWindowAgg(), expand_array(), file_acquire_sample_rows(), fill_hba_view(), geqo_eval(), get_stmt_mcontext(), GetLocalBufferStorage(), gin_xlog_startup(), ginbeginscan(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistrescan(), HandleParallelMessages(), hash_create(), index_register(), init_MultiFuncCall(), init_sql_fcache(), initArrayResult(), initArrayResultArr(), initGISTstate(), initialize_peragg(), InitXLogInsert(), inline_function(), inline_set_returning_function(), load_domaintype_info(), load_hba(), load_ident(), load_relcache_init_file(), load_tzoffsets(), logicalrep_relmap_init(), lookup_ts_dictionary_cache(), materializeQueryResult(), mdinit(), MemoryContextInit(), mXactCachePut(), NIStartBuild(), ParallelWorkerMain(), PerformAuthentication(), pg_decode_startup(), pgoutput_startup(), pgstat_setup_memcxt(), plperl_return_next(), plperl_spi_prepare(), plpgsql_compile_inline(), plpgsql_estate_setup(), plpython_inline_handler(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_cursor_query(), PLy_get_scratch_context(), PLy_procedure_create(), PLy_spi_execute_fetch_result(), PLy_spi_prepare(), PLyObject_ToComposite(), PLyString_ToComposite(), PortalCreateHoldStore(), postgresAcquireSampleRowsFunc(), postgresBeginDirectModify(), postgresBeginForeignModify(), postgresBeginForeignScan(), PostgresMain(), PostmasterMain(), printtup_startup(), publicationListToArray(), rebuild_database_list(), ReindexMultipleTables(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationInitIndexAccessInfo(), ReorderBufferAllocate(), ResetUnloggedRelations(), RevalidateCachedQuery(), sepgsql_avc_init(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), SPI_connect(), spi_dest_startup(), StartupDecodingContext(), strlist_to_textarray(), tokenize_file(), tqueueReceiveSlot(), tuplesort_begin_common(), union_tuples(), vacuum(), WalWriterMain(), and XLOGShmemInit().

445 {
446  AllocSet set;
447 
448  /*
449  * First, validate allocation parameters. (If we're going to throw an
450  * error, we should do so before the context is created, not after.) We
451  * somewhat arbitrarily enforce a minimum 1K block size.
452  */
453  if (initBlockSize != MAXALIGN(initBlockSize) ||
454  initBlockSize < 1024)
455  elog(ERROR, "invalid initBlockSize for memory context: %zu",
456  initBlockSize);
457  if (maxBlockSize != MAXALIGN(maxBlockSize) ||
458  maxBlockSize < initBlockSize ||
459  !AllocHugeSizeIsValid(maxBlockSize)) /* must be safe to double */
460  elog(ERROR, "invalid maxBlockSize for memory context: %zu",
461  maxBlockSize);
462  if (minContextSize != 0 &&
463  (minContextSize != MAXALIGN(minContextSize) ||
464  minContextSize <= ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ))
465  elog(ERROR, "invalid minContextSize for memory context: %zu",
466  minContextSize);
467 
468  /* Do the type-independent part of context creation */
470  sizeof(AllocSetContext),
472  parent,
473  name);
474 
475  /* Save allocation parameters */
476  set->initBlockSize = initBlockSize;
477  set->maxBlockSize = maxBlockSize;
478  set->nextBlockSize = initBlockSize;
479 
480  /*
481  * Compute the allocation chunk size limit for this context. It can't be
482  * more than ALLOC_CHUNK_LIMIT because of the fixed number of freelists.
483  * If maxBlockSize is small then requests exceeding the maxBlockSize, or
484  * even a significant fraction of it, should be treated as large chunks
485  * too. For the typical case of maxBlockSize a power of 2, the chunk size
486  * limit will be at most 1/8th maxBlockSize, so that given a stream of
487  * requests that are all the maximum chunk size we will waste at most
488  * 1/8th of the allocated space.
489  *
490  * We have to have allocChunkLimit a power of two, because the requested
491  * and actually-allocated sizes of any chunk must be on the same side of
492  * the limit, else we get confused about whether the chunk is "big".
493  *
494  * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD.
495  */
497  "ALLOC_CHUNK_LIMIT != ALLOCSET_SEPARATE_THRESHOLD");
498 
500  while ((Size) (set->allocChunkLimit + ALLOC_CHUNKHDRSZ) >
501  (Size) ((maxBlockSize - ALLOC_BLOCKHDRSZ) / ALLOC_CHUNK_FRACTION))
502  set->allocChunkLimit >>= 1;
503 
504  /*
505  * Grab always-allocated space, if requested
506  */
507  if (minContextSize > 0)
508  {
509  Size blksize = minContextSize;
510  AllocBlock block;
511 
512  block = (AllocBlock) malloc(blksize);
513  if (block == NULL)
514  {
516  ereport(ERROR,
517  (errcode(ERRCODE_OUT_OF_MEMORY),
518  errmsg("out of memory"),
519  errdetail("Failed while creating memory context \"%s\".",
520  name)));
521  }
522  block->aset = set;
523  block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ;
524  block->endptr = ((char *) block) + blksize;
525  block->next = set->blocks;
526  set->blocks = block;
527  /* Mark block as not to be released at reset time */
528  set->keeper = block;
529 
530  /* Mark unallocated space NOACCESS; leave the block header alone. */
532  blksize - ALLOC_BLOCKHDRSZ);
533  }
534 
535  return (MemoryContext) set;
536 }
Size initBlockSize
Definition: aset.c:180
AllocBlock blocks
Definition: aset.c:177
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition: memdebug.h:27
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ALLOC_BLOCKHDRSZ
Definition: aset.c:139
AllocBlock keeper
Definition: aset.c:184
AllocSet aset
Definition: aset.c:203
char * freeptr
Definition: aset.c:205
#define malloc(a)
Definition: header.h:45
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:753
#define ERROR
Definition: elog.h:43
#define ALLOC_CHUNK_LIMIT
Definition: aset.c:123
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:483
char * endptr
Definition: aset.c:206
#define ALLOCSET_SEPARATE_THRESHOLD
Definition: memutils.h:172
int errdetail(const char *fmt,...)
Definition: elog.c:873
MemoryContext MemoryContextCreate(NodeTag tag, Size size, MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:682
#define ALLOC_CHUNKHDRSZ
Definition: aset.c:140
static MemoryContextMethods AllocSetMethods
Definition: aset.c:266
AllocBlock next
Definition: aset.c:204
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define ALLOC_CHUNK_FRACTION
Definition: aset.c:125
struct AllocBlockData * AllocBlock
Definition: aset.c:155
Size nextBlockSize
Definition: aset.c:182
Size allocChunkLimit
Definition: aset.c:183
#define NULL
Definition: c.h:226
size_t Size
Definition: c.h:353
#define MAXALIGN(LEN)
Definition: c.h:584
const char * name
Definition: encode.c:521
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
AllocSetContext * AllocSet
Definition: aset.c:187
#define elog
Definition: elog.h:219
Size maxBlockSize
Definition: aset.c:181
MemoryContext GetMemoryChunkContext ( void *  pointer)

Definition at line 420 of file mcxt.c.

References Assert, AssertArg, StandardChunkHeader::context, header(), MAXALIGN, MemoryContextIsValid, NULL, and STANDARDCHUNKHEADERSIZE.

Referenced by mark_dummy_rel().

421 {
423 
424  /*
425  * Try to detect bogus pointers handed to us, poorly though we can.
426  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
427  * allocated chunk.
428  */
429  Assert(pointer != NULL);
430  Assert(pointer == (void *) MAXALIGN(pointer));
431 
432  /*
433  * OK, it's probably safe to look at the chunk header.
434  */
435  header = (StandardChunkHeader *)
436  ((char *) pointer - STANDARDCHUNKHEADERSIZE);
437 
439 
440  return header->context;
441 }
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define STANDARDCHUNKHEADERSIZE
Definition: memutils.h:67
MemoryContext context
Definition: memutils.h:59
#define MAXALIGN(LEN)
Definition: c.h:584
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:205
Size GetMemoryChunkSpace ( void *  pointer)

Definition at line 390 of file mcxt.c.

References Assert, AssertArg, StandardChunkHeader::context, MemoryContextMethods::get_chunk_space, header(), MAXALIGN, MemoryContextIsValid, MemoryContextData::methods, NULL, and STANDARDCHUNKHEADERSIZE.

Referenced by copytup_cluster(), copytup_heap(), copytup_index(), free_sort_tuple(), getDatumCopy(), ginAllocEntryAccumulator(), ginCombineData(), ginInsertBAEntry(), grow_memtuples(), inittapes(), mergeruns(), readtup_heap(), tuplesort_begin_common(), tuplesort_putdatum(), tuplesort_putindextuplevalues(), tuplestore_begin_common(), tuplestore_clear(), tuplestore_puttupleslot(), tuplestore_putvalues(), tuplestore_trim(), writetup_cluster(), writetup_datum(), writetup_heap(), and writetup_index().

391 {
393 
394  /*
395  * Try to detect bogus pointers handed to us, poorly though we can.
396  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
397  * allocated chunk.
398  */
399  Assert(pointer != NULL);
400  Assert(pointer == (void *) MAXALIGN(pointer));
401 
402  /*
403  * OK, it's probably safe to look at the chunk header.
404  */
405  header = (StandardChunkHeader *)
406  ((char *) pointer - STANDARDCHUNKHEADERSIZE);
407 
409 
410  return (*header->context->methods->get_chunk_space) (header->context,
411  pointer);
412 }
MemoryContextMethods * methods
Definition: memnodes.h:79
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define STANDARDCHUNKHEADERSIZE
Definition: memutils.h:67
MemoryContext context
Definition: memutils.h:59
#define MAXALIGN(LEN)
Definition: c.h:584
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:205
Size(* get_chunk_space)(MemoryContext context, void *pointer)
Definition: memnodes.h:63
void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 374 of file mcxt.c.

References MemoryContextData::allowInCritSection, AssertArg, and MemoryContextIsValid.

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

375 {
377 
378  context->allowInCritSection = allow;
379 }
bool allowInCritSection
Definition: memnodes.h:78
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
bool MemoryContextContains ( MemoryContext  context,
void *  pointer 
)

Definition at line 612 of file mcxt.c.

References StandardChunkHeader::context, header(), MAXALIGN, NULL, and STANDARDCHUNKHEADERSIZE.

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

613 {
615 
616  /*
617  * Try to detect bogus pointers handed to us, poorly though we can.
618  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
619  * allocated chunk.
620  */
621  if (pointer == NULL || pointer != (void *) MAXALIGN(pointer))
622  return false;
623 
624  /*
625  * OK, it's probably safe to look at the chunk header.
626  */
627  header = (StandardChunkHeader *)
628  ((char *) pointer - STANDARDCHUNKHEADERSIZE);
629 
630  return header->context == context;
631 }
#define NULL
Definition: c.h:226
#define STANDARDCHUNKHEADERSIZE
Definition: memutils.h:67
MemoryContext context
Definition: memutils.h:59
#define MAXALIGN(LEN)
Definition: c.h:584
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:205
MemoryContext MemoryContextCreate ( NodeTag  tag,
Size  size,
MemoryContextMethods methods,
MemoryContext  parent,
const char *  name 
)

Definition at line 682 of file mcxt.c.

References MemoryContextData::allowInCritSection, Assert, CritSectionCount, MemoryContextData::firstchild, MemoryContextMethods::init, MemoryContextData::isReset, malloc, MemoryContextAlloc(), MemSet, MemoryContextData::methods, MemoryContextData::name, MemoryContextData::nextchild, NULL, MemoryContextData::parent, MemoryContextData::prevchild, MemoryContextData::type, and VALGRIND_CREATE_MEMPOOL.

Referenced by AllocSetContextCreate().

686 {
687  MemoryContext node;
688  Size needed = size + strlen(name) + 1;
689 
690  /* creating new memory contexts is not allowed in a critical section */
691  Assert(CritSectionCount == 0);
692 
693  /* Get space for node and name */
694  if (TopMemoryContext != NULL)
695  {
696  /* Normal case: allocate the node in TopMemoryContext */
698  needed);
699  }
700  else
701  {
702  /* Special case for startup: use good ol' malloc */
703  node = (MemoryContext) malloc(needed);
704  Assert(node != NULL);
705  }
706 
707  /* Initialize the node as best we can */
708  MemSet(node, 0, size);
709  node->type = tag;
710  node->methods = methods;
711  node->parent = NULL; /* for the moment */
712  node->firstchild = NULL;
713  node->prevchild = NULL;
714  node->nextchild = NULL;
715  node->isReset = true;
716  node->name = ((char *) node) + size;
717  strcpy(node->name, name);
718 
719  /* Type-specific routine finishes any other essential initialization */
720  (*node->methods->init) (node);
721 
722  /* OK to link node to parent (if any) */
723  /* Could use MemoryContextSetParent here, but doesn't seem worthwhile */
724  if (parent)
725  {
726  node->parent = parent;
727  node->nextchild = parent->firstchild;
728  if (parent->firstchild != NULL)
729  parent->firstchild->prevchild = node;
730  parent->firstchild = node;
731  /* inherit allowInCritSection flag from parent */
732  node->allowInCritSection = parent->allowInCritSection;
733  }
734 
735  VALGRIND_CREATE_MEMPOOL(node, 0, false);
736 
737  /* Return to type-specific creation routine to finish up */
738  return node;
739 }
MemoryContextMethods * methods
Definition: memnodes.h:79
bool allowInCritSection
Definition: memnodes.h:78
#define MemSet(start, val, len)
Definition: c.h:853
#define malloc(a)
Definition: header.h:45
MemoryContext firstchild
Definition: memnodes.h:81
MemoryContext prevchild
Definition: memnodes.h:82
volatile uint32 CritSectionCount
Definition: globals.c:36
MemoryContext TopMemoryContext
Definition: mcxt.c:43
struct MemoryContextData * MemoryContext
Definition: palloc.h:36
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
size_t Size
Definition: c.h:353
const char * name
Definition: encode.c:521
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:749
MemoryContext parent
Definition: memnodes.h:80
void(* init)(MemoryContext context)
Definition: memnodes.h:60
MemoryContext nextchild
Definition: memnodes.h:83
NodeTag type
Definition: memnodes.h:75
void MemoryContextDelete ( MemoryContext  context)

Definition at line 200 of file mcxt.c.

References Assert, AssertArg, MemoryContextMethods::delete_context, MemoryContextCallResetCallbacks(), MemoryContextDeleteChildren(), MemoryContextIsValid, MemoryContextSetParent(), MemoryContextData::methods, NULL, pfree(), and VALGRIND_DESTROY_MEMPOOL.

Referenced by AfterTriggerEndXact(), afterTriggerInvokeEvents(), ApplyLauncherMain(), AtCleanup_Memory(), AtCommit_Memory(), AtEOSubXact_SPI(), AtEOXact_LargeObject(), AtSubCleanup_Memory(), AtSubCommit_Memory(), blbuild(), blinsert(), brin_free_desc(), bringetbitmap(), brininsert(), btendscan(), btvacuumscan(), cluster(), compile_plperl_function(), compile_pltcl_function(), compute_index_stats(), CopyTo(), createTrgmNFA(), decr_dcc_refcount(), DeleteExpandedObject(), do_analyze_rel(), do_start_bgworker(), do_start_worker(), DropCachedPlan(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), end_heap_rewrite(), EndCopy(), EventTriggerEndCompleteQuery(), EventTriggerInvoke(), exec_replication_command(), ExecEndRecursiveUnion(), ExecEndSetOp(), ExecEndUnique(), ExecEndWindowAgg(), ExecHashTableDestroy(), file_acquire_sample_rows(), fill_hba_view(), fmgr_sql(), free_plperl_function(), FreeDecodingContext(), FreeExecutorState(), FreeExprContext(), freeGISTstate(), FreeSnapshotBuilder(), geqo_eval(), gin_xlog_cleanup(), ginbuild(), ginbulkdelete(), ginendscan(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gist_xlog_cleanup(), gistbuild(), hash_destroy(), inline_function(), inline_set_returning_function(), load_hba(), load_ident(), load_tzoffsets(), makeArrayResultArr(), makeMdArrayResult(), materializeQueryResult(), MemoryContextDeleteChildren(), mergeruns(), NIFinishBuild(), pg_decode_shutdown(), 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(), PLyObject_ToComposite(), PLyString_ToComposite(), PortalDrop(), PostgresMain(), printtup_shutdown(), publicationListToArray(), rebuild_database_list(), ReindexMultipleTables(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationDestroyRelation(), ReleaseCachedPlan(), ReorderBufferFree(), ResetUnloggedRelations(), RevalidateCachedQuery(), shutdown_MultiFuncCall(), spg_xlog_cleanup(), spgbuild(), spgendscan(), spginsert(), SPI_finish(), SPI_freeplan(), SPI_freetuptable(), StartChildProcess(), strlist_to_textarray(), tokenize_inc_file(), tqueueDestroyReceiver(), tuplesort_end(), union_tuples(), and vacuum().

201 {
203  /* We had better not be deleting TopMemoryContext ... */
204  Assert(context != TopMemoryContext);
205  /* And not CurrentMemoryContext, either */
206  Assert(context != CurrentMemoryContext);
207 
209 
210  /*
211  * It's not entirely clear whether 'tis better to do this before or after
212  * delinking the context; but an error in a callback will likely result in
213  * leaking the whole context (if it's not a root context) if we do it
214  * after, so let's do it before.
215  */
217 
218  /*
219  * We delink the context from its parent before deleting it, so that if
220  * there's an error we won't have deleted/busted contexts still attached
221  * to the context tree. Better a leak than a crash.
222  */
223  MemoryContextSetParent(context, NULL);
224 
225  (*context->methods->delete_context) (context);
226  VALGRIND_DESTROY_MEMPOOL(context);
227  pfree(context);
228 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:282
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:317
MemoryContextMethods * methods
Definition: memnodes.h:79
void(* delete_context)(MemoryContext context)
Definition: memnodes.h:62
void pfree(void *pointer)
Definition: mcxt.c:992
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define AssertArg(condition)
Definition: c.h:673
MemoryContext TopMemoryContext
Definition: mcxt.c:43
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:236
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 236 of file mcxt.c.

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

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

237 {
239 
240  /*
241  * MemoryContextDelete will delink the child from me, so just iterate as
242  * long as there is a child.
243  */
244  while (context->firstchild != NULL)
246 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
MemoryContext firstchild
Definition: memnodes.h:81
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
MemoryContext MemoryContextGetParent ( MemoryContext  context)

Definition at line 448 of file mcxt.c.

References AssertArg, MemoryContextIsValid, and MemoryContextData::parent.

Referenced by advance_combine_function(), advance_transition_function(), advance_windowaggregate(), advance_windowaggregate_base(), GetCachedPlan(), pop_stmt_mcontext(), and push_stmt_mcontext().

449 {
451 
452  return context->parent;
453 }
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
MemoryContext parent
Definition: memnodes.h:80
void MemoryContextInit ( void  )

Definition at line 89 of file mcxt.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), AssertState, MemoryContextAllowInCriticalSection(), NULL, and TopMemoryContext.

Referenced by main().

90 {
92 
93  /*
94  * First, initialize TopMemoryContext, which will hold the MemoryContext
95  * nodes for all other contexts. (There is special-case code in
96  * MemoryContextCreate() to handle this call.)
97  */
99  "TopMemoryContext",
101 
102  /*
103  * Not having any other place to point CurrentMemoryContext, make it point
104  * to TopMemoryContext. Caller should change this soon!
105  */
107 
108  /*
109  * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
110  * we don't really expect much to be allocated in it. More to the point,
111  * require it to contain at least 8K at all times. This is the only case
112  * where retained memory in a context is *essential* --- we want to be
113  * sure ErrorContext still has some memory even if we've run out
114  * elsewhere! Also, allow allocations in ErrorContext within a critical
115  * section. Otherwise a PANIC will cause an assertion failure in the error
116  * reporting code, before printing out the real cause of the failure.
117  *
118  * This should be the last step in this function, as elog.c assumes memory
119  * management works once ErrorContext is non-null.
120  */
122  "ErrorContext",
123  8 * 1024,
124  8 * 1024,
125  8 * 1024);
127 }
#define AssertState(condition)
Definition: c.h:674
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:374
MemoryContext ErrorContext
Definition: mcxt.c:44
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
MemoryContext TopMemoryContext
Definition: mcxt.c:43
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
#define NULL
Definition: c.h:226
bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 460 of file mcxt.c.

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

Referenced by AtSubCommit_Memory().

461 {
463 
464  /*
465  * For now, we consider a memory context nonempty if it has any children;
466  * perhaps this should be changed later.
467  */
468  if (context->firstchild != NULL)
469  return false;
470  /* Otherwise use the type-specific inquiry */
471  return (*context->methods->is_empty) (context);
472 }
MemoryContextMethods * methods
Definition: memnodes.h:79
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:64
MemoryContext firstchild
Definition: memnodes.h:81
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
void MemoryContextReset ( MemoryContext  context)

Definition at line 135 of file mcxt.c.

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

Referenced by _bt_preprocess_array_keys(), AfterTriggerExecute(), bloomBuildCallback(), brin_memtuple_initialize(), btvacuumpage(), buildSubPlanHash(), CopyOneRowTo(), dumpbatch(), 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(), ExecHashTableReset(), ExecMakeTableFunctionResult(), ExecRecursiveUnion(), execTuplesMatch(), execTuplesUnequal(), fetch_more_data(), file_acquire_sample_rows(), gin_redo(), ginBuildCallback(), ginHeapTupleBulkInsert(), ginInsertCleanup(), ginVacuumPostingTreeLeaves(), gist_redo(), gistBuildCallback(), gistgetbitmap(), gistgettuple(), gistinsert(), gistProcessEmptyingQueue(), gistrescan(), gistScanPage(), HandleParallelMessages(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), keyGetItem(), make_tuple_from_result_row(), pg_decode_change(), pgoutput_change(), plperl_return_next(), PLyDict_FromTuple(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), printtup(), printtup_20(), printtup_internal_20(), process_ordered_aggregate_multi(), process_ordered_aggregate_single(), ReScanExprContext(), scanPendingInsert(), sepgsql_avc_reset(), setop_fill_hash_table(), spg_redo(), spginsert(), spgistBuildCallback(), spgWalk(), startScanKey(), storeRow(), tqueueReceiveSlot(), and validate_index_heapscan().

136 {
138 
139  /* save a function call in common case where there are no children */
140  if (context->firstchild != NULL)
142 
143  /* save a function call if no pallocs since startup or last reset */
144  if (!context->isReset)
145  MemoryContextResetOnly(context);
146 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:154
MemoryContext firstchild
Definition: memnodes.h:81
#define AssertArg(condition)
Definition: c.h:673
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:236
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 176 of file mcxt.c.

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

Referenced by MemoryContextResetChildren().

177 {
178  MemoryContext child;
179 
181 
182  for (child = context->firstchild; child != NULL; child = child->nextchild)
183  {
185  MemoryContextResetOnly(child);
186  }
187 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:154
MemoryContext firstchild
Definition: memnodes.h:81
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:176
MemoryContext nextchild
Definition: memnodes.h:83
void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 154 of file mcxt.c.

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

Referenced by MemoryContextReset(), and MemoryContextResetChildren().

155 {
157 
158  /* Nothing to do if no pallocs since startup or last reset */
159  if (!context->isReset)
160  {
162  (*context->methods->reset) (context);
163  context->isReset = true;
164  VALGRIND_DESTROY_MEMPOOL(context);
165  VALGRIND_CREATE_MEMPOOL(context, 0, false);
166  }
167 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:282
MemoryContextMethods * methods
Definition: memnodes.h:79
void(* reset)(MemoryContext context)
Definition: memnodes.h:61
#define AssertArg(condition)
Definition: c.h:673
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 317 of file mcxt.c.

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

Referenced by _SPI_save_plan(), CachedPlanSetParentContext(), CompleteCachedPlan(), exec_parse_message(), GetCachedPlan(), load_domaintype_info(), MemoryContextDelete(), RevalidateCachedQuery(), SaveCachedPlan(), SPI_keepplan(), and TransferExpandedObject().

318 {
320  AssertArg(context != new_parent);
321 
322  /* Fast path if it's got correct parent already */
323  if (new_parent == context->parent)
324  return;
325 
326  /* Delink from existing parent, if any */
327  if (context->parent)
328  {
329  MemoryContext parent = context->parent;
330 
331  if (context->prevchild != NULL)
332  context->prevchild->nextchild = context->nextchild;
333  else
334  {
335  Assert(parent->firstchild == context);
336  parent->firstchild = context->nextchild;
337  }
338 
339  if (context->nextchild != NULL)
340  context->nextchild->prevchild = context->prevchild;
341  }
342 
343  /* And relink */
344  if (new_parent)
345  {
346  AssertArg(MemoryContextIsValid(new_parent));
347  context->parent = new_parent;
348  context->prevchild = NULL;
349  context->nextchild = new_parent->firstchild;
350  if (new_parent->firstchild != NULL)
351  new_parent->firstchild->prevchild = context;
352  new_parent->firstchild = context;
353  }
354  else
355  {
356  context->parent = NULL;
357  context->prevchild = NULL;
358  context->nextchild = NULL;
359  }
360 }
MemoryContext firstchild
Definition: memnodes.h:81
MemoryContext prevchild
Definition: memnodes.h:82
#define AssertArg(condition)
Definition: c.h:673
#define MemoryContextIsValid(context)
Definition: memnodes.h:97
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
MemoryContext parent
Definition: memnodes.h:80
MemoryContext nextchild
Definition: memnodes.h:83
void MemoryContextStats ( MemoryContext  context)

Definition at line 483 of file mcxt.c.

References MemoryContextStatsDetail().

Referenced by AllocSetContextCreate(), finish_xact_command(), MemoryContextAlloc(), MemoryContextAllocExtended(), MemoryContextAllocHuge(), MemoryContextAllocZero(), MemoryContextAllocZeroAligned(), palloc(), palloc0(), palloc_extended(), repalloc(), and repalloc_huge().

484 {
485  /* A hard-wired limit on the number of children is usually good enough */
486  MemoryContextStatsDetail(context, 100);
487 }
void MemoryContextStatsDetail(MemoryContext context, int max_children)
Definition: mcxt.c:495
void MemoryContextStatsDetail ( MemoryContext  context,
int  max_children 
)

Definition at line 495 of file mcxt.c.

References MemoryContextCounters::freechunks, MemoryContextCounters::freespace, MemoryContextStatsInternal(), MemoryContextCounters::nblocks, and MemoryContextCounters::totalspace.

Referenced by MemoryContextStats().

496 {
497  MemoryContextCounters grand_totals;
498 
499  memset(&grand_totals, 0, sizeof(grand_totals));
500 
501  MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals);
502 
503  fprintf(stderr,
504  "Grand total: %zu bytes in %zd blocks; %zu free (%zd chunks); %zu used\n",
505  grand_totals.totalspace, grand_totals.nblocks,
506  grand_totals.freespace, grand_totals.freechunks,
507  grand_totals.totalspace - grand_totals.freespace);
508 }
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals)
Definition: mcxt.c:518

Variable Documentation

PGDLLIMPORT MemoryContext CacheMemoryContext
PGDLLIMPORT MemoryContext TopMemoryContext

Definition at line 43 of file mcxt.c.

Referenced by _PG_init(), add_reloption(), add_string_reloption(), allocate_reloption(), AllocateAttribute(), AllocSetContextCreate(), ApplyLauncherMain(), ApplyLoop(), AtAbort_Memory(), AtCleanup_Memory(), AtCommit_Memory(), AtStart_Memory(), AutoVacLauncherMain(), BackendRun(), BackgroundWriterMain(), be_tls_open_server(), cache_single_time(), CheckpointerMain(), compile_plperl_function(), compile_pltcl_function(), ConditionVariablePrepareToSleep(), ConvertTriggerToFK(), CreateCacheMemoryContext(), dblink_connect(), do_autovacuum(), do_compile(), do_start_bgworker(), dsm_create_descriptor(), dsm_impl_sysv(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), Exec_ListenCommit(), finish_xact_command(), get_tabstat_entry(), GetLocalBufferStorage(), GetLockConflicts(), HandleParallelMessages(), hash_create(), InitDeadLockChecking(), initialize_reloptions(), InitializeParallelDSM(), InitializeSearchPath(), InitXLogInsert(), LockAcquireExtended(), mdinit(), MemoryContextInit(), mxid_to_string(), on_dsm_detach(), PageSetChecksumCopy(), ParallelWorkerMain(), PerformAuthentication(), pg_start_backup(), pgstat_setup_memcxt(), plperl_spi_prepare(), plpgsql_estate_setup(), plpython_inline_handler(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_cursor_query(), PLy_procedure_create(), PLy_spi_execute_fetch_result(), PLy_spi_prepare(), PostgresMain(), PostmasterMain(), pq_init(), PrepareClientEncoding(), ProcessStartupPacket(), PushOverrideSearchPath(), px_find_cipher(), px_find_digest(), recomputeNamespacePath(), register_label_provider(), RegisterLWLockTranches(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), regress_putenv(), RelationCreateStorage(), RelationDropStorage(), RequestNamedLWLockTranche(), ResourceArrayEnlarge(), ResourceOwnerCreate(), ri_HashCompareOp(), roles_has_privs_of(), roles_is_member_of(), sepgsql_avc_init(), sepgsql_xact_callback(), SetDatabasePath(), StartChildProcess(), WalWriterMain(), and XLOGShmemInit().