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(parent, name, allocparams)   AllocSetContextCreateExtended(parent, name, allocparams)
 
#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)
 
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 AllocSetContextCreateExtended (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)

Definition at line 190 of file memutils.h.

Referenced by AllocSetContextCreateExtended(), and get_agg_clause_costs_walker().

◆ ALLOCSET_DEFAULT_MAXSIZE

#define ALLOCSET_DEFAULT_MAXSIZE   (8 * 1024 * 1024)

Definition at line 191 of file memutils.h.

◆ ALLOCSET_DEFAULT_MINSIZE

#define ALLOCSET_DEFAULT_MINSIZE   0

Definition at line 189 of file memutils.h.

Referenced by AllocSetContextCreateExtended().

◆ 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(), btvacuumscan(), BuildEventTriggerCache(), BuildRelationExtStatistics(), CheckpointerMain(), cluster(), compute_index_stats(), CopyTo(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContext(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), do_analyze_rel(), do_autovacuum(), do_compile(), do_start_worker(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), EventTriggerInvoke(), exec_parse_message(), exec_replication_command(), ExecHashTableCreate(), ExecInitFunctionScan(), ExecInitProjectSet(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitTableFuncScan(), ExecInitWindowAgg(), ExecSetupPartitionPruneState(), file_acquire_sample_rows(), geqo_eval(), get_stmt_mcontext(), GetLocalBufferStorage(), gin_xlog_startup(), ginbeginscan(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistrescan(), HandleParallelMessages(), hash_create(), index_register(), init_sql_fcache(), initArrayResult(), initArrayResultArr(), initGISTstate(), initialize_peragg(), InitXLogInsert(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), logicalrep_relmap_init(), LogicalRepApplyLoop(), make_expanded_record_from_datum(), make_expanded_record_from_exprecord(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), materializeQueryResult(), 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(), RelationBuildPartitionDesc(), ReorderBufferAllocate(), ResetUnloggedRelations(), sepgsql_avc_init(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), SPI_connect_ext(), spi_dest_startup(), StartupDecodingContext(), strlist_to_textarray(), tuplesort_begin_common(), union_tuples(), vacuum(), WalWriterMain(), XLOGShmemInit(), and xml_is_document().

◆ ALLOCSET_SEPARATE_THRESHOLD

#define ALLOCSET_SEPARATE_THRESHOLD   8192

◆ ALLOCSET_SMALL_INITSIZE

#define ALLOCSET_SMALL_INITSIZE   (1 * 1024)

Definition at line 200 of file memutils.h.

Referenced by AllocSetContextCreateExtended(), 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 AllocSetContextCreateExtended().

◆ ALLOCSET_SMALL_SIZES

◆ ALLOCSET_START_SMALL_SIZES

◆ AllocSetContextCreate

#define AllocSetContextCreate (   parent,
  name,
  allocparams 
)    AllocSetContextCreateExtended(parent, name, allocparams)

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(), btvacuumscan(), BuildCachedPlan(), BuildEventTriggerCache(), BuildRelationExtStatistics(), CheckpointerMain(), CloneRowTriggersToPartition(), cluster(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_index_stats(), CopyCachedPlan(), CopyTo(), create_foreign_modify(), CreateCachedPlan(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContext(), 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(), ExecHashTableCreate(), ExecInitFunctionScan(), ExecInitProjectSet(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitTableFuncScan(), ExecInitWindowAgg(), ExecSetupPartitionPruneState(), expand_array(), file_acquire_sample_rows(), fill_hba_view(), geqo_eval(), get_short_term_cxt(), get_stmt_mcontext(), GetLocalBufferStorage(), gin_xlog_startup(), ginbeginscan(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistrescan(), HandleParallelMessages(), hash_create(), index_register(), init_MultiFuncCall(), init_sql_fcache(), initArrayResult(), initArrayResultArr(), initGISTstate(), initialize_peragg(), InitXLogInsert(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), load_domaintype_info(), load_hba(), load_ident(), load_relcache_init_file(), load_tzoffsets(), 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(), materializeQueryResult(), 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(), 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(), 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(), tokenize_file(), tuplesort_begin_common(), union_tuples(), vacuum(), WalWriterMain(), XLOGShmemInit(), and xml_is_document().

◆ AllocSizeIsValid

◆ MaxAllocHugeSize

#define MaxAllocHugeSize   (SIZE_MAX / 2)

Definition at line 44 of file memutils.h.

Referenced by grow_memtuples(), and qtext_load_file().

◆ 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

◆ AllocSetContextCreateExtended()

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

Definition at line 388 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 AtStart_Memory(), GetMemoryChunkContext(), and MemoryContextInit().

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

◆ GenerationContextCreate()

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

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

215 {
216  GenerationContext *set;
217 
218  /* Assert we padded GenerationChunk properly */
220  "sizeof(GenerationChunk) is not maxaligned");
223  "padding calculation in GenerationChunk is wrong");
224 
225  /*
226  * First, validate allocation parameters. (If we're going to throw an
227  * error, we should do so before the context is created, not after.) We
228  * somewhat arbitrarily enforce a minimum 1K block size, mostly because
229  * that's what AllocSet does.
230  */
231  if (blockSize != MAXALIGN(blockSize) ||
232  blockSize < 1024 ||
233  !AllocHugeSizeIsValid(blockSize))
234  elog(ERROR, "invalid blockSize for memory context: %zu",
235  blockSize);
236 
237  /*
238  * Allocate the context header. Unlike aset.c, we never try to combine
239  * this with the first regular block, since that would prevent us from
240  * freeing the first generation of allocations.
241  */
242 
244  if (set == NULL)
245  {
247  ereport(ERROR,
248  (errcode(ERRCODE_OUT_OF_MEMORY),
249  errmsg("out of memory"),
250  errdetail("Failed while creating memory context \"%s\".",
251  name)));
252  }
253 
254  /*
255  * Avoid writing code that can fail between here and MemoryContextCreate;
256  * we'd leak the header if we ereport in this stretch.
257  */
258 
259  /* Fill in GenerationContext-specific header fields */
260  set->blockSize = blockSize;
261  set->block = NULL;
262  dlist_init(&set->blocks);
263 
264  /* Finally, do the type-independent part of context creation */
268  parent,
269  name);
270 
271  return (MemoryContext) set;
272 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define malloc(a)
Definition: header.h:50
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:795
#define ERROR
Definition: elog.h:43
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:474
int errdetail(const char *fmt,...)
Definition: elog.c:873
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:724
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define MAXALIGN(LEN)
Definition: c.h:652
const char * name
Definition: encode.c:521
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define Generation_CHUNKHDRSZ
Definition: generation.c:47
#define elog
Definition: elog.h:219
#define offsetof(type, field)
Definition: c.h:622

◆ GetMemoryChunkContext()

static MemoryContext GetMemoryChunkContext ( void *  pointer)
inlinestatic

Definition at line 112 of file memutils.h.

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

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

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

◆ GetMemoryChunkSpace()

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 411 of file mcxt.c.

References MemoryContextData::allowInCritSection, AssertArg, and MemoryContextIsValid.

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

412 {
414 
415  context->allowInCritSection = allow;
416 }
bool allowInCritSection
Definition: memnodes.h:81
#define AssertArg(condition)
Definition: c.h:701
#define MemoryContextIsValid(context)
Definition: memnodes.h:101

◆ MemoryContextContains()

bool MemoryContextContains ( MemoryContext  context,
void *  pointer 
)

Definition at line 667 of file mcxt.c.

References MAXALIGN.

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

668 {
669  MemoryContext ptr_context;
670 
671  /*
672  * NB: Can't use GetMemoryChunkContext() here - that performs assertions
673  * that aren't acceptable here since we might be passed memory not
674  * allocated by any memory context.
675  *
676  * Try to detect bogus pointers handed to us, poorly though we can.
677  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
678  * allocated chunk.
679  */
680  if (pointer == NULL || pointer != (void *) MAXALIGN(pointer))
681  return false;
682 
683  /*
684  * OK, it's probably safe to look at the context.
685  */
686  ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
687 
688  return ptr_context == context;
689 }
#define MAXALIGN(LEN)
Definition: c.h:652

◆ MemoryContextCreate()

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

Definition at line 724 of file mcxt.c.

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

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

729 {
730  /* Creating new memory contexts is not allowed in a critical section */
731  Assert(CritSectionCount == 0);
732 
733  /* Initialize all standard fields of memory context header */
734  node->type = tag;
735  node->isReset = true;
736  node->methods = methods;
737  node->parent = parent;
738  node->firstchild = NULL;
739  node->prevchild = NULL;
740  node->name = name;
741  node->ident = NULL;
742  node->reset_cbs = NULL;
743 
744  /* OK to link node into context tree */
745  if (parent)
746  {
747  node->nextchild = parent->firstchild;
748  if (parent->firstchild != NULL)
749  parent->firstchild->prevchild = node;
750  parent->firstchild = node;
751  /* inherit allowInCritSection flag from parent */
752  node->allowInCritSection = parent->allowInCritSection;
753  }
754  else
755  {
756  node->nextchild = NULL;
757  node->allowInCritSection = false;
758  }
759 
760  VALGRIND_CREATE_MEMPOOL(node, 0, false);
761 }
MemoryContextCallback * reset_cbs
Definition: memnodes.h:89
const MemoryContextMethods * methods
Definition: memnodes.h:82
bool allowInCritSection
Definition: memnodes.h:81
MemoryContext firstchild
Definition: memnodes.h:84
MemoryContext prevchild
Definition: memnodes.h:85
volatile uint32 CritSectionCount
Definition: globals.c:40
const char * ident
Definition: memnodes.h:88
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define Assert(condition)
Definition: c.h:699
const char * name
Definition: encode.c:521
MemoryContext parent
Definition: memnodes.h:83
const char * name
Definition: memnodes.h:87
MemoryContext nextchild
Definition: memnodes.h:86
NodeTag type
Definition: memnodes.h:78

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 211 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(), btvacuumscan(), BuildRelationExtStatistics(), CloneRowTriggersToPartition(), cluster(), compile_plperl_function(), compile_pltcl_function(), compute_index_stats(), 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(), ExecEndRecursiveUnion(), ExecEndSetOp(), ExecEndWindowAgg(), ExecHashTableDestroy(), file_acquire_sample_rows(), fill_hba_view(), fmgr_sql(), free_plperl_function(), FreeDecodingContext(), FreeExecutorState(), FreeExprContext(), freeGISTstate(), FreeSnapshotBuilder(), geqo_eval(), gin_xlog_cleanup(), ginbuild(), ginbulkdelete(), ginendscan(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gist_xlog_cleanup(), gistbuild(), hash_destroy(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), load_hba(), load_ident(), load_tzoffsets(), makeArrayResultArr(), makeMdArrayResult(), materializeQueryResult(), MemoryContextDeleteChildren(), mergeruns(), NIFinishBuild(), pg_decode_shutdown(), pgstat_clear_snapshot(), plperl_spi_freeplan(), plperl_spi_prepare(), plpgsql_free_function_memory(), pltcl_handler(), pltcl_SPI_prepare(), PLy_cursor_dealloc(), PLy_plan_dealloc(), PLy_pop_execution_context(), PLy_procedure_delete(), PLy_spi_execute_fetch_result(), PortalDrop(), PostgresMain(), printtup_shutdown(), publicationListToArray(), rebuild_database_list(), ReindexMultipleTables(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationDestroyRelation(), ReleaseCachedPlan(), ReorderBufferFree(), ResetUnloggedRelations(), RevalidateCachedQuery(), shutdown_MultiFuncCall(), spg_xlog_cleanup(), spgbuild(), spgendscan(), spginsert(), SPI_finish(), SPI_freeplan(), SPI_freetuptable(), StartChildProcess(), strlist_to_textarray(), tokenize_inc_file(), tuplesort_end(), union_tuples(), and vacuum().

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

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 256 of file mcxt.c.

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

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

257 {
259 
260  /*
261  * MemoryContextDelete will delink the child from me, so just iterate as
262  * long as there is a child.
263  */
264  while (context->firstchild != NULL)
266 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
MemoryContext firstchild
Definition: memnodes.h:84
#define AssertArg(condition)
Definition: c.h:701
#define MemoryContextIsValid(context)
Definition: memnodes.h:101

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

Definition at line 439 of file mcxt.c.

References AssertArg, MemoryContextIsValid, and MemoryContextData::parent.

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

440 {
442 
443  return context->parent;
444 }
#define AssertArg(condition)
Definition: c.h:701
#define MemoryContextIsValid(context)
Definition: memnodes.h:101
MemoryContext parent
Definition: memnodes.h:83

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 92 of file mcxt.c.

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

Referenced by main().

93 {
95 
96  /*
97  * First, initialize TopMemoryContext, which is the parent of all others.
98  */
100  "TopMemoryContext",
102 
103  /*
104  * Not having any other place to point CurrentMemoryContext, make it point
105  * to TopMemoryContext. Caller should change this soon!
106  */
108 
109  /*
110  * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
111  * we don't really expect much to be allocated in it. More to the point,
112  * require it to contain at least 8K at all times. This is the only case
113  * where retained memory in a context is *essential* --- we want to be
114  * sure ErrorContext still has some memory even if we've run out
115  * elsewhere! Also, allow allocations in ErrorContext within a critical
116  * section. Otherwise a PANIC will cause an assertion failure in the error
117  * reporting code, before printing out the real cause of the failure.
118  *
119  * This should be the last step in this function, as elog.c assumes memory
120  * management works once ErrorContext is non-null.
121  */
123  "ErrorContext",
124  8 * 1024,
125  8 * 1024,
126  8 * 1024);
128 }
MemoryContext AllocSetContextCreateExtended(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:388
#define AssertState(condition)
Definition: c.h:702
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:411
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
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 451 of file mcxt.c.

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

Referenced by AtSubCommit_Memory().

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

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 136 of file mcxt.c.

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

Referenced by _bt_preprocess_array_keys(), AfterTriggerExecute(), bloomBuildCallback(), brin_memtuple_initialize(), bt_check_level_from_leftmost(), 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(), ExecFindInitialMatchingSubPlans(), ExecFindMatchingSubPlans(), ExecHashTableReset(), ExecMakeTableFunctionResult(), ExecProjectSet(), ExecQualAndReset(), ExecRecursiveUnion(), execTuplesUnequal(), 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_redo(), gistBuildCallback(), gistgetbitmap(), gistgettuple(), gistinsert(), gistProcessEmptyingQueue(), gistrescan(), gistScanPage(), HandleParallelMessages(), IndexBuildHeapRangeScan(), 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(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), printtup(), printtup_20(), printtup_internal_20(), process_ordered_aggregate_single(), ReScanExprContext(), scanPendingInsert(), sepgsql_avc_reset(), spg_redo(), spginsert(), spgistBuildCallback(), spgrescan(), spgWalk(), startScanKey(), storeRow(), tfuncLoadRows(), and validate_index_heapscan().

137 {
139 
140  /* save a function call in common case where there are no children */
141  if (context->firstchild != NULL)
143 
144  /* save a function call if no pallocs since startup or last reset */
145  if (!context->isReset)
146  MemoryContextResetOnly(context);
147 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:155
MemoryContext firstchild
Definition: memnodes.h:84
#define AssertArg(condition)
Definition: c.h:701
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:256
#define MemoryContextIsValid(context)
Definition: memnodes.h:101

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 188 of file mcxt.c.

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

Referenced by MemoryContextResetChildren().

189 {
190  MemoryContext child;
191 
193 
194  for (child = context->firstchild; child != NULL; child = child->nextchild)
195  {
197  MemoryContextResetOnly(child);
198  }
199 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:155
MemoryContext firstchild
Definition: memnodes.h:84
#define AssertArg(condition)
Definition: c.h:701
#define MemoryContextIsValid(context)
Definition: memnodes.h:101
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:188
MemoryContext nextchild
Definition: memnodes.h:86

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 155 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(), and MemoryContextResetChildren().

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

◆ MemoryContextSetIdentifier()

void MemoryContextSetIdentifier ( MemoryContext  context,
const char *  id 
)

Definition at line 329 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(), and PLy_procedure_create().

330 {
332  context->ident = id;
333 }
#define AssertArg(condition)
Definition: c.h:701
const char * ident
Definition: memnodes.h:88
#define MemoryContextIsValid(context)
Definition: memnodes.h:101

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 354 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(), GetCachedPlan(), load_domaintype_info(), MemoryContextDelete(), RelationBuildPartitionKey(), RevalidateCachedQuery(), SaveCachedPlan(), SPI_keepplan(), and TransferExpandedObject().

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

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

Definition at line 474 of file mcxt.c.

References MemoryContextStatsDetail().

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

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

◆ MemoryContextStatsDetail()

void MemoryContextStatsDetail ( MemoryContext  context,
int  max_children 
)

Definition at line 486 of file mcxt.c.

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

Referenced by MemoryContextStats().

487 {
488  MemoryContextCounters grand_totals;
489 
490  memset(&grand_totals, 0, sizeof(grand_totals));
491 
492  MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals);
493 
494  fprintf(stderr,
495  "Grand total: %zu bytes in %zd blocks; %zu free (%zd chunks); %zu used\n",
496  grand_totals.totalspace, grand_totals.nblocks,
497  grand_totals.freespace, grand_totals.freechunks,
498  grand_totals.totalspace - grand_totals.freespace);
499 }
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals)
Definition: mcxt.c:509

◆ SlabContextCreate()

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

Definition at line 188 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(), SlabContext::minFreeChunks, SlabContext::nblocks, offsetof, StaticAssertStmt, T_SlabContext, and TopMemoryContext.

Referenced by ReorderBufferAllocate().

192 {
193  int chunksPerBlock;
194  Size fullChunkSize;
195  Size freelistSize;
196  Size headerSize;
197  SlabContext *slab;
198  int i;
199 
200  /* Assert we padded SlabChunk properly */
201  StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)),
202  "sizeof(SlabChunk) is not maxaligned");
204  sizeof(SlabChunk),
205  "padding calculation in SlabChunk is wrong");
206 
207  /* Make sure the linked list node fits inside a freed chunk */
208  if (chunkSize < sizeof(int))
209  chunkSize = sizeof(int);
210 
211  /* chunk, including SLAB header (both addresses nicely aligned) */
212  fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize);
213 
214  /* Make sure the block can store at least one chunk. */
215  if (blockSize < fullChunkSize + sizeof(SlabBlock))
216  elog(ERROR, "block size %zu for slab is too small for %zu chunks",
217  blockSize, chunkSize);
218 
219  /* Compute maximum number of chunks per block */
220  chunksPerBlock = (blockSize - sizeof(SlabBlock)) / fullChunkSize;
221 
222  /* The freelist starts with 0, ends with chunksPerBlock. */
223  freelistSize = sizeof(dlist_head) * (chunksPerBlock + 1);
224 
225  /*
226  * Allocate the context header. Unlike aset.c, we never try to combine
227  * this with the first regular block; not worth the extra complication.
228  */
229 
230  /* Size of the memory context header */
231  headerSize = offsetof(SlabContext, freelist) + freelistSize;
232 
233  slab = (SlabContext *) malloc(headerSize);
234  if (slab == NULL)
235  {
237  ereport(ERROR,
238  (errcode(ERRCODE_OUT_OF_MEMORY),
239  errmsg("out of memory"),
240  errdetail("Failed while creating memory context \"%s\".",
241  name)));
242  }
243 
244  /*
245  * Avoid writing code that can fail between here and MemoryContextCreate;
246  * we'd leak the header if we ereport in this stretch.
247  */
248 
249  /* Fill in SlabContext-specific header fields */
250  slab->chunkSize = chunkSize;
251  slab->fullChunkSize = fullChunkSize;
252  slab->blockSize = blockSize;
253  slab->headerSize = headerSize;
254  slab->chunksPerBlock = chunksPerBlock;
255  slab->minFreeChunks = 0;
256  slab->nblocks = 0;
257 
258  /* initialize the freelist slots */
259  for (i = 0; i < (slab->chunksPerBlock + 1); i++)
260  dlist_init(&slab->freelist[i]);
261 
262  /* Finally, do the type-independent part of context creation */
265  &SlabMethods,
266  parent,
267  name);
268 
269  return (MemoryContext) slab;
270 }
int nblocks
Definition: slab.c:73
Size blockSize
Definition: slab.c:69
struct dlist_head dlist_head
int errcode(int sqlerrcode)
Definition: elog.c:575
dlist_head freelist[FLEXIBLE_ARRAY_MEMBER]
Definition: slab.c:75
Size chunkSize
Definition: slab.c:67
#define malloc(a)
Definition: header.h:50
static const MemoryContextMethods SlabMethods
Definition: slab.c:144
Size headerSize
Definition: slab.c:70
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:795
#define ERROR
Definition: elog.h:43
int chunksPerBlock
Definition: slab.c:71
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:474
Size fullChunkSize
Definition: slab.c:68
int errdetail(const char *fmt,...)
Definition: elog.c:873
void MemoryContextCreate(MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:724
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
struct SlabBlock SlabBlock
size_t Size
Definition: c.h:433
#define MAXALIGN(LEN)
Definition: c.h:652
const char * name
Definition: encode.c:521
Definition: slab.c:86
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
int minFreeChunks
Definition: slab.c:72
struct SlabChunk SlabChunk
#define elog
Definition: elog.h:219
#define offsetof(type, field)
Definition: c.h:622

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(), 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_relmap_init(), lookup_ts_config_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), 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(), RelationSetIndexList(), RememberToFreeTupleDescAtEOX(), SaveCachedPlan(), SearchCatCacheList(), 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(), add_string_reloption(), allocate_reloption(), AllocateAttribute(), AllocSetContextCreateExtended(), ApplyLauncherMain(), ApplyWorkerMain(), AtAbort_Memory(), AtCleanup_Memory(), AtCommit_Memory(), AtStart_Memory(), AttachSession(), AutoVacLauncherMain(), BackendRun(), BackgroundWriterMain(), be_tls_open_server(), cache_single_time(), CheckpointerMain(), compile_plperl_function(), compile_pltcl_function(), ConditionVariablePrepareToSleep(), ConvertTriggerToFK(), CreateCacheMemoryContext(), dblink_connect(), dblink_init(), do_autovacuum(), do_compile(), do_start_bgworker(), dsm_create_descriptor(), dsm_impl_sysv(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), Exec_ListenCommit(), finish_xact_command(), GenerationContextCreate(), get_tabstat_entry(), GetLocalBufferStorage(), GetLockConflicts(), GetSessionDsmHandle(), HandleParallelMessages(), hash_create(), InitDeadLockChecking(), initialize_reloptions(), InitializeParallelDSM(), InitializeSearchPath(), InitializeSession(), InitXLogInsert(), llvm_compile_module(), llvm_create_context(), llvm_session_initialize(), LockAcquireExtended(), LogicalRepApplyLoop(), mdinit(), MemoryContextInit(), mxid_to_string(), on_dsm_detach(), PageSetChecksumCopy(), ParallelWorkerMain(), PerformAuthentication(), pg_newlocale_from_collation(), pg_start_backup(), pgstat_setup_memcxt(), plperl_spi_prepare(), plpgsql_estate_setup(), plpython_inline_handler(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_cursor_query(), PLy_procedure_create(), PLy_spi_execute_fetch_result(), PLy_spi_prepare(), PostgresMain(), PostmasterMain(), pq_init(), PrepareClientEncoding(), ProcessStartupPacket(), PushOverrideSearchPath(), px_find_cipher(), px_find_digest(), recomputeNamespacePath(), register_label_provider(), RegisterLWLockTranches(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), regress_putenv(), RelationCreateStorage(), RelationDropStorage(), RequestNamedLWLockTranche(), ResourceArrayEnlarge(), ResourceOwnerCreate(), 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