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)
 
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)
 
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 191 of file memutils.h.

Referenced by CreateWorkExprContext().

◆ ALLOCSET_DEFAULT_MINSIZE

#define ALLOCSET_DEFAULT_MINSIZE   0

Definition at line 189 of file memutils.h.

Referenced by AllocSetContextCreateInternal(), and CreateWorkExprContext().

◆ ALLOCSET_DEFAULT_SIZES

Definition at line 192 of file memutils.h.

Referenced by afterTriggerAddEvent(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), ApplyLauncherMain(), ApplyWorkerMain(), AtStart_Memory(), AtSubStart_Memory(), AttachPartitionEnsureIndexes(), AutoVacLauncherMain(), BackgroundWriterMain(), begin_heap_rewrite(), BeginCopy(), blbuild(), blinsert(), brin_new_memtuple(), bringetbitmap(), brininsert(), bt_check_every_level(), btree_xlog_startup(), btvacuumscan(), BuildEventTriggerCache(), BuildParamLogString(), BuildRelationExtStatistics(), CheckpointerMain(), cluster(), compute_index_stats(), ComputeExtStatisticsRows(), 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(), exec_simple_query(), ExecCreatePartitionPruneState(), ExecHashTableCreate(), ExecInitAgg(), ExecInitFunctionScan(), 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(), 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 219 of file memutils.h.

Referenced by AllocSetContextCreateInternal(), and tuplestore_begin_common().

◆ ALLOCSET_SMALL_INITSIZE

#define ALLOCSET_SMALL_INITSIZE   (1 * 1024)

Definition at line 200 of file memutils.h.

Referenced by AllocSetContextCreateInternal(), and get_agg_clause_costs_walker().

◆ ALLOCSET_SMALL_MAXSIZE

#define ALLOCSET_SMALL_MAXSIZE   (8 * 1024)

Definition at line 201 of file memutils.h.

◆ ALLOCSET_SMALL_MINSIZE

#define ALLOCSET_SMALL_MINSIZE   0

Definition at line 199 of file memutils.h.

Referenced by AllocSetContextCreateInternal().

◆ ALLOCSET_SMALL_SIZES

◆ ALLOCSET_START_SMALL_SIZES

◆ AllocSetContextCreate

#define AllocSetContextCreate   AllocSetContextCreateInternal

Definition at line 170 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(), BeginCopy(), blbuild(), blinsert(), brin_build_desc(), brin_new_memtuple(), bringetbitmap(), brininsert(), bt_check_every_level(), btree_xlog_startup(), btvacuumscan(), BuildCachedPlan(), BuildEventTriggerCache(), BuildParamLogString(), BuildRelationExtStatistics(), CheckpointerMain(), CloneRowTriggersToPartition(), cluster(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_index_stats(), ComputeExtStatisticsRows(), CopyCachedPlan(), CopyTo(), create_foreign_modify(), CreateCachedPlan(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContextInternal(), CreatePortal(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), CreateTrigger(), DiscreteKnapsack(), 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(), exec_simple_query(), ExecCreatePartitionPruneState(), ExecHashTableCreate(), ExecInitAgg(), ExecInitFunctionScan(), 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_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(), 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 221 of file memutils.h.

Referenced by ReorderBufferAllocate().

◆ SLAB_LARGE_BLOCK_SIZE

#define SLAB_LARGE_BLOCK_SIZE   (8 * 1024 * 1024)

Definition at line 222 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 378 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().

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

◆ GenerationContextCreate()

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

Definition at line 196 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().

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

◆ GetMemoryChunkContext()

static MemoryContext GetMemoryChunkContext ( void *  pointer)
inlinestatic

Definition at line 113 of file memutils.h.

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

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

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

◆ GetMemoryChunkSpace()

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 412 of file mcxt.c.

References MemoryContextData::allowInCritSection, AssertArg, and MemoryContextIsValid.

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

413 {
415 
416  context->allowInCritSection = allow;
417 }
bool allowInCritSection
Definition: memnodes.h:81
#define AssertArg(condition)
Definition: c.h:747
#define MemoryContextIsValid(context)
Definition: memnodes.h:102

◆ MemoryContextContains()

bool MemoryContextContains ( MemoryContext  context,
void *  pointer 
)

Definition at line 692 of file mcxt.c.

References MAXALIGN.

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

693 {
694  MemoryContext ptr_context;
695 
696  /*
697  * NB: Can't use GetMemoryChunkContext() here - that performs assertions
698  * that aren't acceptable here since we might be passed memory not
699  * allocated by any memory context.
700  *
701  * Try to detect bogus pointers handed to us, poorly though we can.
702  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
703  * allocated chunk.
704  */
705  if (pointer == NULL || pointer != (void *) MAXALIGN(pointer))
706  return false;
707 
708  /*
709  * OK, it's probably safe to look at the context.
710  */
711  ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
712 
713  return ptr_context == context;
714 }
#define MAXALIGN(LEN)
Definition: c.h:698

◆ MemoryContextCreate()

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

Definition at line 749 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().

754 {
755  /* Creating new memory contexts is not allowed in a critical section */
756  Assert(CritSectionCount == 0);
757 
758  /* Initialize all standard fields of memory context header */
759  node->type = tag;
760  node->isReset = true;
761  node->methods = methods;
762  node->parent = parent;
763  node->firstchild = NULL;
764  node->mem_allocated = 0;
765  node->prevchild = NULL;
766  node->name = name;
767  node->ident = NULL;
768  node->reset_cbs = NULL;
769 
770  /* OK to link node into context tree */
771  if (parent)
772  {
773  node->nextchild = parent->firstchild;
774  if (parent->firstchild != NULL)
775  parent->firstchild->prevchild = node;
776  parent->firstchild = node;
777  /* inherit allowInCritSection flag from parent */
778  node->allowInCritSection = parent->allowInCritSection;
779  }
780  else
781  {
782  node->nextchild = NULL;
783  node->allowInCritSection = false;
784  }
785 
786  VALGRIND_CREATE_MEMPOOL(node, 0, false);
787 }
MemoryContextCallback * reset_cbs
Definition: memnodes.h:90
const MemoryContextMethods * methods
Definition: memnodes.h:83
bool allowInCritSection
Definition: memnodes.h:81
MemoryContext firstchild
Definition: memnodes.h:85
MemoryContext prevchild
Definition: memnodes.h:86
volatile uint32 CritSectionCount
Definition: globals.c:38
const char * ident
Definition: memnodes.h:89
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define Assert(condition)
Definition: c.h:745
const char * name
Definition: encode.c:561
Size mem_allocated
Definition: memnodes.h:82
MemoryContext parent
Definition: memnodes.h:84
const char * name
Definition: memnodes.h:88
MemoryContext nextchild
Definition: memnodes.h:87
NodeTag type
Definition: memnodes.h:78

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 212 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(), bringetbitmap(), brininsert(), bt_check_every_level(), btendscan(), btree_xlog_cleanup(), btvacuumscan(), BuildParamLogString(), BuildRelationExtStatistics(), CloneRowTriggersToPartition(), cluster(), compile_plperl_function(), compile_pltcl_function(), compute_index_stats(), ComputeExtStatisticsRows(), CopyTo(), createTrgmNFA(), CreateTrigger(), decr_dcc_refcount(), DeleteExpandedObject(), DiscreteKnapsack(), 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(), exec_simple_query(), ExecEndAgg(), 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_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(), strlist_to_textarray(), test_pattern(), tokenize_inc_file(), tuplesort_end(), union_tuples(), vacuum(), and validateForeignKeyConstraint().

213 {
215  /* We had better not be deleting TopMemoryContext ... */
216  Assert(context != TopMemoryContext);
217  /* And not CurrentMemoryContext, either */
218  Assert(context != CurrentMemoryContext);
219 
220  /* save a function call in common case where there are no children */
221  if (context->firstchild != NULL)
223 
224  /*
225  * It's not entirely clear whether 'tis better to do this before or after
226  * delinking the context; but an error in a callback will likely result in
227  * leaking the whole context (if it's not a root context) if we do it
228  * after, so let's do it before.
229  */
231 
232  /*
233  * We delink the context from its parent before deleting it, so that if
234  * there's an error we won't have deleted/busted contexts still attached
235  * to the context tree. Better a leak than a crash.
236  */
237  MemoryContextSetParent(context, NULL);
238 
239  /*
240  * Also reset the context's ident pointer, in case it points into the
241  * context. This would only matter if someone tries to get stats on the
242  * (already unlinked) context, which is unlikely, but let's be safe.
243  */
244  context->ident = NULL;
245 
246  context->methods->delete_context(context);
247 
248  VALGRIND_DESTROY_MEMPOOL(context);
249 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:303
const MemoryContextMethods * methods
Definition: memnodes.h:83
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:355
MemoryContext firstchild
Definition: memnodes.h:85
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define AssertArg(condition)
Definition: c.h:747
const char * ident
Definition: memnodes.h:89
MemoryContext TopMemoryContext
Definition: mcxt.c:44
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:257
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
#define MemoryContextIsValid(context)
Definition: memnodes.h:102
#define Assert(condition)
Definition: c.h:745
void(* delete_context)(MemoryContext context)
Definition: memnodes.h:64

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 257 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().

258 {
260 
261  /*
262  * MemoryContextDelete will delink the child from me, so just iterate as
263  * long as there is a child.
264  */
265  while (context->firstchild != NULL)
267 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
MemoryContext firstchild
Definition: memnodes.h:85
#define AssertArg(condition)
Definition: c.h:747
#define MemoryContextIsValid(context)
Definition: memnodes.h:102

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

Definition at line 440 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().

441 {
443 
444  return context->parent;
445 }
#define AssertArg(condition)
Definition: c.h:747
#define MemoryContextIsValid(context)
Definition: memnodes.h:102
MemoryContext parent
Definition: memnodes.h:84

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 93 of file mcxt.c.

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

Referenced by main().

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

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 452 of file mcxt.c.

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

Referenced by AtSubCommit_Memory().

453 {
455 
456  /*
457  * For now, we consider a memory context nonempty if it has any children;
458  * perhaps this should be changed later.
459  */
460  if (context->firstchild != NULL)
461  return false;
462  /* Otherwise use the type-specific inquiry */
463  return context->methods->is_empty(context);
464 }
const MemoryContextMethods * methods
Definition: memnodes.h:83
MemoryContext firstchild
Definition: memnodes.h:85
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:66
#define AssertArg(condition)
Definition: c.h:747
#define MemoryContextIsValid(context)
Definition: memnodes.h:102

◆ MemoryContextMemAllocated()

Size MemoryContextMemAllocated ( MemoryContext  context,
bool  recurse 
)

Definition at line 471 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().

472 {
473  Size total = context->mem_allocated;
474 
476 
477  if (recurse)
478  {
479  MemoryContext child;
480 
481  for (child = context->firstchild;
482  child != NULL;
483  child = child->nextchild)
484  total += MemoryContextMemAllocated(child, true);
485  }
486 
487  return total;
488 }
MemoryContext firstchild
Definition: memnodes.h:85
#define AssertArg(condition)
Definition: c.h:747
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition: mcxt.c:471
#define MemoryContextIsValid(context)
Definition: memnodes.h:102
size_t Size
Definition: c.h:473
Size mem_allocated
Definition: memnodes.h:82
MemoryContext nextchild
Definition: memnodes.h:87

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 137 of file mcxt.c.

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

Referenced by _bt_preprocess_array_keys(), AfterTriggerExecute(), apply_handle_stream_commit(), apply_handle_stream_stop(), bloomBuildCallback(), brin_memtuple_initialize(), bt_check_level_from_leftmost(), btree_redo(), btvacuumpage(), buildSubPlanHash(), check_domain_for_new_field(), check_domain_for_new_tuple(), CloneRowTriggersToPartition(), CopyOneRowTo(), CreateTrigger(), 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(), printtup_20(), printtup_internal_20(), process_ordered_aggregate_single(), ReScanExprContext(), resetSpGistScanOpaque(), scanPendingInsert(), sepgsql_avc_reset(), spg_redo(), spginsert(), spgistBuildCallback(), spgWalk(), startScanKey(), storeRow(), tfuncFetchRows(), tfuncLoadRows(), tuplesort_free(), and validateForeignKeyConstraint().

138 {
140 
141  /* save a function call in common case where there are no children */
142  if (context->firstchild != NULL)
144 
145  /* save a function call if no pallocs since startup or last reset */
146  if (!context->isReset)
147  MemoryContextResetOnly(context);
148 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:156
MemoryContext firstchild
Definition: memnodes.h:85
#define AssertArg(condition)
Definition: c.h:747
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:257
#define MemoryContextIsValid(context)
Definition: memnodes.h:102

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 189 of file mcxt.c.

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

Referenced by MemoryContextResetChildren().

190 {
191  MemoryContext child;
192 
194 
195  for (child = context->firstchild; child != NULL; child = child->nextchild)
196  {
198  MemoryContextResetOnly(child);
199  }
200 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:156
MemoryContext firstchild
Definition: memnodes.h:85
#define AssertArg(condition)
Definition: c.h:747
#define MemoryContextIsValid(context)
Definition: memnodes.h:102
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:189
MemoryContext nextchild
Definition: memnodes.h:87

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 156 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().

157 {
159 
160  /* Nothing to do if no pallocs since startup or last reset */
161  if (!context->isReset)
162  {
164 
165  /*
166  * If context->ident points into the context's memory, it will become
167  * a dangling pointer. We could prevent that by setting it to NULL
168  * here, but that would break valid coding patterns that keep the
169  * ident elsewhere, e.g. in a parent context. Another idea is to use
170  * MemoryContextContains(), but we don't require ident strings to be
171  * in separately-palloc'd chunks, so that risks false positives. So
172  * for now we assume the programmer got it right.
173  */
174 
175  context->methods->reset(context);
176  context->isReset = true;
177  VALGRIND_DESTROY_MEMPOOL(context);
178  VALGRIND_CREATE_MEMPOOL(context, 0, false);
179  }
180 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:303
const MemoryContextMethods * methods
Definition: memnodes.h:83
void(* reset)(MemoryContext context)
Definition: memnodes.h:63
#define AssertArg(condition)
Definition: c.h:747
#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:102

◆ MemoryContextSetIdentifier()

void MemoryContextSetIdentifier ( MemoryContext  context,
const char *  id 
)

Definition at line 330 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().

331 {
333  context->ident = id;
334 }
#define AssertArg(condition)
Definition: c.h:747
const char * ident
Definition: memnodes.h:89
#define MemoryContextIsValid(context)
Definition: memnodes.h:102

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 355 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().

356 {
358  AssertArg(context != new_parent);
359 
360  /* Fast path if it's got correct parent already */
361  if (new_parent == context->parent)
362  return;
363 
364  /* Delink from existing parent, if any */
365  if (context->parent)
366  {
367  MemoryContext parent = context->parent;
368 
369  if (context->prevchild != NULL)
370  context->prevchild->nextchild = context->nextchild;
371  else
372  {
373  Assert(parent->firstchild == context);
374  parent->firstchild = context->nextchild;
375  }
376 
377  if (context->nextchild != NULL)
378  context->nextchild->prevchild = context->prevchild;
379  }
380 
381  /* And relink */
382  if (new_parent)
383  {
384  AssertArg(MemoryContextIsValid(new_parent));
385  context->parent = new_parent;
386  context->prevchild = NULL;
387  context->nextchild = new_parent->firstchild;
388  if (new_parent->firstchild != NULL)
389  new_parent->firstchild->prevchild = context;
390  new_parent->firstchild = context;
391  }
392  else
393  {
394  context->parent = NULL;
395  context->prevchild = NULL;
396  context->nextchild = NULL;
397  }
398 }
MemoryContext firstchild
Definition: memnodes.h:85
MemoryContext prevchild
Definition: memnodes.h:86
#define AssertArg(condition)
Definition: c.h:747
#define MemoryContextIsValid(context)
Definition: memnodes.h:102
#define Assert(condition)
Definition: c.h:745
MemoryContext parent
Definition: memnodes.h:84
MemoryContext nextchild
Definition: memnodes.h:87

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

Definition at line 499 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().

500 {
501  /* A hard-wired limit on the number of children is usually good enough */
502  MemoryContextStatsDetail(context, 100);
503 }
void MemoryContextStatsDetail(MemoryContext context, int max_children)
Definition: mcxt.c:511

◆ MemoryContextStatsDetail()

void MemoryContextStatsDetail ( MemoryContext  context,
int  max_children 
)

Definition at line 511 of file mcxt.c.

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

Referenced by MemoryContextStats().

512 {
513  MemoryContextCounters grand_totals;
514 
515  memset(&grand_totals, 0, sizeof(grand_totals));
516 
517  MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals);
518 
519  fprintf(stderr,
520  "Grand total: %zu bytes in %zd blocks; %zu free (%zd chunks); %zu used\n",
521  grand_totals.totalspace, grand_totals.nblocks,
522  grand_totals.freespace, grand_totals.freechunks,
523  grand_totals.totalspace - grand_totals.freespace);
524 }
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals)
Definition: mcxt.c:534
#define fprintf
Definition: port.h:197

◆ SlabContextCreate()

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

Definition at line 174 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().

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

Variable Documentation

◆ CacheMemoryContext

PGDLLIMPORT MemoryContext CacheMemoryContext

Definition at line 47 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(), generate_partition_qual(), get_attribute_options(), get_rel_sync_entry(), get_tablespace(), GetCachedExpression(), GetCachedPlan(), GetConnection(), 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(), process_syncing_tables_for_apply(), register_on_commit_action(), RehashCatCache(), RelationBuildLocalRelation(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), RelationGetFKeyList(), 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 44 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(), CheckpointerMain(), CheckSCRAMAuth(), 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_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_array(), PostgresMain(), PostmasterMain(), pq_init(), PrepareClientEncoding(), ProcessStartupPacket(), PushOverrideSearchPath(), px_find_cipher(), px_find_digest(), recomputeNamespacePath(), register_label_provider(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), regress_putenv(), RelationCreateStorage(), RelationDropStorage(), RequestNamedLWLockTranche(), ResourceArrayEnlarge(), ResourceOwnerCreate(), RestoreReindexState(), ri_HashCompareOp(), roles_has_privs_of(), roles_is_member_of(), sepgsql_avc_init(), sepgsql_xact_callback(), SetDatabasePath(), SharedRecordTypmodRegistryAttach(), SharedRecordTypmodRegistryInit(), SlabContextCreate(), SPI_connect_ext(), StartChildProcess(), WalWriterMain(), XLOGShmemInit(), and xml_is_document().

◆ TopTransactionContext