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 blockSize)
 

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

◆ ALLOCSET_DEFAULT_INITSIZE

#define ALLOCSET_DEFAULT_INITSIZE   (8 * 1024)

◆ ALLOCSET_DEFAULT_MAXSIZE

#define ALLOCSET_DEFAULT_MAXSIZE   (8 * 1024 * 1024)

Definition at line 194 of file memutils.h.

Referenced by CreateWorkExprContext().

◆ ALLOCSET_DEFAULT_MINSIZE

#define ALLOCSET_DEFAULT_MINSIZE   0

Definition at line 192 of file memutils.h.

Referenced by AllocSetContextCreateInternal(), and CreateWorkExprContext().

◆ ALLOCSET_DEFAULT_SIZES

Definition at line 195 of file memutils.h.

Referenced by afterTriggerAddEvent(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), ApplyLauncherMain(), ApplyWorkerMain(), AtStart_Memory(), AtSubStart_Memory(), AttachPartitionEnsureIndexes(), AutoVacLauncherMain(), BackgroundWriterMain(), begin_heap_rewrite(), BeginCopyFrom(), BeginCopyTo(), blbuild(), blinsert(), brin_minmax_multi_union(), brin_new_memtuple(), bringetbitmap(), brininsert(), bt_check_every_level(), btree_xlog_startup(), btvacuumscan(), BuildEventTriggerCache(), BuildParamLogString(), BuildRelationExtStatistics(), CheckpointerMain(), cluster(), compactify_ranges(), compute_expr_stats(), compute_index_stats(), ComputeExtStatisticsRows(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContext(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), do_analyze_rel(), do_autovacuum(), do_compile(), do_start_worker(), DoCopyTo(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), EnablePortalManager(), ensure_free_space_in_buffer(), EventTriggerBeginCompleteQuery(), EventTriggerInvoke(), exec_parse_message(), exec_replication_command(), exec_simple_query(), ExecCreatePartitionPruneState(), ExecHashTableCreate(), ExecInitAgg(), ExecInitFunctionScan(), ExecInitMemoize(), ExecInitProjectSet(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitTableFuncScan(), ExecInitWindowAgg(), execute_sql_string(), file_acquire_sample_rows(), geqo_eval(), get_actual_variable_range(), 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(), InitSync(), InitXLogInsert(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), logicalrep_partmap_init(), logicalrep_relmap_init(), LogicalRepApplyLoop(), make_expanded_record_from_datum(), make_expanded_record_from_exprecord(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), mdinit(), MemoryContextInit(), NIStartBuild(), ParallelWorkerMain(), PerformAuthentication(), pg_decode_startup(), pgoutput_startup(), plperl_return_next_internal(), 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(), PortalCreateHoldStore(), postgresBeginForeignScan(), PostgresMain(), PostmasterMain(), printtup_startup(), publicationListToArray(), rebuild_database_list(), ReindexPartitions(), RelationBuildDesc(), ReorderBufferAllocate(), ResetUnloggedRelations(), sepgsql_avc_init(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), SPI_connect_ext(), spi_dest_startup(), StartupDecodingContext(), statext_dependencies_build(), strlist_to_textarray(), tuplesort_begin_batch(), tuplesort_begin_common(), union_tuples(), vacuum(), WalWriterMain(), XLOGShmemInit(), and xml_is_document().

◆ ALLOCSET_SEPARATE_THRESHOLD

#define ALLOCSET_SEPARATE_THRESHOLD   8192

Definition at line 222 of file memutils.h.

Referenced by AllocSetContextCreateInternal(), and tuplestore_begin_common().

◆ ALLOCSET_SMALL_INITSIZE

#define ALLOCSET_SMALL_INITSIZE   (1 * 1024)

Definition at line 203 of file memutils.h.

Referenced by AllocSetContextCreateInternal(), and get_agg_clause_costs().

◆ ALLOCSET_SMALL_MAXSIZE

#define ALLOCSET_SMALL_MAXSIZE   (8 * 1024)

Definition at line 204 of file memutils.h.

◆ ALLOCSET_SMALL_MINSIZE

#define ALLOCSET_SMALL_MINSIZE   0

Definition at line 202 of file memutils.h.

Referenced by AllocSetContextCreateInternal().

◆ ALLOCSET_SMALL_SIZES

◆ ALLOCSET_START_SMALL_SIZES

◆ AllocSetContextCreate

#define AllocSetContextCreate   AllocSetContextCreateInternal

Definition at line 173 of file memutils.h.

Referenced by _bt_preprocess_array_keys(), _SPI_make_plan_non_temp(), _SPI_save_plan(), afterTriggerAddEvent(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), ApplyLauncherMain(), ApplyWorkerMain(), AtStart_Memory(), AtSubStart_Memory(), AttachPartitionEnsureIndexes(), AutoVacLauncherMain(), BackgroundWriterMain(), begin_heap_rewrite(), BeginCopyFrom(), BeginCopyTo(), blbuild(), blinsert(), brin_build_desc(), brin_minmax_multi_union(), brin_new_memtuple(), bringetbitmap(), brininsert(), bt_check_every_level(), btree_xlog_startup(), btvacuumscan(), BuildCachedPlan(), BuildEventTriggerCache(), BuildParamLogString(), BuildRelationExtStatistics(), CheckpointerMain(), CloneRowTriggersToPartition(), cluster(), compactify_ranges(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_expr_stats(), compute_index_stats(), ComputeExtStatisticsRows(), CopyCachedPlan(), create_foreign_modify(), CreateCachedPlan(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContextInternal(), CreatePortal(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), CreateTriggerFiringOn(), DiscreteKnapsack(), do_analyze_rel(), do_autovacuum(), do_compile(), do_start_worker(), DoCopyTo(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), EnablePortalManager(), ensure_free_space_in_buffer(), EventTriggerBeginCompleteQuery(), EventTriggerInvoke(), exec_parse_message(), exec_replication_command(), exec_simple_query(), ExecCreatePartitionPruneState(), ExecHashTableCreate(), ExecInitAgg(), ExecInitFunctionScan(), ExecInitMemoize(), ExecInitProjectSet(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitTableFuncScan(), ExecInitWindowAgg(), execute_sql_string(), expand_array(), file_acquire_sample_rows(), fill_hba_view(), generate_partition_qual(), geqo_eval(), get_actual_variable_range(), get_short_term_cxt(), get_stmt_mcontext(), GetCachedExpression(), 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(), InitSync(), InitXLogInsert(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), load_domaintype_info(), load_hba(), load_ident(), load_relcache_init_file(), load_tzoffsets(), logicalrep_partmap_init(), logicalrep_relmap_init(), LogicalRepApplyLoop(), lookup_ts_dictionary_cache(), make_expanded_record_from_datum(), make_expanded_record_from_exprecord(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), mdinit(), MemoryContextInit(), mXactCachePut(), NIStartBuild(), ParallelWorkerMain(), PerformAuthentication(), pg_decode_startup(), pgoutput_startup(), pgstat_setup_backend_status_context(), pgstat_setup_memcxt(), plperl_return_next_internal(), plperl_spi_prepare(), plpgsql_compile_inline(), plpgsql_estate_setup(), plpython_inline_handler(), plsample_func_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(), PortalCreateHoldStore(), postgresAcquireSampleRowsFunc(), postgresBeginDirectModify(), postgresBeginForeignScan(), PostgresMain(), PostmasterMain(), printtup_startup(), publicationListToArray(), rebuild_database_list(), ReindexMultipleTables(), ReindexPartitions(), ReindexRelationConcurrently(), RelationBuildDesc(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationInitIndexAccessInfo(), ReorderBufferAllocate(), ResetUnloggedRelations(), RevalidateCachedQuery(), sepgsql_avc_init(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), SPI_connect_ext(), spi_dest_startup(), StartupDecodingContext(), statext_dependencies_build(), strlist_to_textarray(), test_pattern(), tokenize_file(), tuplesort_begin_batch(), tuplesort_begin_common(), union_tuples(), vacuum(), validateForeignKeyConstraint(), WalWriterMain(), XLOGShmemInit(), and xml_is_document().

◆ AllocSizeIsValid

◆ MaxAllocHugeSize

#define MaxAllocHugeSize   (SIZE_MAX / 2)

◆ MaxAllocSize

◆ MemoryContextCopyAndSetIdentifier

◆ MemoryContextResetAndDeleteChildren

◆ SLAB_DEFAULT_BLOCK_SIZE

#define SLAB_DEFAULT_BLOCK_SIZE   (8 * 1024)

Definition at line 224 of file memutils.h.

Referenced by ReorderBufferAllocate().

◆ SLAB_LARGE_BLOCK_SIZE

#define SLAB_LARGE_BLOCK_SIZE   (8 * 1024 * 1024)

Definition at line 225 of file memutils.h.

Referenced by ReorderBufferAllocate().

Function Documentation

◆ AllocSetContextCreateInternal()

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

Definition at line 379 of file aset.c.

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

Referenced by GetMemoryChunkContext().

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 MemSetAligned(start, val, len)
Definition: c.h:1041
MemoryContextData header
Definition: aset.c:123
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition: memdebug.h:27
int num_free
Definition: aset.c:248
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ALLOC_BLOCKHDRSZ
Definition: aset.c:100
AllocSet aset
Definition: aset.c:153
char * freeptr
Definition: aset.c:156
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:192
#define ALLOCSET_SMALL_MINSIZE
Definition: memutils.h:202
AllocSetContext * first_free
Definition: aset.c:249
#define malloc(a)
Definition: header.h:50
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
static AllocSetFreeList context_freelists[2]
Definition: aset.c:253
#define ERROR
Definition: elog.h:46
#define ALLOC_CHUNK_LIMIT
Definition: aset.c:81
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:505
char * endptr
Definition: aset.c:157
#define ALLOCSET_SEPARATE_THRESHOLD
Definition: memutils.h:222
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define ALLOC_CHUNKHDRSZ
Definition: aset.c:101
AllocBlock next
Definition: aset.c:155
void MemoryContextCreate(MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:815
MemoryContext TopMemoryContext
Definition: mcxt.c:48
struct MemoryContextData * MemoryContext
Definition: palloc.h:36
#define ALLOCSET_SMALL_INITSIZE
Definition: memutils.h:203
#define ALLOC_CHUNK_FRACTION
Definition: aset.c:83
struct AllocBlockData * AllocBlock
Definition: aset.c:103
#define ereport(elevel,...)
Definition: elog.h:157
AllocBlock prev
Definition: aset.c:154
#define Max(x, y)
Definition: c.h:980
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
const char * name
Definition: encode.c:561
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:193
static const MemoryContextMethods AllocSetMethods
Definition: aset.c:285
AllocSetContext * AllocSet
Definition: aset.c:137
#define offsetof(type, field)
Definition: c.h:727
MemoryContext nextchild
Definition: memnodes.h:89

◆ GenerationContextCreate()

MemoryContext GenerationContextCreate ( MemoryContext  parent,
const char *  name,
Size  blockSize 
)

Definition at line 197 of file generation.c.

References AllocHugeSizeIsValid, GenerationContext::blockSize, dlist_init(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, Generation_CHUNKHDRSZ, malloc, MAXALIGN, MemoryContextCreate(), MemoryContextStats(), offsetof, StaticAssertStmt, T_GenerationContext, and TopMemoryContext.

Referenced by gistvacuumscan(), and ReorderBufferAllocate().

200 {
201  GenerationContext *set;
202 
203  /* Assert we padded GenerationChunk properly */
205  "sizeof(GenerationChunk) is not maxaligned");
208  "padding calculation in GenerationChunk is wrong");
209 
210  /*
211  * First, validate allocation parameters. (If we're going to throw an
212  * error, we should do so before the context is created, not after.) We
213  * somewhat arbitrarily enforce a minimum 1K block size, mostly because
214  * that's what AllocSet does.
215  */
216  if (blockSize != MAXALIGN(blockSize) ||
217  blockSize < 1024 ||
218  !AllocHugeSizeIsValid(blockSize))
219  elog(ERROR, "invalid blockSize for memory context: %zu",
220  blockSize);
221 
222  /*
223  * Allocate the context header. Unlike aset.c, we never try to combine
224  * this with the first regular block, since that would prevent us from
225  * freeing the first generation of allocations.
226  */
227 
229  if (set == NULL)
230  {
232  ereport(ERROR,
233  (errcode(ERRCODE_OUT_OF_MEMORY),
234  errmsg("out of memory"),
235  errdetail("Failed while creating memory context \"%s\".",
236  name)));
237  }
238 
239  /*
240  * Avoid writing code that can fail between here and MemoryContextCreate;
241  * we'd leak the header if we ereport in this stretch.
242  */
243 
244  /* Fill in GenerationContext-specific header fields */
245  set->blockSize = blockSize;
246  set->block = NULL;
247  dlist_init(&set->blocks);
248 
249  /* Finally, do the type-independent part of context creation */
253  parent,
254  name);
255 
256  return (MemoryContext) set;
257 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define malloc(a)
Definition: header.h:50
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
#define ERROR
Definition: elog.h:46
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:505
int errdetail(const char *fmt,...)
Definition: elog.c:1042
static const MemoryContextMethods GenerationMethods
Definition: generation.c:168
void MemoryContextCreate(MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:815
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define ereport(elevel,...)
Definition: elog.h:157
#define MAXALIGN(LEN)
Definition: c.h:757
const char * name
Definition: encode.c:561
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define Generation_CHUNKHDRSZ
Definition: generation.c:47
#define offsetof(type, field)
Definition: c.h:727

◆ GetMemoryChunkContext()

static MemoryContext GetMemoryChunkContext ( void *  pointer)
inlinestatic

Definition at line 114 of file memutils.h.

References AllocSetContextCreateInternal(), Assert, AssertArg, HandleLogMemoryContextInterrupt(), MAXALIGN, MemoryContextCreate(), MemoryContextIsValid, name, and ProcessLogMemoryContextInterrupt().

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

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:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
#define Assert(condition)
Definition: c.h:804
#define MAXALIGN(LEN)
Definition: c.h:757

◆ GetMemoryChunkSpace()

◆ HandleLogMemoryContextInterrupt()

void HandleLogMemoryContextInterrupt ( void  )

Definition at line 1024 of file mcxt.c.

References InterruptPending, and LogMemoryContextPending.

Referenced by GetMemoryChunkContext(), and procsignal_sigusr1_handler().

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

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 418 of file mcxt.c.

References MemoryContextData::allowInCritSection, AssertArg, and MemoryContextIsValid.

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

419 {
421 
422  context->allowInCritSection = allow;
423 }
bool allowInCritSection
Definition: memnodes.h:83
#define AssertArg(condition)
Definition: c.h:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104

◆ MemoryContextContains()

bool MemoryContextContains ( MemoryContext  context,
void *  pointer 
)

Definition at line 758 of file mcxt.c.

References MAXALIGN.

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

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 }
#define MAXALIGN(LEN)
Definition: c.h:757

◆ MemoryContextCreate()

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

Definition at line 815 of file mcxt.c.

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

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

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 }
MemoryContextCallback * reset_cbs
Definition: memnodes.h:92
const MemoryContextMethods * methods
Definition: memnodes.h:85
bool allowInCritSection
Definition: memnodes.h:83
MemoryContext firstchild
Definition: memnodes.h:87
MemoryContext prevchild
Definition: memnodes.h:88
volatile uint32 CritSectionCount
Definition: globals.c:41
const char * ident
Definition: memnodes.h:91
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define Assert(condition)
Definition: c.h:804
const char * name
Definition: encode.c:561
Size mem_allocated
Definition: memnodes.h:84
MemoryContext parent
Definition: memnodes.h:86
const char * name
Definition: memnodes.h:90
MemoryContext nextchild
Definition: memnodes.h:89
NodeTag type
Definition: memnodes.h:80

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 218 of file mcxt.c.

References Assert, AssertArg, MemoryContextMethods::delete_context, MemoryContextData::firstchild, MemoryContextData::ident, MemoryContextCallResetCallbacks(), MemoryContextDeleteChildren(), MemoryContextIsValid, MemoryContextSetParent(), MemoryContextData::methods, 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(), fmgr_sql(), free_plperl_function(), FreeCachedExpression(), FreeDecodingContext(), FreeExecutorState(), FreeExprContext(), freeGISTstate(), FreeSnapshotBuilder(), geqo_eval(), get_actual_variable_range(), 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(), 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().

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
const MemoryContextMethods * methods
Definition: memnodes.h:85
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:361
MemoryContext firstchild
Definition: memnodes.h:87
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
#define AssertArg(condition)
Definition: c.h:806
const char * ident
Definition: memnodes.h:91
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:263
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
#define Assert(condition)
Definition: c.h:804
void(* delete_context)(MemoryContext context)
Definition: memnodes.h:65

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 263 of file mcxt.c.

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

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

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
MemoryContext firstchild
Definition: memnodes.h:87
#define AssertArg(condition)
Definition: c.h:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

Definition at line 446 of file mcxt.c.

References AssertArg, MemoryContextIsValid, and MemoryContextData::parent.

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

447 {
449 
450  return context->parent;
451 }
#define AssertArg(condition)
Definition: c.h:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
MemoryContext parent
Definition: memnodes.h:86

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 99 of file mcxt.c.

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

Referenced by main().

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 AllocSetContextCreate
Definition: memutils.h:173
#define AssertState(condition)
Definition: c.h:807
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:418
MemoryContext ErrorContext
Definition: mcxt.c:49
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
MemoryContext TopMemoryContext
Definition: mcxt.c:48

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 458 of file mcxt.c.

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

Referenced by AtSubCommit_Memory().

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 }
const MemoryContextMethods * methods
Definition: memnodes.h:85
MemoryContext firstchild
Definition: memnodes.h:87
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:67
#define AssertArg(condition)
Definition: c.h:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104

◆ MemoryContextMemAllocated()

Size MemoryContextMemAllocated ( MemoryContext  context,
bool  recurse 
)

Definition at line 477 of file mcxt.c.

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

Referenced by hash_agg_check_limits(), hash_agg_update_metrics(), and MemoryContextMemAllocated().

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 }
MemoryContext firstchild
Definition: memnodes.h:87
#define AssertArg(condition)
Definition: c.h:806
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition: mcxt.c:477
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
size_t Size
Definition: c.h:540
Size mem_allocated
Definition: memnodes.h:84
MemoryContext nextchild
Definition: memnodes.h:89

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 143 of file mcxt.c.

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

Referenced by _bt_preprocess_array_keys(), AfterTriggerExecute(), apply_handle_stream_stop(), apply_spooled_messages(), bloomBuildCallback(), brin_memtuple_initialize(), bt_check_level_from_leftmost(), btree_redo(), btvacuumpage(), BuildRelationExtStatistics(), buildSubPlanHash(), 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(), ExecFindInitialMatchingSubPlans(), 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().

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
MemoryContext firstchild
Definition: memnodes.h:87
#define AssertArg(condition)
Definition: c.h:806
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:263
#define MemoryContextIsValid(context)
Definition: memnodes.h:104

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 195 of file mcxt.c.

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

Referenced by MemoryContextResetChildren().

196 {
197  MemoryContext child;
198 
200 
201  for (child = context->firstchild; child != NULL; child = child->nextchild)
202  {
204  MemoryContextResetOnly(child);
205  }
206 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:162
MemoryContext firstchild
Definition: memnodes.h:87
#define AssertArg(condition)
Definition: c.h:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:195
MemoryContext nextchild
Definition: memnodes.h:89

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 162 of file mcxt.c.

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

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

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 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:309
const MemoryContextMethods * methods
Definition: memnodes.h:85
void(* reset)(MemoryContext context)
Definition: memnodes.h:64
#define AssertArg(condition)
Definition: c.h:806
#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:104

◆ MemoryContextSetIdentifier()

void MemoryContextSetIdentifier ( MemoryContext  context,
const char *  id 
)

Definition at line 336 of file mcxt.c.

References AssertArg, MemoryContextData::ident, and MemoryContextIsValid.

Referenced by compile_plperl_function(), compile_pltcl_function(), CopyCachedPlan(), CreateCachedPlan(), CreatePortal(), do_compile(), hash_create(), init_sql_fcache(), lookup_ts_dictionary_cache(), PLy_procedure_create(), and test_pattern().

337 {
339  context->ident = id;
340 }
#define AssertArg(condition)
Definition: c.h:806
const char * ident
Definition: memnodes.h:91
#define MemoryContextIsValid(context)
Definition: memnodes.h:104

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 361 of file mcxt.c.

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().

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 }
MemoryContext firstchild
Definition: memnodes.h:87
MemoryContext prevchild
Definition: memnodes.h:88
#define AssertArg(condition)
Definition: c.h:806
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
#define Assert(condition)
Definition: c.h:804
MemoryContext parent
Definition: memnodes.h:86
MemoryContext nextchild
Definition: memnodes.h:89

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

Definition at line 505 of file mcxt.c.

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().

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

◆ MemoryContextStatsDetail()

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

Definition at line 520 of file mcxt.c.

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().

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 %zd blocks; %zu free (%zd 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 %zd blocks; %zu free (%zd 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 }
#define LOG_SERVER_ONLY
Definition: elog.h:28
int errhidestmt(bool hide_stmt)
Definition: elog.c:1250
#define fprintf
Definition: port.h:221
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals, bool print_to_stderr)
Definition: mcxt.c:564
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
int errhidecontext(bool hide_ctx)
Definition: elog.c:1269

◆ ProcessLogMemoryContextInterrupt()

void ProcessLogMemoryContextInterrupt ( void  )

Definition at line 1041 of file mcxt.c.

References ereport, errmsg(), LOG, LogMemoryContextPending, MemoryContextStatsDetail(), and MyProcPid.

Referenced by GetMemoryChunkContext(), HandleAutoVacLauncherInterrupts(), and ProcessInterrupts().

1042 {
1043  LogMemoryContextPending = false;
1044 
1045  ereport(LOG,
1046  (errmsg("logging memory contexts of PID %d", MyProcPid)));
1047 
1048  /*
1049  * When a backend process is consuming huge memory, logging all its memory
1050  * contexts might overrun available disk space. To prevent this, we limit
1051  * the number of child contexts to log per parent to 100.
1052  *
1053  * As with MemoryContextStats(), we suppose that practical cases where the
1054  * dump gets long will typically be huge numbers of siblings under the
1055  * same parent context; while the additional debugging value from seeing
1056  * details about individual siblings beyond 100 will not be large.
1057  */
1059 }
int MyProcPid
Definition: globals.c:43
#define LOG
Definition: elog.h:26
void MemoryContextStatsDetail(MemoryContext context, int max_children, bool print_to_stderr)
Definition: mcxt.c:520
MemoryContext TopMemoryContext
Definition: mcxt.c:48
#define ereport(elevel,...)
Definition: elog.h:157
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ SlabContextCreate()

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

Definition at line 175 of file slab.c.

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(), offsetof, StaticAssertStmt, T_SlabContext, and TopMemoryContext.

Referenced by ReorderBufferAllocate().

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 }
struct dlist_head dlist_head
int errcode(int sqlerrcode)
Definition: elog.c:698
#define malloc(a)
Definition: header.h:50
static const MemoryContextMethods SlabMethods
Definition: slab.c:147
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
#define ERROR
Definition: elog.h:46
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:505
int errdetail(const char *fmt,...)
Definition: elog.c:1042
void MemoryContextCreate(MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:815
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define ereport(elevel,...)
Definition: elog.h:157
struct SlabBlock SlabBlock
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
const char * name
Definition: encode.c:561
Definition: slab.c:88
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
int i
struct SlabChunk SlabChunk
#define offsetof(type, field)
Definition: c.h:727
unsigned char bool
Definition: c.h:391

Variable Documentation

◆ CacheMemoryContext

PGDLLIMPORT MemoryContext CacheMemoryContext

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(), GetRelationPublicationActions(), init_ts_config_cache(), 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(), maybe_send_schema(), pgoutput_startup(), register_on_commit_action(), RehashCatCache(), RelationBuildLocalRelation(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), 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

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(), be_tls_open_server(), cache_single_string(), check_foreign_key(), check_primary_key(), CheckMD5Auth(), 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(), get_tabstat_entry(), GetLocalBufferStorage(), GetLockConflicts(), GetSessionDsmHandle(), HandleParallelMessages(), hash_create(), init_string_reloption(), InitDeadLockChecking(), initialize_reloptions(), InitializeClientEncoding(), InitializeLatchWaitSet(), InitializeParallelDSM(), InitializeSearchPath(), InitializeSession(), InitSync(), InitXLogInsert(), llvm_compile_module(), llvm_create_context(), llvm_session_initialize(), LockAcquireExtended(), LogicalRepApplyLoop(), LWLockRegisterTranche(), mdinit(), MemoryContextInit(), mxid_to_string(), NUM_cache_getnew(), on_dsm_detach(), PageSetChecksumCopy(), ParallelWorkerMain(), PerformAuthentication(), pg_get_backend_memory_contexts(), pg_newlocale_from_collation(), pg_start_backup(), pgstat_setup_backend_status_context(), pgstat_setup_memcxt(), plperl_spi_prepare(), plpgsql_estate_setup(), plpython_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(), ProcessStartupPacket(), PushOverrideSearchPath(), px_find_cipher(), px_find_digest(), recomputeNamespacePath(), register_label_provider(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), RelationCreateStorage(), RelationDropStorage(), 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(), XLOGShmemInit(), and xml_is_document().

◆ TopTransactionContext