Remove MemoryContextContains().
[pgsql.git] / src / backend / utils / mmgr / mcxt.c
blobc80236d285ae6e421d7bbeb8b39aa3cae8305a28
1 /*-------------------------------------------------------------------------
3 * mcxt.c
4 * POSTGRES memory context management code.
6 * This module handles context management operations that are independent
7 * of the particular kind of context being operated on. It calls
8 * context-type-specific operations via the function pointers in a
9 * context's MemoryContextMethods struct.
12 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
16 * IDENTIFICATION
17 * src/backend/utils/mmgr/mcxt.c
19 *-------------------------------------------------------------------------
22 #include "postgres.h"
24 #include "mb/pg_wchar.h"
25 #include "miscadmin.h"
26 #include "storage/proc.h"
27 #include "storage/procarray.h"
28 #include "storage/procsignal.h"
29 #include "utils/fmgrprotos.h"
30 #include "utils/memdebug.h"
31 #include "utils/memutils.h"
32 #include "utils/memutils_internal.h"
35 /*****************************************************************************
36 * GLOBAL MEMORY *
37 *****************************************************************************/
39 static const MemoryContextMethods mcxt_methods[] = {
40 /* aset.c */
41 [MCTX_ASET_ID].alloc = AllocSetAlloc,
42 [MCTX_ASET_ID].free_p = AllocSetFree,
43 [MCTX_ASET_ID].realloc = AllocSetRealloc,
44 [MCTX_ASET_ID].reset = AllocSetReset,
45 [MCTX_ASET_ID].delete_context = AllocSetDelete,
46 [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext,
47 [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace,
48 [MCTX_ASET_ID].is_empty = AllocSetIsEmpty,
49 [MCTX_ASET_ID].stats = AllocSetStats,
50 #ifdef MEMORY_CONTEXT_CHECKING
51 [MCTX_ASET_ID].check = AllocSetCheck,
52 #endif
54 /* generation.c */
55 [MCTX_GENERATION_ID].alloc = GenerationAlloc,
56 [MCTX_GENERATION_ID].free_p = GenerationFree,
57 [MCTX_GENERATION_ID].realloc = GenerationRealloc,
58 [MCTX_GENERATION_ID].reset = GenerationReset,
59 [MCTX_GENERATION_ID].delete_context = GenerationDelete,
60 [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext,
61 [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace,
62 [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty,
63 [MCTX_GENERATION_ID].stats = GenerationStats,
64 #ifdef MEMORY_CONTEXT_CHECKING
65 [MCTX_GENERATION_ID].check = GenerationCheck,
66 #endif
68 /* slab.c */
69 [MCTX_SLAB_ID].alloc = SlabAlloc,
70 [MCTX_SLAB_ID].free_p = SlabFree,
71 [MCTX_SLAB_ID].realloc = SlabRealloc,
72 [MCTX_SLAB_ID].reset = SlabReset,
73 [MCTX_SLAB_ID].delete_context = SlabDelete,
74 [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext,
75 [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace,
76 [MCTX_SLAB_ID].is_empty = SlabIsEmpty,
77 [MCTX_SLAB_ID].stats = SlabStats
78 #ifdef MEMORY_CONTEXT_CHECKING
79 ,[MCTX_SLAB_ID].check = SlabCheck
80 #endif
84 * CurrentMemoryContext
85 * Default memory context for allocations.
87 MemoryContext CurrentMemoryContext = NULL;
90 * Standard top-level contexts. For a description of the purpose of each
91 * of these contexts, refer to src/backend/utils/mmgr/README
93 MemoryContext TopMemoryContext = NULL;
94 MemoryContext ErrorContext = NULL;
95 MemoryContext PostmasterContext = NULL;
96 MemoryContext CacheMemoryContext = NULL;
97 MemoryContext MessageContext = NULL;
98 MemoryContext TopTransactionContext = NULL;
99 MemoryContext CurTransactionContext = NULL;
101 /* This is a transient link to the active portal's memory context: */
102 MemoryContext PortalContext = NULL;
104 static void MemoryContextCallResetCallbacks(MemoryContext context);
105 static void MemoryContextStatsInternal(MemoryContext context, int level,
106 bool print, int max_children,
107 MemoryContextCounters *totals,
108 bool print_to_stderr);
109 static void MemoryContextStatsPrint(MemoryContext context, void *passthru,
110 const char *stats_string,
111 bool print_to_stderr);
114 * You should not do memory allocations within a critical section, because
115 * an out-of-memory error will be escalated to a PANIC. To enforce that
116 * rule, the allocation functions Assert that.
118 #define AssertNotInCriticalSection(context) \
119 Assert(CritSectionCount == 0 || (context)->allowInCritSection)
122 * Call the given function in the MemoryContextMethods for the memory context
123 * type that 'pointer' belongs to.
125 #define MCXT_METHOD(pointer, method) \
126 mcxt_methods[GetMemoryChunkMethodID(pointer)].method
129 /*****************************************************************************
130 * EXPORTED ROUTINES *
131 *****************************************************************************/
135 * MemoryContextInit
136 * Start up the memory-context subsystem.
138 * This must be called before creating contexts or allocating memory in
139 * contexts. TopMemoryContext and ErrorContext are initialized here;
140 * other contexts must be created afterwards.
142 * In normal multi-backend operation, this is called once during
143 * postmaster startup, and not at all by individual backend startup
144 * (since the backends inherit an already-initialized context subsystem
145 * by virtue of being forked off the postmaster). But in an EXEC_BACKEND
146 * build, each process must do this for itself.
148 * In a standalone backend this must be called during backend startup.
150 void
151 MemoryContextInit(void)
153 AssertState(TopMemoryContext == NULL);
156 * First, initialize TopMemoryContext, which is the parent of all others.
158 TopMemoryContext = AllocSetContextCreate((MemoryContext) NULL,
159 "TopMemoryContext",
160 ALLOCSET_DEFAULT_SIZES);
163 * Not having any other place to point CurrentMemoryContext, make it point
164 * to TopMemoryContext. Caller should change this soon!
166 CurrentMemoryContext = TopMemoryContext;
169 * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
170 * we don't really expect much to be allocated in it. More to the point,
171 * require it to contain at least 8K at all times. This is the only case
172 * where retained memory in a context is *essential* --- we want to be
173 * sure ErrorContext still has some memory even if we've run out
174 * elsewhere! Also, allow allocations in ErrorContext within a critical
175 * section. Otherwise a PANIC will cause an assertion failure in the error
176 * reporting code, before printing out the real cause of the failure.
178 * This should be the last step in this function, as elog.c assumes memory
179 * management works once ErrorContext is non-null.
181 ErrorContext = AllocSetContextCreate(TopMemoryContext,
182 "ErrorContext",
183 8 * 1024,
184 8 * 1024,
185 8 * 1024);
186 MemoryContextAllowInCriticalSection(ErrorContext, true);
190 * MemoryContextReset
191 * Release all space allocated within a context and delete all its
192 * descendant contexts (but not the named context itself).
194 void
195 MemoryContextReset(MemoryContext context)
197 AssertArg(MemoryContextIsValid(context));
199 /* save a function call in common case where there are no children */
200 if (context->firstchild != NULL)
201 MemoryContextDeleteChildren(context);
203 /* save a function call if no pallocs since startup or last reset */
204 if (!context->isReset)
205 MemoryContextResetOnly(context);
209 * MemoryContextResetOnly
210 * Release all space allocated within a context.
211 * Nothing is done to the context's descendant contexts.
213 void
214 MemoryContextResetOnly(MemoryContext context)
216 AssertArg(MemoryContextIsValid(context));
218 /* Nothing to do if no pallocs since startup or last reset */
219 if (!context->isReset)
221 MemoryContextCallResetCallbacks(context);
224 * If context->ident points into the context's memory, it will become
225 * a dangling pointer. We could prevent that by setting it to NULL
226 * here, but that would break valid coding patterns that keep the
227 * ident elsewhere, e.g. in a parent context. So for now we assume
228 * the programmer got it right.
231 context->methods->reset(context);
232 context->isReset = true;
233 VALGRIND_DESTROY_MEMPOOL(context);
234 VALGRIND_CREATE_MEMPOOL(context, 0, false);
239 * MemoryContextResetChildren
240 * Release all space allocated within a context's descendants,
241 * but don't delete the contexts themselves. The named context
242 * itself is not touched.
244 void
245 MemoryContextResetChildren(MemoryContext context)
247 MemoryContext child;
249 AssertArg(MemoryContextIsValid(context));
251 for (child = context->firstchild; child != NULL; child = child->nextchild)
253 MemoryContextResetChildren(child);
254 MemoryContextResetOnly(child);
259 * MemoryContextDelete
260 * Delete a context and its descendants, and release all space
261 * allocated therein.
263 * The type-specific delete routine removes all storage for the context,
264 * but we have to recurse to handle the children.
265 * We must also delink the context from its parent, if it has one.
267 void
268 MemoryContextDelete(MemoryContext context)
270 AssertArg(MemoryContextIsValid(context));
271 /* We had better not be deleting TopMemoryContext ... */
272 Assert(context != TopMemoryContext);
273 /* And not CurrentMemoryContext, either */
274 Assert(context != CurrentMemoryContext);
276 /* save a function call in common case where there are no children */
277 if (context->firstchild != NULL)
278 MemoryContextDeleteChildren(context);
281 * It's not entirely clear whether 'tis better to do this before or after
282 * delinking the context; but an error in a callback will likely result in
283 * leaking the whole context (if it's not a root context) if we do it
284 * after, so let's do it before.
286 MemoryContextCallResetCallbacks(context);
289 * We delink the context from its parent before deleting it, so that if
290 * there's an error we won't have deleted/busted contexts still attached
291 * to the context tree. Better a leak than a crash.
293 MemoryContextSetParent(context, NULL);
296 * Also reset the context's ident pointer, in case it points into the
297 * context. This would only matter if someone tries to get stats on the
298 * (already unlinked) context, which is unlikely, but let's be safe.
300 context->ident = NULL;
302 context->methods->delete_context(context);
304 VALGRIND_DESTROY_MEMPOOL(context);
308 * MemoryContextDeleteChildren
309 * Delete all the descendants of the named context and release all
310 * space allocated therein. The named context itself is not touched.
312 void
313 MemoryContextDeleteChildren(MemoryContext context)
315 AssertArg(MemoryContextIsValid(context));
318 * MemoryContextDelete will delink the child from me, so just iterate as
319 * long as there is a child.
321 while (context->firstchild != NULL)
322 MemoryContextDelete(context->firstchild);
326 * MemoryContextRegisterResetCallback
327 * Register a function to be called before next context reset/delete.
328 * Such callbacks will be called in reverse order of registration.
330 * The caller is responsible for allocating a MemoryContextCallback struct
331 * to hold the info about this callback request, and for filling in the
332 * "func" and "arg" fields in the struct to show what function to call with
333 * what argument. Typically the callback struct should be allocated within
334 * the specified context, since that means it will automatically be freed
335 * when no longer needed.
337 * There is no API for deregistering a callback once registered. If you
338 * want it to not do anything anymore, adjust the state pointed to by its
339 * "arg" to indicate that.
341 void
342 MemoryContextRegisterResetCallback(MemoryContext context,
343 MemoryContextCallback *cb)
345 AssertArg(MemoryContextIsValid(context));
347 /* Push onto head so this will be called before older registrants. */
348 cb->next = context->reset_cbs;
349 context->reset_cbs = cb;
350 /* Mark the context as non-reset (it probably is already). */
351 context->isReset = false;
355 * MemoryContextCallResetCallbacks
356 * Internal function to call all registered callbacks for context.
358 static void
359 MemoryContextCallResetCallbacks(MemoryContext context)
361 MemoryContextCallback *cb;
364 * We pop each callback from the list before calling. That way, if an
365 * error occurs inside the callback, we won't try to call it a second time
366 * in the likely event that we reset or delete the context later.
368 while ((cb = context->reset_cbs) != NULL)
370 context->reset_cbs = cb->next;
371 cb->func(cb->arg);
376 * MemoryContextSetIdentifier
377 * Set the identifier string for a memory context.
379 * An identifier can be provided to help distinguish among different contexts
380 * of the same kind in memory context stats dumps. The identifier string
381 * must live at least as long as the context it is for; typically it is
382 * allocated inside that context, so that it automatically goes away on
383 * context deletion. Pass id = NULL to forget any old identifier.
385 void
386 MemoryContextSetIdentifier(MemoryContext context, const char *id)
388 AssertArg(MemoryContextIsValid(context));
389 context->ident = id;
393 * MemoryContextSetParent
394 * Change a context to belong to a new parent (or no parent).
396 * We provide this as an API function because it is sometimes useful to
397 * change a context's lifespan after creation. For example, a context
398 * might be created underneath a transient context, filled with data,
399 * and then reparented underneath CacheMemoryContext to make it long-lived.
400 * In this way no special effort is needed to get rid of the context in case
401 * a failure occurs before its contents are completely set up.
403 * Callers often assume that this function cannot fail, so don't put any
404 * elog(ERROR) calls in it.
406 * A possible caller error is to reparent a context under itself, creating
407 * a loop in the context graph. We assert here that context != new_parent,
408 * but checking for multi-level loops seems more trouble than it's worth.
410 void
411 MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
413 AssertArg(MemoryContextIsValid(context));
414 AssertArg(context != new_parent);
416 /* Fast path if it's got correct parent already */
417 if (new_parent == context->parent)
418 return;
420 /* Delink from existing parent, if any */
421 if (context->parent)
423 MemoryContext parent = context->parent;
425 if (context->prevchild != NULL)
426 context->prevchild->nextchild = context->nextchild;
427 else
429 Assert(parent->firstchild == context);
430 parent->firstchild = context->nextchild;
433 if (context->nextchild != NULL)
434 context->nextchild->prevchild = context->prevchild;
437 /* And relink */
438 if (new_parent)
440 AssertArg(MemoryContextIsValid(new_parent));
441 context->parent = new_parent;
442 context->prevchild = NULL;
443 context->nextchild = new_parent->firstchild;
444 if (new_parent->firstchild != NULL)
445 new_parent->firstchild->prevchild = context;
446 new_parent->firstchild = context;
448 else
450 context->parent = NULL;
451 context->prevchild = NULL;
452 context->nextchild = NULL;
457 * MemoryContextAllowInCriticalSection
458 * Allow/disallow allocations in this memory context within a critical
459 * section.
461 * Normally, memory allocations are not allowed within a critical section,
462 * because a failure would lead to PANIC. There are a few exceptions to
463 * that, like allocations related to debugging code that is not supposed to
464 * be enabled in production. This function can be used to exempt specific
465 * memory contexts from the assertion in palloc().
467 void
468 MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
470 AssertArg(MemoryContextIsValid(context));
472 context->allowInCritSection = allow;
476 * GetMemoryChunkContext
477 * Given a currently-allocated chunk, determine the MemoryContext that
478 * the chunk belongs to.
480 MemoryContext
481 GetMemoryChunkContext(void *pointer)
483 return MCXT_METHOD(pointer, get_chunk_context) (pointer);
487 * GetMemoryChunkSpace
488 * Given a currently-allocated chunk, determine the total space
489 * it occupies (including all memory-allocation overhead).
491 * This is useful for measuring the total space occupied by a set of
492 * allocated chunks.
494 Size
495 GetMemoryChunkSpace(void *pointer)
497 return MCXT_METHOD(pointer, get_chunk_space) (pointer);
501 * MemoryContextGetParent
502 * Get the parent context (if any) of the specified context
504 MemoryContext
505 MemoryContextGetParent(MemoryContext context)
507 AssertArg(MemoryContextIsValid(context));
509 return context->parent;
513 * MemoryContextIsEmpty
514 * Is a memory context empty of any allocated space?
516 bool
517 MemoryContextIsEmpty(MemoryContext context)
519 AssertArg(MemoryContextIsValid(context));
522 * For now, we consider a memory context nonempty if it has any children;
523 * perhaps this should be changed later.
525 if (context->firstchild != NULL)
526 return false;
527 /* Otherwise use the type-specific inquiry */
528 return context->methods->is_empty(context);
532 * Find the memory allocated to blocks for this memory context. If recurse is
533 * true, also include children.
535 Size
536 MemoryContextMemAllocated(MemoryContext context, bool recurse)
538 Size total = context->mem_allocated;
540 AssertArg(MemoryContextIsValid(context));
542 if (recurse)
544 MemoryContext child;
546 for (child = context->firstchild;
547 child != NULL;
548 child = child->nextchild)
549 total += MemoryContextMemAllocated(child, true);
552 return total;
556 * MemoryContextStats
557 * Print statistics about the named context and all its descendants.
559 * This is just a debugging utility, so it's not very fancy. However, we do
560 * make some effort to summarize when the output would otherwise be very long.
561 * The statistics are sent to stderr.
563 void
564 MemoryContextStats(MemoryContext context)
566 /* A hard-wired limit on the number of children is usually good enough */
567 MemoryContextStatsDetail(context, 100, true);
571 * MemoryContextStatsDetail
573 * Entry point for use if you want to vary the number of child contexts shown.
575 * If print_to_stderr is true, print statistics about the memory contexts
576 * with fprintf(stderr), otherwise use ereport().
578 void
579 MemoryContextStatsDetail(MemoryContext context, int max_children,
580 bool print_to_stderr)
582 MemoryContextCounters grand_totals;
584 memset(&grand_totals, 0, sizeof(grand_totals));
586 MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals, print_to_stderr);
588 if (print_to_stderr)
589 fprintf(stderr,
590 "Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used\n",
591 grand_totals.totalspace, grand_totals.nblocks,
592 grand_totals.freespace, grand_totals.freechunks,
593 grand_totals.totalspace - grand_totals.freespace);
594 else
597 * Use LOG_SERVER_ONLY to prevent the memory contexts from being sent
598 * to the connected client.
600 * We don't buffer the information about all memory contexts in a
601 * backend into StringInfo and log it as one message. Otherwise which
602 * may require the buffer to be enlarged very much and lead to OOM
603 * error since there can be a large number of memory contexts in a
604 * backend. Instead, we log one message per memory context.
606 ereport(LOG_SERVER_ONLY,
607 (errhidestmt(true),
608 errhidecontext(true),
609 errmsg_internal("Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used",
610 grand_totals.totalspace, grand_totals.nblocks,
611 grand_totals.freespace, grand_totals.freechunks,
612 grand_totals.totalspace - grand_totals.freespace)));
616 * MemoryContextStatsInternal
617 * One recursion level for MemoryContextStats
619 * Print this context if print is true, but in any case accumulate counts into
620 * *totals (if given).
622 static void
623 MemoryContextStatsInternal(MemoryContext context, int level,
624 bool print, int max_children,
625 MemoryContextCounters *totals,
626 bool print_to_stderr)
628 MemoryContextCounters local_totals;
629 MemoryContext child;
630 int ichild;
632 AssertArg(MemoryContextIsValid(context));
634 /* Examine the context itself */
635 context->methods->stats(context,
636 print ? MemoryContextStatsPrint : NULL,
637 (void *) &level,
638 totals, print_to_stderr);
641 * Examine children. If there are more than max_children of them, we do
642 * not print the rest explicitly, but just summarize them.
644 memset(&local_totals, 0, sizeof(local_totals));
646 for (child = context->firstchild, ichild = 0;
647 child != NULL;
648 child = child->nextchild, ichild++)
650 if (ichild < max_children)
651 MemoryContextStatsInternal(child, level + 1,
652 print, max_children,
653 totals,
654 print_to_stderr);
655 else
656 MemoryContextStatsInternal(child, level + 1,
657 false, max_children,
658 &local_totals,
659 print_to_stderr);
662 /* Deal with excess children */
663 if (ichild > max_children)
665 if (print)
667 if (print_to_stderr)
669 int i;
671 for (i = 0; i <= level; i++)
672 fprintf(stderr, " ");
673 fprintf(stderr,
674 "%d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used\n",
675 ichild - max_children,
676 local_totals.totalspace,
677 local_totals.nblocks,
678 local_totals.freespace,
679 local_totals.freechunks,
680 local_totals.totalspace - local_totals.freespace);
682 else
683 ereport(LOG_SERVER_ONLY,
684 (errhidestmt(true),
685 errhidecontext(true),
686 errmsg_internal("level: %d; %d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used",
687 level,
688 ichild - max_children,
689 local_totals.totalspace,
690 local_totals.nblocks,
691 local_totals.freespace,
692 local_totals.freechunks,
693 local_totals.totalspace - local_totals.freespace)));
696 if (totals)
698 totals->nblocks += local_totals.nblocks;
699 totals->freechunks += local_totals.freechunks;
700 totals->totalspace += local_totals.totalspace;
701 totals->freespace += local_totals.freespace;
707 * MemoryContextStatsPrint
708 * Print callback used by MemoryContextStatsInternal
710 * For now, the passthru pointer just points to "int level"; later we might
711 * make that more complicated.
713 static void
714 MemoryContextStatsPrint(MemoryContext context, void *passthru,
715 const char *stats_string,
716 bool print_to_stderr)
718 int level = *(int *) passthru;
719 const char *name = context->name;
720 const char *ident = context->ident;
721 char truncated_ident[110];
722 int i;
725 * It seems preferable to label dynahash contexts with just the hash table
726 * name. Those are already unique enough, so the "dynahash" part isn't
727 * very helpful, and this way is more consistent with pre-v11 practice.
729 if (ident && strcmp(name, "dynahash") == 0)
731 name = ident;
732 ident = NULL;
735 truncated_ident[0] = '\0';
737 if (ident)
740 * Some contexts may have very long identifiers (e.g., SQL queries).
741 * Arbitrarily truncate at 100 bytes, but be careful not to break
742 * multibyte characters. Also, replace ASCII control characters, such
743 * as newlines, with spaces.
745 int idlen = strlen(ident);
746 bool truncated = false;
748 strcpy(truncated_ident, ": ");
749 i = strlen(truncated_ident);
751 if (idlen > 100)
753 idlen = pg_mbcliplen(ident, idlen, 100);
754 truncated = true;
757 while (idlen-- > 0)
759 unsigned char c = *ident++;
761 if (c < ' ')
762 c = ' ';
763 truncated_ident[i++] = c;
765 truncated_ident[i] = '\0';
767 if (truncated)
768 strcat(truncated_ident, "...");
771 if (print_to_stderr)
773 for (i = 0; i < level; i++)
774 fprintf(stderr, " ");
775 fprintf(stderr, "%s: %s%s\n", name, stats_string, truncated_ident);
777 else
778 ereport(LOG_SERVER_ONLY,
779 (errhidestmt(true),
780 errhidecontext(true),
781 errmsg_internal("level: %d; %s: %s%s",
782 level, name, stats_string, truncated_ident)));
786 * MemoryContextCheck
787 * Check all chunks in the named context.
789 * This is just a debugging utility, so it's not fancy.
791 #ifdef MEMORY_CONTEXT_CHECKING
792 void
793 MemoryContextCheck(MemoryContext context)
795 MemoryContext child;
797 AssertArg(MemoryContextIsValid(context));
799 context->methods->check(context);
800 for (child = context->firstchild; child != NULL; child = child->nextchild)
801 MemoryContextCheck(child);
803 #endif
806 * MemoryContextCreate
807 * Context-type-independent part of context creation.
809 * This is only intended to be called by context-type-specific
810 * context creation routines, not by the unwashed masses.
812 * The memory context creation procedure goes like this:
813 * 1. Context-type-specific routine makes some initial space allocation,
814 * including enough space for the context header. If it fails,
815 * it can ereport() with no damage done.
816 * 2. Context-type-specific routine sets up all type-specific fields of
817 * the header (those beyond MemoryContextData proper), as well as any
818 * other management fields it needs to have a fully valid context.
819 * Usually, failure in this step is impossible, but if it's possible
820 * the initial space allocation should be freed before ereport'ing.
821 * 3. Context-type-specific routine calls MemoryContextCreate() to fill in
822 * the generic header fields and link the context into the context tree.
823 * 4. We return to the context-type-specific routine, which finishes
824 * up type-specific initialization. This routine can now do things
825 * that might fail (like allocate more memory), so long as it's
826 * sure the node is left in a state that delete will handle.
828 * node: the as-yet-uninitialized common part of the context header node.
829 * tag: NodeTag code identifying the memory context type.
830 * method_id: MemoryContextMethodID of the context-type being created.
831 * parent: parent context, or NULL if this will be a top-level context.
832 * name: name of context (must be statically allocated).
834 * Context routines generally assume that MemoryContextCreate can't fail,
835 * so this can contain Assert but not elog/ereport.
837 void
838 MemoryContextCreate(MemoryContext node,
839 NodeTag tag,
840 MemoryContextMethodID method_id,
841 MemoryContext parent,
842 const char *name)
844 /* Creating new memory contexts is not allowed in a critical section */
845 Assert(CritSectionCount == 0);
847 /* Initialize all standard fields of memory context header */
848 node->type = tag;
849 node->isReset = true;
850 node->methods = &mcxt_methods[method_id];
851 node->parent = parent;
852 node->firstchild = NULL;
853 node->mem_allocated = 0;
854 node->prevchild = NULL;
855 node->name = name;
856 node->ident = NULL;
857 node->reset_cbs = NULL;
859 /* OK to link node into context tree */
860 if (parent)
862 node->nextchild = parent->firstchild;
863 if (parent->firstchild != NULL)
864 parent->firstchild->prevchild = node;
865 parent->firstchild = node;
866 /* inherit allowInCritSection flag from parent */
867 node->allowInCritSection = parent->allowInCritSection;
869 else
871 node->nextchild = NULL;
872 node->allowInCritSection = false;
875 VALGRIND_CREATE_MEMPOOL(node, 0, false);
879 * MemoryContextAlloc
880 * Allocate space within the specified context.
882 * This could be turned into a macro, but we'd have to import
883 * nodes/memnodes.h into postgres.h which seems a bad idea.
885 void *
886 MemoryContextAlloc(MemoryContext context, Size size)
888 void *ret;
890 AssertArg(MemoryContextIsValid(context));
891 AssertNotInCriticalSection(context);
893 if (!AllocSizeIsValid(size))
894 elog(ERROR, "invalid memory alloc request size %zu", size);
896 context->isReset = false;
898 ret = context->methods->alloc(context, size);
899 if (unlikely(ret == NULL))
901 MemoryContextStats(TopMemoryContext);
904 * Here, and elsewhere in this module, we show the target context's
905 * "name" but not its "ident" (if any) in user-visible error messages.
906 * The "ident" string might contain security-sensitive data, such as
907 * values in SQL commands.
909 ereport(ERROR,
910 (errcode(ERRCODE_OUT_OF_MEMORY),
911 errmsg("out of memory"),
912 errdetail("Failed on request of size %zu in memory context \"%s\".",
913 size, context->name)));
916 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
918 return ret;
922 * MemoryContextAllocZero
923 * Like MemoryContextAlloc, but clears allocated memory
925 * We could just call MemoryContextAlloc then clear the memory, but this
926 * is a very common combination, so we provide the combined operation.
928 void *
929 MemoryContextAllocZero(MemoryContext context, Size size)
931 void *ret;
933 AssertArg(MemoryContextIsValid(context));
934 AssertNotInCriticalSection(context);
936 if (!AllocSizeIsValid(size))
937 elog(ERROR, "invalid memory alloc request size %zu", size);
939 context->isReset = false;
941 ret = context->methods->alloc(context, size);
942 if (unlikely(ret == NULL))
944 MemoryContextStats(TopMemoryContext);
945 ereport(ERROR,
946 (errcode(ERRCODE_OUT_OF_MEMORY),
947 errmsg("out of memory"),
948 errdetail("Failed on request of size %zu in memory context \"%s\".",
949 size, context->name)));
952 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
954 MemSetAligned(ret, 0, size);
956 return ret;
960 * MemoryContextAllocZeroAligned
961 * MemoryContextAllocZero where length is suitable for MemSetLoop
963 * This might seem overly specialized, but it's not because newNode()
964 * is so often called with compile-time-constant sizes.
966 void *
967 MemoryContextAllocZeroAligned(MemoryContext context, Size size)
969 void *ret;
971 AssertArg(MemoryContextIsValid(context));
972 AssertNotInCriticalSection(context);
974 if (!AllocSizeIsValid(size))
975 elog(ERROR, "invalid memory alloc request size %zu", size);
977 context->isReset = false;
979 ret = context->methods->alloc(context, size);
980 if (unlikely(ret == NULL))
982 MemoryContextStats(TopMemoryContext);
983 ereport(ERROR,
984 (errcode(ERRCODE_OUT_OF_MEMORY),
985 errmsg("out of memory"),
986 errdetail("Failed on request of size %zu in memory context \"%s\".",
987 size, context->name)));
990 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
992 MemSetLoop(ret, 0, size);
994 return ret;
998 * MemoryContextAllocExtended
999 * Allocate space within the specified context using the given flags.
1001 void *
1002 MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
1004 void *ret;
1006 AssertArg(MemoryContextIsValid(context));
1007 AssertNotInCriticalSection(context);
1009 if (((flags & MCXT_ALLOC_HUGE) != 0 && !AllocHugeSizeIsValid(size)) ||
1010 ((flags & MCXT_ALLOC_HUGE) == 0 && !AllocSizeIsValid(size)))
1011 elog(ERROR, "invalid memory alloc request size %zu", size);
1013 context->isReset = false;
1015 ret = context->methods->alloc(context, size);
1016 if (unlikely(ret == NULL))
1018 if ((flags & MCXT_ALLOC_NO_OOM) == 0)
1020 MemoryContextStats(TopMemoryContext);
1021 ereport(ERROR,
1022 (errcode(ERRCODE_OUT_OF_MEMORY),
1023 errmsg("out of memory"),
1024 errdetail("Failed on request of size %zu in memory context \"%s\".",
1025 size, context->name)));
1027 return NULL;
1030 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1032 if ((flags & MCXT_ALLOC_ZERO) != 0)
1033 MemSetAligned(ret, 0, size);
1035 return ret;
1039 * HandleLogMemoryContextInterrupt
1040 * Handle receipt of an interrupt indicating logging of memory
1041 * contexts.
1043 * All the actual work is deferred to ProcessLogMemoryContextInterrupt(),
1044 * because we cannot safely emit a log message inside the signal handler.
1046 void
1047 HandleLogMemoryContextInterrupt(void)
1049 InterruptPending = true;
1050 LogMemoryContextPending = true;
1051 /* latch will be set by procsignal_sigusr1_handler */
1055 * ProcessLogMemoryContextInterrupt
1056 * Perform logging of memory contexts of this backend process.
1058 * Any backend that participates in ProcSignal signaling must arrange
1059 * to call this function if we see LogMemoryContextPending set.
1060 * It is called from CHECK_FOR_INTERRUPTS(), which is enough because
1061 * the target process for logging of memory contexts is a backend.
1063 void
1064 ProcessLogMemoryContextInterrupt(void)
1066 LogMemoryContextPending = false;
1069 * Use LOG_SERVER_ONLY to prevent this message from being sent to the
1070 * connected client.
1072 ereport(LOG_SERVER_ONLY,
1073 (errhidestmt(true),
1074 errhidecontext(true),
1075 errmsg("logging memory contexts of PID %d", MyProcPid)));
1078 * When a backend process is consuming huge memory, logging all its memory
1079 * contexts might overrun available disk space. To prevent this, we limit
1080 * the number of child contexts to log per parent to 100.
1082 * As with MemoryContextStats(), we suppose that practical cases where the
1083 * dump gets long will typically be huge numbers of siblings under the
1084 * same parent context; while the additional debugging value from seeing
1085 * details about individual siblings beyond 100 will not be large.
1087 MemoryContextStatsDetail(TopMemoryContext, 100, false);
1090 void *
1091 palloc(Size size)
1093 /* duplicates MemoryContextAlloc to avoid increased overhead */
1094 void *ret;
1095 MemoryContext context = CurrentMemoryContext;
1097 AssertArg(MemoryContextIsValid(context));
1098 AssertNotInCriticalSection(context);
1100 if (!AllocSizeIsValid(size))
1101 elog(ERROR, "invalid memory alloc request size %zu", size);
1103 context->isReset = false;
1105 ret = context->methods->alloc(context, size);
1106 if (unlikely(ret == NULL))
1108 MemoryContextStats(TopMemoryContext);
1109 ereport(ERROR,
1110 (errcode(ERRCODE_OUT_OF_MEMORY),
1111 errmsg("out of memory"),
1112 errdetail("Failed on request of size %zu in memory context \"%s\".",
1113 size, context->name)));
1116 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1118 return ret;
1121 void *
1122 palloc0(Size size)
1124 /* duplicates MemoryContextAllocZero to avoid increased overhead */
1125 void *ret;
1126 MemoryContext context = CurrentMemoryContext;
1128 AssertArg(MemoryContextIsValid(context));
1129 AssertNotInCriticalSection(context);
1131 if (!AllocSizeIsValid(size))
1132 elog(ERROR, "invalid memory alloc request size %zu", size);
1134 context->isReset = false;
1136 ret = context->methods->alloc(context, size);
1137 if (unlikely(ret == NULL))
1139 MemoryContextStats(TopMemoryContext);
1140 ereport(ERROR,
1141 (errcode(ERRCODE_OUT_OF_MEMORY),
1142 errmsg("out of memory"),
1143 errdetail("Failed on request of size %zu in memory context \"%s\".",
1144 size, context->name)));
1147 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1149 MemSetAligned(ret, 0, size);
1151 return ret;
1154 void *
1155 palloc_extended(Size size, int flags)
1157 /* duplicates MemoryContextAllocExtended to avoid increased overhead */
1158 void *ret;
1159 MemoryContext context = CurrentMemoryContext;
1161 AssertArg(MemoryContextIsValid(context));
1162 AssertNotInCriticalSection(context);
1164 if (((flags & MCXT_ALLOC_HUGE) != 0 && !AllocHugeSizeIsValid(size)) ||
1165 ((flags & MCXT_ALLOC_HUGE) == 0 && !AllocSizeIsValid(size)))
1166 elog(ERROR, "invalid memory alloc request size %zu", size);
1168 context->isReset = false;
1170 ret = context->methods->alloc(context, size);
1171 if (unlikely(ret == NULL))
1173 if ((flags & MCXT_ALLOC_NO_OOM) == 0)
1175 MemoryContextStats(TopMemoryContext);
1176 ereport(ERROR,
1177 (errcode(ERRCODE_OUT_OF_MEMORY),
1178 errmsg("out of memory"),
1179 errdetail("Failed on request of size %zu in memory context \"%s\".",
1180 size, context->name)));
1182 return NULL;
1185 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1187 if ((flags & MCXT_ALLOC_ZERO) != 0)
1188 MemSetAligned(ret, 0, size);
1190 return ret;
1194 * pfree
1195 * Release an allocated chunk.
1197 void
1198 pfree(void *pointer)
1200 #ifdef USE_VALGRIND
1201 MemoryContext context = GetMemoryChunkContext(pointer);
1202 #endif
1204 MCXT_METHOD(pointer, free_p) (pointer);
1205 VALGRIND_MEMPOOL_FREE(context, pointer);
1209 * repalloc
1210 * Adjust the size of a previously allocated chunk.
1212 void *
1213 repalloc(void *pointer, Size size)
1215 #if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
1216 MemoryContext context = GetMemoryChunkContext(pointer);
1217 #endif
1218 void *ret;
1220 if (!AllocSizeIsValid(size))
1221 elog(ERROR, "invalid memory alloc request size %zu", size);
1223 AssertNotInCriticalSection(context);
1225 /* isReset must be false already */
1226 Assert(!context->isReset);
1228 ret = MCXT_METHOD(pointer, realloc) (pointer, size);
1229 if (unlikely(ret == NULL))
1231 MemoryContext cxt = GetMemoryChunkContext(pointer);
1233 MemoryContextStats(TopMemoryContext);
1234 ereport(ERROR,
1235 (errcode(ERRCODE_OUT_OF_MEMORY),
1236 errmsg("out of memory"),
1237 errdetail("Failed on request of size %zu in memory context \"%s\".",
1238 size, cxt->name)));
1241 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1243 return ret;
1247 * MemoryContextAllocHuge
1248 * Allocate (possibly-expansive) space within the specified context.
1250 * See considerations in comment at MaxAllocHugeSize.
1252 void *
1253 MemoryContextAllocHuge(MemoryContext context, Size size)
1255 void *ret;
1257 AssertArg(MemoryContextIsValid(context));
1258 AssertNotInCriticalSection(context);
1260 if (!AllocHugeSizeIsValid(size))
1261 elog(ERROR, "invalid memory alloc request size %zu", size);
1263 context->isReset = false;
1265 ret = context->methods->alloc(context, size);
1266 if (unlikely(ret == NULL))
1268 MemoryContextStats(TopMemoryContext);
1269 ereport(ERROR,
1270 (errcode(ERRCODE_OUT_OF_MEMORY),
1271 errmsg("out of memory"),
1272 errdetail("Failed on request of size %zu in memory context \"%s\".",
1273 size, context->name)));
1276 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1278 return ret;
1282 * repalloc_huge
1283 * Adjust the size of a previously allocated chunk, permitting a large
1284 * value. The previous allocation need not have been "huge".
1286 void *
1287 repalloc_huge(void *pointer, Size size)
1289 #if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
1290 MemoryContext context = GetMemoryChunkContext(pointer);
1291 #endif
1292 void *ret;
1294 if (!AllocHugeSizeIsValid(size))
1295 elog(ERROR, "invalid memory alloc request size %zu", size);
1297 AssertNotInCriticalSection(context);
1299 /* isReset must be false already */
1300 Assert(!context->isReset);
1302 ret = MCXT_METHOD(pointer, realloc) (pointer, size);
1303 if (unlikely(ret == NULL))
1305 MemoryContext cxt = GetMemoryChunkContext(pointer);
1307 MemoryContextStats(TopMemoryContext);
1308 ereport(ERROR,
1309 (errcode(ERRCODE_OUT_OF_MEMORY),
1310 errmsg("out of memory"),
1311 errdetail("Failed on request of size %zu in memory context \"%s\".",
1312 size, cxt->name)));
1315 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1317 return ret;
1321 * MemoryContextStrdup
1322 * Like strdup(), but allocate from the specified context
1324 char *
1325 MemoryContextStrdup(MemoryContext context, const char *string)
1327 char *nstr;
1328 Size len = strlen(string) + 1;
1330 nstr = (char *) MemoryContextAlloc(context, len);
1332 memcpy(nstr, string, len);
1334 return nstr;
1337 char *
1338 pstrdup(const char *in)
1340 return MemoryContextStrdup(CurrentMemoryContext, in);
1344 * pnstrdup
1345 * Like pstrdup(), but append null byte to a
1346 * not-necessarily-null-terminated input string.
1348 char *
1349 pnstrdup(const char *in, Size len)
1351 char *out;
1353 len = strnlen(in, len);
1355 out = palloc(len + 1);
1356 memcpy(out, in, len);
1357 out[len] = '\0';
1359 return out;
1363 * Make copy of string with all trailing newline characters removed.
1365 char *
1366 pchomp(const char *in)
1368 size_t n;
1370 n = strlen(in);
1371 while (n > 0 && in[n - 1] == '\n')
1372 n--;
1373 return pnstrdup(in, n);