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 AllocSetContextCreate(parent, name, allocparams)   AllocSetContextCreateExtended(parent, name, 0, allocparams)
 
#define MEMCONTEXT_COPY_NAME   0x0001 /* is passed name transient? */
 
#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 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, Size size, Size nameoffset, const MemoryContextMethods *methods, MemoryContext parent, const char *name, int flags)
 
MemoryContext AllocSetContextCreateExtended (MemoryContext parent, const char *name, int flags, Size minContextSize, Size initBlockSize, Size maxBlockSize)
 
MemoryContext SlabContextCreate (MemoryContext parent, const char *name, int flags, Size blockSize, Size chunkSize)
 
MemoryContext GenerationContextCreate (MemoryContext parent, const char *name, int flags, 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 195 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 196 of file memutils.h.

◆ ALLOCSET_DEFAULT_MINSIZE

#define ALLOCSET_DEFAULT_MINSIZE   0

Definition at line 194 of file memutils.h.

Referenced by AllocSetContextCreateExtended().

◆ ALLOCSET_DEFAULT_SIZES

Definition at line 197 of file memutils.h.

Referenced by afterTriggerAddEvent(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), ApplyLauncherMain(), ApplyWorkerMain(), AtStart_Memory(), AtSubStart_Memory(), 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(), ExecInitUnique(), ExecInitWindowAgg(), file_acquire_sample_rows(), geqo_eval(), get_stmt_mcontext(), GetLocalBufferStorage(), gin_xlog_startup(), ginbeginscan(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistrescan(), HandleParallelMessages(), hash_create(), index_register(), init_sql_fcache(), initArrayResult(), initArrayResultArr(), initGISTstate(), initialize_peragg(), InitXLogInsert(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), logicalrep_relmap_init(), LogicalRepApplyLoop(), 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(), 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 205 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 206 of file memutils.h.

◆ ALLOCSET_SMALL_MINSIZE

#define ALLOCSET_SMALL_MINSIZE   0

Definition at line 204 of file memutils.h.

Referenced by AllocSetContextCreateExtended().

◆ ALLOCSET_SMALL_SIZES

◆ ALLOCSET_START_SMALL_SIZES

◆ AllocSetContextCreate

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

Definition at line 165 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(), 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(), cluster(), CompleteCachedPlan(), compute_index_stats(), CopyCachedPlan(), CopyTo(), CreateCachedPlan(), CreateCacheMemoryContext(), CreateExecutorState(), CreateExprContext(), CreatePortal(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), 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(), ExecInitUnique(), ExecInitWindowAgg(), expand_array(), file_acquire_sample_rows(), fill_hba_view(), geqo_eval(), get_stmt_mcontext(), GetLocalBufferStorage(), gin_xlog_startup(), ginbeginscan(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistrescan(), HandleParallelMessages(), 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_tzoffsets(), logicalrep_relmap_init(), LogicalRepApplyLoop(), 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_spi_execute_fetch_result(), PLy_spi_prepare(), PortalCreateHoldStore(), postgresAcquireSampleRowsFunc(), postgresBeginDirectModify(), postgresBeginForeignModify(), postgresBeginForeignScan(), PostgresMain(), PostmasterMain(), printtup_startup(), publicationListToArray(), rebuild_database_list(), ReindexMultipleTables(), RelationBuildRowSecurity(), ReorderBufferAllocate(), ResetUnloggedRelations(), RevalidateCachedQuery(), sepgsql_avc_init(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), SPI_connect(), 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

◆ MEMCONTEXT_COPY_NAME

◆ MemoryContextResetAndDeleteChildren

◆ SLAB_DEFAULT_BLOCK_SIZE

#define SLAB_DEFAULT_BLOCK_SIZE   (8 * 1024)

Definition at line 226 of file memutils.h.

Referenced by ReorderBufferAllocate().

◆ SLAB_LARGE_BLOCK_SIZE

#define SLAB_LARGE_BLOCK_SIZE   (8 * 1024 * 1024)

Definition at line 227 of file memutils.h.

Referenced by ReorderBufferAllocate().

Function Documentation

◆ AllocSetContextCreateExtended()

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

Definition at line 394 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, AllocBlockData::aset, Assert, AllocBlockData::endptr, ereport, errcode(), errdetail(), errmsg(), ERROR, AllocSetFreeList::first_free, AllocSetContext::freelist, AllocSetContext::freeListIndex, AllocBlockData::freeptr, AllocSetContext::header, AllocSetContext::headerSize, AllocSetContext::initBlockSize, malloc, Max, MAXALIGN, AllocSetContext::maxBlockSize, MEMCONTEXT_COPY_NAME, MemoryContextCreate(), MemoryContextStats(), MemSetAligned, AllocBlockData::next, MemoryContextData::nextchild, AllocSetFreeList::num_free, offsetof, AllocBlockData::prev, StaticAssertStmt, T_AllocSetContext, TopMemoryContext, and VALGRIND_MAKE_MEM_NOACCESS.

Referenced by AtStart_Memory(), compile_plperl_function(), compile_pltcl_function(), GetMemoryChunkContext(), hash_create(), load_relcache_init_file(), lookup_ts_dictionary_cache(), MemoryContextInit(), PLy_procedure_create(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRuleLock(), and RelationInitIndexAccessInfo().

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

◆ GenerationContextCreate()

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

Definition at line 208 of file generation.c.

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

Referenced by ReorderBufferAllocate().

212 {
213  Size headerSize;
214  GenerationContext *set;
215 
216  /* Assert we padded GenerationChunk properly */
218  "sizeof(GenerationChunk) is not maxaligned");
221  "padding calculation in GenerationChunk is wrong");
222 
223  /*
224  * First, validate allocation parameters. (If we're going to throw an
225  * error, we should do so before the context is created, not after.) We
226  * somewhat arbitrarily enforce a minimum 1K block size, mostly because
227  * that's what AllocSet does.
228  */
229  if (blockSize != MAXALIGN(blockSize) ||
230  blockSize < 1024 ||
231  !AllocHugeSizeIsValid(blockSize))
232  elog(ERROR, "invalid blockSize for memory context: %zu",
233  blockSize);
234 
235  /*
236  * Allocate the context header. Unlike aset.c, we never try to combine
237  * this with the first regular block, since that would prevent us from
238  * freeing the first generation of allocations.
239  */
240 
241  /* Size of the memory context header, including name storage if needed */
242  if (flags & MEMCONTEXT_COPY_NAME)
243  headerSize = MAXALIGN(sizeof(GenerationContext) + strlen(name) + 1);
244  else
245  headerSize = MAXALIGN(sizeof(GenerationContext));
246 
247  set = (GenerationContext *) malloc(headerSize);
248  if (set == NULL)
249  {
251  ereport(ERROR,
252  (errcode(ERRCODE_OUT_OF_MEMORY),
253  errmsg("out of memory"),
254  errdetail("Failed while creating memory context \"%s\".",
255  name)));
256  }
257 
258  /*
259  * Avoid writing code that can fail between here and MemoryContextCreate;
260  * we'd leak the header if we ereport in this stretch.
261  */
262 
263  /* Fill in GenerationContext-specific header fields */
264  set->blockSize = blockSize;
265  set->headerSize = headerSize;
266  set->block = NULL;
267  dlist_init(&set->blocks);
268 
269  /* Finally, do the type-independent part of context creation */
272  headerSize,
273  sizeof(GenerationContext),
275  parent,
276  name,
277  flags);
278 
279  return (MemoryContext) set;
280 }
#define MEMCONTEXT_COPY_NAME
Definition: memutils.h:188
int errcode(int sqlerrcode)
Definition: elog.c:575
#define malloc(a)
Definition: header.h:50
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:764
#define ERROR
Definition: elog.h:43
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:437
void MemoryContextCreate(MemoryContext node, NodeTag tag, Size size, Size nameoffset, const MemoryContextMethods *methods, MemoryContext parent, const char *name, int flags)
Definition: mcxt.c:627
int errdetail(const char *fmt,...)
Definition: elog.c:873
static const MemoryContextMethods GenerationMethods
Definition: generation.c:167
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
size_t Size
Definition: c.h:414
#define MAXALIGN(LEN)
Definition: c.h:633
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:603

◆ GetMemoryChunkContext()

static MemoryContext GetMemoryChunkContext ( void *  pointer)
inlinestatic

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

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

◆ GetMemoryChunkSpace()

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 374 of file mcxt.c.

References MemoryContextData::allowInCritSection, AssertArg, and MemoryContextIsValid.

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

375 {
377 
378  context->allowInCritSection = allow;
379 }
bool allowInCritSection
Definition: memnodes.h:77
#define AssertArg(condition)
Definition: c.h:682
#define MemoryContextIsValid(context)
Definition: memnodes.h:96

◆ MemoryContextContains()

bool MemoryContextContains ( MemoryContext  context,
void *  pointer 
)

Definition at line 566 of file mcxt.c.

References MAXALIGN.

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

567 {
568  MemoryContext ptr_context;
569 
570  /*
571  * NB: Can't use GetMemoryChunkContext() here - that performs assertions
572  * that aren't acceptable here since we might be passed memory not
573  * allocated by any memory context.
574  *
575  * Try to detect bogus pointers handed to us, poorly though we can.
576  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
577  * allocated chunk.
578  */
579  if (pointer == NULL || pointer != (void *) MAXALIGN(pointer))
580  return false;
581 
582  /*
583  * OK, it's probably safe to look at the context.
584  */
585  ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
586 
587  return ptr_context == context;
588 }
#define MAXALIGN(LEN)
Definition: c.h:633

◆ MemoryContextCreate()

void MemoryContextCreate ( MemoryContext  node,
NodeTag  tag,
Size  size,
Size  nameoffset,
const MemoryContextMethods methods,
MemoryContext  parent,
const char *  name,
int  flags 
)

Definition at line 627 of file mcxt.c.

References MemoryContextData::allowInCritSection, Assert, CritSectionCount, MemoryContextData::firstchild, MemoryContextData::isReset, MEMCONTEXT_COPY_NAME, 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().

633 {
634  /* Creating new memory contexts is not allowed in a critical section */
635  Assert(CritSectionCount == 0);
636 
637  /* Check size is sane */
638  Assert(nameoffset >= sizeof(MemoryContextData));
639  Assert((flags & MEMCONTEXT_COPY_NAME) ?
640  size >= nameoffset + strlen(name) + 1 :
641  size >= nameoffset);
642 
643  /* Initialize all standard fields of memory context header */
644  node->type = tag;
645  node->isReset = true;
646  node->methods = methods;
647  node->parent = parent;
648  node->firstchild = NULL;
649  node->prevchild = NULL;
650  node->reset_cbs = NULL;
651 
652  if (flags & MEMCONTEXT_COPY_NAME)
653  {
654  /* Insert context name into space reserved for it */
655  char *namecopy = ((char *) node) + nameoffset;
656 
657  node->name = namecopy;
658  strcpy(namecopy, name);
659  }
660  else
661  {
662  /* Assume the passed-in name is statically allocated */
663  node->name = name;
664  }
665 
666  /* OK to link node into context tree */
667  if (parent)
668  {
669  node->nextchild = parent->firstchild;
670  if (parent->firstchild != NULL)
671  parent->firstchild->prevchild = node;
672  parent->firstchild = node;
673  /* inherit allowInCritSection flag from parent */
674  node->allowInCritSection = parent->allowInCritSection;
675  }
676  else
677  {
678  node->nextchild = NULL;
679  node->allowInCritSection = false;
680  }
681 
682  VALGRIND_CREATE_MEMPOOL(node, 0, false);
683 }
MemoryContextCallback * reset_cbs
Definition: memnodes.h:84
const MemoryContextMethods * methods
Definition: memnodes.h:78
#define MEMCONTEXT_COPY_NAME
Definition: memutils.h:188
bool allowInCritSection
Definition: memnodes.h:77
MemoryContext firstchild
Definition: memnodes.h:80
MemoryContext prevchild
Definition: memnodes.h:81
volatile uint32 CritSectionCount
Definition: globals.c:37
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define Assert(condition)
Definition: c.h:680
const char * name
Definition: encode.c:521
MemoryContext parent
Definition: memnodes.h:79
const char * name
Definition: memnodes.h:83
MemoryContext nextchild
Definition: memnodes.h:82
NodeTag type
Definition: memnodes.h:74

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 198 of file mcxt.c.

References Assert, AssertArg, MemoryContextMethods::delete_context, MemoryContextData::firstchild, 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(), blbuild(), blinsert(), brin_free_desc(), bringetbitmap(), brininsert(), bt_check_every_level(), btendscan(), btvacuumscan(), BuildRelationExtStatistics(), cluster(), compile_plperl_function(), compile_pltcl_function(), compute_index_stats(), CopyTo(), createTrgmNFA(), 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(), ExecEndUnique(), ExecEndWindowAgg(), ExecHashTableDestroy(), file_acquire_sample_rows(), fill_hba_view(), fmgr_sql(), free_plperl_function(), FreeDecodingContext(), FreeExecutorState(), FreeExprContext(), freeGISTstate(), FreeSnapshotBuilder(), geqo_eval(), gin_xlog_cleanup(), ginbuild(), ginbulkdelete(), ginendscan(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gist_xlog_cleanup(), gistbuild(), hash_destroy(), inline_function(), inline_set_returning_function(), 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().

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

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

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

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

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

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

403 {
405 
406  return context->parent;
407 }
#define AssertArg(condition)
Definition: c.h:682
#define MemoryContextIsValid(context)
Definition: memnodes.h:96
MemoryContext parent
Definition: memnodes.h:79

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 89 of file mcxt.c.

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

Referenced by main().

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

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 414 of file mcxt.c.

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

Referenced by AtSubCommit_Memory().

415 {
417 
418  /*
419  * For now, we consider a memory context nonempty if it has any children;
420  * perhaps this should be changed later.
421  */
422  if (context->firstchild != NULL)
423  return false;
424  /* Otherwise use the type-specific inquiry */
425  return context->methods->is_empty(context);
426 }
const MemoryContextMethods * methods
Definition: memnodes.h:78
MemoryContext firstchild
Definition: memnodes.h:80
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:63
#define AssertArg(condition)
Definition: c.h:682
#define MemoryContextIsValid(context)
Definition: memnodes.h:96

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 134 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(), CopyOneRowTo(), 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(), ExecHashTableReset(), ExecMakeTableFunctionResult(), ExecProjectSet(), ExecRecursiveUnion(), execTuplesMatch(), execTuplesUnequal(), fetch_more_data(), file_acquire_sample_rows(), gin_redo(), ginBuildCallback(), ginHeapTupleBulkInsert(), ginInsertCleanup(), ginVacuumPostingTreeLeaves(), gist_redo(), gistBuildCallback(), gistgetbitmap(), gistgettuple(), gistinsert(), gistProcessEmptyingQueue(), gistrescan(), gistScanPage(), HandleParallelMessages(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), keyGetItem(), libpqrcv_processTuples(), LogicalRepApplyLoop(), make_tuple_from_result_row(), pg_decode_change(), pgoutput_change(), plperl_return_next_internal(), PLy_input_convert(), PLy_input_from_tuple(), postgresExecForeignDelete(), postgresExecForeignInsert(), postgresExecForeignUpdate(), printtup(), printtup_20(), printtup_internal_20(), process_ordered_aggregate_multi(), process_ordered_aggregate_single(), ReScanExprContext(), scanPendingInsert(), sepgsql_avc_reset(), setop_fill_hash_table(), spg_redo(), spginsert(), spgistBuildCallback(), spgWalk(), startScanKey(), storeRow(), tfuncLoadRows(), and validate_index_heapscan().

135 {
137 
138  /* save a function call in common case where there are no children */
139  if (context->firstchild != NULL)
141 
142  /* save a function call if no pallocs since startup or last reset */
143  if (!context->isReset)
144  MemoryContextResetOnly(context);
145 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:153
MemoryContext firstchild
Definition: memnodes.h:80
#define AssertArg(condition)
Definition: c.h:682
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:236
#define MemoryContextIsValid(context)
Definition: memnodes.h:96

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 175 of file mcxt.c.

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

Referenced by MemoryContextResetChildren().

176 {
177  MemoryContext child;
178 
180 
181  for (child = context->firstchild; child != NULL; child = child->nextchild)
182  {
184  MemoryContextResetOnly(child);
185  }
186 }
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:153
MemoryContext firstchild
Definition: memnodes.h:80
#define AssertArg(condition)
Definition: c.h:682
#define MemoryContextIsValid(context)
Definition: memnodes.h:96
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:175
MemoryContext nextchild
Definition: memnodes.h:82

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

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

154 {
156 
157  /* Nothing to do if no pallocs since startup or last reset */
158  if (!context->isReset)
159  {
161  context->methods->reset(context);
162  context->isReset = true;
163  VALGRIND_DESTROY_MEMPOOL(context);
164  VALGRIND_CREATE_MEMPOOL(context, 0, false);
165  }
166 }
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:282
const MemoryContextMethods * methods
Definition: memnodes.h:78
void(* reset)(MemoryContext context)
Definition: memnodes.h:60
#define AssertArg(condition)
Definition: c.h:682
#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:96

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

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

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

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

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

438 {
439  /* A hard-wired limit on the number of children is usually good enough */
440  MemoryContextStatsDetail(context, 100);
441 }
void MemoryContextStatsDetail(MemoryContext context, int max_children)
Definition: mcxt.c:449

◆ MemoryContextStatsDetail()

void MemoryContextStatsDetail ( MemoryContext  context,
int  max_children 
)

Definition at line 449 of file mcxt.c.

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

Referenced by MemoryContextStats().

450 {
451  MemoryContextCounters grand_totals;
452 
453  memset(&grand_totals, 0, sizeof(grand_totals));
454 
455  MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals);
456 
457  fprintf(stderr,
458  "Grand total: %zu bytes in %zd blocks; %zu free (%zd chunks); %zu used\n",
459  grand_totals.totalspace, grand_totals.nblocks,
460  grand_totals.freespace, grand_totals.freechunks,
461  grand_totals.totalspace - grand_totals.freespace);
462 }
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals)
Definition: mcxt.c:472

◆ SlabContextCreate()

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

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

Referenced by ReorderBufferAllocate().

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

Variable Documentation

◆ CacheMemoryContext

PGDLLIMPORT MemoryContext CacheMemoryContext

Definition at line 46 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 43 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(), 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(), ri_HashCompareOp(), roles_has_privs_of(), roles_is_member_of(), sepgsql_avc_init(), sepgsql_xact_callback(), SetDatabasePath(), SharedRecordTypmodRegistryAttach(), SharedRecordTypmodRegistryInit(), SlabContextCreate(), StartChildProcess(), WalWriterMain(), XLOGShmemInit(), and xml_is_document().

◆ TopTransactionContext